summary refs log tree commit diff stats
path: root/tests
diff options
context:
space:
mode:
Diffstat (limited to 'tests')
-rw-r--r--tests/alias/t19349.nim19
-rw-r--r--tests/align/talign.nim18
-rw-r--r--tests/alloc/tmembug.nim54
-rw-r--r--tests/alloc/tmembug2.nim58
-rw-r--r--tests/arc/amodule.nim21
-rw-r--r--tests/arc/bmodule.nim4
-rw-r--r--tests/arc/cmodule.nim4
-rw-r--r--tests/arc/dmodule.nim23
-rw-r--r--tests/arc/nim.cfg1
-rw-r--r--tests/arc/t14383.nim217
-rw-r--r--tests/arc/t14472.nim43
-rw-r--r--tests/arc/t14864.nim5
-rw-r--r--tests/arc/t15909.nim16
-rw-r--r--tests/arc/t16033.nim10
-rw-r--r--tests/arc/t16458.nim6
-rw-r--r--tests/arc/t16558.nim9
-rw-r--r--tests/arc/t17025.nim56
-rw-r--r--tests/arc/t17173.nim10
-rw-r--r--tests/arc/t17812.nim41
-rw-r--r--tests/arc/t18645.nim18
-rw-r--r--tests/arc/t18971.nim10
-rw-r--r--tests/arc/t18977.nim26
-rw-r--r--tests/arc/t19231.nim18
-rw-r--r--tests/arc/t19364.nim30
-rw-r--r--tests/arc/t19401.nim32
-rw-r--r--tests/arc/t19402.nim32
-rw-r--r--tests/arc/t19435.nim29
-rw-r--r--tests/arc/t19457.nim16
-rw-r--r--tests/arc/t19862.nim15
-rw-r--r--tests/arc/t20456.nim7
-rw-r--r--tests/arc/t20588.nim25
-rw-r--r--tests/arc/t21184.nim77
-rw-r--r--tests/arc/t22218.nim25
-rw-r--r--tests/arc/t22237.nim55
-rw-r--r--tests/arc/t22478.nim46
-rw-r--r--tests/arc/t22787.nim37
-rw-r--r--tests/arc/t23247.nim52
-rw-r--r--tests/arc/t9650.nim87
-rw-r--r--tests/arc/taliased_reassign.nim41
-rw-r--r--tests/arc/tamemfiles.nim110
-rw-r--r--tests/arc/tamodule.nim9
-rw-r--r--tests/arc/tarc_macro.nim57
-rw-r--r--tests/arc/tarc_orc.nim186
-rw-r--r--tests/arc/tarcmisc.nim836
-rw-r--r--tests/arc/tasyncawait.nim43
-rw-r--r--tests/arc/tasyncleak.nim21
-rw-r--r--tests/arc/tasyncleak2.nim88
-rw-r--r--tests/arc/tasyncleak3.nim47
-rw-r--r--tests/arc/tasyncleak4.nim21
-rw-r--r--tests/arc/tasyncorc.nim26
-rw-r--r--tests/arc/tcaseobj.nim222
-rw-r--r--tests/arc/tcaseobjcopy.nim253
-rw-r--r--tests/arc/tclosureiter.nim36
-rw-r--r--tests/arc/tcomputedgoto.nim (renamed from tests/casestmt/t12785.nim)21
-rw-r--r--tests/arc/tcomputedgotocopy.nim44
-rw-r--r--tests/arc/tconst_to_sink.nim26
-rw-r--r--tests/arc/tcontrolflow.nim118
-rw-r--r--tests/arc/tcursor_field_obj_constr.nim44
-rw-r--r--tests/arc/tcursor_on_localvar.nim161
-rw-r--r--tests/arc/tcursorloop.nim45
-rw-r--r--tests/arc/tcustomtrace.nim240
-rw-r--r--tests/arc/tdeepcopy.nim67
-rw-r--r--tests/arc/tdestroy_in_loopcond.nim74
-rw-r--r--tests/arc/tdup.nim71
-rw-r--r--tests/arc/testfile.txt2
-rw-r--r--tests/arc/texceptions.nim16
-rw-r--r--tests/arc/texplicit_sink.nim29
-rw-r--r--tests/arc/tfuncobj.nim38
-rw-r--r--tests/arc/thamming_orc.nim155
-rw-r--r--tests/arc/thamming_thinout.nim183
-rw-r--r--tests/arc/thard_alignment.nim148
-rw-r--r--tests/arc/thavlak_orc_stress.nim414
-rw-r--r--tests/arc/theavy_recursion.nim43
-rw-r--r--tests/arc/timportedobj.nim14
-rw-r--r--tests/arc/titeration_doesnt_copy.nim67
-rw-r--r--tests/arc/tkeys_lent.nim17
-rw-r--r--tests/arc/tmalloc.nim16
-rw-r--r--tests/arc/tmarshal.nim140
-rw-r--r--tests/arc/tmove_regression.nim22
-rw-r--r--tests/arc/tmovebug.nim779
-rw-r--r--tests/arc/tmovebugcopy.nim526
-rw-r--r--tests/arc/tnewseq_legacy.nim13
-rw-r--r--tests/arc/top_no_cursor2.nim53
-rw-r--r--tests/arc/topenarray.nim86
-rw-r--r--tests/arc/topt_cursor.nim57
-rw-r--r--tests/arc/topt_cursor2.nim76
-rw-r--r--tests/arc/topt_no_cursor.nim376
-rw-r--r--tests/arc/topt_refcursors.nim54
-rw-r--r--tests/arc/topt_wasmoved_destroy_pairs.nim94
-rw-r--r--tests/arc/torc_basic_test.nim138
-rw-r--r--tests/arc/torc_selfcycles.nim33
-rw-r--r--tests/arc/torcbench.nim38
-rw-r--r--tests/arc/torcmisc.nim66
-rw-r--r--tests/arc/tref_cast_error.nim15
-rw-r--r--tests/arc/trepr.nim63
-rw-r--r--tests/arc/trtree.nim (renamed from tests/generics/trtree.nim)116
-rw-r--r--tests/arc/tshared_ptr_crash.nim67
-rw-r--r--tests/arc/tstrformat.nim22
-rw-r--r--tests/arc/tstringliteral.nim17
-rw-r--r--tests/arc/tthread.nim63
-rw-r--r--tests/arc/tunref_cycle.nim26
-rw-r--r--tests/arc/tweave.nim157
-rw-r--r--tests/arc/tweavecopy.nim154
-rw-r--r--tests/arc/twrong_sinkinference.nim18
-rw-r--r--tests/array/t15117.nim27
-rw-r--r--tests/array/t20248.nim14
-rw-r--r--tests/array/t9932.nim11
-rw-r--r--tests/array/tarray.nim33
-rw-r--r--tests/array/tinvalidarrayaccess.nim (renamed from tests/misc/tinvalidarrayaccess.nim)0
-rw-r--r--tests/array/tinvalidarrayaccess2.nim (renamed from tests/misc/tinvalidarrayaccess2.nim)0
-rw-r--r--tests/array/tlargeindex.nim18
-rw-r--r--tests/assert/panicoverride.nim15
-rw-r--r--tests/assert/t21195.nim6
-rw-r--r--tests/assert/tassert.nim2
-rw-r--r--tests/assert/tassert2.nim58
-rw-r--r--tests/assert/tassert_c.nim15
-rw-r--r--tests/assert/tdoassert.nim20
-rw-r--r--tests/assert/testhelper.nim12
-rw-r--r--tests/assert/trelativeassert.nim11
-rw-r--r--tests/assign/moverload_asgn2.nim4
-rw-r--r--tests/assign/tassign.nim8
-rw-r--r--tests/assign/tobject_assign.nim49
-rw-r--r--tests/assign/tvariantasgn.nim13
-rw-r--r--tests/ast_pattern_matching.nim6
-rw-r--r--tests/astspec/tastspec.nim58
-rw-r--r--tests/async/nim.cfg1
-rw-r--r--tests/async/t11558.nim13
-rw-r--r--tests/async/t12221.nim34
-rw-r--r--tests/async/t13889.nim27
-rw-r--r--tests/async/t14820.nim25
-rw-r--r--tests/async/t15148.nim12
-rw-r--r--tests/async/t15804.nim15
-rw-r--r--tests/async/t17045.nim28
-rw-r--r--tests/async/t20111.nim19
-rw-r--r--tests/async/t21447.nim6
-rw-r--r--tests/async/t21893.nim13
-rw-r--r--tests/async/t22210.nim41
-rw-r--r--tests/async/t22210_2.nim73
-rw-r--r--tests/async/t6846.nim3
-rw-r--r--tests/async/t7758.nim10
-rw-r--r--tests/async/tacceptcloserace.nim4
-rw-r--r--tests/async/tasync_gcsafe.nim2
-rw-r--r--tests/async/tasync_gcunsafe.nim4
-rw-r--r--tests/async/tasync_misc.nim43
-rw-r--r--tests/async/tasync_noasync.nim44
-rw-r--r--tests/async/tasync_nofuture.nim11
-rw-r--r--tests/async/tasync_traceback.nim105
-rw-r--r--tests/async/tasyncawait.nim35
-rw-r--r--tests/async/tasyncawait_cyclebreaker.nim73
-rw-r--r--tests/async/tasyncclosestall.nim1
-rw-r--r--tests/async/tasyncconnect.nim2
-rw-r--r--tests/async/tasyncdial.nim3
-rw-r--r--tests/async/tasynceagain.nim67
-rw-r--r--tests/async/tasyncfilewrite.nim3
-rw-r--r--tests/async/tasyncintemplate.nim62
-rw-r--r--tests/async/tasyncnetudp.nim90
-rw-r--r--tests/async/tasyncsend4757.nim20
-rw-r--r--tests/async/tasyncssl.nim33
-rw-r--r--tests/async/tasynctry.nim29
-rw-r--r--tests/async/tbreak_must_exec_finally.nim25
-rw-r--r--tests/async/tdiscardableproc.nim9
-rw-r--r--tests/async/testmanyasyncevents.nim3
-rw-r--r--tests/async/tfuturestream.nim2
-rw-r--r--tests/async/tfuturevar.nim5
-rw-r--r--tests/async/tioselectors.nim50
-rw-r--r--tests/async/tjsandnativeasync.nim2
-rw-r--r--tests/async/tnewasyncudp.nim18
-rw-r--r--tests/async/tpendingcheck.nim2
-rw-r--r--tests/async/tupcoming_async.nim4
-rw-r--r--tests/async/twinasyncrw.nim45
-rw-r--r--tests/avr/nim.cfg12
-rw-r--r--tests/avr/panicoverride.nim13
-rw-r--r--tests/avr/thello.nim6
-rw-r--r--tests/benchmarks/readme.md5
-rw-r--r--tests/benchmarks/ttls.nim30
-rw-r--r--tests/bind/tdatabind.nim95
-rw-r--r--tests/borrow/tborrow.nim21
-rw-r--r--tests/borrow/tinvalidborrow.nim16
-rw-r--r--tests/c/tcompile.c (renamed from tests/compilepragma/test.c)0
-rw-r--r--tests/c/tcompile.nim (renamed from tests/compilepragma/test.nim)2
-rw-r--r--tests/c/temit.nim (renamed from tests/misc/temit.nim)1
-rw-r--r--tests/c/treservedcidentsasfields.nim (renamed from tests/misc/treservedcidentsasfields.nim)78
-rw-r--r--tests/casestmt/t18964.nim12
-rw-r--r--tests/casestmt/tcase_issues.nim7
-rw-r--r--tests/casestmt/tcaseexpr1.nim26
-rw-r--r--tests/casestmt/tcasestmt.nim79
-rw-r--r--tests/casestmt/tcstring.nim52
-rw-r--r--tests/casestmt/tincompletecaseobject.nim4
-rw-r--r--tests/casestmt/tincompletecaseobject2.nim19
-rw-r--r--tests/casestmt/trangeexhaustiveness.nim7
-rw-r--r--tests/cast/tcast.nim21
-rw-r--r--tests/ccgbugs/m1/defs.nim4
-rw-r--r--tests/ccgbugs/m19445.c3
-rw-r--r--tests/ccgbugs/m2/defs.nim4
-rw-r--r--tests/ccgbugs/mstatic_assert.nim6
-rw-r--r--tests/ccgbugs/t10128.nim18
-rw-r--r--tests/ccgbugs/t10964.nim7
-rw-r--r--tests/ccgbugs/t13062.nim33
-rw-r--r--tests/ccgbugs/t13902.nim12
-rw-r--r--tests/ccgbugs/t15428.nim22
-rw-r--r--tests/ccgbugs/t16027.nim13
-rw-r--r--tests/ccgbugs/t16374.nim38
-rw-r--r--tests/ccgbugs/t19445.nim13
-rw-r--r--tests/ccgbugs/t20139.nim10
-rw-r--r--tests/ccgbugs/t20141.nim27
-rw-r--r--tests/ccgbugs/t20787.nim4
-rw-r--r--tests/ccgbugs/t21116.nim10
-rw-r--r--tests/ccgbugs/t21972.nim33
-rw-r--r--tests/ccgbugs/t21995.nim9
-rw-r--r--tests/ccgbugs/t22462.nim20
-rw-r--r--tests/ccgbugs/t23796.nim25
-rw-r--r--tests/ccgbugs/t2procs.nim18
-rw-r--r--tests/ccgbugs/t5296.nim9
-rw-r--r--tests/ccgbugs/t6756.nim2
-rw-r--r--tests/ccgbugs/t8967.nim12
-rw-r--r--tests/ccgbugs/t9286.nim4
-rw-r--r--tests/ccgbugs/t9655.nim30
-rw-r--r--tests/ccgbugs/targ_lefttoright.nim71
-rw-r--r--tests/ccgbugs/tassign_nil_strings.nim2
-rw-r--r--tests/ccgbugs/tbug21505.nim39
-rw-r--r--tests/ccgbugs/tccgen1.nim2
-rw-r--r--tests/ccgbugs/tcgbug.nim70
-rw-r--r--tests/ccgbugs/tcodegenbug1.nim51
-rw-r--r--tests/ccgbugs/tcodegenbug_bool.nim11
-rw-r--r--tests/ccgbugs/tcompile_time_var_at_runtime.nim11
-rw-r--r--tests/ccgbugs/tctypes.nim43
-rw-r--r--tests/ccgbugs/tdeepcopy_addr_rval.nim1
-rw-r--r--tests/ccgbugs/tderefblock.nim76
-rw-r--r--tests/ccgbugs/tforward_decl_only.nim4
-rw-r--r--tests/ccgbugs/thtiobj.nim1
-rw-r--r--tests/ccgbugs/tissues.nim (renamed from tests/ccgbugs/trecursive_closure.nim)20
-rw-r--r--tests/ccgbugs/tlvalueconv.nim32
-rw-r--r--tests/ccgbugs/tmangle.nim16
-rw-r--r--tests/ccgbugs/tmissingbracket.nim2
-rw-r--r--tests/ccgbugs/tmissingderef.nim1
-rw-r--r--tests/ccgbugs/tmissinginit.nim1
-rw-r--r--tests/ccgbugs/tmissingvolatile.nim4
-rw-r--r--tests/ccgbugs/tnoalias.nim13
-rw-r--r--tests/ccgbugs/tprogmem.nim2
-rw-r--r--tests/ccgbugs/tret_arg_init.nim2
-rw-r--r--tests/ccgbugs/tsamename3.nim120
-rw-r--r--tests/ccgbugs/tuple_canon.nim2
-rw-r--r--tests/ccgbugs/twrong_setconstr.nim146
-rw-r--r--tests/ccgbugs/twrong_tupleconv.nim17
-rw-r--r--tests/ccgbugs2/tcodegen.nim47
-rw-r--r--tests/ccgbugs2/tinefficient_const_table.nim (renamed from tests/ccgbugs/tinefficient_const_table.nim)4
-rw-r--r--tests/closure/t11042.nim55
-rw-r--r--tests/closure/t15594.nim10
-rw-r--r--tests/closure/t19095.nim35
-rw-r--r--tests/closure/t20152.nim20
-rw-r--r--tests/closure/t8550.nim1
-rw-r--r--tests/closure/t9334.nim19
-rw-r--r--tests/closure/tcapture.nim26
-rw-r--r--tests/closure/tclosure.nim247
-rw-r--r--tests/closure/tclosure_issues.nim6
-rw-r--r--tests/closure/tinvalidclosure.nim2
-rw-r--r--tests/closure/tinvalidclosure4.nim9
-rw-r--r--tests/closure/tinvalidclosure5.nim10
-rw-r--r--tests/closure/tnested.nim36
-rw-r--r--tests/closure/tstmtlist.nim9
-rw-r--r--tests/closure/ttimeinfo.nim8
-rw-r--r--tests/codegen/titaniummangle.nim193
-rw-r--r--tests/collections/tactiontable.nim (renamed from tests/actiontable/tactiontable.nim)0
-rw-r--r--tests/collections/tcollections.nim81
-rw-r--r--tests/collections/tcollections_to_string.nim11
-rw-r--r--tests/collections/thashsets.nim280
-rw-r--r--tests/collections/tseq.nim (renamed from tests/seq/tseq.nim)116
-rw-r--r--tests/collections/ttables.nim202
-rw-r--r--tests/collections/ttablesthreads.nim115
-rw-r--r--tests/compileoption/texperimental.nim20
-rw-r--r--tests/compileoption/texperimental.nims19
-rw-r--r--tests/compiler/samplelib.nim2
-rw-r--r--tests/compiler/t12684.nim7
-rw-r--r--tests/compiler/tasciitables.nim4
-rw-r--r--tests/compiler/tasm.nim15
-rw-r--r--tests/compiler/tbtrees.nim84
-rw-r--r--tests/compiler/tcmdlineclib.nim3
-rw-r--r--tests/compiler/tcmdlineclib.nims10
-rw-r--r--tests/compiler/tcmdlineoswin.nim2
-rw-r--r--tests/compiler/tcppCompileToNamespace.nim1
-rw-r--r--tests/compiler/tdebugutils.nim38
-rw-r--r--tests/compiler/tgrammar.nim7
-rw-r--r--tests/compiler/tint128.nim184
-rw-r--r--tests/compiler/tnimblecmd.nim75
-rw-r--r--tests/compiler/tpathutils.nim18
-rw-r--r--tests/compiler/tprefixmatches.nim32
-rw-r--r--tests/compiler/tunittest_light.nim4
-rw-r--r--tests/compilerapi/invalid.nim1
-rw-r--r--tests/compilerapi/tcompilerapi.nim71
-rw-r--r--tests/compiles/mstaticlib.nim1
-rw-r--r--tests/compiles/t8630.nim2
-rw-r--r--tests/compiles/trecursive_generic_in_compiles.nim2
-rw-r--r--tests/compiles/tstaticlib.nim22
-rw-r--r--tests/concepts/t18409.nim37
-rw-r--r--tests/concepts/t19730.nim20
-rw-r--r--tests/concepts/t20237.nim3
-rw-r--r--tests/concepts/t3330.nim47
-rw-r--r--tests/concepts/t8012.nim15
-rw-r--r--tests/concepts/t8558.nim26
-rw-r--r--tests/concepts/t976.nim57
-rw-r--r--tests/concepts/tconcepts.nim13
-rw-r--r--tests/concepts/tconcepts_issues.nim197
-rw-r--r--tests/concepts/tconcepts_overload_precedence.nim2
-rw-r--r--tests/concepts/texplain.nim112
-rw-r--r--tests/concepts/tmapconcept.nim2
-rw-r--r--tests/concepts/treversable.nim2
-rw-r--r--tests/concepts/tspec.nim105
-rw-r--r--tests/concepts/tusertypeclasses.nim3
-rw-r--r--tests/concepts/tusertypeclasses2.nim73
-rw-r--r--tests/concepts/twrapconcept.nim3
-rw-r--r--tests/config.nims46
-rw-r--r--tests/constr/tglobal.nim7
-rw-r--r--tests/constructors/a.nim2
-rw-r--r--tests/constructors/b.nim2
-rw-r--r--tests/constructors/t18990.nim3
-rw-r--r--tests/constructors/tconstr1.nim (renamed from tests/constr/tconstr1.nim)0
-rw-r--r--tests/constructors/tconstr2.nim (renamed from tests/constr/tconstr2.nim)0
-rw-r--r--tests/constructors/tinvalid_construction.nim327
-rw-r--r--tests/controlflow/tcontrolflow.nim21
-rw-r--r--tests/controlflow/tstatret.nim6
-rw-r--r--tests/controlflow/tunamedbreak.nim15
-rw-r--r--tests/controlflow/tunreachable.nim79
-rw-r--r--tests/controlflow/tunreachable2.nim12
-rw-r--r--tests/converter/m18986.nim3
-rw-r--r--tests/converter/mdontleak.nim3
-rw-r--r--tests/converter/t18986.nim10
-rw-r--r--tests/converter/t21531.nim10
-rw-r--r--tests/converter/t7097.nim38
-rw-r--r--tests/converter/t7098.nim4
-rw-r--r--tests/converter/t9165.nim11
-rw-r--r--tests/converter/tconverter.nim11
-rw-r--r--tests/converter/tconverter_unique_ptr.nim15
-rw-r--r--tests/converter/tconverter_with_varargs.nim2
-rw-r--r--tests/converter/tdontleak.nim10
-rw-r--r--tests/converter/texplicit_conversion.nim6
-rw-r--r--tests/converter/tgenericconverter.nim24
-rw-r--r--tests/converter/tor_in_converter.nim2
-rw-r--r--tests/coroutines/texceptions.nim2
-rw-r--r--tests/coroutines/tgc.nim27
-rw-r--r--tests/coroutines/titerators.nim2
-rw-r--r--tests/coroutines/twait.nim35
-rw-r--r--tests/cpp/23962.h17
-rw-r--r--tests/cpp/enum.hpp3
-rw-r--r--tests/cpp/fam.h4
-rw-r--r--tests/cpp/t12946.nim8
-rw-r--r--tests/cpp/t22679.nim50
-rw-r--r--tests/cpp/t22680.nim50
-rw-r--r--tests/cpp/t22712.nim15
-rw-r--r--tests/cpp/t23306.nim12
-rw-r--r--tests/cpp/t23434.nim17
-rw-r--r--tests/cpp/t23657.nim54
-rw-r--r--tests/cpp/t23962.nim32
-rw-r--r--tests/cpp/t4834.nim17
-rw-r--r--tests/cpp/t6986.nim3
-rw-r--r--tests/cpp/tasync_cpp.nim2
-rw-r--r--tests/cpp/tcasts.nim3
-rw-r--r--tests/cpp/tcodegendecl.nim17
-rw-r--r--tests/cpp/tconstructor.nim131
-rw-r--r--tests/cpp/tcovariancerules.nim43
-rw-r--r--tests/cpp/tcppraise.nim2
-rw-r--r--tests/cpp/tdont_init_instantiation.nim2
-rw-r--r--tests/cpp/temitlist.nim6
-rw-r--r--tests/cpp/tempty_generic_obj.nim4
-rw-r--r--tests/cpp/tenum_set.nim9
-rw-r--r--tests/cpp/tevalorder.nim2
-rw-r--r--tests/cpp/tfam.nim7
-rw-r--r--tests/cpp/tinitializers.nim60
-rw-r--r--tests/cpp/tmember.nim75
-rw-r--r--tests/cpp/tmember_forward_declaration.nim27
-rw-r--r--tests/cpp/tnoinitfield.nim30
-rw-r--r--tests/cpp/torc.nim75
-rw-r--r--tests/cpp/tpassbypragmas.nim27
-rw-r--r--tests/cpp/tretvar.nim4
-rw-r--r--tests/cpp/ttemplatetype.nim2
-rw-r--r--tests/cpp/tterminate_handler.nim3
-rw-r--r--tests/cpp/ttypeinfo1.nim (renamed from tests/cpp/ttypeinfo.nim)0
-rw-r--r--tests/cpp/tvector_iterator.nim4
-rw-r--r--tests/cpp/tvirtual.nim126
-rw-r--r--tests/cpp/virtualptr.nim9
-rw-r--r--tests/defaultprocparam/tdefaultprocparam.nim8
-rw-r--r--tests/defer/t22309.nim11
-rw-r--r--tests/deprecated/tannot.nim9
-rw-r--r--tests/deprecated/tmodule1.nim23
-rw-r--r--tests/deps/jester-#head/jester.nim1350
-rw-r--r--tests/deps/jester-#head/jester.nimble22
-rw-r--r--tests/deps/jester-#head/jester/patterns.nim141
-rw-r--r--tests/deps/jester-#head/jester/private/errorpages.nim19
-rw-r--r--tests/deps/jester-#head/jester/private/utils.nim195
-rw-r--r--tests/deps/jester-#head/jester/request.nim184
-rw-r--r--tests/deps/opengl-1.1.0/glu.nim326
-rw-r--r--tests/deps/opengl-1.1.0/glut.nim366
-rw-r--r--tests/deps/opengl-1.1.0/glx.nim154
-rw-r--r--tests/deps/opengl-1.1.0/opengl.nim8481
-rw-r--r--tests/deps/opengl-1.1.0/opengl.nimble12
-rw-r--r--tests/deps/opengl-1.1.0/wingl.nim369
-rw-r--r--tests/deps/x11-1.0/cursorfont.nim110
-rw-r--r--tests/deps/x11-1.0/keysym.nim1926
-rw-r--r--tests/deps/x11-1.0/x.nim400
-rw-r--r--tests/deps/x11-1.0/x11.nimble11
-rw-r--r--tests/deps/x11-1.0/x11pragma.nim20
-rw-r--r--tests/deps/x11-1.0/xatom.nim81
-rw-r--r--tests/deps/x11-1.0/xcms.nim389
-rw-r--r--tests/deps/x11-1.0/xf86dga.nim235
-rw-r--r--tests/deps/x11-1.0/xf86vmode.nim229
-rw-r--r--tests/deps/x11-1.0/xi.nim307
-rw-r--r--tests/deps/x11-1.0/xinerama.nim25
-rw-r--r--tests/deps/x11-1.0/xkb.nim2387
-rw-r--r--tests/deps/x11-1.0/xkblib.nim661
-rw-r--r--tests/deps/x11-1.0/xlib.nim2026
-rw-r--r--tests/deps/x11-1.0/xrandr.nim194
-rw-r--r--tests/deps/x11-1.0/xrender.nim241
-rw-r--r--tests/deps/x11-1.0/xresource.nim201
-rw-r--r--tests/deps/x11-1.0/xshm.nim77
-rw-r--r--tests/deps/x11-1.0/xutil.nim412
-rw-r--r--tests/deps/x11-1.0/xv.nim84
-rw-r--r--tests/deps/x11-1.0/xvlib.nim234
-rw-r--r--tests/deps/zip-0.2.1/zip.nimble18
-rw-r--r--tests/deps/zip-0.2.1/zip/gzipfiles.nim97
-rw-r--r--tests/deps/zip-0.2.1/zip/libzip.nim252
-rw-r--r--tests/deps/zip-0.2.1/zip/private/libzip_all.c4193
-rw-r--r--tests/deps/zip-0.2.1/zip/zipfiles.nim193
-rw-r--r--tests/deps/zip-0.2.1/zip/zlib.nim425
-rw-r--r--tests/deps/zip-0.2.1/zip/zzip.nim176
-rw-r--r--tests/destructor/const_smart_ptr.nim10
-rw-r--r--tests/destructor/nim.cfg1
-rw-r--r--tests/destructor/t12037.nim8
-rw-r--r--tests/destructor/t16607.nim23
-rw-r--r--tests/destructor/t17198.nim32
-rw-r--r--tests/destructor/t23748.nim31
-rw-r--r--tests/destructor/t23837.nim51
-rw-r--r--tests/destructor/t5342.nim24
-rw-r--r--tests/destructor/t7346.nim3
-rw-r--r--tests/destructor/t9440.nim52
-rw-r--r--tests/destructor/tarc.nim39
-rw-r--r--tests/destructor/tarc2.nim5
-rw-r--r--tests/destructor/tarray_indexing.nim4
-rw-r--r--tests/destructor/tasync_prototype.nim5
-rw-r--r--tests/destructor/tasync_prototype_cyclic.nim1
-rw-r--r--tests/destructor/tatomicptrs.nim15
-rw-r--r--tests/destructor/tbintree2.nim12
-rw-r--r--tests/destructor/tcaseobj_transitions.nim2
-rw-r--r--tests/destructor/tcomplexobjconstr.nim16
-rw-r--r--tests/destructor/tconsume_twice.nim4
-rw-r--r--tests/destructor/tcustomseqs.nim2
-rw-r--r--tests/destructor/tcustomstrings.nim22
-rw-r--r--tests/destructor/tcycle1.nim1
-rw-r--r--tests/destructor/tcycle2.nim18
-rw-r--r--tests/destructor/tcycle3.nim34
-rw-r--r--tests/destructor/tdestructor.nim52
-rw-r--r--tests/destructor/tdestructor3.nim79
-rw-r--r--tests/destructor/tdestructor_too_late.nim2
-rw-r--r--tests/destructor/tdistinctseq.nim8
-rw-r--r--tests/destructor/tdont_return_unowned_from_owned.nim37
-rw-r--r--tests/destructor/tfinalizer.nim2
-rw-r--r--tests/destructor/tgcdestructors.nim4
-rw-r--r--tests/destructor/tglobaldestructor.nim2
-rw-r--r--tests/destructor/tgotoexc_leak.nim19
-rw-r--r--tests/destructor/tgotoexceptions4.nim22
-rw-r--r--tests/destructor/tgotoexceptions5.nim45
-rw-r--r--tests/destructor/tgotoexceptions6.nim10
-rw-r--r--tests/destructor/tgotoexceptions7.nim49
-rw-r--r--tests/destructor/tgotoexceptions8.nim76
-rw-r--r--tests/destructor/tmatrix.nim11
-rw-r--r--tests/destructor/tmisc_destructors.nim6
-rw-r--r--tests/destructor/tmove.nim18
-rw-r--r--tests/destructor/tmove_objconstr.nim43
-rw-r--r--tests/destructor/tnewruntime_misc.nim27
-rw-r--r--tests/destructor/tnewruntime_strutils.nim47
-rw-r--r--tests/destructor/tnonvardestructor.nim247
-rw-r--r--tests/destructor/topttree.nim1
-rw-r--r--tests/destructor/towned_binary_tree.nim8
-rw-r--r--tests/destructor/tprevent_assign.nim2
-rw-r--r--tests/destructor/tprevent_assign2.nim11
-rw-r--r--tests/destructor/tprevent_assign3.nim11
-rw-r--r--tests/destructor/trecursive.nim26
-rw-r--r--tests/destructor/tselect.nim26
-rw-r--r--tests/destructor/tsetjmp_raise.nim2
-rw-r--r--tests/destructor/tsimpleclosure.nim4
-rw-r--r--tests/destructor/tsink.nim70
-rw-r--r--tests/destructor/ttuple.nim2
-rw-r--r--tests/destructor/tuse_ownedref_after_move.nim2
-rw-r--r--tests/destructor/tuse_result_prevents_sinks.nim7
-rw-r--r--tests/destructor/tv2_cast.nim99
-rw-r--r--tests/destructor/tv2_raise.nim2
-rw-r--r--tests/destructor/twasmoved.nim14
-rw-r--r--tests/destructor/twasmoved_error.nim37
-rw-r--r--tests/destructor/twidgets_unown.nim2
-rw-r--r--tests/discard/t23677.nim12
-rw-r--r--tests/discard/tdiscardable.nim108
-rw-r--r--tests/discard/tfinallyerrmsg.nim19
-rw-r--r--tests/discard/tillegaldiscardtypes.nim14
-rw-r--r--tests/discard/tneedsdiscard.nim2
-rw-r--r--tests/discard/tneedsdiscard_in_for.nim4
-rw-r--r--tests/discard/tvoidcontext.nim2
-rw-r--r--tests/distinct/t7165.nim15
-rw-r--r--tests/distinct/tborrow.nim132
-rw-r--r--tests/distinct/tcomplexaddressableconv.nim21
-rw-r--r--tests/distinct/tdistinct.nim119
-rw-r--r--tests/distinct/tdistinct_issues.nim14
-rw-r--r--tests/distinct/tinvalidborrow.nim42
-rw-r--r--tests/distinct/tnil.nim18
-rw-r--r--tests/distinct/typeclassborrow.nim56
-rw-r--r--tests/dll/client.nim9
-rw-r--r--tests/dll/nimhcr_0_3.nim1
-rw-r--r--tests/dll/nimhcr_2_1.nim2
-rw-r--r--tests/dll/nimhcr_basic.nim8
-rw-r--r--tests/dll/nimhcr_integration.nim20
-rw-r--r--tests/dll/nimhcr_unit.nim8
-rw-r--r--tests/dll/server.nim1
-rw-r--r--tests/effects/tcast_as_pragma.nim18
-rw-r--r--tests/effects/tdiagnostic_messages.nim37
-rw-r--r--tests/effects/teffects1.nim38
-rw-r--r--tests/effects/teffects10.nim12
-rw-r--r--tests/effects/teffects11.nim21
-rw-r--r--tests/effects/teffects12.nim52
-rw-r--r--tests/effects/teffects13.nim19
-rw-r--r--tests/effects/teffects14.nim15
-rw-r--r--tests/effects/teffects15.nim18
-rw-r--r--tests/effects/teffects16.nim20
-rw-r--r--tests/effects/teffects17.nim17
-rw-r--r--tests/effects/teffects18.nim19
-rw-r--r--tests/effects/teffects19.nim23
-rw-r--r--tests/effects/teffects2.nim5
-rw-r--r--tests/effects/teffects3.nim2
-rw-r--r--tests/effects/teffects4.nim2
-rw-r--r--tests/effects/teffects6.nim22
-rw-r--r--tests/effects/teffects7.nim8
-rw-r--r--tests/effects/teffects8.nim3
-rw-r--r--tests/effects/teffects9.nim22
-rw-r--r--tests/effects/teffectsmisc.nim39
-rw-r--r--tests/effects/tfuncs_cannot_mutate.nim35
-rw-r--r--tests/effects/tfuncs_cannot_mutate2.nim24
-rw-r--r--tests/effects/tfuncs_cannot_mutate3.nim35
-rw-r--r--tests/effects/tfuncs_cannot_mutate_simple.nim19
-rw-r--r--tests/effects/tgcsafe.nim4
-rw-r--r--tests/effects/tgcsafe2.nim2
-rw-r--r--tests/effects/tgcsafe3.nim2
-rw-r--r--tests/effects/thooks.nim16
-rw-r--r--tests/effects/tlaxeffects.nim11
-rw-r--r--tests/effects/tnestedprocs.nim63
-rw-r--r--tests/effects/tnosideeffect.nim24
-rw-r--r--tests/effects/tstrict_caseobjects.nim47
-rw-r--r--tests/effects/tstrict_effects.nim27
-rw-r--r--tests/effects/tstrict_effects2.nim28
-rw-r--r--tests/effects/tstrict_effects3.nim57
-rw-r--r--tests/effects/tstrict_effects_sort.nim27
-rw-r--r--tests/effects/tstrict_funcs.nim46
-rw-r--r--tests/effects/tstrict_funcs_imports.nim176
-rw-r--r--tests/effects/tstrict_funcs_imports_js.nim20
-rw-r--r--tests/effects/tstrictfuncs_misc.nim65
-rw-r--r--tests/enum/m16462_1.nim3
-rw-r--r--tests/enum/m16462_2.nim3
-rw-r--r--tests/enum/mcrossmodule.nim6
-rw-r--r--tests/enum/t16462.nim5
-rw-r--r--tests/enum/t21863.nim28
-rw-r--r--tests/enum/tambiguousoverloads.nim26
-rw-r--r--tests/enum/tcrossmodule.nim15
-rw-r--r--tests/enum/tenum.nim139
-rw-r--r--tests/enum/tenum_duplicate.nim10
-rw-r--r--tests/enum/tenum_invalid.nim8
-rw-r--r--tests/enum/tenum_self.nim11
-rw-r--r--tests/enum/toverloadable_enums.nim120
-rw-r--r--tests/enum/toverloadedname.nim7
-rw-r--r--tests/enum/tpure_enums_conflict.nim14
-rw-r--r--tests/enum/tpure_enums_conflict_legacy.nim25
-rw-r--r--tests/enum/tredefinition.nim9
-rw-r--r--tests/enum/ttypenameconflict.nim13
-rw-r--r--tests/errmsgs/mambparam1.nim1
-rw-r--r--tests/errmsgs/mambparam2.nim2
-rw-r--r--tests/errmsgs/mambparam3.nim1
-rw-r--r--tests/errmsgs/mb.nim (renamed from tests/clearmsg/mb.nim)0
-rw-r--r--tests/errmsgs/mc.nim (renamed from tests/clearmsg/mc.nim)0
-rw-r--r--tests/errmsgs/t10251.nim19
-rw-r--r--tests/errmsgs/t10376.nim3
-rw-r--r--tests/errmsgs/t10489_a.nim2
-rw-r--r--tests/errmsgs/t10489_b.nim2
-rw-r--r--tests/errmsgs/t10542.nim24
-rw-r--r--tests/errmsgs/t10594.nim2
-rw-r--r--tests/errmsgs/t10734.nim20
-rw-r--r--tests/errmsgs/t10735.nim68
-rw-r--r--tests/errmsgs/t12844.nim6
-rw-r--r--tests/errmsgs/t14444.nim14
-rw-r--r--tests/errmsgs/t16654.nim12
-rw-r--r--tests/errmsgs/t17460.nim19
-rw-r--r--tests/errmsgs/t18327.nim5
-rw-r--r--tests/errmsgs/t18886.nim18
-rw-r--r--tests/errmsgs/t18983.nim7
-rw-r--r--tests/errmsgs/t19224.nim12
-rw-r--r--tests/errmsgs/t19882.nim10
-rw-r--r--tests/errmsgs/t19882_2.nim5
-rw-r--r--tests/errmsgs/t21257.nim20
-rw-r--r--tests/errmsgs/t22097.nim9
-rw-r--r--tests/errmsgs/t22284.nim25
-rw-r--r--tests/errmsgs/t22753.nim52
-rw-r--r--tests/errmsgs/t22852.nim9
-rw-r--r--tests/errmsgs/t22996.nim7
-rw-r--r--tests/errmsgs/t23060.nim5
-rw-r--r--tests/errmsgs/t23419.nim5
-rw-r--r--tests/errmsgs/t23435.nim12
-rw-r--r--tests/errmsgs/t23536.nim26
-rw-r--r--tests/errmsgs/t2614.nim21
-rw-r--r--tests/errmsgs/t5167_4.nim2
-rw-r--r--tests/errmsgs/t5167_5.nim22
-rw-r--r--tests/errmsgs/t5282.nim5
-rw-r--r--tests/errmsgs/t5870.nim2
-rw-r--r--tests/errmsgs/t6499.nim6
-rw-r--r--tests/errmsgs/t6608.nim15
-rw-r--r--tests/errmsgs/t8064.nim9
-rw-r--r--tests/errmsgs/t8434.nim5
-rw-r--r--tests/errmsgs/t8610.nim4
-rw-r--r--tests/errmsgs/t8794.nim28
-rw-r--r--tests/errmsgs/t9768.nim11
-rw-r--r--tests/errmsgs/t9908_01.nim2
-rw-r--r--tests/errmsgs/t9908_02.nim2
-rw-r--r--tests/errmsgs/ta.nim (renamed from tests/clearmsg/ta.nim)0
-rw-r--r--tests/errmsgs/tambparam.nim16
-rw-r--r--tests/errmsgs/tambparam_legacy.nim14
-rw-r--r--tests/errmsgs/tassignunpack.nim3
-rw-r--r--tests/errmsgs/tcall_with_default_arg.nim2
-rw-r--r--tests/errmsgs/tcannot_capture_builtin.nim2
-rw-r--r--tests/errmsgs/tcase_stmt.nim29
-rw-r--r--tests/errmsgs/tconceptconstraint.nim3
-rw-r--r--tests/errmsgs/tconcisetypemismatch.nim23
-rw-r--r--tests/errmsgs/tconstinfo.nim7
-rw-r--r--tests/errmsgs/tconsttypemismatch.nim (renamed from tests/clearmsg/tconsttypemismatch.nim)0
-rw-r--r--tests/errmsgs/tdeclaredlocs.nim92
-rw-r--r--tests/errmsgs/tdistinct_nil.nim23
-rw-r--r--tests/errmsgs/tdont_show_system.nim2
-rw-r--r--tests/errmsgs/tgcsafety.nim11
-rw-r--r--tests/errmsgs/tgenericconstraint.nim3
-rw-r--r--tests/errmsgs/tgenericmismatchsegfault.nim13
-rw-r--r--tests/errmsgs/tgenericmismatchsegfault_legacy.nim10
-rw-r--r--tests/errmsgs/tinconsistentgensym.nim25
-rw-r--r--tests/errmsgs/tinteger_literals.nim25
-rw-r--r--tests/errmsgs/tinvalidinout.nim2
-rw-r--r--tests/errmsgs/tmacroerrorproc.nim (renamed from tests/clearmsg/tmacroerrorproc.nim)0
-rw-r--r--tests/errmsgs/tmetaobjectfields.nim75
-rw-r--r--tests/errmsgs/tnested_empty_seq.nim2
-rw-r--r--tests/errmsgs/tnon_concrete_cast.nim2
-rw-r--r--tests/errmsgs/tnoop.nim (renamed from tests/misc/tnoop.nim)3
-rw-r--r--tests/errmsgs/tproc_mismatch.nim74
-rw-r--r--tests/errmsgs/tproper_stacktrace.nim33
-rw-r--r--tests/errmsgs/tproper_stacktrace2.nim3
-rw-r--r--tests/errmsgs/tproper_stacktrace3.nim3
-rw-r--r--tests/errmsgs/treportunused.nim58
-rw-r--r--tests/errmsgs/tsigmatch.nim60
-rw-r--r--tests/errmsgs/tsigmatch2.nim47
-rw-r--r--tests/errmsgs/tsimpletypecheck.nim (renamed from tests/misc/tsimtych.nim)2
-rw-r--r--tests/errmsgs/tstaticexprscope.nim2
-rw-r--r--tests/errmsgs/tsubscriptmismatch.nim11
-rw-r--r--tests/errmsgs/tsubscriptmismatch_legacy.nim10
-rw-r--r--tests/errmsgs/ttupleindexoutofbounds.nim2
-rw-r--r--tests/errmsgs/ttypeAllowed.nim10
-rw-r--r--tests/errmsgs/tundeclared_field.nim50
-rw-r--r--tests/errmsgs/tundeclared_routine.nim44
-rw-r--r--tests/errmsgs/tundeclared_routine_compiles.nim (renamed from tests/errmsgs/undeclared_routime_compiles.nim)0
-rw-r--r--tests/errmsgs/tunknown_named_parameter.nim14
-rw-r--r--tests/errmsgs/tunresolvedinnerproc.nim (renamed from tests/misc/tnoinst.nim)10
-rw-r--r--tests/errmsgs/tuntypedoverload.nim37
-rw-r--r--tests/errmsgs/twrong_at_operator.nim9
-rw-r--r--tests/errmsgs/twrong_explicit_typeargs.nim26
-rw-r--r--tests/errmsgs/twrong_explicit_typeargs_legacy.nim25
-rw-r--r--tests/errmsgs/twrongcolon.nim7
-rw-r--r--tests/errmsgs/undeclared_routime.nim13
-rw-r--r--tests/errmsgs/undeclared_routime2.nim9
-rw-r--r--tests/errmsgs/undeclared_routime3.nim13
-rw-r--r--tests/errmsgs/undeclared_routime4.nim10
-rw-r--r--tests/errmsgs/undeclared_routime5.nim9
-rw-r--r--tests/exception/m21261.nim1
-rw-r--r--tests/exception/m22469.nim4
-rw-r--r--tests/exception/t13115.nim31
-rw-r--r--tests/exception/t18620.nim17
-rw-r--r--tests/exception/t20613.nim8
-rw-r--r--tests/exception/t21261.nim9
-rw-r--r--tests/exception/t22008.nim8
-rw-r--r--tests/exception/t22469.nim16
-rw-r--r--tests/exception/t9657.nim7
-rw-r--r--tests/exception/tcpp_imported_exc.nim30
-rw-r--r--tests/exception/tcpp_imported_exc2.nim10
-rw-r--r--tests/exception/texcas.nim5
-rw-r--r--tests/exception/texception_inference.nim32
-rw-r--r--tests/exception/texceptionbreak.nim8
-rw-r--r--tests/exception/texceptions.nim13
-rw-r--r--tests/exception/texceptions2.nim130
-rw-r--r--tests/exception/tindexerrorformatbounds.nim31
-rw-r--r--tests/exception/tsetexceptions.nim11
-rw-r--r--tests/exception/twrongexc.nim2
-rw-r--r--tests/exprs/t22604.nim36
-rw-r--r--tests/exprs/texprstmt.nim2
-rw-r--r--tests/exprs/tresultwarning.nim2
-rw-r--r--tests/exprs/tstmtexp.nim2
-rw-r--r--tests/float/tfloat1.nim2
-rw-r--r--tests/float/tfloat2.nim2
-rw-r--r--tests/float/tfloat4.nim14
-rw-r--r--tests/float/tfloat6.nim23
-rw-r--r--tests/float/tfloatmod.nim2
-rw-r--r--tests/float/tfloatnan.nim15
-rw-r--r--tests/float/tfloats.nim163
-rw-r--r--tests/gc/closureleak.nim14
-rw-r--r--tests/gc/cyclecollector.nim5
-rw-r--r--tests/gc/gcleak.nim9
-rw-r--r--tests/gc/gcleak2.nim14
-rw-r--r--tests/gc/gcleak3.nim8
-rw-r--r--tests/gc/gcleak4.nim2
-rw-r--r--tests/gc/gcleak5.nim2
-rw-r--r--tests/gc/growobjcrash.nim9
-rw-r--r--tests/gc/panicoverride.nim14
-rw-r--r--tests/gc/tdisable_orc.nim9
-rw-r--r--tests/gc/thavlak.nim19
-rw-r--r--tests/gc/trace_globals.nim33
-rw-r--r--tests/gc/tregionleak.nim23
-rw-r--r--tests/gc/tstandalone.nim14
-rw-r--r--tests/generics/m14509.nim16
-rw-r--r--tests/generics/m22373a.nim7
-rw-r--r--tests/generics/m22373b.nim18
-rw-r--r--tests/generics/m3770.nim11
-rw-r--r--tests/generics/mdotlookup.nim18
-rw-r--r--tests/generics/mfriends.nim (renamed from tests/friends/mfriends.nim)0
-rw-r--r--tests/generics/module_with_generics.nim2
-rw-r--r--tests/generics/mopensymimport1.nim34
-rw-r--r--tests/generics/mopensymimport2.nim16
-rw-r--r--tests/generics/mtypenodes.nim6
-rw-r--r--tests/generics/muninstantiatedgenericcalls.nim26
-rw-r--r--tests/generics/t12938.nim9
-rw-r--r--tests/generics/t13525.nim6
-rw-r--r--tests/generics/t14193.nim6
-rw-r--r--tests/generics/t14509.nim4
-rw-r--r--tests/generics/t1500.nim8
-rw-r--r--tests/generics/t17509.nim25
-rw-r--r--tests/generics/t18823.nim6
-rw-r--r--tests/generics/t18859.nim17
-rw-r--r--tests/generics/t19848.nim16
-rw-r--r--tests/generics/t20996.nim15
-rw-r--r--tests/generics/t21742.nim10
-rw-r--r--tests/generics/t21760.nim8
-rw-r--r--tests/generics/t21958.nim11
-rw-r--r--tests/generics/t22373.nim16
-rw-r--r--tests/generics/t22826.nim8
-rw-r--r--tests/generics/t23186.nim155
-rw-r--r--tests/generics/t23790.nim14
-rw-r--r--tests/generics/t23853.nim91
-rw-r--r--tests/generics/t23854.nim71
-rw-r--r--tests/generics/t23855.nim61
-rw-r--r--tests/generics/t3770.nim13
-rw-r--r--tests/generics/t4668.nim166
-rw-r--r--tests/generics/t500.nim8
-rw-r--r--tests/generics/t5926.nim22
-rw-r--r--tests/generics/t6060.nim11
-rw-r--r--tests/generics/t6137.nim6
-rw-r--r--tests/generics/t6637.nim9
-rw-r--r--tests/generics/t7446.nim10
-rw-r--r--tests/generics/t7839.nim9
-rw-r--r--tests/generics/taliashijack.nim8
-rw-r--r--tests/generics/tarc_misc.nim21
-rw-r--r--tests/generics/tbadcache.nim26
-rw-r--r--tests/generics/tbaddeprecated.nim55
-rw-r--r--tests/generics/tbintree.nim4
-rw-r--r--tests/generics/tbracketinstantiation.nim86
-rw-r--r--tests/generics/tcalltype.nim26
-rw-r--r--tests/generics/tcan.nim2
-rw-r--r--tests/generics/tconstraints.nim (renamed from tests/constraints/tconstraints.nim)0
-rw-r--r--tests/generics/texplicitgeneric2.nim7
-rw-r--r--tests/generics/tfriends.nim (renamed from tests/friends/tfriends.nim)0
-rw-r--r--tests/generics/tgeneric0.nim72
-rw-r--r--tests/generics/tgeneric3.nim40
-rw-r--r--tests/generics/tgeneric_recursionlimit.nim123
-rw-r--r--tests/generics/tgenerics_issues.nim140
-rw-r--r--tests/generics/tgenerics_various.nim99
-rw-r--r--tests/generics/tgenericwhen.nim58
-rw-r--r--tests/generics/tgensyminst.nim29
-rw-r--r--tests/generics/timpl_ast.nim80
-rw-r--r--tests/generics/timplicit_and_explicit.nim65
-rw-r--r--tests/generics/timports.nim22
-rw-r--r--tests/generics/tinheritable_importcpp.nim10
-rw-r--r--tests/generics/tmacroinjectedsym.nim186
-rw-r--r--tests/generics/tmacroinjectedsymwarning.nim59
-rw-r--r--tests/generics/tmetafield.nim20
-rw-r--r--tests/generics/tnestedissues.nim24
-rw-r--r--tests/generics/tnestedtemplate.nim9
-rw-r--r--tests/generics/tnullary_generics.nim26
-rw-r--r--tests/generics/tobjecttyperel.nim1
-rw-r--r--tests/generics/topensymimport.nim5
-rw-r--r--tests/generics/toverloading_typedesc.nim5
-rw-r--r--tests/generics/tparam_binding.nim3
-rw-r--r--tests/generics/tparser_generator.nim16
-rw-r--r--tests/generics/tpointerprocs.nim28
-rw-r--r--tests/generics/tprevent_double_bind.nim2
-rw-r--r--tests/generics/trecursivegenerics.nim96
-rw-r--r--tests/generics/treentranttypes.nim19
-rw-r--r--tests/generics/treturn_inference.nim184
-rw-r--r--tests/generics/tstatic_constrained.nim79
-rw-r--r--tests/generics/tthread_generic.nim2
-rw-r--r--tests/generics/tuninstantiated_failure.nim16
-rw-r--r--tests/generics/tuninstantiatedgenericcalls.nim517
-rw-r--r--tests/generics/twrong_explicit_typeargs.nim16
-rw-r--r--tests/generics/twrong_generic_object.nim4
-rw-r--r--tests/global/a_module.nim (renamed from tests/constr/a_module.nim)0
-rw-r--r--tests/global/t15005.nim18
-rw-r--r--tests/global/t21896.nim9
-rw-r--r--tests/global/t3505.nim41
-rw-r--r--tests/global/tglobal2.nim9
-rw-r--r--tests/ic/config.nims1
-rw-r--r--tests/ic/mbaseobj.nim7
-rw-r--r--tests/ic/mcompiletime_counter.nim15
-rw-r--r--tests/ic/mdefconverter.nim2
-rw-r--r--tests/ic/mimports.nim9
-rw-r--r--tests/ic/mimportsb.nim4
-rw-r--r--tests/ic/tcompiletime_counter.nim24
-rw-r--r--tests/ic/tconverter.nim18
-rw-r--r--tests/ic/tgenericinst.nim11
-rw-r--r--tests/ic/tgenerics.nim1
-rw-r--r--tests/ic/timports.nim29
-rw-r--r--tests/ic/tmethods.nim28
-rw-r--r--tests/ic/tstdlib_import_changed.nim15
-rw-r--r--tests/implicit/timplicit.nim49
-rw-r--r--tests/import/buzz/m21496.nim1
-rw-r--r--tests/import/fizz/m21496.nim1
-rw-r--r--tests/import/t21496.nim9
-rw-r--r--tests/import/t22065.nim5
-rw-r--r--tests/import/t22208.nim6
-rw-r--r--tests/import/t23167.nim5
-rw-r--r--tests/importalls/m1.nim70
-rw-r--r--tests/importalls/m2.nim3
-rw-r--r--tests/importalls/m3.nim5
-rw-r--r--tests/importalls/m4.nim9
-rw-r--r--tests/importalls/mt0.nim9
-rw-r--r--tests/importalls/mt1.nim23
-rw-r--r--tests/importalls/mt2.nim104
-rw-r--r--tests/importalls/mt3.nim12
-rw-r--r--tests/importalls/mt4.nim4
-rw-r--r--tests/importalls/mt4b.nim3
-rw-r--r--tests/importalls/mt5.nim9
-rw-r--r--tests/importalls/mt6.nim13
-rw-r--r--tests/importalls/mt7.nim14
-rw-r--r--tests/importalls/mt8.nim23
-rw-r--r--tests/importalls/mt9.nim12
-rw-r--r--tests/importalls/tmain2.nim7
-rw-r--r--tests/init/tcompiles.nim101
-rw-r--r--tests/init/tinitchecks_v2.nim83
-rw-r--r--tests/init/tlet.nim55
-rw-r--r--tests/init/tlet_uninit2.nim5
-rw-r--r--tests/init/tlet_uninit3.nim24
-rw-r--r--tests/init/tlet_uninit4.nim12
-rw-r--r--tests/init/toutparam_subtype.nim24
-rw-r--r--tests/init/toutparams.nim14
-rw-r--r--tests/init/tproveinit.nim18
-rw-r--r--tests/init/treturns.nim106
-rw-r--r--tests/init/tuninit1.nim5
-rw-r--r--tests/int/t1.nim61
-rw-r--r--tests/int/tarithm.nim (renamed from tests/arithm/tarithm.nim)22
-rw-r--r--tests/int/tashr.nim (renamed from tests/arithm/tashr.nim)0
-rw-r--r--tests/int/tdiv.nim19
-rw-r--r--tests/int/tints.nim (renamed from tests/misc/tints.nim)77
-rw-r--r--tests/int/tunsigned64mod.nim (renamed from tests/misc/tunsigned64mod.nim)0
-rw-r--r--tests/int/tunsignedcmp.nim (renamed from tests/misc/tunsignedcmp.nim)0
-rw-r--r--tests/int/tunsignedcomp.nim136
-rw-r--r--tests/int/tunsignedconv.nim115
-rw-r--r--tests/int/tunsignedinc.nim (renamed from tests/misc/tunsignedinc.nim)10
-rw-r--r--tests/int/tunsignedmisc.nim (renamed from tests/misc/tunsignedmisc.nim)0
-rw-r--r--tests/int/twrongexplicitvarconv.nim16
-rw-r--r--tests/int/twrongvarconv.nim9
-rw-r--r--tests/isolate/tisolate.nim41
-rw-r--r--tests/isolate/tisolate2.nim22
-rw-r--r--tests/isolate/tisolated_lock.nim67
-rw-r--r--tests/iter/t1550.nim24
-rw-r--r--tests/iter/t16076.nim45
-rw-r--r--tests/iter/t20891.nim28
-rw-r--r--tests/iter/t21306.nim118
-rw-r--r--tests/iter/t21737.nim22
-rw-r--r--tests/iter/t22148.nim15
-rw-r--r--tests/iter/t22548.nim21
-rw-r--r--tests/iter/t22619.nim83
-rw-r--r--tests/iter/t2771.nim25
-rw-r--r--tests/iter/tanoniter1.nim1
-rw-r--r--tests/iter/tarrayiter.nim14
-rw-r--r--tests/iter/tclosureiters.nim39
-rw-r--r--tests/iter/tgeniteratorinblock.nim54
-rw-r--r--tests/iter/titer.nim90
-rw-r--r--tests/iter/titer11.nim12
-rw-r--r--tests/iter/titer12.nim1
-rw-r--r--tests/iter/titer13.nim2
-rw-r--r--tests/iter/titer2.nim2
-rw-r--r--tests/iter/titer3.nim2
-rw-r--r--tests/iter/titer_issues.nim200
-rw-r--r--tests/iter/titervaropenarray.nim2
-rw-r--r--tests/iter/tmoditer.nim2
-rw-r--r--tests/iter/tpermutations.nim2
-rw-r--r--tests/iter/tshallowcopy_closures.nim1
-rw-r--r--tests/iter/tyieldintry.nim102
-rw-r--r--tests/js/readme.md5
-rw-r--r--tests/js/t11166.nim18
-rw-r--r--tests/js/t11354.nim20
-rw-r--r--tests/js/t11697.nim5
-rw-r--r--tests/js/t12303.nim16
-rw-r--r--tests/js/t12672.nim12
-rw-r--r--tests/js/t14153.nim22
-rw-r--r--tests/js/t14570.nim11
-rw-r--r--tests/js/t17177.nim10
-rw-r--r--tests/js/t20233.nim7
-rw-r--r--tests/js/t20235.nim11
-rw-r--r--tests/js/t21209.nim6
-rw-r--r--tests/js/t21209.nims1
-rw-r--r--tests/js/t21247.nim15
-rw-r--r--tests/js/t21439.nim11
-rw-r--r--tests/js/t7109.nim8
-rw-r--r--tests/js/t7127.nim2
-rw-r--r--tests/js/t7224.nim9
-rw-r--r--tests/js/t8231.nim3
-rw-r--r--tests/js/t8821.nim9
-rw-r--r--tests/js/t9410.nim4
-rw-r--r--tests/js/taddr.nim79
-rw-r--r--tests/js/tarrayboundscheck.nim6
-rw-r--r--tests/js/tasync.nim33
-rw-r--r--tests/js/tasyncjs.nim107
-rw-r--r--tests/js/tasyncjs_bad.nim22
-rw-r--r--tests/js/tasyncjs_pragma.nim (renamed from tests/js/tasync_pragma.nim)2
-rw-r--r--tests/js/tbasics.nim2
-rw-r--r--tests/js/tbigint_backend.nim57
-rw-r--r--tests/js/tbyvar.nim15
-rw-r--r--tests/js/tclosures.nim2
-rw-r--r--tests/js/tcodegendeclproc.nim2
-rw-r--r--tests/js/tconsole.nim1
-rw-r--r--tests/js/tcsymbol.nim6
-rw-r--r--tests/js/tdanger.nim17
-rw-r--r--tests/js/tdiscard.nim3
-rw-r--r--tests/js/tdollar_float.nim62
-rw-r--r--tests/js/temptyseq.nim8
-rw-r--r--tests/js/tfieldchecks.nim6
-rw-r--r--tests/js/tglobal.nim30
-rw-r--r--tests/js/tindexdefect.nim9
-rw-r--r--tests/js/tjsffi.nim447
-rw-r--r--tests/js/tjsffi_old.nim9
-rw-r--r--tests/js/tjshello.nim2
-rw-r--r--tests/js/tjshello_stacktrace.nim9
-rw-r--r--tests/js/tjsnimscombined.nim1
-rw-r--r--tests/js/tjsnimscombined.nims1
-rw-r--r--tests/js/tlent.nim33
-rw-r--r--tests/js/tmangle.nim4
-rw-r--r--tests/js/tmodify_cstring.nim6
-rw-r--r--tests/js/tnativeexc.nim2
-rw-r--r--tests/js/tneginthash.nim21
-rw-r--r--tests/js/tnilstrs.nim10
-rw-r--r--tests/js/tos.nim21
-rw-r--r--tests/js/trepr.nim93
-rw-r--r--tests/js/treprinifexpr.nim18
-rw-r--r--tests/js/tseqops.nim21
-rw-r--r--tests/js/tsourcemap.nim96
-rw-r--r--tests/js/tstdlib_imports.nim80
-rw-r--r--tests/js/tstdlib_various.nim174
-rw-r--r--tests/js/tstreams.nim22
-rw-r--r--tests/js/ttempgen.nim79
-rw-r--r--tests/js/ttypedarray.nim26
-rw-r--r--tests/js/tunion.nim7
-rw-r--r--tests/js/tunittest_error.nim24
-rw-r--r--tests/js/tunittest_error2.nim16
-rw-r--r--tests/js/tunittests.nim11
-rw-r--r--tests/js/twritestacktrace.nim12
-rw-r--r--tests/lent/t16898.nim31
-rw-r--r--tests/lent/t17621.nim15
-rw-r--r--tests/lent/tbasic_lent_check.nim46
-rw-r--r--tests/lent/tlent_from_var.nim107
-rw-r--r--tests/lent/tnot_allowed_lent.nim6
-rw-r--r--tests/lent/tnot_allowed_lent2.nim14
-rw-r--r--tests/lent/tvm.nim21
-rw-r--r--tests/let/timportc.nim24
-rw-r--r--tests/let/timportc2.nim8
-rw-r--r--tests/lexer/mlexerutils.nim9
-rw-r--r--tests/lexer/tcustom_numeric_literals.nim177
-rw-r--r--tests/lexer/tintegerliterals.nim14
-rw-r--r--tests/lexer/tlexerspaces.nim2
-rw-r--r--tests/lexer/trawstr.nim (renamed from tests/misc/trawstr.nim)0
-rw-r--r--tests/lexer/tunary_minus.nim83
-rw-r--r--tests/lexer/tunicode_operators.nim16
-rw-r--r--tests/lookups/issue_23032/deep_scope.nim2
-rw-r--r--tests/lookups/issue_23172/m23172.nim6
-rw-r--r--tests/lookups/mambsym1.nim (renamed from tests/ambsym/mambsym1.nim)0
-rw-r--r--tests/lookups/mambsym2.nim (renamed from tests/ambsym/mambsym2.nim)0
-rw-r--r--tests/lookups/mambsym3.nim4
-rw-r--r--tests/lookups/mambsym4.nim4
-rw-r--r--tests/lookups/mambsys1.nim (renamed from tests/ambsym/mambsys1.nim)0
-rw-r--r--tests/lookups/mambsys2.nim (renamed from tests/ambsym/mambsys2.nim)0
-rw-r--r--tests/lookups/mambtype1.nim1
-rw-r--r--tests/lookups/mambtype2.nim4
-rw-r--r--tests/lookups/mbind3.nim (renamed from tests/bind/mbind3.nim)0
-rw-r--r--tests/lookups/mdisambsym1.nim2
-rw-r--r--tests/lookups/mdisambsym2.nim1
-rw-r--r--tests/lookups/mdisambsym3.nim1
-rw-r--r--tests/lookups/mmacroamb.nim10
-rw-r--r--tests/lookups/t23032.nim13
-rw-r--r--tests/lookups/t23172.nim9
-rw-r--r--tests/lookups/t23749.nim37
-rw-r--r--tests/lookups/tambiguousemit.nim12
-rw-r--r--tests/lookups/tambprocvar.nim19
-rw-r--r--tests/lookups/tambsym.nim (renamed from tests/ambsym/tambsym.nim)0
-rw-r--r--tests/lookups/tambsym2.nim (renamed from tests/ambsym/tambsym2.nim)0
-rw-r--r--tests/lookups/tambsym3.nim (renamed from tests/ambsym/tambsym3.nim)2
-rw-r--r--tests/lookups/tambsymmanual.nim25
-rw-r--r--tests/lookups/tambsys.nim (renamed from tests/ambsym/tambsys.nim)0
-rw-r--r--tests/lookups/tambtype.nim20
-rw-r--r--tests/lookups/tbind.nim (renamed from tests/bind/tbind.nim)11
-rw-r--r--tests/lookups/tbind_for_generics.nim17
-rw-r--r--tests/lookups/tdisambsym.nim8
-rw-r--r--tests/lookups/tenumlocalsym.nim22
-rw-r--r--tests/lookups/test.nim2
-rw-r--r--tests/lookups/tgensym.nim (renamed from tests/gensym/tgensym.nim)0
-rw-r--r--tests/lookups/tgensymgeneric.nim (renamed from tests/gensym/tgensymgeneric.nim)2
-rw-r--r--tests/lookups/tinvalidbindtypedesc.nim (renamed from tests/bind/tinvalidbindtypedesc.nim)2
-rw-r--r--tests/lookups/tmacroamb.nim5
-rw-r--r--tests/lookups/tmoduleclash1.nim13
-rw-r--r--tests/lookups/tmoduleclash2.nim6
-rw-r--r--tests/lookups/tnicerrorforsymchoice.nim (renamed from tests/bind/tnicerrorforsymchoice.nim)2
-rw-r--r--tests/lookups/told_bind_expr.nim (renamed from tests/bind/tbind2.nim)7
-rw-r--r--tests/lookups/tredef.nim2
-rw-r--r--tests/lookups/tundeclaredmixin.nim17
-rw-r--r--tests/m14634.nim48
-rw-r--r--tests/macros/m18235.nim42
-rw-r--r--tests/macros/mparsefile.nim4
-rw-r--r--tests/macros/t14227.nim23
-rw-r--r--tests/macros/t14329.nim4
-rw-r--r--tests/macros/t14511.nim54
-rw-r--r--tests/macros/t14847.nim20
-rw-r--r--tests/macros/t15691.nim22
-rw-r--r--tests/macros/t15751.nim11
-rw-r--r--tests/macros/t16758.nim38
-rw-r--r--tests/macros/t17836.nim15
-rw-r--r--tests/macros/t18203.nim15
-rw-r--r--tests/macros/t18235.nim18
-rw-r--r--tests/macros/t19766_20114.nim16
-rw-r--r--tests/macros/t20067.nim28
-rw-r--r--tests/macros/t20435.nim30
-rw-r--r--tests/macros/t21593.nim13
-rw-r--r--tests/macros/t23032_1.nim19
-rw-r--r--tests/macros/t23032_2.nim20
-rw-r--r--tests/macros/t23547.nim23
-rw-r--r--tests/macros/t23784.nim157
-rw-r--r--tests/macros/t7875.nim22
-rw-r--r--tests/macros/tastrepr.nim17
-rw-r--r--tests/macros/tcasestmtmacro.nim33
-rw-r--r--tests/macros/tclosuremacro.nim38
-rw-r--r--tests/macros/tdumpast.nim168
-rw-r--r--tests/macros/texpectIdent1.nim18
-rw-r--r--tests/macros/texpectIdent2.nim24
-rw-r--r--tests/macros/tfail_parse.nim15
-rw-r--r--tests/macros/tforloop_macro1.nim2
-rw-r--r--tests/macros/tgetimpl.nim46
-rw-r--r--tests/macros/tgetraiseslist.nim29
-rw-r--r--tests/macros/tgettype.nim100
-rw-r--r--tests/macros/tgettypeinst.nim4
-rw-r--r--tests/macros/tgettypeinst7737.nim61
-rw-r--r--tests/macros/tmacro2.nim8
-rw-r--r--tests/macros/tmacro6.nim16
-rw-r--r--tests/macros/tmacrogensym.nim8
-rw-r--r--tests/macros/tmacrogetimpl.nim31
-rw-r--r--tests/macros/tmacros1.nim19
-rw-r--r--tests/macros/tmacros_issues.nim277
-rw-r--r--tests/macros/tmacros_various.nim197
-rw-r--r--tests/macros/tmacrostmt.nim17
-rw-r--r--tests/macros/tmacrotypes.nim92
-rw-r--r--tests/macros/tmemit.nim3
-rw-r--r--tests/macros/tparsefile.nim11
-rw-r--r--tests/macros/tprocgettype.nim28
-rw-r--r--tests/macros/tprochelpers.nim22
-rw-r--r--tests/macros/tstaticparamsmacro.nim4
-rw-r--r--tests/macros/tstructuredlogging.nim6
-rw-r--r--tests/macros/ttemplatesymbols.nim2
-rw-r--r--tests/macros/ttryparseexpr.nim4
-rw-r--r--tests/macros/ttypenodes.nim16
-rw-r--r--tests/macros/tvtable.nim2
-rw-r--r--tests/magics/trunnableexamples.nim60
-rw-r--r--tests/manyloc/argument_parser/argument_parser.nim21
-rw-r--r--tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim2
-rw-r--r--tests/manyloc/keineschweine/dependencies/enet/enet.nim4
-rw-r--r--tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim4
-rw-r--r--tests/manyloc/keineschweine/dependencies/nake/nake.nim11
-rw-r--r--tests/manyloc/keineschweine/enet_server/enet_server.nim6
-rw-r--r--tests/manyloc/keineschweine/enet_server/server_utils.nim4
-rw-r--r--tests/manyloc/keineschweine/keineschweine.nim6
-rw-r--r--tests/manyloc/keineschweine/keineschweine.nim.cfg2
-rw-r--r--tests/manyloc/keineschweine/lib/client_helpers.nim14
-rw-r--r--tests/manyloc/keineschweine/lib/estreams.nim4
-rw-r--r--tests/manyloc/keineschweine/lib/glut.nim2
-rw-r--r--tests/manyloc/keineschweine/lib/sg_assets.nim8
-rw-r--r--tests/manyloc/keineschweine/lib/sg_gui.nim40
-rw-r--r--tests/manyloc/keineschweine/lib/sg_packets.nim4
-rw-r--r--tests/manyloc/keineschweine/lib/zlib_helpers.nim15
-rw-r--r--tests/manyloc/keineschweine/server/old_dirserver.nim8
-rw-r--r--tests/manyloc/keineschweine/server/old_server_utils.nim4
-rw-r--r--tests/manyloc/keineschweine/server/old_sg_server.nim6
-rw-r--r--tests/manyloc/keineschweine/server/sg_lobby.nim3
-rw-r--r--tests/manyloc/nake/nake.nim7
-rw-r--r--tests/manyloc/nake/nakefile.nim19
-rw-r--r--tests/manyloc/named_argument_bug/tri_engine/gfx/gl/gl.nim2
-rw-r--r--tests/manyloc/named_argument_bug/tri_engine/gfx/gl/primitive.nim2
-rw-r--r--tests/manyloc/standalone/panicoverride.nim5
-rw-r--r--tests/manyloc/standalone2/panicoverride.nim14
-rw-r--r--tests/manyloc/standalone2/tavr.nim7
-rw-r--r--tests/manyloc/standalone2/tavr.nim.cfg5
-rw-r--r--tests/metatype/tcompositetypeclasses.nim2
-rw-r--r--tests/metatype/tcps.nim35
-rw-r--r--tests/metatype/tmatrix3.nim2
-rw-r--r--tests/metatype/tmetatype_issues.nim9
-rw-r--r--tests/metatype/tmetatype_various.nim30
-rw-r--r--tests/metatype/tshacontext.nim44
-rw-r--r--tests/metatype/tstatic_generic_typeclass.nim30
-rw-r--r--tests/metatype/tstaticparammacro.nim4
-rw-r--r--tests/metatype/tstaticparams.nim24
-rw-r--r--tests/metatype/tstaticvector.nim3
-rw-r--r--tests/metatype/ttensor.nim6
-rw-r--r--tests/metatype/ttypedesc1.nim6
-rw-r--r--tests/metatype/ttypedesc2.nim14
-rw-r--r--tests/metatype/ttypedesc3.nim16
-rw-r--r--tests/metatype/ttypedescnotnimnode.nim21
-rw-r--r--tests/metatype/ttypeselectors.nim13
-rw-r--r--tests/metatype/ttypetraits.nim293
-rw-r--r--tests/metatype/tunresolved_return_type.nim2
-rw-r--r--tests/metatype/twildtypedesc.nim10
-rw-r--r--tests/metatype/twrong_same_type.nim28
-rw-r--r--tests/metatype/typeclassinference.nim22
-rw-r--r--tests/metatype/typedesc_as_value.nim2
-rw-r--r--tests/metatype/utypeclasses.nim4
-rw-r--r--tests/method/nim.cfg1
-rw-r--r--tests/method/t20515.nim20
-rw-r--r--tests/method/t22673.nim21
-rw-r--r--tests/method/tcompilegenerics.nim24
-rw-r--r--tests/method/tgeneric_methods.nim83
-rw-r--r--tests/method/tmethod_issues.nim44
-rw-r--r--tests/method/tmethod_various.nim12
-rw-r--r--tests/method/tmethods_old.nim12
-rw-r--r--tests/method/tmultim.nim192
-rw-r--r--tests/method/tmultimjs.nim1
-rw-r--r--tests/method/tnildispatcher.nim2
-rw-r--r--tests/method/tsingle_methods.nim2
-rw-r--r--tests/method/tvtable.nim24
-rw-r--r--tests/misc/m15316.nim1
-rw-r--r--tests/misc/m15955.nim4
-rw-r--r--tests/misc/m15955_main.nim11
-rw-r--r--tests/misc/m20149.nim2
-rw-r--r--tests/misc/m20456.nims1
-rw-r--r--tests/misc/mbackend.nim30
-rw-r--r--tests/misc/mbetterrun.nim3
-rw-r--r--tests/misc/mfield_defect.nim30
-rw-r--r--tests/misc/mimportc.nim26
-rw-r--r--tests/misc/mjsondoc.nim14
-rw-r--r--tests/misc/msizeof5.nim131
-rw-r--r--tests/misc/msizeof5.nim.cfg5
-rw-r--r--tests/misc/mtlsemulation.h37
-rw-r--r--tests/misc/parsecomb.nim4
-rw-r--r--tests/misc/t11634.nim17
-rw-r--r--tests/misc/t12869.nim14
-rw-r--r--tests/misc/t14667.nim12
-rw-r--r--tests/misc/t15351.nim5
-rw-r--r--tests/misc/t15955.nim22
-rw-r--r--tests/misc/t16244.nim9
-rw-r--r--tests/misc/t16264.nim2
-rw-r--r--tests/misc/t16541.nim12
-rw-r--r--tests/misc/t17286.nim16
-rw-r--r--tests/misc/t18077.nim21
-rw-r--r--tests/misc/t18079.nim15
-rw-r--r--tests/misc/t19046.nim19
-rw-r--r--tests/misc/t20253.nim10
-rw-r--r--tests/misc/t20289.nim15
-rw-r--r--tests/misc/t20456_2.nim14
-rw-r--r--tests/misc/t20883.nim13
-rw-r--r--tests/misc/t21109.nim13
-rw-r--r--tests/misc/t21443.nim6
-rw-r--r--tests/misc/t23240.nim6
-rw-r--r--tests/misc/t3482.nim15
-rw-r--r--tests/misc/t3907.nim10
-rw-r--r--tests/misc/t5540.nim45
-rw-r--r--tests/misc/t6549.nim4
-rw-r--r--tests/misc/t8404.nim33
-rw-r--r--tests/misc/t8545.nim24
-rw-r--r--tests/misc/t9039.nim24
-rw-r--r--tests/misc/t9091.nim33
-rw-r--r--tests/misc/t9710.nim6
-rw-r--r--tests/misc/taddr.nim295
-rw-r--r--tests/misc/tapp_lib_staticlib.nim27
-rw-r--r--tests/misc/tcast.nim88
-rw-r--r--tests/misc/tconv.nim88
-rw-r--r--tests/misc/tcsharpusingstatement.nim (renamed from tests/usingstmt/tusingstatement.nim)28
-rw-r--r--tests/misc/tdangerisrelease.nim14
-rw-r--r--tests/misc/tdefine.nim69
-rw-r--r--tests/misc/temptyecho.nim2
-rw-r--r--tests/misc/tevents.nim48
-rw-r--r--tests/misc/tgenconstraints.nim31
-rw-r--r--tests/misc/theaproots.nim2
-rw-r--r--tests/misc/tinvalidnewseq.nim2
-rw-r--r--tests/misc/tjoinable.nim3
-rw-r--r--tests/misc/tnoforward.nim2
-rw-r--r--tests/misc/tparseopt.nim35
-rw-r--r--tests/misc/tradix.nim54
-rw-r--r--tests/misc/trfc405.nim112
-rw-r--r--tests/misc/trunner.nim444
-rw-r--r--tests/misc/trunner_special.nim37
-rw-r--r--tests/misc/tsemfold.nim30
-rw-r--r--tests/misc/tsimplesort.nim7
-rw-r--r--tests/misc/tsizeof.nim58
-rw-r--r--tests/misc/tsizeof2.nim2
-rw-r--r--tests/misc/tsizeof3.nim29
-rw-r--r--tests/misc/ttlsemulation.nim76
-rw-r--r--tests/misc/tunsignedcomp.nim136
-rw-r--r--tests/misc/tunsignedconv.nim45
-rw-r--r--tests/misc/tupcomingfeatures.nim35
-rw-r--r--tests/misc/tvarious1.nim10
-rw-r--r--tests/misc/tvarnums.nim26
-rw-r--r--tests/misc/tvcc.nim9
-rw-r--r--tests/mmaptest.nim7
-rw-r--r--tests/modules/a/module_name_clashes.nim8
-rw-r--r--tests/modules/b/module_name_clashes.nim3
-rw-r--r--tests/modules/mforwarded_pure_enum.nim3
-rw-r--r--tests/modules/mforwarded_pure_enum2.nim4
-rw-r--r--tests/modules/mincludeprefix.nim1
-rw-r--r--tests/modules/mincludetemplate.nim1
-rw-r--r--tests/modules/seq.nim5
-rw-r--r--tests/modules/texplicit_system_import.nim6
-rw-r--r--tests/modules/tfowarded_pure_enum.nim7
-rw-r--r--tests/modules/timportas.nim11
-rw-r--r--tests/modules/tincludeprefix.nim3
-rw-r--r--tests/modules/tincludetemplate.nim5
-rw-r--r--tests/modules/tmodule_name_clashes.nim17
-rw-r--r--tests/modules/tmodulesymtype.nim22
-rw-r--r--tests/modules/treorder.nim6
-rw-r--r--tests/modules/tselfimport.nim2
-rw-r--r--tests/modules/tseq.nim8
-rw-r--r--tests/modules/tstrutils_insert_sep.nim13
-rw-r--r--tests/msgs/mdeprecated3.nim (renamed from tests/deprecated/importme.nim)0
-rw-r--r--tests/msgs/mspellsuggest.nim7
-rw-r--r--tests/msgs/mused2a.nim23
-rw-r--r--tests/msgs/mused2b.nim3
-rw-r--r--tests/msgs/mused2c.nim1
-rw-r--r--tests/msgs/mused3.nim76
-rw-r--r--tests/msgs/mused3a.nim41
-rw-r--r--tests/msgs/mused3b.nim12
-rw-r--r--tests/msgs/tdeprecated1.nim15
-rw-r--r--tests/msgs/tdeprecated2.nim (renamed from tests/deprecated/tdeprecated.nim)8
-rw-r--r--tests/msgs/tdeprecated3.nim33
-rw-r--r--tests/msgs/tdeprecatedequalhook.nim11
-rw-r--r--tests/msgs/texpandmacro.nim (renamed from tests/compilerfeatures/texpandmacro.nim)2
-rw-r--r--tests/msgs/thints_off.nim4
-rw-r--r--tests/msgs/tspellsuggest.nim45
-rw-r--r--tests/msgs/tspellsuggest2.nim45
-rw-r--r--tests/msgs/tspellsuggest3.nim21
-rw-r--r--tests/msgs/tused2.nim46
-rw-r--r--tests/msgs/twarningaserror.nim35
-rw-r--r--tests/navigator/minclude.nim2
-rw-r--r--tests/navigator/tincludefile.nim29
-rw-r--r--tests/navigator/tnav1.nim33
-rw-r--r--tests/newconfig/bar/config.nims0
-rw-r--r--tests/newconfig/bar/mfoo.nim0
-rw-r--r--tests/newconfig/bar/mfoo.nim.cfg0
-rw-r--r--tests/newconfig/bar/mfoo.nims0
-rw-r--r--tests/newconfig/bar/nim.cfg0
-rw-r--r--tests/newconfig/foo2/mfoo2.customext2
-rw-r--r--tests/newconfig/mconfigcheck.nims9
-rw-r--r--tests/newconfig/tfoo.nim6
-rw-r--r--tests/newconfig/tfoo.nims80
-rw-r--r--tests/nimble/tnimblepathdollar_fault.nim (renamed from tests/nimble/tnimblepathdollarfail.nim)5
-rw-r--r--tests/nimble/tnimblepathdollar_fault.nims (renamed from tests/nimble/tnimblepathdollarfail.nims)0
-rw-r--r--tests/nimdoc/imp.nim1
-rw-r--r--tests/nimdoc/m13129.nim37
-rw-r--r--tests/nimdoc/readme.md3
-rw-r--r--tests/nimdoc/sub/imp.nim1
-rw-r--r--tests/nimdoc/sub/imp2.nim1
-rw-r--r--tests/nimdoc/sub/mmain.nim8
-rw-r--r--tests/nimdoc/t15916.nim16
-rw-r--r--tests/nimdoc/t17615.nim11
-rw-r--r--tests/nimdoc/trunnableexamples.nim213
-rw-r--r--tests/niminaction/Chapter1/various1.nim2
-rw-r--r--tests/niminaction/Chapter2/explicit_discard.nim2
-rw-r--r--tests/niminaction/Chapter2/resultaccept.nim2
-rw-r--r--tests/niminaction/Chapter2/resultreject.nim2
-rw-r--r--tests/niminaction/Chapter2/various2.nim10
-rw-r--r--tests/niminaction/Chapter3/various3.nim29
-rw-r--r--tests/niminaction/Chapter7/Tweeter/src/createDatabase.nim1
-rw-r--r--tests/niminaction/Chapter7/Tweeter/src/database.nim4
-rw-r--r--tests/niminaction/Chapter7/Tweeter/src/tweeter.nim4
-rw-r--r--tests/niminaction/Chapter7/Tweeter/src/views/user.nim2
-rw-r--r--tests/niminaction/Chapter7/Tweeter/tests/database_test.nim1
-rw-r--r--tests/niminaction/Chapter8/sdl/sdl.nim6
-rw-r--r--tests/niminaction/Chapter8/sdl/sdl_test.nim2
-rw-r--r--tests/niminaction/Chapter8/sfml/sfml_test.nim1
-rw-r--r--tests/notnil/tmust_compile.nim10
-rw-r--r--tests/notnil/tnotnil4.nim5
-rw-r--r--tests/notnil/tnotnil5.nim28
-rw-r--r--tests/notnil/tnotnil_in_objconstr.nim10
-rw-r--r--tests/notnil/tparse.nim18
-rw-r--r--tests/objects/m19342.c12
-rw-r--r--tests/objects/mobject_default_value.nim15
-rw-r--r--tests/objects/t17437.nim22
-rw-r--r--tests/objects/t19342.nim18
-rw-r--r--tests/objects/t19342_2.nim18
-rw-r--r--tests/objects/t20972.nim15
-rw-r--r--tests/objects/t22301.nim17
-rw-r--r--tests/objects/t4318.nim17
-rw-r--r--tests/objects/tdefaultfieldscheck.nim16
-rw-r--r--tests/objects/tdefaultrangetypescheck.nim11
-rw-r--r--tests/objects/tillegal_recursion.nim2
-rw-r--r--tests/objects/tillegal_recursion2.nim6
-rw-r--r--tests/objects/tillegal_recursion3.nim6
-rw-r--r--tests/objects/tobj_asgn_dont_slice.nim3
-rw-r--r--tests/objects/tobjconstr.nim43
-rw-r--r--tests/objects/tobjconstr2.nim4
-rw-r--r--tests/objects/tobjcov.nim2
-rw-r--r--tests/objects/tobject.nim50
-rw-r--r--tests/objects/tobject3.nim11
-rw-r--r--tests/objects/tobject_default_value.nim780
-rw-r--r--tests/objects/tobjects_issues.nim2
-rw-r--r--tests/objects/tobjects_various.nim15
-rw-r--r--tests/objects/trequireinit.nim10
-rw-r--r--tests/objects/tunsafenew.nim10
-rw-r--r--tests/objects/tunsafenew2.nim15
-rw-r--r--tests/objects/twhen1.nim38
-rw-r--r--tests/objvariant/t14581.nim25
-rw-r--r--tests/objvariant/tcheckedfield1.nim3
-rw-r--r--tests/objvariant/tconstobjvariant.nim18
-rw-r--r--tests/objvariant/tconstructionorder.nim20
-rw-r--r--tests/objvariant/treassign.nim31
-rw-r--r--tests/openarray/topena1.nim2
-rw-r--r--tests/openarray/topenarray.nim88
-rw-r--r--tests/openarray/topenarrayrepr.nim4
-rw-r--r--tests/openarray/topenlen.nim2
-rw-r--r--tests/openarray/tptrarrayderef.nim6
-rw-r--r--tests/openarray/tuncheckedarray.nim19
-rw-r--r--tests/options/tnimbasepattern.nim26
-rw-r--r--tests/osproc/passenv.nim2
-rw-r--r--tests/osproc/ta_in.nim9
-rw-r--r--tests/osproc/ta_out.nim33
-rw-r--r--tests/osproc/tafalse.nim7
-rw-r--r--tests/osproc/tclose.nim8
-rw-r--r--tests/osproc/texecps.nim4
-rw-r--r--tests/osproc/texitcode.nim23
-rw-r--r--tests/osproc/tnoexe.nim27
-rw-r--r--tests/osproc/treadlines.nim23
-rw-r--r--tests/osproc/tstderr.nim37
-rw-r--r--tests/osproc/tstdin.nim17
-rw-r--r--tests/osproc/tstdout.nim31
-rw-r--r--tests/osproc/twaitforexit.nim38
-rw-r--r--tests/overflow/tdistinct_range.nim6
-rw-r--r--tests/overflow/toverflow.nim82
-rw-r--r--tests/overflow/toverflow2.nim (renamed from tests/overflw/toverflw2.nim)2
-rw-r--r--tests/overflow/toverflow_reorder.nim (renamed from tests/overflw/toverflw.nim)12
-rw-r--r--tests/overflow/tovfint.nim (renamed from tests/overflw/tovfint.nim)0
-rw-r--r--tests/overflow/trangechecks.nim (renamed from tests/misc/trangechecks.nim)13
-rw-r--r--tests/overflow/twronginference.nim10
-rw-r--r--tests/overload/issue22142/tfail_implicit_ambiguous.nim10
-rw-r--r--tests/overload/issue22142/tfail_nested_pointers.nim12
-rw-r--r--tests/overload/issue22142/tfail_object_is_generic.nim16
-rw-r--r--tests/overload/issue22142/tfail_typeclass_var_invar.nim9
-rw-r--r--tests/overload/issue22142/tissue22142_shouldpass.nim68
-rw-r--r--tests/overload/m19737.nim10
-rw-r--r--tests/overload/mvaruintconv.nim145
-rw-r--r--tests/overload/t19737.nim15
-rw-r--r--tests/overload/t23249.nim17
-rw-r--r--tests/overload/t23755.nim62
-rw-r--r--tests/overload/t7416.nim9
-rw-r--r--tests/overload/t8829.nim18
-rw-r--r--tests/overload/tgenericalias.nim13
-rw-r--r--tests/overload/tnamedparamoverloading.nim14
-rw-r--r--tests/overload/tor_isnt_better.nim47
-rw-r--r--tests/overload/toverl4.nim26
-rw-r--r--tests/overload/toverload_issues.nim45
-rw-r--r--tests/overload/toverload_various.nim300
-rw-r--r--tests/overload/tproc_types_dont_like_subtypes.nim20
-rw-r--r--tests/overload/tselfderef.nim20
-rw-r--r--tests/overload/tstatic_with_converter.nim9
-rw-r--r--tests/overload/tuntypedarg.nim19
-rw-r--r--tests/overload/tvartypeclass.nim11
-rw-r--r--tests/overload/tvaruintconv.nim207
-rw-r--r--tests/package/stdlib/stdlib.nimble0
-rw-r--r--tests/package/stdlib/system.nim2
-rw-r--r--tests/package/tstdlib_name_not_special.nim3
-rw-r--r--tests/parallel/t10913.nim20
-rw-r--r--tests/parallel/t7535.nim11
-rw-r--r--tests/parallel/t9691.nim9
-rw-r--r--tests/parallel/tarray_of_channels.nim1
-rw-r--r--tests/parallel/tblocking_channel.nim6
-rw-r--r--tests/parallel/tconvexhull.nim10
-rw-r--r--tests/parallel/tdeepcopy.nim61
-rw-r--r--tests/parallel/tdeepcopy2.nim7
-rw-r--r--tests/parallel/tdisjoint_slice1.nim58
-rw-r--r--tests/parallel/tdisjoint_slice2.nim40
-rw-r--r--tests/parallel/tflowvar.nim2
-rw-r--r--tests/parallel/tgc_unsafe2.nim7
-rw-r--r--tests/parallel/tguard1.nim2
-rw-r--r--tests/parallel/tinvalid_array_bounds.nim3
-rw-r--r--tests/parallel/tlet_spawn.nim11
-rw-r--r--tests/parallel/tmissing_deepcopy.nim7
-rw-r--r--tests/parallel/tnon_disjoint_slice1.nim3
-rw-r--r--tests/parallel/tparfind.nim1
-rw-r--r--tests/parallel/tpi.nim1
-rw-r--r--tests/parallel/tsendtwice.nim27
-rw-r--r--tests/parallel/tsimple_array_checks.nim12
-rw-r--r--tests/parallel/tsysspawn.nim37
-rw-r--r--tests/parallel/tuseafterdef.nim5
-rw-r--r--tests/parallel/twaitany.nim9
-rw-r--r--tests/parser/t12274.nim13
-rw-r--r--tests/parser/t15667.nim61
-rw-r--r--tests/parser/t19430.nim3
-rw-r--r--tests/parser/t19662.nim6
-rw-r--r--tests/parser/t20922.nim35
-rw-r--r--tests/parser/tbinarynotindented.nim3
-rw-r--r--tests/parser/tbinarynotsameline.nim10
-rw-r--r--tests/parser/tcommand_as_expr.nim9
-rw-r--r--tests/parser/tcommandequals.nim17
-rw-r--r--tests/parser/tcommandindent.nim16
-rw-r--r--tests/parser/tdo.nim19
-rw-r--r--tests/parser/tdoc_comments.nim4
-rw-r--r--tests/parser/tdotlikeoperators.nim30
-rw-r--r--tests/parser/tdoublenotnil.nim3
-rw-r--r--tests/parser/tifexprs.nim12
-rw-r--r--tests/parser/tifextracolon.nim8
-rw-r--r--tests/parser/tinvifstmt.nim12
-rw-r--r--tests/parser/tpostexprblocks.nim126
-rw-r--r--tests/parser/tprecedence.nim7
-rw-r--r--tests/parser/tprocexprasstmt.nim14
-rw-r--r--tests/parser/tstatementoperators.nim12
-rw-r--r--tests/parser/tstmtlists.nim180
-rw-r--r--tests/parser/ttry.nim27
-rw-r--r--tests/parser/ttupleunpack.nim65
-rw-r--r--tests/parser/ttypeclasses.nim50
-rw-r--r--tests/parser/ttypecommandcomma.nim9
-rw-r--r--tests/parser/ttypecommandindent1.nim9
-rw-r--r--tests/parser/ttypecommandindent2.nim11
-rw-r--r--tests/parser/ttypecommandindent3.nim11
-rw-r--r--tests/parser/ttypeexprobject.nim10
-rw-r--r--tests/parser/ttypeexprs.nim25
-rw-r--r--tests/parser/ttypemodifiers.nim15
-rw-r--r--tests/parser/ttypesectioncalls.nim328
-rw-r--r--tests/pragmas/cfunction.c4
-rw-r--r--tests/pragmas/monoff1.nim1
-rw-r--r--tests/pragmas/mqualifiedmacro.nim10
-rw-r--r--tests/pragmas/t12558.nim15
-rw-r--r--tests/pragmas/t12640.nim26
-rw-r--r--tests/pragmas/t13306.nim10
-rw-r--r--tests/pragmas/t22713.nim12
-rw-r--r--tests/pragmas/t6448.nim2
-rw-r--r--tests/pragmas/t8741.nim4
-rw-r--r--tests/pragmas/tbitsize.nim10
-rw-r--r--tests/pragmas/tcompile_missing_file.nim5
-rw-r--r--tests/pragmas/tcompile_pragma.nim10
-rw-r--r--tests/pragmas/tcustom_pragma.nim347
-rw-r--r--tests/pragmas/thintprocessing.nim18
-rw-r--r--tests/pragmas/tinvalid_user_pragma.nim9
-rw-r--r--tests/pragmas/tinvalidcustompragma.nim23
-rw-r--r--tests/pragmas/tlocks.nim1
-rw-r--r--tests/pragmas/tnoreturn.nim1
-rw-r--r--tests/pragmas/tonoff1.nim8
-rw-r--r--tests/pragmas/tonoff2.nim14
-rw-r--r--tests/pragmas/tpragmas_misc.nim75
-rw-r--r--tests/pragmas/tpragmas_reorder.nim19
-rw-r--r--tests/pragmas/tpush.nim129
-rw-r--r--tests/pragmas/tpushnotes.nim13
-rw-r--r--tests/pragmas/tqualifiedmacro.nim14
-rw-r--r--tests/pragmas/ttypedef_macro.nim66
-rw-r--r--tests/pragmas/tuserpragma2.nim3
-rw-r--r--tests/pragmas/tuserpragmaargs.nim5
-rw-r--r--tests/pragmas/tvar_macro.nim128
-rw-r--r--tests/pragmas/twarning_off.nim2
-rw-r--r--tests/proc/mdefaultprocparam.nim (renamed from tests/defaultprocparam/mdefaultprocparam.nim)0
-rw-r--r--tests/proc/t15949.nim16
-rw-r--r--tests/proc/t17157.nim6
-rw-r--r--tests/proc/t19795.nim19
-rw-r--r--tests/proc/t23874.nim26
-rw-r--r--tests/proc/tcolonisproc.nim (renamed from tests/misc/tcolonisproc.nim)0
-rw-r--r--tests/proc/tdefaultprocparam.nim90
-rw-r--r--tests/proc/texplicitgenericcount.nim24
-rw-r--r--tests/proc/texplicitgenericcountverbose.nim22
-rw-r--r--tests/proc/texplicitgenerics.nim55
-rw-r--r--tests/proc/tfunc_type.nim2
-rw-r--r--tests/proc/tgenericdefaultparam.nim98
-rw-r--r--tests/proc/tillegalreturntype.nim4
-rw-r--r--tests/proc/tinferlambdareturn.nim36
-rw-r--r--tests/proc/tlambdadonotation.nim (renamed from tests/misc/tlambdadonotation.nim)2
-rw-r--r--tests/proc/tlambdapragma.nim7
-rw-r--r--tests/proc/tnamedparams.nim (renamed from tests/namedparams/tnamedparams.nim)0
-rw-r--r--tests/proc/tnamedparams2.nim (renamed from tests/namedparams/tnamedparams2.nim)0
-rw-r--r--tests/proc/tnamedparams3.nim (renamed from tests/namedparams/tnamedparams3.nim)0
-rw-r--r--tests/proc/tparamsindefault.nim (renamed from tests/misc/tparamsindefault.nim)0
-rw-r--r--tests/proc/tprocvar.nim (renamed from tests/procvar/tprocvar.nim)0
-rw-r--r--tests/proc/tprocvarmismatch.nim (renamed from tests/procvar/tprocvarmismatch.nim)0
-rw-r--r--tests/proc/tstaticsignature.nim268
-rw-r--r--tests/proc/tunderscoreparam.nim122
-rw-r--r--tests/proc/twrongdefaultvalue.nim25
-rw-r--r--tests/range/t19678.nim17
-rw-r--r--tests/range/tcompiletime_range_checks.nim6
-rw-r--r--tests/range/texplicitvarconv.nim13
-rw-r--r--tests/range/toutofrangevarconv.nim14
-rw-r--r--tests/range/trange.nim34
-rw-r--r--tests/range/tsubrange2.nim2
-rw-r--r--tests/range/tsubrange3.nim2
-rw-r--r--tests/readme.md37
-rw-r--r--tests/realtimeGC/cmain.c67
-rw-r--r--tests/realtimeGC/main.nim.cfg6
-rw-r--r--tests/realtimeGC/nmain.nim46
-rw-r--r--tests/realtimeGC/readme.txt21
-rw-r--r--tests/realtimeGC/shared.nim5
-rw-r--r--tests/realtimeGC/shared.nim.cfg5
-rw-r--r--tests/realtimeGC/tmain.nim62
-rw-r--r--tests/refc/tsinkbug.nim26
-rw-r--r--tests/rodfiles/aconv.nim9
-rw-r--r--tests/rodfiles/amethods.nim13
-rw-r--r--tests/rodfiles/bconv.nim9
-rw-r--r--tests/rodfiles/bmethods.nim29
-rw-r--r--tests/rodfiles/bmethods2.nim29
-rw-r--r--tests/rodfiles/deada.nim8
-rw-r--r--tests/rodfiles/deada2.nim12
-rw-r--r--tests/rodfiles/deadb.nim7
-rw-r--r--tests/rodfiles/deadg.nim7
-rw-r--r--tests/rodfiles/gtkex1.nim14
-rw-r--r--tests/rodfiles/gtkex2.nim22
-rw-r--r--tests/rodfiles/hallo.nim6
-rw-r--r--tests/rodfiles/hallo2.nim17
-rw-r--r--tests/rodfiles/int2bool.nim7
-rw-r--r--tests/rodfiles/nim.cfg2
-rw-r--r--tests/rodfiles/tgeneric1.nim13
-rw-r--r--tests/rodfiles/tgeneric2.nim13
-rw-r--r--tests/sandwich/generic_library.nim6
-rw-r--r--tests/sandwich/helper_module.nim3
-rw-r--r--tests/sandwich/module_using_generic_library.nim12
-rw-r--r--tests/sandwich/tmain.nim9
-rw-r--r--tests/sets/m17385.nim11
-rw-r--r--tests/sets/t13764.nim6
-rw-r--r--tests/sets/t15435.nim29
-rw-r--r--tests/sets/t17385.nim4
-rw-r--r--tests/sets/t20997.nim18
-rw-r--r--tests/sets/t5792.nim17
-rw-r--r--tests/sets/thugeset.nim10
-rw-r--r--tests/sets/tnewsets.nim (renamed from tests/misc/tnewsets.nim)0
-rw-r--r--tests/sets/trangeincompatible.nim32
-rw-r--r--tests/sets/tsets.nim293
-rw-r--r--tests/sets/tsets_various.nim228
-rw-r--r--tests/sets/twrongenumrange.nim50
-rw-r--r--tests/showoff/tdrdobbs_examples.nim4
-rw-r--r--tests/showoff/tformatopt.nim2
-rw-r--r--tests/showoff/tgenericmacrotypes.nim55
-rw-r--r--tests/specialops/tcallops.nim49
-rw-r--r--tests/specialops/tcallprecedence.nim44
-rw-r--r--tests/specialops/tdotops.nim12
-rw-r--r--tests/specialops/terrmsgs.nim76
-rw-r--r--tests/specialops/tnewseq.nim22
-rw-r--r--tests/specialops/tsetter.nim10
-rw-r--r--tests/statictypes/t20148.nim8
-rw-r--r--tests/statictypes/t5780.nim3
-rw-r--r--tests/statictypes/t9255.nim2
-rw-r--r--tests/statictypes/tgenericcomputedrange.nim125
-rw-r--r--tests/statictypes/tpassthruarith.nim4
-rw-r--r--tests/statictypes/tstatic.nim56
-rw-r--r--tests/statictypes/tstaticgenericparam.nim24
-rw-r--r--tests/statictypes/tstaticimportcpp.nim6
-rw-r--r--tests/statictypes/tstaticprocparams.nim16
-rw-r--r--tests/statictypes/tstatictypes.nim309
-rw-r--r--tests/stdlib/concurrency/atomicSample.nim9
-rw-r--r--tests/stdlib/concurrency/tatomic_import.nim11
-rw-r--r--tests/stdlib/concurrency/tatomics.nim637
-rw-r--r--tests/stdlib/concurrency/tatomics_size.nim21
-rw-r--r--tests/stdlib/config.nims5
-rw-r--r--tests/stdlib/mgenast.nim57
-rw-r--r--tests/stdlib/mimportutils.nim38
-rw-r--r--tests/stdlib/mintsets.nim11
-rw-r--r--tests/stdlib/mstackframes.nim38
-rw-r--r--tests/stdlib/nre/captures.nim16
-rw-r--r--tests/stdlib/nre/escape.nim4
-rw-r--r--tests/stdlib/nre/find.nim12
-rw-r--r--tests/stdlib/nre/init.nim10
-rw-r--r--tests/stdlib/nre/match.nim8
-rw-r--r--tests/stdlib/nre/misc.nim10
-rw-r--r--tests/stdlib/nre/replace.nim12
-rw-r--r--tests/stdlib/nre/split.nim14
-rw-r--r--tests/stdlib/t10231.nim3
-rw-r--r--tests/stdlib/t14139.nim10
-rw-r--r--tests/stdlib/t15663.nim9
-rw-r--r--tests/stdlib/t19304.nim7
-rw-r--r--tests/stdlib/t20023.nim10
-rw-r--r--tests/stdlib/t21251.nim6
-rw-r--r--tests/stdlib/t21406.nim7
-rw-r--r--tests/stdlib/t21564.nim32
-rw-r--r--tests/stdlib/t7686.nim10
-rw-r--r--tests/stdlib/t8925.nim2
-rw-r--r--tests/stdlib/t9754.nim6
-rw-r--r--tests/stdlib/talgorithm.nim275
-rw-r--r--tests/stdlib/tarithmetics.nim50
-rw-r--r--tests/stdlib/tasynchttpserver.nim121
-rw-r--r--tests/stdlib/tasynchttpserver_transferencoding.nim91
-rw-r--r--tests/stdlib/tbase64.nim49
-rw-r--r--tests/stdlib/tbitops.nim348
-rw-r--r--tests/stdlib/tbitops.nim.cfg2
-rw-r--r--tests/stdlib/tbitops2.nim167
-rw-r--r--tests/stdlib/tbitops2.nim.cfg2
-rw-r--r--tests/stdlib/tbitops_utils.nim19
-rw-r--r--tests/stdlib/tcasts.nim26
-rw-r--r--tests/stdlib/tcgi.nim22
-rw-r--r--tests/stdlib/tclosures.nim47
-rw-r--r--tests/stdlib/tcmdline.nim13
-rw-r--r--tests/stdlib/tcomplex.nim115
-rw-r--r--tests/stdlib/tcookies.nim22
-rw-r--r--tests/stdlib/tcritbits.nim89
-rw-r--r--tests/stdlib/tcstring.nim93
-rw-r--r--tests/stdlib/tcstrutils.nim39
-rw-r--r--tests/stdlib/tdb.nim0
-rw-r--r--tests/stdlib/tdb.nims1
-rw-r--r--tests/stdlib/tdb_mysql.nim0
-rw-r--r--tests/stdlib/tdecls.nim50
-rw-r--r--tests/stdlib/tdecode_helpers.nim27
-rw-r--r--tests/stdlib/tdeques.nim243
-rw-r--r--tests/stdlib/tdiff.nim75
-rw-r--r--tests/stdlib/tdistros_detect.nim16
-rw-r--r--tests/stdlib/tdochelpers.nim221
-rw-r--r--tests/stdlib/teditdistance.nim45
-rw-r--r--tests/stdlib/tencodings.nim107
-rw-r--r--tests/stdlib/tenumerate.nim24
-rw-r--r--tests/stdlib/tenumutils.nim49
-rw-r--r--tests/stdlib/tenvvars.nim162
-rw-r--r--tests/stdlib/texitprocs.nim22
-rw-r--r--tests/stdlib/tfdleak.nim152
-rw-r--r--tests/stdlib/tfdleak_multiple.nim31
-rw-r--r--tests/stdlib/tfenv.nim8
-rw-r--r--tests/stdlib/tfilesanddirs.nim36
-rw-r--r--tests/stdlib/tfrexp1.nim19
-rw-r--r--tests/stdlib/tgenast.nim274
-rw-r--r--tests/stdlib/tgetaddrinfo.nim4
-rw-r--r--tests/stdlib/tgetfileinfo.nim32
-rw-r--r--tests/stdlib/tgetprotobyname.nim19
-rw-r--r--tests/stdlib/tglobs.nim25
-rw-r--r--tests/stdlib/thashes.nim249
-rw-r--r--tests/stdlib/theapqueue.nim106
-rw-r--r--tests/stdlib/thighlite.nim45
-rw-r--r--tests/stdlib/thtmlparser.nim21
-rw-r--r--tests/stdlib/thttpclient.nim55
-rw-r--r--tests/stdlib/thttpclient_ssl.nim150
-rw-r--r--tests/stdlib/thttpclient_ssl_cert.pem29
-rw-r--r--tests/stdlib/thttpclient_ssl_key.pem52
-rw-r--r--tests/stdlib/thttpclient_standalone.nim59
-rw-r--r--tests/stdlib/thttpcore.nim116
-rw-r--r--tests/stdlib/timportutils.nim151
-rw-r--r--tests/stdlib/tintsets.nim6
-rw-r--r--tests/stdlib/tio.nim60
-rw-r--r--tests/stdlib/tisolation.nim135
-rw-r--r--tests/stdlib/tjsbigints.nim46
-rw-r--r--tests/stdlib/tjson.nim382
-rw-r--r--tests/stdlib/tjsonmacro.nim24
-rw-r--r--tests/stdlib/tjsonutils.nim476
-rw-r--r--tests/stdlib/tlists.nim298
-rw-r--r--tests/stdlib/tlocks.nim7
-rw-r--r--tests/stdlib/tlwip.nim30
-rw-r--r--tests/stdlib/tmacros.nim349
-rw-r--r--tests/stdlib/tmarshal.nim259
-rw-r--r--tests/stdlib/tmarshalsegfault.nim54
-rw-r--r--tests/stdlib/tmath.nim606
-rw-r--r--tests/stdlib/tmemfiles1.nim2
-rw-r--r--tests/stdlib/tmemfiles2.nim8
-rw-r--r--tests/stdlib/tmemlinesBuf.nim12
-rw-r--r--tests/stdlib/tmemmapstreams.nim2
-rw-r--r--tests/stdlib/tmersenne.nim13
-rw-r--r--tests/stdlib/tmget.nim19
-rw-r--r--tests/stdlib/tmimetypes.nim28
-rw-r--r--tests/stdlib/tmisc_issues.nim39
-rw-r--r--tests/stdlib/tmitems.nim32
-rw-r--r--tests/stdlib/tmonotimes.nim22
-rw-r--r--tests/stdlib/tnativesockets.nim30
-rw-r--r--tests/stdlib/tnet.nim69
-rw-r--r--tests/stdlib/tnet_ll.nim94
-rw-r--r--tests/stdlib/tnetbind.nim11
-rw-r--r--tests/stdlib/tnetconnect.nim30
-rw-r--r--tests/stdlib/tnetdial.nim9
-rw-r--r--tests/stdlib/tnre.nim18
-rw-r--r--tests/stdlib/tntpath.nim50
-rw-r--r--tests/stdlib/tobjectdollar.nim14
-rw-r--r--tests/stdlib/toids.nim15
-rw-r--r--tests/stdlib/topenssl.nim46
-rw-r--r--tests/stdlib/toptions.nim207
-rw-r--r--tests/stdlib/tos.nim531
-rw-r--r--tests/stdlib/tos_unc.nim2
-rw-r--r--tests/stdlib/tosenv.nim163
-rw-r--r--tests/stdlib/toserrors.nim9
-rw-r--r--tests/stdlib/tosproc.nim259
-rw-r--r--tests/stdlib/tosprocterminate.nim33
-rw-r--r--tests/stdlib/tpackedsets.nim265
-rw-r--r--tests/stdlib/tparscfg.nim69
-rw-r--r--tests/stdlib/tparsecfg.nim149
-rw-r--r--tests/stdlib/tparsecsv.nim36
-rw-r--r--tests/stdlib/tparseipv6.nim95
-rw-r--r--tests/stdlib/tparsesql.nim123
-rw-r--r--tests/stdlib/tparseuints.nim16
-rw-r--r--tests/stdlib/tparseutils.nim112
-rw-r--r--tests/stdlib/tparsopt.nim4
-rw-r--r--tests/stdlib/tpathnorm.nim36
-rw-r--r--tests/stdlib/tpaths.nim238
-rw-r--r--tests/stdlib/tpegs.nim210
-rw-r--r--tests/stdlib/tposix.nim71
-rw-r--r--tests/stdlib/tprelude.nim16
-rw-r--r--tests/stdlib/tquit.nim13
-rw-r--r--tests/stdlib/trandom.nim310
-rw-r--r--tests/stdlib/trat_float.nim (renamed from tests/rational/trat_float.nim)0
-rw-r--r--tests/stdlib/trat_init.nim (renamed from tests/rational/trat_init.nim)2
-rw-r--r--tests/stdlib/trationals.nim117
-rw-r--r--tests/stdlib/tre.nim122
-rw-r--r--tests/stdlib/treadln.nim (renamed from tests/misc/treadln.nim)4
-rw-r--r--tests/stdlib/tregex.nim3
-rw-r--r--tests/stdlib/tregistry.nim16
-rw-r--r--tests/stdlib/trepr.nim358
-rw-r--r--tests/stdlib/trepr2.nim37
-rw-r--r--tests/stdlib/trlocks.nim14
-rw-r--r--tests/stdlib/tropes.nim104
-rw-r--r--tests/stdlib/trst.nim1931
-rw-r--r--tests/stdlib/trstgen.nim1579
-rw-r--r--tests/stdlib/tsequtils.nim547
-rw-r--r--tests/stdlib/tsetutils.nim49
-rw-r--r--tests/stdlib/tsharedlist.nim49
-rw-r--r--tests/stdlib/tsharedtable.nim89
-rw-r--r--tests/stdlib/tsince.nim32
-rw-r--r--tests/stdlib/tsocketstreams.nim65
-rw-r--r--tests/stdlib/tsortcall.nim2
-rw-r--r--tests/stdlib/tsqlitebindatas.nim0
-rw-r--r--tests/stdlib/tsqlparser.nim1
-rw-r--r--tests/stdlib/tssl.nim138
-rw-r--r--tests/stdlib/tssl.nims5
-rw-r--r--tests/stdlib/tstackframes.nim34
-rw-r--r--tests/stdlib/tstaticos.nim8
-rw-r--r--tests/stdlib/tstats.nim61
-rw-r--r--tests/stdlib/tstdlib_issues.nim7
-rw-r--r--tests/stdlib/tstdlib_various.nim63
-rw-r--r--tests/stdlib/tstrbasics.nim103
-rw-r--r--tests/stdlib/tstreams.nim79
-rw-r--r--tests/stdlib/tstreams2.nim12
-rw-r--r--tests/stdlib/tstreams3.nim20
-rw-r--r--tests/stdlib/tstrformat.nim753
-rw-r--r--tests/stdlib/tstrformatlineinfo.nim8
-rw-r--r--tests/stdlib/tstrimpl.nim12
-rw-r--r--tests/stdlib/tstring.nim207
-rw-r--r--tests/stdlib/tstrmiscs.nim27
-rw-r--r--tests/stdlib/tstrscans.nim214
-rw-r--r--tests/stdlib/tstrset.nim16
-rw-r--r--tests/stdlib/tstrtabs.nim15
-rw-r--r--tests/stdlib/tstrtabs.nims5
-rw-r--r--tests/stdlib/tstrtabs2.nim32
-rw-r--r--tests/stdlib/tstrutil.nim350
-rw-r--r--tests/stdlib/tstrutils.nim913
-rw-r--r--tests/stdlib/tsugar.nim310
-rw-r--r--tests/stdlib/tsums.nim27
-rw-r--r--tests/stdlib/tsysrand.nim34
-rw-r--r--tests/stdlib/tsystem.nim200
-rw-r--r--tests/stdlib/ttables.nim316
-rw-r--r--tests/stdlib/ttasks.nim561
-rw-r--r--tests/stdlib/ttempfiles.nim51
-rw-r--r--tests/stdlib/tterminal.nim7
-rw-r--r--tests/stdlib/tterminal_12759.nim11
-rw-r--r--tests/stdlib/tterminal_15874.nim8
-rw-r--r--tests/stdlib/ttestutils.nim40
-rw-r--r--tests/stdlib/tthreadpool.nim14
-rw-r--r--tests/stdlib/ttimes.nim300
-rw-r--r--tests/stdlib/ttypeinfo.nim93
-rw-r--r--tests/stdlib/ttypeinfo.nims1
-rw-r--r--tests/stdlib/ttypetraits.nim94
-rw-r--r--tests/stdlib/tunicode.nim228
-rw-r--r--tests/stdlib/tunidecode.nim9
-rw-r--r--tests/stdlib/tunittest.nim106
-rw-r--r--tests/stdlib/tunittest_error.nim22
-rw-r--r--tests/stdlib/tunittestpass.nim20
-rw-r--r--tests/stdlib/tunittesttemplate.nim25
-rw-r--r--tests/stdlib/tunixsocket.nim35
-rw-r--r--tests/stdlib/turi.nim323
-rw-r--r--tests/stdlib/tuserlocks.nim21
-rw-r--r--tests/stdlib/tvarargs.nim18
-rw-r--r--tests/stdlib/tvarints.nim73
-rw-r--r--tests/stdlib/tvmutils.nim31
-rw-r--r--tests/stdlib/tvolatile.nim15
-rw-r--r--tests/stdlib/twchartoutf8.nim7
-rw-r--r--tests/stdlib/twith.nim44
-rw-r--r--tests/stdlib/twordwrap.nim48
-rw-r--r--tests/stdlib/twrapnils.nim288
-rw-r--r--tests/stdlib/twrongstattype.nim14
-rw-r--r--tests/stdlib/txmltree.nim120
-rw-r--r--tests/stdlib/tyield.nim258
-rw-r--r--tests/stdlib/unixsockettest.nim26
-rw-r--r--tests/stdlib/uselocks.nim5
-rw-r--r--tests/stmt/tforloop_tuple_multiple_underscore.nim10
-rw-r--r--tests/stmt/tforloop_tuple_underscore.nim16
-rw-r--r--tests/stmt/tforloop_underscore.nim6
-rw-r--r--tests/stmt/tgenericsunderscore.nim4
-rw-r--r--tests/stmt/tmiscunderscore.nim15
-rw-r--r--tests/strictnotnil/tnilcheck.nim381
-rw-r--r--tests/strictnotnil/tnilcheck_no_warnings.nim182
-rw-r--r--tests/stylecheck/fileinfo.nim2
-rw-r--r--tests/stylecheck/foreign_package/foreign_package.nim1
-rw-r--r--tests/stylecheck/foreign_package/foreign_package.nimble2
-rw-r--r--tests/stylecheck/t20397.nim4
-rw-r--r--tests/stylecheck/t20397_1.nim8
-rw-r--r--tests/stylecheck/t20397_2.nim7
-rw-r--r--tests/stylecheck/taccept.nim22
-rw-r--r--tests/stylecheck/tforeign_package.nim16
-rw-r--r--tests/stylecheck/thint.nim43
-rw-r--r--tests/stylecheck/treject.nim17
-rw-r--r--tests/stylecheck/tusages.nim22
-rw-r--r--tests/system/t10307.nim24
-rw-r--r--tests/system/t20938.nim12
-rw-r--r--tests/system/talloc.nim6
-rw-r--r--tests/system/talloc2.nim3
-rw-r--r--tests/system/tatomics1.nim9
-rw-r--r--tests/system/tcomparisons.nim51
-rw-r--r--tests/system/tconcat.nim (renamed from tests/concat/tconcat.nim)0
-rw-r--r--tests/system/tdeepcopy.nim1
-rw-r--r--tests/system/tdollars.nim199
-rw-r--r--tests/system/temptyecho.nim6
-rw-r--r--tests/system/tensuremove.nim131
-rw-r--r--tests/system/tensuremove1.nim16
-rw-r--r--tests/system/tensuremove2.nim15
-rw-r--r--tests/system/tensuremove3.nim28
-rw-r--r--tests/system/tenum_array_repr.nim2
-rw-r--r--tests/system/tfielditerator.nim (renamed from tests/fields/tfielditerator.nim)28
-rw-r--r--tests/system/tfields.nim (renamed from tests/fields/tfields.nim)0
-rw-r--r--tests/system/tgcnone.nim7
-rw-r--r--tests/system/tgcregions.nim (renamed from tests/misc/tgcregions.nim)0
-rw-r--r--tests/system/timmutableinc.nim (renamed from tests/misc/tinc.nim)2
-rw-r--r--tests/system/tinvalidnot.nim (renamed from tests/misc/tnot.nim)2
-rw-r--r--tests/system/tio.nim8
-rw-r--r--tests/system/tlocals.nim (renamed from tests/misc/tlocals.nim)12
-rw-r--r--tests/system/tlowhigh.nim (renamed from tests/misc/tlowhigh.nim)0
-rw-r--r--tests/system/tmagics.nim (renamed from tests/magics/tmagics.nim)7
-rw-r--r--tests/system/tmemory.nim16
-rw-r--r--tests/system/tnew.nim (renamed from tests/misc/tnew.nim)6
-rw-r--r--tests/system/tnewderef.nim (renamed from tests/misc/tnewderef.nim)0
-rw-r--r--tests/system/tnewstring_uninitialized.nim11
-rw-r--r--tests/system/tnilconcats.nim3
-rw-r--r--tests/system/tnim_stacktrace_override.nim18
-rw-r--r--tests/system/tostring.nim27
-rw-r--r--tests/system/trealloc.nim13
-rw-r--r--tests/system/trefs.nim15
-rw-r--r--tests/system/tsigexitcode.nim23
-rw-r--r--tests/system/tslices.nim (renamed from tests/misc/tslices.nim)17
-rw-r--r--tests/system/tslimsystem.nim6
-rw-r--r--tests/system/tstatic.nim58
-rw-r--r--tests/system/tstatic_callable.nim12
-rw-r--r--tests/system/tstatic_callable_error.nim14
-rw-r--r--tests/system/tsystem_misc.nim71
-rw-r--r--tests/system/tuse_version16.nim49
-rw-r--r--tests/system/tvarargslen.nim (renamed from tests/system/tlenvarargs.nim)19
-rw-r--r--tests/template/m1027a.nim1
-rw-r--r--tests/template/m1027b.nim1
-rw-r--r--tests/template/m19277_1.nim2
-rw-r--r--tests/template/m19277_2.nim2
-rw-r--r--tests/template/mdotcall.nim82
-rw-r--r--tests/template/mdotcall2.nim7
-rw-r--r--tests/template/mqualifiedtype1.nim2
-rw-r--r--tests/template/mqualifiedtype2.nim2
-rw-r--r--tests/template/otests.nim4
-rw-r--r--tests/template/sunset.nimf2
-rw-r--r--tests/template/t1027.nim22
-rw-r--r--tests/template/t11705.nim17
-rw-r--r--tests/template/t13426.nim87
-rw-r--r--tests/template/t17433.nim16
-rw-r--r--tests/template/t18113.nim14
-rw-r--r--tests/template/t19149.nim19
-rw-r--r--tests/template/t19277.nim19
-rw-r--r--tests/template/t19700.nim10
-rw-r--r--tests/template/t21231.nim10
-rw-r--r--tests/template/t21532.nim8
-rw-r--r--tests/template/t24112.nim19
-rw-r--r--tests/template/t6217.nim19
-rw-r--r--tests/template/t9534.nim21
-rw-r--r--tests/template/taliassyntax.nim74
-rw-r--r--tests/template/taliassyntaxerrors.nim28
-rw-r--r--tests/template/tcallsitelineinfo.nim17
-rw-r--r--tests/template/tcallsitelineinfo2.nim20
-rw-r--r--tests/template/tdefaultparam.nim56
-rw-r--r--tests/template/tdotcall.nim32
-rw-r--r--tests/template/template_issues.nim59
-rw-r--r--tests/template/template_pragmas.nim2
-rw-r--r--tests/template/template_various.nim165
-rw-r--r--tests/template/tgenericparam.nim93
-rw-r--r--tests/template/tgensym_instantiationinfo.nim2
-rw-r--r--tests/template/tgensymhijack.nim37
-rw-r--r--tests/template/tgensymregression.nim4
-rw-r--r--tests/template/tidentconcatenations.nim (renamed from tests/misc/tidentconcatenations.nim)0
-rw-r--r--tests/template/tinnerouterproc.nim20
-rw-r--r--tests/template/tmodulealias.nim2
-rw-r--r--tests/template/tnested.nim38
-rw-r--r--tests/template/tobjectdeclfield.nim21
-rw-r--r--tests/template/topensym.nim209
-rw-r--r--tests/template/topensymoverride.nim39
-rw-r--r--tests/template/topensymwarning.nim60
-rw-r--r--tests/template/tparams_gensymed.nim210
-rw-r--r--tests/template/tparamscope.nim10
-rw-r--r--tests/template/tqualifiedident.nim8
-rw-r--r--tests/template/tqualifiedtype.nim25
-rw-r--r--tests/template/tredefinition_override.nim33
-rw-r--r--tests/template/tshadow.nim29
-rw-r--r--tests/template/tunderscore1.nim11
-rw-r--r--tests/template/twhenintemplates.nim11
-rw-r--r--tests/template/twrongmapit.nim6
-rw-r--r--tests/template/utemplates.nim8
-rw-r--r--tests/test_nimscript.nims153
-rw-r--r--tests/testament/t16576.nim7
-rw-r--r--tests/testament/tinlinemsg.nim8
-rw-r--r--tests/testament/tjoinable.nim9
-rw-r--r--tests/testament/treject.nim6
-rw-r--r--tests/testament/tshould_not_work.nim52
-rw-r--r--tests/testament/tspecialpaths.nim9
-rw-r--r--tests/testdata/mycert.pem105
-rw-r--r--tests/threads/t7172.nim34
-rw-r--r--tests/threads/t8535.nim3
-rw-r--r--tests/threads/threadex.nim1
-rw-r--r--tests/threads/tjsthreads.nim6
-rw-r--r--tests/threads/tmanyjoin.nim3
-rw-r--r--tests/threads/tmembug.nim51
-rw-r--r--tests/threads/tonthreadcreation.nim2
-rw-r--r--tests/threads/tracy_allocator.nim1
-rw-r--r--tests/threads/treusetvar.nim7
-rw-r--r--tests/threads/tthreadanalysis2.nim51
-rw-r--r--tests/threads/tthreadvars.nim1
-rw-r--r--tests/threads/ttryrecv.nim3
-rw-r--r--tests/tools/compile/config.nims1
-rw-r--r--tests/tools/compile/readme.md1
-rw-r--r--tests/tools/compile/tdeps.nim (renamed from tests/flags/tgenscript.nim)3
-rw-r--r--tests/tools/compile/tdetect.nim5
-rw-r--r--tests/tools/compile/tkoch.nim5
-rw-r--r--tests/tools/compile/tniminst.nim5
-rw-r--r--tests/tools/config.nims3
-rw-r--r--tests/tools/second.nim6
-rw-r--r--tests/tools/tlinter.nim10
-rw-r--r--tests/tools/tnimgrep.nim404
-rw-r--r--tests/tools/tunused_imports.nim13
-rw-r--r--tests/trmacros/tdisallowif.nim5
-rw-r--r--tests/trmacros/tnorewrite.nim20
-rw-r--r--tests/trmacros/tor.nim24
-rw-r--r--tests/trmacros/trmacros_various.nim3
-rw-r--r--tests/trmacros/trmacros_various2.nim8
-rw-r--r--tests/tuples/mnimsconstunpack.nim4
-rw-r--r--tests/tuples/t12892.nim8
-rw-r--r--tests/tuples/t18125_1.nim14
-rw-r--r--tests/tuples/t18125_2.nim20
-rw-r--r--tests/tuples/t7012.nim7
-rw-r--r--tests/tuples/tinferred_generic_const.nim14
-rw-r--r--tests/tuples/tnimsconstunpack.nim8
-rw-r--r--tests/tuples/ttuples_issues.nim204
-rw-r--r--tests/tuples/ttuples_various.nim38
-rw-r--r--tests/tuples/tuple_with_nil.nim15
-rw-r--r--tests/typerel/t4799_1.nim3
-rw-r--r--tests/typerel/t4799_2.nim3
-rw-r--r--tests/typerel/t4799_3.nim3
-rw-r--r--tests/typerel/t7600_1.nim2
-rw-r--r--tests/typerel/t7600_2.nim2
-rw-r--r--tests/typerel/tcommontype.nim4
-rw-r--r--tests/typerel/texplicitcmp.nim2
-rw-r--r--tests/typerel/tnoargopenarray.nim8
-rw-r--r--tests/typerel/tproctypeclass.nim89
-rw-r--r--tests/typerel/tregionptrs.nim16
-rw-r--r--tests/typerel/tsigmatch.nim6
-rw-r--r--tests/typerel/tstr_as_openarray.nim6
-rw-r--r--tests/typerel/ttynilinstantiation.nim7
-rw-r--r--tests/typerel/ttypedesc_as_genericparam1.nim7
-rw-r--r--tests/typerel/ttypedesc_as_genericparam1_orc.nim5
-rw-r--r--tests/typerel/ttypedesc_as_genericparam2.nim3
-rw-r--r--tests/typerel/ttypelessemptyset.nim2
-rw-r--r--tests/typerel/ttypenoval.nim2
-rw-r--r--tests/typerel/ttypenovalue.nim3
-rw-r--r--tests/typerel/tuncheckedarray_eq.nim2
-rw-r--r--tests/typerel/tvoid.nim61
-rw-r--r--tests/typerel/typedescs.nim15
-rw-r--r--tests/typerel/typedescs2.nim4
-rw-r--r--tests/types/t14127_cast_number.nim30
-rw-r--r--tests/types/t15836.nim11
-rw-r--r--tests/types/t15836_2.nim21
-rw-r--r--tests/types/t21027.nim5
-rw-r--r--tests/types/t21260.nim13
-rw-r--r--tests/types/t5648.nim32
-rw-r--r--tests/types/tcast1.nim42
-rw-r--r--tests/types/tcyclic.nim135
-rw-r--r--tests/types/temptyseqs.nim8
-rw-r--r--tests/types/texportgeneric.nim8
-rw-r--r--tests/types/tfinalobj.nim2
-rw-r--r--tests/types/tillegalseqrecursion.nim6
-rw-r--r--tests/types/tillegaltuplerecursion.nim4
-rw-r--r--tests/types/tillegaltyperecursion.nim51
-rw-r--r--tests/types/tinheritgenericparameter.nim39
-rw-r--r--tests/types/tinheritref.nim6
-rw-r--r--tests/types/tisop.nim48
-rw-r--r--tests/types/tisopr.nim80
-rw-r--r--tests/types/tissues_types.nim92
-rw-r--r--tests/types/titerable.nim143
-rw-r--r--tests/types/tlent_var.nim2
-rw-r--r--tests/types/tnontype.nim9
-rw-r--r--tests/types/told_pragma_syntax1.nim5
-rw-r--r--tests/types/told_pragma_syntax2.nim5
-rw-r--r--tests/types/ttopdowninference.nim333
-rw-r--r--tests/types/tyet_another_generic_regression.nim9
-rw-r--r--tests/untestable/gdb/gdb_pretty_printer_test.py50
-rw-r--r--tests/untestable/gdb/gdb_pretty_printer_test_output.txt3
-rw-r--r--tests/untestable/gdb/gdb_pretty_printer_test_program.nim68
-rwxr-xr-x[-rw-r--r--]tests/untestable/gdb/gdb_pretty_printer_test_run.sh20
-rw-r--r--tests/untestable/thttpclient_ssl_disabled.nim36
-rw-r--r--tests/untestable/thttpclient_ssl_env_var.nim74
-rw-r--r--tests/untestable/thttpclient_ssl_remotenetwork.nim230
-rw-r--r--tests/untestable/tpostgres.nim327
-rw-r--r--tests/usingstmt/tthis.nim15
-rw-r--r--tests/usingstmt/tusingstmt.nim16
-rw-r--r--tests/valgrind/tleak_arc.nim14
-rw-r--r--tests/varres/tprevent_forloopvar_mutations.nim9
-rw-r--r--tests/varres/tvarres0.nim111
-rw-r--r--tests/varstmt/tvardecl.nim7
-rw-r--r--tests/views/t19986.nim42
-rw-r--r--tests/views/tcan_compile_nim.nim4
-rw-r--r--tests/views/tcannot_borrow.nim22
-rw-r--r--tests/views/tconst_views.nim37
-rw-r--r--tests/views/tdont_mutate.nim58
-rw-r--r--tests/views/tmust_borrow_from_first_parameter.nim9
-rw-r--r--tests/views/tsplit_into_openarray.nim37
-rw-r--r--tests/views/tsplit_into_seq.nim41
-rw-r--r--tests/views/tsplit_into_table.nim40
-rw-r--r--tests/views/tviews1.nim136
-rw-r--r--tests/views/tviews2.nim90
-rw-r--r--tests/vm/mevalffi.nim (renamed from tests/vm/tevalffi.nim)57
-rw-r--r--tests/vm/mscriptcompiletime.nim7
-rw-r--r--tests/vm/t11637.nim52
-rw-r--r--tests/vm/t17039.nim10
-rw-r--r--tests/vm/t17121.nim9
-rw-r--r--tests/vm/t18103.nim35
-rw-r--r--tests/vm/t19075.nim19
-rw-r--r--tests/vm/t19199.nim6
-rw-r--r--tests/vm/t20746.nim13
-rw-r--r--tests/vm/t21704.nim69
-rw-r--r--tests/vm/t9622.nim30
-rw-r--r--tests/vm/tableinstatic.nim2
-rw-r--r--tests/vm/tcastint.nim46
-rw-r--r--tests/vm/tclosureiterator.nim9
-rw-r--r--tests/vm/tcnstseq.nim (renamed from tests/cnstseq/tcnstseq.nim)0
-rw-r--r--tests/vm/tcompilesetting.nim18
-rw-r--r--tests/vm/tcompiletimetable.nim8
-rw-r--r--tests/vm/tconst.nim58
-rw-r--r--tests/vm/tconstarrayresem.nim29
-rw-r--r--tests/vm/tconsteval.nim31
-rw-r--r--tests/vm/tconstobj.nim23
-rw-r--r--tests/vm/tconstresem.nim10
-rw-r--r--tests/vm/tconstscope1.nim5
-rw-r--r--tests/vm/tconstscope2.nim5
-rw-r--r--tests/vm/tconsttable.nim15
-rw-r--r--tests/vm/tconvaddr.nim49
-rw-r--r--tests/vm/textensionmap.nim2
-rw-r--r--tests/vm/tfibconst.nim43
-rw-r--r--tests/vm/tfile_rw.nim5
-rw-r--r--tests/vm/tgenericcompiletimeproc.nim36
-rw-r--r--tests/vm/tgloballetfrommacro.nim2
-rw-r--r--tests/vm/tissues.nim52
-rw-r--r--tests/vm/tmisc_vm.nim216
-rw-r--r--tests/vm/tnewseqofcap.nim14
-rw-r--r--tests/vm/tnilclosurecall.nim8
-rw-r--r--tests/vm/tnilclosurecallstacktrace.nim23
-rw-r--r--tests/vm/tnocompiletimefunc.nim14
-rw-r--r--tests/vm/tnocompiletimefunclambda.nim6
-rw-r--r--tests/vm/tnoreturn.nim32
-rw-r--r--tests/vm/topenarrays.nim89
-rw-r--r--tests/vm/toverflowopcaddimmint.nim2
-rw-r--r--tests/vm/toverflowopcaddint.nim2
-rw-r--r--tests/vm/toverflowopcmulint.nim2
-rw-r--r--tests/vm/toverflowopcsubimmint.nim2
-rw-r--r--tests/vm/toverflowopcsubint.nim2
-rw-r--r--tests/vm/tquadplus.nim5
-rw-r--r--tests/vm/tref.nim11
-rw-r--r--tests/vm/treset.nim5
-rw-r--r--tests/vm/triangle_array.nim6
-rw-r--r--tests/vm/tscriptcompiletime.nims9
-rw-r--r--tests/vm/tsignaturehash.nim2
-rw-r--r--tests/vm/tslow_tables.nim4
-rw-r--r--tests/vm/tstring_openarray.nim25
-rw-r--r--tests/vm/tstringnil.nim2
-rw-r--r--tests/vm/tswap.nim12
-rw-r--r--tests/vm/ttouintconv.nim7
-rw-r--r--tests/vm/ttypedesc.nim31
-rw-r--r--tests/vm/tunsupportedintfloatcast.nim3
-rw-r--r--tests/vm/tvarsection.nim10
-rw-r--r--tests/vm/tvmmisc.nim666
-rw-r--r--tests/vm/tvmops.nim20
-rw-r--r--tests/vm/tvmopsDanger.nim13
-rw-r--r--tests/vm/twrong_concat.nim8
-rw-r--r--tests/vm/twrongarray.nim2
-rw-r--r--tests/vm/tyaytypedesc.nim8
-rw-r--r--tests/vm/tzero_extend.nim8
-rw-r--r--tests/whenstmt/t12517.nim21
-rw-r--r--tests/whenstmt/t19426.nim16
-rw-r--r--tests/whenstmt/twhen.nim47
-rw-r--r--tests/whenstmt/twhen_macro.nim18
-rw-r--r--tests/xml/ttree_add.nim51
-rw-r--r--tests/xml/ttree_add1.nim53
-rw-r--r--tests/xml/ttree_delete.nim47
-rw-r--r--tests/xml/ttree_delete1.nim48
-rw-r--r--tests/xml/ttree_insert.nim53
-rw-r--r--tests/xml/ttree_insert1.nim51
-rw-r--r--tests/xml/ttree_replace.nim46
-rw-r--r--tests/xml/ttree_replace1.nim53
2088 files changed, 72026 insertions, 35409 deletions
diff --git a/tests/alias/t19349.nim b/tests/alias/t19349.nim
new file mode 100644
index 000000000..1e1e58264
--- /dev/null
+++ b/tests/alias/t19349.nim
@@ -0,0 +1,19 @@
+discard """
+  action: "compile"
+"""
+
+type
+  Vec3[T: SomeNumber] = object
+    arr: array[3, T]
+
+var 
+  cfloatArr: array[3, array[3, cfloat]]
+  cfloatSeq = newSeq[Vec3[cfloat]]()
+for row in cfloatArr:
+  cfloatSeq.add(Vec3[float32](arr: [row[0], row[1], row[2]]))
+
+var 
+  cuintArr: array[3, array[3, cuint]]
+  cuintSeq = newSeq[Vec3[cuint]]()
+for row in cuintArr:
+  cuintSeq.add(Vec3[uint32](arr: [row[0], row[1], row[2]]))
diff --git a/tests/align/talign.nim b/tests/align/talign.nim
index e0503cc70..08373ee49 100644
--- a/tests/align/talign.nim
+++ b/tests/align/talign.nim
@@ -1,6 +1,6 @@
 discard """
 ccodeCheck: "\\i @'NIM_ALIGN(128) NI mylocal1' .*"
-target: "c cpp"
+targets: "c cpp"
 output: "align ok"
 """
 
@@ -51,3 +51,19 @@ type Bug[T] = object
 
 var bug: Bug[int]
 doAssert sizeof(bug) == 128, "Oops my size is " & $sizeof(bug) # 16
+
+
+block: # bug #22419
+  type
+    ValidatorPubKey = object
+      blob: array[96, byte]
+
+  proc f(): auto =
+    return iterator() =
+      var pad: int8 = 0
+      var y {.align: 16.}: ValidatorPubKey
+      let value = cast[uint64](addr y)
+      doAssert value mod 16 == 0
+
+  f()()
+
diff --git a/tests/alloc/tmembug.nim b/tests/alloc/tmembug.nim
new file mode 100644
index 000000000..63b51ec5d
--- /dev/null
+++ b/tests/alloc/tmembug.nim
@@ -0,0 +1,54 @@
+discard """
+  joinable: false
+"""
+
+import std / [atomics, strutils, sequtils]
+
+type
+  BackendMessage* = object
+    field*: seq[int]
+
+var
+  chan1: Channel[BackendMessage]
+  chan2: Channel[BackendMessage]
+
+chan1.open()
+chan2.open()
+
+proc routeMessage*(msg: BackendMessage) =
+  discard chan2.trySend(msg)
+
+var
+  recv: Thread[void]
+  stopToken: Atomic[bool]
+
+proc recvMsg() =
+  while not stopToken.load(moRelaxed):
+    let resp = chan1.tryRecv()
+    if resp.dataAvailable:
+      routeMessage(resp.msg)
+      echo "child consumes ", formatSize getOccupiedMem()
+
+createThread[void](recv, recvMsg)
+
+const MESSAGE_COUNT = 100
+
+proc main() =
+  let msg: BackendMessage = BackendMessage(field: (0..500).toSeq())
+  for j in 0..0: #100:
+    echo "New iteration"
+
+    for _ in 1..MESSAGE_COUNT:
+      chan1.send(msg)
+    echo "After sending"
+
+    var counter = 0
+    while counter < MESSAGE_COUNT:
+      let resp = recv(chan2)
+      counter.inc
+    echo "After receiving ", formatSize getOccupiedMem()
+
+  stopToken.store true, moRelaxed
+  joinThreads(recv)
+
+main()
diff --git a/tests/alloc/tmembug2.nim b/tests/alloc/tmembug2.nim
new file mode 100644
index 000000000..01bce6f14
--- /dev/null
+++ b/tests/alloc/tmembug2.nim
@@ -0,0 +1,58 @@
+discard """
+  disabled: "true"
+"""
+
+import std / [atomics, strutils, sequtils, isolation]
+
+import threading / channels
+
+type
+  BackendMessage* = object
+    field*: seq[int]
+
+const MESSAGE_COUNT = 100
+
+var
+  chan1 = newChan[BackendMessage](MESSAGE_COUNT*2)
+  chan2 = newChan[BackendMessage](MESSAGE_COUNT*2)
+
+#chan1.open()
+#chan2.open()
+
+proc routeMessage*(msg: BackendMessage) =
+  var m = isolate(msg)
+  discard chan2.trySend(m)
+
+var
+  thr: Thread[void]
+  stopToken: Atomic[bool]
+
+proc recvMsg() =
+  while not stopToken.load(moRelaxed):
+    var resp: BackendMessage
+    if chan1.tryRecv(resp):
+      #if resp.dataAvailable:
+      routeMessage(resp)
+      echo "child consumes ", formatSize getOccupiedMem()
+
+createThread[void](thr, recvMsg)
+
+proc main() =
+  let msg: BackendMessage = BackendMessage(field: (0..5).toSeq())
+  for j in 0..100:
+    echo "New iteration"
+
+    for _ in 1..MESSAGE_COUNT:
+      chan1.send(msg)
+    echo "After sending"
+
+    var counter = 0
+    while counter < MESSAGE_COUNT:
+      let resp = recv(chan2)
+      counter.inc
+    echo "After receiving ", formatSize getOccupiedMem()
+
+  stopToken.store true, moRelaxed
+  joinThreads(thr)
+
+main()
diff --git a/tests/arc/amodule.nim b/tests/arc/amodule.nim
new file mode 100644
index 000000000..2b4204a66
--- /dev/null
+++ b/tests/arc/amodule.nim
@@ -0,0 +1,21 @@
+# bug #14219
+var vectors = @["a", "b", "c", "d", "e"]
+
+iterator testVectors(): string =
+  for vector in vectors:
+    yield vector
+
+var r = ""
+for item in testVectors():
+  r.add item
+echo r
+
+# bug #12990
+iterator test(): int {.closure.} =
+  yield 0
+
+let x = test
+while true:
+  let val = x()
+  if finished(x): break
+  echo val
diff --git a/tests/arc/bmodule.nim b/tests/arc/bmodule.nim
new file mode 100644
index 000000000..70c2cc645
--- /dev/null
+++ b/tests/arc/bmodule.nim
@@ -0,0 +1,4 @@
+import cmodule
+
+for i in @[1, 2, 3].cycle():
+  echo i
diff --git a/tests/arc/cmodule.nim b/tests/arc/cmodule.nim
new file mode 100644
index 000000000..6c6e6c0fa
--- /dev/null
+++ b/tests/arc/cmodule.nim
@@ -0,0 +1,4 @@
+iterator cycle*[T](s: openArray[T]): T =
+  let s = @s
+  for x in s:
+    yield x
diff --git a/tests/arc/dmodule.nim b/tests/arc/dmodule.nim
new file mode 100644
index 000000000..455ec7084
--- /dev/null
+++ b/tests/arc/dmodule.nim
@@ -0,0 +1,23 @@
+type
+  MinKind* = enum
+    minDictionary
+    minBool
+  MinValue* = object
+    case kind*: MinKind
+    of minDictionary:
+      symbols: seq[MinOperator]
+    else: discard
+  MinOperator = object
+
+# remove this inline pragma to make it compile
+proc `$`*(a: MinValue): string {.inline.} =
+  case a.kind
+  of minDictionary:
+    result = "hello"
+    for i in a.symbols:
+      result = "hello"
+  else: discard
+
+proc parseMinValue*(): MinValue =
+  # or this echo
+  echo result
diff --git a/tests/arc/nim.cfg b/tests/arc/nim.cfg
new file mode 100644
index 000000000..7c148b797
--- /dev/null
+++ b/tests/arc/nim.cfg
@@ -0,0 +1 @@
+--sinkInference:on
diff --git a/tests/arc/t14383.nim b/tests/arc/t14383.nim
new file mode 100644
index 000000000..96b505166
--- /dev/null
+++ b/tests/arc/t14383.nim
@@ -0,0 +1,217 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+  output: '''
+hello
+hello
+@["a", "b"]
+---------------------
+plain:
+destroying: ('first', 42)
+destroying: ('second', 20)
+destroying: ('third', 12)
+
+Option[T]:
+destroying: ('first', 42)
+destroying: ('second', 20)
+destroying: ('third', 12)
+
+seq[T]:
+destroying: ('first', 42)
+destroying: ('second', 20)
+destroying: ('third', 12)
+
+1 1
+'''
+"""
+
+import dmodule
+
+var val = parseMinValue()
+if val.kind == minDictionary:
+  echo val
+
+#------------------------------------------------------------------------------
+# Issue #15238
+#------------------------------------------------------------------------------
+
+proc sinkArg(x: sink seq[string]) =
+  discard
+
+proc varArg(lst: var seq[string]) = 
+  sinkArg(lst)
+
+var x = @["a", "b"]
+varArg(x)
+echo x
+
+
+#------------------------------------------------------------------------------
+# Issue #15286
+#------------------------------------------------------------------------------
+
+import std/os
+discard getFileInfo(".")
+
+
+#------------------------------------------------------------------------------
+# Issue #15707
+#------------------------------------------------------------------------------
+
+type
+  JVMObject = ref object
+proc freeJVMObject(o: JVMObject) =
+  discard
+proc fromJObject(T: typedesc[JVMObject]): T =
+  result.new(cast[proc(r: T) {.nimcall.}](freeJVMObject))
+
+discard JVMObject.fromJObject()
+
+
+#------------------------------------------------------------------------------
+# Issue #15910
+#------------------------------------------------------------------------------
+
+import options
+
+type
+  Thing = object
+    name: string
+    age: int
+
+proc `=destroy`(thing: var Thing) =
+  if thing.name != "":
+    echo "destroying: ('", thing.name, "', ", thing.age, ")"
+  `=destroy`(thing.name)
+  `=destroy`(thing.age)
+
+proc plain() =
+  var t = Thing(name: "first", age: 42)
+  t = Thing(name: "second", age: 20)
+  t = Thing()
+  let u = Thing(name: "third", age: 12)
+
+proc optionT() =
+  var t = Thing(name: "first", age: 42).some
+  t = Thing(name: "second", age: 20).some
+  t = none(Thing)
+  let u = Thing(name: "third", age: 12).some
+
+proc seqT() =
+  var t = @[Thing(name: "first", age: 42)]
+  t = @[Thing(name: "second", age: 20)]
+  t = @[]
+  let u = @[Thing(name: "third", age: 12)]
+
+echo "---------------------"
+echo "plain:"
+plain()
+echo()
+
+echo "Option[T]:"
+optionT()
+echo()
+
+echo "seq[T]:"
+seqT()
+echo()
+
+
+#------------------------------------------------------------------------------
+# Issue #16120, const seq into sink
+#------------------------------------------------------------------------------
+
+proc main =
+  let avals = @[@[1.0'f32, 4.0, 7.0, 10.0]]
+  let rankdef = avals
+  echo avals.len, " ", rankdef.len
+
+main()
+
+
+#------------------------------------------------------------------------------
+# Issue #16722, ref on distinct type, wrong destructors called
+#------------------------------------------------------------------------------
+
+type
+  Obj = object of RootObj
+  ObjFinal = object
+  ObjRef = ref Obj
+  ObjFinalRef = ref ObjFinal
+  D = distinct Obj
+  DFinal = distinct ObjFinal
+  DRef = ref D
+  DFinalRef = ref DFinal
+
+proc `=destroy`(o: var Obj) =
+  doAssert false, "no Obj is constructed in this sample"
+
+proc `=destroy`(o: var ObjFinal) =
+  doAssert false, "no ObjFinal is constructed in this sample"
+
+var dDestroyed: int
+proc `=destroy`(d: var D) =
+  dDestroyed.inc
+
+proc `=destroy`(d: var DFinal) =
+  dDestroyed.inc
+
+func newD(): DRef =
+  DRef ObjRef()
+
+func newDFinal(): DFinalRef =
+  DFinalRef ObjFinalRef()
+
+proc testRefs() =
+  discard newD()
+  discard newDFinal()
+
+testRefs()
+
+doAssert(dDestroyed == 2)
+
+
+#------------------------------------------------------------------------------
+# Issue #16185, complex self-assingment elimination
+#------------------------------------------------------------------------------
+
+type
+  CpuStorage*[T] = ref CpuStorageObj[T]
+  CpuStorageObj[T] = object
+    size*: int
+    raw_buffer*: ptr UncheckedArray[T]
+  Tensor[T] = object
+    buf*: CpuStorage[T]
+  TestObject = object
+    x: Tensor[float]
+
+proc `=destroy`[T](s: var CpuStorageObj[T]) =
+  if s.raw_buffer != nil:
+    s.raw_buffer.deallocShared()
+    s.size = 0
+    s.raw_buffer = nil
+
+proc `=`[T](a: var CpuStorageObj[T]; b: CpuStorageObj[T]) {.error.}
+
+proc allocCpuStorage[T](s: var CpuStorage[T], size: int) =
+  new(s)
+  s.raw_buffer = cast[ptr UncheckedArray[T]](allocShared0(sizeof(T) * size))
+  s.size = size
+
+proc newTensor[T](size: int): Tensor[T] =
+  allocCpuStorage(result.buf, size)
+
+proc `[]`[T](t: Tensor[T], idx: int): T = t.buf.raw_buffer[idx]
+proc `[]=`[T](t: Tensor[T], idx: int, val: T) = t.buf.raw_buffer[idx] = val
+
+proc toTensor[T](s: seq[T]): Tensor[T] =
+  result = newTensor[T](s.len)
+  for i, x in s:
+    result[i] = x
+
+proc main2() =
+  var t: TestObject
+  t.x = toTensor(@[1.0, 2, 3, 4])
+  t.x = t.x  
+  doAssert(t.x.buf != nil) # self-assignment above should be eliminated
+
+main2()
diff --git a/tests/arc/t14472.nim b/tests/arc/t14472.nim
new file mode 100644
index 000000000..4ef661161
--- /dev/null
+++ b/tests/arc/t14472.nim
@@ -0,0 +1,43 @@
+discard """
+  valgrind: true
+  cmd: "nim cpp --gc:arc -d:useMalloc --deepcopy:on $file"
+"""
+
+type
+  ImportMaterial* = object
+    # Adding a field here makes the problem go away.
+
+  Mesh* = object
+    vertices: seq[float32]
+    material: ImportMaterial
+
+  ImportedScene* = object
+    meshes*: seq[Mesh]
+
+proc bork() : ImportedScene =
+  var mats: seq[ImportMaterial]
+
+  setLen(mats, 1)
+  add(result.meshes, Mesh(material: mats[0]))
+
+var s = bork()
+
+
+#------------------------------------------------------------------------
+# issue #15543
+
+import tables
+
+type
+  cdbl {.importc: "double".} = object
+
+  MyObject = ref object of RootObj
+    y: Table[string, cdbl]
+        
+
+proc test =
+  var x = new(MyObject)
+
+test()
+
+
diff --git a/tests/arc/t14864.nim b/tests/arc/t14864.nim
new file mode 100644
index 000000000..f59b14d2c
--- /dev/null
+++ b/tests/arc/t14864.nim
@@ -0,0 +1,5 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+"""
+
+import bmodule
diff --git a/tests/arc/t15909.nim b/tests/arc/t15909.nim
new file mode 100644
index 000000000..f25c89daf
--- /dev/null
+++ b/tests/arc/t15909.nim
@@ -0,0 +1,16 @@
+discard """
+  action: run
+  cmd: "nim c --gc:arc $file"
+"""
+
+proc f1() {.noreturn.} = raise newException(CatchableError, "")
+
+proc f2(y: int): int =
+  if y != 0:
+    y
+  else:
+    f1()
+
+doAssert f2(5) == 5
+doAssertRaises(CatchableError):
+  discard f2(0)
diff --git a/tests/arc/t16033.nim b/tests/arc/t16033.nim
new file mode 100644
index 000000000..59ed22e4d
--- /dev/null
+++ b/tests/arc/t16033.nim
@@ -0,0 +1,10 @@
+discard """
+  targets: "c js"
+  matrix: "--gc:arc"
+"""
+
+# bug #16033
+when defined js:
+  doAssert not compileOption("gc", "arc")
+else:
+  doAssert compileOption("gc", "arc")
diff --git a/tests/arc/t16458.nim b/tests/arc/t16458.nim
new file mode 100644
index 000000000..6ae114287
--- /dev/null
+++ b/tests/arc/t16458.nim
@@ -0,0 +1,6 @@
+discard """
+  matrix: "--gc:orc --d:useNimRtl"
+  action: "compile"
+"""
+
+echo 134
\ No newline at end of file
diff --git a/tests/arc/t16558.nim b/tests/arc/t16558.nim
new file mode 100644
index 000000000..0dbe02b33
--- /dev/null
+++ b/tests/arc/t16558.nim
@@ -0,0 +1,9 @@
+discard """
+  matrix: "--gc:arc"
+  errormsg: "expression cannot be cast to 'int'"
+"""
+
+block: # bug #16558
+  var value = "hi there"
+  var keepInt: int
+  keepInt = cast[int](value)
diff --git a/tests/arc/t17025.nim b/tests/arc/t17025.nim
new file mode 100644
index 000000000..a64c59ac1
--- /dev/null
+++ b/tests/arc/t17025.nim
@@ -0,0 +1,56 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+  output: '''
+{"Package": {"name": "hello"}, "Author": {"name": "name", "qq": "123456789", "email": "email"}}
+hello
+name
+123456789
+email
+hello
+name2
+987654321
+liame
+'''
+"""
+
+import parsecfg, streams, tables
+
+const cfg = """[Package]
+name=hello
+[Author]
+name=name
+qq=123456789
+email="email""""
+
+proc main() =
+    let stream = newStringStream(cfg)
+    let dict = loadConfig(stream)
+    var pname = dict.getSectionValue("Package","name")
+    var name = dict.getSectionValue("Author","name")
+    var qq = dict.getSectionValue("Author","qq")
+    var email = dict.getSectionValue("Author","email")
+    echo dict[]
+    echo pname & "\n" & name & "\n" & qq & "\n" & email
+    stream.close()
+
+main()
+
+proc getDict(): OrderedTableRef[string, OrderedTableRef[string, string]] =
+    result = newOrderedTable[string, OrderedTableRef[string, string]]()
+    result["Package"] = newOrderedTable[string, string]()
+    result["Package"]["name"] = "hello"
+    result["Author"] = newOrderedTable[string, string]()
+    result["Author"]["name"] = "name2"
+    result["Author"]["qq"] = "987654321"
+    result["Author"]["email"] = "liame"
+
+proc main2() =
+    let dict = getDict()
+    var pname = dict.getSectionValue("Package","name")
+    var name = dict.getSectionValue("Author","name")
+    var qq = dict.getSectionValue("Author","qq")
+    var email = dict.getSectionValue("Author","email")
+    echo pname & "\n" & name & "\n" & qq & "\n" & email
+
+main2()
+
diff --git a/tests/arc/t17173.nim b/tests/arc/t17173.nim
new file mode 100644
index 000000000..0acd886a2
--- /dev/null
+++ b/tests/arc/t17173.nim
@@ -0,0 +1,10 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+import std/strbasics
+
+
+var a = "  vhellov   "
+strip(a)
+doAssert a == "vhellov"
diff --git a/tests/arc/t17812.nim b/tests/arc/t17812.nim
new file mode 100644
index 000000000..dd8ac89b0
--- /dev/null
+++ b/tests/arc/t17812.nim
@@ -0,0 +1,41 @@
+discard """
+  targets: "c js"
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+import std/times
+
+block: # bug #17812
+  block:
+    type
+      Task = object
+        cb: proc ()
+
+    proc hello() = discard
+
+
+    let t = Task(cb: hello)
+
+    doAssert t.repr.len > 0
+
+
+  block:
+    type MyObj = object
+      field: DateTime
+
+
+    proc `$`(o: MyObj): string = o.repr
+
+    doAssert ($MyObj()).len > 0
+
+# bug #22175
+
+type Xxx = object
+  value: string
+
+proc complete(xxx: ref Xxx, v: sink string) =
+  xxx.value = move(v)
+
+let yyy = (ref Xxx)()
+
+yyy.complete("test")
diff --git a/tests/arc/t18645.nim b/tests/arc/t18645.nim
new file mode 100644
index 000000000..c5fddd4bb
--- /dev/null
+++ b/tests/arc/t18645.nim
@@ -0,0 +1,18 @@
+discard """
+  matrix: "--gc:arc; --gc:refc"
+  output: '''
+1
+2
+3
+'''
+"""
+
+proc bitTypeIdUnion() =
+  var bitId {.global.} = block:
+    0
+  inc bitId
+  echo bitId
+
+bitTypeIdUnion()
+bitTypeIdUnion()
+bitTypeIdUnion()
diff --git a/tests/arc/t18971.nim b/tests/arc/t18971.nim
new file mode 100644
index 000000000..9b587d956
--- /dev/null
+++ b/tests/arc/t18971.nim
@@ -0,0 +1,10 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+"""
+
+type MyObj = ref object
+
+var o = MyObj()
+proc x: var MyObj = o
+
+var o2 = x()
diff --git a/tests/arc/t18977.nim b/tests/arc/t18977.nim
new file mode 100644
index 000000000..c775551a4
--- /dev/null
+++ b/tests/arc/t18977.nim
@@ -0,0 +1,26 @@
+discard """
+  matrix: "--mm:arc"
+"""
+
+type
+  E = enum
+    a, b, c, d
+  X = object
+    v: int
+  O = object
+    case kind: E
+    of a:
+      a: int
+    of {b, c}:
+      b: float
+    else:
+      d: X
+
+proc `=destroy`(x: var X) =
+  echo "x destroyed"
+
+var o = O(kind: d, d: X(v: 12345))
+doAssert o.d.v == 12345
+
+doAssertRaises(FieldDefect):
+  o.kind = a
diff --git a/tests/arc/t19231.nim b/tests/arc/t19231.nim
new file mode 100644
index 000000000..40fcf277c
--- /dev/null
+++ b/tests/arc/t19231.nim
@@ -0,0 +1,18 @@
+discard """
+  matrix: "--mm:orc"
+  targets: "c cpp"
+"""
+
+type
+  Game* = ref object
+
+proc free*(game: Game) =
+  var mixNumOpened:cint = 0
+  for i in 0..<mixNumOpened:
+    mixNumOpened -= 1
+
+proc newGame*(): Game =
+  new result, free
+
+var
+  game*: Game
diff --git a/tests/arc/t19364.nim b/tests/arc/t19364.nim
new file mode 100644
index 000000000..f520f3291
--- /dev/null
+++ b/tests/arc/t19364.nim
@@ -0,0 +1,30 @@
+discard """
+  cmd: '''nim c --gc:arc --expandArc:fooLeaks $file'''
+  nimout: '''
+--expandArc: fooLeaks
+
+var
+  tmpTuple_cursor
+  a_cursor
+  b_cursor
+  c_cursor
+tmpTuple_cursor = refTuple
+a_cursor = tmpTuple_cursor[0]
+b_cursor = tmpTuple_cursor[1]
+c_cursor = tmpTuple_cursor[2]
+-- end of expandArc ------------------------
+'''
+"""
+
+func fooLeaks(refTuple: tuple[a,
+                              b,
+                              c: seq[float]]): float =
+  let (a, b, c) = refTuple
+
+let refset = (a: newSeq[float](25_000_000),
+              b: newSeq[float](25_000_000),
+              c: newSeq[float](25_000_000))
+
+var res = newSeq[float](1_000_000)
+for i in 0 .. res.high:
+  res[i] = fooLeaks(refset)
diff --git a/tests/arc/t19401.nim b/tests/arc/t19401.nim
new file mode 100644
index 000000000..56702a4a2
--- /dev/null
+++ b/tests/arc/t19401.nim
@@ -0,0 +1,32 @@
+discard """
+  output: '''
+delete foo
+delete foo
+delete foo
+'''
+  matrix: "--mm:arc"
+"""
+
+type Foo = ref object
+  data: int
+proc delete(self: Foo) 
+proc newFoo: Foo =
+  let x = 12
+  discard x
+  new(result, delete)
+  result.data = x
+proc delete(self: Foo) =
+  doAssert self.data == 12
+  echo("delete foo")
+
+if isMainModule:
+  proc test() =
+    let x1 = newFoo()
+    let x2 = newFoo()
+    discard x1
+    discard x2
+    var x3: Foo
+    new(x3, delete)
+    x3.data = 12
+    discard x3
+  test()
diff --git a/tests/arc/t19402.nim b/tests/arc/t19402.nim
new file mode 100644
index 000000000..5ee6fc798
--- /dev/null
+++ b/tests/arc/t19402.nim
@@ -0,0 +1,32 @@
+discard """
+  output: '''
+delete foo
+delete foo
+delete foo
+'''
+  matrix: "--mm:arc"
+"""
+
+type Foo = ref object of RootObj
+  data: int
+proc delete(self: Foo)
+proc newFoo: Foo =
+  let x = 12
+  discard x
+  new(result, delete)
+  result.data = x
+proc delete(self: Foo) =
+  doAssert self.data == 12
+  echo("delete foo")
+
+if isMainModule:
+  proc test() =
+    let x1 = newFoo()
+    let x2 = newFoo()
+    discard x1
+    discard x2
+    var x3: Foo
+    new(x3, delete)
+    x3.data = 12
+    discard x3
+  test()
\ No newline at end of file
diff --git a/tests/arc/t19435.nim b/tests/arc/t19435.nim
new file mode 100644
index 000000000..519216bad
--- /dev/null
+++ b/tests/arc/t19435.nim
@@ -0,0 +1,29 @@
+discard """
+  matrix: "--gc:arc"
+"""
+
+# bug #19435
+{.experimental: "views".}
+
+type
+  Bar = object
+    placeholder: int
+  Foo = object
+    placeholder: int
+    c: seq[Bar] # remove this line to make things right
+
+func children*(s: var seq[Foo]): openArray[Foo] =
+  s.toOpenArray(0, s.len-1)
+
+proc test =
+  var foos = @[Foo(), Foo()]
+
+  assert foos.children.len == 2
+  var flag = true
+  for a in foos.children:
+    flag = false
+
+  if flag:
+    doAssert false
+
+test()
\ No newline at end of file
diff --git a/tests/arc/t19457.nim b/tests/arc/t19457.nim
new file mode 100644
index 000000000..78447ce82
--- /dev/null
+++ b/tests/arc/t19457.nim
@@ -0,0 +1,16 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+# bug #19457
+proc gcd(x, y: seq[int]): seq[int] =
+    var
+      a = x
+      b = y
+    while b[0] > 0:
+      let c = @[a[0] mod b[0]]
+      a = b
+      b = c
+    return a
+
+doAssert gcd(@[1], @[2]) == @[1]
\ No newline at end of file
diff --git a/tests/arc/t19862.nim b/tests/arc/t19862.nim
new file mode 100644
index 000000000..6d3f57692
--- /dev/null
+++ b/tests/arc/t19862.nim
@@ -0,0 +1,15 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+import std/widestrs
+
+# bug #19862
+type NewString = object
+
+proc len(s: NewString): int = 10
+
+converter toNewString(x: WideCStringObj): NewString = discard
+
+let w = newWideCString("test")
+doAssert len(w) == 4
diff --git a/tests/arc/t20456.nim b/tests/arc/t20456.nim
new file mode 100644
index 000000000..ace79255a
--- /dev/null
+++ b/tests/arc/t20456.nim
@@ -0,0 +1,7 @@
+discard """
+  cmd: "nim check $file"
+  action: "compile"
+"""
+
+when not defined(gcOrc):
+  {.error: "orc".}
diff --git a/tests/arc/t20588.nim b/tests/arc/t20588.nim
new file mode 100644
index 000000000..008bd1dcd
--- /dev/null
+++ b/tests/arc/t20588.nim
@@ -0,0 +1,25 @@
+discard """
+  cmd: "nim check --warnings:off --hints:off $file"
+  errormsg: ""
+  nimout: '''
+t20588.nim(20, 12) Error: illegal type conversion to 'auto'
+t20588.nim(21, 14) Error: illegal type conversion to 'typed'
+t20588.nim(22, 16) Error: illegal type conversion to 'untyped'
+t20588.nim(24, 7) Error: illegal type conversion to 'any'
+'''
+"""
+
+
+
+
+
+
+
+
+
+discard 0.0.auto
+discard typed("abc")
+discard untyped(4)
+var a = newSeq[bool](1000)
+if any(a):
+  echo "ok?"
\ No newline at end of file
diff --git a/tests/arc/t21184.nim b/tests/arc/t21184.nim
new file mode 100644
index 000000000..91d0c42c7
--- /dev/null
+++ b/tests/arc/t21184.nim
@@ -0,0 +1,77 @@
+discard """
+  matrix: "--mm:orc"
+"""
+
+import std/[with]
+
+type
+  Node* {.acyclic.} = ref object of RootObj
+    name: string
+    data: pointer
+    children: seq[Node]
+  TextNode = ref object of Node
+    text: string
+
+proc fakeEcho(s: string) =
+  if s.len < 0:
+    echo s
+
+proc newNode[T: Node](parent: Node): T =
+  new result
+  result.data = alloc0(250)
+  parent.children.add(result)
+
+proc newRootNode(): Node =
+  new result
+  result.data = alloc0(250)
+
+method printNode(node: Node) {.base.} =
+  fakeEcho node.name
+
+method printNode(node: TextNode) =
+  procCall printNode(Node(node))
+  fakeEcho node.text
+
+proc printChildren(node: Node) =
+  for child in node.children:
+    child.printNode()
+    printChildren(child)
+
+proc free(node: Node) =
+  for child in node.children:
+    free(child)
+  dealloc(node.data)
+
+template node(parent: Node, body: untyped): untyped =
+  var node = newNode[Node](parent)
+  with node:
+    body
+
+proc textNode(parent: Node, text: string) =
+  var node = newNode[TextNode](parent)
+  node.text = text
+
+template withRootNode(body: untyped): untyped =
+  var root = newRootNode()
+  root.name = "root"
+  with root:
+    body
+  root.printNode()
+  printChildren(root)
+  root.free()
+
+proc doTest() =
+  withRootNode:
+    node:
+      name = "child1"
+      node:
+        name = "child2"
+        node:
+          name = "child3"
+          textNode "Hello, world!"
+
+
+# bug #21171
+if isMainModule:
+  for i in 0..100000:
+    doTest()
diff --git a/tests/arc/t22218.nim b/tests/arc/t22218.nim
new file mode 100644
index 000000000..7837ed1d0
--- /dev/null
+++ b/tests/arc/t22218.nim
@@ -0,0 +1,25 @@
+discard """
+  cmd: "nim c --mm:arc $file"
+  errormsg: "'=copy' is not available for type <Obj>; requires a copy because it's not the last read of 'chan[]'; routine: test"
+"""
+
+# bug #22218
+type Obj[T] = object
+  v: T
+
+proc `=copy`[T](
+    dest: var Obj[T],
+    source: Obj[T]
+  ) {.error: "A channel cannot be copied".}
+
+from system/ansi_c import c_calloc
+
+proc test() =
+    var v: bool = true
+    var chan = cast[ptr Obj[int]](c_calloc(1, csize_t sizeof(Obj[int])))
+    var copy = chan[]
+
+    echo chan.v
+    echo v
+
+test()
\ No newline at end of file
diff --git a/tests/arc/t22237.nim b/tests/arc/t22237.nim
new file mode 100644
index 000000000..c6dbf768a
--- /dev/null
+++ b/tests/arc/t22237.nim
@@ -0,0 +1,55 @@
+discard """
+  matrix: "--mm:arc; --mm:orc"
+"""
+
+import std/macros
+import std/streams
+
+# bug #22237
+
+proc iterlines_closure2(f: File | Stream): iterator (): string =
+  result = iterator(): string =
+    for line in f.lines:
+      if line.len == 0:
+        break
+      yield line
+
+proc test() =
+  let f = newStringStream("""
+    1
+    2
+
+    3
+    4
+
+    5
+    6
+    7
+
+    8
+""")
+  while not f.atEnd():
+    let iterator_inst = iterlines_closure2(f)
+    for item in iterator_inst(): # Fails with "SIGSEGV: Illegal storage access. (Attempt to read from nil?)"
+      discard
+
+test()
+
+# bug #21160
+import sequtils
+
+iterator allMoves(fls: seq[int]): seq[int] =
+  yield fls
+
+proc neighbors(flrs: seq[int]): iterator: seq[int] =
+  return iterator(): seq[int] =
+    for flrs2 in allMoves(flrs):
+      yield flrs2
+      for flrs3 in allMoves(flrs2):
+        yield flrs3
+
+let f = @[1]
+for _ in neighbors(f):
+  discard
+for _ in neighbors(f):
+  discard
diff --git a/tests/arc/t22478.nim b/tests/arc/t22478.nim
new file mode 100644
index 000000000..5373fa161
--- /dev/null
+++ b/tests/arc/t22478.nim
@@ -0,0 +1,46 @@
+discard """
+  matrix: "-d:nimNoLentIterators --mm:arc"
+  output: '''PUSH DATA: {"test.message":{"test":{"nested":"v1"}}}'''
+  joinable: false
+"""
+
+# bug #22748
+import std/[json, typetraits, times]
+
+# publish
+
+proc publish*[T](payload: T) =
+  discard
+
+type MetricsPoint* = JsonNode
+
+proc push*(stat: string, data: JsonNode, usec: int64 = 0) =
+  let payload = newJObject()
+
+  # this results in a infinite recursion unless we deepCopy()
+  payload[stat] = data #.deepCopy
+
+  echo "PUSH DATA: ", payload
+
+  publish[MetricsPoint](payload)
+
+var scopes {.threadvar.}: seq[JsonNode]
+
+type WithTimeCallback*[T] = proc(data: var JsonNode): T
+
+proc pushScoped*[T](metric: string, blk: WithTimeCallback[T]): T {.gcsafe.} =
+  scopes.add newJObject()
+  defer: discard scopes.pop()
+
+  let stc = (cpuTime() * 1000_000).int64
+  result = blk(scopes[^1])
+  let dfc = (cpuTime() * 1000_000).int64 - stc
+
+  push(metric, scopes[^1], dfc)
+
+# demo code
+
+discard pushScoped[int]("test.message") do (data: var JsonNode) -> int:
+  data["test"] = %*{
+    "nested": "v1"
+  }
\ No newline at end of file
diff --git a/tests/arc/t22787.nim b/tests/arc/t22787.nim
new file mode 100644
index 000000000..5840a984b
--- /dev/null
+++ b/tests/arc/t22787.nim
@@ -0,0 +1,37 @@
+discard """
+  joinable: false
+"""
+
+import std/assertions
+
+proc foo =
+  var s:seq[string]
+  var res = ""
+
+  for i in 0..3:
+    s.add ("test" & $i)
+    s.add ("test" & $i)
+
+  var lastname:string
+
+  for i in s:
+    var name = i[0..4]
+
+    if name != lastname:
+      res.add "NEW:" & name & "\n"
+    else:
+      res.add name & ">" & lastname & "\n"
+
+    lastname = name
+
+  doAssert res == """
+NEW:test0
+test0>test0
+NEW:test1
+test1>test1
+NEW:test2
+test2>test2
+NEW:test3
+test3>test3
+"""
+foo()
\ No newline at end of file
diff --git a/tests/arc/t23247.nim b/tests/arc/t23247.nim
new file mode 100644
index 000000000..0fadc50cd
--- /dev/null
+++ b/tests/arc/t23247.nim
@@ -0,0 +1,52 @@
+discard """
+  matrix: ";-d:useMalloc"
+"""
+
+# bug #23247
+import std/hashes
+
+func baseAddr[T](x: openArray[T]): ptr T =
+  # Return the address of the zero:th element of x or `nil` if x is empty
+  if x.len == 0: nil else: cast[ptr T](x)
+
+func makeUncheckedArray[T](p: ptr T): ptr UncheckedArray[T] =
+  cast[ptr UncheckedArray[T]](p)
+
+type
+  LabelKey = object
+    data: seq[string]
+    refs: ptr UncheckedArray[string]
+    refslen: int
+
+  Gauge = ref object
+    metrics: seq[seq[seq[string]]]
+
+template values(key: LabelKey): openArray[string] =
+  if key.refslen > 0:
+    key.refs.toOpenArray(0, key.refslen - 1)
+  else:
+    key.data
+
+proc hash(key: LabelKey): Hash =
+  hash(key.values)
+
+proc view(T: type LabelKey, values: openArray[string]): T =
+  # TODO some day, we might get view types - until then..
+  LabelKey(refs: baseAddr(values).makeUncheckedArray(), refslen: values.len())
+
+template withValue2(k: untyped) =
+  discard hash(k)
+
+proc setGauge(
+    collector: Gauge,
+    labelValues: openArray[string],
+) =
+  let v = LabelKey.view(labelValues)
+  withValue2(v)
+  collector.metrics.add @[@labelValues, @labelValues]
+  discard @labelValues
+
+var nim_gc_mem_bytes = Gauge()
+let threadID = $getThreadId()
+setGauge(nim_gc_mem_bytes, @[threadID])
+setGauge(nim_gc_mem_bytes, @[threadID])
\ No newline at end of file
diff --git a/tests/arc/t9650.nim b/tests/arc/t9650.nim
new file mode 100644
index 000000000..a8182db68
--- /dev/null
+++ b/tests/arc/t9650.nim
@@ -0,0 +1,87 @@
+discard """
+  matrix: "--gc:arc"
+"""
+
+import typetraits
+
+# bug #9650
+type
+  SharedPtr*[T] = object
+    val: ptr tuple[atomicCounter: int, value: T]
+
+  Node*[T] = object
+    value: T
+    next: SharedPtr[Node[T]]
+
+  ForwardList*[T] = object
+    first: SharedPtr[Node[T]]
+
+proc `=destroy`*[T](p: var SharedPtr[T]) =
+  if p.val != nil:
+    let c = atomicDec(p.val[].atomicCounter)
+    if c == 0:
+      when not supportsCopyMem(T):
+         `=destroy`(p.val[])
+      dealloc(p.val)
+    p.val = nil
+
+proc `=`*[T](dest: var SharedPtr[T], src: SharedPtr[T]) =
+  if dest.val != src.val:
+    if dest.val != nil:
+      `=destroy`(dest)
+    if src.val != nil:
+      discard atomicInc(src.val[].atomicCounter)
+      dest.val = src.val
+
+proc `=sink`*[T](dest: var SharedPtr[T], src: SharedPtr[T]) =
+  if dest.val != nil and dest.val != src.val:
+    `=destroy`(dest)
+  dest.val = src.val
+
+ 
+proc newSharedPtr*[T](val: sink T): SharedPtr[T] =
+  result.val = cast[type(result.val)](alloc(sizeof(result.val[])))
+  reset(result.val[])
+  result.val.atomicCounter = 1
+  result.val.value = val
+
+proc isNil*[T](p: SharedPtr[T]): bool =
+  p.val == nil
+
+template `->`*[T](p: SharedPtr[T], name: untyped): untyped =
+  p.val.value.name
+
+proc createNode[T](val: T): SharedPtr[ Node[T] ]=
+  result = newSharedPtr(Node[T](value: val))
+
+proc push_front*[T](list: var ForwardList[T], val: T) =
+  var newElem = createNode(val)
+  newElem->next = list.first
+  list.first = newElem
+
+proc pop_front*[T](list: var ForwardList[T]) =
+  let head = list.first
+  list.first = head->next
+
+proc toString*[T](list: ForwardList[T]): string =
+  result = "["
+  var head = list.first
+  while not head.isNil:
+    result &= $(head->value) & ", "
+    head = head->next
+  result &= ']'
+
+block:
+  var x: ForwardList[int]
+  x.push_front(1)
+  x.push_front(2)
+  x.push_front(3)
+
+  doAssert toString(x) == "[3, 2, 1, ]"
+
+  x.pop_front()
+  x.pop_front()
+  doAssert toString(x) == "[1, ]"
+
+  x.pop_front()
+  doAssert toString(x) == "[]"
diff --git a/tests/arc/taliased_reassign.nim b/tests/arc/taliased_reassign.nim
new file mode 100644
index 000000000..5563fae8c
--- /dev/null
+++ b/tests/arc/taliased_reassign.nim
@@ -0,0 +1,41 @@
+discard """
+  matrix: "--mm:orc"
+"""
+
+# bug #20993
+
+type
+  Dual[int] = object # must be generic (even if fully specified)
+    p: int
+proc D(p: int): Dual[int] = Dual[int](p: p)
+proc `+`(x: Dual[int], y: Dual[int]): Dual[int] = D(x.p + y.p)
+
+type
+  Tensor[T] = object
+    buf: seq[T]
+proc newTensor*[T](s: int): Tensor[T] = Tensor[T](buf: newSeq[T](s))
+proc `[]`*[T](t: Tensor[T], idx: int): T = t.buf[idx]
+proc `[]=`*[T](t: var Tensor[T], idx: int, val: T) = t.buf[idx] = val
+
+proc `+.`[T](t1, t2: Tensor[T]): Tensor[T] =
+  let n = t1.buf.len
+  result = newTensor[T](n)
+  for i in 0 ..< n:
+    result[i] = t1[i] + t2[i]
+
+proc toTensor*[T](a: sink seq[T]): Tensor[T] =
+  ## This breaks it: Using `T` instead makes it work
+  type U = typeof(a[0])
+  var t: Tensor[U] # Tensor[T] works
+  t.buf = a
+  result = t
+
+proc loss() =
+  var B = toTensor(@[D(123)])
+  let a = toTensor(@[D(-10)])
+  B = B +. a
+  doAssert B[0].p == 113, "I want to be 113, but I am " & $B[0].p
+
+loss()
+
+
diff --git a/tests/arc/tamemfiles.nim b/tests/arc/tamemfiles.nim
new file mode 100644
index 000000000..97deb489f
--- /dev/null
+++ b/tests/arc/tamemfiles.nim
@@ -0,0 +1,110 @@
+discard """
+  output: '''
+loop 1a
+loop 1b; cols: @[1, x]
+loop 1c
+loop 1d
+loop 1a
+loop 1b; cols: @[2, y]
+loop 1c
+loop 1d
+'''
+  cmd: "nim c --gc:arc $file"
+"""
+
+# bug #13596
+
+import tables, memfiles, strutils, os
+
+type Splitr* = tuple[ repeat: bool, chrDlm: char, setDlm: set[char], n: int ]
+
+type csize = uint
+proc cmemchr*(s: pointer, c: char, n: csize): pointer {.
+  importc: "memchr", header: "<string.h>" .}
+proc `-!`*(p, q: pointer): int {.inline.} =
+  (cast[int](p) -% cast[int](q)).int
+proc `+!`*(p: pointer, i: int): pointer {.inline.} =
+  cast[pointer](cast[int](p) +% i)
+proc `+!`*(p: pointer, i: uint64): pointer {.inline.} =
+  cast[pointer](cast[uint64](p) + i)
+
+proc charEq(x, c: char): bool {.inline.} = x == c
+
+proc initSplitr*(delim: string): Splitr =
+  if delim == "white":          #User can use any other permutation if needed
+    result.repeat = true
+    result.chrDlm = ' '
+    result.setDlm = { ' ', '\t', '\n' }
+    result.n      = result.setDlm.card
+    return
+  for c in delim:
+    if c in result.setDlm:
+      result.repeat = true
+      continue
+    result.setDlm.incl(c)
+    inc(result.n)
+  if result.n == 1:             #support n==1 test to allow memchr optimization
+    result.chrDlm = delim[0]
+
+proc hash(x: MemSlice): int = 55542
+
+template defSplit[T](slc: T, fs: var seq[MemSlice], n: int, repeat: bool,
+                     sep: untyped, nextSep: untyped, isSep: untyped) {.dirty.} =
+  fs.setLen(if n < 1: 16 else: n)
+  var b   = slc.data
+  var eob = b +! slc.size
+  while repeat and eob -! b > 0 and isSep((cast[cstring](b))[0], sep):
+    b = b +! 1
+    if b == eob: fs.setLen(0); return
+  var e = nextSep(b, sep, (eob -! b).csize)
+  while e != nil:
+    if n < 1:                               #Unbounded msplit
+      if result == fs.len - 1:              #Expand capacity
+        fs.setLen(if fs.len < 512: 2*fs.len else: fs.len + 512)
+    elif result == n - 1:                   #Need 1 more slot for final field
+      break
+    fs[result].data = b
+    fs[result].size = e -! b
+    result += 1
+    while repeat and eob -! e > 0 and isSep((cast[cstring](e))[1], sep):
+      e = e +! 1
+    b = e +! 1
+    if eob -! b <= 0:
+      b = eob
+      break
+    e = nextSep(b, sep, (eob -! b).csize)
+  if not repeat or eob -! b > 0:
+    fs[result].data = b
+    fs[result].size = eob -! b
+    result += 1
+  fs.setLen(result)
+
+proc msplit*(s: MemSlice, fs: var seq[MemSlice], sep=' ', n=0,
+             repeat=false): int =
+  defSplit(s, fs, n, repeat, sep, cmemchr, charEq)
+
+proc split*(s: Splitr, line: MemSlice, cols: var seq[MemSlice],
+            n=0) {.inline.} =
+  discard msplit(line, cols, s.chrDlm, n, s.repeat)
+
+########################################################################
+# Using lines instead of memSlices & split instead of splitr.split seems
+# to mask the arc problem, as does simplifying `Table` to `seq[char]`.
+
+proc load(path: string, delim=" "): Table[MemSlice, seq[char]] =
+  let f = memfiles.open(path)
+  let splitr = initSplitr(delim)
+  var cols: seq[MemSlice] = @[ ]    # re-used seq buffer
+  var nwSq = newSeqOfCap[char](1)   # re-used seq value
+  nwSq.setLen 1
+  for line in memSlices(f, eat='\0'):
+    stderr.write "loop 1a\n"
+    splitr.split(line, cols, 2)
+    stderr.write "loop 1b; cols: ", cols, "\n"
+    let cs = cast[cstring](cols[0].data)
+    stderr.write "loop 1c\n"        #..reports exception here, but
+    nwSq[0] = cs[0]                 #..actually doing out of bounds here
+    stderr.write "loop 1d\n"
+    result[cols[1]] = nwSq
+
+discard load(getAppDir() / "testfile.txt")
diff --git a/tests/arc/tamodule.nim b/tests/arc/tamodule.nim
new file mode 100644
index 000000000..1412e0a7c
--- /dev/null
+++ b/tests/arc/tamodule.nim
@@ -0,0 +1,9 @@
+discard """
+  output: '''
+abcde
+0
+'''
+  cmd: "nim c --gc:arc $file"
+"""
+
+import amodule
diff --git a/tests/arc/tarc_macro.nim b/tests/arc/tarc_macro.nim
new file mode 100644
index 000000000..33ade1da4
--- /dev/null
+++ b/tests/arc/tarc_macro.nim
@@ -0,0 +1,57 @@
+import macros
+
+var destroyCalled = false
+macro bar() =
+  let s = newTree(nnkAccQuoted, ident"=destroy")
+  # let s = ident"`=destroy`" # this would not work
+  result = quote do:
+    type Foo = object
+    # proc `=destroy`(a: var Foo) = destroyCalled = true # this would not work
+    proc `s`(a: var Foo) = destroyCalled = true
+    block:
+      let a = Foo()
+bar()
+doAssert destroyCalled
+
+# custom `op`
+var destroyCalled2 = false
+macro bar(ident) =
+  var x = 1.5
+  result = quote("@") do:
+    type Foo = object
+    let `@ident` = 0 # custom op interpolated symbols need quoted (``)
+    proc `=destroy`(a: var Foo) =
+      doAssert @x == 1.5
+      doAssert compiles(@x == 1.5)
+      let b1 = @[1,2]
+      let b2 = @@[1,2]
+      doAssert $b1 == "[1, 2]"
+      doAssert $b2 == "@[1, 2]"
+      destroyCalled2 = true
+    block:
+      let a = Foo()
+bar(someident)
+doAssert destroyCalled2
+
+proc `&%`(x: int): int = 1
+proc `&%`(x, y: int): int = 2
+
+macro bar2() =
+  var x = 3
+  result = quote("&%") do:
+    var y = &%x # quoting operator
+    doAssert &%&%y == 1 # unary operator => need to escape
+    doAssert y &% y == 2 # binary operator => no need to escape
+    doAssert y == 3
+bar2()
+
+block:
+  macro foo(a: openArray[string] = []): string =
+    echo a # Segfault doesn't happen if this is removed
+    newLit ""
+
+  proc bar(a: static[openArray[string]] = []) =
+    const tmp = foo(a)
+
+  # bug #22909
+  doAssert not compiles(bar())
diff --git a/tests/arc/tarc_orc.nim b/tests/arc/tarc_orc.nim
new file mode 100644
index 000000000..f2c7de2fc
--- /dev/null
+++ b/tests/arc/tarc_orc.nim
@@ -0,0 +1,186 @@
+discard """
+  targets: "c cpp"
+  matrix: "--mm:arc; --mm:orc"
+"""
+
+block:
+  type
+    PublicKey = array[32, uint8]
+    PrivateKey = array[64, uint8]
+
+  proc ed25519_create_keypair(publicKey: ptr PublicKey; privateKey: ptr PrivateKey) =
+    publicKey[][0] = uint8(88)
+
+  type
+    KeyPair = object
+      public: PublicKey
+      private: PrivateKey
+
+  proc initKeyPair(): KeyPair =
+    ed25519_create_keypair(result.public.addr, result.private.addr)
+
+  let keys = initKeyPair()
+  doAssert keys.public[0] == 88
+
+
+template minIndexByIt: untyped =
+  var other = 3
+  other
+
+proc bug20303() =
+  var hlibs = @["hello", "world", "how", "are", "you"]
+  let res = hlibs[minIndexByIt()]
+  doAssert res == "are"
+
+bug20303()
+
+proc main() = # todo bug with templates
+  block: # bug #11267
+    var a: seq[char] = block: @[]
+    doAssert a == @[]
+    # 2
+    proc b: seq[string] =
+      discard
+      @[]
+    doAssert b() == @[]
+static: main()
+main()
+
+
+type Obj = tuple
+  value: int
+  arr: seq[int]
+
+proc bug(): seq[Obj] =
+  result.add (value: 0, arr: @[])
+  result[^1].value = 1
+  result[^1].arr.add 1
+
+# bug #19990
+let s = bug()
+doAssert s[0] == (value: 1, arr: @[1])
+
+block: # bug #21974
+  type Test[T] = ref object
+      values : seq[T]
+      counter: int
+
+  proc newTest[T](): Test[T] =
+      result         = new(Test[T])
+      result.values  = newSeq[T](16)
+      result.counter = 0
+
+  proc push[T](self: Test[T], value: T) =
+      self.counter += 1
+      if self.counter >= self.values.len:
+          self.values.setLen(self.values.len * 2)
+      self.values[self.counter - 1] = value
+
+  proc pop[T](self: Test[T]): T =
+      result         = self.values[0]
+      self.values[0] = self.values[self.counter - 1] # <--- This line
+      self.counter  -= 1
+
+
+  type X = tuple
+      priority: int
+      value   : string
+
+  var a = newTest[X]()
+  a.push((1, "One"))
+  doAssert a.pop.value == "One"
+
+# bug #21987
+
+type
+  EmbeddedImage* = distinct Image
+  Image = object
+    len: int
+
+proc imageCopy*(image: Image): Image {.nodestroy.}
+
+proc `=destroy`*(x: var Image) =
+  discard
+proc `=sink`*(dest: var Image; source: Image) =
+  `=destroy`(dest)
+  wasMoved(dest)
+
+proc `=dup`*(source: Image): Image {.nodestroy.} =
+  result = imageCopy(source)
+
+proc `=copy`*(dest: var Image; source: Image) =
+  dest = imageCopy(source) # calls =sink implicitly
+
+proc `=destroy`*(x: var EmbeddedImage) = discard
+
+proc `=dup`*(source: EmbeddedImage): EmbeddedImage {.nodestroy.} = source
+
+proc `=copy`*(dest: var EmbeddedImage; source: EmbeddedImage) {.nodestroy.} =
+  dest = source
+
+proc imageCopy*(image: Image): Image =
+  result = image
+
+proc main2 =
+  block:
+    var a = Image(len: 2).EmbeddedImage
+    var b = Image(len: 1).EmbeddedImage
+    b = a
+    doAssert Image(a).len == 2
+    doAssert Image(b).len == 2
+
+  block:
+    var a = Image(len: 2)
+    var b = Image(len: 1)
+    b = a
+    doAssert a.len == 2
+    doAssert b.len == 0
+
+main2()
+
+block:
+  type
+    TestObj = object of RootObj
+      name: string
+    
+    TestSubObj = object of TestObj
+      objname: string
+
+  proc `=destroy`(x: TestObj) =
+    `=destroy`(x.name)
+
+  proc `=destroy`(x: TestSubObj) =
+    `=destroy`(x.objname)
+    `=destroy`(TestObj(x))
+
+  proc testCase() =
+    let t1 {.used.} = TestSubObj(objname: "tso1", name: "to1")
+
+  proc main() =
+    testCase()
+
+  main()
+
+block: # bug #23858
+  type Object = object
+    a: int
+    b: ref int
+  var x = 0
+  proc fn(): auto {.cdecl.} =
+    inc x
+    return Object()
+  discard fn()
+  doAssert x == 1
+
+block: # bug #24147
+  type
+    O = object of RootObj
+      val: string
+    OO = object of O
+
+  proc `=copy`(dest: var O, src: O) =
+      dest.val = src.val
+
+  let oo = OO(val: "hello world")
+  var ooCopy : OO
+  `=copy`(ooCopy, oo)
diff --git a/tests/arc/tarcmisc.nim b/tests/arc/tarcmisc.nim
new file mode 100644
index 000000000..b4476ef4f
--- /dev/null
+++ b/tests/arc/tarcmisc.nim
@@ -0,0 +1,836 @@
+discard """
+  output: '''
+Destructor for TestTestObj
+=destroy called
+123xyzabc
+destroyed: false
+destroyed: false
+destroyed2: false
+destroyed2: false
+destroying variable: 2
+destroying variable: 1
+whiley ends :(
+1
+(x: "0")
+(x: "1")
+(x: "2")
+(x: "3")
+(x: "4")
+(x: "5")
+(x: "6")
+(x: "7")
+(x: "8")
+(x: "9")
+(x: "10")
+0
+new line before - @['a']
+new line after - @['a']
+finalizer
+aaaaa
+hello
+true
+copying
+123
+42
+@["", "d", ""]
+ok
+destroying variable: 20
+destroying variable: 10
+closed
+'''
+  cmd: "nim c --mm:arc --deepcopy:on -d:nimAllocPagesViaMalloc $file"
+"""
+
+block: # bug #23627
+  type
+    TestObj = object of RootObj
+
+    Test2 = object of RootObj
+      foo: TestObj
+
+    TestTestObj = object of RootObj
+      shit: TestObj
+
+  proc `=destroy`(x: TestTestObj) =
+    echo "Destructor for TestTestObj"
+    let test = Test2(foo: TestObj())
+
+  proc testCaseT() =
+    let tt1 {.used.} = TestTestObj(shit: TestObj())
+
+
+  proc main() =
+    testCaseT()
+
+  main()
+
+
+# bug #9401
+
+type
+  MyObj = object
+    len: int
+    data: ptr UncheckedArray[float]
+
+proc `=destroy`*(m: MyObj) =
+
+  echo "=destroy called"
+
+  if m.data != nil:
+    deallocShared(m.data)
+
+type
+  MyObjDistinct = distinct MyObj
+
+proc `=copy`*(m: var MyObj, m2: MyObj) =
+  if m.data == m2.data: return
+  if m.data != nil:
+    `=destroy`(m)
+  m.len = m2.len
+  if m.len > 0:
+    m.data = cast[ptr UncheckedArray[float]](allocShared(sizeof(float) * m.len))
+    copyMem(m.data, m2.data, sizeof(float) * m.len)
+
+
+proc `=sink`*(m: var MyObj, m2: MyObj) =
+  if m.data != m2.data:
+    if m.data != nil:
+      `=destroy`(m)
+    m.len = m2.len
+    m.data = m2.data
+
+proc newMyObj(len: int): MyObj =
+  result.len = len
+  result.data = cast[ptr UncheckedArray[float]](allocShared(sizeof(float) * len))
+
+proc newMyObjDistinct(len: int): MyObjDistinct =
+  MyObjDistinct(newMyObj(len))
+
+proc fooDistinct =
+  doAssert newMyObjDistinct(2).MyObj.len == 2
+
+fooDistinct()
+
+
+proc takeSink(x: sink string): bool = true
+
+proc b(x: sink string): string =
+  if takeSink(x):
+    return x & "abc"
+
+proc bbb(inp: string) =
+  let y = inp & "xyz"
+  echo b(y)
+
+bbb("123")
+
+
+# bug #13691
+type Variable = ref object
+  value: int
+
+proc `=destroy`(self: typeof(Variable()[])) =
+  echo "destroying variable: ",self.value
+
+proc newVariable(value: int): Variable =
+  result = Variable()
+  result.value = value
+  #echo "creating variable: ",result.value
+
+proc test(count: int) =
+  var v {.global.} = newVariable(10)
+
+  var count = count - 1
+  if count == 0: return
+
+  test(count)
+  echo "destroyed: ", v.isNil
+
+test(3)
+
+proc test2(count: int) =
+  block: #XXX: Fails with block currently
+    var v {.global.} = newVariable(20)
+
+    var count = count - 1
+    if count == 0: return
+
+    test2(count)
+    echo "destroyed2: ", v.isNil
+
+test2(3)
+
+proc whiley =
+  var a = newVariable(1)
+  while true:
+    var b = newVariable(2)
+    if true: raise newException(CatchableError, "test")
+
+try:
+  whiley()
+except CatchableError:
+  echo "whiley ends :("
+
+#------------------------------------------------------------------------------
+# issue #13810
+
+import streams
+
+type
+  A = ref AObj
+  AObj = object of RootObj
+    io: Stream
+  B = ref object of A
+    x: int
+
+proc `=destroy`(x: AObj) =
+  close(x.io)
+  echo "closed"
+
+var x = B(io: newStringStream("thestream"))
+
+
+#------------------------------------------------------------------------------
+# issue #14003
+
+proc cryptCTR*(nonce: var openArray[char]) =
+  nonce[1] = 'A'
+
+proc main() =
+  var nonce1 = "0123456701234567"
+  cryptCTR(nonce1)
+  doAssert(nonce1 == "0A23456701234567")
+  var nonce2 = "01234567"
+  cryptCTR(nonce2.toOpenArray(0, nonce2.len-1))
+  doAssert(nonce2 == "0A234567")
+
+main()
+
+# bug #14079
+import std/algorithm
+
+let
+  n = @["c", "b"]
+  q = @[("c", "2"), ("b", "1")]
+
+doAssert n.sortedByIt(it) == @["b", "c"], "fine"
+doAssert q.sortedByIt(it[0]) == @[("b", "1"), ("c", "2")], "fails under arc"
+
+
+#------------------------------------------------------------------------------
+# issue #14236
+
+type
+  MyType = object
+    a: seq[int]
+
+proc re(x: static[string]): static MyType =
+  MyType()
+
+proc match(inp: string, rg: static MyType) =
+  doAssert rg.a.len == 0
+
+match("ac", re"a(b|c)")
+
+#------------------------------------------------------------------------------
+# issue #14243
+
+type
+  Game* = ref object
+
+proc free*(game: Game) =
+  let a = 5
+
+proc newGame*(): Game =
+  new(result, free)
+
+var game*: Game
+
+
+#------------------------------------------------------------------------------
+# issue #14333
+
+type
+  SimpleLoop = object
+
+  Lsg = object
+    loops: seq[ref SimpleLoop]
+    root: ref SimpleLoop
+
+var lsg: Lsg
+lsg.loops.add lsg.root
+echo lsg.loops.len
+
+# bug #14495
+type
+  Gah = ref object
+    x: string
+
+proc bug14495 =
+  var owners: seq[Gah]
+  for i in 0..10:
+    owners.add Gah(x: $i)
+
+  var x: seq[Gah]
+  for i in 0..10:
+    x.add owners[i]
+
+  for i in 0..100:
+    setLen(x, 0)
+    setLen(x, 10)
+
+  for i in 0..x.len-1:
+    if x[i] != nil:
+      echo x[i][]
+
+  for o in owners:
+    echo o[]
+
+bug14495()
+
+# bug #14396
+type
+  Spinny = ref object
+    t: ref int
+    text: string
+
+proc newSpinny*(): Spinny =
+  Spinny(t: new(int), text: "hello")
+
+proc spinnyLoop(x: ref int, spinny: sink Spinny) =
+  echo x[]
+
+proc start*(spinny: sink Spinny) =
+  spinnyLoop(spinny.t, spinny)
+
+var spinner1 = newSpinny()
+spinner1.start()
+
+# bug #14345
+
+type
+  SimpleLoopB = ref object
+    children: seq[SimpleLoopB]
+    parent: SimpleLoopB
+
+proc addChildLoop(self: SimpleLoopB, loop: SimpleLoopB) =
+  self.children.add loop
+
+proc setParent(self: SimpleLoopB, parent: SimpleLoopB) =
+  self.parent = parent
+  self.parent.addChildLoop(self)
+
+var l = SimpleLoopB()
+l.setParent(l)
+
+
+# bug #14968
+import times
+let currentTime = now().utc
+
+
+# bug #14994
+import sequtils
+var newLine = @['a']
+let indent = newSeq[char]()
+
+echo "new line before - ", newline
+
+newline.insert(indent, 0)
+
+echo "new line after - ", newline
+
+# bug #15044
+
+type
+  Test = ref object
+
+proc test: Test =
+  # broken
+  new(result, proc(x: Test) =
+    echo "finalizer"
+  )
+
+proc tdirectFinalizer =
+  discard test()
+
+tdirectFinalizer()
+
+
+# bug #14480
+proc hello(): int =
+  result = 42
+
+var leaves {.global.} = hello()
+doAssert leaves == 42
+
+# bug #15052
+
+proc mutstrings =
+  var data = "hello"
+  for c in data.mitems():
+    c = 'a'
+  echo data
+
+mutstrings()
+
+# bug #15038
+
+type
+  Machine = ref object
+    hello: string
+
+var machineTypes: seq[tuple[factory: proc(): Machine]]
+
+proc registerMachine(factory: proc(): Machine) =
+  var mCreator = proc(): Machine =
+    result = factory()
+
+  machineTypes.add((factory: mCreator))
+
+proc facproc(): Machine =
+  result = Machine(hello: "hello")
+
+registerMachine(facproc)
+
+proc createMachine =
+  for machine in machineTypes:
+    echo machine.factory().hello
+
+createMachine()
+
+# bug #15122
+
+import tables
+
+type
+  BENodeKind = enum
+    tkBytes,
+    tkList,
+    tkDict
+
+  BENode = object
+    case kind: BENodeKind
+    of tkBytes: strVal: string
+    of tkList: listVal: seq[BENode]
+    of tkDict: dictVal: Table[string, BENode]
+
+var data = {
+  "examples": {
+    "values": BENode(
+      kind: tkList,
+      listVal: @[BENode(kind: tkBytes, strVal: "test")]
+    )
+  }.toTable()
+}.toTable()
+
+# For ARC listVal is empty for some reason
+doAssert data["examples"]["values"].listVal[0].strVal == "test"
+
+
+
+
+###############################################################################
+# bug #15405
+import parsexml
+const test_xml_str = "<A><B>value</B></A>"
+var stream = newStringStream(test_xml_str)
+var xml: XmlParser
+open(xml, stream, "test")
+var xml2 = deepCopy(xml)
+
+proc text_parser(xml: var XmlParser) =
+  var test_passed = false
+  while true:
+    xml.next()
+    case xml.kind
+    of xmlElementStart:
+      if xml.elementName == "B":
+        xml.next()
+        if xml.kind == xmlCharData and xml.charData == "value":
+          test_passed = true
+
+    of xmlEof: break
+    else: discard
+  xml.close()
+  doAssert(test_passed)
+
+text_parser(xml)
+text_parser(xml2)
+
+# bug #15599
+type
+  PixelBuffer = ref object
+
+proc newPixelBuffer(): PixelBuffer =
+  new(result) do (buffer: PixelBuffer):
+    echo "ok"
+
+discard newPixelBuffer()
+
+
+# bug #17199
+
+proc passSeq(data: seq[string]) =
+  # used the system.& proc initially
+  let wat = data & "hello"
+
+proc test2 =
+  let name = @["hello", "world"]
+  passSeq(name)
+  doAssert name == @["hello", "world"]
+
+static: test2() # was buggy
+test2()
+
+proc merge(x: sink seq[string], y: sink string): seq[string] =
+  newSeq(result, x.len + 1)
+  for i in 0..x.len-1:
+    result[i] = move(x[i])
+  result[x.len] = move(y)
+
+proc passSeq2(data: seq[string]) =
+  # used the system.& proc initially
+  let wat = merge(data, "hello")
+
+proc test3 =
+  let name = @["hello", "world"]
+  passSeq2(name)
+  doAssert name == @["hello", "world"]
+
+static: test3() # was buggy
+test3()
+
+# bug #17712
+proc t17712 =
+  var ppv = new int
+  discard @[ppv]
+  var el: ref int
+  el = [ppv][0]
+  echo el != nil
+
+t17712()
+
+# bug #18030
+
+type
+  Foo = object
+    n: int
+
+proc `=copy`(dst: var Foo, src: Foo) =
+  echo "copying"
+  dst.n = src.n
+
+proc `=sink`(dst: var Foo, src: Foo) =
+  echo "sinking"
+  dst.n = src.n
+
+var a: Foo
+
+proc putValue[T](n: T)
+
+proc useForward =
+  putValue(123)
+
+proc putValue[T](n: T) =
+  var b = Foo(n:n)
+  a = b
+  echo b.n
+
+useForward()
+
+
+# bug #17319
+type
+  BrokenObject = ref object
+    brokenType: seq[int]
+
+proc use(obj: BrokenObject) =
+  discard
+
+method testMethod(self: BrokenObject) {.base.} =
+  iterator testMethodIter() {.closure.} =
+    use(self)
+
+  var nameIterVar = testMethodIter
+  nameIterVar()
+
+let mikasa = BrokenObject()
+mikasa.testMethod()
+
+# bug #19205
+type
+  InputSectionBase* = object of RootObj
+    relocations*: seq[int]   # traced reference. string has a similar SIGSEGV.
+  InputSection* = object of InputSectionBase
+
+proc fooz(sec: var InputSectionBase) =
+  if sec of InputSection:  # this line SIGSEGV.
+    echo 42
+
+var sec = create(InputSection)
+sec[] = InputSection(relocations: newSeq[int]())
+fooz sec[]
+
+block:
+  type
+    Data = ref object
+      id: int
+  proc main =
+    var x = Data(id: 99)
+    var y = x
+    x[] = Data(id: 778)[]
+    doAssert y.id == 778
+    doAssert x[].id == 778
+  main()
+
+block: # bug #19857
+  type
+    ValueKind = enum VNull, VFloat, VObject # need 3 elements. Cannot remove VNull or VObject
+
+    Value = object
+      case kind: ValueKind
+      of VFloat: fnum: float
+      of VObject: tab: Table[int, int] # OrderedTable[T, U] also makes it fail.
+                                      # "simpler" types also work though
+      else: discard # VNull can be like this, but VObject must be filled
+
+    # required. Pure proc works
+    FormulaNode = proc(c: OrderedTable[string, int]): Value
+
+  proc toF(v: Value): float =
+    doAssert v.kind == VFloat
+    case v.kind
+    of VFloat: result = v.fnum
+    else: discard
+
+
+  proc foo() =
+    let fuck = initOrderedTable[string, int]()
+    proc cb(fuck: OrderedTable[string, int]): Value =
+                            # works:
+                            #result = Value(kind: VFloat, fnum: fuck["field_that_does_not_exist"].float)
+                            # broken:
+      discard "actuall runs!"
+      let t = fuck["field_that_does_not_exist"]
+      echo "never runs, but we crash after! ", t
+
+    doAssertRaises(KeyError):
+      let fn = FormulaNode(cb)
+      let v = fn(fuck)
+      #echo v
+      let res = v.toF()
+
+  foo()
+
+import std/options
+
+# bug #21592
+type Event* = object
+  code*: string
+
+type App* = ref object of RootObj
+  id*: string
+
+method process*(self: App): Option[Event] {.base.} =
+  raise Exception.new_exception("not impl")
+
+# bug #21617
+type Test2 = ref object of RootObj
+
+method bug(t: Test2): seq[float] {.base.} = discard
+
+block: # bug #22664
+  type
+    ElementKind = enum String, Number
+    Element = object
+      case kind: ElementKind
+      of String:
+        str: string
+      of Number:
+        num: float
+    Calc = ref object
+      stack: seq[Element]
+
+  var calc = new Calc
+
+  calc.stack.add Element(kind: Number, num: 200.0)
+  doAssert $calc.stack == "@[(kind: Number, num: 200.0)]"
+  let calc2 = calc
+  calc2.stack = calc.stack # This nulls out the object in the stack
+  doAssert $calc.stack == "@[(kind: Number, num: 200.0)]"
+  doAssert $calc2.stack == "@[(kind: Number, num: 200.0)]"
+
+block: # bug #19250
+  type
+    Bar[T] = object
+      err: proc(): string
+
+    Foo[T] = object
+      run: proc(): Bar[T]
+
+  proc bar[T](err: proc(): string): Bar[T] =
+    assert not err.isNil
+    Bar[T](err: err)
+
+  proc foo(): Foo[char] = 
+    result.run = proc(): Bar[char] =
+      # works
+      # result = Bar[char](err: proc(): string = "x")
+      # not work
+      result = bar[char](proc(): string = "x")
+
+  proc bug[T](fs: Foo[T]): Foo[T] =
+    result.run = proc(): Bar[T] =
+      let res = fs.run()
+      
+      # works
+      # var errors = @[res.err] 
+      
+      # not work
+      var errors: seq[proc(): string]
+      errors.add res.err
+      
+      return bar[T] do () -> string:
+        for err in errors:
+          result.add res.err()
+
+  doAssert bug(foo()).run().err() == "x"
+
+block: # bug #22259
+  type
+    ProcWrapper = tuple
+      p: proc() {.closure.}
+
+
+  proc f(wrapper: ProcWrapper) =
+    let s = @[wrapper.p]
+    let a = [wrapper.p]
+
+  proc main =
+    # let wrapper: ProcWrapper = ProcWrapper(p: proc {.closure.} = echo 10)
+    let wrapper: ProcWrapper = (p: proc {.closure.} = echo 10)
+    f(wrapper)
+
+  main()
+
+block:
+  block: # bug #22923
+    block:
+      let
+        a: int = 100
+        b: int32 = 200'i32
+
+      let
+        x = arrayWith(a, 8) # compiles
+        y = arrayWith(b, 8) # internal error
+        z = arrayWith(14, 8) # integer literal also results in a crash
+
+      doAssert x == [100, 100, 100, 100, 100, 100, 100, 100]
+      doAssert $y == "[200, 200, 200, 200, 200, 200, 200, 200]"
+      doAssert z == [14, 14, 14, 14, 14, 14, 14, 14]
+
+    block:
+      let a: string = "nim"
+      doAssert arrayWith(a, 3) == ["nim", "nim", "nim"]
+
+      let b: char = 'c'
+      doAssert arrayWith(b, 3) == ['c', 'c', 'c']
+
+      let c: uint = 300'u
+      doAssert $arrayWith(c, 3) == "[300, 300, 300]"
+
+block: # bug #23505
+  type
+    K = object
+    C = object
+      value: ptr K
+
+  proc init(T: type C): C =
+    let tmp = new K
+    C(value: addr tmp[])
+
+  discard init(C)
+
+block: # bug #23524
+  type MyType = object
+    a: int
+
+  proc `=destroy`(typ: MyType) = discard
+
+  var t1 = MyType(a: 100)
+  var t2 = t1 # Should be a copy?
+
+  proc main() =
+    t2 = t1
+    doAssert t1.a == 100
+    doAssert t2.a == 100
+
+  main()
+
+block: # bug #23907
+  type
+    Thingy = object
+      value: int
+
+    ExecProc[C] = proc(value: sink C): int {.nimcall.}
+
+  proc `=copy`(a: var Thingy, b: Thingy) {.error.}
+
+  var thingyDestroyCount = 0
+
+  proc `=destroy`(thingy: Thingy) =
+    assert(thingyDestroyCount <= 0)
+    thingyDestroyCount += 1
+
+  proc store(value: sink Thingy): int =
+    result = value.value
+
+  let callback: ExecProc[Thingy] = store
+
+  doAssert callback(Thingy(value: 123)) == 123
+
+import std/strutils
+
+block: # bug #23974
+  func g(e: seq[string]): lent seq[string] = result = e
+  proc k(f: string): seq[string] = f.split("/")
+  proc n() =
+    const r = "/d/"
+    let t =
+      if true:
+        k(r).g()
+      else:
+        k("/" & r).g()
+    echo t
+
+  n()
+
+block: # bug #23973
+  func g(e: seq[string]): lent seq[string] = result = e
+  proc k(f: string): seq[string] = f.split("/")
+  proc n() =
+    const r = "/test/empty"  # or "/test/empty/1"
+    let a = k(r).g()
+    let t =
+      if true:
+        k(r).g()
+      else:
+        k("/" & r).g()   # or raiseAssert ""
+    doAssert t == a
+
+  n()
+
+block: # bug #24141
+  func reverse(s: var openArray[char]) =
+    s[0] = 'f'
+
+  func rev(s: var string) =
+    s.reverse
+
+  proc main =
+    var abc = "abc"
+    abc.rev
+    doAssert abc == "fbc"
+
+  main()
diff --git a/tests/arc/tasyncawait.nim b/tests/arc/tasyncawait.nim
index 89e924104..91a7453cd 100644
--- a/tests/arc/tasyncawait.nim
+++ b/tests/arc/tasyncawait.nim
@@ -1,9 +1,10 @@
 discard """
-  output: "5000"
-  cmd: "nim c --gc:arc $file"
+  outputsub: "result: 5000"
+  cmd: "nim c --gc:orc $file"
 """
 
-import asyncdispatch, asyncnet, nativesockets, net, strutils, os
+import asyncdispatch, asyncnet, nativesockets, net, strutils
+from stdtest/netutils import bindAvailablePort
 
 var msgCount = 0
 
@@ -39,31 +40,29 @@ proc readMessages(client: AsyncFD) {.async.} =
       clientCount.inc
       break
     else:
-      if line.startswith("Message "):
+      if line.startsWith("Message "):
         msgCount.inc
       else:
         doAssert false
 
-proc createServer(port: Port) {.async.} =
-  var server = createAsyncNativeSocket()
-  block:
-    var name: Sockaddr_in
-    name.sin_family = typeof(name.sin_family)(toInt(AF_INET))
-    name.sin_port = htons(uint16(port))
-    name.sin_addr.s_addr = htonl(INADDR_ANY)
-    if bindAddr(server.SocketHandle, cast[ptr SockAddr](addr(name)),
-                sizeof(name).Socklen) < 0'i32:
-      raiseOSError(osLastError())
-
+proc createServer(server: AsyncFD) {.async.} =
   discard server.SocketHandle.listen()
   while true:
     asyncCheck readMessages(await accept(server))
 
-asyncCheck createServer(Port(10335))
-asyncCheck launchSwarm(Port(10335))
-while true:
-  poll()
-  if clientCount == swarmSize: break
+proc main =
+  let server = createAsyncNativeSocket()
+  let port = bindAvailablePort(server.SocketHandle)
+  asyncCheck createServer(server)
+  asyncCheck launchSwarm(port)
+  while true:
+    poll()
+    if clientCount == swarmSize: break
+
+let mem = getOccupiedMem()
+main()
 
-assert msgCount == swarmSize * messagesToSend
-echo msgCount
+doAssert msgCount == swarmSize * messagesToSend
+echo "result: ", msgCount
+GC_fullCollect()
+echo "memory: ", formatSize(getOccupiedMem() - mem)
diff --git a/tests/arc/tasyncleak.nim b/tests/arc/tasyncleak.nim
new file mode 100644
index 000000000..8e3a7b3e7
--- /dev/null
+++ b/tests/arc/tasyncleak.nim
@@ -0,0 +1,21 @@
+discard """
+  outputsub: "(allocCount: 4050, deallocCount: 4048)"
+  cmd: "nim c --gc:orc -d:nimAllocStats $file"
+"""
+
+import asyncdispatch
+# bug #15076
+const
+  # Just to occupy some RAM
+  BigData = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+
+proc doNothing(): Future[void] {.async.} =
+  discard
+
+proc main(): Future[void] {.async.} =
+  for x in 0 .. 1_000:
+    await doNothing()
+
+waitFor main()
+GC_fullCollect()
+echo getAllocStats()
diff --git a/tests/arc/tasyncleak2.nim b/tests/arc/tasyncleak2.nim
new file mode 100644
index 000000000..87d7e73f9
--- /dev/null
+++ b/tests/arc/tasyncleak2.nim
@@ -0,0 +1,88 @@
+discard """
+  output: "success"
+  cmd: "nim c --gc:orc $file"
+"""
+
+# issue #15076
+import deques, strutils, asyncdispatch
+
+proc doNothing(): Future[void] =
+  #[
+  var
+    :env
+    :env_1
+  try:
+    `=destroy`(:env)
+    internalNew(:env)
+    `=sink`(:env.retFuture1, newFuture("doNothing"))
+
+    `=destroy_1`(:env_1)
+    internalNew(:env_1)
+    `=`(:env_1.:up, :env)
+    `=sink_1`(:env.nameIterVar2, (doNothingIter, :env_1))
+
+    (doNothingNimAsyncContinue, :env)()
+    return `=_1`(result, :env.retFuture1)
+  finally:
+    `=destroy`(:env)
+  ]#
+
+  var retFuture = newFuture[void]("doNothing")
+  iterator doNothingIter(): FutureBase {.closure.} =
+    # inspected ARC code: looks correct!
+    block:
+      var qqq = initDeque[string]()
+      for i in 0 .. 1000:
+        qqq.addLast($i)
+    complete(retFuture) # env.up.retFuture1
+
+  var nameIterVar = doNothingIter  # iter_Env -> retFuture ->
+
+  proc doNothingNimAsyncContinue() {.closure.} =
+    # inspected ARC code: looks correct
+    if not nameIterVar.finished:
+      var next_gensym0 = nameIterVar()
+      while (not next_gensym0.isNil) and next_gensym0.finished:
+        next_gensym0 = nameIterVar()
+        if nameIterVar.finished:
+          break
+      if next_gensym0 != nil:
+        {.gcsafe.}:
+          next_gensym0.addCallback cast[proc () {.closure, gcsafe.}](doNothingNimAsyncContinue)
+
+  doNothingNimAsyncContinue()
+  return retFuture
+
+proc main(): Future[void] =
+  template await[T](f_gensym12: Future[T]): auto {.used.} =
+    var internalTmpFuture_gensym12: FutureBase = f_gensym12
+    yield internalTmpFuture_gensym12
+    (cast[typeof(f_gensym12)](internalTmpFuture_gensym12)).read()
+
+  var retFuture = newFuture[void]("main")
+  iterator mainIter(): FutureBase {.closure.} =
+    block:
+      for x in 0 .. 1000:
+        await doNothing()
+    complete(retFuture)
+
+  var nameIterVar_gensym11 = mainIter
+  proc mainNimAsyncContinue() {.closure.} =
+    if not nameIterVar_gensym11.finished:
+      var next_gensym11 = unown nameIterVar_gensym11()
+      while (not next_gensym11.isNil) and next_gensym11.finished:
+        next_gensym11 = unown nameIterVar_gensym11()
+        if nameIterVar_gensym11.finished:
+          break
+      if next_gensym11 != nil:
+        {.gcsafe.}:
+          next_gensym11.addCallback cast[proc () {.closure, gcsafe.}](mainNimAsyncContinue)
+
+  mainNimAsyncContinue()
+  return retFuture
+
+for i in 0..9:
+  waitFor main()
+  GC_fullCollect()
+  doAssert getOccupiedMem() < 1024
+echo "success"
diff --git a/tests/arc/tasyncleak3.nim b/tests/arc/tasyncleak3.nim
new file mode 100644
index 000000000..21e963b7f
--- /dev/null
+++ b/tests/arc/tasyncleak3.nim
@@ -0,0 +1,47 @@
+discard """
+  cmd: "nim c --gc:orc -d:useMalloc $file"
+  output: "true"
+  valgrind: "true"
+"""
+
+import strutils
+
+type
+  FutureBase* = ref object of RootObj  ## Untyped future.
+    finished: bool
+    stackTrace: seq[StackTraceEntry] ## For debugging purposes only.
+
+proc newFuture*(): FutureBase =
+  new(result)
+  result.finished = false
+  result.stackTrace = getStackTraceEntries()
+
+type
+  PDispatcher {.acyclic.} = ref object
+
+var gDisp: PDispatcher
+new gDisp
+
+proc testCompletion(): FutureBase =
+  var retFuture = newFuture()
+
+  iterator testCompletionIter(): FutureBase {.closure.} =
+    retFuture.finished = true
+    when not defined(nobug):
+      let disp = gDisp # even worse memory consumption this way...
+
+  var nameIterVar = testCompletionIter
+  proc testCompletionNimAsyncContinue() {.closure.} =
+    if not nameIterVar.finished:
+      discard nameIterVar()
+  testCompletionNimAsyncContinue()
+  return retFuture
+
+proc main =
+  for i in 0..10_000:
+    discard testCompletion()
+
+main()
+
+GC_fullCollect()
+echo getOccupiedMem() < 1024
diff --git a/tests/arc/tasyncleak4.nim b/tests/arc/tasyncleak4.nim
new file mode 100644
index 000000000..58cd7f0b7
--- /dev/null
+++ b/tests/arc/tasyncleak4.nim
@@ -0,0 +1,21 @@
+discard """
+  cmd: "nim c --gc:orc -d:useMalloc $file"
+  output: '''ok'''
+  valgrind: "leaks"
+"""
+
+# bug #15076
+import asyncdispatch
+
+var futures: seq[Future[void]]
+
+for i in 1..20:
+  futures.add sleepAsync 1
+  futures.add sleepAsync 1
+
+  futures.all.waitFor()
+  futures.setLen 0
+
+setGlobalDispatcher nil
+GC_fullCollect()
+echo "ok"
diff --git a/tests/arc/tasyncorc.nim b/tests/arc/tasyncorc.nim
new file mode 100644
index 000000000..63703b559
--- /dev/null
+++ b/tests/arc/tasyncorc.nim
@@ -0,0 +1,26 @@
+discard """
+  output: '''230000'''
+  cmd: '''nim c --gc:orc -d:useMalloc $file'''
+  valgrind: "leaks"
+"""
+
+# bug #14402
+
+import asynchttpserver, asyncdispatch, httpclient, strutils
+
+proc cb(req: Request) {.async, gcsafe.} =
+  const html = " ".repeat(230000)
+  await req.respond(Http200, html)
+
+var server = newAsyncHttpServer()
+asyncCheck server.serve(Port(8080), cb)
+
+proc test {.async.} =
+  var
+    client = newAsyncHttpClient()
+    resp = await client.get("http://localhost:8080")
+
+  let x = (await resp.body).len
+  echo x # crash
+
+waitFor test()
diff --git a/tests/arc/tcaseobj.nim b/tests/arc/tcaseobj.nim
index 44daa5979..3499f5c1e 100644
--- a/tests/arc/tcaseobj.nim
+++ b/tests/arc/tcaseobj.nim
@@ -8,6 +8,9 @@ A
 B
 begin
 end
+prevented
+(ok: true, value: "ok")
+@[(kind: P, pChildren: @[])]
 myobj destroyed
 '''
 """
@@ -57,7 +60,7 @@ proc `=destroy`(o: var TMyObj) =
     o.p = nil
     echo "myobj destroyed"
 
-proc `=`(dst: var TMyObj, src: TMyObj) =
+proc `=copy`(dst: var TMyObj, src: TMyObj) =
   `=destroy`(dst)
   dst.p = alloc(src.len)
   dst.len = src.len
@@ -144,3 +147,220 @@ when true:
     let x = sequence([charSet({'a'..'z', 'A'..'Z', '_'})])
     echo "end"
   testSubObjAssignment()
+
+
+#------------------------------------------------
+
+type
+  MyObject = object
+    x1: string
+    case kind1: bool
+      of false: y1: string
+      of true:
+          y2: seq[string]
+          case kind2: bool
+              of true: z1: string
+              of false:
+                z2: seq[string]
+                flag: bool
+    x2: string
+
+proc test_myobject =
+  var x: MyObject
+  x.x1 = "x1"
+  x.x2 = "x2"
+  x.y1 = "ljhkjhkjh"
+  {.cast(uncheckedAssign).}:
+    x.kind1 = true
+  x.y2 = @["1", "2"]
+  {.cast(uncheckedAssign).}:
+    x.kind2 = true
+  x.z1 = "yes"
+  {.cast(uncheckedAssign).}:
+    x.kind2 = false
+  x.z2 = @["1", "2"]
+  {.cast(uncheckedAssign).}:
+    x.kind2 = true
+  x.z1 = "yes"
+  x.kind2 = true # should be no effect
+  doAssert(x.z1 == "yes")
+  {.cast(uncheckedAssign).}:
+    x.kind2 = false
+  {.cast(uncheckedAssign).}:
+    x.kind1 = x.kind2 # support self assignment with effect
+
+  try:
+    x.kind1 = x.flag # flag is not accesible
+  except FieldDefect:
+    echo "prevented"
+
+  doAssert(x.x1 == "x1")
+  doAssert(x.x2 == "x2")
+
+
+test_myobject()
+
+
+#------------------------------------------------
+# bug #14244
+
+type
+  RocksDBResult*[T] = object
+    case ok*: bool
+    of true:
+      value*: T
+    else:
+      error*: string
+
+proc init(): RocksDBResult[string] =
+  {.cast(uncheckedAssign).}:
+    result.ok = true
+    result.value = "ok"
+
+echo init()
+
+
+#------------------------------------------------
+# bug #14312
+
+type MyObj = object
+  case kind: bool
+    of false: x0: int # would work with a type like seq[int]; value would be reset
+    of true: x1: string
+
+var a = MyObj(kind: false, x0: 1234)
+{.cast(uncheckedAssign).}:
+  a.kind = true
+doAssert(a.x1 == "")
+
+block:
+  # bug #15532
+  type Kind = enum
+    k0, k1
+
+  type Foo = object
+    y: int
+    case kind: Kind
+    of k0: x0: int
+    of k1: x1: int
+
+  const j0 = Foo(y: 1, kind: k0, x0: 2)
+  const j1 = Foo(y: 1, kind: k1, x1: 2)
+
+  doAssert j0.y == 1
+  doAssert j0.kind == k0
+  doAssert j1.kind == k1
+
+  doAssert j1.x1 == 2
+  doAssert j0.x0 == 2
+
+# ------------------------------------
+# bug #20305
+
+type
+  ContentNodeKind = enum
+    P, Br, Text
+  ContentNode = object
+    case kind: ContentNodeKind
+    of P: pChildren: seq[ContentNode]
+    of Br: discard
+    of Text: textStr: string
+
+proc bug20305 =
+  var x = ContentNode(kind: P, pChildren: @[
+    ContentNode(kind: P, pChildren: @[ContentNode(kind: Text, textStr: "brrr")])
+  ])
+  x.pChildren.add ContentNode(kind: Br)
+  x.pChildren.del(0)
+  {.cast(uncheckedAssign).}:
+    x.pChildren[0].kind = P
+  echo x.pChildren
+
+bug20305()
+
+# bug #21023
+block:
+  block:
+    type
+      MGErrorKind = enum
+        mgeUnexpected, mgeNotFound
+
+    type Foo = object
+      kind: MGErrorKind
+      ex: Exception
+
+    type Boo = object
+      a: seq[int]
+
+    type
+      Result2 = object
+        case o: bool
+        of false:
+          e: Foo
+        of true:
+          v: Boo
+
+    proc startSessionSync(): Result2 =
+      return Result2(o: true)
+
+    proc mainSync =
+      let ff = startSessionSync()
+      doAssert ff.o == true
+
+    mainSync()
+
+  block:
+    type
+      MGErrorKind = enum
+        mgeUnexpected, mgeNotFound
+
+    type Foo = object
+      kind: MGErrorKind
+      ex: Exception
+
+    type Boo = object
+      a: seq[int]
+
+    type
+      Result2 = object
+        case o: bool
+        of false:
+          e: Foo
+        of true:
+          v: Boo
+          s: int
+
+    proc startSessionSync(): Result2 =
+      return Result2(o: true, s: 12)
+
+    proc mainSync =
+      let ff = startSessionSync()
+      doAssert ff.s == 12
+
+    mainSync()
+
+import std/sequtils
+
+# bug #23690
+type
+  SomeObj* = object of RootObj
+
+  Item* = object
+    case kind*: 0..1
+    of 0:
+      a*: int
+      b*: SomeObj
+    of 1:
+      c*: string
+
+  ItemExt* = object
+    a*: Item
+    b*: string
+
+proc do1(x: int): seq[(string, Item)] =
+  result = @[("zero", Item(kind: 1, c: "first"))]
+
+proc do2(x: int, e: ItemExt): seq[(string, ItemExt)] =
+  do1(x).map(proc(v: (string, Item)): auto = (v[0], ItemExt(a: v[1], b: e.b)))
+
+doAssert $do2(0, ItemExt(a: Item(kind: 1, c: "second"), b: "third")) == """@[("zero", (a: (kind: 1, c: "first"), b: "third"))]"""
diff --git a/tests/arc/tcaseobjcopy.nim b/tests/arc/tcaseobjcopy.nim
new file mode 100644
index 000000000..fb26a4973
--- /dev/null
+++ b/tests/arc/tcaseobjcopy.nim
@@ -0,0 +1,253 @@
+discard """
+  valgrind: true
+  cmd: "nim c --gc:arc -d:useMalloc $file"
+  output: '''myobj destroyed
+myobj destroyed
+myobj destroyed
+A
+B
+begin
+end
+prevented
+(ok: true, value: "ok")
+myobj destroyed
+'''
+"""
+
+# bug #13102
+
+type
+  D = ref object
+  R = object
+    case o: bool
+    of false:
+      discard
+    of true:
+      field: D
+
+iterator things(): R =
+  when true:
+    var
+      unit = D()
+    while true:
+      yield R(o: true, field: unit)
+  else:
+    while true:
+      var
+        unit = D()
+      yield R(o: true, field: unit)
+
+proc main =
+  var i = 0
+  for item in things():
+    discard item.field
+    inc i
+    if i == 2: break
+
+main()
+
+# bug #13149
+
+type
+  TMyObj = object
+    p: pointer
+    len: int
+
+proc `=destroy`(o: var TMyObj) =
+  if o.p != nil:
+    dealloc o.p
+    o.p = nil
+    echo "myobj destroyed"
+
+proc `=copy`(dst: var TMyObj, src: TMyObj) =
+  `=destroy`(dst)
+  dst.p = alloc(src.len)
+  dst.len = src.len
+
+proc `=sink`(dst: var TMyObj, src: TMyObj) =
+  `=destroy`(dst)
+  dst.p = src.p
+  dst.len = src.len
+
+type
+  TObjKind = enum Z, A, B
+  TCaseObj = object
+    case kind: TObjKind
+    of Z: discard
+    of A:
+      x1: int # this int plays important role
+      x2: TMyObj
+    of B:
+      y: TMyObj
+
+proc testSinks: TCaseObj =
+  result = TCaseObj(kind: A, x1: 5000, x2: TMyObj(len: 5, p: alloc(5)))
+  result = TCaseObj(kind: B, y: TMyObj(len: 3, p: alloc(3)))
+
+proc use(x: TCaseObj) = discard
+
+proc testCopies(i: int) =
+  var a: array[2, TCaseObj]
+  a[i] = TCaseObj(kind: A, x1: 5000, x2: TMyObj(len: 5, p: alloc(5)))
+  a[i+1] = a[i] # copy, cannot move
+  use(a[i])
+
+let x1 = testSinks()
+testCopies(0)
+
+# bug #12957
+
+type
+  PegKind* = enum
+    pkCharChoice,
+    pkSequence
+  Peg* = object ## type that represents a PEG
+    case kind: PegKind
+    of pkCharChoice: charChoice: ref set[char]
+    else: discard
+    sons: seq[Peg]
+
+proc charSet*(s: set[char]): Peg =
+  ## constructs a PEG from a character set `s`
+  result = Peg(kind: pkCharChoice)
+  new(result.charChoice)
+  result.charChoice[] = s
+
+proc len(a: Peg): int {.inline.} = return a.sons.len
+proc myadd(d: var Peg, s: Peg) {.inline.} = add(d.sons, s)
+
+proc sequence*(a: openArray[Peg]): Peg =
+  result = Peg(kind: pkSequence, sons: @[])
+  when false:
+    #works too:
+    result.myadd(a[0])
+    result.myadd(a[1])
+  for x in items(a):
+    # works:
+    #result.sons.add(x)
+    # fails:
+    result.myadd x
+  if result.len == 1:
+    result = result.sons[0] # this must not move!
+
+when true:
+  # bug #12957
+
+  proc p =
+    echo "A"
+    let x = sequence([charSet({'a'..'z', 'A'..'Z', '_'}),
+              charSet({'a'..'z', 'A'..'Z', '0'..'9', '_'})])
+    echo "B"
+  p()
+
+  proc testSubObjAssignment =
+    echo "begin"
+    # There must be extactly one element in the array constructor!
+    let x = sequence([charSet({'a'..'z', 'A'..'Z', '_'})])
+    echo "end"
+  testSubObjAssignment()
+
+
+#------------------------------------------------
+
+type
+  MyObject = object
+    x1: string
+    case kind1: bool
+      of false: y1: string
+      of true:
+          y2: seq[string]
+          case kind2: bool
+              of true: z1: string
+              of false:
+                z2: seq[string]
+                flag: bool
+    x2: string
+
+proc test_myobject =
+  var x: MyObject
+  x.x1 = "x1"
+  x.x2 = "x2"
+  x.y1 = "ljhkjhkjh"
+  {.cast(uncheckedAssign).}:
+    x.kind1 = true
+  x.y2 = @["1", "2"]
+  {.cast(uncheckedAssign).}:
+    x.kind2 = true
+  x.z1 = "yes"
+  {.cast(uncheckedAssign).}:
+    x.kind2 = false
+  x.z2 = @["1", "2"]
+  {.cast(uncheckedAssign).}:
+    x.kind2 = true
+  x.z1 = "yes"
+  x.kind2 = true # should be no effect
+  doAssert(x.z1 == "yes")
+  {.cast(uncheckedAssign).}:
+    x.kind2 = false
+    x.kind1 = x.kind2 # support self assignment with effect
+
+  try:
+    x.kind1 = x.flag # flag is not accesible
+  except FieldDefect:
+    echo "prevented"
+
+  doAssert(x.x1 == "x1")
+  doAssert(x.x2 == "x2")
+
+
+test_myobject()
+
+
+#------------------------------------------------
+# bug #14244
+
+type
+  RocksDBResult*[T] = object
+    case ok*: bool
+    of true:
+      value*: T
+    else:
+      error*: string
+
+proc init(): RocksDBResult[string] =
+  {.cast(uncheckedAssign).}:
+    result.ok = true
+  result.value = "ok"
+
+echo init()
+
+
+#------------------------------------------------
+# bug #14312
+
+type MyObj = object
+  case kind: bool
+    of false: x0: int # would work with a type like seq[int]; value would be reset
+    of true: x1: string
+
+var a = MyObj(kind: false, x0: 1234)
+{.cast(uncheckedAssign).}:
+  a.kind = true
+doAssert(a.x1 == "")
+
+block:
+  # bug #15532
+  type Kind = enum
+    k0, k1
+
+  type Foo = object
+    y: int
+    case kind: Kind
+    of k0: x0: int
+    of k1: x1: int
+
+  const j0 = Foo(y: 1, kind: k0, x0: 2)
+  const j1 = Foo(y: 1, kind: k1, x1: 2)
+
+  doAssert j0.y == 1
+  doAssert j0.kind == k0
+  doAssert j1.kind == k1
+
+  doAssert j1.x1 == 2
+  doAssert j0.x0 == 2
diff --git a/tests/arc/tclosureiter.nim b/tests/arc/tclosureiter.nim
new file mode 100644
index 000000000..e4a2ceac6
--- /dev/null
+++ b/tests/arc/tclosureiter.nim
@@ -0,0 +1,36 @@
+discard """
+  cmd: '''nim c -d:nimAllocStats --gc:arc $file'''
+  output: '''(allocCount: 102, deallocCount: 102)'''
+"""
+
+type
+  FutureBase = ref object
+    someData: string
+
+const
+  # Just to occupy some RAM
+  BigData = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"
+
+iterator mainIter(): FutureBase {.closure.} =
+  for x in 0 .. 100:
+    var internalTmpFuture = FutureBase(someData: BigData)
+    yield internalTmpFuture
+
+proc main() =
+  var nameIterVar = mainIter
+  var next = nameIterVar()
+  while not isNil(next):
+    next = nameIterVar()
+    if not isNil(next):
+      doAssert next.someData.len == 97
+    # GC_unref(next)
+    # If you uncomment the GC_ref above,
+    # the program basically uses no memory after the run.
+    # but crashes with refc, which might indicate
+    # that arc/orc simply never frees the result of "next"?
+    if finished(nameIterVar):
+      break
+
+main()
+GC_fullCollect()
+echo getAllocStats()
diff --git a/tests/casestmt/t12785.nim b/tests/arc/tcomputedgoto.nim
index bf0f30d42..07487684a 100644
--- a/tests/casestmt/t12785.nim
+++ b/tests/arc/tcomputedgoto.nim
@@ -1,22 +1,19 @@
 discard """
-  cmd: '''nim c --newruntime $file'''
-  output: '''copied
-copied
+  cmd: '''nim c --mm:arc $file'''
+  output: '''
 2
-copied
-copied
 2
 destroyed
-destroyed'''
+'''
 """
 
 type
   ObjWithDestructor = object
     a: int
-proc `=destroy`(self: var ObjWithDestructor) =
+proc `=destroy`(self: ObjWithDestructor) =
   echo "destroyed"
 
-proc `=`(self: var ObjWithDestructor, other: ObjWithDestructor) =
+proc `=copy`(self: var ObjWithDestructor, other: ObjWithDestructor) =
   echo "copied"
 
 proc test(a: range[0..1], arg: ObjWithDestructor) =
@@ -37,11 +34,11 @@ proc test(a: range[0..1], arg: ObjWithDestructor) =
     inc iteration
 
     case a
-    of 0:  
-        assert false
-    of 1:      
+    of 0:
+      assert false
+    of 1:
       echo b
       if iteration == 2:
         break
 
-test(1, ObjWithDestructor())
\ No newline at end of file
+test(1, ObjWithDestructor())
diff --git a/tests/arc/tcomputedgotocopy.nim b/tests/arc/tcomputedgotocopy.nim
new file mode 100644
index 000000000..07487684a
--- /dev/null
+++ b/tests/arc/tcomputedgotocopy.nim
@@ -0,0 +1,44 @@
+discard """
+  cmd: '''nim c --mm:arc $file'''
+  output: '''
+2
+2
+destroyed
+'''
+"""
+
+type
+  ObjWithDestructor = object
+    a: int
+proc `=destroy`(self: ObjWithDestructor) =
+  echo "destroyed"
+
+proc `=copy`(self: var ObjWithDestructor, other: ObjWithDestructor) =
+  echo "copied"
+
+proc test(a: range[0..1], arg: ObjWithDestructor) =
+  var iteration = 0
+  while true:
+    {.computedGoto.}
+
+    let
+      b = int(a) * 2
+      c = a
+      d = arg
+      e = arg
+
+    discard c
+    discard d
+    discard e
+
+    inc iteration
+
+    case a
+    of 0:
+      assert false
+    of 1:
+      echo b
+      if iteration == 2:
+        break
+
+test(1, ObjWithDestructor())
diff --git a/tests/arc/tconst_to_sink.nim b/tests/arc/tconst_to_sink.nim
new file mode 100644
index 000000000..25f659341
--- /dev/null
+++ b/tests/arc/tconst_to_sink.nim
@@ -0,0 +1,26 @@
+discard """
+  output: '''@[(s1: "333", s2: ""), (s1: "abc", s2: "def"), (s1: "3x", s2: ""), (s1: "3x", s2: ""), (s1: "3x", s2: ""), (s1: "3x", s2: ""), (s1: "lastone", s2: "")]'''
+  matrix: "--gc:arc"
+  targets: "c cpp"
+"""
+
+# bug #13240
+
+type
+  Thing = object
+    s1: string
+    s2: string
+
+var box: seq[Thing]
+
+const c = [Thing(s1: "333"), Thing(s1: "abc", s2: "def")]
+
+for i in 0..high(c):
+  box.add c[i]
+
+for i in 0..3:
+  box.add Thing(s1: "3x")
+
+box.add Thing(s1: "lastone")
+
+echo box
diff --git a/tests/arc/tcontrolflow.nim b/tests/arc/tcontrolflow.nim
new file mode 100644
index 000000000..dbc115903
--- /dev/null
+++ b/tests/arc/tcontrolflow.nim
@@ -0,0 +1,118 @@
+discard """
+  output: '''begin A
+elif
+end A
+destroyed
+begin false
+if
+end false
+destroyed
+begin true
+if
+end true
+7
+##index 2 not in 0 .. 1##
+true
+'''
+  cmd: "nim c --gc:arc -d:danger $file"
+"""
+# we use the -d:danger switch to detect uninitialized stack
+# slots more reliably (there shouldn't be any, of course).
+
+type
+  Foo = object
+    id: int
+
+proc `=destroy`(x: var Foo) =
+  if x.id != 0:
+    echo "destroyed"
+    x.id = 0
+
+proc construct(): Foo = Foo(id: 3)
+
+proc elifIsEasy(cond: bool) =
+  echo "begin A"
+  if cond:
+    echo "if"
+  elif construct().id == 3:
+    echo "elif"
+  else:
+    echo "else"
+  echo "end A"
+
+elifIsEasy(false)
+
+
+proc orIsHard(cond: bool) =
+  echo "begin ", cond
+  if cond or construct().id == 3:
+    echo "if"
+  else:
+    echo "else"
+  echo "end ", cond
+
+orIsHard(false)
+orIsHard(true)
+
+type
+  Control = ref object
+    x: int
+
+  MouseEvent = ref object
+    control: Control
+    button: int
+
+proc run(data: Control) =
+  var evt = MouseEvent(button: 1)
+  evt.control = data
+  if evt.button == 1:
+    discard
+  else:
+    return
+
+  echo data.x
+
+var c = Control(x: 7)
+
+run(c)
+
+proc sysFatal(exceptn: typedesc, message: string) {.inline.} =
+  var buf = newStringOfCap(200)
+  add(buf, "##")
+  add(buf, message)
+  add(buf, "##")
+  echo buf
+
+proc ifexpr(i, a, b: int) {.compilerproc, noinline.} =
+  sysFatal(IndexDefect,
+    if b < a: "index out of bounds, the container is empty"
+    else: "index " & $i & " not in " & $a & " .. " & $b)
+
+ifexpr(2, 0, 1)
+
+# bug #14899
+template toSeq(): untyped =
+  block:
+    var result = @[1]
+    result
+
+proc clItems(s: seq[int]) =
+  assert s.len == 1
+
+proc escapeCheck =
+  clItems(toSeq())
+
+escapeCheck()
+
+# bug #14900
+
+proc seqsEqual(a, b: string): bool =
+  if false:
+    false
+  else:
+    (var result1 = a; result1) == (var result2 = b; result2)
+
+# can be const or var too
+let expected = "hello"
+
+echo seqsEqual(expected, expected)
diff --git a/tests/arc/tcursor_field_obj_constr.nim b/tests/arc/tcursor_field_obj_constr.nim
new file mode 100644
index 000000000..b87f734bd
--- /dev/null
+++ b/tests/arc/tcursor_field_obj_constr.nim
@@ -0,0 +1,44 @@
+discard """
+  output: '''a
+b
+c'''
+  cmd: "nim c --gc:arc $file"
+"""
+
+# bug #18469
+
+type
+  Edge = object
+    neighbor {.cursor.}: Node
+
+  NodeObj = object
+    neighbors: seq[Edge]
+    label: string
+    visited: bool
+  Node = ref NodeObj
+
+  Graph = object
+    nodes: seq[Node]
+
+proc `=destroy`(x: var NodeObj) =
+  echo x.label
+  `=destroy`(x.neighbors)
+  `=destroy`(x.label)
+
+proc addNode(self: var Graph; label: string): Node =
+  self.nodes.add(Node(label: label))
+  result = self.nodes[^1]
+
+proc addEdge(self: Graph; source, neighbor: Node) =
+  source.neighbors.add(Edge(neighbor: neighbor))
+
+proc main =
+  var graph: Graph
+  let nodeA = graph.addNode("a")
+  let nodeB = graph.addNode("b")
+  let nodeC = graph.addNode("c")
+
+  graph.addEdge(nodeA, neighbor = nodeB)
+  graph.addEdge(nodeA, neighbor = nodeC)
+
+main()
diff --git a/tests/arc/tcursor_on_localvar.nim b/tests/arc/tcursor_on_localvar.nim
new file mode 100644
index 000000000..0f53c5efa
--- /dev/null
+++ b/tests/arc/tcursor_on_localvar.nim
@@ -0,0 +1,161 @@
+discard """
+  output: '''Section: common
+  Param: Floats1
+Section: local
+  Param: Str
+  Param: Bool
+  Param: Floats2
+destroy Foo
+destroy Foo
+'''
+  cmd: '''nim c --gc:arc $file'''
+"""
+
+# bug #15325
+
+import tables
+import strutils
+
+const defaultSection = "***"
+
+type
+    Config* = ref object
+        table: OrderedTableRef[string, OrderedTable[string, string]]
+
+# ----------------------------------------------------------------------------------------------------------------------
+proc newConfig*(): Config =
+    result       = new(Config)
+    result.table = newOrderedTable[string, OrderedTable[string, string]]()
+
+# ----------------------------------------------------------------------------------------------------------------------
+proc add*(self: Config, param, value, section: string) {.nosinks.} =
+    let s = if section == "": defaultSection else: section
+
+    if not self.table.contains(s):
+        self.table[s] = initOrderedTable[string, string]()
+
+    self.table[s][param] = value
+
+# ----------------------------------------------------------------------------------------------------------------------
+proc sections*(self: Config): seq[string] =
+    for i in self.table.keys:
+        let s = if i == defaultSection: "" else: i
+        result.add(s)
+
+# ----------------------------------------------------------------------------------------------------------------------
+proc params*(self: Config, section: string): seq[string] =
+    let s = if section == "": defaultSection else: section
+
+    if self.table.contains(s):
+        for i in self.table[s].keys:
+            result.add(i)
+
+# ----------------------------------------------------------------------------------------------------------------------
+proc extract*(str, start, finish: string): string =
+    let startPos = str.find(start)
+
+    if startPos < 0:
+        return ""
+
+    let endPos = str.find(finish, startPos)
+
+    if endPos < 0:
+        return ""
+
+    return str[startPos + start.len() ..< endPos]
+
+# ----------------------------------------------------------------------------------------------------------------------
+proc loadString*(self: Config, text: string): tuple[valid: bool, errorInLine: int] {.discardable.} =
+    self.table.clear()
+
+    var data = ""
+
+    data = text
+
+    var
+        actualSection = ""
+        lineCount     = 0
+
+    for i in splitLines(data):
+        lineCount += 1
+
+        var line = strip(i)
+
+        if line.len() == 0:
+            continue
+
+        if line[0] == '#' or line[0] == ';':
+            continue
+
+        if line[0] == '[':
+            let section = strip(extract(line, "[", "]"))
+
+            if section.len() != 0:
+                actualSection = section
+            else:
+                self.table.clear()
+                return (false, lineCount)
+        else:
+            let equal = find(line, '=')
+
+            if equal <= 0:
+                self.table.clear()
+                return (false, lineCount)
+            else:
+                let
+                    param = strip(line[0 .. equal - 1])
+                    value = strip(line[equal + 1 .. ^1])
+
+                if param.len() == 0:
+                    self.table.clear()
+                    return (false, lineCount)
+                else:
+                    self.add(param, value, actualSection)
+
+    return (true, 0)
+
+# ----------------------------------------------------------------------------------------------------------------------
+when isMainModule:
+    var cfg = newConfig()
+
+    cfg.loadString("[common]\nFloats1 = 1,2,3\n[local]\nStr = \"String...\"\nBool = true\nFloats2 = 4, 5, 6\n")
+
+    for s in cfg.sections():
+        echo "Section: " & s
+
+        for p in cfg.params(s):
+            echo "  Param: " & p
+
+# bug #16437
+
+type
+  Foo = object
+  FooRef = ref Foo
+
+  Bar = ref object
+    f: FooRef
+
+proc `=destroy`(o: var Foo) =
+  echo "destroy Foo"
+
+proc testMe(x: Bar) =
+  var c = (if x != nil: x.f else: nil)
+  assert c != nil
+
+proc main =
+  var b = Bar(f: FooRef())
+  testMe(b)
+
+main()
+
+proc testMe2(x: Bar) =
+  var c: FooRef
+  c = (if x != nil: x.f else: nil)
+  assert c != nil
+
+proc main2 =
+  var b = Bar(f: FooRef())
+  testMe2(b)
+
+main2()
+
diff --git a/tests/arc/tcursorloop.nim b/tests/arc/tcursorloop.nim
new file mode 100644
index 000000000..a37a6a036
--- /dev/null
+++ b/tests/arc/tcursorloop.nim
@@ -0,0 +1,45 @@
+discard """
+  cmd: '''nim c --gc:arc --expandArc:traverse --hint:Performance:off $file'''
+  nimout: '''
+--expandArc: traverse
+
+var
+  it
+  jt_cursor
+try:
+  `=copy`(it, root)
+  block :tmp:
+    while (
+      not (it == nil)):
+      if true:
+        echo [it.s]
+        `=copy`(it, it.ri)
+  jt_cursor = root
+  if (
+    not (jt_cursor == nil)):
+    echo [jt_cursor.s]
+    jt_cursor = jt_cursor.ri
+finally:
+  `=destroy`(it)
+-- end of expandArc ------------------------
+'''
+"""
+
+type
+  Node = ref object
+    le, ri: Node
+    s: string
+
+proc traverse(root: Node) =
+  var it = root
+  while it != nil:
+    if true:
+      echo it.s
+      it = it.ri
+
+  var jt = root
+  if jt != nil:
+    echo jt.s
+    jt = jt.ri
+
+traverse(nil)
diff --git a/tests/arc/tcustomtrace.nim b/tests/arc/tcustomtrace.nim
new file mode 100644
index 000000000..5e0ecfb24
--- /dev/null
+++ b/tests/arc/tcustomtrace.nim
@@ -0,0 +1,240 @@
+discard """
+  outputsub: '''1
+2
+3
+4
+5
+6
+89
+90
+90
+0 0 1
+0 1 2
+0 2 3
+1 0 4
+1 1 5
+1 2 6
+1 3 7
+after 6 6
+MEM 0'''
+joinable: false
+  cmd: "nim c --gc:orc -d:useMalloc $file"
+  valgrind: "true"
+"""
+
+import typetraits
+
+type
+  myseq*[T] = object
+    len, cap: int
+    data: ptr UncheckedArray[T]
+
+# XXX make code memory safe for overflows in '*'
+var
+  allocCount, deallocCount: int
+
+proc `=destroy`*[T](x: var myseq[T]) =
+  if x.data != nil:
+    when not supportsCopyMem(T):
+      for i in 0..<x.len: `=destroy`(x[i])
+    dealloc(x.data)
+    inc deallocCount
+    x.data = nil
+    x.len = 0
+    x.cap = 0
+
+proc `=copy`*[T](a: var myseq[T]; b: myseq[T]) =
+  if a.data == b.data: return
+  if a.data != nil:
+    `=destroy`(a)
+    #dealloc(a.data)
+    #inc deallocCount
+    #a.data = nil
+  a.len = b.len
+  a.cap = b.cap
+  if b.data != nil:
+    a.data = cast[type(a.data)](alloc(a.cap * sizeof(T)))
+    inc allocCount
+    when supportsCopyMem(T):
+      copyMem(a.data, b.data, a.cap * sizeof(T))
+    else:
+      for i in 0..<a.len:
+        a.data[i] = b.data[i]
+
+proc `=sink`*[T](a: var myseq[T]; b: myseq[T]) =
+  if a.data != nil and a.data != b.data:
+    dealloc(a.data)
+    inc deallocCount
+  a.len = b.len
+  a.cap = b.cap
+  a.data = b.data
+
+proc `=trace`*[T](x: var myseq[T]; env: pointer) =
+  if x.data != nil:
+    for i in 0..<x.len: `=trace`(x[i], env)
+
+proc resize[T](s: var myseq[T]) =
+  let oldCap = s.cap
+  if oldCap == 0: s.cap = 8
+  else: s.cap = (s.cap * 3) shr 1
+  if s.data == nil: inc allocCount
+  s.data = cast[typeof(s.data)](realloc0(s.data, oldCap * sizeof(T), s.cap * sizeof(T)))
+
+proc reserveSlot[T](x: var myseq[T]): ptr T =
+  if x.len >= x.cap: resize(x)
+  result = addr(x.data[x.len])
+  inc x.len
+
+template add*[T](x: var myseq[T]; y: T) =
+  reserveSlot(x)[] = y
+
+proc shrink*[T](x: var myseq[T]; newLen: int) =
+  assert newLen <= x.len
+  assert newLen >= 0
+  when not supportsCopyMem(T):
+    for i in countdown(x.len - 1, newLen - 1):
+      `=destroy`(x.data[i])
+  x.len = newLen
+
+proc grow*[T](x: var myseq[T]; newLen: int; value: T) =
+  if newLen <= x.len: return
+  assert newLen >= 0
+  let oldCap = x.cap
+  if oldCap == 0: x.cap = newLen
+  else: x.cap = max(newLen, (oldCap * 3) shr 1)
+  if x.data == nil: inc allocCount
+  x.data = cast[type(x.data)](realloc0(x.data, oldCap * sizeof(T), x.cap * sizeof(T)))
+  for i in x.len..<newLen:
+    x.data[i] = value
+  x.len = newLen
+
+template default[T](t: typedesc[T]): T =
+  var v: T
+  v
+
+proc setLen*[T](x: var myseq[T]; newLen: int) {.deprecated.} =
+  if newlen < x.len: shrink(x, newLen)
+  else: grow(x, newLen, default(T))
+
+template `[]`*[T](x: myseq[T]; i: Natural): T =
+  assert i < x.len
+  x.data[i]
+
+template `[]=`*[T](x: myseq[T]; i: Natural; y: T) =
+  assert i < x.len
+  x.data[i] = y
+
+proc createSeq*[T](elems: varargs[T]): myseq[T] =
+  result.cap = max(elems.len, 2)
+  result.len = elems.len
+  result.data = cast[type(result.data)](alloc0(result.cap * sizeof(T)))
+  inc allocCount
+  when supportsCopyMem(T):
+    copyMem(result.data, addr(elems[0]), result.cap * sizeof(T))
+  else:
+    for i in 0..<result.len:
+      result.data[i] = elems[i]
+
+proc len*[T](x: myseq[T]): int {.inline.} = x.len
+
+proc main =
+  var s = createSeq(1, 2, 3, 4, 5, 6)
+  s.add 89
+  s.grow s.len + 2, 90
+  for i in 0 ..< s.len:
+    echo s[i]
+
+  var nested = createSeq(createSeq(1, 2, 3), createSeq(4, 5, 6, 7))
+  for i in 0 ..< nested.len:
+    for j in 0 ..< nested[i].len:
+      echo i, " ", j, " ", nested[i][j]
+
+main()
+echo "after ", allocCount, " ", deallocCount
+
+type
+  Node = ref object
+    name: char
+    sccId: int
+    kids: myseq[Node]
+    rc: int
+
+proc edge(a, b: Node) =
+  inc b.rc
+  a.kids.add b
+
+proc createNode(name: char): Node =
+  new result
+  result.name = name
+  result.kids = createSeq[Node]()
+
+proc use(x: Node) = discard
+
+proc buildComplexGraph: Node =
+  # see https://en.wikipedia.org/wiki/Strongly_connected_component for the
+  # graph:
+  let a = createNode('a')
+  let b = createNode('b')
+  let c = createNode('c')
+  let d = createNode('d')
+  let e = createNode('e')
+
+  a.edge c
+  c.edge b
+  c.edge e
+  b.edge a
+  d.edge c
+  e.edge d
+
+
+  let f = createNode('f')
+  b.edge f
+  e.edge f
+
+  let g = createNode('g')
+  let h = createNode('h')
+  let i = createNode('i')
+
+  f.edge g
+  f.edge i
+  g.edge h
+  h.edge i
+  i.edge g
+
+  let j = createNode('j')
+
+  h.edge j
+  i.edge j
+
+  let k = createNode('k')
+  let l = createNode('l')
+
+  f.edge k
+  k.edge l
+  l.edge k
+  k.edge j
+
+  let m = createNode('m')
+  let n = createNode('n')
+  let p = createNode('p')
+  let q = createNode('q')
+
+  m.edge n
+  n.edge p
+  n.edge q
+  q.edge p
+  p.edge m
+
+  q.edge k
+
+  d.edge m
+  e.edge n
+
+  result = a
+
+proc main2 =
+  let g = buildComplexGraph()
+
+main2()
+GC_fullCollect()
+echo "MEM ", getOccupiedMem()
diff --git a/tests/arc/tdeepcopy.nim b/tests/arc/tdeepcopy.nim
new file mode 100644
index 000000000..91d93aa28
--- /dev/null
+++ b/tests/arc/tdeepcopy.nim
@@ -0,0 +1,67 @@
+discard """
+  cmd: "nim c --gc:arc --deepcopy:on $file"
+  output: '''13 abc
+13 abc
+13 abc
+13 abc
+13 abc
+13 abc
+13 abc
+13 abc
+13 abc
+13 abc
+13 abc
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+called deepCopy for int
+0'''
+"""
+
+type
+  PBinaryTree = ref object of RootObj
+    le, ri: PBinaryTree
+    value: int
+
+proc mainB =
+  var x: PBinaryTree
+  deepCopy(x, PBinaryTree(ri: PBinaryTree(le: PBinaryTree(value: 13))))
+
+  var y: string
+  deepCopy y, "abc"
+  echo x.ri.le.value, " ", y
+
+for i in 0..10:
+  mainB()
+
+
+type
+  Bar[T] = object
+    x: T
+
+proc `=deepCopy`[T](b: ref Bar[T]): ref Bar[T] =
+  result.new
+  result.x = b.x
+  when T is int:
+    echo "called deepCopy for int"
+  else:
+    echo "called deepCopy for something else"
+
+proc main =
+  var dummy, c: ref Bar[int]
+  new(dummy)
+  dummy.x = 44
+
+  deepCopy c, dummy
+
+for i in 0..10:
+  main()
+
+echo getOccupiedMem()
diff --git a/tests/arc/tdestroy_in_loopcond.nim b/tests/arc/tdestroy_in_loopcond.nim
new file mode 100644
index 000000000..62532664d
--- /dev/null
+++ b/tests/arc/tdestroy_in_loopcond.nim
@@ -0,0 +1,74 @@
+discard """
+  output: '''400 true'''
+  cmd: "nim c --gc:orc $file"
+"""
+
+type HeapQueue*[T] = object
+  data: seq[T]
+
+
+proc len*[T](heap: HeapQueue[T]): int {.inline.} =
+  heap.data.len
+
+proc `[]`*[T](heap: HeapQueue[T], i: Natural): T {.inline.} =
+  heap.data[i]
+
+proc push*[T](heap: var HeapQueue[T], item: T) =
+  heap.data.add(item)
+
+proc pop*[T](heap: var HeapQueue[T]): T =
+  result = heap.data.pop
+
+proc clear*[T](heap: var HeapQueue[T]) = heap.data.setLen 0
+
+
+type
+  Future = ref object of RootObj
+    s: string
+    callme: proc()
+
+var called = 0
+
+proc consume(f: Future) =
+  inc called
+
+proc newFuture(s: string): Future =
+  var r: Future
+  r = Future(s: s, callme: proc() =
+    consume r)
+  result = r
+
+var q: HeapQueue[tuple[finishAt: int64, fut: Future]]
+
+proc sleep(f: int64): Future =
+  q.push (finishAt: f, fut: newFuture("async-sleep"))
+
+proc processTimers =
+  # Pop the timers in the order in which they will expire (smaller `finishAt`).
+  var count = q.len
+  let t = high(int64)
+  while count > 0 and t >= q[0].finishAt:
+    q.pop().fut.callme()
+    dec count
+
+var futures: seq[Future]
+
+proc main =
+  for i in 1..200:
+    futures.add sleep(56020904056300)
+    futures.add sleep(56020804337500)
+    #futures.add sleep(2.0)
+
+    #futures.add sleep(4.0)
+
+    processTimers()
+    #q.pop()[1].callme()
+    #q.pop()[1].callme()
+
+    futures.setLen 0
+
+  q.clear()
+
+main()
+GC_fullCollect()
+echo called, " ", getOccupiedMem() < 160
diff --git a/tests/arc/tdup.nim b/tests/arc/tdup.nim
new file mode 100644
index 000000000..61f262a68
--- /dev/null
+++ b/tests/arc/tdup.nim
@@ -0,0 +1,71 @@
+discard """
+  cmd: "nim c --mm:arc --expandArc:foo --hints:off $file"
+  nimout: '''
+--expandArc: foo
+
+var
+  x
+  :tmpD
+  s
+  :tmpD_1
+x = Ref(id: 8)
+inc:
+  :tmpD = `=dup`(x)
+  :tmpD
+inc:
+  let blitTmp = x
+  blitTmp
+var id_1 = 777
+s = RefCustom(id_2: addr(id_1))
+inc_1 :
+  :tmpD_1 = `=dup_1`(s)
+  :tmpD_1
+inc_1 :
+  let blitTmp_1 = s
+  blitTmp_1
+-- end of expandArc ------------------------
+'''
+"""
+
+type
+  Ref = ref object
+    id: int
+
+  RefCustom = object
+    id: ptr int
+
+proc `=dup`(x: RefCustom): RefCustom =
+  result.id = x.id
+
+proc inc(x: sink Ref) =
+  inc x.id
+
+proc inc(x: sink RefCustom) =
+  inc x.id[]
+
+
+proc foo =
+  var x = Ref(id: 8)
+  inc(x)
+  inc(x)
+  var id = 777
+  var s = RefCustom(id: addr id)
+  inc s
+  inc s
+
+foo()
+
+proc foo2 =
+  var x = Ref(id: 8)
+  inc(x)
+  doAssert x.id == 9
+  inc(x)
+  doAssert x.id == 10
+  var id = 777
+  var s = RefCustom(id: addr id)
+  inc s
+  doAssert s.id[] == 778
+  inc s
+  doAssert s.id[] == 779
+
+foo2()
diff --git a/tests/arc/testfile.txt b/tests/arc/testfile.txt
new file mode 100644
index 000000000..5169490be
--- /dev/null
+++ b/tests/arc/testfile.txt
@@ -0,0 +1,2 @@
+1 x
+2 y
diff --git a/tests/arc/texceptions.nim b/tests/arc/texceptions.nim
new file mode 100644
index 000000000..c55b463fc
--- /dev/null
+++ b/tests/arc/texceptions.nim
@@ -0,0 +1,16 @@
+discard """
+  cmd: "nim cpp --gc:arc $file"
+"""
+
+block: # issue #13071
+  type MyExcept = object of CatchableError
+  proc gun()=
+    raise newException(MyExcept, "foo:")
+  proc fun()=
+    var a = ""
+    try:
+      gun()
+    except Exception as e:
+      a = e.msg & $e.name # was segfaulting here for `nim cpp --gc:arc`
+    doAssert a == "foo:MyExcept"
+  fun()
diff --git a/tests/arc/texplicit_sink.nim b/tests/arc/texplicit_sink.nim
new file mode 100644
index 000000000..4b021ed62
--- /dev/null
+++ b/tests/arc/texplicit_sink.nim
@@ -0,0 +1,29 @@
+discard """
+  output: '''de'''
+  cmd: '''nim c --mm:arc --expandArc:main $file'''
+  nimout: '''--expandArc: main
+
+var
+  a
+  b_cursor
+try:
+  a = f "abc"
+  b_cursor = "de"
+  `=sink`(a, b_cursor)
+  echo [a]
+finally:
+  `=destroy`(a)
+-- end of expandArc ------------------------'''
+"""
+
+# bug #20572
+
+proc f(s: string): string = s
+
+proc main =
+  var a = f "abc"
+  var b = "de"
+  `=sink`(a, b)
+  echo a
+
+main()
diff --git a/tests/arc/tfuncobj.nim b/tests/arc/tfuncobj.nim
new file mode 100644
index 000000000..50cd9425e
--- /dev/null
+++ b/tests/arc/tfuncobj.nim
@@ -0,0 +1,38 @@
+discard """
+  outputsub: '''f1
+f2
+f3'''
+  cmd: "nim c --gc:orc $file"
+  valgrind: true
+"""
+
+type
+  FuncObj = object
+    fn: proc (env: pointer) {.cdecl.}
+    env: pointer
+
+proc `=destroy`(x: var FuncObj) =
+  GC_unref(cast[RootRef](x.env))
+
+proc `=copy`(x: var FuncObj, y: FuncObj) {.error.}
+
+# bug #18433
+
+proc main =
+  var fs: seq[FuncObj]
+
+  proc wrap(p: proc()) =
+    proc closeOver() = p()
+    let env = rawEnv closeOver
+    GC_ref(cast[RootRef](env))
+    fs.add(FuncObj(fn: cast[proc(env: pointer){.cdecl.}](rawProc closeOver), env: env))
+
+  wrap(proc() {.closure.} = echo "f1")
+  wrap(proc() {.closure.} = echo "f2")
+  wrap(proc() {.closure.} = echo "f3")
+
+  for a in fs:
+    a.fn(a.env)
+
+main()
+
diff --git a/tests/arc/thamming_orc.nim b/tests/arc/thamming_orc.nim
new file mode 100644
index 000000000..777efb38e
--- /dev/null
+++ b/tests/arc/thamming_orc.nim
@@ -0,0 +1,155 @@
+discard """
+  output: '''(allocCount: 1114, deallocCount: 1112)
+created 491 destroyed 491'''
+  cmd: "nim c --gc:orc -d:nimAllocStats $file"
+"""
+
+# bug #18421
+
+# test Nim Hamming Number Lazy List algo with reference counts and not...
+# compile with "-d:release -d:danger" and test with various
+# memory managment GC's, allocators, threading, etc.
+# it should be guaranteed to work with zero memory leaks with `--gc:orc`...
+
+# compile with `-d:trace20` to trace creation and destruction of first 20 values.
+
+from math import log2
+
+# implement our own basic BigInt so the bigints library isn't necessary...
+type
+  BigInt = object
+    digits: seq[uint32]
+let zeroBigInt = BigInt(digits: @[ 0'u32 ])
+let oneBigInt = BigInt(digits: @[ 1'u32 ])
+
+proc shladd(bi: var BigInt; n: int; a: BigInt) =
+  # assume that both `bi` and `a` are sized correctly with
+  # msuint32 for both not containing a zero
+  let alen = a.digits.len
+  let mx = max(bi.digits.len, a.digits.len)
+  for i in bi.digits.len ..< mx: bi.digits.add 0'u32
+  var cry = 0'u64
+  for i in 0 ..< alen:
+    cry += (bi.digits[i].uint64 shl n) + a.digits[i].uint64
+    bi.digits[i] = cry.uint32; cry = cry shr 32
+  for i in alen ..< mx:
+    cry += bi.digits[i].uint64 shl n
+    bi.digits[i] = cry.uint32; cry = cry shr 32
+  if cry > 0'u64:
+    bi.digits.add cry.uint32
+
+proc `$`(x: BigInt): string =
+  if x.digits.len == 0 or (x.digits.len == 1 and x.digits[0] == 0'u32):
+    return "0"
+  result = ""; var n = x; var msd = n.digits.high
+  while msd >= 0:
+    if n.digits[msd] == 0'u32: msd.dec; continue
+    var brw = 0.uint64
+    for i in countdown(msd, 0):
+      let dvdnd = n.digits[i].uint64 + (brw shl 32)
+      let q = dvdnd div 10'u64; brw = dvdnd - q * 10'u64
+      n.digits[i] = q.uint32
+    result &= $brw
+  for i in 0 .. result.high shr 1: # reverse result string in place
+    let tmp = result[^(i + 1)]
+    result[^(i + 1)] = result[i]
+    result[i] = tmp
+
+type TriVal = (uint32, uint32, uint32)
+type LogRep = (float64, TriVal)
+type LogRepf = proc(x: LogRep): LogRep
+const one: LogRep = (0.0'f64, (0'u32, 0'u32, 0'u32))
+proc `<`(me: LogRep, othr: LogRep): bool = me[0] < othr[0]
+
+proc convertTriVal2BigInt(tpl: TriVal): BigInt =
+  result = oneBigInt
+  let (x2, x3, x5) = tpl
+  for _ in 1 .. x2: result.shladd 1, zeroBigInt
+  for _ in 1 .. x3: result.shladd 1, result
+  for _ in 1 .. x5: result.shladd 2, result
+
+const lb2 = 1.0'f64
+const lb3 = 3.0'f64.log2
+const lb5 = 5.0'f64.log2
+
+proc mul2(me: LogRep): LogRep =
+  let (lr, tpl) = me; let (x2, x3, x5) = tpl
+  (lr + lb2, (x2 + 1, x3, x5))
+
+proc mul3(me: LogRep): LogRep =
+  let (lr, tpl) = me; let (x2, x3, x5) = tpl
+  (lr + lb3, (x2, x3 + 1, x5))
+
+proc mul5(me: LogRep): LogRep =
+  let (lr, tpl) = me; let (x2, x3, x5) = tpl
+  (lr + lb5, (x2, x3, x5 + 1))
+
+type
+  LazyListObj = object
+    hd: LogRep
+    tlf: proc(): LazyList {.closure.}
+    tl: LazyList
+  LazyList = ref LazyListObj
+
+var destroyed = 0
+
+proc `=destroy`(ll: var LazyListObj) =
+  destroyed += 1
+  if ll.tlf == nil and ll.tl == nil: return
+
+  when defined(trace20):
+    echo "destroying:  ", (destroyed, ll.hd[1].convertTriVal2BigInt)
+  if ll.tlf != nil: ll.tlf.`=destroy`
+  if ll.tl != nil: ll.tl.`=destroy`
+  #wasMoved(ll)
+
+proc rest(ll: LazyList): LazyList = # not thread-safe; needs lock on thunk
+  if ll.tlf != nil: ll.tl = ll.tlf(); ll.tlf = nil
+  ll.tl
+
+var created = 0
+iterator hammings(until: int): TriVal =
+  proc merge(x, y: LazyList): LazyList =
+    let xh = x.hd; let yh = y.hd; created += 1
+    when defined(trace20):
+      echo "merge create:  ", (created - 1, (if xh < yh: xh else: yh)[1].convertTriVal2BigInt)
+    if xh < yh: LazyList(hd: xh, tlf: proc(): auto = merge x.rest, y)
+    else: LazyList(hd: yh, tlf: proc(): auto = merge x, y.rest)
+  proc smult(mltf: LogRepf; s: LazyList): LazyList =
+    proc smults(ss: LazyList): LazyList =
+      when defined(trace20):
+        echo "mult create:  ", (created, ss.hd.mltf[1].convertTriVal2BigInt)
+      created += 1; LazyList(hd: ss.hd.mltf, tlf: proc(): auto = ss.rest.smults)
+    s.smults
+  proc unnsm(s: LazyList, mltf: LogRepf): LazyList =
+    var r: LazyList = nil
+    when defined(trace20):
+      echo "first create:  ", (created, one[1].convertTriVal2BigInt)
+    let frst = LazyList(hd: one, tlf: proc(): LazyList = r); created += 1
+    r = if s == nil: smult(mltf, frst) else: s.merge smult(mltf, frst)
+    r
+  yield one[1]
+  var hmpll: LazyList = ((nil.unnsm mul5).unnsm mul3).unnsm mul2
+  for _ in 2 .. until:
+    yield hmpll.hd[1]; hmpll = hmpll.rest # almost forever
+
+proc main =
+  var s = ""
+  for h in hammings(20): s &= $h.convertTrival2BigInt & " "
+  doAssert s == "1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 ",
+           "Algorithmic error finding first 20 Hamming numbers!!!"
+
+  when not defined(trace20):
+    var lsth: TriVal
+    for h in hammings(200): lsth = h
+    doAssert $lsth.convertTriVal2BigInt == "16200",
+             "Algorithmic error finding 200th Hamming number!!!"
+
+let mem = getOccupiedMem()
+main()
+GC_FullCollect()
+let mb = getOccupiedMem() - mem
+doAssert mb == 0, "Found memory leak of " & $mb & " bytes!!!"
+
+echo getAllocStats()
+echo "created ", created, " destroyed ", destroyed
diff --git a/tests/arc/thamming_thinout.nim b/tests/arc/thamming_thinout.nim
new file mode 100644
index 000000000..65c34ef49
--- /dev/null
+++ b/tests/arc/thamming_thinout.nim
@@ -0,0 +1,183 @@
+discard """
+  cmd: "nim c --gc:orc -d:nimThinout -r $file"
+  output: '''The first 20 hammings are:  1 2 3 4 5 MEM IS 0'''
+"""
+
+# test Nim Hamming Number Lazy List algo with reference counts and not...
+# compile with "-d:release -d:danger" and test with various
+# memory managment GC's, allocators, threading, etc.
+
+from times import epochTime
+from math import log2
+
+# implement our own basic BigInt so the bigints library isn't necessary...
+type
+  BigInt = object
+    digits: seq[uint32]
+let zeroBigInt = BigInt(digits: @[ 0'u32 ])
+let oneBigInt = BigInt(digits: @[ 1'u32 ])
+
+proc shladd(bi: var BigInt; n: int; a: BigInt) =
+  var cry = 0'u64
+  for i in 0 ..< min(bi.digits.len, a.digits.len):
+    cry += (bi.digits[i].uint64 shl n) + a.digits[i].uint64
+    bi.digits[i] = cry.uint32
+    cry = cry shr 32
+  if cry > 0'u64:
+    bi.digits.add cry.uint32
+
+proc `$`(x: BigInt): string =
+  if x.digits.len == 0 or (x.digits.len == 1 and x.digits[0] == 0'u32):
+    return "0"
+  var n = x
+  var msd = n.digits.high
+  result = ""
+  while msd >= 0:
+    if n.digits[msd] == 0'u32: msd.dec; continue
+    var brw = 0.uint64
+    for i in countdown(msd, 0):
+      let dvdnd = n.digits[i].uint64 + (brw shl 32)
+      let q = dvdnd div 10'u64; brw = dvdnd - q*10'u64; n.digits[i] = q.uint32
+    result &= $brw
+  for i in 0 .. result.high shr 1:
+    let tmp = result[^(i + 1)]
+    result[^(i + 1)] = result[i]
+    result[i] = tmp
+
+proc convertTrival2BigInt(tpl: (uint32, uint32, uint32)): BigInt =
+  result = oneBigInt
+  let (x2, x3, x5) = tpl
+  for _ in 1 .. x2: result.shladd 1, zeroBigInt
+  for _ in 1 .. x3: result.shladd 1, result
+  for _ in 1 .. x5: result.shladd 2, result
+
+type LogRep = (float64, (uint32, uint32, uint32))
+type LogRepf = proc(x: LogRep): LogRep
+const one: LogRep = (0.0f64, (0u32, 0u32, 0u32))
+proc `<`(me: LogRep, othr: LogRep): bool = me[0] < othr[0]
+
+const lb2 = 1.0'f64
+const lb3 = 3.0'f64.log2
+const lb5 = 5.0'f64.log2
+
+proc mul2(me: LogRep): LogRep =
+  let (lr, tpl) = me; let (x2, x3, x5) = tpl
+  (lr + lb2, (x2 + 1, x3, x5))
+
+proc mul3(me: LogRep): LogRep =
+  let (lr, tpl) = me; let (x2, x3, x5) = tpl
+  (lr + lb3, (x2, x3 + 1, x5))
+
+proc mul5(me: LogRep): LogRep =
+  let (lr, tpl) = me; let (x2, x3, x5) = tpl
+  (lr + lb5, (x2, x3, x5 + 1))
+
+type
+  LazyList = ref object
+    hd: LogRep
+    tlf: proc(): LazyList {.closure.}
+    tl: LazyList
+
+proc rest(ll: LazyList): LazyList = # not thread-safe; needs lock on thunk
+  if ll.tlf != nil:
+    ll.tl = ll.tlf()
+    ll.tlf = nil
+  ll.tl
+
+iterator hamming(until: int): (uint32, uint32, uint32) =
+  proc merge(x, y: LazyList): LazyList =
+    let xh = x.hd
+    let yh = y.hd
+    if xh < yh: LazyList(hd: xh, tlf: proc(): auto = merge x.rest, y)
+    else: LazyList(hd: yh, tlf: proc(): auto = merge x, y.rest)
+  proc smult(mltf: LogRepf; s: LazyList): LazyList =
+    proc smults(ss: LazyList): LazyList =
+      LazyList(hd: ss.hd.mltf, tlf: proc(): auto = ss.rest.smults)
+    s.smults
+  proc unnsm(s: LazyList, mltf: LogRepf): LazyList =
+    var r: LazyList = nil
+    let frst = LazyList(hd: one, tlf: proc(): LazyList = r)
+    r = if s == nil: smult mltf, frst else: s.merge smult(mltf, frst)
+    r
+  var hmpll: LazyList = ((nil.unnsm mul5).unnsm mul3).unnsm mul2
+  #  var hmpll: LazyList = nil; for m in [mul5, mul3, mul2]: echo one.m # ; hmpll = unnsm(hmpll, m)
+  yield one[1]
+  var cnt = 1
+  while hmpll != nil:
+    yield hmpll.hd[1]
+    hmpll = hmpll.rest # almost forever
+    cnt.inc
+    if cnt > until: break
+  #when declared(thinout):
+  thinout(hmpll)
+
+proc main =
+  stdout.write "The first 20 hammings are:  "
+  for h in hamming(4):
+    write stdout, h.convertTrival2BigInt, " "
+
+  for h in hamming(200):
+    discard h.convertTrival2BigInt
+
+let mem = getOccupiedMem()
+main()
+echo "MEM IS ", getOccupiedMem() - mem
+
+#[
+result = (smults, :envP.:up)(rest(:envP.ss2))
+
+proc anon =
+  var
+    :tmpD_284230
+    :tmpD_284233
+    :tmpD_284236
+  try:
+    `=sink_283407`(result_283502,
+      `=sink_283927`(:tmpD_284236, (smults_283495,
+        wasMoved_284234(:tmpD_284233)
+        `=_284014`(:tmpD_284233, :envP_283898.:up_283899)
+        :tmpD_284233))
+      :tmpD_284236(
+      `=sink_283407`(:tmpD_284230, rest_283366(:envP_283898.ss2_-283497))
+      :tmpD_284230))
+  finally:
+    `=destroy_283914`(:tmpD_284236)
+    `=destroy_283388`(:tmpD_284230)
+
+proc smuls(ss: LazyList_283350; :envP_283891): LazyList_283350  =
+  var :env_283913
+  try:
+    `=destroy_283951`(:env_283913)
+    internalNew_43643(:env_283913)
+    `=_283401`(:env_283913.ss2_-283497, ss_283497)
+    :env_283913.:up_283899 = :envP_283891
+    `=sink_283407`(result_283498, LazyList_283350(hd_283353: :envP_283891.mltf1_-283492(
+        :env_283913.ss2_-283497.hd_283353), tlf_283356: (:anonymous_283499,
+      let blitTmp_284227 = :env_283913
+      wasMoved_284228(:env_283913)
+      blitTmp_284227)))
+  finally:
+    `=destroy_283951`(:env_283913)
+
+proc smul =
+  var
+    :env_283969
+    :tmpD_284220
+  try:
+    `=destroy_284008`(:env_283969)
+    internalNew_43643(:env_283969)
+    `=_283976`(:env_283969.mltf1_-283492, mltf_283492)
+    proc smults(ss: LazyList_283350; :envP_283891): LazyList_283350 =
+      result_283498 = LazyList_283350(hd_283353: mltf_283492(ss_283497.hd_283353), tlf_283356: proc (
+          :envP_283898): auto_43100 = result_283502 = smults_283495(rest_283366(ss_283497)))
+
+    `=sink_283407`(result_283494,
+      `=sink_283927`(:tmpD_284220, (smults_283495,
+        let blitTmp_284218 = :env_283969
+        wasMoved_284219(:env_283969)
+        blitTmp_284218))
+      :tmpD_284220(s_283493))
+  finally:
+    `=destroy_283914`(:tmpD_284220)
+    `=destroy_284008`(:env_283969)
+]#
diff --git a/tests/arc/thard_alignment.nim b/tests/arc/thard_alignment.nim
new file mode 100644
index 000000000..30cfddb05
--- /dev/null
+++ b/tests/arc/thard_alignment.nim
@@ -0,0 +1,148 @@
+discard """
+disabled: "arm64"
+cmd: "nim c --mm:arc -u:nimPreviewNonVarDestructor $file"
+output: "y"
+"""
+
+# TODO: fixme: investigate why it failed with non-var destructors
+
+{.passC: "-march=native".}
+
+proc isAlignedCheck(p: pointer, alignment: int) = 
+  doAssert (cast[uint](p) and uint(alignment - 1)) == 0
+
+proc isAlignedCheck[T](p: ref T, alignment: int) = 
+  isAlignedCheck(cast[pointer](p), alignment)
+
+type
+  m256d {.importc: "__m256d", header: "immintrin.h".} = object
+
+proc set1(x: float): m256d {.importc: "_mm256_set1_pd", header: "immintrin.h".}
+func `+`(a,b: m256d): m256d {.importc: "_mm256_add_pd", header: "immintrin.h".}
+proc `$`(a: m256d): string =  
+  result = $(cast[ptr float](a.addr)[])
+
+
+var res: seq[seq[m256d]]
+
+for _ in 1..1000:
+  var x = newSeq[m256d](1)
+  x[0] = set1(1.0) # test if operation causes segfault
+  isAlignedCheck(x[0].addr, alignof(m256d))
+  res.add x
+
+var res2: seq[m256d]
+for i in 1..10000:
+  res2.setLen(res2.len + 1) # check if realloc works
+  isAlignedCheck(res2[0].addr, alignof(m256d))  
+
+proc lambdaGen(a, b: float, z: ref m256d) : auto =
+  var x1 = new(m256d)
+  var x2 = new(m256d)
+  isAlignedCheck(x1, alignof(m256d))
+  isAlignedCheck(x2, alignof(m256d))
+  x1[] = set1(2.0 + a)  
+  x2[] = set1(-23.0 - b)
+  let capturingLambda = proc(x: ref m256d): ref m256d =
+    var cc = new(m256d)
+    var bb = new(m256d)
+    isAlignedCheck(x1, alignof(m256d))
+    isAlignedCheck(x2, alignof(m256d))
+    isAlignedCheck(cc, alignof(m256d))
+    isAlignedCheck(bb, alignof(m256d))
+    isAlignedCheck(z, alignof(m256d))
+        
+    cc[] = x1[] + x1[] + z[]
+    bb[] = x2[] + set1(12.5) + z[]
+    
+    result = new(m256d)
+    isAlignedCheck(result, alignof(m256d))
+    result[] = cc[] + bb[] + x[]
+    
+  return capturingLambda
+
+var xx = new(m256d)
+xx[] = set1(10)
+isAlignedCheck(xx, alignOf(m256d))
+
+let f1 = lambdaGen(2.0 , 2.221, xx)
+let f2 = lambdaGen(-1.226 , 3.5, xx)
+isAlignedCheck(f1(xx), alignOf(m256d))
+isAlignedCheck(f2(xx), alignOf(m256d))
+
+
+#-----------------------------------------------------------------------------
+
+type
+  MyAligned = object of RootObj
+    a{.align: 128.}: float
+
+
+var f: MyAligned
+isAlignedCheck(f.addr, MyAligned.alignOf)
+
+var fref = new(MyAligned)
+isAlignedCheck(fref, MyAligned.alignOf)
+
+var fs: seq[MyAligned]
+var fr: seq[RootRef]
+
+for i in 0..1000:
+  fs.add MyAligned()
+  isAlignedCheck(fs[^1].addr, MyAligned.alignOf)
+  fs[^1].a = i.float
+
+  fr.add new(MyAligned)
+  isAlignedCheck(fr[^1], MyAligned.alignOf)
+  ((ref MyAligned)fr[^1])[].a = i.float
+
+for i in 0..1000:
+  doAssert(fs[i].a == i.float)
+  doAssert(((ref MyAligned)fr[i]).a == i.float)
+
+
+proc lambdaTest2(a: MyAligned, z: ref MyAligned): auto =
+  var x1: MyAligned
+  x1.a = a.a + z.a  
+  var x2: MyAligned
+  x2.a = a.a - z.a
+  let capturingLambda = proc(x: MyAligned): MyAligned =
+    var cc: MyAligned
+    var bb: MyAligned
+    isAlignedCheck(x1.addr, MyAligned.alignOf)
+    isAlignedCheck(x2.addr, MyAligned.alignOf)
+    isAlignedCheck(cc.addr, MyAligned.alignOf)
+    isAlignedCheck(bb.addr, MyAligned.alignOf)
+    isAlignedCheck(z, MyAligned.alignOf)
+        
+    cc.a = x1.a + x1.a + z.a
+    bb.a = x2.a - z.a
+    
+    isAlignedCheck(result.addr, MyAligned.alignOf)
+    result.a = cc.a + bb.a + x2.a
+    
+  return capturingLambda
+
+
+let q1 = lambdaTest2(MyAligned(a: 1.0), (ref MyAligned)(a: 2.0))
+let q2 = lambdaTest2(MyAligned( a: -1.0), (ref MyAligned)(a: -2.0))
+
+isAlignedCheck(rawEnv(q1), MyAligned.alignOf)
+isAlignedCheck(rawEnv(q2), MyAligned.alignOf)
+discard q1(MyAligned(a: 1.0))
+discard q2(MyAligned(a: -1.0))
+
+
+#-----------------------------------------------------------------------------
+
+block:
+  var s: seq[seq[MyAligned]]
+  for len in 0..128:
+    s.add newSeq[MyAligned](len)
+    for i in 0..<len:
+      s[^1][i] = MyAligned(a: 1.0)
+
+    if len > 0:
+      isAlignedCheck(s[^1][0].addr, MyAligned.alignOf)
+  
+echo "y"
diff --git a/tests/arc/thavlak_orc_stress.nim b/tests/arc/thavlak_orc_stress.nim
new file mode 100644
index 000000000..862e1a097
--- /dev/null
+++ b/tests/arc/thavlak_orc_stress.nim
@@ -0,0 +1,414 @@
+discard """
+  cmd: "nim c --gc:orc -d:useMalloc -d:nimStressOrc $file"
+  valgrind: "leaks"
+  output: "done"
+"""
+
+import tables
+import sets
+import net
+
+type
+  BasicBlock = object
+    inEdges: seq[ref BasicBlock]
+    outEdges: seq[ref BasicBlock]
+    name: int
+
+proc newBasicBlock(name: int): ref BasicBlock =
+  new(result)
+  result.inEdges = newSeq[ref BasicBlock]()
+  result.outEdges = newSeq[ref BasicBlock]()
+  result.name = name
+
+proc hash(x: ref BasicBlock): int {.inline.} =
+  result = x.name
+
+type
+  BasicBlockEdge = object
+    fr: ref BasicBlock
+    to: ref BasicBlock
+
+  Cfg = object
+    basicBlockMap: Table[int, ref BasicBlock]
+    edgeList: seq[BasicBlockEdge]
+    startNode: ref BasicBlock
+
+proc newCfg(): Cfg =
+  result.basicBlockMap = initTable[int, ref BasicBlock]()
+  result.edgeList = newSeq[BasicBlockEdge]()
+
+proc createNode(self: var Cfg, name: int): ref BasicBlock =
+  #var node: ref BasicBlock
+  result = self.basicBlockMap.getOrDefault(name)
+  if result == nil:
+    result = newBasicBlock(name)
+    self.basicBlockMap.add name, result
+
+  if self.startNode == nil:
+    self.startNode = result
+
+proc addEdge(self: var Cfg, edge: BasicBlockEdge) =
+  self.edgeList.add(edge)
+
+proc getNumNodes(self: Cfg): int =
+  self.basicBlockMap.len
+
+proc newBasicBlockEdge(cfg: var Cfg, fromName: int, toName: int) =
+  var newEdge = BasicBlockEdge()
+  newEdge.fr = cfg.createNode(fromName)
+  newEdge.to = cfg.createNode(toName)
+  newEdge.fr.outEdges.add(newEdge.to)
+  newEdge.to.inEdges.add(newEdge.fr)
+  cfg.addEdge(newEdge)
+
+type
+  SimpleLoop = object
+    basicBlocks: seq[ref BasicBlock] # TODO: set here
+    children: seq[ref SimpleLoop] # TODO: set here
+    parent: ref SimpleLoop
+    header: ref BasicBlock
+    isRoot: bool
+    isReducible: bool
+    counter: int
+    nestingLevel: int
+    depthLevel: int
+
+proc newSimpleLoop(): ref SimpleLoop =
+  new(result)
+  result.basicBlocks = newSeq[ref BasicBlock]()
+  result.children = newSeq[ref SimpleLoop]()
+  result.parent = nil
+  result.header = nil
+  result.isRoot = false
+  result.isReducible = true
+  result.counter = 0
+  result.nestingLevel = 0
+  result.depthLevel = 0
+
+proc addNode(self: ref SimpleLoop, bb: ref BasicBlock) =
+  self.basicBlocks.add bb
+
+proc addChildLoop(self: ref SimpleLoop, loop: ref SimpleLoop) =
+  self.children.add loop
+
+proc setParent(self: ref SimpleLoop, parent: ref SimpleLoop) =
+  self.parent = parent
+  self.parent.addChildLoop(self)
+
+proc setHeader(self: ref SimpleLoop, bb: ref BasicBlock) =
+  self.basicBlocks.add(bb)
+  self.header = bb
+
+proc setNestingLevel(self: ref SimpleLoop, level: int) =
+  self.nestingLevel = level
+  if level == 0: self.isRoot = true
+
+var loop_counter: int = 0
+
+type
+  Lsg = object
+    loops: seq[ref SimpleLoop]
+    root: ref SimpleLoop
+
+proc createNewLoop(self: var Lsg): ref SimpleLoop =
+  var s = newSimpleLoop()
+  loop_counter += 1
+  s.counter = loop_counter
+  s
+
+proc addLoop(self: var Lsg, l: ref SimpleLoop) =
+  self.loops.add l
+
+proc newLsg(): Lsg =
+  result.loops = newSeq[ref SimpleLoop]()
+  result.root = result.createNewLoop()
+  result.root.setNestingLevel(0)
+  result.addLoop(result.root)
+
+proc getNumLoops(self: Lsg): int =
+  self.loops.len
+
+type
+  UnionFindNode = object
+    parent: ref UnionFindNode
+    bb: ref BasicBlock
+    l: ref SimpleLoop
+    dfsNumber: int
+
+proc newUnionFindNode(): ref UnionFindNode =
+  new(result)
+  result.parent = nil
+  result.bb = nil
+  result.l = nil
+  result.dfsNumber = 0
+
+proc initNode(self: ref UnionFindNode, bb: ref BasicBlock, dfsNumber: int) =
+  self.parent = self
+  self.bb = bb
+  self.dfsNumber = dfsNumber
+
+proc findSet(self: ref UnionFindNode): ref UnionFindNode =
+  var nodeList = newSeq[ref UnionFindNode]()
+  var node = self
+
+  while node != node.parent:
+    var parent = node.parent
+    if parent != parent.parent: nodeList.add node
+    node = parent
+
+  for iter in nodeList: iter.parent = node.parent
+  node
+
+proc union(self: ref UnionFindNode, unionFindNode: ref UnionFindNode) =
+  self.parent = unionFindNode
+
+
+const
+  BB_NONHEADER    = 1 # a regular BB
+  BB_REDUCIBLE    = 2 # reducible loop
+  BB_SELF         = 3 # single BB loop
+  BB_IRREDUCIBLE  = 4 # irreducible loop
+  BB_DEAD         = 5 # a dead BB
+
+  # # Marker for uninitialized nodes.
+  UNVISITED = -1
+
+  # # Safeguard against pathologic algorithm behavior.
+  MAXNONBACKPREDS = (32 * 1024)
+
+type
+  HavlakLoopFinder = object
+    cfg: Cfg
+    lsg: Lsg
+
+proc newHavlakLoopFinder(cfg: sink Cfg, lsg: sink Lsg): HavlakLoopFinder =
+  result.cfg = cfg
+  result.lsg = lsg
+
+proc isAncestor(w: int, v: int, last: seq[int]): bool =
+  w <= v and v <= last[w]
+
+proc dfs(currentNode: ref BasicBlock, nodes: var seq[ref UnionFindNode], number: var Table[ref BasicBlock, int], last: var seq[int], current: int): int =
+  nodes[current].initNode(currentNode, current)
+  number[currentNode] = current
+
+  var lastid = current
+  for target in currentNode.outEdges:
+    if number[target] == UNVISITED:
+      lastid = dfs(target, nodes, number, last, lastid + 1)
+
+  last[number[currentNode]] = lastid
+  return lastid
+
+proc findLoops(self: var HavlakLoopFinder): int =
+  var startNode = self.cfg.startNode
+  if startNode == nil: return 0
+  var size = self.cfg.getNumNodes
+
+  var nonBackPreds = newSeq[HashSet[int]]()
+  var backPreds = newSeq[seq[int]]()
+  var number = initTable[ref BasicBlock, int]()
+  var header = newSeq[int](size)
+  var types = newSeq[int](size)
+  var last = newSeq[int](size)
+  var nodes = newSeq[ref UnionFindNode]()
+
+  for i in 1..size:
+    nonBackPreds.add initHashSet[int](1)
+    backPreds.add newSeq[int]()
+    nodes.add newUnionFindNode()
+
+  # Step a:
+  #   - initialize all nodes as unvisited.
+  #   - depth-first traversal and numbering.
+  #   - unreached BB's are marked as dead.
+  #
+  for v in self.cfg.basicBlockMap.values: number[v] = UNVISITED
+  discard dfs(startNode, nodes, number, last, 0)
+
+  # Step b:
+  #   - iterate over all nodes.
+  #
+  #   A backedge comes from a descendant in the DFS tree, and non-backedges
+  #   from non-descendants (following Tarjan).
+  #
+  #   - check incoming edges 'v' and add them to either
+  #     - the list of backedges (backPreds) or
+  #     - the list of non-backedges (nonBackPreds)
+  #
+  for w in 0 ..< size:
+    header[w] = 0
+    types[w]  = BB_NONHEADER
+
+    var nodeW = nodes[w].bb
+    if nodeW != nil:
+      for nodeV in nodeW.inEdges:
+        var v = number[nodeV]
+        if v != UNVISITED:
+          if isAncestor(w, v, last):
+            backPreds[w].add v
+          else:
+            nonBackPreds[w].incl v
+    else:
+      types[w] = BB_DEAD
+
+  # Start node is root of all other loops.
+  header[0] = 0
+
+  # Step c:
+  #
+  # The outer loop, unchanged from Tarjan. It does nothing except
+  # for those nodes which are the destinations of backedges.
+  # For a header node w, we chase backward from the sources of the
+  # backedges adding nodes to the set P, representing the body of
+  # the loop headed by w.
+  #
+  # By running through the nodes in reverse of the DFST preorder,
+  # we ensure that inner loop headers will be processed before the
+  # headers for surrounding loops.
+
+  for w in countdown(size - 1, 0):
+    # this is 'P' in Havlak's paper
+    var nodePool = newSeq[ref UnionFindNode]()
+
+    var nodeW = nodes[w].bb
+    if nodeW != nil: # dead BB
+      # Step d:
+      for v in backPreds[w]:
+        if v != w:
+          nodePool.add nodes[v].findSet
+        else:
+          types[w] = BB_SELF
+
+      # Copy nodePool to workList.
+      #
+      var workList = newSeq[ref UnionFindNode]()
+      for x in nodePool: workList.add x
+
+      if nodePool.len != 0: types[w] = BB_REDUCIBLE
+
+      # work the list...
+      #
+      while workList.len > 0:
+        var x = workList[0]
+        workList.del(0)
+
+        # Step e:
+        #
+        # Step e represents the main difference from Tarjan's method.
+        # Chasing upwards from the sources of a node w's backedges. If
+        # there is a node y' that is not a descendant of w, w is marked
+        # the header of an irreducible loop, there is another entry
+        # into this loop that avoids w.
+        #
+
+        # The algorithm has degenerated. Break and
+        # return in this case.
+        #
+        var nonBackSize = nonBackPreds[x.dfsNumber].len
+        if nonBackSize > MAXNONBACKPREDS: return 0
+
+        for iter in nonBackPreds[x.dfsNumber]:
+          var y = nodes[iter]
+          var ydash = y.findSet
+
+          if not isAncestor(w, ydash.dfsNumber, last):
+            types[w] = BB_IRREDUCIBLE
+            nonBackPreds[w].incl ydash.dfsNumber
+          else:
+            if ydash.dfsNumber != w and not nodePool.contains(ydash):
+              workList.add ydash
+              nodePool.add ydash
+
+      # Collapse/Unionize nodes in a SCC to a single node
+      # For every SCC found, create a loop descriptor and link it in.
+      #
+      if (nodePool.len > 0) or (types[w] == BB_SELF):
+        var l = self.lsg.createNewLoop
+
+        l.setHeader(nodeW)
+        l.isReducible = types[w] != BB_IRREDUCIBLE
+
+        # At this point, one can set attributes to the loop, such as:
+        #
+        # the bottom node:
+        #    iter  = backPreds(w).begin();
+        #    loop bottom is: nodes(iter).node;
+        #
+        # the number of backedges:
+        #    backPreds(w).size()
+        #
+        # whether this loop is reducible:
+        #    types(w) != BB_IRREDUCIBLE
+        #
+        nodes[w].l = l
+
+        for node in nodePool:
+          # Add nodes to loop descriptor.
+          header[node.dfsNumber] = w
+          node.union(nodes[w])
+
+          # Nested loops are not added, but linked together.
+          var node_l = node.l
+          if node_l != nil:
+            node_l.setParent(l)
+          else:
+            l.addNode(node.bb)
+
+        self.lsg.addLoop(l)
+
+  result = self.lsg.getNumLoops
+
+
+type
+  LoopTesterApp = object
+    cfg: Cfg
+    lsg: Lsg
+
+proc newLoopTesterApp(): LoopTesterApp =
+  result.cfg = newCfg()
+  result.lsg = newLsg()
+
+proc buildDiamond(self: var LoopTesterApp, start: int): int =
+  var bb0 = start
+  newBasicBlockEdge(self.cfg, bb0, bb0 + 1)
+  newBasicBlockEdge(self.cfg, bb0, bb0 + 2)
+  newBasicBlockEdge(self.cfg, bb0 + 1, bb0 + 3)
+  newBasicBlockEdge(self.cfg, bb0 + 2, bb0 + 3)
+  result = bb0 + 3
+
+proc buildConnect(self: var LoopTesterApp, start1: int, end1: int) =
+  newBasicBlockEdge(self.cfg, start1, end1)
+
+proc buildStraight(self: var LoopTesterApp, start: int, n: int): int =
+  for i in 0..n-1:
+    self.buildConnect(start + i, start + i + 1)
+  result = start + n
+
+proc buildBaseLoop(self: var LoopTesterApp, from1: int): int =
+  var header   = self.buildStraight(from1, 1)
+  var diamond1 = self.buildDiamond(header)
+  var d11      = self.buildStraight(diamond1, 1)
+  var diamond2 = self.buildDiamond(d11)
+  var footer   = self.buildStraight(diamond2, 1)
+
+  self.buildConnect(diamond2, d11)
+  self.buildConnect(diamond1, header)
+  self.buildConnect(footer, from1)
+  result = self.buildStraight(footer, 1)
+
+proc run(self: var LoopTesterApp) =
+  discard self.cfg.createNode(0)
+  discard self.buildBaseLoop(0)
+  discard self.cfg.createNode(1)
+  self.buildConnect(0, 2)
+
+  for i in 1..8:
+    # yes, it's 8 and it's correct.
+    var h = newHavlakLoopFinder(self.cfg, newLsg())
+    discard h.findLoops()
+
+  echo "done"
+
+var l = newLoopTesterApp()
+l.run()
diff --git a/tests/arc/theavy_recursion.nim b/tests/arc/theavy_recursion.nim
new file mode 100644
index 000000000..9813331f4
--- /dev/null
+++ b/tests/arc/theavy_recursion.nim
@@ -0,0 +1,43 @@
+discard """
+  output: "yay"
+  cmd: "nim c --gc:arc $file"
+"""
+
+# bug #15122
+
+import tables
+
+type
+  BENodeKind* = enum
+    tkEof,
+    tkBytes,
+    tkList,
+    tkDict
+
+  BENode* = object
+    case kind: BENodeKind
+    of tkBytes: strVal: string
+    of tkList: listVal: seq[BENode]
+    of tkDict: dictVal*: Table[string, BENode]
+    else:
+      discard
+
+proc unused(s: string): BENode =
+  # bad:
+  result = BENode(kind: tkBytes, strVal: "abc")
+
+proc main =
+  var data = {
+    "examples": {
+      "values": BENode(
+        kind: tkList,
+        listVal: @[BENode(kind: tkBytes, strVal: "test")]
+      )
+    }.toTable()
+  }.toTable()
+
+  # For ARC listVal is empty for some reason
+  doAssert data["examples"]["values"].listVal[0].strVal == "test"
+
+main()
+echo "yay"
diff --git a/tests/arc/timportedobj.nim b/tests/arc/timportedobj.nim
new file mode 100644
index 000000000..9a88a9468
--- /dev/null
+++ b/tests/arc/timportedobj.nim
@@ -0,0 +1,14 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+  action: "compile"
+"""
+
+# bug #13269
+
+import posix
+proc foo*() =
+  var last = newSeq[Stat]()
+  var next = last
+  for i in 0..3:
+    last = next
+foo()
diff --git a/tests/arc/titeration_doesnt_copy.nim b/tests/arc/titeration_doesnt_copy.nim
new file mode 100644
index 000000000..e510a6eff
--- /dev/null
+++ b/tests/arc/titeration_doesnt_copy.nim
@@ -0,0 +1,67 @@
+discard """
+  output: "true"
+"""
+
+type
+  Idx = object
+    i: int
+  Node = object
+    n: int
+    next: seq[Idx]
+  FooBar = object
+    s: seq[Node]
+
+proc `=copy`(dest: var Idx; source: Idx) {.error.}
+proc `=copy`(dest: var Node; source: Node) {.error.}
+proc `=copy`(dest: var FooBar; source: FooBar) {.error.}
+
+proc doSomething(ss: var seq[int], s: FooBar) =
+  for i in 0 .. s.s.len-1:
+    for elm in items s.s[i].next:
+      ss.add s.s[elm.i].n
+
+when isMainModule:
+  const foo = FooBar(s: @[Node(n: 1, next: @[Idx(i: 0)])])
+  var ss: seq[int]
+  doSomething(ss, foo)
+  echo ss == @[1]
+
+from sequtils import mapIt
+from strutils import join
+
+proc toBinSeq*(b: uint8): seq[uint8] =
+  ## Return binary sequence from each bits of uint8.
+  runnableExamples:
+    from sequtils import repeat
+    doAssert 0'u8.toBinSeq == 0'u8.repeat(8)
+    doAssert 0b1010_1010.toBinSeq == @[1'u8, 0, 1, 0, 1, 0, 1, 0]
+  result = @[]
+  var c = b
+  for i in 1..8:
+    result.add (uint8(c and 0b1000_0000) shr 7)
+    c = c shl 1
+
+proc toBinString*(data: openArray[uint8], col: int): string =
+  ## Return binary string from each bits of uint8.
+  runnableExamples:
+    doAssert @[0b0000_1111'u8, 0b1010_1010].toBinString(8) == "0000111110101010"
+    doAssert @[0b1000_0000'u8, 0b0000_0000].toBinString(1) == "10"
+  result = ""
+  for b in items data.mapIt(it.toBinSeq.mapIt(it.`$`[0].char)):
+    for i, c in b:
+      if i < col:
+        result.add c
+
+doAssert @[0b0000_1111'u8, 0b1010_1010].toBinString(8) == "0000111110101010"
+doAssert @[0b1000_0000'u8, 0b0000_0000].toBinString(1) == "10"
+
+block: # bug #23982
+  iterator `..`(a, b: ptr int16): ptr int16 = discard
+  var a: seq[int16] #; let p = a[0].addr
+  var b: seq[ptr int16]
+
+  try:
+    for x in a[0].addr .. b[1]: # `p .. b[1]` works
+      discard
+  except IndexDefect:
+    discard
diff --git a/tests/arc/tkeys_lent.nim b/tests/arc/tkeys_lent.nim
new file mode 100644
index 000000000..2c92350b1
--- /dev/null
+++ b/tests/arc/tkeys_lent.nim
@@ -0,0 +1,17 @@
+discard """
+  output: '''{"string": 2}'''
+  cmd: "nim c --gc:orc $file"
+"""
+
+import tables
+
+proc use(x: int) = echo x
+
+proc main =
+  var tab = {"string": 1}.toTable
+  for keyAAA in tab.keys():
+    template alias(): untyped = tab[keyAAA]
+    alias() = 2
+  echo tab
+
+main()
diff --git a/tests/arc/tmalloc.nim b/tests/arc/tmalloc.nim
new file mode 100644
index 000000000..1d72646c8
--- /dev/null
+++ b/tests/arc/tmalloc.nim
@@ -0,0 +1,16 @@
+discard """
+  matrix: "--mm:arc -d:useMalloc; --mm:arc"
+"""
+
+block: # bug #22058
+  template foo(): auto =
+    {.noSideEffect.}:
+      newSeq[byte](1)
+
+  type V = object
+    v: seq[byte]
+
+  proc bar(): V =
+    V(v: foo())
+
+  doAssert bar().v == @[byte(0)]
diff --git a/tests/arc/tmarshal.nim b/tests/arc/tmarshal.nim
new file mode 100644
index 000000000..f7ec6e2c5
--- /dev/null
+++ b/tests/arc/tmarshal.nim
@@ -0,0 +1,140 @@
+discard """
+  cmd: "nim c --gc:orc $file"
+  output: '''
+{"age": 12, "bio": "Я Cletus", "blob": [65, 66, 67, 128], "name": "Cletus"}
+true
+true
+alpha 100
+omega 200
+0'''
+"""
+
+import marshal
+
+template testit(x) = discard $$to[typeof(x)]($$x)
+
+var x: array[0..4, array[0..4, string]] = [
+  ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
+  ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
+  ["test", "1", "2", "3", "4"]]
+
+proc blockA =
+  testit(x)
+  var test2: tuple[name: string, s: int] = ("tuple test", 56)
+  testit(test2)
+
+blockA()
+
+type
+  TE = enum
+    blah, blah2
+
+  TestObj = object
+    test, asd: int
+    case test2: TE
+    of blah:
+      help: string
+    else:
+      discard
+
+  PNode = ref TNode
+  TNode = object
+    next, prev: PNode
+    data: string
+
+proc buildList(): PNode =
+  new(result)
+  new(result.next)
+  new(result.prev)
+  result.data = "middle"
+  result.next.data = "next"
+  result.prev.data = "prev"
+  result.next.next = result.prev
+  result.next.prev = result
+  result.prev.next = result
+  result.prev.prev = result.next
+
+proc blockB =
+  var test3: TestObj
+  test3.test = 42
+  test3.test2 = blah
+  testit(test3)
+
+  var test4: ref tuple[a, b: string]
+  new(test4)
+  test4.a = "ref string test: A"
+  test4.b = "ref string test: B"
+  testit(test4)
+
+  var test5 = @[(0,1),(2,3),(4,5)]
+  testit(test5)
+
+  var test7 = buildList()
+  testit(test7)
+
+  var test6: set[char] = {'A'..'Z', '_'}
+  testit(test6)
+
+blockB()
+
+# bug #1352
+
+type
+  Entity = object of RootObj
+    name: string
+
+  Person = object of Entity
+    age: int
+    bio: string
+    blob: string
+
+proc blockC =
+  var instance1 = Person(name: "Cletus", age: 12,
+                        bio: "Я Cletus",
+                        blob: "ABC\x80")
+  echo($$instance1)
+  echo(to[Person]($$instance1).bio == instance1.bio) # true
+  echo(to[Person]($$instance1).blob == instance1.blob) # true
+
+blockC()
+
+# bug 5757
+
+type
+  Something = object
+    x: string
+    y: int
+
+proc blockD =
+  var data1 = """{"x": "alpha", "y": 100}"""
+  var data2 = """{"x": "omega", "y": 200}"""
+
+  var r = to[Something](data1)
+
+  echo r.x, " ", r.y
+
+  r = to[Something](data2)
+
+  echo r.x, " ", r.y
+
+blockD()
+
+type
+  Foo = object
+    a1: string
+    a2: string
+    a3: seq[string]
+    a4: seq[int]
+    a5: seq[int]
+    a6: seq[int]
+
+proc blockE =
+  var foo = Foo(a2: "", a4: @[], a6: @[1])
+  foo.a6.setLen 0
+  doAssert $$foo == """{"a1": "", "a2": "", "a3": [], "a4": [], "a5": [], "a6": []}"""
+  testit(foo)
+
+blockE()
+
+GC_fullCollect()
+echo getOccupiedMem()
diff --git a/tests/arc/tmove_regression.nim b/tests/arc/tmove_regression.nim
new file mode 100644
index 000000000..7d9a867c3
--- /dev/null
+++ b/tests/arc/tmove_regression.nim
@@ -0,0 +1,22 @@
+discard """
+  output: '''/1/2
+/1
+/
+'''
+""""
+
+# bug #22001
+
+import std / [os, strutils]
+
+proc finOp2(path, name: string): (string, File) = # Find & open FIRST `name`
+  var current = path
+  while true:
+    if current.isRootDir: break # <- current=="" => current.isRootDir
+    current = current.parentDir
+    let dir = current
+    echo dir.replace('\\', '/')  # Commenting out try/except below hides bug
+    try: result[0] = dir/name; result[1] = open(result[0]); return
+    except CatchableError: discard
+
+discard finOp2("/1/2/3", "4")  # All same if this->inside a proc
diff --git a/tests/arc/tmovebug.nim b/tests/arc/tmovebug.nim
index 98f181b81..8ad7c955c 100644
--- a/tests/arc/tmovebug.nim
+++ b/tests/arc/tmovebug.nim
@@ -1,6 +1,116 @@
 discard """
   cmd: "nim c --gc:arc $file"
-  output: '''5'''
+  output: '''5
+(w: 5)
+(w: -5)
+c.text = hello
+c.text = hello
+p.text = hello
+p.toks = @["hello"]
+c.text = hello
+c[].text = hello
+pA.text = hello
+pA.toks = @["hello"]
+c.text = hello
+c.text = hello
+pD.text = hello
+pD.toks = @["hello"]
+c.text = hello
+c.text = hello
+pOD.text = hello
+pOD.toks = @["hello"]
+fff
+fff
+2
+fff
+fff
+2
+fff
+fff
+2
+mmm
+fff
+fff
+fff
+3
+mmm
+sink me (sink)
+assign me (not sink)
+sink me (not sink)
+sinked and not optimized to a bitcopy
+sinked and not optimized to a bitcopy
+sinked and not optimized to a bitcopy
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+100
+hey
+hey
+(a: "a", b: 2)
+ho
+(a: "b", b: 3)
+(b: "b", a: 2)
+ho
+(b: "a", a: 3)
+hey
+break
+break
+hey
+ho
+hey
+ho
+ho
+king
+live long; long live
+king
+hi
+try
+bye
+()
+()
+()
+1
+destroy
+1
+destroy
+1
+destroy
+copy (self-assign)
+1
+destroy
+1
+destroy
+1
+destroy
+destroy
+copy
+@[(f: 2), (f: 2), (f: 3)]
+destroy
+destroy
+destroy
+sink
+sink
+destroy
+copy
+(f: 1)
+destroy
+destroy
+part-to-whole assigment:
+sink
+(children: @[])
+destroy
+sink
+(children: @[])
+destroy
+copy
+destroy
+(f: 1)
+destroy
+'''
 """
 
 # move bug
@@ -62,3 +172,670 @@ proc main =
 
 main()
 echo destroyCounter
+
+# bug #13314
+
+type
+  O = object
+    v: int
+  R = ref object
+    w: int
+
+proc `$`(r: R): string = $r[]
+
+proc tbug13314 =
+  var t5 = R(w: 5)
+  var execute = proc () =
+    echo t5
+
+  execute()
+  t5.w = -5
+  execute()
+
+tbug13314()
+
+#-------------------------------------------------------------------------
+# bug #13368
+
+import strutils
+proc procStat() =
+  for line in @["a b", "c d", "e f"]:
+    let cols = line.splitWhitespace(maxSplit=1)
+    let x = cols[0]
+    let (nm, rest) = (cols[0], cols[1])
+procStat()
+
+
+# bug #14269
+
+import sugar, strutils
+
+type
+  Cursor = object
+    text: string
+  Parsed = object
+    text: string
+    toks: seq[string]
+
+proc tokenize(c: var Cursor): seq[string] =
+  dump c.text
+  return c.text.splitWhitespace()
+
+proc parse(): Parsed =
+  var c = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c.tokenize) # note: c.tokenized uses c.text
+
+let p = parse()
+dump p.text
+dump p.toks
+
+
+proc tokenizeA(c: ptr Cursor): seq[string] =
+  dump c[].text
+  return c[].text.splitWhitespace()
+
+proc parseA(): Parsed =
+  var c = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c.addr.tokenizeA) # note: c.tokenized uses c.text
+
+let pA = parseA()
+dump pA.text
+dump pA.toks
+
+
+proc tokenizeD(c: Cursor): seq[string] =
+  dump c.text
+  return c.text.splitWhitespace()
+
+proc parseD(): Parsed =
+  var c = cast[ptr Cursor](alloc0(sizeof(Cursor)))
+  c[] = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c[].tokenizeD) # note: c.tokenized uses c.text
+
+let pD = parseD()
+dump pD.text
+dump pD.toks
+
+# Bug would only pop up with owned refs
+proc tokenizeOD(c: Cursor): seq[string] =
+  dump c.text
+  return c.text.splitWhitespace()
+
+proc parseOD(): Parsed =
+  var c = new Cursor
+  c[] = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c[].tokenizeOD) # note: c.tokenized uses c.text
+
+let pOD = parseOD()
+dump pOD.text
+dump pOD.toks
+
+when false:
+  # Bug would only pop up with owned refs and implicit derefs, but since they don't work together..
+  {.experimental: "implicitDeref".}
+  proc tokenizeOHD(c: Cursor): seq[string] =
+    dump c.text
+    return c.text.splitWhitespace()
+
+  proc parseOHD(): Parsed =
+    var c = new Cursor
+    c[] = Cursor(text: "hello")
+    dump c.text
+    return Parsed(text: c.text, toks: c.tokenizeOHD) # note: c.tokenized uses c.text
+
+  let pOHD = parseOHD()
+  dump pOHD.text
+  dump pOHD.toks
+
+# bug #13456
+
+iterator combinations[T](s: openArray[T], k: int): seq[T] =
+  let n = len(s)
+  assert k >= 0 and k <= n
+  var pos = newSeq[int](k)
+  var current = newSeq[T](k)
+  for i in 0..k-1:
+    pos[k-i-1] = i
+  var done = false
+  while not done:
+    for i in 0..k-1:
+      current[i] = s[pos[k-i-1]]
+    yield current
+    var i = 0
+    while i < k:
+      pos[i] += 1
+      if pos[i] < n-i:
+        for j in 0..i-1:
+          pos[j] = pos[i] + i - j
+        break
+      i += 1
+    if i >= k:
+      break
+
+type
+  UndefEx = object of ValueError
+
+proc main2 =
+  var delayedSyms = @[1, 2, 3]
+  var unp: seq[int]
+  block myb:
+    for a in 1 .. 2:
+      if delayedSyms.len > a:
+        unp = delayedSyms
+        for t in unp.combinations(a + 1):
+          try:
+            var h = false
+            for k in t:
+              echo "fff"
+            if h: continue
+            if true:
+              raise newException(UndefEx, "forward declaration")
+            break myb
+          except UndefEx:
+            echo t.len
+        echo "mmm"
+
+main2()
+
+
+
+type ME = object
+  who: string
+
+proc `=`(x: var ME, y: ME) =
+  if y.who.len > 0: echo "assign ",y.who
+
+proc `=sink`(x: var ME, y: ME) =
+  if y.who.len > 0: echo "sink ",y.who
+
+var dump: ME
+template use(x) = dump = x
+template def(x) = x = dump
+
+var c = true
+
+proc shouldSink() =
+  var x = ME(who: "me (sink)")
+  use(x) # we analyse this
+  if c: def(x)
+  else: def(x)
+  use(x) # ok, with the [else] part.
+
+shouldSink()
+
+dump = ME()
+
+proc shouldNotSink() =
+  var x = ME(who: "me (not sink)")
+  use(x) # we analyse this
+  if c: def(x)
+  use(x) # Not ok without the '[else]'
+
+shouldNotSink()
+
+# bug #14568
+import os
+
+type O2 = object
+  s: seq[int]
+
+proc `=sink`(dest: var O2, src: O2) =
+  echo "sinked and not optimized to a bitcopy"
+
+var testSeq: O2
+
+proc update() =
+  # testSeq.add(0) # uncommenting this line fixes the leak
+  testSeq = O2(s: @[])
+  testSeq.s.add(0)
+
+for i in 1..3:
+  update()
+
+
+# bug #14961
+type
+  Foo = object
+    data: seq[int]
+
+proc initFoo(len: int): Foo =
+  result = (let s = newSeq[int](len); Foo(data: s) )
+
+var f = initFoo(2)
+echo initFoo(2)
+
+proc initFoo2(len: int) =
+  echo   if true:
+             let s = newSeq[int](len); Foo(data: s)
+         else:
+             let s = newSeq[int](len); Foo(data: s)
+
+initFoo2(2)
+
+proc initFoo3(len: int) =
+  echo (block:
+         let s = newSeq[int](len); Foo(data: s))
+
+initFoo3(2)
+
+proc initFoo4(len: int) =
+  echo (let s = newSeq[int](len); Foo(data: s))
+
+initFoo4(2)
+
+proc initFoo5(len: int) =
+  echo (case true
+        of true:
+          let s = newSeq[int](len); Foo(data: s)
+        of false:
+          let s = newSeq[int](len); Foo(data: s))
+
+initFoo5(2)
+
+proc initFoo6(len: int) =
+  echo (block:
+          try:
+            let s = newSeq[int](len); Foo(data: s)
+          finally: discard)
+
+initFoo6(2)
+
+proc initFoo7(len: int) =
+  echo (block:
+          try:
+            raise newException(CatchableError, "sup")
+            let s = newSeq[int](len); Foo(data: s)
+          except CatchableError:
+            let s = newSeq[int](len); Foo(data: s) )
+
+initFoo7(2)
+
+
+# bug #14902
+iterator zip[T](s: openArray[T]): (T, T) =
+  var i = 0
+  while i < 10:
+    yield (s[i mod 2], s[i mod 2 + 1])
+    inc i
+
+var lastMem = int.high
+
+proc leak =
+  const len = 10
+  var x = @[newString(len), newString(len), newString(len)]
+
+  var c = 0
+  for (a, b) in zip(x):
+    let newMem = getOccupiedMem()
+    assert newMem <= lastMem
+    lastMem = newMem
+    c += a.len
+  echo c
+
+leak()
+
+
+proc consume(a: sink string) = echo a
+
+proc weirdScopes =
+  if (let a = "hey"; a.len > 0):
+    echo a
+
+  while (let a = "hey"; a.len > 0):
+    echo a
+    break
+
+  var a = block: (a: "a", b: 2)
+  echo a
+  (discard; a) = (echo "ho"; (a: "b", b: 3))
+  echo a
+
+  var b = try: (b: "b", a: 2)
+          except: raise
+  echo b
+  (discard; b) = (echo "ho"; (b: "a", a: 3))
+  echo b
+
+  var s = "break"
+  consume((echo "hey"; s))
+  echo s
+
+  echo (block:
+          var a = "hey"
+          (echo "hey"; "ho"))
+
+  var b2 = "ho"
+  echo (block:
+          var a = "hey"
+          (echo "hey"; b2))
+  echo b2
+
+  type status = enum
+    alive
+
+  var king = "king"
+  echo (block:
+          var a = "a"
+          when true:
+            var b = "b"
+            case alive
+            of alive:
+              try:
+                var c = "c"
+                if true:
+                  king
+                else:
+                  "the abyss"
+              except:
+                echo "he ded"
+                "dead king")
+  echo "live long; long live"
+  echo king
+
+weirdScopes()
+
+
+# bug #14985
+proc getScope(): string =
+  if true:
+    return "hi"
+  else:
+    "else"
+
+echo getScope()
+
+proc getScope3(): string =
+  try:
+    "try"
+  except:
+    return "except"
+
+echo getScope3()
+
+proc getScope2(): string =
+  case true
+  of true:
+    return "bye"
+  else:
+    "else"
+
+echo getScope2()
+
+
+#--------------------------------------------------------------------
+#bug  #15609
+
+type
+  Wrapper = object
+    discard
+
+proc newWrapper(): ref Wrapper =
+  new(result)
+  result
+
+
+proc newWrapper2(a: int): ref Wrapper =
+  new(result)
+  if a > 0:
+    result
+  else:
+    new(Wrapper)
+
+
+let w1 = newWrapper()
+echo $w1[]
+
+let w2 = newWrapper2(1)
+echo $w2[]
+
+let w3 = newWrapper2(-1)
+echo $w3[]
+
+
+#--------------------------------------------------------------------
+#self-assignments
+
+# Self-assignments that are not statically determinable will get
+# turned into `=copy` calls as caseBracketExprCopy demonstrates.
+# (`=copy` handles self-assignments at runtime)
+
+type
+  OO = object
+    f: int
+  W = object
+    o: OO
+
+proc `=destroy`(x: var OO) =
+  if x.f != 0:
+    echo "destroy"
+    x.f = 0
+
+proc `=sink`(x: var OO, y: OO) =
+  `=destroy`(x)
+  echo "sink"
+  x.f = y.f
+
+proc `=copy`(x: var OO, y: OO) =
+  if x.f != y.f:
+    `=destroy`(x)
+    echo "copy"
+    x.f = y.f
+  else:
+    echo "copy (self-assign)"
+
+proc caseSym =
+  var o = OO(f: 1)
+  o = o # NOOP
+  echo o.f # "1"
+  # "destroy"
+
+caseSym()
+
+proc caseDotExpr =
+  var w = W(o: OO(f: 1))
+  w.o = w.o # NOOP
+  echo w.o.f # "1"
+  # "destroy"
+
+caseDotExpr()
+
+proc caseBracketExpr =
+  var w = [0: OO(f: 1)]
+  w[0] = w[0] # NOOP
+  echo w[0].f # "1"
+  # "destroy"
+
+caseBracketExpr()
+
+proc caseBracketExprCopy =
+  var w = [0: OO(f: 1)]
+  let i = 0
+  w[i] = w[0] # "copy (self-assign)"
+  echo w[0].f # "1"
+  # "destroy"
+
+caseBracketExprCopy()
+
+proc caseDotExprAddr =
+  var w = W(o: OO(f: 1))
+  w.o = addr(w.o)[] # NOOP
+  echo w.o.f # "1"
+  # "destroy"
+
+caseDotExprAddr()
+
+proc caseBracketExprAddr =
+  var w = [0: OO(f: 1)]
+  addr(w[0])[] = addr(addr(w[0])[])[] # NOOP
+  echo w[0].f # "1"
+  # "destroy"
+
+caseBracketExprAddr()
+
+proc caseNotAConstant =
+  var i = 0
+  proc rand: int =
+    result = i
+    inc i
+  var s = @[OO(f: 1), OO(f: 2), OO(f: 3)]
+  s[rand()] = s[rand()] # "destroy" "copy"
+  echo s # @[(f: 2), (f: 2), (f: 3)]
+
+caseNotAConstant()
+
+proc potentialSelfAssign(i: var int) =
+  var a: array[2, OO]
+  a[i] = OO(f: 1) # turned into a memcopy
+  a[1] = OO(f: 2)
+  a[i+1] = a[i] # This must not =sink, but =copy
+  inc i
+  echo a[i-1] # (f: 1)
+
+potentialSelfAssign (var xi = 0; xi)
+
+
+#--------------------------------------------------------------------
+echo "part-to-whole assigment:"
+
+type
+  Tree = object
+    children: seq[Tree]
+
+  TreeDefaultHooks = object
+    children: seq[TreeDefaultHooks]
+
+proc `=destroy`(x: var Tree) = echo "destroy"
+proc `=sink`(x: var Tree, y: Tree) = echo "sink"
+proc `=copy`(x: var Tree, y: Tree) = echo "copy"
+
+proc partToWholeSeq =
+  var t = Tree(children: @[Tree()])
+  t = t.children[0] # This should be sunk, but with the special transform (tmp = t.children[0]; wasMoved(0); `=sink`(t, tmp))
+
+  var tc = TreeDefaultHooks(children: @[TreeDefaultHooks()])
+  tc = tc.children[0] # Ditto; if this were sunk with the normal transform (`=sink`(t, t.children[0]); wasMoved(t.children[0]))
+  echo tc             #        then it would crash because t.children[0] does not exist after the call to `=sink`
+
+partToWholeSeq()
+
+proc partToWholeSeqRTIndex =
+  var i = 0
+  var t = Tree(children: @[Tree()])
+  t = t.children[i] # See comment in partToWholeSeq
+
+  var tc = TreeDefaultHooks(children: @[TreeDefaultHooks()])
+  tc = tc.children[i] # See comment in partToWholeSeq
+  echo tc
+
+partToWholeSeqRTIndex()
+
+type List = object
+  next: ref List
+
+proc `=destroy`(x: var List) = echo "destroy"
+proc `=sink`(x: var List, y: List) = echo "sink"
+proc `=copy`(x: var List, y: List) = echo "copy"
+
+proc partToWholeUnownedRef =
+  var t = List(next: new List)
+  t = t.next[] # Copy because t.next is not an owned ref, and thus t.next[] cannot be moved
+
+partToWholeUnownedRef()
+
+
+#--------------------------------------------------------------------
+# test that nodes that get copied during the transformation
+# (like dot exprs) don't loose their firstWrite/lastRead property
+
+type
+  OOO = object
+    initialized: bool
+
+  C = object
+    o: OOO
+
+proc `=destroy`(o: var OOO) =
+  doAssert o.initialized, "OOO was destroyed before initialization!"
+
+proc initO(): OOO =
+  OOO(initialized: true)
+
+proc initC(): C =
+  C(o: initO())
+
+proc pair(): tuple[a: C, b: C] =
+  result = (a: initC(), b: initC())# <- when firstWrite tries to find this node to start its analysis it fails, because injectdestructors uses copyTree/shallowCopy
+
+discard pair()
+
+
+# bug #17450
+proc noConsume(x: OO) {.nosinks.} = echo x
+
+proc main3 =
+  var i = 1
+  noConsume:
+    block:
+      OO(f: i)
+
+main3()
+
+# misc
+proc smoltest(x: bool): bool =
+  while true:
+    if true: return x
+
+discard smoltest(true)
+
+# bug #18002
+type
+  TTypeAttachedOp = enum
+    attachedAsgn
+    attachedSink
+    attachedTrace
+
+  PNode = ref object
+    discard
+
+proc genAddrOf(n: PNode) =
+  assert n != nil, "moved?!"
+
+proc atomicClosureOp =
+  let x = PNode()
+
+  genAddrOf:
+    block:
+      x
+
+  case attachedTrace
+  of attachedSink: discard
+  of attachedAsgn: discard
+  of attachedTrace: genAddrOf(x)
+
+atomicClosureOp()
+
+
+template assertEq(a, b: untyped): untyped =
+  block:
+    let
+      aval = a
+      bval = b
+
+    if aval != bval:
+      quit "bug!"
+
+proc convoluted =
+  let _ = (;
+    var val1: string;
+    if true: val1 = "22"
+    true
+  )
+
+  assertEq val1, "22"
+  assertEq val1, "22"
+
+convoluted()
diff --git a/tests/arc/tmovebugcopy.nim b/tests/arc/tmovebugcopy.nim
new file mode 100644
index 000000000..ec4315777
--- /dev/null
+++ b/tests/arc/tmovebugcopy.nim
@@ -0,0 +1,526 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+  output: '''5
+(w: 5)
+(w: -5)
+c.text = hello
+c.text = hello
+p.text = hello
+p.toks = @["hello"]
+c.text = hello
+c[].text = hello
+pA.text = hello
+pA.toks = @["hello"]
+c.text = hello
+c.text = hello
+pD.text = hello
+pD.toks = @["hello"]
+c.text = hello
+c.text = hello
+pOD.text = hello
+pOD.toks = @["hello"]
+fff
+fff
+2
+fff
+fff
+2
+fff
+fff
+2
+mmm
+fff
+fff
+fff
+3
+mmm
+sink me (sink)
+assign me (not sink)
+sink me (not sink)
+sinked and not optimized to a bitcopy
+sinked and not optimized to a bitcopy
+sinked and not optimized to a bitcopy
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+(data: @[0, 0])
+100
+hey
+hey
+(a: "a", b: 2)
+ho
+(a: "b", b: 3)
+(b: "b", a: 2)
+ho
+(b: "a", a: 3)
+hey
+break
+break
+hey
+ho
+hey
+ho
+ho
+king
+live long; long live
+king
+hi
+try
+bye
+'''
+"""
+
+# move bug
+type
+  TMyObj = object
+    p: pointer
+    len: int
+
+var destroyCounter = 0
+
+proc `=destroy`(o: var TMyObj) =
+  if o.p != nil:
+    dealloc o.p
+    o.p = nil
+    inc destroyCounter
+
+proc `=copy`(dst: var TMyObj, src: TMyObj) =
+  `=destroy`(dst)
+  dst.p = alloc(src.len)
+  dst.len = src.len
+
+proc `=sink`(dst: var TMyObj, src: TMyObj) =
+  `=destroy`(dst)
+  dst.p = src.p
+  dst.len = src.len
+
+type
+  TObjKind = enum Z, A, B
+  TCaseObj = object
+    case kind: TObjKind
+    of Z: discard
+    of A:
+      x1: int # this int plays important role
+      x2: TMyObj
+    of B:
+      y: TMyObj
+
+proc use(a: TCaseObj) = discard
+
+proc moveBug(i: var int) =
+  var a: array[2, TCaseObj]
+  a[i] = TCaseObj(kind: A, x1: 5000, x2: TMyObj(len: 5, p: alloc(5))) # 1
+  a[i+1] = a[i] # 2
+  inc i
+  use(a[i-1])
+
+var x = 0
+moveBug(x)
+
+proc moveBug2(): (TCaseObj, TCaseObj) =
+  var a: array[2, TCaseObj]
+  a[0] = TCaseObj(kind: A, x1: 5000, x2: TMyObj(len: 5, p: alloc(5)))
+  a[1] = a[0] # can move 3
+  result[0] = TCaseObj(kind: A, x1: 5000, x2: TMyObj(len: 5, p: alloc(5))) # 4
+  result[1] = result[0] # 5
+
+proc main =
+  discard moveBug2()
+
+main()
+echo destroyCounter
+
+# bug #13314
+
+type
+  O = object
+    v: int
+  R = ref object
+    w: int
+
+proc `$`(r: R): string = $r[]
+
+proc tbug13314 =
+  var t5 = R(w: 5)
+  var execute = proc () =
+    echo t5
+
+  execute()
+  t5.w = -5
+  execute()
+
+tbug13314()
+
+#-------------------------------------------------------------------------
+# bug #13368
+
+import strutils
+proc procStat() =
+  for line in @["a b", "c d", "e f"]:
+    let cols = line.splitWhitespace(maxSplit=1)
+    let x = cols[0]
+    let (nm, rest) = (cols[0], cols[1])
+procStat()
+
+
+# bug #14269
+
+import sugar, strutils
+
+type
+  Cursor = object
+    text: string
+  Parsed = object
+    text: string
+    toks: seq[string]
+
+proc tokenize(c: var Cursor): seq[string] =
+  dump c.text
+  return c.text.splitWhitespace()
+
+proc parse(): Parsed =
+  var c = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c.tokenize) # note: c.tokenized uses c.text
+
+let p = parse()
+dump p.text
+dump p.toks
+
+
+proc tokenizeA(c: ptr Cursor): seq[string] =
+  dump c[].text
+  return c[].text.splitWhitespace()
+
+proc parseA(): Parsed =
+  var c = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c.addr.tokenizeA) # note: c.tokenized uses c.text
+
+let pA = parseA()
+dump pA.text
+dump pA.toks
+
+
+proc tokenizeD(c: Cursor): seq[string] =
+  dump c.text
+  return c.text.splitWhitespace()
+
+proc parseD(): Parsed =
+  var c = cast[ptr Cursor](alloc0(sizeof(Cursor)))
+  c[] = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c[].tokenizeD) # note: c.tokenized uses c.text
+
+let pD = parseD()
+dump pD.text
+dump pD.toks
+
+# Bug would only pop up with owned refs
+proc tokenizeOD(c: Cursor): seq[string] =
+  dump c.text
+  return c.text.splitWhitespace()
+
+proc parseOD(): Parsed =
+  var c = new Cursor
+  c[] = Cursor(text: "hello")
+  dump c.text
+  return Parsed(text: c.text, toks: c[].tokenizeOD) # note: c.tokenized uses c.text
+
+let pOD = parseOD()
+dump pOD.text
+dump pOD.toks
+
+when false:
+  # Bug would only pop up with owned refs and implicit derefs, but since they don't work together..
+  {.experimental: "implicitDeref".}
+  proc tokenizeOHD(c: Cursor): seq[string] =
+    dump c.text
+    return c.text.splitWhitespace()
+
+  proc parseOHD(): Parsed =
+    var c = new Cursor
+    c[] = Cursor(text: "hello")
+    dump c.text
+    return Parsed(text: c.text, toks: c.tokenizeOHD) # note: c.tokenized uses c.text
+
+  let pOHD = parseOHD()
+  dump pOHD.text
+  dump pOHD.toks
+
+# bug #13456
+
+iterator combinations[T](s: openArray[T], k: int): seq[T] =
+  let n = len(s)
+  assert k >= 0 and k <= n
+  var pos = newSeq[int](k)
+  var current = newSeq[T](k)
+  for i in 0..k-1:
+    pos[k-i-1] = i
+  var done = false
+  while not done:
+    for i in 0..k-1:
+      current[i] = s[pos[k-i-1]]
+    yield current
+    var i = 0
+    while i < k:
+      pos[i] += 1
+      if pos[i] < n-i:
+        for j in 0..i-1:
+          pos[j] = pos[i] + i - j
+        break
+      i += 1
+    if i >= k:
+      break
+
+type
+  UndefEx = object of ValueError
+
+proc main2 =
+  var delayedSyms = @[1, 2, 3]
+  var unp: seq[int]
+  block myb:
+    for a in 1 .. 2:
+      if delayedSyms.len > a:
+        unp = delayedSyms
+        for t in unp.combinations(a + 1):
+          try:
+            var h = false
+            for k in t:
+              echo "fff"
+            if h: continue
+            if true:
+              raise newException(UndefEx, "forward declaration")
+            break myb
+          except UndefEx:
+            echo t.len
+        echo "mmm"
+
+main2()
+
+
+
+type ME = object
+  who: string
+
+proc `=copy`(x: var ME, y: ME) =
+  if y.who.len > 0: echo "assign ",y.who
+
+proc `=sink`(x: var ME, y: ME) =
+  if y.who.len > 0: echo "sink ",y.who
+
+var dump: ME
+template use(x) = dump = x
+template def(x) = x = dump
+
+var c = true
+
+proc shouldSink() =
+  var x = ME(who: "me (sink)")
+  use(x) # we analyse this
+  if c: def(x)
+  else: def(x)
+  use(x) # ok, with the [else] part.
+
+shouldSink()
+
+dump = ME()
+
+proc shouldNotSink() =
+  var x = ME(who: "me (not sink)")
+  use(x) # we analyse this
+  if c: def(x)
+  use(x) # Not ok without the '[else]'
+
+shouldNotSink()
+
+# bug #14568
+import os
+
+type O2 = object
+  s: seq[int]
+
+proc `=sink`(dest: var O2, src: O2) =
+  echo "sinked and not optimized to a bitcopy"
+
+var testSeq: O2
+
+proc update() =
+  # testSeq.add(0) # uncommenting this line fixes the leak
+  testSeq = O2(s: @[])
+  testSeq.s.add(0)
+
+for i in 1..3:
+  update()
+
+
+# bug #14961
+type
+  Foo = object
+    data: seq[int]
+
+proc initFoo(len: int): Foo =
+  result = (let s = newSeq[int](len); Foo(data: s) )
+
+var f = initFoo(2)
+echo initFoo(2)
+
+proc initFoo2(len: int) =
+  echo   if true:
+             let s = newSeq[int](len); Foo(data: s)
+         else:
+             let s = newSeq[int](len); Foo(data: s)
+
+initFoo2(2)
+
+proc initFoo3(len: int) =
+  echo (block:
+         let s = newSeq[int](len); Foo(data: s))
+
+initFoo3(2)
+
+proc initFoo4(len: int) =
+  echo (let s = newSeq[int](len); Foo(data: s))
+
+initFoo4(2)
+
+proc initFoo5(len: int) =
+  echo (case true
+        of true:
+          let s = newSeq[int](len); Foo(data: s)
+        of false:
+          let s = newSeq[int](len); Foo(data: s))
+
+initFoo5(2)
+
+proc initFoo6(len: int) =
+  echo (block:
+          try:
+            let s = newSeq[int](len); Foo(data: s)
+          finally: discard)
+
+initFoo6(2)
+
+proc initFoo7(len: int) =
+  echo (block:
+          try:
+            raise newException(CatchableError, "sup")
+            let s = newSeq[int](len); Foo(data: s)
+          except CatchableError:
+            let s = newSeq[int](len); Foo(data: s) )
+
+initFoo7(2)
+
+
+# bug #14902
+iterator zip[T](s: openArray[T]): (T, T) =
+  var i = 0
+  while i < 10:
+    yield (s[i mod 2], s[i mod 2 + 1])
+    inc i
+
+var lastMem = int.high
+
+proc leak =
+  const len = 10
+  var x = @[newString(len), newString(len), newString(len)]
+
+  var c = 0
+  for (a, b) in zip(x):
+    let newMem = getOccupiedMem()
+    assert newMem <= lastMem
+    lastMem = newMem
+    c += a.len
+  echo c
+
+leak()
+
+
+proc consume(a: sink string) = echo a
+
+proc weirdScopes =
+  if (let a = "hey"; a.len > 0):
+    echo a
+
+  while (let a = "hey"; a.len > 0):
+    echo a
+    break
+
+  var a = block: (a: "a", b: 2)
+  echo a
+  (discard; a) = (echo "ho"; (a: "b", b: 3))
+  echo a
+
+  var b = try: (b: "b", a: 2)
+          except: raise
+  echo b
+  (discard; b) = (echo "ho"; (b: "a", a: 3))
+  echo b
+
+  var s = "break"
+  consume((echo "hey"; s))
+  echo s
+
+  echo (block:
+          var a = "hey"
+          (echo "hey"; "ho"))
+
+  var b2 = "ho"
+  echo (block:
+          var a = "hey"
+          (echo "hey"; b2))
+  echo b2
+
+  type status = enum
+    alive
+
+  var king = "king"
+  echo (block:
+          var a = "a"
+          when true:
+            var b = "b"
+            case alive
+            of alive:
+              try:
+                var c = "c"
+                if true:
+                  king
+                else:
+                  "the abyss"
+              except:
+                echo "he ded"
+                "dead king")
+  echo "live long; long live"
+  echo king
+
+weirdScopes()
+
+
+# bug #14985
+proc getScope(): string =
+  if true:
+    "hi"
+  else:
+    "else"
+
+echo getScope()
+
+proc getScope3(): string =
+  try:
+    "try"
+  except:
+    "except"
+
+echo getScope3()
+
+proc getScope2(): string =
+  case true
+  of true:
+    "bye"
+  else:
+    "else"
+
+echo getScope2()
diff --git a/tests/arc/tnewseq_legacy.nim b/tests/arc/tnewseq_legacy.nim
new file mode 100644
index 000000000..4730d2c2b
--- /dev/null
+++ b/tests/arc/tnewseq_legacy.nim
@@ -0,0 +1,13 @@
+discard """
+  output: "(allocCount: 201, deallocCount: 201)"
+  cmd: "nim c --gc:orc -d:nimAllocStats $file"
+"""
+
+proc main(prefix: string) =
+  var c: seq[string]
+  for i in 0..<100:
+    newSeq(c, 100)
+    c[i] = prefix & $i
+
+main("abc")
+echo getAllocStats()
diff --git a/tests/arc/top_no_cursor2.nim b/tests/arc/top_no_cursor2.nim
new file mode 100644
index 000000000..5dfde57aa
--- /dev/null
+++ b/tests/arc/top_no_cursor2.nim
@@ -0,0 +1,53 @@
+discard """
+  output: '''true
+true
+true
+true
+true'''
+  cmd: "nim c --gc:arc $file"
+"""
+# bug #15361
+
+type
+  ErrorNodeKind = enum Branch, Leaf
+  Error = ref object
+    case kind: ErrorNodeKind
+      of Branch:
+        left: Error
+        right: Error
+      of Leaf:
+        leafError: string
+    input: string
+
+proc ret(input: string, lefterr, righterr: Error): Error =
+  result = Error(kind: Branch, left: lefterr, right: righterr, input: input)
+
+proc parser() =
+  var rerrors: Error
+  let lerrors = Error(
+    kind: Leaf,
+    leafError: "first error",
+    input: "123 ;"
+  )
+  # If you remove "block" - everything works
+  block:
+    let rresult = Error(
+      kind: Leaf,
+      leafError: "second error",
+      input: ";"
+    )
+    # this assignment is needed too
+    rerrors = rresult
+
+  # Returns Error(kind: Branch, left: lerrors, right: rerrors, input: "some val")
+  # needs to be a proc call for some reason, can't inline the result
+  var data = ret(input = "some val", lefterr = lerrors, righterr = rerrors)
+
+  echo data.left.leafError == "first error"
+  echo data.left.input == "123 ;"
+  # stacktrace shows this line
+  echo data.right.leafError == "second error"
+  echo data.right.input == ";"
+  echo data.input == "some val"
+
+parser()
diff --git a/tests/arc/topenarray.nim b/tests/arc/topenarray.nim
new file mode 100644
index 000000000..ba91666ba
--- /dev/null
+++ b/tests/arc/topenarray.nim
@@ -0,0 +1,86 @@
+discard """
+  input: "hi"
+  output: '''
+hi
+Nim
+'''
+  matrix: "--gc:arc -d:useMalloc; --gc:arc"
+"""
+{.experimental: "views".}
+
+block: # bug 18627
+  proc setPosition(params: openArray[string]) =
+    for i in params.toOpenArray(0, params.len - 1):
+      echo i
+
+  proc uciLoop() =
+    let params = @[readLine(stdin)]
+    setPosition(params)
+
+  uciLoop()
+
+  proc uciLoop2() =
+    let params = @["Nim"]
+    for i in params.toOpenArray(0, params.len - 1):
+      echo i
+  uciLoop2()
+
+when defined(nimPreviewSlimSystem):
+  import std/assertions
+
+block: # bug #20954
+  block:
+    doAssertRaises(IndexDefect):
+      var v: array[10, int]
+
+      echo len(toOpenArray(v, 20, 30))
+
+  block:
+    doAssertRaises(IndexDefect):
+      var v: seq[int]
+
+      echo len(toOpenArray(v, 20, 30))
+
+# bug #20422
+
+proc f(a: var string) =
+  var v = a.toOpenArray(1, 3)
+  v[0] = 'a'
+
+var a = "Hello"
+f(a)
+doAssert a == "Hallo"
+
+# bug #22132
+block:
+  func foo[T](arr: openArray[T], idx: int = arr.low): string =
+    doAssert idx == 0
+    return $arr
+
+  let bug = ["0", "c", "a"]
+
+  let str = foo(bug)
+
+  const expected = """["0", "c", "a"]"""
+  doAssert str == expected
+
+  const noBugConst = ["0", "c", "a"]
+  doAssert foo(noBugConst) == expected
+  let noBugSeq = @["0", "c", "a"]
+  doAssert foo(noBugSeq) == expected
+
+block: # bug #20865
+  var p: pointer
+  var x: array[0, int]
+  # echo toOpenArray(x, 0, 1)[0] # Raises IndexDefect
+  doAssertRaises(IndexDefect):
+    echo toOpenArray(cast[ptr array[0, int]](p)[], 0, 1)[0] # Does not raise IndexDefect
+
+block: # bug #20987
+  var v: array[1, byte]
+
+  var p = cast[ptr array[0, byte]](addr v)
+
+  doAssertRaises(IndexDefect):
+    echo toOpenArray(p[], 1, 2)
+
diff --git a/tests/arc/topt_cursor.nim b/tests/arc/topt_cursor.nim
new file mode 100644
index 000000000..794132921
--- /dev/null
+++ b/tests/arc/topt_cursor.nim
@@ -0,0 +1,57 @@
+discard """
+  output: '''("string here", 80)'''
+  cmd: '''nim c --gc:arc --expandArc:main --expandArc:sio --hint:Performance:off $file'''
+  nimout: '''--expandArc: main
+
+var
+  x_cursor
+  :tmpD
+try:
+  x_cursor = ("hi", 5)
+  if cond:
+    x_cursor = ("different", 54) else:
+    x_cursor = ("string here", 80)
+  echo [
+    :tmpD = `$$`(x_cursor)
+    :tmpD]
+finally:
+  `=destroy`(:tmpD)
+-- end of expandArc ------------------------
+--expandArc: sio
+
+block :tmp:
+  var x_cursor
+  var f = open("debug.txt", fmRead, 8000)
+  try:
+    var res
+    try:
+      res = newStringOfCap(80)
+      block :tmp_1:
+        while readLine(f, res):
+          x_cursor = res
+          echo [x_cursor]
+    finally:
+      `=destroy`(res)
+  finally:
+    close(f)
+-- end of expandArc ------------------------'''
+"""
+
+proc main(cond: bool) =
+  var x = ("hi", 5) # goal: computed as cursor
+
+  x = if cond:
+        ("different", 54)
+      else:
+        ("string here", 80)
+
+  echo x
+
+main(false)
+
+proc sio =
+  for x in lines("debug.txt"):
+    echo x
+
+if false:
+  sio()
diff --git a/tests/arc/topt_cursor2.nim b/tests/arc/topt_cursor2.nim
new file mode 100644
index 000000000..4b566ed24
--- /dev/null
+++ b/tests/arc/topt_cursor2.nim
@@ -0,0 +1,76 @@
+discard """  
+  cmd: '''nim c --gc:arc $file'''
+  output: '''emptyemptyempty
+inner destroy
+'''
+"""
+
+# bug #15039
+
+import lists
+
+type
+  Token = ref object of RootObj
+    children: DoublyLinkedList[Token]
+
+  Paragraph = ref object of Token
+
+method `$`(token: Token): string {.base.} =
+  result = "empty"
+
+method `$`(token: Paragraph): string =
+  if token.children.head == nil:
+    result = ""
+  else:
+    for c in token.children:
+      result.add $c
+
+proc parseLeafBlockInlines(token: Token) =
+  token.children.append(Token())
+  token.children.append(Token()) # <-- this one AAA
+
+  var emNode = newDoublyLinkedNode(Token())
+  var i = 0
+
+  var it = token.children.head
+  while it != nil:
+    var nxt = it.next  # this is not a cursor, it takes over ownership.
+    var childNode = it
+    if i == 0:
+      childNode.next = emNode # frees the object allocated in line 29 marked with AAA
+    elif i == 1:
+      emNode.next = childNode  #
+    it = nxt # incref on freed data, 'nxt' is freed
+    inc i
+
+proc parse() =
+  var token = Token()
+  token.children.append Paragraph()
+  parseLeafBlockInlines(token.children.head.value)
+  for children in token.children:
+    echo children
+
+parse()
+
+
+#------------------------------------------------------------------------------
+# issue #15629
+
+type inner = object
+type outer = ref inner
+
+proc `=destroy`(b: var inner) =
+  echo "inner destroy"
+
+proc newOuter(): outer =
+  new(result)
+
+type holder = object
+  contents: outer
+
+proc main() = 
+  var t: holder
+  t.contents = newOuter()
+  
+main()
+
diff --git a/tests/arc/topt_no_cursor.nim b/tests/arc/topt_no_cursor.nim
new file mode 100644
index 000000000..0a4984a69
--- /dev/null
+++ b/tests/arc/topt_no_cursor.nim
@@ -0,0 +1,376 @@
+discard """
+  nimoutFull: true
+  cmd: '''nim c -r --warnings:off --hints:off --mm:arc --expandArc:newTarget --expandArc:delete --expandArc:p1 --expandArc:tt --hint:Performance:off --assertions:off --expandArc:extractConfig --expandArc:mergeShadowScope --expandArc:check $file'''
+  nimout: '''
+--expandArc: newTarget
+
+var
+  splat
+  :tmp
+  :tmp_1
+splat = splitDrive do:
+  let blitTmp = path
+  blitTmp
+:tmp = splat.drive
+`=wasMoved`(splat.drive)
+:tmp_1 = splat.path_1
+`=wasMoved`(splat.path_1)
+result = (
+  let blitTmp_1 = :tmp
+  blitTmp_1,
+  let blitTmp_2 = :tmp_1
+  blitTmp_2)
+`=destroy`(splat)
+-- end of expandArc ------------------------
+--expandArc: delete
+
+var
+  sibling
+  saved
+`=copy`(sibling, target.parent.left)
+`=copy`(saved, sibling.right)
+`=copy`(sibling.right, saved.left)
+`=sink`(sibling.parent, saved)
+`=destroy`(sibling)
+-- end of expandArc ------------------------
+--expandArc: p1
+
+var
+  lresult
+  lvalue
+  lnext
+  tmpTupleAsgn
+lresult = @[123]
+tmpTupleAsgn = (
+  let blitTmp = lresult
+  blitTmp, ";")
+lvalue = tmpTupleAsgn[0]
+lnext = tmpTupleAsgn[1]
+`=sink`(result.value, move lvalue)
+`=destroy`(lnext)
+`=destroy_1`(lvalue)
+-- end of expandArc ------------------------
+--expandArc: tt
+
+var
+  it_cursor
+  a
+  :tmpD
+  :tmpD_1
+  :tmpD_2
+try:
+  it_cursor = x
+  a = (
+    :tmpD = `=dup`(it_cursor.key)
+    :tmpD,
+    :tmpD_1 = `=dup`(it_cursor.val)
+    :tmpD_1)
+  echo [
+    :tmpD_2 = `$$`(a)
+    :tmpD_2]
+finally:
+  `=destroy`(:tmpD_2)
+  `=destroy_1`(a)
+-- end of expandArc ------------------------
+--expandArc: extractConfig
+
+var lan_ip
+try:
+  lan_ip = ""
+  block :tmp:
+    var line
+    var i = 0
+    let L = len(txt)
+    block :tmp_1:
+      while i < L:
+        var splitted
+        try:
+          line = txt[i]
+          splitted = split(line, " ", -1)
+          if splitted[0] == "opt":
+            `=copy`(lan_ip, splitted[1])
+          echo [lan_ip]
+          echo [splitted[1]]
+          {.push, overflowChecks: false.}
+          inc(i, 1)
+          {.pop.}
+        finally:
+          `=destroy`(splitted)
+finally:
+  `=destroy_1`(lan_ip)
+-- end of expandArc ------------------------
+--expandArc: mergeShadowScope
+
+var shadowScope
+`=copy`(shadowScope, c.currentScope)
+rawCloseScope(c)
+block :tmp:
+  var sym
+  var i = 0
+  let L = len(shadowScope.symbols)
+  block :tmp_1:
+    while i < L:
+      var :tmpD
+      sym = shadowScope.symbols[i]
+      addInterfaceDecl(c):
+        :tmpD = `=dup`(sym)
+        :tmpD
+      {.push, overflowChecks: false.}
+      inc(i, 1)
+      {.pop.}
+`=destroy`(shadowScope)
+-- end of expandArc ------------------------
+--expandArc: check
+
+var par
+this.isValid = fileExists(this.value)
+if dirExists(this.value):
+  var :tmpD
+  par = (dir:
+    :tmpD = `=dup`(this.value)
+    :tmpD, front: "") else:
+  var
+    :tmpD_1
+    :tmpD_2
+    :tmpD_3
+  par = (dir_1: parentDir(this.value), front_1:
+    :tmpD_1 = `=dup`(
+      :tmpD_3 = splitDrive do:
+        :tmpD_2 = `=dup`(this.value)
+        :tmpD_2
+      :tmpD_3.path)
+    :tmpD_1)
+  `=destroy`(:tmpD_3)
+if dirExists(par.dir):
+  `=sink`(this.matchDirs, getSubDirs(par.dir, par.front))
+else:
+  `=sink`(this.matchDirs, [])
+`=destroy`(par)
+-- end of expandArc ------------------------
+--expandArc: check
+
+check(this)
+-- end of expandArc ------------------------
+(package: "", ext: "meo")
+doing shady stuff...
+3
+6
+(@[1], @[2])
+192.168.0.1
+192.168.0.1
+192.168.0.1
+192.168.0.1
+'''
+"""
+
+import os, std/private/ntpath
+
+type Target = tuple[package, ext: string]
+
+proc newTarget*(path: string): Target =
+  let splat = path.splitDrive
+  result = (package: splat.drive, ext: splat.path)
+
+echo newTarget("meo")
+
+type
+  Node = ref object
+    left, right, parent: Node
+    value: int
+
+proc delete(target: var Node) =
+  var sibling = target.parent.left # b3
+  var saved = sibling.right # b3.right -> r4
+
+  sibling.right = saved.left # b3.right -> r4.left = nil
+  sibling.parent = saved # b3.parent -> r5 = r4
+
+  #[after this proc:
+        b 5
+      /   \
+    b 3     b 6
+  ]#
+
+
+#[before:
+      r 5
+    /   \
+  b 3    b 6 - to delete
+  /    \
+empty  r 4
+]#
+proc main =
+  var five = Node(value: 5)
+
+  var six = Node(value: 6)
+  six.parent = five
+  five.right = six
+
+  var three = Node(value: 3)
+  three.parent = five
+  five.left = three
+
+  var four = Node(value: 4)
+  four.parent = three
+  three.right = four
+
+  echo "doing shady stuff..."
+  delete(six)
+  # need both of these echos
+  echo five.left.value
+  echo five.right.value
+
+main()
+
+type
+  Maybe = object
+    value: seq[int]
+
+proc p1(): Maybe =
+  let lresult = @[123]
+  var lvalue: seq[int]
+  var lnext: string
+  (lvalue, lnext) = (lresult, ";")
+
+  result.value = move lvalue
+
+proc tissue15130 =
+  doAssert p1().value == @[123]
+
+tissue15130()
+
+type
+  KeyValue = tuple[key, val: seq[int]]
+
+proc tt(x: KeyValue) =
+  var it = x
+  let a = (it.key, it.val)
+  echo a
+
+proc encodedQuery =
+  var query: seq[KeyValue]
+  query.add (key: @[1], val: @[2])
+
+  for elem in query:
+    elem.tt()
+
+encodedQuery()
+
+# bug #15147
+
+proc s(input: string): (string, string) =
+  result = (";", "")
+
+proc charmatch(input: string): (string, string) =
+  result = ("123", input[0 .. input.high])
+
+proc plus(input: string) =
+  var
+    lvalue, rvalue: string # cursors
+    lnext: string # must be cursor!!!
+    rnext: string # cursor
+  let lresult = charmatch(input)
+  (lvalue, lnext) = lresult
+
+  let rresult = s(lnext)
+  (rvalue, rnext) = rresult
+
+plus("123;")
+
+func substrEq(s: string, pos: int, substr: string): bool =
+  var i = 0
+  var length = substr.len
+  while i < length and pos+i < s.len and s[pos+i] == substr[i]:
+    inc i
+  return i == length
+
+template stringHasSep(s: string, index: int, sep: string): bool =
+  s.substrEq(index, sep)
+
+template splitCommon(s, sep, maxsplit, sepLen) =
+  var last = 0
+  var splits = maxsplit
+
+  while last <= len(s):
+    var first = last
+    while last < len(s) and not stringHasSep(s, last, sep):
+      inc(last)
+    if splits == 0: last = len(s)
+    yield substr(s, first, last-1)
+    if splits == 0: break
+    dec(splits)
+    inc(last, sepLen)
+
+iterator split(s: string, sep: string, maxsplit = -1): string =
+  splitCommon(s, sep, maxsplit, sep.len)
+
+template accResult(iter: untyped) =
+  result = @[]
+  for x in iter: add(result, x)
+
+func split*(s: string, sep: string, maxsplit = -1): seq[string] =
+  accResult(split(s, sep, maxsplit))
+
+
+let txt = @["opt 192.168.0.1", "static_lease 192.168.0.1"]
+
+# bug #17033
+
+proc extractConfig() =
+  var lan_ip = ""
+
+  for line in txt:
+    let splitted = line.split(" ")
+    if splitted[0] == "opt":
+      lan_ip = splitted[1] # "borrow" is conditional and inside a loop.
+      # Not good enough...
+      # we need a flag that live-ranges are disjoint
+    echo lan_ip
+    echo splitted[1] # Without this line everything works
+
+extractConfig()
+
+
+type
+  Symbol = ref object
+    name: string
+
+  Scope = ref object
+    parent: Scope
+    symbols: seq[Symbol]
+
+  PContext = ref object
+    currentScope: Scope
+
+proc rawCloseScope(c: PContext) =
+  c.currentScope = c.currentScope.parent
+
+proc addInterfaceDecl(c: PContext; s: Symbol) =
+  c.currentScope.symbols.add s
+
+proc mergeShadowScope*(c: PContext) =
+  let shadowScope = c.currentScope
+  c.rawCloseScope
+  for sym in shadowScope.symbols:
+    c.addInterfaceDecl(sym)
+
+mergeShadowScope(PContext(currentScope: Scope(parent: Scope())))
+
+type
+  Foo = ref object
+    isValid*: bool
+    value*: string
+    matchDirs*: seq[string]
+
+proc getSubDirs(parent, front: string): seq[string] = @[]
+
+method check(this: Foo) {.base.} =
+  this.isValid = fileExists(this.value)
+  let par = if dirExists(this.value): (dir: this.value, front: "")
+            else: (dir: parentDir(this.value), front: splitDrive(this.value).path)
+  if dirExists(par.dir):
+    this.matchDirs = getSubDirs(par.dir, par.front)
+  else:
+    this.matchDirs = @[]
+
+check(Foo())
diff --git a/tests/arc/topt_refcursors.nim b/tests/arc/topt_refcursors.nim
new file mode 100644
index 000000000..8c638a4a1
--- /dev/null
+++ b/tests/arc/topt_refcursors.nim
@@ -0,0 +1,54 @@
+discard """
+  output: ''''''
+  cmd: '''nim c --gc:arc --expandArc:traverse --hint:Performance:off $file'''
+  nimout: '''
+--expandArc: traverse
+
+var
+  it_cursor
+  jt
+try:
+  it_cursor = root
+  block :tmp:
+    while (
+      not (it_cursor == nil)):
+      echo [it_cursor.s]
+      it_cursor = it_cursor.ri
+  `=copy`(jt, root)
+  block :tmp_1:
+    while (
+      not (jt == nil)):
+      var ri_1
+      try:
+        `=copy`(ri_1, jt.ri)
+        echo [jt.s]
+        `=sink`(jt, ri_1)
+        `=wasMoved`(ri_1)
+      finally:
+        `=destroy`(ri_1)
+finally:
+  `=destroy`(jt)
+-- end of expandArc ------------------------
+'''
+"""
+
+type
+  Node = ref object
+    le, ri: Node
+    s: string
+
+proc traverse(root: Node) =
+  var it = root
+  while it != nil:
+    echo it.s
+    it = it.ri
+
+  var jt = root
+  while jt != nil:
+    let ri = jt.ri
+    echo jt.s
+    jt = ri
+
+traverse(nil)
+
+# XXX: This optimization is not sound
diff --git a/tests/arc/topt_wasmoved_destroy_pairs.nim b/tests/arc/topt_wasmoved_destroy_pairs.nim
new file mode 100644
index 000000000..c96340a30
--- /dev/null
+++ b/tests/arc/topt_wasmoved_destroy_pairs.nim
@@ -0,0 +1,94 @@
+discard """
+  output: ''''''
+  cmd: '''nim c --gc:arc --expandArc:main --expandArc:tfor --hint:Performance:off $file'''
+  nimout: '''
+--expandArc: main
+
+var
+  a
+  b
+  x
+x = f()
+if cond:
+  add(a):
+    let blitTmp = x
+    blitTmp
+else:
+  add(b):
+    let blitTmp_1 = x
+    blitTmp_1
+`=destroy`(b)
+`=destroy`(a)
+-- end of expandArc ------------------------
+--expandArc: tfor
+
+var
+  a
+  b
+  x
+try:
+  x = f()
+  block :tmp:
+    var i_cursor
+    mixin inc
+    var i_1 = 0
+    block :tmp_1:
+      while i_1 < 4:
+        var :tmpD
+        i_cursor = i_1
+        if i_cursor == 2:
+          return
+        add(a):
+          :tmpD = `=dup`(x)
+          :tmpD
+        inc i_1, 1
+  if cond:
+    add(a):
+      let blitTmp = x
+      `=wasMoved`(x)
+      blitTmp
+  else:
+    add(b):
+      let blitTmp_1 = x
+      `=wasMoved`(x)
+      blitTmp_1
+finally:
+  `=destroy`(x)
+  `=destroy_1`(b)
+  `=destroy_1`(a)
+-- end of expandArc ------------------------
+'''
+"""
+
+proc f(): seq[int] =
+  @[1, 2, 3]
+
+proc main(cond: bool) =
+  var a, b: seq[seq[int]]
+  var x = f()
+  if cond:
+    a.add x
+  else:
+    b.add x
+
+# all paths move 'x' so no wasMoved(x); destroy(x) pair should be left in the
+# AST.
+
+main(false)
+
+
+proc tfor(cond: bool) =
+  var a, b: seq[seq[int]]
+
+  var x = f()
+
+  for i in 0 ..< 4:
+    if i == 2: return
+    a.add x
+
+  if cond:
+    a.add x
+  else:
+    b.add x
+
+tfor(false)
diff --git a/tests/arc/torc_basic_test.nim b/tests/arc/torc_basic_test.nim
new file mode 100644
index 000000000..73039fad7
--- /dev/null
+++ b/tests/arc/torc_basic_test.nim
@@ -0,0 +1,138 @@
+discard """
+  output: "MEM 0"
+  cmd: "nim c --gc:orc $file"
+"""
+
+type
+  Node = ref object
+    name: char
+    sccId: int
+    #a: array[3, Node]
+    a0, a1, a2: Node
+    rc: int
+
+proc edge(a, b: Node) =
+  inc b.rc
+  if a.a0 == nil: a.a0 = b
+  elif a.a1 == nil: a.a1 = b
+  else: a.a2 = b
+  when false:
+    var i = 0
+    while a.a[i] != nil: inc i
+    a.a[i] = b
+
+proc createNode(name: char): Node =
+  new result
+  result.name = name
+
+#[
+
+     +--------------------------------+
+     v                                |
++---------+      +------+             |
+|         |      |      |             |
+|  A      +----->+      |      +------+------+
++--+------+      |      |      |             |
+   |             |      |      |     C       ------------>  G  <--|
+   |             |  R   |      |             |
++--v------+      |      |      +-------------+
+|         |      |      |        ^
+|   B     <------+      |        |
+|         |      |      +--------+
++---------+      |      |
+                 +------+
+
+]#
+proc use(x: Node) = discard
+
+proc main =
+  let a = createNode('A')
+  let b = createNode('B')
+  let r = createNode('R')
+  let c = createNode('C')
+
+  a.edge b
+  a.edge r
+
+  r.edge b
+  r.edge c
+
+  let g = createNode('G')
+  g.edge g
+  g.edge g
+
+  c.edge g
+  c.edge a
+
+  use g
+  use b
+
+proc buildComplexGraph: Node =
+  # see https://en.wikipedia.org/wiki/Strongly_connected_component for the
+  # graph:
+  let a = createNode('a')
+  let b = createNode('b')
+  let c = createNode('c')
+  let d = createNode('d')
+  let e = createNode('e')
+
+  a.edge c
+  c.edge b
+  c.edge e
+  b.edge a
+  d.edge c
+  e.edge d
+
+
+  let f = createNode('f')
+  b.edge f
+  e.edge f
+
+  let g = createNode('g')
+  let h = createNode('h')
+  let i = createNode('i')
+
+  f.edge g
+  f.edge i
+  g.edge h
+  h.edge i
+  i.edge g
+
+  let j = createNode('j')
+
+  h.edge j
+  i.edge j
+
+  let k = createNode('k')
+  let l = createNode('l')
+
+  f.edge k
+  k.edge l
+  l.edge k
+  k.edge j
+
+  let m = createNode('m')
+  let n = createNode('n')
+  let p = createNode('p')
+  let q = createNode('q')
+
+  m.edge n
+  n.edge p
+  n.edge q
+  q.edge p
+  p.edge m
+
+  q.edge k
+
+  d.edge m
+  e.edge n
+
+  result = a
+
+proc main2 =
+  let g = buildComplexGraph()
+
+main()
+main2()
+GC_fullCollect()
+echo "MEM ", getOccupiedMem()
diff --git a/tests/arc/torc_selfcycles.nim b/tests/arc/torc_selfcycles.nim
new file mode 100644
index 000000000..ac4fa52ce
--- /dev/null
+++ b/tests/arc/torc_selfcycles.nim
@@ -0,0 +1,33 @@
+discard """
+  output: '''ok'''
+  cmd: '''nim c --gc:orc -d:useMalloc -d:nimStressOrc $file'''
+  valgrind: "leaks"
+"""
+
+# bug #15753
+
+type
+  NodeKind = enum
+    nkDancing,
+    nkColumn
+
+  DancingNode = ref object
+    right: DancingNode
+    column: DancingNode
+    kind: NodeKind
+
+proc newColumnNode(): DancingNode =
+  result = DancingNode(kind: nkColumn)
+  result.right = result
+  result.column = result
+
+proc createDLXList(): DancingNode =
+  result = newColumnNode()
+
+  for i in 0 .. 15:
+    let n = newColumnNode()
+    n.right = result.right
+    result = n
+  echo "ok"
+
+var dlxlist = createDLXList()
diff --git a/tests/arc/torcbench.nim b/tests/arc/torcbench.nim
new file mode 100644
index 000000000..4c9e65fee
--- /dev/null
+++ b/tests/arc/torcbench.nim
@@ -0,0 +1,38 @@
+discard """
+  output: '''true peak memory: true'''
+  cmd: "nim c --gc:orc -d:release $file"
+"""
+
+import lists, strutils, times
+
+type
+  Base = ref object of RootObj
+
+  Node = ref object of Base
+    parent: DoublyLinkedList[string]
+    le, ri: Node
+    self: Node # in order to create a cycle
+
+proc buildTree(parent: DoublyLinkedList[string]; depth: int): Node =
+  if depth == 0:
+    result = nil
+  elif depth == 1:
+    result = Node(parent: parent, le: nil, ri: nil, self: nil)
+    when not defined(gcArc):
+      result.self = result
+  else:
+    result = Node(parent: parent, le: buildTree(parent, depth - 1), ri: buildTree(parent, depth - 2), self: nil)
+    result.self = result
+
+proc main() =
+  for i in countup(1, 100):
+    var leakList = initDoublyLinkedList[string]()
+    for j in countup(1, 5000):
+      leakList.append(newString(200))
+    #GC_fullCollect()
+    for i in 0..400:
+      discard buildTree(leakList, 8)
+
+main()
+GC_fullCollect()
+echo getOccupiedMem() < 10 * 1024 * 1024, " peak memory: ", getMaxMem() < 10 * 1024 * 1024
diff --git a/tests/arc/torcmisc.nim b/tests/arc/torcmisc.nim
new file mode 100644
index 000000000..e41ad7c77
--- /dev/null
+++ b/tests/arc/torcmisc.nim
@@ -0,0 +1,66 @@
+discard """
+  output: '''success'''
+  cmd: "nim c --gc:orc -d:release $file"
+"""
+
+# bug #17170
+
+when true:
+  import asyncdispatch
+
+  type
+    Flags = ref object
+      returnedEof, reading: bool
+
+  proc dummy(): Future[string] {.async.} =
+    result = "foobar"
+
+  proc hello(s: Flags) {.async.} =
+    let buf =
+      try:
+        await dummy()
+      except CatchableError as exc:
+        # When an exception happens here, the Bufferstream is effectively
+        # broken and no more reads will be valid - for now, return EOF if it's
+        # called again, though this is not completely true - EOF represents an
+        # "orderly" shutdown and that's not what happened here..
+        s.returnedEof = true
+        raise exc
+      finally:
+        s.reading = false
+
+  waitFor hello(Flags())
+  echo "success"
+
+# bug #18240
+import tables
+
+type
+  TopicHandler* = proc(topic: string,
+                       data: seq[byte]): Future[void] {.gcsafe, raises: [Defect].}
+
+  PeerID* = object
+    data*: seq[byte]
+
+  PeerInfo* = ref object of RootObj
+    peerId*: PeerID
+
+  Connection* = ref object of RootObj
+    peerInfo*: PeerInfo
+
+  PubSubPeer* = ref object of RootObj
+    codec*: string
+
+  PubSub* = ref object of RootObj
+    topics*: Table[string, seq[TopicHandler]]
+    peers*: Table[PeerID, PubSubPeer]
+
+proc getOrCreatePeer*(myParam: PubSub, peerId: PeerID, protos: seq[string]): PubSubPeer =
+  myParam.peers.withValue(peerId, peer):
+    return peer[]
+
+method handleConn*(myParam: PubSub,
+                  conn: Connection,
+                  proto: string) {.base, async.} =
+  myParam.peers.withValue(conn.peerInfo.peerId, peer):
+    let peerB = peer[]
diff --git a/tests/arc/tref_cast_error.nim b/tests/arc/tref_cast_error.nim
new file mode 100644
index 000000000..20139c1be
--- /dev/null
+++ b/tests/arc/tref_cast_error.nim
@@ -0,0 +1,15 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+  errormsg: "expression cannot be cast to 'ref RootObj'"
+  joinable: false
+"""
+
+type Variant* = object
+    refval: ref RootObj
+
+proc newVariant*[T](val: T): Variant =
+    let pt = T.new()
+    pt[] = val
+    result = Variant(refval: cast[ref RootObj](pt))
+
+var v = newVariant(@[1, 2, 3])
diff --git a/tests/arc/trepr.nim b/tests/arc/trepr.nim
index 7a92112ed..abf28330a 100644
--- a/tests/arc/trepr.nim
+++ b/tests/arc/trepr.nim
@@ -4,7 +4,17 @@ discard """
 Table[system.string, trepr.MyType](data: @[], counter: 0)
 nil
 '''
+  output: '''
+nil
+2
+Obj(member: ref @["hello"])
+ref (member: ref @["hello"])
+ObjUa(v: 0, a: [...])
+'''
 """
+
+# xxx consider merging with `tests/stdlib/trepr.nim` to increase overall test coverage
+
 import tables
 
 type
@@ -32,3 +42,56 @@ macro dumpSym(a: typed) =
 
 dumpSym(doAssert)
 
+# bug 13731
+
+import os
+var a: File
+echo repr a
+
+# bug 13872
+
+echo repr(2'u16)
+
+# bug 14270
+
+type
+  Obj = ref object
+    member: ref seq[string]
+
+var c = Obj(member: new seq[string])
+c.member[] = @["hello"]
+echo c.repr
+
+var c2 = new tuple[member: ref seq[string]]
+c2.member = new seq[string]
+c2.member[] = @["hello"]
+echo c2.repr
+
+proc p2 =
+  echo "hey"
+
+discard repr p2
+
+
+#####################################################################
+# bug #15043
+
+import macros
+
+macro extract(): untyped =
+  result = newStmtList()
+  var x: seq[tuple[node: NimNode]]
+
+  proc test(n: NimNode) {.closure.} =
+    x.add (node: n)
+  
+  test(parseExpr("discard"))
+  
+extract()
+
+type
+  ObjUa = ref object
+    v: int
+    a: UncheckedArray[char]
+
+echo ObjUa().repr
diff --git a/tests/generics/trtree.nim b/tests/arc/trtree.nim
index 4bd7d11f4..683403a62 100644
--- a/tests/generics/trtree.nim
+++ b/tests/arc/trtree.nim
@@ -1,7 +1,7 @@
 discard """
   output: '''1 [2, 3, 4, 7]
 [0, 0]'''
-  target: "c"
+  targets: "c"
   joinable: false
 disabled: 32bit
   cmd: "nim c --gc:arc $file"
@@ -71,24 +71,24 @@ proc newRStarTree*[M, D: Dim; RT, LT](minFill: range[30 .. 50] = 40): RStarTree[
   result.p = M * 30 div 100
   result.root = newLeaf[M, D, RT, LT]()
 
-proc center(r: Box): auto =#BoxCenter[r.len, type(r[0].a)] =
-  var result: BoxCenter[r.len, type(r[0].a)]
+proc center(r: Box): auto =#BoxCenter[r.len, typeof(r[0].a)] =
+  var res: BoxCenter[r.len, typeof(r[0].a)]
   for i in 0 .. r.high:
     when r[0].a is SomeInteger:
-      result[i] = (r[i].a + r[i].b) div 2
+      res[i] = (r[i].a + r[i].b) div 2
     elif r[0].a is SomeFloat:
-      result[i] = (r[i].a + r[i].b) / 2
+      res[i] = (r[i].a + r[i].b) / 2
     else: assert false
-  return result
+  return res
 
 proc distance(c1, c2: BoxCenter): auto =
-  var result: type(c1[0])
+  var res: typeof(c1[0])
   for i in 0 .. c1.high:
-    result += (c1[i] - c2[i]) * (c1[i] - c2[i])
-  return result
+    res += (c1[i] - c2[i]) * (c1[i] - c2[i])
+  return res
 
 proc overlap(r1, r2: Box): auto =
-  result = type(r1[0].a)(1)
+  result = typeof(r1[0].a)(1)
   for i in 0 .. r1.high:
     result *= (min(r1[i].b, r2[i].b) - max(r1[i].a, r2[i].a))
     if result <= 0: return 0
@@ -104,13 +104,13 @@ proc intersect(r1, r2: Box): bool =
       return false
   return true
 
-proc area(r: Box): auto = #type(r[0].a) =
-  result = type(r[0].a)(1)
+proc area(r: Box): auto = #typeof(r[0].a) =
+  result = typeof(r[0].a)(1)
   for i in 0 .. r.high:
     result *= r[i].b - r[i].a
 
-proc margin(r: Box): auto = #type(r[0].a) =
-  result = type(r[0].a)(0)
+proc margin(r: Box): auto = #typeof(r[0].a) =
+  result = typeof(r[0].a)(0)
   for i in 0 .. r.high:
     result += r[i].b - r[i].a
 
@@ -138,16 +138,16 @@ proc search*[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; b: Box[D, RT]): seq[LT]
 # a R*TREE proc
 proc chooseSubtree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; b: Box[D, RT]; level: int): H[M, D, RT, LT] =
   assert level >= 0
-  var n = t.root
-  while n.level > level:
-    let nn = Node[M, D, RT, LT](n)
+  var it = t.root
+  while it.level > level:
+    let nn = Node[M, D, RT, LT](it)
     var i0 = 0 # selected index
-    var minLoss = type(b[0].a).high
-    if n.level == 1: # childreen are leaves -- determine the minimum overlap costs
-      for i in 0 ..< n.numEntries:
+    var minLoss = typeof(b[0].a).high
+    if it.level == 1: # childreen are leaves -- determine the minimum overlap costs
+      for i in 0 ..< it.numEntries:
         let nx = union(nn.a[i].b, b)
         var loss = 0
-        for j in 0 ..< n.numEntries:
+        for j in 0 ..< it.numEntries:
           if i == j: continue
           loss += (overlap(nx, nn.a[j].b) - overlap(nn.a[i].b, nn.a[j].b)) # overlap (i, j) == (j, i), so maybe cache that?
         var rep = loss < minLoss
@@ -163,7 +163,7 @@ proc chooseSubtree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; b: Box[D, RT]; lev
           i0 = i
           minLoss = loss
     else:
-      for i in 0 ..< n.numEntries:
+      for i in 0 ..< it.numEntries:
         let loss = enlargement(nn.a[i].b, b)
         var rep = loss < minLoss
         if loss == minLoss:
@@ -174,28 +174,13 @@ proc chooseSubtree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; b: Box[D, RT]; lev
         if rep:
           i0 = i
           minLoss = loss
-    n = nn.a[i0].n
-  return n
-
-proc chooseLeaf[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; b: Box[D, RT]; level: int): H[M, D, RT, LT] =
-  assert level >= 0
-  var n = t.root
-  while n.level > level:
-    var j = -1 # selected index
-    var x: type(b[0].a)
-    let nn = Node[M, D, RT, LT](n)
-    for i in 0 ..< n.numEntries:
-      let h = enlargement(nn.a[i].b, b)
-      if j < 0 or h < x or (x == h and area(nn.a[i].b) < area(nn.a[j].b)):
-        x = h
-        j = i
-    n = nn.a[j].n
-  return n
+    it = nn.a[i0].n
+  return it
 
 proc pickSeeds[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n: Node[M, D, RT, LT] | Leaf[M, D, RT, LT]; bx: Box[D, RT]): (int, int) =
   var i0, j0: int
-  var bi, bj: type(bx)
-  var largestWaste = type(bx[0].a).low
+  var bi, bj: typeof(bx)
+  var largestWaste = typeof(bx[0].a).low
   for i in -1 .. n.a.high:
     for j in 0 .. n.a.high:
       if unlikely(i == j): continue
@@ -215,7 +200,7 @@ proc pickSeeds[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n: Node[M, D, RT, LT]
 proc pickNext[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n0, n1, n2: Node[M, D, RT, LT] | Leaf[M, D, RT, LT]; b1, b2: Box[D, RT]): int =
   let a1 = area(b1)
   let a2 = area(b2)
-  var d = type(a1).low
+  var d = typeof(a1).low
   for i in 0 ..< n0.numEntries:
     let d1 = area(union(b1, n0.a[i].b)) - a1
     let d2 = area(union(b2, n0.a[i].b)) - a2
@@ -235,15 +220,15 @@ proc sortPlus[T](a: var openArray[T], ax: var T, cmp: proc (x, y: T): int {.clos
   a.sort(cmp, order)
 
 # R*TREE procs
-proc rstarSplit[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): type(n) =
-  type NL = type(lx)
-  var nBest: type(n)
+proc rstarSplit[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): typeof(n) =
+  type NL = typeof(lx)
+  var nBest: typeof(n)
   new nBest
   var lx = lx
   when n is Node[M, D, RT, LT]:
     lx.n.parent = n
-  var lxbest: type(lx)
-  var m0 = lx.b[0].a.high
+  var lxbest: typeof(lx)
+  var m0 = lx.b[0].a.typeof.high
   for d2 in 0 ..< 2 * D:
     let d = d2 div 2
     if d2 mod 2 == 0:
@@ -266,8 +251,8 @@ proc rstarSplit[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D,
         lxbest = lx
         m0 = m
   var i0 = -1
-  var o0 = lx.b[0].a.high
-  for i in t.m - 1 .. n.a.high - t.m + 1:
+  var o0 = lx.b[0].a.typeof.high
+  for i in t.m - 1 .. n.a.typeof.high - t.m + 1:
     var b1 = lxbest.b
     for j in 0 ..< i:
       b1 = union(nbest.a[j].b, b1)
@@ -292,8 +277,8 @@ proc rstarSplit[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D,
     for i in 0 ..< result.numEntries:
       result.a[i].n.parent = result
 
-proc quadraticSplit[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): type(n) =
-  var n1, n2: type(n)
+proc quadraticSplit[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): typeof(n) =
+  var n1, n2: typeof(n)
   var s1, s2: int
   new n1
   new n2
@@ -356,7 +341,7 @@ proc quadraticSplit[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; n: var Node[M, D,
   n[] = n1[]
   return n2
 
-proc overflowTreatment[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): type(n)
+proc overflowTreatment[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): typeof(n)
 
 proc adjustTree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; l, ll: H[M, D, RT, LT]; hb: Box[D, RT]) =
   var n = l
@@ -376,7 +361,7 @@ proc adjustTree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; l, ll: H[M, D, RT, LT
     var i = 0
     while p.a[i].n != n:
       inc(i)
-    var b: type(p.a[0].b)
+    var b: typeof(p.a[0].b)
     if n of Leaf[M, D, RT, LT]:
       when false:#if likely(nn.isNil): # no performance gain
         b = union(p.a[i].b, Leaf[M, D, RT, LT](n).a[n.numEntries - 1].b)
@@ -412,12 +397,7 @@ proc adjustTree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; l, ll: H[M, D, RT, LT
         nn = nil
       else:
         let h: N[M, D, RT, LT] = (b, nn)
-        if t of RStarTree[M, D, RT, LT]:
-          nn = overflowTreatment(RStarTree[M, D, RT, LT](t), p, h)
-        elif t of RTree[M, D, RT, LT]:
-          nn = quadraticSplit(RTree[M, D, RT, LT](t), p, h)
-        else:
-          assert false
+        nn = quadraticSplit(t, p, h)
     assert n == H[M, D, RT, LT](p)
     assert n != nil
     assert t.root != nil
@@ -447,9 +427,9 @@ proc insert*[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; leaf: N[M, D, RT, LT] |
 proc rsinsert[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; leaf: N[M, D, RT, LT] | L[D, RT, LT]; level: int)
 
 proc reInsert[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]) =
-  type NL = type(lx)
+  type NL = typeof(lx)
   var lx = lx
-  var buf: type(n.a)
+  var buf: typeof(n.a)
   let p = Node[M, D, RT, LT](n.parent)
   var i = 0
   while p.a[i].n != n:
@@ -469,7 +449,7 @@ proc reInsert[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, R
   for i in M - t.p + 1 .. n.a.high:
     rsinsert(t, buf[i], n.level)
 
-proc overflowTreatment[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): type(n) =
+proc overflowTreatment[M, D: Dim; RT, LT](t: RStarTree[M, D, RT, LT]; n: var Node[M, D, RT, LT] | var Leaf[M, D, RT, LT]; lx: L[D, RT, LT] | N[M, D, RT, LT]): typeof(n) =
   if n.level != t.root.level and t.firstOverflow[n.level]:
     t.firstOverflow[n.level] = false
     reInsert(t, n, lx)
@@ -567,18 +547,16 @@ proc condenseTree[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; leaf: Leaf[M, D, RT
           rsinsert(RStarTree[M, D, RT, LT](t), Node[M, D, RT, LT](n).a[i], n.level)
       else:
         assert false
-  elif t of RTree[M, D, RT, LT]:
+  else:
     for n in q:
       if n of Leaf[M, D, RT, LT]:
         for i in 0 ..< n.numEntries:
-          insert(RTree[M, D, RT, LT](t), Leaf[M, D, RT, LT](n).a[i])
+          insert(t, Leaf[M, D, RT, LT](n).a[i])
       elif n of Node[M, D, RT, LT]:
         for i in 0 ..< n.numEntries:
-          insert(RTree[M, D, RT, LT](t), Node[M, D, RT, LT](n).a[i], n.level)
+          insert(t, Node[M, D, RT, LT](n).a[i], n.level)
       else:
         assert false
-  else:
-    assert false
 
 proc delete*[M, D: Dim; RT, LT](t: RTree[M, D, RT, LT]; leaf: L[D, RT, LT]): bool {.discardable.} =
   let l = findLeaf(t, leaf)
@@ -659,6 +637,4 @@ proc test(n: int) =
       assert r.len == r2.len
       assert r.sorted(system.cmp) == r2.sorted(system.cmp)
 
-test(1500)
-
-# 651 lines
+test(500)
diff --git a/tests/arc/tshared_ptr_crash.nim b/tests/arc/tshared_ptr_crash.nim
new file mode 100644
index 000000000..1794834db
--- /dev/null
+++ b/tests/arc/tshared_ptr_crash.nim
@@ -0,0 +1,67 @@
+discard """
+  cmd: "nim c --threads:on --gc:arc $file"
+  action: compile
+"""
+
+# bug #17893
+
+type
+  SharedPtr*[T] = object
+    val: ptr tuple[value: T, atomicCounter: int]
+
+proc `=destroy`*[T](p: var SharedPtr[T]) =
+  mixin `=destroy`
+  if p.val != nil:
+    if atomicLoadN(addr p.val[].atomicCounter, AtomicConsume) == 0:
+      `=destroy`(p.val[])
+      deallocShared(p.val)
+    else:
+      discard atomicDec(p.val[].atomicCounter)
+
+proc `=copy`*[T](dest: var SharedPtr[T], src: SharedPtr[T]) =
+  if src.val != nil:
+    discard atomicInc(src.val[].atomicCounter)
+  if dest.val != nil:
+    `=destroy`(dest)
+  dest.val = src.val
+
+proc newSharedPtr*[T](val: sink T): SharedPtr[T] {.nodestroy.} =
+  result.val = cast[typeof(result.val)](allocShared(sizeof(result.val[])))
+  result.val.atomicCounter = 0
+  result.val.value = val
+
+proc isNil*[T](p: SharedPtr[T]): bool {.inline.} =
+  p.val == nil
+
+proc `[]`*[T](p: SharedPtr[T]): var T {.inline.} =
+  when compileOption("boundChecks"):
+    doAssert(p.val != nil, "deferencing nil shared pointer")
+  result = p.val.value
+
+type
+  Sender*[T] = object
+    queue: SharedPtr[seq[T]]
+
+proc newSender*[T](queue: sink SharedPtr[seq[T]]): Sender[T] =
+  result = Sender[T](queue: queue)
+
+proc send*[T](self: Sender[T]; t: sink T) =
+  self.queue[].add t
+
+proc newChannel*(): Sender[int] =
+  let queue = newSharedPtr(newSeq[int]())
+  result = newSender(queue)
+
+
+var
+  p: Thread[Sender[int]]
+
+proc threadFn(tx: Sender[int]) =
+  send tx, 0
+
+proc multiThreadedChannel =
+  let tx = newChannel()
+  createThread(p, threadFn, tx)
+  joinThread(p)
+
+multiThreadedChannel()
diff --git a/tests/arc/tstrformat.nim b/tests/arc/tstrformat.nim
new file mode 100644
index 000000000..641f323da
--- /dev/null
+++ b/tests/arc/tstrformat.nim
@@ -0,0 +1,22 @@
+discard """
+  output: '''
+verstuff
+'''
+  cmd: "nim c --gc:arc $file"
+"""
+
+# bug #13622
+
+import strformat
+
+template necho*(args: string) {.dirty.} =
+  if getCurrentException() != nil:
+    echo args
+  else:
+    stdout.writeLine(args)
+
+proc main(cond: bool; arg: string) =
+  if cond:
+    necho &"ver{arg}\n"
+
+main(true, "stuff")
diff --git a/tests/arc/tstringliteral.nim b/tests/arc/tstringliteral.nim
new file mode 100644
index 000000000..c5fac22d8
--- /dev/null
+++ b/tests/arc/tstringliteral.nim
@@ -0,0 +1,17 @@
+discard """
+  matrix: "--mm:arc; --mm:orc"
+"""
+
+block: # issue #24080
+  var a = (s: "a")
+  var b = "a"
+  a.s.setLen 0
+  b = a.s
+  doAssert b == ""
+
+block: # issue #24080, longer string
+  var a = (s: "abc")
+  var b = "abc"
+  a.s.setLen 2
+  b = a.s
+  doAssert b == "ab"
diff --git a/tests/arc/tthread.nim b/tests/arc/tthread.nim
new file mode 100644
index 000000000..8a55a666e
--- /dev/null
+++ b/tests/arc/tthread.nim
@@ -0,0 +1,63 @@
+discard """
+  cmd: "nim cpp --gc:arc --threads:on $file"
+  output: '''ok1
+ok2
+destroyed
+destroyed
+destroyed
+'''
+"""
+import threadpool, os
+
+type
+  MyObj = object
+    p: int
+  MyObjRef = ref MyObj
+
+proc `=destroy`(x: var MyObj) =
+  if x.p != 0:
+    echo "destroyed"
+
+proc thread1(): string =
+  os.sleep(1000)
+  return "ok1"
+
+proc thread2(): ref string =
+  os.sleep(1000)
+  new(result)
+  result[] = "ok2"
+
+proc thread3(): ref MyObj =
+  os.sleep(1000)
+  new(result)
+  result[].p = 2
+
+var fv1 = spawn thread1()
+var fv2 = spawn thread2()
+var fv3 = spawn thread3()
+sync()
+echo ^fv1
+echo (^fv2)[]
+
+
+proc thread4(x: MyObjRef): MyObjRef {.nosinks.} =
+  os.sleep(1000)
+  result = x
+
+proc thread5(x: sink MyObjRef): MyObjRef =
+  os.sleep(1000)
+  result = x
+
+proc ref_forwarding_test =
+  var x = new(MyObj)
+  x[].p = 2
+  var y = spawn thread4(x)
+
+proc ref_sink_forwarding_test =
+  var x = new(MyObj)
+  x[].p = 2
+  var y = spawn thread5(x)
+
+ref_forwarding_test()
+ref_sink_forwarding_test()
+sync()
diff --git a/tests/arc/tunref_cycle.nim b/tests/arc/tunref_cycle.nim
new file mode 100644
index 000000000..82551b7f7
--- /dev/null
+++ b/tests/arc/tunref_cycle.nim
@@ -0,0 +1,26 @@
+discard """
+  outputsub: '''inside closure
+hello world'''
+  cmd: "nim c --gc:orc -d:useMalloc $file"
+  valgrind: true
+"""
+
+# bug #18579
+
+var fp: proc (env: pointer) {.cdecl.}
+var env: pointer
+
+proc store(f: proc (){.closure.}) =
+  proc closeOver() =
+    echo "inside closure"
+    f()
+  (fp,env) = (cast[proc(env: pointer){.cdecl.}](rawProc closeOver), rawEnv closeOver)
+  GC_ref(cast[RootRef](env))
+
+proc run() =
+  fp(env)
+  GC_unref(cast[RootRef](env))
+
+store(proc() = echo "hello world")
+run()
+GC_fullCollect()
diff --git a/tests/arc/tweave.nim b/tests/arc/tweave.nim
new file mode 100644
index 000000000..1c60ac403
--- /dev/null
+++ b/tests/arc/tweave.nim
@@ -0,0 +1,157 @@
+discard """
+  outputsub: '''Success'''
+  cmd: '''nim c --gc:arc --threads:on $file'''
+  disabled: "bsd"
+"""
+
+# bug #13936
+
+import std/atomics
+
+when defined(nimPreviewSlimSystem):
+  import std/[assertions, typedthreads]
+
+const MemBlockSize = 256
+
+type
+  ChannelSPSCSingle* = object
+    full{.align: 128.}: Atomic[bool]
+    itemSize*: uint8
+    buffer*{.align: 8.}: UncheckedArray[byte]
+
+proc `=`(
+    dest: var ChannelSPSCSingle,
+    source: ChannelSPSCSingle
+  ) {.error: "A channel cannot be copied".}
+
+proc initialize*(chan: var ChannelSPSCSingle, itemsize: SomeInteger) {.inline.} =
+  ## If ChannelSPSCSingle is used intrusive another data structure
+  ## be aware that it should be the last part due to ending by UncheckedArray
+  ## Also due to 128 bytes padding, it automatically takes half
+  ## of the default MemBlockSize
+  assert itemsize.int in 0 .. int high(uint8)
+  assert itemSize.int +
+          sizeof(chan.itemsize) +
+          sizeof(chan.full) < MemBlockSize
+
+  chan.itemSize = uint8 itemsize
+  chan.full.store(false, moRelaxed)
+
+func isEmpty*(chan: var ChannelSPSCSingle): bool {.inline.} =
+  not chan.full.load(moAcquire)
+
+func tryRecv*[T](chan: var ChannelSPSCSingle, dst: var T): bool {.inline.} =
+  ## Try receiving the item buffered in the channel
+  ## Returns true if successful (channel was not empty)
+  ##
+  ## ⚠ Use only in the consumer thread that reads from the channel.
+  assert (sizeof(T) == chan.itemsize.int) or
+          # Support dummy object
+          (sizeof(T) == 0 and chan.itemsize == 1)
+
+  let full = chan.full.load(moAcquire)
+  if not full:
+    return false
+  dst = cast[ptr T](chan.buffer.addr)[]
+  chan.full.store(false, moRelease)
+  return true
+
+func trySend*[T](chan: var ChannelSPSCSingle, src: sink T): bool {.inline.} =
+  ## Try sending an item into the channel
+  ## Reurns true if successful (channel was empty)
+  ##
+  ## ⚠ Use only in the producer thread that writes from the channel.
+  assert (sizeof(T) == chan.itemsize.int) or
+          # Support dummy object
+          (sizeof(T) == 0 and chan.itemsize == 1)
+
+  let full = chan.full.load(moAcquire)
+  if full:
+    return false
+  cast[ptr T](chan.buffer.addr)[] = src
+  chan.full.store(true, moRelease)
+  return true
+
+# Sanity checks
+# ------------------------------------------------------------------------------
+when isMainModule:
+
+  when not compileOption("threads"):
+    {.error: "This requires --threads:on compilation flag".}
+
+  template sendLoop[T](chan: var ChannelSPSCSingle,
+                       data: sink T,
+                       body: untyped): untyped =
+    while not chan.trySend(data):
+      body
+
+  template recvLoop[T](chan: var ChannelSPSCSingle,
+                       data: var T,
+                       body: untyped): untyped =
+    while not chan.tryRecv(data):
+      body
+
+  type
+    ThreadArgs = object
+      ID: WorkerKind
+      chan: ptr ChannelSPSCSingle
+
+    WorkerKind = enum
+      Sender
+      Receiver
+
+  template Worker(id: WorkerKind, body: untyped): untyped {.dirty.} =
+    if args.ID == id:
+      body
+
+  proc thread_func(args: ThreadArgs) =
+
+    # Worker RECEIVER:
+    # ---------
+    # <- chan
+    # <- chan
+    # <- chan
+    #
+    # Worker SENDER:
+    # ---------
+    # chan <- 42
+    # chan <- 53
+    # chan <- 64
+    Worker(Receiver):
+      var val: int
+      for j in 0 ..< 10:
+        args.chan[].recvLoop(val):
+          # Busy loop, in prod we might want to yield the core/thread timeslice
+          discard
+        echo "                  Receiver got: ", val
+        doAssert val == 42 + j*11
+
+    Worker(Sender):
+      doAssert args.chan.full.load(moRelaxed) == false
+      for j in 0 ..< 10:
+        let val = 42 + j*11
+        args.chan[].sendLoop(val):
+          # Busy loop, in prod we might want to yield the core/thread timeslice
+          discard
+        echo "Sender sent: ", val
+
+  proc main() =
+    echo "Testing if 2 threads can send data"
+    echo "-----------------------------------"
+    var threads: array[2, Thread[ThreadArgs]]
+
+    var chan = cast[ptr ChannelSPSCSingle](allocShared(MemBlockSize))
+    chan[].initialize(itemSize = sizeof(int))
+
+    createThread(threads[0], thread_func, ThreadArgs(ID: Receiver, chan: chan))
+    createThread(threads[1], thread_func, ThreadArgs(ID: Sender, chan: chan))
+
+    joinThread(threads[0])
+    joinThread(threads[1])
+
+    freeShared(chan)
+
+    echo "-----------------------------------"
+    echo "Success"
+
+  main()
diff --git a/tests/arc/tweavecopy.nim b/tests/arc/tweavecopy.nim
new file mode 100644
index 000000000..fc796b352
--- /dev/null
+++ b/tests/arc/tweavecopy.nim
@@ -0,0 +1,154 @@
+discard """
+  outputsub: '''Success'''
+  cmd: '''nim c --gc:arc --threads:on $file'''
+  disabled: "bsd"
+"""
+
+# bug #13936
+
+import std/atomics
+
+const MemBlockSize = 256
+
+type
+  ChannelSPSCSingle* = object
+    full{.align: 128.}: Atomic[bool]
+    itemSize*: uint8
+    buffer*{.align: 8.}: UncheckedArray[byte]
+
+proc `=copy`(
+    dest: var ChannelSPSCSingle,
+    source: ChannelSPSCSingle
+  ) {.error: "A channel cannot be copied".}
+
+proc initialize*(chan: var ChannelSPSCSingle, itemsize: SomeInteger) {.inline.} =
+  ## If ChannelSPSCSingle is used intrusive another data structure
+  ## be aware that it should be the last part due to ending by UncheckedArray
+  ## Also due to 128 bytes padding, it automatically takes half
+  ## of the default MemBlockSize
+  assert itemsize.int in 0 .. int high(uint8)
+  assert itemSize.int +
+          sizeof(chan.itemsize) +
+          sizeof(chan.full) < MemBlockSize
+
+  chan.itemSize = uint8 itemsize
+  chan.full.store(false, moRelaxed)
+
+func isEmpty*(chan: var ChannelSPSCSingle): bool {.inline.} =
+  not chan.full.load(moAcquire)
+
+func tryRecv*[T](chan: var ChannelSPSCSingle, dst: var T): bool {.inline.} =
+  ## Try receiving the item buffered in the channel
+  ## Returns true if successful (channel was not empty)
+  ##
+  ## ⚠ Use only in the consumer thread that reads from the channel.
+  assert (sizeof(T) == chan.itemsize.int) or
+          # Support dummy object
+          (sizeof(T) == 0 and chan.itemsize == 1)
+
+  let full = chan.full.load(moAcquire)
+  if not full:
+    return false
+  dst = cast[ptr T](chan.buffer.addr)[]
+  chan.full.store(false, moRelease)
+  return true
+
+func trySend*[T](chan: var ChannelSPSCSingle, src: sink T): bool {.inline.} =
+  ## Try sending an item into the channel
+  ## Reurns true if successful (channel was empty)
+  ##
+  ## ⚠ Use only in the producer thread that writes from the channel.
+  assert (sizeof(T) == chan.itemsize.int) or
+          # Support dummy object
+          (sizeof(T) == 0 and chan.itemsize == 1)
+
+  let full = chan.full.load(moAcquire)
+  if full:
+    return false
+  cast[ptr T](chan.buffer.addr)[] = src
+  chan.full.store(true, moRelease)
+  return true
+
+# Sanity checks
+# ------------------------------------------------------------------------------
+when isMainModule:
+
+  when not compileOption("threads"):
+    {.error: "This requires --threads:on compilation flag".}
+
+  template sendLoop[T](chan: var ChannelSPSCSingle,
+                       data: sink T,
+                       body: untyped): untyped =
+    while not chan.trySend(data):
+      body
+
+  template recvLoop[T](chan: var ChannelSPSCSingle,
+                       data: var T,
+                       body: untyped): untyped =
+    while not chan.tryRecv(data):
+      body
+
+  type
+    ThreadArgs = object
+      ID: WorkerKind
+      chan: ptr ChannelSPSCSingle
+
+    WorkerKind = enum
+      Sender
+      Receiver
+
+  template Worker(id: WorkerKind, body: untyped): untyped {.dirty.} =
+    if args.ID == id:
+      body
+
+  proc thread_func(args: ThreadArgs) =
+
+    # Worker RECEIVER:
+    # ---------
+    # <- chan
+    # <- chan
+    # <- chan
+    #
+    # Worker SENDER:
+    # ---------
+    # chan <- 42
+    # chan <- 53
+    # chan <- 64
+    Worker(Receiver):
+      var val: int
+      for j in 0 ..< 10:
+        args.chan[].recvLoop(val):
+          # Busy loop, in prod we might want to yield the core/thread timeslice
+          discard
+        echo "                  Receiver got: ", val
+        doAssert val == 42 + j*11
+
+    Worker(Sender):
+      doAssert args.chan.full.load(moRelaxed) == false
+      for j in 0 ..< 10:
+        let val = 42 + j*11
+        args.chan[].sendLoop(val):
+          # Busy loop, in prod we might want to yield the core/thread timeslice
+          discard
+        echo "Sender sent: ", val
+
+  proc main() =
+    echo "Testing if 2 threads can send data"
+    echo "-----------------------------------"
+    var threads: array[2, Thread[ThreadArgs]]
+
+    var chan = cast[ptr ChannelSPSCSingle](allocShared(MemBlockSize))
+    chan[].initialize(itemSize = sizeof(int))
+
+    createThread(threads[0], thread_func, ThreadArgs(ID: Receiver, chan: chan))
+    createThread(threads[1], thread_func, ThreadArgs(ID: Sender, chan: chan))
+
+    joinThread(threads[0])
+    joinThread(threads[1])
+
+    freeShared(chan)
+
+    echo "-----------------------------------"
+    echo "Success"
+
+  main()
diff --git a/tests/arc/twrong_sinkinference.nim b/tests/arc/twrong_sinkinference.nim
new file mode 100644
index 000000000..ecf09d28a
--- /dev/null
+++ b/tests/arc/twrong_sinkinference.nim
@@ -0,0 +1,18 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+  errormsg: "type mismatch: got <proc (a: string, b: sink string){.noSideEffect, gcsafe.}>"
+  line: 18
+"""
+
+type
+  Foo = proc (a, b: string)
+
+proc take(x: Foo) =
+  x("a", "b")
+
+proc willSink(a, b: string) = # {.nosinks.} =
+  var arr: array[3, string]
+  var x = a
+  arr[0] = b
+
+take willSink
diff --git a/tests/array/t15117.nim b/tests/array/t15117.nim
new file mode 100644
index 000000000..157b04bee
--- /dev/null
+++ b/tests/array/t15117.nim
@@ -0,0 +1,27 @@
+discard """
+  matrix: "--cc:vcc"
+  disabled: "linux"
+  disabled: "bsd"
+  disabled: "osx"
+  disabled: "unix"
+  disabled: "posix"
+"""
+{.experimental: "views".}
+
+let a: array[0, byte] = []
+discard a
+
+type B = object
+  a:int
+let b: array[0, B] = []
+let c: array[0, ptr B] = []
+let d: array[0, ref B] = []
+discard b
+discard c
+discard d
+
+discard default(array[0, B])
+
+type
+  View1 = openArray[byte]
+discard default(View1)
diff --git a/tests/array/t20248.nim b/tests/array/t20248.nim
new file mode 100644
index 000000000..66142548b
--- /dev/null
+++ b/tests/array/t20248.nim
@@ -0,0 +1,14 @@
+discard """
+cmd: "nim check --hints:off $file"
+errormsg: "ordinal type expected; given: Error Type"
+nimout: '''
+t20248.nim(10, 36) Error: ordinal type expected; given: Error Type
+t20248.nim(14, 20) Error: ordinal type expected; given: Error Type
+'''
+"""
+
+type Vec[N: static[int]] = array[0 ..< N, float]
+
+var v: Vec[32]
+
+var stuff: array[0 ..< 16, int]
diff --git a/tests/array/t9932.nim b/tests/array/t9932.nim
new file mode 100644
index 000000000..e3c8abba3
--- /dev/null
+++ b/tests/array/t9932.nim
@@ -0,0 +1,11 @@
+discard """
+cmd: "nim check $file"
+errormsg: "invalid type: 'typedesc[int]' in this context: 'array[0..0, typedesc[int]]' for var"
+nimout: '''
+t9932.nim(10, 5) Error: invalid type: 'type' in this context: 'array[0..0, type]' for var
+t9932.nim(11, 5) Error: invalid type: 'typedesc[int]' in this context: 'array[0..0, typedesc[int]]' for var
+'''
+"""
+
+var y: array[1,type]
+var x = [int]
diff --git a/tests/array/tarray.nim b/tests/array/tarray.nim
index 27288bab3..e9f330e3b 100644
--- a/tests/array/tarray.nim
+++ b/tests/array/tarray.nim
@@ -1,11 +1,8 @@
 discard """
 output: '''
 [4, 5, 6]
-
 [16, 25, 36]
-
 [16, 25, 36]
-
 apple
 banana
 Fruit
@@ -47,7 +44,7 @@ block tarray:
       arr: TMyarray
 
 
-  proc sum(a: openarray[int]): int =
+  proc sum(a: openArray[int]): int =
     result = 0
     var i = 0
     while i < len(a):
@@ -347,11 +344,11 @@ block troofregression:
     if $a != b:
       echo "Failure ", a, " != ", b
 
-  check type(4 ...< 1), "HSlice[system.int, system.int]"
-  check type(4 ...< ^1), "HSlice[system.int, system.BackwardsIndex]"
-  check type(4 ... pred(^1)), "HSlice[system.int, system.BackwardsIndex]"
-  check type(4 ... mypred(8)), "HSlice[system.int, system.int]"
-  check type(4 ... mypred(^1)), "HSlice[system.int, system.BackwardsIndex]"
+  check typeof(4 ...< 1), "HSlice[system.int, system.int]"
+  check typeof(4 ...< ^1), "HSlice[system.int, system.BackwardsIndex]"
+  check typeof(4 ... pred(^1)), "HSlice[system.int, system.BackwardsIndex]"
+  check typeof(4 ... mypred(8)), "HSlice[system.int, system.int]"
+  check typeof(4 ... mypred(^1)), "HSlice[system.int, system.BackwardsIndex]"
 
   var rot = 8
 
@@ -590,3 +587,21 @@ block t12466:
     a[0'u16 + i] = i
   for i in 0'u16 ..< 8'u16:
     a[0'u16 + i] = i
+
+block t17705:
+  # https://github.com/nim-lang/Nim/pull/17705
+  var a = array[0, int].low
+  a = int(a)
+  var b = array[0, int].high
+  b = int(b)
+
+block t18643:
+  # https://github.com/nim-lang/Nim/issues/18643
+  let a: array[0, int] = []
+  var caught = false
+  let b = 9999999
+  try:
+    echo a[b]
+  except IndexDefect:
+    caught = true
+  doAssert caught, "IndexDefect not caught!"
diff --git a/tests/misc/tinvalidarrayaccess.nim b/tests/array/tinvalidarrayaccess.nim
index f8bce45ef..f8bce45ef 100644
--- a/tests/misc/tinvalidarrayaccess.nim
+++ b/tests/array/tinvalidarrayaccess.nim
diff --git a/tests/misc/tinvalidarrayaccess2.nim b/tests/array/tinvalidarrayaccess2.nim
index 0a0703834..0a0703834 100644
--- a/tests/misc/tinvalidarrayaccess2.nim
+++ b/tests/array/tinvalidarrayaccess2.nim
diff --git a/tests/array/tlargeindex.nim b/tests/array/tlargeindex.nim
new file mode 100644
index 000000000..61bcbd61d
--- /dev/null
+++ b/tests/array/tlargeindex.nim
@@ -0,0 +1,18 @@
+discard """
+  cmd: "nim check --hints:off $file"
+"""
+
+# issue #17163
+var e: array[int32, byte] #[tt.Error
+             ^ index type 'int32' for array is too large]#
+var f: array[uint32, byte] #[tt.Error
+             ^ index type 'uint32' for array is too large]#
+var g: array[int64, byte] #[tt.Error
+             ^ index type 'int64' for array is too large]#
+var h: array[uint64, byte] #[tt.Error
+             ^ index type 'uint64' for array is too large]#
+
+# crash in issue #23204
+proc y[N](): array[N, int] = default(array[N, int]) #[tt.Error
+                                           ^ index type 'int' for array is too large]#
+discard y[int]()
diff --git a/tests/assert/panicoverride.nim b/tests/assert/panicoverride.nim
new file mode 100644
index 000000000..53ad64215
--- /dev/null
+++ b/tests/assert/panicoverride.nim
@@ -0,0 +1,15 @@
+# panicoverride.nim
+
+proc printf(fmt: cstring) {.varargs, importc, header:"stdio.h".}
+proc exit(code: cint) {.importc, header:"stdlib.h".}
+
+{.push stack_trace: off, profiler:off.}
+
+proc rawoutput(s: cstring) =
+  printf("RAW: %s\n", s)
+  
+proc panic(s: cstring) {.noreturn.} =
+  printf("PANIC: %s\n", s)
+  exit(0)
+
+{.pop.}
\ No newline at end of file
diff --git a/tests/assert/t21195.nim b/tests/assert/t21195.nim
new file mode 100644
index 000000000..b690d22a0
--- /dev/null
+++ b/tests/assert/t21195.nim
@@ -0,0 +1,6 @@
+discard """
+  matrix: "--verbosity:0 --os:standalone --mm:none"
+"""
+# bug #21195
+var n = 11
+assert(n == 12)
diff --git a/tests/assert/tassert.nim b/tests/assert/tassert.nim
index 99929f080..a14fec317 100644
--- a/tests/assert/tassert.nim
+++ b/tests/assert/tassert.nim
@@ -10,7 +10,7 @@ proc callC() = callA()
 
 try:
   callC()
-except AssertionError:
+except AssertionDefect:
   write(stdout, "assertion failure!")
 except:
   write(stdout, "unknown exception!")
diff --git a/tests/assert/tassert2.nim b/tests/assert/tassert2.nim
index 50753ba11..e32ab72e1 100644
--- a/tests/assert/tassert2.nim
+++ b/tests/assert/tassert2.nim
@@ -1,59 +1,44 @@
 discard """
   output: '''
-test1:ok
-test2:ok
-test3:ok
-test4:ok
-test5:ok
-test6:ok
-test7:ok
+`false` first assertion from bar
+`false` second assertion from bar
 -1
-tassert2.nim
-test8:ok
-test9:ok
-test10:ok
-test11:ok
 '''
 """
-import testhelper
+from strutils import endsWith
+
 type
   TLineInfo = tuple[filename: string, line: int, column: int]
   TMyError = object of Exception
     lineinfo: TLineInfo
   EMyError = ref TMyError
 
-echo("")
 
 # NOTE: when entering newlines, adjust `expectedEnd` outputs
 
 try:
   doAssert(false, "msg1") # doAssert test
-except AssertionError as e:
-  checkMsg(e.msg, "tassert2.nim(30, 11) `false` msg1", "test1")
-
-try:
-  assert false, "msg2"  # assert test
-except AssertionError as e:
-  checkMsg(e.msg, "tassert2.nim(35, 10) `false` msg2", "test2")
+except AssertionDefect as e:
+  assert e.msg.endsWith "tassert2.nim(20, 11) `false` msg1"
 
 try:
   assert false # assert test with no msg
-except AssertionError as e:
-  checkMsg(e.msg, "tassert2.nim(40, 10) `false` ", "test3")
+except AssertionDefect as e:
+  assert e.msg.endsWith "tassert2.nim(25, 3) `false` "
 
 try:
   let a = 1
   doAssert(a+a==1) # assert test with Ast expression
   # BUG: const folding would make "1+1==1" appear as `false` in
   # assert message
-except AssertionError as e:
-  checkMsg(e.msg, "`a + a == 1` ", "test4")
+except AssertionDefect as e:
+  assert e.msg.endsWith "`a + a == 1` "
 
 try:
   let a = 1
   doAssert a+a==1 # ditto with `doAssert` and no parens
-except AssertionError as e:
-  checkMsg(e.msg, "`a + a == 1` ", "test5")
+except AssertionDefect as e:
+  assert e.msg.endsWith "`a + a == 1` "
 
 proc fooStatic() =
   # protect against https://github.com/nim-lang/Nim/issues/8758
@@ -80,12 +65,12 @@ block:
   proc bar: int =
     # local overrides that are active only in this proc
     onFailedAssert(msg):
-      checkMsg(msg, "tassert2.nim(85, 11) `false` first assertion from bar", "test6")
+      echo msg[^32..^1]
 
     assert(false, "first assertion from bar")
 
     onFailedAssert(msg):
-      checkMsg(msg, "tassert2.nim(91, 11) `false` second assertion from bar", "test7")
+      echo msg[^33..^1]
       return -1
 
     assert(false, "second assertion from bar")
@@ -97,8 +82,7 @@ block:
     foo()
   except:
     let e = EMyError(getCurrentException())
-    echo e.lineinfo.filename
-    checkMsg(e.msg, "tassert2.nim(77, 11) `false` assertion from foo", "test8")
+    assert e.msg.endsWith "tassert2.nim(62, 11) `false` assertion from foo"
 
 block: ## checks for issue https://github.com/nim-lang/Nim/issues/8518
   template fun(a: string): string =
@@ -107,21 +91,21 @@ block: ## checks for issue https://github.com/nim-lang/Nim/issues/8518
 
   try:
     doAssert fun("foo1") == fun("foo2"), "mymsg"
-  except AssertionError as e:
+  except AssertionDefect as e:
     # used to expand out the template instantiaiton, sometimes filling hundreds of lines
-    checkMsg(e.msg, """tassert2.nim(109, 14) `fun("foo1") == fun("foo2")` mymsg""", "test9")
+    assert e.msg.endsWith ""
 
 block: ## checks for issue https://github.com/nim-lang/Nim/issues/9301
   try:
     doAssert 1 + 1 == 3
-  except AssertionError as e:
+  except AssertionDefect as e:
     # used to const fold as false
-    checkMsg(e.msg, "tassert2.nim(116, 14) `1 + 1 == 3` ", "test10")
+    assert e.msg.endsWith "tassert2.nim(100, 5) `1 + 1 == 3` "
 
 block: ## checks AST isn't transformed as it used to
   let a = 1
   try:
     doAssert a > 1
-  except AssertionError as e:
+  except AssertionDefect as e:
     # used to rewrite as `1 < a`
-    checkMsg(e.msg, "tassert2.nim(124, 14) `a > 1` ", "test11")
+    assert e.msg.endsWith "tassert2.nim(108, 5) `a > 1` "
diff --git a/tests/assert/tassert_c.nim b/tests/assert/tassert_c.nim
index 84ccea823..e3e3b8147 100644
--- a/tests/assert/tassert_c.nim
+++ b/tests/assert/tassert_c.nim
@@ -1,14 +1,14 @@
 discard """
-  cmd: "nim $target $options --excessiveStackTrace:off $file"
+  matrix: "-d:nimPreviewSlimSystem --stackTrace:on --excessiveStackTrace:off"
   output: '''true'''
 """
-
+import std/assertions
 const expected = """
 tassert_c.nim(35)        tassert_c
 tassert_c.nim(34)        foo
-assertions.nim(27)       failedAssertImpl
-assertions.nim(20)       raiseAssert
-fatal.nim(55)            sysFatal"""
+assertions.nim(*)       failedAssertImpl
+assertions.nim(*)       raiseAssert
+"""
 
 proc tmatch(x, p: string): bool =
   var i = 0
@@ -33,7 +33,8 @@ try:
   proc foo() =
     assert(false)
   foo()
-except AssertionError:
+except AssertionDefect:
   let e = getCurrentException()
   let trace = e.getStackTrace
-  echo tmatch(trace, expected)
+  if tmatch(trace, expected): echo true
+  else: echo "wrong trace:\n" & trace
diff --git a/tests/assert/tdoassert.nim b/tests/assert/tdoassert.nim
deleted file mode 100644
index fa9893505..000000000
--- a/tests/assert/tdoassert.nim
+++ /dev/null
@@ -1,20 +0,0 @@
-discard """
-  cmd: "nim $target -d:release $options $file"
-  output: '''
-test1:ok
-test2:ok
-'''
-"""
-
-import testhelper
-
-onFailedAssert(msg):
-  checkMsg(msg, "tdoassert.nim(15, 9) `a == 2` foo", "test1")
-
-var a = 1
-doAssert(a == 2, "foo")
-
-onFailedAssert(msg):
-  checkMsg(msg, "tdoassert.nim(20, 10) `a == 3` ", "test2")
-
-doAssert a == 3
diff --git a/tests/assert/testhelper.nim b/tests/assert/testhelper.nim
deleted file mode 100644
index 03bdd2468..000000000
--- a/tests/assert/testhelper.nim
+++ /dev/null
@@ -1,12 +0,0 @@
-from strutils import endsWith, split
-from os import isAbsolute
-
-proc checkMsg*(msg, expectedEnd, name: string, absolute = true)=
-  let filePrefix = msg.split(' ', maxSplit = 1)[0]
-  if absolute and not filePrefix.isAbsolute:
-    echo name, ":not absolute: `", msg & "`"
-  elif not msg.endsWith expectedEnd:
-    echo name, ":expected suffix:\n`" & expectedEnd & "`\ngot:\n`" & msg & "`"
-  else:
-    echo name, ":ok"
-
diff --git a/tests/assert/trelativeassert.nim b/tests/assert/trelativeassert.nim
deleted file mode 100644
index 62ab2c421..000000000
--- a/tests/assert/trelativeassert.nim
+++ /dev/null
@@ -1,11 +0,0 @@
-discard """
-  cmd: "nim $target $options --excessiveStackTrace:off $file"
-  output: '''
-test:ok
-'''
-"""
-import testhelper
-try:
-  doAssert(false, "msg")
-except AssertionError as e:
-  checkMsg(e.msg, "trelativeassert.nim(9, 11) `false` msg", "test", false)
diff --git a/tests/assign/moverload_asgn2.nim b/tests/assign/moverload_asgn2.nim
index 6620adbeb..cfea48cd1 100644
--- a/tests/assign/moverload_asgn2.nim
+++ b/tests/assign/moverload_asgn2.nim
@@ -1,3 +1,7 @@
+discard """
+  matrix: "--mm:refc"
+"""
+
 type
   Concrete* = object
     a*, b*: string
diff --git a/tests/assign/tassign.nim b/tests/assign/tassign.nim
index 0589b0214..fdec04d22 100644
--- a/tests/assign/tassign.nim
+++ b/tests/assign/tassign.nim
@@ -80,7 +80,7 @@ block tcopy:
 
 block tgenericassign:
   type
-    TAny = object {.pure.}
+    TAny {.pure.} = object
       value: pointer
       rawType: pointer
 
@@ -93,9 +93,9 @@ block tgenericassign:
   var ret: seq[tuple[name: string, a: TAny]] = @[]
   for i in 0 .. 8000:
     var tup = ($name, newAny(nil, nil))
-    assert(tup[0] == "example")
+    doAssert(tup[0] == "example")
     ret.add(tup)
-    assert(ret[ret.len()-1][0] == "example")
+    doAssert(ret[ret.len()-1][0] == "example")
 
 
 
@@ -178,7 +178,7 @@ when false:
   proc `=`[T](d: var GenericT[T]; src: GenericT[T]) =
     shallowCopy(d.a, src.a)
     shallowCopy(d.b, src.b)
-    echo "GenericT[T] '=' ", type(T).name
+    echo "GenericT[T] '=' ", typeof(T).name
 
   var ag: GenericT[int]
   var bg: GenericT[int]
diff --git a/tests/assign/tobject_assign.nim b/tests/assign/tobject_assign.nim
new file mode 100644
index 000000000..8e39ead53
--- /dev/null
+++ b/tests/assign/tobject_assign.nim
@@ -0,0 +1,49 @@
+# bug #16706
+
+block: # reduced example
+  type
+    A = object of RootObj
+      a0: string
+    B = object
+      b0: seq[A]
+  var c = newSeq[A](2)
+  var d = B(b0: c)
+
+when true: # original example
+  import std/[options, tables, times]
+
+  type
+    Data* = object
+      shifts*: OrderedTable[int64, Shift]
+      balance*: float
+
+    Shift* = object
+      quoted*: bool
+      date*: DateTime
+      description*: string
+      start*: Option[DateTime]
+      finish*: Option[DateTime]
+      breakTime*: Option[Duration]
+      rate*: float
+      qty: Option[float]
+      id*: int64
+
+  let shift = Shift(
+    quoted: true,
+    date: parse("2000-01-01", "yyyy-MM-dd"),
+    description: "abcdef",
+    start: none(DateTime),
+    finish: none(DateTime),
+    breakTime: none(Duration),
+    rate: 462.11,
+    qty: some(10.0),
+    id: getTime().toUnix()
+  )
+
+  var shifts: OrderedTable[int64, Shift]
+  shifts[shift.id] = shift
+
+  discard Data(
+    shifts: shifts,
+    balance: 0.00
+  )
diff --git a/tests/assign/tvariantasgn.nim b/tests/assign/tvariantasgn.nim
index 1c3deeae1..4c3c38ca5 100644
--- a/tests/assign/tvariantasgn.nim
+++ b/tests/assign/tvariantasgn.nim
@@ -24,3 +24,16 @@ s = TAny(kind: nkInt, intVal: 78)
 # s = nr # works
 nr = s # fails!
 echo "came here"
+
+block: # bug #12464
+  type
+    Foo = object
+      case isFunc: bool
+      of false: nil
+      of true:
+        fun: proc(): int
+
+  const i = Foo(isFunc: false)
+
+  let j = i
+  doAssert not j.isFunc
diff --git a/tests/ast_pattern_matching.nim b/tests/ast_pattern_matching.nim
index c08234b9e..0ba0aa57a 100644
--- a/tests/ast_pattern_matching.nim
+++ b/tests/ast_pattern_matching.nim
@@ -133,8 +133,8 @@ proc matchLengthKind*(arg: NimNode; kind: NimNodeKind; length: int): MatchingErr
   matchLengthKind(arg, {kind}, length)
 
 proc matchValue(arg: NimNode; kind: set[NimNodeKind]; value: SomeInteger): MatchingError {.compileTime.} =
-  let kindFail   = not(kind.card == 0 or arg.kind in kind)
-  let valueFail  = arg.intVal != int(value)
+  template kindFail: bool  = not(kind.card == 0 or arg.kind in kind)
+  template valueFail: bool = arg.intVal != int(value)
   if kindFail or valueFail:
     result.node = arg
     result.kind = WrongKindValue
@@ -561,7 +561,7 @@ when isMainModule:
         echo "got the ident m"
 
     testRecCase:
-      type Obj[T] = object {.inheritable.}
+      type Obj[T] {.inheritable.} = object
         name: string
         case isFat: bool
         of true:
diff --git a/tests/astspec/tastspec.nim b/tests/astspec/tastspec.nim
index e2cfed277..c99d8ec79 100644
--- a/tests/astspec/tastspec.nim
+++ b/tests/astspec/tastspec.nim
@@ -327,19 +327,43 @@ static:
 
   testArrayAccessOperator(x[y])
 
-
-
   ## Parentheses
 
   scope:
-
     let ast = myquote:
-      (1, 2, (3))
+      (a + b) * c
 
     ast.matchAst:
-    of nnkPar(nnkIntLit(intVal = 1), nnkIntLit(intVal = 2), nnkPar(nnkIntLit(intVal = 3))):
-      echo "ok"
+    of nnkInfix(ident"*", nnkPar(nnkInfix(ident"+", ident"a", ident"b")), ident"c"):
+      echo "parentheses ok"
 
+  ## Tuple Constructors
+
+  scope:
+    let ast = myquote:
+      (1, 2, 3)
+      (a: 1, b: 2, c: 3)
+      (1,)
+      (a: 1)
+      ()
+
+    for it in ast:
+      echo it.lispRepr
+      it.matchAst:
+      of nnkTupleConstr(nnkIntLit(intVal = 1), nnkIntLit(intVal = 2), nnkIntLit(intVal = 3)):
+        echo "simple tuple ok"
+      of nnkTupleConstr(
+        nnkExprColonExpr(ident"a", nnkIntLit(intVal = 1)),
+        nnkExprColonExpr(ident"b", nnkIntLit(intVal = 2)),
+        nnkExprColonExpr(ident"c", nnkIntLit(intVal = 3))
+      ):
+        echo "named tuple ok"
+      of nnkTupleConstr(nnkIntLit(intVal = 1)):
+        echo "one tuple ok"
+      of nnkTupleConstr(nnkExprColonExpr(ident"a", nnkIntLit(intVal = 1))):
+        echo "named one tuple ok"
+      of nnkTupleConstr():
+       echo "empty tuple ok"
 
   ## Curly braces
 
@@ -847,11 +871,20 @@ static:
 
   scope:
     macro testRecCase(ast: untyped): untyped =
-      ast.peelOff({nnkStmtList, nnkTypeSection})[2].matchAst:
-      of nnkObjectTy(
-        nnkPragma(
-          ident"inheritable"
+      ast.peelOff({nnkStmtList, nnkTypeSection}).matchAst:
+      of nnkTypeDef(
+        nnkPragmaExpr(
+          ident"Obj",
+          nnkPragma(ident"inheritable")
         ),
+        nnkGenericParams(
+        nnkIdentDefs(
+          ident"T",
+          nnkEmpty(),
+          nnkEmpty())
+        ),
+        nnkObjectTy(
+        nnkEmpty(),
         nnkEmpty(),
         nnkRecList( # list of object parameters
           nnkIdentDefs(
@@ -890,6 +923,7 @@ static:
                     ident"T"
                   ),
                   nnkEmpty()
+                  )
                 )
               )
             )
@@ -898,10 +932,8 @@ static:
       ):
         echo "ok"
 
-
-
     testRecCase:
-      type Obj[T] = object {.inheritable.}
+      type Obj[T] {.inheritable.} = object
         name: string
         case isFat: bool
         of true:
diff --git a/tests/async/nim.cfg b/tests/async/nim.cfg
new file mode 100644
index 000000000..be50f572c
--- /dev/null
+++ b/tests/async/nim.cfg
@@ -0,0 +1 @@
+--experimental:strictEffects
diff --git a/tests/async/t11558.nim b/tests/async/t11558.nim
new file mode 100644
index 000000000..99961e7b6
--- /dev/null
+++ b/tests/async/t11558.nim
@@ -0,0 +1,13 @@
+discard """
+output: "Hello\n9"
+"""
+import std/asyncdispatch
+
+proc foo(): Future[string] {.async.} =
+  "Hello"
+
+proc bar(): Future[int] {.async.} =
+  result = 9
+
+echo waitFor foo()
+echo waitFor bar()
diff --git a/tests/async/t12221.nim b/tests/async/t12221.nim
index a6ccfb060..e8bd9c11a 100644
--- a/tests/async/t12221.nim
+++ b/tests/async/t12221.nim
@@ -1,13 +1,13 @@
 import asyncdispatch, os, times
 
 proc doubleSleep(hardSleep: int) {.async.} =
-  await sleepAsync(100)
+  await sleepAsync(50)
   sleep(hardSleep)
 
 template assertTime(target, timeTook: float): untyped {.dirty.} =
-  assert(timeTook*1000 > target - 1000, "Took too short, should've taken " &
+  doAssert(timeTook*1000 > target - 1000, "Took too short, should've taken " &
     $target & "ms, but took " & $(timeTook*1000) & "ms")
-  assert(timeTook*1000 < target + 1000, "Took too long, should've taken " &
+  doAssert(timeTook*1000 < target + 1000, "Took too long, should've taken " &
     $target & "ms, but took " & $(timeTook*1000) & "ms")
 
 var
@@ -16,37 +16,25 @@ var
 
 # NOTE: this uses poll(3000) to limit timing error potential.
 start = epochTime()
-fut = sleepAsync(50) and sleepAsync(150) and doubleSleep(40)
+fut = sleepAsync(40) and sleepAsync(100) and doubleSleep(20)
 while not fut.finished:
-  poll(3000)
+  poll(1000)
 assertTime(150, epochTime() - start)
 
 start = epochTime()
-fut = sleepAsync(50) and sleepAsync(150) and doubleSleep(100)
+fut = sleepAsync(40) and sleepAsync(100) and doubleSleep(50)
 while not fut.finished:
-  poll(3000)
+  poll(1000)
 assertTime(200, epochTime() - start)
 
 start = epochTime()
-fut = sleepAsync(50) and sleepAsync(150) and doubleSleep(40) and sleepAsync(300)
+fut = sleepAsync(40) and sleepAsync(100) and doubleSleep(20) and sleepAsync(200)
 while not fut.finished:
-  poll(3000)
+  poll(1000)
 assertTime(300, epochTime() - start)
 
 start = epochTime()
-fut = sleepAsync(50) and sleepAsync(150) and doubleSleep(100) and sleepAsync(300)
+fut = (sleepAsync(40) and sleepAsync(100) and doubleSleep(20)) or sleepAsync(300)
 while not fut.finished:
-  poll(3000)
-assertTime(300, epochTime() - start)
-
-start = epochTime()
-fut = (sleepAsync(50) and sleepAsync(150) and doubleSleep(40)) or sleepAsync(700)
-while not fut.finished:
-  poll(3000)
+  poll(1000)
 assertTime(150, epochTime() - start)
-
-start = epochTime()
-fut = (sleepAsync(50) and sleepAsync(150) and doubleSleep(100)) or sleepAsync(700)
-while not fut.finished:
-  poll(3000)
-assertTime(200, epochTime() - start)
diff --git a/tests/async/t13889.nim b/tests/async/t13889.nim
new file mode 100644
index 000000000..fe75fe38a
--- /dev/null
+++ b/tests/async/t13889.nim
@@ -0,0 +1,27 @@
+discard """
+  output: '''
+believer Foo is saved:true
+believer Bar is saved:true
+believer Baz is saved:true
+'''
+"""
+
+import asyncdispatch
+
+var
+  promise = newFuture[bool]()
+
+proc believers(name: string) {.async.} =
+  let v = await promise
+  echo "believer " & name & " is saved:" & $v
+
+asyncCheck believers("Foo")
+asyncCheck believers("Bar")
+asyncCheck believers("Baz")
+
+proc savior() {.async.} =
+  await sleepAsync(50)
+  complete(promise, true)
+  await sleepAsync(50) # give enough time to see who was saved
+
+waitFor(savior())
diff --git a/tests/async/t14820.nim b/tests/async/t14820.nim
new file mode 100644
index 000000000..359884468
--- /dev/null
+++ b/tests/async/t14820.nim
@@ -0,0 +1,25 @@
+discard """
+output: '''
+iteration: 1
+iteration: 2
+iteration: 3
+iteration: 4
+async done
+iteration: 5
+'''
+"""
+
+import asyncdispatch, times
+
+var done = false
+proc somethingAsync() {.async.} =
+  yield sleepAsync 5000
+  echo "async done"
+  done = true
+  
+asyncCheck somethingAsync()
+var count = 0
+while not done:
+  count += 1
+  drain 1000
+  echo "iteration: ", count 
diff --git a/tests/async/t15148.nim b/tests/async/t15148.nim
new file mode 100644
index 000000000..ba14c1157
--- /dev/null
+++ b/tests/async/t15148.nim
@@ -0,0 +1,12 @@
+import asyncdispatch, asyncfile, os
+
+const Filename = "t15148.txt"
+
+proc saveEmpty() {.async.} =
+  let
+    text = ""
+    file = openAsync(Filename, fmWrite)
+  await file.write(text)
+  file.close()
+
+waitFor saveEmpty()
diff --git a/tests/async/t15804.nim b/tests/async/t15804.nim
new file mode 100644
index 000000000..8de012196
--- /dev/null
+++ b/tests/async/t15804.nim
@@ -0,0 +1,15 @@
+import asyncdispatch
+
+type
+  Foo*[E] = ref object 
+    op: proc(): Future[bool] {.gcsafe.}
+
+proc newFoo*[E](): Foo[E] =
+  result = Foo[E]()
+  result.op = proc(): Future[bool] {.gcsafe,async.} =
+    await sleepAsync(100)
+    result = false
+
+when isMainModule:
+  let f = newFoo[int]()
+  echo waitFor f.op()
diff --git a/tests/async/t17045.nim b/tests/async/t17045.nim
new file mode 100644
index 000000000..2b5acf48a
--- /dev/null
+++ b/tests/async/t17045.nim
@@ -0,0 +1,28 @@
+discard """
+  targets: "c cpp"
+  matrix: "--mm:refc; --mm:arc"
+"""
+
+type Future = ref object
+
+iterator paths: string = 
+  # without "when nimvm" everything works
+  when nimvm:
+    yield "test.md"
+  else:
+    yield "test.md"
+
+template await(f: Future): string =
+  # need this yield, also the template has to return something
+  yield f
+  "hello world"
+
+proc generatePostContextsAsync() =
+  iterator generatePostContextsAsyncIter(): Future {.closure.} =
+    for filePath in paths():
+      var temp = await Future()
+
+  # need this line
+  var nameIterVar = generatePostContextsAsyncIter
+
+generatePostContextsAsync()
\ No newline at end of file
diff --git a/tests/async/t20111.nim b/tests/async/t20111.nim
new file mode 100644
index 000000000..0aaa7d886
--- /dev/null
+++ b/tests/async/t20111.nim
@@ -0,0 +1,19 @@
+discard """
+  action: "run"
+"""
+import asyncdispatch
+type
+    Sync = object
+    Async = object
+    SyncRes = (Sync, string)
+    AsyncRes = (Async, string)
+
+proc foo(val: Sync | Async): Future[(Async, string) | (Sync, string)] {.multisync.} =
+    return (val, "hello")
+
+let
+  myAsync = Async()
+  mySync = Sync()
+
+doAssert typeof(waitFor foo(myAsync)) is AsyncRes
+doAssert typeof(foo(mySync)) is SyncRes
diff --git a/tests/async/t21447.nim b/tests/async/t21447.nim
new file mode 100644
index 000000000..e4f7ae31f
--- /dev/null
+++ b/tests/async/t21447.nim
@@ -0,0 +1,6 @@
+discard """
+  action: "compile"
+  cmd: "nim c -d:release -d:futureLogging $file"
+"""
+
+import std/asyncdispatch
diff --git a/tests/async/t21893.nim b/tests/async/t21893.nim
new file mode 100644
index 000000000..658cb02eb
--- /dev/null
+++ b/tests/async/t21893.nim
@@ -0,0 +1,13 @@
+discard """
+output: "@[97]\ntrue"
+"""
+
+import asyncdispatch
+
+proc test(): Future[bool] {.async.} =
+  const S4 = @[byte('a')]
+  echo S4
+  return true
+
+echo waitFor test()
+
diff --git a/tests/async/t22210.nim b/tests/async/t22210.nim
new file mode 100644
index 000000000..fcf939472
--- /dev/null
+++ b/tests/async/t22210.nim
@@ -0,0 +1,41 @@
+discard """
+output: '''
+stage 1
+stage 2
+stage 3
+(status: 200, data: "SOMEDATA")
+'''
+"""
+
+import std/asyncdispatch
+
+
+# bug #22210
+type
+  ClientResponse = object
+    status*: int
+    data*: string
+
+proc subFoo1(): Future[int] {.async.} =
+  await sleepAsync(100)
+  return 200
+
+proc subFoo2(): Future[string] {.async.} =
+  await sleepAsync(100)
+  return "SOMEDATA"
+
+proc testFoo(): Future[ClientResponse] {.async.} =
+  try:
+    let status = await subFoo1()
+    doAssert(status == 200)
+    let data = await subFoo2()
+    return ClientResponse(status: status, data: data)
+  finally:
+    echo "stage 1"
+    await sleepAsync(100)
+    echo "stage 2"
+    await sleepAsync(200)
+    echo "stage 3"
+
+when isMainModule:
+  echo waitFor testFoo()
\ No newline at end of file
diff --git a/tests/async/t22210_2.nim b/tests/async/t22210_2.nim
new file mode 100644
index 000000000..9db664a32
--- /dev/null
+++ b/tests/async/t22210_2.nim
@@ -0,0 +1,73 @@
+import std/asyncdispatch
+
+
+# bug #22210
+type
+  ClientResponse = object
+    status*: int
+    data*: string
+
+proc subFoo1(): Future[int] {.async.} =
+  await sleepAsync(100)
+  return 200
+
+proc subFoo2(): Future[string] {.async.} =
+  await sleepAsync(100)
+  return "SOMEDATA"
+
+
+proc testFoo2(): Future[ClientResponse] {.async.} =
+  var flag = 0
+  try:
+    let status = await subFoo1()
+    doAssert(status == 200)
+    let data = await subFoo2()
+    result = ClientResponse(status: status, data: data)
+  finally:
+    inc flag
+    await sleepAsync(100)
+    inc flag
+    await sleepAsync(200)
+    inc flag
+  doAssert flag == 3
+
+discard waitFor testFoo2()
+
+proc testFoo3(): Future[ClientResponse] {.async.} =
+  var flag = 0
+  try:
+    let status = await subFoo1()
+    doAssert(status == 200)
+    let data = await subFoo2()
+    if false:
+      return ClientResponse(status: status, data: data)
+  finally:
+    inc flag
+    await sleepAsync(100)
+    inc flag
+    await sleepAsync(200)
+    inc flag
+  doAssert flag == 3
+
+discard waitFor testFoo3()
+
+
+proc testFoo4(): Future[ClientResponse] {.async.} =
+  var flag = 0
+  try:
+    let status = await subFoo1()
+    doAssert(status == 200)
+    let data = await subFoo2()
+    if status == 200:
+      return ClientResponse(status: status, data: data)
+    else:
+      return ClientResponse()
+  finally:
+    inc flag
+    await sleepAsync(100)
+    inc flag
+    await sleepAsync(200)
+    inc flag
+  doAssert flag == 3
+
+discard waitFor testFoo4()
diff --git a/tests/async/t6846.nim b/tests/async/t6846.nim
index 687a3f865..7fe38f3b3 100644
--- a/tests/async/t6846.nim
+++ b/tests/async/t6846.nim
@@ -6,11 +6,10 @@ discard """
 
 import asyncdispatch
 import asyncfile
-import times
 
 var asyncStdout = 1.AsyncFD.newAsyncFile()
 proc doStuff: Future[void] {.async.} =
   await asyncStdout.write "hello world\n"
 
 let fut = doStuff()
-doAssert fut.finished, "Poll is needed unnecessarily. See #6846."
\ No newline at end of file
+doAssert fut.finished, "Poll is needed unnecessarily. See #6846."
diff --git a/tests/async/t7758.nim b/tests/async/t7758.nim
index ce4df1fc9..fe6d32ad3 100644
--- a/tests/async/t7758.nim
+++ b/tests/async/t7758.nim
@@ -1,7 +1,9 @@
 import asyncdispatch
+import std/unittest
 
 proc task() {.async.} =
-  await sleepAsync(40)
+  const tSleep = 40
+  await sleepAsync(tSleep)
 
 proc main() =
   var counter = 0
@@ -10,6 +12,10 @@ proc main() =
     inc(counter)
     poll(10)
 
-  doAssert counter <= 4
+  const slack = 1
+    # because there is overhead in `async` + `sleepAsync`
+    # as can be seen by increasing `tSleep` from 40 to 49, which increases the number
+    # of failures.
+  check counter <= 4 + slack
 
 for i in 0 .. 10: main()
diff --git a/tests/async/tacceptcloserace.nim b/tests/async/tacceptcloserace.nim
index cbb5b5098..fee6537d2 100644
--- a/tests/async/tacceptcloserace.nim
+++ b/tests/async/tacceptcloserace.nim
@@ -8,7 +8,7 @@ import asyncdispatch, net, os, nativesockets
 # bug: https://github.com/nim-lang/Nim/issues/5279
 
 proc setupServerSocket(hostname: string, port: Port): AsyncFD =
-  let fd = newNativeSocket()
+  let fd = createNativeSocket()
   if fd == osInvalidSocket:
     raiseOSError(osLastError())
   setSockOptInt(fd, SOL_SOCKET, SO_REUSEADDR, 1)
@@ -30,7 +30,7 @@ for i in 0..100:
     if not fut.failed:
       fut.read().closeSocket()
 
-  var fd = newAsyncNativeSocket()
+  var fd = createAsyncNativeSocket()
   waitFor fd.connect("localhost", port)
   serverFd.closeSocket()
   fd.closeSocket()
diff --git a/tests/async/tasync_gcsafe.nim b/tests/async/tasync_gcsafe.nim
index 89df6456a..bc0eb4271 100644
--- a/tests/async/tasync_gcsafe.nim
+++ b/tests/async/tasync_gcsafe.nim
@@ -7,7 +7,7 @@ discard """
 '''
 """
 
-assert compileOption("threads"), "this test will not do anything useful without --threads:on"
+doAssert compileOption("threads"), "this test will not do anything useful without --threads:on"
 
 import asyncdispatch
 
diff --git a/tests/async/tasync_gcunsafe.nim b/tests/async/tasync_gcunsafe.nim
index 55b66aaef..f3e6bc691 100644
--- a/tests/async/tasync_gcunsafe.nim
+++ b/tests/async/tasync_gcunsafe.nim
@@ -1,10 +1,10 @@
 discard """
-  errormsg: "'anotherGCSafeAsyncProcIter' is not GC-safe as it calls 'asyncGCUnsafeProc'"
+  errormsg: "'anotherGCSafeAsyncProc (Async)' is not GC-safe as it calls 'asyncGCUnsafeProc'"
   cmd: "nim c --threads:on $file"
   file: "asyncmacro.nim"
 """
 
-assert compileOption("threads"), "this test will not do anything useful without --threads:on"
+doAssert compileOption("threads"), "this test will not do anything useful without --threads:on"
 
 import asyncdispatch
 
diff --git a/tests/async/tasync_misc.nim b/tests/async/tasync_misc.nim
index 1febdedb3..ec1418e8c 100644
--- a/tests/async/tasync_misc.nim
+++ b/tests/async/tasync_misc.nim
@@ -1,19 +1,14 @@
-discard """
-  exitcode: 0
-  output: "ok"
-"""
-
 import json, asyncdispatch
 block: #6100
   let done = newFuture[int]()
   done.complete(1)
 
   proc asyncSum: Future[int] {.async.} =
-    for _ in 1..10_000_000:
+    for _ in 1..1_000_000:
       result += await done
 
   let res = waitFor asyncSum()
-  doAssert(res == 10000000)
+  doAssert(res == 1_000_000)
 
 block: #7985
   proc getData(): Future[JsonNode] {.async.} =
@@ -53,4 +48,36 @@ block: # nkCheckedFieldExpr
 
   waitFor foo()
 
-echo "ok"
+block: # 12743
+
+  template templ = await sleepAsync 0
+
+  proc prc {.async.} = templ
+
+  waitFor prc()
+
+block: # issue #13899
+  proc someConnect() {.async.} =
+    await sleepAsync(1)
+  proc someClose() {.async.} =
+    await sleepAsync(2)
+  proc testFooFails(): Future[bool] {.async.} =
+    await someConnect()
+    defer:
+      await someClose()
+      result = true
+  proc testFooSucceed(): Future[bool] {.async.} =
+    try:
+      await someConnect()
+    finally:
+      await someClose()
+      result = true
+  doAssert waitFor testFooSucceed()
+  doAssert waitFor testFooFails()
+
+block: # issue #9313
+  doAssert compiles(block:
+    proc a() {.async.} =
+      echo "Hi"
+      quit(0)
+  )
diff --git a/tests/async/tasync_noasync.nim b/tests/async/tasync_noasync.nim
new file mode 100644
index 000000000..0927148bf
--- /dev/null
+++ b/tests/async/tasync_noasync.nim
@@ -0,0 +1,44 @@
+discard """
+  cmd: "nim check --hints:off --warnings:off $file"
+  action: "reject"
+  nimout: '''
+tasync_noasync.nim(21, 10) Error: Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead
+tasync_noasync.nim(25, 12) Error: Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead
+tasync_noasync.nim(28, 10) Error: Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead
+tasync_noasync.nim(31, 10) Error: Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead
+tasync_noasync.nim(35, 10) Error: Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead
+tasync_noasync.nim(38, 10) Error: Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead
+tasync_noasync.nim(40, 8) Error: Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead
+'''
+"""
+import async
+
+proc a {.async.} =
+  discard
+
+# Bad await usage
+proc nonAsyncProc =
+  await a()
+
+proc nestedNonAsyncProc {.async.} =
+  proc nested =
+    await a()
+
+iterator customIterator: int =
+  await a()
+
+macro awaitInMacro =
+  await a()
+
+type DummyRef = ref object of RootObj
+method awaitInMethod(_: DummyRef) {.base.} =
+  await a()
+
+proc improperMultisync {.multisync.} =
+  await a()
+
+await a()
+
+# if we overload a fallback handler to get
+# await only available within {.async.}
+# we would need `{.dirty.}` templates for await
diff --git a/tests/async/tasync_nofuture.nim b/tests/async/tasync_nofuture.nim
new file mode 100644
index 000000000..16155601a
--- /dev/null
+++ b/tests/async/tasync_nofuture.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "await expects Future[T], got int"
+  cmd: "nim c $file"
+  file: "asyncmacro.nim"
+"""
+import async
+
+proc a {.async.} =
+  await 0
+
+waitFor a()
diff --git a/tests/async/tasync_traceback.nim b/tests/async/tasync_traceback.nim
index 7cfbd563f..98f71b192 100644
--- a/tests/async/tasync_traceback.nim
+++ b/tests/async/tasync_traceback.nim
@@ -1,6 +1,5 @@
 discard """
   exitcode: 0
-  disabled: "windows"
   output: "Matched"
 """
 import asyncdispatch, strutils
@@ -68,80 +67,56 @@ import re
 const expected = """
 b failure
 Async traceback:
-  tasync_traceback\.nim\(\d+?\)\s+?tasync_traceback
-  asyncmacro\.nim\(\d+?\)\s+?a
-  asyncmacro\.nim\(\d+?\)\s+?aNimAsyncContinue
-    ## Resumes an async procedure
-  tasync_traceback\.nim\(\d+?\)\s+?aIter
-  asyncmacro\.nim\(\d+?\)\s+?b
-  asyncmacro\.nim\(\d+?\)\s+?bNimAsyncContinue
-    ## Resumes an async procedure
-  tasync_traceback\.nim\(\d+?\)\s+?bIter
-  #\[
-    tasync_traceback\.nim\(\d+?\)\s+?tasync_traceback
-    asyncmacro\.nim\(\d+?\)\s+?a
-    asyncmacro\.nim\(\d+?\)\s+?aNimAsyncContinue
-      ## Resumes an async procedure
-    tasync_traceback\.nim\(\d+?\)\s+?aIter
-    asyncfutures\.nim\(\d+?\)\s+?read
-  \]#
+  tasync_traceback\.nim\(\d+?\) tasync_traceback
+  tasync_traceback\.nim\(\d+?\) a \(Async\)
+  tasync_traceback\.nim\(\d+?\) b \(Async\)
 Exception message: b failure
-Exception type:
+
 
 bar failure
 Async traceback:
-  tasync_traceback\.nim\(\d+?\)\s+?tasync_traceback
-  asyncdispatch\.nim\(\d+?\)\s+?waitFor
-  asyncdispatch\.nim\(\d+?\)\s+?poll
+  tasync_traceback\.nim\(\d+?\) tasync_traceback
+  asyncdispatch\.nim\(\d+?\) waitFor
+  asyncdispatch\.nim\(\d+?\) poll
     ## Processes asynchronous completion events
-  asyncdispatch\.nim\(\d+?\)\s+?runOnce
-  asyncdispatch\.nim\(\d+?\)\s+?processPendingCallbacks
+  asyncdispatch\.nim\(\d+?\) runOnce
+  asyncdispatch\.nim\(\d+?\) processPendingCallbacks
     ## Executes pending callbacks
-  asyncmacro\.nim\(\d+?\)\s+?barNimAsyncContinue
-    ## Resumes an async procedure
-  tasync_traceback\.nim\(\d+?\)\s+?barIter
-  #\[
-    tasync_traceback\.nim\(\d+?\)\s+?tasync_traceback
-    asyncdispatch\.nim\(\d+?\)\s+?waitFor
-    asyncdispatch\.nim\(\d+?\)\s+?poll
-      ## Processes asynchronous completion events
-    asyncdispatch\.nim\(\d+?\)\s+?runOnce
-    asyncdispatch\.nim\(\d+?\)\s+?processPendingCallbacks
-      ## Executes pending callbacks
-    asyncmacro\.nim\(\d+?\)\s+?fooNimAsyncContinue
-      ## Resumes an async procedure
-    tasync_traceback\.nim\(\d+?\)\s+?fooIter
-    asyncfutures\.nim\(\d+?\)\s+?read
-  \]#
+  tasync_traceback\.nim\(\d+?\) bar \(Async\)
 Exception message: bar failure
-Exception type:
+
 """
 
+# TODO: is asyncmacro good enough location for fooIter traceback/debugging? just put the callsite info for all?
+
 let resLines = splitLines(result.strip)
 let expLines = splitLines(expected.strip)
 
-if resLines.len != expLines.len:
-  echo("Not matched! Wrong number of lines!")
-  echo expLines.len
-  echo resLines.len
-  echo("Expected: -----------")
-  echo expected
-  echo("Gotten: -------------")
-  echo result
-  echo("---------------------")
-  quit(QuitFailure)
-
-var ok = true
-for i in 0 ..< resLines.len:
-  if not resLines[i].match(re(expLines[i])):
-    echo "Not matched! Line ", i + 1
-    echo "Expected:"
-    echo expLines[i]
-    echo "Actual:"
-    echo resLines[i]
-    ok = false
-
-if ok:
-  echo("Matched")
+when not defined(cpp): # todo fixme
+  if resLines.len != expLines.len:
+    echo("Not matched! Wrong number of lines!")
+    echo expLines.len
+    echo resLines.len
+    echo("Expected: -----------")
+    echo expected
+    echo("Gotten: -------------")
+    echo result
+    echo("---------------------")
+    quit(QuitFailure)
+
+  var ok = true
+  for i in 0 ..< resLines.len:
+    if not resLines[i].match(re(expLines[i])):
+      echo "Not matched! Line ", i + 1
+      echo "Expected:"
+      echo expLines[i]
+      echo "Actual:"
+      echo resLines[i]
+      ok = false
+
+  if ok:
+    echo("Matched")
+  else:
+    quit(QuitFailure)
 else:
-  quit(QuitFailure)
+  echo("Matched")
diff --git a/tests/async/tasyncawait.nim b/tests/async/tasyncawait.nim
index b1f893489..e86542b2d 100644
--- a/tests/async/tasyncawait.nim
+++ b/tests/async/tasyncawait.nim
@@ -1,13 +1,10 @@
-discard """
-  output: "5000"
-"""
-import asyncdispatch, asyncnet, nativesockets, net, strutils, os
-
+import asyncdispatch, asyncnet, nativesockets, net, strutils
+from stdtest/netutils import bindAvailablePort
 var msgCount = 0
 
 const
-  swarmSize = 50
-  messagesToSend = 100
+  swarmSize = 40
+  messagesToSend = 50
 
 var clientCount = 0
 
@@ -37,31 +34,23 @@ proc readMessages(client: AsyncFD) {.async.} =
       clientCount.inc
       break
     else:
-      if line.startswith("Message "):
+      if line.startsWith("Message "):
         msgCount.inc
       else:
         doAssert false
 
-proc createServer(port: Port) {.async.} =
-  var server = createAsyncNativeSocket()
-  block:
-    var name: Sockaddr_in
-    name.sin_family = typeof(name.sin_family)(toInt(AF_INET))
-    name.sin_port = htons(uint16(port))
-    name.sin_addr.s_addr = htonl(INADDR_ANY)
-    if bindAddr(server.SocketHandle, cast[ptr SockAddr](addr(name)),
-                sizeof(name).Socklen) < 0'i32:
-      raiseOSError(osLastError())
-
+proc createServer(server: AsyncFD) {.async.} =
   discard server.SocketHandle.listen()
   while true:
     asyncCheck readMessages(await accept(server))
 
-asyncCheck createServer(Port(10335))
-asyncCheck launchSwarm(Port(10335))
+let server = createAsyncNativeSocket()
+let port = bindAvailablePort(server.SocketHandle)
+asyncCheck createServer(server)
+asyncCheck launchSwarm(port)
 while true:
   poll()
   if clientCount == swarmSize: break
 
-assert msgCount == swarmSize * messagesToSend
-echo msgCount
+doAssert msgCount == swarmSize * messagesToSend
+doAssert msgCount == 2000
diff --git a/tests/async/tasyncawait_cyclebreaker.nim b/tests/async/tasyncawait_cyclebreaker.nim
deleted file mode 100644
index 1eb2c4676..000000000
--- a/tests/async/tasyncawait_cyclebreaker.nim
+++ /dev/null
@@ -1,73 +0,0 @@
-discard """
-  output: "50000"
-  cmd: "nim c -d:nimTypeNames -d:nimCycleBreaker $file"
-"""
-import asyncdispatch, asyncnet, nativesockets, net, strutils, os
-
-var msgCount = 0
-
-const
-  swarmSize = 500
-  messagesToSend = 100
-
-var clientCount = 0
-
-proc sendMessages(client: AsyncFD) {.async.} =
-  for i in 0 ..< messagesToSend:
-    await send(client, "Message " & $i & "\c\L")
-
-proc launchSwarm(port: Port) {.async.} =
-  for i in 0 ..< swarmSize:
-    var sock = createAsyncNativeSocket()
-
-    await connect(sock, "localhost", port)
-    await sendMessages(sock)
-    closeSocket(sock)
-
-proc readMessages(client: AsyncFD) {.async.} =
-  # wrapping the AsyncFd into a AsyncSocket object
-  var sockObj = newAsyncSocket(client)
-  var (ipaddr, port) = sockObj.getPeerAddr()
-  doAssert ipaddr == "127.0.0.1"
-  (ipaddr, port) = sockObj.getLocalAddr()
-  doAssert ipaddr == "127.0.0.1"
-  while true:
-    var line = await recvLine(sockObj)
-    if line == "":
-      closeSocket(client)
-      clientCount.inc
-      break
-    else:
-      if line.startswith("Message "):
-        msgCount.inc
-      else:
-        doAssert false
-
-proc createServer(port: Port) {.async.} =
-  var server = createAsyncNativeSocket()
-  block:
-    var name: Sockaddr_in
-    name.sin_family = typeof(name.sin_family)(toInt(AF_INET))
-    name.sin_port = htons(uint16(port))
-    name.sin_addr.s_addr = htonl(INADDR_ANY)
-    if bindAddr(server.SocketHandle, cast[ptr SockAddr](addr(name)),
-                sizeof(name).Socklen) < 0'i32:
-      raiseOSError(osLastError())
-
-  discard server.SocketHandle.listen()
-  while true:
-    asyncCheck readMessages(await accept(server))
-
-asyncCheck createServer(Port(10335))
-asyncCheck launchSwarm(Port(10335))
-while true:
-  poll()
-  GC_collectZct()
-
-  let (allocs, deallocs) = getMemCounters()
-  doAssert allocs < deallocs + 1000
-
-  if clientCount == swarmSize: break
-
-assert msgCount == swarmSize * messagesToSend
-echo msgCount
diff --git a/tests/async/tasyncclosestall.nim b/tests/async/tasyncclosestall.nim
index be8a13b98..d1c7a5fba 100644
--- a/tests/async/tasyncclosestall.nim
+++ b/tests/async/tasyncclosestall.nim
@@ -99,4 +99,3 @@ proc server() {.async.} =
 
 when isMainModule:
   waitFor server()
-
diff --git a/tests/async/tasyncconnect.nim b/tests/async/tasyncconnect.nim
index f63a87990..564f6c67c 100644
--- a/tests/async/tasyncconnect.nim
+++ b/tests/async/tasyncconnect.nim
@@ -18,7 +18,7 @@ when defined(windows) or defined(nimdoc):
     quit("Error: unhandled exception: Connection refused")
 else:
     proc testAsyncConnect() {.async.} =
-        var s = newAsyncNativeSocket()
+        var s = createAsyncNativeSocket()
 
         await s.connect(testHost, testPort)
 
diff --git a/tests/async/tasyncdial.nim b/tests/async/tasyncdial.nim
index bbff7028d..f0377dfd5 100644
--- a/tests/async/tasyncdial.nim
+++ b/tests/async/tasyncdial.nim
@@ -3,7 +3,6 @@ discard """
 OK AF_INET
 OK AF_INET6
 '''
-  disabled: "travis"
 """
 
 import
@@ -13,7 +12,7 @@ proc setupServerSocket(hostname: string, port: Port, domain: Domain): AsyncFD =
   ## Creates a socket, binds it to the specified address, and starts listening for connections.
   ## Registers the descriptor with the dispatcher of the current thread
   ## Raises OSError in case of an error.
-  let fd = newNativeSocket(domain)
+  let fd = createNativeSocket(domain)
   setSockOptInt(fd, SOL_SOCKET, SO_REUSEADDR, 1)
   var aiList = getAddrInfo(hostname, port, domain)
   if bindAddr(fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32:
diff --git a/tests/async/tasynceagain.nim b/tests/async/tasynceagain.nim
new file mode 100644
index 000000000..94c3645dc
--- /dev/null
+++ b/tests/async/tasynceagain.nim
@@ -0,0 +1,67 @@
+discard """
+  disabled: "windows"
+  exitcode: 0
+"""
+# AsyncSocketBug.nim
+# Jens Alfke (@snej) -- 16 July 2020
+# Demonstrates data loss by Nim's AsyncSocket.
+# Just run it, and it will raise an assertion failure within a minute.
+
+import asyncdispatch, asyncnet, strformat, strutils, sugar
+
+const FrameSize = 9999   # Exact size not important, but larger sizes fail quicker
+
+proc runServer() {.async.} =
+  # Server side:
+  var server = newAsyncSocket()
+  server.bindAddr(Port(9001))
+  server.listen()
+  let client = await server.accept()
+  echo "Server got client connection"
+  var lastN = 0
+  while true:
+    let frame = await client.recv(FrameSize)
+    doAssert frame.len == FrameSize
+    let n = frame[0..<6].parseInt()
+    echo "RCVD #", n, ":  ", frame[0..80], "..."
+    if n != lastN + 1:
+      echo &"******** ERROR: Server received #{n}, but last was #{lastN}!"
+    doAssert n == lastN + 1
+    lastN = n
+    await sleepAsync 100
+
+
+proc main() {.async.} =
+  asyncCheck runServer()
+
+  # Client side:
+  let socket = newAsyncSocket(buffered = false)
+  await socket.connect("localhost", Port(9001))
+  echo "Client socket connected"
+
+  var sentCount = 0
+  var completedCount = 0
+
+  while sentCount < 2000:
+    sentCount += 1
+    let n = sentCount
+
+    var message = &"{n:06} This is message #{n} of ∞. Please stay tuned for more. "
+    #echo ">>> ", message
+    while message.len < FrameSize:
+      message = message & message
+    let frame = message[0..<FrameSize]
+
+    capture n:
+      socket.send(frame).addCallback proc(f: Future[void]) =
+        # Callback when the send completes:
+        assert not f.failed
+        echo "SENT #", n
+        if n != completedCount + 1:
+          echo &"******** ERROR: Client completed #{n}, but last completed was #{completedCount}!"
+        # If this assert is enabled, it will trigger earlier than the server-side assert above:
+        assert n == completedCount + 1
+        completedCount = n
+    await sleepAsync 1
+
+waitFor main()
\ No newline at end of file
diff --git a/tests/async/tasyncfilewrite.nim b/tests/async/tasyncfilewrite.nim
index 3baf2bbc6..72a2df0b0 100644
--- a/tests/async/tasyncfilewrite.nim
+++ b/tests/async/tasyncfilewrite.nim
@@ -1,7 +1,8 @@
 discard """
   output: '''string 1
 string 2
-string 3'''
+string 3
+'''
 """
 # bug #5532
 import os, asyncfile, asyncdispatch
diff --git a/tests/async/tasyncintemplate.nim b/tests/async/tasyncintemplate.nim
new file mode 100644
index 000000000..4bddb1d18
--- /dev/null
+++ b/tests/async/tasyncintemplate.nim
@@ -0,0 +1,62 @@
+discard """
+  output: '''
+42
+43
+43
+1
+2
+3
+4
+'''
+"""
+
+# xxx move to tests/async/tasyncintemplate.nim
+import asyncdispatch
+
+block: # bug #16159
+  template foo() =
+    proc temp(): Future[int] {.async.} = return 42
+    proc tempVoid(): Future[void] {.async.} = echo await temp()
+  foo()
+  waitFor tempVoid()
+
+block: # aliasing `void`
+  template foo() =
+    type Foo = void
+    proc temp(): Future[int] {.async.} = return 43
+    proc tempVoid(): Future[Foo] {.async.} = echo await temp()
+    proc tempVoid2() {.async.} = echo await temp()
+  foo()
+  waitFor tempVoid()
+  waitFor tempVoid2()
+
+block: # sanity check
+  template foo() =
+    proc bad(): int {.async.} = discard
+  doAssert not compiles(bad())
+
+block: # bug #16786
+  block:
+    proc main(a: int|string)=
+      proc bar(b: int|string) = echo b
+      bar(a)
+    main(1)
+
+  block:
+    proc main(a: int) : Future[void] {.async.} =
+      proc bar(b: int): Future[void] {.async.} = echo b
+      await bar(a)
+    waitFor main(2)
+
+  block:
+    proc main(a: int) : Future[void] {.async.} =
+      proc bar(b: int | string): Future[void] {.async.} = echo b
+      await bar(a)
+    waitFor main(3)
+
+  block:
+    # bug
+    proc main(a: int|string) =
+      proc bar(b: int): Future[void] {.async.} = echo b
+      waitFor bar(a)
+    main(4)
diff --git a/tests/async/tasyncnetudp.nim b/tests/async/tasyncnetudp.nim
new file mode 100644
index 000000000..dade96fb2
--- /dev/null
+++ b/tests/async/tasyncnetudp.nim
@@ -0,0 +1,90 @@
+# It is a reproduction of the 'tnewasyncudp' test code, but using a high level
+# of asynchronous procedures. Output: "5000"
+import asyncdispatch, asyncnet, nativesockets, net, strutils
+
+var msgCount = 0
+var recvCount = 0
+
+const
+  messagesToSend = 100
+  swarmSize = 50
+  serverPort = 10333
+
+var
+  sendports = 0
+  recvports = 0
+
+proc saveSendingPort(port: Port) =
+  sendports = sendports + int(port)
+
+proc saveReceivedPort(port: Port) =
+  recvports = recvports + int(port)
+
+proc launchSwarm(serverIp: string, serverPort: Port) {.async.} =
+  var i = 0
+
+  while i < swarmSize:
+    var sock = newAsyncSocket(nativesockets.AF_INET, nativesockets.SOCK_DGRAM,
+                              Protocol.IPPROTO_UDP, false)
+
+    bindAddr(sock, address = "127.0.0.1")
+
+    let (null, localPort) = getLocalAddr(sock)
+
+    var k = 0
+    
+    while k < messagesToSend:
+      let message = "Message " & $(i * messagesToSend + k)
+
+      await asyncnet.sendTo(sock, serverIp, serverPort, message)
+
+      let (data, fromIp, fromPort) = await recvFrom(sock, 16384)
+
+      if data == message:
+        saveSendingPort(localPort)
+
+        inc(recvCount)
+
+      inc(k)
+    
+    close(sock)
+
+    inc(i)
+
+proc readMessages(server: AsyncSocket) {.async.} =
+  let maxResponses = (swarmSize * messagesToSend)
+
+  var i = 0
+  
+  while i < maxResponses:
+    let (data, fromIp, fromPort) = await recvFrom(server, 16384)
+
+    if data.startsWith("Message ") and fromIp == "127.0.0.1":
+      await sendTo(server, fromIp, fromPort, data)
+
+      inc(msgCount)
+
+      saveReceivedPort(fromPort)
+
+    inc(i)
+
+proc createServer() {.async.} =
+  var server = newAsyncSocket(nativesockets.AF_INET, nativesockets.SOCK_DGRAM, Protocol.IPPROTO_UDP, false)
+  
+  bindAddr(server, Port(serverPort), "127.0.0.1")
+
+  asyncCheck readMessages(server)
+
+asyncCheck createServer()
+asyncCheck launchSwarm("127.0.0.1", Port(serverPort))
+
+while true:
+  poll()
+
+  if recvCount == swarmSize * messagesToSend:
+    break
+
+doAssert msgCount == swarmSize * messagesToSend
+doAssert sendports == recvports
+
+echo msgCount
\ No newline at end of file
diff --git a/tests/async/tasyncsend4757.nim b/tests/async/tasyncsend4757.nim
index a87c5df95..29873a905 100644
--- a/tests/async/tasyncsend4757.nim
+++ b/tests/async/tasyncsend4757.nim
@@ -1,24 +1,24 @@
-discard """
-output: "Finished"
-"""
-
 import asyncdispatch, asyncnet
 
-proc createServer(port: Port) {.async.} =
+var port: Port
+proc createServer() {.async.} =
   var server = newAsyncSocket()
   server.setSockOpt(OptReuseAddr, true)
-  bindAddr(server, port)
+  bindAddr(server)
+  port = getLocalAddr(server)[1]
   server.listen()
   while true:
     let client = await server.accept()
     discard await client.recvLine()
 
-asyncCheck createServer(10335.Port)
+asyncCheck createServer()
 
+var done = false
 proc f(): Future[void] {.async.} =
-  let s = newAsyncNativeSocket()
-  await s.connect("localhost", 10335.Port)
+  let s = createAsyncNativeSocket()
+  await s.connect("localhost", port)
   await s.send("123")
-  echo "Finished"
+  done = true
 
 waitFor f()
+doAssert done
diff --git a/tests/async/tasyncssl.nim b/tests/async/tasyncssl.nim
index 88a5eb32e..57de3271d 100644
--- a/tests/async/tasyncssl.nim
+++ b/tests/async/tasyncssl.nim
@@ -1,16 +1,13 @@
 discard """
   cmd: "nim $target --hints:on --define:ssl $options $file"
-  output: "500"
-  disabled: "windows"
-  target: c
-  action: compile
+  disabled: osx
 """
 
-# XXX, deactivated
-
-import asyncdispatch, asyncnet, net, strutils, os
+import asyncdispatch, asyncnet, net, strutils
+import stdtest/testutils
 
 when defined(ssl):
+  var port0: Port
   var msgCount = 0
 
   const
@@ -40,30 +37,38 @@ when defined(ssl):
         inc(clientCount)
         break
       else:
-        if line.startswith("Message "):
+        if line.startsWith("Message "):
           inc(msgCount)
         else:
           doAssert false
 
-  proc createServer(port: Port) {.async.} =
+  proc createServer() {.async.} =
     let serverContext = newContext(verifyMode = CVerifyNone,
                                    certFile = "tests/testdata/mycert.pem",
                                    keyFile = "tests/testdata/mycert.pem")
     var server = newAsyncSocket()
     serverContext.wrapSocket(server)
     server.setSockOpt(OptReuseAddr, true)
-    bindAddr(server, port)
+    bindAddr(server)
+    port0 = getLocalAddr(server)[1]
     server.listen()
     while true:
       let client = await accept(server)
       serverContext.wrapConnectedSocket(client, handshakeAsServer)
       asyncCheck readMessages(client)
 
-  asyncCheck createServer(Port(10335))
-  asyncCheck launchSwarm(Port(10335))
+  asyncCheck createServer()
+  asyncCheck launchSwarm(port0)
   while true:
     poll()
     if clientCount == swarmSize: break
 
-  assert msgCount == swarmSize * messagesToSend
-  echo msgCount
+  template cond(): bool = msgCount == swarmSize * messagesToSend
+  when defined(windows):
+    # currently: msgCount == 0
+    flakyAssert cond()
+  elif defined(linux) and int.sizeof == 8:
+    # currently:  msgCount == 10
+    flakyAssert cond()
+    doAssert msgCount > 0
+  else: doAssert cond(), $msgCount
diff --git a/tests/async/tasynctry.nim b/tests/async/tasynctry.nim
index a7cb5223d..25eab87fb 100644
--- a/tests/async/tasynctry.nim
+++ b/tests/async/tasynctry.nim
@@ -5,6 +5,7 @@ Specific except
 Multiple idents in except
 Multiple except branches
 Multiple except branches 2
+success
 '''
 targets: "c"
 """
@@ -14,7 +15,7 @@ import asyncdispatch, strutils
 
 proc foobar() {.async.} =
   if 5 == 5:
-    raise newException(IndexError, "Test")
+    raise newException(IndexDefect, "Test")
 
 proc catch() {.async.} =
   # TODO: Create a test for when exceptions are not caught.
@@ -25,26 +26,26 @@ proc catch() {.async.} =
 
   try:
     await foobar()
-  except IndexError:
+  except IndexDefect:
     echo("Specific except")
 
   try:
     await foobar()
-  except OSError, FieldError, IndexError:
+  except OSError, FieldDefect, IndexDefect:
     echo("Multiple idents in except")
 
   try:
     await foobar()
-  except OSError, FieldError:
+  except OSError, FieldDefect:
     assert false
-  except IndexError:
+  except IndexDefect:
     echo("Multiple except branches")
 
   try:
     await foobar()
-  except IndexError:
+  except IndexDefect:
     echo("Multiple except branches 2")
-  except OSError, FieldError:
+  except OSError, FieldDefect:
     assert false
 
 waitFor catch()
@@ -101,3 +102,17 @@ assert y.waitFor() == 2
 
 y = test4()
 assert y.waitFor() == 2
+
+# bug #14279
+
+proc expandValue: Future[int] {.async.} =
+  return 0
+
+proc a(b: int): Future[void] {.async.} =
+  return
+
+proc b: Future[void] {.async.} =
+  await a(await expandValue())
+  echo "success"
+
+waitFor(b())
diff --git a/tests/async/tbreak_must_exec_finally.nim b/tests/async/tbreak_must_exec_finally.nim
new file mode 100644
index 000000000..8780e6149
--- /dev/null
+++ b/tests/async/tbreak_must_exec_finally.nim
@@ -0,0 +1,25 @@
+discard """
+  output: '''
+finally handler 8
+do not duplicate this one
+'''
+"""
+
+# bug #15243
+
+import asyncdispatch
+
+proc f() {.async.} =
+  try:
+    while true:
+      try:
+        await sleepAsync(400)
+        break
+      finally:
+        var localHere = 8
+        echo "finally handler ", localHere
+  finally:
+    echo "do not duplicate this one"
+
+when isMainModule:
+  waitFor f()
diff --git a/tests/async/tdiscardableproc.nim b/tests/async/tdiscardableproc.nim
new file mode 100644
index 000000000..93cd83be9
--- /dev/null
+++ b/tests/async/tdiscardableproc.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "Cannot make async proc discardable. Futures have to be checked with `asyncCheck` instead of discarded"
+"""
+
+import async
+
+proc foo {.async, discardable.} = discard
+
+foo()
diff --git a/tests/async/testmanyasyncevents.nim b/tests/async/testmanyasyncevents.nim
index 5a103736f..9fdd01b4f 100644
--- a/tests/async/testmanyasyncevents.nim
+++ b/tests/async/testmanyasyncevents.nim
@@ -1,8 +1,9 @@
 discard """
 output: '''
 hasPendingOperations: false
-triggerCount: 100 
+triggerCount: 100
 '''
+disabled: "windows"
 """
 
 import asyncDispatch
diff --git a/tests/async/tfuturestream.nim b/tests/async/tfuturestream.nim
index b5772d5ac..a019df400 100644
--- a/tests/async/tfuturestream.nim
+++ b/tests/async/tfuturestream.nim
@@ -17,7 +17,7 @@ var fs = newFutureStream[int]()
 proc alpha() {.async.} =
   for i in 0 .. 5:
     await fs.write(i)
-    await sleepAsync(200)
+    await sleepAsync(100)
 
   echo("Done")
   fs.complete()
diff --git a/tests/async/tfuturevar.nim b/tests/async/tfuturevar.nim
index 9e3134261..b70f1d166 100644
--- a/tests/async/tfuturevar.nim
+++ b/tests/async/tfuturevar.nim
@@ -1,8 +1,3 @@
-discard """
-action: compile
-"""
-# XXX: action should be run!
-
 import asyncdispatch
 
 proc completeOnReturn(fut: FutureVar[string], x: bool) {.async.} =
diff --git a/tests/async/tioselectors.nim b/tests/async/tioselectors.nim
index e172e1452..f53767408 100644
--- a/tests/async/tioselectors.nim
+++ b/tests/async/tioselectors.nim
@@ -10,10 +10,8 @@ template processTest(t, x: untyped) =
   #stdout.flushFile()
   if not x: echo(t & " FAILED\r\n")
 
-when defined(macosx):
-  echo "All tests passed!"
-elif not defined(windows):
-  import os, posix, nativesockets, times
+when not defined(windows):
+  import os, posix, nativesockets
 
   when ioselSupportedPlatform:
     import osproc
@@ -60,7 +58,11 @@ elif not defined(windows):
     registerHandle(selector, client_socket, {Event.Write}, 0)
 
     freeAddrInfo(aiList)
-    discard selector.select(100)
+
+    # make sure both sockets are selected
+    var nevs = 0
+    while nevs < 2:
+      nevs += selector.select(100).len
 
     var sockAddress: SockAddr
     var addrLen = sizeof(sockAddress).Socklen
@@ -147,15 +149,16 @@ elif not defined(windows):
     proc timer_notification_test(): bool =
       var selector = newSelector[int]()
       var timer = selector.registerTimer(100, false, 0)
-      var rc1 = selector.select(140)
-      var rc2 = selector.select(140)
-      assert(len(rc1) == 1 and len(rc2) == 1)
+      var rc1 = selector.select(10000)
+      var rc2 = selector.select(10000)
+      # if this flakes, see tests/m14634.nim
+      assert len(rc1) == 1 and len(rc2) == 1, $(len(rc1), len(rc2))
       selector.unregister(timer)
       discard selector.select(0)
       selector.registerTimer(100, true, 0)
-      var rc4 = selector.select(120)
-      var rc5 = selector.select(120)
-      assert(len(rc4) == 1 and len(rc5) == 0)
+      var rc4 = selector.select(10000)
+      var rc5 = selector.select(1000) # this will be an actual wait, keep it small
+      assert len(rc4) == 1 and len(rc5) == 0, $(len(rc4), len(rc5))
       assert(selector.isEmpty())
       selector.close()
       result = true
@@ -235,7 +238,7 @@ elif not defined(windows):
       if fd == -1:
         raiseOsError(osLastError())
       let length = len(data).cint
-      if posix.write(fd, cast[pointer](unsafeAddr data[0]),
+      if posix.write(fd, cast[pointer](addr data[0]),
                      len(data).cint) != length:
         raiseOsError(osLastError())
       if posix.close(fd) == -1:
@@ -289,8 +292,8 @@ elif not defined(windows):
         events: set[Event]
 
     proc vnode_test(): bool =
-      proc validate(test: openarray[ReadyKey],
-                    check: openarray[valType]): bool =
+      proc validate(test: openArray[ReadyKey],
+                    check: openArray[valType]): bool =
         result = false
         if len(test) == len(check):
           for checkItem in check:
@@ -428,6 +431,20 @@ elif not defined(windows):
       doAssert(res[0].fd == dirfd and
                {Event.Vnode, Event.VnodeDelete} <= res[0].events)
 
+  proc pipe_test(): bool =
+    # closing the read end of a pipe will result in it automatically
+    # being removed from the kqueue; make sure no exception is raised
+    var s = newSelector[int]()
+    var fds: array[2, cint]
+    discard pipe(fds)
+    s.registerHandle(fds[1], {Write}, 0)
+    discard close(fds[0])
+    let res = s.select(-1)
+    doAssert(res.len == 1)
+    s.unregister(fds[1])
+    discard close(fds[1])
+    return true
+
   when hasThreadSupport:
 
     var counter = 0
@@ -445,7 +462,7 @@ elif not defined(windows):
       var
         thr: array[0..7, Thread[SelectEvent]]
       var selector = newSelector[int]()
-      var sock = newNativeSocket()
+      var sock = createNativeSocket()
       var event = newSelectEvent()
       for i in 0..high(thr):
         createThread(thr[i], event_wait_thread, event)
@@ -469,13 +486,14 @@ elif not defined(windows):
   when defined(macosx) or defined(freebsd) or defined(openbsd) or
        defined(netbsd):
     processTest("File notification test...", vnode_test())
+    processTest("Pipe test...", pipe_test())
   echo("All tests passed!")
 else:
   import nativesockets, winlean, os, osproc
 
   proc socket_notification_test(): bool =
     proc create_test_socket(): SocketHandle =
-      var sock = newNativeSocket()
+      var sock = createNativeSocket()
       setBlocking(sock, false)
       result = sock
 
diff --git a/tests/async/tjsandnativeasync.nim b/tests/async/tjsandnativeasync.nim
index 45839899f..c4db3bcfb 100644
--- a/tests/async/tjsandnativeasync.nim
+++ b/tests/async/tjsandnativeasync.nim
@@ -19,7 +19,7 @@ else:
 proc foo() {.async.} =
     echo "hi"
     var s = epochTime()
-    await sleepAsync(500)
+    await sleepAsync(200)
     var e = epochTime()
     doAssert(e - s > 0.1)
     echo "bye"
diff --git a/tests/async/tnewasyncudp.nim b/tests/async/tnewasyncudp.nim
index feab46319..68de796a0 100644
--- a/tests/async/tnewasyncudp.nim
+++ b/tests/async/tnewasyncudp.nim
@@ -40,9 +40,9 @@ proc launchSwarm(name: ptr SockAddr) {.async.} =
   var saddr = Sockaddr_in()
   while i < swarmSize:
     var peeraddr = prepareAddress(INADDR_LOOPBACK, 0)
-    var sock = newAsyncNativeSocket(nativesockets.AF_INET,
-                                    nativesockets.SOCK_DGRAM,
-                                    Protocol.IPPROTO_UDP)
+    var sock = createAsyncNativeSocket(nativesockets.AF_INET,
+                                       nativesockets.SOCK_DGRAM,
+                                       Protocol.IPPROTO_UDP)
     if bindAddr(sock.SocketHandle, cast[ptr SockAddr](peeraddr),
               sizeof(Sockaddr_in).Socklen) < 0'i32:
       raiseOSError(osLastError())
@@ -58,7 +58,7 @@ proc launchSwarm(name: ptr SockAddr) {.async.} =
                                     16384, cast[ptr SockAddr](addr saddr),
                                     addr slen)
       size = 0
-      var grammString = $cstring(addr buffer)
+      var grammString = $cast[cstring](addr buffer)
       if grammString == message:
         saveSendingPort(sockport)
         inc(recvCount)
@@ -80,8 +80,8 @@ proc readMessages(server: AsyncFD) {.async.} =
                                   16384, cast[ptr SockAddr](addr(saddr)),
                                   addr(slen))
     size = 0
-    var grammString = $cstring(addr buffer)
-    if grammString.startswith("Message ") and
+    var grammString = $cast[cstring](addr buffer)
+    if grammString.startsWith("Message ") and
        saddr.sin_addr.s_addr == nativesockets.ntohl(INADDR_LOOPBACK.uint32):
       await sendTo(server, addr grammString[0], len(grammString),
                    cast[ptr SockAddr](addr saddr), slen)
@@ -91,9 +91,9 @@ proc readMessages(server: AsyncFD) {.async.} =
 
 proc createServer() {.async.} =
   var name = prepareAddress(INADDR_LOOPBACK, serverPort)
-  var server = newAsyncNativeSocket(nativesockets.AF_INET,
-                                    nativesockets.SOCK_DGRAM,
-                                    Protocol.IPPROTO_UDP)
+  var server = createAsyncNativeSocket(nativesockets.AF_INET,
+                                       nativesockets.SOCK_DGRAM,
+                                       Protocol.IPPROTO_UDP)
   if bindAddr(server.SocketHandle, cast[ptr SockAddr](name),
               sizeof(Sockaddr_in).Socklen) < 0'i32:
     raiseOSError(osLastError())
diff --git a/tests/async/tpendingcheck.nim b/tests/async/tpendingcheck.nim
index a5537d8cb..4eceb0353 100644
--- a/tests/async/tpendingcheck.nim
+++ b/tests/async/tpendingcheck.nim
@@ -7,7 +7,7 @@ import asyncdispatch
 doAssert(not hasPendingOperations())
 
 proc test() {.async.} =
-  await sleepAsync(100)
+  await sleepAsync(50)
 
 var f = test()
 while not f.finished:
diff --git a/tests/async/tupcoming_async.nim b/tests/async/tupcoming_async.nim
index da98fc4d8..0b6e53454 100644
--- a/tests/async/tupcoming_async.nim
+++ b/tests/async/tupcoming_async.nim
@@ -45,7 +45,7 @@ when defined(upcoming):
     poll()
 
   proc eventTest5298() =
-    # Event must raise `AssertionError` if event was unregistered twice.
+    # Event must raise `AssertionDefect` if event was unregistered twice.
     # Issue #5298.
     let e = newAsyncEvent()
     var eventReceived = false
@@ -57,7 +57,7 @@ when defined(upcoming):
       poll()
     try:
       e.unregister()
-    except AssertionError:
+    except AssertionDefect:
       discard
     e.close()
 
diff --git a/tests/async/twinasyncrw.nim b/tests/async/twinasyncrw.nim
index db10fffce..f0a8f6a62 100644
--- a/tests/async/twinasyncrw.nim
+++ b/tests/async/twinasyncrw.nim
@@ -1,9 +1,6 @@
-discard """
-  output: "5000"
-"""
 when defined(windows):
   import asyncdispatch, nativesockets, net, strutils, os, winlean
-
+  from stdtest/netutils import bindAvailablePort
   var msgCount = 0
 
   const
@@ -22,7 +19,7 @@ when defined(windows):
           retFuture.complete()
           return true
       else:
-          retFuture.fail(newException(OSError, osErrorMsg(OSErrorCode(ret))))
+          retFuture.fail(newOSError(OSErrorCode(ret)))
           return true
 
     var aiList = getAddrInfo(address, port, domain)
@@ -48,7 +45,7 @@ when defined(windows):
 
     freeAddrInfo(aiList)
     if not success:
-      retFuture.fail(newException(OSError, osErrorMsg(lastError)))
+      retFuture.fail(newOSError(lastError))
     return retFuture
 
   proc winRecv*(socket: AsyncFD, size: int,
@@ -66,7 +63,7 @@ when defined(windows):
         if flags.isDisconnectionError(lastError):
           retFuture.complete("")
         else:
-          retFuture.fail(newException(OSError, osErrorMsg(lastError)))
+          retFuture.fail(newOSError(lastError))
       elif res == 0:
         # Disconnected
         retFuture.complete("")
@@ -91,7 +88,7 @@ when defined(windows):
         if flags.isDisconnectionError(lastError):
           retFuture.complete(0)
         else:
-          retFuture.fail(newException(OSError, osErrorMsg(lastError)))
+          retFuture.fail(newOSError(lastError))
       else:
         retFuture.complete(res)
     # TODO: The following causes a massive slowdown.
@@ -115,7 +112,7 @@ when defined(windows):
         if flags.isDisconnectionError(lastError):
           retFuture.complete()
         else:
-          retFuture.fail(newException(OSError, osErrorMsg(lastError)))
+          retFuture.fail(newOSError(lastError))
       else:
         written.inc(res)
         if res != netSize:
@@ -139,7 +136,7 @@ when defined(windows):
         var client = nativesockets.accept(sock.SocketHandle,
                                           cast[ptr SockAddr](addr(sockAddress)), addr(addrLen))
         if client == osInvalidSocket:
-          retFuture.fail(newException(OSError, osErrorMsg(osLastError())))
+          retFuture.fail(newOSError(osLastError()))
         else:
           retFuture.complete((getAddrString(cast[ptr SockAddr](addr sockAddress)), client.AsyncFD))
 
@@ -208,7 +205,7 @@ when defined(windows):
 
   proc launchSwarm(port: Port) {.async.} =
     for i in 0 ..< swarmSize:
-      var sock = newNativeSocket()
+      var sock = createNativeSocket()
       setBlocking(sock, false)
 
       await winConnect(AsyncFD(sock), "localhost", port)
@@ -223,34 +220,24 @@ when defined(windows):
         clientCount.inc
         break
       else:
-        if line.startswith("Message "):
+        if line.startsWith("Message "):
           msgCount.inc
         else:
           doAssert false
 
-  proc createServer(port: Port) {.async.} =
-    var server = newNativeSocket()
-    setBlocking(server, false)
-    block:
-      var name = Sockaddr_in()
-      name.sin_family = toInt(Domain.AF_INET).uint16
-      name.sin_port = htons(uint16(port))
-      name.sin_addr.s_addr = htonl(INADDR_ANY)
-      if bindAddr(server, cast[ptr SockAddr](addr(name)),
-                  sizeof(name).Socklen) < 0'i32:
-        raiseOSError(osLastError())
-
+  proc createServer(server: SocketHandle) {.async.} =
     discard server.listen()
     while true:
       asyncCheck readMessages(await winAccept(AsyncFD(server)))
 
-  asyncCheck createServer(Port(10335))
-  asyncCheck launchSwarm(Port(10335))
+  var server = createNativeSocket()
+  setBlocking(server, false)
+  let port = bindAvailablePort(server)
+  asyncCheck createServer(server)
+  asyncCheck launchSwarm(port)
   while true:
     poll()
     if clientCount == swarmSize: break
 
   assert msgCount == swarmSize * messagesToSend
-  echo msgCount
-else:
-  echo(5000)
+  doAssert msgCount == 5000
diff --git a/tests/avr/nim.cfg b/tests/avr/nim.cfg
new file mode 100644
index 000000000..d6eba8eda
--- /dev/null
+++ b/tests/avr/nim.cfg
@@ -0,0 +1,12 @@
+avr.standalone.gcc.path = "/usr/bin"
+avr.standalone.gcc.exe = "avr-gcc"
+avr.standalone.gcc.linkerexe = "avr-gcc"
+passC = "-Os"
+passC = "-DF_CPU=16000000UL"
+passC = "-mmcu=atmega328p"
+passL = "-mmcu=atmega328p"
+passC = "-flto"
+passL = "-flto"
+cpu = "avr"
+deadCodeElim = "on"
+gc = "arc"
diff --git a/tests/avr/panicoverride.nim b/tests/avr/panicoverride.nim
new file mode 100644
index 000000000..770933ddd
--- /dev/null
+++ b/tests/avr/panicoverride.nim
@@ -0,0 +1,13 @@
+proc printf(frmt: cstring) {.varargs, importc, header: "<stdio.h>", cdecl.}
+proc exit(code: int) {.importc, header: "<stdlib.h>", cdecl.}
+
+{.push stack_trace: off, profiler:off.}
+
+proc rawoutput(s: string) =
+  printf("%s\n", s)
+
+proc panic(s: string) =
+  rawoutput(s)
+  exit(1)
+
+{.pop.}
diff --git a/tests/avr/thello.nim b/tests/avr/thello.nim
new file mode 100644
index 000000000..7ebaeae5f
--- /dev/null
+++ b/tests/avr/thello.nim
@@ -0,0 +1,6 @@
+discard """
+  cmd: "nim c --compileOnly --os:standalone --exceptions:quirky -d:noSignalHandler -d:danger --threads:off $file"
+  action: "compile"
+"""
+
+echo "hi"
diff --git a/tests/benchmarks/readme.md b/tests/benchmarks/readme.md
new file mode 100644
index 000000000..1e744fc40
--- /dev/null
+++ b/tests/benchmarks/readme.md
@@ -0,0 +1,5 @@
+# Collection of benchmarks
+
+In future work, benchmarks can be added to CI, but for now we provide benchmarks that can be run locally.
+
+See RFC: https://github.com/timotheecour/Nim/issues/425
diff --git a/tests/benchmarks/ttls.nim b/tests/benchmarks/ttls.nim
new file mode 100644
index 000000000..f5314850f
--- /dev/null
+++ b/tests/benchmarks/ttls.nim
@@ -0,0 +1,30 @@
+discard """
+  action: compile
+"""
+
+#[
+## on osx
+nim r -d:danger --threads --tlsEmulation:off tests/benchmarks/ttls.nim
+9.999999999992654e-07
+
+ditto with `--tlsEmulation:on`:
+0.216999
+]#
+
+import times
+
+proc main2(): int =
+  var g0 {.threadvar.}: int
+  g0.inc
+  result = g0
+
+proc main =
+  let n = 100_000_000
+  var c = 0
+  let t = cpuTime()
+  for i in 0..<n:
+    c += main2()
+  let t2 = cpuTime() - t
+  doAssert c != 0
+  echo t2
+main()
diff --git a/tests/bind/tdatabind.nim b/tests/bind/tdatabind.nim
deleted file mode 100644
index f6455749c..000000000
--- a/tests/bind/tdatabind.nim
+++ /dev/null
@@ -1,95 +0,0 @@
-discard """
-  disabled: true
-"""
-
-import events
-type
-  TProperty*[T] = object of TObject
-    getProc: proc(property: TProperty[T]): T {.nimcall.}
-    setProc: proc(property: var TProperty[T], value: T) {.nimcall.}
-    value: T
-    ValueChanged*: TEventHandler
-    Binders: seq[TProperty[T]]
-    EEmitter: TEventEmitter
-  # Not a descriptive name but it was that or TPropertyValueChangeEventArgs.
-  TValueEventArgs[T] = object of TEventArgs
-    Property*: TProperty[T]
-
-
-proc newProperty*[T](value: T): TProperty[T] =
-  var prop: TProperty[T]
-
-  prop.EEmitter = initEventEmitter()
-  prop.Binders = @[]
-  prop.ValueChanged = initEventHandler("ValueChanged")
-  prop.value = value
-
-  proc getter(property: TProperty[T]): T =
-   return property.value
-
-  prop.getProc = getter
-
-  proc setter(property: var TProperty[T], v: T) =
-    property.value = v
-
-    # fire event here
-    var args: TValueEventArgs[T]
-    args.Property = property
-    property.EEmitter.emit(property.ValueChanged, args)
-
-  prop.setProc = setter
-
-  return prop
-
-proc `prop`[T] (p: TProperty[T]): T =
-  # I'm assuming this is trying to get a value from the property.
-  # i.e. myVar = myProperty
-  return p.getProc(p)
-
-proc `~=`[T] (p: var TProperty[T], v: T) =
-  # Assuming this is setting the value.
-  p.setProc(p, v)
-
-proc `$`[T] (p: TProperty[T]): string =
-  var value = p.getProc(p)
-  return $value
-
-proc propertyBind*[T](p1: var TProperty[T], p2: var TProperty[T]) =
-  p1.Binders.add(p2)
-
-  # make handler -> handler[T] so trigger even more generics bugs ...
-  proc handler(e: TEventArgs) =
-    type TEA = TValueEventArgs[T]
-    var args = TEA(e)
-    var val = args.Property.getProc(p1)
-    for i in countup(0, len(e.Property.ValueChanged.Binders) -1):
-      var binded = e.Property.ValueChanged.Binders[i]
-      binded.setProc(binded, val)
-
-    echo("Property 1 has changed to " & $val)
-
-  if p1.ValueChanged.containsHandler(handler) == false:
-    addHandler(p1.ValueChanged, handler)
-
-proc `->`[T](p1: var TProperty[T], p2: var TProperty[T]) =
-  propertyBind(p2,p1)
-
-when true:
-  # Initial value testing
-  var myProp = newProperty(5)
-
-  echo(myProp)
-
-  myProp ~= 7 # Temp operator until overloading of '=' is implemented.
-  echo(myProp)
-
-  # Binding testing
-
-  var prop1 = newProperty(9)
-  var prop2: TProperty[int]
-
-  prop2 -> prop1 # Binds prop2 to prop1
-
-  prop1 ~= 7
-  echo(prop2) # Output: 7
-
diff --git a/tests/borrow/tborrow.nim b/tests/borrow/tborrow.nim
deleted file mode 100644
index ee0d0194d..000000000
--- a/tests/borrow/tborrow.nim
+++ /dev/null
@@ -1,21 +0,0 @@
-discard """
-  output: "4887 true"
-"""
-
-# test the new borrow feature that works with generics:
-
-proc `++`*[T: int | float](a, b: T): T =
-  result = a + b
-
-type
-  DI = distinct int
-  DF = distinct float
-  DS = distinct string
-
-proc `++`(x, y: DI): DI {.borrow.}
-proc `++`(x, y: DF): DF {.borrow.}
-
-proc `$`(x: DI): string {.borrow.}
-proc `$`(x: DF): string {.borrow.}
-
-echo  4544.DI ++ 343.DI, " ", (4.5.DF ++ 0.5.DF).float == 5.0
diff --git a/tests/borrow/tinvalidborrow.nim b/tests/borrow/tinvalidborrow.nim
deleted file mode 100644
index 89aa4e2e8..000000000
--- a/tests/borrow/tinvalidborrow.nim
+++ /dev/null
@@ -1,16 +0,0 @@
-discard """
-  errormsg: "no symbol to borrow from found"
-  line: 11
-"""
-
-# bug #516
-
-type
-  TAtom = culong
-
-proc `==`*(a, b: TAtom): bool {.borrow.}
-
-var
-  d, e: TAtom
-
-echo( $(d == e) )
diff --git a/tests/compilepragma/test.c b/tests/c/tcompile.c
index fc0482e40..fc0482e40 100644
--- a/tests/compilepragma/test.c
+++ b/tests/c/tcompile.c
diff --git a/tests/compilepragma/test.nim b/tests/c/tcompile.nim
index 56087fa57..cf99fd7ed 100644
--- a/tests/compilepragma/test.nim
+++ b/tests/c/tcompile.nim
@@ -3,7 +3,7 @@ discard """
   joinable: "false"
 """
 
-{.compile: "test.c".}
+{.compile: "tcompile.c".}
 
 proc foo(a, b: cint): cint {.importc: "foo", cdecl.}
 
diff --git a/tests/misc/temit.nim b/tests/c/temit.nim
index ee7455d4c..1943c94ea 100644
--- a/tests/misc/temit.nim
+++ b/tests/c/temit.nim
@@ -4,6 +4,7 @@ discard """
 # Test the new ``emit`` pragma:
 
 {.emit: """
+#include <stdio.h>
 static int cvariable = 420;
 
 """.}
diff --git a/tests/misc/treservedcidentsasfields.nim b/tests/c/treservedcidentsasfields.nim
index a9a954651..6cdf9e855 100644
--- a/tests/misc/treservedcidentsasfields.nim
+++ b/tests/c/treservedcidentsasfields.nim
@@ -1,39 +1,39 @@
-discard """

-  targets: "c cpp"

-"""

-

-import macros

-

-macro make_test_type(idents: varargs[untyped]): untyped =

-  result = nnkStmtList.newTree()

-

-  var ident_defs: seq[NimNode] = @[]

-  for i in idents:

-    ident_defs.add newIdentDefs(i, ident("int"))

-

-  result.add newTree(nnkTypeSection,

-    newTree(nnkTypeDef,

-      ident("TestType"),

-      newEmptyNode(),

-      newTree(nnkObjectTy,

-        newEmptyNode(),

-        newEmptyNode(),

-        newTree(nnkRecList,

-          ident_defs

-        )

-      )

-    )

-  )

-

-make_test_type(

-  auto, bool, catch, char, class, compl, const_cast, default, delete, double,

-  dynamic_cast, explicit, extern, false, float, friend, goto, int, long,

-  mutable, namespace, new, operator, private, protected, public, register,

-  reinterpret_cast, restrict, short, signed, sizeof, static_cast, struct, switch,

-  this, throw, true, typedef, typeid, typeof, typename, union, packed, unsigned,

-  virtual, void, volatile, wchar_t, alignas, alignof, constexpr, decltype, nullptr,

-  noexcept, thread_local, static_assert, char16_t, char32_t

-)

-

-# Make sure the type makes it to codegen.

-var test_instance: TestType

+discard """
+  targets: "c cpp"
+"""
+
+import macros
+
+macro make_test_type(idents: varargs[untyped]): untyped =
+  result = nnkStmtList.newTree()
+
+  var ident_defs: seq[NimNode] = @[]
+  for i in idents:
+    ident_defs.add newIdentDefs(i, ident("int"))
+
+  result.add newTree(nnkTypeSection,
+    newTree(nnkTypeDef,
+      ident("TestType"),
+      newEmptyNode(),
+      newTree(nnkObjectTy,
+        newEmptyNode(),
+        newEmptyNode(),
+        newTree(nnkRecList,
+          ident_defs
+        )
+      )
+    )
+  )
+
+make_test_type(
+  auto, bool, catch, char, class, compl, const_cast, default, delete, double,
+  dynamic_cast, explicit, extern, false, float, friend, goto, int, long,
+  mutable, namespace, new, operator, private, protected, public, register,
+  reinterpret_cast, restrict, short, signed, sizeof, static_cast, struct, switch,
+  this, throw, true, typedef, typeid, typeof, typename, union, packed, unsigned,
+  virtual, void, volatile, wchar_t, alignas, alignof, constexpr, decltype, nullptr,
+  noexcept, thread_local, static_assert, char16_t, char32_t
+)
+
+# Make sure the type makes it to codegen.
+var test_instance: TestType
diff --git a/tests/casestmt/t18964.nim b/tests/casestmt/t18964.nim
new file mode 100644
index 000000000..1d2de2bbc
--- /dev/null
+++ b/tests/casestmt/t18964.nim
@@ -0,0 +1,12 @@
+discard """
+errormsg: "invalid order of case branches"
+"""
+
+import macros
+
+macro genCase(val: string): untyped =
+  result = nnkCaseStmt.newTree(val,
+    nnkElse.newTree(quote do: echo "else"),
+    nnkOfBranch.newTree(newLit("miauz"), quote do: echo "first branch"))
+
+genCase("miauz")
diff --git a/tests/casestmt/tcase_issues.nim b/tests/casestmt/tcase_issues.nim
new file mode 100644
index 000000000..20a79df2c
--- /dev/null
+++ b/tests/casestmt/tcase_issues.nim
@@ -0,0 +1,7 @@
+discard """
+  targets: "c js"
+"""
+
+block: # bug #24031
+  case 0
+  else: discard
\ No newline at end of file
diff --git a/tests/casestmt/tcaseexpr1.nim b/tests/casestmt/tcaseexpr1.nim
index 3d4b6c087..4f5bbf100 100644
--- a/tests/casestmt/tcaseexpr1.nim
+++ b/tests/casestmt/tcaseexpr1.nim
@@ -1,17 +1,23 @@
 discard """
-  errormsg: "type mismatch: got <string> but expected 'int'"
-  line: 33
-  file: "tcaseexpr1.nim"
-
-  errormsg: "not all cases are covered; missing: {C}"
-  line: 27
-  file: "tcaseexpr1.nim"
+  cmd: "nim check $options $file"
+  action: "reject"
+  nimout: '''
+tcaseexpr1.nim(33, 10) Error: not all cases are covered; missing: {C}
+tcaseexpr1.nim(39, 12) Error: type mismatch: got <string> but expected 'int literal(10)'
+'''
 """
 
-# NOTE: This spec is wrong. Spec doesn't support multiple error
-# messages. The first one is simply overridden by the second one.
-# This just has never been noticed.
 
+
+
+
+
+
+
+
+
+
+# line 20
 type
   E = enum A, B, C
 
diff --git a/tests/casestmt/tcasestmt.nim b/tests/casestmt/tcasestmt.nim
index b7454ef99..66de4183d 100644
--- a/tests/casestmt/tcasestmt.nim
+++ b/tests/casestmt/tcasestmt.nim
@@ -41,6 +41,11 @@ block t8333:
   case 0
   of 'a': echo 0
   else: echo 1
+block: # issue #11422
+  var c: int = 5
+  case c
+  of 'a' .. 'c': discard
+  else: discard
 
 
 block emptyset_when:
@@ -184,33 +189,33 @@ block tcasestm:
     doAssert(bstatic == false)
 
   var bb: bool
-  doassert(not compiles(
+  doAssert(not compiles(
     bb = case str2:
       of "": raise newException(ValueError, "Invalid boolean")
       elif str.startsWith("Y"): true
       elif str.startsWith("N"): false
   ))
 
-  doassert(not compiles(
+  doAssert(not compiles(
     bb = case str2:
       of "Y": true
       of "N": false
   ))
 
-  doassert(not compiles(
+  doAssert(not compiles(
     bb = case str2:
       of "Y": true
       of "N": raise newException(ValueError, "N not allowed")
   ))
 
-  doassert(not compiles(
+  doAssert(not compiles(
     bb = case str2:
       of "Y": raise newException(ValueError, "Invalid Y")
       else: raise newException(ValueError, "Invalid N")
   ))
 
 
-  doassert(not compiles(
+  doAssert(not compiles(
     bb = case str2:
       of "Y":
         raise newException(ValueError, "Invalid Y")
@@ -219,7 +224,7 @@ block tcasestm:
   ))
 
 
-  doassert(not compiles(
+  doAssert(not compiles(
     bb = case str2:
       of "Y":
         "invalid Y".quit(3)
@@ -250,3 +255,65 @@ proc negativeOrNot(num: int): string =
 doAssert negativeOrNot(-1) == "negative"
 doAssert negativeOrNot(10000000) == "zero or positive"
 doAssert negativeOrNot(0) == "zero or positive"
+
+########################################################
+# issue #13490
+import strutils
+func foo(input: string): int =
+  try:
+    parseInt(input)
+  except:
+    return
+
+func foo2(b, input: string): int =
+  case b:
+    of "Y":
+      for c in input:
+        result =  if c in '0'..'9': parseInt($c)
+                  else: break
+    of "N":
+      for c in input:
+        result =  if c in '0'..'9': parseInt($c)
+                  else: continue
+    else: return
+
+
+static:
+  doAssert(foo("3") == 3)
+  doAssert(foo("a") == 0)
+  doAssert(foo2("Y", "a2") == 0)
+  doAssert(foo2("Y", "2a") == 2)
+  doAssert(foo2("N", "a3") == 3)
+  doAssert(foo2("z", "2") == 0)
+
+doAssert(foo("3") == 3)
+doAssert(foo("a") == 0)
+doAssert(foo2("Y", "a2") == 0)
+doAssert(foo2("Y", "2a") == 2)
+doAssert(foo2("N", "a3") == 3)
+doAssert(foo2("z", "2") == 0)
+
+
+# bug #20031
+proc main(a: uint64) =
+  case a
+  else:
+    discard
+
+static:
+  main(10)
+main(10)
+
+block:
+  # Just needs to compile
+  proc bar(): int {.discardable.} = discard
+
+  proc foo() {.noreturn.} = discard
+
+  case "*"
+  of "*":
+    bar()
+  else:
+    # Make sure this noreturn doesn't
+    # cause the discardable to not discard
+    foo()
diff --git a/tests/casestmt/tcstring.nim b/tests/casestmt/tcstring.nim
new file mode 100644
index 000000000..288373402
--- /dev/null
+++ b/tests/casestmt/tcstring.nim
@@ -0,0 +1,52 @@
+discard """
+  targets: "c cpp js"
+"""
+
+type Result = enum none, a, b, c, d, e, f
+
+proc foo1(x: cstring): Result =
+  const y = cstring"hash"
+  const arr = [cstring"it", cstring"finally"]
+  result = none
+  case x
+  of "Andreas", "Rumpf": result = a
+  of cstring"aa", "bb": result = b
+  of "cc", y, "when": result = c
+  of "will", arr, "be", "generated": result = d
+  of nil: result = f
+
+var results = [
+  foo1("Rumpf"), foo1("Andreas"),
+  foo1("aa"), foo1(cstring"bb"),
+  foo1("cc"), foo1("hash"),
+  foo1("finally"), foo1("generated"),
+  foo1("no"), foo1("another no"),
+  foo1(nil)]
+doAssert results == [a, a, b, b, c, c, d, d, none, none, f], $results
+
+proc foo2(x: cstring): Result =
+  const y = cstring"hash"
+  const arr = [cstring"it", cstring"finally"]
+  doAssert not (compiles do:
+    result = case x
+    of "Andreas", "Rumpf": a
+    of cstring"aa", "bb": b
+    of "cc", y, "when": c
+    of "will", arr, "be", "generated": d)
+  case x
+  of "Andreas", "Rumpf": a
+  of cstring"aa", "bb": b
+  of "cc", y, "when": c
+  of "will", arr, "be", "generated": d
+  of nil: f
+  else: e
+
+results = [
+  foo2("Rumpf"), foo2("Andreas"),
+  foo2("aa"), foo2(cstring"bb"),
+  foo2("cc"), foo2("hash"),
+  foo2("finally"), foo2("generated"),
+  foo2("no"), foo2("another no"),
+  foo2(nil)]
+
+doAssert results == [a, a, b, b, c, c, d, d, e, e, f], $results
diff --git a/tests/casestmt/tincompletecaseobject.nim b/tests/casestmt/tincompletecaseobject.nim
index 909ee4e1c..aa5deda7a 100644
--- a/tests/casestmt/tincompletecaseobject.nim
+++ b/tests/casestmt/tincompletecaseobject.nim
@@ -1,6 +1,6 @@
 discard """
 errormsg: '''
-not all cases are covered; missing: {nnkComesFrom, nnkDotCall, nnkHiddenCallConv, nnkVarTuple, nnkCurlyExpr, nnkRange, nnkCheckedFieldExpr, nnkDerefExpr, nnkElifExpr, nnkElseExpr, nnkLambda, nnkDo, nnkBind, nnkClosedSymChoice, nnkHiddenSubConv, nnkConv, nnkStaticExpr, nnkAddr, nnkHiddenAddr, nnkHiddenDeref, nnkObjDownConv, nnkObjUpConv, nnkChckRangeF, nnkChckRange64, nnkChckRange, nnkStringToCString, nnkCStringToString, nnkFastAsgn, nnkGenericParams, nnkFormalParams, nnkOfInherit, nnkImportAs, nnkConverterDef, nnkMacroDef, nnkTemplateDef, nnkIteratorDef, nnkOfBranch, nnkElifBranch, nnkExceptBranch, nnkElse, nnkAsmStmt, nnkTypeDef, nnkFinally, nnkContinueStmt, nnkImportStmt, nnkImportExceptStmt, nnkExportStmt, nnkExportExceptStmt, nnkFromStmt, nnkIncludeStmt, nnkUsingStmt, nnkBlockExpr, nnkStmtListType, nnkBlockType, nnkWith, nnkWithout, nnkTypeOfExpr, nnkObjectTy, nnkTupleTy, nnkTupleClassTy, nnkTypeClassTy, nnkStaticTy, nnkRecList, nnkRecCase, nnkRecWhen, nnkVarTy, nnkConstTy, nnkMutableTy, nnkDistinctTy, nnkProcTy, nnkIteratorTy, nnkSharedTy, nnkEnumTy, nnkEnumFieldDef, nnkArglist, nnkPattern, nnkReturnToken, nnkClosure, nnkGotoState, nnkState, nnkBreakState, nnkFuncDef, nnkTupleConstr}
+not all cases are covered; missing: {nnkComesFrom, nnkDotCall, nnkHiddenCallConv, nnkVarTuple, nnkCurlyExpr, nnkRange, nnkCheckedFieldExpr, nnkDerefExpr, nnkElifExpr, nnkElseExpr, nnkLambda, nnkDo, nnkBind, nnkClosedSymChoice, nnkHiddenSubConv, nnkConv, nnkStaticExpr, nnkAddr, nnkHiddenAddr, nnkHiddenDeref, nnkObjDownConv, nnkObjUpConv, nnkChckRangeF, nnkChckRange64, nnkChckRange, nnkStringToCString, nnkCStringToString, nnkFastAsgn, nnkGenericParams, nnkFormalParams, nnkOfInherit, nnkImportAs, nnkConverterDef, nnkMacroDef, nnkTemplateDef, nnkIteratorDef, nnkOfBranch, nnkElifBranch, nnkExceptBranch, nnkElse, nnkAsmStmt, nnkTypeDef, nnkFinally, nnkContinueStmt, nnkImportStmt, nnkImportExceptStmt, nnkExportStmt, nnkExportExceptStmt, nnkFromStmt, nnkIncludeStmt, nnkUsingStmt, nnkBlockExpr, nnkStmtListType, nnkBlockType, nnkWith, nnkWithout, nnkTypeOfExpr, nnkObjectTy, nnkTupleTy, nnkTupleClassTy, nnkTypeClassTy, nnkStaticTy, nnkRecList, nnkRecCase, nnkRecWhen, nnkVarTy, nnkConstTy, nnkMutableTy, nnkDistinctTy, nnkProcTy, nnkIteratorTy, nnkSharedTy, nnkEnumTy, nnkEnumFieldDef, nnkArgList, nnkPattern, nnkReturnToken, nnkClosure, nnkGotoState, nnkState, nnkBreakState, nnkFuncDef, nnkTupleConstr}
 '''
 """
 
@@ -62,7 +62,7 @@ type
     nnkSharedTy,           # 'shared T'
     nnkEnumTy,
     nnkEnumFieldDef,
-    nnkArglist, nnkPattern
+    nnkArgList, nnkPattern
     nnkReturnToken,
     nnkClosure,
     nnkGotoState,
diff --git a/tests/casestmt/tincompletecaseobject2.nim b/tests/casestmt/tincompletecaseobject2.nim
index c080cfeb1..bbeae1909 100644
--- a/tests/casestmt/tincompletecaseobject2.nim
+++ b/tests/casestmt/tincompletecaseobject2.nim
@@ -1,12 +1,5 @@
 discard """
 cmd: "nim check $file"
-errormsg: "not all cases are covered; missing: {A, B}"
-nimout: '''
-tincompletecaseobject2.nim(18, 1) Error: not all cases are covered; missing: {' ', '!', '\"', '#', '$', '%', '&', '\'', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'}
-tincompletecaseobject2.nim(22, 1) Error: not all cases are covered; missing: {B, C, D}
-tincompletecaseobject2.nim(25, 1) Error: not all cases are covered; missing: {A, C}
-tincompletecaseobject2.nim(28, 1) Error: not all cases are covered; missing: {A, B}
-'''
 """
 type
   ABCD = enum A, B, C, D
@@ -15,15 +8,19 @@ type
   AliasRangeABC = RangeABC
   PrintableChars = range[' ' .. '~']
 
-case PrintableChars 'x':
+case PrintableChars 'x': #[tt.Error
+^ not all cases are covered; missing: {' ', '!', '\"', '#', '$$', '%', '&', '\'', '*', '+', ',', '-', '.', '/', ':', ';', '<', '=', '>', '?', '@', '[', '\\', ']', '^', '_', '`', '{', '|', '}', '~'}]#
 of '0'..'9', 'A'..'Z', 'a'..'z': discard
 of '(', ')': discard
 
-case AliasABCD A:
+case AliasABCD A: #[tt.Error
+^ not all cases are covered; missing: {B, C, D}]#
 of A: discard
 
-case RangeABC A:
+case RangeABC A: #[tt.Error
+^ not all cases are covered; missing: {A, C}]#
 of B: discard
 
-case AliasRangeABC A:
+case AliasRangeABC A: #[tt.Error
+^ not all cases are covered; missing: {A, B}]#
 of C: discard
diff --git a/tests/casestmt/trangeexhaustiveness.nim b/tests/casestmt/trangeexhaustiveness.nim
new file mode 100644
index 000000000..2b7f3558e
--- /dev/null
+++ b/tests/casestmt/trangeexhaustiveness.nim
@@ -0,0 +1,7 @@
+block: # issue #22661
+  template foo(a: typed) =
+    a
+    
+  foo:
+    case false
+    of false..true: discard
diff --git a/tests/cast/tcast.nim b/tests/cast/tcast.nim
new file mode 100644
index 000000000..205444ea3
--- /dev/null
+++ b/tests/cast/tcast.nim
@@ -0,0 +1,21 @@
+discard """
+  targets: "c cpp js"
+"""
+
+proc main() =
+  block: # bug #16806
+    let
+      a = 42u16
+      b = cast[int16](a)
+    doAssert a.int16 == 42
+    doAssert b in int16.low..int16.high
+
+  block: # bug #16808
+    doAssert cast[int8](cast[uint8](int8(-12))) == int8(-12)
+    doAssert cast[int16](cast[uint16](int16(-12))) == int16(-12)
+    doAssert cast[int32](cast[uint32](int32(-12))) == int32(-12)
+
+  doAssert cast[int8](int16.high) == -1
+
+static: main()
+main()
diff --git a/tests/ccgbugs/m1/defs.nim b/tests/ccgbugs/m1/defs.nim
new file mode 100644
index 000000000..ed78d8b72
--- /dev/null
+++ b/tests/ccgbugs/m1/defs.nim
@@ -0,0 +1,4 @@
+type MyObj* = object
+  field1*: int
+  s*: string
+  ch*: char
diff --git a/tests/ccgbugs/m19445.c b/tests/ccgbugs/m19445.c
new file mode 100644
index 000000000..74c23d4b4
--- /dev/null
+++ b/tests/ccgbugs/m19445.c
@@ -0,0 +1,3 @@
+#include "m19445.h"
+
+const Foo f = {10, 20, 30, 40};
\ No newline at end of file
diff --git a/tests/ccgbugs/m2/defs.nim b/tests/ccgbugs/m2/defs.nim
new file mode 100644
index 000000000..798d1fea8
--- /dev/null
+++ b/tests/ccgbugs/m2/defs.nim
@@ -0,0 +1,4 @@
+type MyObj* = object
+  s*: string
+  field1*: int
+  ch*: char
diff --git a/tests/ccgbugs/mstatic_assert.nim b/tests/ccgbugs/mstatic_assert.nim
new file mode 100644
index 000000000..dbf9c03d1
--- /dev/null
+++ b/tests/ccgbugs/mstatic_assert.nim
@@ -0,0 +1,6 @@
+{.emit:"""
+NIM_STATIC_ASSERT(sizeof(bool) == 1, "");
+#warning "foo2"
+NIM_STATIC_ASSERT(sizeof(bool) == 2, "");
+#warning "foo3"
+""".}
diff --git a/tests/ccgbugs/t10128.nim b/tests/ccgbugs/t10128.nim
new file mode 100644
index 000000000..48970916f
--- /dev/null
+++ b/tests/ccgbugs/t10128.nim
@@ -0,0 +1,18 @@
+# bug #10128
+let data = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
+var seq2 = newSeq[char](data.len)
+for i in 0..<data.len:
+  seq2[i] = data[i]
+
+let c = '\128'
+
+# case 1
+doAssert data[c.int] == 'y'
+doAssert seq2[c.int] == 'y'
+
+proc play(x: openArray[char]) =
+  doAssert x[c.int] == 'y'
+
+# case2
+play(data)
+play(seq2)
\ No newline at end of file
diff --git a/tests/ccgbugs/t10964.nim b/tests/ccgbugs/t10964.nim
new file mode 100644
index 000000000..c19db6997
--- /dev/null
+++ b/tests/ccgbugs/t10964.nim
@@ -0,0 +1,7 @@
+func test*(input: var openArray[int32], start: int = 0, fin: int = input.len - 1) =

+    discard

+

+var someSeq = @[1'i32]

+

+test(someSeq)

+# bug with gcc 14
\ No newline at end of file
diff --git a/tests/ccgbugs/t13062.nim b/tests/ccgbugs/t13062.nim
new file mode 100644
index 000000000..cfda1da7c
--- /dev/null
+++ b/tests/ccgbugs/t13062.nim
@@ -0,0 +1,33 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp"
+"""
+
+import atomics
+
+type
+  Pledge* {.exportc.} = object
+    p: PledgePtr
+
+  PledgeKind {.exportc.} = enum
+    Single
+    Iteration
+
+  PledgePtr {.exportc.} = ptr object
+    case kind: PledgeKind
+    of Single:
+      impl: PledgeImpl
+    of Iteration:
+      discard
+
+  PledgeImpl {.exportc.} = object
+    fulfilled: Atomic[bool]
+
+var x: Pledge
+when defined(cpp):
+  # TODO: fixme
+  discard "it doesn't work for refc/orc because of contrived `Atomic` in cpp"
+elif defined(gcRefc):
+  doAssert x.repr == "[p = nil]"
+else: # fixme # bug #20081
+  doAssert x.repr == "Pledge(p: nil)"
diff --git a/tests/ccgbugs/t13902.nim b/tests/ccgbugs/t13902.nim
new file mode 100644
index 000000000..fd4f76d15
--- /dev/null
+++ b/tests/ccgbugs/t13902.nim
@@ -0,0 +1,12 @@
+
+#issue #13902
+block:
+  type Slot = distinct uint64
+  var s = Slot(1)
+  proc `$`(x: Slot): string {.borrow.}
+  proc `+=`(x: var Slot, y: uint64) {.borrow.}
+  # test was failing with either 0 or 2 echos but not with 1 echo
+  # echo "s = ", s
+  s += 1
+  # echo "s = ", s
+  doAssert s.uint64 == 2, $s # was failing, showing 18419607611339964418
diff --git a/tests/ccgbugs/t15428.nim b/tests/ccgbugs/t15428.nim
new file mode 100644
index 000000000..d9ae8ff16
--- /dev/null
+++ b/tests/ccgbugs/t15428.nim
@@ -0,0 +1,22 @@
+discard """

+    cmd: "nim $target --mm:refc $file"

+    output: '''5

+5

+[1, 2, 3, 4, 5]

+(data: [1, 2, 3, 4, 5])

+'''

+"""

+

+proc take[T](f: openArray[T]) =

+  echo f.len

+let f = @[0,1,2,3,4]

+take(f.toOpenArray(0,4))

+

+{.experimental: "views".}

+type

+  Foo = object

+    data: openArray[int]

+let f2 = Foo(data: [1,2,3,4,5])

+echo f2.data.len

+echo f2.data

+echo f2
\ No newline at end of file
diff --git a/tests/ccgbugs/t16027.nim b/tests/ccgbugs/t16027.nim
new file mode 100644
index 000000000..58f15eb6e
--- /dev/null
+++ b/tests/ccgbugs/t16027.nim
@@ -0,0 +1,13 @@
+discard """
+  ccodecheck: "__restrict__"
+  action: compile
+  joinable: false
+"""
+
+# see bug #16027
+iterator myitems(s: seq[int]): int =
+  var data {.codegenDecl: "$# __restrict__ $#".} : ptr int = nil
+  yield 1
+
+for i in @[1].myitems:
+  discard
diff --git a/tests/ccgbugs/t16374.nim b/tests/ccgbugs/t16374.nim
new file mode 100644
index 000000000..8ccfa4815
--- /dev/null
+++ b/tests/ccgbugs/t16374.nim
@@ -0,0 +1,38 @@
+discard """
+  matrix: "--gc:refc; --gc:orc"
+"""
+
+block:
+  iterator mvalues(t: var seq[seq[int]]): var seq[int] =
+    yield t[0]
+
+  var t: seq[seq[int]]
+
+  while false:
+    for v in t.mvalues:
+      discard
+
+  proc ok =
+    while false:
+      for v in t.mvalues:
+        discard
+
+  ok()
+
+block:
+  iterator mvalues(t: var seq[seq[int]]): lent seq[int] =
+    yield t[0]
+
+  var t: seq[seq[int]]
+
+  while false:
+    for v in t.mvalues:
+      discard
+
+  proc ok =
+    while false:
+      for v in t.mvalues:
+        discard
+
+  ok()
+
diff --git a/tests/ccgbugs/t19445.nim b/tests/ccgbugs/t19445.nim
new file mode 100644
index 000000000..b6e8d028c
--- /dev/null
+++ b/tests/ccgbugs/t19445.nim
@@ -0,0 +1,13 @@
+discard """
+  matrix: "--nimcache:tests/ccgbugs/nimcache19445 --cincludes:nimcache19445 --header:m19445"
+  targets: "c"
+"""
+
+# bug #19445
+type
+  Foo* {.exportc.} = object
+    a*, b*, c*, d*: int
+
+proc dummy(): Foo {.exportc.} = discard
+
+{.compile:"m19445.c".}
\ No newline at end of file
diff --git a/tests/ccgbugs/t20139.nim b/tests/ccgbugs/t20139.nim
new file mode 100644
index 000000000..4592b994d
--- /dev/null
+++ b/tests/ccgbugs/t20139.nim
@@ -0,0 +1,10 @@
+discard """
+  joinable: false
+"""
+
+# bug #20139
+import m1/defs as md1
+import m2/defs as md2
+
+doAssert $(md1.MyObj(field1: 1)) == """(field1: 1, s: "", ch: '\x00')"""
+doAssert $(md2.MyObj(field1: 1)) == """(s: "", field1: 1, ch: '\x00')"""
diff --git a/tests/ccgbugs/t20141.nim b/tests/ccgbugs/t20141.nim
new file mode 100644
index 000000000..60e130690
--- /dev/null
+++ b/tests/ccgbugs/t20141.nim
@@ -0,0 +1,27 @@
+discard """
+  joinable: false
+"""
+
+# bug #20141
+type
+  A = object
+  B = object
+  U = proc()
+
+proc m(h: var B) = discard
+
+template n[T, U](x: U): T =
+  static: doAssert true
+  cast[ptr T](addr x)[]
+
+proc k() =
+  var res: A
+  m(n[B, A](res))
+
+proc w(mounter: U) = discard
+
+proc mount(proto: U) = discard
+proc v() = mount k
+
+# This is required for failure
+w(v)
diff --git a/tests/ccgbugs/t20787.nim b/tests/ccgbugs/t20787.nim
new file mode 100644
index 000000000..c2d848c2c
--- /dev/null
+++ b/tests/ccgbugs/t20787.nim
@@ -0,0 +1,4 @@
+type
+  Obj = object
+    f: UncheckedArray[byte]
+let o = new Obj
\ No newline at end of file
diff --git a/tests/ccgbugs/t21116.nim b/tests/ccgbugs/t21116.nim
new file mode 100644
index 000000000..cc77de198
--- /dev/null
+++ b/tests/ccgbugs/t21116.nim
@@ -0,0 +1,10 @@
+discard """
+  targets: "c cpp"
+  disabled: windows
+"""
+# bug #21116
+import std/os
+
+proc p(glob: string) =
+  for _ in walkFiles(glob): discard
+p("dir/*")
diff --git a/tests/ccgbugs/t21972.nim b/tests/ccgbugs/t21972.nim
new file mode 100644
index 000000000..58d0cfc62
--- /dev/null
+++ b/tests/ccgbugs/t21972.nim
@@ -0,0 +1,33 @@
+discard """

+    targets: "c cpp"

+    outputsub: "Error: unhandled exception: Err2 [IOError]"

+    exitcode: "1"

+"""

+

+proc bar(x: var int) =

+  inc x

+  if x == 3:

+    raise newException(ValueError, "H0")

+

+  elif x == 5:

+    raise newException(IOError, "H1")

+

+  elif x > 7:

+    raise newException(IOError, "H2")

+

+

+proc foo() =

+  var i = 0

+  while true:

+    try:

+      bar(i)

+      echo i

+

+    except ValueError:

+      debugEcho("ValueError")

+

+    except IOError:

+      raise newException(IOError, "Err2")

+

+when isMainModule:

+  foo()
\ No newline at end of file
diff --git a/tests/ccgbugs/t21995.nim b/tests/ccgbugs/t21995.nim
new file mode 100644
index 000000000..0ec88aa59
--- /dev/null
+++ b/tests/ccgbugs/t21995.nim
@@ -0,0 +1,9 @@
+discard """
+    targets: "c cpp"
+    output: "Hi!"
+"""
+
+try:
+  raise
+except:
+  echo "Hi!"
\ No newline at end of file
diff --git a/tests/ccgbugs/t22462.nim b/tests/ccgbugs/t22462.nim
new file mode 100644
index 000000000..9adfbb19b
--- /dev/null
+++ b/tests/ccgbugs/t22462.nim
@@ -0,0 +1,20 @@
+discard """
+  action: "run"
+  output: '''
+1
+1
+1
+'''
+  matrix: "--mm:refc"
+  targets: "c cpp"
+"""
+
+type Object = object
+  someComplexType: seq[int]
+  index: Natural
+
+func newObject(): Object = result.index.inc
+
+for i in 1..3:
+  let o = newObject()
+  echo o.index
diff --git a/tests/ccgbugs/t23796.nim b/tests/ccgbugs/t23796.nim
new file mode 100644
index 000000000..421ec04d8
--- /dev/null
+++ b/tests/ccgbugs/t23796.nim
@@ -0,0 +1,25 @@
+discard """
+    targets: "c cpp"
+"""
+
+# bug #23796
+
+{.emit: """
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+void fooArr(float data[3]) {}
+void fooIntArr(int id, float data[3]) {}
+
+#ifdef __cplusplus
+}
+#endif
+""".}
+
+proc fooArr(data: var array[3, cfloat]) {.importc.}
+proc fooIntArr(id: cint, data: var array[3, cfloat]) {.importc, nodecl.}
+
+var arr = [cfloat 1, 2, 3]
+fooArr(arr)
+fooIntArr(1, arr)
diff --git a/tests/ccgbugs/t2procs.nim b/tests/ccgbugs/t2procs.nim
new file mode 100644
index 000000000..d8b7a2815
--- /dev/null
+++ b/tests/ccgbugs/t2procs.nim
@@ -0,0 +1,18 @@
+discard """
+  output: '''before
+1
+before
+2'''
+"""
+
+proc fn[T1, T2](a: T1, b: T2) =
+  a(1)
+  b(2)
+
+fn( (proc(x: int) =
+      echo "before" # example block, can span multiple lines
+      echo x),
+    (proc (y: int) =
+      echo "before"
+      echo y)
+)
diff --git a/tests/ccgbugs/t5296.nim b/tests/ccgbugs/t5296.nim
index 990b4bee2..8fbed35c4 100644
--- a/tests/ccgbugs/t5296.nim
+++ b/tests/ccgbugs/t5296.nim
@@ -1,6 +1,7 @@
 discard """
 cmd: "nim c -d:release $file"
-output: 1
+output: '''1
+-1'''
 """
 
 proc bug() : void =
@@ -12,3 +13,9 @@ proc bug() : void =
         echo x
 
 bug()
+
+# bug #19051
+type GInt[T] = int
+
+var a = 1
+echo -a
diff --git a/tests/ccgbugs/t6756.nim b/tests/ccgbugs/t6756.nim
index 5170a99f4..5990eba58 100644
--- a/tests/ccgbugs/t6756.nim
+++ b/tests/ccgbugs/t6756.nim
@@ -10,7 +10,7 @@ type
     v: T
 
 template templ(o: A, op: untyped): untyped =
-  type T = type(o.v)
+  type T = typeof(o.v)
 
   var res: A[T]
 
diff --git a/tests/ccgbugs/t8967.nim b/tests/ccgbugs/t8967.nim
index e342b7eae..0301a2e4f 100644
--- a/tests/ccgbugs/t8967.nim
+++ b/tests/ccgbugs/t8967.nim
@@ -4,7 +4,11 @@ discard """
 
 import marshal
 
-let orig: set[char] = {'A'..'Z'}
-let m = $$orig
-let old = to[set[char]](m)
-doAssert orig - old == {}
+template main() =
+  let orig: set[char] = {'A'..'Z'}
+  let m = $$orig
+  let old = to[set[char]](m)
+  doAssert orig - old == {}
+
+static: main()
+main()
diff --git a/tests/ccgbugs/t9286.nim b/tests/ccgbugs/t9286.nim
index 8a45a7bf6..2fec23307 100644
--- a/tests/ccgbugs/t9286.nim
+++ b/tests/ccgbugs/t9286.nim
@@ -7,7 +7,7 @@ type Foo  = ref object
   i:      int
 
 proc next(foo: Foo): Option[Foo] =
-  try:    assert(foo.i == 0)
+  try:    doAssert(foo.i == 0)
   except: return      # 2º: none
   return some(foo)    # 1º: some
 
@@ -17,6 +17,6 @@ proc test =
   while isSome(opt) and foo.i < 10:
     inc(foo.i)
     opt = next(foo)   # 2º None
-  assert foo.i == 1, $foo.i
+  doAssert foo.i == 1, $foo.i
 
 test()
diff --git a/tests/ccgbugs/t9655.nim b/tests/ccgbugs/t9655.nim
new file mode 100644
index 000000000..29fb903a4
--- /dev/null
+++ b/tests/ccgbugs/t9655.nim
@@ -0,0 +1,30 @@
+discard """
+  action: "compile"
+"""
+
+import std/[asynchttpserver, asyncdispatch]
+import std/[strformat]
+
+proc main() =
+  let local = "123"
+
+  proc serveIndex(req: Request) {.async, gcsafe.} =
+    await req.respond(Http200, &"{local}")
+
+  proc serve404(req: Request) {.async, gcsafe.} =
+    echo req.url.path
+    await req.respond(Http404, "not found")
+
+  proc serve(req: Request) {.async, gcsafe.} =
+    let handler = case req.url.path:
+      of "/":
+        serveIndex
+      else:
+        serve404
+    await handler(req)
+
+  let server = newAsyncHttpServer()
+  waitFor server.serve(Port(8080), serve, address = "127.0.0.1")
+
+when isMainModule:
+  main()
diff --git a/tests/ccgbugs/targ_lefttoright.nim b/tests/ccgbugs/targ_lefttoright.nim
new file mode 100644
index 000000000..a0adce157
--- /dev/null
+++ b/tests/ccgbugs/targ_lefttoright.nim
@@ -0,0 +1,71 @@
+discard """
+  nimout: '''1,2
+2,3
+2,2
+1,2
+1,2
+2,2
+1,2
+'''
+  output: '''1,2
+2,3
+1,2
+2,2
+1,2
+1,2
+2,2
+1,2
+'''
+  cmd: "nim c --gc:orc $file"
+"""
+
+template test =
+  proc say(a, b: int) =
+    echo a,",",b
+
+  var a = 1
+  say a, (a += 1; a) #1,2
+
+  var b = 1
+  say (b += 1; b), (b += 1; b) #2,3
+
+  type C {.byRef.} = object
+    i: int
+
+  proc say(a, b: C) =
+    echo a.i,",",b.i
+
+  proc `+=`(x: var C, y: C) = x.i += y.i
+
+  var c = C(i: 1)
+  when nimvm: #XXX: This would output 2,2 in the VM, which is wrong
+    discard
+  else:
+    say c, (c += C(i: 1); c) #1,2
+
+  proc sayVar(a: var int, b: int) =
+    echo a,",",b
+
+  var d = 1
+  sayVar d, (d += 1; d) #2,2
+
+  var e = 1
+  say (addr e)[], (e += 1; e) #1,2
+
+  var f = 1
+  say f, if false: f
+         else: f += 1; f #1,2
+
+  var g = 1
+  say g + 1, if false: g
+             else: g += 1; g #2,2
+
+  proc `+=+`(x: var int, y: int): int = (inc(x, y); x)
+
+  var h = 1
+  say h, h +=+ 1 # 1,2
+
+test
+
+static:
+  test
diff --git a/tests/ccgbugs/tassign_nil_strings.nim b/tests/ccgbugs/tassign_nil_strings.nim
index 07d2c2aeb..e32bfcade 100644
--- a/tests/ccgbugs/tassign_nil_strings.nim
+++ b/tests/ccgbugs/tassign_nil_strings.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: "nim $target --nilseqs:off $options $file"
+  matrix: "--mm:refc"
   output: "Hello"
   ccodecheck: "\\i@'a = ((NimStringDesc*) NIM_NIL)'"
 """
diff --git a/tests/ccgbugs/tbug21505.nim b/tests/ccgbugs/tbug21505.nim
new file mode 100644
index 000000000..0c0811ec5
--- /dev/null
+++ b/tests/ccgbugs/tbug21505.nim
@@ -0,0 +1,39 @@
+discard """
+    action: "compile"
+    targets: "cpp"
+    cmd: "nim cpp $file"
+"""
+
+# see #21505: ensure compilation of imported C++ objects with explicit constructors while retaining default initialization through codegen changes due to #21279
+
+{.emit:"""/*TYPESECTION*/
+
+struct ExplObj
+{
+  explicit ExplObj(int bar = 0) {}  
+};
+
+struct BareObj
+{
+    BareObj() {}
+};
+
+""".}
+
+type
+  ExplObj {.importcpp.} = object
+  BareObj {.importcpp.} = object
+
+type
+  Composer = object
+    explObj: ExplObj
+    bareObj: BareObj
+
+proc foo =
+  var composer1 {.used.}: Composer
+  let composer2 {.used.} = Composer()
+
+var composer1 {.used.}: Composer
+let composer2 {.used.} = Composer()
+
+foo()
\ No newline at end of file
diff --git a/tests/ccgbugs/tccgen1.nim b/tests/ccgbugs/tccgen1.nim
index 4917c9848..be571de08 100644
--- a/tests/ccgbugs/tccgen1.nim
+++ b/tests/ccgbugs/tccgen1.nim
@@ -7,7 +7,7 @@ type
     Features: seq[Feature] # Read-Only
 
   PNode* = ref Node
-  Node = object {.inheritable.}
+  Node {.inheritable.} = object
     attributes*: seq[PAttr]
     childNodes*: seq[PNode]
     FLocalName: string # Read-only
diff --git a/tests/ccgbugs/tcgbug.nim b/tests/ccgbugs/tcgbug.nim
index db9c116be..2eddc6fdd 100644
--- a/tests/ccgbugs/tcgbug.nim
+++ b/tests/ccgbugs/tcgbug.nim
@@ -4,6 +4,7 @@ success
 M1 M2
 ok
 '''
+matrix: "--mm:refc;--mm:orc"
 """
 
 type
@@ -24,6 +25,7 @@ q(a)
 
 # bug #914
 when defined(windows):
+  import std/widestrs
   var x = newWideCString("Hello")
 
 echo "success"
@@ -91,3 +93,71 @@ proc test(c: Helper): string =
   c.formatted
 
 echo test(Helper(isKind: true, formatted: "ok"))
+
+
+# bug #19613
+
+type
+  Eth2Digest = object
+    data: array[42, byte]
+
+  BlockId* = object
+    root*: Eth2Digest
+
+  BlockSlotId* = object
+    bid*: BlockId
+    slot*: uint64
+
+func init*(T: type BlockSlotId, bid: BlockId, slot: uint64): T =
+  #debugecho "init ", bid, " ", slot
+  BlockSlotId(bid: bid, slot: slot)
+
+proc bug19613 =
+  var x: BlockSlotId
+  x.bid.root.data[0] = 42
+
+  x =
+    if x.slot > 0:
+      BlockSlotId.init(x.bid, x.slot)
+    else:
+      BlockSlotId.init(x.bid, x.slot)
+  doAssert x.bid.root.data[0] == 42
+
+bug19613()
+
+proc foo = # bug #23280
+  let foo = @[1,2,3,4,5,6]
+  doAssert toOpenArray(foo, 0, 5).len == 6
+  doAssert toOpenArray(foo, 0, 5).len mod 6 == 0 # this should output 0
+  doAssert toOpenArray(foo, 0, 5).max mod 6 == 0
+  let L = toOpenArray(foo, 0, 5).len
+  doAssert L mod 6 == 0 
+
+foo()
+
+block: # bug #9940
+  {.emit:"""/*TYPESECTION*/
+typedef struct { int base; } S;
+""".}
+
+  type S {.importc: "S", completeStruct.} = object
+    base: cint
+  proc init(x:ptr S) =
+    x.base = 1
+
+  type
+    Foo = object
+      a: seq[float]
+      b: seq[float]
+      c: seq[float]
+      d: seq[float]
+      s: S
+
+  proc newT(): Foo =
+    var t: Foo
+    t.s.addr.init
+    doAssert t.s.base == 1
+    t
+
+  var t = newT()
+  doAssert t.s.base == 1
diff --git a/tests/ccgbugs/tcodegenbug1.nim b/tests/ccgbugs/tcodegenbug1.nim
index ebdc57144..d2ab97ede 100644
--- a/tests/ccgbugs/tcodegenbug1.nim
+++ b/tests/ccgbugs/tcodegenbug1.nim
@@ -1,9 +1,13 @@
 discard """
+  matrix: "--mm:refc"
   output: '''obj = (inner: (kind: Just, id: 7))
 obj.inner.id = 7
 id = 7
 obj = (inner: (kind: Just, id: 7))
-2'''
+2
+(a: "a", b: "b", c: "")
+caught
+(a: "a", b: "b", c: "")'''
 """
 
 # bug #6960
@@ -129,12 +133,53 @@ import macros
 func myfunc(obj: MyObject): MyResult {.raises: [].} =
   template index: auto =
     case obj.kind:
-      of Float: $obj.index 
+      of Float: $obj.index
       of Fixed: "Fixed"
   macro to_str(a: untyped): string =
-    result = newStrLitNode(a.repr)  
+    result = newStrLitNode(a.repr)
   result.val[0] = index
   result.val[1] = to_str(obj.kind + Ola)
 
 let x = MyObject(someInt: 10, kind: Fixed)
 echo myfunc(x).val.len
+
+# bug #14126
+
+type X = object
+  a, b, c: string
+
+proc f(): X =
+  result.a = "a"
+  result.b = "b"
+  raise (ref ValueError)()
+
+proc ohmanNoNRVO =
+  var x: X
+  x.a = "1"
+  x.b = "2"
+  x.c = "3"
+
+  try:
+    x = f()
+  except:
+    discard
+
+  echo x
+  # once NVRO is sorted out, x.c == "3"
+  doAssert x.c == "", "shouldn't modify x if f raises"
+
+ohmanNoNRVO()
+
+proc ohmanNoNRVO2(x: var X) =
+  x.a = "1"
+  x.c = "3"
+  x = f()
+
+var xgg: X
+try:
+  ohmanNoNRVO2(xgg)
+except:
+  echo "caught"
+echo xgg
+# once NVRO is sorted out, xgg.c == "3"
+doAssert xgg.c == "", "this assert will fail"
diff --git a/tests/ccgbugs/tcodegenbug_bool.nim b/tests/ccgbugs/tcodegenbug_bool.nim
new file mode 100644
index 000000000..a0dbf4eb2
--- /dev/null
+++ b/tests/ccgbugs/tcodegenbug_bool.nim
@@ -0,0 +1,11 @@
+discard """
+"""
+
+# issue #13798
+{.emit:"""
+#include <stdbool.h>
+void fun(bool a){}
+""".}
+
+proc fun(a: bool) {.importc.}
+fun(true)
diff --git a/tests/ccgbugs/tcompile_time_var_at_runtime.nim b/tests/ccgbugs/tcompile_time_var_at_runtime.nim
new file mode 100644
index 000000000..c0de0390b
--- /dev/null
+++ b/tests/ccgbugs/tcompile_time_var_at_runtime.nim
@@ -0,0 +1,11 @@
+discard """
+  output: "1\n2\n2\n3"
+"""
+var a {.compileTime.} = 1
+
+echo a
+a = 2
+echo a
+echo a
+a = 3
+echo a 
\ No newline at end of file
diff --git a/tests/ccgbugs/tctypes.nim b/tests/ccgbugs/tctypes.nim
new file mode 100644
index 000000000..be6009115
--- /dev/null
+++ b/tests/ccgbugs/tctypes.nim
@@ -0,0 +1,43 @@
+discard """
+  targets: "c cpp"
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+# bug #7308
+proc foo(x: seq[int32]) =
+  var y = newSeq[cint](1)
+
+proc bar =
+  var t = newSeq[int32](1)
+  foo(t)
+
+bar()
+
+
+# bug #16246
+
+proc testWeirdTypeAliases() =
+  var values = newSeq[cuint](8)
+  # var values: seq[cuint] does not produce codegen error
+  var drawCb = proc(): seq[uint32] =
+    result = newSeq[uint32](10)
+
+testWeirdTypeAliases()
+
+block: # bug #11797
+  block:
+    type cdouble2 = cdouble
+    type Foo1 = seq[cdouble]
+    type Foo2 = seq[cdouble2]
+    static: doAssert Foo1 is Foo2
+    var a1: Foo1
+    var a2: Foo2
+    doAssert a1 == @[]
+    doAssert a2 == @[]
+
+  block:
+    proc foo[T: int|cint](fun: proc(): T) = discard
+    proc foo1(): cint = 1
+    proc foo3(): int32 = 2
+    foo(proc(): cint = foo1())
+    foo(proc(): int32 = foo3())
diff --git a/tests/ccgbugs/tdeepcopy_addr_rval.nim b/tests/ccgbugs/tdeepcopy_addr_rval.nim
index 07fb8f8ef..4a0b0deaa 100644
--- a/tests/ccgbugs/tdeepcopy_addr_rval.nim
+++ b/tests/ccgbugs/tdeepcopy_addr_rval.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc --deepcopy:on"
   output: "3"
 """
 
diff --git a/tests/ccgbugs/tderefblock.nim b/tests/ccgbugs/tderefblock.nim
new file mode 100644
index 000000000..d3ba07667
--- /dev/null
+++ b/tests/ccgbugs/tderefblock.nim
@@ -0,0 +1,76 @@
+discard """
+  matrix: "--mm:refc -d:release -d:danger;--mm:orc -d:useMalloc -d:release -d:danger"
+  output: "42"
+"""
+
+# bug #20107
+
+type Foo = object
+  a, b, c, d: uint64
+
+proc c(i: uint64): Foo =
+  Foo(a: i, b: i, c: i, d: i)
+
+func x(f: Foo): lent Foo {.inline.} =
+  f
+
+proc m() =
+  let f = block:
+    let i = c(42)
+    x(i)
+
+  echo $f.a
+
+m()
+
+block: # bug #21540
+  type
+    Option = object
+      val: string
+      has: bool
+
+  proc some(val: string): Option =
+    result.has = true
+    result.val = val
+
+  # Remove lent and it works
+  proc get(self: Option): lent string =
+    result = self.val
+
+  type
+    StringStream = ref object
+      data: string
+      pos: int
+
+  proc readAll(s: StringStream): string =
+    result = newString(s.data.len)
+    copyMem(addr(result[0]), addr(s.data[0]), s.data.len)
+
+  proc newStringStream(s: string = ""): StringStream =
+    new(result)
+    result.data = s
+
+  proc parseJson(s: string): string =
+    let stream = newStringStream(s)
+    result = stream.readAll()
+
+  proc main =
+    let initialFEN = block:
+      let initialFEN = some parseJson("startpos")
+      initialFEN.get
+
+    doAssert initialFEN == "startpos"
+
+  main()
+
+import std/[
+    json,
+    options
+]
+
+block: # bug #21540
+  let cheek = block:
+    let initialFEN = some("""{"initialFen": "startpos"}""".parseJson{"initialFen"}.getStr)
+    initialFEN.get
+
+  doAssert cheek == "startpos"
diff --git a/tests/ccgbugs/tforward_decl_only.nim b/tests/ccgbugs/tforward_decl_only.nim
index 74fbae303..b115dcbe7 100644
--- a/tests/ccgbugs/tforward_decl_only.nim
+++ b/tests/ccgbugs/tforward_decl_only.nim
@@ -1,7 +1,5 @@
 discard """
-ccodecheck: "\\i !@('struct tyObject_MyRefObject'[0-z]+' {')"
-ccodecheck: "\\i !@('mymoduleInit')"
-ccodecheck: "\\i @('mymoduleDatInit')"
+ccodecheck: "\\i !@('struct tyObject_MyRefObject'[0-z]+' _')"
 output: "hello"
 """
 
diff --git a/tests/ccgbugs/thtiobj.nim b/tests/ccgbugs/thtiobj.nim
index 7a656905f..6db24dad0 100644
--- a/tests/ccgbugs/thtiobj.nim
+++ b/tests/ccgbugs/thtiobj.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   targets: "c cpp"
 """
 
diff --git a/tests/ccgbugs/trecursive_closure.nim b/tests/ccgbugs/tissues.nim
index 4b6514b90..a0c402cc0 100644
--- a/tests/ccgbugs/trecursive_closure.nim
+++ b/tests/ccgbugs/tissues.nim
@@ -16,3 +16,23 @@ f(nil)
 type A = object #of RootObj <-- Uncomment this to get no errors
   test: proc(i: A): bool
 var a: proc(i: A): bool # Or comment this line to get no errors
+
+
+# bug #2703
+type
+  fooObj[T] = object of RootObj
+  bazObj[T] = object of fooObj[T]
+    x: T
+
+var troz: fooObj[string]
+echo bazObj[string](troz).x
+
+
+# bug #14880
+type step = object
+  exec: proc ()
+
+const pipeline = @[step()]
+
+let crash = pipeline[0]
+
diff --git a/tests/ccgbugs/tlvalueconv.nim b/tests/ccgbugs/tlvalueconv.nim
new file mode 100644
index 000000000..b2cb11eef
--- /dev/null
+++ b/tests/ccgbugs/tlvalueconv.nim
@@ -0,0 +1,32 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+# bug #14160
+
+type
+  TPassContext = object of RootObj
+  PPassContext = ref TPassContext
+
+  PCtx = ref object of TPassContext
+    a: int
+
+  ModuleGraph = object
+    vm: RootRef
+
+proc main() =
+  var g = ModuleGraph(vm: new(Pctx))
+  PCtx(g.vm) = nil #This generates invalid C code
+  doAssert g.vm == nil
+
+main()
+
+# bug #14325
+
+proc main2() =
+  var g = ModuleGraph(vm: new(Pctx))
+  PPassContext(PCtx(g.vm)) = nil #This compiles, but crashes at runtime with gc:arc
+  doAssert g.vm == nil
+
+main2()
+
diff --git a/tests/ccgbugs/tmangle.nim b/tests/ccgbugs/tmangle.nim
new file mode 100644
index 000000000..0050cef92
--- /dev/null
+++ b/tests/ccgbugs/tmangle.nim
@@ -0,0 +1,16 @@
+block:
+  proc hello() =
+    let NAN_INFINITY = 12
+    doAssert NAN_INFINITY == 12
+    let INF = "2.0"
+    doAssert INF == "2.0"
+    let NAN = 2.3
+    doAssert NAN == 2.3
+
+  hello()
+
+block:
+  proc hello(NAN: float) =
+    doAssert NAN == 2.0
+
+  hello(2.0)
diff --git a/tests/ccgbugs/tmissingbracket.nim b/tests/ccgbugs/tmissingbracket.nim
index 468e13366..2919efe0e 100644
--- a/tests/ccgbugs/tmissingbracket.nim
+++ b/tests/ccgbugs/tmissingbracket.nim
@@ -11,7 +11,7 @@ type
     className* : string
   TClassOfTobj = object of TClassOfTCustomObject
     nil
-  TCustomObject = ref object {.inheritable.}
+  TCustomObject {.inheritable.} = ref object
     class* : ptr TClassOfTCustomObject
   TObj = ref object of TCustomObject
     data: int
diff --git a/tests/ccgbugs/tmissingderef.nim b/tests/ccgbugs/tmissingderef.nim
index 26418800a..eb7da3023 100644
--- a/tests/ccgbugs/tmissingderef.nim
+++ b/tests/ccgbugs/tmissingderef.nim
@@ -1,6 +1,5 @@
 discard """
   output: '''[10, 0, 0, 0, 0, 0, 0, 0]
-
 255
 1 1
 0.5'''
diff --git a/tests/ccgbugs/tmissinginit.nim b/tests/ccgbugs/tmissinginit.nim
index 8806a2f21..9eb58221c 100644
--- a/tests/ccgbugs/tmissinginit.nim
+++ b/tests/ccgbugs/tmissinginit.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   output: '''0
 0
 0
diff --git a/tests/ccgbugs/tmissingvolatile.nim b/tests/ccgbugs/tmissingvolatile.nim
index 60b1771dc..b877eff71 100644
--- a/tests/ccgbugs/tmissingvolatile.nim
+++ b/tests/ccgbugs/tmissingvolatile.nim
@@ -1,8 +1,8 @@
 discard """
   output: "1"
-  cmd: r"nim c --hints:on $options -d:release $file"
+  cmd: r"nim c --hints:on $options --mm:refc -d:release $file"
   ccodecheck: "'NI volatile state;'"
-  target: "C"
+  targets: "c"
 """
 
 # bug #1539
diff --git a/tests/ccgbugs/tnoalias.nim b/tests/ccgbugs/tnoalias.nim
new file mode 100644
index 000000000..2c3c2f0f4
--- /dev/null
+++ b/tests/ccgbugs/tnoalias.nim
@@ -0,0 +1,13 @@
+discard """
+  ccodecheck: "\\i@'NI* NIM_NOALIAS field;' @'NIM_CHAR* NIM_NOALIAS x_p0,' @'void* NIM_NOALIAS q'"
+"""
+
+type
+  BigNum = object
+    field {.noalias.}: ptr UncheckedArray[int]
+
+proc p(x {.noalias.}: openArray[char]) =
+  var q {.noalias.}: pointer = addr(x[0])
+
+var bn: BigNum
+p "abc"
diff --git a/tests/ccgbugs/tprogmem.nim b/tests/ccgbugs/tprogmem.nim
index 884ca158a..58a20583a 100644
--- a/tests/ccgbugs/tprogmem.nim
+++ b/tests/ccgbugs/tprogmem.nim
@@ -2,7 +2,7 @@ discard """
   output: "5"
   cmd: r"nim c --hints:on $options -d:release $file"
   ccodecheck: "'/*PROGMEM*/ myLetVariable = {'"
-  target: "C"
+  targets: "c"
 """
 
 var myLetVariable {.exportc, codegenDecl: "$# /*PROGMEM*/ $#".} = [1, 2, 3]
diff --git a/tests/ccgbugs/tret_arg_init.nim b/tests/ccgbugs/tret_arg_init.nim
index 5cd67de3e..e39e5a0de 100644
--- a/tests/ccgbugs/tret_arg_init.nim
+++ b/tests/ccgbugs/tret_arg_init.nim
@@ -1,6 +1,8 @@
 discard """
   output: '''
 
+
+
 '''
 """
 
diff --git a/tests/ccgbugs/tsamename3.nim b/tests/ccgbugs/tsamename3.nim
new file mode 100644
index 000000000..ded18e9f8
--- /dev/null
+++ b/tests/ccgbugs/tsamename3.nim
@@ -0,0 +1,120 @@
+block: # bug #15526
+  block:
+    type Foo = ref object
+      x1: int
+    let f1 = Foo(x1: 1)
+  block:
+    type Foo = ref object
+      x2: int
+    let f2 = Foo(x2: 2)
+
+block: # ditto
+  template fn() =
+    block:
+      type Foo = ref object
+        x1: int
+      let f1 = Foo(x1: 1)
+      doAssert f1.x1 == 1
+    block:
+      type Foo = ref object
+        x2: int
+      let f2 = Foo(x2: 2)
+      doAssert f2.x2 == 2
+  static: fn()
+  fn()
+
+block: # bug #17162
+  template fn =
+    var ret: string
+    block:
+      type A = enum a0, a1, a2
+      for ai in A:
+        ret.add $ai
+    block:
+      type A = enum b0, b1, b2, b3
+      for ai in A:
+        ret.add $ai
+    doAssert ret == "a0a1a2b0b1b2b3"
+
+  static: fn() # ok
+  fn() # was bug
+
+block: # ditto
+  proc fn =
+    var ret: string
+    block:
+      type A = enum a0, a1, a2
+      for ai in A:
+        ret.add $ai
+    block:
+      type A = enum b0, b1, b2, b3
+      for ai in A:
+        ret.add $ai
+    doAssert ret == "a0a1a2b0b1b2b3"
+
+  static: fn() # ok
+  fn() # was bug
+
+block: # bug #5170
+  block:
+    type Foo = object
+      x1: int
+    let f1 = Foo(x1: 1)
+  block:
+    type Foo = object
+      x2: int
+    let f2 = Foo(x2: 2)
+
+block: # ditto
+  block:
+    type Foo = object
+      bar: bool
+    var f1: Foo
+
+  block:
+    type Foo = object
+      baz: int
+    var f2: Foo
+    doAssert f2.baz == 0
+
+  block:
+    template fn() =
+      block:
+        type Foo = object
+          x1: int
+        let f1 = Foo(x1: 1)
+        doAssert f1.x1 == 1
+      block:
+        type Foo = object
+          x2: int
+        let f2 = Foo(x2: 2)
+        doAssert f2.x2 == 2
+    static: fn()
+    fn()
+
+when true: # ditto, refs https://github.com/nim-lang/Nim/issues/5170#issuecomment-582712132
+  type Foo1 = object # at top level
+    bar: bool
+  var f1: Foo1
+
+  block:
+    type Foo1 = object
+      baz: int
+    var f2: Foo1
+    doAssert f2.baz == 0
+
+block: # make sure `hashType` doesn't recurse infinitely
+  type
+    PFoo = ref object
+      a, b: PFoo
+      c: int
+  var a: PFoo
+
+block: # issue #22571
+  macro foo(x: typed) =
+    result = x
+
+  block: # or `proc main =`
+    foo:
+      type Foo = object
+    doAssert $Foo() == "()"
diff --git a/tests/ccgbugs/tuple_canon.nim b/tests/ccgbugs/tuple_canon.nim
index aa9605d4b..fbb971861 100644
--- a/tests/ccgbugs/tuple_canon.nim
+++ b/tests/ccgbugs/tuple_canon.nim
@@ -68,7 +68,7 @@ template odd*(i: int) : untyped =
 
 proc vidx(hg: HexGrid; col, row: int; i: HexVtxIndex) : Index =
     #NOTE: this variation compiles
-    #var offset : type(evenSharingOffsets[i])
+    #var offset : typeof(evenSharingOffsets[i])
     #
     #if odd(col):
     #    offset = oddSharingOffsets[i]
diff --git a/tests/ccgbugs/twrong_setconstr.nim b/tests/ccgbugs/twrong_setconstr.nim
deleted file mode 100644
index 8be0b82b5..000000000
--- a/tests/ccgbugs/twrong_setconstr.nim
+++ /dev/null
@@ -1,146 +0,0 @@
-discard """
-  output: ""
-"""
-
-# bug #2880
-
-type
-  TMsgKind* = enum
-    errUnknown, errIllFormedAstX, errInternal, errCannotOpenFile, errGenerated,
-    errXCompilerDoesNotSupportCpp, errStringLiteralExpected,
-    errIntLiteralExpected, errInvalidCharacterConstant,
-    errClosingTripleQuoteExpected, errClosingQuoteExpected,
-    errTabulatorsAreNotAllowed, errInvalidToken, errLineTooLong,
-    errInvalidNumber, errInvalidNumberOctalCode, errNumberOutOfRange,
-    errNnotAllowedInCharacter, errClosingBracketExpected, errMissingFinalQuote,
-    errIdentifierExpected, errNewlineExpected, errInvalidModuleName,
-    errOperatorExpected, errTokenExpected, errStringAfterIncludeExpected,
-    errRecursiveDependencyX, errOnOrOffExpected, errNoneSpeedOrSizeExpected,
-    errInvalidPragma, errUnknownPragma, errInvalidDirectiveX,
-    errAtPopWithoutPush, errEmptyAsm, errInvalidIndentation,
-    errExceptionExpected, errExceptionAlreadyHandled,
-    errYieldNotAllowedHere, errYieldNotAllowedInTryStmt,
-    errInvalidNumberOfYieldExpr, errCannotReturnExpr, errAttemptToRedefine,
-    errStmtInvalidAfterReturn, errStmtExpected, errInvalidLabel,
-    errInvalidCmdLineOption, errCmdLineArgExpected, errCmdLineNoArgExpected,
-    errInvalidVarSubstitution, errUnknownVar, errUnknownCcompiler,
-    errOnOrOffExpectedButXFound, errOnOffOrListExpectedButXFound,
-    errNoneBoehmRefcExpectedButXFound,
-    errNoneSpeedOrSizeExpectedButXFound, errGuiConsoleOrLibExpectedButXFound,
-    errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound,
-    errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected,
-    errExprExpected, errUndeclaredIdentifier, errUseQualifier, errTypeExpected,
-    errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable,
-    errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue,
-    errXExpectsArrayType, errIteratorCannotBeInstantiated, errExprXAmbiguous,
-    errConstantDivisionByZero, errOrdinalTypeExpected,
-    errOrdinalOrFloatTypeExpected, errOverOrUnderflow,
-    errCannotEvalXBecauseIncompletelyDefined, errChrExpectsRange0_255,
-    errDynlibRequiresExportc, errUndeclaredFieldX, errNilAccess,
-    errIndexOutOfBounds, errIndexTypesDoNotMatch, errBracketsInvalidForType,
-    errValueOutOfSetBounds, errFieldInitTwice, errFieldNotInit,
-    errExprXCannotBeCalled, errExprHasNoType, errExprXHasNoType,
-    errCastNotInSafeMode, errExprCannotBeCastedToX, errCommaOrParRiExpected,
-    errCurlyLeOrParLeExpected, errSectionExpected, errRangeExpected,
-    errMagicOnlyInSystem, errPowerOfTwoExpected,
-    errStringMayNotBeEmpty, errCallConvExpected, errProcOnlyOneCallConv,
-    errSymbolMustBeImported, errExprMustBeBool, errConstExprExpected,
-    errDuplicateCaseLabel, errRangeIsEmpty, errSelectorMustBeOfCertainTypes,
-    errSelectorMustBeOrdinal, errOrdXMustNotBeNegative, errLenXinvalid,
-    errWrongNumberOfVariables, errExprCannotBeRaised, errBreakOnlyInLoop,
-    errTypeXhasUnknownSize, errConstNeedsConstExpr, errConstNeedsValue,
-    errResultCannotBeOpenArray, errSizeTooBig, errSetTooBig,
-    errBaseTypeMustBeOrdinal, errInheritanceOnlyWithNonFinalObjects,
-    errInheritanceOnlyWithEnums, errIllegalRecursionInTypeX,
-    errCannotInstantiateX, errExprHasNoAddress, errXStackEscape,
-    errVarForOutParamNeeded,
-    errPureTypeMismatch, errTypeMismatch, errButExpected, errButExpectedX,
-    errAmbiguousCallXYZ, errWrongNumberOfArguments,
-    errXCannotBePassedToProcVar,
-    errXCannotBeInParamDecl, errPragmaOnlyInHeaderOfProc, errImplOfXNotAllowed,
-    errImplOfXexpected, errNoSymbolToBorrowFromFound, errDiscardValueX,
-    errInvalidDiscard, errIllegalConvFromXtoY, errCannotBindXTwice,
-    errInvalidOrderInArrayConstructor,
-    errInvalidOrderInEnumX, errEnumXHasHoles, errExceptExpected, errInvalidTry,
-    errOptionExpected, errXisNoLabel, errNotAllCasesCovered,
-    errUnknownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable,
-    errNoPragmasAllowedForX, errNoGenericParamsAllowedForX,
-    errInvalidParamKindX, errDefaultArgumentInvalid, errNamedParamHasToBeIdent,
-    errNoReturnTypeForX, errConvNeedsOneArg, errInvalidPragmaX,
-    errXNotAllowedHere, errInvalidControlFlowX,
-    errXisNoType, errCircumNeedsPointer, errInvalidExpression,
-    errInvalidExpressionX, errEnumHasNoValueX, errNamedExprExpected,
-    errNamedExprNotAllowed, errXExpectsOneTypeParam,
-    errArrayExpectsTwoTypeParams, errInvalidVisibilityX, errInitHereNotAllowed,
-    errXCannotBeAssignedTo, errIteratorNotAllowed, errXNeedsReturnType,
-    errNoReturnTypeDeclared,
-    errInvalidCommandX, errXOnlyAtModuleScope,
-    errXNeedsParamObjectType,
-    errTemplateInstantiationTooNested, errInstantiationFrom,
-    errInvalidIndexValueForTuple, errCommandExpectsFilename,
-    errMainModuleMustBeSpecified,
-    errXExpected,
-    errTIsNotAConcreteType,
-    errInvalidSectionStart, errGridTableNotImplemented, errGeneralParseError,
-    errNewSectionExpected, errWhitespaceExpected, errXisNoValidIndexFile,
-    errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitly,
-    errOnlyACallOpCanBeDelegator, errUsingNoSymbol,
-    errMacroBodyDependsOnGenericTypes,
-    errDestructorNotGenericEnough,
-    errInlineIteratorsAsProcParams,
-    errXExpectsTwoArguments,
-    errXExpectsObjectTypes, errXcanNeverBeOfThisSubtype, errTooManyIterations,
-    errCannotInterpretNodeX, errFieldXNotFound, errInvalidConversionFromTypeX,
-    errAssertionFailed, errCannotGenerateCodeForX, errXRequiresOneArgument,
-    errUnhandledExceptionX, errCyclicTree, errXisNoMacroOrTemplate,
-    errXhasSideEffects, errIteratorExpected, errLetNeedsInit,
-    errThreadvarCannotInit, errWrongSymbolX, errIllegalCaptureX,
-    errXCannotBeClosure, errXMustBeCompileTime,
-    errCannotInferTypeOfTheLiteral,
-    errCannotInferReturnType,
-    errGenericLambdaNotAllowed,
-    errCompilerDoesntSupportTarget,
-    errUser,
-    warnCannotOpenFile,
-    warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit,
-    warnDeprecated, warnConfigDeprecated,
-    warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel,
-    warnUnknownSubstitutionX, warnLanguageXNotSupported,
-    warnFieldXNotSupported, warnCommentXIgnored,
-    warnNilStatement, warnTypelessParam,
-    warnDifferentHeaps, warnWriteToForeignHeap, warnUnsafeCode,
-    warnEachIdentIsTuple
-    warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2,
-    warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed,
-    warnUser,
-    hintSuccess, hintSuccessX,
-    hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded,
-    hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled,
-    hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath,
-    hintConditionAlwaysTrue, hintName, hintPattern,
-    hintExecuting, hintLinking, hintDependency,
-    hintSource, hintStackTrace, hintGCStats,
-    hintUser
-
-const
-  warnMin = warnCannotOpenFile
-  hintMax = high(TMsgKind)
-
-type
-  TNoteKind = range[warnMin..hintMax] # "notes" are warnings or hints
-  TNoteKinds = set[TNoteKind]
-
-const
-  NotesVerbosityConst: array[0..0, TNoteKinds] = [
-    {low(TNoteKind)..high(TNoteKind)} - {hintGCStats}]
-  fuckyou = NotesVerbosityConst[0]
-
-var
-  gNotesFromConst: TNoteKinds = NotesVerbosityConst[0]
-  gNotesFromConst2: TNoteKinds = fuckyou
-
-if hintGCStats in gNotesFromConst:
-  echo "hintGCStats in gNotesFromConst A"
-
-if hintGCStats in gNotesFromConst2:
-  echo "hintGCStats in gNotesFromConst B"
diff --git a/tests/ccgbugs/twrong_tupleconv.nim b/tests/ccgbugs/twrong_tupleconv.nim
index 7b1e58083..031712dac 100644
--- a/tests/ccgbugs/twrong_tupleconv.nim
+++ b/tests/ccgbugs/twrong_tupleconv.nim
@@ -1,3 +1,8 @@
+discard """
+  targets: "c cpp"
+  matrix: "--gc:refc; --gc:arc"
+"""
+
 # bug #1833
 iterator myitems*[T](a: var seq[T]): var T {.inline.} =
   ## iterates over each item of `a` so that you can modify the yielded value.
@@ -6,7 +11,7 @@ iterator myitems*[T](a: var seq[T]): var T {.inline.} =
   while i < L:
     yield a[i]
     inc(i)
-    assert(len(a) == L, "the length of the seq changed while iterating over it")
+    doAssert(len(a) == L, "the length of the seq changed while iterating over it")
 
 # Works fine
 var xs = @[1,2,3]
@@ -18,3 +23,13 @@ var ys = @[(1,"a"),(2,"b"),(3,"c")]
 for y in myitems(ys):
   inc y[0]
 
+# bug #16331
+type T1 = tuple[a, b: int]
+
+proc p(b: bool): string =
+  var x: T1 = (10, 20)
+  x = if b: (x.b, x.a) else: (-x.b, -x.a)
+  $x
+
+assert p(false) == "(a: -20, b: -10)"
+assert p(true) == "(a: 20, b: 10)"
diff --git a/tests/ccgbugs2/tcodegen.nim b/tests/ccgbugs2/tcodegen.nim
new file mode 100644
index 000000000..aac1ecaf3
--- /dev/null
+++ b/tests/ccgbugs2/tcodegen.nim
@@ -0,0 +1,47 @@
+discard """

+  targets: "c cpp"

+"""

+

+# bug #19094

+type

+  X = object

+    filler: array[2048, int]

+    innerAddress: uint

+

+proc initX(): X =

+  result.innerAddress = cast[uint](result.addr)

+

+proc initXInPlace(x: var X) =

+  x.innerAddress = cast[uint](x.addr)

+

+block: # NRVO1

+  var x = initX()

+  let innerAddress = x.innerAddress

+  let outerAddress = cast[uint](x.addr)

+  doAssert(innerAddress == outerAddress) # [OK]

+

+block: # NRVO2

+  var x: X

+  initXInPlace(x)

+  let innerAddress = x.innerAddress

+  let outerAddress = cast[uint](x.addr)

+  doAssert(innerAddress == outerAddress) # [OK]

+

+block: # bug #22354

+  type Object = object

+    foo: int

+

+  proc takeFoo(self: var Object): int =

+    result = self.foo

+    self.foo = 999

+

+  proc doSomething(self: var Object; foo: int = self.takeFoo()) =

+    discard

+

+  proc main() =

+    var obj = Object(foo: 2)

+    obj.doSomething()

+    doAssert obj.foo == 999

+

+

+  main()

diff --git a/tests/ccgbugs/tinefficient_const_table.nim b/tests/ccgbugs2/tinefficient_const_table.nim
index 7422d0676..8ab895cb0 100644
--- a/tests/ccgbugs/tinefficient_const_table.nim
+++ b/tests/ccgbugs2/tinefficient_const_table.nim
@@ -6,7 +6,7 @@ of
 words'''
   cmd: r"nim c --hints:on $options -d:release $file"
   ccodecheck: "! @'genericSeqAssign'"
-  target: "c"
+  targets: "c"
 """
 
 # bug #4354
@@ -15,7 +15,7 @@ import sets
 import strutils
 
 #const FRUITS = ["banana", "apple", "grapes"]
-#let FRUITS = ["banana", "apple", "grapes"].toSet
+#let FRUITS = ["banana", "apple", "grapes"].toHashSet
 const FRUITS = {"banana":0, "apple":0, "grapes":0}.toTable
 
 proc main() =
diff --git a/tests/closure/t11042.nim b/tests/closure/t11042.nim
new file mode 100644
index 000000000..6a3928316
--- /dev/null
+++ b/tests/closure/t11042.nim
@@ -0,0 +1,55 @@
+discard """
+  output:'''
+foo: 1
+foo: 2
+bar: 1
+bar: 2
+foo: 1
+foo: 2
+bar: 1
+bar: 2
+bar: 3
+bar: 4
+bar: 5
+bar: 6
+bar: 7
+bar: 8
+bar: 9
+'''
+"""
+
+# bug #11042
+block:
+  iterator foo: int =
+    for x in 1..2:
+      echo "foo: ", x
+      for y in 1..2:
+        discard
+
+  for x in foo(): discard
+
+  let bar = iterator: int =
+    for x in 1..2:
+      echo "bar: ", x
+      for y in 1..2:
+        discard
+
+  for x in bar(): discard
+
+
+block:
+  iterator foo: int =
+    for x in 1..2:
+      echo "foo: ", x
+      for y in 1..2:
+        discard
+
+  for x in foo(): discard
+
+  let bar = iterator: int =
+    for x in 1..9:
+      echo "bar: ", x
+      for y in 1..2:
+        discard
+
+  for x in bar(): discard
\ No newline at end of file
diff --git a/tests/closure/t15594.nim b/tests/closure/t15594.nim
new file mode 100644
index 000000000..aacd9ed84
--- /dev/null
+++ b/tests/closure/t15594.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "The variable name cannot be `result`!"
+"""
+
+import sugar
+
+proc begin(): int =
+  capture result:
+    echo 1+1
+  result
diff --git a/tests/closure/t19095.nim b/tests/closure/t19095.nim
new file mode 100644
index 000000000..880456e02
--- /dev/null
+++ b/tests/closure/t19095.nim
@@ -0,0 +1,35 @@
+discard """
+  action: compile
+"""
+
+block:
+  func inCheck() =
+    discard
+
+  iterator iter(): int =
+    yield 0
+    yield 0
+
+  func search() =
+    let inCheck = 0
+
+    for i in iter():
+
+      proc hello() =
+        inCheck()
+
+  search()
+block:
+  iterator iter(): int =
+    yield 0
+    yield 0
+
+  func search() =
+    let lmrMoveCounter = 0
+
+    for i in iter():
+
+      proc hello() =
+        discard lmrMoveCounter
+
+  search()
diff --git a/tests/closure/t20152.nim b/tests/closure/t20152.nim
new file mode 100644
index 000000000..484ea0741
--- /dev/null
+++ b/tests/closure/t20152.nim
@@ -0,0 +1,20 @@
+discard """

+  action: compile

+"""

+

+proc foo() =

+  iterator it():int {.closure.} =

+    yield 1

+  proc useIter() {.nimcall.} =

+    var iii = it # <-- illegal capture

+    doAssert iii() == 1

+  useIter()

+foo()

+

+proc foo2() =

+  proc bar() = # Local function, but not a closure, because no captures

+    echo "hi"

+  proc baz() {.nimcall.} = # Calls local function

+    bar()

+  baz()

+foo2()

diff --git a/tests/closure/t8550.nim b/tests/closure/t8550.nim
index 153246f08..a07f45cdc 100644
--- a/tests/closure/t8550.nim
+++ b/tests/closure/t8550.nim
@@ -1,4 +1,5 @@
 discard """
+  targets: "c js"
   output: "@[\"42\"]"
 """
 
diff --git a/tests/closure/t9334.nim b/tests/closure/t9334.nim
new file mode 100644
index 000000000..36a9a7d77
--- /dev/null
+++ b/tests/closure/t9334.nim
@@ -0,0 +1,19 @@
+discard """
+  cmd: "nim $target --hints:off $options -r $file"
+  nimout: '''@[1]
+@[1, 1]
+'''
+  nimoutFull: true
+"""
+proc p(s: var seq[int]): auto =
+  let sptr = addr s
+  return proc() = sptr[].add 1
+
+proc f =
+  var data = @[1]
+  p(data)()
+  echo repr data
+
+static:
+  f() # prints [1]
+f() # prints [1, 1]
diff --git a/tests/closure/tcapture.nim b/tests/closure/tcapture.nim
index 304a76285..dafc44739 100644
--- a/tests/closure/tcapture.nim
+++ b/tests/closure/tcapture.nim
@@ -1,6 +1,11 @@
 discard """
   output: '''
-to be, or not to be'''
+to be, or not to be
+(v: 1)
+(w: -1)
+(v: 1)
+(w: -1)
+'''
   joinable: false
 """
 
@@ -9,4 +14,21 @@ import sequtils, sugar
 let m = @[proc (s: string): string = "to " & s, proc (s: string): string = "not to " & s]
 var l = m.mapIt(capture([it], proc (s: string): string = it(s)))
 let r = l.mapIt(it("be"))
-echo r[0] & ", or " & r[1]
\ No newline at end of file
+echo r[0] & ", or " & r[1]
+
+type
+  O = object
+    v: int
+  U = object
+    w: int
+var o = O(v: 1)
+var u = U(w: -1)
+var execute: proc()
+capture o, u:
+  execute = proc() =
+    echo o
+    echo u
+execute()
+o.v = -1
+u.w = 1
+execute()
diff --git a/tests/closure/tclosure.nim b/tests/closure/tclosure.nim
index cfef4193a..401a71d40 100644
--- a/tests/closure/tclosure.nim
+++ b/tests/closure/tclosure.nim
@@ -1,5 +1,5 @@
 discard """
-  target: "c"
+  targets: "c"
   output: '''
 1 3 6 11 20 foo
 foo88
@@ -38,14 +38,10 @@ joinable: false
 
 
 block tclosure:
-  proc map(n: var openarray[int], fn: proc (x: int): int {.closure}) =
+  proc map(n: var openArray[int], fn: proc (x: int): int {.closure}) =
     for i in 0..n.len-1: n[i] = fn(n[i])
 
-  proc foldr(n: openarray[int], fn: proc (x, y: int): int {.closure}): int =
-    for i in 0..n.len-1:
-      result = fn(result, n[i])
-
-  proc each(n: openarray[int], fn: proc(x: int) {.closure.}) =
+  proc each(n: openArray[int], fn: proc(x: int) {.closure.}) =
     for i in 0..n.len-1:
       fn(n[i])
 
@@ -67,21 +63,9 @@ block tclosure:
 
   #OUT 2 4 6 8 10
 
-  type
-    ITest = tuple[
-      setter: proc(v: int),
-      getter: proc(): int]
-
-  proc getInterf(): ITest =
-    var shared: int
-
-    return (setter: proc (x: int) = shared = x,
-            getter: proc (): int = return shared)
-
-
   # bug #5015
 
-  type Mutator = proc(matched: string): string {.noSideEffect, gcsafe, locks: 0.}
+  type Mutator = proc(matched: string): string {.noSideEffect, gcsafe.}
 
   proc putMutated(
       MutatorCount: static[int],
@@ -180,7 +164,7 @@ block tclosure0:
 block tclosure3:
   proc main =
     const n = 30
-    for iterations in 0..50_000:
+    for iterations in 0..10_000:
       var s: seq[proc(): string {.closure.}] = @[]
       for i in 0 .. n-1:
         (proc () =
@@ -203,210 +187,12 @@ block tclosure4:
     let json_elems = json_params["files"].elems
     # These fail compilation.
     var files = map(json_elems, proc (x: JsonNode): string = x.str)
-    #var files = json_elems.map do (x: JsonNode) -> string: x.str
 
   let text = """{"files": ["a", "b", "c"]}"""
   run((text.parseJson).fields)
 
 
 
-import hashes, math
-block tclosurebug2:
-  type
-    TSlotEnum = enum seEmpty, seFilled, seDeleted
-    TKeyValuePair[A, B] = tuple[slot: TSlotEnum, key: A, val: B]
-    TKeyValuePairSeq[A, B] = seq[TKeyValuePair[A, B]]
-
-    TOrderedKeyValuePair[A, B] = tuple[
-      slot: TSlotEnum, next: int, key: A, val: B]
-    TOrderedKeyValuePairSeq[A, B] = seq[TOrderedKeyValuePair[A, B]]
-    OrderedTable[A, B] = object ## table that remembers insertion order
-      data: TOrderedKeyValuePairSeq[A, B]
-      counter, first, last: int
-
-  const
-    growthFactor = 2
-
-  proc mustRehash(length, counter: int): bool {.inline.} =
-    assert(length > counter)
-    result = (length * 2 < counter * 3) or (length - counter < 4)
-
-  proc nextTry(h, maxHash: Hash): Hash {.inline.} =
-    result = ((5 * h) + 1) and maxHash
-
-  template rawGetImpl() {.dirty.} =
-    var h: Hash = hash(key) and high(t.data) # start with real hash value
-    while t.data[h].slot != seEmpty:
-      if t.data[h].key == key and t.data[h].slot == seFilled:
-        return h
-      h = nextTry(h, high(t.data))
-    result = -1
-
-  template rawInsertImpl() {.dirty.} =
-    var h: Hash = hash(key) and high(data)
-    while data[h].slot == seFilled:
-      h = nextTry(h, high(data))
-    data[h].key = key
-    data[h].val = val
-    data[h].slot = seFilled
-
-  template addImpl() {.dirty.} =
-    if mustRehash(len(t.data), t.counter): enlarge(t)
-    rawInsert(t, t.data, key, val)
-    inc(t.counter)
-
-  template putImpl() {.dirty.} =
-    var index = rawGet(t, key)
-    if index >= 0:
-      t.data[index].val = val
-    else:
-      addImpl()
-
-  proc len[A, B](t: OrderedTable[A, B]): int {.inline.} =
-    ## returns the number of keys in `t`.
-    result = t.counter
-
-  template forAllOrderedPairs(yieldStmt: untyped) {.dirty.} =
-    var h = t.first
-    while h >= 0:
-      var nxt = t.data[h].next
-      if t.data[h].slot == seFilled: yieldStmt
-      h = nxt
-
-  iterator pairs[A, B](t: OrderedTable[A, B]): tuple[key: A, val: B] =
-    ## iterates over any (key, value) pair in the table `t` in insertion
-    ## order.
-    forAllOrderedPairs:
-      yield (t.data[h].key, t.data[h].val)
-
-  iterator mpairs[A, B](t: var OrderedTable[A, B]): tuple[key: A, val: var B] =
-    ## iterates over any (key, value) pair in the table `t` in insertion
-    ## order. The values can be modified.
-    forAllOrderedPairs:
-      yield (t.data[h].key, t.data[h].val)
-
-  iterator keys[A, B](t: OrderedTable[A, B]): A =
-    ## iterates over any key in the table `t` in insertion order.
-    forAllOrderedPairs:
-      yield t.data[h].key
-
-  iterator values[A, B](t: OrderedTable[A, B]): B =
-    ## iterates over any value in the table `t` in insertion order.
-    forAllOrderedPairs:
-      yield t.data[h].val
-
-  iterator mvalues[A, B](t: var OrderedTable[A, B]): var B =
-    ## iterates over any value in the table `t` in insertion order. The values
-    ## can be modified.
-    forAllOrderedPairs:
-      yield t.data[h].val
-
-  proc rawGet[A, B](t: OrderedTable[A, B], key: A): int =
-    rawGetImpl()
-
-  proc `[]`[A, B](t: OrderedTable[A, B], key: A): B =
-    ## retrieves the value at ``t[key]``. If `key` is not in `t`,
-    ## default empty value for the type `B` is returned
-    ## and no exception is raised. One can check with ``hasKey`` whether the key
-    ## exists.
-    var index = rawGet(t, key)
-    if index >= 0: result = t.data[index].val
-
-  proc mget[A, B](t: var OrderedTable[A, B], key: A): var B =
-    ## retrieves the value at ``t[key]``. The value can be modified.
-    ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised.
-    var index = rawGet(t, key)
-    if index >= 0: result = t.data[index].val
-    else: raise newException(KeyError, "key not found: " & $key)
-
-  proc hasKey[A, B](t: OrderedTable[A, B], key: A): bool =
-    ## returns true iff `key` is in the table `t`.
-    result = rawGet(t, key) >= 0
-
-  proc rawInsert[A, B](t: var OrderedTable[A, B],
-                      data: var TOrderedKeyValuePairSeq[A, B],
-                      key: A, val: B) =
-    rawInsertImpl()
-    data[h].next = -1
-    if t.first < 0: t.first = h
-    if t.last >= 0: data[t.last].next = h
-    t.last = h
-
-  proc enlarge[A, B](t: var OrderedTable[A, B]) =
-    var n: TOrderedKeyValuePairSeq[A, B]
-    newSeq(n, len(t.data) * growthFactor)
-    var h = t.first
-    t.first = -1
-    t.last = -1
-    while h >= 0:
-      var nxt = t.data[h].next
-      if t.data[h].slot == seFilled:
-        rawInsert(t, n, t.data[h].key, t.data[h].val)
-      h = nxt
-    swap(t.data, n)
-
-  proc `[]=`[A, B](t: var OrderedTable[A, B], key: A, val: B) =
-    ## puts a (key, value)-pair into `t`.
-    putImpl()
-
-  proc add[A, B](t: var OrderedTable[A, B], key: A, val: B) =
-    ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists.
-    addImpl()
-
-  proc iniOrderedTable[A, B](initialSize=64): OrderedTable[A, B] =
-    ## creates a new ordered hash table that is empty. `initialSize` needs to be
-    ## a power of two.
-    assert isPowerOfTwo(initialSize)
-    result.counter = 0
-    result.first = -1
-    result.last = -1
-    newSeq(result.data, initialSize)
-
-  proc toOrderedTable[A, B](pairs: openarray[tuple[key: A,
-                            val: B]]): OrderedTable[A, B] =
-    ## creates a new ordered hash table that contains the given `pairs`.
-    result = iniOrderedTable[A, B](nextPowerOfTwo(pairs.len+10))
-    for key, val in items(pairs): result[key] = val
-
-  proc sort[A, B](t: var OrderedTable[A,B],
-                  cmp: proc (x, y: tuple[key: A, val: B]): int {.closure.}) =
-    ## sorts the ordered table so that the entry with the highest counter comes
-    ## first. This is destructive (with the advantage of being efficient)!
-    ## You must not modify `t` afterwards!
-    ## You can use the iterators `pairs`,  `keys`, and `values` to iterate over
-    ## `t` in the sorted order.
-
-    # we use shellsort here; fast enough and simple
-    var h = 1
-    while true:
-      h = 3 * h + 1
-      if h >= high(t.data): break
-    while true:
-      h = h div 3
-      for i in countup(h, high(t.data)):
-        var j = i
-        #echo(t.data.len, " ", j, " - ", h)
-        #echo(repr(t.data[j-h]))
-        proc rawCmp(x, y: TOrderedKeyValuePair[A, B]): int =
-          if x.slot in {seEmpty, seDeleted} and y.slot in {seEmpty, seDeleted}:
-            return 0
-          elif x.slot in {seEmpty, seDeleted}:
-            return -1
-          elif y.slot in {seEmpty, seDeleted}:
-            return 1
-          else:
-            let item1 = (x.key, x.val)
-            let item2 = (y.key, y.val)
-            return cmp(item1, item2)
-
-        while rawCmp(t.data[j-h], t.data[j]) <= 0:
-          swap(t.data[j], t.data[j-h])
-          j = j-h
-          if j < h: break
-      if h == 1: break
-
-
-
 import sugar
 block inference3304:
   type
@@ -453,19 +239,19 @@ block doNotation:
   b.onClick do (e: Event):
     echo "click at ", e.x, ",", e.y
 
-  b.onFocusLost:
+  b.onFocusLost do ():
     echo "lost focus 1"
 
-  b.onFocusLost do:
+  b.onFocusLost do ():
     echo "lost focus 2"
 
-  b.onUserEvent("UserEvent 1") do:
+  b.onUserEvent("UserEvent 1") do ():
     discard
 
-  b.onUserEvent "UserEvent 2":
+  onUserEvent(b, "UserEvent 2") do ():
     discard
 
-  b.onUserEvent("UserEvent 3"):
+  b.onUserEvent("UserEvent 3") do ():
     discard
 
   b.onUserEvent("UserEvent 4", () => echo "event 4")
@@ -513,7 +299,7 @@ block tflatmap:
     let g: A -> Rand[B] = (a: A) => ((rng: RNG) => (f(a), rng))
     flatMap(s, g)
 
-  let f = nextInt.map(i => i - i mod 2)
+  discard nextInt.map(i => i - i mod 2)
 
 
 
@@ -705,3 +491,14 @@ block tnoclosure:
       row = zip(row & @[0], @[0] & row).mapIt(it[0] + it[1])
     echo row
   pascal(10)
+
+block: # bug #22297
+  iterator f: int {.closure.} =
+    try:
+      yield 12
+    finally:
+      return 14
+
+  let s = f
+  doAssert s() == 12
+  doAssert s() == 14
diff --git a/tests/closure/tclosure_issues.nim b/tests/closure/tclosure_issues.nim
index 4688834de..b1a2d7c6b 100644
--- a/tests/closure/tclosure_issues.nim
+++ b/tests/closure/tclosure_issues.nim
@@ -71,12 +71,12 @@ block tissue7104:
   proc sp(cb: proc())=
       cb()
 
-  sp:
+  sp do ():
       var i = 0
       echo "ok ", i
-      sp():
+      sp do ():
           inc i
           echo "ok ", i
-          sp do:
+          sp do ():
               inc i
               echo "ok ", i
diff --git a/tests/closure/tinvalidclosure.nim b/tests/closure/tinvalidclosure.nim
index b2d8bd28d..37d0f68a2 100644
--- a/tests/closure/tinvalidclosure.nim
+++ b/tests/closure/tinvalidclosure.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "type mismatch: got <proc (x: int){.gcsafe, locks: 0.}>"
+  errormsg: "type mismatch: got <proc (x: int){.nimcall, gcsafe.}>"
   line: 12
 """
 
diff --git a/tests/closure/tinvalidclosure4.nim b/tests/closure/tinvalidclosure4.nim
new file mode 100644
index 000000000..7985a2488
--- /dev/null
+++ b/tests/closure/tinvalidclosure4.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "illegal capture 'v'"
+  line: 7
+"""
+
+proc outer(v: int) =
+  proc b {.nimcall.} = echo v
+  b()
+outer(5)
diff --git a/tests/closure/tinvalidclosure5.nim b/tests/closure/tinvalidclosure5.nim
new file mode 100644
index 000000000..3b5f46a40
--- /dev/null
+++ b/tests/closure/tinvalidclosure5.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "type mismatch: got <proc (){.closure, gcsafe.}> but expected 'A = proc (){.nimcall.}'"
+  line: 9
+"""
+
+type A = proc() {.nimcall.}
+proc main =
+  let b = 1
+  let a: A = proc() = echo b
+
diff --git a/tests/closure/tnested.nim b/tests/closure/tnested.nim
index dbbe9ba58..ec5af9b13 100644
--- a/tests/closure/tnested.nim
+++ b/tests/closure/tnested.nim
@@ -1,4 +1,5 @@
 discard """
+targets: "c js"
 output: '''
 foo88
 23 24foo 88
@@ -33,6 +34,7 @@ py
 py
 px
 6
+proc (){.closure, noSideEffect, gcsafe.}
 '''
 """
 
@@ -177,3 +179,37 @@ block tclosure2:
 
 
     outer2()
+
+# bug #5688
+
+import typetraits
+
+block:
+  proc myDiscard[T](a: T) = discard
+
+  proc foo() =
+    let a = 5
+    let f = (proc() =
+              myDiscard (proc() = echo a)
+            )
+    echo name(typeof(f))
+
+  foo()
+
+
+block:
+  iterator foo: int {.closure.} =
+    yield 1
+    yield 2
+    yield 3
+
+  proc pork =
+    let call = foo
+    for i in call():
+      discard i
+
+    let call2 = foo
+    while not finished(call2):
+      discard call2()
+
+  pork()
diff --git a/tests/closure/tstmtlist.nim b/tests/closure/tstmtlist.nim
new file mode 100644
index 000000000..6a1390617
--- /dev/null
+++ b/tests/closure/tstmtlist.nim
@@ -0,0 +1,9 @@
+discard """
+  action: compile
+"""
+
+proc foo(x: proc()) = x()
+foo: echo "a" #[tt.Warning
+     ^ statement list expression assumed to be anonymous proc; this is deprecated, use `do (): ...` or `proc () = ...` instead [StmtListLambda]]#
+foo do: echo "b" #[tt.Warning
+        ^ statement list expression assumed to be anonymous proc; this is deprecated, use `do (): ...` or `proc () = ...` instead [StmtListLambda]]#
diff --git a/tests/closure/ttimeinfo.nim b/tests/closure/ttimeinfo.nim
index 7416c0d31..24d535cbf 100644
--- a/tests/closure/ttimeinfo.nim
+++ b/tests/closure/ttimeinfo.nim
@@ -1,7 +1,7 @@
 discard """
 output: '''
-@[2000-01-01T00:00:00+00:00, 2001-01-01T00:00:00+00:00, 2002-01-01T00:00:00+00:00, 2003-01-01T00:00:00+00:00, 2004-01-01T00:00:00+00:00, 2005-01-01T00:00:00+00:00, 2006-01-01T00:00:00+00:00, 2007-01-01T00:00:00+00:00, 2008-01-01T00:00:00+00:00, 2009-01-01T00:00:00+00:00, 2010-01-01T00:00:00+00:00, 2011-01-01T00:00:00+00:00, 2012-01-01T00:00:00+00:00, 2013-01-01T00:00:00+00:00, 2014-01-01T00:00:00+00:00, 2015-01-01T00:00:00+00:00]
-@[2000-01-01T00:00:00+00:00, 2001-01-01T00:00:00+00:00, 2002-01-01T00:00:00+00:00, 2003-01-01T00:00:00+00:00, 2004-01-01T00:00:00+00:00, 2005-01-01T00:00:00+00:00, 2006-01-01T00:00:00+00:00, 2007-01-01T00:00:00+00:00, 2008-01-01T00:00:00+00:00, 2009-01-01T00:00:00+00:00, 2010-01-01T00:00:00+00:00, 2011-01-01T00:00:00+00:00, 2012-01-01T00:00:00+00:00, 2013-01-01T00:00:00+00:00, 2014-01-01T00:00:00+00:00, 2015-01-01T00:00:00+00:00]
+@[2000-01-01T00:00:00Z, 2001-01-01T00:00:00Z, 2002-01-01T00:00:00Z, 2003-01-01T00:00:00Z, 2004-01-01T00:00:00Z, 2005-01-01T00:00:00Z, 2006-01-01T00:00:00Z, 2007-01-01T00:00:00Z, 2008-01-01T00:00:00Z, 2009-01-01T00:00:00Z, 2010-01-01T00:00:00Z, 2011-01-01T00:00:00Z, 2012-01-01T00:00:00Z, 2013-01-01T00:00:00Z, 2014-01-01T00:00:00Z, 2015-01-01T00:00:00Z]
+@[2000-01-01T00:00:00Z, 2001-01-01T00:00:00Z, 2002-01-01T00:00:00Z, 2003-01-01T00:00:00Z, 2004-01-01T00:00:00Z, 2005-01-01T00:00:00Z, 2006-01-01T00:00:00Z, 2007-01-01T00:00:00Z, 2008-01-01T00:00:00Z, 2009-01-01T00:00:00Z, 2010-01-01T00:00:00Z, 2011-01-01T00:00:00Z, 2012-01-01T00:00:00Z, 2013-01-01T00:00:00Z, 2014-01-01T00:00:00Z, 2015-01-01T00:00:00Z]
 '''
 """
 
@@ -12,11 +12,11 @@ import times
 
 # 1
 proc f(n: int): DateTime =
-  DateTime(year: n, month: mJan, monthday: 1)
+  initDateTime(1, mJan, n, 0, 0, 0, utc())
 
 echo toSeq(2000 || 2015).map(f)
 
 # 2
 echo toSeq(2000 || 2015).map(proc (n: int): DateTime =
-  DateTime(year: n, month: mJan, monthday: 1)
+  initDateTime(1, mJan, n, 0, 0, 0, utc())
 )
diff --git a/tests/codegen/titaniummangle.nim b/tests/codegen/titaniummangle.nim
new file mode 100644
index 000000000..4b45e59ae
--- /dev/null
+++ b/tests/codegen/titaniummangle.nim
@@ -0,0 +1,193 @@
+discard """
+  targets: "c"
+  matrix: "--debugger:native"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE6stringN14titaniummangle3FooE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3int7varargsI6stringE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncEN14titaniummangle3BooE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE8typeDescIN14titaniummangle17EnumAnotherSampleEE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3ptrI14uncheckedArrayI3intEE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3setIN14titaniummangle10EnumSampleEE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE4procI6string6stringE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3intN10Comparable10ComparableE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3int3int'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncEN14titaniummangle10EnumSampleE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncEN14titaniummangle17EnumAnotherSampleE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3int3int'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncEN14titaniummangle10EnumSampleE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncEN14titaniummangle17EnumAnotherSampleE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE5tupleI3int3intE7cstring'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE5tupleI5float5floatE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3ptrI3intE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3ptrIN14titaniummangle3FooEE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3ptrI3ptrI3intEE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3refIN14titaniummangle3FooEE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3varIN14titaniummangle3FooEE5int325int323refIN14titaniummangle3FooEE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE3varI3intE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE9openArrayI6stringE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE5arrayI7range013intE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE9ContainerI3intE'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE10Container2I5int325int32E'"
+  ccodecheck: "'_ZN14titaniummangle8testFuncE9ContainerI10Container2I5int325int32EE'"
+"""
+
+#When debugging this notice that if one check fails, it can be due to any of the above.
+
+type
+  Comparable = concept x, y
+    (x < y) is bool
+
+  Foo = object
+    a: int32
+    b: int32
+
+  FooTuple = tuple
+    a: int
+    b: int
+
+  Container[T] = object
+    data: T
+      
+  Container2[T, T2] = object
+    data: T
+    data2: T2
+
+  Boo = distinct Foo
+
+  Coo = Foo
+
+  Doo = Boo | Foo 
+
+  TestProc = proc(a:string): string
+
+type EnumSample = enum
+  a, b, c
+
+type EnumAnotherSample = enum
+  a, b, c
+
+proc testFunc(a: set[EnumSample]) = 
+  echo $a
+
+proc testFunc(a: typedesc) = 
+  echo $a
+
+proc testFunc(a: ptr Foo) = 
+  echo repr a
+
+proc testFunc(s: string, a: Coo) = 
+  echo repr a
+
+proc testFunc(s: int, a: Comparable) = 
+  echo repr a
+
+proc testFunc(a: TestProc) = 
+  let b = ""
+  echo repr a("")
+
+proc testFunc(a: ref Foo) = 
+  echo repr a
+
+proc testFunc(b: Boo) = 
+  echo repr b
+
+proc testFunc(a: ptr UncheckedArray[int]) = 
+  echo repr a
+
+proc testFunc(a: ptr int) = 
+  echo repr a
+
+proc testFunc(a: ptr ptr int) = 
+  echo repr a
+
+proc testFunc(e: FooTuple, str: cstring) = 
+  echo e
+
+proc testFunc(e: (float, float)) = 
+  echo e
+
+proc testFunc(e: EnumSample) = 
+  echo e
+
+proc testFunc(e: var int) = 
+  echo e
+
+proc testFunc(e: var Foo, a, b: int32, refFoo: ref Foo) = 
+  echo e
+
+proc testFunc(xs: Container[int]) = 
+  let a = 2
+  echo xs
+
+proc testFunc(xs: Container2[int32, int32]) = 
+  let a = 2
+  echo xs
+
+proc testFunc(xs: Container[Container2[int32, int32]]) = 
+  let a = 2
+  echo xs
+
+proc testFunc(xs: seq[int]) = 
+  let a = 2
+  echo xs
+
+proc testFunc(xs: openArray[string]) = 
+  let a = 2
+  echo xs
+
+proc testFunc(xs: array[2, int]) = 
+  let a = 2
+  echo xs
+
+proc testFunc(e: EnumAnotherSample) = 
+  echo e
+
+proc testFunc(a, b: int) = 
+  echo "hola"
+  discard
+
+proc testFunc(a: int, xs: varargs[string]) = 
+  let a = 10
+  for x in xs:
+    echo x
+
+proc testFunc() = 
+  var a = 2
+  var aPtr = a.addr
+  var foo = Foo()
+  let refFoo : ref Foo = new(Foo)
+  let b = Foo().Boo()
+  let d: Doo = Foo()
+  testFunc("", Coo())
+  testFunc(1, )
+  testFunc(b)
+  testFunc(EnumAnotherSample)
+  var t = [1, 2]
+  let uArr = cast[ptr UncheckedArray[int]](t.addr)
+  testFunc(uArr)
+  testFunc({})
+  testFunc(proc(s:string): string = "test")
+  testFunc(20, a.int32)
+  testFunc(20, 2)
+  testFunc(EnumSample.c)
+  testFunc(EnumAnotherSample.c)
+  testFunc((2, 1), "adios")
+  testFunc((22.1, 1.2))
+  testFunc(a.addr)
+  testFunc(foo.addr)
+  testFunc(aPtr.addr)
+  testFunc(refFoo)
+  testFunc(foo, 2, 1, refFoo)
+  testFunc(a)
+  testFunc(@[2, 1, 2])
+  testFunc(@["hola"])
+  testFunc(2, "hola", "adios")
+  let arr: array[2, int] = [2, 1]
+  testFunc(arr)
+  testFunc(Container[int](data: 10))
+  let c2 = Container2[int32, int32](data: 10, data2: 20)
+  testFunc(c2)
+  testFunc(Container[Container2[int32, int32]](data: c2))
+  
+
+testFunc()
\ No newline at end of file
diff --git a/tests/actiontable/tactiontable.nim b/tests/collections/tactiontable.nim
index 3f15a70bd..3f15a70bd 100644
--- a/tests/actiontable/tactiontable.nim
+++ b/tests/collections/tactiontable.nim
diff --git a/tests/collections/tcollections.nim b/tests/collections/tcollections.nim
index 2f8cfece7..7677f7c1a 100644
--- a/tests/collections/tcollections.nim
+++ b/tests/collections/tcollections.nim
@@ -1,9 +1,10 @@
 discard """
-  output: ""
+  targets: "c js"
 """
 
-import deques, sequtils
+# see also: tdeques, tlists, tcritbits
 
+import sets, tables, sequtils
 
 block tapply:
   var x = @[1, 2, 3]
@@ -12,19 +13,6 @@ block tapply:
   x.applyIt(it+5000)
   doAssert x == @[5111, 5112, 5113]
 
-
-block tdeques:
-  proc index(self: Deque[int], idx: Natural): int =
-    self[idx]
-
-  proc main =
-    var testDeque = initDeque[int]()
-    testDeque.addFirst(1)
-    assert testDeque.index(0) == 1
-
-  main()
-
-
 block tmapit:
   var x = @[1, 2, 3]
   # This mapIt call will run with preallocation because ``len`` is available.
@@ -52,3 +40,66 @@ block tmapit:
   # since ``len`` is not available
   var r = st.mapIt($(it+10))
   doAssert r == @["10", "11", "12", "13", "14"]
+
+
+
+# Collections to string:
+
+# Tests for tuples
+doAssert $(1, 2, 3) == "(1, 2, 3)"
+doAssert $("1", "2", "3") == """("1", "2", "3")"""
+doAssert $('1', '2', '3') == """('1', '2', '3')"""
+
+# Tests for seqs
+doAssert $(@[1, 2, 3]) == "@[1, 2, 3]"
+doAssert $(@["1", "2", "3"]) == """@["1", "2", "3"]"""
+doAssert $(@['1', '2', '3']) == """@['1', '2', '3']"""
+
+# Tests for sets
+doAssert $(toHashSet([1])) == "{1}"
+doAssert $(toHashSet(["1"])) == """{"1"}"""
+doAssert $(toHashSet(['1'])) == """{'1'}"""
+doAssert $(toOrderedSet([1, 2, 3])) == "{1, 2, 3}"
+doAssert $(toOrderedSet(["1", "2", "3"])) == """{"1", "2", "3"}"""
+doAssert $(toOrderedSet(['1', '2', '3'])) == """{'1', '2', '3'}"""
+
+# see also: tcritbitsToString, tlistsToString
+
+# Tests for tables
+when defined(nimIntHash1):
+  doAssert $({1: "1", 2: "2"}.toTable) == """{1: "1", 2: "2"}"""
+else:
+  doAssert $({1: "1", 2: "2"}.toTable) == """{2: "2", 1: "1"}"""
+let tabStr = $({"1": 1, "2": 2}.toTable)
+doAssert (tabStr == """{"2": 2, "1": 1}""" or tabStr == """{"1": 1, "2": 2}""")
+
+# Test escaping behavior
+block:
+  var s = ""
+  s.addQuoted('\0')
+  s.addQuoted('\31')
+  s.addQuoted('\127')
+  doAssert s == "'\\x00''\\x1F''\\x7F'"
+block:
+  var s = ""
+  s.addQuoted('\\')
+  s.addQuoted('\'')
+  s.addQuoted('\"')
+  doAssert s == """'\\''\'''\"'"""
+block:
+  var s = ""
+  s.addQuoted("å")
+  s.addQuoted("ä")
+  s.addQuoted("ö")
+  s.addEscapedChar('\xFF')
+  doAssert s == """"å""ä""ö"\xFF"""
+
+# Test customized element representation
+type CustomString = object
+
+proc addQuoted(s: var string, x: CustomString) =
+  s.add("<CustomString>")
+
+block:
+  let s = @[CustomString()]
+  doAssert $s == "@[<CustomString>]"
diff --git a/tests/collections/tcollections_to_string.nim b/tests/collections/tcollections_to_string.nim
index 686b9916b..62ba87334 100644
--- a/tests/collections/tcollections_to_string.nim
+++ b/tests/collections/tcollections_to_string.nim
@@ -19,15 +19,18 @@ doAssert $(@["1", "2", "3"]) == """@["1", "2", "3"]"""
 doAssert $(@['1', '2', '3']) == """@['1', '2', '3']"""
 
 # Tests for sets
-doAssert $(toSet([1])) == "{1}"
-doAssert $(toSet(["1"])) == """{"1"}"""
-doAssert $(toSet(['1'])) == """{'1'}"""
+doAssert $(toHashSet([1])) == "{1}"
+doAssert $(toHashSet(["1"])) == """{"1"}"""
+doAssert $(toHashSet(['1'])) == """{'1'}"""
 doAssert $(toOrderedSet([1, 2, 3])) == "{1, 2, 3}"
 doAssert $(toOrderedSet(["1", "2", "3"])) == """{"1", "2", "3"}"""
 doAssert $(toOrderedSet(['1', '2', '3'])) == """{'1', '2', '3'}"""
 
 # Tests for tables
-doAssert $({1: "1", 2: "2"}.toTable) == """{1: "1", 2: "2"}"""
+when defined(nimIntHash1):
+  doAssert $({1: "1", 2: "2"}.toTable) == """{1: "1", 2: "2"}"""
+else:
+  doAssert $({1: "1", 2: "2"}.toTable) == """{2: "2", 1: "1"}"""
 doAssert $({"1": 1, "2": 2}.toTable) == """{"1": 1, "2": 2}"""
 
 # Tests for deques
diff --git a/tests/collections/thashsets.nim b/tests/collections/thashsets.nim
index cd4401511..359eaa51e 100644
--- a/tests/collections/thashsets.nim
+++ b/tests/collections/thashsets.nim
@@ -3,9 +3,9 @@ import sets, hashes, algorithm
 
 block setEquality:
   var
-    a = initSet[int]()
-    b = initSet[int]()
-    c = initSet[string]()
+    a = initHashSet[int]()
+    b = initHashSet[int]()
+    c = initHashSet[string]()
 
   for i in 0..5: a.incl(i)
   for i in 1..6: b.incl(i)
@@ -16,27 +16,27 @@ block setEquality:
 
 
 block setsContainingTuples:
-  var set = initSet[tuple[i: int, i64: int64, f: float]]()
+  var set = initHashSet[tuple[i: int, i64: int64, f: float]]()
   set.incl( (i: 123, i64: 123'i64, f: 3.14) )
   doAssert set.contains( (i: 123, i64: 123'i64, f: 3.14) )
   doAssert( not set.contains( (i: 456, i64: 789'i64, f: 2.78) ) )
 
 
 block setWithTuplesWithSeqs:
-  var s = initSet[tuple[s: seq[int]]]()
+  var s = initHashSet[tuple[s: seq[int]]]()
   s.incl( (s: @[1, 2, 3]) )
   doAssert s.contains( (s: @[1, 2, 3]) )
   doAssert( not s.contains((s: @[4, 5, 6])) )
 
 
 block setWithSequences:
-  var s = initSet[seq[int]]()
+  var s = initHashSet[seq[int]]()
   s.incl( @[1, 2, 3] )
   doAssert s.contains(@[1, 2, 3])
   doAssert( not s.contains(@[4, 5, 6]) )
 
 block setClearWorked:
-  var s = initSet[char]()
+  var s = initHashSet[char]()
 
   for c in "this is a test":
     s.incl(c)
@@ -79,9 +79,8 @@ block hashForHashedSet:
   let
     seq1 = "This is the test."
     seq2 = "the test is This."
-    s1 = seq1.toSet()
-    s2 = seq2.toSet()
-  var hashSeq: seq[Hash] = @[]
+    s1 = seq1.toHashSet()
+    s2 = seq2.toHashSet()
   doAssert s1 == s2
   doAssert hash(s1) == hash(s2)
 
@@ -120,3 +119,264 @@ block hashForOrderdSet:
   reversed = !$reversed
   doAssert hash(r) == reversed
   doAssert hash(s1) != reversed
+
+
+proc testModule() =
+  ## Internal micro test to validate docstrings and such.
+  block lenTest:
+    var values: HashSet[int]
+    doAssert values.len == 0
+    doAssert values.card == 0
+
+  block setIterator:
+    type pair = tuple[a, b: int]
+    var a, b = initHashSet[pair]()
+    a.incl((2, 3))
+    a.incl((3, 2))
+    a.incl((2, 3))
+    for x, y in a.items:
+      b.incl((x - 2, y + 1))
+    doAssert a.len == b.card
+    doAssert a.len == 2
+    #echo b
+
+  block setContains:
+    var values = initHashSet[int]()
+    doAssert(not values.contains(2))
+    values.incl(2)
+    doAssert values.contains(2)
+    values.excl(2)
+    doAssert(not values.contains(2))
+
+    values.incl(4)
+    var others = toHashSet([6, 7])
+    values.incl(others)
+    doAssert values.len == 3
+
+    values.init
+    doAssert values.containsOrIncl(2) == false
+    doAssert values.containsOrIncl(2) == true
+    var
+      a = toHashSet([1, 2])
+      b = toHashSet([1])
+    b.incl(2)
+    doAssert a == b
+
+  block exclusions:
+    var s = toHashSet([2, 3, 6, 7])
+    s.excl(2)
+    s.excl(2)
+    doAssert s.len == 3
+
+    var
+      numbers = toHashSet([1, 2, 3, 4, 5])
+      even = toHashSet([2, 4, 6, 8])
+    numbers.excl(even)
+    #echo numbers
+    # --> {1, 3, 5}
+
+  block toSeqAndString:
+    var a = toHashSet([2, 7, 5])
+    var b = initHashSet[int](a.len)
+    for x in [2, 7, 5]: b.incl(x)
+    doAssert($a == $b)
+    #echo a
+    #echo toHashSet(["no", "esc'aping", "is \" provided"])
+
+  #block orderedToSeqAndString:
+  #  echo toOrderedSet([2, 4, 5])
+  #  echo toOrderedSet(["no", "esc'aping", "is \" provided"])
+
+  block setOperations:
+    var
+      a = toHashSet(["a", "b"])
+      b = toHashSet(["b", "c"])
+      c = union(a, b)
+    doAssert c == toHashSet(["a", "b", "c"])
+    var d = intersection(a, b)
+    doAssert d == toHashSet(["b"])
+    var e = difference(a, b)
+    doAssert e == toHashSet(["a"])
+    var f = symmetricDifference(a, b)
+    doAssert f == toHashSet(["a", "c"])
+    doAssert d < a and d < b
+    doAssert((a < a) == false)
+    doAssert d <= a and d <= b
+    doAssert((a <= a))
+    # Alias test.
+    doAssert a + b == toHashSet(["a", "b", "c"])
+    doAssert a * b == toHashSet(["b"])
+    doAssert a - b == toHashSet(["a"])
+    doAssert a -+- b == toHashSet(["a", "c"])
+    doAssert disjoint(a, b) == false
+    doAssert disjoint(a, b - a) == true
+
+  block mapSet:
+    var a = toHashSet([1, 2, 3])
+    var b = a.map(proc (x: int): string = $x)
+    doAssert b == toHashSet(["1", "2", "3"])
+
+  block lenTest:
+    var values: OrderedSet[int]
+    doAssert values.len == 0
+    doAssert values.card == 0
+
+  block setIterator:
+    type pair = tuple[a, b: int]
+    var a, b = initOrderedSet[pair]()
+    a.incl((2, 3))
+    a.incl((3, 2))
+    a.incl((2, 3))
+    for x, y in a.items:
+      b.incl((x - 2, y + 1))
+    doAssert a.len == b.card
+    doAssert a.len == 2
+
+  block setPairsIterator:
+    var s = toOrderedSet([1, 3, 5, 7])
+    var items = newSeq[tuple[a: int, b: int]]()
+    for idx, item in s: items.add((idx, item))
+    doAssert items == @[(0, 1), (1, 3), (2, 5), (3, 7)]
+
+  block exclusions:
+    var s = toOrderedSet([1, 2, 3, 6, 7, 4])
+
+    s.excl(3)
+    s.excl(3)
+    s.excl(1)
+    s.excl(4)
+
+    var items = newSeq[int]()
+    for item in s: items.add item
+    doAssert items == @[2, 6, 7]
+
+  block: #9005
+    var s = initOrderedSet[(int, int)]()
+    for i in 0 .. 30: incl(s, (i, 0))
+    for i in 0 .. 30: excl(s, (i, 0))
+    doAssert s.len == 0
+
+  #block orderedSetIterator:
+  #  var a = initOrderedSet[int]()
+  #  for value in [9, 2, 1, 5, 1, 8, 4, 2]:
+  #    a.incl(value)
+  #  for value in a.items:
+  #    echo "Got ", value
+
+  block setContains:
+    var values = initOrderedSet[int]()
+    doAssert(not values.contains(2))
+    values.incl(2)
+    doAssert values.contains(2)
+
+  block toSeqAndString:
+    var a = toOrderedSet([2, 4, 5])
+    var b = initOrderedSet[int]()
+    for x in [2, 4, 5]: b.incl(x)
+    doAssert($a == $b)
+    doAssert(a == b) # https://github.com/Araq/Nim/issues/1413
+
+  block initBlocks:
+    var a: OrderedSet[int]
+    a.init(4)
+    a.incl(2)
+    a.init
+    doAssert a.len == 0
+    a = initOrderedSet[int](4)
+    a.incl(2)
+    doAssert a.len == 1
+
+    var b: HashSet[int]
+    b.init(4)
+    b.incl(2)
+    b.init
+    doAssert b.len == 0
+    b = initHashSet[int](4)
+    b.incl(2)
+    doAssert b.len == 1
+
+  block missingOrExcl:
+    var s = toOrderedSet([2, 3, 6, 7])
+    doAssert s.missingOrExcl(4) == true
+    doAssert s.missingOrExcl(6) == false
+
+  block orderedSetEquality:
+    type pair = tuple[a, b: int]
+
+    var aa = initOrderedSet[pair]()
+    var bb = initOrderedSet[pair]()
+
+    var x = (a: 1, b: 2)
+    var y = (a: 3, b: 4)
+
+    aa.incl(x)
+    aa.incl(y)
+
+    bb.incl(x)
+    bb.incl(y)
+    doAssert aa == bb
+
+  block setsWithoutInit:
+    var
+      a: HashSet[int]
+      b: HashSet[int]
+      c: HashSet[int]
+      d: HashSet[int]
+      e: HashSet[int]
+
+    doAssert a.containsOrIncl(3) == false
+    doAssert a.contains(3)
+    doAssert a.len == 1
+    doAssert a.containsOrIncl(3)
+    a.incl(3)
+    doAssert a.len == 1
+    a.incl(6)
+    doAssert a.len == 2
+
+    b.incl(5)
+    doAssert b.len == 1
+    b.excl(5)
+    b.excl(c)
+    doAssert b.missingOrExcl(5)
+    doAssert b.disjoint(c)
+
+    d = b + c
+    doAssert d.len == 0
+    d = b * c
+    doAssert d.len == 0
+    d = b - c
+    doAssert d.len == 0
+    d = b -+- c
+    doAssert d.len == 0
+
+    doAssert (d < e) == false
+    doAssert d <= e
+    doAssert d == e
+
+  block setsWithoutInit:
+    var
+      a: OrderedSet[int]
+      b: OrderedSet[int]
+      c: OrderedSet[int]
+      d: HashSet[int]
+
+
+    doAssert a.containsOrIncl(3) == false
+    doAssert a.contains(3)
+    doAssert a.len == 1
+    doAssert a.containsOrIncl(3)
+    a.incl(3)
+    doAssert a.len == 1
+    a.incl(6)
+    doAssert a.len == 2
+
+    b.incl(5)
+    doAssert b.len == 1
+    doAssert b.missingOrExcl(5) == false
+    doAssert b.missingOrExcl(5)
+
+    doAssert c.missingOrExcl(9)
+    d.incl(c)
+    doAssert d.len == 0
+
+testModule()
diff --git a/tests/seq/tseq.nim b/tests/collections/tseq.nim
index 6a28bc8e6..0f8084c78 100644
--- a/tests/seq/tseq.nim
+++ b/tests/collections/tseq.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: '''
 Hithere, what's your name?Hathere, what's your name?
 fA13msg1falsefB14msg2truefC15msg3false
@@ -11,8 +12,7 @@ FilterIt: [1, 3, 7]
 Concat: [1, 3, 5, 7, 2, 4, 6]
 Deduplicate: [1, 2, 3, 4, 5, 7]
 @[()]
-@[1, 42, 3]
-@[1, 42, 3]
+Minmax: (1, 7)
 2345623456
 '''
 """
@@ -24,7 +24,7 @@ block tseq2:
     # multiply two int sequences:
     for i in 0..len(a)-1: result[i] = a[i] * b[i]
 
-  assert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9])
+  doAssert(@[1, 2, 3] * @[1, 2, 3] == @[1, 4, 9])
 
 
 
@@ -157,42 +157,51 @@ block tsequtils:
   let someObjSeq = aSeq.mapIt(it.field)
   echo someObjSeq
 
-
-
-block tshallowseq:
-  proc xxx() =
-    var x: seq[int] = @[1, 2, 3]
-    var y: seq[int]
-    system.shallowCopy(y, x)
-    y[1] = 42
-    echo y
-    echo x
-  xxx()
-
-
-block tshallowemptyseq:
-  proc test() =
-    var nilSeq: seq[int] = @[]
-    var emptySeq: seq[int] = newSeq[int]()
-    block:
-      var t = @[1,2,3]
-      shallow(nilSeq)
-      t = nilSeq
-      doAssert t == @[]
-    block:
-      var t = @[1,2,3]
-      shallow(emptySeq)
-      t = emptySeq
-      doAssert t == @[]
-    block:
-      var t = @[1,2,3]
-      shallowCopy(t, nilSeq)
-      doAssert t == @[]
-    block:
-      var t = @[1,2,3]
-      shallowCopy(t, emptySeq)
-      doAssert t == @[]
-  test()
+  block minmax:
+    doAssert minmax(@[0]) == (0, 0)
+    doAssert minmax(@[0, 1]) == (0, 1)
+    doAssert minmax(@[1, 0]) == (0, 1)
+    doAssert minmax(@[8,2,1,7,3,9,4,0,5]) == (0, 9)
+    echo "Minmax: ", $(minmax(concat(seq1, seq2)))
+
+
+when not defined(nimseqsv2):
+  block tshallowseq:
+    proc xxx() =
+      var x: seq[int] = @[1, 2, 3]
+      var y: seq[int]
+      system.shallowCopy(y, x)
+      y[1] = 42
+      doAssert y == @[1, 42, 3]
+      doAssert x == @[1, 42, 3]
+    xxx()
+
+
+  block tshallowemptyseq:
+    proc test() =
+      var nilSeq: seq[int] = @[]
+      var emptySeq: seq[int] = newSeq[int]()
+      block:
+        var t = @[1,2,3]
+        when defined(gcRefc):
+          shallow(nilSeq)
+        t = nilSeq
+        doAssert t == @[]
+      block:
+        var t = @[1,2,3]
+        when defined(gcRefc):
+          shallow(emptySeq)
+        t = emptySeq
+        doAssert t == @[]
+      block:
+        var t = @[1,2,3]
+        shallowCopy(t, nilSeq)
+        doAssert t == @[]
+      block:
+        var t = @[1,2,3]
+        shallowCopy(t, emptySeq)
+        doAssert t == @[]
+    test()
 
 
 import strutils
@@ -201,6 +210,33 @@ block ttoseq:
     stdout.write(x)
   for x in items(toSeq(countup(2, 6))):
     stdout.write(x)
-  var y: type("a b c".split)
+  var y: typeof("a b c".split)
   y = "xzy"
   stdout.write("\n")
+
+block tseqmapitchain:
+  doAssert @[101, 102] == [1, 2].mapIt(func (x: int): int = it + x).mapIt(it(100))
+
+
+for i in 0..100:
+  # fix #14655
+  var test = newSeqOfCap[uint32](1)
+  test.setLen(1)
+  doAssert test[0] == 0, $(test[0], i)
+
+
+# bug #22560
+doAssert len(newSeqOfCap[int](42)) == 0
+
+block: # bug #17197
+  type Matrix = seq[seq[int]]
+
+  proc needlemanWunsch(sequence1: string, sequence2: string, gap_penal: int8, match: int8, indel_penal: int8): bool =
+    let seq2_len = sequence2.len
+
+    var grid: Matrix
+    for i in sequence1:
+      grid.add(newSeqOfCap[seq[int]](seq2_len))
+    result = true
+
+  doAssert needlemanWunsch("ABC", "DEFG", 1, 2, 3)
diff --git a/tests/collections/ttables.nim b/tests/collections/ttables.nim
index 9eccf345a..95f9418a0 100644
--- a/tests/collections/ttables.nim
+++ b/tests/collections/ttables.nim
@@ -7,15 +7,27 @@ And we get here
 3
 '''
 joinable: false
+targets: "c cpp js"
 """
+
+# xxx wrap in a template to test in VM, see https://github.com/timotheecour/Nim/issues/534#issuecomment-769565033
+
 import hashes, sequtils, tables, algorithm
 
+proc sortedPairs[T](t: T): auto = toSeq(t.pairs).sorted
+template sortedItems(t: untyped): untyped = sorted(toSeq(t))
+
+block tableDollar:
+  # other tests should use `sortedPairs` to be robust to future table/hash
+  # implementation changes
+  doAssert ${1: 'a', 2: 'b'}.toTable in ["{1: 'a', 2: 'b'}", "{2: 'b', 1: 'a'}"]
+
 # test should not be joined because it takes too long.
 block tableadds:
   proc main =
     var tab = newTable[string, string]()
     for i in 0..1000:
-      tab.add "key", "value " & $i
+      tab["key"] = "value " & $i
 
   main()
   echo "done tableadds"
@@ -42,20 +54,20 @@ block thashes:
     var t = initTable[int,int]()
     t[0] = 42
     t[1] = t[0] + 1
-    assert(t[0] == 42)
-    assert(t[1] == 43)
+    doAssert(t[0] == 42)
+    doAssert(t[1] == 43)
     let t2 = {1: 1, 2: 2}.toTable
-    assert(t2[2] == 2)
+    doAssert(t2[2] == 2)
 
   # Test with char
   block:
     var t = initTable[char,int]()
     t['0'] = 42
     t['1'] = t['0'] + 1
-    assert(t['0'] == 42)
-    assert(t['1'] == 43)
+    doAssert(t['0'] == 42)
+    doAssert(t['1'] == 43)
     let t2 = {'1': 1, '2': 2}.toTable
-    assert(t2['2'] == 2)
+    doAssert(t2['2'] == 2)
 
   # Test with enum
   block:
@@ -64,22 +76,22 @@ block thashes:
     var t = initTable[E,int]()
     t[eA] = 42
     t[eB] = t[eA] + 1
-    assert(t[eA] == 42)
-    assert(t[eB] == 43)
+    doAssert(t[eA] == 42)
+    doAssert(t[eB] == 43)
     let t2 = {eA: 1, eB: 2}.toTable
-    assert(t2[eB] == 2)
+    doAssert(t2[eB] == 2)
 
   # Test with range
   block:
     type
-      R = range[1..10]
+      R = range[0..9]
     var t = initTable[R,int]() # causes warning, why?
     t[1] = 42 # causes warning, why?
     t[2] = t[1] + 1
-    assert(t[1] == 42)
-    assert(t[2] == 43)
+    doAssert(t[1] == 42)
+    doAssert(t[2] == 43)
     let t2 = {1.R: 1, 2.R: 2}.toTable
-    assert(t2[2.R] == 2)
+    doAssert(t2[2.R] == 2)
 
   # Test which combines the generics for tuples + ordinals
   block:
@@ -88,10 +100,10 @@ block thashes:
     var t = initTable[(string, E, int, char), int]()
     t[("a", eA, 0, '0')] = 42
     t[("b", eB, 1, '1')] = t[("a", eA, 0, '0')] + 1
-    assert(t[("a", eA, 0, '0')] == 42)
-    assert(t[("b", eB, 1, '1')] == 43)
+    doAssert(t[("a", eA, 0, '0')] == 42)
+    doAssert(t[("b", eB, 1, '1')] == 43)
     let t2 = {("a", eA, 0, '0'): 1, ("b", eB, 1, '1'): 2}.toTable
-    assert(t2[("b", eB, 1, '1')] == 2)
+    doAssert(t2[("b", eB, 1, '1')] == 2)
 
   # Test to check if overloading is possible
   # Unfortunately, this does not seem to work for int
@@ -125,8 +137,8 @@ block tindexby:
   doAssert indexBy(newSeq[int](), proc(x: int):int = x) == initTable[int, int](), "empty int table"
 
   var tbl1 = initTable[int, int]()
-  tbl1.add(1,1)
-  tbl1.add(2,2)
+  tbl1[1] = 1
+  tbl1[2] = 2
   doAssert indexBy(@[1,2], proc(x: int):int = x) == tbl1, "int table"
 
   type
@@ -139,8 +151,8 @@ block tindexby:
     elem2 = TElem(foo: 2, bar: "baz")
 
   var tbl2 = initTable[string, TElem]()
-  tbl2.add("bar", elem1)
-  tbl2.add("baz", elem2)
+  tbl2["bar"] = elem1
+  tbl2["baz"] = elem2
   doAssert indexBy(@[elem1,elem2], proc(x: TElem): string = x.bar) == tbl2, "element table"
 
 
@@ -157,23 +169,22 @@ block tableconstr:
   ignoreExpr({2: 3, "key": "value"})
 
   # NEW:
-  assert 56 in 50..100
+  doAssert 56 in 50..100
 
-  assert 56 in ..60
+  doAssert 56 in 0..60
 
 
 block ttables2:
   proc TestHashIntInt() =
     var tab = initTable[int,int]()
-    for i in 1..1_000_000:
+    let n = 10
+    for i in 1..n:
       tab[i] = i
-    for i in 1..1_000_000:
+    for i in 1..n:
       var x = tab[i]
       if x != i : echo "not found ", i
 
-  proc run1() =         # occupied Memory stays constant, but
-    for i in 1 .. 50:   # aborts at run: 44 on win32 with 3.2GB with out of memory
-      TestHashIntInt()
+  TestHashIntInt()
 
   # bug #2107
 
@@ -185,10 +196,8 @@ block ttables2:
   delTab[5] = 5
 
 
-  run1()
   echo "2"
 
-
 block tablesref:
   const
     data = {
@@ -231,9 +240,9 @@ block tablesref:
     t[(1,1)] = "11"
     for x in 0..1:
       for y in 0..1:
-        assert t[(x,y)] == $x & $y
-    assert($t ==
-      "{(x: 1, y: 1): \"11\", (x: 0, y: 0): \"00\", (x: 0, y: 1): \"01\", (x: 1, y: 0): \"10\"}")
+        doAssert t[(x,y)] == $x & $y
+    doAssert t.sortedPairs ==
+      @[((x: 0, y: 0), "00"), ((x: 0, y: 1), "01"), ((x: 1, y: 0), "10"), ((x: 1, y: 1), "11")]
 
   block tableTest2:
     var t = newTable[string, float]()
@@ -245,31 +254,31 @@ block tablesref:
     t["012"] = 67.9
     t["123"] = 1.5 # test overwriting
 
-    assert t["123"] == 1.5
+    doAssert t["123"] == 1.5
     try:
       echo t["111"] # deleted
     except KeyError:
       discard
-    assert(not hasKey(t, "111"))
-    assert "111" notin t
+    doAssert(not hasKey(t, "111"))
+    doAssert "111" notin t
 
     for key, val in items(data): t[key] = val.toFloat
-    for key, val in items(data): assert t[key] == val.toFloat
+    for key, val in items(data): doAssert t[key] == val.toFloat
 
 
   block orderedTableTest1:
     var t = newOrderedTable[string, int](2)
     for key, val in items(data): t[key] = val
-    for key, val in items(data): assert t[key] == val
+    for key, val in items(data): doAssert t[key] == val
     var i = 0
     # `pairs` needs to yield in insertion order:
     for key, val in pairs(t):
-      assert key == data[i][0]
-      assert val == data[i][1]
+      doAssert key == data[i][0]
+      doAssert val == data[i][1]
       inc(i)
 
     for key, val in mpairs(t): val = 99
-    for val in mvalues(t): assert val == 99
+    for val in mvalues(t): doAssert val == 99
 
   block countTableTest1:
     var s = data.toTable
@@ -278,11 +287,11 @@ block tablesref:
     for x in [t, r]:
       for k in s.keys:
         x.inc(k)
-        assert x[k] == 1
+        doAssert x[k] == 1
       x.inc("90", 3)
       x.inc("12", 2)
       x.inc("34", 1)
-    assert t.largest()[0] == "90"
+    doAssert t.largest()[0] == "90"
 
     t.sort()
     r.sort(SortOrder.Ascending)
@@ -293,29 +302,43 @@ block tablesref:
       var i = 0
       for (k, v) in ps:
         case i
-        of 0: assert k == "90" and v == 4
-        of 1: assert k == "12" and v == 3
-        of 2: assert k == "34" and v == 2
+        of 0: doAssert k == "90" and v == 4
+        of 1: doAssert k == "12" and v == 3
+        of 2: doAssert k == "34" and v == 2
         else: break
         inc i
 
+  block smallestLargestNamedFieldsTest: # bug #14918
+    const a = [7, 8, 8]
+
+    proc testNamedFields(t: CountTable | CountTableRef) =
+      doAssert t.smallest.key == 7
+      doAssert t.smallest.val == 1
+      doAssert t.largest.key == 8
+      doAssert t.largest.val == 2
+
+    let t1 = toCountTable(a)
+    testNamedFields(t1)
+    let t2 = newCountTable(a)
+    testNamedFields(t2)
+
   block SyntaxTest:
     var x = newTable[int, string]({:})
     discard x
 
   block nilTest:
     var i, j: TableRef[int, int] = nil
-    assert i == j
+    doAssert i == j
     j = newTable[int, int]()
-    assert i != j
-    assert j != i
+    doAssert i != j
+    doAssert j != i
     i = newTable[int, int]()
-    assert i == j
+    doAssert i == j
 
   proc orderedTableSortTest() =
     var t = newOrderedTable[string, int](2)
     for key, val in items(data): t[key] = val
-    for key, val in items(data): assert t[key] == val
+    for key, val in items(data): doAssert t[key] == val
     proc cmper(x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key)
     t.sort(cmper)
     var i = 0
@@ -340,32 +363,95 @@ block tablesref:
   block anonZipTest:
     let keys = @['a','b','c']
     let values = @[1, 2, 3]
-    doAssert "{'c': 3, 'a': 1, 'b': 2}" == $ toTable zip(keys, values)
+    doAssert zip(keys, values).toTable.sortedPairs == @[('a', 1), ('b', 2), ('c', 3)]
 
   block clearTableTest:
     var t = newTable[string, float]()
     t["test"] = 1.2345
     t["111"] = 1.000043
     t["123"] = 1.23
-    assert t.len() != 0
+    doAssert t.len() != 0
     t.clear()
-    assert t.len() == 0
+    doAssert t.len() == 0
 
   block clearOrderedTableTest:
     var t = newOrderedTable[string, int](2)
     for key, val in items(data): t[key] = val
-    assert t.len() != 0
+    doAssert t.len() != 0
     t.clear()
-    assert t.len() == 0
+    doAssert t.len() == 0
 
   block clearCountTableTest:
     var t = newCountTable[string]()
     t.inc("90", 3)
     t.inc("12", 2)
     t.inc("34", 1)
-    assert t.len() != 0
+    doAssert t.len() != 0
     t.clear()
-    assert t.len() == 0
+    doAssert t.len() == 0
 
   orderedTableSortTest()
   echo "3"
+
+
+block: # https://github.com/nim-lang/Nim/issues/13496
+  template testDel(body) =
+    block:
+      body
+      when t is CountTable|CountTableRef:
+        t.inc(15, 1)
+        t.inc(19, 2)
+        t.inc(17, 3)
+        t.inc(150, 4)
+        t.del(150)
+      else:
+        t[15] = 1
+        t[19] = 2
+        t[17] = 3
+        t[150] = 4
+        t.del(150)
+      doAssert t.len == 3
+      doAssert sortedItems(t.values) == @[1, 2, 3]
+      doAssert sortedItems(t.keys) == @[15, 17, 19]
+      doAssert sortedPairs(t) == @[(15, 1), (17, 3), (19, 2)]
+      var s = newSeq[int]()
+      for v in t.values: s.add(v)
+      doAssert s.len == 3
+      doAssert sortedItems(s) == @[1, 2, 3]
+      when t is OrderedTable|OrderedTableRef:
+        doAssert toSeq(t.keys) == @[15, 19, 17]
+        doAssert toSeq(t.values) == @[1,2,3]
+        doAssert toSeq(t.pairs) == @[(15, 1), (19, 2), (17, 3)]
+
+  testDel(): (var t: Table[int, int])
+  testDel(): (let t = newTable[int, int]())
+  testDel(): (var t: OrderedTable[int, int])
+  testDel(): (let t = newOrderedTable[int, int]())
+  testDel(): (var t: CountTable[int])
+  testDel(): (let t = newCountTable[int]())
+
+
+block testNonPowerOf2:
+  var a = initTable[int, int](7)
+  a[1] = 10
+  doAssert a[1] == 10
+
+  var b = initTable[int, int](9)
+  b[1] = 10
+  doAssert b[1] == 10
+
+block emptyOrdered:
+  var t1: OrderedTable[int, string]
+  var t2: OrderedTable[int, string]
+  doAssert t1 == t2
+
+block: # Table[ref, int]
+  type A = ref object
+    x: int
+  var t: OrderedTable[A, int]
+  let a1 = A(x: 3)
+  let a2 = A(x: 3)
+  t[a1] = 10
+  t[a2] = 11
+  doAssert t[a1] == 10
+  doAssert t[a2] == 11
diff --git a/tests/collections/ttablesthreads.nim b/tests/collections/ttablesthreads.nim
index 5553b31ef..2a4e1bf42 100644
--- a/tests/collections/ttablesthreads.nim
+++ b/tests/collections/ttablesthreads.nim
@@ -3,7 +3,9 @@ discard """
   output: '''true'''
 """
 
-import hashes, tables, sharedtables
+import hashes, tables, sharedtables, algorithm, sequtils
+
+proc sortedPairs[T](t: T): auto = toSeq(t.pairs).sorted
 
 const
   data = {
@@ -46,9 +48,8 @@ block tableTest1:
   t[(1,1)] = "11"
   for x in 0..1:
     for y in 0..1:
-      assert t[(x,y)] == $x & $y
-  assert($t ==
-    "{(x: 1, y: 1): \"11\", (x: 0, y: 0): \"00\", (x: 0, y: 1): \"01\", (x: 1, y: 0): \"10\"}")
+      doAssert t[(x,y)] == $x & $y
+  doAssert t.sortedPairs == @[((x: 0, y: 0), "00"), ((x: 0, y: 1), "01"), ((x: 1, y: 0), "10"), ((x: 1, y: 1), "11")]
 
 block tableTest2:
   var t = initTable[string, float]()
@@ -60,74 +61,74 @@ block tableTest2:
   t["012"] = 67.9
   t["123"] = 1.5 # test overwriting
 
-  assert t["123"] == 1.5
+  doAssert t["123"] == 1.5
   try:
     echo t["111"] # deleted
   except KeyError:
     discard
-  assert(not hasKey(t, "111"))
+  doAssert(not hasKey(t, "111"))
 
-  assert "123" in t
-  assert("111" notin t)
+  doAssert "123" in t
+  doAssert("111" notin t)
 
   for key, val in items(data): t[key] = val.toFloat
-  for key, val in items(data): assert t[key] == val.toFloat
+  for key, val in items(data): doAssert t[key] == val.toFloat
 
-  assert(not t.hasKeyOrPut("456", 4.0))     # test absent key
-  assert t.hasKeyOrPut("012", 3.0)          # test present key
+  doAssert(not t.hasKeyOrPut("456", 4.0))     # test absent key
+  doAssert t.hasKeyOrPut("012", 3.0)          # test present key
   var x = t.mgetOrPut("111", 1.5)           # test absent key
   x = x * 2
-  assert x == 3.0
+  doAssert x == 3.0
   x = t.mgetOrPut("test", 1.5)              # test present key
   x = x * 2
-  assert x == 2 * 1.2345
+  doAssert x == 2 * 1.2345
 
 block orderedTableTest1:
   var t = initOrderedTable[string, int](2)
   for key, val in items(data): t[key] = val
-  for key, val in items(data): assert t[key] == val
+  for key, val in items(data): doAssert t[key] == val
   var i = 0
   # `pairs` needs to yield in insertion order:
   for key, val in pairs(t):
-    assert key == data[i][0]
-    assert val == data[i][1]
+    doAssert key == data[i][0]
+    doAssert val == data[i][1]
     inc(i)
 
   for key, val in mpairs(t): val = 99
-  for val in mvalues(t): assert val == 99
+  for val in mvalues(t): doAssert val == 99
 
 block orderedTableTest2:
   var
     s = initOrderedTable[string, int]()
     t = initOrderedTable[string, int]()
-  assert s == t
+  doAssert s == t
   for key, val in items(data): t[key] = val
-  assert s != t
+  doAssert s != t
   for key, val in items(sorteddata): s[key] = val
-  assert s != t
+  doAssert s != t
   t.clear()
-  assert s != t
+  doAssert s != t
   for key, val in items(sorteddata): t[key] = val
-  assert s == t
+  doAssert s == t
 
 block countTableTest1:
   var s = data.toTable
   var t = initCountTable[string]()
 
   for k in s.keys: t.inc(k)
-  for k in t.keys: assert t[k] == 1
+  for k in t.keys: doAssert t[k] == 1
   t.inc("90", 3)
   t.inc("12", 2)
   t.inc("34", 1)
-  assert t.largest()[0] == "90"
+  doAssert t.largest()[0] == "90"
 
   t.sort()
   var i = 0
   for k, v in t.pairs:
     case i
-    of 0: assert k == "90" and v == 4
-    of 1: assert k == "12" and v == 3
-    of 2: assert k == "34" and v == 2
+    of 0: doAssert k == "90" and v == 4
+    of 1: doAssert k == "12" and v == 3
+    of 2: doAssert k == "34" and v == 2
     else: break
     inc i
 
@@ -135,19 +136,19 @@ block countTableTest2:
   var
     s = initCountTable[int]()
     t = initCountTable[int]()
-  assert s == t
+  doAssert s == t
   s.inc(1)
-  assert s != t
+  doAssert s != t
   t.inc(2)
-  assert s != t
+  doAssert s != t
   t.inc(1)
-  assert s != t
+  doAssert s != t
   s.inc(2)
-  assert s == t
+  doAssert s == t
   s.inc(1)
-  assert s != t
+  doAssert s != t
   t.inc(1)
-  assert s == t
+  doAssert s == t
 
 block mpairsTableTest1:
   var t = initTable[string, int]()
@@ -161,9 +162,9 @@ block mpairsTableTest1:
 
   for k, v in t.pairs:
     if k == "a" or k == "c":
-      assert v == 9
+      doAssert v == 9
     else:
-      assert v != 1 and v != 3
+      doAssert v != 1 and v != 3
 
 block SyntaxTest:
   var x = toTable[int, string]({:})
@@ -173,10 +174,10 @@ block zeroHashKeysTest:
     let initialLen = t.len
     var testTable = t
     testTable[nullHashKey] = value
-    assert testTable[nullHashKey] == value
-    assert testTable.len == initialLen + 1
+    doAssert testTable[nullHashKey] == value
+    doAssert testTable.len == initialLen + 1
     testTable.del(nullHashKey)
-    assert testTable.len == initialLen
+    doAssert testTable.len == initialLen
 
   # with empty table
   doZeroHashValueTest(toTable[int,int]({:}), 0, 42)
@@ -193,46 +194,46 @@ block zeroHashKeysTest:
 
 block clearTableTest:
   var t = data.toTable
-  assert t.len() != 0
+  doAssert t.len() != 0
   t.clear()
-  assert t.len() == 0
+  doAssert t.len() == 0
 
 block clearOrderedTableTest:
   var t = data.toOrderedTable
-  assert t.len() != 0
+  doAssert t.len() != 0
   t.clear()
-  assert t.len() == 0
+  doAssert t.len() == 0
 
 block clearCountTableTest:
   var t = initCountTable[string]()
   t.inc("90", 3)
   t.inc("12", 2)
   t.inc("34", 1)
-  assert t.len() != 0
+  doAssert t.len() != 0
   t.clear()
-  assert t.len() == 0
+  doAssert t.len() == 0
 
 block withKeyTest:
   var t: SharedTable[int, int]
   t.init()
   t.withKey(1) do (k: int, v: var int, pairExists: var bool):
-    assert(v == 0)
+    doAssert(v == 0)
     pairExists = true
     v = 42
-  assert(t.mget(1) == 42)
+  doAssert(t.mget(1) == 42)
   t.withKey(1) do (k: int, v: var int, pairExists: var bool):
-    assert(v == 42)
+    doAssert(v == 42)
     pairExists = false
   try:
     discard t.mget(1)
-    assert(false, "KeyError expected")
+    doAssert(false, "KeyError expected")
   except KeyError:
     discard
   t.withKey(2) do (k: int, v: var int, pairExists: var bool):
     pairExists = false
   try:
     discard t.mget(2)
-    assert(false, "KeyError expected")
+    doAssert(false, "KeyError expected")
   except KeyError:
     discard
 
@@ -241,20 +242,20 @@ block takeTest:
   t["key"] = 123
 
   var val = 0
-  assert(t.take("key", val))
-  assert(val == 123)
+  doAssert(t.take("key", val))
+  doAssert(val == 123)
 
   val = -1
-  assert(not t.take("key", val))
-  assert(val == -1)
+  doAssert(not t.take("key", val))
+  doAssert(val == -1)
 
-  assert(not t.take("otherkey", val))
-  assert(val == -1)
+  doAssert(not t.take("otherkey", val))
+  doAssert(val == -1)
 
 proc orderedTableSortTest() =
   var t = initOrderedTable[string, int](2)
   for key, val in items(data): t[key] = val
-  for key, val in items(data): assert t[key] == val
+  for key, val in items(data): doAssert t[key] == val
   t.sort(proc (x, y: tuple[key: string, val: int]): int = cmp(x.key, y.key))
   var i = 0
   # `pairs` needs to yield in sorted order:
diff --git a/tests/compileoption/texperimental.nim b/tests/compileoption/texperimental.nim
new file mode 100644
index 000000000..be637e58a
--- /dev/null
+++ b/tests/compileoption/texperimental.nim
@@ -0,0 +1,20 @@
+static:
+  doAssert compileOption("experimental", "dotOperators")
+  doAssert compileOption("experimental", "callOperator")
+  doAssert compileOption("experimental", "parallel")
+  doAssert compileOption("experimental", "destructor")
+  doAssert compileOption("experimental", "notnil")
+  doAssert compileOption("experimental", "dynamicBindSym")
+  doAssert compileOption("experimental", "codeReordering")
+  doAssert compileOption("experimental", "compiletimeFFI")
+  doAssert compileOption("experimental", "vmopsDanger")
+  doAssert compileOption("experimental", "strictFuncs")
+  doAssert compileOption("experimental", "views")
+  doAssert compileOption("experimental", "strictNotNil")
+  doAssert compileOption("experimental", "strictEffects")
+  doAssert compileOption("experimental", "flexibleOptionalParams")
+  doAssert compileOption("experimental", "strictDefs")
+  doAssert compileOption("experimental", "strictCaseObjects")
+  doAssert compileOption("experimental", "inferGenericTypes")
+  doAssert compileOption("experimental", "openSym")
+  doAssert compileOption("experimental", "vtables")
diff --git a/tests/compileoption/texperimental.nims b/tests/compileoption/texperimental.nims
new file mode 100644
index 000000000..c2c357caa
--- /dev/null
+++ b/tests/compileoption/texperimental.nims
@@ -0,0 +1,19 @@
+switch("experimental", "dotOperators")
+switch("experimental", "callOperator")
+switch("experimental", "parallel")
+switch("experimental", "destructor")
+switch("experimental", "notnil")
+switch("experimental", "dynamicBindSym")
+switch("experimental", "codeReordering")
+switch("experimental", "compiletimeFFI")
+switch("experimental", "vmopsDanger")
+switch("experimental", "strictFuncs")
+switch("experimental", "views")
+switch("experimental", "strictNotNil")
+switch("experimental", "strictEffects")
+switch("experimental", "flexibleOptionalParams")
+switch("experimental", "strictDefs")
+switch("experimental", "strictCaseObjects")
+switch("experimental", "inferGenericTypes")
+switch("experimental", "openSym")
+switch("experimental", "vtables")
diff --git a/tests/compiler/samplelib.nim b/tests/compiler/samplelib.nim
new file mode 100644
index 000000000..c70971722
--- /dev/null
+++ b/tests/compiler/samplelib.nim
@@ -0,0 +1,2 @@
+# Sample library used by tcmdlineclib.nim
+proc test(): int {.cdecl, exportc, dynlib.} = 123
diff --git a/tests/compiler/t12684.nim b/tests/compiler/t12684.nim
new file mode 100644
index 000000000..a5f33d2c9
--- /dev/null
+++ b/tests/compiler/t12684.nim
@@ -0,0 +1,7 @@
+discard """
+  cmd: "nim check --hints:off --warnings:off $file"
+  errormsg: "undeclared identifier: 'Undeclared'"
+"""
+
+var x: Undeclared
+import compiler/nimeval
diff --git a/tests/compiler/tasciitables.nim b/tests/compiler/tasciitables.nim
index 0a5ee0f05..2f3b7bf2f 100644
--- a/tests/compiler/tasciitables.nim
+++ b/tests/compiler/tasciitables.nim
@@ -1,5 +1,5 @@
-import compiler/unittest_light
-import compiler/asciitables
+import stdtest/unittest_light
+import std/private/asciitables
 
 import strformat
 
diff --git a/tests/compiler/tasm.nim b/tests/compiler/tasm.nim
new file mode 100644
index 000000000..9f60231e0
--- /dev/null
+++ b/tests/compiler/tasm.nim
@@ -0,0 +1,15 @@
+proc testAsm() =
+  let src = 41
+  var dst = 0
+
+  asm """
+    mov %1, %0\n\t
+    add $1, %0
+    : "=r" (`dst`)
+    : "r" (`src`)"""
+
+  doAssert dst == 42
+
+when defined(gcc) or defined(clang) and not defined(cpp):
+  {.passc: "-std=c99".}
+  testAsm()
\ No newline at end of file
diff --git a/tests/compiler/tbtrees.nim b/tests/compiler/tbtrees.nim
new file mode 100644
index 000000000..973c26420
--- /dev/null
+++ b/tests/compiler/tbtrees.nim
@@ -0,0 +1,84 @@
+discard """
+  output: '''
+www.amazon.com: 207.171.182.16
+www.apple.com: 17.112.152.32
+www.cnn.com: 64.236.16.20
+www.cs.princeton.edu: abc
+www.dell.com: 143.166.224.230
+www.ebay.com: 66.135.192.87
+www.espn.com: 199.181.135.201
+www.google.com: 216.239.41.99
+www.microsoft.com: 207.126.99.140
+www.nytimes.com: 199.239.136.200
+www.princeton.edu: 128.112.128.15
+www.simpsons.com: 209.052.165.60
+www.slashdot.org: 66.35.250.151
+www.weather.com: 63.111.66.11
+www.yahoo.com: 216.109.118.65
+www.yale.edu: 130.132.143.21
+'''
+"""
+
+import compiler/btrees
+
+import random, tables
+
+proc main =
+  var st = initBTree[string, string]()
+  st.add("www.cs.princeton.edu", "abc")
+  st.add("www.princeton.edu",    "128.112.128.15")
+  st.add("www.yale.edu",         "130.132.143.21")
+  st.add("www.simpsons.com",     "209.052.165.60")
+  st.add("www.apple.com",        "17.112.152.32")
+  st.add("www.amazon.com",       "207.171.182.16")
+  st.add("www.ebay.com",         "66.135.192.87")
+  st.add("www.cnn.com",          "64.236.16.20")
+  st.add("www.google.com",       "216.239.41.99")
+  st.add("www.nytimes.com",      "199.239.136.200")
+  st.add("www.microsoft.com",    "207.126.99.140")
+  st.add("www.dell.com",         "143.166.224.230")
+  st.add("www.slashdot.org",     "66.35.250.151")
+  st.add("www.espn.com",         "199.181.135.201")
+  st.add("www.weather.com",      "63.111.66.11")
+  st.add("www.yahoo.com",        "216.109.118.65")
+
+  doAssert st.getOrDefault("www.cs.princeton.edu") == "abc"
+  doAssert st.getOrDefault("www.harvardsucks.com") == ""
+
+  doAssert st.getOrDefault("www.simpsons.com") == "209.052.165.60"
+  doAssert st.getOrDefault("www.apple.com") == "17.112.152.32"
+  doAssert st.getOrDefault("www.ebay.com") == "66.135.192.87"
+  doAssert st.getOrDefault("www.dell.com") == "143.166.224.230"
+  doAssert(st.len == 16)
+
+  for k, v in st:
+    echo k, ": ", v
+
+  when false:
+    var b2 = initBTree[string, string]()
+    const iters = 10_000
+    for i in 1..iters:
+      b2.add($i, $(iters - i))
+    for i in 1..iters:
+      let x = b2.getOrDefault($i)
+      if x != $(iters - i):
+        echo "got ", x, ", but expected ", iters - i
+    echo b2.len
+
+  when true:
+    var b2 = initBTree[int, string]()
+    var t2 = initTable[int, string]()
+    const iters = 100
+    for i in 1..iters:
+      let x = rand(high(int))
+      if not t2.hasKey(x):
+        doAssert b2.getOrDefault(x).len == 0, " what, tree has this element " & $x
+        t2[x] = $x
+        b2.add(x, $x)
+
+    doAssert(b2.len == t2.len, "unique entries " & $b2.len)
+    for k, v in t2:
+      doAssert $k == v
+      doAssert b2.getOrDefault(k) == $k
+
+main()
diff --git a/tests/compiler/tcmdlineclib.nim b/tests/compiler/tcmdlineclib.nim
new file mode 100644
index 000000000..c06d6f103
--- /dev/null
+++ b/tests/compiler/tcmdlineclib.nim
@@ -0,0 +1,3 @@
+proc test(): int {.importc, cdecl.}
+
+doAssert test() == 123
diff --git a/tests/compiler/tcmdlineclib.nims b/tests/compiler/tcmdlineclib.nims
new file mode 100644
index 000000000..f7899d92e
--- /dev/null
+++ b/tests/compiler/tcmdlineclib.nims
@@ -0,0 +1,10 @@
+import os
+
+selfExec "c --app:lib " & (projectDir() / "samplelib.nim")
+switch("clibdir", projectDir())
+--clib:samplelib
+
+# Make test executable can load sample shared library.
+# `-rpath` option doesn't work and ignored on Windows.
+# But the dll file in same directory as executable file is loaded.
+switch("passL", "-Wl,-rpath," & projectDir())
diff --git a/tests/compiler/tcmdlineoswin.nim b/tests/compiler/tcmdlineoswin.nim
index 6642c5ac6..602671e98 100644
--- a/tests/compiler/tcmdlineoswin.nim
+++ b/tests/compiler/tcmdlineoswin.nim
@@ -2,7 +2,7 @@ discard """
   cmd: "nim $target $options --os:windows $file"
   disabled: "linux"
   disabled: "bsd"
-  disabled: "macosx"
+  disabled: "osx"
   disabled: "unix"
   disabled: "posix"
 """
diff --git a/tests/compiler/tcppCompileToNamespace.nim b/tests/compiler/tcppCompileToNamespace.nim
index 1d0977236..4e895c38b 100644
--- a/tests/compiler/tcppCompileToNamespace.nim
+++ b/tests/compiler/tcppCompileToNamespace.nim
@@ -1,6 +1,5 @@
 discard """
 cmd: "nim cpp --cppCompileToNamespace:foo $options -r $file"
-target: cpp
 """
 
 # Theoretically nim could just ignore the flag cppCompileToNamespace
diff --git a/tests/compiler/tdebugutils.nim b/tests/compiler/tdebugutils.nim
new file mode 100644
index 000000000..50b15cb78
--- /dev/null
+++ b/tests/compiler/tdebugutils.nim
@@ -0,0 +1,38 @@
+discard """
+  joinable: false
+  disabled: true
+"""
+
+#[
+This test illustrates some features of `debugutils` to debug the compiler.
+
+## example
+this shows how to enable compiler logging just for a section of user code,
+without generating tons of unrelated log messages for code you're not interested
+in debugging.
+
+```sh
+# enable some debugging code, e.g. the `when false:` block in `semExpr`
+nim c -o:bin/nim_temp --stacktrace -d:debug -d:nimDebugUtils compiler/nim
+bin/nim_temp c tests/compiler/tdebugutils.nim
+```
+
+(use --filenames:abs for abs files)
+
+## result
+("<", "tdebugutils.nim(16, 3)",  {.define(nimCompilerDebug).}, nil)
+(">", "tdebugutils.nim(17, 3)", let a = 2.5 * 3, {}, nkLetSection)
+(">", "tdebugutils.nim(17, 15)", 2.5 * 3, {efAllowDestructor, efWantValue}, nkInfix)
+(">", "tdebugutils.nim(17, 11)", 2.5, {efAllowStmt, efDetermineType, efOperand}, nkFloatLit)
+("<", "tdebugutils.nim(17, 11)", 2.5, float64)
+(">", "tdebugutils.nim(17, 17)", 3, {efAllowStmt, efDetermineType, efOperand}, nkIntLit)
+("<", "tdebugutils.nim(17, 17)", 3, int literal(3))
+("<", "tdebugutils.nim(17, 15)", 2.5 * 3, float)
+("<", "tdebugutils.nim(17, 3)", let a = 2.5 * 3, nil)
+(">", "tdebugutils.nim(18, 3)",  {.undef(nimCompilerDebug).}, {}, nkPragma)
+]#
+
+proc main =
+  {.define(nimCompilerDebug).}
+  let a = 2.5 * 3
+  {.undef(nimCompilerDebug).}
diff --git a/tests/compiler/tgrammar.nim b/tests/compiler/tgrammar.nim
new file mode 100644
index 000000000..772d0f0cc
--- /dev/null
+++ b/tests/compiler/tgrammar.nim
@@ -0,0 +1,7 @@
+discard """
+  matrix: "-d:nimTestGrammar"
+"""
+
+import compiler/parser
+
+checkSameGrammar()
diff --git a/tests/compiler/tint128.nim b/tests/compiler/tint128.nim
new file mode 100644
index 000000000..a30b1b1cc
--- /dev/null
+++ b/tests/compiler/tint128.nim
@@ -0,0 +1,184 @@
+import compiler/int128
+
+let (a,b) = divMod(Ten,Ten)
+
+doAssert $One == "1"
+doAssert $Ten == "10"
+doAssert $Zero == "0"
+let c = parseDecimalInt128("12345678989876543210123456789")
+doAssert $c == "12345678989876543210123456789"
+
+var d : array[39, Int128]
+d[0] =  parseDecimalInt128("1")
+d[1] =  parseDecimalInt128("10")
+d[2] =  parseDecimalInt128("100")
+d[3] =  parseDecimalInt128("1000")
+d[4] =  parseDecimalInt128("10000")
+d[5] =  parseDecimalInt128("100000")
+d[6] =  parseDecimalInt128("1000000")
+d[7] =  parseDecimalInt128("10000000")
+d[8] =  parseDecimalInt128("100000000")
+d[9] =  parseDecimalInt128("1000000000")
+d[10] = parseDecimalInt128("10000000000")
+d[11] = parseDecimalInt128("100000000000")
+d[12] = parseDecimalInt128("1000000000000")
+d[13] = parseDecimalInt128("10000000000000")
+d[14] = parseDecimalInt128("100000000000000")
+d[15] = parseDecimalInt128("1000000000000000")
+d[16] = parseDecimalInt128("10000000000000000")
+d[17] = parseDecimalInt128("100000000000000000")
+d[18] = parseDecimalInt128("1000000000000000000")
+d[19] = parseDecimalInt128("10000000000000000000")
+d[20] = parseDecimalInt128("100000000000000000000")
+d[21] = parseDecimalInt128("1000000000000000000000")
+d[22] = parseDecimalInt128("10000000000000000000000")
+d[23] = parseDecimalInt128("100000000000000000000000")
+d[24] = parseDecimalInt128("1000000000000000000000000")
+d[25] = parseDecimalInt128("10000000000000000000000000")
+d[26] = parseDecimalInt128("100000000000000000000000000")
+d[27] = parseDecimalInt128("1000000000000000000000000000")
+d[28] = parseDecimalInt128("10000000000000000000000000000")
+d[29] = parseDecimalInt128("100000000000000000000000000000")
+d[30] = parseDecimalInt128("1000000000000000000000000000000")
+d[31] = parseDecimalInt128("10000000000000000000000000000000")
+d[32] = parseDecimalInt128("100000000000000000000000000000000")
+d[33] = parseDecimalInt128("1000000000000000000000000000000000")
+d[34] = parseDecimalInt128("10000000000000000000000000000000000")
+d[35] = parseDecimalInt128("100000000000000000000000000000000000")
+d[36] = parseDecimalInt128("1000000000000000000000000000000000000")
+d[37] = parseDecimalInt128("10000000000000000000000000000000000000")
+d[38] = parseDecimalInt128("100000000000000000000000000000000000000")
+
+for i in 0..<d.len:
+  for j in 0..<d.len:
+    doAssert(cmp(d[i], d[j]) == cmp(i,j))
+    if i + j < d.len:
+      doAssert d[i] * d[j] == d[i+j]
+    if i - j >= 0:
+      doAssert d[i] div d[j] == d[i-j]
+
+var sum: Int128
+
+for it in d:
+  sum += it
+
+doAssert $sum == "111111111111111111111111111111111111111"
+
+for it in d.mitems:
+  it = -it
+
+for i in 0..<d.len:
+  for j in 0..<d.len:
+    doAssert(cmp(d[i], d[j]) == -cmp(i,j))
+    if i + j < d.len:
+      doAssert d[i] * d[j] == -d[i+j]
+    if i - j >= 0:
+      doAssert d[i] div d[j] == -d[i-j]
+
+doAssert $high(Int128) == "170141183460469231731687303715884105727"
+doAssert $low(Int128) == "-170141183460469231731687303715884105728"
+
+var ma = 100'i64
+var mb = 13
+
+doAssert toInt128(ma) * toInt128(0) == toInt128(0)
+doAssert toInt128(-ma) * toInt128(0) == toInt128(0)
+
+# sign correctness
+doAssert divMod(toInt128( ma),toInt128( mb)) == (toInt128( ma div  mb), toInt128( ma mod  mb))
+doAssert divMod(toInt128(-ma),toInt128( mb)) == (toInt128(-ma div  mb), toInt128(-ma mod  mb))
+doAssert divMod(toInt128( ma),toInt128(-mb)) == (toInt128( ma div -mb), toInt128( ma mod -mb))
+doAssert divMod(toInt128(-ma),toInt128(-mb)) == (toInt128(-ma div -mb), toInt128(-ma mod -mb))
+
+doAssert divMod(toInt128( mb),toInt128( mb)) == (toInt128( mb div  mb), toInt128( mb mod  mb))
+doAssert divMod(toInt128(-mb),toInt128( mb)) == (toInt128(-mb div  mb), toInt128(-mb mod  mb))
+doAssert divMod(toInt128( mb),toInt128(-mb)) == (toInt128( mb div -mb), toInt128( mb mod -mb))
+doAssert divMod(toInt128(-mb),toInt128(-mb)) == (toInt128(-mb div -mb), toInt128(-mb mod -mb))
+
+doAssert divMod(toInt128( mb),toInt128( ma)) == (toInt128( mb div  ma), toInt128( mb mod  ma))
+doAssert divMod(toInt128(-mb),toInt128( ma)) == (toInt128(-mb div  ma), toInt128(-mb mod  ma))
+doAssert divMod(toInt128( mb),toInt128(-ma)) == (toInt128( mb div -ma), toInt128( mb mod -ma))
+doAssert divMod(toInt128(-mb),toInt128(-ma)) == (toInt128(-mb div -ma), toInt128(-mb mod -ma))
+
+let e = parseDecimalInt128("70997106675279150998592376708984375")
+
+let strArray = [
+  # toHex(e shr 0), toHex(e shr 1), toHex(e shr 2), toHex(e shr 3)
+  "000dac6d782d266a37300c32591eee37", "0006d636bc1693351b9806192c8f771b", "00036b1b5e0b499a8dcc030c9647bb8d", "0001b58daf05a4cd46e601864b23ddc6",
+  "0000dac6d782d266a37300c32591eee3", "00006d636bc1693351b9806192c8f771", "000036b1b5e0b499a8dcc030c9647bb8", "00001b58daf05a4cd46e601864b23ddc",
+  "00000dac6d782d266a37300c32591eee", "000006d636bc1693351b9806192c8f77", "0000036b1b5e0b499a8dcc030c9647bb", "000001b58daf05a4cd46e601864b23dd",
+  "000000dac6d782d266a37300c32591ee", "0000006d636bc1693351b9806192c8f7", "00000036b1b5e0b499a8dcc030c9647b", "0000001b58daf05a4cd46e601864b23d",
+  "0000000dac6d782d266a37300c32591e", "00000006d636bc1693351b9806192c8f", "000000036b1b5e0b499a8dcc030c9647", "00000001b58daf05a4cd46e601864b23",
+  "00000000dac6d782d266a37300c32591", "000000006d636bc1693351b9806192c8", "0000000036b1b5e0b499a8dcc030c964", "000000001b58daf05a4cd46e601864b2",
+  "000000000dac6d782d266a37300c3259", "0000000006d636bc1693351b9806192c", "00000000036b1b5e0b499a8dcc030c96", "0000000001b58daf05a4cd46e601864b",
+  "0000000000dac6d782d266a37300c325", "00000000006d636bc1693351b9806192", "000000000036b1b5e0b499a8dcc030c9", "00000000001b58daf05a4cd46e601864",
+  "00000000000dac6d782d266a37300c32", "000000000006d636bc1693351b980619", "0000000000036b1b5e0b499a8dcc030c", "000000000001b58daf05a4cd46e60186",
+  "000000000000dac6d782d266a37300c3", "0000000000006d636bc1693351b98061", "00000000000036b1b5e0b499a8dcc030", "0000000000001b58daf05a4cd46e6018",
+  "0000000000000dac6d782d266a37300c", "00000000000006d636bc1693351b9806", "000000000000036b1b5e0b499a8dcc03", "00000000000001b58daf05a4cd46e601",
+  "00000000000000dac6d782d266a37300", "000000000000006d636bc1693351b980", "0000000000000036b1b5e0b499a8dcc0", "000000000000001b58daf05a4cd46e60",
+  "000000000000000dac6d782d266a3730", "0000000000000006d636bc1693351b98", "00000000000000036b1b5e0b499a8dcc", "0000000000000001b58daf05a4cd46e6",
+  "0000000000000000dac6d782d266a373", "00000000000000006d636bc1693351b9", "000000000000000036b1b5e0b499a8dc", "00000000000000001b58daf05a4cd46e",
+  "00000000000000000dac6d782d266a37", "000000000000000006d636bc1693351b", "0000000000000000036b1b5e0b499a8d", "000000000000000001b58daf05a4cd46",
+  "000000000000000000dac6d782d266a3", "0000000000000000006d636bc1693351", "00000000000000000036b1b5e0b499a8", "0000000000000000001b58daf05a4cd4",
+  "0000000000000000000dac6d782d266a", "00000000000000000006d636bc169335", "000000000000000000036b1b5e0b499a", "00000000000000000001b58daf05a4cd",
+  "00000000000000000000dac6d782d266", "000000000000000000006d636bc16933", "0000000000000000000036b1b5e0b499", "000000000000000000001b58daf05a4c",
+  "000000000000000000000dac6d782d26", "0000000000000000000006d636bc1693", "00000000000000000000036b1b5e0b49", "0000000000000000000001b58daf05a4",
+  "0000000000000000000000dac6d782d2", "00000000000000000000006d636bc169", "000000000000000000000036b1b5e0b4", "00000000000000000000001b58daf05a",
+  "00000000000000000000000dac6d782d", "000000000000000000000006d636bc16", "0000000000000000000000036b1b5e0b", "000000000000000000000001b58daf05",
+  "000000000000000000000000dac6d782", "0000000000000000000000006d636bc1", "00000000000000000000000036b1b5e0", "0000000000000000000000001b58daf0",
+  "0000000000000000000000000dac6d78", "00000000000000000000000006d636bc", "000000000000000000000000036b1b5e", "00000000000000000000000001b58daf",
+  "00000000000000000000000000dac6d7", "000000000000000000000000006d636b", "0000000000000000000000000036b1b5", "000000000000000000000000001b58da",
+  "000000000000000000000000000dac6d", "0000000000000000000000000006d636", "00000000000000000000000000036b1b", "0000000000000000000000000001b58d",
+  "0000000000000000000000000000dac6", "00000000000000000000000000006d63", "000000000000000000000000000036b1", "00000000000000000000000000001b58",
+  "00000000000000000000000000000dac", "000000000000000000000000000006d6", "0000000000000000000000000000036b", "000000000000000000000000000001b5",
+  "000000000000000000000000000000da", "0000000000000000000000000000006d", "00000000000000000000000000000036", "0000000000000000000000000000001b",
+  "0000000000000000000000000000000d", "00000000000000000000000000000006", "00000000000000000000000000000003", "00000000000000000000000000000001",
+  "00000000000000000000000000000000", "00000000000000000000000000000000", "00000000000000000000000000000000", "00000000000000000000000000000000",
+  "00000000000000000000000000000000", "00000000000000000000000000000000", "00000000000000000000000000000000", "00000000000000000000000000000000",
+  "00000000000000000000000000000000", "00000000000000000000000000000000", "00000000000000000000000000000000", "00000000000000000000000000000000",
+]
+
+for i in 0 ..< 128:
+  let str1 = toHex(e shr i)
+  let str2 = strArray[i]
+  doAssert str1 == str2
+
+let strArray2 = [
+  "000dac6d782d266a37300c32591eee37", "001b58daf05a4cd46e601864b23ddc6e", "0036b1b5e0b499a8dcc030c9647bb8dc", "006d636bc1693351b9806192c8f771b8",
+  "00dac6d782d266a37300c32591eee370", "01b58daf05a4cd46e601864b23ddc6e0", "036b1b5e0b499a8dcc030c9647bb8dc0", "06d636bc1693351b9806192c8f771b80",
+  "0dac6d782d266a37300c32591eee3700", "1b58daf05a4cd46e601864b23ddc6e00", "36b1b5e0b499a8dcc030c9647bb8dc00", "6d636bc1693351b9806192c8f771b800",
+  "dac6d782d266a37300c32591eee37000", "b58daf05a4cd46e601864b23ddc6e000", "6b1b5e0b499a8dcc030c9647bb8dc000", "d636bc1693351b9806192c8f771b8000",
+  "ac6d782d266a37300c32591eee370000", "58daf05a4cd46e601864b23ddc6e0000", "b1b5e0b499a8dcc030c9647bb8dc0000", "636bc1693351b9806192c8f771b80000",
+  "c6d782d266a37300c32591eee3700000", "8daf05a4cd46e601864b23ddc6e00000", "1b5e0b499a8dcc030c9647bb8dc00000", "36bc1693351b9806192c8f771b800000",
+  "6d782d266a37300c32591eee37000000", "daf05a4cd46e601864b23ddc6e000000", "b5e0b499a8dcc030c9647bb8dc000000", "6bc1693351b9806192c8f771b8000000",
+  "d782d266a37300c32591eee370000000", "af05a4cd46e601864b23ddc6e0000000", "5e0b499a8dcc030c9647bb8dc0000000", "bc1693351b9806192c8f771b80000000",
+  "782d266a37300c32591eee3700000000", "f05a4cd46e601864b23ddc6e00000000", "e0b499a8dcc030c9647bb8dc00000000", "c1693351b9806192c8f771b800000000",
+  "82d266a37300c32591eee37000000000", "05a4cd46e601864b23ddc6e000000000", "0b499a8dcc030c9647bb8dc000000000", "1693351b9806192c8f771b8000000000",
+  "2d266a37300c32591eee370000000000", "5a4cd46e601864b23ddc6e0000000000", "b499a8dcc030c9647bb8dc0000000000", "693351b9806192c8f771b80000000000",
+  "d266a37300c32591eee3700000000000", "a4cd46e601864b23ddc6e00000000000", "499a8dcc030c9647bb8dc00000000000", "93351b9806192c8f771b800000000000",
+  "266a37300c32591eee37000000000000", "4cd46e601864b23ddc6e000000000000", "99a8dcc030c9647bb8dc000000000000", "3351b9806192c8f771b8000000000000",
+  "66a37300c32591eee370000000000000", "cd46e601864b23ddc6e0000000000000", "9a8dcc030c9647bb8dc0000000000000", "351b9806192c8f771b80000000000000",
+  "6a37300c32591eee3700000000000000", "d46e601864b23ddc6e00000000000000", "a8dcc030c9647bb8dc00000000000000", "51b9806192c8f771b800000000000000",
+  "a37300c32591eee37000000000000000", "46e601864b23ddc6e000000000000000", "8dcc030c9647bb8dc000000000000000", "1b9806192c8f771b8000000000000000",
+  "37300c32591eee370000000000000000", "6e601864b23ddc6e0000000000000000", "dcc030c9647bb8dc0000000000000000", "b9806192c8f771b80000000000000000",
+  "7300c32591eee3700000000000000000", "e601864b23ddc6e00000000000000000", "cc030c9647bb8dc00000000000000000", "9806192c8f771b800000000000000000",
+  "300c32591eee37000000000000000000", "601864b23ddc6e000000000000000000", "c030c9647bb8dc000000000000000000", "806192c8f771b8000000000000000000",
+  "00c32591eee370000000000000000000", "01864b23ddc6e0000000000000000000", "030c9647bb8dc0000000000000000000", "06192c8f771b80000000000000000000",
+  "0c32591eee3700000000000000000000", "1864b23ddc6e00000000000000000000", "30c9647bb8dc00000000000000000000", "6192c8f771b800000000000000000000",
+  "c32591eee37000000000000000000000", "864b23ddc6e000000000000000000000", "0c9647bb8dc000000000000000000000", "192c8f771b8000000000000000000000",
+  "32591eee370000000000000000000000", "64b23ddc6e0000000000000000000000", "c9647bb8dc0000000000000000000000", "92c8f771b80000000000000000000000",
+  "2591eee3700000000000000000000000", "4b23ddc6e00000000000000000000000", "9647bb8dc00000000000000000000000", "2c8f771b800000000000000000000000",
+  "591eee37000000000000000000000000", "b23ddc6e000000000000000000000000", "647bb8dc000000000000000000000000", "c8f771b8000000000000000000000000",
+  "91eee370000000000000000000000000", "23ddc6e0000000000000000000000000", "47bb8dc0000000000000000000000000", "8f771b80000000000000000000000000",
+  "1eee3700000000000000000000000000", "3ddc6e00000000000000000000000000", "7bb8dc00000000000000000000000000", "f771b800000000000000000000000000",
+  "eee37000000000000000000000000000", "ddc6e000000000000000000000000000", "bb8dc000000000000000000000000000", "771b8000000000000000000000000000",
+  "ee370000000000000000000000000000", "dc6e0000000000000000000000000000", "b8dc0000000000000000000000000000", "71b80000000000000000000000000000",
+  "e3700000000000000000000000000000", "c6e00000000000000000000000000000", "8dc00000000000000000000000000000", "1b800000000000000000000000000000",
+  "37000000000000000000000000000000", "6e000000000000000000000000000000", "dc000000000000000000000000000000", "b8000000000000000000000000000000",
+  "70000000000000000000000000000000", "e0000000000000000000000000000000", "c0000000000000000000000000000000", "80000000000000000000000000000000",
+]
+
+for i in 0 ..< 128:
+  let str1 = toHex(e shl i)
+  let str2 = strArray2[i]
+  doAssert str1 == str2
diff --git a/tests/compiler/tnimblecmd.nim b/tests/compiler/tnimblecmd.nim
new file mode 100644
index 000000000..53bce4625
--- /dev/null
+++ b/tests/compiler/tnimblecmd.nim
@@ -0,0 +1,75 @@
+include compiler/[nimblecmd], sets
+
+proc v(s: string): Version = s.newVersion
+
+proc testVersionsComparison =
+  # #head is special in the sense that it's assumed to always be newest.
+  doAssert v"1.0" < v"#head"
+  doAssert v"1.0" < v"1.1"
+  doAssert v"1.0.1" < v"1.1"
+  doAssert v"1" < v"1.1"
+  doAssert v"#aaaqwe" < v"1.1" # We cannot assume that a branch is newer.
+  doAssert v"#a111" < v"#head"
+
+proc testAddPackageWithoutChecksum =
+  ## For backward compatibility it is not required all packages to have a
+  ## sha1 checksum at the end of the name of the Nimble cache directory.
+  ## This way a new compiler will be able to work with an older Nimble.
+
+  let conf = newConfigRef()
+  var rr: PackageInfo
+
+  addPackage conf, rr, "irc-#a111", unknownLineInfo
+  addPackage conf, rr, "irc-#head", unknownLineInfo
+  addPackage conf, rr, "irc-0.1.0", unknownLineInfo
+
+  addPackage conf, rr, "another-0.1", unknownLineInfo
+
+  addPackage conf, rr, "ab-0.1.3", unknownLineInfo
+  addPackage conf, rr, "ab-0.1", unknownLineInfo
+  addPackage conf, rr, "justone-1.0", unknownLineInfo
+
+  doAssert toSeq(rr.chosen).toHashSet ==
+    ["irc-#head", "another-0.1", "ab-0.1.3", "justone-1.0"].toHashSet
+
+proc testAddPackageWithChecksum =
+  let conf = newConfigRef()
+  var rr: PackageInfo
+
+  # in the case of packages with the same version, but different checksums for
+  # now the first one will be chosen
+
+  addPackage conf, rr, "irc-#a111-DBC1F902CB79946E990E38AF51F0BAD36ACFABD9",
+             unknownLineInfo
+  addPackage conf, rr, "irc-#head-042D4BE2B90ED0672E717D71850ABDB0A2D19CD1",
+             unknownLineInfo
+  addPackage conf, rr, "irc-#head-042D4BE2B90ED0672E717D71850ABDB0A2D19CD2",
+             unknownLineInfo
+  addPackage conf, rr, "irc-0.1.0-6EE6DE936B32E82C7DBE526DA3463574F6568FAF",
+             unknownLineInfo
+
+  addPackage conf, rr, "another-0.1", unknownLineInfo
+  addPackage conf, rr, "another-0.1-F07EE6040579F0590608A8FD34F5F2D91D859340",
+             unknownLineInfo
+
+  addPackage conf, rr, "ab-0.1.3-34BC3B72CE46CF5A496D1121CFEA7369385E9EA2",
+             unknownLineInfo
+  addPackage conf, rr, "ab-0.1.3-24BC3B72CE46CF5A496D1121CFEA7369385E9EA2",
+             unknownLineInfo
+  addPackage conf, rr, "ab-0.1-A3CFFABDC4759F7779D541F5E031AED17169390A",
+             unknownLineInfo
+
+  # lower case hex digits is also a valid sha1 checksum
+  addPackage conf, rr, "justone-1.0-f07ee6040579f0590608a8fd34f5f2d91d859340",
+             unknownLineInfo
+
+  doAssert toSeq(rr.chosen).toHashSet == [
+    "irc-#head-042D4BE2B90ED0672E717D71850ABDB0A2D19CD1",
+    "another-0.1",
+    "ab-0.1.3-34BC3B72CE46CF5A496D1121CFEA7369385E9EA2",
+    "justone-1.0-f07ee6040579f0590608a8fd34f5f2d91d859340"
+    ].toHashSet
+
+testVersionsComparison()
+testAddPackageWithoutChecksum()
+testAddPackageWithChecksum()
diff --git a/tests/compiler/tpathutils.nim b/tests/compiler/tpathutils.nim
new file mode 100644
index 000000000..47ff0f06a
--- /dev/null
+++ b/tests/compiler/tpathutils.nim
@@ -0,0 +1,18 @@
+import compiler/pathutils
+import os, strutils
+
+
+doAssert AbsoluteDir"/Users/me///" / RelativeFile"z.nim" == AbsoluteFile"/Users/me/z.nim"
+doAssert AbsoluteDir"/Users/me" / RelativeFile"../z.nim" == AbsoluteFile"/Users/z.nim"
+doAssert AbsoluteDir"/Users/me/" / RelativeFile"../z.nim" == AbsoluteFile"/Users/z.nim"
+doAssert relativePath("/foo/bar.nim", "/foo/", '/') == "bar.nim"
+doAssert $RelativeDir"foo/bar" == "foo/bar"
+doAssert RelativeDir"foo/bar" == RelativeDir"foo/bar"
+doAssert RelativeFile"foo/bar".changeFileExt(".txt") == RelativeFile"foo/bar.txt"
+doAssert RelativeFile"foo/bar".addFileExt(".txt") == RelativeFile"foo/bar.txt"
+doAssert not RelativeDir"foo/bar".isEmpty
+doAssert RelativeDir"".isEmpty
+
+when defined(windows):
+  let nasty = string(AbsoluteDir(r"C:\Users\rumpf\projects\nim\tests\nimble\nimbleDir\linkedPkgs\pkgB-#head\../../simplePkgs/pkgB-#head/") / RelativeFile"pkgA/module.nim")
+  doAssert nasty.replace('/', '\\') == r"C:\Users\rumpf\projects\nim\tests\nimble\nimbleDir\simplePkgs\pkgB-#head\pkgA\module.nim"
diff --git a/tests/compiler/tprefixmatches.nim b/tests/compiler/tprefixmatches.nim
new file mode 100644
index 000000000..6a3186729
--- /dev/null
+++ b/tests/compiler/tprefixmatches.nim
@@ -0,0 +1,32 @@
+import compiler/prefixmatches
+import macros
+
+macro check(val, body: untyped): untyped =
+  result = newStmtList()
+  expectKind body, nnkStmtList
+  for b in body:
+    expectKind b, nnkTupleConstr
+    expectLen b, 2
+    let p = b[0]
+    let s = b[1]
+    result.add quote do:
+      doAssert prefixMatch(`p`, `s`) == `val`
+
+check PrefixMatch.Prefix:
+  ("abc", "abc")
+  ("a", "abc")
+  ("xyz", "X_yzzzZe")
+
+check PrefixMatch.Substr:
+  ("b", "abc")
+  ("abc", "fooabcabc")
+  ("abC", "foo_AB_c")
+
+check PrefixMatch.Abbrev:
+  ("abc", "AxxxBxxxCxxx")
+  ("xyz", "X_yabcZe")
+
+check PrefixMatch.None:
+  ("foobar", "afkslfjd_as")
+  ("xyz", "X_yuuZuuZe")
+  ("ru", "remotes")
diff --git a/tests/compiler/tunittest_light.nim b/tests/compiler/tunittest_light.nim
index 422474002..2951cc664 100644
--- a/tests/compiler/tunittest_light.nim
+++ b/tests/compiler/tunittest_light.nim
@@ -1,8 +1,8 @@
-import compiler/unittest_light
+import stdtest/unittest_light
 
 proc testAssertEquals() =
   assertEquals("foo", "foo")
-  doAssertRaises(AssertionError):
+  doAssertRaises(AssertionDefect):
     assertEquals("foo", "foo ")
 
 proc testMismatch() =
diff --git a/tests/compilerapi/invalid.nim b/tests/compilerapi/invalid.nim
new file mode 100644
index 000000000..3c9364402
--- /dev/null
+++ b/tests/compilerapi/invalid.nim
@@ -0,0 +1 @@
+noSuchProc()
diff --git a/tests/compilerapi/tcompilerapi.nim b/tests/compilerapi/tcompilerapi.nim
index edeaa2ba5..2d6cfa0ca 100644
--- a/tests/compilerapi/tcompilerapi.nim
+++ b/tests/compilerapi/tcompilerapi.nim
@@ -5,6 +5,7 @@ discard """
 my secret
 11
 12
+raising VMQuit
 '''
   joinable: "false"
 """
@@ -12,33 +13,35 @@ my secret
 ## Example program that demonstrates how to use the
 ## compiler as an API to embed into your own projects.
 
-import "../../compiler" / [ast, vmdef, vm, nimeval, llstream]
+import "../../compiler" / [ast, vmdef, vm, nimeval, llstream, lineinfos, options]
 import std / [os]
 
-proc main() =
+proc initInterpreter(script: string): Interpreter =
   let std = findNimStdLibCompileTime()
-  var intr = createInterpreter("myscript.nim",[std, parentDir(currentSourcePath)])
-  intr.implementRoutine("*", "exposed", "addFloats", proc (a: VmArgs) =
+  result = createInterpreter(script, [std, parentDir(currentSourcePath),
+    std / "pure", std / "core"])
+
+proc main() =
+  let i = initInterpreter("myscript.nim")
+  i.implementRoutine("nim", "exposed", "addFloats", proc (a: VmArgs) =
     setResult(a, getFloat(a, 0) + getFloat(a, 1) + getFloat(a, 2))
   )
-
-  intr.evalScript()
-
-  let foreignProc = selectRoutine(intr, "hostProgramRunsThis")
+  i.evalScript()
+  let foreignProc = i.selectRoutine("hostProgramRunsThis")
   if foreignProc == nil:
     quit "script does not export a proc of the name: 'hostProgramRunsThis'"
-  let res = intr.callRoutine(foreignProc, [newFloatNode(nkFloatLit, 0.9),
-                                           newFloatNode(nkFloatLit, 0.1)])
+  let res = i.callRoutine(foreignProc, [newFloatNode(nkFloatLit, 0.9),
+                                        newFloatNode(nkFloatLit, 0.1)])
   doAssert res.kind == nkFloatLit
   echo res.floatVal
 
-  let foreignValue = selectUniqueSymbol(intr, "hostProgramWantsThis")
+  let foreignValue = i.selectUniqueSymbol("hostProgramWantsThis")
   if foreignValue == nil:
     quit "script does not export a global of the name: hostProgramWantsThis"
-  let val = intr.getGlobalValue(foreignValue)
+  let val = i.getGlobalValue(foreignValue)
   doAssert val.kind in {nkStrLit..nkTripleStrLit}
   echo val.strVal
-  destroyInterpreter(intr)
+  i.destroyInterpreter()
 
 main()
 
@@ -46,10 +49,50 @@ block issue9180:
   proc evalString(code: string, moduleName = "script.nim") =
     let stream = llStreamOpen(code)
     let std = findNimStdLibCompileTime()
-    var intr = createInterpreter(moduleName, [std])
+    var intr = createInterpreter(moduleName, [std, std / "pure", std / "core"])
     intr.evalScript(stream)
     destroyInterpreter(intr)
     llStreamClose(stream)
 
   evalString("echo 10+1")
   evalString("echo 10+2")
+
+block error_hook:
+  type VMQuit = object of CatchableError
+
+  let i = initInterpreter("invalid.nim")
+  i.registerErrorHook proc(config: ConfigRef; info: TLineInfo; msg: string;
+                           severity: Severity) {.gcsafe.} =
+    if severity == Error and config.errorCounter >= config.errorMax:
+      echo "raising VMQuit"
+      raise newException(VMQuit, "Script error")
+
+  doAssertRaises(VMQuit):
+    i.evalScript()
+
+block resetmacrocache:
+  let std = findNimStdLibCompileTime()
+  let intr = createInterpreter("script.nim", [std, std / "pure", std / "core"])
+  proc evalString(intr: Interpreter; code: string) =
+    let stream = llStreamOpen(code)
+    intr.evalScript(stream)
+    llStreamClose(stream)
+  let code = """
+import std/[macrocache, macros]
+static:
+  let counter = CacheCounter"valTest"
+  inc counter
+  assert counter.value == 1
+
+  const mySeq = CacheSeq"addTest"
+  mySeq.add(newLit(5))
+  mySeq.add(newLit("hello ic"))
+  assert mySeq.len == 2
+
+  const mcTable = CacheTable"subTest"
+  mcTable["toAdd"] = newStmtList() #would crash if not empty
+  assert mcTable.len == 1
+"""
+  intr.evalString(code)
+  intr.evalString(code)
+  destroyInterpreter(intr)
\ No newline at end of file
diff --git a/tests/compiles/mstaticlib.nim b/tests/compiles/mstaticlib.nim
new file mode 100644
index 000000000..6ed593691
--- /dev/null
+++ b/tests/compiles/mstaticlib.nim
@@ -0,0 +1 @@
+echo 1234
\ No newline at end of file
diff --git a/tests/compiles/t8630.nim b/tests/compiles/t8630.nim
index aa2be11cd..8b447d061 100644
--- a/tests/compiles/t8630.nim
+++ b/tests/compiles/t8630.nim
@@ -7,7 +7,7 @@ bar
 
 proc test(strings: seq[string]) =
   for s in strings:
-    var p3 = unsafeAddr(s)
+    var p3 = addr(s)
     echo p3[]
 
 test(@["foo", "bar"])
diff --git a/tests/compiles/trecursive_generic_in_compiles.nim b/tests/compiles/trecursive_generic_in_compiles.nim
index 88d3faeed..ab31ad0f5 100644
--- a/tests/compiles/trecursive_generic_in_compiles.nim
+++ b/tests/compiles/trecursive_generic_in_compiles.nim
@@ -50,7 +50,7 @@ proc `==`*[T](xs, ys: List[T]): bool =
 
 proc asList*[T](xs: varargs[T]): List[T] =
   ## Creates list from varargs
-  proc initListImpl(i: int, xs: openarray[T]): List[T] =
+  proc initListImpl(i: int, xs: openArray[T]): List[T] =
     if i > high(xs):
       Nil[T]()
     else:
diff --git a/tests/compiles/tstaticlib.nim b/tests/compiles/tstaticlib.nim
new file mode 100644
index 000000000..a18b59204
--- /dev/null
+++ b/tests/compiles/tstaticlib.nim
@@ -0,0 +1,22 @@
+import std/[os, osproc, strformat]
+
+
+const dir = "tests/compiles"
+const fileName = dir / "mstaticlib.nim"
+const nim = getCurrentCompilerExe()
+
+block: # bug #18578
+  const libName = dir / "tstaticlib1.a"
+  let (_, status) = execCmdEx(fmt"{nim} c -o:{libName} --app:staticlib {fileName}")
+  doAssert status == 0
+  doAssert fileExists(libName)
+  removeFile(libName)
+
+block: # bug #16947
+  const libName = dir / "tstaticlib2.a"
+  writeFile(libName, "echo 124")
+  doAssert fileExists(libName)
+  let (_, status) = execCmdEx(fmt"{nim} c -o:{libName} --app:staticlib {fileName}")
+  doAssert status == 0
+  doAssert fileExists(libName)
+  removeFile(libName)
diff --git a/tests/concepts/t18409.nim b/tests/concepts/t18409.nim
new file mode 100644
index 000000000..0edba2d31
--- /dev/null
+++ b/tests/concepts/t18409.nim
@@ -0,0 +1,37 @@
+discard """
+  action: "compile"
+"""
+
+# A vector space over a field F concept.
+type VectorSpace*[F] = concept x, y, type V
+  vector_add(x, y) is V
+  scalar_mul(x, F) is V
+  dimension(V) is Natural
+
+# Real numbers (here floats) form a vector space.
+func vector_add*(v: float, w: float): float =  v + w
+func scalar_mul*(v: float, s: float): float =   v * s
+func dimension*(x: typedesc[float]): Natural = 1
+
+# 2-tuples of real numbers form a vector space.
+func vector_add*(v, w: (float, float)): (float, float) =
+  (vector_add(v[0], w[0]), vector_add(v[1], w[1]))
+
+func scalar_mul*(v: (float, float), s: float): (float, float) =
+  (scalar_mul(v[0], s), scalar_mul(v[1], s))
+
+func dimension*(x: typedesc[(float, float)]): Natural = 2
+
+# Check concept requirements.
+assert float is VectorSpace
+assert (float, float) is VectorSpace
+
+# Commutivity axiom for vector spaces over the same field.
+func axiom_commutivity*[F](u, v: VectorSpace[F]): bool =
+  vector_add(u, v) == vector_add(v, u)
+
+# This is okay.
+assert axiom_commutivity(2.2, 3.3)
+
+# This is not.
+assert axiom_commutivity((2.2, 3.3), (4.4, 5.5))
diff --git a/tests/concepts/t19730.nim b/tests/concepts/t19730.nim
new file mode 100644
index 000000000..575d45dda
--- /dev/null
+++ b/tests/concepts/t19730.nim
@@ -0,0 +1,20 @@
+discard """
+  output: '''1.01.01.01.0
+1.01.01.01.0
+'''
+"""
+
+type
+  Color = concept c
+    c.r is SomeFloat
+    c.g is SomeFloat
+    c.b is SomeFloat
+    c.a is SomeFloat
+
+proc useColor(color: Color) =
+  echo(color.r, color.g, color.b, color.a)
+
+let color = (r: 1.0, g: 1.0, b: 1.0, a: 1.0)
+useColor(color)
+
+useColor((r: 1.0, g: 1.0, b: 1.0, a: 1.0))
diff --git a/tests/concepts/t20237.nim b/tests/concepts/t20237.nim
new file mode 100644
index 000000000..175c7a9d1
--- /dev/null
+++ b/tests/concepts/t20237.nim
@@ -0,0 +1,3 @@
+type Foo* = concept
+  ## doc comment
+  proc foo(x: Self)
diff --git a/tests/concepts/t3330.nim b/tests/concepts/t3330.nim
index 067e81133..901f8d2f4 100644
--- a/tests/concepts/t3330.nim
+++ b/tests/concepts/t3330.nim
@@ -1,55 +1,47 @@
 discard """
+matrix: "--mm:refc"
 errormsg: "type mismatch: got <Bar[system.int]>"
-disabled: "32bit"
 nimout: '''
-t3330.nim(78, 4) Error: type mismatch: got <Bar[system.int]>
+t3330.nim(70, 4) Error: type mismatch: got <Bar[system.int]>
 but expected one of:
 proc test(foo: Foo[int])
   first type mismatch at position: 1
   required type for foo: Foo[int]
   but expression 'bar' is of type: Bar[system.int]
-t3330.nim(63, 8) Hint: Non-matching candidates for add(k, string, T)
-proc add(x: var string; y: string)
+t3330.nim(55, 8) Hint: Non-matching candidates for add(k, string, T)
+proc add(x: var string; y: char)
   first type mismatch at position: 1
   required type for x: var string
   but expression 'k' is of type: Alias
-proc add[T](x: var seq[T]; y: openArray[T])
-  first type mismatch at position: 1
-  required type for x: var seq[T]
-  but expression 'k' is of type: Alias
-proc add(result: var string; x: float)
-  first type mismatch at position: 1
-  required type for result: var string
-  but expression 'k' is of type: Alias
-proc add[T](x: var seq[T]; y: T)
-  first type mismatch at position: 1
-  required type for x: var seq[T]
-  but expression 'k' is of type: Alias
 proc add(x: var string; y: cstring)
   first type mismatch at position: 1
   required type for x: var string
   but expression 'k' is of type: Alias
-proc add(x: var string; y: char)
+proc add(x: var string; y: string)
   first type mismatch at position: 1
   required type for x: var string
   but expression 'k' is of type: Alias
-proc add(result: var string; x: int64)
+proc add[T](x: var seq[T]; y: openArray[T])
+  first type mismatch at position: 1
+  required type for x: var seq[T]
+  but expression 'k' is of type: Alias
+proc add[T](x: var seq[T]; y: sink T)
   first type mismatch at position: 1
-  required type for result: var string
+  required type for x: var seq[T]
   but expression 'k' is of type: Alias
 
-t3330.nim(63, 8) template/generic instantiation of `add` from here
-t3330.nim(70, 6) Foo: 'bar.value' cannot be assigned to
-t3330.nim(63, 8) template/generic instantiation of `add` from here
-t3330.nim(71, 6) Foo: 'bar.x' cannot be assigned to
+t3330.nim(55, 8) template/generic instantiation of `add` from here
+t3330.nim(62, 6) Foo: 'bar.value' cannot be assigned to
+t3330.nim(55, 8) template/generic instantiation of `add` from here
+t3330.nim(63, 6) Foo: 'bar.x' cannot be assigned to
 
 expression: test(bar)'''
 """
 
-# Note: currently disabled on 32bit because the candidates are presented in
-# different order on travis with `NIM_COMPILE_TO_CPP=false CPU=i386`;
-# a possible fix would be to sort the candidates by proc signature or
-# declaration location
+
+
+
+
 
 
 
@@ -76,4 +68,3 @@ proc test(foo: Foo[int]) =
 
 var bar = Bar[int]()
 bar.test()
-
diff --git a/tests/concepts/t8012.nim b/tests/concepts/t8012.nim
new file mode 100644
index 000000000..ec2aa6e5c
--- /dev/null
+++ b/tests/concepts/t8012.nim
@@ -0,0 +1,15 @@
+type
+  MyTypeCon = concept c
+    c.counter is int
+  MyType = object
+    counter: int
+
+proc foo(conc: var MyTypeCon) =
+  conc.counter.inc
+  if conc.counter < 5:
+    foo(conc)
+
+var x: MyType
+
+x.foo
+discard x.repr
diff --git a/tests/concepts/t8558.nim b/tests/concepts/t8558.nim
new file mode 100644
index 000000000..acb2de30e
--- /dev/null
+++ b/tests/concepts/t8558.nim
@@ -0,0 +1,26 @@
+discard """
+  output: '''10
+9
+8
+7
+6
+5
+4
+3
+2
+1
+go!
+'''
+"""
+
+type Integral = concept x
+  x == 0 is bool
+  x - 1 is type(x)
+
+proc countToZero(n: Integral) =
+  if n == 0: echo "go!"
+  else:
+    echo n
+    countToZero(n-1)
+
+countToZero(10)
\ No newline at end of file
diff --git a/tests/concepts/t976.nim b/tests/concepts/t976.nim
new file mode 100644
index 000000000..776d53827
--- /dev/null
+++ b/tests/concepts/t976.nim
@@ -0,0 +1,57 @@
+discard """
+  output: '''
+Printable
+'''
+joinable: false
+"""
+
+#[
+  The converter is a proper example of a confounding variable
+  Moved to an isolated file
+]#
+
+type
+  Obj1[T] = object
+      v: T
+converter toObj1[T](t: T): Obj1[T] =
+  return Obj1[T](v: t)
+block t976:
+  type
+    int1 = distinct int
+    int2 = distinct int
+    int1g = concept x
+      x is int1
+    int2g = concept x
+      x is int2
+
+  proc take[T: int1g](value: int1) =
+    when T is int2:
+      static: error("killed in take(int1)")
+
+  proc take[T: int2g](vale: int2) =
+    when T is int1:
+      static: error("killed in take(int2)")
+
+  var i1: int1 = 1.int1
+  var i2: int2 = 2.int2
+
+  take[int1](i1)
+  take[int2](i2)
+
+  template reject(e) =
+    static: assert(not compiles(e))
+
+  reject take[string](i2)
+  reject take[int1](i2)
+
+  # bug #6249
+  type
+      Obj2 = ref object
+      PrintAble = concept x
+          $x is string
+
+  proc `$`[T](nt: Obj1[T]): string =
+      when T is PrintAble: result = "Printable"
+      else: result = "Non Printable"
+
+  echo Obj2()
\ No newline at end of file
diff --git a/tests/concepts/tconcepts.nim b/tests/concepts/tconcepts.nim
index d0bc76c20..ea3ddc401 100644
--- a/tests/concepts/tconcepts.nim
+++ b/tests/concepts/tconcepts.nim
@@ -31,6 +31,7 @@ e
 20
 10
 5
+9
 '''
 """
 
@@ -98,7 +99,7 @@ block tconceptinclosure:
 block overload_precedence:
   type ParameterizedType[T] = object
 
-  type CustomTypeClass = concept
+  type CustomTypeClass = concept c
     true
 
   # 3 competing procs
@@ -438,3 +439,13 @@ import mvarconcept
 block tvar:
   # bug #2346, bug #2404
   echo randomInt(5)
+
+block tcomment:
+  type
+    Foo = concept
+      ## Some comment
+      proc bar(x: Self)
+
+  proc bar(x: int) = echo x
+  proc foo(x: Foo) = x.bar
+  foo(9)
diff --git a/tests/concepts/tconcepts_issues.nim b/tests/concepts/tconcepts_issues.nim
index 65f6d4660..c6d0267c5 100644
--- a/tests/concepts/tconcepts_issues.nim
+++ b/tests/concepts/tconcepts_issues.nim
@@ -1,7 +1,6 @@
 discard """
   output: '''
 20.0 USD
-Printable
 true
 true
 true
@@ -27,6 +26,8 @@ false
 true
 -1
 Meow
+10 0.0
+1 2.0
 '''
 joinable: false
 """
@@ -76,55 +77,6 @@ block t3414:
   let s2 = s1.find(10)
 
 
-
-type
-  Obj1[T] = object
-      v: T
-converter toObj1[T](t: T): Obj1[T] =
-  return Obj1[T](v: t)
-block t976:
-  type
-    int1 = distinct int
-    int2 = distinct int
-    int1g = concept x
-      x is int1
-    int2g = concept x
-      x is int2
-
-  proc take[T: int1g](value: int1) =
-    when T is int2:
-      static: error("killed in take(int1)")
-
-  proc take[T: int2g](vale: int2) =
-    when T is int1:
-      static: error("killed in take(int2)")
-
-  var i1: int1 = 1.int1
-  var i2: int2 = 2.int2
-
-  take[int1](i1)
-  take[int2](i2)
-
-  template reject(e) =
-    static: assert(not compiles(e))
-
-  reject take[string](i2)
-  reject take[int1](i2)
-
-  # bug #6249
-  type
-      Obj2 = ref object
-      PrintAble = concept x
-          $x is string
-
-  proc `$`[T](nt: Obj1[T]): string =
-      when T is PrintAble: result = "Printable"
-      else: result = "Non Printable"
-
-  echo Obj2()
-
-
-
 block t1128:
   type
     TFooContainer[T] = object
@@ -324,15 +276,15 @@ block t6691:
 block t6782:
   type
     Reader = concept c
-      c.read(openarray[byte], int, int) is int
+      c.read(openArray[byte], int, int) is int
     Rdr = concept c
-      c.rd(openarray[byte], int, int) is int
+      c.rd(openArray[byte], int, int) is int
 
   type TestFile = object
 
-  proc read(r: TestFile, dest: openarray[byte], offset: int, limit: int): int =
+  proc read(r: TestFile, dest: openArray[byte], offset: int, limit: int): int =
       result = 0
-  proc rd(r: TestFile, dest: openarray[byte], offset: int, limit: int): int =
+  proc rd(r: TestFile, dest: openArray[byte], offset: int, limit: int): int =
       result = 0
 
   doAssert TestFile is Reader
@@ -397,7 +349,7 @@ block misc_issues:
   echo p2.x is float and p2.y is float # true
 
   # https://github.com/nim-lang/Nim/issues/2018
-  type ProtocolFollower = concept
+  type ProtocolFollower = concept c
     true # not a particularly involved protocol
 
   type ImplementorA = object
@@ -467,3 +419,138 @@ block misc_issues:
   # anyway and will be an error soon.
   var a: Cat = Cat()
   a.sayHello()
+
+
+# bug #16897
+
+type
+  Fp[N: static int, T] = object
+    big: array[N, T]
+
+type
+  QuadraticExt* = concept x
+    ## Quadratic Extension concept (like complex)
+    type BaseField = auto
+    x.c0 is BaseField
+    x.c1 is BaseField
+var address = pointer(nil)
+proc prod(r: var QuadraticExt, b: QuadraticExt) =
+  if address == nil:
+    address = addr b
+    prod(r, b)
+  else:
+    assert address == addr b
+
+type
+  Fp2[N: static int, T] {.byref.} = object
+    c0, c1: Fp[N, T]
+
+# This should be passed by reference,
+# but concepts do not respect the 24 bytes rule
+# or `byref` pragma.
+var r, b: Fp2[6, uint64]
+
+prod(r, b)
+
+
+block: # bug #21263
+  type
+    DateDayFraction = concept # no T, an atom
+      proc date(a: Self): int
+      proc fraction(b: Self): float
+    Date = distinct int
+    DateDayFractionImpl = object
+      date : int
+      fraction : float
+
+  proc date(a: Date): int = a.int
+  proc fraction(a:Date): float = 0.0
+
+  proc date(a: DateDayFractionImpl): int = a.date
+  proc fraction(b: DateDayFractionImpl): float = b.fraction
+
+
+  proc print(a: DateDayFraction) =
+    echo a.date, " ", a.fraction
+
+  print(10.Date) # ok
+  print(DateDayFractionImpl(date: 1, fraction: 2))  # error
+
+import sets
+import deques
+
+type AnyTree[V] = concept t, type T
+  for v in t.leaves(V):
+    v is V
+
+type BreadthOrder[V] = ref object
+  frontier: Deque[V]
+  visited: HashSet[V]
+
+proc expand[V, T](order: ref BreadthOrder[T], tree: AnyTree[V], node: V, transform: (V) -> (T)) =
+  for leaf in tree.leaves(node):
+    if not order.visited.containsOrIncl(transform(leaf)):
+      order.frontier.addLast(transform(leaf))
+
+proc hasNext[V](order: ref BreadthOrder[V]): bool =
+  order.frontier.len > 0
+
+proc init[V](_: typedesc[BreadthOrder]): ref BreadthOrder[V] =
+  result.new()
+  result[] = BreadthOrder[V](frontier: initDeque[V](), visited: initHashSet[V]())
+
+proc popNext[V](order: ref BreadthOrder[V]): V =
+  order.frontier.popFirst()
+
+type LevelNode[V] = tuple
+  depth: uint
+  node: V
+
+proc depthOf*[V](orderType: typedesc[BreadthOrder], tree: AnyTree[V], root, goal: V): uint =
+  if root == goal:
+    return 0
+  var order = init[LevelNode[V]](orderType)
+  order.expand(tree, root, (leaf) => (1.uint, leaf))
+  while order.hasNext():
+    let depthNode: LevelNode[V] = order.popNext()
+    if depthNode.node == goal:
+      return depthNode.depth
+    order.expand(tree, depthNode.node, (leaf) => (depthNode.depth + 1, leaf))
+
+type CappedStringTree = ref object
+  symbols: string
+  cap: Natural
+
+iterator leaves*(t: CappedStringTree, s: string): string =
+  if s.len < t.cap:
+    for c in t.symbols:
+      yield s & c
+
+block: # bug #12852
+  var tree = CappedStringTree(symbols: "^v><", cap: 5)
+
+  doAssert BreadthOrder.depthOf(tree, "", ">>>") == 3
+
+block: #bug #22723
+  type
+    Node  = concept n, type T 
+      for i in n.children:
+        i is T
+      n.parent is T
+
+    Nd = ref object
+      parent: Nd
+      children: seq[Nd]
+
+  proc addChild(parent, child: Node) =
+    parent.children.add(child)
+    child.parent = parent
+
+  proc foo =
+    var
+      a = Nd()
+      b = Nd()
+    a.addChild(b)
+    doAssert a.children.len == 1
+
+  foo()
diff --git a/tests/concepts/tconcepts_overload_precedence.nim b/tests/concepts/tconcepts_overload_precedence.nim
index 9eed6256a..c580d2688 100644
--- a/tests/concepts/tconcepts_overload_precedence.nim
+++ b/tests/concepts/tconcepts_overload_precedence.nim
@@ -9,7 +9,7 @@ x as CustomTypeClass'''
 
 type ParameterizedType[T] = object
 
-type CustomTypeClass = concept
+type CustomTypeClass = concept c
   true
 
 # 3 competing procs
diff --git a/tests/concepts/texplain.nim b/tests/concepts/texplain.nim
index 2b19c8b4d..8cf04ae82 100644
--- a/tests/concepts/texplain.nim
+++ b/tests/concepts/texplain.nim
@@ -1,106 +1,92 @@
 discard """
   cmd: "nim c --verbosity:0 --colors:off $file"
   nimout: '''
-texplain.nim(158, 10) Hint: Non-matching candidates for e(y)
+texplain.nim(162, 10) Hint: Non-matching candidates for e(y)
 proc e(i: int): int
   first type mismatch at position: 1
   required type for i: int
   but expression 'y' is of type: MatchingType
 
-texplain.nim(161, 7) Hint: Non-matching candidates for e(10)
+texplain.nim(165, 7) Hint: Non-matching candidates for e(10)
 proc e(o: ExplainedConcept): int
   first type mismatch at position: 1
   required type for o: ExplainedConcept
   but expression '10' is of type: int literal(10)
-texplain.nim(124, 6) ExplainedConcept: undeclared field: 'foo'
-texplain.nim(124, 6) ExplainedConcept: undeclared field: '.'
-texplain.nim(124, 6) ExplainedConcept: expression '.' cannot be called
-texplain.nim(124, 5) ExplainedConcept: concept predicate failed
-texplain.nim(125, 6) ExplainedConcept: undeclared field: 'bar'
-texplain.nim(125, 6) ExplainedConcept: undeclared field: '.'
-texplain.nim(125, 6) ExplainedConcept: expression '.' cannot be called
-texplain.nim(124, 5) ExplainedConcept: concept predicate failed
-
-texplain.nim(164, 10) Hint: Non-matching candidates for e(10)
+texplain.nim(128, 6) ExplainedConcept: undeclared field: 'foo'
+texplain.nim(128, 5) ExplainedConcept: concept predicate failed
+texplain.nim(129, 6) ExplainedConcept: undeclared field: 'bar'
+texplain.nim(128, 5) ExplainedConcept: concept predicate failed
+
+texplain.nim(168, 10) Hint: Non-matching candidates for e(10)
 proc e(o: ExplainedConcept): int
   first type mismatch at position: 1
   required type for o: ExplainedConcept
   but expression '10' is of type: int literal(10)
-texplain.nim(124, 6) ExplainedConcept: undeclared field: 'foo'
-texplain.nim(124, 6) ExplainedConcept: undeclared field: '.'
-texplain.nim(124, 6) ExplainedConcept: expression '.' cannot be called
-texplain.nim(124, 5) ExplainedConcept: concept predicate failed
-texplain.nim(125, 6) ExplainedConcept: undeclared field: 'bar'
-texplain.nim(125, 6) ExplainedConcept: undeclared field: '.'
-texplain.nim(125, 6) ExplainedConcept: expression '.' cannot be called
-texplain.nim(124, 5) ExplainedConcept: concept predicate failed
-
-texplain.nim(168, 20) Error: type mismatch: got <NonMatchingType>
+texplain.nim(128, 6) ExplainedConcept: undeclared field: 'foo'
+texplain.nim(128, 5) ExplainedConcept: concept predicate failed
+texplain.nim(129, 6) ExplainedConcept: undeclared field: 'bar'
+texplain.nim(128, 5) ExplainedConcept: concept predicate failed
+
+texplain.nim(172, 20) Error: type mismatch: got <NonMatchingType>
 but expected one of:
-proc e(o: ExplainedConcept): int
-  first type mismatch at position: 1
-  required type for o: ExplainedConcept
-  but expression 'n' is of type: NonMatchingType
-texplain.nim(168, 9) template/generic instantiation of `assert` from here
-texplain.nim(124, 5) ExplainedConcept: concept predicate failed
 proc e(i: int): int
   first type mismatch at position: 1
   required type for i: int
   but expression 'n' is of type: NonMatchingType
+proc e(o: ExplainedConcept): int
+  first type mismatch at position: 1
+  required type for o: ExplainedConcept
+  but expression 'n' is of type: NonMatchingType
+texplain.nim(172, 9) template/generic instantiation of `assert` from here
+texplain.nim(128, 5) ExplainedConcept: concept predicate failed
 
 expression: e(n)
-texplain.nim(169, 20) Error: type mismatch: got <NonMatchingType>
+texplain.nim(173, 20) Error: type mismatch: got <NonMatchingType>
 but expected one of:
+proc r(i: string): int
+  first type mismatch at position: 1
+  required type for i: string
+  but expression 'n' is of type: NonMatchingType
 proc r(o: RegularConcept): int
   first type mismatch at position: 1
   required type for o: RegularConcept
   but expression 'n' is of type: NonMatchingType
-texplain.nim(169, 9) template/generic instantiation of `assert` from here
-texplain.nim(128, 5) RegularConcept: concept predicate failed
+texplain.nim(173, 9) template/generic instantiation of `assert` from here
+texplain.nim(132, 5) RegularConcept: concept predicate failed
 proc r[T](a: SomeNumber; b: T; c: auto)
   first type mismatch at position: 1
   required type for a: SomeNumber
   but expression 'n' is of type: NonMatchingType
+
+expression: r(n)
+texplain.nim(174, 20) Hint: Non-matching candidates for r(y)
 proc r(i: string): int
   first type mismatch at position: 1
   required type for i: string
-  but expression 'n' is of type: NonMatchingType
-
-expression: r(n)
-texplain.nim(170, 20) Hint: Non-matching candidates for r(y)
+  but expression 'y' is of type: MatchingType
 proc r[T](a: SomeNumber; b: T; c: auto)
   first type mismatch at position: 1
   required type for a: SomeNumber
   but expression 'y' is of type: MatchingType
-proc r(i: string): int
-  first type mismatch at position: 1
-  required type for i: string
-  but expression 'y' is of type: MatchingType
 
-texplain.nim(178, 2) Error: type mismatch: got <MatchingType>
+texplain.nim(182, 2) Error: type mismatch: got <MatchingType>
 but expected one of:
 proc f(o: NestedConcept)
   first type mismatch at position: 1
   required type for o: NestedConcept
   but expression 'y' is of type: MatchingType
-texplain.nim(128, 6) RegularConcept: undeclared field: 'foo'
-texplain.nim(128, 6) RegularConcept: undeclared field: '.'
-texplain.nim(128, 6) RegularConcept: expression '.' cannot be called
-texplain.nim(128, 5) RegularConcept: concept predicate failed
-texplain.nim(129, 6) RegularConcept: undeclared field: 'bar'
-texplain.nim(129, 6) RegularConcept: undeclared field: '.'
-texplain.nim(129, 6) RegularConcept: expression '.' cannot be called
-texplain.nim(128, 5) RegularConcept: concept predicate failed
-texplain.nim(132, 5) NestedConcept: concept predicate failed
+texplain.nim(132, 6) RegularConcept: undeclared field: 'foo'
+texplain.nim(132, 5) RegularConcept: concept predicate failed
+texplain.nim(133, 6) RegularConcept: undeclared field: 'bar'
+texplain.nim(132, 5) RegularConcept: concept predicate failed
+texplain.nim(136, 5) NestedConcept: concept predicate failed
 
 expression: f(y)'''
   errormsg: "type mismatch: got <MatchingType>"
-  line: 178
-
-  disabled: 32bit
 """
 
-# disabled on 32 bit, because the order of suggested alternatives ``r`` differs
+
+
 # proc r[T](a: SomeNumber; b: T; c: auto)
 # proc r(i: string): int
 # proc r(o: RegularConcept): int
@@ -117,7 +103,25 @@ expression: f(y)'''
 
 
 
-# line 120 HERE
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# line 124 HERE
 
 type
   ExplainedConcept {.explain.} = concept o
diff --git a/tests/concepts/tmapconcept.nim b/tests/concepts/tmapconcept.nim
index 6b959eff2..cc99737df 100644
--- a/tests/concepts/tmapconcept.nim
+++ b/tests/concepts/tmapconcept.nim
@@ -78,7 +78,7 @@ proc getFirstValue[K,V](m : Map[K,V]): V =
   for i in m.valuesSeq:
     return i
 
-  raise newException(RangeError, "no values")
+  raise newException(RangeDefect, "no values")
 
 proc useConceptProcInGeneric[K, V](t: Table[K, V]): V =
   return t.getFirstValue
diff --git a/tests/concepts/treversable.nim b/tests/concepts/treversable.nim
index 6ebc077d9..d30ba0a3c 100644
--- a/tests/concepts/treversable.nim
+++ b/tests/concepts/treversable.nim
@@ -3,7 +3,7 @@ discard """
   output: '''
 z
 e
-  '''
+'''
 """
 
 type
diff --git a/tests/concepts/tspec.nim b/tests/concepts/tspec.nim
new file mode 100644
index 000000000..52f13a40a
--- /dev/null
+++ b/tests/concepts/tspec.nim
@@ -0,0 +1,105 @@
+discard """
+  output: '''4
+0
+4
+4
+1
+2
+3
+yes int
+string int'''
+  joinable: false
+"""
+
+import hashes
+
+type
+  Comparable = concept # no T, an atom
+    proc cmp(a, b: Self): int
+
+  ToStringable = concept
+    proc `$`(a: Self): string
+
+  Hashable = concept   ## the most basic of identity assumptions
+    proc hash(x: Self): int
+    proc `==`(x, y: Self): bool
+
+  Swapable = concept
+    proc swap(x, y: var Self)
+
+
+proc h(x: Hashable) =
+  echo x
+
+h(4)
+
+when true:
+  proc compare(a: Comparable) =
+    echo cmp(a, a)
+
+  compare(4)
+
+proc dollar(x: ToStringable) =
+  echo x
+
+when true:
+  dollar 4
+  dollar "4"
+
+#type D = distinct int
+
+#dollar D(4)
+
+when true:
+  type
+    Iterable[Ix] = concept
+      iterator items(c: Self): Ix
+
+  proc g[Tu](it: Iterable[Tu]) =
+    for x in it:
+      echo x
+
+  g(@[1, 2, 3])
+
+proc hs(x: Swapable) =
+  var y = x
+  swap y, y
+
+hs(4)
+
+type
+  Indexable[T] = concept # has a T, a collection
+    proc `[]`(a: Self; index: int): T # we need to describe how to infer 'T'
+    # and then we can use the 'T' and it must match:
+    proc `[]=`(a: var Self; index: int; value: T)
+    proc len(a: Self): int
+
+proc indexOf[T](a: Indexable[T]; value: T) =
+  echo "yes ", T
+
+block:
+  var x = @[1, 2, 3]
+  indexOf(x, 4)
+
+import tables, typetraits
+
+type
+  Dict[K, V] = concept
+    proc `[]`(s: Self; k: K): V
+    proc `[]=`(s: var Self; k: K; v: V)
+
+proc d[K2, V2](x: Dict[K2, V2]) =
+  echo K2, " ", V2
+
+var x = initTable[string, int]()
+d(x)
+
+
+type Monoid = concept
+  proc `+`(x, y: Self): Self
+  proc z(t: typedesc[Self]): Self
+
+proc z(x: typedesc[int]): int = 0
+
+doAssert int is Monoid
+
diff --git a/tests/concepts/tusertypeclasses.nim b/tests/concepts/tusertypeclasses.nim
index c7104f2a6..83e2b176e 100644
--- a/tests/concepts/tusertypeclasses.nim
+++ b/tests/concepts/tusertypeclasses.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   output: '''Sortable
 Sortable
 Container
@@ -9,6 +10,8 @@ int
 '''
 """
 
+# todo wait for https://github.com/nim-lang/Nim/pull/20380
+
 import typetraits
 
 template reject(expr) = assert(not compiles(x))
diff --git a/tests/concepts/tusertypeclasses2.nim b/tests/concepts/tusertypeclasses2.nim
index ae05540cd..6132bc2d8 100644
--- a/tests/concepts/tusertypeclasses2.nim
+++ b/tests/concepts/tusertypeclasses2.nim
@@ -1,24 +1,63 @@
-type
-  hasFieldX = concept z
-    z.x is int
+discard """
+  targets: "c js"
+"""
 
-  obj_x = object
-    x: int
+block:
+  type
+    hasFieldX = concept z
+      z.x is int
 
-  ref_obj_x = ref object
-    x: int
+    obj_x = object
+      x: int
 
-  ref_to_obj_x = ref obj_x
+    ref_obj_x = ref object
+      x: int
 
-  p_o_x = ptr obj_x
-  v_o_x = var obj_x
+    ref_to_obj_x = ref obj_x
 
-template check(x) =
-  static: assert(x)
+    p_o_x = ptr obj_x
+    v_o_x = var obj_x
 
-check obj_x is hasFieldX
-check ref_obj_x is hasFieldX
-check ref_to_obj_x is hasFieldX
-check p_o_x is hasFieldX
-check v_o_x is hasFieldX
+  template check(x) =
+    static: assert(x)
 
+  check obj_x is hasFieldX
+  check ref_obj_x is hasFieldX
+  check ref_to_obj_x is hasFieldX
+  check p_o_x is hasFieldX
+  check v_o_x is hasFieldX
+
+block:
+  type
+    Foo = concept x
+      x.isFoo
+    Bar = distinct float
+  template isFoo(x: Bar): untyped = true
+  proc foo(x: var Foo) =
+    float(x) = 1.0
+  proc foo2(x: var Bar) =
+    float(x) = 1.0
+  proc foo3(x: var (Bar|SomeNumber)) =
+    float(x) = 1.0
+  proc foo4(x: var any) =
+    float(x) = 1.0
+  var x: Bar
+  foo(x)
+  foo2(x)
+  foo3(x)
+  foo4(x)
+
+block: # bug #9550
+  block:
+    type Foo = concept c
+      for v in c: (v is char)
+
+    func foo(c: Foo) = (for v in c: discard)
+    foo @['a', 'b' ,'c']
+
+  block:
+    type Foo = concept c
+      for v in c: (v is char)
+
+    func foo(c: Foo) = (for v in c: discard)
+    foo ['a', 'b' ,'c']
diff --git a/tests/concepts/twrapconcept.nim b/tests/concepts/twrapconcept.nim
index 377b63afe..c3dea2ff9 100644
--- a/tests/concepts/twrapconcept.nim
+++ b/tests/concepts/twrapconcept.nim
@@ -1,7 +1,6 @@
 discard """
   errormsg: "type mismatch: got <string>"
-  line: 21
-  nimout: "twrapconcept.nim(11, 5) Foo: concept predicate failed"
+  nimout: "twrapconcept.nim(10, 5) Foo: concept predicate failed"
 """
 
 # https://github.com/nim-lang/Nim/issues/5127
diff --git a/tests/config.nims b/tests/config.nims
index cd4ee4b08..0b2b66d81 100644
--- a/tests/config.nims
+++ b/tests/config.nims
@@ -1,7 +1,49 @@
-switch("path", "$nim/testament/lib") # so we can `import stdtest/foo` in this dir
+switch("path", "$lib/../testament/lib")
+  # so we can `import stdtest/foo` inside tests
+  # Using $lib/../ instead of $nim/ so you can use a different nim to run tests
+  # during local testing, e.g. nim --lib:lib.
 
 ## prevent common user config settings to interfere with testament expectations
 ## Indifidual tests can override this if needed to test for these options.
 switch("colors", "off")
-switch("listFullPaths", "off")
+
 switch("excessiveStackTrace", "off")
+
+when (NimMajor, NimMinor, NimPatch) >= (1,5,1):
+  # to make it easier to test against older nim versions, (best effort only)
+  switch("filenames", "legacyRelProj")
+  switch("spellSuggest", "0")
+
+# for std/unittest
+switch("define", "nimUnittestOutputLevel:PRINT_FAILURES")
+switch("define", "nimUnittestColor:off")
+
+switch("define", "nimLegacyTypeMismatch")
+
+hint("Processing", off)
+  # dots can cause annoyances; instead, a single test can test `hintProcessing`
+
+# uncomment to enable all flaky tests disabled by this flag
+# (works through process calls, e.g. tests that invoke nim).
+# switch("define", "nimTestsEnableFlaky")
+
+# switch("hint", "ConvFromXtoItselfNotNeeded")
+# switch("warningAsError", "InheritFromException") # would require fixing a few tests
+
+# experimental APIs are enabled in testament, refs https://github.com/timotheecour/Nim/issues/575
+# sync with `kochdocs.docDefines` or refactor.
+switch("define", "nimExperimentalLinenoiseExtra")
+
+# preview APIs are expected to be the new default in upcoming versions
+switch("define", "nimPreviewFloatRoundtrip")
+#switch("define", "nimPreviewDotLikeOps") # deprecated?
+switch("define", "nimPreviewJsonutilsHoleyEnum")
+switch("define", "nimPreviewHashRef")
+switch("define", "nimPreviewRangeDefault")
+switch("define", "nimPreviewNonVarDestructor")
+
+switch("warningAserror", "UnnamedBreak")
+when not defined(testsConciseTypeMismatch):
+  switch("legacy", "verboseTypeMismatch")
+switch("experimental", "vtables")
+switch("experimental", "openSym")
diff --git a/tests/constr/tglobal.nim b/tests/constr/tglobal.nim
deleted file mode 100644
index 056ac9f81..000000000
--- a/tests/constr/tglobal.nim
+++ /dev/null
@@ -1,7 +0,0 @@
-discard """
-output: "0"
-"""
-
-# b.nim
-import a_module
-echo foo()
\ No newline at end of file
diff --git a/tests/constructors/a.nim b/tests/constructors/a.nim
new file mode 100644
index 000000000..03788fc57
--- /dev/null
+++ b/tests/constructors/a.nim
@@ -0,0 +1,2 @@
+type A* = object
+  a: uint8
\ No newline at end of file
diff --git a/tests/constructors/b.nim b/tests/constructors/b.nim
new file mode 100644
index 000000000..437dd0550
--- /dev/null
+++ b/tests/constructors/b.nim
@@ -0,0 +1,2 @@
+type B* = object
+proc A*(a, b: float): B = discard
\ No newline at end of file
diff --git a/tests/constructors/t18990.nim b/tests/constructors/t18990.nim
new file mode 100644
index 000000000..2f60f3c2c
--- /dev/null
+++ b/tests/constructors/t18990.nim
@@ -0,0 +1,3 @@
+import a, b
+discard A(1f, 1f) # works
+proc x(b = A(1f, 1f)) = discard # doesn't work
\ No newline at end of file
diff --git a/tests/constr/tconstr1.nim b/tests/constructors/tconstr1.nim
index a169bf453..a169bf453 100644
--- a/tests/constr/tconstr1.nim
+++ b/tests/constructors/tconstr1.nim
diff --git a/tests/constr/tconstr2.nim b/tests/constructors/tconstr2.nim
index 2557d7db9..2557d7db9 100644
--- a/tests/constr/tconstr2.nim
+++ b/tests/constructors/tconstr2.nim
diff --git a/tests/constructors/tinvalid_construction.nim b/tests/constructors/tinvalid_construction.nim
index b3e56eec6..4b372d68a 100644
--- a/tests/constructors/tinvalid_construction.nim
+++ b/tests/constructors/tinvalid_construction.nim
@@ -3,11 +3,16 @@ template accept(x) =
 
 template reject(x) =
   static: assert(not compiles(x))
+
 {.experimental: "notnil".}
+
 type
   TRefObj = ref object
     x: int
 
+  IllegalToConstruct = object
+    x: cstring not nil
+
   THasNotNils = object of RootObj
     a: TRefObj not nil
     b: TRefObj not nil
@@ -15,6 +20,8 @@ type
 
   THasNotNilsRef = ref THasNotNils
 
+  TRefObjNotNil = TRefObj not nil
+
   TChoice = enum A, B, C, D, E, F
 
   TBaseHasNotNils = object of THasNotNils
@@ -26,6 +33,22 @@ type
     else:
       discard
 
+  PartialRequiresInit = object
+    a {.requiresInit.}: int
+    b: string
+
+  PartialRequiresInitRef = ref PartialRequiresInit
+
+  FullRequiresInit {.requiresInit.} = object
+    a: int
+    b: int
+
+  FullRequiresInitRef = ref FullRequiresInit
+
+  FullRequiresInitWithParent {.requiresInit.} = object of THasNotNils
+    e: int
+    d: int
+
   TObj = object
     case choice: TChoice
     of A:
@@ -55,11 +78,23 @@ type
 
 var x = D
 var nilRef: TRefObj
-var notNilRef = TRefObj(x: 20)
+let notNilRef = TRefObjNotNil(x: 20)
 
 proc makeHasNotNils: ref THasNotNils =
-  result.a = TRefObj(x: 10)
-  result.b = TRefObj(x: 20)
+  (ref THasNotNils)(a: TRefObj(x: 10),
+                    b: TRefObj(x: 20))
+
+proc userDefinedDefault(T: typedesc): T =
+  # We'll use that to make sure the user cannot cheat
+  # with constructing requiresInit types
+  discard
+
+proc genericDefault(T: typedesc): T =
+  result = default(T)
+
+reject IllegalToConstruct()
+reject:
+  var x: IllegalToConstruct
 
 accept TObj()
 accept TObj(choice: A)
@@ -74,14 +109,22 @@ reject TObj(a: 10, f: "")       # conflicting fields
 accept TObj(choice: E, e1: TRefObj(x: 10), e2: 10)
 
 accept THasNotNils(a: notNilRef, b: notNilRef, c: nilRef)
-# XXX: the "not nil" logic in the compiler is not strong enough to catch this one yet:
-# reject THasNotNils(a: notNilRef, b: nilRef, c: nilRef)
+reject THasNotNils(a: notNilRef, b: nilRef, c: nilRef)      # `b` shouldn't be nil
 reject THasNotNils(b: notNilRef, c: notNilRef)              # there is a missing not nil field
 reject THasNotNils()                                        # again, missing fields
 accept THasNotNils(a: notNilRef, b: notNilRef)              # it's OK to omit a non-mandatory field
+# produces only warning: reject default(THasNotNils)
+# produces only warning: reject userDefinedDefault(THasNotNils)
+
+# produces only warning: reject default(TRefObjNotNil)
+# produces only warning: reject userDefinedDefault(TRefObjNotNil)
+# produces only warning: reject genericDefault(TRefObjNotNil)
 
 # missing not nils in base
 reject TBaseHasNotNils()
+# produces only warning: reject default(TBaseHasNotNils)
+# produces only warning: reject userDefinedDefault(TBaseHasNotNils)
+# produces only warning: reject genericDefault(TBaseHasNotNils)
 
 # once you take care of them, it's ok
 accept TBaseHasNotNils(a: notNilRef, b: notNilRef, choice: D)
@@ -106,8 +149,118 @@ accept TBaseHasNotNils(a: notNilRef, b: notNilRef, choice: B, indirectNotNils: m
 reject TBaseHasNotNils(a: notNilRef, b: notNilRef, choice: B, indirectNotNils: THasNotNilsRef())
 accept TBaseHasNotNils(a: notNilRef, b: notNilRef, choice: B, indirectNotNils: THasNotNilsRef(a: notNilRef, b: notNilRef))
 
+# Accept only instances where the `a` field is present
+accept PartialRequiresInit(a: 10, b: "x")
+accept PartialRequiresInit(a: 20)
+reject PartialRequiresInit(b: "x")
+reject PartialRequiresInit()
+accept PartialRequiresInitRef(a: 10, b: "x")
+accept PartialRequiresInitRef(a: 20)
+reject PartialRequiresInitRef(b: "x")
+reject PartialRequiresInitRef()
+accept((ref PartialRequiresInit)(a: 10, b: "x"))
+accept((ref PartialRequiresInit)(a: 20))
+reject((ref PartialRequiresInit)(b: "x"))
+reject((ref PartialRequiresInit)())
+
+# produces only warning: reject default(PartialRequiresInit)
+# produces only warning: reject userDefinedDefault(PartialRequiresInit)
+reject:
+  var obj: PartialRequiresInit
+
+accept FullRequiresInit(a: 10, b: 20)
+reject FullRequiresInit(a: 10)
+reject FullRequiresInit(b: 20)
+reject FullRequiresInit()
+accept FullRequiresInitRef(a: 10, b: 20)
+reject FullRequiresInitRef(a: 10)
+reject FullRequiresInitRef(b: 20)
+reject FullRequiresInitRef()
+accept((ref FullRequiresInit)(a: 10, b: 20))
+reject((ref FullRequiresInit)(a: 10))
+reject((ref FullRequiresInit)(b: 20))
+reject((ref FullRequiresInit)())
+
+# produces only warning: reject default(FullRequiresInit)
+# produces only warning: reject userDefinedDefault(FullRequiresInit)
+reject:
+  var obj: FullRequiresInit
+
+accept FullRequiresInitWithParent(a: notNilRef, b: notNilRef, c: notNilRef, e: 10, d: 20)
+accept FullRequiresInitWithParent(a: notNilRef, b: notNilRef, c: nil, e: 10, d: 20)
+reject FullRequiresInitWithParent(a: notNilRef, b: nil, c: nil, e: 10, d: 20) # b should not be nil
+reject FullRequiresInitWithParent(a: notNilRef, b: notNilRef, e: 10, d: 20)   # c should not be missing
+reject FullRequiresInitWithParent(a: notNilRef, b: notNilRef, c: nil, e: 10)  # d should not be missing
+reject FullRequiresInitWithParent()
+# produces only warning: reject default(FullRequiresInitWithParent)
+# produces only warning: reject userDefinedDefault(FullRequiresInitWithParent)
+reject:
+  var obj: FullRequiresInitWithParent
+
 # this will be accepted, because the false outer branch will be taken and the inner A branch
 accept TNestedChoices()
+accept default(TNestedChoices)
+accept:
+  var obj: TNestedChoices
+
+#[# produces only warning:
+reject:
+  # This proc is illegal, because it tries to produce
+  # a default object of a type that requires initialization:
+  proc defaultHasNotNils: THasNotNils =
+    discard
+#]#
+
+#[# produces only warning:
+reject:
+  # You cannot cheat by using the result variable to specify
+  # only some of the fields
+  proc invalidPartialTHasNotNils: THasNotNils =
+    result.c = nilRef
+#]#
+
+#[# produces only warning:
+reject:
+  # The same applies for requiresInit types
+  proc invalidPartialRequiersInit: PartialRequiresInit =
+    result.b = "x"
+#]#
+
+#[# produces only warning:
+# All code paths must return a value when the result requires initialization:
+reject:
+  proc ifWithoutAnElse: THasNotNils =
+    if stdin.readLine == "":
+      return THasNotNils(a: notNilRef, b: notNilRef, c: nilRef)
+#]#
+
+accept:
+  # All code paths must return a value when the result requires initialization:
+  proc wellFormedIf: THasNotNils =
+    if stdin.readLine == "":
+      return THasNotNils(a: notNilRef, b: notNilRef, c: nilRef)
+    else:
+      return THasNotNIls(a: notNilRef, b: notNilRef)
+
+#[# produces only warning:
+reject:
+  proc caseWithoutAllCasesCovered: FullRequiresInit =
+    # Please note that these is no else branch here:
+    case stdin.readLine
+    of "x":
+      return FullRequiresInit(a: 10, b: 20)
+    of "y":
+      return FullRequiresInit(a: 30, b: 40)
+#]#
+
+accept:
+  proc wellFormedCase: FullRequiresInit =
+    case stdin.readLine
+    of "x":
+      result = FullRequiresInit(a: 10, b: 20)
+    else:
+      # Mixing result and return is fine:
+      return FullRequiresInit(a: 30, b: 40)
 
 # but if we supply a run-time value for the inner branch, the compiler won't be able to prove
 # that the notnil field was initialized
@@ -120,3 +273,167 @@ reject TNestedChoices(outerChoice: false, innerChoice: C)
 accept TNestedChoices(outerChoice: false, innerChoice: C, notnil: notNilRef)
 reject TNestedChoices(outerChoice: false, innerChoice: C, notnil: nil)
 
+# Tests involving generics and sequences:
+#
+block:
+  # This test aims to show that it's possible to instantiate and
+  # use a sequence with a requiresInit type:
+
+  var legalSeq: seq[IllegalToConstruct]
+  legalSeq.add IllegalToConstruct(x: "one")
+  var two = IllegalToConstruct(x: "two")
+  legalSeq.add two
+  var one = legalSeq[0]
+  var twoAgain = legalSeq.pop
+
+  #[# produces only warning:
+  # It's not possible to tell the sequence to create elements
+  # for us though:
+  reject:
+    var illegalSeq = newSeq[IllegalToConstruct](10)
+  #]#
+
+  #[# produces only warning:
+  reject:
+    var illegalSeq: seq[IllegalToConstruct]
+    newSeq(illegalSeq, 10)
+  #]#
+
+  #[# produces only warning:
+  reject:
+    var illegalSeq: seq[IllegalToConstruct]
+    illegalSeq.setLen 10
+  #]#
+
+  # You can still use newSeqOfCap to write efficient code:
+  var anotherLegalSequence = newSeqOfCap[IllegalToConstruct](10)
+  for i in 0..9:
+    anotherLegalSequence.add IllegalToConstruct(x: "x")
+
+type DefaultConstructible[yesOrNo: static[bool]] = object
+  when yesOrNo:
+    x: string
+  else:
+    x: cstring not nil
+
+block:
+  # Constructability may also depend on the generic parameters of the type:
+  accept:
+    var a: DefaultConstructible[true]
+    var b = DefaultConstructible[true]()
+    var c = DefaultConstructible[true](x: "test")
+    var d = DefaultConstructible[false](x: "test")
+
+  reject:
+    var y: DefaultConstructible[false]
+
+  reject:
+    var y = DefaultConstructible[false]()
+
+block:
+  type
+    Hash = int
+
+    HashTableSlotType = enum
+      Free    = Hash(0)
+      Deleted = Hash(1)
+      HasKey  = Hash(2)
+
+    KeyValuePair[A, B] = object
+      key: A
+      case hash: HashTableSlotType
+      of Free, Deleted:
+        discard
+      else:
+        value: B
+
+  # The above KeyValuePair is an interesting type because it
+  # may become unconstructible depending on the generic parameters:
+  accept KeyValuePair[int, string](hash: Deleted)
+  accept KeyValuePair[int, IllegalToConstruct](hash: Deleted)
+
+  accept KeyValuePair[int, string](hash: HasKey)
+  reject KeyValuePair[int, IllegalToConstruct](hash: HasKey)
+
+  # Since all the above variations don't have a non-constructible
+  # field in the default branch of the case object, we can construct
+  # such values:
+  accept KeyValuePair[int, string]()
+  accept KeyValuePair[int, IllegalToConstruct]()
+  accept KeyValuePair[DefaultConstructible[true], string]()
+  accept KeyValuePair[DefaultConstructible[true], IllegalToConstruct]()
+
+  var a: KeyValuePair[int, string]
+  var b: KeyValuePair[int, IllegalToConstruct]
+  var c: KeyValuePair[DefaultConstructible[true], string]
+  var d: KeyValuePair[DefaultConstructible[true], IllegalToConstruct]
+  var s1 = newSeq[KeyValuePair[int, IllegalToConstruct]](10)
+  var s2 = newSeq[KeyValuePair[DefaultConstructible[true], IllegalToConstruct]](10)
+
+  # But let's put the non-constructible values as keys:
+  reject KeyValuePair[IllegalToConstruct, int](hash: Deleted)
+  reject KeyValuePair[IllegalToConstruct, int]()
+
+  type IllegalPair = KeyValuePair[DefaultConstructible[false], string]
+
+  reject:
+    var x: IllegalPair
+
+  #[# produces only warning:
+  reject:
+    var s = newSeq[IllegalPair](10)
+  #]#
+
+# Specific issues:
+#
+block:
+  # https://github.com/nim-lang/Nim/issues/11428
+  type
+    Enum = enum A, B, C
+    Thing = object
+      case kind: Enum
+      of A: discard
+      of B: s: string
+      of C: r: range[1..1] # DateTime
+
+  # Fine to not initialize 'r' because this is implicitly initialized and known to be branch 'A'.
+  var x = Thing()
+  discard x
+
+block:
+  # https://github.com/nim-lang/Nim/issues/4907
+  type
+    Foo = ref object
+    Bar = object
+
+    Thing[A, B] = ref object
+      a: A not nil
+      b: ref B
+      c: ref B not nil
+
+  proc allocNotNil(T: typedesc): T not nil =
+    new result
+
+  proc mutateThing(t: var Thing[Foo, Bar]) =
+    let fooNotNil = allocNotNil(Foo)
+    var foo: Foo
+
+    let barNotNil = allocNotNil(ref Bar)
+    var bar: ref Bar
+
+    t.a = fooNotNil
+    t.b = bar
+    t.b = barNotNil
+    t.c = barNotNil
+
+    reject:
+      t.a = foo
+
+    reject:
+      t.c = bar
+
+  var thing = Thing[Foo, Bar](a: allocNotNil(Foo),
+                              b: allocNotNil(ref Bar),
+                              c: allocNotNil(ref Bar))
+  mutateThing thing
+
diff --git a/tests/controlflow/tcontrolflow.nim b/tests/controlflow/tcontrolflow.nim
index 258f3f50d..dd21a2bb6 100644
--- a/tests/controlflow/tcontrolflow.nim
+++ b/tests/controlflow/tcontrolflow.nim
@@ -19,7 +19,7 @@ block tbreak:
     run = false
     block myblock:
       if true:
-        break
+        break myblock
       echo "leaving myblock"
     x = true
   doAssert(x)
@@ -95,3 +95,22 @@ block tnestif:
   else:
       writeLine(stdout, "looks like Python")
   #OUT i == 2
+
+# bug https://github.com/nim-lang/RFCs/issues/451
+for i in 1..2: # works
+  break
+
+block: # works
+  for i in 1..2:
+    break
+
+block: # works
+  block:
+    discard 12 + 3
+  for i in 1..2:
+    break
+
+block named: # works
+  if true:
+    break named
+  doAssert false, "not reached"
diff --git a/tests/controlflow/tstatret.nim b/tests/controlflow/tstatret.nim
index e0f816c7d..a3558e6f4 100644
--- a/tests/controlflow/tstatret.nim
+++ b/tests/controlflow/tstatret.nim
@@ -1,7 +1,7 @@
 discard """
-  errormsg: "unreachable statement after 'return' statement or '{.noReturn.}' proc"
-  file: "tstatret.nim"
-  line: 9
+  nimout: '''
+tstatret.nim(9, 7) Warning: unreachable code after 'return' statement or '{.noReturn.}' proc [UnreachableCode]
+'''
 """
 # no statement after return
 proc main() =
diff --git a/tests/controlflow/tunamedbreak.nim b/tests/controlflow/tunamedbreak.nim
new file mode 100644
index 000000000..46113cabc
--- /dev/null
+++ b/tests/controlflow/tunamedbreak.nim
@@ -0,0 +1,15 @@
+
+discard """
+  cmd: "nim check $file"
+  action: "reject"
+  nimout: '''
+tunamedbreak.nim(12, 5) Error: Using an unnamed break in a block is deprecated; Use a named block with a named break instead [UnnamedBreak]
+tunamedbreak.nim(15, 3) Error: Using an unnamed break in a block is deprecated; Use a named block with a named break instead [UnnamedBreak]
+  '''
+"""
+for i in 1..2: # errors
+  block:
+    break
+
+block: # errors
+  break
diff --git a/tests/controlflow/tunreachable.nim b/tests/controlflow/tunreachable.nim
new file mode 100644
index 000000000..06321ce8a
--- /dev/null
+++ b/tests/controlflow/tunreachable.nim
@@ -0,0 +1,79 @@
+discard """
+  cmd: "nim check --warningAsError:UnreachableCode $file"
+  action: "reject"
+  nimout: '''
+tunreachable.nim(26, 3) Error: unreachable code after 'return' statement or '{.noReturn.}' proc [UnreachableCode]
+tunreachable.nim(33, 3) Error: unreachable code after 'return' statement or '{.noReturn.}' proc [UnreachableCode]
+tunreachable.nim(42, 3) Error: unreachable code after 'return' statement or '{.noReturn.}' proc [UnreachableCode]
+tunreachable.nim(65, 5) Error: unreachable code after 'return' statement or '{.noReturn.}' proc [UnreachableCode]
+tunreachable.nim(77, 5) Error: unreachable code after 'return' statement or '{.noReturn.}' proc [UnreachableCode]
+'''
+"""
+  
+# bug #9839
+template myquit1():untyped=
+  ## foo
+  quit(1)
+template myquit2():untyped=
+  echo 123
+  myquit1()
+
+proc main1()=
+
+  # BUG: uncommenting this doesn't give `Error: unreachable statement`
+  myquit2()
+
+  echo "after"
+
+main1()
+
+proc main2() =
+  myquit1()
+
+  echo "after"
+
+main2()
+
+proc main3() =
+  if true:
+    return
+  else:
+    return
+  echo "after"
+
+main3()
+
+
+block:
+  # Cases like strings are not checked for exhaustiveness unless they have an else
+  proc main4(x: string) =
+    case x
+    of "a":
+      return
+    # reachable
+    echo "after"
+
+  main4("a")
+
+  proc main5(x: string) =
+    case x
+    of "a":
+      return
+    else:
+      return
+    # unreachable
+    echo "after"
+
+  main5("a")
+
+block:
+  # In this case no else is needed because it's exhaustive
+  proc exhaustive(x: bool) =
+    case x
+    of true:
+      return
+    of false:
+      return
+    echo "after"
+
+  exhaustive(true)
diff --git a/tests/controlflow/tunreachable2.nim b/tests/controlflow/tunreachable2.nim
new file mode 100644
index 000000000..a658880f0
--- /dev/null
+++ b/tests/controlflow/tunreachable2.nim
@@ -0,0 +1,12 @@
+discard """
+  matrix: "--warningAsError:UnreachableCode"
+"""
+
+proc test(): bool =
+  block okay:
+    if true: break okay
+    return false
+
+  return true # Line 7 is here
+
+doAssert test()
diff --git a/tests/converter/m18986.nim b/tests/converter/m18986.nim
new file mode 100644
index 000000000..0ebf343ae
--- /dev/null
+++ b/tests/converter/m18986.nim
@@ -0,0 +1,3 @@
+import std/macros
+
+converter Lit*(x: uint): NimNode = newLit(x)
diff --git a/tests/converter/mdontleak.nim b/tests/converter/mdontleak.nim
new file mode 100644
index 000000000..e55c3f87c
--- /dev/null
+++ b/tests/converter/mdontleak.nim
@@ -0,0 +1,3 @@
+
+converter toBool(x: uint32): bool = x != 0
+# Note: This convertes is not exported!
diff --git a/tests/converter/t18986.nim b/tests/converter/t18986.nim
new file mode 100644
index 000000000..ef300fa49
--- /dev/null
+++ b/tests/converter/t18986.nim
@@ -0,0 +1,10 @@
+discard """
+  output: "Found a 0"
+"""
+
+import m18986 except Lit
+import std/macros
+
+# bug #18986
+var x = 0.uint
+echo "Found a ", x
diff --git a/tests/converter/t21531.nim b/tests/converter/t21531.nim
new file mode 100644
index 000000000..b0198684d
--- /dev/null
+++ b/tests/converter/t21531.nim
@@ -0,0 +1,10 @@
+import std/typetraits
+
+type Foo* = distinct string
+
+converter toBase*(headers: var Foo): var string =
+  headers.distinctBase
+
+proc bar*(headers: var Foo) =
+  for x in headers: discard
+    
diff --git a/tests/converter/t7097.nim b/tests/converter/t7097.nim
new file mode 100644
index 000000000..d8e953080
--- /dev/null
+++ b/tests/converter/t7097.nim
@@ -0,0 +1,38 @@
+type
+  Byte* = uint8
+  Bytes* = seq[Byte]
+  
+  BytesRange* = object
+    bytes: Bytes
+    ibegin, iend: int
+
+proc initBytesRange*(s: var Bytes, ibegin = 0, iend = -1): BytesRange =
+  let e = if iend < 0: s.len + iend + 1
+          else: iend
+  assert ibegin > 0 and e <= s.len
+  when defined(gcRefc):
+    shallow(s)
+  result.bytes = s
+  result.ibegin = ibegin
+  result.iend = e
+
+template `[]=`*(r: var BytesRange, i: int, v: Byte) =
+  r.bytes[r.ibegin + i] = v
+
+converter fromSeq*(s: Bytes): BytesRange =
+  var seqCopy = s
+  return initBytesRange(seqCopy)
+
+type
+  Reader* = object
+    data: BytesRange
+    position: int
+
+proc readerFromHex*(input: string): Reader =
+  let totalBytes = input.len div 2
+  var backingStore = newSeq[Byte](totalBytes)
+  result.data = initBytesRange(backingStore)
+
+  for i in 0 ..< totalBytes:
+    var nextByte = 0
+    result.data[i] = Byte(nextByte) # <-------- instantiated from here
diff --git a/tests/converter/t7098.nim b/tests/converter/t7098.nim
index 8e7634882..30c9c1e25 100644
--- a/tests/converter/t7098.nim
+++ b/tests/converter/t7098.nim
@@ -14,8 +14,8 @@ proc initBytesRange*(s: var Bytes, ibegin = 0, iend = -1): BytesRange =
   let e = if iend < 0: s.len + iend + 1
           else: iend
   assert ibegin >= 0 and e <= s.len
-
-  shallow(s)
+  when defined(gcRefc):
+    shallow(s)
   result.bytes = s
   result.ibegin = ibegin
   result.iend = e
diff --git a/tests/converter/t9165.nim b/tests/converter/t9165.nim
new file mode 100644
index 000000000..d0225ffbc
--- /dev/null
+++ b/tests/converter/t9165.nim
@@ -0,0 +1,11 @@
+type ustring = distinct string
+
+converter toUString(s: string): ustring = ustring(s)
+converter toString(s: ustring): string = string(s)
+
+proc `[]=`*(s: var ustring, slice: Slice[int], replacement: ustring) {.inline.} =
+  s = replacement
+
+var s = ustring("123")
+s[1..2] = "3"
+doAssert s == "3"
\ No newline at end of file
diff --git a/tests/converter/tconverter.nim b/tests/converter/tconverter.nim
new file mode 100644
index 000000000..0bf067c55
--- /dev/null
+++ b/tests/converter/tconverter.nim
@@ -0,0 +1,11 @@
+discard """
+  output: '''fooo fooo'''
+"""
+
+converter intToString[T](i: T): string = "fooo"
+
+let
+  foo: string = 1
+  bar: string = intToString(2)
+
+echo foo, " ", bar
\ No newline at end of file
diff --git a/tests/converter/tconverter_unique_ptr.nim b/tests/converter/tconverter_unique_ptr.nim
index 23c1a3d96..6902f9e9e 100644
--- a/tests/converter/tconverter_unique_ptr.nim
+++ b/tests/converter/tconverter_unique_ptr.nim
@@ -22,12 +22,11 @@ proc `$`(x: MyLen): string {.borrow.}
 proc `==`(x1, x2: MyLen): bool {.borrow.}
 
 
-proc `=destroy`*(m: var MySeq) {.inline.} =
+proc `=destroy`*(m: MySeq) {.inline.} =
   if m.data != nil:
     deallocShared(m.data)
-    m.data = nil
 
-proc `=`*(m: var MySeq, m2: MySeq) =
+proc `=copy`*(m: var MySeq, m2: MySeq) =
   if m.data == m2.data: return
   if m.data != nil:
     `=destroy`(m)
@@ -77,13 +76,12 @@ converter literalToLen*(x: int{lit}): MyLen =
 # Unique pointer implementation
 #-------------------------------------------------------------
 
-proc `=destroy`*[T](p: var UniquePtr[T]) =
+proc `=destroy`*[T](p: UniquePtr[T]) =
   if p.val != nil:
     `=destroy`(p.val[])
     dealloc(p.val)
-    p.val = nil
 
-proc `=`*[T](dest: var UniquePtr[T], src: UniquePtr[T]) {.error.}
+proc `=copy`*[T](dest: var UniquePtr[T], src: UniquePtr[T]) {.error.}
 
 proc `=sink`*[T](dest: var UniquePtr[T], src: UniquePtr[T]) {.inline.} =
   if dest.val != nil and dest.val != src.val:
@@ -118,13 +116,12 @@ type
     ## as it returns only `lent T`
     val: ptr T
 
-proc `=destroy`*[T](p: var ConstPtr[T]) =
+proc `=destroy`*[T](p: ConstPtr[T]) =
   if p.val != nil:
     `=destroy`(p.val[])
     dealloc(p.val)
-    p.val = nil
 
-proc `=`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.error.}
+proc `=copy`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.error.}
 
 proc `=sink`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.inline.} =
   if dest.val != nil and dest.val != src.val:
diff --git a/tests/converter/tconverter_with_varargs.nim b/tests/converter/tconverter_with_varargs.nim
index 6d7e31e85..fae83221b 100644
--- a/tests/converter/tconverter_with_varargs.nim
+++ b/tests/converter/tconverter_with_varargs.nim
@@ -8,7 +8,7 @@ type
 converter to_py*(i: int) : PPyRef = nil
 
 when false:
-  proc to_tuple*(vals: openarray[PPyRef]): PPyRef =
+  proc to_tuple*(vals: openArray[PPyRef]): PPyRef =
     discard
 
 proc abc(args: varargs[PPyRef]) =
diff --git a/tests/converter/tdontleak.nim b/tests/converter/tdontleak.nim
new file mode 100644
index 000000000..4965fa90a
--- /dev/null
+++ b/tests/converter/tdontleak.nim
@@ -0,0 +1,10 @@
+discard """
+  output: '''5'''
+joinable: false
+"""
+
+import mdontleak
+# bug #19213
+
+let a = 5'u32
+echo a
diff --git a/tests/converter/texplicit_conversion.nim b/tests/converter/texplicit_conversion.nim
index 6b2e96faf..e36d78ad5 100644
--- a/tests/converter/texplicit_conversion.nim
+++ b/tests/converter/texplicit_conversion.nim
@@ -11,3 +11,9 @@ converter toInt(s: string): int =
 
 let x = (int)"234"
 echo x
+
+block: # Test for nkconv
+  proc foo(o: var int) =
+    assert o == 0
+  var a = 0
+  foo(int(a))
\ No newline at end of file
diff --git a/tests/converter/tgenericconverter.nim b/tests/converter/tgenericconverter.nim
index e1c9f7c4c..cbbd2e1b0 100644
--- a/tests/converter/tgenericconverter.nim
+++ b/tests/converter/tgenericconverter.nim
@@ -28,3 +28,27 @@ aa.x = 666
 
 p aa
 q aa
+
+
+#-------------------------------------------------------------
+# issue #16651
+type
+  PointTup = tuple
+    x: float32
+    y: float32
+
+converter tupleToPoint[T1, T2: SomeFloat](self: tuple[x: T1, y: T2]): PointTup =
+  result = (self.x.float32, self.y.float32)
+
+proc tupleToPointX(self: tuple[x: SomeFloat, y: SomeFloat]): PointTup =
+  result = (self.x.float32, self.y.float32)
+
+proc tupleToPointX2(self: tuple[x: SomeFloat, y: distinct SomeFloat]): PointTup =
+  result = (self.x.float32, self.y.float32)
+
+var t1: PointTup = tupleToPointX((1.0, 0.0))
+var t2: PointTup = tupleToPointX2((1.0, 0.0))
+var t3: PointTup = tupleToPointX2((1.0'f32, 0.0))
+var t4: PointTup = tupleToPointX2((1.0, 0.0'f32))
+
+var x2: PointTup = (1.0, 0.0)
\ No newline at end of file
diff --git a/tests/converter/tor_in_converter.nim b/tests/converter/tor_in_converter.nim
index 5674526a1..df2334647 100644
--- a/tests/converter/tor_in_converter.nim
+++ b/tests/converter/tor_in_converter.nim
@@ -4,7 +4,7 @@ test'''
 """
 # bug #4537
 
-# nim js --d:nodejs
+# nim js -d:nodejs
 
 type
   Str = distinct string
diff --git a/tests/coroutines/texceptions.nim b/tests/coroutines/texceptions.nim
index 7b5d57ec0..31feffdff 100644
--- a/tests/coroutines/texceptions.nim
+++ b/tests/coroutines/texceptions.nim
@@ -1,5 +1,5 @@
 discard """
-  target: "c"
+  targets: "c"
   disabled: true
 """
 
diff --git a/tests/coroutines/tgc.nim b/tests/coroutines/tgc.nim
index 46f4f8e83..770d413f5 100644
--- a/tests/coroutines/tgc.nim
+++ b/tests/coroutines/tgc.nim
@@ -1,19 +1,22 @@
 discard """
-  target: "c"
+  matrix: "--gc:refc; --gc:arc; --gc:orc"
+  targets: "c"
 """
 
-import coro
+when compileOption("gc", "refc") or not defined(openbsd):
+  # xxx openbsd gave: stdlib_coro.nim.c:406:22: error: array type 'jmp_buf' (aka 'long [11]') is not assignable (*dest).execContext = src.execContext;
+  import coro
 
-var maxOccupiedMemory = 0
+  var maxOccupiedMemory = 0
 
-proc testGC() =
-  var numbers = newSeq[int](100)
-  maxOccupiedMemory = max(maxOccupiedMemory, getOccupiedMem())
-  suspend(0)
+  proc testGC() =
+    var numbers = newSeq[int](100)
+    maxOccupiedMemory = max(maxOccupiedMemory, getOccupiedMem())
+    suspend(0)
 
-start(testGC)
-start(testGC)
-run()
+  start(testGC)
+  start(testGC)
+  run()
 
-GC_fullCollect()
-doAssert(getOccupiedMem() < maxOccupiedMemory, "GC did not free any memory allocated in coroutines")
+  GC_fullCollect()
+  doAssert(getOccupiedMem() < maxOccupiedMemory, "GC did not free any memory allocated in coroutines")
diff --git a/tests/coroutines/titerators.nim b/tests/coroutines/titerators.nim
index d12a5debe..1ea134811 100644
--- a/tests/coroutines/titerators.nim
+++ b/tests/coroutines/titerators.nim
@@ -1,5 +1,5 @@
 discard """
-  target: "c"
+  targets: "c"
 disabled: true
 """
 
diff --git a/tests/coroutines/twait.nim b/tests/coroutines/twait.nim
index 1769966ab..2edfcf675 100644
--- a/tests/coroutines/twait.nim
+++ b/tests/coroutines/twait.nim
@@ -1,21 +1,28 @@
 discard """
   output: "Exit 1\nExit 2"
-  disabled: "macosx"
-  target: "c"
+  matrix: "--gc:refc; --gc:arc; --gc:orc"
+  targets: "c"
 """
-import coro
 
-var coro1: CoroutineRef
+when compileOption("gc", "refc") or not defined(openbsd):
+  # xxx openbsd failed, see tgc.nim
+  import coro
 
-proc testCoroutine1() =
-  for i in 0..<10:
-    suspend(0)
-  echo "Exit 1"
+  var coro1: CoroutineRef
 
-proc testCoroutine2() =
-  coro1.wait()
-  echo "Exit 2"
+  proc testCoroutine1() =
+    for i in 0..<10:
+      suspend(0)
+    echo "Exit 1"
+
+  proc testCoroutine2() =
+    coro1.wait()
+    echo "Exit 2"
 
-coro1 = coro.start(testCoroutine1)
-coro.start(testCoroutine2)
-run()
+  coro1 = coro.start(testCoroutine1)
+  coro.start(testCoroutine2)
+  run()
+else:
+  # workaround
+  echo "Exit 1"
+  echo "Exit 2"
diff --git a/tests/cpp/23962.h b/tests/cpp/23962.h
new file mode 100644
index 000000000..2d8147bfb
--- /dev/null
+++ b/tests/cpp/23962.h
@@ -0,0 +1,17 @@
+#include <iostream>
+
+struct Foo {
+
+  Foo(int inX): x(inX) {
+    std::cout << "Ctor Foo(" << x << ")\n";
+  }
+  ~Foo() {
+    std::cout << "Destory Foo(" << x << ")\n";
+  }
+
+  void print() {
+    std::cout << "Foo.x = " << x << '\n';
+  }
+
+  int x;
+};
\ No newline at end of file
diff --git a/tests/cpp/enum.hpp b/tests/cpp/enum.hpp
new file mode 100644
index 000000000..268999d68
--- /dev/null
+++ b/tests/cpp/enum.hpp
@@ -0,0 +1,3 @@
+namespace namespaced {
+enum Enum { A, B, C };
+}
diff --git a/tests/cpp/fam.h b/tests/cpp/fam.h
new file mode 100644
index 000000000..ad576425b
--- /dev/null
+++ b/tests/cpp/fam.h
@@ -0,0 +1,4 @@
+struct Test{
+  ~Test() {
+  }
+};
diff --git a/tests/cpp/t12946.nim b/tests/cpp/t12946.nim
new file mode 100644
index 000000000..79cd56251
--- /dev/null
+++ b/tests/cpp/t12946.nim
@@ -0,0 +1,8 @@
+discard """
+  targets: "c cpp"
+"""
+
+import std/atomics
+type Futex = distinct Atomic[int32]
+
+var x: Futex
diff --git a/tests/cpp/t22679.nim b/tests/cpp/t22679.nim
new file mode 100644
index 000000000..81defcb58
--- /dev/null
+++ b/tests/cpp/t22679.nim
@@ -0,0 +1,50 @@
+discard """
+  cmd: "nim cpp $file"
+  output:'''
+cppNZ.x = 123
+cppNZInit.x = 123
+hascpp.cppnz.x = 123
+hasCppInit.cppnz.x = 123
+hasCppCtor.cppnz.x = 123
+'''
+"""
+{.emit:"""/*TYPESECTION*/
+struct CppNonZero {
+  int x = 123;
+};
+""".}
+
+import sugar
+type
+  CppNonZero {.importcpp, inheritable.} = object
+    x: cint
+
+  HasCpp = object
+    cppnz: CppNonZero
+
+proc initCppNonZero: CppNonZero =
+  CppNonZero()
+
+proc initHasCpp: HasCpp =
+  HasCpp()
+
+proc ctorHasCpp: HasCpp {.constructor.} =
+  discard
+
+proc main =
+  var cppNZ: CppNonZero
+  dump cppNZ.x
+
+  var cppNZInit = initCppNonZero()
+  dump cppNZInit.x
+
+  var hascpp: HasCpp
+  dump hascpp.cppnz.x
+
+  var hasCppInit = initHasCpp()
+  dump hasCppInit.cppnz.x
+
+  var hasCppCtor = ctorHasCpp()
+  dump hasCppCtor.cppnz.x
+
+main()
\ No newline at end of file
diff --git a/tests/cpp/t22680.nim b/tests/cpp/t22680.nim
new file mode 100644
index 000000000..80f1a8319
--- /dev/null
+++ b/tests/cpp/t22680.nim
@@ -0,0 +1,50 @@
+discard """
+  cmd: "nim cpp $file"
+  output:'''
+cppNZ.x = 123
+cppNZInit.x = 123
+inheritCpp.x = 123
+inheritCppInit.x = 123
+inheritCppCtor.x = 123
+'''
+"""
+import std/sugar
+
+{.emit:"""/*TYPESECTION*/
+struct CppNonZero {
+  int x = 123;
+};
+""".}
+
+type
+  CppNonZero {.importcpp, inheritable.} = object
+    x: cint
+
+  InheritCpp = object of CppNonZero
+
+proc initCppNonZero: CppNonZero =
+  CppNonZero()
+
+proc initInheritCpp: InheritCpp =
+  InheritCpp()
+
+proc ctorInheritCpp: InheritCpp {.constructor.} =
+  discard
+
+proc main =
+  var cppNZ: CppNonZero
+  dump cppNZ.x
+
+  var cppNZInit = initCppNonZero()
+  dump cppNZInit.x
+
+  var inheritCpp: InheritCpp
+  dump inheritCpp.x
+
+  var inheritCppInit = initInheritCpp()
+  dump inheritCppInit.x
+
+  var inheritCppCtor = ctorInheritCpp()
+  dump inheritCppCtor.x
+
+main()
\ No newline at end of file
diff --git a/tests/cpp/t22712.nim b/tests/cpp/t22712.nim
new file mode 100644
index 000000000..34ef67ac8
--- /dev/null
+++ b/tests/cpp/t22712.nim
@@ -0,0 +1,15 @@
+discard """
+targets: "cpp"
+errormsg: "constructor in an imported type needs importcpp pragma"
+line: 14
+"""
+{.emit: """/*TYPESECTION*/
+struct CppStruct {
+  CppStruct();
+};
+""".}
+
+type CppStruct {.importcpp.} = object
+
+proc makeCppStruct(): CppStruct {.constructor.} = 
+  discard
\ No newline at end of file
diff --git a/tests/cpp/t23306.nim b/tests/cpp/t23306.nim
new file mode 100644
index 000000000..ebb4edb8d
--- /dev/null
+++ b/tests/cpp/t23306.nim
@@ -0,0 +1,12 @@
+discard """
+targets: "cpp"
+"""
+
+type K = object
+  h: iterator(f: K): K
+
+iterator d(g: K): K {.closure.} =
+  defer:
+    discard
+
+discard K(h: d)
\ No newline at end of file
diff --git a/tests/cpp/t23434.nim b/tests/cpp/t23434.nim
new file mode 100644
index 000000000..04a83227e
--- /dev/null
+++ b/tests/cpp/t23434.nim
@@ -0,0 +1,17 @@
+discard """
+cmd:"nim cpp $file"
+errormsg: "type mismatch: got <proc (self: SomeObject){.member, gcsafe.}>"
+line: 17
+"""
+type SomeObject = object
+    value: int
+
+proc printValue(self: SomeObject) {.virtual.} =
+    echo "The value is ", self.value
+
+proc callAProc(p: proc(self: SomeObject){.noconv.}) =
+    let someObj = SomeObject(value: 4)
+    echo "calling param proc"
+    p(someObj)
+
+callAProc(printValue)
\ No newline at end of file
diff --git a/tests/cpp/t23657.nim b/tests/cpp/t23657.nim
new file mode 100644
index 000000000..63deb7fb0
--- /dev/null
+++ b/tests/cpp/t23657.nim
@@ -0,0 +1,54 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp -r $file"
+  output: '''
+1.0
+1.0
+'''
+
+"""
+{.emit:"""/*TYPESECTION*/
+struct Point {
+  float x, y, z;
+  Point(float x, float y, float z): x(x), y(y), z(z) {}
+  Point() = default;
+};
+struct Direction {
+  float x, y, z;
+  Direction(float x, float y, float z): x(x), y(y), z(z) {}
+  Direction() = default;
+};
+struct Axis {
+  Point origin;
+  Direction direction;
+  Axis(Point origin, Direction direction): origin(origin), direction(direction) {}
+  Axis() = default;
+};
+
+""".}
+
+type
+  Point {.importcpp.} = object
+    x, y, z: float
+  
+  Direction {.importcpp.} = object
+    x, y, z: float
+
+  Axis {.importcpp.} = object
+    origin: Point
+    direction: Direction
+
+proc makeAxis(origin: Point, direction: Direction): Axis {. constructor, importcpp:"Axis(@)".}
+proc makePoint(x, y, z: float): Point {. constructor, importcpp:"Point(@)".}
+proc makeDirection(x, y, z: float): Direction {. constructor, importcpp:"Direction(@)".}
+
+var axis1 = makeAxis(Point(x: 1.0, y: 2.0, z: 3.0), Direction(x: 4.0, y: 5.0, z: 6.0)) #Triggers the error (T1)
+var axis2Ctor = makeAxis(makePoint(1.0, 2.0, 3.0), makeDirection(4.0, 5.0, 6.0)) #Do not triggers
+
+proc main() = #Do not triggers as Tx are inside the body
+  let test = makeAxis(Point(x: 1.0, y: 2.0, z: 3.0), Direction(x: 4.0, y: 5.0, z: 6.0))
+  echo test.origin.x
+
+main()
+
+echo $axis1.origin.x  #Make sures it's init
\ No newline at end of file
diff --git a/tests/cpp/t23962.nim b/tests/cpp/t23962.nim
new file mode 100644
index 000000000..c79d888df
--- /dev/null
+++ b/tests/cpp/t23962.nim
@@ -0,0 +1,32 @@
+discard """
+  cmd: "nim cpp $file"
+  output: '''
+Ctor Foo(-1)
+Destory Foo(-1)
+Ctor Foo(-1)
+Destory Foo(-1)
+Ctor Foo(-1)
+Destory Foo(-1)
+Foo.x = 1
+Foo.x = 2
+Foo.x = -1
+'''
+"""
+
+type
+  Foo {.importcpp, header: "23962.h".} = object
+    x: cint
+
+proc print(f: Foo) {.importcpp.}
+
+#also tests the right constructor is used
+proc makeFoo(x: int32 = -1): Foo {.importcpp:"Foo(#)", constructor.} 
+
+proc test =
+  var xs = newSeq[Foo](3)
+  xs[0].x = 1
+  xs[1].x = 2
+  for x in xs:
+    x.print
+
+test()
\ No newline at end of file
diff --git a/tests/cpp/t4834.nim b/tests/cpp/t4834.nim
new file mode 100644
index 000000000..0275b1b70
--- /dev/null
+++ b/tests/cpp/t4834.nim
@@ -0,0 +1,17 @@
+discard """
+  targets: "cpp"
+"""
+
+# issue #4834
+block:
+  defer:
+    let x = 0
+
+
+proc main() =
+  block:
+    defer:
+      raise newException(Exception, "foo")
+
+doAssertRaises(Exception):
+  main()
diff --git a/tests/cpp/t6986.nim b/tests/cpp/t6986.nim
index ffd277adb..16e455c3b 100644
--- a/tests/cpp/t6986.nim
+++ b/tests/cpp/t6986.nim
@@ -5,6 +5,9 @@ discard """
 
 import sequtils, strutils
 
+when defined(nimPreviewSlimSystem):
+  import std/syncio
+
 
 let rules = toSeq(lines("input"))
   .mapIt(it.split(" => ").mapIt(it.replace("/", "")))
diff --git a/tests/cpp/tasync_cpp.nim b/tests/cpp/tasync_cpp.nim
index a68be6cd5..3f4ec6208 100644
--- a/tests/cpp/tasync_cpp.nim
+++ b/tests/cpp/tasync_cpp.nim
@@ -1,7 +1,7 @@
 discard """
   targets: "cpp"
   output: "hello"
-  cmd: "nim cpp --nilseqs:on --nimblePath:tests/deps $file"
+  cmd: "nim cpp --clearNimblePath --nimblePath:build/deps/pkgs2 $file"
 """
 
 # bug #3299
diff --git a/tests/cpp/tcasts.nim b/tests/cpp/tcasts.nim
index d968d87db..80527efff 100644
--- a/tests/cpp/tcasts.nim
+++ b/tests/cpp/tcasts.nim
@@ -1,6 +1,5 @@
 discard """
   cmd: "nim cpp $file"
-  output: '''{"vas": "kas", "123": "123"}'''
   targets: "cpp"
 """
 
@@ -18,4 +17,4 @@ import tables
 var t = initTable[string, string]()
 discard t.hasKeyOrPut("123", "123")
 discard t.mgetOrPut("vas", "kas")
-echo t
\ No newline at end of file
+doAssert t.len == 2
diff --git a/tests/cpp/tcodegendecl.nim b/tests/cpp/tcodegendecl.nim
new file mode 100644
index 000000000..e128c5eb7
--- /dev/null
+++ b/tests/cpp/tcodegendecl.nim
@@ -0,0 +1,17 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp $file"
+  output: "3"
+"""
+
+{.emit:"""/*TYPESECTION*/
+  int operate(int x, int y, int (*func)(const int&, const int&)){
+    return func(x, y);
+  };
+""".}
+
+proc operate(x, y: int32, fn: proc(x, y: int32 ): int32 {.cdecl.}): int32 {.importcpp:"$1(@)".}
+
+proc add(a {.codegenDecl:"const $#& $#".}, b {.codegenDecl:"const $# $#", byref.}: int32): int32  {.cdecl.} = a + b
+
+echo operate(1, 2, add)
\ No newline at end of file
diff --git a/tests/cpp/tconstructor.nim b/tests/cpp/tconstructor.nim
new file mode 100644
index 000000000..922ee54fd
--- /dev/null
+++ b/tests/cpp/tconstructor.nim
@@ -0,0 +1,131 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp $file"
+  output: '''
+1
+0
+123
+0
+123
+___
+0
+777
+10
+123
+0
+777
+10
+123
+()
+'''
+"""
+
+{.emit:"""/*TYPESECTION*/
+struct CppClass {
+  int x;
+  int y;
+  CppClass(int inX, int inY) {
+    this->x = inX;
+    this->y = inY;
+  }
+  //CppClass() = default;
+};
+""".}
+
+type  CppClass* {.importcpp, inheritable.} = object
+  x: int32
+  y: int32
+
+proc makeCppClass(x, y: int32): CppClass {.importcpp: "CppClass(@)", constructor.}
+#test globals are init with the constructor call
+var shouldCompile {.used.} = makeCppClass(1, 2)
+
+proc newCpp*[T](): ptr T {.importcpp:"new '*0()".}
+
+#creation
+type NimClassNoNarent* = object
+  x: int32
+
+proc makeNimClassNoParent(x:int32): NimClassNoNarent {. constructor.} =
+  result.x = x
+  discard
+
+let nimClassNoParent = makeNimClassNoParent(1)
+echo nimClassNoParent.x #acess to this just fine. Notice the field will appear last because we are dealing with constructor calls here
+
+var nimClassNoParentDef {.used.}: NimClassNoNarent  #test has a default constructor. 
+
+#inheritance 
+type NimClass* = object of CppClass
+
+proc makeNimClass(x:int32): NimClass {. constructor:"NimClass('1 #1) : CppClass(0, #1) ".} =
+  result.x = x
+
+#optinially define the default constructor so we get rid of the cpp warn and we can declare the obj (note: default constructor of 'tyObject_NimClass__apRyyO8cfRsZtsldq1rjKA' is implicitly deleted because base class 'CppClass' has no default constructor)
+proc makeCppClass(): NimClass {. constructor: "NimClass() : CppClass(0, 0) ".} = 
+  result.x = 1
+
+let nimClass = makeNimClass(1)
+var nimClassDef {.used.}: NimClass  #since we explictly defined the default constructor we can declare the obj
+
+#bug: 22662
+type
+  BugClass* = object
+    x: int          # Not initialized
+
+proc makeBugClass(): BugClass {.constructor.} =
+  discard
+
+proc main =
+  for i in 0 .. 1:
+    var n = makeBugClass()
+    echo n.x
+    n.x = 123
+    echo n.x
+
+main()
+#bug:
+echo "___"
+type
+  NimClassWithDefault = object
+    x: int
+    y = 777
+    case kind: bool = true
+    of true:
+      z: int = 10
+    else: discard
+
+proc makeNimClassWithDefault(): NimClassWithDefault {.constructor.} =
+  result = NimClassWithDefault()
+
+proc init =
+  for i in 0 .. 1:
+    var n = makeNimClassWithDefault()
+    echo n.x
+    echo n.y
+    echo n.z
+    n.x = 123
+    echo n.x
+
+init()
+
+#tests that the ctor is not declared with nodecl. 
+#nodelc also prevents the creation of a default one when another is created.
+type Foo {.exportc.} = object
+
+proc makeFoo(): Foo {.used, constructor, nodecl.} = discard
+
+echo $Foo()
+
+type Boo = object
+proc `=copy`(dest: var Boo; src: Boo) = discard
+
+proc makeBoo(): Boo {.constructor.} = Boo()
+proc makeBoo2(): Boo  = Boo()
+
+block:
+  proc main =
+    var b = makeBoo()
+    var b2 = makeBoo2()
+
+  main()
\ No newline at end of file
diff --git a/tests/cpp/tcovariancerules.nim b/tests/cpp/tcovariancerules.nim
index e1769b0e6..9d49f2cbd 100644
--- a/tests/cpp/tcovariancerules.nim
+++ b/tests/cpp/tcovariancerules.nim
@@ -28,10 +28,10 @@ template reject(x) =
 
 import macros
 
-macro skipElse(n: untyped): typed = n[0]
+macro skipElse(n: untyped): untyped = n[0]
 
-template acceptWithCovariance(x, otherwise): typed =
-  when nimEnableCovariance:
+template acceptWithCovariance(x, otherwise): untyped =
+  when defined nimEnableCovariance:
     x
   else:
     reject(x)
@@ -79,16 +79,16 @@ proc wantsCovariantSeq2(s: seq[AnimalRef]) =
 proc wantsCovariantSeq3(s: seq[RefAlias[Animal]]) =
   for a in s: echo a.x
 
-proc wantsCovariantOperArray(s: openarray[ref Animal]) =
+proc wantsCovariantOpenArray(s: openArray[ref Animal]) =
   for a in s: echo a.x
 
-proc modifiesCovariantOperArray(s: var openarray[ref Animal]) =
+proc modifiesCovariantOpenArray(s: var openArray[ref Animal]) =
   for a in s: echo a.x
 
-proc modifiesDerivedOperArray(s: var openarray[ref Dog]) =
+proc modifiesDerivedOpenArray(s: var openArray[ref Dog]) =
   for a in s: echo a.x
 
-proc wantsNonCovariantOperArray(s: openarray[Animal]) =
+proc wantsNonCovariantOpenArray(s: openArray[Animal]) =
   for a in s: echo a.x
 
 proc wantsCovariantArray(s: array[2, ref Animal]) =
@@ -199,15 +199,15 @@ accept:
   wantsCovariantSeq3(@[AnimalRef(cat), dog])
   wantsCovariantSeq3(@[cat, dog])
 
-  wantsCovariantOperArray([cat, dog])
+  wantsCovariantOpenArray([cat, dog])
 
 acceptWithCovariance:
   wantsCovariantSeq1(@[cat, cat])
   wantsCovariantSeq2(@[dog, makeDerivedRef("dog X")])
   # XXX: wantsCovariantSeq3(@[cat, cat])
 
-  wantsCovariantOperArray(@[cat, cat])
-  wantsCovariantOperArray([dog, dog])
+  wantsCovariantOpenArray(@[cat, cat])
+  wantsCovariantOpenArray([dog, dog])
 else:
   echo "cat"
   echo "cat"
@@ -226,7 +226,7 @@ accept:
   modifiesDerivedArray(dogRefsArray)
   modifiesDerivedSeq(dogRefs)
 
-reject modifiesCovariantSeq(dogRefs)
+reject modifiesCovariantSeqd(ogRefs)
 reject modifiesCovariantSeq(addr(dogRefs))
 reject modifiesCovariantSeq(dogRefs.addr)
 
@@ -245,19 +245,19 @@ when false:
   wantsNonCovariantArray animalValuesArray
 
 reject wantsNonCovariantSeq(dogRefs)
-reject modifiesCovariantOperArray(dogRefs)
+reject modifiesCovariantOpenArray(dogRefs)
 reject wantsNonCovariantArray(dogRefsArray)
 reject wantsNonCovariantSeq(dogValues)
 reject wantsNonCovariantArray(dogValuesArray)
 reject modifiesValueArray()
 
-modifiesDerivedOperArray dogRefs
-reject modifiesDerivedOperArray(dogValues)
-reject modifiesDerivedOperArray(animalRefs)
+modifiesDerivedOpenArray dogRefs
+reject modifiesDerivedOpenArray(dogValues)
+reject modifiesDerivedOpenArray(animalRefs)
 
-reject wantsNonCovariantOperArray(animalRefs)
-reject wantsNonCovariantOperArray(dogRefs)
-reject wantsNonCovariantOperArray(dogValues)
+reject wantsNonCovariantOpenArray(animalRefs)
+reject wantsNonCovariantOpenArray(dogRefs)
+reject wantsNonCovariantOpenArray(dogValues)
 
 var animalRefSeq: seq[ref Animal]
 
@@ -300,12 +300,12 @@ template <class T> struct ARR { typedef T DataType[2]; DataType data; };
 """.}
 
 type
-  MyPtr {.importcpp: "'0 *"} [out T] = object
+  MyPtr[out T] {.importcpp: "'0 *"}  = object
 
-  MySeq {.importcpp: "ARR<'0>", nodecl} [out T] = object
+  MySeq[out T] {.importcpp: "ARR<'0>", nodecl}  = object
     data: array[2, T]
 
-  MyAction {.importcpp: "FN<'0>::type"} [in T] = object
+  MyAction[in T] {.importcpp: "FN<'0>::type"}  = object
 
 var
   cAnimal: MyPtr[Animal]
@@ -415,4 +415,3 @@ reject usesAddressOfAnimalRefSeq(addr cAnimalValues)
 reject usesAddressOfAnimalRefSeq(addr cDogValues)
 accept usesAddressOfAnimalRefSeq(addr cAnimals)
 reject usesAddressOfAnimalRefSeq(addr cDogs)
-
diff --git a/tests/cpp/tcppraise.nim b/tests/cpp/tcppraise.nim
index 8f34cb3e4..f03956d4c 100644
--- a/tests/cpp/tcppraise.nim
+++ b/tests/cpp/tcppraise.nim
@@ -68,4 +68,4 @@ except:
   echo getCurrentExceptionMsg()
   discard
 
-doAssert: getCurrentException() == nil
\ No newline at end of file
+doAssert: getCurrentException() == nil
diff --git a/tests/cpp/tdont_init_instantiation.nim b/tests/cpp/tdont_init_instantiation.nim
index fe487fba0..a13a3f6b4 100644
--- a/tests/cpp/tdont_init_instantiation.nim
+++ b/tests/cpp/tdont_init_instantiation.nim
@@ -20,7 +20,7 @@ template <typename X> class C {
 };
 """.}
 
-type C{.importcpp, header: "<stdio.h>", nodecl.} [X] = object
+type C[X] {.importcpp, header: "<stdio.h>", nodecl.} = object
 proc mkC[X]: C[X] {.importcpp: "C<'*0>()", constructor, nodecl.}
 
 proc foo(): C[int] =
diff --git a/tests/cpp/temitlist.nim b/tests/cpp/temitlist.nim
index 852537518..9170be079 100644
--- a/tests/cpp/temitlist.nim
+++ b/tests/cpp/temitlist.nim
@@ -1,12 +1,14 @@
 discard """
   targets: "cpp"
-  output: '''6.0
+  output: '''
+6.0
 0'''
+disabled: "windows" # pending bug #18011
 """
 
 # bug #4730
 
-type Vector* {.importcpp: "std::vector", header: "<vector>".}[T] = object
+type Vector*[T] {.importcpp: "std::vector", header: "<vector>".} = object
 
 template `[]=`*[T](v: var Vector[T], key: int, val: T) =
   {.emit: [v, "[", key, "] = ", val, ";"].}
diff --git a/tests/cpp/tempty_generic_obj.nim b/tests/cpp/tempty_generic_obj.nim
index 913c1ec3c..6125190b4 100644
--- a/tests/cpp/tempty_generic_obj.nim
+++ b/tests/cpp/tempty_generic_obj.nim
@@ -1,7 +1,9 @@
 discard """
   targets: "cpp"
-  output: '''int
+  output: '''
+int
 float'''
+disabled: "windows" # pending bug #18011
 """
 
 import typetraits
diff --git a/tests/cpp/tenum_set.nim b/tests/cpp/tenum_set.nim
new file mode 100644
index 000000000..6afed722f
--- /dev/null
+++ b/tests/cpp/tenum_set.nim
@@ -0,0 +1,9 @@
+discard """
+targets: "cpp"
+output: "{A, B, C}"
+"""
+
+type Enum {.importcpp: "namespaced::Enum", header: "enum.hpp".} = enum A, B, C
+
+var vals = {low(Enum) .. high(Enum)}
+echo vals
diff --git a/tests/cpp/tevalorder.nim b/tests/cpp/tevalorder.nim
index f130cef6c..4764f3aca 100644
--- a/tests/cpp/tevalorder.nim
+++ b/tests/cpp/tevalorder.nim
@@ -2,7 +2,7 @@ discard """
   output: '''0
 1
 2'''
-target: "cpp"
+targets: "cpp"
 """
 
 # bug #8202
diff --git a/tests/cpp/tfam.nim b/tests/cpp/tfam.nim
new file mode 100644
index 000000000..6bd89fe24
--- /dev/null
+++ b/tests/cpp/tfam.nim
@@ -0,0 +1,7 @@
+discard """
+  targets: "cpp"
+"""
+type 
+  Test {.importcpp, header: "fam.h".} = object
+
+let test = newSeq[Test]()
\ No newline at end of file
diff --git a/tests/cpp/tinitializers.nim b/tests/cpp/tinitializers.nim
new file mode 100644
index 000000000..0199fb96b
--- /dev/null
+++ b/tests/cpp/tinitializers.nim
@@ -0,0 +1,60 @@
+discard """
+  cmd: "nim cpp $file"
+"""
+
+{.emit:"""/*TYPESECTION*/
+struct CppStruct {
+  CppStruct(int x, char* y): x(x), y(y){}
+  void doSomething() {}
+  int x;
+  char* y;
+};
+""".}
+type
+  CppStruct {.importcpp, inheritable.} = object
+  ChildStruct = object of CppStruct
+  HasCppStruct = object
+    cppstruct: CppStruct 
+
+proc constructCppStruct(a:cint = 5, b:cstring = "hello"): CppStruct {.importcpp: "CppStruct(@)", constructor.}
+proc doSomething(this: CppStruct) {.importcpp.}
+proc returnCppStruct(): CppStruct = discard
+proc initChildStruct: ChildStruct = ChildStruct() 
+proc makeChildStruct(): ChildStruct {.constructor:"""ChildStruct(): CppStruct(5, "10")""".} = discard
+proc initHasCppStruct(x: cint): HasCppStruct =
+  HasCppStruct(cppstruct: constructCppStruct(x))
+
+proc main =
+  var hasCppStruct = initHasCppStruct(2) #generates cppstruct = { 10 } inside the struct
+  hasCppStruct.cppstruct.doSomething() 
+  discard returnCppStruct() #generates result = { 10 } 
+  discard initChildStruct() #generates ChildStruct temp ({}) bypassed with makeChildStruct
+  (proc (s:CppStruct) = discard)(CppStruct()) #CppStruct temp ({10})
+main()
+
+
+#Should handle ObjectCalls
+{.emit:"""/*TYPESECTION*/
+struct Foo {
+};
+struct Boo {
+  Boo(int x, char* y, Foo f): x(x), y(y), foo(f){}
+  int x;
+  char* y;
+  Foo foo;
+};
+""".}
+type
+  Foo {.importcpp, inheritable, bycopy.} = object
+  Boo {.importcpp, inheritable.} = object
+    x: int32
+    y: cstring
+    foo: Foo
+
+proc makeBoo(a:cint = 10, b:cstring = "hello", foo: Foo = Foo()): Boo {.importcpp, constructor.}
+
+proc main2() = 
+  let cppStruct = makeBoo()
+  (proc (s:Boo) = discard)(Boo()) 
+
+main2()
\ No newline at end of file
diff --git a/tests/cpp/tmember.nim b/tests/cpp/tmember.nim
new file mode 100644
index 000000000..1a5b6fd97
--- /dev/null
+++ b/tests/cpp/tmember.nim
@@ -0,0 +1,75 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp $file"
+  output: '''
+2
+false
+hello foo
+hello boo
+hello boo
+FunctorSupport!
+static
+static
+destructing
+destructing
+'''
+"""
+proc print(s: cstring) {.importcpp:"printf(@)", header:"<stdio.h>".}
+
+type
+  Doo  {.exportc.} = object
+    test: int
+
+proc memberProc(f: Doo) {.exportc, member.} = 
+  echo $f.test
+
+proc destructor(f: Doo) {.member: "~'1()", used.} = 
+  print "destructing\n"
+
+proc `==`(self, other: Doo): bool {.member:"operator==('2 const & #2) const -> '0"} = 
+  self.test == other.test
+
+let doo = Doo(test: 2)
+doo.memberProc()
+echo doo == Doo(test: 1)
+
+#virtual
+proc newCpp*[T](): ptr T {.importcpp:"new '*0()".}
+type 
+  Foo {.exportc.} = object of RootObj
+  FooPtr = ptr Foo
+  Boo = object of Foo
+  BooPtr = ptr Boo
+
+proc salute(self: FooPtr) {.member: "virtual $1()".} = 
+  echo "hello foo"
+
+proc salute(self: BooPtr) {.member: "virtual $1()".} =
+  echo "hello boo"
+
+let foo = newCpp[Foo]()
+let boo = newCpp[Boo]()
+let booAsFoo = cast[FooPtr](newCpp[Boo]())  
+
+foo.salute()
+boo.salute()
+booAsFoo.salute()
+
+type
+  NimFunctor = object
+    discard
+proc invoke(f: NimFunctor, n:int) {.member:"operator ()('2 #2)" .} = 
+  echo "FunctorSupport!"
+
+{.experimental: "callOperator".}
+proc `()`(f: NimFunctor, n:int) {.importcpp:"#(@)" .} 
+NimFunctor()(1)
+
+#static
+proc staticProc(self: FooPtr) {.member: "static $1()".} = 
+  echo "static"
+
+proc importedStaticProc() {.importcpp:"Foo::staticProc()".}
+
+foo.staticProc()
+importedStaticProc()
diff --git a/tests/cpp/tmember_forward_declaration.nim b/tests/cpp/tmember_forward_declaration.nim
new file mode 100644
index 000000000..2f4a79daa
--- /dev/null
+++ b/tests/cpp/tmember_forward_declaration.nim
@@ -0,0 +1,27 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp $file"
+  output: '''
+abc called
+def called
+abc called
+'''
+"""
+
+type Foo = object
+
+proc abc(this: Foo, x: int): void {.member: "$1('2 #2)".}
+proc def(this: Foo, y: int): void {.virtual: "$1('2 #2)".}
+
+proc abc(this: Foo, x: int): void =
+  echo "abc called"
+  if x > 0:
+    this.def(x - 1)
+
+proc def(this: Foo, y: int): void =
+  echo "def called"
+  this.abc(y)
+
+var x = Foo()
+x.abc(1)
+
diff --git a/tests/cpp/tnoinitfield.nim b/tests/cpp/tnoinitfield.nim
new file mode 100644
index 000000000..4deffece8
--- /dev/null
+++ b/tests/cpp/tnoinitfield.nim
@@ -0,0 +1,30 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp $file"
+  output: '''
+'''
+"""
+{.emit: """/*TYPESECTION*/
+  struct Foo {
+    Foo(int a){};
+  };
+  struct Boo {
+    Boo(int a){};
+  };
+
+  """.}
+
+type 
+  Foo {.importcpp.} = object
+  Boo {.importcpp, noInit.} = object
+  Test {.exportc.} = object
+    foo {.noInit.}: Foo
+    boo: Boo
+
+proc makeTest(): Test {.constructor: "Test() : foo(10), boo(1)".} = 
+  discard
+
+proc main() = 
+  var t = makeTest()
+
+main()
\ No newline at end of file
diff --git a/tests/cpp/torc.nim b/tests/cpp/torc.nim
new file mode 100644
index 000000000..9f1a41a21
--- /dev/null
+++ b/tests/cpp/torc.nim
@@ -0,0 +1,75 @@
+discard """
+  targets: "cpp"
+  matrix: "--gc:orc"
+"""
+
+import std/options
+
+# bug #18410
+type
+  O = object of RootObj
+   val: pointer
+
+proc p(): Option[O] = none(O)
+
+doAssert $p() == "none(O)"
+
+# bug #17351
+type
+  Foo = object of RootObj
+  Foo2 = object of Foo
+  Bar = object
+    x: Foo2
+
+var b = Bar()
+discard b
+
+# bug #4678
+{.emit: """/*TYPESECTION*/
+enum class SomeEnum {A,B,C};
+""".}
+type
+  EnumVector[T: enum] {.importcpp: "std::vector", header: "vector".} = object
+  SomeEnum {.importcpp, nodecl.} = enum
+    A,B,C
+
+proc asVector*[T](t: T): EnumVector[T] =
+  discard
+# Nim generates this signature here:
+# N_NIMCALL(std::vector<> , asvector_106028_3197418230)(SomeEnum t0)
+
+discard asVector(SomeEnum.A)
+
+
+block: # bug #10219
+  type
+    Vector[T]  {.importcpp: "std::vector", header: "vector".} = object
+
+  proc initVector[T](n: csize_t): Vector[T] 
+      {.importcpp: "std::vector<'*0>(@)", header: "vector".}
+
+  proc unsafeIndex[T](this: var Vector[T], i: csize_t): var T 
+      {.importcpp: "#[#]", header: "vector".}
+
+  proc `[]`[T](this: var Vector[T], i: Natural): var T {.inline, noinit.} =
+    when compileOption("boundChecks"):
+        # this.checkIndex i
+        discard
+    result = this.unsafeIndex(csize_t(i))
+
+  var v1 = initVector[int](10)
+  doAssert v1[0] == 0
+
+block: # bug #12703 bug #19588
+  type
+    cstringConstImpl {.importc:"const char*".} = cstring
+    constChar = distinct cstringConstImpl
+
+  {.emit: """
+  const char* foo() {
+    return "hello";
+  }
+  """.}
+  proc foo(): constChar {.importcpp.} # change to importcpp for C++ backend
+  doAssert $(foo().cstring) == "hello"
+
diff --git a/tests/cpp/tpassbypragmas.nim b/tests/cpp/tpassbypragmas.nim
new file mode 100644
index 000000000..f4301656a
--- /dev/null
+++ b/tests/cpp/tpassbypragmas.nim
@@ -0,0 +1,27 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp $file"
+"""
+{.emit:"""/*TYPESECTION*/
+
+  template<typename T>
+  struct Box {
+      T first;
+  };
+  struct Foo {
+  void test(void (*func)(Box<Foo>& another)){
+
+    };
+  };
+""".}
+
+type 
+  Foo {.importcpp.} = object
+  Box[T] {.importcpp:"Box<'0>".} = object
+    first: T
+
+proc test(self: Foo, fn: proc(another {.byref.}: Box[Foo]) {.cdecl.}) {.importcpp.}
+
+proc fn(another {.byref.} : Box[Foo]) {.cdecl.} = discard
+
+Foo().test(fn)
\ No newline at end of file
diff --git a/tests/cpp/tretvar.nim b/tests/cpp/tretvar.nim
index 83c37721e..0c3765346 100644
--- a/tests/cpp/tretvar.nim
+++ b/tests/cpp/tretvar.nim
@@ -16,9 +16,9 @@ type
 
 proc c_str(a: stdString): cstring {.importcpp: "(char *)(#.c_str())", header: "<string>".}
 
-proc len(a: stdString): csize {.importcpp: "(#.length())", header: "<string>".}
+proc len(a: stdString): csize_t {.importcpp: "(#.length())", header: "<string>".}
 
-proc setChar(a: var stdString, i: csize, c: char) {.importcpp: "(#[#] = #)", header: "<string>".}
+proc setChar(a: var stdString, i: csize_t, c: char) {.importcpp: "(#[#] = #)", header: "<string>".}
 
 proc `*`*[T](this: stdUniquePtr[T]): var T {.noSideEffect, importcpp: "(* #)", header: "<memory>".}
 
diff --git a/tests/cpp/ttemplatetype.nim b/tests/cpp/ttemplatetype.nim
index ef24e4cdc..bf243ac43 100644
--- a/tests/cpp/ttemplatetype.nim
+++ b/tests/cpp/ttemplatetype.nim
@@ -3,7 +3,7 @@ discard """
 """
 
 type
-  Map {.importcpp: "std::map", header: "<map>".} [T,U] = object
+  Map[T,U] {.importcpp: "std::map", header: "<map>".} = object
 
 proc cInitMap(T: typedesc, U: typedesc): Map[T,U] {.importcpp: "std::map<'*1,'*2>()", nodecl.}
 
diff --git a/tests/cpp/tterminate_handler.nim b/tests/cpp/tterminate_handler.nim
index 79949f4da..c5ccef53c 100644
--- a/tests/cpp/tterminate_handler.nim
+++ b/tests/cpp/tterminate_handler.nim
@@ -2,8 +2,9 @@ discard """
   targets: "cpp"
   outputsub: "Error: unhandled unknown cpp exception"
   exitcode: 1
+  disabled: true
 """
 type Crap {.importcpp: "int".} = object
 
 var c: Crap
-raise c
\ No newline at end of file
+raise c
diff --git a/tests/cpp/ttypeinfo.nim b/tests/cpp/ttypeinfo1.nim
index 97825f452..97825f452 100644
--- a/tests/cpp/ttypeinfo.nim
+++ b/tests/cpp/ttypeinfo1.nim
diff --git a/tests/cpp/tvector_iterator.nim b/tests/cpp/tvector_iterator.nim
index 4d686955f..c3886c547 100644
--- a/tests/cpp/tvector_iterator.nim
+++ b/tests/cpp/tvector_iterator.nim
@@ -12,8 +12,8 @@ struct Vector {
 """.}
 
 type
-  Vector {.importcpp: "Vector".} [T] = object
-  VectorIterator {.importcpp: "Vector<'0>::Iterator".} [T] = object
+  Vector[T] {.importcpp: "Vector".} = object
+  VectorIterator[T] {.importcpp: "Vector<'0>::Iterator".} = object
 
 var x: VectorIterator[void]
 
diff --git a/tests/cpp/tvirtual.nim b/tests/cpp/tvirtual.nim
new file mode 100644
index 000000000..385d052b8
--- /dev/null
+++ b/tests/cpp/tvirtual.nim
@@ -0,0 +1,126 @@
+discard """
+  targets: "cpp"
+  cmd: "nim cpp $file"
+  output: '''
+hello foo
+hello boo
+hello boo
+Const Message: hello world
+NimPrinter: hello world
+NimPrinterConstRef: hello world
+NimPrinterConstRefByRef: hello world
+'''
+"""
+
+{.emit:"""/*TYPESECTION*/
+#include <iostream>
+  class CppPrinter {
+  public:
+    
+    virtual void printConst(char* message) const {
+        std::cout << "Const Message: " << message << std::endl;
+    }
+    virtual void printConstRef(char* message, const int& flag) const {
+        std::cout << "Const Ref Message: " << message << std::endl;
+    }  
+    virtual void printConstRef2(char* message, const int& flag) const {
+        std::cout << "Const Ref2 Message: " << message << std::endl;
+    }  
+    
+};
+""".}
+
+proc newCpp*[T](): ptr T {.importcpp:"new '*0()".}
+type 
+  Foo = object of RootObj
+  FooPtr = ptr Foo
+  Boo = object of Foo
+  BooPtr = ptr Boo
+  CppPrinter {.importcpp, inheritable.} = object
+  NimPrinter {.exportc.} = object of CppPrinter
+
+proc salute(self: FooPtr) {.virtual.} = 
+  echo "hello foo"
+
+proc salute(self: BooPtr) {.virtual.} =
+  echo "hello boo"
+
+let foo = newCpp[Foo]()
+let boo = newCpp[Boo]()
+let booAsFoo = cast[FooPtr](newCpp[Boo]())
+
+#polymorphism works
+foo.salute()
+boo.salute()
+booAsFoo.salute()
+let message = "hello world".cstring
+
+proc printConst(self: CppPrinter, message: cstring) {.importcpp.}
+CppPrinter().printConst(message)
+
+#notice override is optional. 
+#Will make the cpp compiler to fail if not virtual function with the same signature if found in the base type
+proc printConst(self: NimPrinter, message: cstring) {.virtual:"$1('2 #2) const override".} =
+  echo "NimPrinter: " & $message
+
+proc printConstRef(self: NimPrinter, message: cstring, flag: int32) {.virtual:"$1('2 #2, const '3& #3 ) const override".} =
+  echo "NimPrinterConstRef: " & $message
+
+proc printConstRef2(self: NimPrinter, message: cstring, flag {.byref.}: int32) {.virtual:"$1('2 #2, const '3 #3 ) const override".} =
+  echo "NimPrinterConstRefByRef: " & $message
+
+NimPrinter().printConst(message)
+var val : int32 = 10
+NimPrinter().printConstRef(message, val)
+NimPrinter().printConstRef2(message, val)
+
+#bug 22269
+type Doo = object
+proc naiveMember(x: Doo): int {. virtual .} = 2
+discard naiveMember(Doo())
+
+#asmnostackframe works with virtual
+{.emit:"""/*TYPESECTION*/
+  template<typename T>
+  struct Box {
+      T* first;
+     
+      Box(int x){
+        first = new T(x);
+      };
+  };
+  struct Inner {
+    int val;
+    //Coo() = default;
+    Inner(int x){
+      val = x;
+    };
+  };
+  struct Base {
+    virtual Box<Inner> test() = 0;
+  };
+""".}
+
+type 
+  Inner {.importcpp.} = object
+  Base {.importcpp, inheritable.} = object
+  Child  = object of Base
+  Box[T] {.importcpp, inheritable.} = object
+    first: T
+
+proc makeBox[T](x:int32): Box[T] {.importcpp:"Box<'0>(@)", constructor.}
+
+proc test(self: Child): Box[Inner] {.virtual, asmnostackframe.} = 
+  let res {.exportc.} = makeBox[Inner](100)
+  {.emit:"return res;".}
+  
+
+discard Child().test() 
+
+import virtualptr
+
+#We dont want to pull Loo directly by using it as we are testing that the pointer pulls it. 
+proc makeMoo(): Moo {.importcpp:"{ new Loo() }".}
+
+makeMoo().loo.salute()
+
diff --git a/tests/cpp/virtualptr.nim b/tests/cpp/virtualptr.nim
new file mode 100644
index 000000000..f96264081
--- /dev/null
+++ b/tests/cpp/virtualptr.nim
@@ -0,0 +1,9 @@
+type 
+  Loo* {.exportc.} = object
+  LooPtr* = ptr Loo
+  Moo* {.exportc.} = object 
+    loo*: LooPtr
+
+
+proc salute*(foo: LooPtr) {.virtual.} = 
+  discard 
diff --git a/tests/defaultprocparam/tdefaultprocparam.nim b/tests/defaultprocparam/tdefaultprocparam.nim
deleted file mode 100644
index 5f8c1adab..000000000
--- a/tests/defaultprocparam/tdefaultprocparam.nim
+++ /dev/null
@@ -1,8 +0,0 @@
-discard """
-output: '''
-hi
-'''
-"""
-import mdefaultprocparam
-
-p()
diff --git a/tests/defer/t22309.nim b/tests/defer/t22309.nim
new file mode 100644
index 000000000..34ca4843b
--- /dev/null
+++ b/tests/defer/t22309.nim
@@ -0,0 +1,11 @@
+block:
+  defer:
+    let a = 42
+  doAssert not declared(a)
+
+proc lol() =
+  defer:
+    let a = 42
+  doAssert not declared(a)
+
+lol()
diff --git a/tests/deprecated/tannot.nim b/tests/deprecated/tannot.nim
deleted file mode 100644
index d14f6cc23..000000000
--- a/tests/deprecated/tannot.nim
+++ /dev/null
@@ -1,9 +0,0 @@
-discard """
-  nimout: '''tannot.nim(9, 1) Warning: efgh; foo1 is deprecated [Deprecated]
-tannot.nim(9, 8) Warning: abcd; foo is deprecated [Deprecated]
-'''
-"""
-
-let foo* {.deprecated: "abcd".} = 42
-var foo1* {.deprecated: "efgh".} = 42
-foo1 = foo
diff --git a/tests/deprecated/tmodule1.nim b/tests/deprecated/tmodule1.nim
deleted file mode 100644
index 954836889..000000000
--- a/tests/deprecated/tmodule1.nim
+++ /dev/null
@@ -1,23 +0,0 @@
-discard """
-  nimout: '''tmodule1.nim(11, 8) Warning: goodbye; importme is deprecated [Deprecated]
-tmodule1.nim(14, 10) Warning: Ty is deprecated [Deprecated]
-tmodule1.nim(17, 10) Warning: hello; Ty1 is deprecated [Deprecated]
-tmodule1.nim(20, 8) Warning: aVar is deprecated [Deprecated]
-tmodule1.nim(22, 3) Warning: aProc is deprecated [Deprecated]
-tmodule1.nim(23, 3) Warning: hello; aProc1 is deprecated [Deprecated]
-'''
-"""
-
-import importme
-
-block:
-  var z: Ty
-  z = 0
-block:
-  var z: Ty1
-  z = 0
-block:
-  echo aVar
-block:
-  aProc()
-  aProc1()
diff --git a/tests/deps/jester-#head/jester.nim b/tests/deps/jester-#head/jester.nim
deleted file mode 100644
index 013f0d16d..000000000
--- a/tests/deps/jester-#head/jester.nim
+++ /dev/null
@@ -1,1350 +0,0 @@
-# Copyright (C) 2015 Dominik Picheta
-# MIT License - Look at license.txt for details.
-import net, strtabs, re, tables, parseutils, os, strutils, uri,
-       times, mimetypes, asyncnet, asyncdispatch, macros, md5,
-       logging, httpcore, asyncfile, macrocache, json, options,
-       strformat
-
-import jester/private/[errorpages, utils]
-import jester/[request, patterns]
-
-from cgi import decodeData, decodeUrl, CgiError
-
-export request
-export strtabs
-export tables
-export httpcore
-export MultiData
-export HttpMethod
-export asyncdispatch
-
-export SameSite
-
-when useHttpBeast:
-  import httpbeast except Settings, Request
-  import options
-else:
-  import asynchttpserver except Request
-
-type
-  MatchProc* = proc (request: Request): Future[ResponseData] {.gcsafe, closure.}
-  MatchProcSync* = proc (request: Request): ResponseData{.gcsafe, closure.}
-
-  Matcher = object
-    case async: bool
-    of false:
-      syncProc: MatchProcSync
-    of true:
-      asyncProc: MatchProc
-
-  ErrorProc* = proc (
-    request: Request, error: RouteError
-  ): Future[ResponseData] {.gcsafe, closure.}
-
-  Jester* = object
-    when not useHttpBeast:
-      httpServer*: AsyncHttpServer
-    settings: Settings
-    matchers: seq[Matcher]
-    errorHandlers: seq[ErrorProc]
-
-  MatchType* = enum
-    MRegex, MSpecial, MStatic
-
-  RawHeaders* = seq[tuple[key, val: string]]
-  ResponseData* = tuple[
-    action: CallbackAction,
-    code: HttpCode,
-    headers: Option[RawHeaders],
-    content: string,
-    matched: bool
-  ]
-
-  CallbackAction* = enum
-    TCActionNothing, TCActionSend, TCActionRaw, TCActionPass
-
-  RouteErrorKind* = enum
-    RouteException, RouteCode
-  RouteError* = object
-    case kind*: RouteErrorKind
-    of RouteException:
-      exc: ref Exception
-    of RouteCode:
-      data: ResponseData
-
-const jesterVer = "0.4.0"
-
-proc toStr(headers: Option[RawHeaders]): string =
-  return $newHttpHeaders(headers.get(@({:})))
-
-proc createHeaders(headers: RawHeaders): string =
-  result = ""
-  if headers != nil:
-    for header in headers:
-      let (key, value) = header
-      result.add(key & ": " & value & "\c\L")
-
-    result = result[0 .. ^3] # Strip trailing \c\L
-
-proc createResponse(status: HttpCode, headers: RawHeaders): string =
-  return "HTTP/1.1 " & $status & "\c\L" & createHeaders(headers) & "\c\L\c\L"
-
-proc unsafeSend(request: Request, content: string) =
-  when useHttpBeast:
-    request.getNativeReq.unsafeSend(content)
-  else:
-    # TODO: This may cause issues if we send too fast.
-    asyncCheck request.getNativeReq.client.send(content)
-
-proc send(
-  request: Request, code: HttpCode, headers: Option[RawHeaders], body: string
-) =
-  when useHttpBeast:
-    let h =
-      if headers.isNone: ""
-      else: headers.get().createHeaders
-    request.getNativeReq.send(code, body, h)
-  else:
-    # TODO: This may cause issues if we send too fast.
-    asyncCheck request.getNativeReq.respond(
-      code, body, newHttpHeaders(headers.get(@({:})))
-    )
-
-proc statusContent(request: Request, status: HttpCode, content: string,
-                   headers: Option[RawHeaders]) =
-  try:
-    send(request, status, headers, content)
-    when not defined(release):
-      logging.debug("  $1 $2" % [$status, toStr(headers)])
-  except:
-    logging.error("Could not send response: $1" % osErrorMsg(osLastError()))
-
-# TODO: Add support for proper Future Streams instead of this weird raw mode.
-template enableRawMode* =
-  # TODO: Use the effect system to make this implicit?
-  result.action = TCActionRaw
-
-proc send*(request: Request, content: string) =
-  ## Sends ``content`` immediately to the client socket.
-  ##
-  ## Routes using this procedure must enable raw mode.
-  unsafeSend(request, content)
-
-proc sendHeaders*(request: Request, status: HttpCode,
-                  headers: RawHeaders) =
-  ## Sends ``status`` and ``headers`` to the client socket immediately.
-  ## The user is then able to send the content immediately to the client on
-  ## the fly through the use of ``response.client``.
-  let headerData = createResponse(status, headers)
-  try:
-    request.send(headerData)
-    logging.debug("  $1 $2" % [$status, $headers])
-  except:
-    logging.error("Could not send response: $1" % [osErrorMsg(osLastError())])
-
-proc sendHeaders*(request: Request, status: HttpCode) =
-  ## Sends ``status`` and ``Content-Type: text/html`` as the headers to the
-  ## client socket immediately.
-  let headers = @({"Content-Type": "text/html;charset=utf-8"})
-  request.sendHeaders(status, headers)
-
-proc sendHeaders*(request: Request) =
-  ## Sends ``Http200`` and ``Content-Type: text/html`` as the headers to the
-  ## client socket immediately.
-  request.sendHeaders(Http200)
-
-proc send*(request: Request, status: HttpCode, headers: RawHeaders,
-           content: string) =
-  ## Sends out a HTTP response comprising of the ``status``, ``headers`` and
-  ## ``content`` specified.
-  var headers = headers & @({"Content-Length": $content.len})
-  request.sendHeaders(status, headers)
-  request.send(content)
-
-# TODO: Cannot capture 'paths: varargs[string]' here.
-proc sendStaticIfExists(
-  req: Request, paths: seq[string]
-): Future[HttpCode] {.async.} =
-  result = Http200
-  for p in paths:
-    if existsFile(p):
-
-      var fp = getFilePermissions(p)
-      if not fp.contains(fpOthersRead):
-        return Http403
-
-      let fileSize = getFileSize(p)
-      let mimetype = req.settings.mimes.getMimetype(p.splitFile.ext[1 .. ^1])
-      if fileSize < 10_000_000: # 10 mb
-        var file = readFile(p)
-
-        var hashed = getMD5(file)
-
-        # If the user has a cached version of this file and it matches our
-        # version, let them use it
-        if req.headers.hasKey("If-None-Match") and req.headers["If-None-Match"] == hashed:
-          req.statusContent(Http304, "", none[RawHeaders]())
-        else:
-          req.statusContent(Http200, file, some(@({
-                              "Content-Type": mimetype,
-                              "ETag": hashed
-                            })))
-      else:
-        let headers = @({
-          "Content-Type": mimetype,
-          "Content-Length": $fileSize
-        })
-        req.statusContent(Http200, "", some(headers))
-
-        var fileStream = newFutureStream[string]("sendStaticIfExists")
-        var file = openAsync(p, fmRead)
-        # Let `readToStream` write file data into fileStream in the
-        # background.
-        asyncCheck file.readToStream(fileStream)
-        # The `writeFromStream` proc will complete once all the data in the
-        # `bodyStream` has been written to the file.
-        while true:
-          let (hasValue, value) = await fileStream.read()
-          if hasValue:
-            req.unsafeSend(value)
-          else:
-            break
-        file.close()
-
-      return
-
-  # If we get to here then no match could be found.
-  return Http404
-
-proc defaultErrorFilter(error: RouteError): ResponseData =
-  case error.kind
-  of RouteException:
-    let e = error.exc
-    let traceback = getStackTrace(e)
-    var errorMsg = e.msg
-    if errorMsg.isNil: errorMsg = "(nil)"
-
-    let error = traceback & errorMsg
-    logging.error(error)
-    result.headers = some(@({
-      "Content-Type": "text/html;charset=utf-8"
-    }))
-    result.content = routeException(
-      error.replace("\n", "<br/>\n"),
-      jesterVer
-    )
-    result.code = Http502
-    result.matched = true
-    result.action = TCActionSend
-  of RouteCode:
-    result.headers = some(@({
-      "Content-Type": "text/html;charset=utf-8"
-    }))
-    result.content = error(
-      $error.data.code,
-      jesterVer
-    )
-    result.code = error.data.code
-    result.matched = true
-    result.action = TCActionSend
-
-proc initRouteError(exc: ref Exception): RouteError =
-  RouteError(
-    kind: RouteException,
-    exc: exc
-  )
-
-proc initRouteError(data: ResponseData): RouteError =
-  RouteError(
-    kind: RouteCode,
-    data: data
-  )
-
-proc dispatchError(
-  jes: Jester,
-  request: Request,
-  error: RouteError
-): Future[ResponseData] {.async.} =
-  for errorProc in jes.errorHandlers:
-    let data = await errorProc(request, error)
-    if data.matched:
-      return data
-
-  return defaultErrorFilter(error)
-
-proc dispatch(
-  self: Jester,
-  req: Request
-): Future[ResponseData] {.async.} =
-  for matcher in self.matchers:
-    if matcher.async:
-      let data = await matcher.asyncProc(req)
-      if data.matched:
-        return data
-    else:
-      let data = matcher.syncProc(req)
-      if data.matched:
-        return data
-
-proc handleFileRequest(
-  jes: Jester, req: Request
-): Future[ResponseData] {.async.} =
-  # Find static file.
-  # TODO: Caching.
-  let path = normalizedPath(
-    jes.settings.staticDir / cgi.decodeUrl(req.pathInfo)
-  )
-
-  # Verify that this isn't outside our static` dir.
-  var status = Http400
-  if path.splitFile.dir.startsWith(jes.settings.staticDir):
-    if existsDir(path):
-      status = await sendStaticIfExists(
-        req,
-        @[path / "index.html", path / "index.htm"]
-      )
-    else:
-      status = await sendStaticIfExists(req, @[path])
-
-    # Http200 means that the data was sent so there is nothing else to do.
-    if status == Http200:
-      result[0] = TCActionRaw
-      when not defined(release):
-        logging.debug("  -> $1" % path)
-      return
-
-  return (TCActionSend, status, none[seq[(string, string)]](), "", true)
-
-proc handleRequestSlow(
-  jes: Jester,
-  req: Request,
-  respDataFut: Future[ResponseData] | ResponseData,
-  dispatchedError: bool
-): Future[void] {.async.} =
-  var dispatchedError = dispatchedError
-  var respData: ResponseData
-
-  # httpReq.send(Http200, "Hello, World!", "")
-  try:
-    when respDataFut is Future[ResponseData]:
-      respData = await respDataFut
-    else:
-      respData = respDataFut
-  except:
-    # Handle any errors by showing them in the browser.
-    # TODO: Improve the look of this.
-    let exc = getCurrentException()
-    respData = await dispatchError(jes, req, initRouteError(exc))
-    dispatchedError = true
-
-  # TODO: Put this in a custom matcher?
-  if not respData.matched:
-    respData = await handleFileRequest(jes, req)
-
-  case respData.action
-  of TCActionSend:
-    if (respData.code.is4xx or respData.code.is5xx) and
-        not dispatchedError and respData.content.len == 0:
-      respData = await dispatchError(jes, req, initRouteError(respData))
-
-    statusContent(
-      req,
-      respData.code,
-      respData.content,
-      respData.headers
-    )
-  else:
-    when not defined(release):
-      logging.debug("  $1" % [$respData.action])
-
-  # Cannot close the client socket. AsyncHttpServer may be keeping it alive.
-
-proc handleRequest(jes: Jester, httpReq: NativeRequest): Future[void] =
-  var req = initRequest(httpReq, jes.settings)
-  try:
-    when not defined(release):
-      logging.debug("$1 $2" % [$req.reqMethod, req.pathInfo])
-
-    if likely(jes.matchers.len == 1 and not jes.matchers[0].async):
-      let respData = jes.matchers[0].syncProc(req)
-      if likely(respData.matched):
-        statusContent(
-          req,
-          respData.code,
-          respData.content,
-          respData.headers
-        )
-      else:
-        return handleRequestSlow(jes, req, respData, false)
-    else:
-      return handleRequestSlow(jes, req, dispatch(jes, req), false)
-  except:
-    let exc = getCurrentException()
-    let respDataFut = dispatchError(jes, req, initRouteError(exc))
-    return handleRequestSlow(jes, req, respDataFut, true)
-
-proc newSettings*(
-  port = Port(5000), staticDir = getCurrentDir() / "public",
-  appName = "", bindAddr = "", reusePort = false,
-  futureErrorHandler: proc (fut: Future[void]) {.closure, gcsafe.} = nil
-): Settings =
-  result = Settings(
-    staticDir: staticDir,
-    appName: appName,
-    port: port,
-    bindAddr: bindAddr,
-    reusePort: reusePort,
-    futureErrorHandler: futureErrorHandler
-  )
-
-proc register*(self: var Jester, matcher: MatchProc) =
-  ## Adds the specified matcher procedure to the specified Jester instance.
-  self.matchers.add(
-    Matcher(
-      async: true,
-      asyncProc: matcher
-    )
-  )
-
-proc register*(self: var Jester, matcher: MatchProcSync) =
-  ## Adds the specified matcher procedure to the specified Jester instance.
-  self.matchers.add(
-    Matcher(
-      async: false,
-      syncProc: matcher
-    )
-  )
-
-proc register*(self: var Jester, errorHandler: ErrorProc) =
-  ## Adds the specified error handler procedure to the specified Jester instance.
-  self.errorHandlers.add(errorHandler)
-
-proc initJester*(
-  settings: Settings = newSettings()
-): Jester =
-  result.settings = settings
-  result.settings.mimes = newMimetypes()
-  result.matchers = @[]
-  result.errorHandlers = @[]
-
-proc initJester*(
-  matcher: MatchProc,
-  settings: Settings = newSettings()
-): Jester =
-  result = initJester(settings)
-  result.register(matcher)
-
-proc initJester*(
-  matcher: MatchProcSync, # TODO: Annoying nim bug: `MatchProc | MatchProcSync` doesn't work.
-  settings: Settings = newSettings()
-): Jester =
-  result = initJester(settings)
-  result.register(matcher)
-
-proc serve*(
-  self: var Jester
-) =
-  ## Creates a new async http server instance and registers
-  ## it with the dispatcher.
-  ##
-  ## The event loop is executed by this function, so it will block forever.
-
-  # Ensure we have at least one logger enabled, defaulting to console.
-  if logging.getHandlers().len == 0:
-    addHandler(logging.newConsoleLogger())
-    setLogFilter(when defined(release): lvlInfo else: lvlDebug)
-
-  if self.settings.bindAddr.len > 0:
-    logging.info("Jester is making jokes at http://$1:$2$3" %
-      [
-        self.settings.bindAddr, $self.settings.port, self.settings.appName
-      ]
-    )
-  else:
-    logging.info("Jester is making jokes at http://0.0.0.0:$1$2" %
-                 [$self.settings.port, self.settings.appName])
-
-  var jes = self
-  when useHttpBeast:
-    run(
-      proc (req: httpbeast.Request): Future[void] =
-        result = handleRequest(jes, req),
-      httpbeast.initSettings(self.settings.port, self.settings.bindAddr)
-    )
-  else:
-    self.httpServer = newAsyncHttpServer(reusePort=self.settings.reusePort)
-    let serveFut = self.httpServer.serve(
-      self.settings.port,
-      proc (req: asynchttpserver.Request): Future[void] {.gcsafe, closure.} =
-        result = handleRequest(jes, req),
-      self.settings.bindAddr)
-    if not self.settings.futureErrorHandler.isNil:
-      serveFut.callback = self.settings.futureErrorHandler
-    else:
-      asyncCheck serveFut
-    runForever()
-
-template resp*(code: HttpCode,
-               headers: openarray[tuple[key, value: string]],
-               content: string): typed =
-  ## Sets ``(code, headers, content)`` as the response.
-  bind TCActionSend, newHttpHeaders
-  result = (TCActionSend, code, headers.newHttpHeaders.some(), content, true)
-  break route
-
-template setHeader(headers: var Option[RawHeaders], key, value: string): typed =
-  bind isNone
-  if isNone(headers):
-    headers = some(@({key: value}))
-  else:
-    block outer:
-      # Overwrite key if it exists.
-      var h = headers.get()
-      for i in 0 ..< h.len:
-        if h[i][0] == key:
-          h[i][1] = value
-          headers = some(h)
-          break outer
-
-      # Add key if it doesn't exist.
-      headers = some(h & @({key: value}))
-
-template resp*(content: string, contentType = "text/html;charset=utf-8"): typed =
-  ## Sets ``content`` as the response; ``Http200`` as the status code
-  ## and ``contentType`` as the Content-Type.
-  bind TCActionSend, newHttpHeaders, strtabs.`[]=`
-  result[0] = TCActionSend
-  result[1] = Http200
-  setHeader(result[2], "Content-Type", contentType)
-  result[3] = content
-  # This will be set by our macro, so this is here for those not using it.
-  result.matched = true
-  break route
-
-template resp*(content: JsonNode): typed =
-  ## Serializes ``content`` as the response, sets ``Http200`` as status code
-  ## and "application/json" Content-Type.
-  resp($content, contentType="application/json")
-
-template resp*(code: HttpCode, content: string,
-               contentType = "text/html;charset=utf-8"): typed =
-  ## Sets ``content`` as the response; ``code`` as the status code
-  ## and ``contentType`` as the Content-Type.
-  bind TCActionSend, newHttpHeaders
-  result[0] = TCActionSend
-  result[1] = code
-  setHeader(result[2], "Content-Type", contentType)
-  result[3] = content
-  result.matched = true
-  break route
-
-template resp*(code: HttpCode): typed =
-  ## Responds with the specified ``HttpCode``. This ensures that error handlers
-  ## are called.
-  bind TCActionSend, newHttpHeaders
-  result[0] = TCActionSend
-  result[1] = code
-  result.matched = true
-  break route
-
-template redirect*(url: string): typed =
-  ## Redirects to ``url``. Returns from this request handler immediately.
-  ## Any set response headers are preserved for this request.
-  bind TCActionSend, newHttpHeaders
-  result[0] = TCActionSend
-  result[1] = Http303
-  setHeader(result[2], "Location", url)
-  result[3] = ""
-  result.matched = true
-  break route
-
-template pass*(): typed =
-  ## Skips this request handler.
-  ##
-  ## If you want to stop this request from going further use ``halt``.
-  result.action = TCActionPass
-  break outerRoute
-
-template cond*(condition: bool): typed =
-  ## If ``condition`` is ``False`` then ``pass`` will be called,
-  ## i.e. this request handler will be skipped.
-  if not condition: break outerRoute
-
-template halt*(code: HttpCode,
-               headers: openarray[tuple[key, val: string]],
-               content: string): typed =
-  ## Immediately replies with the specified request. This means any further
-  ## code will not be executed after calling this template in the current
-  ## route.
-  bind TCActionSend, newHttpHeaders
-  result[0] = TCActionSend
-  result[1] = code
-  result[2] = some(@headers)
-  result[3] = content
-  result.matched = true
-  break allRoutes
-
-template halt*(): typed =
-  ## Halts the execution of this request immediately. Returns a 404.
-  ## All previously set values are **discarded**.
-  halt(Http404, {"Content-Type": "text/html;charset=utf-8"}, error($Http404, jesterVer))
-
-template halt*(code: HttpCode): typed =
-  halt(code, {"Content-Type": "text/html;charset=utf-8"}, error($code, jesterVer))
-
-template halt*(content: string): typed =
-  halt(Http404, {"Content-Type": "text/html;charset=utf-8"}, content)
-
-template halt*(code: HttpCode, content: string): typed =
-  halt(code, {"Content-Type": "text/html;charset=utf-8"}, content)
-
-template attachment*(filename = ""): typed =
-  ## Instructs the browser that the response should be stored on disk
-  ## rather than displayed in the browser.
-  var disposition = "attachment"
-  if filename != "":
-    disposition.add("; filename=\"" & extractFilename(filename) & "\"")
-    let ext = splitFile(filename).ext
-    let contentTypeSet =
-      isSome(result[2]) and result[2].get().toTable.hasKey("Content-Type")
-    if not contentTypeSet and ext != "":
-      setHeader(result[2], "Content-Type", getMimetype(request.settings.mimes, ext))
-  setHeader(result[2], "Content-Disposition", disposition)
-
-template sendFile*(filename: string): typed =
-  ## Sends the file at the specified filename as the response.
-  result[0] = TCActionRaw
-  let sendFut = sendStaticIfExists(request, @[filename])
-  yield sendFut
-  let status = sendFut.read()
-  if status != Http200:
-    raise newException(JesterError, "Couldn't send requested file: " & filename)
-  # This will be set by our macro, so this is here for those not using it.
-  result.matched = true
-  break route
-
-template `@`*(s: string): untyped =
-  ## Retrieves the parameter ``s`` from ``request.params``. ``""`` will be
-  ## returned if parameter doesn't exist.
-  if s in params(request):
-    # TODO: Why does request.params not work? :(
-    # TODO: This is some weird bug with macros/templates, I couldn't
-    # TODO: reproduce it easily.
-    params(request)[s]
-  else:
-    ""
-
-proc setStaticDir*(request: Request, dir: string) =
-  ## Sets the directory in which Jester will look for static files. It is
-  ## ``./public`` by default.
-  ##
-  ## The files will be served like so:
-  ##
-  ## ./public/css/style.css ``->`` http://example.com/css/style.css
-  ##
-  ## (``./public`` is not included in the final URL)
-  request.settings.staticDir = dir
-
-proc getStaticDir*(request: Request): string =
-  ## Gets the directory in which Jester will look for static files.
-  ##
-  ## ``./public`` by default.
-  return request.settings.staticDir
-
-proc makeUri*(request: Request, address = "", absolute = true,
-              addScriptName = true): string =
-  ## Creates a URI based on the current request. If ``absolute`` is true it will
-  ## add the scheme (Usually 'http://'), `request.host` and `request.port`.
-  ## If ``addScriptName`` is true `request.appName` will be prepended before
-  ## ``address``.
-
-  # Check if address already starts with scheme://
-  var uri = parseUri(address)
-
-  if uri.scheme != "": return address
-  uri.path = "/"
-  uri.query = ""
-  uri.anchor = ""
-  if absolute:
-    uri.hostname = request.host
-    uri.scheme = (if request.secure: "https" else: "http")
-    if request.port != (if request.secure: 443 else: 80):
-      uri.port = $request.port
-
-  if addScriptName: uri = uri / request.appName
-  if address != "":
-    uri = uri / address
-  else:
-    uri = uri / request.pathInfo
-  return $uri
-
-template uri*(address = "", absolute = true, addScriptName = true): untyped =
-  ## Convenience template which can be used in a route.
-  request.makeUri(address, absolute, addScriptName)
-
-proc daysForward*(days: int): DateTime =
-  ## Returns a DateTime object referring to the current time plus ``days``.
-  return getTime().utc + initInterval(days = days)
-
-template setCookie*(name, value: string, expires="",
-                    sameSite: SameSite=Lax): typed =
-  ## Creates a cookie which stores ``value`` under ``name``.
-  ##
-  ## The SameSite argument determines the level of CSRF protection that
-  ## you wish to adopt for this cookie. It's set to Lax by default which
-  ## should protect you from most vulnerabilities. Note that this is only
-  ## supported by some browsers:
-  ## https://caniuse.com/#feat=same-site-cookie-attribute
-  let newCookie = makeCookie(name, value, expires)
-  if isSome(result[2]) and
-     (let headers = result[2].get(); headers.toTable.hasKey("Set-Cookie")):
-    result[2] = some(headers & @({"Set-Cookie": newCookie}))
-  else:
-    setHeader(result[2], "Set-Cookie", newCookie)
-
-template setCookie*(name, value: string, expires: DateTime,
-                    sameSite: SameSite=Lax): typed =
-  ## Creates a cookie which stores ``value`` under ``name``.
-  setCookie(name, value, format(expires, "ddd',' dd MMM yyyy HH:mm:ss 'GMT'"))
-
-proc normalizeUri*(uri: string): string =
-  ## Remove any trailing ``/``.
-  if uri[uri.len-1] == '/': result = uri[0 .. uri.len-2]
-  else: result = uri
-
-# -- Macro
-
-proc checkAction*(respData: var ResponseData): bool =
-  case respData.action
-  of TCActionSend, TCActionRaw:
-    result = true
-  of TCActionPass:
-    result = false
-  of TCActionNothing:
-    assert(false)
-
-proc skipDo(node: NimNode): NimNode {.compiletime.} =
-  if node.kind == nnkDo:
-    result = node[6]
-  else:
-    result = node
-
-proc ctParsePattern(pattern, pathPrefix: string): NimNode {.compiletime.} =
-  result = newNimNode(nnkPrefix)
-  result.add newIdentNode("@")
-  result.add newNimNode(nnkBracket)
-
-  proc addPattNode(res: var NimNode, typ, text,
-                   optional: NimNode) {.compiletime.} =
-    var objConstr = newNimNode(nnkObjConstr)
-
-    objConstr.add bindSym("Node")
-    objConstr.add newNimNode(nnkExprColonExpr).add(
-        newIdentNode("typ"), typ)
-    objConstr.add newNimNode(nnkExprColonExpr).add(
-        newIdentNode("text"), text)
-    objConstr.add newNimNode(nnkExprColonExpr).add(
-        newIdentNode("optional"), optional)
-
-    res[1].add objConstr
-
-  var patt = parsePattern(pattern)
-  if pathPrefix.len > 0:
-    result.addPattNode(
-      bindSym("NodeText"), # Node kind
-      newStrLitNode(pathPrefix), # Text
-      newIdentNode("false") # Optional?
-    )
-
-  for node in patt:
-    result.addPattNode(
-      case node.typ
-      of NodeText: bindSym("NodeText")
-      of NodeField: bindSym("NodeField"),
-      newStrLitNode(node.text),
-      newIdentNode(if node.optional: "true" else: "false"))
-
-template setDefaultResp*(): typed =
-  # TODO: bindSym this in the 'routes' macro and put it in each route
-  bind TCActionNothing, newHttpHeaders
-  result.action = TCActionNothing
-  result.code = Http200
-  result.content = ""
-
-template declareSettings(): typed {.dirty.} =
-  when not declaredInScope(settings):
-    var settings = newSettings()
-
-proc createJesterPattern(
-  routeNode, patternMatchSym: NimNode,
-  pathPrefix: string
-): NimNode {.compileTime.} =
-  var ctPattern = ctParsePattern(routeNode[1].strVal, pathPrefix)
-  # -> let <patternMatchSym> = <ctPattern>.match(request.path)
-  return newLetStmt(patternMatchSym,
-      newCall(bindSym"match", ctPattern, parseExpr("request.pathInfo")))
-
-proc escapeRegex(s: string): string =
-  result = ""
-  for i in s:
-    case i
-    # https://stackoverflow.com/a/400316/492186
-    of '.', '^', '$', '*', '+', '?', '(', ')', '[', '{', '\\', '|':
-      result.add('\\')
-      result.add(i)
-    else:
-      result.add(i)
-
-proc createRegexPattern(
-  routeNode, reMatchesSym, patternMatchSym: NimNode,
-  pathPrefix: string
-): NimNode {.compileTime.} =
-  # -> let <patternMatchSym> = find(request.pathInfo, <pattern>, <reMatches>)
-  var strNode = routeNode[1].copyNimTree()
-  strNode[1].strVal = escapeRegex(pathPrefix) & strNode[1].strVal
-  return newLetStmt(
-    patternMatchSym,
-    newCall(
-      bindSym"find",
-      parseExpr("request.pathInfo"),
-      strNode,
-      reMatchesSym
-    )
-  )
-
-proc determinePatternType(pattern: NimNode): MatchType {.compileTime.} =
-  case pattern.kind
-  of nnkStrLit:
-    var patt = parsePattern(pattern.strVal)
-    if patt.len == 1 and patt[0].typ == NodeText:
-      return MStatic
-    else:
-      return MSpecial
-  of nnkCallStrLit:
-    expectKind(pattern[0], nnkIdent)
-    case ($pattern[0]).normalize
-    of "re": return MRegex
-    else:
-      macros.error("Invalid pattern type: " & $pattern[0])
-  else:
-    macros.error("Unexpected node kind: " & $pattern.kind)
-
-proc createCheckActionIf(): NimNode =
-  var checkActionIf = parseExpr(
-    "if checkAction(result): result.matched = true; break routesList"
-  )
-  checkActionIf[0][0][0] = bindSym"checkAction"
-  return checkActionIf
-
-proc createGlobalMetaRoute(routeNode, dest: NimNode) {.compileTime.} =
-  ## Creates a ``before`` or ``after`` route with no pattern, i.e. one which
-  ## will be always executed.
-
-  # -> block route: <ifStmtBody>
-  var innerBlockStmt = newStmtList(
-    newNimNode(nnkBlockStmt).add(newIdentNode("route"), routeNode[1].skipDo())
-  )
-
-  # -> block outerRoute: <innerBlockStmt>
-  var blockStmt = newNimNode(nnkBlockStmt).add(
-    newIdentNode("outerRoute"), innerBlockStmt)
-  dest.add blockStmt
-
-proc createRoute(
-  routeNode, dest: NimNode, pathPrefix: string, isMetaRoute: bool = false
-) {.compileTime.} =
-  ## Creates code which checks whether the current request path
-  ## matches a route.
-  ##
-  ## The `isMetaRoute` parameter determines whether the route to be created is
-  ## one of either a ``before`` or an ``after`` route.
-
-  var patternMatchSym = genSym(nskLet, "patternMatchRet")
-
-  # Only used for Regex patterns.
-  var reMatchesSym = genSym(nskVar, "reMatches")
-  var reMatches = parseExpr("var reMatches: array[20, string]")
-  reMatches[0][0] = reMatchesSym
-  reMatches[0][1][1] = bindSym("MaxSubpatterns")
-
-  let patternType = determinePatternType(routeNode[1])
-  case patternType
-  of MStatic:
-    discard
-  of MSpecial:
-    dest.add createJesterPattern(routeNode, patternMatchSym, pathPrefix)
-  of MRegex:
-    dest.add reMatches
-    dest.add createRegexPattern(
-      routeNode, reMatchesSym, patternMatchSym, pathPrefix
-    )
-
-  var ifStmtBody = newStmtList()
-  case patternType
-  of MStatic: discard
-  of MSpecial:
-    # -> setPatternParams(request, ret.params)
-    ifStmtBody.add newCall(bindSym"setPatternParams", newIdentNode"request",
-                           newDotExpr(patternMatchSym, newIdentNode"params"))
-  of MRegex:
-    # -> setReMatches(request, <reMatchesSym>)
-    ifStmtBody.add newCall(bindSym"setReMatches", newIdentNode"request",
-                           reMatchesSym)
-
-  ifStmtBody.add routeNode[2].skipDo()
-
-  let checkActionIf =
-    if isMetaRoute:
-      parseExpr("break routesList")
-    else:
-      createCheckActionIf()
-  # -> block route: <ifStmtBody>; <checkActionIf>
-  var innerBlockStmt = newStmtList(
-    newNimNode(nnkBlockStmt).add(newIdentNode("route"), ifStmtBody),
-    checkActionIf
-  )
-
-  let ifCond =
-    case patternType
-    of MStatic:
-      infix(
-        parseExpr("request.pathInfo"),
-        "==",
-        newStrLitNode(pathPrefix & routeNode[1].strVal)
-      )
-    of MSpecial:
-      newDotExpr(patternMatchSym, newIdentNode("matched"))
-    of MRegex:
-      infix(patternMatchSym, "!=", newIntLitNode(-1))
-
-  # -> if <patternMatchSym>.matched: <innerBlockStmt>
-  var ifStmt = newIfStmt((ifCond, innerBlockStmt))
-
-  # -> block outerRoute: <ifStmt>
-  var blockStmt = newNimNode(nnkBlockStmt).add(
-    newIdentNode("outerRoute"), ifStmt)
-  dest.add blockStmt
-
-proc createError(
-  errorNode: NimNode,
-  httpCodeBranches,
-  exceptionBranches: var seq[tuple[cond, body: NimNode]]
-) =
-  if errorNode.len != 3:
-    error("Missing error condition or body.", errorNode)
-
-  let routeIdent = newIdentNode("route")
-  let outerRouteIdent = newIdentNode("outerRoute")
-  let checkActionIf = createCheckActionIf()
-  let exceptionIdent = newIdentNode("exception")
-  let errorIdent = newIdentNode("error") # TODO: Ugh. I shouldn't need these...
-  let errorCond = errorNode[1]
-  let errorBody = errorNode[2]
-  let body = quote do:
-    block `outerRouteIdent`:
-      block `routeIdent`:
-        `errorBody`
-      `checkActionIf`
-
-  case errorCond.kind
-  of nnkIdent:
-    let name = errorCond.strVal
-    if name.len == 7 and name.startsWith("Http"):
-      # HttpCode.
-      httpCodeBranches.add(
-        (
-          infix(parseExpr("error.data.code"), "==", errorCond),
-          body
-        )
-      )
-    else:
-      # Exception
-      exceptionBranches.add(
-        (
-          infix(parseExpr("error.exc"), "of", errorCond),
-          quote do:
-            let `exceptionIdent` = (ref `errorCond`)(`errorIdent`.exc)
-            `body`
-        )
-      )
-  of nnkCurly:
-    expectKind(errorCond[0], nnkInfix)
-    httpCodeBranches.add(
-      (
-        infix(parseExpr("error.data.code"), "in", errorCond),
-        body
-      )
-    )
-  else:
-    error("Expected exception type or set[HttpCode].", errorCond)
-
-const definedRoutes = CacheTable"jester.routes"
-
-proc processRoutesBody(
-  body: NimNode,
-  # For HTTP methods.
-  caseStmtGetBody,
-  caseStmtPostBody,
-  caseStmtPutBody,
-  caseStmtDeleteBody,
-  caseStmtHeadBody,
-  caseStmtOptionsBody,
-  caseStmtTraceBody,
-  caseStmtConnectBody,
-  caseStmtPatchBody: var NimNode,
-  # For `error`.
-  httpCodeBranches,
-  exceptionBranches: var seq[tuple[cond, body: NimNode]],
-  # For before/after stmts.
-  beforeStmts,
-  afterStmts: var NimNode,
-  # For other statements.
-  outsideStmts: var NimNode,
-  pathPrefix: string
-) =
-  for i in 0..<body.len:
-    case body[i].kind
-    of nnkCall:
-      let cmdName = body[i][0].`$`.normalize
-      case cmdName
-      of "before":
-        createGlobalMetaRoute(body[i], beforeStmts)
-      of "after":
-        createGlobalMetaRoute(body[i], afterStmts)
-      else:
-        outsideStmts.add(body[i])
-    of nnkCommand:
-      let cmdName = body[i][0].`$`.normalize
-      case cmdName
-      # HTTP Methods
-      of "get":
-        createRoute(body[i], caseStmtGetBody, pathPrefix)
-      of "post":
-        createRoute(body[i], caseStmtPostBody, pathPrefix)
-      of "put":
-        createRoute(body[i], caseStmtPutBody, pathPrefix)
-      of "delete":
-        createRoute(body[i], caseStmtDeleteBody, pathPrefix)
-      of "head":
-        createRoute(body[i], caseStmtHeadBody, pathPrefix)
-      of "options":
-        createRoute(body[i], caseStmtOptionsBody, pathPrefix)
-      of "trace":
-        createRoute(body[i], caseStmtTraceBody, pathPrefix)
-      of "connect":
-        createRoute(body[i], caseStmtConnectBody, pathPrefix)
-      of "patch":
-        createRoute(body[i], caseStmtPatchBody, pathPrefix)
-      # Other
-      of "error":
-        createError(body[i], httpCodeBranches, exceptionBranches)
-      of "before":
-        createRoute(body[i], beforeStmts, pathPrefix, isMetaRoute=true)
-      of "after":
-        createRoute(body[i], afterStmts, pathPrefix, isMetaRoute=true)
-      of "extend":
-        # Extend another router.
-        let extend = body[i]
-        if extend[1].kind != nnkIdent:
-          error("Expected identifier.", extend[1])
-
-        let prefix =
-          if extend.len > 1:
-            extend[2].strVal
-          else:
-            ""
-        if prefix.len != 0 and prefix[0] != '/':
-          error("Path prefix for extended route must start with '/'", extend[2])
-
-        processRoutesBody(
-          definedRoutes[extend[1].strVal],
-          caseStmtGetBody,
-          caseStmtPostBody,
-          caseStmtPutBody,
-          caseStmtDeleteBody,
-          caseStmtHeadBody,
-          caseStmtOptionsBody,
-          caseStmtTraceBody,
-          caseStmtConnectBody,
-          caseStmtPatchBody,
-          httpCodeBranches,
-          exceptionBranches,
-          beforeStmts,
-          afterStmts,
-          outsideStmts,
-          pathPrefix & prefix
-        )
-      else:
-        outsideStmts.add(body[i])
-    of nnkCommentStmt:
-      discard
-    of nnkPragma:
-      if body[i][0].strVal.normalize notin ["async", "sync"]:
-        outsideStmts.add(body[i])
-    else:
-      outsideStmts.add(body[i])
-
-type
-  NeedsAsync = enum
-    ImplicitTrue, ImplicitFalse, ExplicitTrue, ExplicitFalse
-proc needsAsync(node: NimNode): NeedsAsync =
-  result = ImplicitFalse
-  case node.kind
-  of nnkCommand, nnkCall:
-    if node[0].kind == nnkIdent:
-      case node[0].strVal.normalize
-      of "await", "sendfile":
-        return ImplicitTrue
-      of "resp", "halt", "attachment", "pass", "redirect", "cond", "get",
-         "post", "patch", "delete":
-        # This is just a simple heuristic. It's by no means meant to be
-        # exhaustive.
-        discard
-      else:
-        return ImplicitTrue
-  of nnkYieldStmt:
-    return ImplicitTrue
-  of nnkPragma:
-    if node[0].kind == nnkIdent:
-      case node[0].strVal.normalize
-      of "sync":
-        return ExplicitFalse
-      of "async":
-        return ExplicitTrue
-      else: discard
-  else: discard
-
-  for c in node:
-    let r = needsAsync(c)
-    if r in {ImplicitTrue, ExplicitTrue, ExplicitFalse}: return r
-
-proc routesEx(name: string, body: NimNode): NimNode =
-  # echo(treeRepr(body))
-  # echo(treeRepr(name))
-
-  # Save this route's body so that it can be incorporated into another route.
-  definedRoutes[name] = body.copyNimTree
-
-  result = newStmtList()
-
-  # -> declareSettings()
-  result.add newCall(bindSym"declareSettings")
-
-  var outsideStmts = newStmtList()
-
-  var matchBody = newNimNode(nnkStmtList)
-  let setDefaultRespIdent = bindSym"setDefaultResp"
-  matchBody.add newCall(setDefaultRespIdent)
-  # TODO: This diminishes the performance. Would be nice to only include it
-  # TODO: when setPatternParams or setReMatches is used.
-  matchBody.add parseExpr("var request = request")
-
-  # HTTP router case statement nodes:
-  var caseStmt = newNimNode(nnkCaseStmt)
-  caseStmt.add parseExpr("request.reqMethod")
-
-  var caseStmtGetBody = newNimNode(nnkStmtList)
-  var caseStmtPostBody = newNimNode(nnkStmtList)
-  var caseStmtPutBody = newNimNode(nnkStmtList)
-  var caseStmtDeleteBody = newNimNode(nnkStmtList)
-  var caseStmtHeadBody = newNimNode(nnkStmtList)
-  var caseStmtOptionsBody = newNimNode(nnkStmtList)
-  var caseStmtTraceBody = newNimNode(nnkStmtList)
-  var caseStmtConnectBody = newNimNode(nnkStmtList)
-  var caseStmtPatchBody = newNimNode(nnkStmtList)
-
-  # Error handler nodes:
-  var httpCodeBranches: seq[tuple[cond, body: NimNode]] = @[]
-  var exceptionBranches: seq[tuple[cond, body: NimNode]] = @[]
-
-  # Before/After nodes:
-  var beforeRoutes = newStmtList()
-  var afterRoutes = newStmtList()
-
-  processRoutesBody(
-    body,
-    caseStmtGetBody,
-    caseStmtPostBody,
-    caseStmtPutBody,
-    caseStmtDeleteBody,
-    caseStmtHeadBody,
-    caseStmtOptionsBody,
-    caseStmtTraceBody,
-    caseStmtConnectBody,
-    caseStmtPatchBody,
-    httpCodeBranches,
-    exceptionBranches,
-    beforeRoutes,
-    afterRoutes,
-    outsideStmts,
-    ""
-  )
-
-  var ofBranchGet = newNimNode(nnkOfBranch)
-  ofBranchGet.add newIdentNode("HttpGet")
-  ofBranchGet.add caseStmtGetBody
-  caseStmt.add ofBranchGet
-
-  var ofBranchPost = newNimNode(nnkOfBranch)
-  ofBranchPost.add newIdentNode("HttpPost")
-  ofBranchPost.add caseStmtPostBody
-  caseStmt.add ofBranchPost
-
-  var ofBranchPut = newNimNode(nnkOfBranch)
-  ofBranchPut.add newIdentNode("HttpPut")
-  ofBranchPut.add caseStmtPutBody
-  caseStmt.add ofBranchPut
-
-  var ofBranchDelete = newNimNode(nnkOfBranch)
-  ofBranchDelete.add newIdentNode("HttpDelete")
-  ofBranchDelete.add caseStmtDeleteBody
-  caseStmt.add ofBranchDelete
-
-  var ofBranchHead = newNimNode(nnkOfBranch)
-  ofBranchHead.add newIdentNode("HttpHead")
-  ofBranchHead.add caseStmtHeadBody
-  caseStmt.add ofBranchHead
-
-  var ofBranchOptions = newNimNode(nnkOfBranch)
-  ofBranchOptions.add newIdentNode("HttpOptions")
-  ofBranchOptions.add caseStmtOptionsBody
-  caseStmt.add ofBranchOptions
-
-  var ofBranchTrace = newNimNode(nnkOfBranch)
-  ofBranchTrace.add newIdentNode("HttpTrace")
-  ofBranchTrace.add caseStmtTraceBody
-  caseStmt.add ofBranchTrace
-
-  var ofBranchConnect = newNimNode(nnkOfBranch)
-  ofBranchConnect.add newIdentNode("HttpConnect")
-  ofBranchConnect.add caseStmtConnectBody
-  caseStmt.add ofBranchConnect
-
-  var ofBranchPatch = newNimNode(nnkOfBranch)
-  ofBranchPatch.add newIdentNode("HttpPatch")
-  ofBranchPatch.add caseStmtPatchBody
-  caseStmt.add ofBranchPatch
-
-  # Wrap the routes inside ``routesList`` blocks accordingly, and add them to
-  # the `match` procedure body.
-  let routesListIdent = newIdentNode("routesList")
-  matchBody.add(
-    quote do:
-      block `routesListIdent`:
-        `beforeRoutes`
-  )
-
-  matchBody.add(
-    quote do:
-      block `routesListIdent`:
-        `caseStmt`
-  )
-
-  matchBody.add(
-    quote do:
-      block `routesListIdent`:
-        `afterRoutes`
-  )
-
-  let matchIdent = newIdentNode(name)
-  let reqIdent = newIdentNode("request")
-  let needsAsync = needsAsync(body)
-  case needsAsync
-  of ImplicitFalse, ExplicitFalse:
-    hint(fmt"Synchronous route `{name}` has been optimised. Use `{{.async.}}` to change.")
-  of ImplicitTrue, ExplicitTrue:
-    hint(fmt"Asynchronous route: {name}.")
-  var matchProc =
-    if needsAsync in {ImplicitTrue, ExplicitTrue}:
-      quote do:
-        proc `matchIdent`(
-          `reqIdent`: Request
-        ): Future[ResponseData] {.async, gcsafe.} =
-          discard
-    else:
-      quote do:
-        proc `matchIdent`(
-          `reqIdent`: Request
-        ): ResponseData {.gcsafe.} =
-          discard
-
-  # The following `block` is for `halt`. (`return` didn't work :/)
-  let allRoutesBlock = newTree(
-    nnkBlockStmt,
-    newIdentNode("allRoutes"),
-    matchBody
-  )
-  matchProc[6] = newTree(nnkStmtList, allRoutesBlock)
-  result.add(outsideStmts)
-  result.add(matchProc)
-
-  # Error handler proc
-  let errorHandlerIdent = newIdentNode(name & "ErrorHandler")
-  let errorIdent = newIdentNode("error")
-  let exceptionIdent = newIdentNode("exception")
-  let resultIdent = newIdentNode("result")
-  var errorHandlerProc = quote do:
-    proc `errorHandlerIdent`(
-      `reqIdent`: Request, `errorIdent`: RouteError
-    ): Future[ResponseData] {.gcsafe, async.} =
-      block `routesListIdent`:
-        `setDefaultRespIdent`()
-        case `errorIdent`.kind
-        of RouteException:
-          discard
-        of RouteCode:
-          discard
-  if exceptionBranches.len != 0:
-    var stmts = newStmtList()
-    for branch in exceptionBranches:
-      stmts.add(newIfStmt(branch))
-    errorHandlerProc[6][0][1][^1][1][1][0] = stmts
-  if httpCodeBranches.len > 1:
-    var stmts = newStmtList()
-    for branch in httpCodeBranches:
-      stmts.add(newIfStmt(branch))
-    errorHandlerProc[6][0][1][^1][2][1][0] = stmts
-  result.add(errorHandlerProc)
-
-  # TODO: Replace `body`, `headers`, `code` in routes with `result[i]` to
-  # get these shortcuts back without sacrificing usability.
-  # TODO2: Make sure you replace what `guessAction` used to do for this.
-
-  # echo toStrLit(result)
-  # echo treeRepr(result)
-
-macro routes*(body: untyped): typed =
-  result = routesEx("match", body)
-  let jesIdent = genSym(nskVar, "jes")
-  let matchIdent = newIdentNode("match")
-  let errorHandlerIdent = newIdentNode("matchErrorHandler")
-  let settingsIdent = newIdentNode("settings")
-  result.add(
-    quote do:
-      var `jesIdent` = initJester(`matchIdent`, `settingsIdent`)
-      `jesIdent`.register(`errorHandlerIdent`)
-  )
-  result.add(
-    quote do:
-      serve(`jesIdent`)
-  )
-
-macro router*(name: untyped, body: untyped): typed =
-  if name.kind != nnkIdent:
-    error("Need an ident.", name)
-
-  routesEx($name.ident, body)
-
-macro settings*(body: untyped): typed =
-  #echo(treeRepr(body))
-  expectKind(body, nnkStmtList)
-
-  result = newStmtList()
-
-  # var settings = newSettings()
-  let settingsIdent = newIdentNode("settings")
-  result.add newVarStmt(settingsIdent, newCall("newSettings"))
-
-  for asgn in body.children:
-    expectKind(asgn, nnkAsgn)
-    result.add newAssignment(newDotExpr(settingsIdent, asgn[0]), asgn[1])
diff --git a/tests/deps/jester-#head/jester.nimble b/tests/deps/jester-#head/jester.nimble
deleted file mode 100644
index 08e990bd7..000000000
--- a/tests/deps/jester-#head/jester.nimble
+++ /dev/null
@@ -1,22 +0,0 @@
-# Package
-
-version       = "0.4.0" # Be sure to update jester.jesterVer too!
-author        = "Dominik Picheta"
-description   = "A sinatra-like web framework for Nim."
-license       = "MIT"
-
-skipFiles = @["todo.markdown"]
-skipDirs = @["tests"]
-
-# Deps
-
-requires "nim >= 0.18.1"
-
-when not defined(windows):
-  requires "httpbeast >= 0.2.0"
-
-# For tests
-requires "asynctools"
-
-task test, "Runs the test suite.":
-  exec "nimble c -y -r tests/tester"
\ No newline at end of file
diff --git a/tests/deps/jester-#head/jester/patterns.nim b/tests/deps/jester-#head/jester/patterns.nim
deleted file mode 100644
index c827fbc7f..000000000
--- a/tests/deps/jester-#head/jester/patterns.nim
+++ /dev/null
@@ -1,141 +0,0 @@
-# Copyright (C) 2012-2018 Dominik Picheta
-# MIT License - Look at license.txt for details.
-import parseutils, tables
-type
-  NodeType* = enum
-    NodeText, NodeField
-  Node* = object
-    typ*: NodeType
-    text*: string
-    optional*: bool
-  
-  Pattern* = seq[Node]
-
-#/show/@id/?
-proc parsePattern*(pattern: string): Pattern =
-  result = @[]
-  template addNode(result: var Pattern, theT: NodeType, theText: string,
-                   isOptional: bool): typed =
-    block:
-      var newNode: Node
-      newNode.typ = theT
-      newNode.text = theText
-      newNode.optional = isOptional
-      result.add(newNode)
-
-  template `{}`(s: string, i: int): char =
-    if i >= len(s):
-      '\0'
-    else:
-      s[i]
-
-  var i = 0
-  var text = ""
-  while i < pattern.len():
-    case pattern[i]
-    of '@':
-      # Add the stored text.
-      if text != "":
-        result.addNode(NodeText, text, false)
-        text = ""
-      # Parse named parameter.
-      inc(i) # Skip @
-      var nparam = ""
-      i += pattern.parseUntil(nparam, {'/', '?'}, i)
-      var optional = pattern{i} == '?'
-      result.addNode(NodeField, nparam, optional)
-      if pattern{i} == '?': inc(i) # Only skip ?. / should not be skipped.
-    of '?':
-      var optionalChar = text[^1]
-      setLen(text, text.len-1) # Truncate ``text``.
-      # Add the stored text.
-      if text != "":
-        result.addNode(NodeText, text, false)
-        text = ""
-      # Add optional char.
-      inc(i) # Skip ?
-      result.addNode(NodeText, $optionalChar, true)
-    of '\\':
-      inc i # Skip \
-      if pattern[i] notin {'?', '@', '\\'}:
-        raise newException(ValueError, 
-                "This character does not require escaping: " & pattern[i])
-      text.add(pattern{i})
-      inc i # Skip ``pattern[i]``
-    else:
-      text.add(pattern{i})
-      inc(i)
-  
-  if text != "":
-    result.addNode(NodeText, text, false)
-
-proc findNextText(pattern: Pattern, i: int, toNode: var Node): bool =
-  ## Finds the next NodeText in the pattern, starts looking from ``i``.
-  result = false
-  for n in i..pattern.len()-1:
-    if pattern[n].typ == NodeText:
-      toNode = pattern[n]
-      return true
-
-proc check(n: Node, s: string, i: int): bool =
-  let cutTo = (n.text.len-1)+i
-  if cutTo > s.len-1: return false
-  return s.substr(i, cutTo) == n.text
-
-proc match*(pattern: Pattern, s: string):
-      tuple[matched: bool, params: Table[string, string]] =
-  var i = 0 # Location in ``s``.
-
-  result.matched = true
-  result.params = initTable[string, string]()
-
-  for ncount, node in pattern:
-    case node.typ
-    of NodeText:
-      if node.optional:
-        if check(node, s, i):
-          inc(i, node.text.len) # Skip over this optional character.
-        else:
-          # If it's not there, we have nothing to do. It's optional after all.
-          discard
-      else:
-        if check(node, s, i):
-          inc(i, node.text.len) # Skip over this
-        else:
-          # No match.
-          result.matched = false
-          return
-    of NodeField:
-      var nextTxtNode: Node
-      var stopChar = '/'
-      if findNextText(pattern, ncount, nextTxtNode):
-        stopChar = nextTxtNode.text[0]
-      var matchNamed = ""
-      i += s.parseUntil(matchNamed, stopChar, i)
-      result.params[node.text] = matchNamed
-      if matchNamed == "" and not node.optional:
-        result.matched = false
-        return
-
-  if s.len != i:
-    result.matched = false
-
-when true:
-  let f = parsePattern("/show/@id/test/@show?/?")
-  doAssert match(f, "/show/12/test/hallo/").matched
-  doAssert match(f, "/show/2131726/test/jjjuuwąąss").matched
-  doAssert(not match(f, "/").matched)
-  doAssert(not match(f, "/show//test//").matched)
-  doAssert(match(f, "/show/asd/test//").matched)
-  doAssert(not match(f, "/show/asd/asd/test/jjj/").matched)
-  doAssert(match(f, "/show/@łę¶ŧ←/test/asd/").params["id"] == "@łę¶ŧ←")
-
-  let f2 = parsePattern("/test42/somefile.?@ext?/?")
-  doAssert(match(f2, "/test42/somefile/").params["ext"] == "")
-  doAssert(match(f2, "/test42/somefile.txt").params["ext"] == "txt")
-  doAssert(match(f2, "/test42/somefile.txt/").params["ext"] == "txt")
-  
-  let f3 = parsePattern(r"/test32/\@\\\??")
-  doAssert(match(f3, r"/test32/@\").matched)
-  doAssert(not match(f3, r"/test32/@\\").matched)
-  doAssert(match(f3, r"/test32/@\?").matched)
diff --git a/tests/deps/jester-#head/jester/private/errorpages.nim b/tests/deps/jester-#head/jester/private/errorpages.nim
deleted file mode 100644
index d1e695040..000000000
--- a/tests/deps/jester-#head/jester/private/errorpages.nim
+++ /dev/null
@@ -1,19 +0,0 @@
-# Copyright (C) 2012 Dominik Picheta
-# MIT License - Look at license.txt for details.
-import htmlgen
-proc error*(err, jesterVer: string): string =
-   return html(head(title(err)),
-               body(h1(err),
-                    "<hr/>",
-                    p("Jester " & jesterVer),
-                    style = "text-align: center;"
-               ),
-               xmlns="http://www.w3.org/1999/xhtml")
-
-proc routeException*(error: string, jesterVer: string): string =
-  return html(head(title("Jester route exception")),
-              body(
-                h1("An error has occured in one of your routes."),
-                p(b("Detail: "), error)
-              ),
-             xmlns="http://www.w3.org/1999/xhtml")
diff --git a/tests/deps/jester-#head/jester/private/utils.nim b/tests/deps/jester-#head/jester/private/utils.nim
deleted file mode 100644
index 16dce61fe..000000000
--- a/tests/deps/jester-#head/jester/private/utils.nim
+++ /dev/null
@@ -1,195 +0,0 @@
-# Copyright (C) 2012 Dominik Picheta
-# MIT License - Look at license.txt for details.
-import parseutils, strtabs, strutils, tables, net, mimetypes, asyncdispatch, os
-from cgi import decodeUrl
-
-const
-  useHttpBeast* = false # not defined(windows) and not defined(useStdLib)
-
-type
-  MultiData* = OrderedTable[string, tuple[fields: StringTableRef, body: string]]
-
-  Settings* = ref object
-    staticDir*: string # By default ./public
-    appName*: string
-    mimes*: MimeDb
-    port*: Port
-    bindAddr*: string
-    reusePort*: bool
-    futureErrorHandler*: proc (fut: Future[void]) {.closure, gcsafe.}
-
-  JesterError* = object of Exception
-
-proc parseUrlQuery*(query: string, result: var Table[string, string])
-    {.deprecated: "use stdlib".} =
-  var i = 0
-  i = query.skip("?")
-  while i < query.len()-1:
-    var key = ""
-    var val = ""
-    i += query.parseUntil(key, '=', i)
-    if query[i] != '=':
-      raise newException(ValueError, "Expected '=' at " & $i &
-                         " but got: " & $query[i])
-    inc(i) # Skip =
-    i += query.parseUntil(val, '&', i)
-    inc(i) # Skip &
-    result[decodeUrl(key)] = decodeUrl(val)
-
-template parseContentDisposition(): typed =
-  var hCount = 0
-  while hCount < hValue.len()-1:
-    var key = ""
-    hCount += hValue.parseUntil(key, {';', '='}, hCount)
-    if hValue[hCount] == '=':
-      var value = hvalue.captureBetween('"', start = hCount)
-      hCount += value.len+2
-      inc(hCount) # Skip ;
-      hCount += hValue.skipWhitespace(hCount)
-      if key == "name": name = value
-      newPart[0][key] = value
-    else:
-      inc(hCount)
-      hCount += hValue.skipWhitespace(hCount)
-
-proc parseMultiPart*(body: string, boundary: string): MultiData =
-  result = initOrderedTable[string, tuple[fields: StringTableRef, body: string]]()
-  var mboundary = "--" & boundary
-
-  var i = 0
-  var partsLeft = true
-  while partsLeft:
-    var firstBoundary = body.skip(mboundary, i)
-    if firstBoundary == 0:
-      raise newException(ValueError, "Expected boundary. Got: " & body.substr(i, i+25))
-    i += firstBoundary
-    i += body.skipWhitespace(i)
-
-    # Headers
-    var newPart: tuple[fields: StringTableRef, body: string] = ({:}.newStringTable, "")
-    var name = ""
-    while true:
-      if body[i] == '\c':
-        inc(i, 2) # Skip \c\L
-        break
-      var hName = ""
-      i += body.parseUntil(hName, ':', i)
-      if body[i] != ':':
-        raise newException(ValueError, "Expected : in headers.")
-      inc(i) # Skip :
-      i += body.skipWhitespace(i)
-      var hValue = ""
-      i += body.parseUntil(hValue, {'\c', '\L'}, i)
-      if toLowerAscii(hName) == "content-disposition":
-        parseContentDisposition()
-      newPart[0][hName] = hValue
-      i += body.skip("\c\L", i) # Skip *one* \c\L
-
-    # Parse body.
-    while true:
-      if body[i] == '\c' and body[i+1] == '\L' and
-         body.skip(mboundary, i+2) != 0:
-        if body.skip("--", i+2+mboundary.len) != 0:
-          partsLeft = false
-          break
-        break
-      else:
-        newPart[1].add(body[i])
-      inc(i)
-    i += body.skipWhitespace(i)
-
-    result.add(name, newPart)
-
-proc parseMPFD*(contentType: string, body: string): MultiData =
-  var boundaryEqIndex = contentType.find("boundary=")+9
-  var boundary = contentType.substr(boundaryEqIndex, contentType.len()-1)
-  return parseMultiPart(body, boundary)
-
-proc parseCookies*(s: string): Table[string, string] =
-  ## parses cookies into a string table.
-  ##
-  ## The proc is meant to parse the Cookie header set by a client, not the
-  ## "Set-Cookie" header set by servers.
-
-  result = initTable[string, string]()
-  var i = 0
-  while true:
-    i += skipWhile(s, {' ', '\t'}, i)
-    var keystart = i
-    i += skipUntil(s, {'='}, i)
-    var keyend = i-1
-    if i >= len(s): break
-    inc(i) # skip '='
-    var valstart = i
-    i += skipUntil(s, {';'}, i)
-    result[substr(s, keystart, keyend)] = substr(s, valstart, i-1)
-    if i >= len(s): break
-    inc(i) # skip ';'
-
-type
-  SameSite* = enum
-    None, Lax, Strict
-
-proc makeCookie*(key, value, expires: string, domain = "", path = "",
-                 secure = false, httpOnly = false,
-                 sameSite = Lax): string =
-  result = ""
-  result.add key & "=" & value
-  if domain != "": result.add("; Domain=" & domain)
-  if path != "": result.add("; Path=" & path)
-  if expires != "": result.add("; Expires=" & expires)
-  if secure: result.add("; Secure")
-  if httpOnly: result.add("; HttpOnly")
-  if sameSite != None:
-    result.add("; SameSite=" & $sameSite)
-
-when not declared(tables.getOrDefault):
-  template getOrDefault*(tab, key): untyped = tab[key]
-
-when not declared(normalizePath) and not declared(normalizedPath):
-  proc normalizePath*(path: var string) =
-    ## Normalize a path.
-    ##
-    ## Consecutive directory separators are collapsed, including an initial double slash.
-    ##
-    ## On relative paths, double dot (..) sequences are collapsed if possible.
-    ## On absolute paths they are always collapsed.
-    ##
-    ## Warning: URL-encoded and Unicode attempts at directory traversal are not detected.
-    ## Triple dot is not handled.
-    let isAbs = isAbsolute(path)
-    var stack: seq[string] = @[]
-    for p in split(path, {DirSep}):
-      case p
-      of "", ".":
-        continue
-      of "..":
-        if stack.len == 0:
-          if isAbs:
-            discard  # collapse all double dots on absoluta paths
-          else:
-            stack.add(p)
-        elif stack[^1] == "..":
-          stack.add(p)
-        else:
-          discard stack.pop()
-      else:
-        stack.add(p)
-
-    if isAbs:
-      path = DirSep & join(stack, $DirSep)
-    elif stack.len > 0:
-      path = join(stack, $DirSep)
-    else:
-      path = "."
-
-  proc normalizedPath*(path: string): string =
-    ## Returns a normalized path for the current OS. See `<#normalizePath>`_
-    result = path
-    normalizePath(result)
-
-when false:
-  var r = {:}.newStringTable
-  parseUrlQuery("FirstName=Mickey", r)
-  echo r
-
diff --git a/tests/deps/jester-#head/jester/request.nim b/tests/deps/jester-#head/jester/request.nim
deleted file mode 100644
index 1b837d728..000000000
--- a/tests/deps/jester-#head/jester/request.nim
+++ /dev/null
@@ -1,184 +0,0 @@
-import uri, cgi, tables, logging, strutils, re, options
-
-import jester/private/utils
-
-when useHttpBeast:
-  import httpbeast except Settings
-  import options, httpcore
-
-  type
-    NativeRequest* = httpbeast.Request
-else:
-  import asynchttpserver
-
-  type
-    NativeRequest* = asynchttpserver.Request
-
-type
-  Request* = object
-    req: NativeRequest
-    patternParams: Option[Table[string, string]]
-    reMatches: array[MaxSubpatterns, string]
-    settings*: Settings
-
-proc body*(req: Request): string =
-  ## Body of the request, only for POST.
-  ##
-  ## You're probably looking for ``formData``
-  ## instead.
-  when useHttpBeast:
-    req.req.body.get("")
-  else:
-    req.req.body
-
-proc headers*(req: Request): HttpHeaders =
-  ## Headers received with the request.
-  ## Retrieving these is case insensitive.
-  when useHttpBeast:
-    if req.req.headers.isNone:
-      newHttpHeaders()
-    else:
-      req.req.headers.get()
-  else:
-    req.req.headers
-
-proc path*(req: Request): string =
-  ## Path of request without the query string.
-  when useHttpBeast:
-    let p = req.req.path.get("")
-    let queryStart = p.find('?')
-    if unlikely(queryStart != -1):
-      return p[0 .. queryStart-1]
-    else:
-      return p
-  else:
-    let u = req.req.url
-    return u.path
-
-proc reqMethod*(req: Request): HttpMethod =
-  ## Request method, eg. HttpGet, HttpPost
-  when useHttpBeast:
-    req.req.httpMethod.get()
-  else:
-    req.req.reqMethod
-proc reqMeth*(req: Request): HttpMethod {.deprecated.} =
-  req.reqMethod
-
-proc ip*(req: Request): string =
-  ## IP address of the requesting client.
-  when useHttpBeast:
-    result = req.req.ip
-  else:
-    result = req.req.hostname
-
-  let headers = req.headers
-  if headers.hasKey("REMOTE_ADDR"):
-    result = headers["REMOTE_ADDR"]
-  if headers.hasKey("x-forwarded-for"):
-    result = headers["x-forwarded-for"]
-
-proc params*(req: Request): Table[string, string] =
-  ## Parameters from the pattern and the query string.
-  if req.patternParams.isSome():
-    result = req.patternParams.get()
-  else:
-    result = initTable[string, string]()
-
-  when useHttpBeast:
-    let query = req.req.path.get("").parseUri().query
-  else:
-    let query = req.req.url.query
-
-  try:
-    for key, val in cgi.decodeData(query):
-      result[key] = val
-  except CgiError:
-    logging.warn("Incorrect query. Got: $1" % [query])
-
-  let contentType = req.headers.getOrDefault("Content-Type")
-  if contentType.startswith("application/x-www-form-urlencoded"):
-    try:
-      parseUrlQuery(req.body, result)
-    except:
-      logging.warn("Could not parse URL query.")
-
-proc formData*(req: Request): MultiData =
-  let contentType = req.headers.getOrDefault("Content-Type")
-  if contentType.startsWith("multipart/form-data"):
-    result = parseMPFD(contentType, req.body)
-
-proc matches*(req: Request): array[MaxSubpatterns, string] =
-  req.reMatches
-
-proc secure*(req: Request): bool =
-  if req.headers.hasKey("x-forwarded-proto"):
-    let proto = req.headers["x-forwarded-proto"]
-    case proto.toLowerAscii()
-    of "https":
-      result = true
-    of "http":
-      result = false
-    else:
-      logging.warn("Unknown x-forwarded-proto ", proto)
-
-proc port*(req: Request): int =
-  if (let p = req.headers.getOrDefault("SERVER_PORT"); p != ""):
-    result = p.parseInt
-  else:
-    result = if req.secure: 443 else: 80
-
-proc host*(req: Request): string =
-  req.headers.getOrDefault("HOST")
-
-proc appName*(req: Request): string =
-  ## This is set by the user in ``run``, it is
-  ## overriden by the "SCRIPT_NAME" scgi
-  ## parameter.
-  req.settings.appName
-
-proc stripAppName(path, appName: string): string =
-  result = path
-  if appname.len > 0:
-    var slashAppName = appName
-    if slashAppName[0] != '/' and path[0] == '/':
-      slashAppName = '/' & slashAppName
-
-    if path.startsWith(slashAppName):
-      if slashAppName.len() == path.len:
-        return "/"
-      else:
-        return path[slashAppName.len .. path.len-1]
-    else:
-      raise newException(ValueError,
-          "Expected script name at beginning of path. Got path: " &
-           path & " script name: " & slashAppName)
-
-proc pathInfo*(req: Request): string =
-  ## This is ``.path`` without ``.appName``.
-  req.path.stripAppName(req.appName)
-
-# TODO: Can cookie keys be duplicated?
-proc cookies*(req: Request): Table[string, string] =
-  ## Cookies from the browser.
-  if (let cookie = req.headers.getOrDefault("Cookie"); cookie != ""):
-    result = parseCookies(cookie)
-  else:
-    result = initTable[string, string]()
-
-#[ Protected procs ]#
-
-proc initRequest*(req: NativeRequest, settings: Settings): Request {.inline.} =
-  Request(
-    req: req,
-    settings: settings
-  )
-
-proc getNativeReq*(req: Request): NativeRequest =
-  req.req
-
-#[ Only to be used by our route macro. ]#
-proc setPatternParams*(req: var Request, p: Table[string, string]) =
-  req.patternParams = some(p)
-
-proc setReMatches*(req: var Request, r: array[MaxSubpatterns, string]) =
-  req.reMatches = r
diff --git a/tests/deps/opengl-1.1.0/glu.nim b/tests/deps/opengl-1.1.0/glu.nim
deleted file mode 100644
index 5594ef915..000000000
--- a/tests/deps/opengl-1.1.0/glu.nim
+++ /dev/null
@@ -1,326 +0,0 @@
-#
-#
-#  Adaption of the delphi3d.net OpenGL units to FreePascal
-#  Sebastian Guenther (sg@freepascal.org) in 2002
-#  These units are free to use
-#******************************************************************************
-# Converted to Delphi by Tom Nuydens (tom@delphi3d.net)
-# For the latest updates, visit Delphi3D: http://www.delphi3d.net
-#******************************************************************************
-
-import opengl
-
-{.deadCodeElim: on.}
-
-when defined(windows):
-  {.push, callconv: stdcall.}
-else:
-  {.push, callconv: cdecl.}
-
-when defined(windows):
-  const
-    dllname = "glu32.dll"
-elif defined(macosx):
-  const
-    dllname = "/System/Library/Frameworks/OpenGL.framework/Libraries/libGLU.dylib"
-else:
-  const
-    dllname = "libGLU.so.1"
-
-type
-  ViewPortArray* = array[0..3, GLint]
-  T16dArray* = array[0..15, GLdouble]
-  CallBack* = proc () {.cdecl.}
-  T3dArray* = array[0..2, GLdouble]
-  T4pArray* = array[0..3, pointer]
-  T4fArray* = array[0..3, GLfloat]
-
-{.deprecated: [
-  TViewPortArray: ViewPortArray,
-  TCallBack: CallBack,
-].}
-
-type
-  GLUnurbs*{.final.} = ptr object
-  GLUquadric*{.final.} = ptr object
-  GLUtesselator*{.final.} = ptr object
-  GLUnurbsObj* = GLUnurbs
-  GLUquadricObj* = GLUquadric
-  GLUtesselatorObj* = GLUtesselator
-  GLUtriangulatorObj* = GLUtesselator
-
-proc gluErrorString*(errCode: GLenum): cstring{.dynlib: dllname,
-    importc: "gluErrorString".}
-when defined(Windows):
-  proc gluErrorUnicodeStringEXT*(errCode: GLenum): ptr int16{.dynlib: dllname,
-      importc: "gluErrorUnicodeStringEXT".}
-proc gluGetString*(name: GLenum): cstring{.dynlib: dllname,
-    importc: "gluGetString".}
-proc gluOrtho2D*(left, right, bottom, top: GLdouble){.dynlib: dllname,
-    importc: "gluOrtho2D".}
-proc gluPerspective*(fovy, aspect, zNear, zFar: GLdouble){.dynlib: dllname,
-    importc: "gluPerspective".}
-proc gluPickMatrix*(x, y, width, height: GLdouble, viewport: var ViewPortArray){.
-    dynlib: dllname, importc: "gluPickMatrix".}
-proc gluLookAt*(eyex, eyey, eyez, centerx, centery, centerz, upx, upy, upz: GLdouble){.
-    dynlib: dllname, importc: "gluLookAt".}
-proc gluProject*(objx, objy, objz: GLdouble,
-                 modelMatrix, projMatrix: var T16dArray,
-                 viewport: var ViewPortArray, winx, winy, winz: ptr GLdouble): int{.
-    dynlib: dllname, importc: "gluProject".}
-proc gluUnProject*(winx, winy, winz: GLdouble,
-                   modelMatrix, projMatrix: var T16dArray,
-                   viewport: var ViewPortArray, objx, objy, objz: ptr GLdouble): int{.
-    dynlib: dllname, importc: "gluUnProject".}
-proc gluScaleImage*(format: GLenum, widthin, heightin: GLint, typein: GLenum,
-                    datain: pointer, widthout, heightout: GLint,
-                    typeout: GLenum, dataout: pointer): int{.dynlib: dllname,
-    importc: "gluScaleImage".}
-proc gluBuild1DMipmaps*(target: GLenum, components, width: GLint,
-                        format, atype: GLenum, data: pointer): int{.
-    dynlib: dllname, importc: "gluBuild1DMipmaps".}
-proc gluBuild2DMipmaps*(target: GLenum, components, width, height: GLint,
-                        format, atype: GLenum, data: pointer): int{.
-    dynlib: dllname, importc: "gluBuild2DMipmaps".}
-proc gluNewQuadric*(): GLUquadric{.dynlib: dllname, importc: "gluNewQuadric".}
-proc gluDeleteQuadric*(state: GLUquadric){.dynlib: dllname,
-    importc: "gluDeleteQuadric".}
-proc gluQuadricNormals*(quadObject: GLUquadric, normals: GLenum){.
-    dynlib: dllname, importc: "gluQuadricNormals".}
-proc gluQuadricTexture*(quadObject: GLUquadric, textureCoords: GLboolean){.
-    dynlib: dllname, importc: "gluQuadricTexture".}
-proc gluQuadricOrientation*(quadObject: GLUquadric, orientation: GLenum){.
-    dynlib: dllname, importc: "gluQuadricOrientation".}
-proc gluQuadricDrawStyle*(quadObject: GLUquadric, drawStyle: GLenum){.
-    dynlib: dllname, importc: "gluQuadricDrawStyle".}
-proc gluCylinder*(qobj: GLUquadric, baseRadius, topRadius, height: GLdouble,
-                  slices, stacks: GLint){.dynlib: dllname,
-    importc: "gluCylinder".}
-proc gluDisk*(qobj: GLUquadric, innerRadius, outerRadius: GLdouble,
-              slices, loops: GLint){.dynlib: dllname, importc: "gluDisk".}
-proc gluPartialDisk*(qobj: GLUquadric, innerRadius, outerRadius: GLdouble,
-                     slices, loops: GLint, startAngle, sweepAngle: GLdouble){.
-    dynlib: dllname, importc: "gluPartialDisk".}
-proc gluSphere*(qobj: GLuquadric, radius: GLdouble, slices, stacks: GLint){.
-    dynlib: dllname, importc: "gluSphere".}
-proc gluQuadricCallback*(qobj: GLUquadric, which: GLenum, fn: CallBack){.
-    dynlib: dllname, importc: "gluQuadricCallback".}
-proc gluNewTess*(): GLUtesselator{.dynlib: dllname, importc: "gluNewTess".}
-proc gluDeleteTess*(tess: GLUtesselator){.dynlib: dllname,
-    importc: "gluDeleteTess".}
-proc gluTessBeginPolygon*(tess: GLUtesselator, polygon_data: pointer){.
-    dynlib: dllname, importc: "gluTessBeginPolygon".}
-proc gluTessBeginContour*(tess: GLUtesselator){.dynlib: dllname,
-    importc: "gluTessBeginContour".}
-proc gluTessVertex*(tess: GLUtesselator, coords: var T3dArray, data: pointer){.
-    dynlib: dllname, importc: "gluTessVertex".}
-proc gluTessEndContour*(tess: GLUtesselator){.dynlib: dllname,
-    importc: "gluTessEndContour".}
-proc gluTessEndPolygon*(tess: GLUtesselator){.dynlib: dllname,
-    importc: "gluTessEndPolygon".}
-proc gluTessProperty*(tess: GLUtesselator, which: GLenum, value: GLdouble){.
-    dynlib: dllname, importc: "gluTessProperty".}
-proc gluTessNormal*(tess: GLUtesselator, x, y, z: GLdouble){.dynlib: dllname,
-    importc: "gluTessNormal".}
-proc gluTessCallback*(tess: GLUtesselator, which: GLenum, fn: CallBack){.
-    dynlib: dllname, importc: "gluTessCallback".}
-proc gluGetTessProperty*(tess: GLUtesselator, which: GLenum, value: ptr GLdouble){.
-    dynlib: dllname, importc: "gluGetTessProperty".}
-proc gluNewNurbsRenderer*(): GLUnurbs{.dynlib: dllname,
-                                        importc: "gluNewNurbsRenderer".}
-proc gluDeleteNurbsRenderer*(nobj: GLUnurbs){.dynlib: dllname,
-    importc: "gluDeleteNurbsRenderer".}
-proc gluBeginSurface*(nobj: GLUnurbs){.dynlib: dllname,
-                                        importc: "gluBeginSurface".}
-proc gluBeginCurve*(nobj: GLUnurbs){.dynlib: dllname, importc: "gluBeginCurve".}
-proc gluEndCurve*(nobj: GLUnurbs){.dynlib: dllname, importc: "gluEndCurve".}
-proc gluEndSurface*(nobj: GLUnurbs){.dynlib: dllname, importc: "gluEndSurface".}
-proc gluBeginTrim*(nobj: GLUnurbs){.dynlib: dllname, importc: "gluBeginTrim".}
-proc gluEndTrim*(nobj: GLUnurbs){.dynlib: dllname, importc: "gluEndTrim".}
-proc gluPwlCurve*(nobj: GLUnurbs, count: GLint, aarray: ptr GLfloat,
-                  stride: GLint, atype: GLenum){.dynlib: dllname,
-    importc: "gluPwlCurve".}
-proc gluNurbsCurve*(nobj: GLUnurbs, nknots: GLint, knot: ptr GLfloat,
-                    stride: GLint, ctlarray: ptr GLfloat, order: GLint,
-                    atype: GLenum){.dynlib: dllname, importc: "gluNurbsCurve".}
-proc gluNurbsSurface*(nobj: GLUnurbs, sknot_count: GLint, sknot: ptr GLfloat,
-                      tknot_count: GLint, tknot: ptr GLfloat,
-                      s_stride, t_stride: GLint, ctlarray: ptr GLfloat,
-                      sorder, torder: GLint, atype: GLenum){.dynlib: dllname,
-    importc: "gluNurbsSurface".}
-proc gluLoadSamplingMatrices*(nobj: GLUnurbs,
-                              modelMatrix, projMatrix: var T16dArray,
-                              viewport: var ViewPortArray){.dynlib: dllname,
-    importc: "gluLoadSamplingMatrices".}
-proc gluNurbsProperty*(nobj: GLUnurbs, aproperty: GLenum, value: GLfloat){.
-    dynlib: dllname, importc: "gluNurbsProperty".}
-proc gluGetNurbsProperty*(nobj: GLUnurbs, aproperty: GLenum, value: ptr GLfloat){.
-    dynlib: dllname, importc: "gluGetNurbsProperty".}
-proc gluNurbsCallback*(nobj: GLUnurbs, which: GLenum, fn: CallBack){.
-    dynlib: dllname, importc: "gluNurbsCallback".}
-  #*** Callback function prototypes ***
-type                          # gluQuadricCallback
-  GLUquadricErrorProc* = proc (p: GLenum) # gluTessCallback
-  GLUtessBeginProc* = proc (p: GLenum)
-  GLUtessEdgeFlagProc* = proc (p: GLboolean)
-  GLUtessVertexProc* = proc (p: pointer)
-  GLUtessEndProc* = proc ()
-  GLUtessErrorProc* = proc (p: GLenum)
-  GLUtessCombineProc* = proc (p1: var T3dArray, p2: T4pArray, p3: T4fArray,
-                              p4: ptr pointer)
-  GLUtessBeginDataProc* = proc (p1: GLenum, p2: pointer)
-  GLUtessEdgeFlagDataProc* = proc (p1: GLboolean, p2: pointer)
-  GLUtessVertexDataProc* = proc (p1, p2: pointer)
-  GLUtessEndDataProc* = proc (p: pointer)
-  GLUtessErrorDataProc* = proc (p1: GLenum, p2: pointer)
-  GLUtessCombineDataProc* = proc (p1: var T3dArray, p2: var T4pArray,
-                                  p3: var T4fArray, p4: ptr pointer, p5: pointer) #
-  GLUnurbsErrorProc* = proc (p: GLenum) #***           Generic constants               ****/
-
-const                         # Version
-  GLU_VERSION_1_1* = 1
-  GLU_VERSION_1_2* = 1        # Errors: (return value 0 = no error)
-  GLU_INVALID_ENUM* = 100900
-  GLU_INVALID_VALUE* = 100901
-  GLU_OUT_OF_MEMORY* = 100902
-  GLU_INCOMPATIBLE_GL_VERSION* = 100903 # StringName
-  GLU_VERSION* = 100800
-  GLU_EXTENSIONS* = 100801    # Boolean
-  GLU_TRUE* = GL_TRUE
-  GLU_FALSE* = GL_FALSE #***           Quadric constants               ****/
-                        # QuadricNormal
-  GLU_SMOOTH* = 100000
-  GLU_FLAT* = 100001
-  GLU_NONE* = 100002          # QuadricDrawStyle
-  GLU_POINT* = 100010
-  GLU_LINE* = 100011
-  GLU_FILL* = 100012
-  GLU_SILHOUETTE* = 100013    # QuadricOrientation
-  GLU_OUTSIDE* = 100020
-  GLU_INSIDE* = 100021        # Callback types:
-                              #      GLU_ERROR       = 100103;
-                              #***           Tesselation constants           ****/
-  GLU_TESS_MAX_COORD* = 1.00000e+150 # TessProperty
-  GLU_TESS_WINDING_RULE* = 100140
-  GLU_TESS_BOUNDARY_ONLY* = 100141
-  GLU_TESS_TOLERANCE* = 100142 # TessWinding
-  GLU_TESS_WINDING_ODD* = 100130
-  GLU_TESS_WINDING_NONZERO* = 100131
-  GLU_TESS_WINDING_POSITIVE* = 100132
-  GLU_TESS_WINDING_NEGATIVE* = 100133
-  GLU_TESS_WINDING_ABS_GEQ_TWO* = 100134 # TessCallback
-  GLU_TESS_BEGIN* = 100100    # void (CALLBACK*)(GLenum    type)
-  constGLU_TESS_VERTEX* = 100101 # void (CALLBACK*)(void      *data)
-  GLU_TESS_END* = 100102      # void (CALLBACK*)(void)
-  GLU_TESS_ERROR* = 100103    # void (CALLBACK*)(GLenum    errno)
-  GLU_TESS_EDGE_FLAG* = 100104 # void (CALLBACK*)(GLboolean boundaryEdge)
-  GLU_TESS_COMBINE* = 100105 # void (CALLBACK*)(GLdouble  coords[3],
-                             #                                                            void      *data[4],
-                             #                                                            GLfloat   weight[4],
-                             #                                                            void      **dataOut)
-  GLU_TESS_BEGIN_DATA* = 100106 # void (CALLBACK*)(GLenum    type,
-                                #                                                            void      *polygon_data)
-  GLU_TESS_VERTEX_DATA* = 100107 # void (CALLBACK*)(void      *data,
-                                 #                                                            void      *polygon_data)
-  GLU_TESS_END_DATA* = 100108 # void (CALLBACK*)(void      *polygon_data)
-  GLU_TESS_ERROR_DATA* = 100109 # void (CALLBACK*)(GLenum    errno,
-                                #                                                            void      *polygon_data)
-  GLU_TESS_EDGE_FLAG_DATA* = 100110 # void (CALLBACK*)(GLboolean boundaryEdge,
-                                    #                                                            void      *polygon_data)
-  GLU_TESS_COMBINE_DATA* = 100111 # void (CALLBACK*)(GLdouble  coords[3],
-                                  #                                                            void      *data[4],
-                                  #                                                            GLfloat   weight[4],
-                                  #                                                            void      **dataOut,
-                                  #                                                            void      *polygon_data)
-                                  # TessError
-  GLU_TESS_ERROR1* = 100151
-  GLU_TESS_ERROR2* = 100152
-  GLU_TESS_ERROR3* = 100153
-  GLU_TESS_ERROR4* = 100154
-  GLU_TESS_ERROR5* = 100155
-  GLU_TESS_ERROR6* = 100156
-  GLU_TESS_ERROR7* = 100157
-  GLU_TESS_ERROR8* = 100158
-  GLU_TESS_MISSING_BEGIN_POLYGON* = GLU_TESS_ERROR1
-  GLU_TESS_MISSING_BEGIN_CONTOUR* = GLU_TESS_ERROR2
-  GLU_TESS_MISSING_END_POLYGON* = GLU_TESS_ERROR3
-  GLU_TESS_MISSING_END_CONTOUR* = GLU_TESS_ERROR4
-  GLU_TESS_COORD_TOO_LARGE* = GLU_TESS_ERROR5
-  GLU_TESS_NEED_COMBINE_CALLBACK* = GLU_TESS_ERROR6 #***           NURBS constants                 ****/
-                                                    # NurbsProperty
-  GLU_AUTO_LOAD_MATRIX* = 100200
-  GLU_CULLING* = 100201
-  GLU_SAMPLING_TOLERANCE* = 100203
-  GLU_DISPLAY_MODE* = 100204
-  GLU_PARAMETRIC_TOLERANCE* = 100202
-  GLU_SAMPLING_METHOD* = 100205
-  GLU_U_STEP* = 100206
-  GLU_V_STEP* = 100207        # NurbsSampling
-  GLU_PATH_LENGTH* = 100215
-  GLU_PARAMETRIC_ERROR* = 100216
-  GLU_DOMAIN_DISTANCE* = 100217 # NurbsTrim
-  GLU_MAP1_TRIM_2* = 100210
-  GLU_MAP1_TRIM_3* = 100211   # NurbsDisplay
-                              #      GLU_FILL                = 100012;
-  GLU_OUTLINE_POLYGON* = 100240
-  GLU_OUTLINE_PATCH* = 100241 # NurbsCallback
-                              #      GLU_ERROR               = 100103;
-                              # NurbsErrors
-  GLU_NURBS_ERROR1* = 100251
-  GLU_NURBS_ERROR2* = 100252
-  GLU_NURBS_ERROR3* = 100253
-  GLU_NURBS_ERROR4* = 100254
-  GLU_NURBS_ERROR5* = 100255
-  GLU_NURBS_ERROR6* = 100256
-  GLU_NURBS_ERROR7* = 100257
-  GLU_NURBS_ERROR8* = 100258
-  GLU_NURBS_ERROR9* = 100259
-  GLU_NURBS_ERROR10* = 100260
-  GLU_NURBS_ERROR11* = 100261
-  GLU_NURBS_ERROR12* = 100262
-  GLU_NURBS_ERROR13* = 100263
-  GLU_NURBS_ERROR14* = 100264
-  GLU_NURBS_ERROR15* = 100265
-  GLU_NURBS_ERROR16* = 100266
-  GLU_NURBS_ERROR17* = 100267
-  GLU_NURBS_ERROR18* = 100268
-  GLU_NURBS_ERROR19* = 100269
-  GLU_NURBS_ERROR20* = 100270
-  GLU_NURBS_ERROR21* = 100271
-  GLU_NURBS_ERROR22* = 100272
-  GLU_NURBS_ERROR23* = 100273
-  GLU_NURBS_ERROR24* = 100274
-  GLU_NURBS_ERROR25* = 100275
-  GLU_NURBS_ERROR26* = 100276
-  GLU_NURBS_ERROR27* = 100277
-  GLU_NURBS_ERROR28* = 100278
-  GLU_NURBS_ERROR29* = 100279
-  GLU_NURBS_ERROR30* = 100280
-  GLU_NURBS_ERROR31* = 100281
-  GLU_NURBS_ERROR32* = 100282
-  GLU_NURBS_ERROR33* = 100283
-  GLU_NURBS_ERROR34* = 100284
-  GLU_NURBS_ERROR35* = 100285
-  GLU_NURBS_ERROR36* = 100286
-  GLU_NURBS_ERROR37* = 100287 #***           Backwards compatibility for old tesselator           ****/
-
-proc gluBeginPolygon*(tess: GLUtesselator){.dynlib: dllname,
-    importc: "gluBeginPolygon".}
-proc gluNextContour*(tess: GLUtesselator, atype: GLenum){.dynlib: dllname,
-    importc: "gluNextContour".}
-proc gluEndPolygon*(tess: GLUtesselator){.dynlib: dllname,
-    importc: "gluEndPolygon".}
-const                         # Contours types -- obsolete!
-  GLU_CW* = 100120
-  GLU_CCW* = 100121
-  GLU_INTERIOR* = 100122
-  GLU_EXTERIOR* = 100123
-  GLU_UNKNOWN* = 100124       # Names without "TESS_" prefix
-  GLU_BEGIN* = GLU_TESS_BEGIN
-  GLU_VERTEX* = constGLU_TESS_VERTEX
-  GLU_END* = GLU_TESS_END
-  GLU_ERROR* = GLU_TESS_ERROR
-  GLU_EDGE_FLAG* = GLU_TESS_EDGE_FLAG
-
-{.pop.}
-# implementation
diff --git a/tests/deps/opengl-1.1.0/glut.nim b/tests/deps/opengl-1.1.0/glut.nim
deleted file mode 100644
index 55a5da0c7..000000000
--- a/tests/deps/opengl-1.1.0/glut.nim
+++ /dev/null
@@ -1,366 +0,0 @@
-#
-#
-#  Adaption of the delphi3d.net OpenGL units to FreePascal
-#  Sebastian Guenther (sg@freepascal.org) in 2002
-#  These units are free to use
-#
-
-# Copyright (c) Mark J. Kilgard, 1994, 1995, 1996.
-# This program is freely distributable without licensing fees  and is
-#   provided without guarantee or warrantee expressed or  implied. This
-#   program is -not- in the public domain.
-#******************************************************************************
-# Converted to Delphi by Tom Nuydens (tom@delphi3d.net)
-#   Contributions by Igor Karpov (glygrik@hotbox.ru)
-#   For the latest updates, visit Delphi3D: http://www.delphi3d.net
-#******************************************************************************
-
-import opengl
-
-{.deadCodeElim: on.}
-
-when defined(windows):
-  const
-    dllname = "glut32.dll"
-elif defined(macosx):
-  const
-    dllname = "/System/Library/Frameworks/GLUT.framework/GLUT"
-else:
-  const
-    dllname = "libglut.so.3"
-type
-  TGlutVoidCallback* = proc (){.cdecl.}
-  TGlut1IntCallback* = proc (value: cint){.cdecl.}
-  TGlut2IntCallback* = proc (v1, v2: cint){.cdecl.}
-  TGlut3IntCallback* = proc (v1, v2, v3: cint){.cdecl.}
-  TGlut4IntCallback* = proc (v1, v2, v3, v4: cint){.cdecl.}
-  TGlut1Char2IntCallback* = proc (c: int8, v1, v2: cint){.cdecl.}
-  TGlut1UInt3IntCallback* = proc (u, v1, v2, v3: cint){.cdecl.}
-
-{.deprecated: [Pointer: pointer].}
-
-const
-  GLUT_API_VERSION* = 3
-  GLUT_XLIB_IMPLEMENTATION* = 12 # Display mode bit masks.
-  GLUT_RGB* = 0
-  GLUT_RGBA* = GLUT_RGB
-  GLUT_INDEX* = 1
-  GLUT_SINGLE* = 0
-  GLUT_DOUBLE* = 2
-  GLUT_ACCUM* = 4
-  GLUT_ALPHA* = 8
-  GLUT_DEPTH* = 16
-  GLUT_STENCIL* = 32
-  GLUT_MULTISAMPLE* = 128
-  GLUT_STEREO* = 256
-  GLUT_LUMINANCE* = 512       # Mouse buttons.
-  GLUT_LEFT_BUTTON* = 0
-  GLUT_MIDDLE_BUTTON* = 1
-  GLUT_RIGHT_BUTTON* = 2      # Mouse button state.
-  GLUT_DOWN* = 0
-  GLUT_UP* = 1                # function keys
-  GLUT_KEY_F1* = 1
-  GLUT_KEY_F2* = 2
-  GLUT_KEY_F3* = 3
-  GLUT_KEY_F4* = 4
-  GLUT_KEY_F5* = 5
-  GLUT_KEY_F6* = 6
-  GLUT_KEY_F7* = 7
-  GLUT_KEY_F8* = 8
-  GLUT_KEY_F9* = 9
-  GLUT_KEY_F10* = 10
-  GLUT_KEY_F11* = 11
-  GLUT_KEY_F12* = 12          # directional keys
-  GLUT_KEY_LEFT* = 100
-  GLUT_KEY_UP* = 101
-  GLUT_KEY_RIGHT* = 102
-  GLUT_KEY_DOWN* = 103
-  GLUT_KEY_PAGE_UP* = 104
-  GLUT_KEY_PAGE_DOWN* = 105
-  GLUT_KEY_HOME* = 106
-  GLUT_KEY_END* = 107
-  GLUT_KEY_INSERT* = 108      # Entry/exit  state.
-  GLUT_LEFT* = 0
-  GLUT_ENTERED* = 1           # Menu usage state.
-  GLUT_MENU_NOT_IN_USE* = 0
-  GLUT_MENU_IN_USE* = 1       # Visibility  state.
-  GLUT_NOT_VISIBLE* = 0
-  GLUT_VISIBLE* = 1           # Window status  state.
-  GLUT_HIDDEN* = 0
-  GLUT_FULLY_RETAINED* = 1
-  GLUT_PARTIALLY_RETAINED* = 2
-  GLUT_FULLY_COVERED* = 3     # Color index component selection values.
-  GLUT_RED* = 0
-  GLUT_GREEN* = 1
-  GLUT_BLUE* = 2              # Layers for use.
-  GLUT_NORMAL* = 0
-  GLUT_OVERLAY* = 1
-
-when defined(Windows):
-  const                       # Stroke font constants (use these in GLUT program).
-    GLUT_STROKE_ROMAN* = cast[pointer](0)
-    GLUT_STROKE_MONO_ROMAN* = cast[pointer](1) # Bitmap font constants (use these in GLUT program).
-    GLUT_BITMAP_9_BY_15* = cast[pointer](2)
-    GLUT_BITMAP_8_BY_13* = cast[pointer](3)
-    GLUT_BITMAP_TIMES_ROMAN_10* = cast[pointer](4)
-    GLUT_BITMAP_TIMES_ROMAN_24* = cast[pointer](5)
-    GLUT_BITMAP_HELVETICA_10* = cast[pointer](6)
-    GLUT_BITMAP_HELVETICA_12* = cast[pointer](7)
-    GLUT_BITMAP_HELVETICA_18* = cast[pointer](8)
-else:
-  var                         # Stroke font constants (use these in GLUT program).
-    GLUT_STROKE_ROMAN*: pointer
-    GLUT_STROKE_MONO_ROMAN*: pointer # Bitmap font constants (use these in GLUT program).
-    GLUT_BITMAP_9_BY_15*: pointer
-    GLUT_BITMAP_8_BY_13*: pointer
-    GLUT_BITMAP_TIMES_ROMAN_10*: pointer
-    GLUT_BITMAP_TIMES_ROMAN_24*: pointer
-    GLUT_BITMAP_HELVETICA_10*: pointer
-    GLUT_BITMAP_HELVETICA_12*: pointer
-    GLUT_BITMAP_HELVETICA_18*: pointer
-const                         # glutGet parameters.
-  GLUT_WINDOW_X* = 100
-  GLUT_WINDOW_Y* = 101
-  GLUT_WINDOW_WIDTH* = 102
-  GLUT_WINDOW_HEIGHT* = 103
-  GLUT_WINDOW_BUFFER_SIZE* = 104
-  GLUT_WINDOW_STENCIL_SIZE* = 105
-  GLUT_WINDOW_DEPTH_SIZE* = 106
-  GLUT_WINDOW_RED_SIZE* = 107
-  GLUT_WINDOW_GREEN_SIZE* = 108
-  GLUT_WINDOW_BLUE_SIZE* = 109
-  GLUT_WINDOW_ALPHA_SIZE* = 110
-  GLUT_WINDOW_ACCUM_RED_SIZE* = 111
-  GLUT_WINDOW_ACCUM_GREEN_SIZE* = 112
-  GLUT_WINDOW_ACCUM_BLUE_SIZE* = 113
-  GLUT_WINDOW_ACCUM_ALPHA_SIZE* = 114
-  GLUT_WINDOW_DOUBLEBUFFER* = 115
-  GLUT_WINDOW_RGBA* = 116
-  GLUT_WINDOW_PARENT* = 117
-  GLUT_WINDOW_NUM_CHILDREN* = 118
-  GLUT_WINDOW_COLORMAP_SIZE* = 119
-  GLUT_WINDOW_NUM_SAMPLES* = 120
-  GLUT_WINDOW_STEREO* = 121
-  GLUT_WINDOW_CURSOR* = 122
-  GLUT_SCREEN_WIDTH* = 200
-  GLUT_SCREEN_HEIGHT* = 201
-  GLUT_SCREEN_WIDTH_MM* = 202
-  GLUT_SCREEN_HEIGHT_MM* = 203
-  GLUT_MENU_NUM_ITEMS* = 300
-  GLUT_DISPLAY_MODE_POSSIBLE* = 400
-  GLUT_INIT_WINDOW_X* = 500
-  GLUT_INIT_WINDOW_Y* = 501
-  GLUT_INIT_WINDOW_WIDTH* = 502
-  GLUT_INIT_WINDOW_HEIGHT* = 503
-  constGLUT_INIT_DISPLAY_MODE* = 504
-  GLUT_ELAPSED_TIME* = 700
-  GLUT_WINDOW_FORMAT_ID* = 123 # glutDeviceGet parameters.
-  GLUT_HAS_KEYBOARD* = 600
-  GLUT_HAS_MOUSE* = 601
-  GLUT_HAS_SPACEBALL* = 602
-  GLUT_HAS_DIAL_AND_BUTTON_BOX* = 603
-  GLUT_HAS_TABLET* = 604
-  GLUT_NUM_MOUSE_BUTTONS* = 605
-  GLUT_NUM_SPACEBALL_BUTTONS* = 606
-  GLUT_NUM_BUTTON_BOX_BUTTONS* = 607
-  GLUT_NUM_DIALS* = 608
-  GLUT_NUM_TABLET_BUTTONS* = 609
-  GLUT_DEVICE_IGNORE_KEY_REPEAT* = 610
-  GLUT_DEVICE_KEY_REPEAT* = 611
-  GLUT_HAS_JOYSTICK* = 612
-  GLUT_OWNS_JOYSTICK* = 613
-  GLUT_JOYSTICK_BUTTONS* = 614
-  GLUT_JOYSTICK_AXES* = 615
-  GLUT_JOYSTICK_POLL_RATE* = 616 # glutLayerGet parameters.
-  GLUT_OVERLAY_POSSIBLE* = 800
-  GLUT_LAYER_IN_USE* = 801
-  GLUT_HAS_OVERLAY* = 802
-  GLUT_TRANSPARENT_INDEX* = 803
-  GLUT_NORMAL_DAMAGED* = 804
-  GLUT_OVERLAY_DAMAGED* = 805 # glutVideoResizeGet parameters.
-  GLUT_VIDEO_RESIZE_POSSIBLE* = 900
-  GLUT_VIDEO_RESIZE_IN_USE* = 901
-  GLUT_VIDEO_RESIZE_X_DELTA* = 902
-  GLUT_VIDEO_RESIZE_Y_DELTA* = 903
-  GLUT_VIDEO_RESIZE_WIDTH_DELTA* = 904
-  GLUT_VIDEO_RESIZE_HEIGHT_DELTA* = 905
-  GLUT_VIDEO_RESIZE_X* = 906
-  GLUT_VIDEO_RESIZE_Y* = 907
-  GLUT_VIDEO_RESIZE_WIDTH* = 908
-  GLUT_VIDEO_RESIZE_HEIGHT* = 909 # glutGetModifiers return mask.
-  GLUT_ACTIVE_SHIFT* = 1
-  GLUT_ACTIVE_CTRL* = 2
-  GLUT_ACTIVE_ALT* = 4        # glutSetCursor parameters.
-                              # Basic arrows.
-  GLUT_CURSOR_RIGHT_ARROW* = 0
-  GLUT_CURSOR_LEFT_ARROW* = 1 # Symbolic cursor shapes.
-  GLUT_CURSOR_INFO* = 2
-  GLUT_CURSOR_DESTROY* = 3
-  GLUT_CURSOR_HELP* = 4
-  GLUT_CURSOR_CYCLE* = 5
-  GLUT_CURSOR_SPRAY* = 6
-  GLUT_CURSOR_WAIT* = 7
-  GLUT_CURSOR_TEXT* = 8
-  GLUT_CURSOR_CROSSHAIR* = 9  # Directional cursors.
-  GLUT_CURSOR_UP_DOWN* = 10
-  GLUT_CURSOR_LEFT_RIGHT* = 11 # Sizing cursors.
-  GLUT_CURSOR_TOP_SIDE* = 12
-  GLUT_CURSOR_BOTTOM_SIDE* = 13
-  GLUT_CURSOR_LEFT_SIDE* = 14
-  GLUT_CURSOR_RIGHT_SIDE* = 15
-  GLUT_CURSOR_TOP_LEFT_CORNER* = 16
-  GLUT_CURSOR_TOP_RIGHT_CORNER* = 17
-  GLUT_CURSOR_BOTTOM_RIGHT_CORNER* = 18
-  GLUT_CURSOR_BOTTOM_LEFT_CORNER* = 19 # Inherit from parent window.
-  GLUT_CURSOR_INHERIT* = 100  # Blank cursor.
-  GLUT_CURSOR_NONE* = 101     # Fullscreen crosshair (if available).
-  GLUT_CURSOR_FULL_CROSSHAIR* = 102 # GLUT device control sub-API.
-                                    # glutSetKeyRepeat modes.
-  GLUT_KEY_REPEAT_OFF* = 0
-  GLUT_KEY_REPEAT_ON* = 1
-  GLUT_KEY_REPEAT_DEFAULT* = 2 # Joystick button masks.
-  GLUT_JOYSTICK_BUTTON_A* = 1
-  GLUT_JOYSTICK_BUTTON_B* = 2
-  GLUT_JOYSTICK_BUTTON_C* = 4
-  GLUT_JOYSTICK_BUTTON_D* = 8 # GLUT game mode sub-API.
-                              # glutGameModeGet.
-  GLUT_GAME_MODE_ACTIVE* = 0
-  GLUT_GAME_MODE_POSSIBLE* = 1
-  GLUT_GAME_MODE_WIDTH* = 2
-  GLUT_GAME_MODE_HEIGHT* = 3
-  GLUT_GAME_MODE_PIXEL_DEPTH* = 4
-  GLUT_GAME_MODE_REFRESH_RATE* = 5
-  GLUT_GAME_MODE_DISPLAY_CHANGED* = 6 # GLUT initialization sub-API.
-
-{.push dynlib: dllname, importc.}
-proc glutInit*(argcp: ptr cint, argv: pointer)
-
-proc glutInit*() =
-  ## version that passes `argc` and `argc` implicitely.
-  var
-    cmdLine {.importc: "cmdLine".}: array[0..255, cstring]
-    cmdCount {.importc: "cmdCount".}: cint
-  glutInit(addr(cmdCount), addr(cmdLine))
-
-proc glutInitDisplayMode*(mode: int16)
-proc glutInitDisplayString*(str: cstring)
-proc glutInitWindowPosition*(x, y: int)
-proc glutInitWindowSize*(width, height: int)
-proc glutMainLoop*()
-  # GLUT window sub-API.
-proc glutCreateWindow*(title: cstring): int
-proc glutCreateSubWindow*(win, x, y, width, height: int): int
-proc glutDestroyWindow*(win: int)
-proc glutPostRedisplay*()
-proc glutPostWindowRedisplay*(win: int)
-proc glutSwapBuffers*()
-proc glutSetWindow*(win: int)
-proc glutSetWindowTitle*(title: cstring)
-proc glutSetIconTitle*(title: cstring)
-proc glutPositionWindow*(x, y: int)
-proc glutReshapeWindow*(width, height: int)
-proc glutPopWindow*()
-proc glutPushWindow*()
-proc glutIconifyWindow*()
-proc glutShowWindow*()
-proc glutHideWindow*()
-proc glutFullScreen*()
-proc glutSetCursor*(cursor: int)
-proc glutWarpPointer*(x, y: int)
-  # GLUT overlay sub-API.
-proc glutEstablishOverlay*()
-proc glutRemoveOverlay*()
-proc glutUseLayer*(layer: GLenum)
-proc glutPostOverlayRedisplay*()
-proc glutPostWindowOverlayRedisplay*(win: int)
-proc glutShowOverlay*()
-proc glutHideOverlay*()
-  # GLUT menu sub-API.
-proc glutCreateMenu*(callback: TGlut1IntCallback): int
-proc glutDestroyMenu*(menu: int)
-proc glutSetMenu*(menu: int)
-proc glutAddMenuEntry*(caption: cstring, value: int)
-proc glutAddSubMenu*(caption: cstring, submenu: int)
-proc glutChangeToMenuEntry*(item: int, caption: cstring, value: int)
-proc glutChangeToSubMenu*(item: int, caption: cstring, submenu: int)
-proc glutRemoveMenuItem*(item: int)
-proc glutAttachMenu*(button: int)
-proc glutDetachMenu*(button: int)
-  # GLUT window callback sub-API.
-proc glutDisplayFunc*(f: TGlutVoidCallback)
-proc glutReshapeFunc*(f: TGlut2IntCallback)
-proc glutKeyboardFunc*(f: TGlut1Char2IntCallback)
-proc glutMouseFunc*(f: TGlut4IntCallback)
-proc glutMotionFunc*(f: TGlut2IntCallback)
-proc glutPassiveMotionFunc*(f: TGlut2IntCallback)
-proc glutEntryFunc*(f: TGlut1IntCallback)
-proc glutVisibilityFunc*(f: TGlut1IntCallback)
-proc glutIdleFunc*(f: TGlutVoidCallback)
-proc glutTimerFunc*(millis: int16, f: TGlut1IntCallback, value: int)
-proc glutMenuStateFunc*(f: TGlut1IntCallback)
-proc glutSpecialFunc*(f: TGlut3IntCallback)
-proc glutSpaceballMotionFunc*(f: TGlut3IntCallback)
-proc glutSpaceballRotateFunc*(f: TGlut3IntCallback)
-proc glutSpaceballButtonFunc*(f: TGlut2IntCallback)
-proc glutButtonBoxFunc*(f: TGlut2IntCallback)
-proc glutDialsFunc*(f: TGlut2IntCallback)
-proc glutTabletMotionFunc*(f: TGlut2IntCallback)
-proc glutTabletButtonFunc*(f: TGlut4IntCallback)
-proc glutMenuStatusFunc*(f: TGlut3IntCallback)
-proc glutOverlayDisplayFunc*(f: TGlutVoidCallback)
-proc glutWindowStatusFunc*(f: TGlut1IntCallback)
-proc glutKeyboardUpFunc*(f: TGlut1Char2IntCallback)
-proc glutSpecialUpFunc*(f: TGlut3IntCallback)
-proc glutJoystickFunc*(f: TGlut1UInt3IntCallback, pollInterval: int)
-  # GLUT color index sub-API.
-proc glutSetColor*(cell: int, red, green, blue: GLfloat)
-proc glutGetColor*(ndx, component: int): GLfloat
-proc glutCopyColormap*(win: int)
-  # GLUT state retrieval sub-API.
-  # GLUT extension support sub-API
-proc glutExtensionSupported*(name: cstring): int
-  # GLUT font sub-API
-proc glutBitmapCharacter*(font: pointer, character: int)
-proc glutBitmapWidth*(font: pointer, character: int): int
-proc glutStrokeCharacter*(font: pointer, character: int)
-proc glutStrokeWidth*(font: pointer, character: int): int
-proc glutBitmapLength*(font: pointer, str: cstring): int
-proc glutStrokeLength*(font: pointer, str: cstring): int
-  # GLUT pre-built models sub-API
-proc glutWireSphere*(radius: GLdouble, slices, stacks: GLint)
-proc glutSolidSphere*(radius: GLdouble, slices, stacks: GLint)
-proc glutWireCone*(base, height: GLdouble, slices, stacks: GLint)
-proc glutSolidCone*(base, height: GLdouble, slices, stacks: GLint)
-proc glutWireCube*(size: GLdouble)
-proc glutSolidCube*(size: GLdouble)
-proc glutWireTorus*(innerRadius, outerRadius: GLdouble, sides, rings: GLint)
-proc glutSolidTorus*(innerRadius, outerRadius: GLdouble, sides, rings: GLint)
-proc glutWireDodecahedron*()
-proc glutSolidDodecahedron*()
-proc glutWireTeapot*(size: GLdouble)
-proc glutSolidTeapot*(size: GLdouble)
-proc glutWireOctahedron*()
-proc glutSolidOctahedron*()
-proc glutWireTetrahedron*()
-proc glutSolidTetrahedron*()
-proc glutWireIcosahedron*()
-proc glutSolidIcosahedron*()
-  # GLUT video resize sub-API.
-proc glutVideoResizeGet*(param: GLenum): int
-proc glutSetupVideoResizing*()
-proc glutStopVideoResizing*()
-proc glutVideoResize*(x, y, width, height: int)
-proc glutVideoPan*(x, y, width, height: int)
-  # GLUT debugging sub-API.
-proc glutReportErrors*()
-  # GLUT device control sub-API.
-proc glutIgnoreKeyRepeat*(ignore: int)
-proc glutSetKeyRepeat*(repeatMode: int)
-proc glutForceJoystickFunc*()
-  # GLUT game mode sub-API.
-  #example glutGameModeString('1280x1024:32@75');
-proc glutGameModeString*(AString: cstring)
-proc glutLeaveGameMode*()
-proc glutGameModeGet*(mode: GLenum): int
-# implementation
-{.pop.} # dynlib: dllname, importc
diff --git a/tests/deps/opengl-1.1.0/glx.nim b/tests/deps/opengl-1.1.0/glx.nim
deleted file mode 100644
index 6ad096c7d..000000000
--- a/tests/deps/opengl-1.1.0/glx.nim
+++ /dev/null
@@ -1,154 +0,0 @@
-#
-#
-#  Translation of the Mesa GLX headers for FreePascal
-#  Copyright (C) 1999 Sebastian Guenther
-#
-#
-#  Mesa 3-D graphics library
-#  Version:  3.0
-#  Copyright (C) 1995-1998  Brian Paul
-#
-#  This library is free software; you can redistribute it and/or
-#  modify it under the terms of the GNU Library General Public
-#  License as published by the Free Software Foundation; either
-#  version 2 of the License, or (at your option) any later version.
-#
-#  This library is distributed in the hope that it will be useful,
-#  but WITHOUT ANY WARRANTY; without even the implied warranty of
-#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
-#  Library General Public License for more details.
-#
-#  You should have received a copy of the GNU Library General Public
-#  License along with this library; if not, write to the Free
-#  Software Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
-#
-
-import X, XLib, XUtil, opengl
-
-{.deadCodeElim: on.}
-
-when defined(windows):
-  const
-    dllname = "GL.dll"
-elif defined(macosx):
-  const
-    dllname = "/usr/X11R6/lib/libGL.dylib"
-else:
-  const
-    dllname = "libGL.so"
-const
-  GLX_USE_GL* = 1'i32
-  GLX_BUFFER_SIZE* = 2'i32
-  GLX_LEVEL* = 3'i32
-  GLX_RGBA* = 4'i32
-  GLX_DOUBLEBUFFER* = 5'i32
-  GLX_STEREO* = 6'i32
-  GLX_AUX_BUFFERS* = 7'i32
-  GLX_RED_SIZE* = 8'i32
-  GLX_GREEN_SIZE* = 9'i32
-  GLX_BLUE_SIZE* = 10'i32
-  GLX_ALPHA_SIZE* = 11'i32
-  GLX_DEPTH_SIZE* = 12'i32
-  GLX_STENCIL_SIZE* = 13'i32
-  GLX_ACCUM_RED_SIZE* = 14'i32
-  GLX_ACCUM_GREEN_SIZE* = 15'i32
-  GLX_ACCUM_BLUE_SIZE* = 16'i32
-  GLX_ACCUM_ALPHA_SIZE* = 17'i32  # GLX_EXT_visual_info extension
-  GLX_X_VISUAL_TYPE_EXT* = 0x00000022
-  GLX_TRANSPARENT_TYPE_EXT* = 0x00000023
-  GLX_TRANSPARENT_INDEX_VALUE_EXT* = 0x00000024
-  GLX_TRANSPARENT_RED_VALUE_EXT* = 0x00000025
-  GLX_TRANSPARENT_GREEN_VALUE_EXT* = 0x00000026
-  GLX_TRANSPARENT_BLUE_VALUE_EXT* = 0x00000027
-  GLX_TRANSPARENT_ALPHA_VALUE_EXT* = 0x00000028 # Error codes returned by glXGetConfig:
-  GLX_BAD_SCREEN* = 1
-  GLX_BAD_ATTRIBUTE* = 2
-  GLX_NO_EXTENSION* = 3
-  GLX_BAD_VISUAL* = 4
-  GLX_BAD_CONTEXT* = 5
-  GLX_BAD_VALUE* = 6
-  GLX_BAD_ENUM* = 7           # GLX 1.1 and later:
-  GLX_VENDOR* = 1
-  GLX_VERSION* = 2
-  GLX_EXTENSIONS* = 3         # GLX_visual_info extension
-  GLX_TRUE_COLOR_EXT* = 0x00008002
-  GLX_DIRECT_COLOR_EXT* = 0x00008003
-  GLX_PSEUDO_COLOR_EXT* = 0x00008004
-  GLX_STATIC_COLOR_EXT* = 0x00008005
-  GLX_GRAY_SCALE_EXT* = 0x00008006
-  GLX_STATIC_GRAY_EXT* = 0x00008007
-  GLX_NONE_EXT* = 0x00008000
-  GLX_TRANSPARENT_RGB_EXT* = 0x00008008
-  GLX_TRANSPARENT_INDEX_EXT* = 0x00008009
-
-type                          # From XLib:
-  XPixmap* = TXID
-  XFont* = TXID
-  XColormap* = TXID
-  GLXContext* = pointer
-  GLXPixmap* = TXID
-  GLXDrawable* = TXID
-  GLXContextID* = TXID
-  TXPixmap* = XPixmap
-  TXFont* = XFont
-  TXColormap* = XColormap
-  TGLXContext* = GLXContext
-  TGLXPixmap* = GLXPixmap
-  TGLXDrawable* = GLXDrawable
-  TGLXContextID* = GLXContextID
-
-proc glXChooseVisual*(dpy: PDisplay, screen: int, attribList: ptr int32): PXVisualInfo{.
-    cdecl, dynlib: dllname, importc: "glXChooseVisual".}
-proc glXCreateContext*(dpy: PDisplay, vis: PXVisualInfo, shareList: GLXContext,
-                       direct: bool): GLXContext{.cdecl, dynlib: dllname,
-    importc: "glXCreateContext".}
-proc glXDestroyContext*(dpy: PDisplay, ctx: GLXContext){.cdecl, dynlib: dllname,
-    importc: "glXDestroyContext".}
-proc glXMakeCurrent*(dpy: PDisplay, drawable: GLXDrawable, ctx: GLXContext): bool{.
-    cdecl, dynlib: dllname, importc: "glXMakeCurrent".}
-proc glXCopyContext*(dpy: PDisplay, src, dst: GLXContext, mask: int32){.cdecl,
-    dynlib: dllname, importc: "glXCopyContext".}
-proc glXSwapBuffers*(dpy: PDisplay, drawable: GLXDrawable){.cdecl,
-    dynlib: dllname, importc: "glXSwapBuffers".}
-proc glXCreateGLXPixmap*(dpy: PDisplay, visual: PXVisualInfo, pixmap: XPixmap): GLXPixmap{.
-    cdecl, dynlib: dllname, importc: "glXCreateGLXPixmap".}
-proc glXDestroyGLXPixmap*(dpy: PDisplay, pixmap: GLXPixmap){.cdecl,
-    dynlib: dllname, importc: "glXDestroyGLXPixmap".}
-proc glXQueryExtension*(dpy: PDisplay, errorb, event: var int): bool{.cdecl,
-    dynlib: dllname, importc: "glXQueryExtension".}
-proc glXQueryVersion*(dpy: PDisplay, maj, min: var int): bool{.cdecl,
-    dynlib: dllname, importc: "glXQueryVersion".}
-proc glXIsDirect*(dpy: PDisplay, ctx: GLXContext): bool{.cdecl, dynlib: dllname,
-    importc: "glXIsDirect".}
-proc glXGetConfig*(dpy: PDisplay, visual: PXVisualInfo, attrib: int,
-                   value: var int): int{.cdecl, dynlib: dllname,
-    importc: "glXGetConfig".}
-proc glXGetCurrentContext*(): GLXContext{.cdecl, dynlib: dllname,
-    importc: "glXGetCurrentContext".}
-proc glXGetCurrentDrawable*(): GLXDrawable{.cdecl, dynlib: dllname,
-    importc: "glXGetCurrentDrawable".}
-proc glXWaitGL*(){.cdecl, dynlib: dllname, importc: "glXWaitGL".}
-proc glXWaitX*(){.cdecl, dynlib: dllname, importc: "glXWaitX".}
-proc glXUseXFont*(font: XFont, first, count, list: int){.cdecl, dynlib: dllname,
-    importc: "glXUseXFont".}
-  # GLX 1.1 and later
-proc glXQueryExtensionsString*(dpy: PDisplay, screen: int): cstring{.cdecl,
-    dynlib: dllname, importc: "glXQueryExtensionsString".}
-proc glXQueryServerString*(dpy: PDisplay, screen, name: int): cstring{.cdecl,
-    dynlib: dllname, importc: "glXQueryServerString".}
-proc glXGetClientString*(dpy: PDisplay, name: int): cstring{.cdecl,
-    dynlib: dllname, importc: "glXGetClientString".}
-  # Mesa GLX Extensions
-proc glXCreateGLXPixmapMESA*(dpy: PDisplay, visual: PXVisualInfo,
-                             pixmap: XPixmap, cmap: XColormap): GLXPixmap{.
-    cdecl, dynlib: dllname, importc: "glXCreateGLXPixmapMESA".}
-proc glXReleaseBufferMESA*(dpy: PDisplay, d: GLXDrawable): bool{.cdecl,
-    dynlib: dllname, importc: "glXReleaseBufferMESA".}
-proc glXCopySubBufferMESA*(dpy: PDisplay, drawbale: GLXDrawable,
-                           x, y, width, height: int){.cdecl, dynlib: dllname,
-    importc: "glXCopySubBufferMESA".}
-proc glXGetVideoSyncSGI*(counter: var int32): int{.cdecl, dynlib: dllname,
-    importc: "glXGetVideoSyncSGI".}
-proc glXWaitVideoSyncSGI*(divisor, remainder: int, count: var int32): int{.
-    cdecl, dynlib: dllname, importc: "glXWaitVideoSyncSGI".}
-# implementation
diff --git a/tests/deps/opengl-1.1.0/opengl.nim b/tests/deps/opengl-1.1.0/opengl.nim
deleted file mode 100644
index 55e009a46..000000000
--- a/tests/deps/opengl-1.1.0/opengl.nim
+++ /dev/null
@@ -1,8481 +0,0 @@
-
-#
-#
-#            Nimrod's Runtime Library
-#        (c) Copyright 2012 Andreas Rumpf
-#
-#    See the file "copying.txt", included in this
-#    distribution, for details about the copyright.
-#
-
-## This module is a wrapper around `opengl`:idx:. If you define the symbol
-## ``useGlew`` this wrapper does not use Nimrod's ``dynlib`` mechanism,
-## but `glew`:idx: instead. However, this shouldn't be necessary anymore; even
-## extension loading for the different operating systems is handled here.
-##
-## You need to call ``loadExtensions`` after a rendering context has been
-## created to load any extension proc that your code uses.
-
-{.deadCodeElim: on.}
-
-import macros, sequtils
-
-{.push warning[User]: off.}
-
-when defined(linux) and not defined(android) and not defined(emscripten):
-  import X, XLib, XUtil
-elif defined(windows):
-  import winlean, os
-
-when defined(windows):
-  const
-    ogldll* = "OpenGL32.dll"
-    gludll* = "GLU32.dll"
-elif defined(macosx):
-  #macosx has this notion of a framework, thus the path to the openGL dylib files
-  #is absolute
-  const
-    ogldll* = "/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries/libGL.dylib"
-    gludll* = "/System/Library/Frameworks/OpenGL.framework/Versions/Current/Libraries/libGLU.dylib"
-else:
-  const
-    ogldll* = "libGL.so.1"
-    gludll* = "libGLU.so.1"
-
-when defined(useGlew):
-  {.pragma: ogl, header: "<GL/glew.h>".}
-  {.pragma: oglx, header: "<GL/glxew.h>".}
-  {.pragma: wgl, header: "<GL/wglew.h>".}
-  {.pragma: glu, dynlib: gludll.}
-elif defined(ios):
-  {.pragma: ogl.}
-  {.pragma: oglx.}
-  {.passC: "-framework OpenGLES", passL: "-framework OpenGLES".}
-elif defined(android) or defined(js) or defined(emscripten):
-  {.pragma: ogl.}
-  {.pragma: oglx.}
-else:
-  # quite complex ... thanks to extension support for various platforms:
-  import dynlib
-
-  let oglHandle = loadLib(ogldll)
-  if isNil(oglHandle): quit("could not load: " & ogldll)
-
-  when defined(windows):
-    var wglGetProcAddress = cast[proc (s: cstring): pointer {.stdcall.}](
-      symAddr(oglHandle, "wglGetProcAddress"))
-  elif defined(linux):
-    var glxGetProcAddress = cast[proc (s: cstring): pointer {.cdecl.}](
-      symAddr(oglHandle, "glxGetProcAddress"))
-    var glxGetProcAddressArb = cast[proc (s: cstring): pointer {.cdecl.}](
-      symAddr(oglHandle, "glxGetProcAddressARB"))
-
-  proc glGetProc(h: LibHandle; procName: cstring): pointer =
-    when defined(windows):
-      result = symAddr(h, procname)
-      if result != nil: return
-      if not isNil(wglGetProcAddress): result = wglGetProcAddress(procName)
-    elif defined(linux):
-      if not isNil(glxGetProcAddress): result = glxGetProcAddress(procName)
-      if result != nil: return
-      if not isNil(glxGetProcAddressArb):
-        result = glxGetProcAddressArb(procName)
-        if result != nil: return
-      result = symAddr(h, procname)
-    else:
-      result = symAddr(h, procName)
-    if result == nil: raiseInvalidLibrary(procName)
-
-  var gluHandle: LibHandle
-
-  proc gluGetProc(procname: cstring): pointer =
-    if gluHandle == nil:
-      gluHandle = loadLib(gludll)
-      if gluHandle == nil: quit("could not load: " & gludll)
-    result = glGetProc(gluHandle, procname)
-
-  # undocumented 'dynlib' feature: the string literal is replaced by
-  # the imported proc name:
-  {.pragma: ogl, dynlib: glGetProc(oglHandle, "0").}
-  {.pragma: oglx, dynlib: glGetProc(oglHandle, "0").}
-  {.pragma: wgl, dynlib: glGetProc(oglHandle, "0").}
-  {.pragma: glu, dynlib: gluGetProc("").}
-
-  proc nimLoadProcs0() {.importc.}
-
-  template loadExtensions*() =
-    ## call this after your rendering context has been setup if you use
-    ## extensions.
-    bind nimLoadProcs0
-    nimLoadProcs0()
-
-{.pop.} # warning[User]: off
-
-type
-  GLenum* = distinct uint32
-  GLboolean* = bool
-  GLbitfield* = distinct uint32
-  GLvoid* = pointer
-  GLbyte* = int8
-  GLshort* = int64
-  GLint* = int32
-  GLclampx* = int32
-  GLubyte* = uint8
-  GLushort* = uint16
-  GLuint* = uint32
-  GLhandle* = GLuint
-  GLsizei* = int32
-  GLfloat* = float32
-  GLclampf* = float32
-  GLdouble* = float64
-  GLclampd* = float64
-  GLeglImageOES* = distinct pointer
-  GLchar* = char
-  GLcharArb* = char
-  GLfixed* = int32
-  GLhalfNv* = uint16
-  GLvdpauSurfaceNv* = uint
-  GLintptr* = int
-  GLintptrArb* = int
-  GLint64EXT* = int64
-  GLuint64EXT* = uint64
-  GLint64* = int64
-  GLsizeiptrArb* = int
-  GLsizeiptr* = int
-  GLsync* = distinct pointer
-  GLuint64* = uint64
-  GLvectorub2* = array[0..1, GLubyte]
-  GLvectori2* = array[0..1, GLint]
-  GLvectorf2* = array[0..1, GLfloat]
-  GLvectord2* = array[0..1, GLdouble]
-  GLvectorp2* = array[0..1, pointer]
-  GLvectorb3* = array[0..2, GLbyte]
-  GLvectorub3* = array[0..2, GLubyte]
-  GLvectori3* = array[0..2, GLint]
-  GLvectorui3* = array[0..2, GLuint]
-  GLvectorf3* = array[0..2, GLfloat]
-  GLvectord3* = array[0..2, GLdouble]
-  GLvectorp3* = array[0..2, pointer]
-  GLvectors3* = array[0..2, GLshort]
-  GLvectorus3* = array[0..2, GLushort]
-  GLvectorb4* = array[0..3, GLbyte]
-  GLvectorub4* = array[0..3, GLubyte]
-  GLvectori4* = array[0..3, GLint]
-  GLvectorui4* = array[0..3, GLuint]
-  GLvectorf4* = array[0..3, GLfloat]
-  GLvectord4* = array[0..3, GLdouble]
-  GLvectorp4* = array[0..3, pointer]
-  GLvectors4* = array[0..3, GLshort]
-  GLvectorus4* = array[0..3, GLshort]
-  GLarray4f* = GLvectorf4
-  GLarrayf3* = GLvectorf3
-  GLarrayd3* = GLvectord3
-  GLarrayi4* = GLvectori4
-  GLarrayp4* = GLvectorp4
-  GLmatrixub3* = array[0..2, array[0..2, GLubyte]]
-  GLmatrixi3* = array[0..2, array[0..2, GLint]]
-  GLmatrixf3* = array[0..2, array[0..2, GLfloat]]
-  GLmatrixd3* = array[0..2, array[0..2, GLdouble]]
-  GLmatrixub4* = array[0..3, array[0..3, GLubyte]]
-  GLmatrixi4* = array[0..3, array[0..3, GLint]]
-  GLmatrixf4* = array[0..3, array[0..3, GLfloat]]
-  GLmatrixd4* = array[0..3, array[0..3, GLdouble]]
-  ClContext* = distinct pointer
-  ClEvent* = distinct pointer
-  GLdebugProc* = proc (
-    source: GLenum,
-    typ: GLenum,
-    id: GLuint,
-    severity: GLenum,
-    length: GLsizei,
-    message: ptr GLchar,
-    userParam: pointer) {.stdcall.}
-  GLdebugProcArb* = proc (
-    source: GLenum,
-    typ: GLenum,
-    id: GLuint,
-    severity: GLenum,
-    len: GLsizei,
-    message: ptr GLchar,
-    userParam: pointer) {.stdcall.}
-  GLdebugProcAmd* = proc (
-    id: GLuint,
-    category: GLenum,
-    severity: GLenum,
-    len: GLsizei,
-    message: ptr GLchar,
-    userParam: pointer) {.stdcall.}
-  GLdebugProcKhr* = proc (
-    source, typ: GLenum,
-    id: GLuint,
-    severity: GLenum,
-    length: GLsizei,
-    message: ptr GLchar,
-    userParam: pointer) {.stdcall.}
-type
-  GLerrorCode* {.size: GLenum.sizeof.} = enum # XXX: can't be evaluated when
-                                              # in the same type section as
-                                              # GLenum.
-    glErrNoError = (0, "no error")
-    glErrInvalidEnum = (0x0500, "invalid enum")
-    glErrInvalidValue = (0x0501, "invalid value")
-    glErrInvalidOperation = (0x0502, "invalid operation")
-    glErrStackOverflow = (0x0503, "stack overflow")
-    glErrStackUnderflow = (0x0504, "stack underflow")
-    glErrOutOfMem = (0x0505, "out of memory")
-    glErrInvalidFramebufferOperation = (0x0506, "invalid framebuffer operation")
-    glErrTableTooLarge = (0x8031, "table too large")
-
-const AllErrorCodes = {
-    glErrNoError,
-    glErrInvalidEnum,
-    glErrInvalidValue,
-    glErrInvalidOperation,
-    glErrStackOverflow,
-    glErrStackUnderflow,
-    glErrOutOfMem,
-    glErrInvalidFramebufferOperation,
-    glErrTableTooLarge,
-}
-
-when defined(macosx):
-  type
-    GLhandleArb = pointer
-else:
-  type
-    GLhandleArb = uint32
-
-{.deprecated: [
-  TGLerror: GLerrorCode,
-  TGLhandleARB: GLhandleArb,
-  TGLenum: GLenum,
-  TGLboolean: GLboolean,
-  TGLbitfield: GLbitfield,
-  TGLvoid: GLvoid,
-  TGLbyte: GLbyte,
-  TGLshort: GLshort,
-  TGLint: GLint,
-  TGLclampx: GLclampx,
-  TGLubyte: GLubyte,
-  TGLushort: GLushort,
-  TGLuint: GLuint,
-  TGLsizei: GLsizei,
-  TGLfloat: GLfloat,
-  TGLclampf: GLclampf,
-  TGLdouble: GLdouble,
-  TGLclampd: GLclampd,
-  TGLeglImageOES: GLeglImageOES,
-  TGLchar: GLchar,
-  TGLcharARB: GLcharArb,
-  TGLfixed: GLfixed,
-  TGLhalfNV: GLhalfNv,
-  TGLvdpauSurfaceNv: GLvdpauSurfaceNv,
-  TGLintptr: GLintptr,
-  TGLintptrARB: GLintptrArb,
-  TGLint64EXT: GLint64Ext,
-  TGLuint64EXT: GLuint64Ext,
-  TGLint64: GLint64,
-  TGLsizeiptrARB: GLsizeiptrArb,
-  TGLsizeiptr: GLsizeiptr,
-  TGLsync: GLsync,
-  TGLuint64: GLuint64,
-  TCL_context: ClContext,
-  TCL_event: ClEvent,
-  TGLdebugProc: GLdebugProc,
-  TGLDebugProcARB: GLdebugProcArb,
-  TGLDebugProcAMD: GLdebugProcAmd,
-  TGLDebugProcKHR: GLdebugProcKhr,
-  TGLVectorub2: GLvectorub2,
-  TGLVectori2: GLvectori2,
-  TGLVectorf2: GLvectorf2,
-  TGLVectord2: GLvectord2,
-  TGLVectorp2: GLvectorp2,
-  TGLVectorb3: GLvectorb3,
-  TGLVectorub3: GLvectorub3,
-  TGLVectori3: GLvectori3,
-  TGLVectorui3: GLvectorui3,
-  TGLVectorf3: GLvectorf3,
-  TGLVectord3: GLvectord3,
-  TGLVectorp3: GLvectorp3,
-  TGLVectors3: GLvectors3,
-  TGLVectorus3: GLvectorus3,
-  TGLVectorb4: GLvectorb4,
-  TGLVectorub4: GLvectorub4,
-  TGLVectori4: GLvectori4,
-  TGLVectorui4: GLvectorui4,
-  TGLVectorf4: GLvectorf4,
-  TGLVectord4: GLvectord4,
-  TGLVectorp4: GLvectorp4,
-  TGLVectors4: GLvectors4,
-  TGLVectorus4: GLvectorus4,
-  TGLArrayf4: GLarray4f,
-  TGLArrayf3: GLarrayf3,
-  TGLArrayd3: GLarrayd3,
-  TGLArrayi4: GLarrayi4,
-  TGLArrayp4: GLarrayp4,
-  TGLMatrixub3: GLmatrixub3,
-  TGLMatrixi3: GLmatrixi3,
-  TGLMatrixf3: GLmatrixf3,
-  TGLMatrixd3: GLmatrixd3,
-  TGLMatrixub4: GLmatrixub4,
-  TGLMatrixi4: GLmatrixi4,
-  TGLMatrixf4: GLmatrixf4,
-  TGLMatrixd4: GLmatrixd4,
-  TGLVector3d: GLvectord3,
-  TGLVector4i: GLvectori4,
-  TGLVector4f: GLvectorf4,
-  TGLVector4p: GLvectorp4,
-  TGLMatrix4f: GLmatrixf4,
-  TGLMatrix4d: GLmatrixd4,
-].}
-
-proc `==`*(a, b: GLenum): bool {.borrow.}
-
-proc `==`*(a, b: GLbitfield): bool {.borrow.}
-
-proc `or`*(a, b: GLbitfield): GLbitfield {.borrow.}
-
-proc hash*(x: GLenum): int =
-  result = x.int
-
-proc glGetError*: GLenum {.stdcall, importc, ogl.}
-proc getGLerrorCode*: GLerrorCode = glGetError().GLerrorCode
-  ## Like ``glGetError`` but returns an enumerator instead.
-
-type
-  GLerror* = object of Exception
-    ## An exception for OpenGL errors.
-    code*: GLerrorCode ## The error code. This might be invalid for two reasons:
-                    ## an outdated list of errors or a bad driver.
-
-proc checkGLerror* =
-  ## Raise ``GLerror`` if the last call to an OpenGL function generated an error.
-  ## You might want to call this once every frame for example if automatic
-  ## error checking has been disabled.
-  let error = getGLerrorCode()
-  if error == glErrNoError:
-    return
-
-  var
-    exc = new(GLerror)
-  for e in AllErrorCodes:
-    if e == error:
-      exc.msg = "OpenGL error: " & $e
-      raise exc
-
-  exc.code = error
-  exc.msg = "OpenGL error: unknown (" & $error & ")"
-  raise exc
-
-{.push warning[User]: off.}
-
-const
-  NoAutoGLerrorCheck* = defined(noAutoGLerrorCheck) ##\
-  ## This determines (at compile time) whether an exception should be raised
-  ## if an OpenGL call generates an error. No additional code will be generated
-  ## and ``enableAutoGLerrorCheck(bool)`` will have no effect when
-  ## ``noAutoGLerrorCheck`` is defined.
-
-{.pop.} # warning[User]: off
-
-var
-  gAutoGLerrorCheck = true
-  gInsideBeginEnd* = false # do not change manually.
-
-proc enableAutoGLerrorCheck*(yes: bool) =
-  ## This determines (at run time) whether an exception should be raised if an
-  ## OpenGL call generates an error. This has no effect when
-  ## ``noAutoGLerrorCheck`` is defined.
-  gAutoGLerrorCheck = yes
-
-macro wrapErrorChecking(f: stmt): stmt {.immediate.} =
-  f.expectKind nnkStmtList
-  result = newStmtList()
-
-  for child in f.children:
-    if child.kind == nnkCommentStmt:
-      continue
-    child.expectKind nnkProcDef
-
-    let params = toSeq(child.params.children)
-    var glProc = copy child
-    glProc.pragma = newNimNode(nnkPragma).add(
-        newNimNode(nnkExprColonExpr).add(
-          ident"importc" , newLit($child.name))
-      ).add(ident"ogl")
-
-    let rawGLprocName = $glProc.name
-    glProc.name = ident(rawGLprocName & "Impl")
-    var
-      body = newStmtList glProc
-      returnsSomething = child.params[0].kind != nnkEmpty
-      callParams = newSeq[when defined(nimnode): NimNode else: PNimrodNode]()
-    for param in params[1 ..< params.len]:
-      callParams.add param[0]
-
-    let glCall = newCall(glProc.name, callParams)
-    body.add if returnsSomething:
-        newAssignment(ident"result", glCall)
-      else:
-        glCall
-
-    if rawGLprocName == "glBegin":
-      body.add newAssignment(ident"gInsideBeginEnd", ident"true")
-    if rawGLprocName == "glEnd":
-      body.add newAssignment(ident"gInsideBeginEnd", ident"false")
-
-    template errCheck: stmt =
-      when not (NoAutoGLerrorCheck):
-        if gAutoGLerrorCheck and not gInsideBeginEnd:
-          checkGLerror()
-
-    body.add getAst(errCheck())
-
-    var procc = newProc(child.name, params, body)
-    procc.pragma = newNimNode(nnkPragma).add(ident"inline")
-    procc.name = postfix(procc.name, "*")
-    result.add procc
-
-{.push stdcall, hint[XDeclaredButNotUsed]: off, warning[SmallLshouldNotBeUsed]: off.}
-wrapErrorChecking:
-  proc glMultiTexCoord2d(target: GLenum, s: GLdouble, t: GLdouble) {.importc.}
-  proc glDrawElementsIndirect(mode: GLenum, `type`: GLenum, indirect: pointer) {.importc.}
-  proc glEnableVertexArrayEXT(vaobj: GLuint, `array`: GLenum) {.importc.}
-  proc glDeleteFramebuffers(n: GLsizei, framebuffers: ptr GLuint) {.importc.}
-  proc glMultiTexCoord3dv(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glVertexAttrib4d(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glLoadPaletteFromModelViewMatrixOES() {.importc.}
-  proc glVertex3xvOES(coords: ptr GLfixed) {.importc.}
-  proc glNormalStream3sATI(stream: GLenum, nx: GLshort, ny: GLshort, nz: GLshort) {.importc.}
-  proc glMatrixFrustumEXT(mode: GLenum, left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) {.importc.}
-  proc glUniformMatrix2fvARB(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glColor4dv(v: ptr GLdouble) {.importc.}
-  proc glColor3fv(v: ptr GLfloat) {.importc.}
-  proc glVertexAttribI1uiEXT(index: GLuint, x: GLuint) {.importc.}
-  proc glGetDebugMessageLogKHR(count: GLuint, bufsize: GLsizei, sources: ptr GLenum, types: ptr GLenum, ids: ptr GLuint, severities: ptr GLenum, lengths: ptr GLsizei, messageLog: cstring): GLuint {.importc.}
-  proc glVertexAttribI2iv(index: GLuint, v: ptr GLint) {.importc.}
-  proc glTexCoord1xvOES(coords: ptr GLfixed) {.importc.}
-  proc glVertex3hNV(x: GLhalfNv, y: GLhalfNv, z: GLhalfNv) {.importc.}
-  proc glIsShader(shader: GLuint): GLboolean {.importc.}
-  proc glDeleteRenderbuffersEXT(n: GLsizei, renderbuffers: ptr GLuint) {.importc.}
-  proc glVertex3hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glGetPointervKHR(pname: GLenum, params: ptr pointer) {.importc.}
-  proc glProgramUniform3i64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glNamedFramebufferTexture1DEXT(framebuffer: GLuint, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glGetNamedProgramLocalParameterfvEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLfloat) {.importc.}
-  proc glGenRenderbuffersOES(n: GLsizei, renderbuffers: ptr GLuint) {.importc.}
-  proc glVertex4dv(v: ptr GLdouble) {.importc.}
-  proc glTexCoord2fColor4ubVertex3fvSUN(tc: ptr GLfloat, c: ptr GLubyte, v: ptr GLfloat) {.importc.}
-  proc glTexStorage2DEXT(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glVertexAttrib2d(index: GLuint, x: GLdouble, y: GLdouble) {.importc.}
-  proc glVertexAttrib1dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glBindProgramARB(target: GLenum, program: GLuint) {.importc.}
-  proc glRasterPos2dv(v: ptr GLdouble) {.importc.}
-  proc glCompressedTextureSubImage2DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glNormalPointervINTEL(`type`: GLenum, `pointer`: ptr pointer) {.importc.}
-  proc glGetInteger64vAPPLE(pname: GLenum, params: ptr GLint64) {.importc.}
-  proc glPushMatrix() {.importc.}
-  proc glGetCompressedTexImageARB(target: GLenum, level: GLint, img: pointer) {.importc.}
-  proc glBindMaterialParameterEXT(face: GLenum, value: GLenum): GLuint {.importc.}
-  proc glBlendEquationIndexedAMD(buf: GLuint, mode: GLenum) {.importc.}
-  proc glGetObjectBufferfvATI(buffer: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glMakeNamedBufferNonResidentNV(buffer: GLuint) {.importc.}
-  proc glUniform2ui64NV(location: GLint, x: GLuint64Ext, y: GLuint64Ext) {.importc.}
-  proc glRasterPos4fv(v: ptr GLfloat) {.importc.}
-  proc glDeleteTextures(n: GLsizei, textures: ptr GLuint) {.importc.}
-  proc glSecondaryColorPointer(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glTextureSubImage1DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glEndTilingQCOM(preserveMask: GLbitfield) {.importc.}
-  proc glBindBuffer(target: GLenum, buffer: GLuint) {.importc.}
-  proc glUniformMatrix3fvARB(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glSamplerParameterf(sampler: GLuint, pname: GLenum, param: GLfloat) {.importc.}
-  proc glSecondaryColor3d(red: GLdouble, green: GLdouble, blue: GLdouble) {.importc.}
-  proc glVertexAttrib4sARB(index: GLuint, x: GLshort, y: GLshort, z: GLshort, w: GLshort) {.importc.}
-  proc glNamedProgramLocalParameterI4iEXT(program: GLuint, target: GLenum, index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glProgramUniform2iEXT(program: GLuint, location: GLint, v0: GLint, v1: GLint) {.importc.}
-  proc glPopAttrib() {.importc.}
-  proc glGetnColorTableARB(target: GLenum, format: GLenum, `type`: GLenum, bufSize: GLsizei, table: pointer) {.importc.}
-  proc glMatrixLoadIdentityEXT(mode: GLenum) {.importc.}
-  proc glGetNamedProgramivEXT(program: GLuint, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glCopyTextureSubImage2DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glUniform4i64NV(location: GLint, x: GLint64Ext, y: GLint64Ext, z: GLint64Ext, w: GLint64Ext) {.importc.}
-  proc glDeleteTexturesEXT(n: GLsizei, textures: ptr GLuint) {.importc.}
-  proc glMultiTexCoord1dv(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glMultiTexRenderbufferEXT(texunit: GLenum, target: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glMultiDrawArraysIndirect(mode: GLenum, indirect: ptr pointer, drawcount: GLsizei, stride: GLsizei) {.importc.}
-  proc glGetUniformfvARB(programObj: GLhandleArb, location: GLint, params: ptr GLfloat) {.importc.}
-  proc glBufferDataARB(target: GLenum, size: GLsizeiptrArb, data: pointer, usage: GLenum) {.importc.}
-  proc glTexCoord2d(s: GLdouble, t: GLdouble) {.importc.}
-  proc glGetArrayObjectfvATI(`array`: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glShaderOp1EXT(op: GLenum, res: GLuint, arg1: GLuint) {.importc.}
-  proc glColor3s(red: GLshort, green: GLshort, blue: GLshort) {.importc.}
-  proc glStencilFuncSeparate(face: GLenum, fun: GLenum, `ref`: GLint, mask: GLuint) {.importc.}
-  proc glTextureImage2DMultisampleCoverageNV(texture: GLuint, target: GLenum, coverageSamples: GLsizei, colorSamples: GLsizei, internalFormat: GLint, width: GLsizei, height: GLsizei, fixedSampleLocations: GLboolean) {.importc.}
-  proc glMultiTexCoord2xvOES(texture: GLenum, coords: ptr GLfixed) {.importc.}
-  proc glGetVertexAttribLui64vNV(index: GLuint, pname: GLenum, params: ptr GLuint64Ext) {.importc.}
-  proc glNormal3xOES(nx: GLfixed, ny: GLfixed, nz: GLfixed) {.importc.}
-  proc glMapBufferRangeEXT(target: GLenum, offset: GLintptr, length: GLsizeiptr, access: GLbitfield): pointer {.importc.}
-  proc glCreateShader(`type`: GLenum): GLuint {.importc.}
-  proc glDrawRangeElementArrayAPPLE(mode: GLenum, start: GLuint, `end`: GLuint, first: GLint, count: GLsizei) {.importc.}
-  proc glVertex2bOES(x: GLbyte) {.importc.}
-  proc glGetMapxvOES(target: GLenum, query: GLenum, v: ptr GLfixed) {.importc.}
-  proc glRasterPos3sv(v: ptr GLshort) {.importc.}
-  proc glDeleteQueriesARB(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glProgramUniform1iv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glVertexStream2dvATI(stream: GLenum, coords: ptr GLdouble) {.importc.}
-  proc glBindVertexArrayOES(`array`: GLuint) {.importc.}
-  proc glLightModelfv(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glEvalCoord2dv(u: ptr GLdouble) {.importc.}
-  proc glColor3hNV(red: GLhalfNv, green: GLhalfNv, blue: GLhalfNv) {.importc.}
-  proc glSecondaryColor3iEXT(red: GLint, green: GLint, blue: GLint) {.importc.}
-  proc glBindTexture(target: GLenum, texture: GLuint) {.importc.}
-  proc glUniformBufferEXT(program: GLuint, location: GLint, buffer: GLuint) {.importc.}
-  proc glGetCombinerInputParameterfvNV(stage: GLenum, portion: GLenum, variable: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glUniform2ui64vNV(location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glMatrixMultTransposefEXT(mode: GLenum, m: ptr GLfloat) {.importc.}
-  proc glLineWidth(width: GLfloat) {.importc.}
-  proc glRotatef(angle: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glNormalStream3svATI(stream: GLenum, coords: ptr GLshort) {.importc.}
-  proc glTexCoordP4ui(`type`: GLenum, coords: GLuint) {.importc.}
-  proc glImageTransformParameterfvHP(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glUniform3uiEXT(location: GLint, v0: GLuint, v1: GLuint, v2: GLuint) {.importc.}
-  proc glGetInvariantIntegervEXT(id: GLuint, value: GLenum, data: ptr GLint) {.importc.}
-  proc glGetTransformFeedbackVaryingEXT(program: GLuint, index: GLuint, bufSize: GLsizei, length: ptr GLsizei, size: ptr GLsizei, `type`: ptr GLenum, name: cstring) {.importc.}
-  proc glSamplerParameterIuiv(sampler: GLuint, pname: GLenum, param: ptr GLuint) {.importc.}
-  proc glProgramUniform2fEXT(program: GLuint, location: GLint, v0: GLfloat, v1: GLfloat) {.importc.}
-  proc glMultiTexCoord2hvNV(target: GLenum, v: ptr GLhalfNv) {.importc.}
-  proc glDeleteRenderbuffersOES(n: GLsizei, renderbuffers: ptr GLuint) {.importc.}
-  proc glRenderbufferStorageMultisampleCoverageNV(target: GLenum, coverageSamples: GLsizei, colorSamples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glStencilClearTagEXT(stencilTagBits: GLsizei, stencilClearTag: GLuint) {.importc.}
-  proc glConvolutionParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glFenceSyncAPPLE(condition: GLenum, flags: GLbitfield): GLsync {.importc.}
-  proc glGetVariantArrayObjectivATI(id: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramUniform4dvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glPushDebugGroupKHR(source: GLenum, id: GLuint, length: GLsizei, message: cstring) {.importc.}
-  proc glFragmentLightivSGIX(light: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glFramebufferTexture2DEXT(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glGetActiveSubroutineUniformiv(program: GLuint, shadertype: GLenum, index: GLuint, pname: GLenum, values: ptr GLint) {.importc.}
-  proc glFrustumf(l: GLfloat, r: GLfloat, b: GLfloat, t: GLfloat, n: GLfloat, f: GLfloat) {.importc.}
-  proc glEndQueryIndexed(target: GLenum, index: GLuint) {.importc.}
-  proc glCompressedTextureSubImage3DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glGetProgramPipelineInfoLogEXT(pipeline: GLuint, bufSize: GLsizei, length: ptr GLsizei, infoLog: cstring) {.importc.}
-  proc glGetVertexAttribfvNV(index: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexArrayIndexOffsetEXT(vaobj: GLuint, buffer: GLuint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glDrawTexsvOES(coords: ptr GLshort) {.importc.}
-  proc glMultiTexCoord1hNV(target: GLenum, s: GLhalfNv) {.importc.}
-  proc glWindowPos2iv(v: ptr GLint) {.importc.}
-  proc glMultiTexCoordP1ui(texture: GLenum, `type`: GLenum, coords: GLuint) {.importc.}
-  proc glTexCoord1i(s: GLint) {.importc.}
-  proc glVertex4hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glCallLists(n: GLsizei, `type`: GLenum, lists: pointer) {.importc.}
-  proc glIndexFormatNV(`type`: GLenum, stride: GLsizei) {.importc.}
-  proc glPointParameterfARB(pname: GLenum, param: GLfloat) {.importc.}
-  proc glProgramUniform1dv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glGetVertexAttribArrayObjectfvATI(index: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVDPAUUnmapSurfacesNV(numSurface: GLsizei, surfaces: ptr GLvdpauSurfaceNv) {.importc.}
-  proc glVertexAttribIFormat(attribindex: GLuint, size: GLint, `type`: GLenum, relativeoffset: GLuint) {.importc.}
-  proc glClearColorx(red: GLfixed, green: GLfixed, blue: GLfixed, alpha: GLfixed) {.importc.}
-  proc glColor3bv(v: ptr GLbyte) {.importc.}
-  proc glNamedProgramLocalParameter4dEXT(program: GLuint, target: GLenum, index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glVertexPointer(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glGetObjectLabelKHR(identifier: GLenum, name: GLuint, bufSize: GLsizei, length: ptr GLsizei, label: cstring) {.importc.}
-  proc glCombinerStageParameterfvNV(stage: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glNormal3hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glUniform2i64NV(location: GLint, x: GLint64Ext, y: GLint64Ext) {.importc.}
-  proc glMultiTexCoord2iv(target: GLenum, v: ptr GLint) {.importc.}
-  proc glProgramUniform3i(program: GLuint, location: GLint, v0: GLint, v1: GLint, v2: GLint) {.importc.}
-  proc glDeleteAsyncMarkersSGIX(marker: GLuint, range: GLsizei) {.importc.}
-  proc glStencilOp(fail: GLenum, zfail: GLenum, zpass: GLenum) {.importc.}
-  proc glColorP4ui(`type`: GLenum, color: GLuint) {.importc.}
-  proc glFinishAsyncSGIX(markerp: ptr GLuint): GLint {.importc.}
-  proc glDrawTexsOES(x: GLshort, y: GLshort, z: GLshort, width: GLshort, height: GLshort) {.importc.}
-  proc glLineStipple(factor: GLint, pattern: GLushort) {.importc.}
-  proc glAlphaFragmentOp1ATI(op: GLenum, dst: GLuint, dstMod: GLuint, arg1: GLuint, arg1Rep: GLuint, arg1Mod: GLuint) {.importc.}
-  proc glMapTexture2DINTEL(texture: GLuint, level: GLint, access: GLbitfield, stride: ptr GLint, layout: ptr GLenum): pointer {.importc.}
-  proc glVertex4f(x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glFramebufferTextureARB(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glProgramUniform3ui64NV(program: GLuint, location: GLint, x: GLuint64Ext, y: GLuint64Ext, z: GLuint64Ext) {.importc.}
-  proc glMultTransposeMatrixxOES(m: ptr GLfixed) {.importc.}
-  proc glNormal3fv(v: ptr GLfloat) {.importc.}
-  proc glUniform4fARB(location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat, v3: GLfloat) {.importc.}
-  proc glBinormal3bEXT(bx: GLbyte, by: GLbyte, bz: GLbyte) {.importc.}
-  proc glGenProgramPipelinesEXT(n: GLsizei, pipelines: ptr GLuint) {.importc.}
-  proc glDispatchComputeIndirect(indirect: GLintptr) {.importc.}
-  proc glGetPerfMonitorCounterDataAMD(monitor: GLuint, pname: GLenum, dataSize: GLsizei, data: ptr GLuint, bytesWritten: ptr GLint) {.importc.}
-  proc glStencilOpValueAMD(face: GLenum, value: GLuint) {.importc.}
-  proc glTangent3fvEXT(v: ptr GLfloat) {.importc.}
-  proc glUniform3iARB(location: GLint, v0: GLint, v1: GLint, v2: GLint) {.importc.}
-  proc glMatrixScalefEXT(mode: GLenum, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glVertexAttrib2dARB(index: GLuint, x: GLdouble, y: GLdouble) {.importc.}
-  proc glIsVertexArray(`array`: GLuint): GLboolean {.importc.}
-  proc glGetMaterialx(face: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glMultiTexCoord1dARB(target: GLenum, s: GLdouble) {.importc.}
-  proc glColor3usv(v: ptr GLushort) {.importc.}
-  proc glVertexStream3svATI(stream: GLenum, coords: ptr GLshort) {.importc.}
-  proc glRasterPos3s(x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glMultiTexCoord2bOES(texture: GLenum, s: GLbyte, t: GLbyte) {.importc.}
-  proc glGetClipPlanefOES(plane: GLenum, equation: ptr GLfloat) {.importc.}
-  proc glFramebufferTextureEXT(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glVertexAttrib1dNV(index: GLuint, x: GLdouble) {.importc.}
-  proc glSampleCoverageOES(value: GLfixed, invert: GLboolean) {.importc.}
-  proc glCompressedTexSubImage2DARB(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glUniform1iv(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glExtGetProgramsQCOM(programs: ptr GLuint, maxPrograms: GLint, numPrograms: ptr GLint) {.importc.}
-  proc glFogx(pname: GLenum, param: GLfixed) {.importc.}
-  proc glMultiTexCoord3hNV(target: GLenum, s: GLhalfNv, t: GLhalfNv, r: GLhalfNv) {.importc.}
-  proc glClipPlane(plane: GLenum, equation: ptr GLdouble) {.importc.}
-  proc glConvolutionParameterxvOES(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glInvalidateBufferData(buffer: GLuint) {.importc.}
-  proc glCheckNamedFramebufferStatusEXT(framebuffer: GLuint, target: GLenum): GLenum {.importc.}
-  proc glLinkProgram(program: GLuint) {.importc.}
-  proc glCheckFramebufferStatus(target: GLenum): GLenum {.importc.}
-  proc glBlendFunci(buf: GLuint, src: GLenum, dst: GLenum) {.importc.}
-  proc glProgramUniform4uiv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glConvolutionFilter2D(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, image: pointer) {.importc.}
-  proc glVertex4bvOES(coords: ptr GLbyte) {.importc.}
-  proc glCopyTextureSubImage1DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glColor4uiv(v: ptr GLuint) {.importc.}
-  proc glGetBufferParameteri64v(target: GLenum, pname: GLenum, params: ptr GLint64) {.importc.}
-  proc glGetLocalConstantBooleanvEXT(id: GLuint, value: GLenum, data: ptr GLboolean) {.importc.}
-  proc glCoverStrokePathNV(path: GLuint, coverMode: GLenum) {.importc.}
-  proc glScaled(x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glLightfv(light: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexParameterIiv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMakeImageHandleResidentNV(handle: GLuint64, access: GLenum) {.importc.}
-  proc glWindowPos3iARB(x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glListBase(base: GLuint) {.importc.}
-  proc glFlushMappedBufferRangeEXT(target: GLenum, offset: GLintptr, length: GLsizeiptr) {.importc.}
-  proc glNormal3dv(v: ptr GLdouble) {.importc.}
-  proc glProgramUniform4d(program: GLuint, location: GLint, v0: GLdouble, v1: GLdouble, v2: GLdouble, v3: GLdouble) {.importc.}
-  proc glCreateShaderProgramEXT(`type`: GLenum, string: cstring): GLuint {.importc.}
-  proc glGetLightxvOES(light: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glGetObjectPtrLabelKHR(`ptr`: ptr pointer, bufSize: GLsizei, length: ptr GLsizei, label: cstring) {.importc.}
-  proc glTransformPathNV(resultPath: GLuint, srcPath: GLuint, transformType: GLenum, transformValues: ptr GLfloat) {.importc.}
-  proc glMultTransposeMatrixf(m: ptr GLfloat) {.importc.}
-  proc glMapVertexAttrib2dAPPLE(index: GLuint, size: GLuint, u1: GLdouble, u2: GLdouble, ustride: GLint, uorder: GLint, v1: GLdouble, v2: GLdouble, vstride: GLint, vorder: GLint, points: ptr GLdouble) {.importc.}
-  proc glIsSync(sync: GLsync): GLboolean {.importc.}
-  proc glMultMatrixx(m: ptr GLfixed) {.importc.}
-  proc glInterpolatePathsNV(resultPath: GLuint, pathA: GLuint, pathB: GLuint, weight: GLfloat) {.importc.}
-  proc glEnableClientStateIndexedEXT(`array`: GLenum, index: GLuint) {.importc.}
-  proc glProgramEnvParameter4fARB(target: GLenum, index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glVertexAttrib2svARB(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glLighti(light: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glSelectBuffer(size: GLsizei, buffer: ptr GLuint) {.importc.}
-  proc glReplacementCodeusvSUN(code: ptr GLushort) {.importc.}
-  proc glMapVertexAttrib1fAPPLE(index: GLuint, size: GLuint, u1: GLfloat, u2: GLfloat, stride: GLint, order: GLint, points: ptr GLfloat) {.importc.}
-  proc glMaterialx(face: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glDrawTransformFeedback(mode: GLenum, id: GLuint) {.importc.}
-  proc glWindowPos2i(x: GLint, y: GLint) {.importc.}
-  proc glMultiTexEnviEXT(texunit: GLenum, target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glProgramUniform1fv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glDrawBuffersARB(n: GLsizei, bufs: ptr GLenum) {.importc.}
-  proc glGetUniformLocationARB(programObj: GLhandleArb, name: cstring): GLint {.importc.}
-  proc glResumeTransformFeedback() {.importc.}
-  proc glMap1f(target: GLenum, u1: GLfloat, u2: GLfloat, stride: GLint, order: GLint, points: ptr GLfloat) {.importc.}
-  proc glVertex3xOES(x: GLfixed, y: GLfixed) {.importc.}
-  proc glPathCoordsNV(path: GLuint, numCoords: GLsizei, coordType: GLenum, coords: pointer) {.importc.}
-  proc glListParameterfSGIX(list: GLuint, pname: GLenum, param: GLfloat) {.importc.}
-  proc glGetUniformivARB(programObj: GLhandleArb, location: GLint, params: ptr GLint) {.importc.}
-  proc glBinormal3bvEXT(v: ptr GLbyte) {.importc.}
-  proc glVertexAttribP3ui(index: GLuint, `type`: GLenum, normalized: GLboolean, value: GLuint) {.importc.}
-  proc glGetVertexArrayPointeri_vEXT(vaobj: GLuint, index: GLuint, pname: GLenum, param: ptr pointer) {.importc.}
-  proc glProgramParameter4fvNV(target: GLenum, index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glDiscardFramebufferEXT(target: GLenum, numAttachments: GLsizei, attachments: ptr GLenum) {.importc.}
-  proc glGetDebugMessageLogARB(count: GLuint, bufsize: GLsizei, sources: ptr GLenum, types: ptr GLenum, ids: ptr GLuint, severities: ptr GLenum, lengths: ptr GLsizei, messageLog: cstring): GLuint {.importc.}
-  proc glResolveMultisampleFramebufferAPPLE() {.importc.}
-  proc glGetIntegeri_vEXT(target: GLenum, index: GLuint, data: ptr GLint) {.importc.}
-  proc glDepthBoundsdNV(zmin: GLdouble, zmax: GLdouble) {.importc.}
-  proc glEnd() {.importc.}
-  proc glBindBufferBaseEXT(target: GLenum, index: GLuint, buffer: GLuint) {.importc.}
-  proc glVertexAttribDivisor(index: GLuint, divisor: GLuint) {.importc.}
-  proc glFogCoorddEXT(coord: GLdouble) {.importc.}
-  proc glFrontFace(mode: GLenum) {.importc.}
-  proc glVertexAttrib1hNV(index: GLuint, x: GLhalfNv) {.importc.}
-  proc glNamedProgramLocalParametersI4uivEXT(program: GLuint, target: GLenum, index: GLuint, count: GLsizei, params: ptr GLuint) {.importc.}
-  proc glTexCoord1dv(v: ptr GLdouble) {.importc.}
-  proc glBindVideoCaptureStreamTextureNV(video_capture_slot: GLuint, stream: GLuint, frame_region: GLenum, target: GLenum, texture: GLuint) {.importc.}
-  proc glWindowPos2iARB(x: GLint, y: GLint) {.importc.}
-  proc glVertexAttribFormatNV(index: GLuint, size: GLint, `type`: GLenum, normalized: GLboolean, stride: GLsizei) {.importc.}
-  proc glUniform1uivEXT(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glGetVideoivNV(video_slot: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttrib3fvARB(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glVertexArraySecondaryColorOffsetEXT(vaobj: GLuint, buffer: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glSecondaryColor3bv(v: ptr GLbyte) {.importc.}
-  proc glDispatchComputeGroupSizeARB(num_groups_x: GLuint, num_groups_y: GLuint, num_groups_z: GLuint, group_size_x: GLuint, group_size_y: GLuint, group_size_z: GLuint) {.importc.}
-  proc glNamedCopyBufferSubDataEXT(readBuffer: GLuint, writeBuffer: GLuint, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glSampleCoverage(value: GLfloat, invert: GLboolean) {.importc.}
-  proc glGetnMapfvARB(target: GLenum, query: GLenum, bufSize: GLsizei, v: ptr GLfloat) {.importc.}
-  proc glVertexStream2svATI(stream: GLenum, coords: ptr GLshort) {.importc.}
-  proc glProgramParameters4fvNV(target: GLenum, index: GLuint, count: GLsizei, v: ptr GLfloat) {.importc.}
-  proc glVertexAttrib4fARB(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glIndexd(c: GLdouble) {.importc.}
-  proc glGetInteger64v(pname: GLenum, params: ptr GLint64) {.importc.}
-  proc glGetMultiTexImageEXT(texunit: GLenum, target: GLenum, level: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glLightModelx(pname: GLenum, param: GLfixed) {.importc.}
-  proc glMap2f(target: GLenum, u1: GLfloat, u2: GLfloat, ustride: GLint, uorder: GLint, v1: GLfloat, v2: GLfloat, vstride: GLint, vorder: GLint, points: ptr GLfloat) {.importc.}
-  proc glSecondaryColorPointerListIBM(size: GLint, `type`: GLenum, stride: GLint, `pointer`: ptr pointer, ptrstride: GLint) {.importc.}
-  proc glVertexArrayVertexAttribIOffsetEXT(vaobj: GLuint, buffer: GLuint, index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glProgramUniformHandleui64vARB(program: GLuint, location: GLint, count: GLsizei, values: ptr GLuint64) {.importc.}
-  proc glActiveProgramEXT(program: GLuint) {.importc.}
-  proc glProgramUniformMatrix4x3fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glCompressedTexSubImage3DARB(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glBindProgramPipelineEXT(pipeline: GLuint) {.importc.}
-  proc glDetailTexFuncSGIS(target: GLenum, n: GLsizei, points: ptr GLfloat) {.importc.}
-  proc glSecondaryColor3ubEXT(red: GLubyte, green: GLubyte, blue: GLubyte) {.importc.}
-  proc glDrawArraysInstanced(mode: GLenum, first: GLint, count: GLsizei, instancecount: GLsizei) {.importc.}
-  proc glWindowPos3fARB(x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glNamedProgramLocalParameter4fEXT(program: GLuint, target: GLenum, index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glTextureParameterfvEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glProgramUniformHandleui64ARB(program: GLuint, location: GLint, value: GLuint64) {.importc.}
-  proc glHistogramEXT(target: GLenum, width: GLsizei, internalformat: GLenum, sink: GLboolean) {.importc.}
-  proc glResumeTransformFeedbackNV() {.importc.}
-  proc glGetMaterialxv(face: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glMultiTexCoord1sv(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glReadInstrumentsSGIX(marker: GLint) {.importc.}
-  proc glTexCoord4hNV(s: GLhalfNv, t: GLhalfNv, r: GLhalfNv, q: GLhalfNv) {.importc.}
-  proc glVertexAttribL4i64vNV(index: GLuint, v: ptr GLint64Ext) {.importc.}
-  proc glEnableVariantClientStateEXT(id: GLuint) {.importc.}
-  proc glSyncTextureINTEL(texture: GLuint) {.importc.}
-  proc glGetObjectPtrLabel(`ptr`: ptr pointer, bufSize: GLsizei, length: ptr GLsizei, label: cstring) {.importc.}
-  proc glCopyTexSubImage1D(target: GLenum, level: GLint, xoffset: GLint, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glOrthofOES(l: GLfloat, r: GLfloat, b: GLfloat, t: GLfloat, n: GLfloat, f: GLfloat) {.importc.}
-  proc glWindowPos3sARB(x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glIsBufferARB(buffer: GLuint): GLboolean {.importc.}
-  proc glColor3sv(v: ptr GLshort) {.importc.}
-  proc glEvalMesh1(mode: GLenum, i1: GLint, i2: GLint) {.importc.}
-  proc glMultiDrawArrays(mode: GLenum, first: ptr GLint, count: ptr GLsizei, drawcount: GLsizei) {.importc.}
-  proc glGetMultiTexEnvfvEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glWindowPos3fMESA(x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glExtGetFramebuffersQCOM(framebuffers: ptr GLuint, maxFramebuffers: GLint, numFramebuffers: ptr GLint) {.importc.}
-  proc glTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glVertexAttrib4uiv(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glProgramUniformui64NV(program: GLuint, location: GLint, value: GLuint64Ext) {.importc.}
-  proc glMultiTexCoord2ivARB(target: GLenum, v: ptr GLint) {.importc.}
-  proc glProgramUniform4i64NV(program: GLuint, location: GLint, x: GLint64Ext, y: GLint64Ext, z: GLint64Ext, w: GLint64Ext) {.importc.}
-  proc glWindowPos2svMESA(v: ptr GLshort) {.importc.}
-  proc glVertexAttrib3dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glColor4i(red: GLint, green: GLint, blue: GLint, alpha: GLint) {.importc.}
-  proc glClampColor(target: GLenum, clamp: GLenum) {.importc.}
-  proc glVertexP2ui(`type`: GLenum, value: GLuint) {.importc.}
-  proc glGenQueries(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glBindBufferOffsetNV(target: GLenum, index: GLuint, buffer: GLuint, offset: GLintptr) {.importc.}
-  proc glGetFragDataLocation(program: GLuint, name: cstring): GLint {.importc.}
-  proc glVertexAttribs2svNV(index: GLuint, count: GLsizei, v: ptr GLshort) {.importc.}
-  proc glGetPathLengthNV(path: GLuint, startSegment: GLsizei, numSegments: GLsizei): GLfloat {.importc.}
-  proc glVertexAttrib3dARB(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glMultiTexGenfvEXT(texunit: GLenum, coord: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glFlushPixelDataRangeNV(target: GLenum) {.importc.}
-  proc glReplacementCodeuiNormal3fVertex3fSUN(rc: GLuint, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glPathParameteriNV(path: GLuint, pname: GLenum, value: GLint) {.importc.}
-  proc glVertexAttribI2iEXT(index: GLuint, x: GLint, y: GLint) {.importc.}
-  proc glPixelStorei(pname: GLenum, param: GLint) {.importc.}
-  proc glGetNamedFramebufferParameterivEXT(framebuffer: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetTexEnvxv(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glPathStringNV(path: GLuint, format: GLenum, length: GLsizei, pathString: pointer) {.importc.}
-  proc glDepthMask(flag: GLboolean) {.importc.}
-  proc glCopyTexImage1D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, border: GLint) {.importc.}
-  proc glDepthRangexOES(n: GLfixed, f: GLfixed) {.importc.}
-  proc glUniform2i64vNV(location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glSetFragmentShaderConstantATI(dst: GLuint, value: ptr GLfloat) {.importc.}
-  proc glAttachShader(program: GLuint, shader: GLuint) {.importc.}
-  proc glGetFramebufferParameterivEXT(framebuffer: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glPointParameteriNV(pname: GLenum, param: GLint) {.importc.}
-  proc glWindowPos2dMESA(x: GLdouble, y: GLdouble) {.importc.}
-  proc glGetTextureParameterfvEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexBumpParameterfvATI(pname: GLenum, param: ptr GLfloat) {.importc.}
-  proc glCompressedTexImage1DARB(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, border: GLint, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glGetTexGendv(coord: GLenum, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glGetFragmentMaterialfvSGIX(face: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glBeginConditionalRenderNVX(id: GLuint) {.importc.}
-  proc glLightModelxOES(pname: GLenum, param: GLfixed) {.importc.}
-  proc glTexCoord2xOES(s: GLfixed, t: GLfixed) {.importc.}
-  proc glProgramUniformMatrix2x4fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glRasterPos2xvOES(coords: ptr GLfixed) {.importc.}
-  proc glGetMapiv(target: GLenum, query: GLenum, v: ptr GLint) {.importc.}
-  proc glGetImageHandleARB(texture: GLuint, level: GLint, layered: GLboolean, layer: GLint, format: GLenum): GLuint64 {.importc.}
-  proc glVDPAURegisterVideoSurfaceNV(vdpSurface: pointer, target: GLenum, numTextureNames: GLsizei, textureNames: ptr GLuint): GLvdpauSurfaceNv {.importc.}
-  proc glVertexAttribL2dEXT(index: GLuint, x: GLdouble, y: GLdouble) {.importc.}
-  proc glVertexAttrib1dvNV(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glPollAsyncSGIX(markerp: ptr GLuint): GLint {.importc.}
-  proc glCullParameterfvEXT(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glMakeNamedBufferResidentNV(buffer: GLuint, access: GLenum) {.importc.}
-  proc glPointParameterfSGIS(pname: GLenum, param: GLfloat) {.importc.}
-  proc glGenLists(range: GLsizei): GLuint {.importc.}
-  proc glGetTexBumpParameterfvATI(pname: GLenum, param: ptr GLfloat) {.importc.}
-  proc glCompressedMultiTexSubImage2DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glFinishFenceNV(fence: GLuint) {.importc.}
-  proc glPointSize(size: GLfloat) {.importc.}
-  proc glCompressedTextureImage2DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glGetUniformui64vNV(program: GLuint, location: GLint, params: ptr GLuint64Ext) {.importc.}
-  proc glGetMapControlPointsNV(target: GLenum, index: GLuint, `type`: GLenum, ustride: GLsizei, vstride: GLsizei, packed: GLboolean, points: pointer) {.importc.}
-  proc glGetPathColorGenfvNV(color: GLenum, pname: GLenum, value: ptr GLfloat) {.importc.}
-  proc glTexCoord2f(s: GLfloat, t: GLfloat) {.importc.}
-  proc glSampleMaski(index: GLuint, mask: GLbitfield) {.importc.}
-  proc glReadBufferIndexedEXT(src: GLenum, index: GLint) {.importc.}
-  proc glCoverFillPathNV(path: GLuint, coverMode: GLenum) {.importc.}
-  proc glColorTableParameterfvSGI(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glDeleteVertexArraysAPPLE(n: GLsizei, arrays: ptr GLuint) {.importc.}
-  proc glGetVertexAttribIiv(index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glWeightbvARB(size: GLint, weights: ptr GLbyte) {.importc.}
-  proc glGetNamedBufferPointervEXT(buffer: GLuint, pname: GLenum, params: ptr pointer) {.importc.}
-  proc glTexCoordPointer(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glColor4fv(v: ptr GLfloat) {.importc.}
-  proc glGetnUniformfvARB(program: GLuint, location: GLint, bufSize: GLsizei, params: ptr GLfloat) {.importc.}
-  proc glMaterialxOES(face: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glGetFixedv(pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glMaterialf(face: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glVideoCaptureStreamParameterfvNV(video_capture_slot: GLuint, stream: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetDebugMessageLogAMD(count: GLuint, bufsize: GLsizei, categories: ptr GLenum, severities: ptr GLuint, ids: ptr GLuint, lengths: ptr GLsizei, message: cstring): GLuint {.importc.}
-  proc glProgramUniform2uiv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glMatrixMultTransposedEXT(mode: GLenum, m: ptr GLdouble) {.importc.}
-  proc glIsPointInStrokePathNV(path: GLuint, x: GLfloat, y: GLfloat): GLboolean {.importc.}
-  proc glDisable(cap: GLenum) {.importc.}
-  proc glCompileShader(shader: GLuint) {.importc.}
-  proc glLoadTransposeMatrixd(m: ptr GLdouble) {.importc.}
-  proc glGetMultiTexParameterIuivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glGetHistogram(target: GLenum, reset: GLboolean, format: GLenum, `type`: GLenum, values: pointer) {.importc.}
-  proc glMultiTexCoord3fvARB(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glColor4xvOES(components: ptr GLfixed) {.importc.}
-  proc glIsBuffer(buffer: GLuint): GLboolean {.importc.}
-  proc glVertex2dv(v: ptr GLdouble) {.importc.}
-  proc glNamedProgramLocalParameterI4uivEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLuint) {.importc.}
-  proc glPixelTexGenParameteriSGIS(pname: GLenum, param: GLint) {.importc.}
-  proc glBindVertexBuffers(first: GLuint, count: GLsizei, buffers: ptr GLuint, offsets: ptr GLintptr, strides: ptr GLsizei) {.importc.}
-  proc glUniform1ui64vNV(location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glColor4ub(red: GLubyte, green: GLubyte, blue: GLubyte, alpha: GLubyte) {.importc.}
-  proc glConvolutionParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glReplacementCodeuiColor4fNormal3fVertex3fSUN(rc: GLuint, r: GLfloat, g: GLfloat, b: GLfloat, a: GLfloat, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glVertexAttribI2ui(index: GLuint, x: GLuint, y: GLuint) {.importc.}
-  proc glDeleteNamesAMD(identifier: GLenum, num: GLuint, names: ptr GLuint) {.importc.}
-  proc glPixelTransferxOES(pname: GLenum, param: GLfixed) {.importc.}
-  proc glVertexAttrib4ivARB(index: GLuint, v: ptr GLint) {.importc.}
-  proc glLightModeli(pname: GLenum, param: GLint) {.importc.}
-  proc glGetHistogramEXT(target: GLenum, reset: GLboolean, format: GLenum, `type`: GLenum, values: pointer) {.importc.}
-  proc glWindowPos3svMESA(v: ptr GLshort) {.importc.}
-  proc glRasterPos3iv(v: ptr GLint) {.importc.}
-  proc glCopyTextureSubImage3DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glTextureStorage3DMultisampleEXT(texture: GLuint, target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, fixedsamplelocations: GLboolean) {.importc.}
-  proc glIsNameAMD(identifier: GLenum, name: GLuint): GLboolean {.importc.}
-  proc glProgramUniformMatrix3fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glGetProgramParameterfvNV(target: GLenum, index: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexStorage3D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) {.importc.}
-  proc glMultiTexCoord2xOES(texture: GLenum, s: GLfixed, t: GLfixed) {.importc.}
-  proc glWindowPos2fARB(x: GLfloat, y: GLfloat) {.importc.}
-  proc glGetProgramResourceIndex(program: GLuint, programInterface: GLenum, name: cstring): GLuint {.importc.}
-  proc glProgramUniform2uivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glMakeImageHandleNonResidentNV(handle: GLuint64) {.importc.}
-  proc glNamedProgramLocalParameter4fvEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLfloat) {.importc.}
-  proc glInvalidateFramebuffer(target: GLenum, numAttachments: GLsizei, attachments: ptr GLenum) {.importc.}
-  proc glTexStorage3DMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, fixedsamplelocations: GLboolean) {.importc.}
-  proc glMapVertexAttrib2fAPPLE(index: GLuint, size: GLuint, u1: GLfloat, u2: GLfloat, ustride: GLint, uorder: GLint, v1: GLfloat, v2: GLfloat, vstride: GLint, vorder: GLint, points: ptr GLfloat) {.importc.}
-  proc glCombinerParameterfNV(pname: GLenum, param: GLfloat) {.importc.}
-  proc glCopyMultiTexImage2DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) {.importc.}
-  proc glBindVertexShaderEXT(id: GLuint) {.importc.}
-  proc glPathGlyphsNV(firstPathName: GLuint, fontTarget: GLenum, fontName: pointer, fontStyle: GLbitfield, numGlyphs: GLsizei, `type`: GLenum, charcodes: pointer, handleMissingGlyphs: GLenum, pathParameterTemplate: GLuint, emScale: GLfloat) {.importc.}
-  proc glProgramLocalParametersI4uivNV(target: GLenum, index: GLuint, count: GLsizei, params: ptr GLuint) {.importc.}
-  proc glMultiTexCoord3hvNV(target: GLenum, v: ptr GLhalfNv) {.importc.}
-  proc glMultiTexCoordP2uiv(texture: GLenum, `type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glDisableVariantClientStateEXT(id: GLuint) {.importc.}
-  proc glGetTexLevelParameterxvOES(target: GLenum, level: GLint, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glRasterPos2sv(v: ptr GLshort) {.importc.}
-  proc glWeightPathsNV(resultPath: GLuint, numPaths: GLsizei, paths: ptr GLuint, weights: ptr GLfloat) {.importc.}
-  proc glDrawBuffersNV(n: GLsizei, bufs: ptr GLenum) {.importc.}
-  proc glBindBufferARB(target: GLenum, buffer: GLuint) {.importc.}
-  proc glVariantbvEXT(id: GLuint, `addr`: ptr GLbyte) {.importc.}
-  proc glColorP3uiv(`type`: GLenum, color: ptr GLuint) {.importc.}
-  proc glBlendEquationEXT(mode: GLenum) {.importc.}
-  proc glProgramLocalParameterI4uivNV(target: GLenum, index: GLuint, params: ptr GLuint) {.importc.}
-  proc glRenderMode(mode: GLenum): GLint {.importc.}
-  proc glVertexStream4fATI(stream: GLenum, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glGetObjectLabelEXT(`type`: GLenum, `object`: GLuint, bufSize: GLsizei, length: ptr GLsizei, label: cstring) {.importc.}
-  proc glNamedFramebufferTexture3DEXT(framebuffer: GLuint, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint, zoffset: GLint) {.importc.}
-  proc glLoadMatrixf(m: ptr GLfloat) {.importc.}
-  proc glGetQueryObjectuivEXT(id: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glBindVideoCaptureStreamBufferNV(video_capture_slot: GLuint, stream: GLuint, frame_region: GLenum, offset: GLintPtrArb) {.importc.}
-  proc glMatrixOrthoEXT(mode: GLenum, left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) {.importc.}
-  proc glBlendFunc(sfactor: GLenum, dfactor: GLenum) {.importc.}
-  proc glTexGenxvOES(coord: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glMatrixMode(mode: GLenum) {.importc.}
-  proc glColorTableParameterivSGI(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetProgramInfoLog(program: GLuint, bufSize: GLsizei, length: ptr GLsizei, infoLog: cstring) {.importc.}
-  proc glGetSeparableFilter(target: GLenum, format: GLenum, `type`: GLenum, row: pointer, column: pointer, span: pointer) {.importc.}
-  proc glFogfv(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glDrawTexfvOES(coords: ptr GLfloat) {.importc.}
-  proc glClipPlanexIMG(p: GLenum, eqn: ptr GLfixed) {.importc.}
-  proc glResetHistogramEXT(target: GLenum) {.importc.}
-  proc glMemoryBarrier(barriers: GLbitfield) {.importc.}
-  proc glGetPixelMapusv(map: GLenum, values: ptr GLushort) {.importc.}
-  proc glEvalCoord2f(u: GLfloat, v: GLfloat) {.importc.}
-  proc glUniform4uiv(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glIsProgramARB(program: GLuint): GLboolean {.importc.}
-  proc glPointParameterfv(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexBuffer(target: GLenum, internalformat: GLenum, buffer: GLuint) {.importc.}
-  proc glVertexAttrib1s(index: GLuint, x: GLshort) {.importc.}
-  proc glRenderbufferStorageMultisampleEXT(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glMapNamedBufferEXT(buffer: GLuint, access: GLenum): pointer {.importc.}
-  proc glDebugMessageCallbackAMD(callback: GLdebugProcAmd, userParam: ptr pointer) {.importc.}
-  proc glGetTexEnvfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexAttribI3uivEXT(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glMultiTexEnvfEXT(texunit: GLenum, target: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glGetUniformiv(program: GLuint, location: GLint, params: ptr GLint) {.importc.}
-  proc glProgramLocalParameters4fvEXT(target: GLenum, index: GLuint, count: GLsizei, params: ptr GLfloat) {.importc.}
-  proc glStencilStrokePathInstancedNV(numPaths: GLsizei, pathNameType: GLenum, paths: pointer, pathBase: GLuint, reference: GLint, mask: GLuint, transformType: GLenum, transformValues: ptr GLfloat) {.importc.}
-  proc glBeginConditionalRender(id: GLuint, mode: GLenum) {.importc.}
-  proc glVertexAttribI3uiEXT(index: GLuint, x: GLuint, y: GLuint, z: GLuint) {.importc.}
-  proc glVDPAUMapSurfacesNV(numSurfaces: GLsizei, surfaces: ptr GLvdpauSurfaceNv) {.importc.}
-  proc glGetProgramResourceName(program: GLuint, programInterface: GLenum, index: GLuint, bufSize: GLsizei, length: ptr GLsizei, name: cstring) {.importc.}
-  proc glMultiTexCoord4f(target: GLenum, s: GLfloat, t: GLfloat, r: GLfloat, q: GLfloat) {.importc.}
-  proc glVertexAttrib2hNV(index: GLuint, x: GLhalfNv, y: GLhalfNv) {.importc.}
-  proc glDrawArraysInstancedNV(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei) {.importc.}
-  proc glClearAccum(red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) {.importc.}
-  proc glVertexAttribI4usv(index: GLuint, v: ptr GLushort) {.importc.}
-  proc glGetProgramNamedParameterfvNV(id: GLuint, len: GLsizei, name: ptr GLubyte, params: ptr GLfloat) {.importc.}
-  proc glTextureLightEXT(pname: GLenum) {.importc.}
-  proc glPathSubCoordsNV(path: GLuint, coordStart: GLsizei, numCoords: GLsizei, coordType: GLenum, coords: pointer) {.importc.}
-  proc glBindImageTexture(unit: GLuint, texture: GLuint, level: GLint, layered: GLboolean, layer: GLint, access: GLenum, format: GLenum) {.importc.}
-  proc glGenVertexArraysAPPLE(n: GLsizei, arrays: ptr GLuint) {.importc.}
-  proc glFogCoordf(coord: GLfloat) {.importc.}
-  proc glFrameTerminatorGREMEDY() {.importc.}
-  proc glValidateProgramPipelineEXT(pipeline: GLuint) {.importc.}
-  proc glScalexOES(x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glReplacementCodeuiColor3fVertex3fvSUN(rc: ptr GLuint, c: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glProgramNamedParameter4dNV(id: GLuint, len: GLsizei, name: ptr GLubyte, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glMultiDrawElementsIndirectCountARB(mode: GLenum, `type`: GLenum, indirect: GLintptr, drawcount: GLintptr, maxdrawcount: GLsizei, stride: GLsizei) {.importc.}
-  proc glReferencePlaneSGIX(equation: ptr GLdouble) {.importc.}
-  proc glNormalStream3iATI(stream: GLenum, nx: GLint, ny: GLint, nz: GLint) {.importc.}
-  proc glGetColorTableParameterfvEXT(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetAttribLocation(program: GLuint, name: cstring): GLint {.importc.}
-  proc glMultiTexParameterfEXT(texunit: GLenum, target: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glGenFencesNV(n: GLsizei, fences: ptr GLuint) {.importc.}
-  proc glUniform4dv(location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glGetTexLevelParameterfv(target: GLenum, level: GLint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glProgramUniform1ivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glProgramUniform1dvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glLoadTransposeMatrixdARB(m: ptr GLdouble) {.importc.}
-  proc glVertexAttrib2fvARB(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glMultiTexGendEXT(texunit: GLenum, coord: GLenum, pname: GLenum, param: GLdouble) {.importc.}
-  proc glProgramUniformMatrix4x3dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glUniform4ui(location: GLint, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) {.importc.}
-  proc glTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glVertexAttrib3hNV(index: GLuint, x: GLhalfNv, y: GLhalfNv, z: GLhalfNv) {.importc.}
-  proc glRotatexOES(angle: GLfixed, x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glGenTextures(n: GLsizei, textures: ptr GLuint) {.importc.}
-  proc glCheckFramebufferStatusOES(target: GLenum): GLenum {.importc.}
-  proc glGetVideoCaptureStreamdvNV(video_capture_slot: GLuint, stream: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glCompressedTextureSubImage1DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glCurrentPaletteMatrixOES(matrixpaletteindex: GLuint) {.importc.}
-  proc glCompressedMultiTexSubImage1DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glNormal3d(nx: GLdouble, ny: GLdouble, nz: GLdouble) {.importc.}
-  proc glMultiTexCoord1fv(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glProgramUniform2uiEXT(program: GLuint, location: GLint, v0: GLuint, v1: GLuint) {.importc.}
-  proc glMultiTexCoord3fARB(target: GLenum, s: GLfloat, t: GLfloat, r: GLfloat) {.importc.}
-  proc glRasterPos3xOES(x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glEGLImageTargetRenderbufferStorageOES(target: GLenum, image: GLeglImageOes) {.importc.}
-  proc glGetAttribLocationARB(programObj: GLhandleArb, name: cstring): GLint {.importc.}
-  proc glProgramNamedParameter4dvNV(id: GLuint, len: GLsizei, name: ptr GLubyte, v: ptr GLdouble) {.importc.}
-  proc glProgramLocalParameterI4uiNV(target: GLenum, index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) {.importc.}
-  proc glNamedFramebufferTextureFaceEXT(framebuffer: GLuint, attachment: GLenum, texture: GLuint, level: GLint, face: GLenum) {.importc.}
-  proc glIndexf(c: GLfloat) {.importc.}
-  proc glExtTexObjectStateOverrideiQCOM(target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glCoverageOperationNV(operation: GLenum) {.importc.}
-  proc glColorP4uiv(`type`: GLenum, color: ptr GLuint) {.importc.}
-  proc glDeleteSync(sync: GLsync) {.importc.}
-  proc glGetHistogramParameterfvEXT(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexCoord4fColor4fNormal3fVertex4fSUN(s: GLfloat, t: GLfloat, p: GLfloat, q: GLfloat, r: GLfloat, g: GLfloat, b: GLfloat, a: GLfloat, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glEndPerfMonitorAMD(monitor: GLuint) {.importc.}
-  proc glGetInternalformati64v(target: GLenum, internalformat: GLenum, pname: GLenum, bufSize: GLsizei, params: ptr GLint64) {.importc.}
-  proc glGenNamesAMD(identifier: GLenum, num: GLuint, names: ptr GLuint) {.importc.}
-  proc glDrawElementsInstancedBaseVertexBaseInstance(mode: GLenum, count: GLsizei, `type`: GLenum, indices: ptr pointer, instancecount: GLsizei, basevertex: GLint, baseinstance: GLuint) {.importc.}
-  proc glMultiTexCoord4i(target: GLenum, s: GLint, t: GLint, r: GLint, q: GLint) {.importc.}
-  proc glVertexAttribL1dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glGetProgramNamedParameterdvNV(id: GLuint, len: GLsizei, name: ptr GLubyte, params: ptr GLdouble) {.importc.}
-  proc glSetLocalConstantEXT(id: GLuint, `type`: GLenum, `addr`: pointer) {.importc.}
-  proc glProgramBinary(program: GLuint, binaryFormat: GLenum, binary: pointer, length: GLsizei) {.importc.}
-  proc glVideoCaptureNV(video_capture_slot: GLuint, sequence_num: ptr GLuint, capture_time: ptr GLuint64Ext): GLenum {.importc.}
-  proc glDebugMessageEnableAMD(category: GLenum, severity: GLenum, count: GLsizei, ids: ptr GLuint, enabled: GLboolean) {.importc.}
-  proc glVertexAttribI1i(index: GLuint, x: GLint) {.importc.}
-  proc glVertexWeighthNV(weight: GLhalfNv) {.importc.}
-  proc glTextureParameterIivEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glClipPlanefIMG(p: GLenum, eqn: ptr GLfloat) {.importc.}
-  proc glGetLightxv(light: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glGetAttachedObjectsARB(containerObj: GLhandleArb, maxCount: GLsizei, count: ptr GLsizei, obj: ptr GLhandleArb) {.importc.}
-  proc glVertexAttrib4fv(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glDisableVertexAttribArrayARB(index: GLuint) {.importc.}
-  proc glWindowPos3fvARB(v: ptr GLfloat) {.importc.}
-  proc glClearDepthdNV(depth: GLdouble) {.importc.}
-  proc glMapParameterivNV(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glEndConditionalRenderNVX() {.importc.}
-  proc glGetFragmentLightivSGIX(light: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramUniformMatrix4fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glVertexStream1iATI(stream: GLenum, x: GLint) {.importc.}
-  proc glColorP3ui(`type`: GLenum, color: GLuint) {.importc.}
-  proc glGetLightxOES(light: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glGetLightiv(light: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexStream3dATI(stream: GLenum, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glProgramUniform1iEXT(program: GLuint, location: GLint, v0: GLint) {.importc.}
-  proc glSecondaryColorFormatNV(size: GLint, `type`: GLenum, stride: GLsizei) {.importc.}
-  proc glDrawElementsBaseVertex(mode: GLenum, count: GLsizei, `type`: GLenum, indices: pointer, basevertex: GLint) {.importc.}
-  proc glGenFencesAPPLE(n: GLsizei, fences: ptr GLuint) {.importc.}
-  proc glBinormal3svEXT(v: ptr GLshort) {.importc.}
-  proc glUseProgramStagesEXT(pipeline: GLuint, stages: GLbitfield, program: GLuint) {.importc.}
-  proc glDebugMessageCallbackKHR(callback: GLdebugProcKhr, userParam: ptr pointer) {.importc.}
-  proc glCopyMultiTexSubImage3DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glColor4hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glFenceSync(condition: GLenum, flags: GLbitfield): GLsync {.importc.}
-  proc glTexCoordPointerListIBM(size: GLint, `type`: GLenum, stride: GLint, `pointer`: ptr pointer, ptrstride: GLint) {.importc.}
-  proc glPopName() {.importc.}
-  proc glColor3fVertex3fvSUN(c: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glGetUniformfv(program: GLuint, location: GLint, params: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord2hNV(target: GLenum, s: GLhalfNv, t: GLhalfNv) {.importc.}
-  proc glLightxv(light: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glVideoCaptureStreamParameterivNV(video_capture_slot: GLuint, stream: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glEvalCoord1xvOES(coords: ptr GLfixed) {.importc.}
-  proc glGetProgramEnvParameterIivNV(target: GLenum, index: GLuint, params: ptr GLint) {.importc.}
-  proc glObjectPurgeableAPPLE(objectType: GLenum, name: GLuint, option: GLenum): GLenum {.importc.}
-  proc glRequestResidentProgramsNV(n: GLsizei, programs: ptr GLuint) {.importc.}
-  proc glIsImageHandleResidentNV(handle: GLuint64): GLboolean {.importc.}
-  proc glColor3hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glMultiTexCoord2dARB(target: GLenum, s: GLdouble, t: GLdouble) {.importc.}
-  proc glDeletePathsNV(path: GLuint, range: GLsizei) {.importc.}
-  proc glVertexAttrib4Nsv(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glTexEnvf(target: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glGlobalAlphaFactoriSUN(factor: GLint) {.importc.}
-  proc glBlendColorEXT(red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) {.importc.}
-  proc glSecondaryColor3usvEXT(v: ptr GLushort) {.importc.}
-  proc glProgramEnvParameterI4uiNV(target: GLenum, index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) {.importc.}
-  proc glTexImage4DSGIS(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, size4d: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glMatrixPushEXT(mode: GLenum) {.importc.}
-  proc glGetPixelTexGenParameterivSGIS(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVariantuivEXT(id: GLuint, `addr`: ptr GLuint) {.importc.}
-  proc glTexParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetSubroutineUniformLocation(program: GLuint, shadertype: GLenum, name: cstring): GLint {.importc.}
-  proc glProgramUniformMatrix3fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glDrawBuffersATI(n: GLsizei, bufs: ptr GLenum) {.importc.}
-  proc glGetVertexAttribivNV(index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMultiTexCoord4bvOES(texture: GLenum, coords: ptr GLbyte) {.importc.}
-  proc glCompressedTexSubImage1DARB(target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glClientActiveTexture(texture: GLenum) {.importc.}
-  proc glVertexAttrib2fARB(index: GLuint, x: GLfloat, y: GLfloat) {.importc.}
-  proc glProgramUniform2fvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetBufferParameterui64vNV(target: GLenum, pname: GLenum, params: ptr GLuint64Ext) {.importc.}
-  proc glVertexStream3dvATI(stream: GLenum, coords: ptr GLdouble) {.importc.}
-  proc glReplacementCodeuiNormal3fVertex3fvSUN(rc: ptr GLuint, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glVertexAttrib4svNV(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glClearBufferSubData(target: GLenum, internalformat: GLenum, offset: GLintptr, size: GLsizeiptr, format: GLenum, `type`: GLenum, data: ptr pointer) {.importc.}
-  proc glVertexStream2sATI(stream: GLenum, x: GLshort, y: GLshort) {.importc.}
-  proc glTextureImage2DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGetListParameterfvSGIX(list: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glUniform3uiv(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glIsTexture(texture: GLuint): GLboolean {.importc.}
-  proc glObjectUnpurgeableAPPLE(objectType: GLenum, name: GLuint, option: GLenum): GLenum {.importc.}
-  proc glGetVertexAttribdv(index: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glGetPointeri_vEXT(pname: GLenum, index: GLuint, params: ptr pointer) {.importc.}
-  proc glSampleCoveragex(value: GLclampx, invert: GLboolean) {.importc.}
-  proc glColor3f(red: GLfloat, green: GLfloat, blue: GLfloat) {.importc.}
-  proc glGetnMapivARB(target: GLenum, query: GLenum, bufSize: GLsizei, v: ptr GLint) {.importc.}
-  proc glMakeTextureHandleResidentARB(handle: GLuint64) {.importc.}
-  proc glSecondaryColorP3ui(`type`: GLenum, color: GLuint) {.importc.}
-  proc glMultiTexCoord4sARB(target: GLenum, s: GLshort, t: GLshort, r: GLshort, q: GLshort) {.importc.}
-  proc glUniform3i64NV(location: GLint, x: GLint64Ext, y: GLint64Ext, z: GLint64Ext) {.importc.}
-  proc glVDPAUGetSurfaceivNV(surface: GLvdpauSurfaceNv, pname: GLenum, bufSize: GLsizei, length: ptr GLsizei, values: ptr GLint) {.importc.}
-  proc glTexBufferEXT(target: GLenum, internalformat: GLenum, buffer: GLuint) {.importc.}
-  proc glVertexAttribI4ubvEXT(index: GLuint, v: ptr GLubyte) {.importc.}
-  proc glDeleteFramebuffersOES(n: GLsizei, framebuffers: ptr GLuint) {.importc.}
-  proc glColor3fVertex3fSUN(r: GLfloat, g: GLfloat, b: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glCombinerInputNV(stage: GLenum, portion: GLenum, variable: GLenum, input: GLenum, mapping: GLenum, componentUsage: GLenum) {.importc.}
-  proc glPolygonOffsetEXT(factor: GLfloat, bias: GLfloat) {.importc.}
-  proc glWindowPos4dMESA(x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glVertex3f(x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glTexCoord3f(s: GLfloat, t: GLfloat, r: GLfloat) {.importc.}
-  proc glMultiTexCoord1fARB(target: GLenum, s: GLfloat) {.importc.}
-  proc glVertexAttrib4f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glGetFragDataLocationEXT(program: GLuint, name: cstring): GLint {.importc.}
-  proc glFlushMappedNamedBufferRangeEXT(buffer: GLuint, offset: GLintptr, length: GLsizeiptr) {.importc.}
-  proc glVertexAttrib1sARB(index: GLuint, x: GLshort) {.importc.}
-  proc glBitmapxOES(width: GLsizei, height: GLsizei, xorig: GLfixed, yorig: GLfixed, xmove: GLfixed, ymove: GLfixed, bitmap: ptr GLubyte) {.importc.}
-  proc glEnableVertexArrayAttribEXT(vaobj: GLuint, index: GLuint) {.importc.}
-  proc glDeleteRenderbuffers(n: GLsizei, renderbuffers: ptr GLuint) {.importc.}
-  proc glFramebufferRenderbuffer(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glInvalidateTexImage(texture: GLuint, level: GLint) {.importc.}
-  proc glProgramUniform2i64NV(program: GLuint, location: GLint, x: GLint64Ext, y: GLint64Ext) {.importc.}
-  proc glTextureImage3DMultisampleNV(texture: GLuint, target: GLenum, samples: GLsizei, internalFormat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, fixedSampleLocations: GLboolean) {.importc.}
-  proc glValidateProgram(program: GLuint) {.importc.}
-  proc glUniform1dv(location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glNormalStream3dvATI(stream: GLenum, coords: ptr GLdouble) {.importc.}
-  proc glMultiDrawElementsIndirect(mode: GLenum, `type`: GLenum, indirect: ptr pointer, drawcount: GLsizei, stride: GLsizei) {.importc.}
-  proc glVertexBlendARB(count: GLint) {.importc.}
-  proc glIsSampler(sampler: GLuint): GLboolean {.importc.}
-  proc glVariantdvEXT(id: GLuint, `addr`: ptr GLdouble) {.importc.}
-  proc glProgramUniformMatrix3x2fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glVertexStream4fvATI(stream: GLenum, coords: ptr GLfloat) {.importc.}
-  proc glOrthoxOES(l: GLfixed, r: GLfixed, b: GLfixed, t: GLfixed, n: GLfixed, f: GLfixed) {.importc.}
-  proc glColorFormatNV(size: GLint, `type`: GLenum, stride: GLsizei) {.importc.}
-  proc glFogCoordPointer(`type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glVertexAttrib3dvARB(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glVertex3bOES(x: GLbyte, y: GLbyte) {.importc.}
-  proc glVertexAttribFormat(attribindex: GLuint, size: GLint, `type`: GLenum, normalized: GLboolean, relativeoffset: GLuint) {.importc.}
-  proc glTexCoord4fVertex4fSUN(s: GLfloat, t: GLfloat, p: GLfloat, q: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glEnableDriverControlQCOM(driverControl: GLuint) {.importc.}
-  proc glPointParameteri(pname: GLenum, param: GLint) {.importc.}
-  proc glVertexAttribI2i(index: GLuint, x: GLint, y: GLint) {.importc.}
-  proc glGetDriverControlStringQCOM(driverControl: GLuint, bufSize: GLsizei, length: ptr GLsizei, driverControlString: cstring) {.importc.}
-  proc glGetTexLevelParameteriv(target: GLenum, level: GLint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetHandleARB(pname: GLenum): GLhandleArb {.importc.}
-  proc glIndexubv(c: ptr GLubyte) {.importc.}
-  proc glBlendFunciARB(buf: GLuint, src: GLenum, dst: GLenum) {.importc.}
-  proc glColor4usv(v: ptr GLushort) {.importc.}
-  proc glBlendEquationSeparateOES(modeRgb: GLenum, modeAlpha: GLenum) {.importc.}
-  proc glVertexAttribI4ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) {.importc.}
-  proc glProgramUniform3f(program: GLuint, location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat) {.importc.}
-  proc glVertexAttribL3i64vNV(index: GLuint, v: ptr GLint64Ext) {.importc.}
-  proc glWeightdvARB(size: GLint, weights: ptr GLdouble) {.importc.}
-  proc glVertexArrayRangeAPPLE(length: GLsizei, `pointer`: pointer) {.importc.}
-  proc glMapGrid2d(un: GLint, u1: GLdouble, u2: GLdouble, vn: GLint, v1: GLdouble, v2: GLdouble) {.importc.}
-  proc glFogiv(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glUniform2f(location: GLint, v0: GLfloat, v1: GLfloat) {.importc.}
-  proc glGetDoublei_v(target: GLenum, index: GLuint, data: ptr GLdouble) {.importc.}
-  proc glGetVertexAttribfv(index: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexAttribI2ivEXT(index: GLuint, v: ptr GLint) {.importc.}
-  proc glIsProgramNV(id: GLuint): GLboolean {.importc.}
-  proc glTexCoord1hNV(s: GLhalfNv) {.importc.}
-  proc glMinSampleShadingARB(value: GLfloat) {.importc.}
-  proc glMultiDrawElements(mode: GLenum, count: ptr GLsizei, `type`: GLenum, indices: ptr pointer, drawcount: GLsizei) {.importc.}
-  proc glGetQueryObjectuiv(id: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glReadBuffer(mode: GLenum) {.importc.}
-  proc glMultiTexCoordP3uiv(texture: GLenum, `type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glUniformMatrix3x2fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glBindRenderbuffer(target: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glBinormal3sEXT(bx: GLshort, by: GLshort, bz: GLshort) {.importc.}
-  proc glUniform4iARB(location: GLint, v0: GLint, v1: GLint, v2: GLint, v3: GLint) {.importc.}
-  proc glGetUniformOffsetEXT(program: GLuint, location: GLint): GLintptr {.importc.}
-  proc glDeleteLists(list: GLuint, range: GLsizei) {.importc.}
-  proc glVertexAttribI1iEXT(index: GLuint, x: GLint) {.importc.}
-  proc glFramebufferTexture1D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glVertexAttribI2uiv(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glBindFragDataLocation(program: GLuint, color: GLuint, name: cstring) {.importc.}
-  proc glClearStencil(s: GLint) {.importc.}
-  proc glVertexAttrib4Nubv(index: GLuint, v: ptr GLubyte) {.importc.}
-  proc glConvolutionFilter2DEXT(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, image: pointer) {.importc.}
-  proc glGenFramebuffersEXT(n: GLsizei, framebuffers: ptr GLuint) {.importc.}
-  proc glFogCoordfvEXT(coord: ptr GLfloat) {.importc.}
-  proc glGetRenderbufferParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttribs1fvNV(index: GLuint, count: GLsizei, v: ptr GLfloat) {.importc.}
-  proc glTexCoord2fColor3fVertex3fSUN(s: GLfloat, t: GLfloat, r: GLfloat, g: GLfloat, b: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glRasterPos3i(x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glMultiTexSubImage2DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glConvolutionParameteriEXT(target: GLenum, pname: GLenum, params: GLint) {.importc.}
-  proc glVertexAttribI4iEXT(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glVertexAttribL2i64vNV(index: GLuint, v: ptr GLint64Ext) {.importc.}
-  proc glBlendColor(red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) {.importc.}
-  proc glGetPathColorGenivNV(color: GLenum, pname: GLenum, value: ptr GLint) {.importc.}
-  proc glCompressedTextureImage1DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, border: GLint, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glDrawElementsInstanced(mode: GLenum, count: GLsizei, `type`: GLenum, indices: pointer, instancecount: GLsizei) {.importc.}
-  proc glFogCoordd(coord: GLdouble) {.importc.}
-  proc glTexParameterxvOES(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glWindowPos3svARB(v: ptr GLshort) {.importc.}
-  proc glGetVertexArrayPointervEXT(vaobj: GLuint, pname: GLenum, param: ptr pointer) {.importc.}
-  proc glDrawTextureNV(texture: GLuint, sampler: GLuint, x0: GLfloat, y0: GLfloat, x1: GLfloat, y1: GLfloat, z: GLfloat, s0: GLfloat, t0: GLfloat, s1: GLfloat, t1: GLfloat) {.importc.}
-  proc glUniformMatrix2dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glTexImage3DOES(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glClampColorARB(target: GLenum, clamp: GLenum) {.importc.}
-  proc glTexParameteri(target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glWindowPos4svMESA(v: ptr GLshort) {.importc.}
-  proc glMultiTexCoordP4ui(texture: GLenum, `type`: GLenum, coords: GLuint) {.importc.}
-  proc glVertexP4uiv(`type`: GLenum, value: ptr GLuint) {.importc.}
-  proc glProgramUniform4iEXT(program: GLuint, location: GLint, v0: GLint, v1: GLint, v2: GLint, v3: GLint) {.importc.}
-  proc glTexCoord3xvOES(coords: ptr GLfixed) {.importc.}
-  proc glCopyTexImage2DEXT(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) {.importc.}
-  proc glGenSamplers(count: GLsizei, samplers: ptr GLuint) {.importc.}
-  proc glRasterPos4iv(v: ptr GLint) {.importc.}
-  proc glWindowPos4sMESA(x: GLshort, y: GLshort, z: GLshort, w: GLshort) {.importc.}
-  proc glProgramUniform2dvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glPrioritizeTexturesEXT(n: GLsizei, textures: ptr GLuint, priorities: ptr GLclampf) {.importc.}
-  proc glRects(x1: GLshort, y1: GLshort, x2: GLshort, y2: GLshort) {.importc.}
-  proc glMultiDrawElementsBaseVertex(mode: GLenum, count: ptr GLsizei, `type`: GLenum, indices: ptr pointer, drawcount: GLsizei, basevertex: ptr GLint) {.importc.}
-  proc glProgramBinaryOES(program: GLuint, binaryFormat: GLenum, binary: pointer, length: GLint) {.importc.}
-  proc glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fvSUN(rc: ptr GLuint, tc: ptr GLfloat, c: ptr GLfloat, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glGetMinmaxParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glColor4fNormal3fVertex3fSUN(r: GLfloat, g: GLfloat, b: GLfloat, a: GLfloat, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glWindowPos2d(x: GLdouble, y: GLdouble) {.importc.}
-  proc glGetPerfMonitorGroupStringAMD(group: GLuint, bufSize: GLsizei, length: ptr GLsizei, groupString: cstring) {.importc.}
-  proc glUniformHandleui64vNV(location: GLint, count: GLsizei, value: ptr GLuint64) {.importc.}
-  proc glBlendEquation(mode: GLenum) {.importc.}
-  proc glMapBufferARB(target: GLenum, access: GLenum): pointer {.importc.}
-  proc glGetMaterialxvOES(face: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glVertexAttribI1ivEXT(index: GLuint, v: ptr GLint) {.importc.}
-  proc glTexCoord4hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glVertexArrayVertexAttribLOffsetEXT(vaobj: GLuint, buffer: GLuint, index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glExtGetShadersQCOM(shaders: ptr GLuint, maxShaders: GLint, numShaders: ptr GLint) {.importc.}
-  proc glWindowPos4ivMESA(v: ptr GLint) {.importc.}
-  proc glVertexAttrib1sNV(index: GLuint, x: GLshort) {.importc.}
-  proc glNormalStream3ivATI(stream: GLenum, coords: ptr GLint) {.importc.}
-  proc glSecondaryColor3fEXT(red: GLfloat, green: GLfloat, blue: GLfloat) {.importc.}
-  proc glVertexArrayFogCoordOffsetEXT(vaobj: GLuint, buffer: GLuint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glGetTextureImageEXT(texture: GLuint, target: GLenum, level: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glVertexAttrib4hNV(index: GLuint, x: GLhalfNv, y: GLhalfNv, z: GLhalfNv, w: GLhalfNv) {.importc.}
-  proc glReplacementCodeusSUN(code: GLushort) {.importc.}
-  proc glPixelTexGenSGIX(mode: GLenum) {.importc.}
-  proc glMultiDrawRangeElementArrayAPPLE(mode: GLenum, start: GLuint, `end`: GLuint, first: ptr GLint, count: ptr GLsizei, primcount: GLsizei) {.importc.}
-  proc glDrawElements(mode: GLenum, count: GLsizei, `type`: GLenum, indices: pointer) {.importc.}
-  proc glTexCoord1hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glGetPixelMapuiv(map: GLenum, values: ptr GLuint) {.importc.}
-  proc glRasterPos4d(x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glTexImage1D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glConvolutionParameterxOES(target: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glSecondaryColor3dEXT(red: GLdouble, green: GLdouble, blue: GLdouble) {.importc.}
-  proc glGetCombinerOutputParameterivNV(stage: GLenum, portion: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glQueryCounter(id: GLuint, target: GLenum) {.importc.}
-  proc glGetUniformi64vNV(program: GLuint, location: GLint, params: ptr GLint64Ext) {.importc.}
-  proc glTexCoord2fv(v: ptr GLfloat) {.importc.}
-  proc glWindowPos3d(x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glBlendFuncSeparateINGR(sfactorRgb: GLenum, dfactorRgb: GLenum, sfactorAlpha: GLenum, dfactorAlpha: GLenum) {.importc.}
-  proc glTextureNormalEXT(mode: GLenum) {.importc.}
-  proc glVertexStream2fATI(stream: GLenum, x: GLfloat, y: GLfloat) {.importc.}
-  proc glViewportIndexedf(index: GLuint, x: GLfloat, y: GLfloat, w: GLfloat, h: GLfloat) {.importc.}
-  proc glMultiTexCoord4ivARB(target: GLenum, v: ptr GLint) {.importc.}
-  proc glBindBufferOffsetEXT(target: GLenum, index: GLuint, buffer: GLuint, offset: GLintptr) {.importc.}
-  proc glTexCoord3sv(v: ptr GLshort) {.importc.}
-  proc glVertexArrayVertexAttribBindingEXT(vaobj: GLuint, attribindex: GLuint, bindingindex: GLuint) {.importc.}
-  proc glVertexAttrib2f(index: GLuint, x: GLfloat, y: GLfloat) {.importc.}
-  proc glMultiTexGenivEXT(texunit: GLenum, coord: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glUniformui64vNV(location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glGetInfoLogARB(obj: GLhandleArb, maxLength: GLsizei, length: ptr GLsizei, infoLog: cstring) {.importc.}
-  proc glGetNamedProgramLocalParameterIivEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLint) {.importc.}
-  proc glVertexAttrib4s(index: GLuint, x: GLshort, y: GLshort, z: GLshort, w: GLshort) {.importc.}
-  proc glUniformMatrix4x2dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glVertexAttribs3dvNV(index: GLuint, count: GLsizei, v: ptr GLdouble) {.importc.}
-  proc glSecondaryColor3dvEXT(v: ptr GLdouble) {.importc.}
-  proc glTextureRenderbufferEXT(texture: GLuint, target: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glVertexAttribL2ui64vNV(index: GLuint, v: ptr GLuint64Ext) {.importc.}
-  proc glBlendFuncSeparateOES(srcRgb: GLenum, dstRgb: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) {.importc.}
-  proc glVertexAttribDivisorARB(index: GLuint, divisor: GLuint) {.importc.}
-  proc glWindowPos2sv(v: ptr GLshort) {.importc.}
-  proc glMultiTexCoord3svARB(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glCombinerParameterfvNV(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetImageTransformParameterfvHP(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetArrayObjectivATI(`array`: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetTexParameterIuiv(target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glGetProgramPipelineInfoLog(pipeline: GLuint, bufSize: GLsizei, length: ptr GLsizei, infoLog: cstring) {.importc.}
-  proc glGetOcclusionQueryuivNV(id: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glVertexAttrib4bvARB(index: GLuint, v: ptr GLbyte) {.importc.}
-  proc glListParameterfvSGIX(list: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glDeleteSamplers(count: GLsizei, samplers: ptr GLuint) {.importc.}
-  proc glNormalStream3dATI(stream: GLenum, nx: GLdouble, ny: GLdouble, nz: GLdouble) {.importc.}
-  proc glProgramUniform4i64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glBlendFuncSeparateiARB(buf: GLuint, srcRgb: GLenum, dstRgb: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) {.importc.}
-  proc glEndTransformFeedbackEXT() {.importc.}
-  proc glMultiTexCoord3i(target: GLenum, s: GLint, t: GLint, r: GLint) {.importc.}
-  proc glMakeBufferResidentNV(target: GLenum, access: GLenum) {.importc.}
-  proc glTangent3dvEXT(v: ptr GLdouble) {.importc.}
-  proc glMatrixPopEXT(mode: GLenum) {.importc.}
-  proc glVertexAttrib4NivARB(index: GLuint, v: ptr GLint) {.importc.}
-  proc glProgramUniform2ui64NV(program: GLuint, location: GLint, x: GLuint64Ext, y: GLuint64Ext) {.importc.}
-  proc glWeightPointerARB(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glCullParameterdvEXT(pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glFramebufferTexture2D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glGenVertexArrays(n: GLsizei, arrays: ptr GLuint) {.importc.}
-  proc glUniformHandleui64NV(location: GLint, value: GLuint64) {.importc.}
-  proc glIndexPointer(`type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glGetProgramSubroutineParameteruivNV(target: GLenum, index: GLuint, param: ptr GLuint) {.importc.}
-  proc glVertexAttrib1svARB(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glDetachObjectARB(containerObj: GLhandleArb, attachedObj: GLhandleArb) {.importc.}
-  proc glCompressedTexImage3D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glBlendFuncSeparate(sfactorRgb: GLenum, dfactorRgb: GLenum, sfactorAlpha: GLenum, dfactorAlpha: GLenum) {.importc.}
-  proc glExecuteProgramNV(target: GLenum, id: GLuint, params: ptr GLfloat) {.importc.}
-  proc glAttachObjectARB(containerObj: GLhandleArb, obj: GLhandleArb) {.importc.}
-  proc glCompressedTexSubImage1D(target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glProgramUniform4iv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glVertexAttrib3sv(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glTexCoord3bvOES(coords: ptr GLbyte) {.importc.}
-  proc glGenTexturesEXT(n: GLsizei, textures: ptr GLuint) {.importc.}
-  proc glColor4f(red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) {.importc.}
-  proc glGetFramebufferAttachmentParameterivOES(target: GLenum, attachment: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glClearColor(red: GLfloat, green: GLfloat, blue: GLfloat, alpha: GLfloat) {.importc.}
-  proc glNamedProgramLocalParametersI4ivEXT(program: GLuint, target: GLenum, index: GLuint, count: GLsizei, params: ptr GLint) {.importc.}
-  proc glMakeImageHandleNonResidentARB(handle: GLuint64) {.importc.}
-  proc glGenRenderbuffers(n: GLsizei, renderbuffers: ptr GLuint) {.importc.}
-  proc glVertexAttribL1ui64vARB(index: GLuint, v: ptr GLuint64Ext) {.importc.}
-  proc glBindFramebufferEXT(target: GLenum, framebuffer: GLuint) {.importc.}
-  proc glProgramUniform2dEXT(program: GLuint, location: GLint, x: GLdouble, y: GLdouble) {.importc.}
-  proc glCompressedMultiTexImage2DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glDeleteSyncAPPLE(sync: GLsync) {.importc.}
-  proc glDebugMessageInsertAMD(category: GLenum, severity: GLenum, id: GLuint, length: GLsizei, buf: cstring) {.importc.}
-  proc glSecondaryColorPointerEXT(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glTextureImage2DMultisampleNV(texture: GLuint, target: GLenum, samples: GLsizei, internalFormat: GLint, width: GLsizei, height: GLsizei, fixedSampleLocations: GLboolean) {.importc.}
-  proc glBeginFragmentShaderATI() {.importc.}
-  proc glClearDepth(depth: GLdouble) {.importc.}
-  proc glBindTextures(first: GLuint, count: GLsizei, textures: ptr GLuint) {.importc.}
-  proc glEvalCoord1d(u: GLdouble) {.importc.}
-  proc glSecondaryColor3b(red: GLbyte, green: GLbyte, blue: GLbyte) {.importc.}
-  proc glExtGetTexSubImageQCOM(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, `type`: GLenum, texels: pointer) {.importc.}
-  proc glClearColorIiEXT(red: GLint, green: GLint, blue: GLint, alpha: GLint) {.importc.}
-  proc glVertex2xOES(x: GLfixed) {.importc.}
-  proc glVertexAttrib2s(index: GLuint, x: GLshort, y: GLshort) {.importc.}
-  proc glUniformHandleui64vARB(location: GLint, count: GLsizei, value: ptr GLuint64) {.importc.}
-  proc glAreTexturesResidentEXT(n: GLsizei, textures: ptr GLuint, residences: ptr GLboolean): GLboolean {.importc.}
-  proc glDrawElementsInstancedBaseInstance(mode: GLenum, count: GLsizei, `type`: GLenum, indices: ptr pointer, instancecount: GLsizei, baseinstance: GLuint) {.importc.}
-  proc glGetString(name: GLenum): ptr GLubyte {.importc.}
-  proc glDrawTransformFeedbackStream(mode: GLenum, id: GLuint, stream: GLuint) {.importc.}
-  proc glSecondaryColor3uiv(v: ptr GLuint) {.importc.}
-  proc glNamedFramebufferParameteriEXT(framebuffer: GLuint, pname: GLenum, param: GLint) {.importc.}
-  proc glVertexAttrib4hvNV(index: GLuint, v: ptr GLhalfNv) {.importc.}
-  proc glGetnUniformuivARB(program: GLuint, location: GLint, bufSize: GLsizei, params: ptr GLuint) {.importc.}
-  proc glProgramUniform4ui(program: GLuint, location: GLint, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) {.importc.}
-  proc glPointParameterxvOES(pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glIsEnabledi(target: GLenum, index: GLuint): GLboolean {.importc.}
-  proc glColorPointerEXT(size: GLint, `type`: GLenum, stride: GLsizei, count: GLsizei, `pointer`: pointer) {.importc.}
-  proc glFragmentLightModelfvSGIX(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glRasterPos3f(x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glDeleteObjectARB(obj: GLhandleArb) {.importc.}
-  proc glSetFenceNV(fence: GLuint, condition: GLenum) {.importc.}
-  proc glTransformFeedbackAttribsNV(count: GLuint, attribs: ptr GLint, bufferMode: GLenum) {.importc.}
-  proc glProgramUniformMatrix2fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glGetPointerv(pname: GLenum, params: ptr pointer) {.importc.}
-  proc glWindowPos2dvMESA(v: ptr GLdouble) {.importc.}
-  proc glTexImage2DMultisample(target: GLenum, samples: GLsizei, internalformat: GLint, width: GLsizei, height: GLsizei, fixedsamplelocations: GLboolean) {.importc.}
-  proc glGenFragmentShadersATI(range: GLuint): GLuint {.importc.}
-  proc glTexCoord4fv(v: ptr GLfloat) {.importc.}
-  proc glCompressedTexImage1D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, border: GLint, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glGetNamedBufferSubDataEXT(buffer: GLuint, offset: GLintptr, size: GLsizeiptr, data: pointer) {.importc.}
-  proc glFinish() {.importc.}
-  proc glDeleteVertexShaderEXT(id: GLuint) {.importc.}
-  proc glFinishObjectAPPLE(`object`: GLenum, name: GLint) {.importc.}
-  proc glGetActiveAttribARB(programObj: GLhandleArb, index: GLuint, maxLength: GLsizei, length: ptr GLsizei, size: ptr GLint, `type`: ptr GLenum, name: cstring) {.importc.}
-  proc glPointParameterx(pname: GLenum, param: GLfixed) {.importc.}
-  proc glProgramUniformui64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glSecondaryColor3ubv(v: ptr GLubyte) {.importc.}
-  proc glGetProgramLocalParameterIivNV(target: GLenum, index: GLuint, params: ptr GLint) {.importc.}
-  proc glDeleteProgramPipelinesEXT(n: GLsizei, pipelines: ptr GLuint) {.importc.}
-  proc glVertexAttrib4fNV(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glGetColorTableParameterfvSGI(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetFloati_v(target: GLenum, index: GLuint, data: ptr GLfloat) {.importc.}
-  proc glGenBuffers(n: GLsizei, buffers: ptr GLuint) {.importc.}
-  proc glNormal3b(nx: GLbyte, ny: GLbyte, nz: GLbyte) {.importc.}
-  proc glDrawArraysInstancedARB(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei) {.importc.}
-  proc glTexStorage2DMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, fixedsamplelocations: GLboolean) {.importc.}
-  proc glGetVariantIntegervEXT(id: GLuint, value: GLenum, data: ptr GLint) {.importc.}
-  proc glColor3ubv(v: ptr GLubyte) {.importc.}
-  proc glVertexAttribP4uiv(index: GLuint, `type`: GLenum, normalized: GLboolean, value: ptr GLuint) {.importc.}
-  proc glProgramUniform2ivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glVertexStream4dATI(stream: GLenum, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glVertexAttribL2ui64NV(index: GLuint, x: GLuint64Ext, y: GLuint64Ext) {.importc.}
-  proc glSecondaryColor3bEXT(red: GLbyte, green: GLbyte, blue: GLbyte) {.importc.}
-  proc glGetBufferPointervOES(target: GLenum, pname: GLenum, params: ptr pointer) {.importc.}
-  proc glGetMaterialfv(face: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexStream3sATI(stream: GLenum, x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glUniform1i(location: GLint, v0: GLint) {.importc.}
-  proc glVertexAttribL2d(index: GLuint, x: GLdouble, y: GLdouble) {.importc.}
-  proc glTestObjectAPPLE(`object`: GLenum, name: GLuint): GLboolean {.importc.}
-  proc glGetTransformFeedbackVarying(program: GLuint, index: GLuint, bufSize: GLsizei, length: ptr GLsizei, size: ptr GLsizei, `type`: ptr GLenum, name: cstring) {.importc.}
-  proc glFramebufferRenderbufferOES(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glVertexStream3iATI(stream: GLenum, x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glMakeTextureHandleNonResidentNV(handle: GLuint64) {.importc.}
-  proc glVertexAttrib4fvNV(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glArrayElement(i: GLint) {.importc.}
-  proc glClearBufferData(target: GLenum, internalformat: GLenum, format: GLenum, `type`: GLenum, data: ptr pointer) {.importc.}
-  proc glSecondaryColor3usEXT(red: GLushort, green: GLushort, blue: GLushort) {.importc.}
-  proc glRenderbufferStorageMultisample(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glTexCoord2xvOES(coords: ptr GLfixed) {.importc.}
-  proc glWindowPos3f(x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glTangent3svEXT(v: ptr GLshort) {.importc.}
-  proc glPointParameterf(pname: GLenum, param: GLfloat) {.importc.}
-  proc glVertexAttribI4uivEXT(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glColorTableParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMatrixMultdEXT(mode: GLenum, m: ptr GLdouble) {.importc.}
-  proc glUseProgramStages(pipeline: GLuint, stages: GLbitfield, program: GLuint) {.importc.}
-  proc glVertexStream4sATI(stream: GLenum, x: GLshort, y: GLshort, z: GLshort, w: GLshort) {.importc.}
-  proc glDrawElementsInstancedNV(mode: GLenum, count: GLsizei, `type`: GLenum, indices: pointer, primcount: GLsizei) {.importc.}
-  proc glUniform3d(location: GLint, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glDebugMessageControlARB(source: GLenum, `type`: GLenum, severity: GLenum, count: GLsizei, ids: ptr GLuint, enabled: GLboolean) {.importc.}
-  proc glVertexAttribs3svNV(index: GLuint, count: GLsizei, v: ptr GLshort) {.importc.}
-  proc glElementPointerATI(`type`: GLenum, `pointer`: pointer) {.importc.}
-  proc glColor4fNormal3fVertex3fvSUN(c: ptr GLfloat, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glGetPerfMonitorCountersAMD(group: GLuint, numCounters: ptr GLint, maxActiveCounters: ptr GLint, counterSize: GLsizei, counters: ptr GLuint) {.importc.}
-  proc glDispatchCompute(num_groups_x: GLuint, num_groups_y: GLuint, num_groups_z: GLuint) {.importc.}
-  proc glVertexAttribDivisorNV(index: GLuint, divisor: GLuint) {.importc.}
-  proc glProgramUniform3uiEXT(program: GLuint, location: GLint, v0: GLuint, v1: GLuint, v2: GLuint) {.importc.}
-  proc glRenderbufferStorageMultisampleNV(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glBinormalPointerEXT(`type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glRectxvOES(v1: ptr GLfixed, v2: ptr GLfixed) {.importc.}
-  proc glGenVertexArraysOES(n: GLsizei, arrays: ptr GLuint) {.importc.}
-  proc glDebugMessageControlKHR(source: GLenum, `type`: GLenum, severity: GLenum, count: GLsizei, ids: ptr GLuint, enabled: GLboolean) {.importc.}
-  proc glProgramUniform1uiEXT(program: GLuint, location: GLint, v0: GLuint) {.importc.}
-  proc glPixelTransferi(pname: GLenum, param: GLint) {.importc.}
-  proc glIsPointInFillPathNV(path: GLuint, mask: GLuint, x: GLfloat, y: GLfloat): GLboolean {.importc.}
-  proc glVertexBindingDivisor(bindingindex: GLuint, divisor: GLuint) {.importc.}
-  proc glGetVertexAttribLui64vARB(index: GLuint, pname: GLenum, params: ptr GLuint64Ext) {.importc.}
-  proc glProgramUniformMatrix3dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glDrawBuffer(mode: GLenum) {.importc.}
-  proc glMultiTexCoord1sARB(target: GLenum, s: GLshort) {.importc.}
-  proc glSeparableFilter2DEXT(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, row: pointer, column: pointer) {.importc.}
-  proc glTangent3bvEXT(v: ptr GLbyte) {.importc.}
-  proc glTexParameterIuiv(target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glVertexAttribL4i64NV(index: GLuint, x: GLint64Ext, y: GLint64Ext, z: GLint64Ext, w: GLint64Ext) {.importc.}
-  proc glDebugMessageCallbackARB(callback: GLdebugProcArb, userParam: ptr pointer) {.importc.}
-  proc glMultiTexCoordP1uiv(texture: GLenum, `type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glLabelObjectEXT(`type`: GLenum, `object`: GLuint, length: GLsizei, label: cstring) {.importc.}
-  proc glGetnPolygonStippleARB(bufSize: GLsizei, pattern: ptr GLubyte) {.importc.}
-  proc glTexCoord3xOES(s: GLfixed, t: GLfixed, r: GLfixed) {.importc.}
-  proc glCopyPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, `type`: GLenum) {.importc.}
-  proc glGetnUniformfvEXT(program: GLuint, location: GLint, bufSize: GLsizei, params: ptr GLfloat) {.importc.}
-  proc glColorMaski(index: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean) {.importc.}
-  proc glRasterPos2fv(v: ptr GLfloat) {.importc.}
-  proc glBindBuffersBase(target: GLenum, first: GLuint, count: GLsizei, buffers: ptr GLuint) {.importc.}
-  proc glSpriteParameterfvSGIX(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetSyncivAPPLE(sync: GLsync, pname: GLenum, bufSize: GLsizei, length: ptr GLsizei, values: ptr GLint) {.importc.}
-  proc glVertexAttribI3i(index: GLuint, x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glPixelTransformParameteriEXT(target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glMultiDrawArraysEXT(mode: GLenum, first: ptr GLint, count: ptr GLsizei, primcount: GLsizei) {.importc.}
-  proc glGetTextureHandleNV(texture: GLuint): GLuint64 {.importc.}
-  proc glTexCoordP2ui(`type`: GLenum, coords: GLuint) {.importc.}
-  proc glDeleteQueries(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glGetVertexAttribArrayObjectivATI(index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexArrayVertexBindingDivisorEXT(vaobj: GLuint, bindingindex: GLuint, divisor: GLuint) {.importc.}
-  proc glVertex3i(x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glBlendEquationSeparatei(buf: GLuint, modeRgb: GLenum, modeAlpha: GLenum) {.importc.}
-  proc glGetMapAttribParameterivNV(target: GLenum, index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetVideoCaptureivNV(video_capture_slot: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glFragmentMaterialfvSGIX(face: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glEGLImageTargetTexture2DOES(target: GLenum, image: GLeglImageOes) {.importc.}
-  proc glCopyImageSubDataNV(srcName: GLuint, srcTarget: GLenum, srcLevel: GLint, srcX: GLint, srcY: GLint, srcZ: GLint, dstName: GLuint, dstTarget: GLenum, dstLevel: GLint, dstX: GLint, dstY: GLint, dstZ: GLint, width: GLsizei, height: GLsizei, depth: GLsizei) {.importc.}
-  proc glUniform2i(location: GLint, v0: GLint, v1: GLint) {.importc.}
-  proc glVertexAttrib3fvNV(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glNamedBufferStorageEXT(buffer: GLuint, size: GLsizeiptr, data: ptr pointer, flags: GLbitfield) {.importc.}
-  proc glProgramEnvParameterI4uivNV(target: GLenum, index: GLuint, params: ptr GLuint) {.importc.}
-  proc glGetVertexAttribdvARB(index: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glVertexAttribL3ui64vNV(index: GLuint, v: ptr GLuint64Ext) {.importc.}
-  proc glUniform4fvARB(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glWeightsvARB(size: GLint, weights: ptr GLshort) {.importc.}
-  proc glMakeTextureHandleNonResidentARB(handle: GLuint64) {.importc.}
-  proc glEvalCoord1xOES(u: GLfixed) {.importc.}
-  proc glVertexAttrib2sv(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glVertexAttrib4dvNV(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glProgramNamedParameter4fNV(id: GLuint, len: GLsizei, name: ptr GLubyte, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glCompileShaderARB(shaderObj: GLhandleArb) {.importc.}
-  proc glProgramEnvParameter4fvARB(target: GLenum, index: GLuint, params: ptr GLfloat) {.importc.}
-  proc glGetVertexAttribiv(index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glEvalPoint1(i: GLint) {.importc.}
-  proc glEvalMapsNV(target: GLenum, mode: GLenum) {.importc.}
-  proc glGetTexGenxvOES(coord: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glBlendEquationSeparate(modeRgb: GLenum, modeAlpha: GLenum) {.importc.}
-  proc glGetColorTableParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glQueryCounterEXT(id: GLuint, target: GLenum) {.importc.}
-  proc glExtGetProgramBinarySourceQCOM(program: GLuint, shadertype: GLenum, source: cstring, length: ptr GLint) {.importc.}
-  proc glGetConvolutionParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glIsProgramPipeline(pipeline: GLuint): GLboolean {.importc.}
-  proc glVertexWeightfvEXT(weight: ptr GLfloat) {.importc.}
-  proc glDisableDriverControlQCOM(driverControl: GLuint) {.importc.}
-  proc glVertexStream1fvATI(stream: GLenum, coords: ptr GLfloat) {.importc.}
-  proc glMakeTextureHandleResidentNV(handle: GLuint64) {.importc.}
-  proc glSamplerParameteriv(sampler: GLuint, pname: GLenum, param: ptr GLint) {.importc.}
-  proc glTexEnvxOES(target: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glEndOcclusionQueryNV() {.importc.}
-  proc glFlushMappedBufferRangeAPPLE(target: GLenum, offset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glVertex4iv(v: ptr GLint) {.importc.}
-  proc glVertexArrayVertexAttribIFormatEXT(vaobj: GLuint, attribindex: GLuint, size: GLint, `type`: GLenum, relativeoffset: GLuint) {.importc.}
-  proc glDisableIndexedEXT(target: GLenum, index: GLuint) {.importc.}
-  proc glVertexAttribL1dEXT(index: GLuint, x: GLdouble) {.importc.}
-  proc glBeginPerfMonitorAMD(monitor: GLuint) {.importc.}
-  proc glConvolutionFilter1DEXT(target: GLenum, internalformat: GLenum, width: GLsizei, format: GLenum, `type`: GLenum, image: pointer) {.importc.}
-  proc glPrimitiveRestartIndex(index: GLuint) {.importc.}
-  proc glWindowPos2dv(v: ptr GLdouble) {.importc.}
-  proc glBindFramebufferOES(target: GLenum, framebuffer: GLuint) {.importc.}
-  proc glTessellationModeAMD(mode: GLenum) {.importc.}
-  proc glIsVariantEnabledEXT(id: GLuint, cap: GLenum): GLboolean {.importc.}
-  proc glColor3iv(v: ptr GLint) {.importc.}
-  proc glFogCoordFormatNV(`type`: GLenum, stride: GLsizei) {.importc.}
-  proc glClearNamedBufferDataEXT(buffer: GLuint, internalformat: GLenum, format: GLenum, `type`: GLenum, data: ptr pointer) {.importc.}
-  proc glTextureRangeAPPLE(target: GLenum, length: GLsizei, `pointer`: pointer) {.importc.}
-  proc glTexCoord4bvOES(coords: ptr GLbyte) {.importc.}
-  proc glRotated(angle: GLdouble, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glAccum(op: GLenum, value: GLfloat) {.importc.}
-  proc glVertex3d(x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glGetPathMetricRangeNV(metricQueryMask: GLbitfield, firstPathName: GLuint, numPaths: GLsizei, stride: GLsizei, metrics: ptr GLfloat) {.importc.}
-  proc glUniform4d(location: GLint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glTextureSubImage2DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glMultiTexCoord1iv(target: GLenum, v: ptr GLint) {.importc.}
-  proc glFogFuncSGIS(n: GLsizei, points: ptr GLfloat) {.importc.}
-  proc glGetMaterialxOES(face: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glGlobalAlphaFactorbSUN(factor: GLbyte) {.importc.}
-  proc glGetProgramLocalParameterdvARB(target: GLenum, index: GLuint, params: ptr GLdouble) {.importc.}
-  proc glDeleteProgramsARB(n: GLsizei, programs: ptr GLuint) {.importc.}
-  proc glVertexStream1sATI(stream: GLenum, x: GLshort) {.importc.}
-  proc glMatrixTranslatedEXT(mode: GLenum, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glTexSubImage1D(target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGetBufferSubData(target: GLenum, offset: GLintptr, size: GLsizeiptr, data: pointer) {.importc.}
-  proc glUniform4uiEXT(location: GLint, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) {.importc.}
-  proc glGetShaderiv(shader: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetQueryIndexediv(target: GLenum, index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glDebugMessageInsert(source: GLenum, `type`: GLenum, id: GLuint, severity: GLenum, length: GLsizei, buf: cstring) {.importc.}
-  proc glVertexAttribs2dvNV(index: GLuint, count: GLsizei, v: ptr GLdouble) {.importc.}
-  proc glGetFixedvOES(pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glUniform2iv(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glTextureView(texture: GLuint, target: GLenum, origtexture: GLuint, internalformat: GLenum, minlevel: GLuint, numlevels: GLuint, minlayer: GLuint, numlayers: GLuint) {.importc.}
-  proc glMultiTexCoord1xvOES(texture: GLenum, coords: ptr GLfixed) {.importc.}
-  proc glTexBufferRange(target: GLenum, internalformat: GLenum, buffer: GLuint, offset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glMultiTexCoordPointerEXT(texunit: GLenum, size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glBlendColorxOES(red: GLfixed, green: GLfixed, blue: GLfixed, alpha: GLfixed) {.importc.}
-  proc glReadPixels(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glWindowPos3dARB(x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glPixelTexGenParameterivSGIS(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glSecondaryColor3svEXT(v: ptr GLshort) {.importc.}
-  proc glPopGroupMarkerEXT() {.importc.}
-  proc glImportSyncEXT(external_sync_type: GLenum, external_sync: GLintptr, flags: GLbitfield): GLsync {.importc.}
-  proc glVertexAttribLFormatNV(index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei) {.importc.}
-  proc glVertexAttrib2sNV(index: GLuint, x: GLshort, y: GLshort) {.importc.}
-  proc glGetIntegeri_v(target: GLenum, index: GLuint, data: ptr GLint) {.importc.}
-  proc glProgramUniform3uiv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glGetActiveUniformBlockiv(program: GLuint, uniformBlockIndex: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glCreateShaderProgramv(`type`: GLenum, count: GLsizei, strings: cstringArray): GLuint {.importc.}
-  proc glUniform2fARB(location: GLint, v0: GLfloat, v1: GLfloat) {.importc.}
-  proc glVertexStream4ivATI(stream: GLenum, coords: ptr GLint) {.importc.}
-  proc glNormalP3uiv(`type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glVertexAttribLFormat(attribindex: GLuint, size: GLint, `type`: GLenum, relativeoffset: GLuint) {.importc.}
-  proc glTexCoord2bvOES(coords: ptr GLbyte) {.importc.}
-  proc glGetActiveUniformName(program: GLuint, uniformIndex: GLuint, bufSize: GLsizei, length: ptr GLsizei, uniformName: cstring) {.importc.}
-  proc glTexCoord2sv(v: ptr GLshort) {.importc.}
-  proc glVertexAttrib2dNV(index: GLuint, x: GLdouble, y: GLdouble) {.importc.}
-  proc glGetFogFuncSGIS(points: ptr GLfloat) {.importc.}
-  proc glSetFenceAPPLE(fence: GLuint) {.importc.}
-  proc glRasterPos2f(x: GLfloat, y: GLfloat) {.importc.}
-  proc glVertexWeightPointerEXT(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glEndList() {.importc.}
-  proc glVDPAUFiniNV() {.importc.}
-  proc glTbufferMask3DFX(mask: GLuint) {.importc.}
-  proc glVertexP4ui(`type`: GLenum, value: GLuint) {.importc.}
-  proc glTexEnviv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glColor4xOES(red: GLfixed, green: GLfixed, blue: GLfixed, alpha: GLfixed) {.importc.}
-  proc glBlendEquationi(buf: GLuint, mode: GLenum) {.importc.}
-  proc glLoadMatrixxOES(m: ptr GLfixed) {.importc.}
-  proc glFogxOES(pname: GLenum, param: GLfixed) {.importc.}
-  proc glTexCoord4dv(v: ptr GLdouble) {.importc.}
-  proc glFogCoordPointerListIBM(`type`: GLenum, stride: GLint, `pointer`: ptr pointer, ptrstride: GLint) {.importc.}
-  proc glGetPerfMonitorGroupsAMD(numGroups: ptr GLint, groupsSize: GLsizei, groups: ptr GLuint) {.importc.}
-  proc glVertex2hNV(x: GLhalfNv, y: GLhalfNv) {.importc.}
-  proc glDeleteFragmentShaderATI(id: GLuint) {.importc.}
-  proc glGetSamplerParameterIiv(sampler: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glUniform2fvARB(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glFogf(pname: GLenum, param: GLfloat) {.importc.}
-  proc glMultiTexCoord1iARB(target: GLenum, s: GLint) {.importc.}
-  proc glGetActiveUniformARB(programObj: GLhandleArb, index: GLuint, maxLength: GLsizei, length: ptr GLsizei, size: ptr GLint, `type`: ptr GLenum, name: cstring) {.importc.}
-  proc glMapGrid1xOES(n: GLint, u1: GLfixed, u2: GLfixed) {.importc.}
-  proc glIndexsv(c: ptr GLshort) {.importc.}
-  proc glFragmentMaterialfSGIX(face: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glBindTextureEXT(target: GLenum, texture: GLuint) {.importc.}
-  proc glRectiv(v1: ptr GLint, v2: ptr GLint) {.importc.}
-  proc glTangent3dEXT(tx: GLdouble, ty: GLdouble, tz: GLdouble) {.importc.}
-  proc glProgramUniformMatrix3x4fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glNormal3hNV(nx: GLhalfNv, ny: GLhalfNv, nz: GLhalfNv) {.importc.}
-  proc glPushClientAttribDefaultEXT(mask: GLbitfield) {.importc.}
-  proc glUnmapBufferARB(target: GLenum): GLboolean {.importc.}
-  proc glVertexAttribs1dvNV(index: GLuint, count: GLsizei, v: ptr GLdouble) {.importc.}
-  proc glUniformMatrix2x3dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glUniform3f(location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat) {.importc.}
-  proc glTexEnvxv(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glMapBufferOES(target: GLenum, access: GLenum): pointer {.importc.}
-  proc glBufferData(target: GLenum, size: GLsizeiptr, data: pointer, usage: GLenum) {.importc.}
-  proc glDrawElementsInstancedANGLE(mode: GLenum, count: GLsizei, `type`: GLenum, indices: ptr pointer, primcount: GLsizei) {.importc.}
-  proc glGetTextureHandleARB(texture: GLuint): GLuint64 {.importc.}
-  proc glNormal3f(nx: GLfloat, ny: GLfloat, nz: GLfloat) {.importc.}
-  proc glTexCoordP3uiv(`type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glTexParameterx(target: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glMapBufferRange(target: GLenum, offset: GLintptr, length: GLsizeiptr, access: GLbitfield): pointer {.importc.}
-  proc glTexCoord2fVertex3fSUN(s: GLfloat, t: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glVariantArrayObjectATI(id: GLuint, `type`: GLenum, stride: GLsizei, buffer: GLuint, offset: GLuint) {.importc.}
-  proc glGetnHistogramARB(target: GLenum, reset: GLboolean, format: GLenum, `type`: GLenum, bufSize: GLsizei, values: pointer) {.importc.}
-  proc glWindowPos3sv(v: ptr GLshort) {.importc.}
-  proc glGetVariantPointervEXT(id: GLuint, value: GLenum, data: ptr pointer) {.importc.}
-  proc glGetLightfv(light: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetnTexImageARB(target: GLenum, level: GLint, format: GLenum, `type`: GLenum, bufSize: GLsizei, img: pointer) {.importc.}
-  proc glGenRenderbuffersEXT(n: GLsizei, renderbuffers: ptr GLuint) {.importc.}
-  proc glMultiDrawArraysIndirectBindlessNV(mode: GLenum, indirect: pointer, drawCount: GLsizei, stride: GLsizei, vertexBufferCount: GLint) {.importc.}
-  proc glDisableClientStateIndexedEXT(`array`: GLenum, index: GLuint) {.importc.}
-  proc glMapGrid1f(un: GLint, u1: GLfloat, u2: GLfloat) {.importc.}
-  proc glTexStorage2D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glShaderStorageBlockBinding(program: GLuint, storageBlockIndex: GLuint, storageBlockBinding: GLuint) {.importc.}
-  proc glBlendBarrierNV() {.importc.}
-  proc glGetVideoui64vNV(video_slot: GLuint, pname: GLenum, params: ptr GLuint64Ext) {.importc.}
-  proc glUniform3ui64NV(location: GLint, x: GLuint64Ext, y: GLuint64Ext, z: GLuint64Ext) {.importc.}
-  proc glUniform4ivARB(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glGetQueryObjectivARB(id: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glCompressedTexSubImage3DOES(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glEnableIndexedEXT(target: GLenum, index: GLuint) {.importc.}
-  proc glNamedRenderbufferStorageMultisampleCoverageEXT(renderbuffer: GLuint, coverageSamples: GLsizei, colorSamples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glVertexAttribI3iEXT(index: GLuint, x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glUniform4uivEXT(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glGetUniformLocation(program: GLuint, name: cstring): GLint {.importc.}
-  proc glCurrentPaletteMatrixARB(index: GLint) {.importc.}
-  proc glVertexAttribLPointerEXT(index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glFogCoorddvEXT(coord: ptr GLdouble) {.importc.}
-  proc glInitNames() {.importc.}
-  proc glGetPathSpacingNV(pathListMode: GLenum, numPaths: GLsizei, pathNameType: GLenum, paths: pointer, pathBase: GLuint, advanceScale: GLfloat, kerningScale: GLfloat, transformType: GLenum, returnedSpacing: ptr GLfloat) {.importc.}
-  proc glNormal3fVertex3fvSUN(n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glTexCoord2iv(v: ptr GLint) {.importc.}
-  proc glWindowPos3s(x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glProgramUniformMatrix3x4fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glVertexAttribP4ui(index: GLuint, `type`: GLenum, normalized: GLboolean, value: GLuint) {.importc.}
-  proc glVertexAttribs4ubvNV(index: GLuint, count: GLsizei, v: ptr GLubyte) {.importc.}
-  proc glProgramLocalParameterI4iNV(target: GLenum, index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glStencilMaskSeparate(face: GLenum, mask: GLuint) {.importc.}
-  proc glClientWaitSync(sync: GLsync, flags: GLbitfield, timeout: GLuint64): GLenum {.importc.}
-  proc glPolygonOffsetx(factor: GLfixed, units: GLfixed) {.importc.}
-  proc glCreateProgramObjectARB(): GLhandleArb {.importc.}
-  proc glClearColorIuiEXT(red: GLuint, green: GLuint, blue: GLuint, alpha: GLuint) {.importc.}
-  proc glDeleteTransformFeedbacksNV(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glFramebufferDrawBuffersEXT(framebuffer: GLuint, n: GLsizei, bufs: ptr GLenum) {.importc.}
-  proc glAreTexturesResident(n: GLsizei, textures: ptr GLuint, residences: ptr GLboolean): GLboolean {.importc.}
-  proc glNamedBufferDataEXT(buffer: GLuint, size: GLsizeiptr, data: pointer, usage: GLenum) {.importc.}
-  proc glGetInvariantFloatvEXT(id: GLuint, value: GLenum, data: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord4d(target: GLenum, s: GLdouble, t: GLdouble, r: GLdouble, q: GLdouble) {.importc.}
-  proc glGetPixelTransformParameterfvEXT(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetStringi(name: GLenum, index: GLuint): ptr GLubyte {.importc.}
-  proc glMakeBufferNonResidentNV(target: GLenum) {.importc.}
-  proc glVertex4bOES(x: GLbyte, y: GLbyte, z: GLbyte) {.importc.}
-  proc glGetObjectLabel(identifier: GLenum, name: GLuint, bufSize: GLsizei, length: ptr GLsizei, label: cstring) {.importc.}
-  proc glClipPlanexOES(plane: GLenum, equation: ptr GLfixed) {.importc.}
-  proc glElementPointerAPPLE(`type`: GLenum, `pointer`: pointer) {.importc.}
-  proc glIsAsyncMarkerSGIX(marker: GLuint): GLboolean {.importc.}
-  proc glUseShaderProgramEXT(`type`: GLenum, program: GLuint) {.importc.}
-  proc glReplacementCodeuiColor4ubVertex3fSUN(rc: GLuint, r: GLubyte, g: GLubyte, b: GLubyte, a: GLubyte, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glIsTransformFeedback(id: GLuint): GLboolean {.importc.}
-  proc glEdgeFlag(flag: GLboolean) {.importc.}
-  proc glGetTexGeniv(coord: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glBeginQueryEXT(target: GLenum, id: GLuint) {.importc.}
-  proc glUniform1uiEXT(location: GLint, v0: GLuint) {.importc.}
-  proc glProgramUniform3fvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetVideoi64vNV(video_slot: GLuint, pname: GLenum, params: ptr GLint64Ext) {.importc.}
-  proc glProgramUniform3ui(program: GLuint, location: GLint, v0: GLuint, v1: GLuint, v2: GLuint) {.importc.}
-  proc glSecondaryColor3uiEXT(red: GLuint, green: GLuint, blue: GLuint) {.importc.}
-  proc glPathStencilFuncNV(fun: GLenum, `ref`: GLint, mask: GLuint) {.importc.}
-  proc glVertexAttribP1ui(index: GLuint, `type`: GLenum, normalized: GLboolean, value: GLuint) {.importc.}
-  proc glStencilFillPathInstancedNV(numPaths: GLsizei, pathNameType: GLenum, paths: pointer, pathBase: GLuint, fillMode: GLenum, mask: GLuint, transformType: GLenum, transformValues: ptr GLfloat) {.importc.}
-  proc glFogCoordfEXT(coord: GLfloat) {.importc.}
-  proc glTextureParameterIuivEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glProgramUniform4dEXT(program: GLuint, location: GLint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glFramebufferTextureFaceARB(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint, face: GLenum) {.importc.}
-  proc glTexCoord3s(s: GLshort, t: GLshort, r: GLshort) {.importc.}
-  proc glGetFramebufferAttachmentParameteriv(target: GLenum, attachment: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glEndVideoCaptureNV(video_capture_slot: GLuint) {.importc.}
-  proc glProgramUniformMatrix2x4dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glGetFloatIndexedvEXT(target: GLenum, index: GLuint, data: ptr GLfloat) {.importc.}
-  proc glTexCoord1xOES(s: GLfixed) {.importc.}
-  proc glTexCoord4f(s: GLfloat, t: GLfloat, r: GLfloat, q: GLfloat) {.importc.}
-  proc glShaderSource(shader: GLuint, count: GLsizei, string: cstringArray, length: ptr GLint) {.importc.}
-  proc glGetDetailTexFuncSGIS(target: GLenum, points: ptr GLfloat) {.importc.}
-  proc glResetHistogram(target: GLenum) {.importc.}
-  proc glVertexAttribP2ui(index: GLuint, `type`: GLenum, normalized: GLboolean, value: GLuint) {.importc.}
-  proc glDrawTransformFeedbackNV(mode: GLenum, id: GLuint) {.importc.}
-  proc glWindowPos2fMESA(x: GLfloat, y: GLfloat) {.importc.}
-  proc glObjectLabelKHR(identifier: GLenum, name: GLuint, length: GLsizei, label: cstring) {.importc.}
-  proc glMultiTexCoord2iARB(target: GLenum, s: GLint, t: GLint) {.importc.}
-  proc glVertexAttrib4usv(index: GLuint, v: ptr GLushort) {.importc.}
-  proc glGetGraphicsResetStatusARB(): GLenum {.importc.}
-  proc glProgramUniform3dEXT(program: GLuint, location: GLint, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glPathSubCommandsNV(path: GLuint, commandStart: GLsizei, commandsToDelete: GLsizei, numCommands: GLsizei, commands: ptr GLubyte, numCoords: GLsizei, coordType: GLenum, coords: pointer) {.importc.}
-  proc glEndTransformFeedbackNV() {.importc.}
-  proc glWindowPos2sMESA(x: GLshort, y: GLshort) {.importc.}
-  proc glTangent3sEXT(tx: GLshort, ty: GLshort, tz: GLshort) {.importc.}
-  proc glLineWidthx(width: GLfixed) {.importc.}
-  proc glGetUniformBufferSizeEXT(program: GLuint, location: GLint): GLint {.importc.}
-  proc glTexCoord2bOES(s: GLbyte, t: GLbyte) {.importc.}
-  proc glWindowPos3iMESA(x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glTexGend(coord: GLenum, pname: GLenum, param: GLdouble) {.importc.}
-  proc glRenderbufferStorageMultisampleANGLE(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glGetProgramiv(program: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glDrawTransformFeedbackStreamInstanced(mode: GLenum, id: GLuint, stream: GLuint, instancecount: GLsizei) {.importc.}
-  proc glMatrixTranslatefEXT(mode: GLenum, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glColor4iv(v: ptr GLint) {.importc.}
-  proc glSecondaryColor3ivEXT(v: ptr GLint) {.importc.}
-  proc glIsNamedStringARB(namelen: GLint, name: cstring): GLboolean {.importc.}
-  proc glVertexAttribL4dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glEndTransformFeedback() {.importc.}
-  proc glVertexStream3fvATI(stream: GLenum, coords: ptr GLfloat) {.importc.}
-  proc glProgramUniformMatrix4x2dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glTextureBufferRangeEXT(texture: GLuint, target: GLenum, internalformat: GLenum, buffer: GLuint, offset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glTexCoord2fNormal3fVertex3fvSUN(tc: ptr GLfloat, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glProgramUniform2f(program: GLuint, location: GLint, v0: GLfloat, v1: GLfloat) {.importc.}
-  proc glMultiTexCoord2sv(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glTexCoord3bOES(s: GLbyte, t: GLbyte, r: GLbyte) {.importc.}
-  proc glGenFramebuffersOES(n: GLsizei, framebuffers: ptr GLuint) {.importc.}
-  proc glMultiTexCoord3sv(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glVertexAttrib4Nub(index: GLuint, x: GLubyte, y: GLubyte, z: GLubyte, w: GLubyte) {.importc.}
-  proc glColor3d(red: GLdouble, green: GLdouble, blue: GLdouble) {.importc.}
-  proc glGetActiveAttrib(program: GLuint, index: GLuint, bufSize: GLsizei, length: ptr GLsizei, size: ptr GLint, `type`: ptr GLenum, name: cstring) {.importc.}
-  proc glConvolutionParameterfEXT(target: GLenum, pname: GLenum, params: GLfloat) {.importc.}
-  proc glTexSubImage2DEXT(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glBinormal3fvEXT(v: ptr GLfloat) {.importc.}
-  proc glDebugMessageControl(source: GLenum, `type`: GLenum, severity: GLenum, count: GLsizei, ids: ptr GLuint, enabled: GLboolean) {.importc.}
-  proc glProgramUniform3uivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glPNTrianglesiATI(pname: GLenum, param: GLint) {.importc.}
-  proc glGetPerfMonitorCounterInfoAMD(group: GLuint, counter: GLuint, pname: GLenum, data: pointer) {.importc.}
-  proc glVertexAttribL3ui64NV(index: GLuint, x: GLuint64Ext, y: GLuint64Ext, z: GLuint64Ext) {.importc.}
-  proc glIsRenderbufferOES(renderbuffer: GLuint): GLboolean {.importc.}
-  proc glColorSubTable(target: GLenum, start: GLsizei, count: GLsizei, format: GLenum, `type`: GLenum, data: pointer) {.importc.}
-  proc glCompressedMultiTexImage1DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, border: GLint, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glBindSampler(unit: GLuint, sampler: GLuint) {.importc.}
-  proc glVariantubvEXT(id: GLuint, `addr`: ptr GLubyte) {.importc.}
-  proc glDisablei(target: GLenum, index: GLuint) {.importc.}
-  proc glVertexAttribI2uiEXT(index: GLuint, x: GLuint, y: GLuint) {.importc.}
-  proc glDrawElementArrayATI(mode: GLenum, count: GLsizei) {.importc.}
-  proc glTagSampleBufferSGIX() {.importc.}
-  proc glVertexPointerEXT(size: GLint, `type`: GLenum, stride: GLsizei, count: GLsizei, `pointer`: pointer) {.importc.}
-  proc glFragmentLightiSGIX(light: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glLoadTransposeMatrixxOES(m: ptr GLfixed) {.importc.}
-  proc glProgramLocalParameter4fvARB(target: GLenum, index: GLuint, params: ptr GLfloat) {.importc.}
-  proc glGetVariantFloatvEXT(id: GLuint, value: GLenum, data: ptr GLfloat) {.importc.}
-  proc glProgramUniform4ui64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glFragmentLightfSGIX(light: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glIsVertexArrayAPPLE(`array`: GLuint): GLboolean {.importc.}
-  proc glTexCoord1bvOES(coords: ptr GLbyte) {.importc.}
-  proc glUniform4fv(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glPixelDataRangeNV(target: GLenum, length: GLsizei, `pointer`: pointer) {.importc.}
-  proc glUniformMatrix4x2fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glRectf(x1: GLfloat, y1: GLfloat, x2: GLfloat, y2: GLfloat) {.importc.}
-  proc glCoverageMaskNV(mask: GLboolean) {.importc.}
-  proc glPointParameterfvSGIS(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glProgramUniformMatrix4x2dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glFragmentLightModelfSGIX(pname: GLenum, param: GLfloat) {.importc.}
-  proc glDisableVertexAttribAPPLE(index: GLuint, pname: GLenum) {.importc.}
-  proc glMultiTexCoord3dvARB(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glTexCoord4iv(v: ptr GLint) {.importc.}
-  proc glUniform1f(location: GLint, v0: GLfloat) {.importc.}
-  proc glVertexAttribParameteriAMD(index: GLuint, pname: GLenum, param: GLint) {.importc.}
-  proc glGetConvolutionParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glRecti(x1: GLint, y1: GLint, x2: GLint, y2: GLint) {.importc.}
-  proc glTexEnvxvOES(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glGetRenderbufferParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glBlendFuncIndexedAMD(buf: GLuint, src: GLenum, dst: GLenum) {.importc.}
-  proc glProgramUniformMatrix3x2fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glDrawArraysInstancedANGLE(mode: GLenum, first: GLint, count: GLsizei, primcount: GLsizei) {.importc.}
-  proc glTextureBarrierNV() {.importc.}
-  proc glDrawBuffersIndexedEXT(n: GLint, location: ptr GLenum, indices: ptr GLint) {.importc.}
-  proc glUniformMatrix4fvARB(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glInstrumentsBufferSGIX(size: GLsizei, buffer: ptr GLint) {.importc.}
-  proc glAlphaFuncQCOM(fun: GLenum, `ref`: GLclampf) {.importc.}
-  proc glUniformMatrix4fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glGetMinmaxParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetInvariantBooleanvEXT(id: GLuint, value: GLenum, data: ptr GLboolean) {.importc.}
-  proc glVDPAUIsSurfaceNV(surface: GLvdpauSurfaceNv) {.importc.}
-  proc glGenProgramsARB(n: GLsizei, programs: ptr GLuint) {.importc.}
-  proc glDrawRangeElementArrayATI(mode: GLenum, start: GLuint, `end`: GLuint, count: GLsizei) {.importc.}
-  proc glFramebufferRenderbufferEXT(target: GLenum, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glClearIndex(c: GLfloat) {.importc.}
-  proc glDepthRangeIndexed(index: GLuint, n: GLdouble, f: GLdouble) {.importc.}
-  proc glDrawTexivOES(coords: ptr GLint) {.importc.}
-  proc glTangent3iEXT(tx: GLint, ty: GLint, tz: GLint) {.importc.}
-  proc glStringMarkerGREMEDY(len: GLsizei, string: pointer) {.importc.}
-  proc glTexCoordP1ui(`type`: GLenum, coords: GLuint) {.importc.}
-  proc glOrthox(l: GLfixed, r: GLfixed, b: GLfixed, t: GLfixed, n: GLfixed, f: GLfixed) {.importc.}
-  proc glReplacementCodeuiVertex3fvSUN(rc: ptr GLuint, v: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord1bvOES(texture: GLenum, coords: ptr GLbyte) {.importc.}
-  proc glDrawArraysInstancedBaseInstance(mode: GLenum, first: GLint, count: GLsizei, instancecount: GLsizei, baseinstance: GLuint) {.importc.}
-  proc glMultMatrixf(m: ptr GLfloat) {.importc.}
-  proc glProgramUniform4i(program: GLuint, location: GLint, v0: GLint, v1: GLint, v2: GLint, v3: GLint) {.importc.}
-  proc glScissorArrayv(first: GLuint, count: GLsizei, v: ptr GLint) {.importc.}
-  proc glGetnUniformivEXT(program: GLuint, location: GLint, bufSize: GLsizei, params: ptr GLint) {.importc.}
-  proc glGetTexEnvxvOES(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glWindowPos3ivARB(v: ptr GLint) {.importc.}
-  proc glProgramStringARB(target: GLenum, format: GLenum, len: GLsizei, string: pointer) {.importc.}
-  proc glTextureColorMaskSGIS(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) {.importc.}
-  proc glMultiTexCoord4fv(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glUniformMatrix4x3fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glIsPathNV(path: GLuint): GLboolean {.importc.}
-  proc glStartTilingQCOM(x: GLuint, y: GLuint, width: GLuint, height: GLuint, preserveMask: GLbitfield) {.importc.}
-  proc glVariantivEXT(id: GLuint, `addr`: ptr GLint) {.importc.}
-  proc glGetnMinmaxARB(target: GLenum, reset: GLboolean, format: GLenum, `type`: GLenum, bufSize: GLsizei, values: pointer) {.importc.}
-  proc glTransformFeedbackVaryings(program: GLuint, count: GLsizei, varyings: cstringArray, bufferMode: GLenum) {.importc.}
-  proc glShaderOp2EXT(op: GLenum, res: GLuint, arg1: GLuint, arg2: GLuint) {.importc.}
-  proc glVertexAttribPointer(index: GLuint, size: GLint, `type`: GLenum, normalized: GLboolean, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glMultiTexCoord4dvARB(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glProgramUniform1ui64NV(program: GLuint, location: GLint, x: GLuint64Ext) {.importc.}
-  proc glGetShaderSourceARB(obj: GLhandleArb, maxLength: GLsizei, length: ptr GLsizei, source: cstring) {.importc.}
-  proc glGetBufferSubDataARB(target: GLenum, offset: GLintPtrArb, size: GLsizeiptrArb, data: pointer) {.importc.}
-  proc glCopyTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glProgramEnvParameterI4iNV(target: GLenum, index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glGetVertexAttribivARB(index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetFinalCombinerInputParameterivNV(variable: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glIndexFuncEXT(fun: GLenum, `ref`: GLclampf) {.importc.}
-  proc glProgramUniformMatrix3dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glTexStorage1DEXT(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei) {.importc.}
-  proc glUniformMatrix2fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glConvolutionParameterf(target: GLenum, pname: GLenum, params: GLfloat) {.importc.}
-  proc glGlobalAlphaFactordSUN(factor: GLdouble) {.importc.}
-  proc glCopyTextureImage2DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) {.importc.}
-  proc glVertex4xOES(x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glClearDepthx(depth: GLfixed) {.importc.}
-  proc glGetColorTableParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGenProgramPipelines(n: GLsizei, pipelines: ptr GLuint) {.importc.}
-  proc glVertexAttribL4ui64vNV(index: GLuint, v: ptr GLuint64Ext) {.importc.}
-  proc glUniform1fARB(location: GLint, v0: GLfloat) {.importc.}
-  proc glUniformMatrix3fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glUniform3dv(location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glVertexAttribI4iv(index: GLuint, v: ptr GLint) {.importc.}
-  proc glPixelZoom(xfactor: GLfloat, yfactor: GLfloat) {.importc.}
-  proc glShadeModel(mode: GLenum) {.importc.}
-  proc glFramebufferTexture3DOES(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint, zoffset: GLint) {.importc.}
-  proc glMultiTexCoord2i(target: GLenum, s: GLint, t: GLint) {.importc.}
-  proc glBlendEquationSeparateIndexedAMD(buf: GLuint, modeRgb: GLenum, modeAlpha: GLenum) {.importc.}
-  proc glIsEnabled(cap: GLenum): GLboolean {.importc.}
-  proc glTexImage2D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glPolygonOffsetxOES(factor: GLfixed, units: GLfixed) {.importc.}
-  proc glDrawBuffersEXT(n: GLsizei, bufs: ptr GLenum) {.importc.}
-  proc glPixelTexGenParameterfSGIS(pname: GLenum, param: GLfloat) {.importc.}
-  proc glExtGetRenderbuffersQCOM(renderbuffers: ptr GLuint, maxRenderbuffers: GLint, numRenderbuffers: ptr GLint) {.importc.}
-  proc glBindImageTextures(first: GLuint, count: GLsizei, textures: ptr GLuint) {.importc.}
-  proc glVertexAttribP2uiv(index: GLuint, `type`: GLenum, normalized: GLboolean, value: ptr GLuint) {.importc.}
-  proc glTextureImage3DMultisampleCoverageNV(texture: GLuint, target: GLenum, coverageSamples: GLsizei, colorSamples: GLsizei, internalFormat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, fixedSampleLocations: GLboolean) {.importc.}
-  proc glRasterPos2s(x: GLshort, y: GLshort) {.importc.}
-  proc glVertexAttrib4dvARB(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glProgramUniformMatrix2x3fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glProgramUniformMatrix2x4dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glMultiTexCoord1d(target: GLenum, s: GLdouble) {.importc.}
-  proc glGetProgramParameterdvNV(target: GLenum, index: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glPNTrianglesfATI(pname: GLenum, param: GLfloat) {.importc.}
-  proc glUniformMatrix3x4fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glVertexAttrib3sNV(index: GLuint, x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glGetVideoCaptureStreamfvNV(video_capture_slot: GLuint, stream: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glCombinerParameterivNV(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetTexGenfvOES(coord: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glCopyTexSubImage2DEXT(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glGetProgramLocalParameterfvARB(target: GLenum, index: GLuint, params: ptr GLfloat) {.importc.}
-  proc glTexCoord3iv(v: ptr GLint) {.importc.}
-  proc glVertexAttribs2hvNV(index: GLuint, n: GLsizei, v: ptr GLhalfNv) {.importc.}
-  proc glNormal3sv(v: ptr GLshort) {.importc.}
-  proc glUniform2dv(location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glSecondaryColor3hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glDrawArraysInstancedEXT(mode: GLenum, start: GLint, count: GLsizei, primcount: GLsizei) {.importc.}
-  proc glBeginTransformFeedback(primitiveMode: GLenum) {.importc.}
-  proc glTexParameterIuivEXT(target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glProgramBufferParametersfvNV(target: GLenum, bindingIndex: GLuint, wordIndex: GLuint, count: GLsizei, params: ptr GLfloat) {.importc.}
-  proc glVertexArrayBindVertexBufferEXT(vaobj: GLuint, bindingindex: GLuint, buffer: GLuint, offset: GLintptr, stride: GLsizei) {.importc.}
-  proc glPathParameterfNV(path: GLuint, pname: GLenum, value: GLfloat) {.importc.}
-  proc glGetClipPlanexOES(plane: GLenum, equation: ptr GLfixed) {.importc.}
-  proc glSecondaryColor3ubvEXT(v: ptr GLubyte) {.importc.}
-  proc glGetPixelMapxv(map: GLenum, size: GLint, values: ptr GLfixed) {.importc.}
-  proc glVertexAttribI1uivEXT(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glMultiTexImage3DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glAlphaFuncxOES(fun: GLenum, `ref`: GLfixed) {.importc.}
-  proc glMultiTexCoord2dv(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glBindRenderbufferOES(target: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glPathStencilDepthOffsetNV(factor: GLfloat, units: GLfloat) {.importc.}
-  proc glPointParameterfvEXT(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glSampleCoverageARB(value: GLfloat, invert: GLboolean) {.importc.}
-  proc glVertexAttrib3dNV(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glNamedProgramLocalParameter4dvEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLdouble) {.importc.}
-  proc glGenFramebuffers(n: GLsizei, framebuffers: ptr GLuint) {.importc.}
-  proc glMultiDrawElementsEXT(mode: GLenum, count: ptr GLsizei, `type`: GLenum, indices: ptr pointer, primcount: GLsizei) {.importc.}
-  proc glVertexAttrib2fNV(index: GLuint, x: GLfloat, y: GLfloat) {.importc.}
-  proc glProgramUniform4ivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glTexGeniOES(coord: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glBindProgramPipeline(pipeline: GLuint) {.importc.}
-  proc glBindSamplers(first: GLuint, count: GLsizei, samplers: ptr GLuint) {.importc.}
-  proc glColorTableSGI(target: GLenum, internalformat: GLenum, width: GLsizei, format: GLenum, `type`: GLenum, table: pointer) {.importc.}
-  proc glMultiTexCoord3xOES(texture: GLenum, s: GLfixed, t: GLfixed, r: GLfixed) {.importc.}
-  proc glIsQueryEXT(id: GLuint): GLboolean {.importc.}
-  proc glGenBuffersARB(n: GLsizei, buffers: ptr GLuint) {.importc.}
-  proc glVertex4xvOES(coords: ptr GLfixed) {.importc.}
-  proc glPixelMapuiv(map: GLenum, mapsize: GLsizei, values: ptr GLuint) {.importc.}
-  proc glDrawTexfOES(x: GLfloat, y: GLfloat, z: GLfloat, width: GLfloat, height: GLfloat) {.importc.}
-  proc glPointParameterfEXT(pname: GLenum, param: GLfloat) {.importc.}
-  proc glPathDashArrayNV(path: GLuint, dashCount: GLsizei, dashArray: ptr GLfloat) {.importc.}
-  proc glClearTexImage(texture: GLuint, level: GLint, format: GLenum, `type`: GLenum, data: ptr pointer) {.importc.}
-  proc glIndexdv(c: ptr GLdouble) {.importc.}
-  proc glMultTransposeMatrixfARB(m: ptr GLfloat) {.importc.}
-  proc glVertexAttribL3d(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glUniform3fv(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetProgramInterfaceiv(program: GLuint, programInterface: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glFogCoordfv(coord: ptr GLfloat) {.importc.}
-  proc glTexSubImage3DOES(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGetPolygonStipple(mask: ptr GLubyte) {.importc.}
-  proc glGetQueryObjectivEXT(id: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glColor3xOES(red: GLfixed, green: GLfixed, blue: GLfixed) {.importc.}
-  proc glMultiTexParameterIivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetMaterialiv(face: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertex2fv(v: ptr GLfloat) {.importc.}
-  proc glConvolutionParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGenOcclusionQueriesNV(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glGetVertexAttribdvNV(index: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glVertexAttribs4fvNV(index: GLuint, count: GLsizei, v: ptr GLfloat) {.importc.}
-  proc glVertexAttribL3dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glTexEnvi(target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glObjectPtrLabel(`ptr`: ptr pointer, length: GLsizei, label: cstring) {.importc.}
-  proc glGetTexGenfv(coord: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glMapVertexAttrib1dAPPLE(index: GLuint, size: GLuint, u1: GLdouble, u2: GLdouble, stride: GLint, order: GLint, points: ptr GLdouble) {.importc.}
-  proc glTexCoord3dv(v: ptr GLdouble) {.importc.}
-  proc glIsEnabledIndexedEXT(target: GLenum, index: GLuint): GLboolean {.importc.}
-  proc glGlobalAlphaFactoruiSUN(factor: GLuint) {.importc.}
-  proc glMatrixIndexPointerARB(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glUniformHandleui64ARB(location: GLint, value: GLuint64) {.importc.}
-  proc glUniform1fvARB(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetActiveSubroutineUniformName(program: GLuint, shadertype: GLenum, index: GLuint, bufsize: GLsizei, length: ptr GLsizei, name: cstring) {.importc.}
-  proc glProgramUniformMatrix4x2fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord4fARB(target: GLenum, s: GLfloat, t: GLfloat, r: GLfloat, q: GLfloat) {.importc.}
-  proc glGetDriverControlsQCOM(num: ptr GLint, size: GLsizei, driverControls: ptr GLuint) {.importc.}
-  proc glBindBufferRange(target: GLenum, index: GLuint, buffer: GLuint, offset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glMapGrid2f(un: GLint, u1: GLfloat, u2: GLfloat, vn: GLint, v1: GLfloat, v2: GLfloat) {.importc.}
-  proc glUniform2fv(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glOrtho(left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) {.importc.}
-  proc glGetImageHandleNV(texture: GLuint, level: GLint, layered: GLboolean, layer: GLint, format: GLenum): GLuint64 {.importc.}
-  proc glIsImageHandleResidentARB(handle: GLuint64): GLboolean {.importc.}
-  proc glGetConvolutionParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glLineWidthxOES(width: GLfixed) {.importc.}
-  proc glPathCommandsNV(path: GLuint, numCommands: GLsizei, commands: ptr GLubyte, numCoords: GLsizei, coordType: GLenum, coords: pointer) {.importc.}
-  proc glMaterialxvOES(face: GLenum, pname: GLenum, param: ptr GLfixed) {.importc.}
-  proc glPauseTransformFeedbackNV() {.importc.}
-  proc glTexCoord4d(s: GLdouble, t: GLdouble, r: GLdouble, q: GLdouble) {.importc.}
-  proc glUniform3ui64vNV(location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glMultiTexCoord3dARB(target: GLenum, s: GLdouble, t: GLdouble, r: GLdouble) {.importc.}
-  proc glProgramUniform3fEXT(program: GLuint, location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat) {.importc.}
-  proc glTexImage3DMultisampleCoverageNV(target: GLenum, coverageSamples: GLsizei, colorSamples: GLsizei, internalFormat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, fixedSampleLocations: GLboolean) {.importc.}
-  proc glNormalPointerEXT(`type`: GLenum, stride: GLsizei, count: GLsizei, `pointer`: pointer) {.importc.}
-  proc glPathColorGenNV(color: GLenum, genMode: GLenum, colorFormat: GLenum, coeffs: ptr GLfloat) {.importc.}
-  proc glGetMultiTexGendvEXT(texunit: GLenum, coord: GLenum, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glColor3i(red: GLint, green: GLint, blue: GLint) {.importc.}
-  proc glPointSizex(size: GLfixed) {.importc.}
-  proc glGetConvolutionFilterEXT(target: GLenum, format: GLenum, `type`: GLenum, image: pointer) {.importc.}
-  proc glBindBufferBaseNV(target: GLenum, index: GLuint, buffer: GLuint) {.importc.}
-  proc glInsertComponentEXT(res: GLuint, src: GLuint, num: GLuint) {.importc.}
-  proc glVertex2d(x: GLdouble, y: GLdouble) {.importc.}
-  proc glGetPathDashArrayNV(path: GLuint, dashArray: ptr GLfloat) {.importc.}
-  proc glVertexAttrib2sARB(index: GLuint, x: GLshort, y: GLshort) {.importc.}
-  proc glScissor(x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glLoadMatrixd(m: ptr GLdouble) {.importc.}
-  proc glVertex2bvOES(coords: ptr GLbyte) {.importc.}
-  proc glTexCoord2i(s: GLint, t: GLint) {.importc.}
-  proc glWriteMaskEXT(res: GLuint, `in`: GLuint, outX: GLenum, outY: GLenum, outZ: GLenum, outW: GLenum) {.importc.}
-  proc glClientWaitSyncAPPLE(sync: GLsync, flags: GLbitfield, timeout: GLuint64): GLenum {.importc.}
-  proc glGetObjectBufferivATI(buffer: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetNamedBufferParameterivEXT(buffer: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glTexCoord1bOES(s: GLbyte) {.importc.}
-  proc glVertexAttrib4dARB(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glUniform3fARB(location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat) {.importc.}
-  proc glWindowPos2ivARB(v: ptr GLint) {.importc.}
-  proc glCreateShaderProgramvEXT(`type`: GLenum, count: GLsizei, strings: cstringArray): GLuint {.importc.}
-  proc glListParameterivSGIX(list: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetGraphicsResetStatusEXT(): GLenum {.importc.}
-  proc glActiveShaderProgramEXT(pipeline: GLuint, program: GLuint) {.importc.}
-  proc glTexCoordP1uiv(`type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glVideoCaptureStreamParameterdvNV(video_capture_slot: GLuint, stream: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glGetVertexAttribPointerv(index: GLuint, pname: GLenum, `pointer`: ptr pointer) {.importc.}
-  proc glGetCompressedMultiTexImageEXT(texunit: GLenum, target: GLenum, lod: GLint, img: pointer) {.importc.}
-  proc glWindowPos4fMESA(x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glDrawElementsInstancedARB(mode: GLenum, count: GLsizei, `type`: GLenum, indices: pointer, primcount: GLsizei) {.importc.}
-  proc glVertexStream1dATI(stream: GLenum, x: GLdouble) {.importc.}
-  proc glMatrixMultfEXT(mode: GLenum, m: ptr GLfloat) {.importc.}
-  proc glGetPathParameterivNV(path: GLuint, pname: GLenum, value: ptr GLint) {.importc.}
-  proc glCombinerParameteriNV(pname: GLenum, param: GLint) {.importc.}
-  proc glUpdateObjectBufferATI(buffer: GLuint, offset: GLuint, size: GLsizei, `pointer`: pointer, preserve: GLenum) {.importc.}
-  proc glVertexAttrib4uivARB(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glVertexAttrib4iv(index: GLuint, v: ptr GLint) {.importc.}
-  proc glFrustum(left: GLdouble, right: GLdouble, bottom: GLdouble, top: GLdouble, zNear: GLdouble, zFar: GLdouble) {.importc.}
-  proc glDrawTexxvOES(coords: ptr GLfixed) {.importc.}
-  proc glTexCoord2fColor4ubVertex3fSUN(s: GLfloat, t: GLfloat, r: GLubyte, g: GLubyte, b: GLubyte, a: GLubyte, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glMultiTexCoord2fARB(target: GLenum, s: GLfloat, t: GLfloat) {.importc.}
-  proc glGenTransformFeedbacksNV(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glMultiTexGenfEXT(texunit: GLenum, coord: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glGetMinmax(target: GLenum, reset: GLboolean, format: GLenum, `type`: GLenum, values: pointer) {.importc.}
-  proc glBindTransformFeedback(target: GLenum, id: GLuint) {.importc.}
-  proc glEnableVertexAttribArrayARB(index: GLuint) {.importc.}
-  proc glIsFenceAPPLE(fence: GLuint): GLboolean {.importc.}
-  proc glMultiTexGendvEXT(texunit: GLenum, coord: GLenum, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glRotatex(angle: GLfixed, x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glGetFragmentLightfvSGIX(light: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord4dv(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glBlendFuncSeparateEXT(sfactorRgb: GLenum, dfactorRgb: GLenum, sfactorAlpha: GLenum, dfactorAlpha: GLenum) {.importc.}
-  proc glMultiTexCoord1f(target: GLenum, s: GLfloat) {.importc.}
-  proc glWindowPos2f(x: GLfloat, y: GLfloat) {.importc.}
-  proc glGetPathTexGenivNV(texCoordSet: GLenum, pname: GLenum, value: ptr GLint) {.importc.}
-  proc glIndexxvOES(component: ptr GLfixed) {.importc.}
-  proc glDisableVertexArrayAttribEXT(vaobj: GLuint, index: GLuint) {.importc.}
-  proc glGetProgramivARB(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glPatchParameteri(pname: GLenum, value: GLint) {.importc.}
-  proc glMultiTexCoord2fv(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glTexSubImage3DEXT(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glFramebufferTexture1DEXT(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glTangent3fEXT(tx: GLfloat, ty: GLfloat, tz: GLfloat) {.importc.}
-  proc glIsVertexAttribEnabledAPPLE(index: GLuint, pname: GLenum): GLboolean {.importc.}
-  proc glGetShaderInfoLog(shader: GLuint, bufSize: GLsizei, length: ptr GLsizei, infoLog: cstring) {.importc.}
-  proc glFrustumx(l: GLfixed, r: GLfixed, b: GLfixed, t: GLfixed, n: GLfixed, f: GLfixed) {.importc.}
-  proc glTexGenfv(coord: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glCompressedTexImage2DARB(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glMultiTexCoord2bvOES(texture: GLenum, coords: ptr GLbyte) {.importc.}
-  proc glGetTexBumpParameterivATI(pname: GLenum, param: ptr GLint) {.importc.}
-  proc glMultiTexCoord2svARB(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glProgramBufferParametersIivNV(target: GLenum, bindingIndex: GLuint, wordIndex: GLuint, count: GLsizei, params: ptr GLint) {.importc.}
-  proc glIsQueryARB(id: GLuint): GLboolean {.importc.}
-  proc glFramebufferTextureLayer(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint, layer: GLint) {.importc.}
-  proc glUniform4i(location: GLint, v0: GLint, v1: GLint, v2: GLint, v3: GLint) {.importc.}
-  proc glDrawArrays(mode: GLenum, first: GLint, count: GLsizei) {.importc.}
-  proc glWeightubvARB(size: GLint, weights: ptr GLubyte) {.importc.}
-  proc glGetUniformSubroutineuiv(shadertype: GLenum, location: GLint, params: ptr GLuint) {.importc.}
-  proc glMultTransposeMatrixdARB(m: ptr GLdouble) {.importc.}
-  proc glReplacementCodeuiTexCoord2fNormal3fVertex3fvSUN(rc: ptr GLuint, tc: ptr GLfloat, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glGetMapdv(target: GLenum, query: GLenum, v: ptr GLdouble) {.importc.}
-  proc glGetMultisamplefvNV(pname: GLenum, index: GLuint, val: ptr GLfloat) {.importc.}
-  proc glVertex2hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glProgramUniformMatrix2x3fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glProgramUniform3iEXT(program: GLuint, location: GLint, v0: GLint, v1: GLint, v2: GLint) {.importc.}
-  proc glGetnPixelMapusvARB(map: GLenum, bufSize: GLsizei, values: ptr GLushort) {.importc.}
-  proc glVertexWeighthvNV(weight: ptr GLhalfNv) {.importc.}
-  proc glDrawTransformFeedbackInstanced(mode: GLenum, id: GLuint, instancecount: GLsizei) {.importc.}
-  proc glFlushStaticDataIBM(target: GLenum) {.importc.}
-  proc glWindowPos2fvARB(v: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord3sARB(target: GLenum, s: GLshort, t: GLshort, r: GLshort) {.importc.}
-  proc glWindowPos3fv(v: ptr GLfloat) {.importc.}
-  proc glFlushVertexArrayRangeNV() {.importc.}
-  proc glTangent3bEXT(tx: GLbyte, ty: GLbyte, tz: GLbyte) {.importc.}
-  proc glIglooInterfaceSGIX(pname: GLenum, params: pointer) {.importc.}
-  proc glProgramUniformMatrix4x2fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glVertexAttribIFormatNV(index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei) {.importc.}
-  proc glNamedRenderbufferStorageMultisampleEXT(renderbuffer: GLuint, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glCopyTexImage1DEXT(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, border: GLint) {.importc.}
-  proc glBindTexGenParameterEXT(unit: GLenum, coord: GLenum, value: GLenum): GLuint {.importc.}
-  proc glVertex4hNV(x: GLhalfNv, y: GLhalfNv, z: GLhalfNv, w: GLhalfNv) {.importc.}
-  proc glGetMapfv(target: GLenum, query: GLenum, v: ptr GLfloat) {.importc.}
-  proc glSamplePatternEXT(pattern: GLenum) {.importc.}
-  proc glIndexxOES(component: GLfixed) {.importc.}
-  proc glVertexAttrib4ubv(index: GLuint, v: ptr GLubyte) {.importc.}
-  proc glGetColorTable(target: GLenum, format: GLenum, `type`: GLenum, table: pointer) {.importc.}
-  proc glFragmentLightModelivSGIX(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glPixelTransformParameterfEXT(target: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glSamplerParameterfv(sampler: GLuint, pname: GLenum, param: ptr GLfloat) {.importc.}
-  proc glBindTextureUnitParameterEXT(unit: GLenum, value: GLenum): GLuint {.importc.}
-  proc glColor3ub(red: GLubyte, green: GLubyte, blue: GLubyte) {.importc.}
-  proc glGetMultiTexGenivEXT(texunit: GLenum, coord: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVariantusvEXT(id: GLuint, `addr`: ptr GLushort) {.importc.}
-  proc glMaterialiv(face: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glPassTexCoordATI(dst: GLuint, coord: GLuint, swizzle: GLenum) {.importc.}
-  proc glGetIntegerui64vNV(value: GLenum, result: ptr GLuint64Ext) {.importc.}
-  proc glProgramParameteriEXT(program: GLuint, pname: GLenum, value: GLint) {.importc.}
-  proc glVertexArrayEdgeFlagOffsetEXT(vaobj: GLuint, buffer: GLuint, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glGetCombinerInputParameterivNV(stage: GLenum, portion: GLenum, variable: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glLogicOp(opcode: GLenum) {.importc.}
-  proc glConvolutionParameterfvEXT(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glIsBufferResidentNV(target: GLenum): GLboolean {.importc.}
-  proc glIsProgram(program: GLuint): GLboolean {.importc.}
-  proc glEndQueryARB(target: GLenum) {.importc.}
-  proc glRenderbufferStorage(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glMaterialfv(face: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTranslatex(x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glPathParameterivNV(path: GLuint, pname: GLenum, value: ptr GLint) {.importc.}
-  proc glLightxOES(light: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glSampleMaskEXT(value: GLclampf, invert: GLboolean) {.importc.}
-  proc glReplacementCodeubvSUN(code: ptr GLubyte) {.importc.}
-  proc glVertexAttribArrayObjectATI(index: GLuint, size: GLint, `type`: GLenum, normalized: GLboolean, stride: GLsizei, buffer: GLuint, offset: GLuint) {.importc.}
-  proc glBeginTransformFeedbackNV(primitiveMode: GLenum) {.importc.}
-  proc glEvalCoord1fv(u: ptr GLfloat) {.importc.}
-  proc glProgramUniformMatrix2x3dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glMaterialxv(face: GLenum, pname: GLenum, param: ptr GLfixed) {.importc.}
-  proc glGetIntegerui64i_vNV(value: GLenum, index: GLuint, result: ptr GLuint64Ext) {.importc.}
-  proc glUniformBlockBinding(program: GLuint, uniformBlockIndex: GLuint, uniformBlockBinding: GLuint) {.importc.}
-  proc glColor4ui(red: GLuint, green: GLuint, blue: GLuint, alpha: GLuint) {.importc.}
-  proc glColor4ubVertex2fvSUN(c: ptr GLubyte, v: ptr GLfloat) {.importc.}
-  proc glRectd(x1: GLdouble, y1: GLdouble, x2: GLdouble, y2: GLdouble) {.importc.}
-  proc glGenVertexShadersEXT(range: GLuint): GLuint {.importc.}
-  proc glLinkProgramARB(programObj: GLhandleArb) {.importc.}
-  proc glVertexAttribL4dEXT(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glBlitFramebuffer(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) {.importc.}
-  proc glUseProgram(program: GLuint) {.importc.}
-  proc glNamedProgramLocalParameterI4ivEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLint) {.importc.}
-  proc glMatrixLoadTransposedEXT(mode: GLenum, m: ptr GLdouble) {.importc.}
-  proc glTranslatef(x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glGetBooleani_v(target: GLenum, index: GLuint, data: ptr GLboolean) {.importc.}
-  proc glEndFragmentShaderATI() {.importc.}
-  proc glVertexAttribI4ivEXT(index: GLuint, v: ptr GLint) {.importc.}
-  proc glMultiDrawElementsIndirectBindlessNV(mode: GLenum, `type`: GLenum, indirect: pointer, drawCount: GLsizei, stride: GLsizei, vertexBufferCount: GLint) {.importc.}
-  proc glTexCoord2s(s: GLshort, t: GLshort) {.importc.}
-  proc glProgramUniform1i64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glPointSizePointerOES(`type`: GLenum, stride: GLsizei, `pointer`: ptr pointer) {.importc.}
-  proc glGetTexFilterFuncSGIS(target: GLenum, filter: GLenum, weights: ptr GLfloat) {.importc.}
-  proc glMapGrid2xOES(n: GLint, u1: GLfixed, u2: GLfixed, v1: GLfixed, v2: GLfixed) {.importc.}
-  proc glRasterPos4xvOES(coords: ptr GLfixed) {.importc.}
-  proc glGetProgramBinary(program: GLuint, bufSize: GLsizei, length: ptr GLsizei, binaryFormat: ptr GLenum, binary: pointer) {.importc.}
-  proc glNamedProgramLocalParameterI4uiEXT(program: GLuint, target: GLenum, index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) {.importc.}
-  proc glGetTexImage(target: GLenum, level: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glColor4d(red: GLdouble, green: GLdouble, blue: GLdouble, alpha: GLdouble) {.importc.}
-  proc glTexCoord2fColor4fNormal3fVertex3fSUN(s: GLfloat, t: GLfloat, r: GLfloat, g: GLfloat, b: GLfloat, a: GLfloat, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glIndexi(c: GLint) {.importc.}
-  proc glGetSamplerParameterIuiv(sampler: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glGetnUniformivARB(program: GLuint, location: GLint, bufSize: GLsizei, params: ptr GLint) {.importc.}
-  proc glCopyTexSubImage3DEXT(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glVertexAttribI2uivEXT(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glVertexStream2fvATI(stream: GLenum, coords: ptr GLfloat) {.importc.}
-  proc glArrayElementEXT(i: GLint) {.importc.}
-  proc glVertexAttrib2fv(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glCopyMultiTexSubImage1DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glTexCoord4sv(v: ptr GLshort) {.importc.}
-  proc glTexGenfvOES(coord: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glPointParameteriv(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetNamedRenderbufferParameterivEXT(renderbuffer: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramVertexLimitNV(target: GLenum, limit: GLint) {.importc.}
-  proc glSetMultisamplefvAMD(pname: GLenum, index: GLuint, val: ptr GLfloat) {.importc.}
-  proc glLoadIdentityDeformationMapSGIX(mask: GLbitfield) {.importc.}
-  proc glIsSyncAPPLE(sync: GLsync): GLboolean {.importc.}
-  proc glProgramUniform1ui64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glEdgeFlagPointerListIBM(stride: GLint, `pointer`: ptr ptr GLboolean, ptrstride: GLint) {.importc.}
-  proc glBeginVertexShaderEXT() {.importc.}
-  proc glGetIntegerv(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttrib2dvARB(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glBeginConditionalRenderNV(id: GLuint, mode: GLenum) {.importc.}
-  proc glEdgeFlagv(flag: ptr GLboolean) {.importc.}
-  proc glReplacementCodeubSUN(code: GLubyte) {.importc.}
-  proc glObjectLabel(identifier: GLenum, name: GLuint, length: GLsizei, label: cstring) {.importc.}
-  proc glMultiTexCoord3xvOES(texture: GLenum, coords: ptr GLfixed) {.importc.}
-  proc glNormal3iv(v: ptr GLint) {.importc.}
-  proc glSamplerParameteri(sampler: GLuint, pname: GLenum, param: GLint) {.importc.}
-  proc glTextureStorage1DEXT(texture: GLuint, target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei) {.importc.}
-  proc glVertexStream4dvATI(stream: GLenum, coords: ptr GLdouble) {.importc.}
-  proc glWindowPos2fv(v: ptr GLfloat) {.importc.}
-  proc glTexCoord4i(s: GLint, t: GLint, r: GLint, q: GLint) {.importc.}
-  proc glVertexAttrib4NusvARB(index: GLuint, v: ptr GLushort) {.importc.}
-  proc glVertexAttribL4d(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glVertexAttribDivisorANGLE(index: GLuint, divisor: GLuint) {.importc.}
-  proc glMatrixIndexPointerOES(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glMultMatrixxOES(m: ptr GLfixed) {.importc.}
-  proc glMultiTexCoordP2ui(texture: GLenum, `type`: GLenum, coords: GLuint) {.importc.}
-  proc glDeformationMap3dSGIX(target: GLenum, u1: GLdouble, u2: GLdouble, ustride: GLint, uorder: GLint, v1: GLdouble, v2: GLdouble, vstride: GLint, vorder: GLint, w1: GLdouble, w2: GLdouble, wstride: GLint, worder: GLint, points: ptr GLdouble) {.importc.}
-  proc glClearDepthfOES(depth: GLclampf) {.importc.}
-  proc glVertexStream1ivATI(stream: GLenum, coords: ptr GLint) {.importc.}
-  proc glHint(target: GLenum, mode: GLenum) {.importc.}
-  proc glVertex3fv(v: ptr GLfloat) {.importc.}
-  proc glWaitSyncAPPLE(sync: GLsync, flags: GLbitfield, timeout: GLuint64) {.importc.}
-  proc glWindowPos3i(x: GLint, y: GLint, z: GLint) {.importc.}
-  proc glCompressedTexImage3DARB(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glVertexAttrib1fvARB(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord4xOES(texture: GLenum, s: GLfixed, t: GLfixed, r: GLfixed, q: GLfixed) {.importc.}
-  proc glUniform4ui64NV(location: GLint, x: GLuint64Ext, y: GLuint64Ext, z: GLuint64Ext, w: GLuint64Ext) {.importc.}
-  proc glProgramUniform4uiEXT(program: GLuint, location: GLint, v0: GLuint, v1: GLuint, v2: GLuint, v3: GLuint) {.importc.}
-  proc glUnmapNamedBufferEXT(buffer: GLuint): GLboolean {.importc.}
-  proc glBitmap(width: GLsizei, height: GLsizei, xorig: GLfloat, yorig: GLfloat, xmove: GLfloat, ymove: GLfloat, bitmap: ptr GLubyte) {.importc.}
-  proc glNamedProgramLocalParameters4fvEXT(program: GLuint, target: GLenum, index: GLuint, count: GLsizei, params: ptr GLfloat) {.importc.}
-  proc glGetPathCommandsNV(path: GLuint, commands: ptr GLubyte) {.importc.}
-  proc glVertexAttrib3fNV(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glNamedProgramStringEXT(program: GLuint, target: GLenum, format: GLenum, len: GLsizei, string: pointer) {.importc.}
-  proc glMatrixIndexusvARB(size: GLint, indices: ptr GLushort) {.importc.}
-  proc glBlitFramebufferNV(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) {.importc.}
-  proc glVertexAttribI1uiv(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glEndConditionalRenderNV() {.importc.}
-  proc glFeedbackBuffer(size: GLsizei, `type`: GLenum, buffer: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord3bvOES(texture: GLenum, coords: ptr GLbyte) {.importc.}
-  proc glCopyColorTableSGI(target: GLenum, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glActiveTexture(texture: GLenum) {.importc.}
-  proc glFogCoordhNV(fog: GLhalfNv) {.importc.}
-  proc glColorMaskIndexedEXT(index: GLuint, r: GLboolean, g: GLboolean, b: GLboolean, a: GLboolean) {.importc.}
-  proc glGetCompressedTexImage(target: GLenum, level: GLint, img: pointer) {.importc.}
-  proc glRasterPos2iv(v: ptr GLint) {.importc.}
-  proc glGetBufferParameterivARB(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramUniform3d(program: GLuint, location: GLint, v0: GLdouble, v1: GLdouble, v2: GLdouble) {.importc.}
-  proc glRasterPos3xvOES(coords: ptr GLfixed) {.importc.}
-  proc glGetTextureParameterIuivEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glBindImageTextureEXT(index: GLuint, texture: GLuint, level: GLint, layered: GLboolean, layer: GLint, access: GLenum, format: GLint) {.importc.}
-  proc glWindowPos2iMESA(x: GLint, y: GLint) {.importc.}
-  proc glVertexPointervINTEL(size: GLint, `type`: GLenum, `pointer`: ptr pointer) {.importc.}
-  proc glPixelTexGenParameterfvSGIS(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glUniform1iARB(location: GLint, v0: GLint) {.importc.}
-  proc glTextureSubImage3DEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glStencilOpSeparate(face: GLenum, sfail: GLenum, dpfail: GLenum, dppass: GLenum) {.importc.}
-  proc glVertexAttrib1dARB(index: GLuint, x: GLdouble) {.importc.}
-  proc glGetVideoCaptureStreamivNV(video_capture_slot: GLuint, stream: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glIsFramebufferEXT(framebuffer: GLuint): GLboolean {.importc.}
-  proc glPointParameterxv(pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glProgramUniform4dv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glPassThrough(token: GLfloat) {.importc.}
-  proc glGetProgramPipelineiv(pipeline: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glApplyTextureEXT(mode: GLenum) {.importc.}
-  proc glVertexArrayNormalOffsetEXT(vaobj: GLuint, buffer: GLuint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glTexFilterFuncSGIS(target: GLenum, filter: GLenum, n: GLsizei, weights: ptr GLfloat) {.importc.}
-  proc glRenderbufferStorageOES(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glBindParameterEXT(value: GLenum): GLuint {.importc.}
-  proc glVertex4s(x: GLshort, y: GLshort, z: GLshort, w: GLshort) {.importc.}
-  proc glLoadTransposeMatrixf(m: ptr GLfloat) {.importc.}
-  proc glDepthFunc(fun: GLenum) {.importc.}
-  proc glGetFramebufferAttachmentParameterivEXT(target: GLenum, attachment: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glSampleMaskSGIS(value: GLclampf, invert: GLboolean) {.importc.}
-  proc glGetPointerIndexedvEXT(target: GLenum, index: GLuint, data: ptr pointer) {.importc.}
-  proc glVertexStream4iATI(stream: GLenum, x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glUnlockArraysEXT() {.importc.}
-  proc glReplacementCodeuivSUN(code: ptr GLuint) {.importc.}
-  proc glMatrixScaledEXT(mode: GLenum, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glMultiTexImage2DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glFeedbackBufferxOES(n: GLsizei, `type`: GLenum, buffer: ptr GLfixed) {.importc.}
-  proc glLightEnviSGIX(pname: GLenum, param: GLint) {.importc.}
-  proc glMultiTexCoord4dARB(target: GLenum, s: GLdouble, t: GLdouble, r: GLdouble, q: GLdouble) {.importc.}
-  proc glExtGetTexLevelParameterivQCOM(texture: GLuint, face: GLenum, level: GLint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttribI4usvEXT(index: GLuint, v: ptr GLushort) {.importc.}
-  proc glWindowPos2dvARB(v: ptr GLdouble) {.importc.}
-  proc glBindFramebuffer(target: GLenum, framebuffer: GLuint) {.importc.}
-  proc glGetProgramPipelineivEXT(pipeline: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramUniformHandleui64vNV(program: GLuint, location: GLint, count: GLsizei, values: ptr GLuint64) {.importc.}
-  proc glFogCoordhvNV(fog: ptr GLhalfNv) {.importc.}
-  proc glTextureImage1DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGetActiveAtomicCounterBufferiv(program: GLuint, bufferIndex: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glBeginQueryARB(target: GLenum, id: GLuint) {.importc.}
-  proc glGetTexParameterIuivEXT(target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glUniform4ui64vNV(location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glClearAccumxOES(red: GLfixed, green: GLfixed, blue: GLfixed, alpha: GLfixed) {.importc.}
-  proc glFreeObjectBufferATI(buffer: GLuint) {.importc.}
-  proc glGetVideouivNV(video_slot: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glVertexAttribL4ui64NV(index: GLuint, x: GLuint64Ext, y: GLuint64Ext, z: GLuint64Ext, w: GLuint64Ext) {.importc.}
-  proc glGetUniformBlockIndex(program: GLuint, uniformBlockName: cstring): GLuint {.importc.}
-  proc glCopyMultiTexSubImage2DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glVertex3bvOES(coords: ptr GLbyte) {.importc.}
-  proc glMultiDrawElementArrayAPPLE(mode: GLenum, first: ptr GLint, count: ptr GLsizei, primcount: GLsizei) {.importc.}
-  proc glPrimitiveRestartNV() {.importc.}
-  proc glMateriali(face: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glBegin(mode: GLenum) {.importc.}
-  proc glFogCoordPointerEXT(`type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glTexCoord1sv(v: ptr GLshort) {.importc.}
-  proc glVertexAttribI4sv(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glTexEnvx(target: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glTexParameterIivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glLoadTransposeMatrixfARB(m: ptr GLfloat) {.importc.}
-  proc glGetTextureSamplerHandleARB(texture: GLuint, sampler: GLuint): GLuint64 {.importc.}
-  proc glVertexP3uiv(`type`: GLenum, value: ptr GLuint) {.importc.}
-  proc glProgramUniform2dv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glTexCoord4xvOES(coords: ptr GLfixed) {.importc.}
-  proc glTexStorage1D(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei) {.importc.}
-  proc glTextureParameterfEXT(texture: GLuint, target: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glVertexAttrib1d(index: GLuint, x: GLdouble) {.importc.}
-  proc glGetnPixelMapfvARB(map: GLenum, bufSize: GLsizei, values: ptr GLfloat) {.importc.}
-  proc glDisableVertexAttribArray(index: GLuint) {.importc.}
-  proc glUniformMatrix4x3dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glRasterPos4f(x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glProgramUniform1fEXT(program: GLuint, location: GLint, v0: GLfloat) {.importc.}
-  proc glPathTexGenNV(texCoordSet: GLenum, genMode: GLenum, components: GLint, coeffs: ptr GLfloat) {.importc.}
-  proc glUniform3ui(location: GLint, v0: GLuint, v1: GLuint, v2: GLuint) {.importc.}
-  proc glVDPAURegisterOutputSurfaceNV(vdpSurface: pointer, target: GLenum, numTextureNames: GLsizei, textureNames: ptr GLuint): GLvdpauSurfaceNv {.importc.}
-  proc glGetProgramLocalParameterIuivNV(target: GLenum, index: GLuint, params: ptr GLuint) {.importc.}
-  proc glIsTextureHandleResidentNV(handle: GLuint64): GLboolean {.importc.}
-  proc glProgramEnvParameters4fvEXT(target: GLenum, index: GLuint, count: GLsizei, params: ptr GLfloat) {.importc.}
-  proc glReplacementCodeuiTexCoord2fNormal3fVertex3fSUN(rc: GLuint, s: GLfloat, t: GLfloat, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glGetMultiTexEnvivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetFloatv(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glInsertEventMarkerEXT(length: GLsizei, marker: cstring) {.importc.}
-  proc glRasterPos3d(x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glNamedFramebufferRenderbufferEXT(framebuffer: GLuint, attachment: GLenum, renderbuffertarget: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glGetConvolutionFilter(target: GLenum, format: GLenum, `type`: GLenum, image: pointer) {.importc.}
-  proc glIsOcclusionQueryNV(id: GLuint): GLboolean {.importc.}
-  proc glGetnPixelMapuivARB(map: GLenum, bufSize: GLsizei, values: ptr GLuint) {.importc.}
-  proc glMapParameterfvNV(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glPushDebugGroup(source: GLenum, id: GLuint, length: GLsizei, message: cstring) {.importc.}
-  proc glMakeImageHandleResidentARB(handle: GLuint64, access: GLenum) {.importc.}
-  proc glProgramUniformMatrix2fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glUniform3i64vNV(location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glImageTransformParameteriHP(target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glMultiTexCoord1s(target: GLenum, s: GLshort) {.importc.}
-  proc glVertexAttribL4dvEXT(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glGetProgramEnvParameterfvARB(target: GLenum, index: GLuint, params: ptr GLfloat) {.importc.}
-  proc glVertexArrayColorOffsetEXT(vaobj: GLuint, buffer: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glGetHistogramParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetRenderbufferParameterivOES(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetBufferPointerv(target: GLenum, pname: GLenum, params: ptr pointer) {.importc.}
-  proc glSecondaryColor3ui(red: GLuint, green: GLuint, blue: GLuint) {.importc.}
-  proc glGetDebugMessageLog(count: GLuint, bufsize: GLsizei, sources: ptr GLenum, types: ptr GLenum, ids: ptr GLuint, severities: ptr GLenum, lengths: ptr GLsizei, messageLog: cstring): GLuint {.importc.}
-  proc glNormal3i(nx: GLint, ny: GLint, nz: GLint) {.importc.}
-  proc glTestFenceNV(fence: GLuint): GLboolean {.importc.}
-  proc glSecondaryColor3usv(v: ptr GLushort) {.importc.}
-  proc glGenPathsNV(range: GLsizei): GLuint {.importc.}
-  proc glDeleteBuffersARB(n: GLsizei, buffers: ptr GLuint) {.importc.}
-  proc glProgramUniform4fvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetSharpenTexFuncSGIS(target: GLenum, points: ptr GLfloat) {.importc.}
-  proc glDrawMeshArraysSUN(mode: GLenum, first: GLint, count: GLsizei, width: GLsizei) {.importc.}
-  proc glVertexAttribs4hvNV(index: GLuint, n: GLsizei, v: ptr GLhalfNv) {.importc.}
-  proc glGetClipPlane(plane: GLenum, equation: ptr GLdouble) {.importc.}
-  proc glEvalCoord2fv(u: ptr GLfloat) {.importc.}
-  proc glAsyncMarkerSGIX(marker: GLuint) {.importc.}
-  proc glGetSynciv(sync: GLsync, pname: GLenum, bufSize: GLsizei, length: ptr GLsizei, values: ptr GLint) {.importc.}
-  proc glGetPathTexGenfvNV(texCoordSet: GLenum, pname: GLenum, value: ptr GLfloat) {.importc.}
-  proc glTexParameterf(target: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glMultiTexCoord1fvARB(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glNormalPointerListIBM(`type`: GLenum, stride: GLint, `pointer`: ptr pointer, ptrstride: GLint) {.importc.}
-  proc glFragmentLightfvSGIX(light: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glViewportArrayv(first: GLuint, count: GLsizei, v: ptr GLfloat) {.importc.}
-  proc glNormal3fVertex3fSUN(nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glMultiTexCoord2dvARB(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glCopyColorSubTable(target: GLenum, start: GLsizei, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glTexCoord2hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glGetQueryObjectiv(id: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glColor4hNV(red: GLhalfNv, green: GLhalfNv, blue: GLhalfNv, alpha: GLhalfNv) {.importc.}
-  proc glProgramUniform2fv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord4hNV(target: GLenum, s: GLhalfNv, t: GLhalfNv, r: GLhalfNv, q: GLhalfNv) {.importc.}
-  proc glWindowPos2fvMESA(v: ptr GLfloat) {.importc.}
-  proc glVertexAttrib3s(index: GLuint, x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glGetIntegerIndexedvEXT(target: GLenum, index: GLuint, data: ptr GLint) {.importc.}
-  proc glVertexAttrib4Niv(index: GLuint, v: ptr GLint) {.importc.}
-  proc glProgramLocalParameter4dvARB(target: GLenum, index: GLuint, params: ptr GLdouble) {.importc.}
-  proc glFramebufferTextureLayerEXT(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint, layer: GLint) {.importc.}
-  proc glVertexAttribI1ui(index: GLuint, x: GLuint) {.importc.}
-  proc glFogCoorddv(coord: ptr GLdouble) {.importc.}
-  proc glLightModelxv(pname: GLenum, param: ptr GLfixed) {.importc.}
-  proc glGetCombinerOutputParameterfvNV(stage: GLenum, portion: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glFramebufferReadBufferEXT(framebuffer: GLuint, mode: GLenum) {.importc.}
-  proc glGetActiveUniformsiv(program: GLuint, uniformCount: GLsizei, uniformIndices: ptr GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetProgramStringNV(id: GLuint, pname: GLenum, program: ptr GLubyte) {.importc.}
-  proc glCopyConvolutionFilter2D(target: GLenum, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glMultiTexCoord3iARB(target: GLenum, s: GLint, t: GLint, r: GLint) {.importc.}
-  proc glPushName(name: GLuint) {.importc.}
-  proc glProgramParameter4dNV(target: GLenum, index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glVertexAttrib4svARB(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glSecondaryColor3iv(v: ptr GLint) {.importc.}
-  proc glCopyColorSubTableEXT(target: GLenum, start: GLsizei, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glCallList(list: GLuint) {.importc.}
-  proc glGetMultiTexLevelParameterivEXT(texunit: GLenum, target: GLenum, level: GLint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramUniformMatrix2x4fv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glTexBumpParameterivATI(pname: GLenum, param: ptr GLint) {.importc.}
-  proc glTexGeni(coord: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glSecondaryColor3dv(v: ptr GLdouble) {.importc.}
-  proc glGetnUniformdvARB(program: GLuint, location: GLint, bufSize: GLsizei, params: ptr GLdouble) {.importc.}
-  proc glGetNamedProgramLocalParameterdvEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLdouble) {.importc.}
-  proc glGetVertexAttribPointervARB(index: GLuint, pname: GLenum, `pointer`: ptr pointer) {.importc.}
-  proc glCopyColorTable(target: GLenum, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glNamedFramebufferTextureLayerEXT(framebuffer: GLuint, attachment: GLenum, texture: GLuint, level: GLint, layer: GLint) {.importc.}
-  proc glLoadProgramNV(target: GLenum, id: GLuint, len: GLsizei, program: ptr GLubyte) {.importc.}
-  proc glAlphaFragmentOp2ATI(op: GLenum, dst: GLuint, dstMod: GLuint, arg1: GLuint, arg1Rep: GLuint, arg1Mod: GLuint, arg2: GLuint, arg2Rep: GLuint, arg2Mod: GLuint) {.importc.}
-  proc glBindLightParameterEXT(light: GLenum, value: GLenum): GLuint {.importc.}
-  proc glVertexAttrib1fv(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glLoadIdentity() {.importc.}
-  proc glFramebufferTexture2DMultisampleEXT(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint, samples: GLsizei) {.importc.}
-  proc glVertexAttrib1dvARB(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glDrawRangeElementsBaseVertex(mode: GLenum, start: GLuint, `end`: GLuint, count: GLsizei, `type`: GLenum, indices: pointer, basevertex: GLint) {.importc.}
-  proc glPixelMapfv(map: GLenum, mapsize: GLsizei, values: ptr GLfloat) {.importc.}
-  proc glPointParameterxOES(pname: GLenum, param: GLfixed) {.importc.}
-  proc glBindBufferRangeNV(target: GLenum, index: GLuint, buffer: GLuint, offset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glDepthBoundsEXT(zmin: GLclampd, zmax: GLclampd) {.importc.}
-  proc glProgramUniformMatrix2dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glSecondaryColor3s(red: GLshort, green: GLshort, blue: GLshort) {.importc.}
-  proc glEdgeFlagPointerEXT(stride: GLsizei, count: GLsizei, `pointer`: ptr GLboolean) {.importc.}
-  proc glVertexStream1fATI(stream: GLenum, x: GLfloat) {.importc.}
-  proc glUniformui64NV(location: GLint, value: GLuint64Ext) {.importc.}
-  proc glTexCoordP4uiv(`type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glTexCoord3d(s: GLdouble, t: GLdouble, r: GLdouble) {.importc.}
-  proc glDeleteProgramPipelines(n: GLsizei, pipelines: ptr GLuint) {.importc.}
-  proc glVertex2iv(v: ptr GLint) {.importc.}
-  proc glGetMultisamplefv(pname: GLenum, index: GLuint, val: ptr GLfloat) {.importc.}
-  proc glStartInstrumentsSGIX() {.importc.}
-  proc glGetOcclusionQueryivNV(id: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glDebugMessageCallback(callback: GLdebugProc, userParam: ptr pointer) {.importc.}
-  proc glPixelZoomxOES(xfactor: GLfixed, yfactor: GLfixed) {.importc.}
-  proc glTexCoord3i(s: GLint, t: GLint, r: GLint) {.importc.}
-  proc glEdgeFlagFormatNV(stride: GLsizei) {.importc.}
-  proc glProgramUniform2i(program: GLuint, location: GLint, v0: GLint, v1: GLint) {.importc.}
-  proc glColor3b(red: GLbyte, green: GLbyte, blue: GLbyte) {.importc.}
-  proc glDepthRangefOES(n: GLclampf, f: GLclampf) {.importc.}
-  proc glEndVertexShaderEXT() {.importc.}
-  proc glBindVertexArrayAPPLE(`array`: GLuint) {.importc.}
-  proc glColor4bv(v: ptr GLbyte) {.importc.}
-  proc glNamedFramebufferTexture2DEXT(framebuffer: GLuint, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glTexCoord1f(s: GLfloat) {.importc.}
-  proc glUniform3fvARB(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetQueryObjectuivARB(id: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glVertexAttrib4bv(index: GLuint, v: ptr GLbyte) {.importc.}
-  proc glGetPixelTransformParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttrib3svNV(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glDeleteQueriesEXT(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glUniform3ivARB(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glNormal3xvOES(coords: ptr GLfixed) {.importc.}
-  proc glMatrixLoadfEXT(mode: GLenum, m: ptr GLfloat) {.importc.}
-  proc glGetNamedFramebufferAttachmentParameterivEXT(framebuffer: GLuint, attachment: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glSeparableFilter2D(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, row: pointer, column: pointer) {.importc.}
-  proc glVertexAttribI3uiv(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glTextureStorageSparseAMD(texture: GLuint, target: GLenum, internalFormat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, layers: GLsizei, flags: GLbitfield) {.importc.}
-  proc glMultiDrawArraysIndirectCountARB(mode: GLenum, indirect: GLintptr, drawcount: GLintptr, maxdrawcount: GLsizei, stride: GLsizei) {.importc.}
-  proc glTranslated(x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glColorPointer(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glDrawElementsInstancedBaseVertex(mode: GLenum, count: GLsizei, `type`: GLenum, indices: pointer, instancecount: GLsizei, basevertex: GLint) {.importc.}
-  proc glBindAttribLocationARB(programObj: GLhandleArb, index: GLuint, name: cstring) {.importc.}
-  proc glTexGendv(coord: GLenum, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glGetPathCoordsNV(path: GLuint, coords: ptr GLfloat) {.importc.}
-  proc glGetMapParameterivNV(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glClientAttribDefaultEXT(mask: GLbitfield) {.importc.}
-  proc glProgramUniformMatrix4x3fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glEnable(cap: GLenum) {.importc.}
-  proc glGetVertexAttribPointervNV(index: GLuint, pname: GLenum, `pointer`: ptr pointer) {.importc.}
-  proc glBindMultiTextureEXT(texunit: GLenum, target: GLenum, texture: GLuint) {.importc.}
-  proc glGetConvolutionParameterfvEXT(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glLightModelxvOES(pname: GLenum, param: ptr GLfixed) {.importc.}
-  proc glMultiTexCoord4sv(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glGetColorTableParameterivSGI(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glFramebufferTexture2DOES(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glClearDepthxOES(depth: GLfixed) {.importc.}
-  proc glDisableClientStateiEXT(`array`: GLenum, index: GLuint) {.importc.}
-  proc glWindowPos2dARB(x: GLdouble, y: GLdouble) {.importc.}
-  proc glVertexAttrib1fvNV(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glDepthRangedNV(zNear: GLdouble, zFar: GLdouble) {.importc.}
-  proc glClear(mask: GLbitfield) {.importc.}
-  proc glUnmapTexture2DINTEL(texture: GLuint, level: GLint) {.importc.}
-  proc glSecondaryColor3ub(red: GLubyte, green: GLubyte, blue: GLubyte) {.importc.}
-  proc glVertexAttribI4bv(index: GLuint, v: ptr GLbyte) {.importc.}
-  proc glTexRenderbufferNV(target: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glColor4ubVertex3fvSUN(c: ptr GLubyte, v: ptr GLfloat) {.importc.}
-  proc glVertexAttrib2svNV(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glMultiTexCoord1ivARB(target: GLenum, v: ptr GLint) {.importc.}
-  proc glUniformMatrix3x2dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glVertexAttribL3dvEXT(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glMultiTexSubImage1DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGetBufferPointervARB(target: GLenum, pname: GLenum, params: ptr pointer) {.importc.}
-  proc glGetMultiTexLevelParameterfvEXT(texunit: GLenum, target: GLenum, level: GLint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glMultiTexParameterIuivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glGetShaderSource(shader: GLuint, bufSize: GLsizei, length: ptr GLsizei, source: cstring) {.importc.}
-  proc glStencilFunc(fun: GLenum, `ref`: GLint, mask: GLuint) {.importc.}
-  proc glVertexAttribI4bvEXT(index: GLuint, v: ptr GLbyte) {.importc.}
-  proc glVertexAttrib4NuivARB(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glIsObjectBufferATI(buffer: GLuint): GLboolean {.importc.}
-  proc glRasterPos2xOES(x: GLfixed, y: GLfixed) {.importc.}
-  proc glIsFenceNV(fence: GLuint): GLboolean {.importc.}
-  proc glGetFramebufferParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glClearBufferfv(buffer: GLenum, drawbuffer: GLint, value: ptr GLfloat) {.importc.}
-  proc glClearColorxOES(red: GLfixed, green: GLfixed, blue: GLfixed, alpha: GLfixed) {.importc.}
-  proc glVertexWeightfEXT(weight: GLfloat) {.importc.}
-  proc glExtIsProgramBinaryQCOM(program: GLuint): GLboolean {.importc.}
-  proc glTextureStorage2DMultisampleEXT(texture: GLuint, target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, fixedsamplelocations: GLboolean) {.importc.}
-  proc glGetHistogramParameterxvOES(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glVertexAttrib4dNV(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glGetPerfMonitorCounterStringAMD(group: GLuint, counter: GLuint, bufSize: GLsizei, length: ptr GLsizei, counterString: cstring) {.importc.}
-  proc glMultiTexCoord2sARB(target: GLenum, s: GLshort, t: GLshort) {.importc.}
-  proc glSpriteParameterivSGIX(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glCompressedTextureImage3DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glBufferSubData(target: GLenum, offset: GLintptr, size: GLsizeiptr, data: pointer) {.importc.}
-  proc glBlendParameteriNV(pname: GLenum, value: GLint) {.importc.}
-  proc glVertexAttrib2fvNV(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glGetVariantBooleanvEXT(id: GLuint, value: GLenum, data: ptr GLboolean) {.importc.}
-  proc glProgramParameteri(program: GLuint, pname: GLenum, value: GLint) {.importc.}
-  proc glGetLocalConstantIntegervEXT(id: GLuint, value: GLenum, data: ptr GLint) {.importc.}
-  proc glFragmentMaterialiSGIX(face: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glGetNamedStringivARB(namelen: GLint, name: cstring, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glBinormal3ivEXT(v: ptr GLint) {.importc.}
-  proc glCheckFramebufferStatusEXT(target: GLenum): GLenum {.importc.}
-  proc glVertexAttrib1fNV(index: GLuint, x: GLfloat) {.importc.}
-  proc glNamedRenderbufferStorageEXT(renderbuffer: GLuint, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glPresentFrameKeyedNV(video_slot: GLuint, minPresentTime: GLuint64Ext, beginPresentTimeId: GLuint, presentDurationId: GLuint, `type`: GLenum, target0: GLenum, fill0: GLuint, key0: GLuint, target1: GLenum, fill1: GLuint, key1: GLuint) {.importc.}
-  proc glGetObjectParameterfvARB(obj: GLhandleArb, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertex3sv(v: ptr GLshort) {.importc.}
-  proc glColor4s(red: GLshort, green: GLshort, blue: GLshort, alpha: GLshort) {.importc.}
-  proc glGetQueryObjecti64vEXT(id: GLuint, pname: GLenum, params: ptr GLint64) {.importc.}
-  proc glEvalMesh2(mode: GLenum, i1: GLint, i2: GLint, j1: GLint, j2: GLint) {.importc.}
-  proc glBeginTransformFeedbackEXT(primitiveMode: GLenum) {.importc.}
-  proc glBufferAddressRangeNV(pname: GLenum, index: GLuint, address: GLuint64Ext, length: GLsizeiptr) {.importc.}
-  proc glPointParameterfvARB(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetActiveVaryingNV(program: GLuint, index: GLuint, bufSize: GLsizei, length: ptr GLsizei, size: ptr GLsizei, `type`: ptr GLenum, name: cstring) {.importc.}
-  proc glIndexMask(mask: GLuint) {.importc.}
-  proc glVertexAttribBinding(attribindex: GLuint, bindingindex: GLuint) {.importc.}
-  proc glDeleteFencesNV(n: GLsizei, fences: ptr GLuint) {.importc.}
-  proc glVertexAttribI4ubv(index: GLuint, v: ptr GLubyte) {.importc.}
-  proc glPathParameterfvNV(path: GLuint, pname: GLenum, value: ptr GLfloat) {.importc.}
-  proc glVertexStream3fATI(stream: GLenum, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glVertexAttribs4svNV(index: GLuint, count: GLsizei, v: ptr GLshort) {.importc.}
-  proc glVertexAttrib4sNV(index: GLuint, x: GLshort, y: GLshort, z: GLshort, w: GLshort) {.importc.}
-  proc glAlphaFragmentOp3ATI(op: GLenum, dst: GLuint, dstMod: GLuint, arg1: GLuint, arg1Rep: GLuint, arg1Mod: GLuint, arg2: GLuint, arg2Rep: GLuint, arg2Mod: GLuint, arg3: GLuint, arg3Rep: GLuint, arg3Mod: GLuint) {.importc.}
-  proc glGetHistogramParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexAttribL1ui64NV(index: GLuint, x: GLuint64Ext) {.importc.}
-  proc glVertexAttribs3fvNV(index: GLuint, count: GLsizei, v: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord3ivARB(target: GLenum, v: ptr GLint) {.importc.}
-  proc glClipPlanefOES(plane: GLenum, equation: ptr GLfloat) {.importc.}
-  proc glVertex3s(x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glVertex3dv(v: ptr GLdouble) {.importc.}
-  proc glWeightPointerOES(size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glBindBufferBase(target: GLenum, index: GLuint, buffer: GLuint) {.importc.}
-  proc glIndexs(c: GLshort) {.importc.}
-  proc glTessellationFactorAMD(factor: GLfloat) {.importc.}
-  proc glColor4ubVertex3fSUN(r: GLubyte, g: GLubyte, b: GLubyte, a: GLubyte, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glPauseTransformFeedback() {.importc.}
-  proc glImageTransformParameterivHP(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glColor3dv(v: ptr GLdouble) {.importc.}
-  proc glRasterPos4sv(v: ptr GLshort) {.importc.}
-  proc glInvalidateTexSubImage(texture: GLuint, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei) {.importc.}
-  proc glNormalStream3bvATI(stream: GLenum, coords: ptr GLbyte) {.importc.}
-  proc glUniformMatrix2x4fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glMinmax(target: GLenum, internalformat: GLenum, sink: GLboolean) {.importc.}
-  proc glGetProgramStageiv(program: GLuint, shadertype: GLenum, pname: GLenum, values: ptr GLint) {.importc.}
-  proc glScalex(x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glTexBufferARB(target: GLenum, internalformat: GLenum, buffer: GLuint) {.importc.}
-  proc glDrawArraysIndirect(mode: GLenum, indirect: pointer) {.importc.}
-  proc glMatrixLoadTransposefEXT(mode: GLenum, m: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord2f(target: GLenum, s: GLfloat, t: GLfloat) {.importc.}
-  proc glDrawRangeElements(mode: GLenum, start: GLuint, `end`: GLuint, count: GLsizei, `type`: GLenum, indices: pointer) {.importc.}
-  proc glVertexAttrib4NubARB(index: GLuint, x: GLubyte, y: GLubyte, z: GLubyte, w: GLubyte) {.importc.}
-  proc glMultiTexCoord4xvOES(texture: GLenum, coords: ptr GLfixed) {.importc.}
-  proc glVertexArrayVertexAttribOffsetEXT(vaobj: GLuint, buffer: GLuint, index: GLuint, size: GLint, `type`: GLenum, normalized: GLboolean, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glVertexAttribL1i64vNV(index: GLuint, v: ptr GLint64Ext) {.importc.}
-  proc glMapBuffer(target: GLenum, access: GLenum): pointer {.importc.}
-  proc glUniform1ui(location: GLint, v0: GLuint) {.importc.}
-  proc glGetPixelMapfv(map: GLenum, values: ptr GLfloat) {.importc.}
-  proc glTexImage2DMultisampleCoverageNV(target: GLenum, coverageSamples: GLsizei, colorSamples: GLsizei, internalFormat: GLint, width: GLsizei, height: GLsizei, fixedSampleLocations: GLboolean) {.importc.}
-  proc glUniform2ivARB(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glVertexAttribI3ui(index: GLuint, x: GLuint, y: GLuint, z: GLuint) {.importc.}
-  proc glGetProgramResourceiv(program: GLuint, programInterface: GLenum, index: GLuint, propCount: GLsizei, props: ptr GLenum, bufSize: GLsizei, length: ptr GLsizei, params: ptr GLint) {.importc.}
-  proc glUniform4iv(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glVertexAttrib3f(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glClientActiveVertexStreamATI(stream: GLenum) {.importc.}
-  proc glTexCoord4fColor4fNormal3fVertex4fvSUN(tc: ptr GLfloat, c: ptr GLfloat, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glColor3xvOES(components: ptr GLfixed) {.importc.}
-  proc glVertexPointerListIBM(size: GLint, `type`: GLenum, stride: GLint, `pointer`: ptr pointer, ptrstride: GLint) {.importc.}
-  proc glProgramEnvParameter4dARB(target: GLenum, index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glGetLocalConstantFloatvEXT(id: GLuint, value: GLenum, data: ptr GLfloat) {.importc.}
-  proc glTexCoordPointerEXT(size: GLint, `type`: GLenum, stride: GLsizei, count: GLsizei, `pointer`: pointer) {.importc.}
-  proc glTexCoordPointervINTEL(size: GLint, `type`: GLenum, `pointer`: ptr pointer) {.importc.}
-  proc glSelectPerfMonitorCountersAMD(monitor: GLuint, enable: GLboolean, group: GLuint, numCounters: GLint, counterList: ptr GLuint) {.importc.}
-  proc glVertexStream4svATI(stream: GLenum, coords: ptr GLshort) {.importc.}
-  proc glColor3ui(red: GLuint, green: GLuint, blue: GLuint) {.importc.}
-  proc glBindTransformFeedbackNV(target: GLenum, id: GLuint) {.importc.}
-  proc glDeformSGIX(mask: GLbitfield) {.importc.}
-  proc glDeformationMap3fSGIX(target: GLenum, u1: GLfloat, u2: GLfloat, ustride: GLint, uorder: GLint, v1: GLfloat, v2: GLfloat, vstride: GLint, vorder: GLint, w1: GLfloat, w2: GLfloat, wstride: GLint, worder: GLint, points: ptr GLfloat) {.importc.}
-  proc glNamedBufferSubDataEXT(buffer: GLuint, offset: GLintptr, size: GLsizeiptr, data: pointer) {.importc.}
-  proc glGetNamedProgramStringEXT(program: GLuint, target: GLenum, pname: GLenum, string: pointer) {.importc.}
-  proc glCopyPathNV(resultPath: GLuint, srcPath: GLuint) {.importc.}
-  proc glMapControlPointsNV(target: GLenum, index: GLuint, `type`: GLenum, ustride: GLsizei, vstride: GLsizei, uorder: GLint, vorder: GLint, packed: GLboolean, points: pointer) {.importc.}
-  proc glGetBufferParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glUnmapObjectBufferATI(buffer: GLuint) {.importc.}
-  proc glGetProgramResourceLocation(program: GLuint, programInterface: GLenum, name: cstring): GLint {.importc.}
-  proc glUniform4i64vNV(location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glImageTransformParameterfHP(target: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glArrayObjectATI(`array`: GLenum, size: GLint, `type`: GLenum, stride: GLsizei, buffer: GLuint, offset: GLuint) {.importc.}
-  proc glBindBufferRangeEXT(target: GLenum, index: GLuint, buffer: GLuint, offset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glVertexArrayVertexAttribFormatEXT(vaobj: GLuint, attribindex: GLuint, size: GLint, `type`: GLenum, normalized: GLboolean, relativeoffset: GLuint) {.importc.}
-  proc glBindRenderbufferEXT(target: GLenum, renderbuffer: GLuint) {.importc.}
-  proc glListParameteriSGIX(list: GLuint, pname: GLenum, param: GLint) {.importc.}
-  proc glProgramUniformMatrix2dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glProgramUniform2i64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glObjectPtrLabelKHR(`ptr`: ptr pointer, length: GLsizei, label: cstring) {.importc.}
-  proc glVertexAttribL1i64NV(index: GLuint, x: GLint64Ext) {.importc.}
-  proc glMultiTexBufferEXT(texunit: GLenum, target: GLenum, internalformat: GLenum, buffer: GLuint) {.importc.}
-  proc glCoverFillPathInstancedNV(numPaths: GLsizei, pathNameType: GLenum, paths: pointer, pathBase: GLuint, coverMode: GLenum, transformType: GLenum, transformValues: ptr GLfloat) {.importc.}
-  proc glGetVertexAttribIivEXT(index: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glLightf(light: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glGetMinmaxParameterfvEXT(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glUniform1d(location: GLint, x: GLdouble) {.importc.}
-  proc glLightiv(light: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttrib2dvNV(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glNormalP3ui(`type`: GLenum, coords: GLuint) {.importc.}
-  proc glFinalCombinerInputNV(variable: GLenum, input: GLenum, mapping: GLenum, componentUsage: GLenum) {.importc.}
-  proc glUniform1uiv(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glValidateProgramARB(programObj: GLhandleArb) {.importc.}
-  proc glNormalPointer(`type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glProgramNamedParameter4fvNV(id: GLuint, len: GLsizei, name: ptr GLubyte, v: ptr GLfloat) {.importc.}
-  proc glGetBooleanv(pname: GLenum, params: ptr GLboolean) {.importc.}
-  proc glTangent3ivEXT(v: ptr GLint) {.importc.}
-  proc glTexImage3DMultisample(target: GLenum, samples: GLsizei, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, fixedsamplelocations: GLboolean) {.importc.}
-  proc glGetUniformIndices(program: GLuint, uniformCount: GLsizei, uniformNames: cstringArray, uniformIndices: ptr GLuint) {.importc.}
-  proc glVDPAUInitNV(vdpDevice: pointer, getProcAddress: pointer) {.importc.}
-  proc glGetMinmaxParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMultiTexCoord2fvARB(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glProgramEnvParametersI4ivNV(target: GLenum, index: GLuint, count: GLsizei, params: ptr GLint) {.importc.}
-  proc glClearTexSubImage(texture: GLuint, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, `type`: GLenum, data: ptr pointer) {.importc.}
-  proc glRectxOES(x1: GLfixed, y1: GLfixed, x2: GLfixed, y2: GLfixed) {.importc.}
-  proc glBlendEquationOES(mode: GLenum) {.importc.}
-  proc glFramebufferTexture(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glGetInstrumentsSGIX(): GLint {.importc.}
-  proc glFramebufferParameteri(target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glPathCoverDepthFuncNV(fun: GLenum) {.importc.}
-  proc glGetTranslatedShaderSourceANGLE(shader: GLuint, bufsize: GLsizei, length: ptr GLsizei, source: cstring) {.importc.}
-  proc glIndexfv(c: ptr GLfloat) {.importc.}
-  proc glGetActiveUniformBlockName(program: GLuint, uniformBlockIndex: GLuint, bufSize: GLsizei, length: ptr GLsizei, uniformBlockName: cstring) {.importc.}
-  proc glNormal3s(nx: GLshort, ny: GLshort, nz: GLshort) {.importc.}
-  proc glColorFragmentOp3ATI(op: GLenum, dst: GLuint, dstMask: GLuint, dstMod: GLuint, arg1: GLuint, arg1Rep: GLuint, arg1Mod: GLuint, arg2: GLuint, arg2Rep: GLuint, arg2Mod: GLuint, arg3: GLuint, arg3Rep: GLuint, arg3Mod: GLuint) {.importc.}
-  proc glGetProgramResourceLocationIndex(program: GLuint, programInterface: GLenum, name: cstring): GLint {.importc.}
-  proc glGetBooleanIndexedvEXT(target: GLenum, index: GLuint, data: ptr GLboolean) {.importc.}
-  proc glGenPerfMonitorsAMD(n: GLsizei, monitors: ptr GLuint) {.importc.}
-  proc glDrawRangeElementsEXT(mode: GLenum, start: GLuint, `end`: GLuint, count: GLsizei, `type`: GLenum, indices: pointer) {.importc.}
-  proc glFramebufferTexture3D(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint, zoffset: GLint) {.importc.}
-  proc glGetTexParameterxvOES(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glCompileShaderIncludeARB(shader: GLuint, count: GLsizei, path: cstringArray, length: ptr GLint) {.importc.}
-  proc glGetMultiTexParameterfvEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glEvalPoint2(i: GLint, j: GLint) {.importc.}
-  proc glGetProgramivNV(id: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramParameter4fNV(target: GLenum, index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glMultiTexParameterfvEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexAttrib3svARB(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glDrawElementArrayAPPLE(mode: GLenum, first: GLint, count: GLsizei) {.importc.}
-  proc glMultiTexCoord4x(texture: GLenum, s: GLfixed, t: GLfixed, r: GLfixed, q: GLfixed) {.importc.}
-  proc glUniformMatrix3dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glVertexAttribPointerARB(index: GLuint, size: GLint, `type`: GLenum, normalized: GLboolean, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glProgramUniformMatrix3x4dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glGetFloati_vEXT(pname: GLenum, index: GLuint, params: ptr GLfloat) {.importc.}
-  proc glGetObjectParameterivAPPLE(objectType: GLenum, name: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glPushGroupMarkerEXT(length: GLsizei, marker: cstring) {.importc.}
-  proc glProgramUniform4uivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glReplacementCodeuiVertex3fSUN(rc: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glTexSubImage1DEXT(target: GLenum, level: GLint, xoffset: GLint, width: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glProgramUniform1uivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glGetFenceivNV(fence: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetnCompressedTexImageARB(target: GLenum, lod: GLint, bufSize: GLsizei, img: pointer) {.importc.}
-  proc glTexGenfOES(coord: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glVertexAttrib4dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glVertexAttribL1ui64vNV(index: GLuint, v: ptr GLuint64Ext) {.importc.}
-  proc glVertexAttrib4fvARB(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glDeleteVertexArraysOES(n: GLsizei, arrays: ptr GLuint) {.importc.}
-  proc glSamplerParameterIiv(sampler: GLuint, pname: GLenum, param: ptr GLint) {.importc.}
-  proc glMapGrid1d(un: GLint, u1: GLdouble, u2: GLdouble) {.importc.}
-  proc glTranslatexOES(x: GLfixed, y: GLfixed, z: GLfixed) {.importc.}
-  proc glCullFace(mode: GLenum) {.importc.}
-  proc glPrioritizeTextures(n: GLsizei, textures: ptr GLuint, priorities: ptr GLfloat) {.importc.}
-  proc glGetSeparableFilterEXT(target: GLenum, format: GLenum, `type`: GLenum, row: pointer, column: pointer, span: pointer) {.importc.}
-  proc glVertexAttrib4NubvARB(index: GLuint, v: ptr GLubyte) {.importc.}
-  proc glGetTransformFeedbackVaryingNV(program: GLuint, index: GLuint, location: ptr GLint) {.importc.}
-  proc glTexCoord4xOES(s: GLfixed, t: GLfixed, r: GLfixed, q: GLfixed) {.importc.}
-  proc glGetProgramEnvParameterdvARB(target: GLenum, index: GLuint, params: ptr GLdouble) {.importc.}
-  proc glWindowPos2ivMESA(v: ptr GLint) {.importc.}
-  proc glGlobalAlphaFactorfSUN(factor: GLfloat) {.importc.}
-  proc glNormalStream3fvATI(stream: GLenum, coords: ptr GLfloat) {.importc.}
-  proc glRasterPos4i(x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glReleaseShaderCompiler() {.importc.}
-  proc glProgramUniformMatrix4fvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glCopyMultiTexImage1DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, border: GLint) {.importc.}
-  proc glColorTableParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glSecondaryColor3bvEXT(v: ptr GLbyte) {.importc.}
-  proc glMap1xOES(target: GLenum, u1: GLfixed, u2: GLfixed, stride: GLint, order: GLint, points: GLfixed) {.importc.}
-  proc glVertexStream1svATI(stream: GLenum, coords: ptr GLshort) {.importc.}
-  proc glIsRenderbuffer(renderbuffer: GLuint): GLboolean {.importc.}
-  proc glPatchParameterfv(pname: GLenum, values: ptr GLfloat) {.importc.}
-  proc glProgramUniformMatrix4dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glVertexAttrib4ubNV(index: GLuint, x: GLubyte, y: GLubyte, z: GLubyte, w: GLubyte) {.importc.}
-  proc glVertex2i(x: GLint, y: GLint) {.importc.}
-  proc glPushClientAttrib(mask: GLbitfield) {.importc.}
-  proc glDrawArraysEXT(mode: GLenum, first: GLint, count: GLsizei) {.importc.}
-  proc glCreateProgram(): GLuint {.importc.}
-  proc glPolygonStipple(mask: ptr GLubyte) {.importc.}
-  proc glGetColorTableEXT(target: GLenum, format: GLenum, `type`: GLenum, data: pointer) {.importc.}
-  proc glSharpenTexFuncSGIS(target: GLenum, n: GLsizei, points: ptr GLfloat) {.importc.}
-  proc glNamedFramebufferTextureEXT(framebuffer: GLuint, attachment: GLenum, texture: GLuint, level: GLint) {.importc.}
-  proc glWindowPos3fvMESA(v: ptr GLfloat) {.importc.}
-  proc glBinormal3iEXT(bx: GLint, by: GLint, bz: GLint) {.importc.}
-  proc glEnableClientStateiEXT(`array`: GLenum, index: GLuint) {.importc.}
-  proc glProgramUniform3iv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glProgramUniform1dEXT(program: GLuint, location: GLint, x: GLdouble) {.importc.}
-  proc glPollInstrumentsSGIX(marker_p: ptr GLint): GLint {.importc.}
-  proc glSecondaryColor3f(red: GLfloat, green: GLfloat, blue: GLfloat) {.importc.}
-  proc glDeleteTransformFeedbacks(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glCoverStrokePathInstancedNV(numPaths: GLsizei, pathNameType: GLenum, paths: pointer, pathBase: GLuint, coverMode: GLenum, transformType: GLenum, transformValues: ptr GLfloat) {.importc.}
-  proc glIsTextureHandleResidentARB(handle: GLuint64): GLboolean {.importc.}
-  proc glVariantsvEXT(id: GLuint, `addr`: ptr GLshort) {.importc.}
-  proc glTexCoordFormatNV(size: GLint, `type`: GLenum, stride: GLsizei) {.importc.}
-  proc glTexStorage3DEXT(target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) {.importc.}
-  proc glUniform2ui(location: GLint, v0: GLuint, v1: GLuint) {.importc.}
-  proc glReplacementCodePointerSUN(`type`: GLenum, stride: GLsizei, `pointer`: ptr pointer) {.importc.}
-  proc glFramebufferTextureLayerARB(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint, layer: GLint) {.importc.}
-  proc glBinormal3dvEXT(v: ptr GLdouble) {.importc.}
-  proc glProgramUniform2ui64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glGetnConvolutionFilterARB(target: GLenum, format: GLenum, `type`: GLenum, bufSize: GLsizei, image: pointer) {.importc.}
-  proc glStopInstrumentsSGIX(marker: GLint) {.importc.}
-  proc glVertexAttrib1svNV(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glVertexAttribs2fvNV(index: GLuint, count: GLsizei, v: ptr GLfloat) {.importc.}
-  proc glGetInternalformativ(target: GLenum, internalformat: GLenum, pname: GLenum, bufSize: GLsizei, params: ptr GLint) {.importc.}
-  proc glIsProgramPipelineEXT(pipeline: GLuint): GLboolean {.importc.}
-  proc glMatrixIndexubvARB(size: GLint, indices: ptr GLubyte) {.importc.}
-  proc glTexCoord4bOES(s: GLbyte, t: GLbyte, r: GLbyte, q: GLbyte) {.importc.}
-  proc glSecondaryColor3us(red: GLushort, green: GLushort, blue: GLushort) {.importc.}
-  proc glGlobalAlphaFactorubSUN(factor: GLubyte) {.importc.}
-  proc glNamedStringARB(`type`: GLenum, namelen: GLint, name: cstring, stringlen: GLint, string: cstring) {.importc.}
-  proc glGetAttachedShaders(program: GLuint, maxCount: GLsizei, count: ptr GLsizei, shaders: ptr GLuint) {.importc.}
-  proc glMatrixRotatefEXT(mode: GLenum, angle: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glVertexStream3ivATI(stream: GLenum, coords: ptr GLint) {.importc.}
-  proc glMatrixIndexuivARB(size: GLint, indices: ptr GLuint) {.importc.}
-  proc glMatrixRotatedEXT(mode: GLenum, angle: GLdouble, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glPathFogGenNV(genMode: GLenum) {.importc.}
-  proc glMultiTexCoord4hvNV(target: GLenum, v: ptr GLhalfNv) {.importc.}
-  proc glVertexAttribIPointer(index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glMultiTexCoord3bOES(texture: GLenum, s: GLbyte, t: GLbyte, r: GLbyte) {.importc.}
-  proc glResizeBuffersMESA() {.importc.}
-  proc glPrimitiveRestartIndexNV(index: GLuint) {.importc.}
-  proc glProgramUniform4f(program: GLuint, location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat, v3: GLfloat) {.importc.}
-  proc glColor4ubVertex2fSUN(r: GLubyte, g: GLubyte, b: GLubyte, a: GLubyte, x: GLfloat, y: GLfloat) {.importc.}
-  proc glGetColorTableParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glDepthRangef(n: GLfloat, f: GLfloat) {.importc.}
-  proc glVertexArrayVertexOffsetEXT(vaobj: GLuint, buffer: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glMatrixLoaddEXT(mode: GLenum, m: ptr GLdouble) {.importc.}
-  proc glVariantfvEXT(id: GLuint, `addr`: ptr GLfloat) {.importc.}
-  proc glReplacementCodeuiTexCoord2fVertex3fvSUN(rc: ptr GLuint, tc: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glSamplePatternSGIS(pattern: GLenum) {.importc.}
-  proc glProgramUniform3i64NV(program: GLuint, location: GLint, x: GLint64Ext, y: GLint64Ext, z: GLint64Ext) {.importc.}
-  proc glUniform3uivEXT(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glGetImageTransformParameterivHP(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glPopMatrix() {.importc.}
-  proc glVertexAttrib3sARB(index: GLuint, x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glGenQueriesEXT(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glGetQueryObjectui64v(id: GLuint, pname: GLenum, params: ptr GLuint64) {.importc.}
-  proc glWeightusvARB(size: GLint, weights: ptr GLushort) {.importc.}
-  proc glWindowPos2sARB(x: GLshort, y: GLshort) {.importc.}
-  proc glGetTextureLevelParameterivEXT(texture: GLuint, target: GLenum, level: GLint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glBufferParameteriAPPLE(target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glMultiModeDrawArraysIBM(mode: ptr GLenum, first: ptr GLint, count: ptr GLsizei, primcount: GLsizei, modestride: GLint) {.importc.}
-  proc glUniformMatrix2x3fv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLfloat) {.importc.}
-  proc glTangentPointerEXT(`type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glResetMinmax(target: GLenum) {.importc.}
-  proc glVertexAttribP1uiv(index: GLuint, `type`: GLenum, normalized: GLboolean, value: ptr GLuint) {.importc.}
-  proc glPixelMapx(map: GLenum, size: GLint, values: ptr GLfixed) {.importc.}
-  proc glPixelStoref(pname: GLenum, param: GLfloat) {.importc.}
-  proc glBinormal3dEXT(bx: GLdouble, by: GLdouble, bz: GLdouble) {.importc.}
-  proc glVertexAttribs1hvNV(index: GLuint, n: GLsizei, v: ptr GLhalfNv) {.importc.}
-  proc glVertexAttrib4usvARB(index: GLuint, v: ptr GLushort) {.importc.}
-  proc glUnmapBuffer(target: GLenum): GLboolean {.importc.}
-  proc glFlushRasterSGIX() {.importc.}
-  proc glColor3uiv(v: ptr GLuint) {.importc.}
-  proc glInvalidateBufferSubData(buffer: GLuint, offset: GLintptr, length: GLsizeiptr) {.importc.}
-  proc glPassThroughxOES(token: GLfixed) {.importc.}
-  proc glLockArraysEXT(first: GLint, count: GLsizei) {.importc.}
-  proc glStencilFuncSeparateATI(frontfunc: GLenum, backfunc: GLenum, `ref`: GLint, mask: GLuint) {.importc.}
-  proc glProgramUniform3dvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glGenTransformFeedbacks(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glCopyTexSubImage3DOES(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glIsNamedBufferResidentNV(buffer: GLuint): GLboolean {.importc.}
-  proc glSampleMaskIndexedNV(index: GLuint, mask: GLbitfield) {.importc.}
-  proc glVDPAUSurfaceAccessNV(surface: GLvdpauSurfaceNv, access: GLenum) {.importc.}
-  proc glProgramUniform3dv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLdouble) {.importc.}
-  proc glDeleteProgram(program: GLuint) {.importc.}
-  proc glConvolutionFilter1D(target: GLenum, internalformat: GLenum, width: GLsizei, format: GLenum, `type`: GLenum, image: pointer) {.importc.}
-  proc glVertex2f(x: GLfloat, y: GLfloat) {.importc.}
-  proc glWindowPos4dvMESA(v: ptr GLdouble) {.importc.}
-  proc glColor4us(red: GLushort, green: GLushort, blue: GLushort, alpha: GLushort) {.importc.}
-  proc glColorMask(red: GLboolean, green: GLboolean, blue: GLboolean, alpha: GLboolean) {.importc.}
-  proc glGetTexEnviv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glProgramUniform3ivEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glSecondaryColor3i(red: GLint, green: GLint, blue: GLint) {.importc.}
-  proc glGetSamplerParameteriv(sampler: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glDeleteFramebuffersEXT(n: GLsizei, framebuffers: ptr GLuint) {.importc.}
-  proc glCompressedTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glVertex2s(x: GLshort, y: GLshort) {.importc.}
-  proc glIsQuery(id: GLuint): GLboolean {.importc.}
-  proc glFogxv(pname: GLenum, param: ptr GLfixed) {.importc.}
-  proc glAreProgramsResidentNV(n: GLsizei, programs: ptr GLuint, residences: ptr GLboolean): GLboolean {.importc.}
-  proc glShaderSourceARB(shaderObj: GLhandleArb, count: GLsizei, string: cstringArray, length: ptr GLint) {.importc.}
-  proc glPointSizexOES(size: GLfixed) {.importc.}
-  proc glPixelTransferf(pname: GLenum, param: GLfloat) {.importc.}
-  proc glExtractComponentEXT(res: GLuint, src: GLuint, num: GLuint) {.importc.}
-  proc glUniform1fv(location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetNamedStringARB(namelen: GLint, name: cstring, bufSize: GLsizei, stringlen: ptr GLint, string: cstring) {.importc.}
-  proc glGetProgramBinaryOES(program: GLuint, bufSize: GLsizei, length: ptr GLsizei, binaryFormat: ptr GLenum, binary: pointer) {.importc.}
-  proc glDeleteOcclusionQueriesNV(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glEnableClientState(`array`: GLenum) {.importc.}
-  proc glProgramBufferParametersIuivNV(target: GLenum, bindingIndex: GLuint, wordIndex: GLuint, count: GLsizei, params: ptr GLuint) {.importc.}
-  proc glProgramUniform2ui(program: GLuint, location: GLint, v0: GLuint, v1: GLuint) {.importc.}
-  proc glReplacementCodeuiSUN(code: GLuint) {.importc.}
-  proc glMultMatrixd(m: ptr GLdouble) {.importc.}
-  proc glInvalidateSubFramebuffer(target: GLenum, numAttachments: GLsizei, attachments: ptr GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glGenerateMultiTexMipmapEXT(texunit: GLenum, target: GLenum) {.importc.}
-  proc glDepthRangex(n: GLfixed, f: GLfixed) {.importc.}
-  proc glGetInteger64i_v(target: GLenum, index: GLuint, data: ptr GLint64) {.importc.}
-  proc glDrawBuffers(n: GLsizei, bufs: ptr GLenum) {.importc.}
-  proc glGetPointervEXT(pname: GLenum, params: ptr pointer) {.importc.}
-  proc glFogxvOES(pname: GLenum, param: ptr GLfixed) {.importc.}
-  proc glTexCoordP2uiv(`type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glVertexFormatNV(size: GLint, `type`: GLenum, stride: GLsizei) {.importc.}
-  proc glColorPointervINTEL(size: GLint, `type`: GLenum, `pointer`: ptr pointer) {.importc.}
-  proc glGetMultiTexParameterivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMultiTexCoordP4uiv(texture: GLenum, `type`: GLenum, coords: ptr GLuint) {.importc.}
-  proc glResetMinmaxEXT(target: GLenum) {.importc.}
-  proc glCopyBufferSubData(readTarget: GLenum, writeTarget: GLenum, readOffset: GLintptr, writeOffset: GLintptr, size: GLsizeiptr) {.importc.}
-  proc glSecondaryColor3sv(v: ptr GLshort) {.importc.}
-  proc glPixelStorex(pname: GLenum, param: GLfixed) {.importc.}
-  proc glWaitSync(sync: GLsync, flags: GLbitfield, timeout: GLuint64) {.importc.}
-  proc glVertexAttribI1iv(index: GLuint, v: ptr GLint) {.importc.}
-  proc glColorSubTableEXT(target: GLenum, start: GLsizei, count: GLsizei, format: GLenum, `type`: GLenum, data: pointer) {.importc.}
-  proc glGetDoublev(pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glMultiTexParameterivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMultiTexCoord4svARB(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glColorPointerListIBM(size: GLint, `type`: GLenum, stride: GLint, `pointer`: ptr pointer, ptrstride: GLint) {.importc.}
-  proc glScissorIndexed(index: GLuint, left: GLint, bottom: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glStencilOpSeparateATI(face: GLenum, sfail: GLenum, dpfail: GLenum, dppass: GLenum) {.importc.}
-  proc glLoadName(name: GLuint) {.importc.}
-  proc glIsTransformFeedbackNV(id: GLuint): GLboolean {.importc.}
-  proc glPopDebugGroup() {.importc.}
-  proc glClipPlanef(p: GLenum, eqn: ptr GLfloat) {.importc.}
-  proc glDeleteFencesAPPLE(n: GLsizei, fences: ptr GLuint) {.importc.}
-  proc glGetQueryObjecti64v(id: GLuint, pname: GLenum, params: ptr GLint64) {.importc.}
-  proc glAlphaFunc(fun: GLenum, `ref`: GLfloat) {.importc.}
-  proc glIndexPointerEXT(`type`: GLenum, stride: GLsizei, count: GLsizei, `pointer`: pointer) {.importc.}
-  proc glVertexAttribI3ivEXT(index: GLuint, v: ptr GLint) {.importc.}
-  proc glIndexub(c: GLubyte) {.importc.}
-  proc glVertexP2uiv(`type`: GLenum, value: ptr GLuint) {.importc.}
-  proc glProgramUniform1uiv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glDebugMessageInsertKHR(source: GLenum, `type`: GLenum, id: GLuint, severity: GLenum, length: GLsizei, buf: cstring) {.importc.}
-  proc glColor4b(red: GLbyte, green: GLbyte, blue: GLbyte, alpha: GLbyte) {.importc.}
-  proc glRenderbufferStorageMultisampleAPPLE(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glMinSampleShading(value: GLfloat) {.importc.}
-  proc glBindProgramNV(target: GLenum, id: GLuint) {.importc.}
-  proc glWindowPos3dMESA(x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glEdgeFlagPointer(stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glGetFragDataIndex(program: GLuint, name: cstring): GLint {.importc.}
-  proc glTexCoord3hNV(s: GLhalfNv, t: GLhalfNv, r: GLhalfNv) {.importc.}
-  proc glMultiDrawArraysIndirectAMD(mode: GLenum, indirect: pointer, primcount: GLsizei, stride: GLsizei) {.importc.}
-  proc glFragmentColorMaterialSGIX(face: GLenum, mode: GLenum) {.importc.}
-  proc glTexGenf(coord: GLenum, pname: GLenum, param: GLfloat) {.importc.}
-  proc glVertexAttrib4ubvARB(index: GLuint, v: ptr GLubyte) {.importc.}
-  proc glClearBufferiv(buffer: GLenum, drawbuffer: GLint, value: ptr GLint) {.importc.}
-  proc glGenQueriesARB(n: GLsizei, ids: ptr GLuint) {.importc.}
-  proc glRectdv(v1: ptr GLdouble, v2: ptr GLdouble) {.importc.}
-  proc glBlendEquationSeparateEXT(modeRgb: GLenum, modeAlpha: GLenum) {.importc.}
-  proc glTestFenceAPPLE(fence: GLuint): GLboolean {.importc.}
-  proc glTexGeniv(coord: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glPolygonMode(face: GLenum, mode: GLenum) {.importc.}
-  proc glFrameZoomSGIX(factor: GLint) {.importc.}
-  proc glReplacementCodeuiTexCoord2fVertex3fSUN(rc: GLuint, s: GLfloat, t: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glUniformSubroutinesuiv(shadertype: GLenum, count: GLsizei, indices: ptr GLuint) {.importc.}
-  proc glBeginQueryIndexed(target: GLenum, index: GLuint, id: GLuint) {.importc.}
-  proc glMultiTexGeniEXT(texunit: GLenum, coord: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glRasterPos3fv(v: ptr GLfloat) {.importc.}
-  proc glMapObjectBufferATI(buffer: GLuint): pointer {.importc.}
-  proc glIndexiv(c: ptr GLint) {.importc.}
-  proc glVertexAttribLPointer(index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glMultiTexCoord4s(target: GLenum, s: GLshort, t: GLshort, r: GLshort, q: GLshort) {.importc.}
-  proc glSecondaryColorP3uiv(`type`: GLenum, color: ptr GLuint) {.importc.}
-  proc glNormalFormatNV(`type`: GLenum, stride: GLsizei) {.importc.}
-  proc glVertex4i(x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glUniform1ui64NV(location: GLint, x: GLuint64Ext) {.importc.}
-  proc glScissorIndexedv(index: GLuint, v: ptr GLint) {.importc.}
-  proc glProgramUniform1i(program: GLuint, location: GLint, v0: GLint) {.importc.}
-  proc glCompressedMultiTexSubImage3DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glFinishTextureSUNX() {.importc.}
-  proc glFramebufferTexture3DEXT(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint, zoffset: GLint) {.importc.}
-  proc glSetInvariantEXT(id: GLuint, `type`: GLenum, `addr`: pointer) {.importc.}
-  proc glGetTexParameterIivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMultiTexCoordP3ui(texture: GLenum, `type`: GLenum, coords: GLuint) {.importc.}
-  proc glMultiTexCoord3f(target: GLenum, s: GLfloat, t: GLfloat, r: GLfloat) {.importc.}
-  proc glNormalStream3fATI(stream: GLenum, nx: GLfloat, ny: GLfloat, nz: GLfloat) {.importc.}
-  proc glActiveShaderProgram(pipeline: GLuint, program: GLuint) {.importc.}
-  proc glDisableVertexArrayEXT(vaobj: GLuint, `array`: GLenum) {.importc.}
-  proc glVertexAttribI3iv(index: GLuint, v: ptr GLint) {.importc.}
-  proc glProvokingVertex(mode: GLenum) {.importc.}
-  proc glTexCoord1fv(v: ptr GLfloat) {.importc.}
-  proc glVertexAttrib3fv(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glWindowPos3iv(v: ptr GLint) {.importc.}
-  proc glProgramUniform4ui64NV(program: GLuint, location: GLint, x: GLuint64Ext, y: GLuint64Ext, z: GLuint64Ext, w: GLuint64Ext) {.importc.}
-  proc glProgramUniform2d(program: GLuint, location: GLint, v0: GLdouble, v1: GLdouble) {.importc.}
-  proc glDebugMessageInsertARB(source: GLenum, `type`: GLenum, id: GLuint, severity: GLenum, length: GLsizei, buf: cstring) {.importc.}
-  proc glMultiTexSubImage3DEXT(texunit: GLenum, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glMap1d(target: GLenum, u1: GLdouble, u2: GLdouble, stride: GLint, order: GLint, points: ptr GLdouble) {.importc.}
-  proc glDeleteShader(shader: GLuint) {.importc.}
-  proc glTexturePageCommitmentEXT(texture: GLuint, target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, resident: GLboolean) {.importc.}
-  proc glFramebufferDrawBufferEXT(framebuffer: GLuint, mode: GLenum) {.importc.}
-  proc glTexCoord2fNormal3fVertex3fSUN(s: GLfloat, t: GLfloat, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glDeleteProgramsNV(n: GLsizei, programs: ptr GLuint) {.importc.}
-  proc glPointAlongPathNV(path: GLuint, startSegment: GLsizei, numSegments: GLsizei, distance: GLfloat, x: ptr GLfloat, y: ptr GLfloat, tangentX: ptr GLfloat, tangentY: ptr GLfloat): GLboolean {.importc.}
-  proc glTexCoord1d(s: GLdouble) {.importc.}
-  proc glStencilStrokePathNV(path: GLuint, reference: GLint, mask: GLuint) {.importc.}
-  proc glQueryMatrixxOES(mantissa: ptr GLfixed, exponent: ptr GLint): GLbitfield {.importc.}
-  proc glGetNamedProgramLocalParameterIuivEXT(program: GLuint, target: GLenum, index: GLuint, params: ptr GLuint) {.importc.}
-  proc glGenerateMipmapOES(target: GLenum) {.importc.}
-  proc glRenderbufferStorageMultisampleIMG(target: GLenum, samples: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glVertexBlendEnviATI(pname: GLenum, param: GLint) {.importc.}
-  proc glPushAttrib(mask: GLbitfield) {.importc.}
-  proc glShaderOp3EXT(op: GLenum, res: GLuint, arg1: GLuint, arg2: GLuint, arg3: GLuint) {.importc.}
-  proc glEnableVertexAttribArray(index: GLuint) {.importc.}
-  proc glVertexAttrib4Nbv(index: GLuint, v: ptr GLbyte) {.importc.}
-  proc glExtGetBuffersQCOM(buffers: ptr GLuint, maxBuffers: GLint, numBuffers: ptr GLint) {.importc.}
-  proc glCopyTexSubImage3D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glDeletePerfMonitorsAMD(n: GLsizei, monitors: ptr GLuint) {.importc.}
-  proc glGetTrackMatrixivNV(target: GLenum, address: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glEndConditionalRender() {.importc.}
-  proc glVertexAttribL3i64NV(index: GLuint, x: GLint64Ext, y: GLint64Ext, z: GLint64Ext) {.importc.}
-  proc glProgramLocalParametersI4ivNV(target: GLenum, index: GLuint, count: GLsizei, params: ptr GLint) {.importc.}
-  proc glFlush() {.importc.}
-  proc glGetNamedBufferParameterui64vNV(buffer: GLuint, pname: GLenum, params: ptr GLuint64Ext) {.importc.}
-  proc glGetVertexArrayIntegeri_vEXT(vaobj: GLuint, index: GLuint, pname: GLenum, param: ptr GLint) {.importc.}
-  proc glReadnPixelsEXT(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, bufSize: GLsizei, data: pointer) {.importc.}
-  proc glMultiTexImage1DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGetVaryingLocationNV(program: GLuint, name: cstring): GLint {.importc.}
-  proc glMultiTexCoord4fvARB(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord3iv(target: GLenum, v: ptr GLint) {.importc.}
-  proc glVertexAttribL2dvEXT(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glTexParameterxOES(target: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glSecondaryColor3uivEXT(v: ptr GLuint) {.importc.}
-  proc glReadnPixelsARB(x: GLint, y: GLint, width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, bufSize: GLsizei, data: pointer) {.importc.}
-  proc glCopyTexSubImage1DEXT(target: GLenum, level: GLint, xoffset: GLint, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glGetDoublei_vEXT(pname: GLenum, index: GLuint, params: ptr GLdouble) {.importc.}
-  proc glVariantPointerEXT(id: GLuint, `type`: GLenum, stride: GLuint, `addr`: pointer) {.importc.}
-  proc glProgramUniform3ui64vNV(program: GLuint, location: GLint, count: GLsizei, value: ptr GLuint64Ext) {.importc.}
-  proc glTexCoord2fColor3fVertex3fvSUN(tc: ptr GLfloat, c: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glProgramUniform3fv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glBindFragDataLocationIndexed(program: GLuint, colorNumber: GLuint, index: GLuint, name: cstring) {.importc.}
-  proc glGetnSeparableFilterARB(target: GLenum, format: GLenum, `type`: GLenum, rowBufSize: GLsizei, row: pointer, columnBufSize: GLsizei, column: pointer, span: pointer) {.importc.}
-  proc glTextureParameteriEXT(texture: GLuint, target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glGetUniformuivEXT(program: GLuint, location: GLint, params: ptr GLuint) {.importc.}
-  proc glFragmentMaterialivSGIX(face: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMultiTexCoord1svARB(target: GLenum, v: ptr GLshort) {.importc.}
-  proc glClientActiveTextureARB(texture: GLenum) {.importc.}
-  proc glVertexAttrib1fARB(index: GLuint, x: GLfloat) {.importc.}
-  proc glVertexAttrib4NbvARB(index: GLuint, v: ptr GLbyte) {.importc.}
-  proc glRasterPos2d(x: GLdouble, y: GLdouble) {.importc.}
-  proc glMultiTexCoord4iARB(target: GLenum, s: GLint, t: GLint, r: GLint, q: GLint) {.importc.}
-  proc glGetPixelTexGenParameterfvSGIS(pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexAttribL2dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glGetProgramStringARB(target: GLenum, pname: GLenum, string: pointer) {.importc.}
-  proc glRasterPos2i(x: GLint, y: GLint) {.importc.}
-  proc glTexCoord2fColor4fNormal3fVertex3fvSUN(tc: ptr GLfloat, c: ptr GLfloat, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord3s(target: GLenum, s: GLshort, t: GLshort, r: GLshort) {.importc.}
-  proc glMultTransposeMatrixd(m: ptr GLdouble) {.importc.}
-  proc glActiveVaryingNV(program: GLuint, name: cstring) {.importc.}
-  proc glProgramUniform1f(program: GLuint, location: GLint, v0: GLfloat) {.importc.}
-  proc glGetActiveSubroutineName(program: GLuint, shadertype: GLenum, index: GLuint, bufsize: GLsizei, length: ptr GLsizei, name: cstring) {.importc.}
-  proc glClipPlanex(plane: GLenum, equation: ptr GLfixed) {.importc.}
-  proc glMultiTexCoord4iv(target: GLenum, v: ptr GLint) {.importc.}
-  proc glTransformFeedbackVaryingsEXT(program: GLuint, count: GLsizei, varyings: cstringArray, bufferMode: GLenum) {.importc.}
-  proc glBlendEquationSeparateiARB(buf: GLuint, modeRgb: GLenum, modeAlpha: GLenum) {.importc.}
-  proc glVertex2sv(v: ptr GLshort) {.importc.}
-  proc glAccumxOES(op: GLenum, value: GLfixed) {.importc.}
-  proc glProgramLocalParameter4dARB(target: GLenum, index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glIsRenderbufferEXT(renderbuffer: GLuint): GLboolean {.importc.}
-  proc glMultiDrawElementsIndirectAMD(mode: GLenum, `type`: GLenum, indirect: pointer, primcount: GLsizei, stride: GLsizei) {.importc.}
-  proc glVertexAttribI4uiEXT(index: GLuint, x: GLuint, y: GLuint, z: GLuint, w: GLuint) {.importc.}
-  proc glVertex4fv(v: ptr GLfloat) {.importc.}
-  proc glGenerateMipmapEXT(target: GLenum) {.importc.}
-  proc glVertexP3ui(`type`: GLenum, value: GLuint) {.importc.}
-  proc glTexCoord2dv(v: ptr GLdouble) {.importc.}
-  proc glFlushMappedBufferRange(target: GLenum, offset: GLintptr, length: GLsizeiptr) {.importc.}
-  proc glTrackMatrixNV(target: GLenum, address: GLuint, matrix: GLenum, transform: GLenum) {.importc.}
-  proc glFragmentLightModeliSGIX(pname: GLenum, param: GLint) {.importc.}
-  proc glVertexAttrib4Nusv(index: GLuint, v: ptr GLushort) {.importc.}
-  proc glScalef(x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glLightxvOES(light: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glTextureParameterivEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glCompressedMultiTexImage3DEXT(texunit: GLenum, target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, bits: pointer) {.importc.}
-  proc glVertexAttribL1d(index: GLuint, x: GLdouble) {.importc.}
-  proc glVertexAttrib3fARB(index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glVertexAttrib3hvNV(index: GLuint, v: ptr GLhalfNv) {.importc.}
-  proc glSpriteParameteriSGIX(pname: GLenum, param: GLint) {.importc.}
-  proc glFrustumxOES(l: GLfixed, r: GLfixed, b: GLfixed, t: GLfixed, n: GLfixed, f: GLfixed) {.importc.}
-  proc glGetnMapdvARB(target: GLenum, query: GLenum, bufSize: GLsizei, v: ptr GLdouble) {.importc.}
-  proc glGetMinmaxEXT(target: GLenum, reset: GLboolean, format: GLenum, `type`: GLenum, values: pointer) {.importc.}
-  proc glProgramUniformHandleui64NV(program: GLuint, location: GLint, value: GLuint64) {.importc.}
-  proc glWindowPos4fvMESA(v: ptr GLfloat) {.importc.}
-  proc glExtGetTexturesQCOM(textures: ptr GLuint, maxTextures: GLint, numTextures: ptr GLint) {.importc.}
-  proc glProgramSubroutineParametersuivNV(target: GLenum, count: GLsizei, params: ptr GLuint) {.importc.}
-  proc glSampleCoveragexOES(value: GLclampx, invert: GLboolean) {.importc.}
-  proc glMultiTexEnvivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetFinalCombinerInputParameterfvNV(variable: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glLightModeliv(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glUniform4f(location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat, v3: GLfloat) {.importc.}
-  proc glDepthRange(near: GLdouble, far: GLdouble) {.importc.}
-  proc glProgramUniformMatrix4x3dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glProgramUniform4fv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glGetTexParameterIiv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttribs4dvNV(index: GLuint, count: GLsizei, v: ptr GLdouble) {.importc.}
-  proc glConvolutionParameteri(target: GLenum, pname: GLenum, params: GLint) {.importc.}
-  proc glVertexAttribI4uiv(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glEvalCoord1dv(u: ptr GLdouble) {.importc.}
-  proc glIsFramebuffer(framebuffer: GLuint): GLboolean {.importc.}
-  proc glEvalCoord2d(u: GLdouble, v: GLdouble) {.importc.}
-  proc glClearDepthf(d: GLfloat) {.importc.}
-  proc glCompressedTexSubImage2D(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, width: GLsizei, height: GLsizei, format: GLenum, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glProgramUniformMatrix3x2dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glGetTexParameterxv(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glBinormal3fEXT(bx: GLfloat, by: GLfloat, bz: GLfloat) {.importc.}
-  proc glProgramParameteriARB(program: GLuint, pname: GLenum, value: GLint) {.importc.}
-  proc glWindowPos3ivMESA(v: ptr GLint) {.importc.}
-  proc glReplacementCodeuiColor4fNormal3fVertex3fvSUN(rc: ptr GLuint, c: ptr GLfloat, n: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glPresentFrameDualFillNV(video_slot: GLuint, minPresentTime: GLuint64Ext, beginPresentTimeId: GLuint, presentDurationId: GLuint, `type`: GLenum, target0: GLenum, fill0: GLuint, target1: GLenum, fill1: GLuint, target2: GLenum, fill2: GLuint, target3: GLenum, fill3: GLuint) {.importc.}
-  proc glIndexPointerListIBM(`type`: GLenum, stride: GLint, `pointer`: ptr pointer, ptrstride: GLint) {.importc.}
-  proc glVertexStream2dATI(stream: GLenum, x: GLdouble, y: GLdouble) {.importc.}
-  proc glUniformMatrix3x4dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glMapNamedBufferRangeEXT(buffer: GLuint, offset: GLintptr, length: GLsizeiptr, access: GLbitfield): pointer {.importc.}
-  proc glColor4sv(v: ptr GLshort) {.importc.}
-  proc glStencilFillPathNV(path: GLuint, fillMode: GLenum, mask: GLuint) {.importc.}
-  proc glGetVertexAttribfvARB(index: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glWindowPos3dv(v: ptr GLdouble) {.importc.}
-  proc glHintPGI(target: GLenum, mode: GLint) {.importc.}
-  proc glVertexAttribs3hvNV(index: GLuint, n: GLsizei, v: ptr GLhalfNv) {.importc.}
-  proc glProgramUniform1i64NV(program: GLuint, location: GLint, x: GLint64Ext) {.importc.}
-  proc glReplacementCodeuiColor3fVertex3fSUN(rc: GLuint, r: GLfloat, g: GLfloat, b: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glUniform2iARB(location: GLint, v0: GLint, v1: GLint) {.importc.}
-  proc glViewport(x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glBlendFuncSeparateIndexedAMD(buf: GLuint, srcRgb: GLenum, dstRgb: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) {.importc.}
-  proc glColor3us(red: GLushort, green: GLushort, blue: GLushort) {.importc.}
-  proc glVertexAttrib2hvNV(index: GLuint, v: ptr GLhalfNv) {.importc.}
-  proc glGenerateMipmap(target: GLenum) {.importc.}
-  proc glGetProgramEnvParameterIuivNV(target: GLenum, index: GLuint, params: ptr GLuint) {.importc.}
-  proc glBlendEquationiARB(buf: GLuint, mode: GLenum) {.importc.}
-  proc glReadBufferNV(mode: GLenum) {.importc.}
-  proc glProvokingVertexEXT(mode: GLenum) {.importc.}
-  proc glPointParameterivNV(pname: GLenum, params: ptr GLint) {.importc.}
-  proc glBlitFramebufferANGLE(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) {.importc.}
-  proc glGetObjectParameterivARB(obj: GLhandleArb, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetSubroutineIndex(program: GLuint, shadertype: GLenum, name: cstring): GLuint {.importc.}
-  proc glMap2d(target: GLenum, u1: GLdouble, u2: GLdouble, ustride: GLint, uorder: GLint, v1: GLdouble, v2: GLdouble, vstride: GLint, vorder: GLint, points: ptr GLdouble) {.importc.}
-  proc glRectfv(v1: ptr GLfloat, v2: ptr GLfloat) {.importc.}
-  proc glDepthRangeArrayv(first: GLuint, count: GLsizei, v: ptr GLdouble) {.importc.}
-  proc glMultiTexParameteriEXT(texunit: GLenum, target: GLenum, pname: GLenum, param: GLint) {.importc.}
-  proc glTexStorageSparseAMD(target: GLenum, internalFormat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, layers: GLsizei, flags: GLbitfield) {.importc.}
-  proc glGenerateTextureMipmapEXT(texture: GLuint, target: GLenum) {.importc.}
-  proc glCopyConvolutionFilter1D(target: GLenum, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glVertex4d(x: GLdouble, y: GLdouble, z: GLdouble, w: GLdouble) {.importc.}
-  proc glGetPathParameterfvNV(path: GLuint, pname: GLenum, value: ptr GLfloat) {.importc.}
-  proc glDetachShader(program: GLuint, shader: GLuint) {.importc.}
-  proc glGetColorTableSGI(target: GLenum, format: GLenum, `type`: GLenum, table: pointer) {.importc.}
-  proc glPixelTransformParameterfvEXT(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glBufferSubDataARB(target: GLenum, offset: GLintPtrArb, size: GLsizeiptrArb, data: pointer) {.importc.}
-  proc glVertexAttrib4ubvNV(index: GLuint, v: ptr GLubyte) {.importc.}
-  proc glCopyTextureImage1DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, border: GLint) {.importc.}
-  proc glGetQueryivARB(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glVertexAttribIPointerEXT(index: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glVertexAttribL3dEXT(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glGetQueryObjectui64vEXT(id: GLuint, pname: GLenum, params: ptr GLuint64) {.importc.}
-  proc glColor4x(red: GLfixed, green: GLfixed, blue: GLfixed, alpha: GLfixed) {.importc.}
-  proc glProgramUniformMatrix3x2dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glVertexAttribI4i(index: GLuint, x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glVertexAttrib1f(index: GLuint, x: GLfloat) {.importc.}
-  proc glUnmapBufferOES(target: GLenum): GLboolean {.importc.}
-  proc glVertexStream2ivATI(stream: GLenum, coords: ptr GLint) {.importc.}
-  proc glBeginOcclusionQueryNV(id: GLuint) {.importc.}
-  proc glVertex4sv(v: ptr GLshort) {.importc.}
-  proc glEnablei(target: GLenum, index: GLuint) {.importc.}
-  proc glUseProgramObjectARB(programObj: GLhandleArb) {.importc.}
-  proc glGetVertexAttribLdvEXT(index: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glUniform2d(location: GLint, x: GLdouble, y: GLdouble) {.importc.}
-  proc glMinmaxEXT(target: GLenum, internalformat: GLenum, sink: GLboolean) {.importc.}
-  proc glTexImage3D(target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGenSymbolsEXT(datatype: GLenum, storagetype: GLenum, range: GLenum, components: GLuint): GLuint {.importc.}
-  proc glVertexAttribI4svEXT(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glProgramEnvParameter4dvARB(target: GLenum, index: GLuint, params: ptr GLdouble) {.importc.}
-  proc glProgramUniformMatrix4dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glGetSamplerParameterfv(sampler: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glPopClientAttrib() {.importc.}
-  proc glHistogram(target: GLenum, width: GLsizei, internalformat: GLenum, sink: GLboolean) {.importc.}
-  proc glTexEnvfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord1dvARB(target: GLenum, v: ptr GLdouble) {.importc.}
-  proc glGetTexGenivOES(coord: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glUniform1ivARB(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glTexCoord3fv(v: ptr GLfloat) {.importc.}
-  proc glVertex2xvOES(coords: ptr GLfixed) {.importc.}
-  proc glTexCoord4fVertex4fvSUN(tc: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glUniform2uiv(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glMultiTexEnvfvEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glGetTextureParameterIivEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMemoryBarrierEXT(barriers: GLbitfield) {.importc.}
-  proc glGetTexParameterPointervAPPLE(target: GLenum, pname: GLenum, params: ptr pointer) {.importc.}
-  proc glWindowPos2svARB(v: ptr GLshort) {.importc.}
-  proc glEndQuery(target: GLenum) {.importc.}
-  proc glBlitFramebufferEXT(srcX0: GLint, srcY0: GLint, srcX1: GLint, srcY1: GLint, dstX0: GLint, dstY0: GLint, dstX1: GLint, dstY1: GLint, mask: GLbitfield, filter: GLenum) {.importc.}
-  proc glProgramEnvParametersI4uivNV(target: GLenum, index: GLuint, count: GLsizei, params: ptr GLuint) {.importc.}
-  proc glGetActiveUniform(program: GLuint, index: GLuint, bufSize: GLsizei, length: ptr GLsizei, size: ptr GLint, `type`: ptr GLenum, name: cstring) {.importc.}
-  proc glGenAsyncMarkersSGIX(range: GLsizei): GLuint {.importc.}
-  proc glClipControlARB(origin: GLenum, depth: GLenum) {.importc.}
-  proc glDrawElementsInstancedEXT(mode: GLenum, count: GLsizei, `type`: GLenum, indices: pointer, primcount: GLsizei) {.importc.}
-  proc glGetFragmentMaterialivSGIX(face: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glSwizzleEXT(res: GLuint, `in`: GLuint, outX: GLenum, outY: GLenum, outZ: GLenum, outW: GLenum) {.importc.}
-  proc glMultiTexCoord1bOES(texture: GLenum, s: GLbyte) {.importc.}
-  proc glProgramParameters4dvNV(target: GLenum, index: GLuint, count: GLsizei, v: ptr GLdouble) {.importc.}
-  proc glWindowPos2s(x: GLshort, y: GLshort) {.importc.}
-  proc glBlendFuncSeparatei(buf: GLuint, srcRgb: GLenum, dstRgb: GLenum, srcAlpha: GLenum, dstAlpha: GLenum) {.importc.}
-  proc glMultiModeDrawElementsIBM(mode: ptr GLenum, count: ptr GLsizei, `type`: GLenum, indices: ptr pointer, primcount: GLsizei, modestride: GLint) {.importc.}
-  proc glNormal3x(nx: GLfixed, ny: GLfixed, nz: GLfixed) {.importc.}
-  proc glProgramUniform1fvEXT(program: GLuint, location: GLint, count: GLsizei, value: ptr GLfloat) {.importc.}
-  proc glTexCoord2hNV(s: GLhalfNv, t: GLhalfNv) {.importc.}
-  proc glViewportIndexedfv(index: GLuint, v: ptr GLfloat) {.importc.}
-  proc glDrawTexxOES(x: GLfixed, y: GLfixed, z: GLfixed, width: GLfixed, height: GLfixed) {.importc.}
-  proc glProgramParameter4dvNV(target: GLenum, index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glDeleteBuffers(n: GLsizei, buffers: ptr GLuint) {.importc.}
-  proc glGetVertexArrayIntegervEXT(vaobj: GLuint, pname: GLenum, param: ptr GLint) {.importc.}
-  proc glBindFragDataLocationEXT(program: GLuint, color: GLuint, name: cstring) {.importc.}
-  proc glGenProgramsNV(n: GLsizei, programs: ptr GLuint) {.importc.}
-  proc glMultiTexCoord1i(target: GLenum, s: GLint) {.importc.}
-  proc glCompressedTexImage3DOES(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glGetQueryivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glExtGetBufferPointervQCOM(target: GLenum, params: ptr pointer) {.importc.}
-  proc glVertex3iv(v: ptr GLint) {.importc.}
-  proc glVertexAttribL1dvEXT(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glValidateProgramPipeline(pipeline: GLuint) {.importc.}
-  proc glBindVertexArray(`array`: GLuint) {.importc.}
-  proc glUniform2uiEXT(location: GLint, v0: GLuint, v1: GLuint) {.importc.}
-  proc glUniform3i(location: GLint, v0: GLint, v1: GLint, v2: GLint) {.importc.}
-  proc glGetVertexAttribIuiv(index: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glVertexArrayParameteriAPPLE(pname: GLenum, param: GLint) {.importc.}
-  proc glVertexAttribL2i64NV(index: GLuint, x: GLint64Ext, y: GLint64Ext) {.importc.}
-  proc glTexGenivOES(coord: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glIsFramebufferOES(framebuffer: GLuint): GLboolean {.importc.}
-  proc glColor4ubv(v: ptr GLubyte) {.importc.}
-  proc glDeleteNamedStringARB(namelen: GLint, name: cstring) {.importc.}
-  proc glCopyConvolutionFilter1DEXT(target: GLenum, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei) {.importc.}
-  proc glBufferStorage(target: GLenum, size: GLsizeiptr, data: ptr pointer, flags: GLbitfield) {.importc.}
-  proc glDrawTexiOES(x: GLint, y: GLint, z: GLint, width: GLint, height: GLint) {.importc.}
-  proc glRasterPos3dv(v: ptr GLdouble) {.importc.}
-  proc glIndexMaterialEXT(face: GLenum, mode: GLenum) {.importc.}
-  proc glGetClipPlanex(plane: GLenum, equation: ptr GLfixed) {.importc.}
-  proc glIsVertexArrayOES(`array`: GLuint): GLboolean {.importc.}
-  proc glColorTableEXT(target: GLenum, internalFormat: GLenum, width: GLsizei, format: GLenum, `type`: GLenum, table: pointer) {.importc.}
-  proc glCompressedTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, border: GLint, imageSize: GLsizei, data: pointer) {.importc.}
-  proc glLightx(light: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glGetTexParameterfv(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexAttrib4NsvARB(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glInterleavedArrays(format: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glProgramLocalParameter4fARB(target: GLenum, index: GLuint, x: GLfloat, y: GLfloat, z: GLfloat, w: GLfloat) {.importc.}
-  proc glPopDebugGroupKHR() {.importc.}
-  proc glVDPAUUnregisterSurfaceNV(surface: GLvdpauSurfaceNv) {.importc.}
-  proc glTexCoord1s(s: GLshort) {.importc.}
-  proc glFramebufferTexture2DMultisampleIMG(target: GLenum, attachment: GLenum, textarget: GLenum, texture: GLuint, level: GLint, samples: GLsizei) {.importc.}
-  proc glShaderBinary(count: GLsizei, shaders: ptr GLuint, binaryformat: GLenum, binary: pointer, length: GLsizei) {.importc.}
-  proc glVertexAttrib2dv(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glUniformMatrix4dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glWeightivARB(size: GLint, weights: ptr GLint) {.importc.}
-  proc glGetMultiTexParameterIivEXT(texunit: GLenum, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glCopyConvolutionFilter2DEXT(target: GLenum, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei) {.importc.}
-  proc glSecondaryColor3hNV(red: GLhalfNv, green: GLhalfNv, blue: GLhalfNv) {.importc.}
-  proc glVertexAttrib1sv(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glFrustumfOES(l: GLfloat, r: GLfloat, b: GLfloat, t: GLfloat, n: GLfloat, f: GLfloat) {.importc.}
-  proc glVertexStream2iATI(stream: GLenum, x: GLint, y: GLint) {.importc.}
-  proc glNormalStream3bATI(stream: GLenum, nx: GLbyte, ny: GLbyte, nz: GLbyte) {.importc.}
-  proc glVertexArrayTexCoordOffsetEXT(vaobj: GLuint, buffer: GLuint, size: GLint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glGetQueryiv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glTransformFeedbackStreamAttribsNV(count: GLsizei, attribs: ptr GLint, nbuffers: GLsizei, bufstreams: ptr GLint, bufferMode: GLenum) {.importc.}
-  proc glTextureStorage3DEXT(texture: GLuint, target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei) {.importc.}
-  proc glWindowPos3dvMESA(v: ptr GLdouble) {.importc.}
-  proc glUniform2uivEXT(location: GLint, count: GLsizei, value: ptr GLuint) {.importc.}
-  proc glTextureStorage2DEXT(texture: GLuint, target: GLenum, levels: GLsizei, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glVertexArrayMultiTexCoordOffsetEXT(vaobj: GLuint, buffer: GLuint, texunit: GLenum, size: GLint, `type`: GLenum, stride: GLsizei, offset: GLintptr) {.importc.}
-  proc glVertexStream1dvATI(stream: GLenum, coords: ptr GLdouble) {.importc.}
-  proc glCopyImageSubData(srcName: GLuint, srcTarget: GLenum, srcLevel: GLint, srcX: GLint, srcY: GLint, srcZ: GLint, dstName: GLuint, dstTarget: GLenum, dstLevel: GLint, dstX: GLint, dstY: GLint, dstZ: GLint, srcWidth: GLsizei, srcHeight: GLsizei, srcDepth: GLsizei) {.importc.}
-  proc glClearNamedBufferSubDataEXT(buffer: GLuint, internalformat: GLenum, format: GLenum, `type`: GLenum, offset: GLsizeiptr, size: GLsizeiptr, data: ptr pointer) {.importc.}
-  proc glBindBuffersRange(target: GLenum, first: GLuint, count: GLsizei, buffers: ptr GLuint, offsets: ptr GLintptr, sizes: ptr GLsizeiptr) {.importc.}
-  proc glGetVertexAttribIuivEXT(index: GLuint, pname: GLenum, params: ptr GLuint) {.importc.}
-  proc glLoadMatrixx(m: ptr GLfixed) {.importc.}
-  proc glTransformFeedbackVaryingsNV(program: GLuint, count: GLsizei, locations: ptr GLint, bufferMode: GLenum) {.importc.}
-  proc glUniform1i64vNV(location: GLint, count: GLsizei, value: ptr GLint64Ext) {.importc.}
-  proc glVertexArrayVertexAttribLFormatEXT(vaobj: GLuint, attribindex: GLuint, size: GLint, `type`: GLenum, relativeoffset: GLuint) {.importc.}
-  proc glClearBufferuiv(buffer: GLenum, drawbuffer: GLint, value: ptr GLuint) {.importc.}
-  proc glCombinerOutputNV(stage: GLenum, portion: GLenum, abOutput: GLenum, cdOutput: GLenum, sumOutput: GLenum, scale: GLenum, bias: GLenum, abDotProduct: GLboolean, cdDotProduct: GLboolean, muxSum: GLboolean) {.importc.}
-  proc glTexImage3DEXT(target: GLenum, level: GLint, internalformat: GLenum, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glPixelTransformParameterivEXT(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glActiveStencilFaceEXT(face: GLenum) {.importc.}
-  proc glCreateShaderObjectARB(shaderType: GLenum): GLhandleArb {.importc.}
-  proc glGetTextureParameterivEXT(texture: GLuint, target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glCopyTextureLevelsAPPLE(destinationTexture: GLuint, sourceTexture: GLuint, sourceBaseLevel: GLint, sourceLevelCount: GLsizei) {.importc.}
-  proc glVertexAttrib4Nuiv(index: GLuint, v: ptr GLuint) {.importc.}
-  proc glDrawPixels(width: GLsizei, height: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glWindowPos3dvARB(v: ptr GLdouble) {.importc.}
-  proc glProgramLocalParameterI4ivNV(target: GLenum, index: GLuint, params: ptr GLint) {.importc.}
-  proc glRasterPos4s(x: GLshort, y: GLshort, z: GLshort, w: GLshort) {.importc.}
-  proc glTexCoord2fVertex3fvSUN(tc: ptr GLfloat, v: ptr GLfloat) {.importc.}
-  proc glGetPathMetricsNV(metricQueryMask: GLbitfield, numPaths: GLsizei, pathNameType: GLenum, paths: pointer, pathBase: GLuint, stride: GLsizei, metrics: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord4bOES(texture: GLenum, s: GLbyte, t: GLbyte, r: GLbyte, q: GLbyte) {.importc.}
-  proc glTextureBufferEXT(texture: GLuint, target: GLenum, internalformat: GLenum, buffer: GLuint) {.importc.}
-  proc glSecondaryColor3fv(v: ptr GLfloat) {.importc.}
-  proc glMultiTexCoord3fv(target: GLenum, v: ptr GLfloat) {.importc.}
-  proc glGetTexParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glMap2xOES(target: GLenum, u1: GLfixed, u2: GLfixed, ustride: GLint, uorder: GLint, v1: GLfixed, v2: GLfixed, vstride: GLint, vorder: GLint, points: GLfixed) {.importc.}
-  proc glFlushVertexArrayRangeAPPLE(length: GLsizei, `pointer`: pointer) {.importc.}
-  proc glActiveTextureARB(texture: GLenum) {.importc.}
-  proc glGetVertexAttribLi64vNV(index: GLuint, pname: GLenum, params: ptr GLint64Ext) {.importc.}
-  proc glNormal3bv(v: ptr GLbyte) {.importc.}
-  proc glCreateSyncFromCLeventARB(context: ptr ClContext, event: ptr ClContext, flags: GLbitfield): GLsync {.importc.}
-  proc glRenderbufferStorageEXT(target: GLenum, internalformat: GLenum, width: GLsizei, height: GLsizei) {.importc.}
-  proc glGetCompressedTextureImageEXT(texture: GLuint, target: GLenum, lod: GLint, img: pointer) {.importc.}
-  proc glColorFragmentOp2ATI(op: GLenum, dst: GLuint, dstMask: GLuint, dstMod: GLuint, arg1: GLuint, arg1Rep: GLuint, arg1Mod: GLuint, arg2: GLuint, arg2Rep: GLuint, arg2Mod: GLuint) {.importc.}
-  proc glPixelMapusv(map: GLenum, mapsize: GLsizei, values: ptr GLushort) {.importc.}
-  proc glGlobalAlphaFactorsSUN(factor: GLshort) {.importc.}
-  proc glTexParameterxv(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glEvalCoord2xOES(u: GLfixed, v: GLfixed) {.importc.}
-  proc glIsList(list: GLuint): GLboolean {.importc.}
-  proc glVertexAttrib3d(index: GLuint, x: GLdouble, y: GLdouble, z: GLdouble) {.importc.}
-  proc glSpriteParameterfSGIX(pname: GLenum, param: GLfloat) {.importc.}
-  proc glPathGlyphRangeNV(firstPathName: GLuint, fontTarget: GLenum, fontName: pointer, fontStyle: GLbitfield, firstGlyph: GLuint, numGlyphs: GLsizei, handleMissingGlyphs: GLenum, pathParameterTemplate: GLuint, emScale: GLfloat) {.importc.}
-  proc glUniform3iv(location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glClearBufferfi(buffer: GLenum, drawbuffer: GLint, depth: GLfloat, stencil: GLint) {.importc.}
-  proc glWindowPos3sMESA(x: GLshort, y: GLshort, z: GLshort) {.importc.}
-  proc glGetMapParameterfvNV(target: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glBindFragmentShaderATI(id: GLuint) {.importc.}
-  proc glTexCoord4s(s: GLshort, t: GLshort, r: GLshort, q: GLshort) {.importc.}
-  proc glGetMultiTexGenfvEXT(texunit: GLenum, coord: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glColorMaterial(face: GLenum, mode: GLenum) {.importc.}
-  proc glVertexAttribs1svNV(index: GLuint, count: GLsizei, v: ptr GLshort) {.importc.}
-  proc glEnableVertexAttribAPPLE(index: GLuint, pname: GLenum) {.importc.}
-  proc glGetDoubleIndexedvEXT(target: GLenum, index: GLuint, data: ptr GLdouble) {.importc.}
-  proc glOrthof(l: GLfloat, r: GLfloat, b: GLfloat, t: GLfloat, n: GLfloat, f: GLfloat) {.importc.}
-  proc glVertexBlendEnvfATI(pname: GLenum, param: GLfloat) {.importc.}
-  proc glUniformMatrix2x4dv(location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glPrioritizeTexturesxOES(n: GLsizei, textures: ptr GLuint, priorities: ptr GLfixed) {.importc.}
-  proc glGetTextureSamplerHandleNV(texture: GLuint, sampler: GLuint): GLuint64 {.importc.}
-  proc glDeleteVertexArrays(n: GLsizei, arrays: ptr GLuint) {.importc.}
-  proc glMultiTexCoord1xOES(texture: GLenum, s: GLfixed) {.importc.}
-  proc glGlobalAlphaFactorusSUN(factor: GLushort) {.importc.}
-  proc glGetConvolutionParameterxvOES(target: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glProgramUniform4fEXT(program: GLuint, location: GLint, v0: GLfloat, v1: GLfloat, v2: GLfloat, v3: GLfloat) {.importc.}
-  proc glProgramUniformMatrix3x4dvEXT(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-  proc glBindVertexBuffer(bindingindex: GLuint, buffer: GLuint, offset: GLintptr, stride: GLsizei) {.importc.}
-  proc glGetHistogramParameteriv(target: GLenum, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glGetShaderPrecisionFormat(shadertype: GLenum, precisiontype: GLenum, range: ptr GLint, precision: ptr GLint) {.importc.}
-  proc glTextureMaterialEXT(face: GLenum, mode: GLenum) {.importc.}
-  proc glEvalCoord2xvOES(coords: ptr GLfixed) {.importc.}
-  proc glWeightuivARB(size: GLint, weights: ptr GLuint) {.importc.}
-  proc glGetTextureLevelParameterfvEXT(texture: GLuint, target: GLenum, level: GLint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glVertexAttribP3uiv(index: GLuint, `type`: GLenum, normalized: GLboolean, value: ptr GLuint) {.importc.}
-  proc glProgramEnvParameterI4ivNV(target: GLenum, index: GLuint, params: ptr GLint) {.importc.}
-  proc glFogi(pname: GLenum, param: GLint) {.importc.}
-  proc glTexCoord1iv(v: ptr GLint) {.importc.}
-  proc glReplacementCodeuiColor4ubVertex3fvSUN(rc: ptr GLuint, c: ptr GLubyte, v: ptr GLfloat) {.importc.}
-  proc glProgramUniform1ui(program: GLuint, location: GLint, v0: GLuint) {.importc.}
-  proc glMultiTexCoord3d(target: GLenum, s: GLdouble, t: GLdouble, r: GLdouble) {.importc.}
-  proc glBeginVideoCaptureNV(video_capture_slot: GLuint) {.importc.}
-  proc glEvalCoord1f(u: GLfloat) {.importc.}
-  proc glMultiTexCoord1hvNV(target: GLenum, v: ptr GLhalfNv) {.importc.}
-  proc glSecondaryColor3sEXT(red: GLshort, green: GLshort, blue: GLshort) {.importc.}
-  proc glTextureImage3DEXT(texture: GLuint, target: GLenum, level: GLint, internalformat: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, border: GLint, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glCopyTexImage2D(target: GLenum, level: GLint, internalformat: GLenum, x: GLint, y: GLint, width: GLsizei, height: GLsizei, border: GLint) {.importc.}
-  proc glFinishFenceAPPLE(fence: GLuint) {.importc.}
-  proc glVertexArrayRangeNV(length: GLsizei, `pointer`: pointer) {.importc.}
-  proc glLightModelf(pname: GLenum, param: GLfloat) {.importc.}
-  proc glVertexAttribL1ui64ARB(index: GLuint, x: GLuint64Ext) {.importc.}
-  proc glPolygonOffset(factor: GLfloat, units: GLfloat) {.importc.}
-  proc glRasterPos4xOES(x: GLfixed, y: GLfixed, z: GLfixed, w: GLfixed) {.importc.}
-  proc glVertexAttrib3dvNV(index: GLuint, v: ptr GLdouble) {.importc.}
-  proc glBeginQuery(target: GLenum, id: GLuint) {.importc.}
-  proc glWeightfvARB(size: GLint, weights: ptr GLfloat) {.importc.}
-  proc glGetUniformuiv(program: GLuint, location: GLint, params: ptr GLuint) {.importc.}
-  proc glIsTextureEXT(texture: GLuint): GLboolean {.importc.}
-  proc glGetClipPlanef(plane: GLenum, equation: ptr GLfloat) {.importc.}
-  proc glTexGenxOES(coord: GLenum, pname: GLenum, param: GLfixed) {.importc.}
-  proc glFramebufferTextureFaceEXT(target: GLenum, attachment: GLenum, texture: GLuint, level: GLint, face: GLenum) {.importc.}
-  proc glDisableClientState(`array`: GLenum) {.importc.}
-  proc glTexPageCommitmentARB(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, resident: GLboolean) {.importc.}
-  proc glRasterPos4dv(v: ptr GLdouble) {.importc.}
-  proc glGetLightx(light: GLenum, pname: GLenum, params: ptr GLfixed) {.importc.}
-  proc glVertexAttrib1hvNV(index: GLuint, v: ptr GLhalfNv) {.importc.}
-  proc glMultiTexCoord2s(target: GLenum, s: GLshort, t: GLshort) {.importc.}
-  proc glProgramUniform2iv(program: GLuint, location: GLint, count: GLsizei, value: ptr GLint) {.importc.}
-  proc glGetListParameterivSGIX(list: GLuint, pname: GLenum, params: ptr GLint) {.importc.}
-  proc glColorFragmentOp1ATI(op: GLenum, dst: GLuint, dstMask: GLuint, dstMod: GLuint, arg1: GLuint, arg1Rep: GLuint, arg1Mod: GLuint) {.importc.}
-  proc glReplacementCodeuiTexCoord2fColor4fNormal3fVertex3fSUN(rc: GLuint, s: GLfloat, t: GLfloat, r: GLfloat, g: GLfloat, b: GLfloat, a: GLfloat, nx: GLfloat, ny: GLfloat, nz: GLfloat, x: GLfloat, y: GLfloat, z: GLfloat) {.importc.}
-  proc glSampleMapATI(dst: GLuint, interp: GLuint, swizzle: GLenum) {.importc.}
-  proc glProgramUniform1d(program: GLuint, location: GLint, v0: GLdouble) {.importc.}
-  proc glBindAttribLocation(program: GLuint, index: GLuint, name: cstring) {.importc.}
-  proc glGetCombinerStageParameterfvNV(stage: GLenum, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexSubImage4DSGIS(target: GLenum, level: GLint, xoffset: GLint, yoffset: GLint, zoffset: GLint, woffset: GLint, width: GLsizei, height: GLsizei, depth: GLsizei, size4d: GLsizei, format: GLenum, `type`: GLenum, pixels: pointer) {.importc.}
-  proc glGetMapAttribParameterfvNV(target: GLenum, index: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glNewObjectBufferATI(size: GLsizei, `pointer`: pointer, usage: GLenum): GLuint {.importc.}
-  proc glWindowPos4iMESA(x: GLint, y: GLint, z: GLint, w: GLint) {.importc.}
-  proc glNewList(list: GLuint, mode: GLenum) {.importc.}
-  proc glUniform1i64NV(location: GLint, x: GLint64Ext) {.importc.}
-  proc glTexCoordP3ui(`type`: GLenum, coords: GLuint) {.importc.}
-  proc glEndQueryEXT(target: GLenum) {.importc.}
-  proc glGetVertexAttribLdv(index: GLuint, pname: GLenum, params: ptr GLdouble) {.importc.}
-  proc glStencilMask(mask: GLuint) {.importc.}
-  proc glVertexAttrib4sv(index: GLuint, v: ptr GLshort) {.importc.}
-  proc glRectsv(v1: ptr GLshort, v2: ptr GLshort) {.importc.}
-  proc glGetVariantArrayObjectfvATI(id: GLuint, pname: GLenum, params: ptr GLfloat) {.importc.}
-  proc glTexCoord3hvNV(v: ptr GLhalfNv) {.importc.}
-  proc glGetUniformdv(program: GLuint, location: GLint, params: ptr GLdouble) {.importc.}
-  proc glSecondaryColor3fvEXT(v: ptr GLfloat) {.importc.}
-  proc glAlphaFuncx(fun: GLenum, `ref`: GLfixed) {.importc.}
-  proc glVertexAttribPointerNV(index: GLuint, fsize: GLint, `type`: GLenum, stride: GLsizei, `pointer`: pointer) {.importc.}
-  proc glColorTable(target: GLenum, internalformat: GLenum, width: GLsizei, format: GLenum, `type`: GLenum, table: pointer) {.importc.}
-  proc glProgramUniformMatrix2x3dv(program: GLuint, location: GLint, count: GLsizei, transpose: GLboolean, value: ptr GLdouble) {.importc.}
-
-  ## # GL_ARB_direct_state_access
-  proc glCreateTransformFeedbacks(n: GLsizei; ids: ptr GLuint) {.importc.}
-  proc glTransformFeedbackBufferBase(xfb: GLuint; index: GLuint; buffer: GLuint) {.importc.}
-  proc glTransformFeedbackBufferRange(xfb: GLuint; index: GLuint; buffer: GLuint; offset: GLintptr; size: GLsizeiptr) {.importc.}
-  proc glGetTransformFeedbackiv(xfb: GLuint; pname: GLenum; param: ptr GLint) {.importc.}
-  proc glGetTransformFeedbacki_v(xfb: GLuint; pname: GLenum; index: GLuint; param: ptr GLint) {.importc.}
-  proc glGetTransformFeedbacki64_v(xfb: GLuint; pname: GLenum; index: GLuint; param: ptr GLint64) {.importc.}
-  ## # Buffer object functions 
-
-  proc glCreateBuffers(n: GLsizei; buffers: ptr GLuint) {.importc.}
-  proc glNamedBufferStorage(buffer: GLuint; size: GLsizeiptr; data: pointer; flags: GLbitfield) {.importc.}
-  proc glNamedBufferData(buffer: GLuint; size: GLsizeiptr; data: pointer; usage: GLenum) {.importc.}
-  proc glNamedBufferSubData(buffer: GLuint; offset: GLintptr; size: GLsizeiptr; data: pointer) {.importc.}
-  proc glCopyNamedBufferSubData(readBuffer: GLuint; writeBuffer: GLuint; readOffset: GLintptr; writeOffset: GLintptr; size: GLsizeiptr) {.importc.}
-  proc glClearNamedBufferData(buffer: GLuint; internalformat: GLenum; format: GLenum; `type`: GLenum; data: pointer) {.importc.}
-  proc glClearNamedBufferSubData(buffer: GLuint; internalformat: GLenum; offset: GLintptr; size: GLsizeiptr; format: GLenum; `type`: GLenum; data: pointer) {.importc.}
-  proc glMapNamedBuffer(buffer: GLuint; access: GLenum): pointer {.importc.}
-  proc glMapNamedBufferRange(buffer: GLuint; offset: GLintptr; length: GLsizeiptr; access: GLbitfield): pointer {.importc.}
-  proc glUnmapNamedBuffer(buffer: GLuint): GLboolean {.importc.}
-  proc glFlushMappedNamedBufferRange(buffer: GLuint; offset: GLintptr; length: GLsizeiptr) {.importc.}
-  proc glGetNamedBufferParameteriv(buffer: GLuint; pname: GLenum; params: ptr GLint) {.importc.}
-  proc glGetNamedBufferParameteri64v(buffer: GLuint; pname: GLenum; params: ptr GLint64) {.importc.}
-  proc glGetNamedBufferPointerv(buffer: GLuint; pname: GLenum; params: ptr pointer) {.importc.}
-  proc glGetNamedBufferSubData(buffer: GLuint; offset: GLintptr; size: GLsizeiptr; data: pointer) {.importc.}
-  ## # Framebuffer object functions 
-
-  proc glCreateFramebuffers(n: GLsizei; framebuffers: ptr GLuint) {.importc.}
-  proc glNamedFramebufferRenderbuffer(framebuffer: GLuint; attachment: GLenum; renderbuffertarget: GLenum; renderbuffer: GLuint) {.importc.}
-  proc glNamedFramebufferParameteri(framebuffer: GLuint; pname: GLenum; param: GLint) {.importc.}
-  proc glNamedFramebufferTexture(framebuffer: GLuint; attachment: GLenum; texture: GLuint; level: GLint) {.importc.}
-  proc glNamedFramebufferTextureLayer(framebuffer: GLuint; attachment: GLenum; texture: GLuint; level: GLint; layer: GLint) {.importc.}
-  proc glNamedFramebufferDrawBuffer(framebuffer: GLuint; mode: GLenum) {.importc.}
-  proc glNamedFramebufferDrawBuffers(framebuffer: GLuint; n: GLsizei; bufs: ptr GLenum) {.importc.}
-  proc glNamedFramebufferReadBuffer(framebuffer: GLuint; mode: GLenum) {.importc.}
-  proc glInvalidateNamedFramebufferData(framebuffer: GLuint; numAttachments: GLsizei; attachments: ptr GLenum) {.importc.}
-  proc glInvalidateNamedFramebufferSubData(framebuffer: GLuint; numAttachments: GLsizei; attachments: ptr GLenum; x: GLint; y: GLint; width: GLsizei; height: GLsizei) {.importc.}
-  proc glClearNamedFramebufferiv(framebuffer: GLuint; buffer: GLenum; drawbuffer: GLint; value: ptr GLint) {.importc.}
-  proc glClearNamedFramebufferuiv(framebuffer: GLuint; buffer: GLenum; drawbuffer: GLint; value: ptr GLuint) {.importc.}
-  proc glClearNamedFramebufferfv(framebuffer: GLuint; buffer: GLenum; drawbuffer: GLint; value: ptr cfloat) {.importc.}
-  proc glClearNamedFramebufferfi(framebuffer: GLuint; buffer: GLenum; drawbuffer: GLint; depth: cfloat; stencil: GLint) {.importc.}
-  proc glBlitNamedFramebuffer(readFramebuffer: GLuint; drawFramebuffer: GLuint; srcX0: GLint; srcY0: GLint; srcX1: GLint; srcY1: GLint; dstX0: GLint; dstY0: GLint; dstX1: GLint; dstY1: GLint; mask: GLbitfield; filter: GLenum) {.importc.}
-  proc glCheckNamedFramebufferStatus(framebuffer: GLuint; target: GLenum): GLenum {.importc.}
-  proc glGetNamedFramebufferParameteriv(framebuffer: GLuint; pname: GLenum; param: ptr GLint) {.importc.}
-  proc glGetNamedFramebufferAttachmentParameteriv(framebuffer: GLuint; attachment: GLenum; pname: GLenum; params: ptr GLint) {.importc.}
-  ## # Renderbuffer object functions 
-
-  proc glCreateRenderbuffers(n: GLsizei; renderbuffers: ptr GLuint) {.importc.}
-  proc glNamedRenderbufferStorage(renderbuffer: GLuint; internalformat: GLenum; width: GLsizei; height: GLsizei) {.importc.}
-  proc glNamedRenderbufferStorageMultisample(renderbuffer: GLuint; samples: GLsizei; internalformat: GLenum; width: GLsizei; height: GLsizei) {.importc.}
-  proc glGetNamedRenderbufferParameteriv(renderbuffer: GLuint; pname: GLenum; params: ptr GLint) {.importc.}
-  ## # Texture object functions 
-
-  proc glCreateTextures(target: GLenum; n: GLsizei; textures: ptr GLuint) {.importc.}
-  proc glTextureBuffer(texture: GLuint; internalformat: GLenum; buffer: GLuint) {.importc.}
-  proc glTextureBufferRange(texture: GLuint; internalformat: GLenum; buffer: GLuint; offset: GLintptr; size: GLsizeiptr) {.importc.}
-  proc glTextureStorage1D(texture: GLuint; levels: GLsizei; internalformat: GLenum; width: GLsizei) {.importc.}
-  proc glTextureStorage2D(texture: GLuint; levels: GLsizei; internalformat: GLenum; width: GLsizei; height: GLsizei) {.importc.}
-  proc glTextureStorage3D(texture: GLuint; levels: GLsizei; internalformat: GLenum; width: GLsizei; height: GLsizei; depth: GLsizei) {.importc.}
-  proc glTextureStorage2DMultisample(texture: GLuint; samples: GLsizei; internalformat: GLenum; width: GLsizei; height: GLsizei; fixedsamplelocations: GLboolean) {.importc.}
-  proc glTextureStorage3DMultisample(texture: GLuint; samples: GLsizei; internalformat: GLenum; width: GLsizei; height: GLsizei; depth: GLsizei; fixedsamplelocations: GLboolean) {.importc.}
-  proc glTextureSubImage1D(texture: GLuint; level: GLint; xoffset: GLint; width: GLsizei; format: GLenum; `type`: GLenum; pixels: pointer) {.importc.}
-  proc glTextureSubImage2D(texture: GLuint; level: GLint; xoffset: GLint; yoffset: GLint; width: GLsizei; height: GLsizei; format: GLenum; `type`: GLenum; pixels: pointer) {.importc.}
-  proc glTextureSubImage3D(texture: GLuint; level: GLint; xoffset: GLint; yoffset: GLint; zoffset: GLint; width: GLsizei; height: GLsizei; depth: GLsizei; format: GLenum; `type`: GLenum; pixels: pointer) {.importc.}
-  proc glCompressedTextureSubImage1D(texture: GLuint; level: GLint; xoffset: GLint; width: GLsizei; format: GLenum; imageSize: GLsizei; data: pointer) {.importc.}
-  proc glCompressedTextureSubImage2D(texture: GLuint; level: GLint; xoffset: GLint; yoffset: GLint; width: GLsizei; height: GLsizei; format: GLenum; imageSize: GLsizei; data: pointer) {.importc.}
-  proc glCompressedTextureSubImage3D(texture: GLuint; level: GLint; xoffset: GLint; yoffset: GLint; zoffset: GLint; width: GLsizei; height: GLsizei; depth: GLsizei; format: GLenum; imageSize: GLsizei; data: pointer) {.importc.}
-  proc glCopyTextureSubImage1D(texture: GLuint; level: GLint; xoffset: GLint; x: GLint; y: GLint; width: GLsizei) {.importc.}
-  proc glCopyTextureSubImage2D(texture: GLuint; level: GLint; xoffset: GLint; yoffset: GLint; x: GLint; y: GLint; width: GLsizei; height: GLsizei) {.importc.}
-  proc glCopyTextureSubImage3D(texture: GLuint; level: GLint; xoffset: GLint; yoffset: GLint; zoffset: GLint; x: GLint; y: GLint; width: GLsizei; height: GLsizei) {.importc.}
-  proc glTextureParameterf(texture: GLuint; pname: GLenum; param: cfloat) {.importc.}
-  proc glTextureParameterfv(texture: GLuint; pname: GLenum; param: ptr cfloat) {.importc.}
-  proc glTextureParameteri(texture: GLuint; pname: GLenum; param: GLint) {.importc.}
-  proc glTextureParameterIiv(texture: GLuint; pname: GLenum; params: ptr GLint) {.importc.}
-  proc glTextureParameterIuiv(texture: GLuint; pname: GLenum; params: ptr GLuint) {.importc.}
-  proc glTextureParameteriv(texture: GLuint; pname: GLenum; param: ptr GLint) {.importc.}
-  proc glGenerateTextureMipmap(texture: GLuint) {.importc.}
-  proc glBindTextureUnit(unit: GLuint; texture: GLuint) {.importc.}
-  proc glGetTextureImage(texture: GLuint; level: GLint; format: GLenum; `type`: GLenum; bufSize: GLsizei; pixels: pointer) {.importc.}
-                         
-  proc glGetCompressedTextureImage(texture: GLuint; level: GLint; bufSize: GLsizei; pixels: pointer) {.importc.}
-  proc glGetTextureLevelParameterfv(texture: GLuint; level: GLint; pname: GLenum; params: ptr cfloat) {.importc.}
-  proc glGetTextureLevelParameteriv(texture: GLuint; level: GLint; pname: GLenum; params: ptr GLint) {.importc.}
-  proc glGetTextureParameterfv(texture: GLuint; pname: GLenum; params: ptr cfloat) {.importc.}
-  proc glGetTextureParameterIiv(texture: GLuint; pname: GLenum; params: ptr GLint) {.importc.}
-  proc glGetTextureParameterIuiv(texture: GLuint; pname: GLenum; params: ptr GLuint) {.importc.}
-  proc glGetTextureParameteriv(texture: GLuint; pname: GLenum; params: ptr GLint) {.importc.}
-  ## # Vertex Array object functions 
-
-  proc glCreateVertexArrays(n: GLsizei; arrays: ptr GLuint) {.importc.}
-  proc glDisableVertexArrayAttrib(vaobj: GLuint; index: GLuint) {.importc.}
-  proc glEnableVertexArrayAttrib(vaobj: GLuint; index: GLuint) {.importc.}
-  proc glVertexArrayElementBuffer(vaobj: GLuint; buffer: GLuint) {.importc.}
-  proc glVertexArrayVertexBuffer(vaobj: GLuint; bindingindex: GLuint; buffer: GLuint; offset: GLintptr; stride: GLsizei) {.importc.}
-  proc glVertexArrayVertexBuffers(vaobj: GLuint; first: GLuint; count: GLsizei; buffers: ptr GLuint; offsets: ptr GLintptr; strides: ptr GLsizei) {.importc.}
-  proc glVertexArrayAttribFormat(vaobj: GLuint; attribindex: GLuint; size: GLint; `type`: GLenum; normalized: GLboolean; relativeoffset: GLuint) {.importc.}
-  proc glVertexArrayAttribIFormat(vaobj: GLuint; attribindex: GLuint; size: GLint; `type`: GLenum; relativeoffset: GLuint) {.importc.}
-  proc glVertexArrayAttribLFormat(vaobj: GLuint; attribindex: GLuint; size: GLint; `type`: GLenum; relativeoffset: GLuint) {.importc.}
-  proc glVertexArrayAttribBinding(vaobj: GLuint; attribindex: GLuint; bindingindex: GLuint) {.importc.}
-  proc glVertexArrayBindingDivisor(vaobj: GLuint; bindingindex: GLuint; divisor: GLuint) {.importc.}
-  proc glGetVertexArrayiv(vaobj: GLuint; pname: GLenum; param: ptr GLint) {.importc.}
-  proc glGetVertexArrayIndexediv(vaobj: GLuint; index: GLuint; pname: GLenum; param: ptr GLint) {.importc.}
-  proc glGetVertexArrayIndexed64iv(vaobj: GLuint; index: GLuint; pname: GLenum; param: ptr GLint64) {.importc.}
-  ## # Sampler object functions 
-
-  proc glCreateSamplers(n: GLsizei; samplers: ptr GLuint) {.importc.}
-  ## # Program Pipeline object functions 
-
-  proc glCreateProgramPipelines(n: GLsizei; pipelines: ptr GLuint) {.importc.}
-  ## # Query object functions 
-
-  proc glCreateQueries(target: GLenum; n: GLsizei; ids: ptr GLuint) {.importc.}
-  proc glGetQueryBufferObjectiv(id: GLuint; buffer: GLuint; pname: GLenum; offset: GLintptr) {.importc.}
-  proc glGetQueryBufferObjectuiv(id: GLuint; buffer: GLuint; pname: GLenum; offset: GLintptr) {.importc.}
-  proc glGetQueryBufferObjecti64v(id: GLuint; buffer: GLuint; pname: GLenum; offset: GLintptr) {.importc.}
-  proc glGetQueryBufferObjectui64v(id: GLuint; buffer: GLuint; pname: GLenum; offset: GLintptr) {.importc.}
-
-{.pop.} # stdcall, hint[XDeclaredButNotUsed]: off, warning[SmallLshouldNotBeUsed]: off.
-
-const
-  cGL_UNSIGNED_BYTE* = 0x1401.GLenum
-  cGL_UNSIGNED_SHORT* = 0x1403.GLenum
-
-  GL_2X_BIT_ATI* = 0x00000001.GLbitfield
-  GL_MODELVIEW6_ARB* = 0x8726.GLenum
-  GL_CULL_FACE_MODE* = 0x0B45.GLenum
-  GL_TEXTURE_MAG_FILTER* = 0x2800.GLenum
-  GL_TRANSFORM_FEEDBACK_VARYINGS_EXT* = 0x8C83.GLenum
-  GL_PATH_JOIN_STYLE_NV* = 0x9079.GLenum
-  GL_FEEDBACK_BUFFER_SIZE* = 0x0DF1.GLenum
-  GL_FRAGMENT_LIGHT0_SGIX* = 0x840C.GLenum
-  GL_DRAW_BUFFER7_ARB* = 0x882C.GLenum
-  GL_POINT_SPRITE_OES* = 0x8861.GLenum
-  GL_INT_SAMPLER_RENDERBUFFER_NV* = 0x8E57.GLenum
-  GL_POST_CONVOLUTION_COLOR_TABLE_SGI* = 0x80D1.GLenum
-  GL_ZOOM_X* = 0x0D16.GLenum
-  GL_DRAW_FRAMEBUFFER_NV* = 0x8CA9.GLenum
-  GL_RGB_FLOAT16_ATI* = 0x881B.GLenum
-  GL_NUM_COMPRESSED_TEXTURE_FORMATS* = 0x86A2.GLenum
-  GL_LINE_STRIP* = 0x0003.GLenum
-  GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE_SGI* = 0x80D5.GLenum
-  GL_CURRENT_TIME_NV* = 0x8E28.GLenum
-  GL_FRAMEBUFFER_UNSUPPORTED* = 0x8CDD.GLenum
-  GL_PIXEL_TEX_GEN_Q_CEILING_SGIX* = 0x8184.GLenum
-  GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH_EXT* = 0x8C76.GLenum
-  GL_MAP_PERSISTENT_BIT* = 0x0040.GLbitfield
-  GL_IMAGE_2D_MULTISAMPLE_ARRAY_EXT* = 0x9056.GLenum
-  GL_CON_16_ATI* = 0x8951.GLenum
-  GL_DEPTH_BUFFER_BIT1_QCOM* = 0x00000200.GLbitfield
-  GL_TEXTURE30_ARB* = 0x84DE.GLenum
-  GL_SAMPLER_BUFFER* = 0x8DC2.GLenum
-  GL_MAX_COLOR_TEXTURE_SAMPLES* = 0x910E.GLenum
-  GL_DEPTH_STENCIL* = 0x84F9.GLenum
-  GL_C4F_N3F_V3F* = 0x2A26.GLenum
-  GL_ZOOM_Y* = 0x0D17.GLenum
-  GL_RGB10* = 0x8052.GLenum
-  GL_PRESERVE_ATI* = 0x8762.GLenum
-  GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS_ARB* = 0x8B4D.GLenum
-  GL_COLOR_ATTACHMENT12_NV* = 0x8CEC.GLenum
-  GL_GREEN_MAX_CLAMP_INGR* = 0x8565.GLenum
-  GL_CURRENT_VERTEX_ATTRIB* = 0x8626.GLenum
-  GL_TEXTURE_SHARED_SIZE* = 0x8C3F.GLenum
-  GL_NORMAL_ARRAY_TYPE* = 0x807E.GLenum
-  GL_DYNAMIC_READ* = 0x88E9.GLenum
-  GL_ALPHA4_EXT* = 0x803B.GLenum
-  GL_REPLACEMENT_CODE_ARRAY_SUN* = 0x85C0.GLenum
-  GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_NV* = 0x8852.GLenum
-  GL_MAX_VERTEX_ATTRIBS_ARB* = 0x8869.GLenum
-  GL_VIDEO_COLOR_CONVERSION_MIN_NV* = 0x902B.GLenum
-  GL_SOURCE3_RGB_NV* = 0x8583.GLenum
-  GL_ALPHA* = 0x1906.GLenum
-  GL_OUTPUT_TEXTURE_COORD16_EXT* = 0x87AD.GLenum
-  GL_BLEND_EQUATION_EXT* = 0x8009.GLenum
-  GL_BIAS_BIT_ATI* = 0x00000008.GLbitfield
-  GL_BLEND_EQUATION_RGB* = 0x8009.GLenum
-  GL_SHADER_BINARY_DMP* = 0x9250.GLenum
-  GL_IMAGE_FORMAT_COMPATIBILITY_BY_SIZE* = 0x90C8.GLenum
-  GL_Z4Y12Z4CB12Z4CR12_444_NV* = 0x9037.GLenum
-  GL_READ_PIXELS_TYPE* = 0x828E.GLenum
-  GL_CONVOLUTION_HINT_SGIX* = 0x8316.GLenum
-  GL_TRANSPOSE_AFFINE_3D_NV* = 0x9098.GLenum
-  GL_PIXEL_MAP_B_TO_B* = 0x0C78.GLenum
-  GL_VERTEX_BLEND_ARB* = 0x86A7.GLenum
-  GL_LIGHT2* = 0x4002.GLenum
-  cGL_BYTE* = 0x1400.GLenum
-  GL_MAX_TESS_CONTROL_ATOMIC_COUNTERS* = 0x92D3.GLenum
-  GL_DOMAIN* = 0x0A02.GLenum
-  GL_PROGRAM_NATIVE_TEMPORARIES_ARB* = 0x88A6.GLenum
-  GL_RELATIVE_CUBIC_CURVE_TO_NV* = 0x0D.GLenum
-  GL_TEXTURE_DEPTH_TYPE_ARB* = 0x8C16.GLenum
-  GL_STENCIL_BACK_PASS_DEPTH_PASS* = 0x8803.GLenum
-  GL_MAX_FRAGMENT_PROGRAM_LOCAL_PARAMETERS_NV* = 0x8868.GLenum
-  GL_ATTRIB_STACK_DEPTH* = 0x0BB0.GLenum
-  GL_DEPTH_COMPONENT16_ARB* = 0x81A5.GLenum
-  GL_TESSELLATION_MODE_AMD* = 0x9004.GLenum
-  GL_UNSIGNED_INT8_VEC3_NV* = 0x8FEE.GLenum
-  GL_DOUBLE_VEC4* = 0x8FFE.GLenum
-  GL_MAX_TESS_CONTROL_TOTAL_OUTPUT_COMPONENTS* = 0x8E85.GLenum
-  GL_TEXTURE_GREEN_TYPE_ARB* = 0x8C11.GLenum
-  GL_PIXEL_PACK_BUFFER* = 0x88EB.GLenum
-  GL_VERTEX_WEIGHT_ARRAY_EXT* = 0x850C.GLenum
-  GL_HALF_FLOAT* = 0x140B.GLenum
-  GL_REG_0_ATI* = 0x8921.GLenum
-  GL_DEPTH_BUFFER_BIT4_QCOM* = 0x00001000.GLbitfield
-  GL_UNSIGNED_INT_5_9_9_9_REV_EXT* = 0x8C3E.GLenum
-  GL_DEPTH_COMPONENT16_SGIX* = 0x81A5.GLenum
-  GL_COMPRESSED_RGBA_ASTC_8x5_KHR* = 0x93B5.GLenum
-  GL_EDGE_FLAG_ARRAY_LENGTH_NV* = 0x8F30.GLenum
-  GL_CON_17_ATI* = 0x8952.GLenum
-  GL_PARAMETER_BUFFER_ARB* = 0x80EE.GLenum
-  GL_COLOR_ATTACHMENT6_EXT* = 0x8CE6.GLenum
-  GL_INDEX_ARRAY_EXT* = 0x8077.GLenum
-  GL_ALPHA_SCALE* = 0x0D1C.GLenum
-  GL_LINE_QUALITY_HINT_SGIX* = 0x835B.GLenum
-  GL_SLUMINANCE8* = 0x8C47.GLenum
-  GL_DEBUG_OUTPUT_KHR* = 0x92E0.GLenum
-  GL_TEXTURE_LIGHTING_MODE_HP* = 0x8167.GLenum
-  GL_SPOT_DIRECTION* = 0x1204.GLenum
-  GL_V3F* = 0x2A21.GLenum
-  GL_ALPHA16_EXT* = 0x803E.GLenum
-  GL_DRAW_BUFFER15_NV* = 0x8834.GLenum
-  GL_MIN_PROGRAM_TEXEL_OFFSET_EXT* = 0x8904.GLenum
-  GL_ACTIVE_VARYING_MAX_LENGTH_NV* = 0x8C82.GLenum
-  GL_COLOR_ATTACHMENT10* = 0x8CEA.GLenum
-  GL_COLOR_ARRAY_LIST_STRIDE_IBM* = 103082.GLenum
-  GL_TEXTURE_TARGET_QCOM* = 0x8BDA.GLenum
-  GL_DRAW_BUFFER12_ARB* = 0x8831.GLenum
-  GL_SAMPLE_MASK* = 0x8E51.GLenum
-  GL_TEXTURE_FORMAT_QCOM* = 0x8BD6.GLenum
-  GL_TEXTURE_COMPONENTS* = 0x1003.GLenum
-  GL_PROGRAM_PIPELINE_BINDING* = 0x825A.GLenum
-  GL_HIGH_INT* = 0x8DF5.GLenum
-  GL_MAP_INVALIDATE_BUFFER_BIT* = 0x0008.GLbitfield
-  GL_LAYOUT_LINEAR_CPU_CACHED_INTEL* = 2.GLenum
-  GL_TEXTURE_DS_SIZE_NV* = 0x871D.GLenum
-  GL_HALF_FLOAT_NV* = 0x140B.GLenum
-  GL_PROXY_POST_COLOR_MATRIX_COLOR_TABLE* = 0x80D5.GLenum
-  GL_UNIFORM_BLOCK_REFERENCED_BY_GEOMETRY_SHADER* = 0x8A45.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR* = 0x93DB.GLenum
-  GL_REG_18_ATI* = 0x8933.GLenum
-  GL_MAX_COMBINED_COMPUTE_UNIFORM_COMPONENTS* = 0x8266.GLenum
-  GL_UNPACK_FLIP_Y_WEBGL* = 0x9240.GLenum
-  GL_POLYGON_STIPPLE_BIT* = 0x00000010.GLbitfield
-  GL_MULTISAMPLE_BUFFER_BIT6_QCOM* = 0x40000000.GLbitfield
-  GL_ONE_MINUS_SRC_ALPHA* = 0x0303.GLenum
-  GL_RASTERIZER_DISCARD_EXT* = 0x8C89.GLenum
-  GL_BGRA_INTEGER* = 0x8D9B.GLenum
-  GL_MAX_TESS_EVALUATION_ATOMIC_COUNTER_BUFFERS* = 0x92CE.GLenum
-  GL_MODELVIEW1_EXT* = 0x850A.GLenum
-  GL_VERTEX_ELEMENT_SWIZZLE_AMD* = 0x91A4.GLenum
-  GL_MAP1_GRID_SEGMENTS* = 0x0DD1.GLenum
-  GL_PATH_ERROR_POSITION_NV* = 0x90AB.GLenum
-  GL_FOG_COORDINATE_ARRAY_EXT* = 0x8457.GLenum
-  GL_NUM_INPUT_INTERPOLATOR_COMPONENTS_ATI* = 0x8973.GLenum
-  GL_MAX_PROGRAM_TEX_INDIRECTIONS_ARB* = 0x880D.GLenum
-  GL_PATH_GEN_COLOR_FORMAT_NV* = 0x90B2.GLenum
-  GL_BUFFER_VARIABLE* = 0x92E5.GLenum
-  GL_PROXY_TEXTURE_CUBE_MAP_ARB* = 0x851B.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_BPTC_UNORM_ARB* = 0x8E8D.GLenum
-  GL_TEXT_FRAGMENT_SHADER_ATI* = 0x8200.GLenum
-  GL_ALPHA_MAX_SGIX* = 0x8321.GLenum
-  GL_UNPACK_ALIGNMENT* = 0x0CF5.GLenum
-  GL_POST_COLOR_MATRIX_RED_SCALE* = 0x80B4.GLenum
-  GL_CIRCULAR_CW_ARC_TO_NV* = 0xFA.GLenum
-  GL_MAX_SAMPLES_APPLE* = 0x8D57.GLenum
-  GL_4PASS_3_SGIS* = 0x80A7.GLenum
-  GL_SAMPLER_3D_OES* = 0x8B5F.GLenum
-  GL_UNSIGNED_INT16_VEC2_NV* = 0x8FF1.GLenum
-  GL_UNSIGNED_INT_SAMPLER_1D_ARRAY* = 0x8DD6.GLenum
-  GL_REG_8_ATI* = 0x8929.GLenum
-  GL_UNSIGNED_SHORT_1_5_5_5_REV_EXT* = 0x8366.GLenum
-  GL_QUERY_RESULT_AVAILABLE_EXT* = 0x8867.GLenum
-  GL_INTENSITY8_EXT* = 0x804B.GLenum
-  GL_OUTPUT_TEXTURE_COORD9_EXT* = 0x87A6.GLenum
-  GL_TEXTURE_BINDING_RECTANGLE_NV* = 0x84F6.GLenum
-  GL_OFFSET_PROJECTIVE_TEXTURE_RECTANGLE_SCALE_NV* = 0x8853.GLenum
-  GL_IMAGE_FORMAT_COMPATIBILITY_TYPE* = 0x90C7.GLenum
-  GL_WRITE_ONLY* = 0x88B9.GLenum
-  GL_SAMPLER_1D_SHADOW* = 0x8B61.GLenum
-  GL_DISPATCH_INDIRECT_BUFFER_BINDING* = 0x90EF.GLenum
-  GL_VERTEX_PROGRAM_BINDING_NV* = 0x864A.GLenum
-  GL_RGB8_EXT* = 0x8051.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR* = 0x93D7.GLenum
-  GL_CON_5_ATI* = 0x8946.GLenum
-  GL_DUAL_INTENSITY8_SGIS* = 0x8119.GLenum
-  GL_MAX_SAMPLES_EXT* = 0x8D57.GLenum
-  GL_VERTEX_ARRAY_POINTER_EXT* = 0x808E.GLenum
-  GL_COMBINE_EXT* = 0x8570.GLenum
-  GL_MULTISAMPLE_BUFFER_BIT1_QCOM* = 0x02000000.GLbitfield
-  GL_MAGNITUDE_SCALE_NV* = 0x8712.GLenum
-  GL_SYNC_CONDITION_APPLE* = 0x9113.GLenum
-  GL_RGBA_S3TC* = 0x83A2.GLenum
-  GL_LINE_STIPPLE_REPEAT* = 0x0B26.GLenum
-  GL_TEXTURE_COMPRESSION_HINT* = 0x84EF.GLenum
-  GL_TEXTURE_COMPARE_MODE* = 0x884C.GLenum
-  GL_RGBA_FLOAT_MODE_ATI* = 0x8820.GLenum
-  GL_OPERAND0_RGB* = 0x8590.GLenum
-  GL_SIGNED_RGB8_UNSIGNED_ALPHA8_NV* = 0x870D.GLenum
-  GL_POST_COLOR_MATRIX_GREEN_SCALE_SGI* = 0x80B5.GLenum
-  GL_Z6Y10Z6CB10Z6Y10Z6CR10_422_NV* = 0x9033.GLenum
-  GL_UNPACK_ROW_LENGTH* = 0x0CF2.GLenum
-  GL_DOUBLE_MAT2_EXT* = 0x8F46.GLenum
-  GL_TEXTURE_GEQUAL_R_SGIX* = 0x819D.GLenum
-  GL_UNSIGNED_INT_8_24_REV_MESA* = 0x8752.GLenum
-  GL_DSDT8_NV* = 0x8709.GLenum
-  GL_RESAMPLE_DECIMATE_SGIX* = 0x8430.GLenum
-  GL_DEBUG_SOURCE_OTHER_KHR* = 0x824B.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_ARB* = 0x8DA8.GLenum
-  GL_MAX_VERTEX_UNITS_OES* = 0x86A4.GLenum
-  GL_ISOLINES* = 0x8E7A.GLenum
-  GL_INCR_WRAP* = 0x8507.GLenum
-  GL_BUFFER_MAP_POINTER* = 0x88BD.GLenum
-  GL_INT_SAMPLER_CUBE_MAP_ARRAY* = 0x900E.GLenum
-  GL_UNSIGNED_INT_VEC2* = 0x8DC6.GLenum
-  GL_RENDERBUFFER_HEIGHT_OES* = 0x8D43.GLenum
-  GL_COMPRESSED_RGBA_ASTC_10x10_KHR* = 0x93BB.GLenum
-  GL_PIXEL_TEX_GEN_ALPHA_MS_SGIX* = 0x818A.GLenum
-  GL_LINEAR_SHARPEN_COLOR_SGIS* = 0x80AF.GLenum
-  GL_COLOR_ATTACHMENT5_EXT* = 0x8CE5.GLenum
-  GL_VERTEX_ATTRIB_ARRAY9_NV* = 0x8659.GLenum
-  GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING* = 0x889D.GLenum
-  GL_BLEND_DST_RGB* = 0x80C8.GLenum
-  GL_VERTEX_ARRAY_EXT* = 0x8074.GLenum
-  GL_VERTEX_ARRAY_RANGE_POINTER_NV* = 0x8521.GLenum
-  GL_DEBUG_SEVERITY_MEDIUM_ARB* = 0x9147.GLenum
-  GL_OPERAND0_ALPHA* = 0x8598.GLenum
-  GL_TEXTURE_BINDING_CUBE_MAP* = 0x8514.GLenum
-  GL_ADD_ATI* = 0x8963.GLenum
-  GL_AUX1* = 0x040A.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING_EXT* = 0x8210.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS* = 0x8CD9.GLenum
-  GL_MINUS_NV* = 0x929F.GLenum
-  GL_RGB4* = 0x804F.GLenum
-  GL_COMPRESSED_RGBA_ASTC_12x12_KHR* = 0x93BD.GLenum
-  GL_MAX_GEOMETRY_OUTPUT_VERTICES* = 0x8DE0.GLenum
-  GL_SURFACE_STATE_NV* = 0x86EB.GLenum
-  GL_COLOR_MATERIAL_FACE* = 0x0B55.GLenum
-  GL_TEXTURE18_ARB* = 0x84D2.GLenum
-  GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2_OES* = 0x9277.GLenum
-  GL_LOWER_LEFT* = 0x8CA1.GLenum
-  GL_DRAW_BUFFER8_ATI* = 0x882D.GLenum
-  GL_TEXTURE_CONSTANT_DATA_SUNX* = 0x81D6.GLenum
-  GL_SAMPLER_1D* = 0x8B5D.GLenum
-  GL_POLYGON_OFFSET_EXT* = 0x8037.GLenum
-  GL_EQUIV* = 0x1509.GLenum
-  GL_QUERY_BUFFER_BINDING* = 0x9193.GLenum
-  GL_COMBINE_ARB* = 0x8570.GLenum
-  GL_MATRIX0_NV* = 0x8630.GLenum
-  GL_CLAMP_TO_BORDER_SGIS* = 0x812D.GLint
-  GL_INTENSITY8UI_EXT* = 0x8D7F.GLenum
-  GL_TRACK_MATRIX_TRANSFORM_NV* = 0x8649.GLenum
-  GL_SURFACE_MAPPED_NV* = 0x8700.GLenum
-  GL_INT_VEC3_ARB* = 0x8B54.GLenum
-  GL_IMAGE_TRANSFORM_2D_HP* = 0x8161.GLenum
-  GL_PROGRAM_BINARY_RETRIEVABLE_HINT* = 0x8257.GLenum
-  GL_DRAW_BUFFER8_EXT* = 0x882D.GLenum
-  GL_DEPTH_STENCIL_EXT* = 0x84F9.GLenum
-  GL_CONTEXT_PROFILE_MASK* = 0x9126.GLenum
-  GL_MAX_PROGRAM_NATIVE_INSTRUCTIONS_ARB* = 0x88A3.GLenum
-  GL_MATRIX5_ARB* = 0x88C5.GLenum
-  GL_FRAMEBUFFER_UNDEFINED_OES* = 0x8219.GLenum
-  GL_UNPACK_CMYK_HINT_EXT* = 0x800F.GLenum
-  GL_UNSIGNED_NORMALIZED_EXT* = 0x8C17.GLenum
-  GL_ONE* = 1.GLenum
-  GL_EDGE_FLAG_ARRAY_BUFFER_BINDING_ARB* = 0x889B.GLenum
-  GL_TRANSPOSE_PROJECTION_MATRIX* = 0x84E4.GLenum
-  GL_MAX_PROGRAM_TOTAL_OUTPUT_COMPONENTS_NV* = 0x8C28.GLenum
-  GL_CLIP_DISTANCE3* = 0x3003.GLenum
-  GL_4PASS_1_SGIS* = 0x80A5.GLenum
-  GL_MAX_FRAGMENT_LIGHTS_SGIX* = 0x8404.GLenum
-  GL_TEXTURE_3D_OES* = 0x806F.GLenum
-  GL_TEXTURE0* = 0x84C0.GLenum
-  GL_INT_IMAGE_CUBE_EXT* = 0x905B.GLenum
-  GL_INNOCENT_CONTEXT_RESET_ARB* = 0x8254.GLenum
-  GL_INDEX_ARRAY_TYPE_EXT* = 0x8085.GLenum
-  GL_SAMPLER_OBJECT_AMD* = 0x9155.GLenum
-  GL_INDEX_ARRAY_BUFFER_BINDING_ARB* = 0x8899.GLenum
-  GL_RENDERBUFFER_DEPTH_SIZE_OES* = 0x8D54.GLenum
-  GL_MAX_SAMPLE_MASK_WORDS* = 0x8E59.GLenum
-  GL_COMBINER2_NV* = 0x8552.GLenum
-  GL_COLOR_ARRAY_BUFFER_BINDING_ARB* = 0x8898.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_NORMALIZED_ARB* = 0x886A.GLenum
-  GL_STREAM_DRAW* = 0x88E0.GLenum
-  GL_RGB8I* = 0x8D8F.GLenum
-  GL_BLEND_COLOR_EXT* = 0x8005.GLenum
-  GL_MAX_VARYING_VECTORS* = 0x8DFC.GLenum
-  GL_COPY_WRITE_BUFFER_BINDING* = 0x8F37.GLenum
-  GL_FIXED_ONLY_ARB* = 0x891D.GLenum
-  GL_INT_VEC4* = 0x8B55.GLenum
-  GL_PROGRAM_PIPELINE_BINDING_EXT* = 0x825A.GLenum
-  GL_UNSIGNED_NORMALIZED_ARB* = 0x8C17.GLenum
-  GL_NUM_INSTRUCTIONS_PER_PASS_ATI* = 0x8971.GLenum
-  GL_PIXEL_MODE_BIT* = 0x00000020.GLbitfield
-  GL_COMPRESSED_RED_RGTC1* = 0x8DBB.GLenum
-  GL_SHADER_IMAGE_ACCESS_BARRIER_BIT_EXT* = 0x00000020.GLbitfield
-  GL_VARIANT_DATATYPE_EXT* = 0x87E5.GLenum
-  GL_DARKEN_NV* = 0x9297.GLenum
-  GL_POINT_SIZE_MAX_SGIS* = 0x8127.GLenum
-  GL_OBJECT_ATTACHED_OBJECTS_ARB* = 0x8B85.GLenum
-  GL_SLUMINANCE_ALPHA_EXT* = 0x8C44.GLenum
-  GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY* = 0x906A.GLenum
-  GL_EDGE_FLAG_ARRAY* = 0x8079.GLenum
-  GL_LINEAR_CLIPMAP_NEAREST_SGIX* = 0x844F.GLenum
-  GL_LUMINANCE_ALPHA32F_EXT* = 0x8819.GLenum
-  GL_NORMAL_BIT_PGI* = 0x08000000.GLbitfield
-  GL_SECONDARY_COLOR_ARRAY* = 0x845E.GLenum
-  GL_CLIP_PLANE1_IMG* = 0x3001.GLenum
-  GL_REG_19_ATI* = 0x8934.GLenum
-  GL_PIXEL_PACK_BUFFER_BINDING* = 0x88ED.GLenum
-  GL_PIXEL_GROUP_COLOR_SGIS* = 0x8356.GLenum
-  GL_SELECTION_BUFFER_SIZE* = 0x0DF4.GLenum
-  GL_SRC_OUT_NV* = 0x928C.GLenum
-  GL_TEXTURE7* = 0x84C7.GLenum
-  GL_COMPARE_R_TO_TEXTURE* = 0x884E.GLenum
-  GL_DUDV_ATI* = 0x8779.GLenum
-  GL_TEXTURE_BASE_LEVEL* = 0x813C.GLenum
-  GL_PN_TRIANGLES_POINT_MODE_LINEAR_ATI* = 0x87F5.GLenum
-  GL_LAYOUT_LINEAR_INTEL* = 1.GLenum
-  GL_DEPTH_BUFFER_BIT2_QCOM* = 0x00000400.GLbitfield
-  GL_MAX_TESS_EVALUATION_UNIFORM_BLOCKS* = 0x8E8A.GLenum
-  GL_LIGHT3* = 0x4003.GLenum
-  GL_ALPHA_MAX_CLAMP_INGR* = 0x8567.GLenum
-  GL_RG_INTEGER* = 0x8228.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL* = 0x8CD2.GLenum
-  GL_TEXTURE_STACK_DEPTH* = 0x0BA5.GLenum
-  GL_ALREADY_SIGNALED* = 0x911A.GLenum
-  GL_TEXTURE_CUBE_MAP_OES* = 0x8513.GLenum
-  GL_N3F_V3F* = 0x2A25.GLenum
-  GL_SUBTRACT_ARB* = 0x84E7.GLenum
-  GL_ELEMENT_ARRAY_LENGTH_NV* = 0x8F33.GLenum
-  GL_NORMAL_ARRAY_EXT* = 0x8075.GLenum
-  GL_POLYGON_OFFSET_FACTOR_EXT* = 0x8038.GLenum
-  GL_EIGHTH_BIT_ATI* = 0x00000020.GLbitfield
-  GL_UNSIGNED_INT_SAMPLER_2D_RECT* = 0x8DD5.GLenum
-  GL_OBJECT_ACTIVE_ATTRIBUTES_ARB* = 0x8B89.GLenum
-  GL_MAX_VERTEX_VARYING_COMPONENTS_ARB* = 0x8DDE.GLenum
-  GL_TEXTURE_COORD_ARRAY_STRIDE_EXT* = 0x808A.GLenum
-  GL_4_BYTES* = 0x1409.GLenum
-  GL_SAMPLE_SHADING* = 0x8C36.GLenum
-  GL_FOG_MODE* = 0x0B65.GLenum
-  GL_CON_7_ATI* = 0x8948.GLenum
-  GL_DRAW_FRAMEBUFFER* = 0x8CA9.GLenum
-  GL_TEXTURE_MEMORY_LAYOUT_INTEL* = 0x83FF.GLenum
-  GL_RGB32I_EXT* = 0x8D83.GLenum
-  GL_VERTEX_ARRAY_STRIDE* = 0x807C.GLenum
-  GL_COLOR_ATTACHMENT3_NV* = 0x8CE3.GLenum
-  GL_NORMAL_ARRAY_PARALLEL_POINTERS_INTEL* = 0x83F6.GLenum
-  GL_CONTRAST_NV* = 0x92A1.GLenum
-  GL_RGBA32F* = 0x8814.GLenum
-  GL_YCBAYCR8A_4224_NV* = 0x9032.GLenum
-  GL_MAX_VERTEX_ATTRIB_RELATIVE_OFFSET* = 0x82D9.GLenum
-  GL_TEXTURE22* = 0x84D6.GLenum
-  GL_TEXTURE_3D* = 0x806F.GLenum
-  GL_STENCIL_PASS_DEPTH_FAIL* = 0x0B95.GLenum
-  GL_PROXY_HISTOGRAM_EXT* = 0x8025.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTERS* = 0x92C5.GLenum
-  GL_MAX_ATOMIC_COUNTER_BUFFER_SIZE* = 0x92D8.GLenum
-  GL_FOG_COORD_ARRAY_TYPE* = 0x8454.GLenum
-  GL_MAP2_VERTEX_4* = 0x0DB8.GLenum
-  GL_PACK_COMPRESSED_SIZE_SGIX* = 0x831C.GLenum
-  GL_POST_TEXTURE_FILTER_SCALE_RANGE_SGIX* = 0x817C.GLenum
-  GL_ITALIC_BIT_NV* = 0x02.GLbitfield
-  GL_COMPRESSED_LUMINANCE_ALPHA* = 0x84EB.GLenum
-  GL_COLOR_TABLE_SCALE_SGI* = 0x80D6.GLenum
-  GL_DOUBLE_MAT2x4_EXT* = 0x8F4A.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_ALPHA_SIZE* = 0x8215.GLenum
-  GL_MATRIX11_ARB* = 0x88CB.GLenum
-  GL_REG_5_ATI* = 0x8926.GLenum
-  GL_RGBA2_EXT* = 0x8055.GLenum
-  GL_DISCARD_NV* = 0x8530.GLenum
-  GL_TEXTURE7_ARB* = 0x84C7.GLenum
-  GL_LUMINANCE32UI_EXT* = 0x8D74.GLenum
-  GL_ACTIVE_UNIFORM_BLOCKS* = 0x8A36.GLenum
-  GL_UNSIGNED_INT16_VEC4_NV* = 0x8FF3.GLenum
-  GL_VERTEX_ATTRIB_ARRAY5_NV* = 0x8655.GLenum
-  GL_DOUBLE_MAT3x4* = 0x8F4C.GLenum
-  GL_BOOL* = 0x8B56.GLenum
-  GL_NUM_COMPRESSED_TEXTURE_FORMATS_ARB* = 0x86A2.GLenum
-  GL_COMPRESSED_RGB_ARB* = 0x84ED.GLenum
-  GL_DEBUG_TYPE_MARKER_KHR* = 0x8268.GLenum
-  GL_TEXTURE_DEPTH_QCOM* = 0x8BD4.GLenum
-  GL_VARIABLE_F_NV* = 0x8528.GLenum
-  GL_MAX_PIXEL_MAP_TABLE* = 0x0D34.GLenum
-  GL_DST_COLOR* = 0x0306.GLenum
-  GL_OR_INVERTED* = 0x150D.GLenum
-  GL_TRANSFORM_FEEDBACK_VARYINGS_NV* = 0x8C83.GLenum
-  GL_RGB_INTEGER* = 0x8D98.GLenum
-  GL_COLOR_MATERIAL* = 0x0B57.GLenum
-  GL_DEBUG_SEVERITY_LOW_AMD* = 0x9148.GLenum
-  GL_MIRROR_CLAMP_TO_BORDER_EXT* = 0x8912.GLint
-  GL_TEXTURE1_ARB* = 0x84C1.GLenum
-  GL_MIN_MAP_BUFFER_ALIGNMENT* = 0x90BC.GLenum
-  GL_MATRIX16_ARB* = 0x88D0.GLenum
-  GL_TEXTURE_ALPHA_TYPE_ARB* = 0x8C13.GLenum
-  GL_PROGRAM_POINT_SIZE* = 0x8642.GLenum
-  GL_COMBINER_AB_OUTPUT_NV* = 0x854A.GLenum
-  GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2_OES* = 0x9276.GLenum
-  GL_RGB4_S3TC* = 0x83A1.GLenum
-  GL_TEXTURE_EXTERNAL_OES* = 0x8D65.GLenum
-  GL_MAX_MAP_TESSELLATION_NV* = 0x86D6.GLenum
-  GL_AUX_DEPTH_STENCIL_APPLE* = 0x8A14.GLenum
-  GL_MAX_DEBUG_LOGGED_MESSAGES_AMD* = 0x9144.GLenum
-  GL_CONSTANT_BORDER* = 0x8151.GLenum
-  GL_RESAMPLE_ZERO_FILL_OML* = 0x8987.GLenum
-  GL_POST_CONVOLUTION_ALPHA_SCALE_EXT* = 0x801F.GLenum
-  GL_OBJECT_VALIDATE_STATUS_ARB* = 0x8B83.GLenum
-  GL_DST_ALPHA* = 0x0304.GLenum
-  GL_COMBINER5_NV* = 0x8555.GLenum
-  GL_VERSION_ES_CL_1_1* = 1.GLenum
-  GL_MOVE_TO_CONTINUES_NV* = 0x90B6.GLenum
-  GL_IMAGE_MAG_FILTER_HP* = 0x815C.GLenum
-  GL_TEXTURE_FREE_MEMORY_ATI* = 0x87FC.GLenum
-  GL_DEBUG_TYPE_PORTABILITY_KHR* = 0x824F.GLenum
-  GL_BUFFER_UPDATE_BARRIER_BIT* = 0x00000200.GLbitfield
-  GL_FUNC_ADD* = 0x8006.GLenum
-  GL_PN_TRIANGLES_POINT_MODE_ATI* = 0x87F2.GLenum
-  GL_DEBUG_CALLBACK_USER_PARAM_ARB* = 0x8245.GLenum
-  GL_CURRENT_SECONDARY_COLOR* = 0x8459.GLenum
-  GL_DEPENDENT_RGB_TEXTURE_CUBE_MAP_NV* = 0x885A.GLenum
-  GL_FRAGMENT_LIGHT7_SGIX* = 0x8413.GLenum
-  GL_MAP2_TEXTURE_COORD_4* = 0x0DB6.GLenum
-  GL_PACK_ALIGNMENT* = 0x0D05.GLenum
-  GL_VERTEX23_BIT_PGI* = 0x00000004.GLbitfield
-  GL_MAX_CLIPMAP_DEPTH_SGIX* = 0x8177.GLenum
-  GL_TEXTURE_3D_BINDING_EXT* = 0x806A.GLenum
-  GL_COLOR_ATTACHMENT1* = 0x8CE1.GLenum
-  GL_NEAREST* = 0x2600.GLint
-  GL_MAX_DEBUG_LOGGED_MESSAGES* = 0x9144.GLenum
-  GL_COMBINER6_NV* = 0x8556.GLenum
-  GL_COLOR_SUM_EXT* = 0x8458.GLenum
-  GL_CONVOLUTION_WIDTH* = 0x8018.GLenum
-  GL_SAMPLE_ALPHA_TO_COVERAGE_ARB* = 0x809E.GLenum
-  GL_DRAW_FRAMEBUFFER_EXT* = 0x8CA9.GLenum
-  GL_PROXY_HISTOGRAM* = 0x8025.GLenum
-  GL_PIXEL_FRAGMENT_ALPHA_SOURCE_SGIS* = 0x8355.GLenum
-  GL_COMPRESSED_RGBA_ASTC_10x5_KHR* = 0x93B8.GLenum
-  GL_SMOOTH_CUBIC_CURVE_TO_NV* = 0x10.GLenum
-  GL_BGR_EXT* = 0x80E0.GLenum
-  GL_PROGRAM_UNDER_NATIVE_LIMITS_ARB* = 0x88B6.GLenum
-  GL_VIBRANCE_BIAS_NV* = 0x8719.GLenum
-  GL_UNPACK_COLORSPACE_CONVERSION_WEBGL* = 0x9243.GLenum
-  GL_SLUMINANCE8_NV* = 0x8C47.GLenum
-  GL_TEXTURE_MAX_LEVEL_SGIS* = 0x813D.GLenum
-  GL_UNIFORM_ATOMIC_COUNTER_BUFFER_INDEX* = 0x92DA.GLenum
-  GL_RGB9_E5_EXT* = 0x8C3D.GLenum
-  GL_CULL_VERTEX_IBM* = 103050.GLenum
-  GL_PROXY_COLOR_TABLE* = 0x80D3.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_DEPTH_SIZE* = 0x8216.GLenum
-  GL_MAX_FRAGMENT_UNIFORM_COMPONENTS* = 0x8B49.GLenum
-  GL_CCW* = 0x0901.GLenum
-  GL_COLOR_WRITEMASK* = 0x0C23.GLenum
-  GL_TEXTURE19_ARB* = 0x84D3.GLenum
-  GL_VERTEX_STREAM3_ATI* = 0x876F.GLenum
-  GL_ONE_EXT* = 0x87DE.GLenum
-  GL_MAX_SAMPLES* = 0x8D57.GLenum
-  GL_STENCIL_PASS_DEPTH_PASS* = 0x0B96.GLenum
-  GL_PERFMON_RESULT_AVAILABLE_AMD* = 0x8BC4.GLenum
-  GL_RETURN* = 0x0102.GLenum
-  GL_DETAIL_TEXTURE_LEVEL_SGIS* = 0x809A.GLenum
-  GL_UNSIGNED_INT_IMAGE_CUBE_EXT* = 0x9066.GLenum
-  GL_FOG_OFFSET_VALUE_SGIX* = 0x8199.GLenum
-  GL_TEXTURE_MAX_LOD_SGIS* = 0x813B.GLenum
-  GL_TRANSPOSE_COLOR_MATRIX_ARB* = 0x84E6.GLenum
-  GL_DEBUG_SOURCE_APPLICATION_ARB* = 0x824A.GLenum
-  GL_SIGNED_ALPHA_NV* = 0x8705.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_EXT* = 0x9063.GLenum
-  GL_SHADER_IMAGE_ACCESS_BARRIER_BIT* = 0x00000020.GLbitfield
-  GL_ATOMIC_COUNTER_BARRIER_BIT* = 0x00001000.GLbitfield
-  GL_COLOR3_BIT_PGI* = 0x00010000.GLbitfield
-  GL_MATERIAL_SIDE_HINT_PGI* = 0x1A22C.GLenum
-  GL_LIGHT_MODEL_SPECULAR_VECTOR_APPLE* = 0x85B0.GLenum
-  GL_LINEAR_SHARPEN_SGIS* = 0x80AD.GLenum
-  GL_LUMINANCE_SNORM* = 0x9011.GLenum
-  GL_TEXTURE_LUMINANCE_SIZE* = 0x8060.GLenum
-  GL_REPLACE_MIDDLE_SUN* = 0x0002.GLenum
-  GL_TEXTURE_DEFORMATION_SGIX* = 0x8195.GLenum
-  GL_MULTISAMPLE_BUFFER_BIT7_QCOM* = 0x80000000.GLbitfield
-  GL_FONT_HAS_KERNING_BIT_NV* = 0x10000000.GLbitfield
-  GL_COPY* = 0x1503.GLenum
-  GL_READ_BUFFER_NV* = 0x0C02.GLenum
-  GL_TRANSPOSE_CURRENT_MATRIX_ARB* = 0x88B7.GLenum
-  GL_VERTEX_ARRAY_OBJECT_AMD* = 0x9154.GLenum
-  GL_TIMEOUT_EXPIRED* = 0x911B.GLenum
-  GL_DYNAMIC_COPY* = 0x88EA.GLenum
-  GL_DRAW_BUFFER2_ARB* = 0x8827.GLenum
-  GL_OUTPUT_TEXTURE_COORD10_EXT* = 0x87A7.GLenum
-  GL_SIGNED_RGBA8_NV* = 0x86FC.GLenum
-  GL_MATRIX6_ARB* = 0x88C6.GLenum
-  GL_OP_SUB_EXT* = 0x8796.GLenum
-  GL_NO_RESET_NOTIFICATION_EXT* = 0x8261.GLenum
-  GL_TEXTURE_BASE_LEVEL_SGIS* = 0x813C.GLenum
-  GL_ALPHA_INTEGER* = 0x8D97.GLenum
-  GL_TEXTURE13* = 0x84CD.GLenum
-  GL_EYE_LINEAR* = 0x2400.GLenum
-  GL_INTENSITY4_EXT* = 0x804A.GLenum
-  GL_SOURCE1_RGB_EXT* = 0x8581.GLenum
-  GL_AUX_BUFFERS* = 0x0C00.GLenum
-  GL_SOURCE0_ALPHA* = 0x8588.GLenum
-  GL_RGB32I* = 0x8D83.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS* = 0x8C8A.GLenum
-  GL_VIEW_CLASS_S3TC_DXT1_RGBA* = 0x82CD.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_NV* = 0x8C85.GLenum
-  GL_SAMPLER_KHR* = 0x82E6.GLenum
-  GL_WRITEONLY_RENDERING_QCOM* = 0x8823.GLenum
-  GL_PACK_SKIP_ROWS* = 0x0D03.GLenum
-  GL_MAP1_VERTEX_ATTRIB0_4_NV* = 0x8660.GLenum
-  GL_PATH_STENCIL_VALUE_MASK_NV* = 0x90B9.GLenum
-  GL_REPLACE_EXT* = 0x8062.GLenum
-  GL_MODELVIEW3_ARB* = 0x8723.GLenum
-  GL_ONE_MINUS_CONSTANT_ALPHA* = 0x8004.GLenum
-  GL_DSDT8_MAG8_INTENSITY8_NV* = 0x870B.GLenum
-  GL_CURRENT_QUERY_ARB* = 0x8865.GLenum
-  GL_LUMINANCE8_ALPHA8_OES* = 0x8045.GLenum
-  GL_ARRAY_ELEMENT_LOCK_COUNT_EXT* = 0x81A9.GLenum
-  GL_MODELVIEW19_ARB* = 0x8733.GLenum
-  GL_MAX_VERTEX_SHADER_INSTRUCTIONS_EXT* = 0x87C5.GLenum
-  GL_MAX_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB* = 0x8810.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT* = 0x906C.GLenum
-  GL_NORMAL_ARRAY_BUFFER_BINDING* = 0x8897.GLenum
-  GL_AMBIENT* = 0x1200.GLenum
-  GL_TEXTURE_MATERIAL_PARAMETER_EXT* = 0x8352.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR* = 0x93DA.GLenum
-  GL_MAX_TESS_CONTROL_UNIFORM_COMPONENTS* = 0x8E7F.GLenum
-  GL_COMPRESSED_LUMINANCE_ALPHA_ARB* = 0x84EB.GLenum
-  GL_MODELVIEW14_ARB* = 0x872E.GLenum
-  GL_INTERLACE_READ_OML* = 0x8981.GLenum
-  GL_RENDERBUFFER_FREE_MEMORY_ATI* = 0x87FD.GLenum
-  GL_EMBOSS_MAP_NV* = 0x855F.GLenum
-  GL_POINT_SIZE_RANGE* = 0x0B12.GLenum
-  GL_FOG_COORDINATE* = 0x8451.GLenum
-  GL_MAJOR_VERSION* = 0x821B.GLenum
-  GL_FRAME_NV* = 0x8E26.GLenum
-  GL_CURRENT_TEXTURE_COORDS* = 0x0B03.GLenum
-  GL_PACK_RESAMPLE_OML* = 0x8984.GLenum
-  GL_DEPTH24_STENCIL8_OES* = 0x88F0.GLenum
-  GL_PROGRAM_BINARY_FORMATS_OES* = 0x87FF.GLenum
-  GL_TRANSLATE_3D_NV* = 0x9091.GLenum
-  GL_TEXTURE_GEN_Q* = 0x0C63.GLenum
-  GL_COLOR_ATTACHMENT0_EXT* = 0x8CE0.GLenum
-  GL_ALPHA12* = 0x803D.GLenum
-  GL_INCR_WRAP_EXT* = 0x8507.GLenum
-  GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN* = 0x8C88.GLenum
-  GL_DUAL_ALPHA12_SGIS* = 0x8112.GLenum
-  GL_EYE_LINE_SGIS* = 0x81F6.GLenum
-  GL_TEXTURE_MAX_LEVEL_APPLE* = 0x813D.GLenum
-  GL_TRIANGLE_FAN* = 0x0006.GLenum
-  GL_DEBUG_GROUP_STACK_DEPTH* = 0x826D.GLenum
-  GL_IMAGE_CLASS_1_X_16* = 0x82BE.GLenum
-  GL_COMPILE* = 0x1300.GLenum
-  GL_LINE_SMOOTH* = 0x0B20.GLenum
-  GL_FEEDBACK_BUFFER_POINTER* = 0x0DF0.GLenum
-  GL_CURRENT_SECONDARY_COLOR_EXT* = 0x8459.GLenum
-  GL_DRAW_BUFFER2_ATI* = 0x8827.GLenum
-  GL_PN_TRIANGLES_NORMAL_MODE_ATI* = 0x87F3.GLenum
-  GL_MODELVIEW0_ARB* = 0x1700.GLenum
-  GL_SRGB8_ALPHA8* = 0x8C43.GLenum
-  GL_TEXTURE_BLUE_TYPE* = 0x8C12.GLenum
-  GL_POST_CONVOLUTION_ALPHA_BIAS* = 0x8023.GLenum
-  GL_PATH_STROKE_BOUNDING_BOX_NV* = 0x90A2.GLenum
-  GL_RGBA16UI* = 0x8D76.GLenum
-  GL_OFFSET_HILO_TEXTURE_2D_NV* = 0x8854.GLenum
-  GL_PREVIOUS_ARB* = 0x8578.GLenum
-  GL_BINORMAL_ARRAY_EXT* = 0x843A.GLenum
-  GL_UNSIGNED_INT_IMAGE_CUBE* = 0x9066.GLenum
-  GL_REG_30_ATI* = 0x893F.GLenum
-  GL_VIEWPORT_SUBPIXEL_BITS* = 0x825C.GLenum
-  GL_VERSION* = 0x1F02.GLenum
-  GL_COMPUTE_PROGRAM_PARAMETER_BUFFER_NV* = 0x90FC.GLenum
-  GL_DEBUG_CATEGORY_SHADER_COMPILER_AMD* = 0x914E.GLenum
-  GL_CONVOLUTION_FILTER_SCALE_EXT* = 0x8014.GLenum
-  GL_HALF_BIT_ATI* = 0x00000008.GLbitfield
-  GL_SPRITE_AXIS_SGIX* = 0x814A.GLenum
-  GL_INDEX_ARRAY_STRIDE* = 0x8086.GLenum
-  GL_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB* = 0x88B2.GLenum
-  GL_EVAL_VERTEX_ATTRIB0_NV* = 0x86C6.GLenum
-  GL_COUNTER_RANGE_AMD* = 0x8BC1.GLenum
-  GL_VERTEX_WEIGHTING_EXT* = 0x8509.GLenum
-  GL_POST_CONVOLUTION_GREEN_SCALE* = 0x801D.GLenum
-  GL_UNSIGNED_INT8_NV* = 0x8FEC.GLenum
-  GL_CURRENT_MATRIX_STACK_DEPTH_NV* = 0x8640.GLenum
-  GL_STENCIL_INDEX1_OES* = 0x8D46.GLenum
-  GL_SLUMINANCE_NV* = 0x8C46.GLenum
-  GL_UNSIGNED_INT_8_8_8_8_REV_EXT* = 0x8367.GLenum
-  GL_HISTOGRAM_FORMAT* = 0x8027.GLenum
-  GL_LUMINANCE12_ALPHA4_EXT* = 0x8046.GLenum
-  GL_FLOAT_MAT3* = 0x8B5B.GLenum
-  GL_MAX_PROGRAM_TEXEL_OFFSET_NV* = 0x8905.GLenum
-  GL_PALETTE8_RGBA4_OES* = 0x8B98.GLenum
-  GL_UNPACK_SKIP_IMAGES_EXT* = 0x806D.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Y* = 0x8518.GLenum
-  GL_UNPACK_SUBSAMPLE_RATE_SGIX* = 0x85A1.GLenum
-  GL_NORMAL_ARRAY_LENGTH_NV* = 0x8F2C.GLenum
-  GL_VERTEX_ATTRIB_ARRAY4_NV* = 0x8654.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_OES* = 0x8CD9.GLenum
-  GL_UNSIGNED_BYTE* = 0x1401.GLenum
-  GL_RGB2_EXT* = 0x804E.GLenum
-  GL_TEXTURE_BUFFER_SIZE* = 0x919E.GLenum
-  GL_MAP_STENCIL* = 0x0D11.GLenum
-  GL_TIMEOUT_EXPIRED_APPLE* = 0x911B.GLenum
-  GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS* = 0x8C29.GLenum
-  GL_CON_14_ATI* = 0x894F.GLenum
-  GL_RGBA12* = 0x805A.GLenum
-  GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS* = 0x919A.GLenum
-  GL_CON_20_ATI* = 0x8955.GLenum
-  GL_LOCAL_CONSTANT_DATATYPE_EXT* = 0x87ED.GLenum
-  GL_DUP_FIRST_CUBIC_CURVE_TO_NV* = 0xF2.GLenum
-  GL_SECONDARY_COLOR_ARRAY_ADDRESS_NV* = 0x8F27.GLenum
-  GL_TEXTURE_COORD_ARRAY* = 0x8078.GLenum
-  GL_LUMINANCE8I_EXT* = 0x8D92.GLenum
-  GL_REPLACE_OLDEST_SUN* = 0x0003.GLenum
-  GL_TEXTURE_SHADER_NV* = 0x86DE.GLenum
-  GL_UNSIGNED_INT_8_8_8_8_EXT* = 0x8035.GLenum
-  GL_SAMPLE_COVERAGE_INVERT* = 0x80AB.GLenum
-  GL_FOG_COORD_ARRAY_ADDRESS_NV* = 0x8F28.GLenum
-  GL_GPU_DISJOINT_EXT* = 0x8FBB.GLenum
-  GL_STENCIL_BACK_PASS_DEPTH_PASS_ATI* = 0x8803.GLenum
-  GL_TEXTURE_GREEN_SIZE_EXT* = 0x805D.GLenum
-  GL_INTERLEAVED_ATTRIBS* = 0x8C8C.GLenum
-  GL_FOG_FUNC_SGIS* = 0x812A.GLenum
-  GL_TEXTURE_DEPTH_SIZE_ARB* = 0x884A.GLenum
-  GL_MAP_COHERENT_BIT* = 0x0080.GLbitfield
-  GL_COMPRESSED_SLUMINANCE_ALPHA* = 0x8C4B.GLenum
-  GL_RGB32UI* = 0x8D71.GLenum
-  GL_SEPARABLE_2D* = 0x8012.GLenum
-  GL_MATRIX10_ARB* = 0x88CA.GLenum
-  GL_FLOAT_RGBA32_NV* = 0x888B.GLenum
-  GL_MAX_SPARSE_3D_TEXTURE_SIZE_ARB* = 0x9199.GLenum
-  GL_TEXTURE_RENDERBUFFER_DATA_STORE_BINDING_NV* = 0x8E54.GLenum
-  GL_REG_9_ATI* = 0x892A.GLenum
-  GL_MAP2_VERTEX_ATTRIB14_4_NV* = 0x867E.GLenum
-  GL_OP_EXP_BASE_2_EXT* = 0x8791.GLenum
-  GL_INT_IMAGE_BUFFER_EXT* = 0x905C.GLenum
-  GL_TEXTURE_WRAP_R_EXT* = 0x8072.GLenum
-  GL_DOUBLE_VEC3* = 0x8FFD.GLenum
-  GL_DRAW_BUFFER5_EXT* = 0x882A.GLenum
-  GL_OUTPUT_TEXTURE_COORD7_EXT* = 0x87A4.GLenum
-  GL_DEBUG_OUTPUT_SYNCHRONOUS_ARB* = 0x8242.GLenum
-  GL_MAX_TESS_GEN_LEVEL* = 0x8E7E.GLenum
-  GL_ELEMENT_ARRAY_BUFFER_BINDING_ARB* = 0x8895.GLenum
-  GL_RGBA16I_EXT* = 0x8D88.GLenum
-  GL_REG_10_ATI* = 0x892B.GLenum
-  GL_MAT_EMISSION_BIT_PGI* = 0x00800000.GLbitfield
-  GL_TEXTURE_COORD_ARRAY_SIZE_EXT* = 0x8088.GLenum
-  GL_RED_BIAS* = 0x0D15.GLenum
-  GL_RGB16F_ARB* = 0x881B.GLenum
-  GL_ANY_SAMPLES_PASSED_CONSERVATIVE* = 0x8D6A.GLenum
-  GL_BLUE_MAX_CLAMP_INGR* = 0x8566.GLenum
-  cGL_FLOAT* = 0x1406.GLenum
-  GL_STENCIL_INDEX8_EXT* = 0x8D48.GLenum
-  GL_POINT_SIZE_ARRAY_OES* = 0x8B9C.GLenum
-  GL_INT16_NV* = 0x8FE4.GLenum
-  GL_PALETTE4_RGB8_OES* = 0x8B90.GLenum
-  GL_RENDERBUFFER_GREEN_SIZE_OES* = 0x8D51.GLenum
-  GL_SEPARATE_ATTRIBS_NV* = 0x8C8D.GLenum
-  GL_BOOL_VEC3_ARB* = 0x8B58.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_ACTIVE_ATOMIC_COUNTER_INDICES* = 0x92C6.GLenum
-  GL_STACK_UNDERFLOW_KHR* = 0x0504.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB* = 0x8519.GLenum
-  GL_COMPRESSED_INTENSITY_ARB* = 0x84EC.GLenum
-  GL_MAX_ASYNC_TEX_IMAGE_SGIX* = 0x835F.GLenum
-  GL_TEXTURE_4D_SGIS* = 0x8134.GLenum
-  GL_TEXCOORD3_BIT_PGI* = 0x40000000.GLbitfield
-  GL_PIXEL_MAP_I_TO_R_SIZE* = 0x0CB2.GLenum
-  GL_NORMAL_MAP_ARB* = 0x8511.GLenum
-  GL_MAX_CONVOLUTION_HEIGHT* = 0x801B.GLenum
-  GL_COMPRESSED_INTENSITY* = 0x84EC.GLenum
-  GL_FONT_Y_MAX_BOUNDS_BIT_NV* = 0x00080000.GLbitfield
-  GL_FLOAT_MAT2* = 0x8B5A.GLenum
-  GL_TEXTURE_SRGB_DECODE_EXT* = 0x8A48.GLenum
-  GL_FRAMEBUFFER_BLEND* = 0x828B.GLenum
-  GL_TEXTURE_COORD_ARRAY_LIST_IBM* = 103074.GLenum
-  GL_REG_12_ATI* = 0x892D.GLenum
-  GL_UNSIGNED_INT_ATOMIC_COUNTER* = 0x92DB.GLenum
-  GL_DETAIL_TEXTURE_2D_BINDING_SGIS* = 0x8096.GLenum
-  GL_OCCLUSION_TEST_HP* = 0x8165.GLenum
-  GL_TEXTURE11_ARB* = 0x84CB.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC* = 0x9279.GLenum
-  GL_BUFFER_MAPPED* = 0x88BC.GLenum
-  GL_VARIANT_ARRAY_STRIDE_EXT* = 0x87E6.GLenum
-  GL_CONVOLUTION_BORDER_COLOR_HP* = 0x8154.GLenum
-  GL_UNPACK_RESAMPLE_OML* = 0x8985.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_SIZE* = 0x8C85.GLenum
-  GL_PROXY_TEXTURE_2D_ARRAY_EXT* = 0x8C1B.GLenum
-  GL_RGBA4_EXT* = 0x8056.GLenum
-  GL_ALPHA32I_EXT* = 0x8D84.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_DATA_SIZE* = 0x92C4.GLenum
-  GL_FRAGMENT_LIGHT_MODEL_AMBIENT_SGIX* = 0x840A.GLenum
-  GL_BINORMAL_ARRAY_TYPE_EXT* = 0x8440.GLenum
-  GL_VIEW_CLASS_S3TC_DXT5_RGBA* = 0x82CF.GLenum
-  GL_TEXTURE_CLIPMAP_OFFSET_SGIX* = 0x8173.GLenum
-  GL_RESTART_SUN* = 0x0001.GLenum
-  GL_PERTURB_EXT* = 0x85AE.GLenum
-  GL_UNSIGNED_BYTE_3_3_2_EXT* = 0x8032.GLenum
-  GL_LUMINANCE16I_EXT* = 0x8D8C.GLenum
-  GL_TEXTURE3_ARB* = 0x84C3.GLenum
-  GL_POINT_SIZE_MIN_EXT* = 0x8126.GLenum
-  GL_OUTPUT_TEXTURE_COORD1_EXT* = 0x879E.GLenum
-  GL_COMPARE_REF_TO_TEXTURE* = 0x884E.GLenum
-  GL_KEEP* = 0x1E00.GLenum
-  GL_FLOAT_MAT2x4* = 0x8B66.GLenum
-  GL_FLOAT_VEC4_ARB* = 0x8B52.GLenum
-  GL_BIAS_BY_NEGATIVE_ONE_HALF_NV* = 0x8541.GLenum
-  GL_BGR* = 0x80E0.GLenum
-  GL_SHADER_BINARY_FORMATS* = 0x8DF8.GLenum
-  GL_CND0_ATI* = 0x896B.GLenum
-  GL_MIRRORED_REPEAT_IBM* = 0x8370.GLint
-  GL_REFLECTION_MAP_OES* = 0x8512.GLenum
-  GL_MAX_VERTEX_BINDABLE_UNIFORMS_EXT* = 0x8DE2.GLenum
-  GL_R* = 0x2002.GLenum
-  GL_MAX_SHADER_STORAGE_BLOCK_SIZE* = 0x90DE.GLenum
-  GL_ATTRIB_ARRAY_STRIDE_NV* = 0x8624.GLenum
-  GL_VARIABLE_E_NV* = 0x8527.GLenum
-  GL_HISTOGRAM_EXT* = 0x8024.GLenum
-  GL_TEXTURE_BINDING_BUFFER_ARB* = 0x8C2C.GLenum
-  GL_MAX_SPARSE_TEXTURE_SIZE_ARB* = 0x9198.GLenum
-  GL_TEXTURE5* = 0x84C5.GLenum
-  GL_NUM_ACTIVE_VARIABLES* = 0x9304.GLenum
-  GL_DEPTH_STENCIL_ATTACHMENT* = 0x821A.GLenum
-  GL_WEIGHT_ARRAY_BUFFER_BINDING_ARB* = 0x889E.GLenum
-  GL_AMBIENT_AND_DIFFUSE* = 0x1602.GLenum
-  GL_LAYER_NV* = 0x8DAA.GLenum
-  GL_GLYPH_HORIZONTAL_BEARING_Y_BIT_NV* = 0x08.GLbitfield
-  GL_TEXTURE8* = 0x84C8.GLenum
-  GL_MODELVIEW5_ARB* = 0x8725.GLenum
-  GL_MAX_COMBINED_ATOMIC_COUNTER_BUFFERS* = 0x92D1.GLenum
-  GL_MAX_TESS_CONTROL_ATOMIC_COUNTER_BUFFERS* = 0x92CD.GLenum
-  GL_BLUE_MIN_CLAMP_INGR* = 0x8562.GLenum
-  GL_MAX_TESS_EVALUATION_SHADER_STORAGE_BLOCKS* = 0x90D9.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Z_OES* = 0x8519.GLenum
-  GL_MAX_SAMPLES_IMG* = 0x9135.GLenum
-  GL_QUERY_BY_REGION_WAIT* = 0x8E15.GLenum
-  GL_T* = 0x2001.GLenum
-  GL_VIEW_CLASS_RGTC2_RG* = 0x82D1.GLenum
-  GL_TEXTURE_ENV_MODE* = 0x2200.GLenum
-  GL_COMPRESSED_SRGB8_ETC2* = 0x9275.GLenum
-  GL_MAP_FLUSH_EXPLICIT_BIT* = 0x0010.GLbitfield
-  GL_COLOR_MATERIAL_PARAMETER* = 0x0B56.GLenum
-  GL_HALF_FLOAT_ARB* = 0x140B.GLenum
-  GL_NOTEQUAL* = 0x0205.GLenum
-  GL_MAP_INVALIDATE_BUFFER_BIT_EXT* = 0x0008.GLbitfield
-  GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_EXT* = 0x8C29.GLenum
-  GL_DUAL_TEXTURE_SELECT_SGIS* = 0x8124.GLenum
-  GL_TEXTURE31* = 0x84DF.GLenum
-  GL_EVAL_TRIANGULAR_2D_NV* = 0x86C1.GLenum
-  GL_VIDEO_COLOR_CONVERSION_OFFSET_NV* = 0x902C.GLenum
-  GL_COMPRESSED_R11_EAC_OES* = 0x9270.GLenum
-  GL_RGB8_OES* = 0x8051.GLenum
-  GL_CLIP_PLANE2* = 0x3002.GLenum
-  GL_HINT_BIT* = 0x00008000.GLbitfield
-  GL_TEXTURE6_ARB* = 0x84C6.GLenum
-  GL_FLOAT_VEC2* = 0x8B50.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_SIZE_EXT* = 0x8C85.GLenum
-  GL_MAX_EVAL_ORDER* = 0x0D30.GLenum
-  GL_DUAL_LUMINANCE8_SGIS* = 0x8115.GLenum
-  GL_ALPHA16I_EXT* = 0x8D8A.GLenum
-  GL_IDENTITY_NV* = 0x862A.GLenum
-  GL_VIEW_CLASS_BPTC_UNORM* = 0x82D2.GLenum
-  GL_PATH_DASH_CAPS_NV* = 0x907B.GLenum
-  GL_IGNORE_BORDER_HP* = 0x8150.GLenum
-  GL_PN_TRIANGLES_POINT_MODE_CUBIC_ATI* = 0x87F6.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_EXT* = 0x8C8B.GLenum
-  GL_DRAW_BUFFER1_ATI* = 0x8826.GLenum
-  GL_TEXTURE_MIN_FILTER* = 0x2801.GLenum
-  GL_EVAL_VERTEX_ATTRIB12_NV* = 0x86D2.GLenum
-  GL_INT_IMAGE_2D_ARRAY* = 0x905E.GLenum
-  GL_SRC0_RGB* = 0x8580.GLenum
-  GL_MIN_EXT* = 0x8007.GLenum
-  GL_PROGRAM_PIPELINE_OBJECT_EXT* = 0x8A4F.GLenum
-  GL_STENCIL_BUFFER_BIT* = 0x00000400.GLbitfield
-  GL_SCREEN_COORDINATES_REND* = 0x8490.GLenum
-  GL_DOUBLE_VEC3_EXT* = 0x8FFD.GLenum
-  GL_SUBSAMPLE_DISTANCE_AMD* = 0x883F.GLenum
-  GL_VERTEX_SHADER_LOCALS_EXT* = 0x87D3.GLenum
-  GL_VERTEX_ATTRIB_ARRAY13_NV* = 0x865D.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR* = 0x93D9.GLenum
-  GL_UNSIGNED_NORMALIZED* = 0x8C17.GLenum
-  GL_DRAW_BUFFER10_NV* = 0x882F.GLenum
-  GL_PATH_STROKE_MASK_NV* = 0x9084.GLenum
-  GL_MAX_PROGRAM_NATIVE_TEMPORARIES_ARB* = 0x88A7.GLenum
-  GL_SRGB_ALPHA_EXT* = 0x8C42.GLenum
-  GL_CONST_EYE_NV* = 0x86E5.GLenum
-  GL_MODELVIEW1_ARB* = 0x850A.GLenum
-  GL_FORMAT_SUBSAMPLE_244_244_OML* = 0x8983.GLenum
-  GL_LOGIC_OP_MODE* = 0x0BF0.GLenum
-  GL_CLIP_DISTANCE4* = 0x3004.GLenum
-  GL_DEBUG_CATEGORY_WINDOW_SYSTEM_AMD* = 0x914A.GLenum
-  GL_SAMPLES* = 0x80A9.GLenum
-  GL_UNSIGNED_SHORT_5_5_5_1_EXT* = 0x8034.GLenum
-  GL_POINT_DISTANCE_ATTENUATION* = 0x8129.GLenum
-  GL_3D_COLOR* = 0x0602.GLenum
-  GL_BGRA* = 0x80E1.GLenum
-  GL_PARAMETER_BUFFER_BINDING_ARB* = 0x80EF.GLenum
-  GL_EDGE_FLAG_ARRAY_LIST_STRIDE_IBM* = 103085.GLenum
-  GL_HSL_LUMINOSITY_NV* = 0x92B0.GLenum
-  GL_PROJECTION_STACK_DEPTH* = 0x0BA4.GLenum
-  GL_COMBINER_BIAS_NV* = 0x8549.GLenum
-  GL_AND* = 0x1501.GLenum
-  GL_TEXTURE27* = 0x84DB.GLenum
-  GL_VERTEX_PROGRAM_CALLBACK_DATA_MESA* = 0x8BB7.GLenum
-  GL_DRAW_BUFFER13_ATI* = 0x8832.GLenum
-  GL_UNSIGNED_SHORT_5_5_5_1* = 0x8034.GLenum
-  GL_PERFMON_GLOBAL_MODE_QCOM* = 0x8FA0.GLenum
-  GL_RED_EXT* = 0x1903.GLenum
-  GL_INNOCENT_CONTEXT_RESET_EXT* = 0x8254.GLenum
-  GL_UNIFORM_BUFFER_START* = 0x8A29.GLenum
-  GL_MAX_UNIFORM_BUFFER_BINDINGS* = 0x8A2F.GLenum
-  GL_SLICE_ACCUM_SUN* = 0x85CC.GLenum
-  GL_DRAW_BUFFER9_ATI* = 0x882E.GLenum
-  GL_VERTEX_PROGRAM_PARAMETER_BUFFER_NV* = 0x8DA2.GLenum
-  GL_READ_FRAMEBUFFER_BINDING_APPLE* = 0x8CAA.GLenum
-  GL_INDEX_ARRAY_LENGTH_NV* = 0x8F2E.GLenum
-  GL_DETAIL_TEXTURE_MODE_SGIS* = 0x809B.GLenum
-  GL_MATRIX13_ARB* = 0x88CD.GLenum
-  GL_ADD_SIGNED_ARB* = 0x8574.GLenum
-  GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE* = 0x910A.GLenum
-  GL_DEPTH_BITS* = 0x0D56.GLenum
-  GL_LUMINANCE_ALPHA_SNORM* = 0x9012.GLenum
-  GL_VIEW_CLASS_RGTC1_RED* = 0x82D0.GLenum
-  GL_LINE_WIDTH* = 0x0B21.GLenum
-  GL_DRAW_BUFFER14_ATI* = 0x8833.GLenum
-  GL_CON_30_ATI* = 0x895F.GLenum
-  GL_POST_COLOR_MATRIX_BLUE_BIAS* = 0x80BA.GLenum
-  GL_PIXEL_TRANSFORM_2D_EXT* = 0x8330.GLenum
-  GL_CONTEXT_LOST_WEBGL* = 0x9242.GLenum
-  GL_COLOR_TABLE_BLUE_SIZE_SGI* = 0x80DC.GLenum
-  GL_CONSTANT_EXT* = 0x8576.GLenum
-  GL_IMPLEMENTATION_COLOR_READ_TYPE* = 0x8B9A.GLenum
-  GL_HSL_COLOR_NV* = 0x92AF.GLenum
-  GL_LOAD* = 0x0101.GLenum
-  GL_TEXTURE_BIT* = 0x00040000.GLbitfield
-  GL_FRAMEBUFFER_INCOMPLETE_DIMENSIONS_EXT* = 0x8CD9.GLenum
-  GL_IMAGE_ROTATE_ORIGIN_X_HP* = 0x815A.GLenum
-  GL_DEPTH_BUFFER_BIT6_QCOM* = 0x00004000.GLbitfield
-  GL_QUERY* = 0x82E3.GLenum
-  GL_INVALID_VALUE* = 0x0501.GLenum
-  GL_PACK_COMPRESSED_BLOCK_HEIGHT* = 0x912C.GLenum
-  GL_MAX_PROGRAM_GENERIC_RESULTS_NV* = 0x8DA6.GLenum
-  GL_BACK_PRIMARY_COLOR_NV* = 0x8C77.GLenum
-  GL_ALPHA8_OES* = 0x803C.GLenum
-  GL_INDEX* = 0x8222.GLenum
-  GL_ATTRIB_ARRAY_SIZE_NV* = 0x8623.GLenum
-  GL_INT_IMAGE_1D_ARRAY* = 0x905D.GLenum
-  GL_LOCATION* = 0x930E.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT* = 0x8CD7.GLenum
-  GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_WRITE* = 0x82AF.GLenum
-  GL_RESAMPLE_ZERO_FILL_SGIX* = 0x842F.GLenum
-  GL_VERTEX_ARRAY_BINDING_OES* = 0x85B5.GLenum
-  GL_MATRIX4_ARB* = 0x88C4.GLenum
-  GL_NEXT_BUFFER_NV* = -2
-  GL_ELEMENT_ARRAY_BARRIER_BIT* = 0x00000002.GLbitfield
-  GL_RGBA16_EXT* = 0x805B.GLenum
-  GL_SEPARABLE_2D_EXT* = 0x8012.GLenum
-  GL_R11F_G11F_B10F_EXT* = 0x8C3A.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER_EXT* = 0x8CD4.GLenum
-  GL_IMAGE_2D_EXT* = 0x904D.GLenum
-  GL_DRAW_BUFFER6_NV* = 0x882B.GLenum
-  GL_TEXTURE_RANGE_LENGTH_APPLE* = 0x85B7.GLenum
-  GL_TEXTURE_RED_TYPE_ARB* = 0x8C10.GLenum
-  GL_ALPHA16F_ARB* = 0x881C.GLenum
-  GL_DEBUG_LOGGED_MESSAGES_ARB* = 0x9145.GLenum
-  GL_TRANSPOSE_MODELVIEW_MATRIX_ARB* = 0x84E3.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_EXT* = 0x8C8F.GLenum
-  GL_MAX_CONVOLUTION_WIDTH* = 0x801A.GLenum
-  GL_MIN_FRAGMENT_INTERPOLATION_OFFSET_NV* = 0x8E5B.GLenum
-  GL_PIXEL_TILE_CACHE_SIZE_SGIX* = 0x8145.GLenum
-  GL_4PASS_0_SGIS* = 0x80A4.GLenum
-  GL_PRIMITIVE_RESTART* = 0x8F9D.GLenum
-  GL_RG16_SNORM* = 0x8F99.GLenum
-  GL_SAMPLER_2D_SHADOW_EXT* = 0x8B62.GLenum
-  GL_FRONT* = 0x0404.GLenum
-  GL_PROXY_TEXTURE_2D_MULTISAMPLE_ARRAY* = 0x9103.GLenum
-  GL_SAMPLER_BINDING* = 0x8919.GLenum
-  GL_TEXTURE_2D_STACK_MESAX* = 0x875A.GLenum
-  GL_ASYNC_HISTOGRAM_SGIX* = 0x832C.GLenum
-  GL_IMPLEMENTATION_COLOR_READ_FORMAT_OES* = 0x8B9B.GLenum
-  GL_OP_SET_LT_EXT* = 0x878D.GLenum
-  GL_INTERNALFORMAT_RED_TYPE* = 0x8278.GLenum
-  GL_AUX2* = 0x040B.GLenum
-  GL_CLAMP_FRAGMENT_COLOR* = 0x891B.GLenum
-  GL_BROWSER_DEFAULT_WEBGL* = 0x9244.GLenum
-  GL_IMAGE_CLASS_11_11_10* = 0x82C2.GLenum
-  GL_BUMP_ENVMAP_ATI* = 0x877B.GLenum
-  GL_FLOAT_32_UNSIGNED_INT_24_8_REV_NV* = 0x8DAD.GLenum
-  GL_RG_SNORM* = 0x8F91.GLenum
-  GL_BUMP_ROT_MATRIX_ATI* = 0x8775.GLenum
-  GL_UNIFORM_TYPE* = 0x8A37.GLenum
-  GL_FRAGMENT_COLOR_MATERIAL_PARAMETER_SGIX* = 0x8403.GLenum
-  GL_TEXTURE_BINDING_CUBE_MAP_ARRAY* = 0x900A.GLenum
-  GL_LUMINANCE12* = 0x8041.GLenum
-  GL_QUERY_NO_WAIT_NV* = 0x8E14.GLenum
-  GL_TEXTURE_CUBE_MAP_ARRAY_ARB* = 0x9009.GLenum
-  GL_QUERY_BY_REGION_NO_WAIT_NV* = 0x8E16.GLenum
-  GL_FOG_END* = 0x0B64.GLenum
-  GL_OBJECT_LINK_STATUS_ARB* = 0x8B82.GLenum
-  GL_TEXTURE_COORD_ARRAY_SIZE* = 0x8088.GLenum
-  GL_SOURCE0_ALPHA_ARB* = 0x8588.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB* = 0x8518.GLenum
-  GL_FRAGMENT_LIGHT_MODEL_NORMAL_INTERPOLATION_SGIX* = 0x840B.GLenum
-  GL_STATIC_COPY* = 0x88E6.GLenum
-  GL_LINE_WIDTH_RANGE* = 0x0B22.GLenum
-  GL_VERTEX_SOURCE_ATI* = 0x8774.GLenum
-  GL_FLOAT_MAT4x3* = 0x8B6A.GLenum
-  GL_HALF_APPLE* = 0x140B.GLenum
-  GL_TEXTURE11* = 0x84CB.GLenum
-  GL_DECODE_EXT* = 0x8A49.GLenum
-  GL_VERTEX_ARRAY_STRIDE_EXT* = 0x807C.GLenum
-  GL_SAMPLER_BUFFER_EXT* = 0x8DC2.GLenum
-  GL_TEXTURE_LOD_BIAS_EXT* = 0x8501.GLenum
-  GL_MODULATE_SIGNED_ADD_ATI* = 0x8745.GLenum
-  GL_DEPTH_CLEAR_VALUE* = 0x0B73.GLenum
-  GL_COMPRESSED_ALPHA* = 0x84E9.GLenum
-  GL_TEXTURE_1D_STACK_MESAX* = 0x8759.GLenum
-  GL_TEXTURE_FIXED_SAMPLE_LOCATIONS* = 0x9107.GLenum
-  GL_LARGE_CCW_ARC_TO_NV* = 0x16.GLenum
-  GL_COMBINER1_NV* = 0x8551.GLenum
-  GL_ARRAY_SIZE* = 0x92FB.GLenum
-  GL_MAX_COMPUTE_IMAGE_UNIFORMS* = 0x91BD.GLenum
-  GL_TEXTURE_BINDING_EXTERNAL_OES* = 0x8D67.GLenum
-  GL_REG_26_ATI* = 0x893B.GLenum
-  GL_MUL_ATI* = 0x8964.GLenum
-  GL_STENCIL_BUFFER_BIT6_QCOM* = 0x00400000.GLbitfield
-  GL_INVALID_OPERATION* = 0x0502.GLenum
-  GL_COLOR_SUM* = 0x8458.GLenum
-  GL_OP_CROSS_PRODUCT_EXT* = 0x8797.GLenum
-  GL_COLOR_ATTACHMENT4_NV* = 0x8CE4.GLenum
-  GL_MAX_RECTANGLE_TEXTURE_SIZE_NV* = 0x84F8.GLenum
-  GL_BOOL_ARB* = 0x8B56.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_TYPE_ARB* = 0x8625.GLenum
-  GL_MODELVIEW8_ARB* = 0x8728.GLenum
-  GL_STENCIL_TEST* = 0x0B90.GLenum
-  GL_SRC_OVER_NV* = 0x9288.GLenum
-  GL_COMPRESSED_LUMINANCE* = 0x84EA.GLenum
-  GL_MAX_GEOMETRY_PROGRAM_INVOCATIONS_NV* = 0x8E5A.GLenum
-  GL_WEIGHT_ARRAY_TYPE_ARB* = 0x86A9.GLenum
-  GL_WRITE_PIXEL_DATA_RANGE_POINTER_NV* = 0x887C.GLenum
-  GL_COLOR_ARRAY_STRIDE_EXT* = 0x8083.GLenum
-  GL_BLEND_SRC_ALPHA_EXT* = 0x80CB.GLenum
-  GL_MAX_PROGRAM_LOCAL_PARAMETERS_ARB* = 0x88B4.GLenum
-  GL_SCALAR_EXT* = 0x87BE.GLenum
-  GL_DEBUG_SEVERITY_MEDIUM_KHR* = 0x9147.GLenum
-  GL_IMAGE_SCALE_X_HP* = 0x8155.GLenum
-  GL_LUMINANCE6_ALPHA2_EXT* = 0x8044.GLenum
-  GL_OUTPUT_TEXTURE_COORD22_EXT* = 0x87B3.GLenum
-  GL_CURRENT_PROGRAM* = 0x8B8D.GLenum
-  GL_FRAGMENT_PROGRAM_ARB* = 0x8804.GLenum
-  GL_INFO_LOG_LENGTH* = 0x8B84.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Z* = 0x8519.GLenum
-  GL_PROJECTION_MATRIX_FLOAT_AS_INT_BITS_OES* = 0x898E.GLenum
-  GL_PRIMITIVE_RESTART_FIXED_INDEX* = 0x8D69.GLenum
-  GL_ARRAY_BUFFER_ARB* = 0x8892.GLenum
-  GL_DEPTH_STENCIL_MESA* = 0x8750.GLenum
-  GL_LUMINANCE8_OES* = 0x8040.GLenum
-  GL_REFLECTION_MAP_EXT* = 0x8512.GLenum
-  GL_PRIMITIVES_GENERATED* = 0x8C87.GLenum
-  GL_IMAGE_PIXEL_FORMAT* = 0x82A9.GLenum
-  GL_VERTEX_ARRAY_LIST_STRIDE_IBM* = 103080.GLenum
-  GL_MAP2_COLOR_4* = 0x0DB0.GLenum
-  GL_MULTIPLY_NV* = 0x9294.GLenum
-  GL_UNIFORM_BARRIER_BIT_EXT* = 0x00000004.GLbitfield
-  GL_STENCIL_BUFFER_BIT3_QCOM* = 0x00080000.GLbitfield
-  GL_REG_7_ATI* = 0x8928.GLenum
-  GL_STATIC_READ_ARB* = 0x88E5.GLenum
-  GL_MATRIX2_ARB* = 0x88C2.GLenum
-  GL_STENCIL_BUFFER_BIT5_QCOM* = 0x00200000.GLbitfield
-  GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS_ARB* = 0x8B4C.GLenum
-  GL_COMPRESSED_RGBA_PVRTC_2BPPV1_IMG* = 0x8C03.GLenum
-  GL_R1UI_T2F_N3F_V3F_SUN* = 0x85CA.GLenum
-  GL_TEXTURE27_ARB* = 0x84DB.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_FORMATS_OES* = 0x8CDA.GLenum
-  GL_MAX_PROGRAM_TEXEL_OFFSET* = 0x8905.GLenum
-  GL_INT_SAMPLER_2D_ARRAY_EXT* = 0x8DCF.GLenum
-  GL_DRAW_BUFFER9_EXT* = 0x882E.GLenum
-  GL_RGB5_A1_EXT* = 0x8057.GLenum
-  GL_FIELDS_NV* = 0x8E27.GLenum
-  GL_MAX_TRACK_MATRIX_STACK_DEPTH_NV* = 0x862E.GLenum
-  GL_SHADER_COMPILER* = 0x8DFA.GLenum
-  GL_SRC2_ALPHA* = 0x858A.GLenum
-  GL_TRACE_NAME_MESA* = 0x8756.GLenum
-  GL_MIRROR_CLAMP_TO_EDGE* = 0x8743.GLint
-  GL_OPERAND0_RGB_EXT* = 0x8590.GLenum
-  GL_UNSIGNED_BYTE_2_3_3_REV_EXT* = 0x8362.GLenum
-  GL_UNSIGNED_INT_2_10_10_10_REV* = 0x8368.GLenum
-  GL_MAX_CLIP_DISTANCES* = 0x0D32.GLenum
-  GL_MAP2_TEXTURE_COORD_3* = 0x0DB5.GLenum
-  GL_DUAL_LUMINANCE16_SGIS* = 0x8117.GLenum
-  GL_TEXTURE_UPDATE_BARRIER_BIT_EXT* = 0x00000100.GLbitfield
-  GL_IMAGE_BUFFER_EXT* = 0x9051.GLenum
-  GL_REDUCE_EXT* = 0x8016.GLenum
-  GL_EVAL_VERTEX_ATTRIB9_NV* = 0x86CF.GLenum
-  GL_IMAGE_CLASS_4_X_32* = 0x82B9.GLenum
-  GL_MAX_FRAGMENT_BINDABLE_UNIFORMS_EXT* = 0x8DE3.GLenum
-  GL_FRAGMENTS_INSTRUMENT_MAX_SGIX* = 0x8315.GLenum
-  GL_REG_28_ATI* = 0x893D.GLenum
-  GL_VARIABLE_B_NV* = 0x8524.GLenum
-  GL_GET_TEXTURE_IMAGE_TYPE* = 0x8292.GLenum
-  GL_PERCENTAGE_AMD* = 0x8BC3.GLenum
-  GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_ARB* = 0x8DE1.GLenum
-  GL_MAX_COMPUTE_UNIFORM_BLOCKS* = 0x91BB.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_APPLE* = 0x8D56.GLenum
-  GL_PROVOKING_VERTEX* = 0x8E4F.GLenum
-  GL_FRAMEZOOM_FACTOR_SGIX* = 0x818C.GLenum
-  GL_COLOR_TABLE_ALPHA_SIZE* = 0x80DD.GLenum
-  GL_PIXEL_TEXTURE_SGIS* = 0x8353.GLenum
-  GL_MODELVIEW26_ARB* = 0x873A.GLenum
-  GL_MAX_DEBUG_MESSAGE_LENGTH_KHR* = 0x9143.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT* = 0x8519.GLenum
-  GL_VERTEX_SHADER_LOCAL_CONSTANTS_EXT* = 0x87D2.GLenum
-  GL_DRAW_INDIRECT_LENGTH_NV* = 0x8F42.GLenum
-  GL_OPERAND2_RGB_ARB* = 0x8592.GLenum
-  GL_TESS_EVALUATION_SHADER* = 0x8E87.GLenum
-  GL_INTERLACE_SGIX* = 0x8094.GLenum
-  GL_HARDLIGHT_NV* = 0x929B.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_EXT* = 0x8CD0.GLenum
-  GL_OUTPUT_TEXTURE_COORD6_EXT* = 0x87A3.GLenum
-  GL_SIGNED_LUMINANCE_NV* = 0x8701.GLenum
-  GL_CON_13_ATI* = 0x894E.GLenum
-  GL_CURRENT_TANGENT_EXT* = 0x843B.GLenum
-  GL_UNSIGNED_INT_IMAGE_3D* = 0x9064.GLenum
-  GL_MODELVIEW24_ARB* = 0x8738.GLenum
-  GL_EVAL_FRACTIONAL_TESSELLATION_NV* = 0x86C5.GLenum
-  GL_POINT_SPRITE_NV* = 0x8861.GLenum
-  GL_MULTISAMPLE_EXT* = 0x809D.GLenum
-  GL_INT64_VEC3_NV* = 0x8FEA.GLenum
-  GL_ABGR_EXT* = 0x8000.GLenum
-  GL_MAX_GENERAL_COMBINERS_NV* = 0x854D.GLenum
-  GL_NUM_PROGRAM_BINARY_FORMATS* = 0x87FE.GLenum
-  GL_TEXTURE_LO_SIZE_NV* = 0x871C.GLenum
-  GL_INT_IMAGE_1D_ARRAY_EXT* = 0x905D.GLenum
-  GL_MULTISAMPLE_BUFFER_BIT3_QCOM* = 0x08000000.GLbitfield
-  GL_TEXTURE_GEN_MODE_OES* = 0x2500.GLenum
-  GL_SECONDARY_COLOR_ARRAY_STRIDE* = 0x845C.GLenum
-  GL_ELEMENT_ARRAY_TYPE_APPLE* = 0x8A0D.GLenum
-  GL_UNPACK_IMAGE_HEIGHT_EXT* = 0x806E.GLenum
-  GL_PALETTE4_R5_G6_B5_OES* = 0x8B92.GLenum
-  GL_TEXTURE_RED_SIZE* = 0x805C.GLenum
-  GL_COLOR_ATTACHMENT7_EXT* = 0x8CE7.GLenum
-  GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET* = 0x8E5F.GLenum
-  GL_DRAW_BUFFER11* = 0x8830.GLenum
-  GL_MODELVIEW0_MATRIX_EXT* = 0x0BA6.GLenum
-  GL_LAYER_PROVOKING_VERTEX* = 0x825E.GLenum
-  GL_TEXTURE14* = 0x84CE.GLenum
-  GL_ALPHA8_EXT* = 0x803C.GLenum
-  GL_GENERIC_ATTRIB_NV* = 0x8C7D.GLenum
-  GL_FRAGMENT_SHADER_DERIVATIVE_HINT_OES* = 0x8B8B.GLenum
-  GL_STENCIL_ATTACHMENT_OES* = 0x8D20.GLenum
-  GL_MAX_VARYING_FLOATS* = 0x8B4B.GLenum
-  GL_RGB_SNORM* = 0x8F92.GLenum
-  GL_SECONDARY_COLOR_ARRAY_TYPE_EXT* = 0x845B.GLenum
-  GL_MAX_PROGRAM_LOOP_DEPTH_NV* = 0x88F7.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LAYER* = 0x8CD4.GLenum
-  GL_MAX_MODELVIEW_STACK_DEPTH* = 0x0D36.GLenum
-  GL_CON_23_ATI* = 0x8958.GLenum
-  GL_VERTEX_ARRAY_RANGE_POINTER_APPLE* = 0x8521.GLenum
-  GL_VERTEX_ARRAY_BUFFER_BINDING* = 0x8896.GLenum
-  GL_VERTEX_STREAM2_ATI* = 0x876E.GLenum
-  GL_STENCIL* = 0x1802.GLenum
-  GL_IMAGE_2D_ARRAY_EXT* = 0x9053.GLenum
-  GL_RGBA8* = 0x8058.GLenum
-  GL_TEXTURE_SPARSE_ARB* = 0x91A6.GLenum
-  GL_PIXEL_TEX_GEN_ALPHA_NO_REPLACE_SGIX* = 0x8188.GLenum
-  GL_SECONDARY_INTERPOLATOR_ATI* = 0x896D.GLenum
-  GL_MAX_COMBINED_DIMENSIONS* = 0x8282.GLenum
-  GL_DEBUG_TYPE_POP_GROUP* = 0x826A.GLenum
-  GL_IMAGE_CLASS_4_X_8* = 0x82BF.GLenum
-  GL_VERTEX_ARRAY_RANGE_VALID_NV* = 0x851F.GLenum
-  GL_LUMINANCE_ALPHA8UI_EXT* = 0x8D81.GLenum
-  GL_RGBA32F_ARB* = 0x8814.GLenum
-  GL_GLYPH_HEIGHT_BIT_NV* = 0x02.GLbitfield
-  GL_FOG_COORD_ARRAY_BUFFER_BINDING* = 0x889D.GLenum
-  GL_TRACE_OPERATIONS_BIT_MESA* = 0x0001.GLbitfield
-  GL_INT8_VEC4_NV* = 0x8FE3.GLenum
-  GL_VERTEX_BINDING_STRIDE* = 0x82D8.GLenum
-  GL_LIGHT_ENV_MODE_SGIX* = 0x8407.GLenum
-  GL_PROXY_TEXTURE_1D_EXT* = 0x8063.GLenum
-  GL_CON_31_ATI* = 0x8960.GLenum
-  GL_TEXTURE_BORDER_COLOR* = 0x1004.GLenum
-  GL_ELEMENT_ARRAY_POINTER_APPLE* = 0x8A0E.GLenum
-  GL_NAME_LENGTH* = 0x92F9.GLenum
-  GL_PIXEL_COUNT_AVAILABLE_NV* = 0x8867.GLenum
-  GL_IUI_V3F_EXT* = 0x81AE.GLenum
-  GL_OBJECT_LINE_SGIS* = 0x81F7.GLenum
-  GL_T2F_N3F_V3F* = 0x2A2B.GLenum
-  GL_TRUE* = true.GLboolean
-  GL_COMPARE_REF_TO_TEXTURE_EXT* = 0x884E.GLenum
-  GL_MAX_3D_TEXTURE_SIZE* = 0x8073.GLenum
-  GL_LUMINANCE16_ALPHA16_EXT* = 0x8048.GLenum
-  GL_DRAW_INDIRECT_ADDRESS_NV* = 0x8F41.GLenum
-  GL_TEXTURE_IMAGE_FORMAT* = 0x828F.GLenum
-  GL_MODELVIEW_MATRIX_FLOAT_AS_INT_BITS_OES* = 0x898D.GLenum
-  GL_TEXTURE_RECTANGLE_ARB* = 0x84F5.GLenum
-  GL_TEXTURE_INDEX_SIZE_EXT* = 0x80ED.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_LENGTH_NV* = 0x8F2A.GLenum
-  GL_DEBUG_CALLBACK_USER_PARAM* = 0x8245.GLenum
-  GL_INTENSITY8_SNORM* = 0x9017.GLenum
-  GL_DISTANCE_ATTENUATION_EXT* = 0x8129.GLenum
-  GL_MAX_TESS_EVALUATION_IMAGE_UNIFORMS* = 0x90CC.GLenum
-  GL_ATTRIB_ARRAY_POINTER_NV* = 0x8645.GLenum
-  GL_OBJECT_TYPE* = 0x9112.GLenum
-  GL_PROGRAM_KHR* = 0x82E2.GLenum
-  GL_SOURCE0_ALPHA_EXT* = 0x8588.GLenum
-  GL_PIXEL_MAP_I_TO_G_SIZE* = 0x0CB3.GLenum
-  GL_RGBA_MODE* = 0x0C31.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR* = 0x93D6.GLenum
-  GL_MAX_ELEMENTS_VERTICES_EXT* = 0x80E8.GLenum
-  GL_DEBUG_SOURCE_SHADER_COMPILER* = 0x8248.GLenum
-  GL_ARC_TO_NV* = 0xFE.GLenum
-  GL_CON_6_ATI* = 0x8947.GLenum
-  GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCALS_EXT* = 0x87CE.GLenum
-  GL_VERTEX_ATTRIB_MAP1_DOMAIN_APPLE* = 0x8A05.GLenum
-  GL_R16_SNORM* = 0x8F98.GLenum
-  GL_DOUBLE_VEC2_EXT* = 0x8FFC.GLenum
-  GL_UNSIGNED_INT8_VEC4_NV* = 0x8FEF.GLenum
-  GL_POST_CONVOLUTION_RED_SCALE* = 0x801C.GLenum
-  GL_FULL_STIPPLE_HINT_PGI* = 0x1A219.GLenum
-  GL_ACTIVE_ATTRIBUTES* = 0x8B89.GLenum
-  GL_TEXTURE_MATERIAL_FACE_EXT* = 0x8351.GLenum
-  GL_INCR_WRAP_OES* = 0x8507.GLenum
-  GL_UNPACK_COMPRESSED_BLOCK_WIDTH* = 0x9127.GLenum
-  GL_COMPRESSED_SIGNED_LUMINANCE_ALPHA_LATC2_EXT* = 0x8C73.GLenum
-  GL_MAX_VERTEX_SHADER_LOCALS_EXT* = 0x87C9.GLenum
-  GL_NUM_VIDEO_CAPTURE_STREAMS_NV* = 0x9024.GLenum
-  GL_DRAW_BUFFER3_ARB* = 0x8828.GLenum
-  GL_COMBINER_COMPONENT_USAGE_NV* = 0x8544.GLenum
-  GL_ELEMENT_ARRAY_POINTER_ATI* = 0x876A.GLenum
-  GL_RGB8UI_EXT* = 0x8D7D.GLenum
-  GL_RGBA8I* = 0x8D8E.GLenum
-  GL_TEXTURE_WIDTH_QCOM* = 0x8BD2.GLenum
-  GL_DOT3_RGB* = 0x86AE.GLenum
-  GL_VIDEO_CAPTURE_FIELD_LOWER_HEIGHT_NV* = 0x903B.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_X* = 0x8516.GLenum
-  GL_UNIFORM_BUFFER_SIZE* = 0x8A2A.GLenum
-  GL_OPERAND1_ALPHA* = 0x8599.GLenum
-  GL_TEXTURE_INTENSITY_SIZE_EXT* = 0x8061.GLenum
-  GL_DEBUG_TYPE_OTHER* = 0x8251.GLenum
-  GL_MAX_TESS_PATCH_COMPONENTS* = 0x8E84.GLenum
-  GL_UNIFORM_BUFFER_BINDING* = 0x8A28.GLenum
-  GL_INTENSITY_FLOAT16_APPLE* = 0x881D.GLenum
-  GL_TEXTURE_BLUE_SIZE* = 0x805E.GLenum
-  GL_TEXTURE_BUFFER_OFFSET_ALIGNMENT* = 0x919F.GLenum
-  GL_TEXTURE_SWIZZLE_G* = 0x8E43.GLenum
-  GL_MAX_PROGRAM_TEXEL_OFFSET_EXT* = 0x8905.GLenum
-  GL_COLOR_BUFFER_BIT* = 0x00004000.GLbitfield
-  GL_ALPHA_FLOAT32_APPLE* = 0x8816.GLenum
-  GL_PROXY_TEXTURE_2D_EXT* = 0x8064.GLenum
-  GL_STENCIL_COMPONENTS* = 0x8285.GLenum
-  GL_VIDEO_CAPTURE_TO_422_SUPPORTED_NV* = 0x9026.GLenum
-  GL_TEXTURE_COMPRESSED_ARB* = 0x86A1.GLenum
-  GL_OBJECT_SUBTYPE_ARB* = 0x8B4F.GLenum
-  GL_MAX_PROGRAM_PARAMETERS_ARB* = 0x88A9.GLenum
-  GL_OFFSET_TEXTURE_2D_MATRIX_NV* = 0x86E1.GLenum
-  GL_PN_TRIANGLES_NORMAL_MODE_LINEAR_ATI* = 0x87F7.GLenum
-  GL_PATCH_VERTICES* = 0x8E72.GLenum
-  GL_NEGATIVE_Y_EXT* = 0x87DA.GLenum
-  GL_INT_2_10_10_10_REV* = 0x8D9F.GLenum
-  GL_READ_FRAMEBUFFER_BINDING_NV* = 0x8CAA.GLenum
-  GL_POST_COLOR_MATRIX_COLOR_TABLE_SGI* = 0x80D2.GLenum
-  GL_MAX_FRAGMENT_SHADER_STORAGE_BLOCKS* = 0x90DA.GLenum
-  GL_IMAGE_COMPATIBILITY_CLASS* = 0x82A8.GLenum
-  GL_FLOAT_MAT4* = 0x8B5C.GLenum
-  GL_FIELD_LOWER_NV* = 0x9023.GLenum
-  GL_UNPACK_IMAGE_HEIGHT* = 0x806E.GLenum
-  GL_PATH_COMMAND_COUNT_NV* = 0x909D.GLenum
-  GL_UNSIGNED_SHORT_4_4_4_4_EXT* = 0x8033.GLenum
-  GL_VIEW_CLASS_S3TC_DXT3_RGBA* = 0x82CE.GLenum
-  GL_STENCIL_BUFFER_BIT1_QCOM* = 0x00020000.GLbitfield
-  GL_BLOCK_INDEX* = 0x92FD.GLenum
-  GL_BUMP_TARGET_ATI* = 0x877C.GLenum
-  GL_PATH_STROKE_COVER_MODE_NV* = 0x9083.GLenum
-  GL_INT_IMAGE_2D_RECT* = 0x905A.GLenum
-  GL_VECTOR_EXT* = 0x87BF.GLenum
-  GL_INDEX_ARRAY_BUFFER_BINDING* = 0x8899.GLenum
-  GL_SAMPLER_2D_SHADOW* = 0x8B62.GLenum
-  GL_OBJECT_BUFFER_SIZE_ATI* = 0x8764.GLenum
-  GL_NORMALIZED_RANGE_EXT* = 0x87E0.GLenum
-  GL_DEPTH_COMPONENT32_OES* = 0x81A7.GLenum
-  GL_CON_9_ATI* = 0x894A.GLenum
-  GL_VIRTUAL_PAGE_SIZE_X_ARB* = 0x9195.GLenum
-  GL_LESS* = 0x0201.GLenum
-  GL_FRAMEBUFFER_UNSUPPORTED_OES* = 0x8CDD.GLenum
-  GL_CON_19_ATI* = 0x8954.GLenum
-  GL_PROGRAM_NATIVE_INSTRUCTIONS_ARB* = 0x88A2.GLenum
-  GL_MAX_TEXTURE_COORDS_ARB* = 0x8871.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_MODE* = 0x8C7F.GLenum
-  GL_TEXTURE_1D_BINDING_EXT* = 0x8068.GLenum
-  GL_LINE_TOKEN* = 0x0702.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_OES* = 0x8CD7.GLenum
-  GL_Z4Y12Z4CB12Z4A12Z4Y12Z4CR12Z4A12_4224_NV* = 0x9036.GLenum
-  GL_TEXTURE_SWIZZLE_R* = 0x8E42.GLenum
-  GL_PIXEL_UNPACK_BUFFER_ARB* = 0x88EC.GLenum
-  GL_UNKNOWN_CONTEXT_RESET_EXT* = 0x8255.GLenum
-  GL_PROGRAM_ERROR_POSITION_NV* = 0x864B.GLenum
-  GL_ONE_MINUS_CONSTANT_COLOR* = 0x8002.GLenum
-  GL_POST_COLOR_MATRIX_GREEN_SCALE* = 0x80B5.GLenum
-  GL_TEXTURE_CUBE_MAP_SEAMLESS* = 0x884F.GLenum
-  GL_DRAW_BUFFER2* = 0x8827.GLenum
-  GL_STENCIL_INDEX* = 0x1901.GLenum
-  GL_FOG_DENSITY* = 0x0B62.GLenum
-  GL_MATRIX27_ARB* = 0x88DB.GLenum
-  GL_CURRENT_NORMAL* = 0x0B02.GLenum
-  GL_AFFINE_3D_NV* = 0x9094.GLenum
-  GL_STATIC_COPY_ARB* = 0x88E6.GLenum
-  GL_4X_BIT_ATI* = 0x00000002.GLbitfield
-  GL_COLOR_BUFFER_BIT3_QCOM* = 0x00000008.GLbitfield
-  GL_TEXTURE_MATRIX* = 0x0BA8.GLenum
-  GL_UNDEFINED_APPLE* = 0x8A1C.GLenum
-  GL_COLOR_TABLE_LUMINANCE_SIZE_SGI* = 0x80DE.GLenum
-  GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY* = 0x9061.GLenum
-  GL_RELATIVE_ARC_TO_NV* = 0xFF.GLenum
-  GL_UNPACK_PREMULTIPLY_ALPHA_WEBGL* = 0x9241.GLenum
-  GL_READ_FRAMEBUFFER_BINDING_EXT* = 0x8CAA.GLenum
-  GL_TEXTURE_WRAP_R_OES* = 0x8072.GLenum
-  GL_MAX_GEOMETRY_VARYING_COMPONENTS_EXT* = 0x8DDD.GLenum
-  GL_TEXTURE_CUBE_MAP_EXT* = 0x8513.GLenum
-  GL_COMMAND_BARRIER_BIT_EXT* = 0x00000040.GLbitfield
-  GL_DEBUG_SEVERITY_NOTIFICATION* = 0x826B.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR* = 0x93D8.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS* = 0x8C8B.GLenum
-  GL_MAX_DEEP_3D_TEXTURE_WIDTH_HEIGHT_NV* = 0x90D0.GLenum
-  GL_INT_IMAGE_2D_EXT* = 0x9058.GLenum
-  GL_RGB_S3TC* = 0x83A0.GLenum
-  GL_SUCCESS_NV* = 0x902F.GLenum
-  GL_MATRIX_INDEX_ARRAY_SIZE_OES* = 0x8846.GLenum
-  GL_VIEW_CLASS_8_BITS* = 0x82CB.GLenum
-  GL_DONT_CARE* = 0x1100.GLenum
-  GL_FOG_COORDINATE_ARRAY* = 0x8457.GLenum
-  GL_DRAW_BUFFER9* = 0x882E.GLenum
-  GL_TEXTURE28_ARB* = 0x84DC.GLenum
-  GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_ARB* = 0x8E5F.GLenum
-  GL_TEXTURE21* = 0x84D5.GLenum
-  GL_TRANSLATE_Y_NV* = 0x908F.GLenum
-  GL_MODELVIEW17_ARB* = 0x8731.GLenum
-  GL_ALPHA_FLOAT16_ATI* = 0x881C.GLenum
-  GL_DEPTH_STENCIL_OES* = 0x84F9.GLenum
-  GL_QUAD_MESH_SUN* = 0x8614.GLenum
-  GL_PROGRAM_ADDRESS_REGISTERS_ARB* = 0x88B0.GLenum
-  GL_VERTEX_BINDING_OFFSET* = 0x82D7.GLenum
-  GL_FIRST_TO_REST_NV* = 0x90AF.GLenum
-  GL_SHADE_MODEL* = 0x0B54.GLenum
-  GL_INT_IMAGE_2D_ARRAY_EXT* = 0x905E.GLenum
-  GL_FRONT_FACE* = 0x0B46.GLenum
-  GL_PRIMITIVE_RESTART_INDEX* = 0x8F9E.GLenum
-  GL_LUMINANCE8* = 0x8040.GLenum
-  GL_COVERAGE_ALL_FRAGMENTS_NV* = 0x8ED5.GLenum
-  GL_FRAGMENT_ALPHA_MODULATE_IMG* = 0x8C08.GLenum
-  GL_CLIP_PLANE3_IMG* = 0x3003.GLenum
-  GL_EVAL_VERTEX_ATTRIB15_NV* = 0x86D5.GLenum
-  GL_SYNC_GPU_COMMANDS_COMPLETE* = 0x9117.GLenum
-  GL_FALSE* = false.GLboolean
-  GL_MAX_DEBUG_GROUP_STACK_DEPTH_KHR* = 0x826C.GLenum
-  GL_STENCIL_ATTACHMENT_EXT* = 0x8D20.GLenum
-  GL_DST_ATOP_NV* = 0x928F.GLenum
-  GL_REPLACEMENT_CODE_ARRAY_TYPE_SUN* = 0x85C1.GLenum
-  GL_COMBINE4_NV* = 0x8503.GLenum
-  GL_MINMAX_SINK_EXT* = 0x8030.GLenum
-  GL_RG16I* = 0x8239.GLenum
-  GL_BGRA_IMG* = 0x80E1.GLenum
-  GL_REFERENCED_BY_COMPUTE_SHADER* = 0x930B.GLenum
-  GL_MIN_LOD_WARNING_AMD* = 0x919C.GLenum
-  GL_READ_BUFFER_EXT* = 0x0C02.GLenum
-  GL_RGBA8UI_EXT* = 0x8D7C.GLenum
-  GL_LINE_BIT* = 0x00000004.GLbitfield
-  GL_CONDITION_SATISFIED* = 0x911C.GLenum
-  GL_SLUMINANCE_ALPHA* = 0x8C44.GLenum
-  GL_FOG_COORDINATE_ARRAY_TYPE* = 0x8454.GLenum
-  GL_EXPAND_NORMAL_NV* = 0x8538.GLenum
-  GL_TEXTURE_2D_ARRAY_EXT* = 0x8C1A.GLenum
-  GL_SAMPLER_2D_RECT_ARB* = 0x8B63.GLenum
-  GL_CLAMP_TO_BORDER_NV* = 0x812D.GLint
-  GL_MAX_GEOMETRY_OUTPUT_VERTICES_ARB* = 0x8DE0.GLenum
-  GL_TEXCOORD2_BIT_PGI* = 0x20000000.GLbitfield
-  GL_MATRIX0_ARB* = 0x88C0.GLenum
-  GL_STENCIL_BUFFER_BIT2_QCOM* = 0x00040000.GLbitfield
-  GL_COLOR_MATRIX_SGI* = 0x80B1.GLenum
-  GL_PN_TRIANGLES_TESSELATION_LEVEL_ATI* = 0x87F4.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_EXT* = 0x8CDC.GLenum
-  GL_LEFT* = 0x0406.GLenum
-  GL_LO_SCALE_NV* = 0x870F.GLenum
-  GL_STRICT_DEPTHFUNC_HINT_PGI* = 0x1A216.GLenum
-  GL_MAX_COMBINED_TESS_CONTROL_UNIFORM_COMPONENTS* = 0x8E1E.GLenum
-  GL_REPEAT* = 0x2901.GLint
-  GL_DEBUG_TYPE_PORTABILITY_ARB* = 0x824F.GLenum
-  GL_MAX_FRAMEBUFFER_LAYERS* = 0x9317.GLenum
-  GL_TRIANGLE_STRIP* = 0x0005.GLenum
-  GL_RECLAIM_MEMORY_HINT_PGI* = 0x1A1FE.GLenum
-  GL_RELATIVE_LINE_TO_NV* = 0x05.GLenum
-  GL_MAX_LIGHTS* = 0x0D31.GLenum
-  GL_MULTISAMPLE_BIT* = 0x20000000.GLbitfield
-  GL_READ_PIXELS* = 0x828C.GLenum
-  GL_DISCRETE_AMD* = 0x9006.GLenum
-  GL_QUAD_TEXTURE_SELECT_SGIS* = 0x8125.GLenum
-  GL_CON_25_ATI* = 0x895A.GLenum
-  GL_BUFFER_IMMUTABLE_STORAGE* = 0x821F.GLenum
-  GL_FLOAT_R16_NV* = 0x8884.GLenum
-  GL_GREEN_INTEGER_EXT* = 0x8D95.GLenum
-  cGL_FIXED* = 0x140C.GLenum
-  GL_LIST_PRIORITY_SGIX* = 0x8182.GLenum
-  GL_DRAW_BUFFER6_EXT* = 0x882B.GLenum
-  GL_OFFSET_TEXTURE_BIAS_NV* = 0x86E3.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_POINTER_ARB* = 0x8645.GLenum
-  GL_MALI_SHADER_BINARY_ARM* = 0x8F60.GLenum
-  GL_RGB_422_APPLE* = 0x8A1F.GLenum
-  GL_R1UI_N3F_V3F_SUN* = 0x85C7.GLenum
-  GL_VERTEX_ARRAY_OBJECT_EXT* = 0x9154.GLenum
-  GL_UNSIGNED_INT_10F_11F_11F_REV* = 0x8C3B.GLenum
-  GL_VERSION_ES_CM_1_1* = 1.GLenum
-  GL_CLEAR_TEXTURE* = 0x9365.GLenum
-  GL_FLOAT16_VEC3_NV* = 0x8FFA.GLenum
-  GL_TEXTURE_LUMINANCE_TYPE* = 0x8C14.GLenum
-  GL_TRANSFORM_FEEDBACK* = 0x8E22.GLenum
-  GL_POST_CONVOLUTION_COLOR_TABLE* = 0x80D1.GLenum
-  GL_DEPTH_TEST* = 0x0B71.GLenum
-  GL_CON_1_ATI* = 0x8942.GLenum
-  GL_FRAGMENT_SHADER_ATI* = 0x8920.GLenum
-  GL_SAMPLER_1D_ARRAY_SHADOW* = 0x8DC3.GLenum
-  GL_SHADER_STORAGE_BUFFER_OFFSET_ALIGNMENT* = 0x90DF.GLenum
-  GL_MAX_SERVER_WAIT_TIMEOUT* = 0x9111.GLenum
-  GL_VERTEX_SHADER_BIT_EXT* = 0x00000001.GLbitfield
-  GL_TEXTURE_BINDING_CUBE_MAP_OES* = 0x8514.GLenum
-  GL_PIXEL_MAP_S_TO_S_SIZE* = 0x0CB1.GLenum
-  GL_CURRENT_OCCLUSION_QUERY_ID_NV* = 0x8865.GLenum
-  GL_TIMEOUT_IGNORED_APPLE* = 0xFFFFFFFFFFFFFFFF.GLenum
-  GL_MAX_COMPUTE_UNIFORM_COMPONENTS* = 0x8263.GLenum
-  GL_COPY_PIXEL_TOKEN* = 0x0706.GLenum
-  GL_SPOT_CUTOFF* = 0x1206.GLenum
-  GL_FRACTIONAL_EVEN* = 0x8E7C.GLenum
-  GL_MAP1_VERTEX_ATTRIB6_4_NV* = 0x8666.GLenum
-  GL_TRIANGLE_LIST_SUN* = 0x81D7.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_START* = 0x92C2.GLenum
-  GL_MAX_ELEMENTS_VERTICES* = 0x80E8.GLenum
-  GL_COLOR_ATTACHMENT9_EXT* = 0x8CE9.GLenum
-  GL_ACCUM_CLEAR_VALUE* = 0x0B80.GLenum
-  GL_TEXTURE_COORD_ARRAY_LENGTH_NV* = 0x8F2F.GLenum
-  GL_DRAW_BUFFER3_EXT* = 0x8828.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT* = 0x8517.GLenum
-  GL_C4UB_V3F* = 0x2A23.GLenum
-  GL_MAX_PROGRAM_ATTRIBS_ARB* = 0x88AD.GLenum
-  GL_PIXEL_TILE_CACHE_INCREMENT_SGIX* = 0x813F.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_ARB* = 0x8DA9.GLenum
-  GL_CON_8_ATI* = 0x8949.GLenum
-  GL_POST_COLOR_MATRIX_ALPHA_BIAS* = 0x80BB.GLenum
-  GL_RENDERBUFFER_WIDTH* = 0x8D42.GLenum
-  GL_VERTEX_ID_NV* = 0x8C7B.GLenum
-  GL_STRICT_LIGHTING_HINT_PGI* = 0x1A217.GLenum
-  GL_COMPRESSED_RGBA8_ETC2_EAC_OES* = 0x9278.GLenum
-  GL_PACK_COMPRESSED_BLOCK_WIDTH* = 0x912B.GLenum
-  GL_ZERO_EXT* = 0x87DD.GLenum
-  GL_DEBUG_SOURCE_OTHER* = 0x824B.GLenum
-  GL_MAP_UNSYNCHRONIZED_BIT* = 0x0020.GLbitfield
-  GL_VERTEX_ARRAY_POINTER* = 0x808E.GLenum
-  GL_FLOAT_RGBA_NV* = 0x8883.GLenum
-  GL_WEIGHT_ARRAY_STRIDE_OES* = 0x86AA.GLenum
-  GL_UNPACK_ROW_BYTES_APPLE* = 0x8A16.GLenum
-  GL_CURRENT_COLOR* = 0x0B00.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MISSING_ATTACHMENT_EXT* = 0x8CD7.GLenum
-  GL_MAX_NAME_STACK_DEPTH* = 0x0D37.GLenum
-  GL_SHADER_STORAGE_BUFFER_START* = 0x90D4.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_MODE_EXT* = 0x8C7F.GLenum
-  GL_PATH_GEN_COMPONENTS_NV* = 0x90B3.GLenum
-  GL_AUTO_GENERATE_MIPMAP* = 0x8295.GLenum
-  GL_UNSIGNED_INT_5_9_9_9_REV* = 0x8C3E.GLenum
-  GL_VIEWPORT* = 0x0BA2.GLenum
-  GL_MAX_VERTEX_STREAMS_ATI* = 0x876B.GLenum
-  GL_MAX_OPTIMIZED_VERTEX_SHADER_VARIANTS_EXT* = 0x87CB.GLenum
-  GL_STENCIL_CLEAR_VALUE* = 0x0B91.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_ARRAY_EXT* = 0x9069.GLenum
-  GL_FRAGMENT_LIGHT_MODEL_TWO_SIDE_SGIX* = 0x8409.GLenum
-  GL_FRAGMENT_SHADER_BIT_EXT* = 0x00000002.GLbitfield
-  GL_COLOR_SUM_ARB* = 0x8458.GLenum
-  GL_RGBA4_DXT5_S3TC* = 0x83A5.GLenum
-  GL_INT_IMAGE_CUBE* = 0x905B.GLenum
-  GL_ACTIVE_ATOMIC_COUNTER_BUFFERS* = 0x92D9.GLenum
-  GL_INTERNALFORMAT_GREEN_SIZE* = 0x8272.GLenum
-  GL_OFFSET_HILO_TEXTURE_RECTANGLE_NV* = 0x8855.GLenum
-  GL_MAX_PN_TRIANGLES_TESSELATION_LEVEL_ATI* = 0x87F1.GLenum
-  GL_REG_24_ATI* = 0x8939.GLenum
-  GL_MULT* = 0x0103.GLenum
-  GL_RGBA2* = 0x8055.GLenum
-  GL_CONVOLUTION_WIDTH_EXT* = 0x8018.GLenum
-  GL_STENCIL_EXT* = 0x1802.GLenum
-  GL_PATH_STROKE_WIDTH_NV* = 0x9075.GLenum
-  GL_DEBUG_SOURCE_WINDOW_SYSTEM_ARB* = 0x8247.GLenum
-  GL_QUERY_COUNTER_BITS* = 0x8864.GLenum
-  GL_OUTPUT_FOG_EXT* = 0x87BD.GLenum
-  GL_POST_COLOR_MATRIX_RED_BIAS* = 0x80B8.GLenum
-  GL_UNSIGNED_INT_10_10_10_2* = 0x8036.GLenum
-  GL_INT_SAMPLER_1D* = 0x8DC9.GLenum
-  GL_INT_IMAGE_2D_MULTISAMPLE_EXT* = 0x9060.GLenum
-  GL_RENDERBUFFER_INTERNAL_FORMAT_OES* = 0x8D44.GLenum
-  GL_TRACE_PIXELS_BIT_MESA* = 0x0010.GLbitfield
-  GL_FAILURE_NV* = 0x9030.GLenum
-  GL_INT_SAMPLER_3D_EXT* = 0x8DCB.GLenum
-  GL_MAX_PROGRAM_PARAMETER_BUFFER_SIZE_NV* = 0x8DA1.GLenum
-  GL_OBJECT_DISTANCE_TO_POINT_SGIS* = 0x81F1.GLenum
-  GL_BLEND_SRC_RGB_OES* = 0x80C9.GLenum
-  GL_LUMINANCE4_ALPHA4_OES* = 0x8043.GLenum
-  GL_REG_4_ATI* = 0x8925.GLenum
-  GL_SHADING_LANGUAGE_VERSION_ARB* = 0x8B8C.GLenum
-  GL_RGBA16F_ARB* = 0x881A.GLenum
-  GL_R32F* = 0x822E.GLenum
-  GL_COMPRESSED_SRGB_S3TC_DXT1_NV* = 0x8C4C.GLenum
-  GL_TESS_CONTROL_OUTPUT_VERTICES* = 0x8E75.GLenum
-  GL_ONE_MINUS_DST_COLOR* = 0x0307.GLenum
-  GL_MATRIX19_ARB* = 0x88D3.GLenum
-  GL_INT_SAMPLER_2D_RECT* = 0x8DCD.GLenum
-  GL_POST_CONVOLUTION_GREEN_SCALE_EXT* = 0x801D.GLenum
-  GL_CLIP_DISTANCE5* = 0x3005.GLenum
-  GL_HISTOGRAM_RED_SIZE_EXT* = 0x8028.GLenum
-  GL_INTENSITY_FLOAT32_APPLE* = 0x8817.GLenum
-  GL_MODULATE_ADD_ATI* = 0x8744.GLenum
-  GL_NEGATIVE_X_EXT* = 0x87D9.GLenum
-  GL_REG_21_ATI* = 0x8936.GLenum
-  GL_STENCIL_RENDERABLE* = 0x8288.GLenum
-  GL_FOG_COORD_ARRAY_STRIDE* = 0x8455.GLenum
-  GL_FACTOR_MAX_AMD* = 0x901D.GLenum
-  GL_LUMINANCE16_EXT* = 0x8042.GLenum
-  GL_VARIANT_ARRAY_POINTER_EXT* = 0x87E9.GLenum
-  GL_DECAL* = 0x2101.GLenum
-  GL_SIGNED_ALPHA8_NV* = 0x8706.GLenum
-  GL_ALPHA_BITS* = 0x0D55.GLenum
-  GL_MATRIX29_ARB* = 0x88DD.GLenum
-  GL_FOG* = 0x0B60.GLenum
-  GL_INDEX_ARRAY_LIST_STRIDE_IBM* = 103083.GLenum
-  GL_IMAGE_FORMAT_COMPATIBILITY_BY_CLASS* = 0x90C9.GLenum
-  GL_RGBA4_S3TC* = 0x83A3.GLenum
-  GL_LUMINANCE16_ALPHA16* = 0x8048.GLenum
-  GL_PROXY_TEXTURE_RECTANGLE* = 0x84F7.GLenum
-  GL_FRAGMENT_PROGRAM_PARAMETER_BUFFER_NV* = 0x8DA4.GLenum
-  GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_CONTROL_SHADER* = 0x84F0.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE* = 0x8CD3.GLenum
-  GL_COLOR_TABLE_GREEN_SIZE_SGI* = 0x80DB.GLenum
-  GL_TEXTURE_PRE_SPECULAR_HP* = 0x8169.GLenum
-  GL_SHADOW_ATTENUATION_EXT* = 0x834E.GLenum
-  GL_SIGNED_RGB_NV* = 0x86FE.GLenum
-  GL_CLIENT_ALL_ATTRIB_BITS* = 0xFFFFFFFF.GLbitfield
-  GL_DEPTH_ATTACHMENT_EXT* = 0x8D00.GLenum
-  GL_DEBUG_SOURCE_API_KHR* = 0x8246.GLenum
-  GL_COLOR_INDEXES* = 0x1603.GLenum
-  GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH* = 0x8243.GLenum
-  GL_TEXTURE_BINDING_1D* = 0x8068.GLenum
-  GL_UNSIGNED_INT_SAMPLER_2D* = 0x8DD2.GLenum
-  GL_DRAW_BUFFER9_NV* = 0x882E.GLenum
-  GL_RED* = 0x1903.GLenum
-  GL_LINE_STRIP_ADJACENCY_EXT* = 0x000B.GLenum
-  GL_NUM_PASSES_ATI* = 0x8970.GLenum
-  GL_MAT_DIFFUSE_BIT_PGI* = 0x00400000.GLbitfield
-  GL_LUMINANCE_INTEGER_EXT* = 0x8D9C.GLenum
-  GL_PIXEL_MAP_I_TO_I* = 0x0C70.GLenum
-  GL_SLUMINANCE8_ALPHA8_NV* = 0x8C45.GLenum
-  GL_RGBA4_OES* = 0x8056.GLenum
-  GL_COMPRESSED_SIGNED_R11_EAC* = 0x9271.GLenum
-  GL_FRAGMENT_LIGHT4_SGIX* = 0x8410.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_NV* = 0x8C80.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT* = 0x8C4D.GLenum
-  GL_READ_FRAMEBUFFER_APPLE* = 0x8CA8.GLenum
-  GL_DRAW_BUFFER15_ARB* = 0x8834.GLenum
-  GL_INSTRUMENT_MEASUREMENTS_SGIX* = 0x8181.GLenum
-  GL_REG_15_ATI* = 0x8930.GLenum
-  GL_UNSIGNED_INT_IMAGE_1D_ARRAY* = 0x9068.GLenum
-  GL_COMPUTE_LOCAL_WORK_SIZE* = 0x8267.GLenum
-  GL_RGBA32I* = 0x8D82.GLenum
-  GL_VERTEX_ATTRIB_MAP2_APPLE* = 0x8A01.GLenum
-  GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR* = 0x824D.GLenum
-  GL_READ_FRAMEBUFFER_BINDING_ANGLE* = 0x8CAA.GLenum
-  GL_DEBUG_SOURCE_WINDOW_SYSTEM_KHR* = 0x8247.GLenum
-  GL_OP_FRAC_EXT* = 0x8789.GLenum
-  GL_RGB_FLOAT32_APPLE* = 0x8815.GLenum
-  GL_UNIFORM_BLOCK_REFERENCED_BY_VERTEX_SHADER* = 0x8A44.GLenum
-  GL_NORMAL_ARRAY* = 0x8075.GLenum
-  GL_TEXTURE21_ARB* = 0x84D5.GLenum
-  GL_WRITE_ONLY_OES* = 0x88B9.GLenum
-  GL_TEXTURE0_ARB* = 0x84C0.GLenum
-  GL_SPRITE_OBJECT_ALIGNED_SGIX* = 0x814D.GLenum
-  GL_POSITION* = 0x1203.GLenum
-  GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR* = 0x824E.GLenum
-  GL_GEOMETRY_OUTPUT_TYPE_ARB* = 0x8DDC.GLenum
-  GL_IMAGE_PIXEL_TYPE* = 0x82AA.GLenum
-  GL_UNSIGNED_INT64_AMD* = 0x8BC2.GLenum
-  GL_LIST_INDEX* = 0x0B33.GLenum
-  GL_UNSIGNED_INT_8_8_S8_S8_REV_NV* = 0x86DB.GLenum
-  GL_MAP_ATTRIB_U_ORDER_NV* = 0x86C3.GLenum
-  GL_PROXY_TEXTURE_RECTANGLE_ARB* = 0x84F7.GLenum
-  GL_CLIP_NEAR_HINT_PGI* = 0x1A220.GLenum
-  GL_POST_TEXTURE_FILTER_BIAS_RANGE_SGIX* = 0x817B.GLenum
-  GL_MAX_UNIFORM_BLOCK_SIZE* = 0x8A30.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER* = 0x8CDB.GLenum
-  GL_SAMPLE_MASK_INVERT_EXT* = 0x80AB.GLenum
-  GL_MAP1_VERTEX_ATTRIB14_4_NV* = 0x866E.GLenum
-  GL_SYNC_FLAGS* = 0x9115.GLenum
-  GL_COMPRESSED_RGBA* = 0x84EE.GLenum
-  GL_TEXTURE_COMPRESSED_BLOCK_HEIGHT* = 0x82B2.GLenum
-  GL_INDEX_ARRAY_STRIDE_EXT* = 0x8086.GLenum
-  GL_CLIP_DISTANCE_NV* = 0x8C7A.GLenum
-  GL_UNSIGNED_INT_VEC4* = 0x8DC8.GLenum
-  GL_COMPRESSED_RGB_BPTC_SIGNED_FLOAT_ARB* = 0x8E8E.GLenum
-  GL_MIRRORED_REPEAT_OES* = 0x8370.GLint
-  GL_WEIGHT_ARRAY_SIZE_ARB* = 0x86AB.GLenum
-  GL_MIN_SAMPLE_SHADING_VALUE* = 0x8C37.GLenum
-  GL_SOURCE0_RGB* = 0x8580.GLenum
-  GL_RG32I* = 0x823B.GLenum
-  GL_QUERY_BUFFER_BINDING_AMD* = 0x9193.GLenum
-  GL_OFFSET_PROJECTIVE_TEXTURE_2D_SCALE_NV* = 0x8851.GLenum
-  GL_POST_CONVOLUTION_BLUE_SCALE_EXT* = 0x801E.GLenum
-  GL_DOUBLE_MAT3x4_EXT* = 0x8F4C.GLenum
-  GL_MAX_VERTEX_HINT_PGI* = 0x1A22D.GLenum
-  GL_ADD* = 0x0104.GLenum
-  GL_PATH_FORMAT_SVG_NV* = 0x9070.GLenum
-  GL_VIDEO_BUFFER_BINDING_NV* = 0x9021.GLenum
-  GL_NUM_EXTENSIONS* = 0x821D.GLenum
-  GL_DEPTH_RANGE* = 0x0B70.GLenum
-  GL_FRAGMENT_SUBROUTINE* = 0x92EC.GLenum
-  GL_DEPTH24_STENCIL8_EXT* = 0x88F0.GLenum
-  GL_COMPRESSED_RGBA_S3TC_DXT3_EXT* = 0x83F2.GLenum
-  GL_COLOR_TABLE_SGI* = 0x80D0.GLenum
-  GL_OBJECT_ACTIVE_UNIFORMS_ARB* = 0x8B86.GLenum
-  GL_RGBA16F* = 0x881A.GLenum
-  GL_COORD_REPLACE_ARB* = 0x8862.GLenum
-  GL_SAMPLE_POSITION_NV* = 0x8E50.GLenum
-  GL_SRC_ALPHA* = 0x0302.GLenum
-  GL_COMBINE_ALPHA* = 0x8572.GLenum
-  GL_CLEAR* = 0x1500.GLenum
-  GL_HSL_HUE_NV* = 0x92AD.GLenum
-  GL_SCISSOR_TEST* = 0x0C11.GLenum
-  GL_UNSIGNED_INT_SAMPLER_BUFFER_EXT* = 0x8DD8.GLenum
-  GL_RGB16UI* = 0x8D77.GLenum
-  GL_MATRIX9_ARB* = 0x88C9.GLenum
-  GL_COLOR_ATTACHMENT13* = 0x8CED.GLenum
-  GL_BUMP_ROT_MATRIX_SIZE_ATI* = 0x8776.GLenum
-  GL_PIXEL_PACK_BUFFER_BINDING_ARB* = 0x88ED.GLenum
-  GL_FONT_X_MAX_BOUNDS_BIT_NV* = 0x00040000.GLbitfield
-  GL_MODELVIEW31_ARB* = 0x873F.GLenum
-  GL_DRAW_BUFFER14_ARB* = 0x8833.GLenum
-  GL_EDGEFLAG_BIT_PGI* = 0x00040000.GLbitfield
-  GL_TEXTURE_LOD_BIAS_R_SGIX* = 0x8190.GLenum
-  GL_FIELD_UPPER_NV* = 0x9022.GLenum
-  GL_CLIP_PLANE3* = 0x3003.GLenum
-  GL_FRAGMENT_LIGHT_MODEL_LOCAL_VIEWER_SGIX* = 0x8408.GLenum
-  GL_BLUE* = 0x1905.GLenum
-  GL_LUMINANCE_ALPHA_FLOAT32_ATI* = 0x8819.GLenum
-  GL_MATRIX31_ARB* = 0x88DF.GLenum
-  GL_OR_REVERSE* = 0x150B.GLenum
-  GL_INTERPOLATE_EXT* = 0x8575.GLenum
-  GL_MODELVIEW13_ARB* = 0x872D.GLenum
-  GL_UTF16_NV* = 0x909B.GLenum
-  GL_READ_FRAMEBUFFER_ANGLE* = 0x8CA8.GLenum
-  GL_LUMINANCE16F_EXT* = 0x881E.GLenum
-  GL_VERTEX_ATTRIB_ARRAY7_NV* = 0x8657.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_EXT* = 0x8C8A.GLenum
-  GL_PRIMARY_COLOR_EXT* = 0x8577.GLenum
-  GL_VERTEX_ATTRIB_RELATIVE_OFFSET* = 0x82D5.GLenum
-  GL_LARGE_CW_ARC_TO_NV* = 0x18.GLenum
-  GL_PROGRAM_PARAMETER_NV* = 0x8644.GLenum
-  GL_ASYNC_MARKER_SGIX* = 0x8329.GLenum
-  GL_TEXTURE24_ARB* = 0x84D8.GLenum
-  GL_PIXEL_SUBSAMPLE_4242_SGIX* = 0x85A4.GLenum
-  GL_RGB10_A2_EXT* = 0x8059.GLenum
-  GL_IMAGE_CLASS_2_X_32* = 0x82BA.GLenum
-  GL_TEXTURE_INTENSITY_TYPE* = 0x8C15.GLenum
-  GL_TEXTURE_LOD_BIAS_S_SGIX* = 0x818E.GLenum
-  GL_PROGRAM_BINARY_LENGTH* = 0x8741.GLenum
-  GL_CURRENT_RASTER_NORMAL_SGIX* = 0x8406.GLenum
-  GL_DETAIL_TEXTURE_2D_SGIS* = 0x8095.GLenum
-  GL_MAX_FRAGMENT_INTERPOLATION_OFFSET_NV* = 0x8E5C.GLenum
-  GL_CONVOLUTION_FILTER_BIAS_EXT* = 0x8015.GLenum
-  GL_DT_BIAS_NV* = 0x8717.GLenum
-  GL_RESET_NOTIFICATION_STRATEGY_EXT* = 0x8256.GLenum
-  GL_SHADER_STORAGE_BUFFER* = 0x90D2.GLenum
-  GL_RESET_NOTIFICATION_STRATEGY_ARB* = 0x8256.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_EXT* = 0x8CD1.GLenum
-  GL_SRC_NV* = 0x9286.GLenum
-  GL_POINT_FADE_THRESHOLD_SIZE* = 0x8128.GLenum
-  GL_DEPENDENT_RGB_TEXTURE_3D_NV* = 0x8859.GLenum
-  GL_QUERY_RESULT_ARB* = 0x8866.GLenum
-  GL_GEOMETRY_VERTICES_OUT* = 0x8916.GLenum
-  GL_MAX_COMPUTE_FIXED_GROUP_INVOCATIONS_ARB* = 0x90EB.GLenum
-  GL_MODELVIEW27_ARB* = 0x873B.GLenum
-  GL_DRAW_BUFFER11_NV* = 0x8830.GLenum
-  GL_COLOR_ATTACHMENT9_NV* = 0x8CE9.GLenum
-  GL_BLEND_SRC* = 0x0BE1.GLenum
-  GL_CONVOLUTION_2D_EXT* = 0x8011.GLenum
-  GL_MAX_ELEMENTS_INDICES* = 0x80E9.GLenum
-  GL_LUMINANCE_ALPHA_FLOAT32_APPLE* = 0x8819.GLenum
-  GL_INT_IMAGE_1D* = 0x9057.GLenum
-  GL_CONSTANT_COLOR* = 0x8001.GLenum
-  GL_FRAMEBUFFER_BARRIER_BIT* = 0x00000400.GLbitfield
-  GL_POST_CONVOLUTION_BLUE_SCALE* = 0x801E.GLenum
-  GL_DEBUG_SOURCE_SHADER_COMPILER_ARB* = 0x8248.GLenum
-  GL_RGB16I* = 0x8D89.GLenum
-  GL_MAX_WIDTH* = 0x827E.GLenum
-  GL_LIGHT_MODEL_AMBIENT* = 0x0B53.GLenum
-  GL_COVERAGE_ATTACHMENT_NV* = 0x8ED2.GLenum
-  GL_PROGRAM* = 0x82E2.GLenum
-  GL_IMAGE_ROTATE_ANGLE_HP* = 0x8159.GLenum
-  GL_SRC2_RGB* = 0x8582.GLenum
-  GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_KHR* = 0x824E.GLenum
-  GL_PASS_THROUGH_NV* = 0x86E6.GLenum
-  GL_HALF_BIAS_NEGATE_NV* = 0x853B.GLenum
-  GL_SAMPLER_CUBE_SHADOW_EXT* = 0x8DC5.GLenum
-  GL_COMPRESSED_RGBA_BPTC_UNORM_ARB* = 0x8E8C.GLenum
-  GL_MAX_SERVER_WAIT_TIMEOUT_APPLE* = 0x9111.GLenum
-  GL_STORAGE_PRIVATE_APPLE* = 0x85BD.GLenum
-  GL_VERTEX_SHADER_BIT* = 0x00000001.GLbitfield
-  GL_POST_COLOR_MATRIX_BLUE_SCALE_SGI* = 0x80B6.GLenum
-  GL_VERTEX_SHADER_VARIANTS_EXT* = 0x87D0.GLenum
-  GL_TRANSFORM_FEEDBACK_ACTIVE* = 0x8E24.GLenum
-  GL_ACTIVE_UNIFORMS* = 0x8B86.GLenum
-  GL_MULTISAMPLE_BUFFER_BIT0_QCOM* = 0x01000000.GLbitfield
-  GL_OFFSET_TEXTURE_SCALE_NV* = 0x86E2.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ARB* = 0x88FE.GLenum
-  GL_BEVEL_NV* = 0x90A6.GLenum
-  GL_MAX_DRAW_BUFFERS_NV* = 0x8824.GLenum
-  GL_MAP1_TANGENT_EXT* = 0x8444.GLenum
-  GL_ANY_SAMPLES_PASSED* = 0x8C2F.GLenum
-  GL_MAX_IMAGE_SAMPLES* = 0x906D.GLenum
-  GL_PIXEL_UNPACK_BUFFER_BINDING* = 0x88EF.GLenum
-  GL_SRGB8_ALPHA8_EXT* = 0x8C43.GLenum
-  GL_2PASS_1_SGIS* = 0x80A3.GLenum
-  GL_PROGRAM_POINT_SIZE_ARB* = 0x8642.GLenum
-  GL_ALLOW_DRAW_WIN_HINT_PGI* = 0x1A20F.GLenum
-  GL_INTERNALFORMAT_RED_SIZE* = 0x8271.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_OES* = 0x8CD3.GLenum
-  GL_4PASS_2_SGIS* = 0x80A6.GLenum
-  GL_PROGRAM_OBJECT_EXT* = 0x8B40.GLenum
-  GL_SIMULTANEOUS_TEXTURE_AND_STENCIL_TEST* = 0x82AD.GLenum
-  GL_LIGHTING_BIT* = 0x00000040.GLbitfield
-  GL_DRAW_BUFFER13_EXT* = 0x8832.GLenum
-  GL_STREAM_DRAW_ARB* = 0x88E0.GLenum
-  GL_INDEX_ARRAY_TYPE* = 0x8085.GLenum
-  GL_DEBUG_SOURCE_THIRD_PARTY* = 0x8249.GLenum
-  GL_DYNAMIC_COPY_ARB* = 0x88EA.GLenum
-  GL_COMPARE_R_TO_TEXTURE_ARB* = 0x884E.GLenum
-  GL_FRAGMENTS_INSTRUMENT_COUNTERS_SGIX* = 0x8314.GLenum
-  GL_SPARSE_TEXTURE_FULL_ARRAY_CUBE_MIPMAPS_ARB* = 0x91A9.GLenum
-  GL_MAX_GEOMETRY_UNIFORM_COMPONENTS* = 0x8DDF.GLenum
-  GL_READ_PIXEL_DATA_RANGE_POINTER_NV* = 0x887D.GLenum
-  GL_BUFFER_MAPPED_OES* = 0x88BC.GLenum
-  GL_COLOR_ARRAY_COUNT_EXT* = 0x8084.GLenum
-  GL_SET_AMD* = 0x874A.GLenum
-  GL_BLEND_DST_RGB_OES* = 0x80C8.GLenum
-  GL_MAX_CONVOLUTION_HEIGHT_EXT* = 0x801B.GLenum
-  GL_DEBUG_SEVERITY_MEDIUM* = 0x9147.GLenum
-  GL_TEXTURE_INTENSITY_TYPE_ARB* = 0x8C15.GLenum
-  GL_IMAGE_CLASS_10_10_10_2* = 0x82C3.GLenum
-  GL_TEXTURE_BORDER_COLOR_NV* = 0x1004.GLenum
-  GL_VERTEX_ATTRIB_ARRAY12_NV* = 0x865C.GLenum
-  GL_MAX_GEOMETRY_SHADER_INVOCATIONS* = 0x8E5A.GLenum
-  GL_NEAREST_CLIPMAP_NEAREST_SGIX* = 0x844D.GLenum
-  GL_MAP2_VERTEX_ATTRIB12_4_NV* = 0x867C.GLenum
-  GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING* = 0x889A.GLenum
-  GL_SEPARATE_SPECULAR_COLOR_EXT* = 0x81FA.GLenum
-  GL_MATRIX_INDEX_ARRAY_SIZE_ARB* = 0x8846.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB* = 0x8517.GLenum
-  GL_DECR* = 0x1E03.GLenum
-  GL_DEPTH_BUFFER_BIT7_QCOM* = 0x00008000.GLbitfield
-  GL_LOCAL_EXT* = 0x87C4.GLenum
-  GL_FUNC_REVERSE_SUBTRACT_OES* = 0x800B.GLenum
-  GL_FLOAT_VEC3* = 0x8B51.GLenum
-  GL_POINT_SIZE_GRANULARITY* = 0x0B13.GLenum
-  GL_COLOR_ATTACHMENT9* = 0x8CE9.GLenum
-  GL_MAT_SPECULAR_BIT_PGI* = 0x04000000.GLbitfield
-  GL_VERTEX_ATTRIB_MAP1_APPLE* = 0x8A00.GLenum
-  GL_DEBUG_SOURCE_WINDOW_SYSTEM* = 0x8247.GLenum
-  GL_NEAREST_MIPMAP_NEAREST* = 0x2700.GLint
-  GL_MODELVIEW7_ARB* = 0x8727.GLenum
-  GL_OUTPUT_VERTEX_EXT* = 0x879A.GLenum
-  GL_FRAMEBUFFER_EXT* = 0x8D40.GLenum
-  GL_ATC_RGBA_EXPLICIT_ALPHA_AMD* = 0x8C93.GLenum
-  GL_RENDERBUFFER_WIDTH_OES* = 0x8D42.GLenum
-  GL_TEXTURE_VIEW_MIN_LAYER* = 0x82DD.GLenum
-  GL_TEXTURE25_ARB* = 0x84D9.GLenum
-  GL_LIGHT7* = 0x4007.GLenum
-  GL_TESS_EVALUATION_SHADER_BIT* = 0x00000010.GLbitfield
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_EXT* = 0x8CD2.GLenum
-  GL_COLOR_ATTACHMENT15_NV* = 0x8CEF.GLenum
-  GL_RED_SNORM* = 0x8F90.GLenum
-  GL_VIVIDLIGHT_NV* = 0x92A6.GLenum
-  GL_OBJECT_COMPILE_STATUS_ARB* = 0x8B81.GLenum
-  GL_INTERNALFORMAT_PREFERRED* = 0x8270.GLenum
-  GL_OUT_OF_MEMORY* = 0x0505.GLenum
-  GL_422_REV_EXT* = 0x80CD.GLenum
-  GL_DOT_PRODUCT_TEXTURE_CUBE_MAP_NV* = 0x86F0.GLenum
-  GL_PROXY_TEXTURE_1D* = 0x8063.GLenum
-  GL_FRAGMENT_PROGRAM_CALLBACK_FUNC_MESA* = 0x8BB2.GLenum
-  GL_YCBCR_422_APPLE* = 0x85B9.GLenum
-  GL_DRAW_BUFFER10_ATI* = 0x882F.GLenum
-  GL_COLOR_TABLE_ALPHA_SIZE_SGI* = 0x80DD.GLenum
-  GL_MAX_TESS_EVALUATION_OUTPUT_COMPONENTS* = 0x8E86.GLenum
-  GL_MAX_PROGRAM_OUTPUT_VERTICES_NV* = 0x8C27.GLenum
-  GL_IMAGE_2D_MULTISAMPLE_EXT* = 0x9055.GLenum
-  GL_ACTIVE_TEXTURE_ARB* = 0x84E0.GLenum
-  GL_FONT_MAX_ADVANCE_HEIGHT_BIT_NV* = 0x02000000.GLbitfield
-  GL_QUERY_WAIT_NV* = 0x8E13.GLenum
-  GL_MAX_ELEMENT_INDEX* = 0x8D6B.GLenum
-  GL_OP_LOG_BASE_2_EXT* = 0x8792.GLenum
-  GL_ADD_SIGNED* = 0x8574.GLenum
-  GL_CONVOLUTION_FORMAT* = 0x8017.GLenum
-  GL_RENDERBUFFER_RED_SIZE_EXT* = 0x8D50.GLenum
-  GL_RENDERBUFFER_INTERNAL_FORMAT* = 0x8D44.GLenum
-  GL_COLOR_ATTACHMENT11_NV* = 0x8CEB.GLenum
-  GL_MATRIX14_ARB* = 0x88CE.GLenum
-  GL_COLOR_TABLE_RED_SIZE_SGI* = 0x80DA.GLenum
-  GL_CON_22_ATI* = 0x8957.GLenum
-  GL_TEXTURE_SWIZZLE_B_EXT* = 0x8E44.GLenum
-  GL_SAMPLES_SGIS* = 0x80A9.GLenum
-  GL_WRITE_PIXEL_DATA_RANGE_LENGTH_NV* = 0x887A.GLenum
-  GL_FONT_X_MIN_BOUNDS_BIT_NV* = 0x00010000.GLbitfield
-  GL_3_BYTES* = 0x1408.GLenum
-  GL_TEXTURE_MAX_CLAMP_S_SGIX* = 0x8369.GLenum
-  GL_PROXY_TEXTURE_CUBE_MAP_EXT* = 0x851B.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_DIVISOR_ANGLE* = 0x88FE.GLenum
-  GL_VERTEX_DATA_HINT_PGI* = 0x1A22A.GLenum
-  GL_VERTEX_WEIGHT_ARRAY_SIZE_EXT* = 0x850D.GLenum
-  GL_MAX_INTEGER_SAMPLES* = 0x9110.GLenum
-  GL_TEXTURE_BUFFER_ARB* = 0x8C2A.GLenum
-  GL_FOG_COORD_ARRAY_POINTER* = 0x8456.GLenum
-  GL_UNSIGNED_SHORT_1_15_REV_MESA* = 0x8754.GLenum
-  GL_IMAGE_CUBIC_WEIGHT_HP* = 0x815E.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_OES* = 0x8CD6.GLenum
-  GL_RGBA_DXT5_S3TC* = 0x83A4.GLenum
-  GL_INT_IMAGE_2D_MULTISAMPLE* = 0x9060.GLenum
-  GL_ACTIVE_RESOURCES* = 0x92F5.GLenum
-  GL_TEXTURE_BINDING_2D* = 0x8069.GLenum
-  GL_SAMPLE_COVERAGE* = 0x80A0.GLenum
-  GL_SMOOTH* = 0x1D01.GLenum
-  GL_SAMPLER_1D_SHADOW_ARB* = 0x8B61.GLenum
-  GL_VIRTUAL_PAGE_SIZE_Y_AMD* = 0x9196.GLenum
-  GL_HORIZONTAL_LINE_TO_NV* = 0x06.GLenum
-  GL_HISTOGRAM_GREEN_SIZE_EXT* = 0x8029.GLenum
-  GL_COLOR_FLOAT_APPLE* = 0x8A0F.GLenum
-  GL_NUM_SHADER_BINARY_FORMATS* = 0x8DF9.GLenum
-  GL_TIMESTAMP* = 0x8E28.GLenum
-  GL_SRGB_EXT* = 0x8C40.GLenum
-  GL_MAX_VERTEX_UNIFORM_BLOCKS* = 0x8A2B.GLenum
-  GL_COLOR_ATTACHMENT2_EXT* = 0x8CE2.GLenum
-  GL_DEBUG_CALLBACK_FUNCTION_KHR* = 0x8244.GLenum
-  GL_DISPLAY_LIST* = 0x82E7.GLenum
-  GL_MAP1_NORMAL* = 0x0D92.GLenum
-  GL_COMPUTE_TEXTURE* = 0x82A0.GLenum
-  GL_MAX_COMPUTE_SHADER_STORAGE_BLOCKS* = 0x90DB.GLenum
-  GL_W_EXT* = 0x87D8.GLenum
-  GL_SAMPLE_SHADING_ARB* = 0x8C36.GLenum
-  GL_FRAGMENT_INTERPOLATION_OFFSET_BITS* = 0x8E5D.GLenum
-  GL_IMAGE_CLASS_4_X_16* = 0x82BC.GLenum
-  GL_FRAGMENT_DEPTH_EXT* = 0x8452.GLenum
-  GL_EVAL_BIT* = 0x00010000.GLbitfield
-  GL_UNSIGNED_INT_8_8_8_8* = 0x8035.GLenum
-  GL_MAX_TESS_CONTROL_INPUT_COMPONENTS* = 0x886C.GLenum
-  GL_FRAGMENT_PROGRAM_CALLBACK_DATA_MESA* = 0x8BB3.GLenum
-  GL_SLUMINANCE8_ALPHA8* = 0x8C45.GLenum
-  GL_MODULATE_COLOR_IMG* = 0x8C04.GLenum
-  GL_TEXTURE20* = 0x84D4.GLenum
-  GL_ALPHA_INTEGER_EXT* = 0x8D97.GLenum
-  GL_TEXTURE_BINDING_CUBE_MAP_EXT* = 0x8514.GLenum
-  GL_BACK_LEFT* = 0x0402.GLenum
-  GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS_EXT* = 0x8F39.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_BUFFERS* = 0x8E70.GLenum
-  GL_TRANSFORM_BIT* = 0x00001000.GLbitfield
-  GL_RGB4_EXT* = 0x804F.GLenum
-  GL_FRAGMENT_COLOR_EXT* = 0x834C.GLenum
-  GL_PIXEL_MAP_S_TO_S* = 0x0C71.GLenum
-  GL_COMPRESSED_RGBA_S3TC_DXT5_EXT* = 0x83F3.GLenum
-  GL_PATH_STENCIL_DEPTH_OFFSET_FACTOR_NV* = 0x90BD.GLenum
-  GL_SOURCE0_RGB_EXT* = 0x8580.GLenum
-  GL_PIXEL_COUNTER_BITS_NV* = 0x8864.GLenum
-  GL_ALIASED_LINE_WIDTH_RANGE* = 0x846E.GLenum
-  GL_DRAW_BUFFER10* = 0x882F.GLenum
-  GL_T4F_C4F_N3F_V4F* = 0x2A2D.GLenum
-  GL_BLEND_EQUATION_OES* = 0x8009.GLenum
-  GL_DEPTH_COMPONENT32* = 0x81A7.GLenum
-  GL_MAX_OPTIMIZED_VERTEX_SHADER_INSTRUCTIONS_EXT* = 0x87CA.GLenum
-  GL_DEPTH_BUFFER_BIT5_QCOM* = 0x00002000.GLbitfield
-  GL_RED_MIN_CLAMP_INGR* = 0x8560.GLenum
-  GL_RGBA_INTEGER_MODE_EXT* = 0x8D9E.GLenum
-  GL_DOUBLE_MAT4_EXT* = 0x8F48.GLenum
-  GL_OBJECT_DELETE_STATUS_ARB* = 0x8B80.GLenum
-  GL_FOG_COORD_ARRAY_LENGTH_NV* = 0x8F32.GLenum
-  GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING* = 0x889C.GLenum
-  GL_MAP1_VERTEX_ATTRIB7_4_NV* = 0x8667.GLenum
-  GL_BLEND_SRC_RGB_EXT* = 0x80C9.GLenum
-  GL_VERTEX_PROGRAM_POINT_SIZE_ARB* = 0x8642.GLenum
-  GL_STENCIL_INDEX1_EXT* = 0x8D46.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT* = 0x8516.GLenum
-  GL_FRAGMENT_SHADER_DISCARDS_SAMPLES_EXT* = 0x8A52.GLenum
-  GL_FOG_COORD_SRC* = 0x8450.GLenum
-  GL_ANY_SAMPLES_PASSED_EXT* = 0x8C2F.GLenum
-  GL_ALPHA4* = 0x803B.GLenum
-  GL_TEXTURE_GEN_MODE* = 0x2500.GLenum
-  GL_FLOAT_MAT3_ARB* = 0x8B5B.GLenum
-  GL_PIXEL_MAP_A_TO_A_SIZE* = 0x0CB9.GLenum
-  GL_FRAGMENT_SHADER_DERIVATIVE_HINT_ARB* = 0x8B8B.GLenum
-  GL_STENCIL_BACK_PASS_DEPTH_FAIL_ATI* = 0x8802.GLenum
-  GL_COPY_READ_BUFFER_BINDING* = 0x8F36.GLenum
-  GL_YCRCB_444_SGIX* = 0x81BC.GLenum
-  GL_SLUMINANCE_EXT* = 0x8C46.GLenum
-  GL_EDGE_FLAG_ARRAY_EXT* = 0x8079.GLenum
-  GL_STENCIL_INDEX8_OES* = 0x8D48.GLenum
-  GL_RGBA32UI* = 0x8D70.GLenum
-  GL_TEXTURE_CUBE_MAP* = 0x8513.GLenum
-  GL_STREAM_COPY* = 0x88E2.GLenum
-  GL_VIEWPORT_BOUNDS_RANGE* = 0x825D.GLenum
-  GL_ASYNC_READ_PIXELS_SGIX* = 0x835E.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_INTEGER* = 0x88FD.GLenum
-  GL_INTERNALFORMAT_STENCIL_TYPE* = 0x827D.GLenum
-  GL_OUTPUT_TEXTURE_COORD28_EXT* = 0x87B9.GLenum
-  GL_MATRIX_MODE* = 0x0BA0.GLenum
-  GL_MULTISAMPLE_SGIS* = 0x809D.GLenum
-  GL_R1UI_V3F_SUN* = 0x85C4.GLenum
-  GL_FLOAT_R32_NV* = 0x8885.GLenum
-  GL_MAX_DRAW_BUFFERS* = 0x8824.GLenum
-  GL_CIRCULAR_CCW_ARC_TO_NV* = 0xF8.GLenum
-  GL_PROGRAM_OUTPUT* = 0x92E4.GLenum
-  GL_MAX_CUBE_MAP_TEXTURE_SIZE* = 0x851C.GLenum
-  GL_TRIANGLE_STRIP_ADJACENCY_ARB* = 0x000D.GLenum
-  GL_UNIFORM_BUFFER_OFFSET_ALIGNMENT* = 0x8A34.GLenum
-  GL_SRGB* = 0x8C40.GLenum
-  GL_BUFFER_ACCESS* = 0x88BB.GLenum
-  GL_TEXTURE_WRAP_S* = 0x2802.GLenum
-  GL_TRANSFORM_FEEDBACK_VARYINGS* = 0x8C83.GLenum
-  GL_RG16UI* = 0x823A.GLenum
-  GL_DUAL_LUMINANCE4_SGIS* = 0x8114.GLenum
-  GL_DOT_PRODUCT_DEPTH_REPLACE_NV* = 0x86ED.GLenum
-  GL_READ_FRAMEBUFFER_BINDING* = 0x8CAA.GLenum
-  GL_MAX_FOG_FUNC_POINTS_SGIS* = 0x812C.GLenum
-  GL_QUERY_RESULT_NO_WAIT* = 0x9194.GLenum
-  GL_FILE_NAME_NV* = 0x9074.GLenum
-  GL_DRAW_FRAMEBUFFER_BINDING* = 0x8CA6.GLenum
-  GL_FRAGMENT_SHADER* = 0x8B30.GLenum
-  GL_VIBRANCE_SCALE_NV* = 0x8713.GLenum
-  GL_PATH_FILL_COVER_MODE_NV* = 0x9082.GLenum
-  GL_LINEAR_MIPMAP_LINEAR* = 0x2703.GLint
-  GL_TEXTURE29* = 0x84DD.GLenum
-  GL_SCISSOR_BOX* = 0x0C10.GLenum
-  GL_PACK_SKIP_IMAGES* = 0x806B.GLenum
-  GL_BUFFER_MAP_OFFSET* = 0x9121.GLenum
-  GL_SLUMINANCE8_EXT* = 0x8C47.GLenum
-  GL_CONVOLUTION_1D* = 0x8010.GLenum
-  GL_MAX_GEOMETRY_IMAGE_UNIFORMS* = 0x90CD.GLenum
-  GL_MAP1_VERTEX_ATTRIB11_4_NV* = 0x866B.GLenum
-  GL_COLOR_LOGIC_OP* = 0x0BF2.GLenum
-  GL_SYNC_FLAGS_APPLE* = 0x9115.GLenum
-  GL_ACCUM_RED_BITS* = 0x0D58.GLenum
-  GL_VIEW_CLASS_128_BITS* = 0x82C4.GLenum
-  GL_INT_VEC3* = 0x8B54.GLenum
-  GL_INTENSITY12* = 0x804C.GLenum
-  GL_UNIFORM_BLOCK_REFERENCED_BY_COMPUTE_SHADER* = 0x90EC.GLenum
-  GL_REQUIRED_TEXTURE_IMAGE_UNITS_OES* = 0x8D68.GLenum
-  GL_MAX_COLOR_MATRIX_STACK_DEPTH* = 0x80B3.GLenum
-  GL_GLOBAL_ALPHA_FACTOR_SUN* = 0x81DA.GLenum
-  GL_PACK_RESAMPLE_SGIX* = 0x842C.GLenum
-  GL_MAX_COMPUTE_FIXED_GROUP_SIZE_ARB* = 0x91BF.GLenum
-  GL_DEPTH_BUFFER_FLOAT_MODE_NV* = 0x8DAF.GLenum
-  GL_SIGNED_LUMINANCE_ALPHA_NV* = 0x8703.GLenum
-  GL_OP_MIN_EXT* = 0x878B.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_MODE_NV* = 0x8C7F.GLenum
-  GL_COLOR_INDEX12_EXT* = 0x80E6.GLenum
-  GL_AUTO_NORMAL* = 0x0D80.GLenum
-  GL_ARRAY_BUFFER* = 0x8892.GLenum
-  GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS_EXT* = 0x8DE1.GLenum
-  GL_VIDEO_CAPTURE_SURFACE_ORIGIN_NV* = 0x903C.GLenum
-  GL_ACCUM_BLUE_BITS* = 0x0D5A.GLenum
-  GL_RENDERBUFFER_SAMPLES_ANGLE* = 0x8CAB.GLenum
-  GL_MAX_ASYNC_HISTOGRAM_SGIX* = 0x832D.GLenum
-  GL_GLYPH_HAS_KERNING_BIT_NV* = 0x100.GLbitfield
-  GL_TESS_CONTROL_SUBROUTINE_UNIFORM* = 0x92EF.GLenum
-  GL_DRAW_BUFFER1* = 0x8826.GLenum
-  GL_INT8_NV* = 0x8FE0.GLenum
-  GL_2PASS_0_EXT* = 0x80A2.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_INDEX* = 0x934B.GLenum
-  GL_NUM_VIRTUAL_PAGE_SIZES_ARB* = 0x91A8.GLenum
-  GL_INT_SAMPLER_3D* = 0x8DCB.GLenum
-  GL_RASTERIZER_DISCARD* = 0x8C89.GLenum
-  GL_SOURCE2_RGB_ARB* = 0x8582.GLenum
-  GL_LOCAL_CONSTANT_EXT* = 0x87C3.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_LAYER_COUNT_EXT* = 0x8DA9.GLenum
-  GL_MODELVIEW12_ARB* = 0x872C.GLenum
-  GL_VERTEX_SUBROUTINE_UNIFORM* = 0x92EE.GLenum
-  GL_OPERAND0_ALPHA_ARB* = 0x8598.GLenum
-  GL_DEPTH24_STENCIL8* = 0x88F0.GLenum
-  GL_RENDERBUFFER_RED_SIZE* = 0x8D50.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_COLOR_ENCODING* = 0x8210.GLenum
-  GL_DRAW_BUFFER10_ARB* = 0x882F.GLenum
-  GL_UNSIGNED_INT_SAMPLER_3D* = 0x8DD3.GLenum
-  GL_SKIP_COMPONENTS2_NV* = -5
-  GL_PROGRAM_BINARY_LENGTH_OES* = 0x8741.GLenum
-  GL_VERTEX_ATTRIB_MAP1_SIZE_APPLE* = 0x8A02.GLenum
-  GL_QUERY_RESULT_EXT* = 0x8866.GLenum
-  GL_CONSTANT_COLOR0_NV* = 0x852A.GLenum
-  GL_MAX_ASYNC_DRAW_PIXELS_SGIX* = 0x8360.GLenum
-  GL_DOT_PRODUCT_DIFFUSE_CUBE_MAP_NV* = 0x86F1.GLenum
-  GL_ALPHA_TEST_REF* = 0x0BC2.GLenum
-  GL_MAX_4D_TEXTURE_SIZE_SGIS* = 0x8138.GLenum
-  GL_INT_SAMPLER_2D_MULTISAMPLE* = 0x9109.GLenum
-  GL_DRAW_BUFFER6_ATI* = 0x882B.GLenum
-  GL_INTENSITY16UI_EXT* = 0x8D79.GLenum
-  GL_POINT_FADE_THRESHOLD_SIZE_ARB* = 0x8128.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING* = 0x889F.GLenum
-  GL_RENDERBUFFER_WIDTH_EXT* = 0x8D42.GLenum
-  GL_FIXED_ONLY* = 0x891D.GLenum
-  GL_HISTOGRAM_BLUE_SIZE* = 0x802A.GLenum
-  GL_PROGRAM_TEX_INSTRUCTIONS_ARB* = 0x8806.GLenum
-  GL_MAX_VERTEX_SHADER_VARIANTS_EXT* = 0x87C6.GLenum
-  GL_UNSIGNED_INT_10_10_10_2_EXT* = 0x8036.GLenum
-  GL_SAMPLE_ALPHA_TO_ONE_EXT* = 0x809F.GLenum
-  GL_INDEX_ARRAY* = 0x8077.GLenum
-  GL_GEQUAL* = 0x0206.GLenum
-  GL_MAX_TESS_CONTROL_SHADER_STORAGE_BLOCKS* = 0x90D8.GLenum
-  GL_DITHER* = 0x0BD0.GLenum
-  GL_ATTACHED_SHADERS* = 0x8B85.GLenum
-  GL_FUNC_SUBTRACT* = 0x800A.GLenum
-  GL_ATOMIC_COUNTER_BARRIER_BIT_EXT* = 0x00001000.GLbitfield
-  GL_LUMINANCE4* = 0x803F.GLenum
-  GL_BLEND_EQUATION_RGB_EXT* = 0x8009.GLenum
-  GL_TEXTURE_MULTI_BUFFER_HINT_SGIX* = 0x812E.GLenum
-  GL_DEBUG_SEVERITY_LOW_KHR* = 0x9148.GLenum
-  GL_UNPACK_COMPRESSED_BLOCK_HEIGHT* = 0x9128.GLenum
-  GL_CULL_VERTEX_OBJECT_POSITION_EXT* = 0x81AC.GLenum
-  GL_POST_COLOR_MATRIX_ALPHA_BIAS_SGI* = 0x80BB.GLenum
-  GL_ADD_SIGNED_EXT* = 0x8574.GLenum
-  GL_VERTEX_ARRAY_PARALLEL_POINTERS_INTEL* = 0x83F5.GLenum
-  GL_CURRENT_RASTER_SECONDARY_COLOR* = 0x845F.GLenum
-  GL_MAX_PROGRAM_TEXTURE_GATHER_OFFSET_NV* = 0x8E5F.GLenum
-  GL_CONTINUOUS_AMD* = 0x9007.GLenum
-  GL_R1UI_T2F_C4F_N3F_V3F_SUN* = 0x85CB.GLenum
-  GL_COMPUTE_SHADER* = 0x91B9.GLenum
-  GL_CLIP_DISTANCE6* = 0x3006.GLenum
-  GL_SRC_ATOP_NV* = 0x928E.GLenum
-  GL_DEPTH_COMPONENT16_OES* = 0x81A5.GLenum
-  GL_DOUBLE_MAT4* = 0x8F48.GLenum
-  GL_MAT_SHININESS_BIT_PGI* = 0x02000000.GLbitfield
-  GL_SAMPLER_BUFFER_AMD* = 0x9001.GLenum
-  GL_ARRAY_BUFFER_BINDING_ARB* = 0x8894.GLenum
-  GL_VOLATILE_APPLE* = 0x8A1A.GLenum
-  GL_ALPHA32UI_EXT* = 0x8D72.GLenum
-  GL_COLOR_BUFFER_BIT1_QCOM* = 0x00000002.GLbitfield
-  GL_VERTEX_PROGRAM_CALLBACK_MESA* = 0x8BB4.GLenum
-  GL_CULL_VERTEX_EXT* = 0x81AA.GLenum
-  GL_RENDERBUFFER_STENCIL_SIZE_EXT* = 0x8D55.GLenum
-  GL_SELECT* = 0x1C02.GLenum
-  GL_LUMINANCE12_ALPHA4* = 0x8046.GLenum
-  GL_IMAGE_BINDING_LEVEL_EXT* = 0x8F3B.GLenum
-  GL_MATRIX_PALETTE_ARB* = 0x8840.GLenum
-  GL_DUAL_ALPHA4_SGIS* = 0x8110.GLenum
-  GL_BACK_NORMALS_HINT_PGI* = 0x1A223.GLenum
-  GL_UNSIGNED_SHORT_15_1_MESA* = 0x8753.GLenum
-  GL_UNSIGNED_SHORT_4_4_4_4_REV* = 0x8365.GLenum
-  GL_BUFFER* = 0x82E0.GLenum
-  GL_RENDERBUFFER_INTERNAL_FORMAT_EXT* = 0x8D44.GLenum
-  GL_MATRIX5_NV* = 0x8635.GLenum
-  GL_ATOMIC_COUNTER_BUFFER* = 0x92C0.GLenum
-  GL_SMOOTH_QUADRATIC_CURVE_TO_NV* = 0x0E.GLenum
-  GL_VARIABLE_D_NV* = 0x8526.GLenum
-  GL_PINLIGHT_NV* = 0x92A8.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_INTEGER_EXT* = 0x88FD.GLenum
-  GL_MAX_GEOMETRY_ATOMIC_COUNTER_BUFFERS* = 0x92CF.GLenum
-  GL_Z6Y10Z6CB10Z6A10Z6Y10Z6CR10Z6A10_4224_NV* = 0x9034.GLenum
-  GL_RESAMPLE_REPLICATE_SGIX* = 0x842E.GLenum
-  GL_UNSIGNED_SHORT_5_6_5_REV* = 0x8364.GLenum
-  GL_VERTEX_ATTRIB_ARRAY2_NV* = 0x8652.GLenum
-  GL_3D_COLOR_TEXTURE* = 0x0603.GLenum
-  GL_MAX_VERTEX_TEXTURE_IMAGE_UNITS* = 0x8B4C.GLenum
-  GL_DEBUG_TYPE_PERFORMANCE_KHR* = 0x8250.GLenum
-  GL_MATRIX_INDEX_ARRAY_OES* = 0x8844.GLenum
-  GL_TEXTURE_TOO_LARGE_EXT* = 0x8065.GLenum
-  GL_PACK_IMAGE_HEIGHT_EXT* = 0x806C.GLenum
-  GL_YCBYCR8_422_NV* = 0x9031.GLenum
-  GL_COLOR_ATTACHMENT8* = 0x8CE8.GLenum
-  GL_SAMPLE_COVERAGE_ARB* = 0x80A0.GLenum
-  GL_CURRENT_VERTEX_EXT* = 0x87E2.GLenum
-  GL_LINEAR* = 0x2601.GLint
-  GL_STENCIL_TAG_BITS_EXT* = 0x88F2.GLenum
-  GL_T2F_IUI_V3F_EXT* = 0x81B2.GLenum
-  GL_TEXTURE_3D_BINDING_OES* = 0x806A.GLenum
-  GL_PATH_CLIENT_LENGTH_NV* = 0x907F.GLenum
-  GL_MAT_AMBIENT_BIT_PGI* = 0x00100000.GLbitfield
-  GL_DOUBLE_MAT4x3* = 0x8F4E.GLenum
-  GL_QUERY_BY_REGION_WAIT_NV* = 0x8E15.GLenum
-  GL_LEQUAL* = 0x0203.GLenum
-  GL_PROGRAM_ATTRIBS_ARB* = 0x88AC.GLenum
-  GL_BUFFER_MAPPED_ARB* = 0x88BC.GLenum
-  GL_VERTEX_SHADER_ARB* = 0x8B31.GLenum
-  GL_SOURCE1_ALPHA_EXT* = 0x8589.GLenum
-  GL_UNSIGNED_INT16_VEC3_NV* = 0x8FF2.GLenum
-  GL_MAX_PROGRAM_ADDRESS_REGISTERS_ARB* = 0x88B1.GLenum
-  GL_RGB16* = 0x8054.GLenum
-  GL_TEXTURE15_ARB* = 0x84CF.GLenum
-  GL_TEXTURE_GATHER_SHADOW* = 0x82A3.GLenum
-  GL_FENCE_APPLE* = 0x8A0B.GLenum
-  GL_TRIANGLES* = 0x0004.GLenum
-  GL_DOT4_ATI* = 0x8967.GLenum
-  GL_CURRENT_FOG_COORD* = 0x8453.GLenum
-  GL_DEPTH_CLAMP_NEAR_AMD* = 0x901E.GLenum
-  GL_SYNC_FENCE* = 0x9116.GLenum
-  GL_UNSIGNED_INT64_VEC3_NV* = 0x8FF6.GLenum
-  GL_DEPTH* = 0x1801.GLenum
-  GL_TEXTURE_COORD_NV* = 0x8C79.GLenum
-  GL_COMBINE* = 0x8570.GLenum
-  GL_MAX_VERTEX_UNITS_ARB* = 0x86A4.GLenum
-  GL_COLOR_INDEX2_EXT* = 0x80E3.GLenum
-  GL_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP* = 0x8162.GLenum
-  GL_INT_SAMPLER_CUBE_MAP_ARRAY_ARB* = 0x900E.GLenum
-  GL_MIRROR_CLAMP_EXT* = 0x8742.GLint
-  GL_STENCIL_VALUE_MASK* = 0x0B93.GLenum
-  GL_UNSIGNED_INT_SAMPLER_BUFFER* = 0x8DD8.GLenum
-  GL_TRACK_MATRIX_NV* = 0x8648.GLenum
-  GL_MAP1_VERTEX_3* = 0x0D97.GLenum
-  GL_OP_MOV_EXT* = 0x8799.GLenum
-  GL_MAP_INVALIDATE_RANGE_BIT_EXT* = 0x0004.GLbitfield
-  GL_MAX_CONVOLUTION_WIDTH_EXT* = 0x801A.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_OES* = 0x8518.GLenum
-  GL_RGBA_SNORM* = 0x8F93.GLenum
-  GL_MAX_TRACK_MATRICES_NV* = 0x862F.GLenum
-  GL_MAX_TESS_EVALUATION_INPUT_COMPONENTS* = 0x886D.GLenum
-  GL_DOUBLE_VEC4_EXT* = 0x8FFE.GLenum
-  GL_COLOR_TABLE_BLUE_SIZE* = 0x80DC.GLenum
-  GL_T2F_C3F_V3F* = 0x2A2A.GLenum
-  GL_INTENSITY16_SNORM* = 0x901B.GLenum
-  GL_INT_IMAGE_CUBE_MAP_ARRAY_EXT* = 0x905F.GLenum
-  GL_DEBUG_CATEGORY_UNDEFINED_BEHAVIOR_AMD* = 0x914C.GLenum
-  GL_NORMAL_MAP_EXT* = 0x8511.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_ATTRIBS_NV* = 0x8C8B.GLenum
-  GL_DRAW_BUFFER4_EXT* = 0x8829.GLenum
-  GL_PIXEL_MAP_G_TO_G* = 0x0C77.GLenum
-  GL_TESS_GEN_POINT_MODE* = 0x8E79.GLenum
-  GL_MAX_VERTEX_ATOMIC_COUNTER_BUFFERS* = 0x92CC.GLenum
-  GL_UNSIGNED_INT_SAMPLER_2D_RECT_EXT* = 0x8DD5.GLenum
-  GL_MULTISAMPLE_BUFFER_BIT2_QCOM* = 0x04000000.GLbitfield
-  GL_POST_COLOR_MATRIX_GREEN_BIAS_SGI* = 0x80B9.GLenum
-  GL_POST_COLOR_MATRIX_GREEN_BIAS* = 0x80B9.GLenum
-  GL_TEXTURE10* = 0x84CA.GLenum
-  GL_RGB32F* = 0x8815.GLenum
-  GL_DYNAMIC_READ_ARB* = 0x88E9.GLenum
-  GL_MODELVIEW22_ARB* = 0x8736.GLenum
-  GL_VERTEX_STREAM0_ATI* = 0x876C.GLenum
-  GL_TEXTURE_FETCH_BARRIER_BIT_EXT* = 0x00000008.GLbitfield
-  GL_COMBINER_INPUT_NV* = 0x8542.GLenum
-  GL_DRAW_BUFFER0_NV* = 0x8825.GLenum
-  GL_ALPHA_TEST* = 0x0BC0.GLenum
-  GL_PIXEL_UNPACK_BUFFER* = 0x88EC.GLenum
-  GL_SRC_IN_NV* = 0x928A.GLenum
-  GL_COMPRESSED_SIGNED_RED_RGTC1_EXT* = 0x8DBC.GLenum
-  GL_PACK_SUBSAMPLE_RATE_SGIX* = 0x85A0.GLenum
-  GL_FRAMEBUFFER_DEFAULT_SAMPLES* = 0x9313.GLenum
-  GL_ARRAY_OBJECT_OFFSET_ATI* = 0x8767.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_X_OES* = 0x8515.GLenum
-  GL_STENCIL_BITS* = 0x0D57.GLenum
-  GL_DEPTH_COMPONENT24_OES* = 0x81A6.GLenum
-  GL_FRAMEBUFFER* = 0x8D40.GLenum
-  GL_8X_BIT_ATI* = 0x00000004.GLbitfield
-  GL_TEXTURE_BINDING_2D_MULTISAMPLE_ARRAY* = 0x9105.GLenum
-  GL_BOOL_VEC2* = 0x8B57.GLenum
-  GL_EXP* = 0x0800.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT* = 0x851A.GLenum
-  GL_STENCIL_INDEX16* = 0x8D49.GLenum
-  GL_FRAGMENT_LIGHTING_SGIX* = 0x8400.GLenum
-  GL_PACK_SKIP_PIXELS* = 0x0D04.GLenum
-  GL_TEXTURE_MIN_LOD* = 0x813A.GLenum
-  GL_COMPRESSED_RGB* = 0x84ED.GLenum
-  GL_MAP1_VERTEX_ATTRIB2_4_NV* = 0x8662.GLenum
-  GL_CONJOINT_NV* = 0x9284.GLenum
-  GL_MAX_COMPUTE_SHARED_MEMORY_SIZE* = 0x8262.GLenum
-  GL_INTENSITY8* = 0x804B.GLenum
-  GL_SAMPLER_2D_MULTISAMPLE* = 0x9108.GLenum
-  GL_MAX_LIST_NESTING* = 0x0B31.GLenum
-  GL_DOUBLE_MAT3* = 0x8F47.GLenum
-  GL_TEXTURE_DEPTH* = 0x8071.GLenum
-  GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION* = 0x8E4C.GLenum
-  GL_TEXTURE12_ARB* = 0x84CC.GLenum
-  GL_R1UI_T2F_V3F_SUN* = 0x85C9.GLenum
-  GL_REPLACE* = 0x1E01.GLenum
-  GL_MAX_NUM_ACTIVE_VARIABLES* = 0x92F7.GLenum
-  GL_RGBA_INTEGER_EXT* = 0x8D99.GLenum
-  GL_TEXTURE_COMPRESSED_BLOCK_SIZE* = 0x82B3.GLenum
-  GL_INDEX_CLEAR_VALUE* = 0x0C20.GLenum
-  GL_PROGRAM_ERROR_POSITION_ARB* = 0x864B.GLenum
-  GL_LINEARBURN_NV* = 0x92A5.GLenum
-  GL_TEXTURE_BINDING_CUBE_MAP_ARB* = 0x8514.GLenum
-  GL_TESSELLATION_FACTOR_AMD* = 0x9005.GLenum
-  GL_SHADER_IMAGE_STORE* = 0x82A5.GLenum
-  GL_COMPRESSED_SLUMINANCE_ALPHA_EXT* = 0x8C4B.GLenum
-  GL_MAX_PALETTE_MATRICES_ARB* = 0x8842.GLenum
-  GL_UNPACK_CONSTANT_DATA_SUNX* = 0x81D5.GLenum
-  GL_FLOAT_MAT3x4* = 0x8B68.GLenum
-  GL_DRAW_BUFFER8_NV* = 0x882D.GLenum
-  GL_ATTENUATION_EXT* = 0x834D.GLenum
-  GL_REG_25_ATI* = 0x893A.GLenum
-  GL_UNSIGNED_INT_SAMPLER_1D* = 0x8DD1.GLenum
-  GL_TEXTURE_1D_STACK_BINDING_MESAX* = 0x875D.GLenum
-  GL_SYNC_STATUS_APPLE* = 0x9114.GLenum
-  GL_TEXTURE_CUBE_MAP_ARRAY* = 0x9009.GLenum
-  GL_EXP2* = 0x0801.GLenum
-  GL_COMPRESSED_SIGNED_LUMINANCE_LATC1_EXT* = 0x8C71.GLenum
-  GL_BUFFER_ACCESS_ARB* = 0x88BB.GLenum
-  GL_LO_BIAS_NV* = 0x8715.GLenum
-  GL_MIRROR_CLAMP_ATI* = 0x8742.GLint
-  GL_SAMPLE_COVERAGE_VALUE* = 0x80AA.GLenum
-  GL_UNSIGNED_INT_24_8_EXT* = 0x84FA.GLenum
-  GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_EXT* = 0x8C88.GLenum
-  GL_R16UI* = 0x8234.GLenum
-  GL_BLEND_PREMULTIPLIED_SRC_NV* = 0x9280.GLenum
-  GL_COLOR_ATTACHMENT0* = 0x8CE0.GLenum
-  GL_GEOMETRY_VERTICES_OUT_EXT* = 0x8DDA.GLenum
-  GL_SAMPLE_MASK_NV* = 0x8E51.GLenum
-  GL_BGRA_INTEGER_EXT* = 0x8D9B.GLenum
-  GL_PALETTE8_RGBA8_OES* = 0x8B96.GLenum
-  GL_MAX_ARRAY_TEXTURE_LAYERS_EXT* = 0x88FF.GLenum
-  GL_TEXTURE_COLOR_TABLE_SGI* = 0x80BC.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS_EXT* = 0x8C80.GLenum
-  GL_TEXTURE10_ARB* = 0x84CA.GLenum
-  GL_TRIANGLES_ADJACENCY* = 0x000C.GLenum
-  GL_COLOR_ARRAY_EXT* = 0x8076.GLenum
-  GL_MAX_FRAMEBUFFER_SAMPLES* = 0x9318.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_BUFFER_BINDING_ARB* = 0x889F.GLenum
-  GL_IMAGE_TEXEL_SIZE* = 0x82A7.GLenum
-  GL_MAGNITUDE_BIAS_NV* = 0x8718.GLenum
-  GL_SHADOW_AMBIENT_SGIX* = 0x80BF.GLenum
-  GL_BUFFER_SERIALIZED_MODIFY_APPLE* = 0x8A12.GLenum
-  GL_TEXTURE_COORD_ARRAY_COUNT_EXT* = 0x808B.GLenum
-  GL_MAX_DRAW_BUFFERS_ARB* = 0x8824.GLenum
-  GL_MAX_OPTIMIZED_VERTEX_SHADER_INVARIANTS_EXT* = 0x87CD.GLenum
-  GL_PASS_THROUGH_TOKEN* = 0x0700.GLenum
-  GL_BLEND_EQUATION* = 0x8009.GLenum
-  GL_FOG_HINT* = 0x0C54.GLenum
-  GL_FLOAT_RGB16_NV* = 0x8888.GLenum
-  GL_OUTPUT_TEXTURE_COORD18_EXT* = 0x87AF.GLenum
-  GL_T2F_IUI_N3F_V2F_EXT* = 0x81B3.GLenum
-  GL_SAMPLER_EXTERNAL_OES* = 0x8D66.GLenum
-  GL_MAX_SUBROUTINES* = 0x8DE7.GLenum
-  GL_RED_BIT_ATI* = 0x00000001.GLbitfield
-  GL_SOURCE2_ALPHA* = 0x858A.GLenum
-  GL_AUX0* = 0x0409.GLenum
-  GL_OPERAND1_ALPHA_ARB* = 0x8599.GLenum
-  GL_TEXTURE_MAX_ANISOTROPY_EXT* = 0x84FE.GLenum
-  GL_VERTEX_PROGRAM_POINT_SIZE_NV* = 0x8642.GLenum
-  GL_MULTIVIEW_EXT* = 0x90F1.GLenum
-  GL_FOG_OFFSET_SGIX* = 0x8198.GLenum
-  GL_COLOR_ARRAY_PARALLEL_POINTERS_INTEL* = 0x83F7.GLenum
-  GL_ELEMENT_ARRAY_ATI* = 0x8768.GLenum
-  GL_ALPHA16_SNORM* = 0x9018.GLenum
-  GL_COMPRESSED_SLUMINANCE_EXT* = 0x8C4A.GLenum
-  GL_TEXTURE_OBJECT_VALID_QCOM* = 0x8BDB.GLenum
-  GL_STENCIL_BACK_FUNC* = 0x8800.GLenum
-  GL_CULL_FACE* = 0x0B44.GLenum
-  GL_MAP1_COLOR_4* = 0x0D90.GLenum
-  GL_SHADER_OBJECT_ARB* = 0x8B48.GLenum
-  GL_COMPRESSED_RGB_PVRTC_2BPPV1_IMG* = 0x8C01.GLenum
-  GL_TANGENT_ARRAY_EXT* = 0x8439.GLenum
-  GL_NUM_FRAGMENT_CONSTANTS_ATI* = 0x896F.GLenum
-  GL_COLOR_RENDERABLE* = 0x8286.GLenum
-  GL_MAX_COMBINED_TEXTURE_IMAGE_UNITS* = 0x8B4D.GLenum
-  GL_TRANSFORM_FEEDBACK_RECORD_NV* = 0x8C86.GLenum
-  GL_COLOR_ATTACHMENT1_NV* = 0x8CE1.GLenum
-  GL_ALPHA_SNORM* = 0x9010.GLenum
-  GL_PIXEL_TRANSFORM_2D_MATRIX_EXT* = 0x8338.GLenum
-  GL_SMOOTH_POINT_SIZE_GRANULARITY* = 0x0B13.GLenum
-  GL_R8I* = 0x8231.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_EXT* = 0x8D56.GLenum
-  GL_POLYGON_OFFSET_BIAS_EXT* = 0x8039.GLenum
-  GL_DEPTH_COMPONENT24* = 0x81A6.GLenum
-  GL_TEXTURE_SWIZZLE_B* = 0x8E44.GLenum
-  GL_MAX_TESS_CONTROL_TEXTURE_IMAGE_UNITS* = 0x8E81.GLenum
-  GL_MAP2_INDEX* = 0x0DB1.GLenum
-  GL_SAMPLER_CUBE_MAP_ARRAY* = 0x900C.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT_EXT* = 0x8CD6.GLenum
-  GL_UNSIGNED_INT_8_8_8_8_REV* = 0x8367.GLenum
-  GL_PATH_GEN_COEFF_NV* = 0x90B1.GLenum
-  GL_OPERAND3_ALPHA_NV* = 0x859B.GLenum
-  GL_LUMINANCE* = 0x1909.GLenum
-  GL_MAX_SUBROUTINE_UNIFORM_LOCATIONS* = 0x8DE8.GLenum
-  GL_MAP_READ_BIT* = 0x0001.GLbitfield
-  GL_MAX_TEXTURE_STACK_DEPTH* = 0x0D39.GLenum
-  GL_ORDER* = 0x0A01.GLenum
-  GL_PATH_FILL_MODE_NV* = 0x9080.GLenum
-  GL_RENDERBUFFER_BLUE_SIZE* = 0x8D52.GLenum
-  GL_TEXTURE_INTENSITY_SIZE* = 0x8061.GLenum
-  GL_DRAW_BUFFER1_NV* = 0x8826.GLenum
-  GL_SCREEN_NV* = 0x9295.GLenum
-  GL_RGB8I_EXT* = 0x8D8F.GLenum
-  GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET* = 0x8E5E.GLenum
-  GL_DUAL_INTENSITY12_SGIS* = 0x811A.GLenum
-  GL_SPARE1_NV* = 0x852F.GLenum
-  GL_PALETTE8_R5_G6_B5_OES* = 0x8B97.GLenum
-  GL_COLOR_ATTACHMENT7_NV* = 0x8CE7.GLenum
-  GL_TEXTURE_HEIGHT* = 0x1001.GLenum
-  GL_RENDERBUFFER_BINDING* = 0x8CA7.GLenum
-  GL_DRAW_BUFFER7_EXT* = 0x882C.GLenum
-  GL_HISTOGRAM* = 0x8024.GLenum
-  GL_COLOR_ATTACHMENT0_OES* = 0x8CE0.GLenum
-  GL_BINORMAL_ARRAY_STRIDE_EXT* = 0x8441.GLenum
-  GL_DEBUG_SEVERITY_HIGH_AMD* = 0x9146.GLenum
-  GL_MIN_SPARSE_LEVEL_AMD* = 0x919B.GLenum
-  GL_MAP1_VERTEX_ATTRIB10_4_NV* = 0x866A.GLenum
-  GL_COEFF* = 0x0A00.GLenum
-  GL_COMPRESSED_RGBA_ASTC_6x5_KHR* = 0x93B3.GLenum
-  GL_TEXTURE_4D_BINDING_SGIS* = 0x814F.GLenum
-  GL_BUFFER_USAGE* = 0x8765.GLenum
-  GL_YCBCR_MESA* = 0x8757.GLenum
-  GL_CLAMP_VERTEX_COLOR* = 0x891A.GLenum
-  GL_RGBA8_EXT* = 0x8058.GLenum
-  GL_BITMAP_TOKEN* = 0x0704.GLenum
-  GL_IMAGE_SCALE_Y_HP* = 0x8156.GLenum
-  GL_OUTPUT_TEXTURE_COORD25_EXT* = 0x87B6.GLenum
-  GL_DEBUG_SOURCE_API* = 0x8246.GLenum
-  GL_STACK_UNDERFLOW* = 0x0504.GLenum
-  GL_COMBINER_CD_DOT_PRODUCT_NV* = 0x8546.GLenum
-  GL_FRAMEBUFFER_BINDING_EXT* = 0x8CA6.GLenum
-  GL_REG_20_ATI* = 0x8935.GLenum
-  GL_MAP1_TEXTURE_COORD_4* = 0x0D96.GLenum
-  GL_DEBUG_OUTPUT_SYNCHRONOUS* = 0x8242.GLenum
-  GL_ACCUM_ALPHA_BITS* = 0x0D5B.GLenum
-  GL_INT_10_10_10_2_OES* = 0x8DF7.GLenum
-  GL_FLOAT_MAT2_ARB* = 0x8B5A.GLenum
-  GL_FRONT_RIGHT* = 0x0401.GLenum
-  GL_COMBINER_AB_DOT_PRODUCT_NV* = 0x8545.GLenum
-  GL_LUMINANCE_ALPHA* = 0x190A.GLenum
-  GL_C4UB_V2F* = 0x2A22.GLenum
-  GL_COMBINER_MUX_SUM_NV* = 0x8547.GLenum
-  GL_MODELVIEW_STACK_DEPTH* = 0x0BA3.GLenum
-  GL_SAMPLES_ARB* = 0x80A9.GLenum
-  GL_ALPHA_TEST_FUNC* = 0x0BC1.GLenum
-  GL_DEPTH_CLAMP* = 0x864F.GLenum
-  GL_MAP2_VERTEX_ATTRIB8_4_NV* = 0x8678.GLenum
-  GL_INVALID_INDEX* = 0xFFFFFFFF.GLenum
-  GL_COMBINER_SCALE_NV* = 0x8548.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_FRAGMENT_SHADER* = 0x92CB.GLenum
-  GL_DOT_PRODUCT_TEXTURE_RECTANGLE_NV* = 0x864E.GLenum
-  GL_RELATIVE_SMALL_CW_ARC_TO_NV* = 0x15.GLenum
-  GL_UNSIGNED_INT_10_10_10_2_OES* = 0x8DF6.GLenum
-  GL_DISCARD_ATI* = 0x8763.GLenum
-  GL_PRIMITIVE_RESTART_INDEX_NV* = 0x8559.GLenum
-  GL_IMAGE_CLASS_2_X_8* = 0x82C0.GLenum
-  GL_MANUAL_GENERATE_MIPMAP* = 0x8294.GLenum
-  GL_FLOAT_R_NV* = 0x8880.GLenum
-  GL_SATURATE_BIT_ATI* = 0x00000040.GLbitfield
-  GL_BUFFER_SIZE* = 0x8764.GLenum
-  GL_FRAMEBUFFER_BARRIER_BIT_EXT* = 0x00000400.GLbitfield
-  GL_LUMINANCE8UI_EXT* = 0x8D80.GLenum
-  GL_T2F_IUI_V2F_EXT* = 0x81B1.GLenum
-  GL_OUTPUT_TEXTURE_COORD15_EXT* = 0x87AC.GLenum
-  GL_COVERAGE_AUTOMATIC_NV* = 0x8ED7.GLenum
-  GL_TEXTURE_INTERNAL_FORMAT_QCOM* = 0x8BD5.GLenum
-  GL_INT_IMAGE_CUBE_MAP_ARRAY* = 0x905F.GLenum
-  GL_BUFFER_UPDATE_BARRIER_BIT_EXT* = 0x00000200.GLbitfield
-  GL_GLYPH_WIDTH_BIT_NV* = 0x01.GLbitfield
-  GL_OP_MAX_EXT* = 0x878A.GLenum
-  GL_MINMAX_FORMAT_EXT* = 0x802F.GLenum
-  GL_R16I* = 0x8233.GLenum
-  GL_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB* = 0x8809.GLenum
-  GL_TEXTURE_MAX_LEVEL* = 0x813D.GLenum
-  GL_GEOMETRY_SHADER* = 0x8DD9.GLenum
-  GL_MAX_RENDERBUFFER_SIZE* = 0x84E8.GLenum
-  GL_RGB16_EXT* = 0x8054.GLenum
-  GL_DUAL_INTENSITY16_SGIS* = 0x811B.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_ATTACHMENT* = 0x8CD6.GLenum
-  GL_BLUE_SCALE* = 0x0D1A.GLenum
-  GL_RGBA_FLOAT16_APPLE* = 0x881A.GLenum
-  GL_RGBA8UI* = 0x8D7C.GLenum
-  GL_COLOR_ATTACHMENT5* = 0x8CE5.GLenum
-  GL_UNSIGNED_IDENTITY_NV* = 0x8536.GLenum
-  GL_COMPRESSED_RGBA_ASTC_10x8_KHR* = 0x93BA.GLenum
-  GL_FRAGMENT_SHADER_ARB* = 0x8B30.GLenum
-  GL_R8* = 0x8229.GLenum
-  GL_IMAGE_BINDING_LAYERED* = 0x8F3C.GLenum
-  GL_RGBA_FLOAT32_ATI* = 0x8814.GLenum
-  GL_TEXTURE_RED_SIZE_EXT* = 0x805C.GLenum
-  GL_INT8_VEC2_NV* = 0x8FE1.GLenum
-  GL_NEGATE_BIT_ATI* = 0x00000004.GLbitfield
-  GL_ALL_BARRIER_BITS_EXT* = 0xFFFFFFFF.GLbitfield
-  GL_LIGHT_MODEL_COLOR_CONTROL_EXT* = 0x81F8.GLenum
-  GL_LUMINANCE_ALPHA16UI_EXT* = 0x8D7B.GLenum
-  GL_COUNT_UP_NV* = 0x9088.GLenum
-  GL_QUERY_RESULT_AVAILABLE_ARB* = 0x8867.GLenum
-  GL_DRAW_INDIRECT_BUFFER* = 0x8F3F.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_CUBE_MAP_FACE_EXT* = 0x8CD3.GLenum
-  GL_OP_DOT3_EXT* = 0x8784.GLenum
-  GL_COLOR_ATTACHMENT10_NV* = 0x8CEA.GLenum
-  GL_STENCIL_INDEX4_OES* = 0x8D47.GLenum
-  GL_LUMINANCE_FLOAT32_ATI* = 0x8818.GLenum
-  GL_DRAW_BUFFER9_ARB* = 0x882E.GLenum
-  GL_RG8_EXT* = 0x822B.GLenum
-  GL_FONT_DESCENDER_BIT_NV* = 0x00400000.GLbitfield
-  GL_TEXTURE_ALPHA_SIZE_EXT* = 0x805F.GLenum
-  GL_Y_EXT* = 0x87D6.GLenum
-  GL_MAX_GEOMETRY_BINDABLE_UNIFORMS_EXT* = 0x8DE4.GLenum
-  GL_SAMPLER_3D_ARB* = 0x8B5F.GLenum
-  GL_INVERT_OVG_NV* = 0x92B4.GLenum
-  GL_REFERENCED_BY_TESS_EVALUATION_SHADER* = 0x9308.GLenum
-  GL_TEXTURE_COORD_ARRAY_PARALLEL_POINTERS_INTEL* = 0x83F8.GLenum
-  GL_LIGHT4* = 0x4004.GLenum
-  GL_VERTEX_STATE_PROGRAM_NV* = 0x8621.GLenum
-  GL_ZERO* = 0.GLenum
-  GL_SAMPLER_CUBE_MAP_ARRAY_ARB* = 0x900C.GLenum
-  GL_SAMPLE_MASK_EXT* = 0x80A0.GLenum
-  GL_COMBINER_CD_OUTPUT_NV* = 0x854B.GLenum
-  GL_SAMPLE_ALPHA_TO_MASK_SGIS* = 0x809E.GLenum
-  GL_RGBA16* = 0x805B.GLenum
-  GL_PATH_TERMINAL_DASH_CAP_NV* = 0x907D.GLenum
-  GL_SECONDARY_COLOR_ARRAY_BUFFER_BINDING_ARB* = 0x889C.GLenum
-  GL_DEBUG_SEVERITY_HIGH_KHR* = 0x9146.GLenum
-  GL_DRAW_BUFFER14_EXT* = 0x8833.GLenum
-  GL_READ_FRAMEBUFFER* = 0x8CA8.GLenum
-  GL_UNSIGNED_SHORT_8_8_APPLE* = 0x85BA.GLenum
-  GL_OR* = 0x1507.GLenum
-  GL_ONE_MINUS_DST_ALPHA* = 0x0305.GLenum
-  GL_RGB12* = 0x8053.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_OES* = 0x8CDB.GLenum
-  GL_OUTPUT_TEXTURE_COORD26_EXT* = 0x87B7.GLenum
-  GL_LOCAL_CONSTANT_VALUE_EXT* = 0x87EC.GLenum
-  GL_SURFACE_REGISTERED_NV* = 0x86FD.GLenum
-  GL_FRAGMENT_PROGRAM_INTERPOLATION_OFFSET_BITS_NV* = 0x8E5D.GLenum
-  GL_COMPRESSED_RG_RGTC2* = 0x8DBD.GLenum
-  GL_MAX_VERTEX_ATTRIB_STRIDE* = 0x82E5.GLenum
-  GL_COLOR_ARRAY_ADDRESS_NV* = 0x8F23.GLenum
-  GL_MATRIX_INDEX_ARRAY_POINTER_ARB* = 0x8849.GLenum
-  GL_DUAL_ALPHA8_SGIS* = 0x8111.GLenum
-  GL_TEXTURE_MAX_LOD* = 0x813B.GLenum
-  GL_INTERNALFORMAT_SHARED_SIZE* = 0x8277.GLenum
-  GL_LINEAR_DETAIL_SGIS* = 0x8097.GLenum
-  GL_RG16F_EXT* = 0x822F.GLenum
-  GL_LIST_MODE* = 0x0B30.GLenum
-  GL_VIEWPORT_INDEX_PROVOKING_VERTEX* = 0x825F.GLenum
-  GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW* = 0x900D.GLenum
-  GL_COLOR_TABLE_LUMINANCE_SIZE* = 0x80DE.GLenum
-  GL_COLOR_ARRAY_POINTER* = 0x8090.GLenum
-  GL_MAX_TEXTURE_MAX_ANISOTROPY_EXT* = 0x84FF.GLenum
-  GL_LUMINANCE32F_EXT* = 0x8818.GLenum
-  GL_FRAMEBUFFER_COMPLETE_OES* = 0x8CD5.GLenum
-  GL_MAX_PROGRAM_TEXTURE_GATHER_COMPONENTS_ARB* = 0x8F9F.GLenum
-  GL_FEEDBACK* = 0x1C01.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_ARRAY* = 0x9069.GLenum
-  GL_VERTEX_STREAM1_ATI* = 0x876D.GLenum
-  GL_SLUMINANCE_ALPHA_NV* = 0x8C44.GLenum
-  GL_MAX_TEXTURE_UNITS_ARB* = 0x84E2.GLenum
-  GL_MODELVIEW11_ARB* = 0x872B.GLenum
-  GL_DRAW_FRAMEBUFFER_BINDING_ANGLE* = 0x8CA6.GLenum
-  GL_NEGATIVE_W_EXT* = 0x87DC.GLenum
-  GL_MODELVIEW25_ARB* = 0x8739.GLenum
-  GL_NORMAL_ARRAY_LIST_STRIDE_IBM* = 103081.GLenum
-  GL_CON_0_ATI* = 0x8941.GLenum
-  GL_VERTEX_SHADER_INSTRUCTIONS_EXT* = 0x87CF.GLenum
-  GL_TRANSPOSE_PROGRAM_MATRIX_EXT* = 0x8E2E.GLenum
-  GL_TEXTURE_DEPTH_TYPE* = 0x8C16.GLenum
-  GL_PROGRAM_TARGET_NV* = 0x8646.GLenum
-  GL_MAX_OPTIMIZED_VERTEX_SHADER_LOCAL_CONSTANTS_EXT* = 0x87CC.GLenum
-  GL_NORMAL_ARRAY_STRIDE_EXT* = 0x807F.GLenum
-  GL_INT_SAMPLER_2D* = 0x8DCA.GLenum
-  GL_MAP2_VERTEX_ATTRIB10_4_NV* = 0x867A.GLenum
-  GL_STEREO* = 0x0C33.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_RECT_EXT* = 0x9065.GLenum
-  GL_TESS_EVALUATION_PROGRAM_PARAMETER_BUFFER_NV* = 0x8C75.GLenum
-  GL_TRACE_ERRORS_BIT_MESA* = 0x0020.GLbitfield
-  GL_MAX_GEOMETRY_UNIFORM_BLOCKS* = 0x8A2C.GLenum
-  GL_CONVOLUTION_2D* = 0x8011.GLenum
-  GL_RGB_SCALE_ARB* = 0x8573.GLenum
-  GL_VIDEO_COLOR_CONVERSION_MAX_NV* = 0x902A.GLenum
-  GL_MAX_SHADER_STORAGE_BUFFER_BINDINGS* = 0x90DD.GLenum
-  GL_TABLE_TOO_LARGE_EXT* = 0x8031.GLenum
-  GL_TRANSFORM_FEEDBACK_BINDING_NV* = 0x8E25.GLenum
-  GL_TEXTURE16_ARB* = 0x84D0.GLenum
-  GL_FRAGMENT_SHADER_DERIVATIVE_HINT* = 0x8B8B.GLenum
-  GL_IUI_N3F_V2F_EXT* = 0x81AF.GLenum
-  GL_CLIP_PLANE2_IMG* = 0x3002.GLenum
-  GL_VERTEX_ATTRIB_ARRAY10_NV* = 0x865A.GLenum
-  GL_TEXTURE_FETCH_BARRIER_BIT* = 0x00000008.GLbitfield
-  GL_DOT3_RGBA_EXT* = 0x8741.GLenum
-  GL_RENDERBUFFER_GREEN_SIZE_EXT* = 0x8D51.GLenum
-  GL_MAX_CLIENT_ATTRIB_STACK_DEPTH* = 0x0D3B.GLenum
-  GL_UNPACK_COMPRESSED_BLOCK_SIZE* = 0x912A.GLenum
-  GL_SAMPLE_BUFFERS_SGIS* = 0x80A8.GLenum
-  GL_MAP1_VERTEX_ATTRIB1_4_NV* = 0x8661.GLenum
-  GL_BUFFER_OBJECT_EXT* = 0x9151.GLenum
-  GL_INT_SAMPLER_1D_ARRAY* = 0x8DCE.GLenum
-  GL_POST_TEXTURE_FILTER_SCALE_SGIX* = 0x817A.GLenum
-  GL_RED_MAX_CLAMP_INGR* = 0x8564.GLenum
-  GL_POST_COLOR_MATRIX_RED_SCALE_SGI* = 0x80B4.GLenum
-  GL_TEXTURE_COORD_ARRAY_TYPE* = 0x8089.GLenum
-  GL_COMPRESSED_SIGNED_RG11_EAC* = 0x9273.GLenum
-  GL_MULTISAMPLE_FILTER_HINT_NV* = 0x8534.GLenum
-  GL_COMPRESSED_RGBA8_ETC2_EAC* = 0x9278.GLenum
-  GL_FONT_UNDERLINE_THICKNESS_BIT_NV* = 0x08000000.GLbitfield
-  GL_READ_WRITE_ARB* = 0x88BA.GLenum
-  GL_RENDER_MODE* = 0x0C40.GLenum
-  GL_MAX_NUM_COMPATIBLE_SUBROUTINES* = 0x92F8.GLenum
-  GL_PN_TRIANGLES_NORMAL_MODE_QUADRATIC_ATI* = 0x87F8.GLenum
-  GL_MODELVIEW0_STACK_DEPTH_EXT* = 0x0BA3.GLenum
-  GL_CONTEXT_FLAG_DEBUG_BIT* = 0x00000002.GLbitfield
-  GL_TRANSFORM_FEEDBACK_BUFFER_START_EXT* = 0x8C84.GLenum
-  GL_POINT_SIZE_MAX_EXT* = 0x8127.GLenum
-  GL_COLOR_ARRAY_LENGTH_NV* = 0x8F2D.GLenum
-  GL_COLOR_COMPONENTS* = 0x8283.GLenum
-  GL_LINEARDODGE_NV* = 0x92A4.GLenum
-  GL_TEXTURE20_ARB* = 0x84D4.GLenum
-  GL_UNSIGNED_INT64_VEC4_NV* = 0x8FF7.GLenum
-  GL_TEXTURE28* = 0x84DC.GLenum
-  GL_HISTOGRAM_FORMAT_EXT* = 0x8027.GLenum
-  GL_PROGRAM_MATRIX_EXT* = 0x8E2D.GLenum
-  GL_PIXEL_PACK_BUFFER_EXT* = 0x88EB.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT* = 0x8515.GLenum
-  GL_STANDARD_FONT_NAME_NV* = 0x9072.GLenum
-  GL_REG_13_ATI* = 0x892E.GLenum
-  GL_GREEN_SCALE* = 0x0D18.GLenum
-  GL_COLOR_BUFFER_BIT7_QCOM* = 0x00000080.GLbitfield
-  GL_MAX_COMPUTE_ATOMIC_COUNTER_BUFFERS* = 0x8264.GLenum
-  GL_LUMINANCE8_ALPHA8_SNORM* = 0x9016.GLenum
-  GL_GCCSO_SHADER_BINARY_FJ* = 0x9260.GLenum
-  GL_COORD_REPLACE_NV* = 0x8862.GLenum
-  GL_SOURCE2_RGB_EXT* = 0x8582.GLenum
-  GL_IR_INSTRUMENT1_SGIX* = 0x817F.GLenum
-  GL_CONTEXT_FLAG_DEBUG_BIT_KHR* = 0x00000002.GLbitfield
-  GL_SWIZZLE_STR_ATI* = 0x8976.GLenum
-  GL_OUTPUT_TEXTURE_COORD17_EXT* = 0x87AE.GLenum
-  GL_MODELVIEW2_ARB* = 0x8722.GLenum
-  GL_R1UI_C4F_N3F_V3F_SUN* = 0x85C8.GLenum
-  GL_MAX_TEXTURE_BUFFER_SIZE_ARB* = 0x8C2B.GLenum
-  GL_OUTPUT_TEXTURE_COORD0_EXT* = 0x879D.GLenum
-  GL_POINT_FADE_THRESHOLD_SIZE_EXT* = 0x8128.GLenum
-  GL_OUTPUT_TEXTURE_COORD30_EXT* = 0x87BB.GLenum
-  GL_EVAL_VERTEX_ATTRIB3_NV* = 0x86C9.GLenum
-  GL_SPHERE_MAP* = 0x2402.GLenum
-  GL_SHADER_IMAGE_ATOMIC* = 0x82A6.GLenum
-  GL_INDEX_BITS* = 0x0D51.GLenum
-  GL_INTERNALFORMAT_ALPHA_TYPE* = 0x827B.GLenum
-  GL_CON_15_ATI* = 0x8950.GLenum
-  GL_TESS_EVALUATION_TEXTURE* = 0x829D.GLenum
-  GL_EDGE_FLAG_ARRAY_STRIDE* = 0x808C.GLenum
-  GL_VERTEX_ATTRIB_ARRAY8_NV* = 0x8658.GLenum
-  GL_POST_COLOR_MATRIX_COLOR_TABLE* = 0x80D2.GLenum
-  GL_CLOSE_PATH_NV* = 0x00.GLenum
-  GL_SCALE_BY_TWO_NV* = 0x853E.GLenum
-  GL_PALETTE8_RGB8_OES* = 0x8B95.GLenum
-  GL_MAX_COMPUTE_ATOMIC_COUNTERS* = 0x8265.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_NORMALIZED* = 0x886A.GLenum
-  GL_MAX_VERTEX_ATTRIBS* = 0x8869.GLenum
-  GL_PROGRAM_POINT_SIZE_EXT* = 0x8642.GLenum
-  GL_TRANSLATED_SHADER_SOURCE_LENGTH_ANGLE* = 0x93A0.GLenum
-  GL_SIGNED_NORMALIZED* = 0x8F9C.GLenum
-  GL_MAX_CUBE_MAP_TEXTURE_SIZE_OES* = 0x851C.GLenum
-  GL_OFFSET_TEXTURE_2D_SCALE_NV* = 0x86E2.GLenum
-  GL_COMPRESSED_SLUMINANCE* = 0x8C4A.GLenum
-  GL_MAX_TESS_EVALUATION_UNIFORM_COMPONENTS* = 0x8E80.GLenum
-  GL_RASTER_POSITION_UNCLIPPED_IBM* = 0x19262.GLenum
-  GL_COMPRESSED_TEXTURE_FORMATS_ARB* = 0x86A3.GLenum
-  GL_TRANSPOSE_MODELVIEW_MATRIX* = 0x84E3.GLenum
-  GL_ALPHA_FLOAT16_APPLE* = 0x881C.GLenum
-  GL_PIXEL_MIN_FILTER_EXT* = 0x8332.GLenum
-  GL_MAX_SPARSE_TEXTURE_SIZE_AMD* = 0x9198.GLenum
-  GL_UNSIGNED_SHORT_5_6_5_REV_EXT* = 0x8364.GLenum
-  GL_DU8DV8_ATI* = 0x877A.GLenum
-  GL_COLOR_ARRAY_LIST_IBM* = 103072.GLenum
-  GL_RGBA8I_EXT* = 0x8D8E.GLenum
-  GL_MULTISAMPLE_BUFFER_BIT4_QCOM* = 0x10000000.GLbitfield
-  GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_ARB* = 0x824D.GLenum
-  GL_MODELVIEW20_ARB* = 0x8734.GLenum
-  GL_COLOR_TABLE_RED_SIZE* = 0x80DA.GLenum
-  GL_UNIFORM_BARRIER_BIT* = 0x00000004.GLbitfield
-  GL_TEXTURE* = 0x1702.GLenum
-  GL_CLIP_PLANE0* = 0x3000.GLenum
-  GL_FOG_COORDINATE_ARRAY_POINTER* = 0x8456.GLenum
-  GL_CONSTANT_ALPHA_EXT* = 0x8003.GLenum
-  GL_NAME_STACK_DEPTH* = 0x0D70.GLenum
-  GL_COMPRESSED_RGBA_S3TC_DXT3_ANGLE* = 0x83F2.GLenum
-  GL_LINEAR_DETAIL_ALPHA_SGIS* = 0x8098.GLenum
-  GL_EDGE_FLAG_ARRAY_POINTER_EXT* = 0x8093.GLenum
-  GL_UNSIGNED_SHORT* = 0x1403.GLenum
-  GL_MAP2_VERTEX_ATTRIB1_4_NV* = 0x8671.GLenum
-  GL_DEPTH_CLAMP_FAR_AMD* = 0x901F.GLenum
-  GL_OPERAND3_RGB_NV* = 0x8593.GLenum
-  GL_TEXTURE_SWIZZLE_R_EXT* = 0x8E42.GLenum
-  GL_PATCHES* = 0x000E.GLenum
-  GL_TEXTURE12* = 0x84CC.GLenum
-  GL_COLOR_ATTACHMENT12_EXT* = 0x8CEC.GLenum
-  GL_MAP2_VERTEX_ATTRIB15_4_NV* = 0x867F.GLenum
-  GL_DRAW_BUFFER15_ATI* = 0x8834.GLenum
-  GL_GEOMETRY_INPUT_TYPE* = 0x8917.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ETC2_EAC_OES* = 0x9279.GLenum
-  GL_RGBA32UI_EXT* = 0x8D70.GLenum
-  GL_RGBA_FLOAT32_APPLE* = 0x8814.GLenum
-  GL_NORMAL_MAP_OES* = 0x8511.GLenum
-  GL_MAP2_GRID_DOMAIN* = 0x0DD2.GLenum
-  GL_RELATIVE_HORIZONTAL_LINE_TO_NV* = 0x07.GLenum
-  GL_TANGENT_ARRAY_STRIDE_EXT* = 0x843F.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_DRAW_BUFFER_EXT* = 0x8CDB.GLenum
-  GL_OBJECT_POINT_SGIS* = 0x81F5.GLenum
-  GL_IMAGE_2D_ARRAY* = 0x9053.GLenum
-  GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_ARB* = 0x8DDF.GLenum
-  GL_SPRITE_MODE_SGIX* = 0x8149.GLenum
-  GL_WEIGHT_ARRAY_OES* = 0x86AD.GLenum
-  GL_MAX_VERTEX_STREAMS* = 0x8E71.GLenum
-  GL_R16F_EXT* = 0x822D.GLenum
-  GL_VERSION_ES_CL_1_0* = 1.GLenum
-  GL_PROXY_TEXTURE_COLOR_TABLE_SGI* = 0x80BD.GLenum
-  GL_MAX_PROGRAM_INSTRUCTIONS_ARB* = 0x88A1.GLenum
-  GL_PURGEABLE_APPLE* = 0x8A1D.GLenum
-  GL_TEXTURE_SWIZZLE_G_EXT* = 0x8E43.GLenum
-  GL_FIRST_VERTEX_CONVENTION_EXT* = 0x8E4D.GLenum
-  GL_DEBUG_SEVERITY_LOW* = 0x9148.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT* = 0x00000001.GLbitfield
-  GL_OBJECT_ACTIVE_ATTRIBUTE_MAX_LENGTH_ARB* = 0x8B8A.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR* = 0x93D4.GLenum
-  GL_DOT_PRODUCT_CONST_EYE_REFLECT_CUBE_MAP_NV* = 0x86F3.GLenum
-  GL_RENDERBUFFER_DEPTH_SIZE* = 0x8D54.GLenum
-  GL_OPERAND1_RGB_ARB* = 0x8591.GLenum
-  GL_REFLECTION_MAP_NV* = 0x8512.GLenum
-  GL_MATRIX17_ARB* = 0x88D1.GLenum
-  GL_EYE_PLANE_ABSOLUTE_NV* = 0x855C.GLenum
-  GL_SRC1_ALPHA* = 0x8589.GLenum
-  GL_UNSIGNED_BYTE_2_3_3_REV* = 0x8362.GLenum
-  GL_RGB5_EXT* = 0x8050.GLenum
-  GL_TEXTURE_2D_ARRAY* = 0x8C1A.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB* = 0x8515.GLenum
-  GL_TEXTURE26* = 0x84DA.GLenum
-  GL_MAX_3D_TEXTURE_SIZE_OES* = 0x8073.GLenum
-  GL_PIXEL_TILE_WIDTH_SGIX* = 0x8140.GLenum
-  GL_PIXEL_UNPACK_BUFFER_BINDING_EXT* = 0x88EF.GLenum
-  GL_TEXTURE_ALPHA_SIZE* = 0x805F.GLenum
-  GL_RELATIVE_QUADRATIC_CURVE_TO_NV* = 0x0B.GLenum
-  GL_POINT_SIZE_ARRAY_BUFFER_BINDING_OES* = 0x8B9F.GLenum
-  GL_GEOMETRY_DEFORMATION_BIT_SGIX* = 0x00000002.GLbitfield
-  GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS* = 0x8DA8.GLenum
-  GL_NAMED_STRING_LENGTH_ARB* = 0x8DE9.GLenum
-  GL_IMAGE_1D_ARRAY* = 0x9052.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_OES* = 0x8CD4.GLenum
-  GL_MATRIX28_ARB* = 0x88DC.GLenum
-  GL_FRAGMENT_LIGHT1_SGIX* = 0x840D.GLenum
-  GL_HARDMIX_NV* = 0x92A9.GLenum
-  GL_DEBUG_SOURCE_THIRD_PARTY_KHR* = 0x8249.GLenum
-  GL_PACK_SWAP_BYTES* = 0x0D00.GLenum
-  GL_MAX_VERTEX_UNIFORM_COMPONENTS_ARB* = 0x8B4A.GLenum
-  GL_SOURCE2_ALPHA_EXT* = 0x858A.GLenum
-  GL_DOUBLE_MAT2x4* = 0x8F4A.GLenum
-  GL_MEDIUM_FLOAT* = 0x8DF1.GLenum
-  GL_PIXEL_TILE_BEST_ALIGNMENT_SGIX* = 0x813E.GLenum
-  GL_UNPACK_SKIP_ROWS* = 0x0CF3.GLenum
-  GL_PACK_COMPRESSED_BLOCK_SIZE* = 0x912E.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D* = 0x9063.GLenum
-  GL_COLOR_ARRAY_TYPE_EXT* = 0x8082.GLenum
-  GL_BUFFER_MAP_POINTER_ARB* = 0x88BD.GLenum
-  GL_CALLIGRAPHIC_FRAGMENT_SGIX* = 0x8183.GLenum
-  GL_ONE_MINUS_CONSTANT_COLOR_EXT* = 0x8002.GLenum
-  GL_COMPRESSED_RGBA_FXT1_3DFX* = 0x86B1.GLenum
-  GL_CLIP_PLANE1* = 0x3001.GLenum
-  GL_COVERAGE_BUFFERS_NV* = 0x8ED3.GLenum
-  GL_ADD_BLEND_IMG* = 0x8C09.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR* = 0x93D5.GLenum
-  GL_PIXEL_TILE_HEIGHT_SGIX* = 0x8141.GLenum
-  GL_SAMPLE_COVERAGE_INVERT_ARB* = 0x80AB.GLenum
-  GL_MAP1_VERTEX_ATTRIB9_4_NV* = 0x8669.GLenum
-  GL_COLOR_TABLE_BIAS_SGI* = 0x80D7.GLenum
-  GL_EDGE_FLAG_ARRAY_COUNT_EXT* = 0x808D.GLenum
-  GL_SAMPLE_BUFFERS_EXT* = 0x80A8.GLenum
-  GL_COLOR_INDEX* = 0x1900.GLenum
-  GL_REPLACEMENT_CODE_SUN* = 0x81D8.GLenum
-  GL_INT_SAMPLER_CUBE_EXT* = 0x8DCC.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_ANGLE* = 0x8D56.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_UNIFIED_NV* = 0x8F1E.GLenum
-  GL_DUAL_LUMINANCE_ALPHA8_SGIS* = 0x811D.GLenum
-  GL_PIXEL_TEX_GEN_ALPHA_LS_SGIX* = 0x8189.GLenum
-  GL_CLIP_DISTANCE7* = 0x3007.GLenum
-  GL_DOT3_RGB_ARB* = 0x86AE.GLenum
-  GL_TEXTURE_WRAP_T* = 0x2803.GLenum
-  GL_LUMINANCE12_EXT* = 0x8041.GLenum
-  GL_TEXTURE_CLIPMAP_VIRTUAL_DEPTH_SGIX* = 0x8174.GLenum
-  GL_TEXTURE_COMPRESSED_IMAGE_SIZE_ARB* = 0x86A0.GLenum
-  GL_EVAL_2D_NV* = 0x86C0.GLenum
-  GL_FRAMEBUFFER_DEFAULT_FIXED_SAMPLE_LOCATIONS* = 0x9314.GLenum
-  GL_CURRENT_WEIGHT_ARB* = 0x86A8.GLenum
-  GL_DEBUG_SOURCE_API_ARB* = 0x8246.GLenum
-  GL_FOG_SPECULAR_TEXTURE_WIN* = 0x80EC.GLenum
-  GL_BOOL_VEC4* = 0x8B59.GLenum
-  GL_FRAGMENTS_INSTRUMENT_SGIX* = 0x8313.GLenum
-  GL_GEOMETRY_OUTPUT_TYPE_EXT* = 0x8DDC.GLenum
-  GL_TEXTURE_2D* = 0x0DE1.GLenum
-  GL_MAT_AMBIENT_AND_DIFFUSE_BIT_PGI* = 0x00200000.GLbitfield
-  GL_TEXTURE_BINDING_RECTANGLE_ARB* = 0x84F6.GLenum
-  GL_SAMPLE_BUFFERS_3DFX* = 0x86B3.GLenum
-  GL_INDEX_OFFSET* = 0x0D13.GLenum
-  GL_MAX_COLOR_ATTACHMENTS* = 0x8CDF.GLenum
-  GL_PLUS_CLAMPED_NV* = 0x92B1.GLenum
-  GL_SIGNED_NEGATE_NV* = 0x853D.GLenum
-  GL_PROXY_TEXTURE_2D_STACK_MESAX* = 0x875C.GLenum
-  GL_MAX_VERTEX_UNIFORM_COMPONENTS* = 0x8B4A.GLenum
-  GL_SAMPLE_MASK_VALUE_SGIS* = 0x80AA.GLenum
-  GL_QUADRATIC_ATTENUATION* = 0x1209.GLenum
-  GL_LUMINANCE32F_ARB* = 0x8818.GLenum
-  GL_COVERAGE_COMPONENT4_NV* = 0x8ED1.GLenum
-  GL_MINMAX_FORMAT* = 0x802F.GLenum
-  GL_SRGB_DECODE_ARB* = 0x8299.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_FORMATS_EXT* = 0x8CDA.GLenum
-  GL_UNSIGNED_INT_SAMPLER_CUBE_EXT* = 0x8DD4.GLenum
-  GL_COMPRESSED_SRGB8_PUNCHTHROUGH_ALPHA1_ETC2* = 0x9277.GLenum
-  GL_DISJOINT_NV* = 0x9283.GLenum
-  GL_TEXTURE_ENV_BIAS_SGIX* = 0x80BE.GLenum
-  GL_PROXY_TEXTURE_3D_EXT* = 0x8070.GLenum
-  GL_SGX_BINARY_IMG* = 0x8C0A.GLenum
-  GL_COPY_READ_BUFFER* = 0x8F36.GLenum
-  GL_POINT_FADE_THRESHOLD_SIZE_SGIS* = 0x8128.GLenum
-  GL_UNIFORM_MATRIX_STRIDE* = 0x8A3D.GLenum
-  GL_UNIFORM_BLOCK_NAME_LENGTH* = 0x8A41.GLenum
-  GL_HISTOGRAM_LUMINANCE_SIZE* = 0x802C.GLenum
-  GL_UNSIGNED_SHORT_4_4_4_4* = 0x8033.GLenum
-  GL_MAX_DEPTH* = 0x8280.GLenum
-  GL_IMAGE_1D* = 0x904C.GLenum
-  GL_LUMINANCE8_ALPHA8_EXT* = 0x8045.GLenum
-  GL_MAX_TEXTURE_IMAGE_UNITS* = 0x8872.GLenum
-  GL_MODELVIEW16_ARB* = 0x8730.GLenum
-  GL_CURRENT_PALETTE_MATRIX_OES* = 0x8843.GLenum
-  GL_SIGNED_HILO_NV* = 0x86F9.GLenum
-  GL_FRAMEBUFFER_DEFAULT_HEIGHT* = 0x9311.GLenum
-  GL_UNPACK_SKIP_IMAGES* = 0x806D.GLenum
-  GL_2_BYTES* = 0x1407.GLenum
-  GL_ALLOW_DRAW_FRG_HINT_PGI* = 0x1A210.GLenum
-  GL_INTENSITY16I_EXT* = 0x8D8B.GLenum
-  GL_MAX_SAMPLES_NV* = 0x8D57.GLenum
-  GL_VERTEX_ARRAY_STORAGE_HINT_APPLE* = 0x851F.GLenum
-  GL_LINE_STRIP_ADJACENCY_ARB* = 0x000B.GLenum
-  GL_COORD_REPLACE* = 0x8862.GLenum
-  GL_INDEX_MATERIAL_FACE_EXT* = 0x81BA.GLenum
-  GL_MODELVIEW15_ARB* = 0x872F.GLenum
-  GL_TEXTURE19* = 0x84D3.GLenum
-  GL_UNSIGNED_INT_IMAGE_1D_ARRAY_EXT* = 0x9068.GLenum
-  GL_SIGNED_INTENSITY8_NV* = 0x8708.GLenum
-  GL_TEXTURE_MAG_SIZE_NV* = 0x871F.GLenum
-  GL_DISPATCH_INDIRECT_BUFFER* = 0x90EE.GLenum
-  GL_MAP1_INDEX* = 0x0D91.GLenum
-  GL_TEXTURE_BUFFER_DATA_STORE_BINDING* = 0x8C2D.GLenum
-  GL_MAX_HEIGHT* = 0x827F.GLenum
-  GL_BLEND_DST_ALPHA* = 0x80CA.GLenum
-  GL_R1UI_C3F_V3F_SUN* = 0x85C6.GLenum
-  GL_TEXTURE_PRIORITY_EXT* = 0x8066.GLenum
-  GL_INT_IMAGE_2D* = 0x9058.GLenum
-  GL_MAX_MULTISAMPLE_COVERAGE_MODES_NV* = 0x8E11.GLenum
-  GL_DRAW_BUFFER4_ATI* = 0x8829.GLenum
-  GL_MAX_GEOMETRY_VARYING_COMPONENTS_ARB* = 0x8DDD.GLenum
-  GL_DEPTH_EXT* = 0x1801.GLenum
-  GL_SAMPLE_POSITION* = 0x8E50.GLenum
-  GL_INTERNALFORMAT_DEPTH_TYPE* = 0x827C.GLenum
-  GL_MATRIX23_ARB* = 0x88D7.GLenum
-  GL_DEBUG_TYPE_PUSH_GROUP* = 0x8269.GLenum
-  GL_POLYGON_OFFSET_FILL* = 0x8037.GLenum
-  GL_FRAGMENT_PROGRAM_BINDING_NV* = 0x8873.GLenum
-  GL_FRAMEBUFFER_SRGB_CAPABLE_EXT* = 0x8DBA.GLenum
-  GL_VERTEX_ATTRIB_BINDING* = 0x82D4.GLenum
-  GL_UNSIGNED_INT8_VEC2_NV* = 0x8FED.GLenum
-  GL_POLYGON_OFFSET_FACTOR* = 0x8038.GLenum
-  GL_BOLD_BIT_NV* = 0x01.GLbitfield
-  GL_CLAMP_TO_BORDER_ARB* = 0x812D.GLint
-  GL_INDEX_MODE* = 0x0C30.GLenum
-  GL_SAMPLER_CUBE_SHADOW_NV* = 0x8DC5.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT* = 0x8C4F.GLenum
-  GL_MATRIX21_ARB* = 0x88D5.GLenum
-  GL_UNPACK_ROW_LENGTH_EXT* = 0x0CF2.GLenum
-  GL_FRAGMENT_NORMAL_EXT* = 0x834A.GLenum
-  GL_DOT3_ATI* = 0x8966.GLenum
-  GL_IMPLEMENTATION_COLOR_READ_TYPE_OES* = 0x8B9A.GLenum
-  GL_IMAGE_BINDING_ACCESS_EXT* = 0x8F3E.GLenum
-  GL_SYNC_CL_EVENT_ARB* = 0x8240.GLenum
-  GL_UNSIGNED_INT_24_8* = 0x84FA.GLenum
-  GL_2PASS_1_EXT* = 0x80A3.GLenum
-  GL_POST_TEXTURE_FILTER_BIAS_SGIX* = 0x8179.GLenum
-  GL_TEXTURE_COMPRESSED_IMAGE_SIZE* = 0x86A0.GLenum
-  GL_LUMINANCE_ALPHA32UI_EXT* = 0x8D75.GLenum
-  GL_FORCE_BLUE_TO_ONE_NV* = 0x8860.GLenum
-  GL_FRAMEBUFFER_DEFAULT* = 0x8218.GLenum
-  GL_VIRTUAL_PAGE_SIZE_Z_ARB* = 0x9197.GLenum
-  GL_TEXTURE_LIGHT_EXT* = 0x8350.GLenum
-  GL_MULTISAMPLE_BUFFER_BIT5_QCOM* = 0x20000000.GLbitfield
-  GL_UNSIGNED_INT_SAMPLER_2D_MULTISAMPLE_ARRAY* = 0x910D.GLenum
-  GL_SYNC_CONDITION* = 0x9113.GLenum
-  GL_PERFMON_RESULT_SIZE_AMD* = 0x8BC5.GLenum
-  GL_PROGRAM_OBJECT_ARB* = 0x8B40.GLenum
-  GL_MAX_SHININESS_NV* = 0x8504.GLenum
-  GL_PROGRAM_NATIVE_TEX_INDIRECTIONS_ARB* = 0x880A.GLenum
-  GL_RENDERBUFFER_COLOR_SAMPLES_NV* = 0x8E10.GLenum
-  GL_MAX_COMBINED_VERTEX_UNIFORM_COMPONENTS* = 0x8A31.GLenum
-  GL_ACTIVE_SUBROUTINE_UNIFORM_MAX_LENGTH* = 0x8E49.GLenum
-  GL_MODELVIEW29_ARB* = 0x873D.GLenum
-  GL_PROXY_TEXTURE_CUBE_MAP_ARRAY_ARB* = 0x900B.GLenum
-  GL_SIGNED_HILO16_NV* = 0x86FA.GLenum
-  GL_TRANSFORM_HINT_APPLE* = 0x85B1.GLenum
-  GL_STENCIL_INDEX4* = 0x8D47.GLenum
-  GL_EXTENSIONS* = 0x1F03.GLenum
-  GL_RG16F* = 0x822F.GLenum
-  GL_MAP_UNSYNCHRONIZED_BIT_EXT* = 0x0020.GLbitfield
-  GL_LUMINANCE16F_ARB* = 0x881E.GLenum
-  GL_UNSIGNED_INT_IMAGE_BUFFER* = 0x9067.GLenum
-  GL_COMPRESSED_RGBA_ASTC_8x8_KHR* = 0x93B7.GLenum
-  GL_AVERAGE_HP* = 0x8160.GLenum
-  GL_INDEX_MATERIAL_EXT* = 0x81B8.GLenum
-  GL_COLOR_TABLE* = 0x80D0.GLenum
-  GL_FOG_COORDINATE_ARRAY_LIST_IBM* = 103076.GLenum
-  GL_DEBUG_CATEGORY_OTHER_AMD* = 0x9150.GLenum
-  GL_R1UI_C4UB_V3F_SUN* = 0x85C5.GLenum
-  GL_SYSTEM_FONT_NAME_NV* = 0x9073.GLenum
-  GL_STATIC_VERTEX_ARRAY_IBM* = 103061.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_DIVISOR_NV* = 0x88FE.GLenum
-  GL_SCALE_BY_ONE_HALF_NV* = 0x8540.GLenum
-  GL_INTENSITY_FLOAT32_ATI* = 0x8817.GLenum
-  GL_FRAGMENT_LIGHT6_SGIX* = 0x8412.GLenum
-  GL_DECR_WRAP_OES* = 0x8508.GLenum
-  GL_MODELVIEW23_ARB* = 0x8737.GLenum
-  GL_PROXY_TEXTURE_1D_ARRAY* = 0x8C19.GLenum
-  GL_REFERENCED_BY_VERTEX_SHADER* = 0x9306.GLenum
-  GL_MAX_NAME_LENGTH* = 0x92F6.GLenum
-  GL_AFFINE_2D_NV* = 0x9092.GLenum
-  GL_SYNC_OBJECT_APPLE* = 0x8A53.GLenum
-  GL_PLUS_DARKER_NV* = 0x9292.GLenum
-  GL_TESS_CONTROL_PROGRAM_NV* = 0x891E.GLenum
-  GL_RGB_SCALE* = 0x8573.GLenum
-  GL_RGBA16UI_EXT* = 0x8D76.GLenum
-  GL_COMPATIBLE_SUBROUTINES* = 0x8E4B.GLenum
-  GL_COLOR_TABLE_WIDTH* = 0x80D9.GLenum
-  GL_MAX_COMBINED_UNIFORM_BLOCKS* = 0x8A2E.GLenum
-  GL_BACK_SECONDARY_COLOR_NV* = 0x8C78.GLenum
-  GL_MAX_COMPUTE_VARIABLE_GROUP_INVOCATIONS_ARB* = 0x9344.GLenum
-  GL_SECONDARY_COLOR_NV* = 0x852D.GLenum
-  GL_RGB16UI_EXT* = 0x8D77.GLenum
-  GL_SHADER_STORAGE_BUFFER_SIZE* = 0x90D5.GLenum
-  GL_VERTEX_SUBROUTINE* = 0x92E8.GLenum
-  GL_MAP_COLOR* = 0x0D10.GLenum
-  GL_OBJECT_TYPE_ARB* = 0x8B4E.GLenum
-  GL_LAST_VIDEO_CAPTURE_STATUS_NV* = 0x9027.GLenum
-  GL_RGB12_EXT* = 0x8053.GLenum
-  GL_UNSIGNED_INT_IMAGE_3D_EXT* = 0x9064.GLenum
-  GL_LUMINANCE8_ALPHA8* = 0x8045.GLenum
-  GL_FLOAT_RGBA_MODE_NV* = 0x888E.GLenum
-  GL_CURRENT_RASTER_COLOR* = 0x0B04.GLenum
-  GL_CURRENT_RASTER_POSITION* = 0x0B07.GLenum
-  GL_UNIFORM_BLOCK_DATA_SIZE* = 0x8A40.GLenum
-  GL_MALI_PROGRAM_BINARY_ARM* = 0x8F61.GLenum
-  GL_QUERY_COUNTER_BITS_ARB* = 0x8864.GLenum
-  GL_VARIANT_ARRAY_EXT* = 0x87E8.GLenum
-  GL_VIDEO_CAPTURE_FIELD_UPPER_HEIGHT_NV* = 0x903A.GLenum
-  GL_DEPTH_COMPONENT24_ARB* = 0x81A6.GLenum
-  GL_UNSIGNED_INVERT_NV* = 0x8537.GLenum
-  GL_TEXTURE_IMMUTABLE_LEVELS* = 0x82DF.GLenum
-  GL_DRAW_BUFFER12_ATI* = 0x8831.GLenum
-  GL_MAP_FLUSH_EXPLICIT_BIT_EXT* = 0x0010.GLbitfield
-  GL_INDEX_WRITEMASK* = 0x0C21.GLenum
-  GL_POLYGON_SMOOTH* = 0x0B41.GLenum
-  GL_COMPRESSED_SIGNED_R11_EAC_OES* = 0x9271.GLenum
-  GL_TEXTURE_SWIZZLE_A_EXT* = 0x8E45.GLenum
-  GL_TEXTURE_COORD_ARRAY_STRIDE* = 0x808A.GLenum
-  GL_PIXEL_MAP_I_TO_R* = 0x0C72.GLenum
-  GL_CONVOLUTION_HEIGHT* = 0x8019.GLenum
-  GL_SIGNALED* = 0x9119.GLenum
-  GL_UNSIGNED_INT_24_8_OES* = 0x84FA.GLenum
-  GL_DRAW_BUFFER6_ARB* = 0x882B.GLenum
-  GL_BUFFER_SIZE_ARB* = 0x8764.GLenum
-  GL_CLEAR_BUFFER* = 0x82B4.GLenum
-  GL_LUMINANCE16UI_EXT* = 0x8D7A.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_ANGLE* = 0x93A3.GLenum
-  GL_STENCIL_ATTACHMENT* = 0x8D20.GLenum
-  GL_ALL_COMPLETED_NV* = 0x84F2.GLenum
-  GL_MIN* = 0x8007.GLenum
-  GL_COLOR_ATTACHMENT11* = 0x8CEB.GLenum
-  GL_PATH_STENCIL_FUNC_NV* = 0x90B7.GLenum
-  GL_MAX_LABEL_LENGTH* = 0x82E8.GLenum
-  GL_WEIGHT_ARRAY_TYPE_OES* = 0x86A9.GLenum
-  GL_ACCUM_BUFFER_BIT* = 0x00000200.GLbitfield
-  GL_WEIGHT_ARRAY_POINTER_ARB* = 0x86AC.GLenum
-  GL_WEIGHT_SUM_UNITY_ARB* = 0x86A6.GLenum
-  GL_COMPRESSED_SRGB_EXT* = 0x8C48.GLenum
-  GL_ATTRIB_ARRAY_TYPE_NV* = 0x8625.GLenum
-  GL_RED_INTEGER_EXT* = 0x8D94.GLenum
-  GL_ALWAYS_SOFT_HINT_PGI* = 0x1A20D.GLenum
-  GL_COMPRESSED_SRGB8_ETC2_OES* = 0x9275.GLenum
-  GL_LOW_FLOAT* = 0x8DF0.GLenum
-  GL_PIXEL_FRAGMENT_RGB_SOURCE_SGIS* = 0x8354.GLenum
-  GL_TEXTURE_LEQUAL_R_SGIX* = 0x819C.GLenum
-  GL_CONTEXT_COMPATIBILITY_PROFILE_BIT* = 0x00000002.GLbitfield
-  GL_INCR* = 0x1E02.GLenum
-  GL_3D* = 0x0601.GLenum
-  GL_SHADER_KHR* = 0x82E1.GLenum
-  GL_SRC_COLOR* = 0x0300.GLenum
-  GL_DRAW_BUFFER7_NV* = 0x882C.GLenum
-  GL_VERTEX_ARRAY_SIZE* = 0x807A.GLenum
-  GL_SAMPLER_2D_RECT* = 0x8B63.GLenum
-  GL_UNSIGNED_SHORT_4_4_4_4_REV_IMG* = 0x8365.GLenum
-  GL_READ_PIXEL_DATA_RANGE_NV* = 0x8879.GLenum
-  GL_EDGE_FLAG* = 0x0B43.GLenum
-  GL_TEXTURE_3D_EXT* = 0x806F.GLenum
-  GL_DOT_PRODUCT_TEXTURE_1D_NV* = 0x885C.GLenum
-  GL_COLOR_SUM_CLAMP_NV* = 0x854F.GLenum
-  GL_RGB10_A2* = 0x8059.GLenum
-  GL_BOOL_VEC3* = 0x8B58.GLenum
-  GL_REG_3_ATI* = 0x8924.GLenum
-  GL_LINEAR_SHARPEN_ALPHA_SGIS* = 0x80AE.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_LAYER_TARGETS_EXT* = 0x8DA8.GLenum
-  GL_MAP1_VERTEX_ATTRIB5_4_NV* = 0x8665.GLenum
-  GL_MAX_COMBINED_IMAGE_UNITS_AND_FRAGMENT_OUTPUTS* = 0x8F39.GLenum
-  GL_PIXEL_MAP_I_TO_B_SIZE* = 0x0CB4.GLenum
-  GL_TRANSFORM_FEEDBACK_BARRIER_BIT_EXT* = 0x00000800.GLbitfield
-  GL_COLOR_BUFFER_BIT6_QCOM* = 0x00000040.GLbitfield
-  GL_PROGRAM_TEMPORARIES_ARB* = 0x88A4.GLenum
-  GL_ELEMENT_ARRAY_BUFFER* = 0x8893.GLenum
-  GL_ALWAYS_FAST_HINT_PGI* = 0x1A20C.GLenum
-  GL_INTENSITY_FLOAT16_ATI* = 0x881D.GLenum
-  GL_ACTIVE_ATTRIBUTE_MAX_LENGTH* = 0x8B8A.GLenum
-  GL_CON_12_ATI* = 0x894D.GLenum
-  GL_LINEAR_MIPMAP_NEAREST* = 0x2701.GLint
-  GL_TEXTURE_COVERAGE_SAMPLES_NV* = 0x9045.GLenum
-  GL_MAX_PROGRAM_NATIVE_PARAMETERS_ARB* = 0x88AB.GLenum
-  GL_DEPTH_SCALE* = 0x0D1E.GLenum
-  GL_SOURCE3_ALPHA_NV* = 0x858B.GLenum
-  GL_ACTIVE_VERTEX_UNITS_ARB* = 0x86A5.GLenum
-  GL_SWIZZLE_STR_DR_ATI* = 0x8978.GLenum
-  GL_RGB16I_EXT* = 0x8D89.GLenum
-  GL_INT_IMAGE_2D_RECT_EXT* = 0x905A.GLenum
-  GL_GREEN_BIAS* = 0x0D19.GLenum
-  GL_FRAMEBUFFER_RENDERABLE_LAYERED* = 0x828A.GLenum
-  GL_COMPRESSED_RGB8_ETC2* = 0x9274.GLenum
-  GL_COMPRESSED_RGBA_ARB* = 0x84EE.GLenum
-  GL_MAX_VERTEX_ATOMIC_COUNTERS* = 0x92D2.GLenum
-  GL_RGBA32I_EXT* = 0x8D82.GLenum
-  GL_WAIT_FAILED* = 0x911D.GLenum
-  GL_FOG_COORDINATE_SOURCE_EXT* = 0x8450.GLenum
-  GL_SAMPLE_MASK_VALUE_NV* = 0x8E52.GLenum
-  GL_OP_MUL_EXT* = 0x8786.GLenum
-  GL_FRAGMENT_TEXTURE* = 0x829F.GLenum
-  GL_GEOMETRY_PROGRAM_NV* = 0x8C26.GLenum
-  GL_MATRIX20_ARB* = 0x88D4.GLenum
-  GL_SECONDARY_COLOR_ARRAY_STRIDE_EXT* = 0x845C.GLenum
-  GL_UNSIGNED_INT_2_10_10_10_REV_EXT* = 0x8368.GLenum
-  GL_PHONG_HINT_WIN* = 0x80EB.GLenum
-  GL_EYE_DISTANCE_TO_LINE_SGIS* = 0x81F2.GLenum
-  GL_SAMPLES_PASSED* = 0x8914.GLenum
-  GL_MAX_COLOR_ATTACHMENTS_NV* = 0x8CDF.GLenum
-  GL_WEIGHT_ARRAY_POINTER_OES* = 0x86AC.GLenum
-  GL_MAX_DEBUG_GROUP_STACK_DEPTH* = 0x826C.GLenum
-  GL_TEXTURE_2D_STACK_BINDING_MESAX* = 0x875E.GLenum
-  GL_VARIANT_VALUE_EXT* = 0x87E4.GLenum
-  GL_TEXTURE_GEN_R* = 0x0C62.GLenum
-  GL_COMPRESSED_RG11_EAC* = 0x9272.GLenum
-  GL_IMAGE_ROTATE_ORIGIN_Y_HP* = 0x815B.GLenum
-  GL_BLEND_ADVANCED_COHERENT_NV* = 0x9285.GLenum
-  GL_DEBUG_CALLBACK_FUNCTION* = 0x8244.GLenum
-  GL_PROXY_TEXTURE_4D_SGIS* = 0x8135.GLenum
-  GL_OCCLUSION_TEST_RESULT_HP* = 0x8166.GLenum
-  GL_COLOR_ATTACHMENT13_EXT* = 0x8CED.GLenum
-  GL_LINE_STRIP_ADJACENCY* = 0x000B.GLenum
-  GL_DEBUG_CATEGORY_APPLICATION_AMD* = 0x914F.GLenum
-  GL_CIRCULAR_TANGENT_ARC_TO_NV* = 0xFC.GLenum
-  GL_MAX_PROGRAM_NATIVE_ADDRESS_REGISTERS_ARB* = 0x88B3.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_STRIDE* = 0x8624.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_EXT* = 0x8C49.GLenum
-  GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY* = 0x900F.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_ARRAY* = 0x906C.GLenum
-  GL_LIGHT_MODEL_COLOR_CONTROL* = 0x81F8.GLenum
-  GL_INT_VEC2_ARB* = 0x8B53.GLenum
-  GL_PARALLEL_ARRAYS_INTEL* = 0x83F4.GLenum
-  GL_COLOR_ATTACHMENT11_EXT* = 0x8CEB.GLenum
-  GL_SAMPLE_ALPHA_TO_ONE_SGIS* = 0x809F.GLenum
-  GL_FUNC_ADD_OES* = 0x8006.GLenum
-  GL_COMBINER_MAPPING_NV* = 0x8543.GLenum
-  GL_INT_IMAGE_BUFFER* = 0x905C.GLenum
-  GL_TEXTURE_SWIZZLE_A* = 0x8E45.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_LAYERED_ARB* = 0x8DA7.GLenum
-  GL_EXPAND_NEGATE_NV* = 0x8539.GLenum
-  GL_COVERAGE_EDGE_FRAGMENTS_NV* = 0x8ED6.GLenum
-  GL_PATH_OBJECT_BOUNDING_BOX_NV* = 0x908A.GLenum
-  GL_MAX_RECTANGLE_TEXTURE_SIZE* = 0x84F8.GLenum
-  GL_FONT_ASCENDER_BIT_NV* = 0x00200000.GLbitfield
-  GL_INDEX_SHIFT* = 0x0D12.GLenum
-  GL_LUMINANCE6_ALPHA2* = 0x8044.GLenum
-  GL_FLOAT_CLEAR_COLOR_VALUE_NV* = 0x888D.GLenum
-  GL_V2F* = 0x2A20.GLenum
-  GL_DRAW_BUFFER12_NV* = 0x8831.GLenum
-  GL_RIGHT* = 0x0407.GLenum
-  GL_CON_28_ATI* = 0x895D.GLenum
-  GL_SAMPLER_CUBE_ARB* = 0x8B60.GLenum
-  GL_OUTPUT_TEXTURE_COORD27_EXT* = 0x87B8.GLenum
-  GL_MAX_DEPTH_TEXTURE_SAMPLES* = 0x910F.GLenum
-  GL_MODULATE* = 0x2100.GLenum
-  GL_NUM_FILL_STREAMS_NV* = 0x8E29.GLenum
-  GL_DT_SCALE_NV* = 0x8711.GLenum
-  GL_ONE_MINUS_SRC_COLOR* = 0x0301.GLenum
-  GL_OPERAND2_ALPHA* = 0x859A.GLenum
-  GL_MATRIX15_ARB* = 0x88CF.GLenum
-  GL_MULTISAMPLE* = 0x809D.GLenum
-  GL_DEPTH32F_STENCIL8* = 0x8CAD.GLenum
-  GL_COMPRESSED_RGBA_ASTC_4x4_KHR* = 0x93B0.GLenum
-  GL_DUAL_ALPHA16_SGIS* = 0x8113.GLenum
-  GL_COMPRESSED_RGB_FXT1_3DFX* = 0x86B0.GLenum
-  GL_PROXY_TEXTURE_2D_ARRAY* = 0x8C1B.GLenum
-  GL_UNIFORM_NAME_LENGTH* = 0x8A39.GLenum
-  GL_COMPILE_AND_EXECUTE* = 0x1301.GLenum
-  GL_COMPRESSED_RGBA_PVRTC_4BPPV2_IMG* = 0x9138.GLenum
-  GL_PIXEL_CUBIC_WEIGHT_EXT* = 0x8333.GLenum
-  GL_GREEN_MIN_CLAMP_INGR* = 0x8561.GLenum
-  GL_MAX_TEXTURE_LOD_BIAS* = 0x84FD.GLenum
-  GL_NORMAL_MAP_NV* = 0x8511.GLenum
-  GL_PIXEL_UNPACK_BUFFER_BINDING_ARB* = 0x88EF.GLenum
-  GL_LUMINANCE_ALPHA32F_ARB* = 0x8819.GLenum
-  GL_LUMINANCE_FLOAT16_APPLE* = 0x881E.GLenum
-  GL_FACTOR_MIN_AMD* = 0x901C.GLenum
-  GL_BUFFER_GPU_ADDRESS_NV* = 0x8F1D.GLenum
-  GL_DEBUG_TYPE_PERFORMANCE_ARB* = 0x8250.GLenum
-  GL_TEXTURE_RESIDENT* = 0x8067.GLenum
-  GL_TESS_CONTROL_SHADER_BIT* = 0x00000008.GLbitfield
-  GL_VERTEX_SHADER* = 0x8B31.GLenum
-  GL_COLOR_ATTACHMENT15_EXT* = 0x8CEF.GLenum
-  GL_DRAW_BUFFER2_NV* = 0x8827.GLenum
-  GL_UNSIGNED_INT* = 0x1405.GLenum
-  GL_TEXTURE_SHARED_SIZE_EXT* = 0x8C3F.GLenum
-  GL_LIGHT5* = 0x4005.GLenum
-  GL_VERTEX_ARRAY_SIZE_EXT* = 0x807A.GLenum
-  GL_YCRCB_SGIX* = 0x8318.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_EVALUATION_SHADER* = 0x92C9.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME_OES* = 0x8CD1.GLenum
-  GL_QUADRATIC_CURVE_TO_NV* = 0x0A.GLenum
-  GL_POINTS* = 0x0000.GLenum
-  GL_OPERAND1_RGB* = 0x8591.GLenum
-  GL_POINT_DISTANCE_ATTENUATION_ARB* = 0x8129.GLenum
-  GL_QUERY_BUFFER_BARRIER_BIT* = 0x00008000.GLbitfield
-  GL_QUAD_LUMINANCE4_SGIS* = 0x8120.GLenum
-  GL_GENERATE_MIPMAP_SGIS* = 0x8191.GLenum
-  GL_FRAMEBUFFER_UNSUPPORTED_EXT* = 0x8CDD.GLenum
-  GL_PALETTE4_RGB5_A1_OES* = 0x8B94.GLenum
-  GL_TEXTURE_CROP_RECT_OES* = 0x8B9D.GLenum
-  GL_COMPUTE_SHADER_BIT* = 0x00000020.GLbitfield
-  GL_OUTPUT_TEXTURE_COORD2_EXT* = 0x879F.GLenum
-  GL_PALETTE4_RGBA4_OES* = 0x8B93.GLenum
-  GL_TEXTURE_CLIPMAP_CENTER_SGIX* = 0x8171.GLenum
-  GL_BLUE_BITS* = 0x0D54.GLenum
-  GL_RELATIVE_LARGE_CCW_ARC_TO_NV* = 0x17.GLenum
-  GL_UNSIGNED_SHORT_5_6_5_EXT* = 0x8363.GLenum
-  GL_MAX_GEOMETRY_TOTAL_OUTPUT_COMPONENTS* = 0x8DE1.GLenum
-  GL_UNCORRELATED_NV* = 0x9282.GLenum
-  GL_TESS_EVALUATION_SUBROUTINE* = 0x92EA.GLenum
-  GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_ARB* = 0x8E5E.GLenum
-  GL_CON_11_ATI* = 0x894C.GLenum
-  GL_ACTIVE_TEXTURE* = 0x84E0.GLenum
-  GL_ASYNC_TEX_IMAGE_SGIX* = 0x835C.GLenum
-  GL_COLOR_CLEAR_VALUE* = 0x0C22.GLenum
-  GL_INT_SAMPLER_2D_MULTISAMPLE_ARRAY* = 0x910C.GLenum
-  GL_TESS_CONTROL_TEXTURE* = 0x829C.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_OES* = 0x851A.GLenum
-  GL_HISTOGRAM_BLUE_SIZE_EXT* = 0x802A.GLenum
-  GL_PATCH_DEFAULT_OUTER_LEVEL* = 0x8E74.GLenum
-  GL_PROGRAM_MATRIX_STACK_DEPTH_EXT* = 0x8E2F.GLenum
-  GL_RENDERBUFFER_BINDING_ANGLE* = 0x8CA7.GLenum
-  GL_CONSTANT_ATTENUATION* = 0x1207.GLenum
-  GL_SHADER_CONSISTENT_NV* = 0x86DD.GLenum
-  GL_MAX_TESS_EVALUATION_ATOMIC_COUNTERS* = 0x92D4.GLenum
-  GL_EXTERNAL_VIRTUAL_MEMORY_BUFFER_AMD* = 0x9160.GLenum
-  GL_DETAIL_TEXTURE_FUNC_POINTS_SGIS* = 0x809C.GLenum
-  GL_INT_IMAGE_2D_MULTISAMPLE_ARRAY_EXT* = 0x9061.GLenum
-  GL_COUNT_DOWN_NV* = 0x9089.GLenum
-  GL_MATRIX12_ARB* = 0x88CC.GLenum
-  GL_MAX_VERTEX_SHADER_INVARIANTS_EXT* = 0x87C7.GLenum
-  GL_REPLICATE_BORDER_HP* = 0x8153.GLenum
-  GL_MODELVIEW9_ARB* = 0x8729.GLenum
-  GL_ANY_SAMPLES_PASSED_CONSERVATIVE_EXT* = 0x8D6A.GLenum
-  GL_PROGRAM_PARAMETERS_ARB* = 0x88A8.GLenum
-  GL_LIST_BIT* = 0x00020000.GLbitfield
-  GL_MAX_GEOMETRY_ATOMIC_COUNTERS* = 0x92D5.GLenum
-  GL_CONSTANT_COLOR1_NV* = 0x852B.GLenum
-  GL_AVERAGE_EXT* = 0x8335.GLenum
-  GL_SINGLE_COLOR_EXT* = 0x81F9.GLenum
-  GL_VERTEX_ARRAY* = 0x8074.GLenum
-  GL_COLOR_INDEX1_EXT* = 0x80E2.GLenum
-  GL_COMPUTE_PROGRAM_NV* = 0x90FB.GLenum
-  GL_LINES_ADJACENCY* = 0x000A.GLenum
-  GL_OP_ROUND_EXT* = 0x8790.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_STRIDE* = 0x934C.GLenum
-  GL_MAX_DEEP_3D_TEXTURE_DEPTH_NV* = 0x90D1.GLenum
-  GL_REG_11_ATI* = 0x892C.GLenum
-  GL_SAMPLES_EXT* = 0x80A9.GLenum
-  GL_FUNC_REVERSE_SUBTRACT* = 0x800B.GLenum
-  GL_POINT_SPRITE_COORD_ORIGIN* = 0x8CA0.GLenum
-  GL_REG_27_ATI* = 0x893C.GLenum
-  GL_TEXTURE_VIEW_MIN_LEVEL* = 0x82DB.GLenum
-  GL_NICEST* = 0x1102.GLenum
-  GL_CLIP_PLANE4_IMG* = 0x3004.GLenum
-  GL_ARRAY_BUFFER_BINDING* = 0x8894.GLenum
-  GL_422_AVERAGE_EXT* = 0x80CE.GLenum
-  GL_RENDERER* = 0x1F01.GLenum
-  GL_OVERLAY_NV* = 0x9296.GLenum
-  GL_TEXTURE_SAMPLES_IMG* = 0x9136.GLenum
-  GL_DEBUG_SOURCE_SHADER_COMPILER_KHR* = 0x8248.GLenum
-  GL_EYE_DISTANCE_TO_POINT_SGIS* = 0x81F0.GLenum
-  GL_MAX_PROGRAM_GENERIC_ATTRIBS_NV* = 0x8DA5.GLenum
-  GL_FILTER4_SGIS* = 0x8146.GLenum
-  GL_LIGHT_MODEL_LOCAL_VIEWER* = 0x0B51.GLenum
-  GL_TRIANGLE_MESH_SUN* = 0x8615.GLenum
-  GL_SAMPLER_CUBE_MAP_ARRAY_SHADOW_ARB* = 0x900D.GLenum
-  GL_DEPTH_COMPONENTS* = 0x8284.GLenum
-  GL_NUM_GENERAL_COMBINERS_NV* = 0x854E.GLenum
-  GL_CLIENT_ACTIVE_TEXTURE_ARB* = 0x84E1.GLenum
-  GL_FRAGMENT_DEPTH* = 0x8452.GLenum
-  GL_SEPARATE_ATTRIBS* = 0x8C8D.GLenum
-  GL_HALF_FLOAT_OES* = 0x8D61.GLenum
-  GL_PROXY_TEXTURE_2D* = 0x8064.GLenum
-  GL_VARIANT_ARRAY_TYPE_EXT* = 0x87E7.GLenum
-  GL_DRAW_BUFFER11_ATI* = 0x8830.GLenum
-  GL_MATRIX_INDEX_ARRAY_POINTER_OES* = 0x8849.GLenum
-  GL_CURRENT_INDEX* = 0x0B01.GLenum
-  GL_UNSIGNED_INT_24_8_MESA* = 0x8751.GLenum
-  GL_PROGRAM_SEPARABLE* = 0x8258.GLenum
-  GL_TEXTURE8_ARB* = 0x84C8.GLenum
-  GL_OPERAND0_ALPHA_EXT* = 0x8598.GLenum
-  GL_PER_STAGE_CONSTANTS_NV* = 0x8535.GLenum
-  GL_LINE_LOOP* = 0x0002.GLenum
-  GL_DRAW_PIXEL_TOKEN* = 0x0705.GLenum
-  GL_DRAW_BUFFER3* = 0x8828.GLenum
-  GL_GEOMETRY_DEFORMATION_SGIX* = 0x8194.GLenum
-  GL_MAX_CUBE_MAP_TEXTURE_SIZE_EXT* = 0x851C.GLenum
-  GL_GLYPH_VERTICAL_BEARING_X_BIT_NV* = 0x20.GLbitfield
-  GL_TEXTURE30* = 0x84DE.GLenum
-  GL_4PASS_1_EXT* = 0x80A5.GLenum
-  GL_RGB16F_EXT* = 0x881B.GLenum
-  GL_2PASS_0_SGIS* = 0x80A2.GLenum
-  GL_CON_27_ATI* = 0x895C.GLenum
-  GL_SAMPLE_ALPHA_TO_ONE* = 0x809F.GLenum
-  GL_POLYGON_SMOOTH_HINT* = 0x0C53.GLenum
-  GL_COLOR_ATTACHMENT_EXT* = 0x90F0.GLenum
-  GL_PATCH_DEFAULT_INNER_LEVEL* = 0x8E73.GLenum
-  GL_TEXTURE_MAX_CLAMP_T_SGIX* = 0x836A.GLenum
-  GL_WEIGHT_ARRAY_BUFFER_BINDING_OES* = 0x889E.GLenum
-  GL_TEXTURE1* = 0x84C1.GLenum
-  GL_LINES* = 0x0001.GLenum
-  GL_PIXEL_TILE_GRID_DEPTH_SGIX* = 0x8144.GLenum
-  GL_TEXTURE2* = 0x84C2.GLenum
-  GL_IMAGE_CUBE_MAP_ARRAY_EXT* = 0x9054.GLenum
-  GL_DRAW_BUFFER4* = 0x8829.GLenum
-  GL_DRAW_BUFFER_EXT* = 0x0C01.GLenum
-  GL_STENCIL_INDEX1* = 0x8D46.GLenum
-  GL_DEPTH_COMPONENT32F_NV* = 0x8DAB.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_POINTER* = 0x8645.GLenum
-  GL_DOUBLE_MAT4x2* = 0x8F4D.GLenum
-  GL_MOVE_TO_NV* = 0x02.GLenum
-  GL_OP_RECIP_SQRT_EXT* = 0x8795.GLenum
-  GL_SAMPLER_1D_ARRAY* = 0x8DC0.GLenum
-  GL_MIN_FRAGMENT_INTERPOLATION_OFFSET* = 0x8E5B.GLenum
-  GL_TEXTURE_DEPTH_EXT* = 0x8071.GLenum
-  GL_STENCIL_INDEX8* = 0x8D48.GLenum
-  GL_MAX_PROGRAM_TEX_INSTRUCTIONS_ARB* = 0x880C.GLenum
-  GL_INTERNALFORMAT_DEPTH_SIZE* = 0x8275.GLenum
-  GL_STATE_RESTORE* = 0x8BDC.GLenum
-  GL_SMALL_CW_ARC_TO_NV* = 0x14.GLenum
-  GL_LUMINANCE16* = 0x8042.GLenum
-  GL_VERTEX_ATTRIB_ARRAY1_NV* = 0x8651.GLenum
-  GL_TEXTURE_MAX_CLAMP_R_SGIX* = 0x836B.GLenum
-  GL_LUMINANCE_FLOAT16_ATI* = 0x881E.GLenum
-  GL_MAX_TEXTURE_UNITS* = 0x84E2.GLenum
-  GL_DRAW_BUFFER4_ARB* = 0x8829.GLenum
-  GL_DRAW_BUFFER12* = 0x8831.GLenum
-  GL_R8UI* = 0x8232.GLenum
-  GL_STENCIL_REF* = 0x0B97.GLenum
-  GL_VARIANT_EXT* = 0x87C1.GLenum
-  GL_VERTEX_ATTRIB_MAP2_DOMAIN_APPLE* = 0x8A09.GLenum
-  GL_QUERY_OBJECT_AMD* = 0x9153.GLenum
-  GL_PLUS_NV* = 0x9291.GLenum
-  GL_UNPACK_SWAP_BYTES* = 0x0CF0.GLenum
-  GL_MAX_UNIFORM_LOCATIONS* = 0x826E.GLenum
-  GL_GUILTY_CONTEXT_RESET_EXT* = 0x8253.GLenum
-  GL_DOT3_RGBA_IMG* = 0x86AF.GLenum
-  GL_X_EXT* = 0x87D5.GLenum
-  GL_UNSIGNED_INT_SAMPLER_CUBE_MAP_ARRAY_ARB* = 0x900F.GLenum
-  GL_TEXTURE_COMPARE_FAIL_VALUE_ARB* = 0x80BF.GLenum
-  GL_ETC1_RGB8_OES* = 0x8D64.GLenum
-  GL_LUMINANCE_ALPHA_INTEGER_EXT* = 0x8D9D.GLenum
-  GL_MINMAX_SINK* = 0x8030.GLenum
-  GL_RG32F* = 0x8230.GLenum
-  GL_PROXY_TEXTURE_2D_MULTISAMPLE* = 0x9101.GLenum
-  GL_RGBA_UNSIGNED_DOT_PRODUCT_MAPPING_NV* = 0x86D9.GLenum
-  GL_R16* = 0x822A.GLenum
-  GL_BOUNDING_BOX_NV* = 0x908D.GLenum
-  GL_INVALID_ENUM* = 0x0500.GLenum
-  GL_MOVE_TO_RESETS_NV* = 0x90B5.GLenum
-  GL_SYNC_GPU_COMMANDS_COMPLETE_APPLE* = 0x9117.GLenum
-  GL_MAX_RECTANGLE_TEXTURE_SIZE_ARB* = 0x84F8.GLenum
-  GL_UNSIGNED_INT_10F_11F_11F_REV_EXT* = 0x8C3B.GLenum
-  GL_VERTEX_PRECLIP_HINT_SGIX* = 0x83EF.GLenum
-  GL_CLIENT_VERTEX_ARRAY_BIT* = 0x00000002.GLbitfield
-  GL_MAT_COLOR_INDEXES_BIT_PGI* = 0x01000000.GLbitfield
-  GL_PERFORMANCE_MONITOR_AMD* = 0x9152.GLenum
-  GL_QUAD_STRIP* = 0x0008.GLenum
-  GL_MAX_TEXTURE_COORDS_NV* = 0x8871.GLenum
-  GL_TESS_EVALUATION_SUBROUTINE_UNIFORM* = 0x92F0.GLenum
-  GL_DRAW_BUFFER1_EXT* = 0x8826.GLenum
-  GL_TEXTURE18* = 0x84D2.GLenum
-  GL_COLOR_ATTACHMENT5_NV* = 0x8CE5.GLenum
-  GL_MAX_COMPUTE_WORK_GROUP_SIZE* = 0x91BF.GLenum
-  GL_T2F_C4UB_V3F* = 0x2A29.GLenum
-  GL_MAP1_GRID_DOMAIN* = 0x0DD0.GLenum
-  GL_DEBUG_TYPE_PUSH_GROUP_KHR* = 0x8269.GLenum
-  GL_STATIC_READ* = 0x88E5.GLenum
-  GL_MAX_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB* = 0x880E.GLenum
-  GL_DOUBLE_EXT* = 0x140A.GLenum
-  GL_MAX_FRAGMENT_UNIFORM_VECTORS* = 0x8DFD.GLenum
-  GL_R32F_EXT* = 0x822E.GLenum
-  GL_MAX_RENDERBUFFER_SIZE_EXT* = 0x84E8.GLenum
-  GL_COMPRESSED_TEXTURE_FORMATS* = 0x86A3.GLenum
-  GL_MAX_EXT* = 0x8008.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_ENABLED_ARB* = 0x8622.GLenum
-  GL_INTERPOLATE* = 0x8575.GLenum
-  GL_QUERY_RESULT_NO_WAIT_AMD* = 0x9194.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_X_OES* = 0x8516.GLenum
-  GL_LUMINANCE16_ALPHA16_SNORM* = 0x901A.GLenum
-  GL_SRC_ALPHA_SATURATE* = 0x0308.GLenum
-  GL_DRAW_INDIRECT_BUFFER_BINDING* = 0x8F43.GLenum
-  GL_T2F_IUI_N3F_V3F_EXT* = 0x81B4.GLenum
-  GL_MAX_FRAGMENT_UNIFORM_COMPONENTS_ARB* = 0x8B49.GLenum
-  GL_MAX_ASYNC_READ_PIXELS_SGIX* = 0x8361.GLenum
-  GL_VERTEX_ARRAY_RANGE_APPLE* = 0x851D.GLenum
-  GL_SAMPLER_2D_SHADOW_ARB* = 0x8B62.GLenum
-  GL_ETC1_SRGB8_NV* = 0x88EE.GLenum
-  GL_COLORBURN_NV* = 0x929A.GLenum
-  GL_SAMPLER_2D_ARRAY_SHADOW_EXT* = 0x8DC4.GLenum
-  GL_ALL_BARRIER_BITS* = 0xFFFFFFFF.GLbitfield
-  GL_TRIANGLE_STRIP_ADJACENCY_EXT* = 0x000D.GLenum
-  GL_MAX_TEXTURE_BUFFER_SIZE* = 0x8C2B.GLenum
-  GL_ALIASED_POINT_SIZE_RANGE* = 0x846D.GLenum
-  GL_STENCIL_BACK_VALUE_MASK* = 0x8CA4.GLenum
-  GL_CMYK_EXT* = 0x800C.GLenum
-  GL_OPERAND1_ALPHA_EXT* = 0x8599.GLenum
-  GL_TEXTURE_SHADOW* = 0x82A1.GLenum
-  GL_LINEAR_CLIPMAP_LINEAR_SGIX* = 0x8170.GLenum
-  GL_MIPMAP* = 0x8293.GLenum
-  GL_LINE_SMOOTH_HINT* = 0x0C52.GLenum
-  GL_DEPTH_STENCIL_TEXTURE_MODE* = 0x90EA.GLenum
-  GL_BUFFER_ACCESS_OES* = 0x88BB.GLenum
-  GL_PROXY_TEXTURE_1D_ARRAY_EXT* = 0x8C19.GLenum
-  GL_OBJECT_LINEAR* = 0x2401.GLenum
-  GL_MAP1_TEXTURE_COORD_3* = 0x0D95.GLenum
-  GL_TEXTURE_RENDERBUFFER_NV* = 0x8E55.GLenum
-  GL_FRAMEBUFFER_RENDERABLE* = 0x8289.GLenum
-  GL_DOT3_RGB_EXT* = 0x8740.GLenum
-  GL_QUAD_LUMINANCE8_SGIS* = 0x8121.GLenum
-  GL_UNIFORM_BLOCK_INDEX* = 0x8A3A.GLenum
-  GL_DS_SCALE_NV* = 0x8710.GLenum
-  GL_TYPE* = 0x92FA.GLenum
-  GL_MATRIX_EXT* = 0x87C0.GLenum
-  GL_VERTEX_STREAM4_ATI* = 0x8770.GLenum
-  GL_TOP_LEVEL_ARRAY_STRIDE* = 0x930D.GLenum
-  GL_INT_SAMPLER_2D_EXT* = 0x8DCA.GLenum
-  GL_PATH_FORMAT_PS_NV* = 0x9071.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR* = 0x93D2.GLenum
-  GL_MAX_TEXTURE_COORDS* = 0x8871.GLenum
-  GL_MAX_FRAGMENT_INTERPOLATION_OFFSET* = 0x8E5C.GLenum
-  GL_REG_17_ATI* = 0x8932.GLenum
-  GL_WAIT_FAILED_APPLE* = 0x911D.GLenum
-  GL_TEXTURE_BINDING_3D* = 0x806A.GLenum
-  GL_TEXTURE_VIEW* = 0x82B5.GLenum
-  GL_DOT3_RGBA_ARB* = 0x86AF.GLenum
-  GL_MAX_VARYING_FLOATS_ARB* = 0x8B4B.GLenum
-  GL_UNIFORM_IS_ROW_MAJOR* = 0x8A3E.GLenum
-  GL_FRAGMENT_SHADER_BIT* = 0x00000002.GLbitfield
-  GL_MATRIX_INDEX_ARRAY_ARB* = 0x8844.GLenum
-  GL_PIXEL_PACK_BUFFER_BINDING_EXT* = 0x88ED.GLenum
-  GL_MATRIX_PALETTE_OES* = 0x8840.GLenum
-  GL_INTENSITY_SNORM* = 0x9013.GLenum
-  GL_COLOR_BUFFER_BIT0_QCOM* = 0x00000001.GLbitfield
-  GL_BITMAP* = 0x1A00.GLenum
-  GL_CURRENT_MATRIX_NV* = 0x8641.GLenum
-  GL_QUERY_BUFFER_AMD* = 0x9192.GLenum
-  GL_EDGE_FLAG_ARRAY_BUFFER_BINDING* = 0x889B.GLenum
-  GL_4PASS_3_EXT* = 0x80A7.GLenum
-  GL_TEXTURE_4DSIZE_SGIS* = 0x8136.GLenum
-  GL_PATH_COORD_COUNT_NV* = 0x909E.GLenum
-  GL_SLUMINANCE* = 0x8C46.GLenum
-  GL_POINT_SMOOTH_HINT* = 0x0C51.GLenum
-  GL_ADJACENT_PAIRS_NV* = 0x90AE.GLenum
-  GL_BUFFER_BINDING* = 0x9302.GLenum
-  GL_ARRAY_OBJECT_BUFFER_ATI* = 0x8766.GLenum
-  GL_PATH_INITIAL_DASH_CAP_NV* = 0x907C.GLenum
-  GL_RGBA4* = 0x8056.GLenum
-  GL_PACK_LSB_FIRST* = 0x0D01.GLenum
-  GL_IMAGE_BINDING_NAME_EXT* = 0x8F3A.GLenum
-  GL_UNSIGNED_INT_SAMPLER_2D_EXT* = 0x8DD2.GLenum
-  GL_RGBA12_EXT* = 0x805A.GLenum
-  GL_COMBINER0_NV* = 0x8550.GLenum
-  GL_COLOR_BUFFER_BIT4_QCOM* = 0x00000010.GLbitfield
-  GL_TIME_ELAPSED* = 0x88BF.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_START* = 0x8C84.GLenum
-  GL_COMPRESSED_RGBA_ASTC_5x5_KHR* = 0x93B2.GLenum
-  GL_MAX_SPARSE_3D_TEXTURE_SIZE_AMD* = 0x9199.GLenum
-  GL_RENDERBUFFER_HEIGHT_EXT* = 0x8D43.GLenum
-  GL_QUARTER_BIT_ATI* = 0x00000010.GLbitfield
-  GL_TEXTURE_COMPRESSION_HINT_ARB* = 0x84EF.GLenum
-  GL_DRAW_BUFFER13* = 0x8832.GLenum
-  GL_CURRENT_MATRIX_STACK_DEPTH_ARB* = 0x8640.GLenum
-  GL_DEPENDENT_HILO_TEXTURE_2D_NV* = 0x8858.GLenum
-  GL_DST_NV* = 0x9287.GLenum
-  GL_DEBUG_OBJECT_MESA* = 0x8759.GLenum
-  GL_NUM_INSTRUCTIONS_TOTAL_ATI* = 0x8972.GLenum
-  GL_FLAT* = 0x1D00.GLenum
-  GL_EVAL_VERTEX_ATTRIB8_NV* = 0x86CE.GLenum
-  GL_VERTEX_PROGRAM_CALLBACK_FUNC_MESA* = 0x8BB6.GLenum
-  GL_TEXTURE_COORD_ARRAY_EXT* = 0x8078.GLenum
-  GL_LOCATION_INDEX* = 0x930F.GLenum
-  GL_SLIM10U_SGIX* = 0x831E.GLenum
-  GL_PHONG_WIN* = 0x80EA.GLenum
-  GL_EVAL_VERTEX_ATTRIB1_NV* = 0x86C7.GLenum
-  GL_SMOOTH_LINE_WIDTH_RANGE* = 0x0B22.GLenum
-  GL_SAMPLER_RENDERBUFFER_NV* = 0x8E56.GLenum
-  GL_UNPACK_LSB_FIRST* = 0x0CF1.GLenum
-  GL_SELECTION_BUFFER_POINTER* = 0x0DF3.GLenum
-  GL_PIXEL_SUBSAMPLE_4444_SGIX* = 0x85A2.GLenum
-  GL_COMPRESSED_R11_EAC* = 0x9270.GLenum
-  GL_MAX_CLIP_PLANES* = 0x0D32.GLenum
-  GL_POST_CONVOLUTION_GREEN_BIAS* = 0x8021.GLenum
-  GL_COLOR_EXT* = 0x1800.GLenum
-  GL_VENDOR* = 0x1F00.GLenum
-  GL_MAP1_VERTEX_ATTRIB8_4_NV* = 0x8668.GLenum
-  GL_TEXTURE_ALPHA_TYPE* = 0x8C13.GLenum
-  GL_CURRENT_VERTEX_ATTRIB_ARB* = 0x8626.GLenum
-  GL_COLOR_BUFFER_BIT2_QCOM* = 0x00000004.GLbitfield
-  GL_VERTEX_ATTRIB_ARRAY15_NV* = 0x865F.GLenum
-  GL_OFFSET_PROJECTIVE_TEXTURE_2D_NV* = 0x8850.GLenum
-  GL_DRAW_BUFFER5_ARB* = 0x882A.GLenum
-  GL_SAMPLES_PASSED_ARB* = 0x8914.GLenum
-  GL_PRIMITIVE_RESTART_NV* = 0x8558.GLenum
-  GL_FRAGMENT_LIGHT3_SGIX* = 0x840F.GLenum
-  GL_COLOR_INDEX16_EXT* = 0x80E7.GLenum
-  GL_RGBA8_OES* = 0x8058.GLenum
-  GL_PACK_CMYK_HINT_EXT* = 0x800E.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_BLUE_SIZE* = 0x8214.GLenum
-  GL_MODELVIEW0_EXT* = 0x1700.GLenum
-  GL_RETAINED_APPLE* = 0x8A1B.GLenum
-  GL_DRAW_PIXELS_APPLE* = 0x8A0A.GLenum
-  GL_POINT_BIT* = 0x00000002.GLbitfield
-  GL_PIXEL_MAP_B_TO_B_SIZE* = 0x0CB8.GLenum
-  GL_RELATIVE_SMALL_CCW_ARC_TO_NV* = 0x13.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_STRIDE_ARB* = 0x8624.GLenum
-  GL_DOT_PRODUCT_AFFINE_DEPTH_REPLACE_NV* = 0x885D.GLenum
-  GL_CON_2_ATI* = 0x8943.GLenum
-  GL_SAMPLER_2D_ARRAY* = 0x8DC1.GLenum
-  GL_LINE_STIPPLE_PATTERN* = 0x0B25.GLenum
-  GL_IMPLEMENTATION_COLOR_READ_FORMAT* = 0x8B9B.GLenum
-  GL_TRANSPOSE_AFFINE_2D_NV* = 0x9096.GLenum
-  GL_COLOR_ATTACHMENT7* = 0x8CE7.GLenum
-  GL_COLOR_ATTACHMENT14* = 0x8CEE.GLenum
-  GL_SHADER* = 0x82E1.GLenum
-  GL_SKIP_MISSING_GLYPH_NV* = 0x90A9.GLenum
-  GL_VERTEX_ARRAY_TYPE* = 0x807B.GLenum
-  GL_OP_POWER_EXT* = 0x8793.GLenum
-  GL_MAX_BINDABLE_UNIFORM_SIZE_EXT* = 0x8DED.GLenum
-  GL_SRGB8* = 0x8C41.GLenum
-  GL_INTERNALFORMAT_ALPHA_SIZE* = 0x8274.GLenum
-  GL_IMAGE_2D_MULTISAMPLE* = 0x9055.GLenum
-  GL_VIDEO_CAPTURE_FRAME_HEIGHT_NV* = 0x9039.GLenum
-  GL_NEVER* = 0x0200.GLenum
-  GL_MAP2_TEXTURE_COORD_2* = 0x0DB4.GLenum
-  GL_PROGRAM_RESULT_COMPONENTS_NV* = 0x8907.GLenum
-  GL_SHADER_STORAGE_BARRIER_BIT* = 0x00002000.GLbitfield
-  GL_SLIM8U_SGIX* = 0x831D.GLenum
-  GL_DRAW_BUFFER7_ATI* = 0x882C.GLenum
-  GL_CLAMP_TO_EDGE* = 0x812F.GLint
-  GL_LUMINANCE32I_EXT* = 0x8D86.GLenum
-  GL_NORMAL_ARRAY_POINTER* = 0x808F.GLenum
-  GL_ALPHA_TEST_REF_QCOM* = 0x0BC2.GLenum
-  GL_MATRIX7_NV* = 0x8637.GLenum
-  GL_REFERENCED_BY_FRAGMENT_SHADER* = 0x930A.GLenum
-  GL_COMPRESSED_RGBA_PVRTC_4BPPV1_IMG* = 0x8C02.GLenum
-  GL_DEBUG_TYPE_MARKER* = 0x8268.GLenum
-  GL_DEBUG_OUTPUT_SYNCHRONOUS_KHR* = 0x8242.GLenum
-  GL_CON_26_ATI* = 0x895B.GLenum
-  GL_COMBINER7_NV* = 0x8557.GLenum
-  GL_MAP2_TANGENT_EXT* = 0x8445.GLenum
-  GL_COMPRESSED_RGBA_ASTC_10x6_KHR* = 0x93B9.GLenum
-  GL_RG8* = 0x822B.GLenum
-  GL_INT_SAMPLER_1D_ARRAY_EXT* = 0x8DCE.GLenum
-  GL_POINT_SPRITE_R_MODE_NV* = 0x8863.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_BINDING* = 0x92C1.GLenum
-  GL_INTENSITY16F_ARB* = 0x881D.GLenum
-  GL_DEFORMATIONS_MASK_SGIX* = 0x8196.GLenum
-  GL_PATH_TERMINAL_END_CAP_NV* = 0x9078.GLenum
-  GL_VERTEX_BINDING_DIVISOR* = 0x82D6.GLenum
-  GL_WIDE_LINE_HINT_PGI* = 0x1A222.GLenum
-  GL_LIGHTING* = 0x0B50.GLenum
-  GL_CURRENT_BIT* = 0x00000001.GLbitfield
-  GL_LOSE_CONTEXT_ON_RESET_ARB* = 0x8252.GLenum
-  GL_COLOR_ATTACHMENT15* = 0x8CEF.GLenum
-  GL_REGISTER_COMBINERS_NV* = 0x8522.GLenum
-  GL_UNSIGNED_INT64_VEC2_NV* = 0x8FF5.GLenum
-  GL_TEXTURE_CLIPMAP_DEPTH_SGIX* = 0x8176.GLenum
-  GL_HISTOGRAM_WIDTH* = 0x8026.GLenum
-  GL_RENDERBUFFER_ALPHA_SIZE* = 0x8D53.GLenum
-  GL_POST_CONVOLUTION_BLUE_BIAS_EXT* = 0x8022.GLenum
-  GL_SCALED_RESOLVE_FASTEST_EXT* = 0x90BA.GLenum
-  GL_DRAW_BUFFER15* = 0x8834.GLenum
-  GL_LUMINANCE4_ALPHA4* = 0x8043.GLenum
-  GL_SWIZZLE_STRQ_DQ_ATI* = 0x897B.GLenum
-  GL_OP_MADD_EXT* = 0x8788.GLenum
-  GL_MAX_ATTRIB_STACK_DEPTH* = 0x0D35.GLenum
-  GL_DEBUG_GROUP_STACK_DEPTH_KHR* = 0x826D.GLenum
-  GL_ACTIVE_VARYINGS_NV* = 0x8C81.GLenum
-  GL_DEBUG_SEVERITY_HIGH* = 0x9146.GLenum
-  GL_SRGB8_EXT* = 0x8C41.GLenum
-  GL_STENCIL_WRITEMASK* = 0x0B98.GLenum
-  GL_REG_14_ATI* = 0x892F.GLenum
-  GL_PROGRAM_BINARY_ANGLE* = 0x93A6.GLenum
-  GL_RENDERBUFFER_DEPTH_SIZE_EXT* = 0x8D54.GLenum
-  GL_ALPHA_BIAS* = 0x0D1D.GLenum
-  GL_STATIC_ATI* = 0x8760.GLenum
-  GL_MATRIX_INDEX_ARRAY_BUFFER_BINDING_OES* = 0x8B9E.GLenum
-  GL_SOFTLIGHT_NV* = 0x929C.GLenum
-  GL_INDEX_ARRAY_COUNT_EXT* = 0x8087.GLenum
-  GL_RENDERBUFFER_BLUE_SIZE_EXT* = 0x8D52.GLenum
-  GL_SHARED_TEXTURE_PALETTE_EXT* = 0x81FB.GLenum
-  GL_VERTEX_SHADER_OPTIMIZED_EXT* = 0x87D4.GLenum
-  GL_MAX_SAMPLE_MASK_WORDS_NV* = 0x8E59.GLenum
-  GL_MAX_MATRIX_PALETTE_STACK_DEPTH_ARB* = 0x8841.GLenum
-  GL_MATRIX30_ARB* = 0x88DE.GLenum
-  GL_NORMAL_ARRAY_POINTER_EXT* = 0x808F.GLenum
-  GL_PIXEL_MAP_A_TO_A* = 0x0C79.GLenum
-  GL_MATRIX18_ARB* = 0x88D2.GLenum
-  GL_UNPACK_SKIP_ROWS_EXT* = 0x0CF3.GLenum
-  GL_INVARIANT_DATATYPE_EXT* = 0x87EB.GLenum
-  GL_INT_IMAGE_1D_EXT* = 0x9057.GLenum
-  GL_OUTPUT_TEXTURE_COORD24_EXT* = 0x87B5.GLenum
-  GL_MAP_WRITE_BIT_EXT* = 0x0002.GLbitfield
-  GL_MODELVIEW28_ARB* = 0x873C.GLenum
-  GL_MAX_VARYING_COMPONENTS_EXT* = 0x8B4B.GLenum
-  GL_OUTPUT_TEXTURE_COORD4_EXT* = 0x87A1.GLenum
-  GL_UNSIGNED_INT_VEC2_EXT* = 0x8DC6.GLenum
-  GL_READ_ONLY* = 0x88B8.GLenum
-  GL_SECONDARY_COLOR_ARRAY_LIST_STRIDE_IBM* = 103087.GLenum
-  GL_UNSIGNED_INT64_NV* = 0x140F.GLenum
-  GL_REPLACEMENT_CODE_ARRAY_STRIDE_SUN* = 0x85C2.GLenum
-  GL_DEPTH_BUFFER_BIT0_QCOM* = 0x00000100.GLbitfield
-  GL_VERTEX_ATTRIB_MAP2_SIZE_APPLE* = 0x8A06.GLenum
-  GL_POST_CONVOLUTION_ALPHA_SCALE* = 0x801F.GLenum
-  GL_TEXTURE_COLOR_SAMPLES_NV* = 0x9046.GLenum
-  GL_DEBUG_SEVERITY_HIGH_ARB* = 0x9146.GLenum
-  GL_MAP_WRITE_BIT* = 0x0002.GLbitfield
-  GL_SRC1_RGB* = 0x8581.GLenum
-  GL_LIGHT0* = 0x4000.GLenum
-  GL_READ_PIXELS_FORMAT* = 0x828D.GLenum
-  GL_COMBINE_RGB_EXT* = 0x8571.GLenum
-  GL_MATRIX2_NV* = 0x8632.GLenum
-  GL_INT16_VEC4_NV* = 0x8FE7.GLenum
-  GL_INT_SAMPLER_CUBE* = 0x8DCC.GLenum
-  GL_LUMINANCE_ALPHA8I_EXT* = 0x8D93.GLenum
-  GL_TRIANGLE_STRIP_ADJACENCY* = 0x000D.GLenum
-  GL_MAX_TEXTURE_BUFFER_SIZE_EXT* = 0x8C2B.GLenum
-  GL_COLOR_TABLE_BIAS* = 0x80D7.GLenum
-  GL_MAX_GEOMETRY_INPUT_COMPONENTS* = 0x9123.GLenum
-  GL_TEXTURE_RANGE_POINTER_APPLE* = 0x85B8.GLenum
-  GL_PIXEL_SUBSAMPLE_2424_SGIX* = 0x85A3.GLenum
-  GL_RESAMPLE_REPLICATE_OML* = 0x8986.GLenum
-  GL_ALL_STATIC_DATA_IBM* = 103060.GLenum
-  GL_DEBUG_CATEGORY_PERFORMANCE_AMD* = 0x914D.GLenum
-  GL_ALPHA_TEST_QCOM* = 0x0BC0.GLenum
-  GL_PREVIOUS_TEXTURE_INPUT_NV* = 0x86E4.GLenum
-  GL_SIGNED_RGBA_NV* = 0x86FB.GLenum
-  GL_GLOBAL_ALPHA_SUN* = 0x81D9.GLenum
-  GL_RGB_FLOAT16_APPLE* = 0x881B.GLenum
-  GL_PROGRAM_NATIVE_ALU_INSTRUCTIONS_ARB* = 0x8808.GLenum
-  GL_UTF8_NV* = 0x909A.GLenum
-  GL_ALLOW_DRAW_OBJ_HINT_PGI* = 0x1A20E.GLenum
-  GL_INT_IMAGE_3D* = 0x9059.GLenum
-  GL_PACK_ROW_LENGTH* = 0x0D02.GLenum
-  GL_MAX_TEXTURE_LOD_BIAS_EXT* = 0x84FD.GLenum
-  GL_SCALED_RESOLVE_NICEST_EXT* = 0x90BB.GLenum
-  GL_422_EXT* = 0x80CC.GLenum
-  GL_SAMPLER_1D_ARRAY_SHADOW_EXT* = 0x8DC3.GLenum
-  GL_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT* = 0x8336.GLenum
-  GL_COMPRESSED_RED* = 0x8225.GLenum
-  GL_MAX_RATIONAL_EVAL_ORDER_NV* = 0x86D7.GLenum
-  GL_MAX_COMBINED_IMAGE_UNIFORMS* = 0x90CF.GLenum
-  GL_GLYPH_HORIZONTAL_BEARING_ADVANCE_BIT_NV* = 0x10.GLbitfield
-  GL_TEXTURE_BINDING_1D_ARRAY* = 0x8C1C.GLenum
-  GL_FRAMEBUFFER_COMPLETE* = 0x8CD5.GLenum
-  GL_RG8I* = 0x8237.GLenum
-  GL_COLOR_ATTACHMENT2_NV* = 0x8CE2.GLenum
-  GL_INT64_VEC4_NV* = 0x8FEB.GLenum
-  GL_OP_SET_GE_EXT* = 0x878C.GLenum
-  GL_READ_WRITE* = 0x88BA.GLenum
-  GL_OPERAND1_RGB_EXT* = 0x8591.GLenum
-  GL_SHADER_STORAGE_BLOCK* = 0x92E6.GLenum
-  GL_TEXTURE_UPDATE_BARRIER_BIT* = 0x00000100.GLbitfield
-  GL_MAX_FRAGMENT_ATOMIC_COUNTERS* = 0x92D6.GLenum
-  GL_SHADER_INCLUDE_ARB* = 0x8DAE.GLenum
-  GL_UNSIGNED_SHORT_1_5_5_5_REV* = 0x8366.GLenum
-  GL_PROGRAM_PIPELINE* = 0x82E4.GLenum
-  GL_MAP1_TEXTURE_COORD_2* = 0x0D94.GLenum
-  GL_FOG_COORDINATE_ARRAY_STRIDE_EXT* = 0x8455.GLenum
-  GL_WEIGHT_ARRAY_SIZE_OES* = 0x86AB.GLenum
-  GL_R11F_G11F_B10F* = 0x8C3A.GLenum
-  GL_WRITE_PIXEL_DATA_RANGE_NV* = 0x8878.GLenum
-  GL_UNSIGNED_SHORT_8_8_REV_APPLE* = 0x85BB.GLenum
-  GL_CND_ATI* = 0x896A.GLenum
-  GL_IMAGE_2D_MULTISAMPLE_ARRAY* = 0x9056.GLenum
-  GL_MAX_TEXTURE_IMAGE_UNITS_NV* = 0x8872.GLenum
-  GL_COMPRESSED_SIGNED_RG11_EAC_OES* = 0x9273.GLenum
-  GL_DOT_PRODUCT_TEXTURE_3D_NV* = 0x86EF.GLenum
-  GL_IMAGE_TRANSLATE_Y_HP* = 0x8158.GLenum
-  GL_NORMAL_ARRAY_TYPE_EXT* = 0x807E.GLenum
-  GL_PIXEL_COUNT_NV* = 0x8866.GLenum
-  GL_INT_IMAGE_3D_EXT* = 0x9059.GLenum
-  GL_TEXTURE_TYPE_QCOM* = 0x8BD7.GLenum
-  GL_COMBINE_ALPHA_EXT* = 0x8572.GLenum
-  GL_POINT_TOKEN* = 0x0701.GLenum
-  GL_QUAD_ALPHA4_SGIS* = 0x811E.GLenum
-  GL_SIGNED_HILO8_NV* = 0x885F.GLenum
-  GL_MULTISAMPLE_ARB* = 0x809D.GLenum
-  GL_TEXTURE25* = 0x84D9.GLenum
-  GL_CURRENT_VERTEX_WEIGHT_EXT* = 0x850B.GLenum
-  GL_BLEND_DST_ALPHA_OES* = 0x80CA.GLenum
-  GL_UNSIGNED_SHORT_8_8_REV_MESA* = 0x85BB.GLenum
-  GL_CLAMP_TO_EDGE_SGIS* = 0x812F.GLint
-  GL_PATH_STENCIL_REF_NV* = 0x90B8.GLenum
-  GL_DEBUG_OUTPUT* = 0x92E0.GLenum
-  GL_OBJECT_TYPE_APPLE* = 0x9112.GLenum
-  GL_TEXTURE_COMPARE_MODE_ARB* = 0x884C.GLenum
-  GL_CONSTANT* = 0x8576.GLenum
-  GL_RGB5_A1_OES* = 0x8057.GLenum
-  GL_INT16_VEC2_NV* = 0x8FE5.GLenum
-  GL_CONVOLUTION_BORDER_MODE_EXT* = 0x8013.GLenum
-  GL_CONTEXT_FLAGS* = 0x821E.GLenum
-  GL_MAX_PROGRAM_SUBROUTINE_NUM_NV* = 0x8F45.GLenum
-  GL_SPRITE_SGIX* = 0x8148.GLenum
-  GL_CURRENT_QUERY* = 0x8865.GLenum
-  GL_STENCIL_OP_VALUE_AMD* = 0x874C.GLenum
-  GL_UNIFORM* = 0x92E1.GLenum
-  GL_TEXTURE_BINDING_RECTANGLE* = 0x84F6.GLenum
-  GL_TRIANGLES_ADJACENCY_EXT* = 0x000C.GLenum
-  GL_PROVOKING_VERTEX_EXT* = 0x8E4F.GLenum
-  GL_INT64_VEC2_NV* = 0x8FE9.GLenum
-  GL_INVERSE_NV* = 0x862B.GLenum
-  GL_CON_29_ATI* = 0x895E.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE_NV* = 0x8E24.GLenum
-  GL_FRONT_AND_BACK* = 0x0408.GLenum
-  GL_MAX_LABEL_LENGTH_KHR* = 0x82E8.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_START_NV* = 0x8C84.GLenum
-  GL_EQUAL* = 0x0202.GLenum
-  GL_RGB10_EXT* = 0x8052.GLenum
-  GL_MAX_GEOMETRY_TEXTURE_IMAGE_UNITS_ARB* = 0x8C29.GLenum
-  GL_OP_ADD_EXT* = 0x8787.GLenum
-  GL_REPLACEMENT_CODE_ARRAY_POINTER_SUN* = 0x85C3.GLenum
-  GL_NORMAL_ARRAY_LIST_IBM* = 103071.GLenum
-  GL_RENDERBUFFER_GREEN_SIZE* = 0x8D51.GLenum
-  GL_TESS_CONTROL_PROGRAM_PARAMETER_BUFFER_NV* = 0x8C74.GLenum
-  GL_CURRENT_PALETTE_MATRIX_ARB* = 0x8843.GLenum
-  GL_DEBUG_TYPE_ERROR* = 0x824C.GLenum
-  GL_UNIFORM_BUFFER* = 0x8A11.GLenum
-  GL_NEAREST_CLIPMAP_LINEAR_SGIX* = 0x844E.GLenum
-  GL_LAST_VERTEX_CONVENTION* = 0x8E4E.GLenum
-  GL_COMPRESSED_RGBA_ASTC_12x10_KHR* = 0x93BC.GLenum
-  GL_FENCE_STATUS_NV* = 0x84F3.GLenum
-  GL_POST_CONVOLUTION_BLUE_BIAS* = 0x8022.GLenum
-  GL_BLEND_OVERLAP_NV* = 0x9281.GLenum
-  GL_COMBINE_RGB_ARB* = 0x8571.GLenum
-  GL_TESS_GEN_MODE* = 0x8E76.GLenum
-  GL_TEXTURE_ENV* = 0x2300.GLenum
-  GL_VERTEX_ATTRIB_ARRAY11_NV* = 0x865B.GLenum
-  GL_SHININESS* = 0x1601.GLenum
-  GL_DYNAMIC_STORAGE_BIT* = 0x0100.GLbitfield
-  GL_MODELVIEW30_ARB* = 0x873E.GLenum
-  GL_WRAP_BORDER_SUN* = 0x81D4.GLenum
-  GL_SKIP_COMPONENTS1_NV* = -6
-  GL_DEPTH_CLAMP_NV* = 0x864F.GLenum
-  GL_PROGRAM_BINARY_FORMATS* = 0x87FF.GLenum
-  GL_CURRENT_RASTER_POSITION_VALID* = 0x0B08.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_TESS_CONTROL_SHADER* = 0x92C8.GLenum
-  GL_T2F_C4F_N3F_V3F* = 0x2A2C.GLenum
-  GL_R16F* = 0x822D.GLenum
-  GL_SECONDARY_COLOR_ARRAY_LENGTH_NV* = 0x8F31.GLenum
-  GL_SEPARATE_ATTRIBS_EXT* = 0x8C8D.GLenum
-  GL_NEGATIVE_Z_EXT* = 0x87DB.GLenum
-  GL_Z400_BINARY_AMD* = 0x8740.GLenum
-  GL_DRAW_INDIRECT_UNIFIED_NV* = 0x8F40.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_INTERLEAVED_COMPONENTS_NV* = 0x8C8A.GLenum
-  GL_UNSIGNED_INT_S8_S8_8_8_NV* = 0x86DA.GLenum
-  GL_SRGB8_NV* = 0x8C41.GLenum
-  GL_DEBUG_SEVERITY_MEDIUM_AMD* = 0x9147.GLenum
-  GL_MAX_DRAW_BUFFERS_ATI* = 0x8824.GLenum
-  GL_TEXTURE_COORD_ARRAY_POINTER_EXT* = 0x8092.GLenum
-  GL_RESAMPLE_AVERAGE_OML* = 0x8988.GLenum
-  GL_NO_ERROR* = 0.GLenum
-  GL_RGB5* = 0x8050.GLenum
-  GL_OP_CLAMP_EXT* = 0x878E.GLenum
-  GL_PROGRAM_RESIDENT_NV* = 0x8647.GLenum
-  GL_PROGRAM_ALU_INSTRUCTIONS_ARB* = 0x8805.GLenum
-  GL_ELEMENT_ARRAY_UNIFIED_NV* = 0x8F1F.GLenum
-  GL_SECONDARY_COLOR_ARRAY_LIST_IBM* = 103077.GLenum
-  GL_INTENSITY12_EXT* = 0x804C.GLenum
-  GL_STENCIL_BUFFER_BIT7_QCOM* = 0x00800000.GLbitfield
-  GL_SAMPLER* = 0x82E6.GLenum
-  GL_MAD_ATI* = 0x8968.GLenum
-  GL_STENCIL_BACK_FAIL* = 0x8801.GLenum
-  GL_LIGHT_MODEL_TWO_SIDE* = 0x0B52.GLenum
-  GL_UNPACK_SKIP_PIXELS* = 0x0CF4.GLenum
-  GL_PIXEL_TEX_GEN_SGIX* = 0x8139.GLenum
-  GL_FRACTIONAL_ODD* = 0x8E7B.GLenum
-  GL_LOW_INT* = 0x8DF3.GLenum
-  GL_MODELVIEW* = 0x1700.GLenum
-  GL_POST_CONVOLUTION_RED_SCALE_EXT* = 0x801C.GLenum
-  GL_DRAW_BUFFER11_EXT* = 0x8830.GLenum
-  GL_ACTIVE_UNIFORM_BLOCK_MAX_NAME_LENGTH* = 0x8A35.GLenum
-  GL_CONVOLUTION_BORDER_MODE* = 0x8013.GLenum
-  GL_COMPRESSED_ALPHA_ARB* = 0x84E9.GLenum
-  GL_DEPTH_ATTACHMENT* = 0x8D00.GLenum
-  GL_ALPHA8_SNORM* = 0x9014.GLenum
-  GL_DOUBLE_MAT4x3_EXT* = 0x8F4E.GLenum
-  GL_INTERNALFORMAT_STENCIL_SIZE* = 0x8276.GLenum
-  GL_BOOL_VEC2_ARB* = 0x8B57.GLenum
-  GL_FASTEST* = 0x1101.GLenum
-  GL_MAX_FRAGMENT_INPUT_COMPONENTS* = 0x9125.GLenum
-  GL_STENCIL_BACK_FUNC_ATI* = 0x8800.GLenum
-  GL_POLYGON* = 0x0009.GLenum
-  GL_SAMPLER_1D_ARRAY_EXT* = 0x8DC0.GLenum
-  GL_OUTPUT_COLOR1_EXT* = 0x879C.GLenum
-  GL_IMAGE_2D_RECT* = 0x904F.GLenum
-  GL_RECT_NV* = 0xF6.GLenum
-  GL_OUTPUT_TEXTURE_COORD21_EXT* = 0x87B2.GLenum
-  GL_NOR* = 0x1508.GLenum
-  GL_FOG_COORD_ARRAY* = 0x8457.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Y_OES* = 0x8517.GLenum
-  GL_TANGENT_ARRAY_POINTER_EXT* = 0x8442.GLenum
-  GL_DST_OUT_NV* = 0x928D.GLenum
-  GL_RENDERBUFFER_BINDING_OES* = 0x8CA7.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR* = 0x93D3.GLenum
-  GL_TEXTURE_GEN_S* = 0x0C60.GLenum
-  GL_SLIM12S_SGIX* = 0x831F.GLenum
-  GL_VERTEX_ARRAY_BINDING* = 0x85B5.GLenum
-  GL_TRACE_PRIMITIVES_BIT_MESA* = 0x0002.GLbitfield
-  GL_MAX_DEBUG_MESSAGE_LENGTH* = 0x9143.GLenum
-  GL_EVAL_VERTEX_ATTRIB4_NV* = 0x86CA.GLenum
-  GL_ACTIVE_SUBROUTINE_UNIFORMS* = 0x8DE6.GLenum
-  GL_ACCUM_ADJACENT_PAIRS_NV* = 0x90AD.GLenum
-  GL_NEGATIVE_ONE_EXT* = 0x87DF.GLenum
-  GL_UNPACK_RESAMPLE_SGIX* = 0x842D.GLenum
-  GL_ACTIVE_SUBROUTINE_MAX_LENGTH* = 0x8E48.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT* = 0x8518.GLenum
-  GL_DEBUG_CATEGORY_API_ERROR_AMD* = 0x9149.GLenum
-  GL_INTERNALFORMAT_BLUE_SIZE* = 0x8273.GLenum
-  GL_DRAW_BUFFER13_NV* = 0x8832.GLenum
-  GL_DEBUG_SOURCE_THIRD_PARTY_ARB* = 0x8249.GLenum
-  GL_R8_EXT* = 0x8229.GLenum
-  GL_GENERATE_MIPMAP* = 0x8191.GLenum
-  cGL_SHORT* = 0x1402.GLenum
-  GL_PACK_REVERSE_ROW_ORDER_ANGLE* = 0x93A4.GLenum
-  GL_PATH_DASH_OFFSET_RESET_NV* = 0x90B4.GLenum
-  GL_PACK_SKIP_VOLUMES_SGIS* = 0x8130.GLenum
-  GL_TEXTURE_RED_TYPE* = 0x8C10.GLenum
-  GL_MAX_COLOR_ATTACHMENTS_EXT* = 0x8CDF.GLenum
-  GL_MAP2_VERTEX_ATTRIB5_4_NV* = 0x8675.GLenum
-  GL_CONSTANT_ALPHA* = 0x8003.GLenum
-  GL_COLOR_INDEX8_EXT* = 0x80E5.GLenum
-  GL_DOUBLE_MAT3_EXT* = 0x8F47.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_INDEX* = 0x9301.GLenum
-  GL_LINES_ADJACENCY_EXT* = 0x000A.GLenum
-  GL_RENDERBUFFER_SAMPLES_IMG* = 0x9133.GLenum
-  GL_COLOR_TABLE_FORMAT* = 0x80D8.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_TYPE* = 0x8625.GLenum
-  GL_QUERY_OBJECT_EXT* = 0x9153.GLenum
-  GL_STREAM_READ_ARB* = 0x88E1.GLenum
-  GL_MIRROR_CLAMP_TO_EDGE_ATI* = 0x8743.GLint
-  GL_FRAGMENT_SUBROUTINE_UNIFORM* = 0x92F2.GLenum
-  GL_UNIFORM_BUFFER_EXT* = 0x8DEE.GLenum
-  GL_SOURCE2_RGB* = 0x8582.GLenum
-  GL_PROGRAM_NATIVE_ATTRIBS_ARB* = 0x88AE.GLenum
-  GL_LUMINANCE12_ALPHA12* = 0x8047.GLenum
-  GL_INT_SAMPLER_1D_EXT* = 0x8DC9.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_SAMPLES_EXT* = 0x8D6C.GLenum
-  GL_DEPTH_RENDERABLE* = 0x8287.GLenum
-  GL_INTERNALFORMAT_BLUE_TYPE* = 0x827A.GLenum
-  GL_SLUMINANCE8_ALPHA8_EXT* = 0x8C45.GLenum
-  GL_TEXTURE_BINDING_CUBE_MAP_ARRAY_ARB* = 0x900A.GLenum
-  GL_COLOR_MATRIX* = 0x80B1.GLenum
-  GL_RGB8_SNORM* = 0x8F96.GLenum
-  GL_COLOR_ARRAY_SIZE* = 0x8081.GLenum
-  GL_DRAW_BUFFER4_NV* = 0x8829.GLenum
-  GL_VIDEO_BUFFER_INTERNAL_FORMAT_NV* = 0x902D.GLenum
-  GL_PRESENT_TIME_NV* = 0x8E2A.GLenum
-  GL_COPY_WRITE_BUFFER* = 0x8F37.GLenum
-  GL_UNPACK_SKIP_PIXELS_EXT* = 0x0CF4.GLenum
-  GL_PRIMITIVES_GENERATED_NV* = 0x8C87.GLenum
-  GL_INT_SAMPLER_BUFFER* = 0x8DD0.GLenum
-  GL_GLYPH_HORIZONTAL_BEARING_X_BIT_NV* = 0x04.GLbitfield
-  GL_FOG_COORDINATE_EXT* = 0x8451.GLenum
-  GL_VERTEX_ARRAY_ADDRESS_NV* = 0x8F21.GLenum
-  GL_RENDERBUFFER_RED_SIZE_OES* = 0x8D50.GLenum
-  GL_BGR_INTEGER_EXT* = 0x8D9A.GLenum
-  GL_UNSIGNED_BYTE_3_3_2* = 0x8032.GLenum
-  GL_VBO_FREE_MEMORY_ATI* = 0x87FB.GLenum
-  GL_PATH_COMPUTED_LENGTH_NV* = 0x90A0.GLenum
-  GL_COLOR_MATRIX_STACK_DEPTH_SGI* = 0x80B2.GLenum
-  GL_STACK_OVERFLOW* = 0x0503.GLenum
-  GL_MODELVIEW1_MATRIX_EXT* = 0x8506.GLenum
-  GL_CURRENT_BINORMAL_EXT* = 0x843C.GLenum
-  GL_OP_MULTIPLY_MATRIX_EXT* = 0x8798.GLenum
-  GL_CLIENT_ATTRIB_STACK_DEPTH* = 0x0BB1.GLenum
-  GL_VERTEX_PROGRAM_TWO_SIDE_NV* = 0x8643.GLenum
-  GL_HISTOGRAM_WIDTH_EXT* = 0x8026.GLenum
-  GL_OBJECT_INFO_LOG_LENGTH_ARB* = 0x8B84.GLenum
-  GL_SAMPLER_2D_ARRAY_SHADOW* = 0x8DC4.GLenum
-  GL_UNSIGNED_INT_IMAGE_1D* = 0x9062.GLenum
-  GL_MAX_IMAGE_UNITS* = 0x8F38.GLenum
-  GL_TEXTURE31_ARB* = 0x84DF.GLenum
-  GL_CUBIC_HP* = 0x815F.GLenum
-  GL_OFFSET_HILO_PROJECTIVE_TEXTURE_2D_NV* = 0x8856.GLenum
-  GL_ARRAY_STRIDE* = 0x92FE.GLenum
-  GL_DEPTH_PASS_INSTRUMENT_SGIX* = 0x8310.GLenum
-  GL_COMMAND_BARRIER_BIT* = 0x00000040.GLbitfield
-  GL_STATIC_DRAW_ARB* = 0x88E4.GLenum
-  GL_RGB16F* = 0x881B.GLenum
-  GL_INDEX_MATERIAL_PARAMETER_EXT* = 0x81B9.GLenum
-  GL_UNPACK_SKIP_VOLUMES_SGIS* = 0x8132.GLenum
-  GL_TEXTURE_1D* = 0x0DE0.GLenum
-  GL_VERTEX_PROGRAM_NV* = 0x8620.GLenum
-  GL_COLOR_ATTACHMENT0_NV* = 0x8CE0.GLenum
-  GL_READ_PIXEL_DATA_RANGE_LENGTH_NV* = 0x887B.GLenum
-  GL_FLOAT_32_UNSIGNED_INT_24_8_REV* = 0x8DAD.GLenum
-  GL_LINE_RESET_TOKEN* = 0x0707.GLenum
-  GL_WEIGHT_ARRAY_ARB* = 0x86AD.GLenum
-  GL_TEXTURE17* = 0x84D1.GLenum
-  GL_DEPTH_COMPONENT32_ARB* = 0x81A7.GLenum
-  GL_REFERENCED_BY_TESS_CONTROL_SHADER* = 0x9307.GLenum
-  GL_INVERT* = 0x150A.GLenum
-  GL_FOG_COORDINATE_ARRAY_STRIDE* = 0x8455.GLenum
-  GL_COMPRESSED_SIGNED_RG_RGTC2* = 0x8DBE.GLenum
-  GL_UNSIGNED_SHORT_8_8_MESA* = 0x85BA.GLenum
-  GL_ELEMENT_ARRAY_TYPE_ATI* = 0x8769.GLenum
-  GL_CLAMP_VERTEX_COLOR_ARB* = 0x891A.GLenum
-  GL_POINT_SIZE_ARRAY_STRIDE_OES* = 0x898B.GLenum
-  GL_RGB8* = 0x8051.GLenum
-  GL_MATRIX1_ARB* = 0x88C1.GLenum
-  GL_TEXTURE_POST_SPECULAR_HP* = 0x8168.GLenum
-  GL_TEXTURE_WRAP_Q_SGIS* = 0x8137.GLenum
-  GL_SAMPLER_2D_MULTISAMPLE_ARRAY* = 0x910B.GLenum
-  GL_INVALID_FRAMEBUFFER_OPERATION_OES* = 0x0506.GLenum
-  GL_VERTEX_ID_SWIZZLE_AMD* = 0x91A5.GLenum
-  GL_USE_MISSING_GLYPH_NV* = 0x90AA.GLenum
-  GL_LUMINANCE8_EXT* = 0x8040.GLenum
-  GL_INT_VEC2* = 0x8B53.GLenum
-  GL_TEXTURE9* = 0x84C9.GLenum
-  GL_RGB32UI_EXT* = 0x8D71.GLenum
-  GL_FENCE_CONDITION_NV* = 0x84F4.GLenum
-  GL_QUADS_FOLLOW_PROVOKING_VERTEX_CONVENTION_EXT* = 0x8E4C.GLenum
-  GL_HSL_SATURATION_NV* = 0x92AE.GLenum
-  GL_CMYKA_EXT* = 0x800D.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_NV* = 0x8C8E.GLenum
-  GL_BUFFER_MAP_POINTER_OES* = 0x88BD.GLenum
-  GL_STORAGE_CLIENT_APPLE* = 0x85B4.GLenum
-  GL_VERTEX_ARRAY_BUFFER_BINDING_ARB* = 0x8896.GLenum
-  GL_TEXTURE_INTERNAL_FORMAT* = 0x1003.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED* = 0x8E23.GLenum
-  GL_UNSIGNED_INT_VEC3* = 0x8DC7.GLenum
-  GL_TRACE_MASK_MESA* = 0x8755.GLenum
-  GL_MAP_READ_BIT_EXT* = 0x0001.GLbitfield
-  GL_READ_FRAMEBUFFER_EXT* = 0x8CA8.GLenum
-  GL_HISTOGRAM_GREEN_SIZE* = 0x8029.GLenum
-  GL_COLOR_TABLE_INTENSITY_SIZE_SGI* = 0x80DF.GLenum
-  GL_SMALL_CCW_ARC_TO_NV* = 0x12.GLenum
-  GL_RELATIVE_LARGE_CW_ARC_TO_NV* = 0x19.GLenum
-  GL_POST_COLOR_MATRIX_BLUE_BIAS_SGI* = 0x80BA.GLenum
-  GL_SCISSOR_BIT* = 0x00080000.GLbitfield
-  GL_DRAW_BUFFER0_ATI* = 0x8825.GLenum
-  GL_GEOMETRY_SHADER_BIT* = 0x00000004.GLbitfield
-  GL_CLIP_FAR_HINT_PGI* = 0x1A221.GLenum
-  GL_TEXTURE_COMPARE_FUNC_EXT* = 0x884D.GLenum
-  GL_IS_ROW_MAJOR* = 0x9300.GLenum
-  GL_MAP1_VERTEX_4* = 0x0D98.GLenum
-  GL_OUTPUT_TEXTURE_COORD8_EXT* = 0x87A5.GLenum
-  GL_MAX_VERTEX_IMAGE_UNIFORMS* = 0x90CA.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE* = 0x8211.GLenum
-  GL_SOURCE1_ALPHA_ARB* = 0x8589.GLenum
-  GL_VIRTUAL_PAGE_SIZE_X_AMD* = 0x9195.GLenum
-  GL_CULL_FRAGMENT_NV* = 0x86E7.GLenum
-  GL_MAX_ATOMIC_COUNTER_BUFFER_BINDINGS* = 0x92DC.GLenum
-  GL_QUERY_COUNTER_BITS_EXT* = 0x8864.GLenum
-  GL_RGB565* = 0x8D62.GLenum
-  GL_OFFSET_TEXTURE_RECTANGLE_NV* = 0x864C.GLenum
-  GL_CONVOLUTION_FORMAT_EXT* = 0x8017.GLenum
-  GL_EYE_POINT_SGIS* = 0x81F4.GLenum
-  GL_ALPHA32F_ARB* = 0x8816.GLenum
-  GL_TEXTURE_DEPTH_SIZE* = 0x884A.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR* = 0x93D1.GLenum
-  GL_PRIMARY_COLOR_NV* = 0x852C.GLenum
-  GL_BLEND_DST_ALPHA_EXT* = 0x80CA.GLenum
-  GL_NORMALIZE* = 0x0BA1.GLenum
-  GL_POST_CONVOLUTION_GREEN_BIAS_EXT* = 0x8021.GLenum
-  GL_HI_SCALE_NV* = 0x870E.GLenum
-  GL_TESS_EVALUATION_PROGRAM_NV* = 0x891F.GLenum
-  GL_MAX_DUAL_SOURCE_DRAW_BUFFERS* = 0x88FC.GLenum
-  GL_SWIZZLE_STRQ_ATI* = 0x897A.GLenum
-  GL_READ_FRAMEBUFFER_NV* = 0x8CA8.GLenum
-  GL_MATRIX_INDEX_ARRAY_STRIDE_OES* = 0x8848.GLenum
-  GL_MIN_SPARSE_LEVEL_ARB* = 0x919B.GLenum
-  GL_RG32UI* = 0x823C.GLenum
-  GL_SAMPLER_2D_ARRAY_EXT* = 0x8DC1.GLenum
-  GL_TEXTURE22_ARB* = 0x84D6.GLenum
-  GL_MAX_COMBINED_GEOMETRY_UNIFORM_COMPONENTS* = 0x8A32.GLenum
-  GL_CULL_VERTEX_EYE_POSITION_EXT* = 0x81AB.GLenum
-  GL_TEXTURE_BUFFER* = 0x8C2A.GLenum
-  GL_MAX_CUBE_MAP_TEXTURE_SIZE_ARB* = 0x851C.GLenum
-  GL_NORMAL_ARRAY_COUNT_EXT* = 0x8080.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_NV* = 0x8D56.GLenum
-  GL_ELEMENT_ARRAY_BARRIER_BIT_EXT* = 0x00000002.GLbitfield
-  GL_VERTEX_ARRAY_COUNT_EXT* = 0x807D.GLenum
-  GL_PROGRAM_ERROR_STRING_NV* = 0x8874.GLenum
-  GL_INVALID_FRAMEBUFFER_OPERATION* = 0x0506.GLenum
-  GL_RGB9_E5* = 0x8C3D.GLenum
-  GL_GREEN_BITS* = 0x0D53.GLenum
-  GL_CLIP_DISTANCE0* = 0x3000.GLenum
-  GL_COMBINER_SUM_OUTPUT_NV* = 0x854C.GLenum
-  GL_COLOR_ARRAY* = 0x8076.GLenum
-  GL_RGBA8_SNORM* = 0x8F97.GLenum
-  GL_PROGRAM_BINDING_ARB* = 0x8677.GLenum
-  GL_4PASS_0_EXT* = 0x80A4.GLenum
-  GL_STATIC_DRAW* = 0x88E4.GLenum
-  GL_TEXTURE_COMPRESSED_BLOCK_WIDTH* = 0x82B1.GLenum
-  GL_TEXTURE_STORAGE_SPARSE_BIT_AMD* = 0x00000001.GLbitfield
-  GL_MEDIUM_INT* = 0x8DF4.GLenum
-  GL_TEXTURE13_ARB* = 0x84CD.GLenum
-  GL_LUMINANCE_ALPHA16F_ARB* = 0x881F.GLenum
-  GL_CONTEXT_CORE_PROFILE_BIT* = 0x00000001.GLbitfield
-  GL_LOCATION_COMPONENT* = 0x934A.GLenum
-  GL_TEXTURE_RECTANGLE* = 0x84F5.GLenum
-  GL_SAMPLER_2D_ARB* = 0x8B5E.GLenum
-  GL_FLOAT_RG32_NV* = 0x8887.GLenum
-  GL_SKIP_DECODE_EXT* = 0x8A4A.GLenum
-  GL_LIGHT6* = 0x4006.GLenum
-  GL_ATC_RGBA_INTERPOLATED_ALPHA_AMD* = 0x87EE.GLenum
-  GL_NOOP* = 0x1505.GLenum
-  GL_DEPTH_BUFFER_BIT* = 0x00000100.GLbitfield
-  GL_FRAMEBUFFER_BINDING_ANGLE* = 0x8CA6.GLenum
-  GL_DEBUG_TYPE_POP_GROUP_KHR* = 0x826A.GLenum
-  GL_SAMPLER_2D_RECT_SHADOW* = 0x8B64.GLenum
-  GL_CONSERVE_MEMORY_HINT_PGI* = 0x1A1FD.GLenum
-  GL_QUERY_BY_REGION_NO_WAIT* = 0x8E16.GLenum
-  GL_UNSIGNED_INT_SAMPLER_CUBE* = 0x8DD4.GLenum
-  GL_LUMINANCE4_EXT* = 0x803F.GLenum
-  GL_COLOR_ARRAY_STRIDE* = 0x8083.GLenum
-  GL_SAMPLER_2D_ARRAY_SHADOW_NV* = 0x8DC4.GLenum
-  GL_REFERENCED_BY_GEOMETRY_SHADER* = 0x9309.GLenum
-  GL_SIGNED_RGB_UNSIGNED_ALPHA_NV* = 0x870C.GLenum
-  GL_OBJECT_PLANE* = 0x2501.GLenum
-  GL_Q* = 0x2003.GLenum
-  GL_MAX_SPOT_EXPONENT_NV* = 0x8505.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_LONG* = 0x874E.GLenum
-  GL_COLOR_ATTACHMENT3* = 0x8CE3.GLenum
-  GL_TEXTURE_BINDING_RENDERBUFFER_NV* = 0x8E53.GLenum
-  GL_EXCLUSION_NV* = 0x92A0.GLenum
-  GL_EDGE_FLAG_ARRAY_ADDRESS_NV* = 0x8F26.GLenum
-  GL_PRIMARY_COLOR_ARB* = 0x8577.GLenum
-  GL_LUMINANCE_ALPHA_FLOAT16_ATI* = 0x881F.GLenum
-  GL_TRACE_TEXTURES_BIT_MESA* = 0x0008.GLbitfield
-  GL_FRAMEBUFFER_OES* = 0x8D40.GLenum
-  GL_PIXEL_MAG_FILTER_EXT* = 0x8331.GLenum
-  GL_IMAGE_BINDING_LAYERED_EXT* = 0x8F3C.GLenum
-  GL_PATH_MITER_LIMIT_NV* = 0x907A.GLenum
-  GL_PROJECTION_MATRIX* = 0x0BA7.GLenum
-  GL_TEXTURE23_ARB* = 0x84D7.GLenum
-  GL_VERTEX_ATTRIB_MAP2_COEFF_APPLE* = 0x8A07.GLenum
-  GL_RGB32F_ARB* = 0x8815.GLenum
-  GL_RED_SCALE* = 0x0D14.GLenum
-  GL_GEOMETRY_INPUT_TYPE_ARB* = 0x8DDB.GLenum
-  GL_EVAL_VERTEX_ATTRIB13_NV* = 0x86D3.GLenum
-  GL_INT64_NV* = 0x140E.GLenum
-  GL_VIEW_CLASS_24_BITS* = 0x82C9.GLenum
-  GL_FRAGMENT_LIGHT2_SGIX* = 0x840E.GLenum
-  GL_LUMINANCE12_ALPHA12_EXT* = 0x8047.GLenum
-  GL_MAP2_VERTEX_ATTRIB2_4_NV* = 0x8672.GLenum
-  GL_POINT_SIZE_MIN_SGIS* = 0x8126.GLenum
-  GL_DEBUG_TYPE_OTHER_ARB* = 0x8251.GLenum
-  GL_MAP2_VERTEX_ATTRIB0_4_NV* = 0x8670.GLenum
-  GL_DEBUG_PRINT_MESA* = 0x875A.GLenum
-  GL_TEXTURE_PRIORITY* = 0x8066.GLenum
-  GL_PIXEL_MAP_I_TO_G* = 0x0C73.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_DIVISOR* = 0x88FE.GLenum
-  GL_TEXTURE_CUBE_MAP_ARB* = 0x8513.GLenum
-  GL_LUMINANCE8_SNORM* = 0x9015.GLenum
-  GL_CLIENT_MAPPED_BUFFER_BARRIER_BIT* = 0x00004000.GLbitfield
-  GL_MAX_COMBINED_TESS_EVALUATION_UNIFORM_COMPONENTS* = 0x8E1F.GLenum
-  GL_BUFFER_STORAGE_FLAGS* = 0x8220.GLenum
-  GL_DEPTH_COMPONENT24_SGIX* = 0x81A6.GLenum
-  GL_UNIFORM_OFFSET* = 0x8A3B.GLenum
-  GL_TEXTURE_DT_SIZE_NV* = 0x871E.GLenum
-  GL_POST_COLOR_MATRIX_ALPHA_SCALE_SGI* = 0x80B7.GLenum
-  GL_DEPTH32F_STENCIL8_NV* = 0x8DAC.GLenum
-  GL_STENCIL_FUNC* = 0x0B92.GLenum
-  GL_NEAREST_MIPMAP_LINEAR* = 0x2702.GLint
-  GL_COMPRESSED_LUMINANCE_LATC1_EXT* = 0x8C70.GLenum
-  GL_TEXTURE_BORDER* = 0x1005.GLenum
-  GL_COLOR_ATTACHMENT14_NV* = 0x8CEE.GLenum
-  GL_TEXTURE_STORAGE_HINT_APPLE* = 0x85BC.GLenum
-  GL_VERTEX_ARRAY_RANGE_NV* = 0x851D.GLenum
-  GL_COLOR_ARRAY_SIZE_EXT* = 0x8081.GLenum
-  GL_INTERNALFORMAT_SUPPORTED* = 0x826F.GLenum
-  GL_MULTISAMPLE_BIT_ARB* = 0x20000000.GLbitfield
-  GL_RGB* = 0x1907.GLenum
-  GL_TRANSFORM_FEEDBACK_PAUSED* = 0x8E23.GLenum
-  GL_ALPHA8* = 0x803C.GLenum
-  GL_STENCIL_FAIL* = 0x0B94.GLenum
-  GL_PACK_SKIP_IMAGES_EXT* = 0x806B.GLenum
-  GL_FOG_COORDINATE_ARRAY_TYPE_EXT* = 0x8454.GLenum
-  GL_RESCALE_NORMAL_EXT* = 0x803A.GLenum
-  GL_LERP_ATI* = 0x8969.GLenum
-  GL_MATRIX_INDEX_ARRAY_STRIDE_ARB* = 0x8848.GLenum
-  GL_PROGRAM_LENGTH_NV* = 0x8627.GLenum
-  GL_UNSIGNED_INT_SAMPLER_3D_EXT* = 0x8DD3.GLenum
-  GL_COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT* = 0x8DBE.GLenum
-  GL_UNSIGNED_INT_24_8_NV* = 0x84FA.GLenum
-  GL_POINT_SIZE_MIN_ARB* = 0x8126.GLenum
-  GL_COMP_BIT_ATI* = 0x00000002.GLbitfield
-  GL_NORMAL_ARRAY_ADDRESS_NV* = 0x8F22.GLenum
-  GL_TEXTURE9_ARB* = 0x84C9.GLenum
-  GL_MAX_GEOMETRY_OUTPUT_COMPONENTS* = 0x9124.GLenum
-  GL_DOUBLEBUFFER* = 0x0C32.GLenum
-  GL_OFFSET_TEXTURE_2D_BIAS_NV* = 0x86E3.GLenum
-  GL_ACTIVE_PROGRAM_EXT* = 0x8B8D.GLenum
-  GL_PARTIAL_SUCCESS_NV* = 0x902E.GLenum
-  GL_SUBTRACT* = 0x84E7.GLenum
-  GL_DUAL_INTENSITY4_SGIS* = 0x8118.GLenum
-  GL_FILL* = 0x1B02.GLenum
-  GL_COMPRESSED_SRGB_ALPHA* = 0x8C49.GLenum
-  GL_RENDERBUFFER_OES* = 0x8D41.GLenum
-  GL_PIXEL_MAP_R_TO_R_SIZE* = 0x0CB6.GLenum
-  GL_TEXTURE_LUMINANCE_TYPE_ARB* = 0x8C14.GLenum
-  GL_TEXTURE_BUFFER_FORMAT_EXT* = 0x8C2E.GLenum
-  GL_OUTPUT_TEXTURE_COORD13_EXT* = 0x87AA.GLenum
-  GL_LINES_ADJACENCY_ARB* = 0x000A.GLenum
-  GL_MAX_PROGRAM_SUBROUTINE_PARAMETERS_NV* = 0x8F44.GLenum
-  GL_INTENSITY32UI_EXT* = 0x8D73.GLenum
-  GL_PACK_IMAGE_HEIGHT* = 0x806C.GLenum
-  GL_HI_BIAS_NV* = 0x8714.GLenum
-  GL_DEBUG_TYPE_UNDEFINED_BEHAVIOR_ARB* = 0x824E.GLenum
-  GL_LINE_STIPPLE* = 0x0B24.GLenum
-  GL_INDEX_LOGIC_OP* = 0x0BF1.GLenum
-  GL_CON_18_ATI* = 0x8953.GLenum
-  GL_QUERY_RESULT* = 0x8866.GLenum
-  GL_FRAGMENT_PROGRAM_NV* = 0x8870.GLenum
-  GL_MATRIX1_NV* = 0x8631.GLenum
-  GL_FUNC_SUBTRACT_OES* = 0x800A.GLenum
-  GL_PIXEL_MAP_I_TO_A_SIZE* = 0x0CB5.GLenum
-  GL_UNSIGNED_SHORT_4_4_4_4_REV_EXT* = 0x8365.GLenum
-  GL_OUTPUT_TEXTURE_COORD20_EXT* = 0x87B1.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_BARRIER_BIT_EXT* = 0x00000001.GLbitfield
-  GL_TRIANGULAR_NV* = 0x90A5.GLenum
-  GL_TEXTURE_COMPARE_MODE_EXT* = 0x884C.GLenum
-  GL_SECONDARY_COLOR_ARRAY_SIZE_EXT* = 0x845A.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_LAYERED_EXT* = 0x8DA7.GLenum
-  GL_COMPRESSED_RGBA_S3TC_DXT5_ANGLE* = 0x83F3.GLenum
-  GL_MAX_COMPUTE_VARIABLE_GROUP_SIZE_ARB* = 0x9345.GLenum
-  GL_TEXTURE_COORD_ARRAY_BUFFER_BINDING_ARB* = 0x889A.GLenum
-  GL_PROGRAM_FORMAT_ARB* = 0x8876.GLenum
-  GL_QUAD_INTENSITY4_SGIS* = 0x8122.GLenum
-  GL_REPLICATE_BORDER* = 0x8153.GLenum
-  GL_PN_TRIANGLES_ATI* = 0x87F0.GLenum
-  GL_DEPTH_TEXTURE_MODE* = 0x884B.GLenum
-  GL_VARIABLE_C_NV* = 0x8525.GLenum
-  GL_CLIP_PLANE0_IMG* = 0x3000.GLenum
-  GL_FRONT_LEFT* = 0x0400.GLenum
-  GL_MATRIX3_ARB* = 0x88C3.GLenum
-  GL_BLEND_EQUATION_ALPHA_EXT* = 0x883D.GLenum
-  GL_BGRA8_EXT* = 0x93A1.GLenum
-  GL_INTERLACE_READ_INGR* = 0x8568.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_ACTIVE* = 0x8E24.GLenum
-  GL_MAP1_VERTEX_ATTRIB13_4_NV* = 0x866D.GLenum
-  GL_PIXEL_TEX_GEN_Q_FLOOR_SGIX* = 0x8186.GLenum
-  GL_UNSIGNED_INT_SAMPLER_2D_ARRAY* = 0x8DD7.GLenum
-  GL_ALL_SHADER_BITS_EXT* = 0xFFFFFFFF.GLbitfield
-  GL_ONE_MINUS_SRC1_ALPHA* = 0x88FB.GLenum
-  GL_VERTEX_ARRAY_RANGE_LENGTH_APPLE* = 0x851E.GLenum
-  GL_PROXY_COLOR_TABLE_SGI* = 0x80D3.GLenum
-  GL_MAX_RENDERBUFFER_SIZE_OES* = 0x84E8.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_ENABLED* = 0x8622.GLenum
-  GL_TEXTURE_BINDING_2D_MULTISAMPLE* = 0x9104.GLenum
-  GL_STENCIL_BUFFER_BIT0_QCOM* = 0x00010000.GLbitfield
-  GL_IMAGE_BINDING_FORMAT_EXT* = 0x906E.GLenum
-  GL_RENDERBUFFER_SAMPLES_NV* = 0x8CAB.GLenum
-  GL_ACCUM_GREEN_BITS* = 0x0D59.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_COMPUTE_SHADER* = 0x90ED.GLenum
-  GL_FRAMEBUFFER_UNDEFINED* = 0x8219.GLenum
-  GL_OFFSET_TEXTURE_2D_NV* = 0x86E8.GLenum
-  GL_POST_CONVOLUTION_RED_BIAS* = 0x8020.GLenum
-  GL_DRAW_BUFFER8* = 0x882D.GLenum
-  GL_MAP_INVALIDATE_RANGE_BIT* = 0x0004.GLbitfield
-  GL_ALWAYS* = 0x0207.GLenum
-  GL_ALPHA_MIN_SGIX* = 0x8320.GLenum
-  GL_SOURCE0_RGB_ARB* = 0x8580.GLenum
-  GL_POINT_SIZE_ARRAY_POINTER_OES* = 0x898C.GLenum
-  GL_CUBIC_EXT* = 0x8334.GLenum
-  GL_MAP2_NORMAL* = 0x0DB2.GLenum
-  GL_TEXTURE_RESIDENT_EXT* = 0x8067.GLenum
-  GL_TEXTURE_BUFFER_DATA_STORE_BINDING_ARB* = 0x8C2D.GLenum
-  GL_BUMP_NUM_TEX_UNITS_ATI* = 0x8777.GLenum
-  GL_TEXTURE_LOD_BIAS_T_SGIX* = 0x818F.GLenum
-  GL_FONT_UNDERLINE_POSITION_BIT_NV* = 0x04000000.GLbitfield
-  GL_NORMAL_ARRAY_STRIDE* = 0x807F.GLenum
-  GL_CONDITION_SATISFIED_APPLE* = 0x911C.GLenum
-  GL_POINT_SIZE_MIN* = 0x8126.GLenum
-  GL_SPARE0_PLUS_SECONDARY_COLOR_NV* = 0x8532.GLenum
-  GL_LAYOUT_DEFAULT_INTEL* = 0.GLenum
-  GL_FRAMEBUFFER_BINDING* = 0x8CA6.GLenum
-  GL_HIGH_FLOAT* = 0x8DF2.GLenum
-  GL_NO_RESET_NOTIFICATION_ARB* = 0x8261.GLenum
-  GL_OFFSET_TEXTURE_RECTANGLE_SCALE_NV* = 0x864D.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_ADDRESS_NV* = 0x8F20.GLenum
-  GL_VIEW_CLASS_96_BITS* = 0x82C5.GLenum
-  GL_BACK_RIGHT* = 0x0403.GLenum
-  GL_BLEND_EQUATION_ALPHA* = 0x883D.GLenum
-  GL_DISTANCE_ATTENUATION_SGIS* = 0x8129.GLenum
-  GL_PROXY_TEXTURE_CUBE_MAP_ARRAY* = 0x900B.GLenum
-  GL_RG16* = 0x822C.GLenum
-  GL_UNDEFINED_VERTEX* = 0x8260.GLenum
-  GL_PATH_DASH_OFFSET_NV* = 0x907E.GLenum
-  GL_ALL_ATTRIB_BITS* = 0xFFFFFFFF.GLbitfield
-  GL_VERTEX_ATTRIB_MAP1_ORDER_APPLE* = 0x8A04.GLenum
-  GL_MAX_COLOR_MATRIX_STACK_DEPTH_SGI* = 0x80B3.GLenum
-  GL_TIME_ELAPSED_EXT* = 0x88BF.GLenum
-  GL_MAP2_VERTEX_3* = 0x0DB7.GLenum
-  GL_MAX_PROGRAM_RESULT_COMPONENTS_NV* = 0x8909.GLenum
-  GL_SAMPLER_2D_RECT_SHADOW_ARB* = 0x8B64.GLenum
-  GL_REFERENCE_PLANE_SGIX* = 0x817D.GLenum
-  GL_LUMINANCE4_ALPHA4_EXT* = 0x8043.GLenum
-  GL_PATH_FILL_MASK_NV* = 0x9081.GLenum
-  GL_FILTER* = 0x829A.GLenum
-  GL_INT_SAMPLER_2D_ARRAY* = 0x8DCF.GLenum
-  GL_MAX_PROGRAM_ATTRIB_COMPONENTS_NV* = 0x8908.GLenum
-  GL_EVAL_VERTEX_ATTRIB2_NV* = 0x86C8.GLenum
-  GL_NAND* = 0x150E.GLenum
-  GL_BLEND_SRC_RGB* = 0x80C9.GLenum
-  GL_OPERAND2_ALPHA_EXT* = 0x859A.GLenum
-  GL_IMAGE_1D_EXT* = 0x904C.GLenum
-  GL_CONVOLUTION_FILTER_SCALE* = 0x8014.GLenum
-  GL_IMAGE_CLASS_2_X_16* = 0x82BD.GLenum
-  GL_VIEW_CLASS_BPTC_FLOAT* = 0x82D3.GLenum
-  GL_PROGRAM_INPUT* = 0x92E3.GLenum
-  GL_1PASS_SGIS* = 0x80A1.GLenum
-  GL_FOG_DISTANCE_MODE_NV* = 0x855A.GLenum
-  GL_STENCIL_INDEX16_EXT* = 0x8D49.GLenum
-  GL_POST_CONVOLUTION_RED_BIAS_EXT* = 0x8020.GLenum
-  GL_PIXEL_MAP_R_TO_R* = 0x0C76.GLenum
-  GL_3DC_XY_AMD* = 0x87FA.GLenum
-  GL_POINT_SIZE_MAX* = 0x8127.GLenum
-  GL_DOUBLE_MAT3x2* = 0x8F4B.GLenum
-  GL_DOUBLE_MAT4x2_EXT* = 0x8F4D.GLenum
-  GL_TEXTURE_HI_SIZE_NV* = 0x871B.GLenum
-  GL_MATRIX4_NV* = 0x8634.GLenum
-  GL_SPRITE_TRANSLATION_SGIX* = 0x814B.GLenum
-  GL_TEXTURE_FILTER_CONTROL_EXT* = 0x8500.GLenum
-  GL_SMOOTH_LINE_WIDTH_GRANULARITY* = 0x0B23.GLenum
-  GL_TEXTURE_BINDING_BUFFER* = 0x8C2C.GLenum
-  GL_INTENSITY4* = 0x804A.GLenum
-  GL_MAX_IMAGE_SAMPLES_EXT* = 0x906D.GLenum
-  GL_COLOR_ATTACHMENT12* = 0x8CEC.GLenum
-  GL_CLAMP_READ_COLOR* = 0x891C.GLenum
-  GL_ELEMENT_ARRAY_BUFFER_ARB* = 0x8893.GLenum
-  GL_MAP2_VERTEX_ATTRIB6_4_NV* = 0x8676.GLenum
-  GL_CONVOLUTION_HEIGHT_EXT* = 0x8019.GLenum
-  GL_SGX_PROGRAM_BINARY_IMG* = 0x9130.GLenum
-  GL_MAP1_TEXTURE_COORD_1* = 0x0D93.GLenum
-  GL_COMPRESSED_RGBA_ASTC_6x6_KHR* = 0x93B4.GLenum
-  GL_TEXTURE_APPLICATION_MODE_EXT* = 0x834F.GLenum
-  GL_TEXTURE_GATHER* = 0x82A2.GLenum
-  GL_MAX_COMBINED_SHADER_STORAGE_BLOCKS* = 0x90DC.GLenum
-  GL_DEBUG_LOGGED_MESSAGES_KHR* = 0x9145.GLenum
-  GL_TEXTURE_VIEW_NUM_LEVELS* = 0x82DC.GLenum
-  GL_ENABLE_BIT* = 0x00002000.GLbitfield
-  GL_VERTEX_PROGRAM_TWO_SIDE_ARB* = 0x8643.GLenum
-  GL_INDEX_TEST_EXT* = 0x81B5.GLenum
-  GL_TEXTURE_WRAP_R* = 0x8072.GLenum
-  GL_MAX* = 0x8008.GLenum
-  GL_UNPACK_IMAGE_DEPTH_SGIS* = 0x8133.GLenum
-  GL_COLOR_ATTACHMENT13_NV* = 0x8CED.GLenum
-  GL_FOG_BIT* = 0x00000080.GLbitfield
-  GL_GEOMETRY_SHADER_EXT* = 0x8DD9.GLenum
-  GL_ALPHA_TEST_FUNC_QCOM* = 0x0BC1.GLenum
-  GL_DRAW_BUFFER10_EXT* = 0x882F.GLenum
-  GL_MAX_PROGRAM_NATIVE_TEX_INSTRUCTIONS_ARB* = 0x880F.GLenum
-  GL_STENCIL_BACK_REF* = 0x8CA3.GLenum
-  GL_SAMPLER_1D_ARB* = 0x8B5D.GLenum
-  GL_DRAW_BUFFER* = 0x0C01.GLenum
-  GL_CLIENT_PIXEL_STORE_BIT* = 0x00000001.GLbitfield
-  GL_TEXTURE_STENCIL_SIZE* = 0x88F1.GLenum
-  GL_ELEMENT_ARRAY_APPLE* = 0x8A0C.GLenum
-  GL_CON_21_ATI* = 0x8956.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_VERTEX_SHADER* = 0x92C7.GLenum
-  GL_PIXEL_MAP_I_TO_B* = 0x0C74.GLenum
-  GL_VERTEX_ATTRIB_MAP1_COEFF_APPLE* = 0x8A03.GLenum
-  GL_FOG_INDEX* = 0x0B61.GLenum
-  GL_PROXY_POST_CONVOLUTION_COLOR_TABLE_SGI* = 0x80D4.GLenum
-  GL_OUTPUT_TEXTURE_COORD29_EXT* = 0x87BA.GLenum
-  GL_TESS_CONTROL_SUBROUTINE* = 0x92E9.GLenum
-  GL_IMAGE_CUBE_MAP_ARRAY* = 0x9054.GLenum
-  GL_RGB_FLOAT32_ATI* = 0x8815.GLenum
-  GL_OBJECT_SHADER_SOURCE_LENGTH_ARB* = 0x8B88.GLenum
-  GL_COLOR_INDEX4_EXT* = 0x80E4.GLenum
-  GL_DRAW_BUFFER14* = 0x8833.GLenum
-  GL_PATH_STENCIL_DEPTH_OFFSET_UNITS_NV* = 0x90BE.GLenum
-  GL_NATIVE_GRAPHICS_HANDLE_PGI* = 0x1A202.GLenum
-  GL_UNSIGNED_SHORT_5_6_5* = 0x8363.GLenum
-  GL_GREATER* = 0x0204.GLenum
-  GL_DATA_BUFFER_AMD* = 0x9151.GLenum
-  GL_GLYPH_VERTICAL_BEARING_Y_BIT_NV* = 0x40.GLbitfield
-  GL_COMPRESSED_RGB8_PUNCHTHROUGH_ALPHA1_ETC2* = 0x9276.GLenum
-  GL_RELATIVE_MOVE_TO_NV* = 0x03.GLenum
-  GL_BLUE_INTEGER* = 0x8D96.GLenum
-  GL_BLUE_BIAS* = 0x0D1B.GLenum
-  GL_SHADER_TYPE* = 0x8B4F.GLenum
-  GL_TRANSFORM_FEEDBACK_BINDING* = 0x8E25.GLenum
-  GL_TEXTURE17_ARB* = 0x84D1.GLenum
-  GL_GREEN* = 0x1904.GLenum
-  GL_MAX_TESS_CONTROL_UNIFORM_BLOCKS* = 0x8E89.GLenum
-  GL_DRAW_BUFFER6* = 0x882B.GLenum
-  GL_VALIDATE_STATUS* = 0x8B83.GLenum
-  GL_TEXTURE_COORD_ARRAY_ADDRESS_NV* = 0x8F25.GLenum
-  GL_MVP_MATRIX_EXT* = 0x87E3.GLenum
-  GL_PIXEL_BUFFER_BARRIER_BIT_EXT* = 0x00000080.GLbitfield
-  GL_MAX_VERTEX_VARYING_COMPONENTS_EXT* = 0x8DDE.GLenum
-  GL_STACK_OVERFLOW_KHR* = 0x0503.GLenum
-  GL_MAX_PROJECTION_STACK_DEPTH* = 0x0D38.GLenum
-  GL_SKIP_COMPONENTS3_NV* = -4
-  GL_DEBUG_ASSERT_MESA* = 0x875B.GLenum
-  GL_INSTRUMENT_BUFFER_POINTER_SGIX* = 0x8180.GLenum
-  GL_SAMPLE_ALPHA_TO_MASK_EXT* = 0x809E.GLenum
-  GL_REG_29_ATI* = 0x893E.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_NV* = 0x8C4E.GLenum
-  GL_DEBUG_CATEGORY_DEPRECATION_AMD* = 0x914B.GLenum
-  GL_DEPTH_STENCIL_TO_BGRA_NV* = 0x886F.GLenum
-  GL_UNSIGNED_INT_VEC3_EXT* = 0x8DC7.GLenum
-  GL_VERTEX_SHADER_EXT* = 0x8780.GLenum
-  GL_LIST_BASE* = 0x0B32.GLenum
-  GL_TEXTURE_STENCIL_SIZE_EXT* = 0x88F1.GLenum
-  GL_ACTIVE_PROGRAM* = 0x8259.GLenum
-  GL_RGBA_SIGNED_COMPONENTS_EXT* = 0x8C3C.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR* = 0x93DC.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE* = 0x8CD0.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_STENCIL_SIZE* = 0x8217.GLenum
-  GL_MATRIX7_ARB* = 0x88C7.GLenum
-  GL_FLOAT_VEC3_ARB* = 0x8B51.GLenum
-  GL_PACK_ROW_BYTES_APPLE* = 0x8A15.GLenum
-  GL_PIXEL_TILE_GRID_HEIGHT_SGIX* = 0x8143.GLenum
-  GL_UNIFORM_BLOCK* = 0x92E2.GLenum
-  GL_VIEWPORT_BIT* = 0x00000800.GLbitfield
-  GL_RENDERBUFFER_COVERAGE_SAMPLES_NV* = 0x8CAB.GLenum
-  GL_MAP1_BINORMAL_EXT* = 0x8446.GLenum
-  GL_SAMPLER_3D* = 0x8B5F.GLenum
-  GL_RENDERBUFFER_SAMPLES_APPLE* = 0x8CAB.GLenum
-  GL_DEPTH_WRITEMASK* = 0x0B72.GLenum
-  GL_MAP2_VERTEX_ATTRIB9_4_NV* = 0x8679.GLenum
-  GL_TEXTURE_COMPARE_FUNC* = 0x884D.GLenum
-  GL_CONTEXT_FLAG_ROBUST_ACCESS_BIT_ARB* = 0x00000004.GLbitfield
-  GL_READ_BUFFER* = 0x0C02.GLenum
-  GL_ONE_MINUS_SRC1_COLOR* = 0x88FA.GLenum
-  GL_PROGRAM_FORMAT_ASCII_ARB* = 0x8875.GLenum
-  GL_DRAW_FRAMEBUFFER_APPLE* = 0x8CA9.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_TYPE_OES* = 0x8CD0.GLenum
-  GL_BLEND_DST* = 0x0BE0.GLenum
-  GL_SHADER_OBJECT_EXT* = 0x8B48.GLenum
-  GL_UNSIGNALED* = 0x9118.GLenum
-  GL_VERTEX4_BIT_PGI* = 0x00000008.GLbitfield
-  GL_DRAW_FRAMEBUFFER_BINDING_APPLE* = 0x8CA6.GLenum
-  GL_IMAGE_CUBE_EXT* = 0x9050.GLenum
-  GL_CONTEXT_ROBUST_ACCESS_EXT* = 0x90F3.GLenum
-  GL_TEXTURE14_ARB* = 0x84CE.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_Y* = 0x8517.GLenum
-  GL_OFFSET_HILO_PROJECTIVE_TEXTURE_RECTANGLE_NV* = 0x8857.GLenum
-  GL_COMPRESSED_RG11_EAC_OES* = 0x9272.GLenum
-  GL_OP_DOT4_EXT* = 0x8785.GLenum
-  GL_FRAMEBUFFER_COMPLETE_EXT* = 0x8CD5.GLenum
-  GL_TEXTURE_COMPARE_FUNC_ARB* = 0x884D.GLenum
-  GL_TEXTURE_FILTER4_SIZE_SGIS* = 0x8147.GLenum
-  GL_ELEMENT_ARRAY_BUFFER_BINDING* = 0x8895.GLenum
-  GL_UNSIGNED_INT_IMAGE_BUFFER_EXT* = 0x9067.GLenum
-  GL_IMAGE_1D_ARRAY_EXT* = 0x9052.GLenum
-  GL_CLAMP_READ_COLOR_ARB* = 0x891C.GLenum
-  GL_COMPUTE_SUBROUTINE* = 0x92ED.GLenum
-  GL_R3_G3_B2* = 0x2A10.GLenum
-  GL_PATH_DASH_ARRAY_COUNT_NV* = 0x909F.GLenum
-  GL_SPOT_EXPONENT* = 0x1205.GLenum
-  GL_NUM_PROGRAM_BINARY_FORMATS_OES* = 0x87FE.GLenum
-  GL_SWIZZLE_STQ_ATI* = 0x8977.GLenum
-  GL_SYNC_FLUSH_COMMANDS_BIT_APPLE* = 0x00000001.GLbitfield
-  GL_VERTEX_STREAM6_ATI* = 0x8772.GLenum
-  GL_FRAGMENT_COLOR_MATERIAL_SGIX* = 0x8401.GLenum
-  GL_DYNAMIC_ATI* = 0x8761.GLenum
-  GL_SUB_ATI* = 0x8965.GLenum
-  GL_PREVIOUS_EXT* = 0x8578.GLenum
-  GL_MAP2_TEXTURE_COORD_1* = 0x0DB3.GLenum
-  GL_COLOR_SAMPLES_NV* = 0x8E20.GLenum
-  GL_HILO_NV* = 0x86F4.GLenum
-  GL_SHADER_STORAGE_BUFFER_BINDING* = 0x90D3.GLenum
-  GL_DUP_LAST_CUBIC_CURVE_TO_NV* = 0xF4.GLenum
-  GL_ACTIVE_SUBROUTINES* = 0x8DE5.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE_IMG* = 0x9134.GLenum
-  GL_INTENSITY16* = 0x804D.GLenum
-  GL_MAX_PROGRAM_NATIVE_ATTRIBS_ARB* = 0x88AF.GLenum
-  GL_TIMESTAMP_EXT* = 0x8E28.GLenum
-  GL_CLIENT_ACTIVE_TEXTURE* = 0x84E1.GLenum
-  GL_TEXTURE_BINDING_2D_ARRAY* = 0x8C1D.GLenum
-  GL_INT_SAMPLER_2D_RECT_EXT* = 0x8DCD.GLenum
-  GL_PREFER_DOUBLEBUFFER_HINT_PGI* = 0x1A1F8.GLenum
-  GL_TEXTURE_WIDTH* = 0x1000.GLenum
-  GL_CPU_OPTIMIZED_QCOM* = 0x8FB1.GLenum
-  GL_TEXTURE_IMAGE_TYPE* = 0x8290.GLenum
-  GL_MAX_VERTEX_UNIFORM_VECTORS* = 0x8DFB.GLenum
-  GL_MODULATE_SUBTRACT_ATI* = 0x8746.GLenum
-  GL_SYNC_STATUS* = 0x9114.GLenum
-  GL_IMAGE_2D_RECT_EXT* = 0x904F.GLenum
-  GL_MATRIX6_NV* = 0x8636.GLenum
-  GL_SOURCE1_RGB_ARB* = 0x8581.GLenum
-  GL_MAX_COMBINED_ATOMIC_COUNTERS* = 0x92D7.GLenum
-  GL_MAX_COMPUTE_LOCAL_INVOCATIONS* = 0x90EB.GLenum
-  GL_SAMPLER_CUBE* = 0x8B60.GLenum
-  GL_ALPHA_FLOAT32_ATI* = 0x8816.GLenum
-  GL_COMPRESSED_LUMINANCE_ARB* = 0x84EA.GLenum
-  GL_COMPRESSED_RGB8_ETC2_OES* = 0x9274.GLenum
-  GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_KHR* = 0x8243.GLenum
-  GL_MINUS_CLAMPED_NV* = 0x92B3.GLenum
-  GL_REG_31_ATI* = 0x8940.GLenum
-  GL_ELEMENT_ARRAY_ADDRESS_NV* = 0x8F29.GLenum
-  GL_SRC1_COLOR* = 0x88F9.GLenum
-  GL_DEBUG_SEVERITY_LOW_ARB* = 0x9148.GLenum
-  GL_CON_3_ATI* = 0x8944.GLenum
-  GL_R32I* = 0x8235.GLenum
-  GL_BLEND_COLOR* = 0x8005.GLenum
-  GL_CLIP_PLANE4* = 0x3004.GLenum
-  GL_CONTEXT_FLAG_FORWARD_COMPATIBLE_BIT* = 0x00000001.GLbitfield
-  GL_FLOAT16_VEC4_NV* = 0x8FFB.GLenum
-  GL_DST_IN_NV* = 0x928B.GLenum
-  GL_VIRTUAL_PAGE_SIZE_Y_ARB* = 0x9196.GLenum
-  GL_COLOR_ATTACHMENT8_NV* = 0x8CE8.GLenum
-  GL_TESS_GEN_VERTEX_ORDER* = 0x8E78.GLenum
-  GL_LOSE_CONTEXT_ON_RESET_EXT* = 0x8252.GLenum
-  GL_PROGRAM_INSTRUCTIONS_ARB* = 0x88A0.GLenum
-  GL_TEXTURE_IMAGE_VALID_QCOM* = 0x8BD8.GLenum
-  GL_SAMPLE_MASK_VALUE_EXT* = 0x80AA.GLenum
-  GL_CURRENT_MATRIX_ARB* = 0x8641.GLenum
-  GL_DECR_WRAP_EXT* = 0x8508.GLenum
-  GL_BLUE_INTEGER_EXT* = 0x8D96.GLenum
-  GL_COMPRESSED_RG* = 0x8226.GLenum
-  GL_MAX_PROGRAM_EXEC_INSTRUCTIONS_NV* = 0x88F4.GLenum
-  GL_MINMAX_EXT* = 0x802E.GLenum
-  GL_FLOAT_MAT4_ARB* = 0x8B5C.GLenum
-  GL_TEXTURE_CLIPMAP_FRAME_SGIX* = 0x8172.GLenum
-  GL_PIXEL_UNPACK_BUFFER_EXT* = 0x88EC.GLenum
-  GL_TEXTURE5_ARB* = 0x84C5.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_RECT* = 0x9065.GLenum
-  GL_MAX_COMPUTE_TEXTURE_IMAGE_UNITS* = 0x91BC.GLenum
-  GL_DEPTH_COMPONENT* = 0x1902.GLenum
-  GL_RG32F_EXT* = 0x8230.GLenum
-  GL_FACTOR_ALPHA_MODULATE_IMG* = 0x8C07.GLenum
-  GL_VERTEX_ARRAY_TYPE_EXT* = 0x807B.GLenum
-  GL_DS_BIAS_NV* = 0x8716.GLenum
-  GL_NATIVE_GRAPHICS_BEGIN_HINT_PGI* = 0x1A203.GLenum
-  GL_ALPHA16UI_EXT* = 0x8D78.GLenum
-  GL_DOUBLE_VEC2* = 0x8FFC.GLenum
-  GL_MAP1_VERTEX_ATTRIB12_4_NV* = 0x866C.GLenum
-  GL_4D_COLOR_TEXTURE* = 0x0604.GLenum
-  GL_MAX_VERTEX_SHADER_STORAGE_BLOCKS* = 0x90D6.GLenum
-  GL_SPECULAR* = 0x1202.GLenum
-  GL_TOP_LEVEL_ARRAY_SIZE* = 0x930C.GLenum
-  GL_MAX_SPARSE_ARRAY_TEXTURE_LAYERS_ARB* = 0x919A.GLenum
-  GL_COVERAGE_SAMPLES_NV* = 0x8ED4.GLenum
-  GL_SIGNALED_APPLE* = 0x9119.GLenum
-  GL_DEBUG_TYPE_DEPRECATED_BEHAVIOR_KHR* = 0x824D.GLenum
-  GL_BUFFER_KHR* = 0x82E0.GLenum
-  GL_GEOMETRY_TEXTURE* = 0x829E.GLenum
-  GL_MIN_PROGRAM_TEXTURE_GATHER_OFFSET_NV* = 0x8E5E.GLenum
-  GL_EVAL_VERTEX_ATTRIB7_NV* = 0x86CD.GLenum
-  GL_GLYPH_VERTICAL_BEARING_ADVANCE_BIT_NV* = 0x80.GLbitfield
-  GL_BINORMAL_ARRAY_POINTER_EXT* = 0x8443.GLenum
-  GL_AUX3* = 0x040C.GLenum
-  GL_MULTISAMPLE_BIT_EXT* = 0x20000000.GLbitfield
-  GL_COLOR_TABLE_FORMAT_SGI* = 0x80D8.GLenum
-  GL_VERTEX_PROGRAM_POINT_SIZE* = 0x8642.GLenum
-  GL_LINE_WIDTH_GRANULARITY* = 0x0B23.GLenum
-  GL_MAX_VERTEX_ATTRIB_BINDINGS* = 0x82DA.GLenum
-  GL_TEXTURE_BINDING_2D_ARRAY_EXT* = 0x8C1D.GLenum
-  GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_TEST* = 0x82AC.GLenum
-  GL_SCALE_BY_FOUR_NV* = 0x853F.GLenum
-  GL_VIRTUAL_PAGE_SIZE_Z_AMD* = 0x9197.GLenum
-  GL_TEXTURE16* = 0x84D0.GLenum
-  GL_DSDT8_MAG8_NV* = 0x870A.GLenum
-  GL_OP_FLOOR_EXT* = 0x878F.GLenum
-  GL_MAX_PROGRAM_IF_DEPTH_NV* = 0x88F6.GLenum
-  GL_VERTEX_ARRAY_LIST_IBM* = 103070.GLenum
-  GL_COMPRESSED_SIGNED_RED_RGTC1* = 0x8DBC.GLenum
-  GL_CUBIC_CURVE_TO_NV* = 0x0C.GLenum
-  GL_PROXY_POST_CONVOLUTION_COLOR_TABLE* = 0x80D4.GLenum
-  GL_SIGNED_IDENTITY_NV* = 0x853C.GLenum
-  GL_EVAL_VERTEX_ATTRIB6_NV* = 0x86CC.GLenum
-  GL_MODELVIEW10_ARB* = 0x872A.GLenum
-  GL_MULTISAMPLE_3DFX* = 0x86B2.GLenum
-  GL_COMPRESSED_RGB_PVRTC_4BPPV1_IMG* = 0x8C00.GLenum
-  GL_DSDT_MAG_VIB_NV* = 0x86F7.GLenum
-  GL_TEXCOORD4_BIT_PGI* = 0x80000000.GLbitfield
-  GL_TRANSFORM_FEEDBACK_BARRIER_BIT* = 0x00000800.GLbitfield
-  GL_EVAL_VERTEX_ATTRIB10_NV* = 0x86D0.GLenum
-  GL_DRAW_BUFFER13_ARB* = 0x8832.GLenum
-  GL_RENDERBUFFER_STENCIL_SIZE_OES* = 0x8D55.GLenum
-  GL_INTENSITY8I_EXT* = 0x8D91.GLenum
-  GL_STENCIL_BACK_PASS_DEPTH_FAIL* = 0x8802.GLenum
-  GL_INTENSITY32F_ARB* = 0x8817.GLenum
-  GL_CURRENT_ATTRIB_NV* = 0x8626.GLenum
-  GL_POLYGON_BIT* = 0x00000008.GLbitfield
-  GL_COMBINE_RGB* = 0x8571.GLenum
-  GL_MAX_FRAMEBUFFER_HEIGHT* = 0x9316.GLenum
-  GL_FRAMEBUFFER_BINDING_OES* = 0x8CA6.GLenum
-  GL_TEXTURE_GREEN_TYPE* = 0x8C11.GLenum
-  GL_LINE_TO_NV* = 0x04.GLenum
-  GL_FUNC_ADD_EXT* = 0x8006.GLenum
-  GL_TEXTURE_LOD_BIAS* = 0x8501.GLenum
-  GL_QUAD_INTENSITY8_SGIS* = 0x8123.GLenum
-  GL_SECONDARY_COLOR_ARRAY_EXT* = 0x845E.GLenum
-  GL_UNPACK_COMPRESSED_SIZE_SGIX* = 0x831A.GLenum
-  GL_RGBA_INTEGER* = 0x8D99.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_SIZE* = 0x92C3.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_MULTISAMPLE* = 0x8D56.GLenum
-  GL_OBJECT_DISTANCE_TO_LINE_SGIS* = 0x81F3.GLenum
-  GL_DEPTH_BUFFER_BIT3_QCOM* = 0x00000800.GLbitfield
-  GL_RGB16_SNORM* = 0x8F9A.GLenum
-  GL_MATRIX_INDEX_ARRAY_TYPE_ARB* = 0x8847.GLenum
-  GL_TRANSLATE_X_NV* = 0x908E.GLenum
-  GL_BUFFER_ACCESS_FLAGS* = 0x911F.GLenum
-  GL_IS_PER_PATCH* = 0x92E7.GLenum
-  GL_PATH_GEN_MODE_NV* = 0x90B0.GLenum
-  GL_ALPHA_MIN_CLAMP_INGR* = 0x8563.GLenum
-  GL_LUMINANCE_ALPHA32I_EXT* = 0x8D87.GLenum
-  GL_BUFFER_USAGE_ARB* = 0x8765.GLenum
-  GL_POINT_SIZE* = 0x0B11.GLenum
-  GL_INVARIANT_EXT* = 0x87C2.GLenum
-  GL_IMAGE_BINDING_NAME* = 0x8F3A.GLenum
-  GL_BLEND_SRC_ALPHA* = 0x80CB.GLenum
-  GL_OUTPUT_TEXTURE_COORD23_EXT* = 0x87B4.GLenum
-  GL_EYE_PLANE* = 0x2502.GLenum
-  GL_BOOL_VEC4_ARB* = 0x8B59.GLenum
-  GL_MITER_REVERT_NV* = 0x90A7.GLenum
-  GL_SYNC_X11_FENCE_EXT* = 0x90E1.GLenum
-  GL_GEOMETRY_SHADER_INVOCATIONS* = 0x887F.GLenum
-  GL_DRAW_BUFFER5_ATI* = 0x882A.GLenum
-  GL_FOG_COORDINATE_ARRAY_BUFFER_BINDING_ARB* = 0x889D.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE_EXT* = 0x906B.GLenum
-  GL_PIXEL_TEX_GEN_Q_ROUND_SGIX* = 0x8185.GLenum
-  GL_DOUBLE_MAT3x2_EXT* = 0x8F4B.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB* = 0x8516.GLenum
-  GL_MOV_ATI* = 0x8961.GLenum
-  GL_COLOR4_BIT_PGI* = 0x00020000.GLbitfield
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR* = 0x93DD.GLenum
-  GL_DEPTH_BOUNDS_TEST_EXT* = 0x8890.GLenum
-  GL_DST_OVER_NV* = 0x9289.GLenum
-  GL_PIXEL_MAP_I_TO_I_SIZE* = 0x0CB0.GLenum
-  GL_ALPHA16F_EXT* = 0x881C.GLenum
-  GL_RENDERBUFFER_BINDING_EXT* = 0x8CA7.GLenum
-  GL_MATRIX25_ARB* = 0x88D9.GLenum
-  GL_OUTPUT_TEXTURE_COORD19_EXT* = 0x87B0.GLenum
-  GL_NORMAL_MAP* = 0x8511.GLenum
-  GL_GPU_ADDRESS_NV* = 0x8F34.GLenum
-  GL_STREAM_READ* = 0x88E1.GLenum
-  GL_MIRRORED_REPEAT* = 0x8370.GLint
-  GL_TEXTURE_SWIZZLE_RGBA* = 0x8E46.GLenum
-  GL_HALF_BIAS_NORMAL_NV* = 0x853A.GLenum
-  GL_STENCIL_BACK_OP_VALUE_AMD* = 0x874D.GLenum
-  GL_TEXTURE_BLUE_TYPE_ARB* = 0x8C12.GLenum
-  GL_MODELVIEW_PROJECTION_NV* = 0x8629.GLenum
-  GL_ACTIVE_UNIFORM_MAX_LENGTH* = 0x8B87.GLenum
-  GL_TEXTURE_SWIZZLE_RGBA_EXT* = 0x8E46.GLenum
-  GL_TEXTURE_GEN_T* = 0x0C61.GLenum
-  GL_HILO16_NV* = 0x86F8.GLenum
-  GL_CURRENT_QUERY_EXT* = 0x8865.GLenum
-  GL_FLOAT16_VEC2_NV* = 0x8FF9.GLenum
-  GL_RGBA_FLOAT_MODE_ARB* = 0x8820.GLenum
-  GL_POINT_SIZE_ARRAY_TYPE_OES* = 0x898A.GLenum
-  GL_GENERATE_MIPMAP_HINT* = 0x8192.GLenum
-  GL_1PASS_EXT* = 0x80A1.GLenum
-  GL_SWIZZLE_STQ_DQ_ATI* = 0x8979.GLenum
-  GL_VERTICAL_LINE_TO_NV* = 0x08.GLenum
-  GL_MINMAX* = 0x802E.GLenum
-  GL_RENDERBUFFER_ALPHA_SIZE_EXT* = 0x8D53.GLenum
-  GL_DEPTH_COMPONENT32F* = 0x8CAC.GLenum
-  GL_NEXT_VIDEO_CAPTURE_BUFFER_STATUS_NV* = 0x9025.GLenum
-  GL_CLIP_PLANE5_IMG* = 0x3005.GLenum
-  GL_TEXTURE_2D_MULTISAMPLE* = 0x9100.GLenum
-  GL_PREVIOUS* = 0x8578.GLenum
-  GL_CULL_MODES_NV* = 0x86E0.GLenum
-  GL_TRACE_ARRAYS_BIT_MESA* = 0x0004.GLbitfield
-  GL_MAX_ACTIVE_LIGHTS_SGIX* = 0x8405.GLenum
-  GL_PRIMITIVE_ID_NV* = 0x8C7C.GLenum
-  GL_DEPTH_COMPONENT16* = 0x81A5.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_LAYERED* = 0x8DA7.GLenum
-  GL_MAX_FRAGMENT_UNIFORM_BLOCKS* = 0x8A2D.GLenum
-  GL_OUTPUT_COLOR0_EXT* = 0x879B.GLenum
-  GL_RGBA16F_EXT* = 0x881A.GLenum
-  GL_MAX_PALETTE_MATRICES_OES* = 0x8842.GLenum
-  GL_VIEW_CLASS_64_BITS* = 0x82C6.GLenum
-  GL_TRACE_ALL_BITS_MESA* = 0xFFFF.GLbitfield
-  GL_REPLACE_VALUE_AMD* = 0x874B.GLenum
-  GL_PROXY_POST_IMAGE_TRANSFORM_COLOR_TABLE_HP* = 0x8163.GLenum
-  GL_BGR_INTEGER* = 0x8D9A.GLenum
-  GL_MAX_DEBUG_LOGGED_MESSAGES_ARB* = 0x9144.GLenum
-  GL_FOG_COLOR* = 0x0B66.GLenum
-  GL_MAX_MULTIVIEW_BUFFERS_EXT* = 0x90F2.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER* = 0x8C8E.GLenum
-  GL_E_TIMES_F_NV* = 0x8531.GLenum
-  GL_COLOR_TABLE_WIDTH_SGI* = 0x80D9.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_SIZE* = 0x8623.GLenum
-  GL_422_REV_AVERAGE_EXT* = 0x80CF.GLenum
-  GL_WRITE_DISCARD_NV* = 0x88BE.GLenum
-  GL_DRAW_BUFFER0_EXT* = 0x8825.GLenum
-  GL_FONT_HEIGHT_BIT_NV* = 0x00800000.GLbitfield
-  GL_INTERLACE_OML* = 0x8980.GLenum
-  GL_FUNC_REVERSE_SUBTRACT_EXT* = 0x800B.GLenum
-  GL_MAX_VERTEX_SHADER_LOCAL_CONSTANTS_EXT* = 0x87C8.GLenum
-  GL_PRIMARY_COLOR* = 0x8577.GLenum
-  GL_RGBA16I* = 0x8D88.GLenum
-  GL_TEXTURE6* = 0x84C6.GLenum
-  GL_PATH_FILL_BOUNDING_BOX_NV* = 0x90A1.GLenum
-  GL_WEIGHT_ARRAY_BUFFER_BINDING* = 0x889E.GLenum
-  GL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI* = 0x8835.GLenum
-  GL_YCRCB_422_SGIX* = 0x81BB.GLenum
-  GL_RGB5_A1* = 0x8057.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_COMPONENT_TYPE_EXT* = 0x8211.GLenum
-  GL_DRAW_FRAMEBUFFER_BINDING_EXT* = 0x8CA6.GLenum
-  GL_TEXTURE_1D_ARRAY* = 0x8C18.GLenum
-  GL_CLAMP_FRAGMENT_COLOR_ARB* = 0x891B.GLenum
-  GL_FULL_RANGE_EXT* = 0x87E1.GLenum
-  GL_GEOMETRY_PROGRAM_PARAMETER_BUFFER_NV* = 0x8DA3.GLenum
-  GL_CON_24_ATI* = 0x8959.GLenum
-  GL_2D* = 0x0600.GLenum
-  GL_DRAW_BUFFER5_NV* = 0x882A.GLenum
-  GL_PALETTE4_RGBA8_OES* = 0x8B91.GLenum
-  GL_READ_ONLY_ARB* = 0x88B8.GLenum
-  GL_NUM_SAMPLE_COUNTS* = 0x9380.GLenum
-  GL_MATRIX_STRIDE* = 0x92FF.GLenum
-  GL_HISTOGRAM_RED_SIZE* = 0x8028.GLenum
-  GL_COLOR_ATTACHMENT4* = 0x8CE4.GLenum
-  GL_PATH_INITIAL_END_CAP_NV* = 0x9077.GLenum
-  GL_TEXTURE_USAGE_ANGLE* = 0x93A2.GLenum
-  GL_DOUBLE_MAT2* = 0x8F46.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_RED_SIZE* = 0x8212.GLenum
-  GL_SECONDARY_COLOR_ARRAY_POINTER* = 0x845D.GLenum
-  GL_MAX_VIEWPORTS* = 0x825B.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_EXT* = 0x8C8E.GLenum
-  GL_FRAMEBUFFER_SRGB_EXT* = 0x8DB9.GLenum
-  GL_STORAGE_SHARED_APPLE* = 0x85BF.GLenum
-  GL_TRANSFORM_FEEDBACK_VARYING_MAX_LENGTH* = 0x8C76.GLenum
-  GL_TRANSFORM_FEEDBACK_NV* = 0x8E22.GLenum
-  GL_MIRRORED_REPEAT_ARB* = 0x8370.GLint
-  GL_MAX_VERTEX_OUTPUT_COMPONENTS* = 0x9122.GLenum
-  GL_BUFFER_MAP_LENGTH* = 0x9120.GLenum
-  GL_BUFFER_OBJECT_APPLE* = 0x85B3.GLenum
-  GL_INT_VEC4_ARB* = 0x8B55.GLenum
-  GL_COMBINER3_NV* = 0x8553.GLenum
-  GL_INT16_VEC3_NV* = 0x8FE6.GLenum
-  GL_MAX_3D_TEXTURE_SIZE_EXT* = 0x8073.GLenum
-  GL_GENERATE_MIPMAP_HINT_SGIS* = 0x8192.GLenum
-  GL_SRC0_ALPHA* = 0x8588.GLenum
-  GL_IMAGE_2D* = 0x904D.GLenum
-  GL_VIEW_CLASS_S3TC_DXT1_RGB* = 0x82CC.GLenum
-  GL_DOT3_RGBA* = 0x86AF.GLenum
-  GL_TEXTURE_GREEN_SIZE* = 0x805D.GLenum
-  GL_DOUBLE_MAT2x3* = 0x8F49.GLenum
-  GL_COORD_REPLACE_OES* = 0x8862.GLenum
-  GL_MAX_DEBUG_MESSAGE_LENGTH_ARB* = 0x9143.GLenum
-  GL_TEXTURE_IMMUTABLE_FORMAT_EXT* = 0x912F.GLenum
-  GL_INDEX_ARRAY_POINTER_EXT* = 0x8091.GLenum
-  GL_NUM_SHADING_LANGUAGE_VERSIONS* = 0x82E9.GLenum
-  GL_DEBUG_CALLBACK_FUNCTION_ARB* = 0x8244.GLenum
-  GL_OFFSET_TEXTURE_MATRIX_NV* = 0x86E1.GLenum
-  GL_INTENSITY32I_EXT* = 0x8D85.GLenum
-  GL_BUMP_TEX_UNITS_ATI* = 0x8778.GLenum
-  GL_RENDERBUFFER* = 0x8D41.GLenum
-  GL_UPPER_LEFT* = 0x8CA2.GLenum
-  GL_GUILTY_CONTEXT_RESET_ARB* = 0x8253.GLenum
-  GL_MAP2_GRID_SEGMENTS* = 0x0DD3.GLenum
-  GL_REG_23_ATI* = 0x8938.GLenum
-  GL_UNSIGNED_INT16_NV* = 0x8FF0.GLenum
-  GL_TEXTURE_COORD_ARRAY_LIST_STRIDE_IBM* = 103084.GLenum
-  GL_INVARIANT_VALUE_EXT* = 0x87EA.GLenum
-  GL_TRANSFORM_FEEDBACK_PRIMITIVES_WRITTEN_NV* = 0x8C88.GLenum
-  GL_TEXTURE2_ARB* = 0x84C2.GLenum
-  GL_UNSIGNED_INT_SAMPLER_2D_ARRAY_EXT* = 0x8DD7.GLenum
-  GL_IMAGE_CUBE* = 0x9050.GLenum
-  GL_MAX_PROGRAM_MATRICES_ARB* = 0x862F.GLenum
-  GL_SIGNED_LUMINANCE8_ALPHA8_NV* = 0x8704.GLenum
-  GL_INDEX_ARRAY_LIST_IBM* = 103073.GLenum
-  GL_EVAL_VERTEX_ATTRIB5_NV* = 0x86CB.GLenum
-  GL_SHADER_SOURCE_LENGTH* = 0x8B88.GLenum
-  GL_TEXTURE4* = 0x84C4.GLenum
-  GL_VERTEX_ATTRIB_ARRAY6_NV* = 0x8656.GLenum
-  GL_PROXY_TEXTURE_1D_STACK_MESAX* = 0x875B.GLenum
-  GL_MAP_ATTRIB_V_ORDER_NV* = 0x86C4.GLenum
-  GL_DSDT_NV* = 0x86F5.GLenum
-  GL_DEBUG_SEVERITY_NOTIFICATION_KHR* = 0x826B.GLenum
-  GL_FOG_COORDINATE_ARRAY_LIST_STRIDE_IBM* = 103086.GLenum
-  GL_COMPRESSED_RGBA_ASTC_8x6_KHR* = 0x93B6.GLenum
-  GL_LINEAR_ATTENUATION* = 0x1208.GLenum
-  GL_Z4Y12Z4CB12Z4Y12Z4CR12_422_NV* = 0x9035.GLenum
-  GL_CONVOLUTION_FILTER_BIAS* = 0x8015.GLenum
-  GL_IMAGE_MIN_FILTER_HP* = 0x815D.GLenum
-  GL_EYE_RADIAL_NV* = 0x855B.GLenum
-  GL_TEXTURE_MIN_LOD_SGIS* = 0x813A.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_BINDING_NV* = 0x8C8F.GLenum
-  GL_TRANSLATE_2D_NV* = 0x9090.GLenum
-  GL_CONSTANT_ARB* = 0x8576.GLenum
-  GL_FLOAT_MAT2x3* = 0x8B65.GLenum
-  GL_MULTISAMPLE_COVERAGE_MODES_NV* = 0x8E12.GLenum
-  GL_TRANSPOSE_COLOR_MATRIX* = 0x84E6.GLenum
-  GL_PROGRAM_STRING_NV* = 0x8628.GLenum
-  GL_UNSIGNED_INT_SAMPLER_1D_EXT* = 0x8DD1.GLenum
-  GL_BLEND_SRC_ALPHA_OES* = 0x80CB.GLenum
-  GL_RGB32F_EXT* = 0x8815.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_3D_ZOFFSET_EXT* = 0x8CD4.GLenum
-  GL_RESTART_PATH_NV* = 0xF0.GLenum
-  GL_MAP2_VERTEX_ATTRIB11_4_NV* = 0x867B.GLenum
-  GL_VIEW_CLASS_16_BITS* = 0x82CA.GLenum
-  GL_BUFFER_DATA_SIZE* = 0x9303.GLenum
-  GL_BUFFER_FLUSHING_UNMAP_APPLE* = 0x8A13.GLenum
-  GL_RELATIVE_VERTICAL_LINE_TO_NV* = 0x09.GLenum
-  GL_SRGB_WRITE* = 0x8298.GLenum
-  GL_TEXTURE_LUMINANCE_SIZE_EXT* = 0x8060.GLenum
-  GL_VERTEX_PRECLIP_SGIX* = 0x83EE.GLenum
-  GL_LINEAR_DETAIL_COLOR_SGIS* = 0x8099.GLenum
-  GL_SOURCE2_ALPHA_ARB* = 0x858A.GLenum
-  GL_PATH_FOG_GEN_MODE_NV* = 0x90AC.GLenum
-  GL_RGB10_A2UI* = 0x906F.GLenum
-  GL_MULTISAMPLE_BIT_3DFX* = 0x20000000.GLbitfield
-  GL_PIXEL_MAP_G_TO_G_SIZE* = 0x0CB7.GLenum
-  GL_COVERAGE_BUFFER_BIT_NV* = 0x00008000.GLbitfield
-  GL_TEXTURE_COMPRESSED* = 0x86A1.GLenum
-  GL_ATOMIC_COUNTER_BUFFER_REFERENCED_BY_GEOMETRY_SHADER* = 0x92CA.GLenum
-  GL_NAMED_STRING_TYPE_ARB* = 0x8DEA.GLenum
-  GL_RESCALE_NORMAL* = 0x803A.GLenum
-  GL_OUTPUT_TEXTURE_COORD3_EXT* = 0x87A0.GLenum
-  GL_RENDERBUFFER_EXT* = 0x8D41.GLenum
-  GL_QUERY_NO_WAIT* = 0x8E14.GLenum
-  GL_SAMPLE_ALPHA_TO_COVERAGE* = 0x809E.GLenum
-  GL_RG8UI* = 0x8238.GLenum
-  GL_MATRIX3_NV* = 0x8633.GLenum
-  GL_SAMPLE_BUFFERS_ARB* = 0x80A8.GLenum
-  GL_VERTEX_CONSISTENT_HINT_PGI* = 0x1A22B.GLenum
-  GL_SPRITE_AXIAL_SGIX* = 0x814C.GLenum
-  GL_MODELVIEW_MATRIX* = 0x0BA6.GLenum
-  GL_SAMPLE_PATTERN_SGIS* = 0x80AC.GLenum
-  GL_UNSIGNED_INT_IMAGE_2D_MULTISAMPLE* = 0x906B.GLenum
-  GL_FLOAT_RG16_NV* = 0x8886.GLenum
-  GL_IMAGE_TRANSLATE_X_HP* = 0x8157.GLenum
-  GL_FRAMEBUFFER_SRGB* = 0x8DB9.GLenum
-  GL_DRAW_BUFFER7* = 0x882C.GLenum
-  GL_CONVOLUTION_BORDER_COLOR* = 0x8154.GLenum
-  GL_DRAW_BUFFER5* = 0x882A.GLenum
-  GL_GEOMETRY_INPUT_TYPE_EXT* = 0x8DDB.GLenum
-  GL_IUI_V2F_EXT* = 0x81AD.GLenum
-  GL_FLOAT_RG_NV* = 0x8881.GLenum
-  GL_VERTEX_SHADER_INVARIANTS_EXT* = 0x87D1.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT1_NV* = 0x8C4D.GLenum
-  GL_MAX_PROGRAM_MATRIX_STACK_DEPTH_ARB* = 0x862E.GLenum
-  GL_SAMPLE_PATTERN_EXT* = 0x80AC.GLenum
-  GL_DIFFERENCE_NV* = 0x929E.GLenum
-  GL_POST_CONVOLUTION_ALPHA_BIAS_EXT* = 0x8023.GLenum
-  GL_COLOR_ATTACHMENT1_EXT* = 0x8CE1.GLenum
-  GL_TEXTURE_ALPHA_MODULATE_IMG* = 0x8C06.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_PAUSED_NV* = 0x8E23.GLenum
-  GL_MAX_TEXTURE_IMAGE_UNITS_ARB* = 0x8872.GLenum
-  GL_FIXED_OES* = 0x140C.GLenum
-  GL_ALREADY_SIGNALED_APPLE* = 0x911A.GLenum
-  GL_SET* = 0x150F.GLenum
-  GL_PERFMON_RESULT_AMD* = 0x8BC6.GLenum
-  GL_VARIABLE_G_NV* = 0x8529.GLenum
-  GL_DRAW_FRAMEBUFFER_ANGLE* = 0x8CA9.GLenum
-  GL_GEOMETRY_SUBROUTINE_UNIFORM* = 0x92F1.GLenum
-  GL_COMPARE_REF_DEPTH_TO_TEXTURE_EXT* = 0x884E.GLenum
-  GL_POINT* = 0x1B00.GLenum
-  GL_FONT_MAX_ADVANCE_WIDTH_BIT_NV* = 0x01000000.GLbitfield
-  GL_MAX_TESS_CONTROL_IMAGE_UNIFORMS* = 0x90CB.GLenum
-  GL_PLUS_CLAMPED_ALPHA_NV* = 0x92B2.GLenum
-  GL_DRAW_BUFFER3_ATI* = 0x8828.GLenum
-  GL_LUMINANCE_ALPHA16I_EXT* = 0x8D8D.GLenum
-  GL_SUBPIXEL_BITS* = 0x0D50.GLenum
-  GL_POINT_SPRITE* = 0x8861.GLenum
-  GL_DRAW_BUFFER0* = 0x8825.GLenum
-  GL_DEPTH_BIAS* = 0x0D1F.GLenum
-  GL_COLOR_ARRAY_TYPE* = 0x8082.GLenum
-  GL_DEPENDENT_GB_TEXTURE_2D_NV* = 0x86EA.GLenum
-  GL_MAX_SAMPLES_ANGLE* = 0x8D57.GLenum
-  GL_ALLOW_DRAW_MEM_HINT_PGI* = 0x1A211.GLenum
-  GL_GEOMETRY_OUTPUT_TYPE* = 0x8918.GLenum
-  GL_MAX_DEBUG_LOGGED_MESSAGES_KHR* = 0x9144.GLenum
-  GL_VERTEX_ATTRIB_ARRAY0_NV* = 0x8650.GLenum
-  GL_PRIMITIVES_GENERATED_EXT* = 0x8C87.GLenum
-  GL_TEXTURE_FLOAT_COMPONENTS_NV* = 0x888C.GLenum
-  GL_CLIP_VOLUME_CLIPPING_HINT_EXT* = 0x80F0.GLenum
-  GL_FRAGMENT_PROGRAM_POSITION_MESA* = 0x8BB0.GLenum
-  GL_MAX_FRAGMENT_IMAGE_UNIFORMS* = 0x90CE.GLenum
-  GL_VERTEX_ARRAY_BINDING_APPLE* = 0x85B5.GLenum
-  GL_SHADER_GLOBAL_ACCESS_BARRIER_BIT_NV* = 0x00000010.GLbitfield
-  GL_FIRST_VERTEX_CONVENTION* = 0x8E4D.GLenum
-  GL_DECR_WRAP* = 0x8508.GLenum
-  GL_IMAGE_CLASS_1_X_32* = 0x82BB.GLenum
-  GL_MAX_CLIP_PLANES_IMG* = 0x0D32.GLenum
-  GL_MAX_VARYING_COMPONENTS* = 0x8B4B.GLenum
-  GL_POST_COLOR_MATRIX_RED_BIAS_SGI* = 0x80B8.GLenum
-  GL_DSDT_MAG_NV* = 0x86F6.GLenum
-  GL_DEBUG_SOURCE_APPLICATION* = 0x824A.GLenum
-  GL_OPERAND0_RGB_ARB* = 0x8590.GLenum
-  GL_SIMULTANEOUS_TEXTURE_AND_DEPTH_WRITE* = 0x82AE.GLenum
-  GL_VIDEO_COLOR_CONVERSION_MATRIX_NV* = 0x9029.GLenum
-  GL_MAP2_VERTEX_ATTRIB13_4_NV* = 0x867D.GLenum
-  GL_DOT2_ADD_ATI* = 0x896C.GLenum
-  GL_MAX_COMBINED_FRAGMENT_UNIFORM_COMPONENTS* = 0x8A33.GLenum
-  GL_IMAGE_BINDING_LAYER_EXT* = 0x8F3D.GLenum
-  GL_FRAGMENT_COLOR_MATERIAL_FACE_SGIX* = 0x8402.GLenum
-  GL_PACK_IMAGE_DEPTH_SGIS* = 0x8131.GLenum
-  GL_MAX_GEOMETRY_UNIFORM_COMPONENTS_EXT* = 0x8DDF.GLenum
-  GL_Z_EXT* = 0x87D7.GLenum
-  GL_MAP1_VERTEX_ATTRIB15_4_NV* = 0x866F.GLenum
-  GL_RG8_SNORM* = 0x8F95.GLenum
-  GL_OUTPUT_TEXTURE_COORD5_EXT* = 0x87A2.GLenum
-  GL_TEXTURE_BINDING_1D_ARRAY_EXT* = 0x8C1C.GLenum
-  GL_OBJECT_ACTIVE_UNIFORM_MAX_LENGTH_ARB* = 0x8B87.GLenum
-  GL_PATH_END_CAPS_NV* = 0x9076.GLenum
-  GL_COLOR_TABLE_GREEN_SIZE* = 0x80DB.GLenum
-  GL_MAX_ELEMENTS_INDICES_EXT* = 0x80E9.GLenum
-  GL_TEXTURE_IMMUTABLE_FORMAT* = 0x912F.GLenum
-  GL_WRITE_ONLY_ARB* = 0x88B9.GLenum
-  GL_COLOR_ATTACHMENT10_EXT* = 0x8CEA.GLenum
-  GL_INVERT_RGB_NV* = 0x92A3.GLenum
-  GL_CURRENT_RASTER_DISTANCE* = 0x0B09.GLenum
-  GL_DEPTH_STENCIL_TO_RGBA_NV* = 0x886E.GLenum
-  GL_INVERTED_SCREEN_W_REND* = 0x8491.GLenum
-  GL_TABLE_TOO_LARGE* = 0x8031.GLenum
-  GL_REG_16_ATI* = 0x8931.GLenum
-  GL_BLEND_EQUATION_ALPHA_OES* = 0x883D.GLenum
-  GL_DRAW_FRAMEBUFFER_BINDING_NV* = 0x8CA6.GLenum
-  GL_ACTIVE_SUBROUTINE_UNIFORM_LOCATIONS* = 0x8E47.GLenum
-  GL_TEXTURE_BLUE_SIZE_EXT* = 0x805E.GLenum
-  GL_TEXTURE_BORDER_VALUES_NV* = 0x871A.GLenum
-  GL_PROGRAM_LENGTH_ARB* = 0x8627.GLenum
-  GL_BOUNDING_BOX_OF_BOUNDING_BOXES_NV* = 0x909C.GLenum
-  GL_DOT_PRODUCT_NV* = 0x86EC.GLenum
-  GL_TRANSPOSE_PROJECTION_MATRIX_ARB* = 0x84E4.GLenum
-  GL_TEXTURE_2D_MULTISAMPLE_ARRAY* = 0x9102.GLenum
-  GL_MIN_PROGRAM_TEXEL_OFFSET_NV* = 0x8904.GLenum
-  GL_MAP2_BINORMAL_EXT* = 0x8447.GLenum
-  GL_COLOR_ARRAY_BUFFER_BINDING* = 0x8898.GLenum
-  GL_TEXTURE_COORD_ARRAY_POINTER* = 0x8092.GLenum
-  GL_TEXTURE4_ARB* = 0x84C4.GLenum
-  GL_VARIABLE_A_NV* = 0x8523.GLenum
-  GL_CURRENT_FOG_COORDINATE_EXT* = 0x8453.GLenum
-  GL_TEXTURE_CUBE_MAP_POSITIVE_X* = 0x8515.GLenum
-  GL_DEPENDENT_AR_TEXTURE_2D_NV* = 0x86E9.GLenum
-  GL_TEXTURE29_ARB* = 0x84DD.GLenum
-  GL_INVERSE_TRANSPOSE_NV* = 0x862D.GLenum
-  GL_TEXTURE_COLOR_WRITEMASK_SGIS* = 0x81EF.GLenum
-  GL_HISTOGRAM_SINK* = 0x802D.GLenum
-  GL_ALPHA12_EXT* = 0x803D.GLenum
-  GL_TEXTURE_CLIPMAP_LOD_OFFSET_SGIX* = 0x8175.GLenum
-  GL_DSDT_MAG_INTENSITY_NV* = 0x86DC.GLenum
-  GL_ATC_RGB_AMD* = 0x8C92.GLenum
-  GL_PROGRAM_ATTRIB_COMPONENTS_NV* = 0x8906.GLenum
-  GL_UNIFORM_BLOCK_BINDING* = 0x8A3F.GLenum
-  GL_POLYGON_STIPPLE* = 0x0B42.GLenum
-  GL_BACK* = 0x0405.GLenum
-  GL_DEPTH_COMPONENT16_NONLINEAR_NV* = 0x8E2C.GLenum
-  GL_ALPHA32F_EXT* = 0x8816.GLenum
-  GL_CLAMP_TO_BORDER* = 0x812D.GLint
-  GL_FLOAT_RGBA16_NV* = 0x888A.GLenum
-  GL_VERTEX_ARRAY_RANGE_LENGTH_NV* = 0x851E.GLenum
-  GL_UNSIGNED_INT_SAMPLER_RENDERBUFFER_NV* = 0x8E58.GLenum
-  GL_SAMPLER_2D* = 0x8B5E.GLenum
-  GL_SMOOTH_POINT_SIZE_RANGE* = 0x0B12.GLenum
-  GL_DEPTH_PASS_INSTRUMENT_MAX_SGIX* = 0x8312.GLenum
-  GL_INTERPOLATE_ARB* = 0x8575.GLenum
-  GL_VERTEX_ARRAY_LENGTH_NV* = 0x8F2B.GLenum
-  GL_FUNC_SUBTRACT_EXT* = 0x800A.GLenum
-  GL_OUTPUT_TEXTURE_COORD14_EXT* = 0x87AB.GLenum
-  GL_HISTOGRAM_SINK_EXT* = 0x802D.GLenum
-  GL_RG_EXT* = 0x8227.GLenum
-  GL_SHARPEN_TEXTURE_FUNC_POINTS_SGIS* = 0x80B0.GLenum
-  GL_COLOR_TABLE_SCALE* = 0x80D6.GLenum
-  GL_CURRENT_RASTER_TEXTURE_COORDS* = 0x0B06.GLenum
-  GL_PIXEL_BUFFER_BARRIER_BIT* = 0x00000080.GLbitfield
-  GL_SHADING_LANGUAGE_VERSION* = 0x8B8C.GLenum
-  GL_TEXTURE_MATRIX_FLOAT_AS_INT_BITS_OES* = 0x898F.GLenum
-  GL_DUAL_LUMINANCE_ALPHA4_SGIS* = 0x811C.GLenum
-  GL_CLAMP* = 0x2900.GLint
-  GL_4PASS_2_EXT* = 0x80A6.GLenum
-  GL_POLYGON_OFFSET_LINE* = 0x2A02.GLenum
-  GL_LOGIC_OP* = 0x0BF1.GLenum
-  GL_RENDERBUFFER_HEIGHT* = 0x8D43.GLenum
-  GL_COPY_INVERTED* = 0x150C.GLenum
-  GL_NONE* = 0.GLenum
-  GL_COLOR_ENCODING* = 0x8296.GLenum
-  GL_ONE_MINUS_CONSTANT_ALPHA_EXT* = 0x8004.GLenum
-  GL_DEBUG_TYPE_ERROR_KHR* = 0x824C.GLenum
-  GL_PIXEL_TILE_GRID_WIDTH_SGIX* = 0x8142.GLenum
-  GL_UNIFORM_SIZE* = 0x8A38.GLenum
-  GL_VERTEX_SHADER_BINDING_EXT* = 0x8781.GLenum
-  GL_BLEND_DST_RGB_EXT* = 0x80C8.GLenum
-  GL_QUADS* = 0x0007.GLenum
-  cGL_INT* = 0x1404.GLenum
-  GL_PIXEL_TEX_GEN_MODE_SGIX* = 0x832B.GLenum
-  GL_COMPRESSED_RGB_BPTC_UNSIGNED_FLOAT_ARB* = 0x8E8F.GLenum
-  GL_SAMPLE_ALPHA_TO_ONE_ARB* = 0x809F.GLenum
-  GL_RGBA32F_EXT* = 0x8814.GLenum
-  GL_VERTEX_PROGRAM_POSITION_MESA* = 0x8BB4.GLenum
-  GL_GEOMETRY_SUBROUTINE* = 0x92EB.GLenum
-  GL_UNSIGNED_INT_SAMPLER_1D_ARRAY_EXT* = 0x8DD6.GLenum
-  GL_IMAGE_BINDING_LAYER* = 0x8F3D.GLenum
-  GL_PIXEL_PACK_BUFFER_ARB* = 0x88EB.GLenum
-  GL_UNIFORM_BLOCK_REFERENCED_BY_TESS_EVALUATION_SHADER* = 0x84F1.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_SIZE_ARB* = 0x8623.GLenum
-  GL_ALPHA8UI_EXT* = 0x8D7E.GLenum
-  GL_RELATIVE_SMOOTH_CUBIC_CURVE_TO_NV* = 0x11.GLenum
-  GL_CAVEAT_SUPPORT* = 0x82B8.GLenum
-  GL_ACCUM* = 0x0100.GLenum
-  GL_DRAW_BUFFER3_NV* = 0x8828.GLenum
-  GL_DEBUG_TYPE_OTHER_KHR* = 0x8251.GLenum
-  GL_TESS_GEN_SPACING* = 0x8E77.GLenum
-  GL_FLOAT_MAT4x2* = 0x8B69.GLenum
-  GL_TEXTURE_GEN_STR_OES* = 0x8D60.GLenum
-  GL_NUM_COMPATIBLE_SUBROUTINES* = 0x8E4A.GLenum
-  GL_CLIP_DISTANCE1* = 0x3001.GLenum
-  GL_DEPTH_COMPONENT32_SGIX* = 0x81A7.GLenum
-  GL_FRAMEZOOM_SGIX* = 0x818B.GLenum
-  GL_COLOR_ATTACHMENT14_EXT* = 0x8CEE.GLenum
-  GL_POLYGON_TOKEN* = 0x0703.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_GREEN_SIZE* = 0x8213.GLenum
-  GL_DRAW_BUFFER2_EXT* = 0x8827.GLenum
-  GL_MATRIX_INDEX_ARRAY_TYPE_OES* = 0x8847.GLenum
-  GL_HISTOGRAM_LUMINANCE_SIZE_EXT* = 0x802C.GLenum
-  GL_DEPTH_BOUNDS_EXT* = 0x8891.GLenum
-  GL_TEXTURE24* = 0x84D8.GLenum
-  GL_UNIFORM_BLOCK_ACTIVE_UNIFORM_INDICES* = 0x8A43.GLenum
-  GL_MAX_PATCH_VERTICES* = 0x8E7D.GLenum
-  GL_COMPILE_STATUS* = 0x8B81.GLenum
-  GL_MODELVIEW4_ARB* = 0x8724.GLenum
-  GL_SHADER_BINARY_VIV* = 0x8FC4.GLenum
-  GL_CON_10_ATI* = 0x894B.GLenum
-  GL_FRAGMENT_LIGHT5_SGIX* = 0x8411.GLenum
-  GL_CONVOLUTION_1D_EXT* = 0x8010.GLenum
-  GL_CONSTANT_BORDER_HP* = 0x8151.GLenum
-  GL_SAMPLE_BUFFERS* = 0x80A8.GLenum
-  GL_RGB8UI* = 0x8D7D.GLenum
-  GL_FRAGMENT_MATERIAL_EXT* = 0x8349.GLenum
-  GL_OP_RECIP_EXT* = 0x8794.GLenum
-  GL_SHADER_OPERATION_NV* = 0x86DF.GLenum
-  GL_COMPUTE_SUBROUTINE_UNIFORM* = 0x92F3.GLenum
-  GL_VIDEO_BUFFER_PITCH_NV* = 0x9028.GLenum
-  GL_UNKNOWN_CONTEXT_RESET_ARB* = 0x8255.GLenum
-  GL_COLOR_ATTACHMENT3_EXT* = 0x8CE3.GLenum
-  GL_QUERY_WAIT* = 0x8E13.GLenum
-  GL_SOURCE1_RGB* = 0x8581.GLenum
-  GL_DELETE_STATUS* = 0x8B80.GLenum
-  GL_DEBUG_NEXT_LOGGED_MESSAGE_LENGTH_ARB* = 0x8243.GLenum
-  GL_HILO8_NV* = 0x885E.GLenum
-  GL_UNSIGNED_INT_IMAGE_CUBE_MAP_ARRAY_EXT* = 0x906A.GLenum
-  GL_LUMINANCE_ALPHA_FLOAT16_APPLE* = 0x881F.GLenum
-  GL_LUMINANCE16_SNORM* = 0x9019.GLenum
-  GL_MAX_CLIPMAP_VIRTUAL_DEPTH_SGIX* = 0x8178.GLenum
-  GL_RENDER* = 0x1C00.GLenum
-  GL_RED_INTEGER* = 0x8D94.GLenum
-  GL_DEBUG_TYPE_ERROR_ARB* = 0x824C.GLenum
-  GL_IMAGE_BINDING_ACCESS* = 0x8F3E.GLenum
-  GL_COVERAGE_COMPONENT_NV* = 0x8ED0.GLenum
-  GL_TEXTURE_BINDING_BUFFER_EXT* = 0x8C2C.GLenum
-  GL_MAX_PROGRAM_PATCH_ATTRIBS_NV* = 0x86D8.GLenum
-  GL_DUAL_LUMINANCE12_SGIS* = 0x8116.GLenum
-  GL_QUAD_ALPHA8_SGIS* = 0x811F.GLenum
-  GL_COMPRESSED_RED_GREEN_RGTC2_EXT* = 0x8DBD.GLenum
-  GL_PACK_INVERT_MESA* = 0x8758.GLenum
-  GL_OUTPUT_TEXTURE_COORD11_EXT* = 0x87A8.GLenum
-  GL_DYNAMIC_DRAW_ARB* = 0x88E8.GLenum
-  GL_RGB565_OES* = 0x8D62.GLenum
-  GL_LINE* = 0x1B01.GLenum
-  GL_T2F_V3F* = 0x2A27.GLenum
-  GL_DIFFUSE* = 0x1201.GLenum
-  GL_FOG_COORDINATE_SOURCE* = 0x8450.GLenum
-  GL_TEXTURE_1D_ARRAY_EXT* = 0x8C18.GLenum
-  GL_TEXTURE_RECTANGLE_NV* = 0x84F5.GLenum
-  GL_STENCIL_INDEX4_EXT* = 0x8D47.GLenum
-  GL_VERTEX_PROGRAM_TWO_SIDE* = 0x8643.GLenum
-  GL_REDUCE* = 0x8016.GLenum
-  GL_DEBUG_CALLBACK_USER_PARAM_KHR* = 0x8245.GLenum
-  GL_DEBUG_LOGGED_MESSAGES_AMD* = 0x9145.GLenum
-  GL_FONT_UNITS_PER_EM_BIT_NV* = 0x00100000.GLbitfield
-  GL_INVALID_FRAMEBUFFER_OPERATION_EXT* = 0x0506.GLenum
-  GL_NORMAL_ARRAY_BUFFER_BINDING_ARB* = 0x8897.GLenum
-  GL_SAMPLE_MASK_INVERT_SGIS* = 0x80AB.GLenum
-  GL_MAX_SHADER_BUFFER_ADDRESS_NV* = 0x8F35.GLenum
-  GL_PIXEL_MAP_I_TO_A* = 0x0C75.GLenum
-  GL_MINOR_VERSION* = 0x821C.GLenum
-  GL_TEXTURE_BUFFER_EXT* = 0x8C2A.GLenum
-  GL_SKIP_COMPONENTS4_NV* = -3
-  GL_FLOAT16_NV* = 0x8FF8.GLenum
-  GL_FEEDBACK_BUFFER_TYPE* = 0x0DF2.GLenum
-  GL_COMPRESSED_LUMINANCE_ALPHA_LATC2_EXT* = 0x8C72.GLenum
-  GL_REG_6_ATI* = 0x8927.GLenum
-  GL_EDGE_FLAG_ARRAY_LIST_IBM* = 103075.GLenum
-  GL_MATRIX26_ARB* = 0x88DA.GLenum
-  GL_ALPHA16* = 0x803E.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_OBJECT_NAME* = 0x8CD1.GLenum
-  GL_HISTOGRAM_ALPHA_SIZE* = 0x802B.GLenum
-  GL_COLOR_MATRIX_STACK_DEPTH* = 0x80B2.GLenum
-  GL_INTERNALFORMAT_GREEN_TYPE* = 0x8279.GLenum
-  GL_YCRCBA_SGIX* = 0x8319.GLenum
-  GL_VIEW_CLASS_48_BITS* = 0x82C7.GLenum
-  GL_VERTEX_ATTRIB_ARRAY3_NV* = 0x8653.GLenum
-  GL_CLIENT_STORAGE_BIT* = 0x0200.GLbitfield
-  GL_MIN_SAMPLE_SHADING_VALUE_ARB* = 0x8C37.GLenum
-  GL_PROXY_TEXTURE_CUBE_MAP* = 0x851B.GLenum
-  GL_MAX_COMBINED_SHADER_OUTPUT_RESOURCES* = 0x8F39.GLenum
-  GL_TEXTURE15* = 0x84CF.GLenum
-  GL_COLOR* = 0x1800.GLenum
-  GL_LIGHT1* = 0x4001.GLenum
-  GL_LUMINANCE_ALPHA16F_EXT* = 0x881F.GLenum
-  GL_TEXTURE_VIEW_NUM_LAYERS* = 0x82DE.GLenum
-  GL_MAX_TESS_EVALUATION_TEXTURE_IMAGE_UNITS* = 0x8E82.GLenum
-  GL_INTERLEAVED_ATTRIBS_NV* = 0x8C8C.GLenum
-  GL_INT_SAMPLER_BUFFER_EXT* = 0x8DD0.GLenum
-  GL_EVAL_VERTEX_ATTRIB14_NV* = 0x86D4.GLenum
-  GL_FRAGMENT_PROGRAM_CALLBACK_MESA* = 0x8BB1.GLenum
-  GL_EMISSION* = 0x1600.GLenum
-  GL_WEIGHT_ARRAY_STRIDE_ARB* = 0x86AA.GLenum
-  GL_ACTIVE_VARIABLES* = 0x9305.GLenum
-  GL_TIMEOUT_IGNORED* = 0xFFFFFFFFFFFFFFFF.GLenum
-  GL_VERTEX_STREAM5_ATI* = 0x8771.GLenum
-  GL_INDEX_ARRAY_POINTER* = 0x8091.GLenum
-  GL_POST_COLOR_MATRIX_ALPHA_SCALE* = 0x80B7.GLenum
-  GL_TESS_CONTROL_SHADER* = 0x8E88.GLenum
-  GL_POLYGON_MODE* = 0x0B40.GLenum
-  GL_ASYNC_DRAW_PIXELS_SGIX* = 0x835D.GLenum
-  GL_RGBA16_SNORM* = 0x8F9B.GLenum
-  GL_TEXTURE_NORMAL_EXT* = 0x85AF.GLenum
-  GL_REG_22_ATI* = 0x8937.GLenum
-  GL_FRAMEBUFFER_DEFAULT_WIDTH* = 0x9310.GLenum
-  GL_TEXCOORD1_BIT_PGI* = 0x10000000.GLbitfield
-  GL_REFERENCE_PLANE_EQUATION_SGIX* = 0x817E.GLenum
-  GL_COLOR_ALPHA_PAIRING_ATI* = 0x8975.GLenum
-  GL_SINGLE_COLOR* = 0x81F9.GLenum
-  GL_MODELVIEW21_ARB* = 0x8735.GLenum
-  GL_FORMAT_SUBSAMPLE_24_24_OML* = 0x8982.GLenum
-  GL_SOURCE1_ALPHA* = 0x8589.GLenum
-  GL_LINEARLIGHT_NV* = 0x92A7.GLenum
-  GL_REG_2_ATI* = 0x8923.GLenum
-  GL_QUERY_RESULT_AVAILABLE* = 0x8867.GLenum
-  GL_PERSPECTIVE_CORRECTION_HINT* = 0x0C50.GLenum
-  GL_COMBINE_ALPHA_ARB* = 0x8572.GLenum
-  GL_HISTOGRAM_ALPHA_SIZE_EXT* = 0x802B.GLenum
-  GL_SIGNED_RGB8_NV* = 0x86FF.GLenum
-  GL_DEPTH_TEXTURE_MODE_ARB* = 0x884B.GLenum
-  GL_PRESENT_DURATION_NV* = 0x8E2B.GLenum
-  GL_TRIANGLES_ADJACENCY_ARB* = 0x000C.GLenum
-  GL_TEXTURE_BUFFER_OFFSET* = 0x919D.GLenum
-  GL_PROGRAM_STRING_ARB* = 0x8628.GLenum
-  GL_UNSIGNED_INT_IMAGE_1D_EXT* = 0x9062.GLenum
-  GL_COLOR_ATTACHMENT2* = 0x8CE2.GLenum
-  GL_DOT_PRODUCT_TEXTURE_2D_NV* = 0x86EE.GLenum
-  GL_QUERY_BUFFER* = 0x9192.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Z* = 0x851A.GLenum
-  GL_PIXEL_TEX_GEN_ALPHA_REPLACE_SGIX* = 0x8187.GLenum
-  GL_FULL_SUPPORT* = 0x82B7.GLenum
-  GL_MAX_PROGRAM_ENV_PARAMETERS_ARB* = 0x88B5.GLenum
-  GL_MAX_COMPUTE_WORK_GROUP_COUNT* = 0x91BE.GLenum
-  GL_DEBUG_TYPE_PERFORMANCE* = 0x8250.GLenum
-  GL_DRAW_BUFFER12_EXT* = 0x8831.GLenum
-  GL_UNSIGNED_INT_SAMPLER_BUFFER_AMD* = 0x9003.GLenum
-  GL_CURRENT_FOG_COORDINATE* = 0x8453.GLenum
-  GL_INTENSITY_EXT* = 0x8049.GLenum
-  GL_TRANSPOSE_NV* = 0x862C.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT5_NV* = 0x8C4F.GLenum
-  GL_MAX_TRANSFORM_FEEDBACK_SEPARATE_COMPONENTS* = 0x8C80.GLenum
-  GL_COLOR_ARRAY_POINTER_EXT* = 0x8090.GLenum
-  GL_TEXTURE_BUFFER_DATA_STORE_BINDING_EXT* = 0x8C2D.GLenum
-  GL_GEOMETRY_VERTICES_OUT_ARB* = 0x8DDA.GLenum
-  GL_RELATIVE_SMOOTH_QUADRATIC_CURVE_TO_NV* = 0x0F.GLenum
-  GL_OP_INDEX_EXT* = 0x8782.GLenum
-  GL_REG_1_ATI* = 0x8922.GLenum
-  GL_OFFSET* = 0x92FC.GLenum
-  GL_PATH_COVER_DEPTH_FUNC_NV* = 0x90BF.GLenum
-  GL_UNPACK_COMPRESSED_BLOCK_DEPTH* = 0x9129.GLenum
-  GL_POLYGON_OFFSET_UNITS* = 0x2A00.GLenum
-  GL_INDEX_TEST_FUNC_EXT* = 0x81B6.GLenum
-  GL_POINT_SMOOTH* = 0x0B10.GLenum
-  GL_SCALEBIAS_HINT_SGIX* = 0x8322.GLenum
-  GL_COMPRESSED_RGBA_ASTC_5x4_KHR* = 0x93B1.GLenum
-  GL_SEPARATE_SPECULAR_COLOR* = 0x81FA.GLenum
-  GL_VERTEX_ATTRIB_ARRAY14_NV* = 0x865E.GLenum
-  GL_INTENSITY16_EXT* = 0x804D.GLenum
-  GL_R8_SNORM* = 0x8F94.GLenum
-  GL_DEBUG_LOGGED_MESSAGES* = 0x9145.GLenum
-  GL_ALPHA8I_EXT* = 0x8D90.GLenum
-  GL_OPERAND2_RGB* = 0x8592.GLenum
-  GL_EMBOSS_LIGHT_NV* = 0x855D.GLenum
-  GL_EDGE_FLAG_ARRAY_STRIDE_EXT* = 0x808C.GLenum
-  GL_VERTEX_ATTRIB_ARRAY_INTEGER_NV* = 0x88FD.GLenum
-  GL_NUM_LOOPBACK_COMPONENTS_ATI* = 0x8974.GLenum
-  GL_DEBUG_SOURCE_APPLICATION_KHR* = 0x824A.GLenum
-  GL_COMPRESSED_RGB_S3TC_DXT1_EXT* = 0x83F0.GLenum
-  GL_DEBUG_SOURCE_OTHER_ARB* = 0x824B.GLenum
-  cGL_DOUBLE* = 0x140A.GLenum
-  GL_STENCIL_TEST_TWO_SIDE_EXT* = 0x8910.GLenum
-  GL_MIN_PROGRAM_TEXEL_OFFSET* = 0x8904.GLenum
-  GL_3DC_X_AMD* = 0x87F9.GLenum
-  GL_FLOAT_RGB32_NV* = 0x8889.GLenum
-  GL_SECONDARY_COLOR_ARRAY_POINTER_EXT* = 0x845D.GLenum
-  GL_OPERAND2_ALPHA_ARB* = 0x859A.GLenum
-  GL_IMAGE_3D* = 0x904E.GLenum
-  GL_SECONDARY_COLOR_ARRAY_SIZE* = 0x845A.GLenum
-  GL_RELEASED_APPLE* = 0x8A19.GLenum
-  GL_RENDER_DIRECT_TO_FRAMEBUFFER_QCOM* = 0x8FB3.GLenum
-  GL_FRAMEBUFFER_DEFAULT_LAYERS* = 0x9312.GLenum
-  GL_INTENSITY* = 0x8049.GLenum
-  GL_RENDERBUFFER_BLUE_SIZE_OES* = 0x8D52.GLenum
-  GL_FLOAT_RGB_NV* = 0x8882.GLenum
-  GL_ARRAY_ELEMENT_LOCK_FIRST_EXT* = 0x81A8.GLenum
-  GL_CON_4_ATI* = 0x8945.GLenum
-  GL_ROUND_NV* = 0x90A4.GLenum
-  GL_CLIP_DISTANCE2* = 0x3002.GLenum
-  GL_MAX_PROGRAM_ALU_INSTRUCTIONS_ARB* = 0x880B.GLenum
-  GL_PROGRAM_ERROR_STRING_ARB* = 0x8874.GLenum
-  GL_STORAGE_CACHED_APPLE* = 0x85BE.GLenum
-  GL_LIGHTEN_NV* = 0x9298.GLenum
-  GL_TEXTURE23* = 0x84D7.GLenum
-  GL_SAMPLER_CUBE_SHADOW* = 0x8DC5.GLenum
-  GL_VERTEX_PROGRAM_ARB* = 0x8620.GLenum
-  GL_COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT* = 0x8C4E.GLenum
-  GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB* = 0x851A.GLenum
-  GL_RENDERBUFFER_SAMPLES* = 0x8CAB.GLenum
-  GL_RENDERBUFFER_STENCIL_SIZE* = 0x8D55.GLenum
-  GL_VIRTUAL_PAGE_SIZE_INDEX_ARB* = 0x91A7.GLenum
-  GL_CLIP_PLANE5* = 0x3005.GLenum
-  GL_VERTEX_WEIGHT_ARRAY_POINTER_EXT* = 0x8510.GLenum
-  GL_COLOR_BUFFER_BIT5_QCOM* = 0x00000020.GLbitfield
-  GL_DOUBLE_MAT2x3_EXT* = 0x8F49.GLenum
-  GL_UNIFORM_BLOCK_ACTIVE_UNIFORMS* = 0x8A42.GLenum
-  GL_COLOR_ATTACHMENT8_EXT* = 0x8CE8.GLenum
-  GL_UNIFORM_BUFFER_BINDING_EXT* = 0x8DEF.GLenum
-  GL_MATRIX8_ARB* = 0x88C8.GLenum
-  GL_COUNTER_TYPE_AMD* = 0x8BC0.GLenum
-  GL_INT8_VEC3_NV* = 0x8FE2.GLenum
-  GL_TEXTURE_BINDING_3D_OES* = 0x806A.GLenum
-  GL_DEPTH_PASS_INSTRUMENT_COUNTERS_SGIX* = 0x8311.GLenum
-  GL_IMAGE_BINDING_LEVEL* = 0x8F3B.GLenum
-  GL_STENCIL_BACK_FAIL_ATI* = 0x8801.GLenum
-  GL_TRANSFORM_FEEDBACK_ATTRIBS_NV* = 0x8C7E.GLenum
-  GL_COLOR_TABLE_INTENSITY_SIZE* = 0x80DF.GLenum
-  GL_TEXTURE_2D_BINDING_EXT* = 0x8069.GLenum
-  GL_CW* = 0x0900.GLenum
-  GL_COLOR_ATTACHMENT6* = 0x8CE6.GLenum
-  GL_R32UI* = 0x8236.GLenum
-  GL_PROXY_TEXTURE_3D* = 0x8070.GLenum
-  GL_FLOAT_VEC2_ARB* = 0x8B50.GLenum
-  GL_C3F_V3F* = 0x2A24.GLenum
-  GL_MAX_PROGRAM_PARAMETER_BUFFER_BINDINGS_NV* = 0x8DA0.GLenum
-  GL_EVAL_VERTEX_ATTRIB11_NV* = 0x86D1.GLenum
-  GL_MAX_VERTEX_ARRAY_RANGE_ELEMENT_NV* = 0x8520.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER_OES* = 0x8CDC.GLenum
-  GL_MAX_VIEWPORT_DIMS* = 0x0D3A.GLenum
-  GL_STENCIL_CLEAR_TAG_VALUE_EXT* = 0x88F3.GLenum
-  GL_TEXTURE_BUFFER_FORMAT_ARB* = 0x8C2E.GLenum
-  GL_PROGRAM_NATIVE_PARAMETERS_ARB* = 0x88AA.GLenum
-  GL_FLOAT_MAT3x2* = 0x8B67.GLenum
-  GL_BLUE_BIT_ATI* = 0x00000004.GLbitfield
-  GL_COLOR_ATTACHMENT6_NV* = 0x8CE6.GLenum
-  GL_AND_INVERTED* = 0x1504.GLenum
-  GL_MAX_GEOMETRY_SHADER_STORAGE_BLOCKS* = 0x90D7.GLenum
-  GL_COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR* = 0x93D0.GLenum
-  GL_PACK_COMPRESSED_BLOCK_DEPTH* = 0x912D.GLenum
-  GL_TEXTURE_COMPARE_SGIX* = 0x819A.GLenum
-  GL_SYNC_CL_EVENT_COMPLETE_ARB* = 0x8241.GLenum
-  GL_DEBUG_TYPE_PORTABILITY* = 0x824F.GLenum
-  GL_IMAGE_BINDING_FORMAT* = 0x906E.GLenum
-  GL_RESAMPLE_DECIMATE_OML* = 0x8989.GLenum
-  GL_MAX_PROGRAM_TEMPORARIES_ARB* = 0x88A5.GLenum
-  GL_ALL_SHADER_BITS* = 0xFFFFFFFF.GLbitfield
-  GL_TRANSFORM_FEEDBACK_VARYING* = 0x92F4.GLenum
-  GL_TRANSFORM_FEEDBACK_BUFFER_BINDING* = 0x8C8F.GLenum
-  GL_ACTIVE_STENCIL_FACE_EXT* = 0x8911.GLenum
-  GL_MAP1_VERTEX_ATTRIB4_4_NV* = 0x8664.GLenum
-  GL_LINK_STATUS* = 0x8B82.GLenum
-  GL_SYNC_FLUSH_COMMANDS_BIT* = 0x00000001.GLbitfield
-  GL_BLEND* = 0x0BE2.GLenum
-  GL_OUTPUT_TEXTURE_COORD12_EXT* = 0x87A9.GLenum
-  GL_DRAW_BUFFER11_ARB* = 0x8830.GLenum
-  GL_OBJECT_BUFFER_USAGE_ATI* = 0x8765.GLenum
-  GL_COLORDODGE_NV* = 0x9299.GLenum
-  GL_SHADER_IMAGE_LOAD* = 0x82A4.GLenum
-  GL_EMBOSS_CONSTANT_NV* = 0x855E.GLenum
-  GL_MAP_TESSELLATION_NV* = 0x86C2.GLenum
-  GL_MAX_DRAW_BUFFERS_EXT* = 0x8824.GLenum
-  GL_VERTEX_WEIGHT_ARRAY_TYPE_EXT* = 0x850E.GLenum
-  GL_TEXTURE_ENV_COLOR* = 0x2201.GLenum
-  GL_UNIFORM_BLOCK_REFERENCED_BY_FRAGMENT_SHADER* = 0x8A46.GLenum
-  GL_DOT_PRODUCT_REFLECT_CUBE_MAP_NV* = 0x86F2.GLenum
-  GL_QUERY_KHR* = 0x82E3.GLenum
-  GL_RG* = 0x8227.GLenum
-  GL_MAX_TEXTURE_SIZE* = 0x0D33.GLenum
-  GL_TEXTURE_NUM_LEVELS_QCOM* = 0x8BD9.GLenum
-  GL_MAP2_VERTEX_ATTRIB3_4_NV* = 0x8673.GLenum
-  GL_LUMINANCE_FLOAT32_APPLE* = 0x8818.GLenum
-  GL_MAP2_VERTEX_ATTRIB7_4_NV* = 0x8677.GLenum
-  GL_GEOMETRY_SHADER_ARB* = 0x8DD9.GLenum
-  GL_SYNC_FENCE_APPLE* = 0x9116.GLenum
-  GL_SAMPLE_MASK_VALUE* = 0x8E52.GLenum
-  GL_PROXY_TEXTURE_RECTANGLE_NV* = 0x84F7.GLenum
-  GL_DEPTH_FUNC* = 0x0B74.GLenum
-  GL_S* = 0x2000.GLenum
-  GL_CONSTANT_COLOR_EXT* = 0x8001.GLenum
-  GL_MAX_PROGRAM_LOOP_COUNT_NV* = 0x88F8.GLenum
-  GL_VIEW_COMPATIBILITY_CLASS* = 0x82B6.GLenum
-  GL_INT_SAMPLER_BUFFER_AMD* = 0x9002.GLenum
-  GL_COMPRESSED_SRGB* = 0x8C48.GLenum
-  GL_PROGRAM_SEPARABLE_EXT* = 0x8258.GLenum
-  GL_FOG_FUNC_POINTS_SGIS* = 0x812B.GLenum
-  GL_MITER_TRUNCATE_NV* = 0x90A8.GLenum
-  GL_POLYGON_OFFSET_POINT* = 0x2A01.GLenum
-  GL_SRGB_READ* = 0x8297.GLenum
-  GL_INDEX_ARRAY_ADDRESS_NV* = 0x8F24.GLenum
-  GL_MAX_FRAMEBUFFER_WIDTH* = 0x9315.GLenum
-  GL_COMPRESSED_RED_RGTC1_EXT* = 0x8DBB.GLenum
-  GL_RGB_INTEGER_EXT* = 0x8D98.GLenum
-  GL_OP_NEGATE_EXT* = 0x8783.GLenum
-  GL_POINT_SIZE_MAX_ARB* = 0x8127.GLenum
-  GL_TEXTURE_DEFORMATION_BIT_SGIX* = 0x00000001.GLbitfield
-  GL_SIGNED_LUMINANCE8_NV* = 0x8702.GLenum
-  GL_OPERAND2_RGB_EXT* = 0x8592.GLenum
-  GL_MAX_PIXEL_TRANSFORM_2D_STACK_DEPTH_EXT* = 0x8337.GLenum
-  GL_RECIP_ADD_SIGNED_ALPHA_IMG* = 0x8C05.GLenum
-  GL_VERTEX_STREAM7_ATI* = 0x8773.GLenum
-  GL_MODELVIEW1_STACK_DEPTH_EXT* = 0x8502.GLenum
-  GL_DYNAMIC_DRAW* = 0x88E8.GLenum
-  GL_DRAW_BUFFER15_EXT* = 0x8834.GLenum
-  GL_TEXTURE_COMPARE_OPERATOR_SGIX* = 0x819B.GLenum
-  GL_SQUARE_NV* = 0x90A3.GLenum
-  GL_COMPRESSED_SRGB_S3TC_DXT1_EXT* = 0x8C4C.GLenum
-  GL_DRAW_BUFFER0_ARB* = 0x8825.GLenum
-  GL_GPU_OPTIMIZED_QCOM* = 0x8FB2.GLenum
-  GL_VERTEX_WEIGHT_ARRAY_STRIDE_EXT* = 0x850F.GLenum
-  GL_SPRITE_EYE_ALIGNED_SGIX* = 0x814E.GLenum
-  GL_MAP1_VERTEX_ATTRIB3_4_NV* = 0x8663.GLenum
-  GL_SAMPLE_MASK_SGIS* = 0x80A0.GLenum
-  GL_TEXTURE_SAMPLES* = 0x9106.GLenum
-  GL_AND_REVERSE* = 0x1502.GLenum
-  GL_COMBINER4_NV* = 0x8554.GLenum
-  GL_FONT_Y_MIN_BOUNDS_BIT_NV* = 0x00020000.GLbitfield
-  GL_VIEW_CLASS_32_BITS* = 0x82C8.GLenum
-  GL_BGRA_EXT* = 0x80E1.GLenum
-  GL_TANGENT_ARRAY_TYPE_EXT* = 0x843E.GLenum
-  GL_BLEND_EQUATION_RGB_OES* = 0x8009.GLenum
-  GL_TRANSPOSE_TEXTURE_MATRIX_ARB* = 0x84E5.GLenum
-  GL_GET_TEXTURE_IMAGE_FORMAT* = 0x8291.GLenum
-  GL_PACK_MAX_COMPRESSED_SIZE_SGIX* = 0x831B.GLenum
-  GL_UNIFORM_ARRAY_STRIDE* = 0x8A3C.GLenum
-  GL_REFLECTION_MAP_ARB* = 0x8512.GLenum
-  GL_RGBA_FLOAT16_ATI* = 0x881A.GLenum
-  GL_MAX_TESS_CONTROL_OUTPUT_COMPONENTS* = 0x8E83.GLenum
-  GL_RED_BITS* = 0x0D52.GLenum
-  GL_VERTEX_TEXTURE* = 0x829B.GLenum
-  GL_UNSIGNALED_APPLE* = 0x9118.GLenum
-  GL_RENDERBUFFER_ALPHA_SIZE_OES* = 0x8D53.GLenum
-  GL_DRAW_BUFFER14_NV* = 0x8833.GLenum
-  GL_STREAM_COPY_ARB* = 0x88E2.GLenum
-  GL_SECONDARY_COLOR_ARRAY_TYPE* = 0x845B.GLenum
-  GL_MATRIX22_ARB* = 0x88D6.GLenum
-  GL_VERTEX_ARRAY_RANGE_WITHOUT_FLUSH_NV* = 0x8533.GLenum
-  GL_IUI_N3F_V3F_EXT* = 0x81B0.GLenum
-  GL_SPARE0_NV* = 0x852E.GLenum
-  GL_FOG_COORD* = 0x8451.GLenum
-  GL_DRAW_BUFFER8_ARB* = 0x882D.GLenum
-  GL_MATRIX24_ARB* = 0x88D8.GLenum
-  GL_MAX_DEBUG_MESSAGE_LENGTH_AMD* = 0x9143.GLenum
-  GL_POST_COLOR_MATRIX_BLUE_SCALE* = 0x80B6.GLenum
-  GL_TEXTURE_HEIGHT_QCOM* = 0x8BD3.GLenum
-  GL_NUM_FRAGMENT_REGISTERS_ATI* = 0x896E.GLenum
-  GL_IMAGE_3D_EXT* = 0x904E.GLenum
-  GL_TEXTURE_FILTER_CONTROL* = 0x8500.GLenum
-  GL_VIDEO_BUFFER_NV* = 0x9020.GLenum
-  GL_CURRENT_MATRIX_INDEX_ARB* = 0x8845.GLenum
-  GL_STENCIL_BUFFER_BIT4_QCOM* = 0x00100000.GLbitfield
-  GL_SIGNED_INTENSITY_NV* = 0x8707.GLenum
-  GL_RASTERIZER_DISCARD_NV* = 0x8C89.GLenum
-  GL_MAX_DEFORMATION_ORDER_SGIX* = 0x8197.GLenum
-  GL_SAMPLES_3DFX* = 0x86B4.GLenum
-  GL_DOT_PRODUCT_PASS_THROUGH_NV* = 0x885B.GLenum
-  GL_RGB_SCALE_EXT* = 0x8573.GLenum
-  GL_TEXTURE_UNSIGNED_REMAP_MODE_NV* = 0x888F.GLenum
-  GL_MIRROR_CLAMP_TO_EDGE_EXT* = 0x8743.GLint
-  GL_NATIVE_GRAPHICS_END_HINT_PGI* = 0x1A204.GLenum
-  GL_UNPACK_CLIENT_STORAGE_APPLE* = 0x85B2.GLenum
-  GL_FRAMEBUFFER_INCOMPLETE_READ_BUFFER* = 0x8CDC.GLenum
-  GL_FOG_START* = 0x0B63.GLenum
-  GL_MAX_PROGRAM_CALL_DEPTH_NV* = 0x88F5.GLenum
-  GL_MODELVIEW18_ARB* = 0x8732.GLenum
-  GL_MAX_FRAMEZOOM_FACTOR_SGIX* = 0x818D.GLenum
-  GL_EDGE_FLAG_ARRAY_POINTER* = 0x8093.GLenum
-  GL_GREEN_INTEGER* = 0x8D95.GLenum
-  GL_IMAGE_BUFFER* = 0x9051.GLenum
-  GL_PROJECTION* = 0x1701.GLenum
-  GL_UNSIGNED_INT_VEC4_EXT* = 0x8DC8.GLenum
-  GL_PALETTE8_RGB5_A1_OES* = 0x8B99.GLenum
-  GL_RENDERBUFFER_SAMPLES_EXT* = 0x8CAB.GLenum
-  GL_TEXTURE3* = 0x84C3.GLenum
-  GL_CURRENT_RASTER_INDEX* = 0x0B05.GLenum
-  GL_INTERLEAVED_ATTRIBS_EXT* = 0x8C8C.GLenum
-  GL_STENCIL_BACK_WRITEMASK* = 0x8CA5.GLenum
-  GL_POINT_SPRITE_ARB* = 0x8861.GLenum
-  GL_TRANSPOSE_TEXTURE_MATRIX* = 0x84E5.GLenum
-  GL_DRAW_BUFFER1_ARB* = 0x8826.GLenum
-  GL_MAX_FRAGMENT_ATOMIC_COUNTER_BUFFERS* = 0x92D0.GLenum
-  GL_DEPTH_ATTACHMENT_OES* = 0x8D00.GLenum
-  GL_COMPRESSED_RGBA_PVRTC_2BPPV2_IMG* = 0x9137.GLenum
-  GL_SRGB_ALPHA* = 0x8C42.GLenum
-  GL_UNSIGNED_INT64_ARB* = 0x140F.GLenum
-  GL_LAST_VERTEX_CONVENTION_EXT* = 0x8E4E.GLenum
-  GL_IMAGE_CLASS_1_X_8* = 0x82C1.GLenum
-  GL_COMPRESSED_RGBA_S3TC_DXT1_EXT* = 0x83F1.GLenum
-  GL_REFLECTION_MAP* = 0x8512.GLenum
-  GL_MAX_IMAGE_UNITS_EXT* = 0x8F38.GLenum
-  GL_DEPTH_STENCIL_NV* = 0x84F9.GLenum
-  GL_PROGRAM_TEX_INDIRECTIONS_ARB* = 0x8807.GLenum
-  GL_BINNING_CONTROL_HINT_QCOM* = 0x8FB0.GLenum
-  GL_T4F_V4F* = 0x2A28.GLenum
-  GL_FLOAT_VEC4* = 0x8B52.GLenum
-  GL_CONVEX_HULL_NV* = 0x908B.GLenum
-  GL_TEXTURE26_ARB* = 0x84DA.GLenum
-  GL_INDEX_BIT_PGI* = 0x00080000.GLbitfield
-  GL_TEXTURE_COORD_ARRAY_TYPE_EXT* = 0x8089.GLenum
-  GL_FRAMEBUFFER_ATTACHMENT_TEXTURE_LEVEL_OES* = 0x8CD2.GLenum
-  GL_MAX_ARRAY_TEXTURE_LAYERS* = 0x88FF.GLenum
-  GL_COLOR_ATTACHMENT4_EXT* = 0x8CE4.GLenum
-  GL_SAMPLE_COVERAGE_VALUE_ARB* = 0x80AA.GLenum
-  GL_VERTEX_ATTRIB_MAP2_ORDER_APPLE* = 0x8A08.GLenum
-  GL_MAX_LAYERS* = 0x8281.GLenum
-  GL_FOG_COORDINATE_ARRAY_POINTER_EXT* = 0x8456.GLenum
-  GL_INDEX_TEST_REF_EXT* = 0x81B7.GLenum
-  GL_GREEN_BIT_ATI* = 0x00000002.GLbitfield
-  GL_STRICT_SCISSOR_HINT_PGI* = 0x1A218.GLenum
-  GL_MAP2_VERTEX_ATTRIB4_4_NV* = 0x8674.GLenum
-  GL_MAX_GEOMETRY_OUTPUT_VERTICES_EXT* = 0x8DE0.GLenum
-  GL_OUTPUT_TEXTURE_COORD31_EXT* = 0x87BC.GLenum
-  GL_XOR* = 0x1506.GLenum
-  GL_VIDEO_CAPTURE_FRAME_WIDTH_NV* = 0x9038.GLenum
-  GL_RGBA* = 0x1908.GLenum
-  GL_TEXTURE_TARGET* = 0x1006.GLenum
-  GL_QUERY_TARGET* = 0x82EA.GLenum
-
-{.deprecated: [
-  cGL_TRANSFORM_FEEDBACK_VARYINGS_EXT: GL_TRANSFORM_FEEDBACK_VARYINGS_EXT,
-  cGL_BLEND_EQUATION_EXT: GL_BLEND_EQUATION_EXT,
-  cGL_VERTEX_BLEND_ARB: GL_VERTEX_BLEND_ARB,
-  cGL_TESSELLATION_MODE_AMD: GL_TESSELLATION_MODE_AMD,
-  cGL_POLYGON_OFFSET_EXT: GL_POLYGON_OFFSET_EXT,
-  cGL_BLEND_COLOR_EXT: GL_BLEND_COLOR_EXT,
-  cGL_TRANSFORM_FEEDBACK_VARYINGS_NV: GL_TRANSFORM_FEEDBACK_VARYINGS_NV,
-  cGL_COLOR_MATERIAL: GL_COLOR_MATERIAL,
-  cGL_READ_BUFFER_NV: GL_READ_BUFFER_NV,
-  cGL_FOG_FUNC_SGIS: GL_FOG_FUNC_SGIS,
-  cGL_HISTOGRAM_EXT: GL_HISTOGRAM_EXT,
-  cGL_LINE_WIDTH: GL_LINE_WIDTH,
-  cGL_PROVOKING_VERTEX: GL_PROVOKING_VERTEX,
-  cGL_SHADE_MODEL: GL_SHADE_MODEL,
-  cGL_FRONT_FACE: GL_FRONT_FACE,
-  cGL_PRIMITIVE_RESTART_INDEX: GL_PRIMITIVE_RESTART_INDEX,
-  cGL_READ_PIXELS: GL_READ_PIXELS,
-  cGL_VIEWPORT: GL_VIEWPORT,
-  cGL_DEPTH_RANGE: GL_DEPTH_RANGE,
-  cGL_COLOR_TABLE_SGI: GL_COLOR_TABLE_SGI,
-  cGL_CLEAR: GL_CLEAR,
-  cGL_ASYNC_MARKER_SGIX: GL_ASYNC_MARKER_SGIX,
-  cGL_ACTIVE_TEXTURE_ARB: GL_ACTIVE_TEXTURE_ARB,
-  cGL_SAMPLE_COVERAGE: GL_SAMPLE_COVERAGE,
-  cGL_BLEND_EQUATION_OES: GL_BLEND_EQUATION_OES,
-  cGL_MATRIX_MODE: GL_MATRIX_MODE,
-  cGL_TRANSFORM_FEEDBACK_VARYINGS: GL_TRANSFORM_FEEDBACK_VARYINGS,
-  cGL_SAMPLE_COVERAGE_ARB: GL_SAMPLE_COVERAGE_ARB,
-  cGL_TRACK_MATRIX_NV: GL_TRACK_MATRIX_NV,
-  cGL_COMBINER_INPUT_NV: GL_COMBINER_INPUT_NV,
-  cGL_TESSELLATION_FACTOR_AMD: GL_TESSELLATION_FACTOR_AMD,
-  cGL_BLEND_EQUATION: GL_BLEND_EQUATION,
-  cGL_CULL_FACE: GL_CULL_FACE,
-  cGL_HISTOGRAM: GL_HISTOGRAM,
-  cGL_PRIMITIVE_RESTART_INDEX_NV: GL_PRIMITIVE_RESTART_INDEX_NV,
-  cGL_SAMPLE_MASK_EXT: GL_SAMPLE_MASK_EXT,
-  cGL_RENDER_MODE: GL_RENDER_MODE,
-  cGL_CURRENT_PALETTE_MATRIX_OES: GL_CURRENT_PALETTE_MATRIX_OES,
-  cGL_VERTEX_ATTRIB_BINDING: GL_VERTEX_ATTRIB_BINDING,
-  cGL_TEXTURE_LIGHT_EXT: GL_TEXTURE_LIGHT_EXT,
-  cGL_INDEX_MATERIAL_EXT: GL_INDEX_MATERIAL_EXT,
-  cGL_COLOR_TABLE: GL_COLOR_TABLE,
-  cGL_PATH_STENCIL_FUNC_NV: GL_PATH_STENCIL_FUNC_NV,
-  cGL_EDGE_FLAG: GL_EDGE_FLAG,
-  cGL_ACTIVE_TEXTURE: GL_ACTIVE_TEXTURE,
-  cGL_CLIENT_ACTIVE_TEXTURE_ARB: GL_CLIENT_ACTIVE_TEXTURE_ARB,
-  cGL_VERTEX_ARRAY_RANGE_APPLE: GL_VERTEX_ARRAY_RANGE_APPLE,
-  cGL_TEXTURE_VIEW: GL_TEXTURE_VIEW,
-  cGL_BITMAP: GL_BITMAP,
-  cGL_PRIMITIVE_RESTART_NV: GL_PRIMITIVE_RESTART_NV,
-  cGL_VERTEX_BINDING_DIVISOR: GL_VERTEX_BINDING_DIVISOR,
-  cGL_STENCIL_OP_VALUE_AMD: GL_STENCIL_OP_VALUE_AMD,
-  cGL_PROVOKING_VERTEX_EXT: GL_PROVOKING_VERTEX_EXT,
-  cGL_CURRENT_PALETTE_MATRIX_ARB: GL_CURRENT_PALETTE_MATRIX_ARB,
-  cGL_PIXEL_TEX_GEN_SGIX: GL_PIXEL_TEX_GEN_SGIX,
-  cGL_GENERATE_MIPMAP: GL_GENERATE_MIPMAP,
-  cGL_UNIFORM_BUFFER_EXT: GL_UNIFORM_BUFFER_EXT,
-  cGL_STENCIL_FUNC: GL_STENCIL_FUNC,
-  cGL_VERTEX_ARRAY_RANGE_NV: GL_VERTEX_ARRAY_RANGE_NV,
-  cGL_ACTIVE_PROGRAM_EXT: GL_ACTIVE_PROGRAM_EXT,
-  cGL_LINE_STIPPLE: GL_LINE_STIPPLE,
-  cGL_REFERENCE_PLANE_SGIX: GL_REFERENCE_PLANE_SGIX,
-  cGL_DRAW_BUFFER: GL_DRAW_BUFFER,
-  cGL_LIST_BASE: GL_LIST_BASE,
-  cGL_READ_BUFFER: GL_READ_BUFFER,
-  cGL_FRAGMENT_COLOR_MATERIAL_SGIX: GL_FRAGMENT_COLOR_MATERIAL_SGIX,
-  cGL_CLIENT_ACTIVE_TEXTURE: GL_CLIENT_ACTIVE_TEXTURE,
-  cGL_BLEND_COLOR: GL_BLEND_COLOR,
-  cGL_MINMAX_EXT: GL_MINMAX_EXT,
-  cGL_POINT_SIZE: GL_POINT_SIZE,
-  cGL_MINMAX: GL_MINMAX,
-  cGL_SAMPLE_PATTERN_SGIS: GL_SAMPLE_PATTERN_SGIS,
-  cGL_SAMPLE_PATTERN_EXT: GL_SAMPLE_PATTERN_EXT,
-  cGL_UNIFORM_BLOCK_BINDING: GL_UNIFORM_BLOCK_BINDING,
-  cGL_POLYGON_STIPPLE: GL_POLYGON_STIPPLE,
-  cGL_LOGIC_OP: GL_LOGIC_OP,
-  cGL_ACCUM: GL_ACCUM,
-  cGL_FRAMEZOOM_SGIX: GL_FRAMEZOOM_SGIX,
-  cGL_DEPTH_BOUNDS_EXT: GL_DEPTH_BOUNDS_EXT,
-  cGL_TEXTURE_BUFFER_EXT: GL_TEXTURE_BUFFER_EXT,
-  cGL_POLYGON_MODE: GL_POLYGON_MODE,
-  cGL_TEXTURE_NORMAL_EXT: GL_TEXTURE_NORMAL_EXT,
-  cGL_PROGRAM_STRING_ARB: GL_PROGRAM_STRING_ARB,
-  cGL_PATH_COVER_DEPTH_FUNC_NV: GL_PATH_COVER_DEPTH_FUNC_NV,
-  cGL_TRANSFORM_FEEDBACK_ATTRIBS_NV: GL_TRANSFORM_FEEDBACK_ATTRIBS_NV,
-  cGL_ACTIVE_STENCIL_FACE_EXT: GL_ACTIVE_STENCIL_FACE_EXT,
-  cGL_DEPTH_FUNC: GL_DEPTH_FUNC,
-  cGL_SAMPLE_MASK_SGIS: GL_SAMPLE_MASK_SGIS
-].}
diff --git a/tests/deps/opengl-1.1.0/opengl.nimble b/tests/deps/opengl-1.1.0/opengl.nimble
deleted file mode 100644
index ac3b8aa32..000000000
--- a/tests/deps/opengl-1.1.0/opengl.nimble
+++ /dev/null
@@ -1,12 +0,0 @@
-# Package
-
-version = "1.1.0"
-author = "Andreas Rumpf"
-description = "an OpenGL wrapper"
-license = "MIT"
-
-srcDir = "src"
-
-# Dependencies"
-
-requires "nim >= 0.10.3", "x11"
diff --git a/tests/deps/opengl-1.1.0/wingl.nim b/tests/deps/opengl-1.1.0/wingl.nim
deleted file mode 100644
index 9497bffb4..000000000
--- a/tests/deps/opengl-1.1.0/wingl.nim
+++ /dev/null
@@ -1,369 +0,0 @@
-import opengl, windows
-
-{.deadCodeElim: on.}
-
-proc wglGetExtensionsStringARB*(hdc: HDC): cstring{.dynlib: dllname,
-    importc: "wglGetExtensionsStringARB".}
-const
-  WGL_FRONT_COLOR_BUFFER_BIT_ARB* = 0x00000001
-  WGL_BACK_COLOR_BUFFER_BIT_ARB* = 0x00000002
-  WGL_DEPTH_BUFFER_BIT_ARB* = 0x00000004
-  WGL_STENCIL_BUFFER_BIT_ARB* = 0x00000008
-
-proc WinChoosePixelFormat*(DC: HDC, p2: PPixelFormatDescriptor): int{.
-    dynlib: "gdi32", importc: "ChoosePixelFormat".}
-proc wglCreateBufferRegionARB*(hDC: HDC, iLayerPlane: TGLint, uType: TGLuint): THandle{.
-    dynlib: dllname, importc: "wglCreateBufferRegionARB".}
-proc wglDeleteBufferRegionARB*(hRegion: THandle){.dynlib: dllname,
-    importc: "wglDeleteBufferRegionARB".}
-proc wglSaveBufferRegionARB*(hRegion: THandle, x: TGLint, y: TGLint,
-                             width: TGLint, height: TGLint): BOOL{.
-    dynlib: dllname, importc: "wglSaveBufferRegionARB".}
-proc wglRestoreBufferRegionARB*(hRegion: THandle, x: TGLint, y: TGLint,
-                                width: TGLint, height: TGLint, xSrc: TGLint,
-                                ySrc: TGLint): BOOL{.dynlib: dllname,
-    importc: "wglRestoreBufferRegionARB".}
-proc wglAllocateMemoryNV*(size: TGLsizei, readFrequency: TGLfloat,
-                          writeFrequency: TGLfloat, priority: TGLfloat): PGLvoid{.
-    dynlib: dllname, importc: "wglAllocateMemoryNV".}
-proc wglFreeMemoryNV*(pointer: PGLvoid){.dynlib: dllname,
-    importc: "wglFreeMemoryNV".}
-const
-  WGL_IMAGE_BUFFER_MIN_ACCESS_I3D* = 0x00000001
-  WGL_IMAGE_BUFFER_LOCK_I3D* = 0x00000002
-
-proc wglCreateImageBufferI3D*(hDC: HDC, dwSize: DWORD, uFlags: UINT): PGLvoid{.
-    dynlib: dllname, importc: "wglCreateImageBufferI3D".}
-proc wglDestroyImageBufferI3D*(hDC: HDC, pAddress: PGLvoid): BOOL{.
-    dynlib: dllname, importc: "wglDestroyImageBufferI3D".}
-proc wglAssociateImageBufferEventsI3D*(hdc: HDC, pEvent: PHandle,
-                                       pAddress: PGLvoid, pSize: PDWORD,
-                                       count: UINT): BOOL{.dynlib: dllname,
-    importc: "wglAssociateImageBufferEventsI3D".}
-proc wglReleaseImageBufferEventsI3D*(hdc: HDC, pAddress: PGLvoid, count: UINT): BOOL{.
-    dynlib: dllname, importc: "wglReleaseImageBufferEventsI3D".}
-proc wglEnableFrameLockI3D*(): BOOL{.dynlib: dllname,
-                                     importc: "wglEnableFrameLockI3D".}
-proc wglDisableFrameLockI3D*(): BOOL{.dynlib: dllname,
-                                      importc: "wglDisableFrameLockI3D".}
-proc wglIsEnabledFrameLockI3D*(pFlag: PBOOL): BOOL{.dynlib: dllname,
-    importc: "wglIsEnabledFrameLockI3D".}
-proc wglQueryFrameLockMasterI3D*(pFlag: PBOOL): BOOL{.dynlib: dllname,
-    importc: "wglQueryFrameLockMasterI3D".}
-proc wglGetFrameUsageI3D*(pUsage: PGLfloat): BOOL{.dynlib: dllname,
-    importc: "wglGetFrameUsageI3D".}
-proc wglBeginFrameTrackingI3D*(): BOOL{.dynlib: dllname,
-                                        importc: "wglBeginFrameTrackingI3D".}
-proc wglEndFrameTrackingI3D*(): BOOL{.dynlib: dllname,
-                                      importc: "wglEndFrameTrackingI3D".}
-proc wglQueryFrameTrackingI3D*(pFrameCount: PDWORD, pMissedFrames: PDWORD,
-                               pLastMissedUsage: PGLfloat): BOOL{.
-    dynlib: dllname, importc: "wglQueryFrameTrackingI3D".}
-const
-  WGL_NUMBER_PIXEL_FORMATS_ARB* = 0x00002000
-  WGL_DRAW_TO_WINDOW_ARB* = 0x00002001
-  WGL_DRAW_TO_BITMAP_ARB* = 0x00002002
-  WGL_ACCELERATION_ARB* = 0x00002003
-  WGL_NEED_PALETTE_ARB* = 0x00002004
-  WGL_NEED_SYSTEM_PALETTE_ARB* = 0x00002005
-  WGL_SWAP_LAYER_BUFFERS_ARB* = 0x00002006
-  WGL_SWAP_METHOD_ARB* = 0x00002007
-  WGL_NUMBER_OVERLAYS_ARB* = 0x00002008
-  WGL_NUMBER_UNDERLAYS_ARB* = 0x00002009
-  WGL_TRANSPARENT_ARB* = 0x0000200A
-  WGL_TRANSPARENT_RED_VALUE_ARB* = 0x00002037
-  WGL_TRANSPARENT_GREEN_VALUE_ARB* = 0x00002038
-  WGL_TRANSPARENT_BLUE_VALUE_ARB* = 0x00002039
-  WGL_TRANSPARENT_ALPHA_VALUE_ARB* = 0x0000203A
-  WGL_TRANSPARENT_INDEX_VALUE_ARB* = 0x0000203B
-  WGL_SHARE_DEPTH_ARB* = 0x0000200C
-  WGL_SHARE_STENCIL_ARB* = 0x0000200D
-  WGL_SHARE_ACCUM_ARB* = 0x0000200E
-  WGL_SUPPORT_GDI_ARB* = 0x0000200F
-  WGL_SUPPORT_OPENGL_ARB* = 0x00002010
-  WGL_DOUBLE_BUFFER_ARB* = 0x00002011
-  WGL_STEREO_ARB* = 0x00002012
-  WGL_PIXEL_TYPE_ARB* = 0x00002013
-  WGL_COLOR_BITS_ARB* = 0x00002014
-  WGL_RED_BITS_ARB* = 0x00002015
-  WGL_RED_SHIFT_ARB* = 0x00002016
-  WGL_GREEN_BITS_ARB* = 0x00002017
-  WGL_GREEN_SHIFT_ARB* = 0x00002018
-  WGL_BLUE_BITS_ARB* = 0x00002019
-  WGL_BLUE_SHIFT_ARB* = 0x0000201A
-  WGL_ALPHA_BITS_ARB* = 0x0000201B
-  WGL_ALPHA_SHIFT_ARB* = 0x0000201C
-  WGL_ACCUM_BITS_ARB* = 0x0000201D
-  WGL_ACCUM_RED_BITS_ARB* = 0x0000201E
-  WGL_ACCUM_GREEN_BITS_ARB* = 0x0000201F
-  WGL_ACCUM_BLUE_BITS_ARB* = 0x00002020
-  WGL_ACCUM_ALPHA_BITS_ARB* = 0x00002021
-  WGL_DEPTH_BITS_ARB* = 0x00002022
-  WGL_STENCIL_BITS_ARB* = 0x00002023
-  WGL_AUX_BUFFERS_ARB* = 0x00002024
-  WGL_NO_ACCELERATION_ARB* = 0x00002025
-  WGL_GENERIC_ACCELERATION_ARB* = 0x00002026
-  WGL_FULL_ACCELERATION_ARB* = 0x00002027
-  WGL_SWAP_EXCHANGE_ARB* = 0x00002028
-  WGL_SWAP_COPY_ARB* = 0x00002029
-  WGL_SWAP_UNDEFINED_ARB* = 0x0000202A
-  WGL_TYPE_RGBA_ARB* = 0x0000202B
-  WGL_TYPE_COLORINDEX_ARB* = 0x0000202C
-
-proc wglGetPixelFormatAttribivARB*(hdc: HDC, iPixelFormat: TGLint,
-                                   iLayerPlane: TGLint, nAttributes: TGLuint,
-                                   piAttributes: PGLint, piValues: PGLint): BOOL{.
-    dynlib: dllname, importc: "wglGetPixelFormatAttribivARB".}
-proc wglGetPixelFormatAttribfvARB*(hdc: HDC, iPixelFormat: TGLint,
-                                   iLayerPlane: TGLint, nAttributes: TGLuint,
-                                   piAttributes: PGLint, pfValues: PGLfloat): BOOL{.
-    dynlib: dllname, importc: "wglGetPixelFormatAttribfvARB".}
-proc wglChoosePixelFormatARB*(hdc: HDC, piAttribIList: PGLint,
-                              pfAttribFList: PGLfloat, nMaxFormats: TGLuint,
-                              piFormats: PGLint, nNumFormats: PGLuint): BOOL{.
-    dynlib: dllname, importc: "wglChoosePixelFormatARB".}
-const
-  WGL_ERROR_INVALID_PIXEL_TYPE_ARB* = 0x00002043
-  WGL_ERROR_INCOMPATIBLE_DEVICE_CONTEXTS_ARB* = 0x00002054
-
-proc wglMakeContextCurrentARB*(hDrawDC: HDC, hReadDC: HDC, hglrc: HGLRC): BOOL{.
-    dynlib: dllname, importc: "wglMakeContextCurrentARB".}
-proc wglGetCurrentReadDCARB*(): HDC{.dynlib: dllname,
-                                     importc: "wglGetCurrentReadDCARB".}
-const
-  WGL_DRAW_TO_PBUFFER_ARB* = 0x0000202D # WGL_DRAW_TO_PBUFFER_ARB  { already defined }
-  WGL_MAX_PBUFFER_PIXELS_ARB* = 0x0000202E
-  WGL_MAX_PBUFFER_WIDTH_ARB* = 0x0000202F
-  WGL_MAX_PBUFFER_HEIGHT_ARB* = 0x00002030
-  WGL_PBUFFER_LARGEST_ARB* = 0x00002033
-  WGL_PBUFFER_WIDTH_ARB* = 0x00002034
-  WGL_PBUFFER_HEIGHT_ARB* = 0x00002035
-  WGL_PBUFFER_LOST_ARB* = 0x00002036
-
-proc wglCreatePbufferARB*(hDC: HDC, iPixelFormat: TGLint, iWidth: TGLint,
-                          iHeight: TGLint, piAttribList: PGLint): THandle{.
-    dynlib: dllname, importc: "wglCreatePbufferARB".}
-proc wglGetPbufferDCARB*(hPbuffer: THandle): HDC{.dynlib: dllname,
-    importc: "wglGetPbufferDCARB".}
-proc wglReleasePbufferDCARB*(hPbuffer: THandle, hDC: HDC): TGLint{.
-    dynlib: dllname, importc: "wglReleasePbufferDCARB".}
-proc wglDestroyPbufferARB*(hPbuffer: THandle): BOOL{.dynlib: dllname,
-    importc: "wglDestroyPbufferARB".}
-proc wglQueryPbufferARB*(hPbuffer: THandle, iAttribute: TGLint, piValue: PGLint): BOOL{.
-    dynlib: dllname, importc: "wglQueryPbufferARB".}
-proc wglSwapIntervalEXT*(interval: TGLint): BOOL{.dynlib: dllname,
-    importc: "wglSwapIntervalEXT".}
-proc wglGetSwapIntervalEXT*(): TGLint{.dynlib: dllname,
-                                       importc: "wglGetSwapIntervalEXT".}
-const
-  WGL_BIND_TO_TEXTURE_RGB_ARB* = 0x00002070
-  WGL_BIND_TO_TEXTURE_RGBA_ARB* = 0x00002071
-  WGL_TEXTURE_FORMAT_ARB* = 0x00002072
-  WGL_TEXTURE_TARGET_ARB* = 0x00002073
-  WGL_MIPMAP_TEXTURE_ARB* = 0x00002074
-  WGL_TEXTURE_RGB_ARB* = 0x00002075
-  WGL_TEXTURE_RGBA_ARB* = 0x00002076
-  WGL_NO_TEXTURE_ARB* = 0x00002077
-  WGL_TEXTURE_CUBE_MAP_ARB* = 0x00002078
-  WGL_TEXTURE_1D_ARB* = 0x00002079
-  WGL_TEXTURE_2D_ARB* = 0x0000207A # WGL_NO_TEXTURE_ARB  { already defined }
-  WGL_MIPMAP_LEVEL_ARB* = 0x0000207B
-  WGL_CUBE_MAP_FACE_ARB* = 0x0000207C
-  WGL_TEXTURE_CUBE_MAP_POSITIVE_X_ARB* = 0x0000207D
-  WGL_TEXTURE_CUBE_MAP_NEGATIVE_X_ARB* = 0x0000207E
-  WGL_TEXTURE_CUBE_MAP_POSITIVE_Y_ARB* = 0x0000207F
-  WGL_TEXTURE_CUBE_MAP_NEGATIVE_Y_ARB* = 0x00002080
-  WGL_TEXTURE_CUBE_MAP_POSITIVE_Z_ARB* = 0x00002081
-  WGL_TEXTURE_CUBE_MAP_NEGATIVE_Z_ARB* = 0x00002082
-  WGL_FRONT_LEFT_ARB* = 0x00002083
-  WGL_FRONT_RIGHT_ARB* = 0x00002084
-  WGL_BACK_LEFT_ARB* = 0x00002085
-  WGL_BACK_RIGHT_ARB* = 0x00002086
-  WGL_AUX0_ARB* = 0x00002087
-  WGL_AUX1_ARB* = 0x00002088
-  WGL_AUX2_ARB* = 0x00002089
-  WGL_AUX3_ARB* = 0x0000208A
-  WGL_AUX4_ARB* = 0x0000208B
-  WGL_AUX5_ARB* = 0x0000208C
-  WGL_AUX6_ARB* = 0x0000208D
-  WGL_AUX7_ARB* = 0x0000208E
-  WGL_AUX8_ARB* = 0x0000208F
-  WGL_AUX9_ARB* = 0x00002090
-
-proc wglBindTexImageARB*(hPbuffer: THandle, iBuffer: TGLint): BOOL{.
-    dynlib: dllname, importc: "wglBindTexImageARB".}
-proc wglReleaseTexImageARB*(hPbuffer: THandle, iBuffer: TGLint): BOOL{.
-    dynlib: dllname, importc: "wglReleaseTexImageARB".}
-proc wglSetPbufferAttribARB*(hPbuffer: THandle, piAttribList: PGLint): BOOL{.
-    dynlib: dllname, importc: "wglSetPbufferAttribARB".}
-proc wglGetExtensionsStringEXT*(): cstring{.dynlib: dllname,
-    importc: "wglGetExtensionsStringEXT".}
-proc wglMakeContextCurrentEXT*(hDrawDC: HDC, hReadDC: HDC, hglrc: HGLRC): BOOL{.
-    dynlib: dllname, importc: "wglMakeContextCurrentEXT".}
-proc wglGetCurrentReadDCEXT*(): HDC{.dynlib: dllname,
-                                     importc: "wglGetCurrentReadDCEXT".}
-const
-  WGL_DRAW_TO_PBUFFER_EXT* = 0x0000202D
-  WGL_MAX_PBUFFER_PIXELS_EXT* = 0x0000202E
-  WGL_MAX_PBUFFER_WIDTH_EXT* = 0x0000202F
-  WGL_MAX_PBUFFER_HEIGHT_EXT* = 0x00002030
-  WGL_OPTIMAL_PBUFFER_WIDTH_EXT* = 0x00002031
-  WGL_OPTIMAL_PBUFFER_HEIGHT_EXT* = 0x00002032
-  WGL_PBUFFER_LARGEST_EXT* = 0x00002033
-  WGL_PBUFFER_WIDTH_EXT* = 0x00002034
-  WGL_PBUFFER_HEIGHT_EXT* = 0x00002035
-
-proc wglCreatePbufferEXT*(hDC: HDC, iPixelFormat: TGLint, iWidth: TGLint,
-                          iHeight: TGLint, piAttribList: PGLint): THandle{.
-    dynlib: dllname, importc: "wglCreatePbufferEXT".}
-proc wglGetPbufferDCEXT*(hPbuffer: THandle): HDC{.dynlib: dllname,
-    importc: "wglGetPbufferDCEXT".}
-proc wglReleasePbufferDCEXT*(hPbuffer: THandle, hDC: HDC): TGLint{.
-    dynlib: dllname, importc: "wglReleasePbufferDCEXT".}
-proc wglDestroyPbufferEXT*(hPbuffer: THandle): BOOL{.dynlib: dllname,
-    importc: "wglDestroyPbufferEXT".}
-proc wglQueryPbufferEXT*(hPbuffer: THandle, iAttribute: TGLint, piValue: PGLint): BOOL{.
-    dynlib: dllname, importc: "wglQueryPbufferEXT".}
-const
-  WGL_NUMBER_PIXEL_FORMATS_EXT* = 0x00002000
-  WGL_DRAW_TO_WINDOW_EXT* = 0x00002001
-  WGL_DRAW_TO_BITMAP_EXT* = 0x00002002
-  WGL_ACCELERATION_EXT* = 0x00002003
-  WGL_NEED_PALETTE_EXT* = 0x00002004
-  WGL_NEED_SYSTEM_PALETTE_EXT* = 0x00002005
-  WGL_SWAP_LAYER_BUFFERS_EXT* = 0x00002006
-  WGL_SWAP_METHOD_EXT* = 0x00002007
-  WGL_NUMBER_OVERLAYS_EXT* = 0x00002008
-  WGL_NUMBER_UNDERLAYS_EXT* = 0x00002009
-  WGL_TRANSPARENT_EXT* = 0x0000200A
-  WGL_TRANSPARENT_VALUE_EXT* = 0x0000200B
-  WGL_SHARE_DEPTH_EXT* = 0x0000200C
-  WGL_SHARE_STENCIL_EXT* = 0x0000200D
-  WGL_SHARE_ACCUM_EXT* = 0x0000200E
-  WGL_SUPPORT_GDI_EXT* = 0x0000200F
-  WGL_SUPPORT_OPENGL_EXT* = 0x00002010
-  WGL_DOUBLE_BUFFER_EXT* = 0x00002011
-  WGL_STEREO_EXT* = 0x00002012
-  WGL_PIXEL_TYPE_EXT* = 0x00002013
-  WGL_COLOR_BITS_EXT* = 0x00002014
-  WGL_RED_BITS_EXT* = 0x00002015
-  WGL_RED_SHIFT_EXT* = 0x00002016
-  WGL_GREEN_BITS_EXT* = 0x00002017
-  WGL_GREEN_SHIFT_EXT* = 0x00002018
-  WGL_BLUE_BITS_EXT* = 0x00002019
-  WGL_BLUE_SHIFT_EXT* = 0x0000201A
-  WGL_ALPHA_BITS_EXT* = 0x0000201B
-  WGL_ALPHA_SHIFT_EXT* = 0x0000201C
-  WGL_ACCUM_BITS_EXT* = 0x0000201D
-  WGL_ACCUM_RED_BITS_EXT* = 0x0000201E
-  WGL_ACCUM_GREEN_BITS_EXT* = 0x0000201F
-  WGL_ACCUM_BLUE_BITS_EXT* = 0x00002020
-  WGL_ACCUM_ALPHA_BITS_EXT* = 0x00002021
-  WGL_DEPTH_BITS_EXT* = 0x00002022
-  WGL_STENCIL_BITS_EXT* = 0x00002023
-  WGL_AUX_BUFFERS_EXT* = 0x00002024
-  WGL_NO_ACCELERATION_EXT* = 0x00002025
-  WGL_GENERIC_ACCELERATION_EXT* = 0x00002026
-  WGL_FULL_ACCELERATION_EXT* = 0x00002027
-  WGL_SWAP_EXCHANGE_EXT* = 0x00002028
-  WGL_SWAP_COPY_EXT* = 0x00002029
-  WGL_SWAP_UNDEFINED_EXT* = 0x0000202A
-  WGL_TYPE_RGBA_EXT* = 0x0000202B
-  WGL_TYPE_COLORINDEX_EXT* = 0x0000202C
-
-proc wglGetPixelFormatAttribivEXT*(hdc: HDC, iPixelFormat: TGLint,
-                                   iLayerPlane: TGLint, nAttributes: TGLuint,
-                                   piAttributes: PGLint, piValues: PGLint): BOOL{.
-    dynlib: dllname, importc: "wglGetPixelFormatAttribivEXT".}
-proc wglGetPixelFormatAttribfvEXT*(hdc: HDC, iPixelFormat: TGLint,
-                                   iLayerPlane: TGLint, nAttributes: TGLuint,
-                                   piAttributes: PGLint, pfValues: PGLfloat): BOOL{.
-    dynlib: dllname, importc: "wglGetPixelFormatAttribfvEXT".}
-proc wglChoosePixelFormatEXT*(hdc: HDC, piAttribIList: PGLint,
-                              pfAttribFList: PGLfloat, nMaxFormats: TGLuint,
-                              piFormats: PGLint, nNumFormats: PGLuint): BOOL{.
-    dynlib: dllname, importc: "wglChoosePixelFormatEXT".}
-const
-  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_FRAMEBUFFER_I3D* = 0x00002050
-  WGL_DIGITAL_VIDEO_CURSOR_ALPHA_VALUE_I3D* = 0x00002051
-  WGL_DIGITAL_VIDEO_CURSOR_INCLUDED_I3D* = 0x00002052
-  WGL_DIGITAL_VIDEO_GAMMA_CORRECTED_I3D* = 0x00002053
-
-proc wglGetDigitalVideoParametersI3D*(hDC: HDC, iAttribute: TGLint,
-                                      piValue: PGLint): BOOL{.dynlib: dllname,
-    importc: "wglGetDigitalVideoParametersI3D".}
-proc wglSetDigitalVideoParametersI3D*(hDC: HDC, iAttribute: TGLint,
-                                      piValue: PGLint): BOOL{.dynlib: dllname,
-    importc: "wglSetDigitalVideoParametersI3D".}
-const
-  WGL_GAMMA_TABLE_SIZE_I3D* = 0x0000204E
-  WGL_GAMMA_EXCLUDE_DESKTOP_I3D* = 0x0000204F
-
-proc wglGetGammaTableParametersI3D*(hDC: HDC, iAttribute: TGLint,
-                                    piValue: PGLint): BOOL{.dynlib: dllname,
-    importc: "wglGetGammaTableParametersI3D".}
-proc wglSetGammaTableParametersI3D*(hDC: HDC, iAttribute: TGLint,
-                                    piValue: PGLint): BOOL{.dynlib: dllname,
-    importc: "wglSetGammaTableParametersI3D".}
-proc wglGetGammaTableI3D*(hDC: HDC, iEntries: TGLint, puRed: PGLUSHORT,
-                          puGreen: PGLUSHORT, puBlue: PGLUSHORT): BOOL{.
-    dynlib: dllname, importc: "wglGetGammaTableI3D".}
-proc wglSetGammaTableI3D*(hDC: HDC, iEntries: TGLint, puRed: PGLUSHORT,
-                          puGreen: PGLUSHORT, puBlue: PGLUSHORT): BOOL{.
-    dynlib: dllname, importc: "wglSetGammaTableI3D".}
-const
-  WGL_GENLOCK_SOURCE_MULTIVIEW_I3D* = 0x00002044
-  WGL_GENLOCK_SOURCE_EXTERNAL_SYNC_I3D* = 0x00002045
-  WGL_GENLOCK_SOURCE_EXTERNAL_FIELD_I3D* = 0x00002046
-  WGL_GENLOCK_SOURCE_EXTERNAL_TTL_I3D* = 0x00002047
-  WGL_GENLOCK_SOURCE_DIGITAL_SYNC_I3D* = 0x00002048
-  WGL_GENLOCK_SOURCE_DIGITAL_FIELD_I3D* = 0x00002049
-  WGL_GENLOCK_SOURCE_EDGE_FALLING_I3D* = 0x0000204A
-  WGL_GENLOCK_SOURCE_EDGE_RISING_I3D* = 0x0000204B
-  WGL_GENLOCK_SOURCE_EDGE_BOTH_I3D* = 0x0000204C
-  WGL_FLOAT_COMPONENTS_NV* = 0x000020B0
-  WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_R_NV* = 0x000020B1
-  WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RG_NV* = 0x000020B2
-  WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGB_NV* = 0x000020B3
-  WGL_BIND_TO_TEXTURE_RECTANGLE_FLOAT_RGBA_NV* = 0x000020B4
-  WGL_TEXTURE_FLOAT_R_NV* = 0x000020B5
-  WGL_TEXTURE_FLOAT_RG_NV* = 0x000020B6
-  WGL_TEXTURE_FLOAT_RGB_NV* = 0x000020B7
-  WGL_TEXTURE_FLOAT_RGBA_NV* = 0x000020B8
-
-proc wglEnableGenlockI3D*(hDC: HDC): BOOL{.dynlib: dllname,
-    importc: "wglEnableGenlockI3D".}
-proc wglDisableGenlockI3D*(hDC: HDC): BOOL{.dynlib: dllname,
-    importc: "wglDisableGenlockI3D".}
-proc wglIsEnabledGenlockI3D*(hDC: HDC, pFlag: PBOOL): BOOL{.dynlib: dllname,
-    importc: "wglIsEnabledGenlockI3D".}
-proc wglGenlockSourceI3D*(hDC: HDC, uSource: TGLuint): BOOL{.dynlib: dllname,
-    importc: "wglGenlockSourceI3D".}
-proc wglGetGenlockSourceI3D*(hDC: HDC, uSource: PGLUINT): BOOL{.dynlib: dllname,
-    importc: "wglGetGenlockSourceI3D".}
-proc wglGenlockSourceEdgeI3D*(hDC: HDC, uEdge: TGLuint): BOOL{.dynlib: dllname,
-    importc: "wglGenlockSourceEdgeI3D".}
-proc wglGetGenlockSourceEdgeI3D*(hDC: HDC, uEdge: PGLUINT): BOOL{.
-    dynlib: dllname, importc: "wglGetGenlockSourceEdgeI3D".}
-proc wglGenlockSampleRateI3D*(hDC: HDC, uRate: TGLuint): BOOL{.dynlib: dllname,
-    importc: "wglGenlockSampleRateI3D".}
-proc wglGetGenlockSampleRateI3D*(hDC: HDC, uRate: PGLUINT): BOOL{.
-    dynlib: dllname, importc: "wglGetGenlockSampleRateI3D".}
-proc wglGenlockSourceDelayI3D*(hDC: HDC, uDelay: TGLuint): BOOL{.
-    dynlib: dllname, importc: "wglGenlockSourceDelayI3D".}
-proc wglGetGenlockSourceDelayI3D*(hDC: HDC, uDelay: PGLUINT): BOOL{.
-    dynlib: dllname, importc: "wglGetGenlockSourceDelayI3D".}
-proc wglQueryGenlockMaxSourceDelayI3D*(hDC: HDC, uMaxLineDelay: PGLUINT,
-                                       uMaxPixelDelay: PGLUINT): BOOL{.
-    dynlib: dllname, importc: "wglQueryGenlockMaxSourceDelayI3D".}
-const
-  WGL_BIND_TO_TEXTURE_RECTANGLE_RGB_NV* = 0x000020A0
-  WGL_BIND_TO_TEXTURE_RECTANGLE_RGBA_NV* = 0x000020A1
-  WGL_TEXTURE_RECTANGLE_NV* = 0x000020A2
-
-const
-  WGL_RGBA_FLOAT_MODE_ATI* = 0x00008820
-  WGL_COLOR_CLEAR_UNCLAMPED_VALUE_ATI* = 0x00008835
-  WGL_TYPE_RGBA_FLOAT_ATI* = 0x000021A0
-
-# implementation
diff --git a/tests/deps/x11-1.0/cursorfont.nim b/tests/deps/x11-1.0/cursorfont.nim
deleted file mode 100644
index b262ad7c1..000000000
--- a/tests/deps/x11-1.0/cursorfont.nim
+++ /dev/null
@@ -1,110 +0,0 @@
-# $Xorg: cursorfont.h,v 1.4 2001/02/09 02:03:39 xorgcvs Exp $ 
-#
-#
-#Copyright 1987, 1998  The Open Group
-#
-#Permission to use, copy, modify, distribute, and sell this software and its
-#documentation for any purpose is hereby granted without fee, provided that
-#the above copyright notice appear in all copies and that both that
-#copyright notice and this permission notice appear in supporting
-#documentation.
-#
-#The above copyright notice and this permission notice shall be included
-#in all copies or substantial portions of the Software.
-#
-#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-#OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-#IN NO EVENT SHALL THE OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR
-#OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-#ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-#OTHER DEALINGS IN THE SOFTWARE.
-#
-#Except as contained in this notice, the name of The Open Group shall
-#not be used in advertising or otherwise to promote the sale, use or
-#other dealings in this Software without prior written authorization
-#from The Open Group.
-#
-#
-
-const 
-  XC_num_glyphs* = 154
-  XC_X_cursor* = 0
-  XC_arrow* = 2
-  XC_based_arrow_down* = 4
-  XC_based_arrow_up* = 6
-  XC_boat* = 8
-  XC_bogosity* = 10
-  XC_bottom_left_corner* = 12
-  XC_bottom_right_corner* = 14
-  XC_bottom_side* = 16
-  XC_bottom_tee* = 18
-  XC_box_spiral* = 20
-  XC_center_ptr* = 22
-  XC_circle* = 24
-  XC_clock* = 26
-  XC_coffee_mug* = 28
-  XC_cross* = 30
-  XC_cross_reverse* = 32
-  XC_crosshair* = 34
-  XC_diamond_cross* = 36
-  XC_dot* = 38
-  XC_dotbox* = 40
-  XC_double_arrow* = 42
-  XC_draft_large* = 44
-  XC_draft_small* = 46
-  XC_draped_box* = 48
-  XC_exchange* = 50
-  XC_fleur* = 52
-  XC_gobbler* = 54
-  XC_gumby* = 56
-  XC_hand1* = 58
-  XC_hand2* = 60
-  XC_heart* = 62
-  XC_icon* = 64
-  XC_iron_cross* = 66
-  XC_left_ptr* = 68
-  XC_left_side* = 70
-  XC_left_tee* = 72
-  XC_leftbutton* = 74
-  XC_ll_angle* = 76
-  XC_lr_angle* = 78
-  XC_man* = 80
-  XC_middlebutton* = 82
-  XC_mouse* = 84
-  XC_pencil* = 86
-  XC_pirate* = 88
-  XC_plus* = 90
-  XC_question_arrow* = 92
-  XC_right_ptr* = 94
-  XC_right_side* = 96
-  XC_right_tee* = 98
-  XC_rightbutton* = 100
-  XC_rtl_logo* = 102
-  XC_sailboat* = 104
-  XC_sb_down_arrow* = 106
-  XC_sb_h_double_arrow* = 108
-  XC_sb_left_arrow* = 110
-  XC_sb_right_arrow* = 112
-  XC_sb_up_arrow* = 114
-  XC_sb_v_double_arrow* = 116
-  XC_shuttle* = 118
-  XC_sizing* = 120
-  XC_spider* = 122
-  XC_spraycan* = 124
-  XC_star* = 126
-  XC_target* = 128
-  XC_tcross* = 130
-  XC_top_left_arrow* = 132
-  XC_top_left_corner* = 134
-  XC_top_right_corner* = 136
-  XC_top_side* = 138
-  XC_top_tee* = 140
-  XC_trek* = 142
-  XC_ul_angle* = 144
-  XC_umbrella* = 146
-  XC_ur_angle* = 148
-  XC_watch* = 150
-  XC_xterm* = 152
-
-# implementation
diff --git a/tests/deps/x11-1.0/keysym.nim b/tests/deps/x11-1.0/keysym.nim
deleted file mode 100644
index c001ab622..000000000
--- a/tests/deps/x11-1.0/keysym.nim
+++ /dev/null
@@ -1,1926 +0,0 @@
-#
-#Converted from X11/keysym.h and X11/keysymdef.h
-#
-#Capital letter consts renamed from XK_... to XKc_...
-# (since Pascal isn't case-sensitive)
-#
-#i.e.
-#C      Pascal
-#XK_a   XK_a
-#XK_A   XKc_A
-#
-
-#* default keysyms *
-import x
-
-const 
-  XK_VoidSymbol*: TKeySym = 0x00FFFFFF # void symbol 
-
-when defined(XK_MISCELLANY) or true: 
-  const
-    #*
-    # * TTY Functions, cleverly chosen to map to ascii, for convenience of
-    # * programming, but could have been arbitrary (at the cost of lookup
-    # * tables in client code.
-    # *
-    XK_BackSpace*: TKeySym = 0x0000FF08  # back space, back char 
-    XK_Tab*: TKeySym = 0x0000FF09
-    XK_Linefeed*: TKeySym = 0x0000FF0A   # Linefeed, LF 
-    XK_Clear*: TKeySym = 0x0000FF0B
-    XK_Return*: TKeySym = 0x0000FF0D     # Return, enter 
-    XK_Pause*: TKeySym = 0x0000FF13      # Pause, hold 
-    XK_Scroll_Lock*: TKeySym = 0x0000FF14
-    XK_Sys_Req*: TKeySym = 0x0000FF15
-    XK_Escape*: TKeySym = 0x0000FF1B
-    XK_Delete*: TKeySym = 0x0000FFFF     # Delete, rubout \
-                                # International & multi-key character composition 
-    XK_Multi_key*: TKeySym = 0x0000FF20  # Multi-key character compose 
-    XK_Codeinput*: TKeySym = 0x0000FF37
-    XK_SingleCandidate*: TKeySym = 0x0000FF3C
-    XK_MultipleCandidate*: TKeySym = 0x0000FF3D
-    XK_PreviousCandidate*: TKeySym = 0x0000FF3E # Japanese keyboard support 
-    XK_Kanji*: TKeySym = 0x0000FF21      # Kanji, Kanji convert 
-    XK_Muhenkan*: TKeySym = 0x0000FF22   # Cancel Conversion 
-    XK_Henkan_Mode*: TKeySym = 0x0000FF23 # Start/Stop Conversion 
-    XK_Henkan*: TKeySym = 0x0000FF23     # Alias for Henkan_Mode 
-    XK_Romaji*: TKeySym = 0x0000FF24     # to Romaji 
-    XK_Hiragana*: TKeySym = 0x0000FF25   # to Hiragana 
-    XK_Katakana*: TKeySym = 0x0000FF26   # to Katakana 
-    XK_Hiragana_Katakana*: TKeySym = 0x0000FF27 # Hiragana/Katakana toggle 
-    XK_Zenkaku*: TKeySym = 0x0000FF28    # to Zenkaku 
-    XK_Hankaku*: TKeySym = 0x0000FF29    # to Hankaku 
-    XK_Zenkaku_Hankaku*: TKeySym = 0x0000FF2A # Zenkaku/Hankaku toggle 
-    XK_Touroku*: TKeySym = 0x0000FF2B    # Add to Dictionary 
-    XK_Massyo*: TKeySym = 0x0000FF2C     # Delete from Dictionary 
-    XK_Kana_Lock*: TKeySym = 0x0000FF2D  # Kana Lock 
-    XK_Kana_Shift*: TKeySym = 0x0000FF2E # Kana Shift 
-    XK_Eisu_Shift*: TKeySym = 0x0000FF2F # Alphanumeric Shift 
-    XK_Eisu_toggle*: TKeySym = 0x0000FF30 # Alphanumeric toggle 
-    XK_Kanji_Bangou*: TKeySym = 0x0000FF37 # Codeinput 
-    XK_Zen_Koho*: TKeySym = 0x0000FF3D   # Multiple/All Candidate(s) 
-    XK_Mae_Koho*: TKeySym = 0x0000FF3E   # Previous Candidate \
-                                # = $FF31 thru = $FF3F are under XK_KOREAN 
-                                # Cursor control & motion 
-    XK_Home*: TKeySym = 0x0000FF50
-    XK_Left*: TKeySym = 0x0000FF51       # Move left, left arrow 
-    XK_Up*: TKeySym = 0x0000FF52         # Move up, up arrow 
-    XK_Right*: TKeySym = 0x0000FF53      # Move right, right arrow 
-    XK_Down*: TKeySym = 0x0000FF54       # Move down, down arrow 
-    XK_Prior*: TKeySym = 0x0000FF55      # Prior, previous 
-    XK_Page_Up*: TKeySym = 0x0000FF55
-    XK_Next*: TKeySym = 0x0000FF56       # Next 
-    XK_Page_Down*: TKeySym = 0x0000FF56
-    XK_End*: TKeySym = 0x0000FF57        # EOL 
-    XK_Begin*: TKeySym = 0x0000FF58      # BOL \
-                                # Misc Functions 
-    XK_Select*: TKeySym = 0x0000FF60     # Select, mark 
-    XK_Print*: TKeySym = 0x0000FF61
-    XK_Execute*: TKeySym = 0x0000FF62    # Execute, run, do 
-    XK_Insert*: TKeySym = 0x0000FF63     # Insert, insert here 
-    XK_Undo*: TKeySym = 0x0000FF65       # Undo, oops 
-    XK_Redo*: TKeySym = 0x0000FF66       # redo, again 
-    XK_Menu*: TKeySym = 0x0000FF67
-    XK_Find*: TKeySym = 0x0000FF68       # Find, search 
-    XK_Cancel*: TKeySym = 0x0000FF69     # Cancel, stop, abort, exit 
-    XK_Help*: TKeySym = 0x0000FF6A       # Help 
-    XK_Break*: TKeySym = 0x0000FF6B
-    XK_Mode_switch*: TKeySym = 0x0000FF7E # Character set switch 
-    XK_script_switch*: TKeySym = 0x0000FF7E # Alias for mode_switch 
-    XK_Num_Lock*: TKeySym = 0x0000FF7F   # Keypad Functions, keypad numbers cleverly chosen to map to ascii 
-    XK_KP_Space*: TKeySym = 0x0000FF80   # space 
-    XK_KP_Tab*: TKeySym = 0x0000FF89
-    XK_KP_Enter*: TKeySym = 0x0000FF8D   # enter 
-    XK_KP_F1*: TKeySym = 0x0000FF91      # PF1, KP_A, ... 
-    XK_KP_F2*: TKeySym = 0x0000FF92
-    XK_KP_F3*: TKeySym = 0x0000FF93
-    XK_KP_F4*: TKeySym = 0x0000FF94
-    XK_KP_Home*: TKeySym = 0x0000FF95
-    XK_KP_Left*: TKeySym = 0x0000FF96
-    XK_KP_Up*: TKeySym = 0x0000FF97
-    XK_KP_Right*: TKeySym = 0x0000FF98
-    XK_KP_Down*: TKeySym = 0x0000FF99
-    XK_KP_Prior*: TKeySym = 0x0000FF9A
-    XK_KP_Page_Up*: TKeySym = 0x0000FF9A
-    XK_KP_Next*: TKeySym = 0x0000FF9B
-    XK_KP_Page_Down*: TKeySym = 0x0000FF9B
-    XK_KP_End*: TKeySym = 0x0000FF9C
-    XK_KP_Begin*: TKeySym = 0x0000FF9D
-    XK_KP_Insert*: TKeySym = 0x0000FF9E
-    XK_KP_Delete*: TKeySym = 0x0000FF9F
-    XK_KP_Equal*: TKeySym = 0x0000FFBD   # equals 
-    XK_KP_Multiply*: TKeySym = 0x0000FFAA
-    XK_KP_Add*: TKeySym = 0x0000FFAB
-    XK_KP_Separator*: TKeySym = 0x0000FFAC # separator, often comma 
-    XK_KP_Subtract*: TKeySym = 0x0000FFAD
-    XK_KP_Decimal*: TKeySym = 0x0000FFAE
-    XK_KP_Divide*: TKeySym = 0x0000FFAF
-    XK_KP_0*: TKeySym = 0x0000FFB0
-    XK_KP_1*: TKeySym = 0x0000FFB1
-    XK_KP_2*: TKeySym = 0x0000FFB2
-    XK_KP_3*: TKeySym = 0x0000FFB3
-    XK_KP_4*: TKeySym = 0x0000FFB4
-    XK_KP_5*: TKeySym = 0x0000FFB5
-    XK_KP_6*: TKeySym = 0x0000FFB6
-    XK_KP_7*: TKeySym = 0x0000FFB7
-    XK_KP_8*: TKeySym = 0x0000FFB8
-    XK_KP_9*: TKeySym = 0x0000FFB9 #*\
-                          # * Auxilliary Functions; note the duplicate definitions for left and right
-                          # * function keys;  Sun keyboards and a few other manufactures have such
-                          # * function key groups on the left and/or right sides of the keyboard.
-                          # * We've not found a keyboard with more than 35 function keys total.
-                          # *
-    XK_F1*: TKeySym = 0x0000FFBE
-    XK_F2*: TKeySym = 0x0000FFBF
-    XK_F3*: TKeySym = 0x0000FFC0
-    XK_F4*: TKeySym = 0x0000FFC1
-    XK_F5*: TKeySym = 0x0000FFC2
-    XK_F6*: TKeySym = 0x0000FFC3
-    XK_F7*: TKeySym = 0x0000FFC4
-    XK_F8*: TKeySym = 0x0000FFC5
-    XK_F9*: TKeySym = 0x0000FFC6
-    XK_F10*: TKeySym = 0x0000FFC7
-    XK_F11*: TKeySym = 0x0000FFC8
-    XK_L1*: TKeySym = 0x0000FFC8
-    XK_F12*: TKeySym = 0x0000FFC9
-    XK_L2*: TKeySym = 0x0000FFC9
-    XK_F13*: TKeySym = 0x0000FFCA
-    XK_L3*: TKeySym = 0x0000FFCA
-    XK_F14*: TKeySym = 0x0000FFCB
-    XK_L4*: TKeySym = 0x0000FFCB
-    XK_F15*: TKeySym = 0x0000FFCC
-    XK_L5*: TKeySym = 0x0000FFCC
-    XK_F16*: TKeySym = 0x0000FFCD
-    XK_L6*: TKeySym = 0x0000FFCD
-    XK_F17*: TKeySym = 0x0000FFCE
-    XK_L7*: TKeySym = 0x0000FFCE
-    XK_F18*: TKeySym = 0x0000FFCF
-    XK_L8*: TKeySym = 0x0000FFCF
-    XK_F19*: TKeySym = 0x0000FFD0
-    XK_L9*: TKeySym = 0x0000FFD0
-    XK_F20*: TKeySym = 0x0000FFD1
-    XK_L10*: TKeySym = 0x0000FFD1
-    XK_F21*: TKeySym = 0x0000FFD2
-    XK_R1*: TKeySym = 0x0000FFD2
-    XK_F22*: TKeySym = 0x0000FFD3
-    XK_R2*: TKeySym = 0x0000FFD3
-    XK_F23*: TKeySym = 0x0000FFD4
-    XK_R3*: TKeySym = 0x0000FFD4
-    XK_F24*: TKeySym = 0x0000FFD5
-    XK_R4*: TKeySym = 0x0000FFD5
-    XK_F25*: TKeySym = 0x0000FFD6
-    XK_R5*: TKeySym = 0x0000FFD6
-    XK_F26*: TKeySym = 0x0000FFD7
-    XK_R6*: TKeySym = 0x0000FFD7
-    XK_F27*: TKeySym = 0x0000FFD8
-    XK_R7*: TKeySym = 0x0000FFD8
-    XK_F28*: TKeySym = 0x0000FFD9
-    XK_R8*: TKeySym = 0x0000FFD9
-    XK_F29*: TKeySym = 0x0000FFDA
-    XK_R9*: TKeySym = 0x0000FFDA
-    XK_F30*: TKeySym = 0x0000FFDB
-    XK_R10*: TKeySym = 0x0000FFDB
-    XK_F31*: TKeySym = 0x0000FFDC
-    XK_R11*: TKeySym = 0x0000FFDC
-    XK_F32*: TKeySym = 0x0000FFDD
-    XK_R12*: TKeySym = 0x0000FFDD
-    XK_F33*: TKeySym = 0x0000FFDE
-    XK_R13*: TKeySym = 0x0000FFDE
-    XK_F34*: TKeySym = 0x0000FFDF
-    XK_R14*: TKeySym = 0x0000FFDF
-    XK_F35*: TKeySym = 0x0000FFE0
-    XK_R15*: TKeySym = 0x0000FFE0        # Modifiers 
-    XK_Shift_L*: TKeySym = 0x0000FFE1    # Left shift 
-    XK_Shift_R*: TKeySym = 0x0000FFE2    # Right shift 
-    XK_Control_L*: TKeySym = 0x0000FFE3  # Left control 
-    XK_Control_R*: TKeySym = 0x0000FFE4  # Right control 
-    XK_Caps_Lock*: TKeySym = 0x0000FFE5  # Caps lock 
-    XK_Shift_Lock*: TKeySym = 0x0000FFE6 # Shift lock 
-    XK_Meta_L*: TKeySym = 0x0000FFE7     # Left meta 
-    XK_Meta_R*: TKeySym = 0x0000FFE8     # Right meta 
-    XK_Alt_L*: TKeySym = 0x0000FFE9      # Left alt 
-    XK_Alt_R*: TKeySym = 0x0000FFEA      # Right alt 
-    XK_Super_L*: TKeySym = 0x0000FFEB    # Left super 
-    XK_Super_R*: TKeySym = 0x0000FFEC    # Right super 
-    XK_Hyper_L*: TKeySym = 0x0000FFED    # Left hyper 
-    XK_Hyper_R*: TKeySym = 0x0000FFEE    # Right hyper 
-# XK_MISCELLANY 
-#*
-# * ISO 9995 Function and Modifier Keys
-# * Byte 3 = = $FE
-# *
-
-when defined(XK_XKB_KEYS) or true: 
-  const
-    XK_ISO_Lock*: TKeySym = 0x0000FE01
-    XK_ISO_Level2_Latch*: TKeySym = 0x0000FE02
-    XK_ISO_Level3_Shift*: TKeySym = 0x0000FE03
-    XK_ISO_Level3_Latch*: TKeySym = 0x0000FE04
-    XK_ISO_Level3_Lock*: TKeySym = 0x0000FE05
-    XK_ISO_Group_Shift*: TKeySym = 0x0000FF7E # Alias for mode_switch 
-    XK_ISO_Group_Latch*: TKeySym = 0x0000FE06
-    XK_ISO_Group_Lock*: TKeySym = 0x0000FE07
-    XK_ISO_Next_Group*: TKeySym = 0x0000FE08
-    XK_ISO_Next_Group_Lock*: TKeySym = 0x0000FE09
-    XK_ISO_Prev_Group*: TKeySym = 0x0000FE0A
-    XK_ISO_Prev_Group_Lock*: TKeySym = 0x0000FE0B
-    XK_ISO_First_Group*: TKeySym = 0x0000FE0C
-    XK_ISO_First_Group_Lock*: TKeySym = 0x0000FE0D
-    XK_ISO_Last_Group*: TKeySym = 0x0000FE0E
-    XK_ISO_Last_Group_Lock*: TKeySym = 0x0000FE0F
-    XK_ISO_Left_Tab*: TKeySym = 0x0000FE20
-    XK_ISO_Move_Line_Up*: TKeySym = 0x0000FE21
-    XK_ISO_Move_Line_Down*: TKeySym = 0x0000FE22
-    XK_ISO_Partial_Line_Up*: TKeySym = 0x0000FE23
-    XK_ISO_Partial_Line_Down*: TKeySym = 0x0000FE24
-    XK_ISO_Partial_Space_Left*: TKeySym = 0x0000FE25
-    XK_ISO_Partial_Space_Right*: TKeySym = 0x0000FE26
-    XK_ISO_Set_Margin_Left*: TKeySym = 0x0000FE27
-    XK_ISO_Set_Margin_Right*: TKeySym = 0x0000FE28
-    XK_ISO_Release_Margin_Left*: TKeySym = 0x0000FE29
-    XK_ISO_Release_Margin_Right*: TKeySym = 0x0000FE2A
-    XK_ISO_Release_Both_Margins*: TKeySym = 0x0000FE2B
-    XK_ISO_Fast_Cursor_Left*: TKeySym = 0x0000FE2C
-    XK_ISO_Fast_Cursor_Right*: TKeySym = 0x0000FE2D
-    XK_ISO_Fast_Cursor_Up*: TKeySym = 0x0000FE2E
-    XK_ISO_Fast_Cursor_Down*: TKeySym = 0x0000FE2F
-    XK_ISO_Continuous_Underline*: TKeySym = 0x0000FE30
-    XK_ISO_Discontinuous_Underline*: TKeySym = 0x0000FE31
-    XK_ISO_Emphasize*: TKeySym = 0x0000FE32
-    XK_ISO_Center_Object*: TKeySym = 0x0000FE33
-    XK_ISO_Enter*: TKeySym = 0x0000FE34
-    XK_dead_grave*: TKeySym = 0x0000FE50
-    XK_dead_acute*: TKeySym = 0x0000FE51
-    XK_dead_circumflex*: TKeySym = 0x0000FE52
-    XK_dead_tilde*: TKeySym = 0x0000FE53
-    XK_dead_macron*: TKeySym = 0x0000FE54
-    XK_dead_breve*: TKeySym = 0x0000FE55
-    XK_dead_abovedot*: TKeySym = 0x0000FE56
-    XK_dead_diaeresis*: TKeySym = 0x0000FE57
-    XK_dead_abovering*: TKeySym = 0x0000FE58
-    XK_dead_doubleacute*: TKeySym = 0x0000FE59
-    XK_dead_caron*: TKeySym = 0x0000FE5A
-    XK_dead_cedilla*: TKeySym = 0x0000FE5B
-    XK_dead_ogonek*: TKeySym = 0x0000FE5C
-    XK_dead_iota*: TKeySym = 0x0000FE5D
-    XK_dead_voiced_sound*: TKeySym = 0x0000FE5E
-    XK_dead_semivoiced_sound*: TKeySym = 0x0000FE5F
-    XK_dead_belowdot*: TKeySym = 0x0000FE60
-    XK_dead_hook*: TKeySym = 0x0000FE61
-    XK_dead_horn*: TKeySym = 0x0000FE62
-    XK_First_Virtual_Screen*: TKeySym = 0x0000FED0
-    XK_Prev_Virtual_Screen*: TKeySym = 0x0000FED1
-    XK_Next_Virtual_Screen*: TKeySym = 0x0000FED2
-    XK_Last_Virtual_Screen*: TKeySym = 0x0000FED4
-    XK_Terminate_Server*: TKeySym = 0x0000FED5
-    XK_AccessX_Enable*: TKeySym = 0x0000FE70
-    XK_AccessX_Feedback_Enable*: TKeySym = 0x0000FE71
-    XK_RepeatKeys_Enable*: TKeySym = 0x0000FE72
-    XK_SlowKeys_Enable*: TKeySym = 0x0000FE73
-    XK_BounceKeys_Enable*: TKeySym = 0x0000FE74
-    XK_StickyKeys_Enable*: TKeySym = 0x0000FE75
-    XK_MouseKeys_Enable*: TKeySym = 0x0000FE76
-    XK_MouseKeys_Accel_Enable*: TKeySym = 0x0000FE77
-    XK_Overlay1_Enable*: TKeySym = 0x0000FE78
-    XK_Overlay2_Enable*: TKeySym = 0x0000FE79
-    XK_AudibleBell_Enable*: TKeySym = 0x0000FE7A
-    XK_Pointer_Left*: TKeySym = 0x0000FEE0
-    XK_Pointer_Right*: TKeySym = 0x0000FEE1
-    XK_Pointer_Up*: TKeySym = 0x0000FEE2
-    XK_Pointer_Down*: TKeySym = 0x0000FEE3
-    XK_Pointer_UpLeft*: TKeySym = 0x0000FEE4
-    XK_Pointer_UpRight*: TKeySym = 0x0000FEE5
-    XK_Pointer_DownLeft*: TKeySym = 0x0000FEE6
-    XK_Pointer_DownRight*: TKeySym = 0x0000FEE7
-    XK_Pointer_Button_Dflt*: TKeySym = 0x0000FEE8
-    XK_Pointer_Button1*: TKeySym = 0x0000FEE9
-    XK_Pointer_Button2*: TKeySym = 0x0000FEEA
-    XK_Pointer_Button3*: TKeySym = 0x0000FEEB
-    XK_Pointer_Button4*: TKeySym = 0x0000FEEC
-    XK_Pointer_Button5*: TKeySym = 0x0000FEED
-    XK_Pointer_DblClick_Dflt*: TKeySym = 0x0000FEEE
-    XK_Pointer_DblClick1*: TKeySym = 0x0000FEEF
-    XK_Pointer_DblClick2*: TKeySym = 0x0000FEF0
-    XK_Pointer_DblClick3*: TKeySym = 0x0000FEF1
-    XK_Pointer_DblClick4*: TKeySym = 0x0000FEF2
-    XK_Pointer_DblClick5*: TKeySym = 0x0000FEF3
-    XK_Pointer_Drag_Dflt*: TKeySym = 0x0000FEF4
-    XK_Pointer_Drag1*: TKeySym = 0x0000FEF5
-    XK_Pointer_Drag2*: TKeySym = 0x0000FEF6
-    XK_Pointer_Drag3*: TKeySym = 0x0000FEF7
-    XK_Pointer_Drag4*: TKeySym = 0x0000FEF8
-    XK_Pointer_Drag5*: TKeySym = 0x0000FEFD
-    XK_Pointer_EnableKeys*: TKeySym = 0x0000FEF9
-    XK_Pointer_Accelerate*: TKeySym = 0x0000FEFA
-    XK_Pointer_DfltBtnNext*: TKeySym = 0x0000FEFB
-    XK_Pointer_DfltBtnPrev*: TKeySym = 0x0000FEFC
-  #*
-  # * 3270 Terminal Keys
-  # * Byte 3 = = $FD
-  # *
-
-when defined(XK_3270) or true: 
-  const
-    XK_3270_Duplicate*: TKeySym = 0x0000FD01
-    XK_3270_FieldMark*: TKeySym = 0x0000FD02
-    XK_3270_Right2*: TKeySym = 0x0000FD03
-    XK_3270_Left2*: TKeySym = 0x0000FD04
-    XK_3270_BackTab*: TKeySym = 0x0000FD05
-    XK_3270_EraseEOF*: TKeySym = 0x0000FD06
-    XK_3270_EraseInput*: TKeySym = 0x0000FD07
-    XK_3270_Reset*: TKeySym = 0x0000FD08
-    XK_3270_Quit*: TKeySym = 0x0000FD09
-    XK_3270_PA1*: TKeySym = 0x0000FD0A
-    XK_3270_PA2*: TKeySym = 0x0000FD0B
-    XK_3270_PA3*: TKeySym = 0x0000FD0C
-    XK_3270_Test*: TKeySym = 0x0000FD0D
-    XK_3270_Attn*: TKeySym = 0x0000FD0E
-    XK_3270_CursorBlink*: TKeySym = 0x0000FD0F
-    XK_3270_AltCursor*: TKeySym = 0x0000FD10
-    XK_3270_KeyClick*: TKeySym = 0x0000FD11
-    XK_3270_Jump*: TKeySym = 0x0000FD12
-    XK_3270_Ident*: TKeySym = 0x0000FD13
-    XK_3270_Rule*: TKeySym = 0x0000FD14
-    XK_3270_Copy*: TKeySym = 0x0000FD15
-    XK_3270_Play*: TKeySym = 0x0000FD16
-    XK_3270_Setup*: TKeySym = 0x0000FD17
-    XK_3270_Record*: TKeySym = 0x0000FD18
-    XK_3270_ChangeScreen*: TKeySym = 0x0000FD19
-    XK_3270_DeleteWord*: TKeySym = 0x0000FD1A
-    XK_3270_ExSelect*: TKeySym = 0x0000FD1B
-    XK_3270_CursorSelect*: TKeySym = 0x0000FD1C
-    XK_3270_PrintScreen*: TKeySym = 0x0000FD1D
-    XK_3270_Enter*: TKeySym = 0x0000FD1E
-#*
-# *  Latin 1
-# *  Byte 3 = 0
-# *
-
-when defined(XK_LATIN1) or true: 
-  const
-    XK_space*: TKeySym = 0x00000020
-    XK_exclam*: TKeySym = 0x00000021
-    XK_quotedbl*: TKeySym = 0x00000022
-    XK_numbersign*: TKeySym = 0x00000023
-    XK_dollar*: TKeySym = 0x00000024
-    XK_percent*: TKeySym = 0x00000025
-    XK_ampersand*: TKeySym = 0x00000026
-    XK_apostrophe*: TKeySym = 0x00000027
-    XK_quoteright*: TKeySym = 0x00000027 # deprecated 
-    XK_parenleft*: TKeySym = 0x00000028
-    XK_parenright*: TKeySym = 0x00000029
-    XK_asterisk*: TKeySym = 0x0000002A
-    XK_plus*: TKeySym = 0x0000002B
-    XK_comma*: TKeySym = 0x0000002C
-    XK_minus*: TKeySym = 0x0000002D
-    XK_period*: TKeySym = 0x0000002E
-    XK_slash*: TKeySym = 0x0000002F
-    XK_0*: TKeySym = 0x00000030
-    XK_1*: TKeySym = 0x00000031
-    XK_2*: TKeySym = 0x00000032
-    XK_3*: TKeySym = 0x00000033
-    XK_4*: TKeySym = 0x00000034
-    XK_5*: TKeySym = 0x00000035
-    XK_6*: TKeySym = 0x00000036
-    XK_7*: TKeySym = 0x00000037
-    XK_8*: TKeySym = 0x00000038
-    XK_9*: TKeySym = 0x00000039
-    XK_colon*: TKeySym = 0x0000003A
-    XK_semicolon*: TKeySym = 0x0000003B
-    XK_less*: TKeySym = 0x0000003C
-    XK_equal*: TKeySym = 0x0000003D
-    XK_greater*: TKeySym = 0x0000003E
-    XK_question*: TKeySym = 0x0000003F
-    XK_at*: TKeySym = 0x00000040
-    XKc_A*: TKeySym = 0x00000041
-    XKc_B*: TKeySym = 0x00000042
-    XKc_C*: TKeySym = 0x00000043
-    XKc_D*: TKeySym = 0x00000044
-    XKc_E*: TKeySym = 0x00000045
-    XKc_F*: TKeySym = 0x00000046
-    XKc_G*: TKeySym = 0x00000047
-    XKc_H*: TKeySym = 0x00000048
-    XKc_I*: TKeySym = 0x00000049
-    XKc_J*: TKeySym = 0x0000004A
-    XKc_K*: TKeySym = 0x0000004B
-    XKc_L*: TKeySym = 0x0000004C
-    XKc_M*: TKeySym = 0x0000004D
-    XKc_N*: TKeySym = 0x0000004E
-    XKc_O*: TKeySym = 0x0000004F
-    XKc_P*: TKeySym = 0x00000050
-    XKc_Q*: TKeySym = 0x00000051
-    XKc_R*: TKeySym = 0x00000052
-    XKc_S*: TKeySym = 0x00000053
-    XKc_T*: TKeySym = 0x00000054
-    XKc_U*: TKeySym = 0x00000055
-    XKc_V*: TKeySym = 0x00000056
-    XKc_W*: TKeySym = 0x00000057
-    XKc_X*: TKeySym = 0x00000058
-    XKc_Y*: TKeySym = 0x00000059
-    XKc_Z*: TKeySym = 0x0000005A
-    XK_bracketleft*: TKeySym = 0x0000005B
-    XK_backslash*: TKeySym = 0x0000005C
-    XK_bracketright*: TKeySym = 0x0000005D
-    XK_asciicircum*: TKeySym = 0x0000005E
-    XK_underscore*: TKeySym = 0x0000005F
-    XK_grave*: TKeySym = 0x00000060
-    XK_quoteleft*: TKeySym = 0x00000060  # deprecated 
-    XK_a*: TKeySym = 0x00000061
-    XK_b*: TKeySym = 0x00000062
-    XK_c*: TKeySym = 0x00000063
-    XK_d*: TKeySym = 0x00000064
-    XK_e*: TKeySym = 0x00000065
-    XK_f*: TKeySym = 0x00000066
-    XK_g*: TKeySym = 0x00000067
-    XK_h*: TKeySym = 0x00000068
-    XK_i*: TKeySym = 0x00000069
-    XK_j*: TKeySym = 0x0000006A
-    XK_k*: TKeySym = 0x0000006B
-    XK_l*: TKeySym = 0x0000006C
-    XK_m*: TKeySym = 0x0000006D
-    XK_n*: TKeySym = 0x0000006E
-    XK_o*: TKeySym = 0x0000006F
-    XK_p*: TKeySym = 0x00000070
-    XK_q*: TKeySym = 0x00000071
-    XK_r*: TKeySym = 0x00000072
-    XK_s*: TKeySym = 0x00000073
-    XK_t*: TKeySym = 0x00000074
-    XK_u*: TKeySym = 0x00000075
-    XK_v*: TKeySym = 0x00000076
-    XK_w*: TKeySym = 0x00000077
-    XK_x*: TKeySym = 0x00000078
-    XK_y*: TKeySym = 0x00000079
-    XK_z*: TKeySym = 0x0000007A
-    XK_braceleft*: TKeySym = 0x0000007B
-    XK_bar*: TKeySym = 0x0000007C
-    XK_braceright*: TKeySym = 0x0000007D
-    XK_asciitilde*: TKeySym = 0x0000007E
-    XK_nobreakspace*: TKeySym = 0x000000A0
-    XK_exclamdown*: TKeySym = 0x000000A1
-    XK_cent*: TKeySym = 0x000000A2
-    XK_sterling*: TKeySym = 0x000000A3
-    XK_currency*: TKeySym = 0x000000A4
-    XK_yen*: TKeySym = 0x000000A5
-    XK_brokenbar*: TKeySym = 0x000000A6
-    XK_section*: TKeySym = 0x000000A7
-    XK_diaeresis*: TKeySym = 0x000000A8
-    XK_copyright*: TKeySym = 0x000000A9
-    XK_ordfeminine*: TKeySym = 0x000000AA
-    XK_guillemotleft*: TKeySym = 0x000000AB # left angle quotation mark 
-    XK_notsign*: TKeySym = 0x000000AC
-    XK_hyphen*: TKeySym = 0x000000AD
-    XK_registered*: TKeySym = 0x000000AE
-    XK_macron*: TKeySym = 0x000000AF
-    XK_degree*: TKeySym = 0x000000B0
-    XK_plusminus*: TKeySym = 0x000000B1
-    XK_twosuperior*: TKeySym = 0x000000B2
-    XK_threesuperior*: TKeySym = 0x000000B3
-    XK_acute*: TKeySym = 0x000000B4
-    XK_mu*: TKeySym = 0x000000B5
-    XK_paragraph*: TKeySym = 0x000000B6
-    XK_periodcentered*: TKeySym = 0x000000B7
-    XK_cedilla*: TKeySym = 0x000000B8
-    XK_onesuperior*: TKeySym = 0x000000B9
-    XK_masculine*: TKeySym = 0x000000BA
-    XK_guillemotright*: TKeySym = 0x000000BB # right angle quotation mark 
-    XK_onequarter*: TKeySym = 0x000000BC
-    XK_onehalf*: TKeySym = 0x000000BD
-    XK_threequarters*: TKeySym = 0x000000BE
-    XK_questiondown*: TKeySym = 0x000000BF
-    XKc_Agrave*: TKeySym = 0x000000C0
-    XKc_Aacute*: TKeySym = 0x000000C1
-    XKc_Acircumflex*: TKeySym = 0x000000C2
-    XKc_Atilde*: TKeySym = 0x000000C3
-    XKc_Adiaeresis*: TKeySym = 0x000000C4
-    XKc_Aring*: TKeySym = 0x000000C5
-    XKc_AE*: TKeySym = 0x000000C6
-    XKc_Ccedilla*: TKeySym = 0x000000C7
-    XKc_Egrave*: TKeySym = 0x000000C8
-    XKc_Eacute*: TKeySym = 0x000000C9
-    XKc_Ecircumflex*: TKeySym = 0x000000CA
-    XKc_Ediaeresis*: TKeySym = 0x000000CB
-    XKc_Igrave*: TKeySym = 0x000000CC
-    XKc_Iacute*: TKeySym = 0x000000CD
-    XKc_Icircumflex*: TKeySym = 0x000000CE
-    XKc_Idiaeresis*: TKeySym = 0x000000CF
-    XKc_ETH*: TKeySym = 0x000000D0
-    XKc_Ntilde*: TKeySym = 0x000000D1
-    XKc_Ograve*: TKeySym = 0x000000D2
-    XKc_Oacute*: TKeySym = 0x000000D3
-    XKc_Ocircumflex*: TKeySym = 0x000000D4
-    XKc_Otilde*: TKeySym = 0x000000D5
-    XKc_Odiaeresis*: TKeySym = 0x000000D6
-    XK_multiply*: TKeySym = 0x000000D7
-    XKc_Ooblique*: TKeySym = 0x000000D8
-    XKc_Oslash*: TKeySym = XKc_Ooblique
-    XKc_Ugrave*: TKeySym = 0x000000D9
-    XKc_Uacute*: TKeySym = 0x000000DA
-    XKc_Ucircumflex*: TKeySym = 0x000000DB
-    XKc_Udiaeresis*: TKeySym = 0x000000DC
-    XKc_Yacute*: TKeySym = 0x000000DD
-    XKc_THORN*: TKeySym = 0x000000DE
-    XK_ssharp*: TKeySym = 0x000000DF
-    XK_agrave*: TKeySym = 0x000000E0
-    XK_aacute*: TKeySym = 0x000000E1
-    XK_acircumflex*: TKeySym = 0x000000E2
-    XK_atilde*: TKeySym = 0x000000E3
-    XK_adiaeresis*: TKeySym = 0x000000E4
-    XK_aring*: TKeySym = 0x000000E5
-    XK_ae*: TKeySym = 0x000000E6
-    XK_ccedilla*: TKeySym = 0x000000E7
-    XK_egrave*: TKeySym = 0x000000E8
-    XK_eacute*: TKeySym = 0x000000E9
-    XK_ecircumflex*: TKeySym = 0x000000EA
-    XK_ediaeresis*: TKeySym = 0x000000EB
-    XK_igrave*: TKeySym = 0x000000EC
-    XK_iacute*: TKeySym = 0x000000ED
-    XK_icircumflex*: TKeySym = 0x000000EE
-    XK_idiaeresis*: TKeySym = 0x000000EF
-    XK_eth*: TKeySym = 0x000000F0
-    XK_ntilde*: TKeySym = 0x000000F1
-    XK_ograve*: TKeySym = 0x000000F2
-    XK_oacute*: TKeySym = 0x000000F3
-    XK_ocircumflex*: TKeySym = 0x000000F4
-    XK_otilde*: TKeySym = 0x000000F5
-    XK_odiaeresis*: TKeySym = 0x000000F6
-    XK_division*: TKeySym = 0x000000F7
-    XK_oslash*: TKeySym = 0x000000F8
-    XK_ooblique*: TKeySym = XK_oslash
-    XK_ugrave*: TKeySym = 0x000000F9
-    XK_uacute*: TKeySym = 0x000000FA
-    XK_ucircumflex*: TKeySym = 0x000000FB
-    XK_udiaeresis*: TKeySym = 0x000000FC
-    XK_yacute*: TKeySym = 0x000000FD
-    XK_thorn*: TKeySym = 0x000000FE
-    XK_ydiaeresis*: TKeySym = 0x000000FF
-# XK_LATIN1 
-#*
-# *   Latin 2
-# *   Byte 3 = 1
-# *
-
-when defined(XK_LATIN2) or true: 
-  const
-    XKc_Aogonek*: TKeySym = 0x000001A1
-    XK_breve*: TKeySym = 0x000001A2
-    XKc_Lstroke*: TKeySym = 0x000001A3
-    XKc_Lcaron*: TKeySym = 0x000001A5
-    XKc_Sacute*: TKeySym = 0x000001A6
-    XKc_Scaron*: TKeySym = 0x000001A9
-    XKc_Scedilla*: TKeySym = 0x000001AA
-    XKc_Tcaron*: TKeySym = 0x000001AB
-    XKc_Zacute*: TKeySym = 0x000001AC
-    XKc_Zcaron*: TKeySym = 0x000001AE
-    XKc_Zabovedot*: TKeySym = 0x000001AF
-    XK_aogonek*: TKeySym = 0x000001B1
-    XK_ogonek*: TKeySym = 0x000001B2
-    XK_lstroke*: TKeySym = 0x000001B3
-    XK_lcaron*: TKeySym = 0x000001B5
-    XK_sacute*: TKeySym = 0x000001B6
-    XK_caron*: TKeySym = 0x000001B7
-    XK_scaron*: TKeySym = 0x000001B9
-    XK_scedilla*: TKeySym = 0x000001BA
-    XK_tcaron*: TKeySym = 0x000001BB
-    XK_zacute*: TKeySym = 0x000001BC
-    XK_doubleacute*: TKeySym = 0x000001BD
-    XK_zcaron*: TKeySym = 0x000001BE
-    XK_zabovedot*: TKeySym = 0x000001BF
-    XKc_Racute*: TKeySym = 0x000001C0
-    XKc_Abreve*: TKeySym = 0x000001C3
-    XKc_Lacute*: TKeySym = 0x000001C5
-    XKc_Cacute*: TKeySym = 0x000001C6
-    XKc_Ccaron*: TKeySym = 0x000001C8
-    XKc_Eogonek*: TKeySym = 0x000001CA
-    XKc_Ecaron*: TKeySym = 0x000001CC
-    XKc_Dcaron*: TKeySym = 0x000001CF
-    XKc_Dstroke*: TKeySym = 0x000001D0
-    XKc_Nacute*: TKeySym = 0x000001D1
-    XKc_Ncaron*: TKeySym = 0x000001D2
-    XKc_Odoubleacute*: TKeySym = 0x000001D5
-    XKc_Rcaron*: TKeySym = 0x000001D8
-    XKc_Uring*: TKeySym = 0x000001D9
-    XKc_Udoubleacute*: TKeySym = 0x000001DB
-    XKc_Tcedilla*: TKeySym = 0x000001DE
-    XK_racute*: TKeySym = 0x000001E0
-    XK_abreve*: TKeySym = 0x000001E3
-    XK_lacute*: TKeySym = 0x000001E5
-    XK_cacute*: TKeySym = 0x000001E6
-    XK_ccaron*: TKeySym = 0x000001E8
-    XK_eogonek*: TKeySym = 0x000001EA
-    XK_ecaron*: TKeySym = 0x000001EC
-    XK_dcaron*: TKeySym = 0x000001EF
-    XK_dstroke*: TKeySym = 0x000001F0
-    XK_nacute*: TKeySym = 0x000001F1
-    XK_ncaron*: TKeySym = 0x000001F2
-    XK_odoubleacute*: TKeySym = 0x000001F5
-    XK_udoubleacute*: TKeySym = 0x000001FB
-    XK_rcaron*: TKeySym = 0x000001F8
-    XK_uring*: TKeySym = 0x000001F9
-    XK_tcedilla*: TKeySym = 0x000001FE
-    XK_abovedot*: TKeySym = 0x000001FF
-# XK_LATIN2 
-#*
-# *   Latin 3
-# *   Byte 3 = 2
-# *
-
-when defined(XK_LATIN3) or true: 
-  const
-    XKc_Hstroke*: TKeySym = 0x000002A1
-    XKc_Hcircumflex*: TKeySym = 0x000002A6
-    XKc_Iabovedot*: TKeySym = 0x000002A9
-    XKc_Gbreve*: TKeySym = 0x000002AB
-    XKc_Jcircumflex*: TKeySym = 0x000002AC
-    XK_hstroke*: TKeySym = 0x000002B1
-    XK_hcircumflex*: TKeySym = 0x000002B6
-    XK_idotless*: TKeySym = 0x000002B9
-    XK_gbreve*: TKeySym = 0x000002BB
-    XK_jcircumflex*: TKeySym = 0x000002BC
-    XKc_Cabovedot*: TKeySym = 0x000002C5
-    XKc_Ccircumflex*: TKeySym = 0x000002C6
-    XKc_Gabovedot*: TKeySym = 0x000002D5
-    XKc_Gcircumflex*: TKeySym = 0x000002D8
-    XKc_Ubreve*: TKeySym = 0x000002DD
-    XKc_Scircumflex*: TKeySym = 0x000002DE
-    XK_cabovedot*: TKeySym = 0x000002E5
-    XK_ccircumflex*: TKeySym = 0x000002E6
-    XK_gabovedot*: TKeySym = 0x000002F5
-    XK_gcircumflex*: TKeySym = 0x000002F8
-    XK_ubreve*: TKeySym = 0x000002FD
-    XK_scircumflex*: TKeySym = 0x000002FE
-# XK_LATIN3 
-#*
-# *   Latin 4
-# *   Byte 3 = 3
-# *
-
-when defined(XK_LATIN4) or true: 
-  const
-    XK_kra*: TKeySym = 0x000003A2
-    XK_kappa*: TKeySym = 0x000003A2      # deprecated 
-    XKc_Rcedilla*: TKeySym = 0x000003A3
-    XKc_Itilde*: TKeySym = 0x000003A5
-    XKc_Lcedilla*: TKeySym = 0x000003A6
-    XKc_Emacron*: TKeySym = 0x000003AA
-    XKc_Gcedilla*: TKeySym = 0x000003AB
-    XKc_Tslash*: TKeySym = 0x000003AC
-    XK_rcedilla*: TKeySym = 0x000003B3
-    XK_itilde*: TKeySym = 0x000003B5
-    XK_lcedilla*: TKeySym = 0x000003B6
-    XK_emacron*: TKeySym = 0x000003BA
-    XK_gcedilla*: TKeySym = 0x000003BB
-    XK_tslash*: TKeySym = 0x000003BC
-    XKc_ENG*: TKeySym = 0x000003BD
-    XK_eng*: TKeySym = 0x000003BF
-    XKc_Amacron*: TKeySym = 0x000003C0
-    XKc_Iogonek*: TKeySym = 0x000003C7
-    XKc_Eabovedot*: TKeySym = 0x000003CC
-    XKc_Imacron*: TKeySym = 0x000003CF
-    XKc_Ncedilla*: TKeySym = 0x000003D1
-    XKc_Omacron*: TKeySym = 0x000003D2
-    XKc_Kcedilla*: TKeySym = 0x000003D3
-    XKc_Uogonek*: TKeySym = 0x000003D9
-    XKc_Utilde*: TKeySym = 0x000003DD
-    XKc_Umacron*: TKeySym = 0x000003DE
-    XK_amacron*: TKeySym = 0x000003E0
-    XK_iogonek*: TKeySym = 0x000003E7
-    XK_eabovedot*: TKeySym = 0x000003EC
-    XK_imacron*: TKeySym = 0x000003EF
-    XK_ncedilla*: TKeySym = 0x000003F1
-    XK_omacron*: TKeySym = 0x000003F2
-    XK_kcedilla*: TKeySym = 0x000003F3
-    XK_uogonek*: TKeySym = 0x000003F9
-    XK_utilde*: TKeySym = 0x000003FD
-    XK_umacron*: TKeySym = 0x000003FE
-# XK_LATIN4 
-#*
-# * Latin-8
-# * Byte 3 = 18
-# *
-
-when defined(XK_LATIN8) or true: 
-  const
-    XKc_Babovedot*: TKeySym = 0x000012A1
-    XK_babovedot*: TKeySym = 0x000012A2
-    XKc_Dabovedot*: TKeySym = 0x000012A6
-    XKc_Wgrave*: TKeySym = 0x000012A8
-    XKc_Wacute*: TKeySym = 0x000012AA
-    XK_dabovedot*: TKeySym = 0x000012AB
-    XKc_Ygrave*: TKeySym = 0x000012AC
-    XKc_Fabovedot*: TKeySym = 0x000012B0
-    XK_fabovedot*: TKeySym = 0x000012B1
-    XKc_Mabovedot*: TKeySym = 0x000012B4
-    XK_mabovedot*: TKeySym = 0x000012B5
-    XKc_Pabovedot*: TKeySym = 0x000012B7
-    XK_wgrave*: TKeySym = 0x000012B8
-    XK_pabovedot*: TKeySym = 0x000012B9
-    XK_wacute*: TKeySym = 0x000012BA
-    XKc_Sabovedot*: TKeySym = 0x000012BB
-    XK_ygrave*: TKeySym = 0x000012BC
-    XKc_Wdiaeresis*: TKeySym = 0x000012BD
-    XK_wdiaeresis*: TKeySym = 0x000012BE
-    XK_sabovedot*: TKeySym = 0x000012BF
-    XKc_Wcircumflex*: TKeySym = 0x000012D0
-    XKc_Tabovedot*: TKeySym = 0x000012D7
-    XKc_Ycircumflex*: TKeySym = 0x000012DE
-    XK_wcircumflex*: TKeySym = 0x000012F0
-    XK_tabovedot*: TKeySym = 0x000012F7
-    XK_ycircumflex*: TKeySym = 0x000012FE
-# XK_LATIN8 
-#*
-# * Latin-9 (a.k.a. Latin-0)
-# * Byte 3 = 19
-# *
-
-when defined(XK_LATIN9) or true: 
-  const
-    XKc_OE*: TKeySym = 0x000013BC
-    XK_oe*: TKeySym = 0x000013BD
-    XKc_Ydiaeresis*: TKeySym = 0x000013BE
-# XK_LATIN9 
-#*
-# * Katakana
-# * Byte 3 = 4
-# *
-
-when defined(XK_KATAKANA) or true: 
-  const
-    XK_overline*: TKeySym = 0x0000047E
-    XK_kana_fullstop*: TKeySym = 0x000004A1
-    XK_kana_openingbracket*: TKeySym = 0x000004A2
-    XK_kana_closingbracket*: TKeySym = 0x000004A3
-    XK_kana_comma*: TKeySym = 0x000004A4
-    XK_kana_conjunctive*: TKeySym = 0x000004A5
-    XK_kana_middledot*: TKeySym = 0x000004A5 # deprecated 
-    XKc_kana_WO*: TKeySym = 0x000004A6
-    XK_kana_a*: TKeySym = 0x000004A7
-    XK_kana_i*: TKeySym = 0x000004A8
-    XK_kana_u*: TKeySym = 0x000004A9
-    XK_kana_e*: TKeySym = 0x000004AA
-    XK_kana_o*: TKeySym = 0x000004AB
-    XK_kana_ya*: TKeySym = 0x000004AC
-    XK_kana_yu*: TKeySym = 0x000004AD
-    XK_kana_yo*: TKeySym = 0x000004AE
-    XK_kana_tsu*: TKeySym = 0x000004AF
-    XK_kana_tu*: TKeySym = 0x000004AF    # deprecated 
-    XK_prolongedsound*: TKeySym = 0x000004B0
-    XKc_kana_A*: TKeySym = 0x000004B1
-    XKc_kana_I*: TKeySym = 0x000004B2
-    XKc_kana_U*: TKeySym = 0x000004B3
-    XKc_kana_E*: TKeySym = 0x000004B4
-    XKc_kana_O*: TKeySym = 0x000004B5
-    XKc_kana_KA*: TKeySym = 0x000004B6
-    XKc_kana_KI*: TKeySym = 0x000004B7
-    XKc_kana_KU*: TKeySym = 0x000004B8
-    XKc_kana_KE*: TKeySym = 0x000004B9
-    XKc_kana_KO*: TKeySym = 0x000004BA
-    XKc_kana_SA*: TKeySym = 0x000004BB
-    XKc_kana_SHI*: TKeySym = 0x000004BC
-    XKc_kana_SU*: TKeySym = 0x000004BD
-    XKc_kana_SE*: TKeySym = 0x000004BE
-    XKc_kana_SO*: TKeySym = 0x000004BF
-    XKc_kana_TA*: TKeySym = 0x000004C0
-    XKc_kana_CHI*: TKeySym = 0x000004C1
-    XKc_kana_TI*: TKeySym = 0x000004C1   # deprecated 
-    XKc_kana_TSU*: TKeySym = 0x000004C2
-    XKc_kana_TU*: TKeySym = 0x000004C2   # deprecated 
-    XKc_kana_TE*: TKeySym = 0x000004C3
-    XKc_kana_TO*: TKeySym = 0x000004C4
-    XKc_kana_NA*: TKeySym = 0x000004C5
-    XKc_kana_NI*: TKeySym = 0x000004C6
-    XKc_kana_NU*: TKeySym = 0x000004C7
-    XKc_kana_NE*: TKeySym = 0x000004C8
-    XKc_kana_NO*: TKeySym = 0x000004C9
-    XKc_kana_HA*: TKeySym = 0x000004CA
-    XKc_kana_HI*: TKeySym = 0x000004CB
-    XKc_kana_FU*: TKeySym = 0x000004CC
-    XKc_kana_HU*: TKeySym = 0x000004CC   # deprecated 
-    XKc_kana_HE*: TKeySym = 0x000004CD
-    XKc_kana_HO*: TKeySym = 0x000004CE
-    XKc_kana_MA*: TKeySym = 0x000004CF
-    XKc_kana_MI*: TKeySym = 0x000004D0
-    XKc_kana_MU*: TKeySym = 0x000004D1
-    XKc_kana_ME*: TKeySym = 0x000004D2
-    XKc_kana_MO*: TKeySym = 0x000004D3
-    XKc_kana_YA*: TKeySym = 0x000004D4
-    XKc_kana_YU*: TKeySym = 0x000004D5
-    XKc_kana_YO*: TKeySym = 0x000004D6
-    XKc_kana_RA*: TKeySym = 0x000004D7
-    XKc_kana_RI*: TKeySym = 0x000004D8
-    XKc_kana_RU*: TKeySym = 0x000004D9
-    XKc_kana_RE*: TKeySym = 0x000004DA
-    XKc_kana_RO*: TKeySym = 0x000004DB
-    XKc_kana_WA*: TKeySym = 0x000004DC
-    XKc_kana_N*: TKeySym = 0x000004DD
-    XK_voicedsound*: TKeySym = 0x000004DE
-    XK_semivoicedsound*: TKeySym = 0x000004DF
-    XK_kana_switch*: TKeySym = 0x0000FF7E # Alias for mode_switch 
-# XK_KATAKANA 
-#*
-# *  Arabic
-# *  Byte 3 = 5
-# *
-
-when defined(XK_ARABIC) or true: 
-  const
-    XK_Farsi_0*: TKeySym = 0x00000590
-    XK_Farsi_1*: TKeySym = 0x00000591
-    XK_Farsi_2*: TKeySym = 0x00000592
-    XK_Farsi_3*: TKeySym = 0x00000593
-    XK_Farsi_4*: TKeySym = 0x00000594
-    XK_Farsi_5*: TKeySym = 0x00000595
-    XK_Farsi_6*: TKeySym = 0x00000596
-    XK_Farsi_7*: TKeySym = 0x00000597
-    XK_Farsi_8*: TKeySym = 0x00000598
-    XK_Farsi_9*: TKeySym = 0x00000599
-    XK_Arabic_percent*: TKeySym = 0x000005A5
-    XK_Arabic_superscript_alef*: TKeySym = 0x000005A6
-    XK_Arabic_tteh*: TKeySym = 0x000005A7
-    XK_Arabic_peh*: TKeySym = 0x000005A8
-    XK_Arabic_tcheh*: TKeySym = 0x000005A9
-    XK_Arabic_ddal*: TKeySym = 0x000005AA
-    XK_Arabic_rreh*: TKeySym = 0x000005AB
-    XK_Arabic_comma*: TKeySym = 0x000005AC
-    XK_Arabic_fullstop*: TKeySym = 0x000005AE
-    XK_Arabic_0*: TKeySym = 0x000005B0
-    XK_Arabic_1*: TKeySym = 0x000005B1
-    XK_Arabic_2*: TKeySym = 0x000005B2
-    XK_Arabic_3*: TKeySym = 0x000005B3
-    XK_Arabic_4*: TKeySym = 0x000005B4
-    XK_Arabic_5*: TKeySym = 0x000005B5
-    XK_Arabic_6*: TKeySym = 0x000005B6
-    XK_Arabic_7*: TKeySym = 0x000005B7
-    XK_Arabic_8*: TKeySym = 0x000005B8
-    XK_Arabic_9*: TKeySym = 0x000005B9
-    XK_Arabic_semicolon*: TKeySym = 0x000005BB
-    XK_Arabic_question_mark*: TKeySym = 0x000005BF
-    XK_Arabic_hamza*: TKeySym = 0x000005C1
-    XK_Arabic_maddaonalef*: TKeySym = 0x000005C2
-    XK_Arabic_hamzaonalef*: TKeySym = 0x000005C3
-    XK_Arabic_hamzaonwaw*: TKeySym = 0x000005C4
-    XK_Arabic_hamzaunderalef*: TKeySym = 0x000005C5
-    XK_Arabic_hamzaonyeh*: TKeySym = 0x000005C6
-    XK_Arabic_alef*: TKeySym = 0x000005C7
-    XK_Arabic_beh*: TKeySym = 0x000005C8
-    XK_Arabic_tehmarbuta*: TKeySym = 0x000005C9
-    XK_Arabic_teh*: TKeySym = 0x000005CA
-    XK_Arabic_theh*: TKeySym = 0x000005CB
-    XK_Arabic_jeem*: TKeySym = 0x000005CC
-    XK_Arabic_hah*: TKeySym = 0x000005CD
-    XK_Arabic_khah*: TKeySym = 0x000005CE
-    XK_Arabic_dal*: TKeySym = 0x000005CF
-    XK_Arabic_thal*: TKeySym = 0x000005D0
-    XK_Arabic_ra*: TKeySym = 0x000005D1
-    XK_Arabic_zain*: TKeySym = 0x000005D2
-    XK_Arabic_seen*: TKeySym = 0x000005D3
-    XK_Arabic_sheen*: TKeySym = 0x000005D4
-    XK_Arabic_sad*: TKeySym = 0x000005D5
-    XK_Arabic_dad*: TKeySym = 0x000005D6
-    XK_Arabic_tah*: TKeySym = 0x000005D7
-    XK_Arabic_zah*: TKeySym = 0x000005D8
-    XK_Arabic_ain*: TKeySym = 0x000005D9
-    XK_Arabic_ghain*: TKeySym = 0x000005DA
-    XK_Arabic_tatweel*: TKeySym = 0x000005E0
-    XK_Arabic_feh*: TKeySym = 0x000005E1
-    XK_Arabic_qaf*: TKeySym = 0x000005E2
-    XK_Arabic_kaf*: TKeySym = 0x000005E3
-    XK_Arabic_lam*: TKeySym = 0x000005E4
-    XK_Arabic_meem*: TKeySym = 0x000005E5
-    XK_Arabic_noon*: TKeySym = 0x000005E6
-    XK_Arabic_ha*: TKeySym = 0x000005E7
-    XK_Arabic_heh*: TKeySym = 0x000005E7 # deprecated 
-    XK_Arabic_waw*: TKeySym = 0x000005E8
-    XK_Arabic_alefmaksura*: TKeySym = 0x000005E9
-    XK_Arabic_yeh*: TKeySym = 0x000005EA
-    XK_Arabic_fathatan*: TKeySym = 0x000005EB
-    XK_Arabic_dammatan*: TKeySym = 0x000005EC
-    XK_Arabic_kasratan*: TKeySym = 0x000005ED
-    XK_Arabic_fatha*: TKeySym = 0x000005EE
-    XK_Arabic_damma*: TKeySym = 0x000005EF
-    XK_Arabic_kasra*: TKeySym = 0x000005F0
-    XK_Arabic_shadda*: TKeySym = 0x000005F1
-    XK_Arabic_sukun*: TKeySym = 0x000005F2
-    XK_Arabic_madda_above*: TKeySym = 0x000005F3
-    XK_Arabic_hamza_above*: TKeySym = 0x000005F4
-    XK_Arabic_hamza_below*: TKeySym = 0x000005F5
-    XK_Arabic_jeh*: TKeySym = 0x000005F6
-    XK_Arabic_veh*: TKeySym = 0x000005F7
-    XK_Arabic_keheh*: TKeySym = 0x000005F8
-    XK_Arabic_gaf*: TKeySym = 0x000005F9
-    XK_Arabic_noon_ghunna*: TKeySym = 0x000005FA
-    XK_Arabic_heh_doachashmee*: TKeySym = 0x000005FB
-    XK_Farsi_yeh*: TKeySym = 0x000005FC
-    XK_Arabic_farsi_yeh*: TKeySym = XK_Farsi_yeh
-    XK_Arabic_yeh_baree*: TKeySym = 0x000005FD
-    XK_Arabic_heh_goal*: TKeySym = 0x000005FE
-    XK_Arabic_switch*: TKeySym = 0x0000FF7E # Alias for mode_switch 
-# XK_ARABIC 
-#*
-# * Cyrillic
-# * Byte 3 = 6
-# *
-
-when defined(XK_CYRILLIC) or true: 
-  const
-    XKc_Cyrillic_GHE_bar*: TKeySym = 0x00000680
-    XK_Cyrillic_ghe_bar*: TKeySym = 0x00000690
-    XKc_Cyrillic_ZHE_descender*: TKeySym = 0x00000681
-    XK_Cyrillic_zhe_descender*: TKeySym = 0x00000691
-    XKc_Cyrillic_KA_descender*: TKeySym = 0x00000682
-    XK_Cyrillic_ka_descender*: TKeySym = 0x00000692
-    XKc_Cyrillic_KA_vertstroke*: TKeySym = 0x00000683
-    XK_Cyrillic_ka_vertstroke*: TKeySym = 0x00000693
-    XKc_Cyrillic_EN_descender*: TKeySym = 0x00000684
-    XK_Cyrillic_en_descender*: TKeySym = 0x00000694
-    XKc_Cyrillic_U_straight*: TKeySym = 0x00000685
-    XK_Cyrillic_u_straight*: TKeySym = 0x00000695
-    XKc_Cyrillic_U_straight_bar*: TKeySym = 0x00000686
-    XK_Cyrillic_u_straight_bar*: TKeySym = 0x00000696
-    XKc_Cyrillic_HA_descender*: TKeySym = 0x00000687
-    XK_Cyrillic_ha_descender*: TKeySym = 0x00000697
-    XKc_Cyrillic_CHE_descender*: TKeySym = 0x00000688
-    XK_Cyrillic_che_descender*: TKeySym = 0x00000698
-    XKc_Cyrillic_CHE_vertstroke*: TKeySym = 0x00000689
-    XK_Cyrillic_che_vertstroke*: TKeySym = 0x00000699
-    XKc_Cyrillic_SHHA*: TKeySym = 0x0000068A
-    XK_Cyrillic_shha*: TKeySym = 0x0000069A
-    XKc_Cyrillic_SCHWA*: TKeySym = 0x0000068C
-    XK_Cyrillic_schwa*: TKeySym = 0x0000069C
-    XKc_Cyrillic_I_macron*: TKeySym = 0x0000068D
-    XK_Cyrillic_i_macron*: TKeySym = 0x0000069D
-    XKc_Cyrillic_O_bar*: TKeySym = 0x0000068E
-    XK_Cyrillic_o_bar*: TKeySym = 0x0000069E
-    XKc_Cyrillic_U_macron*: TKeySym = 0x0000068F
-    XK_Cyrillic_u_macron*: TKeySym = 0x0000069F
-    XK_Serbian_dje*: TKeySym = 0x000006A1
-    XK_Macedonia_gje*: TKeySym = 0x000006A2
-    XK_Cyrillic_io*: TKeySym = 0x000006A3
-    XK_Ukrainian_ie*: TKeySym = 0x000006A4
-    XK_Ukranian_je*: TKeySym = 0x000006A4 # deprecated 
-    XK_Macedonia_dse*: TKeySym = 0x000006A5
-    XK_Ukrainian_i*: TKeySym = 0x000006A6
-    XK_Ukranian_i*: TKeySym = 0x000006A6 # deprecated 
-    XK_Ukrainian_yi*: TKeySym = 0x000006A7
-    XK_Ukranian_yi*: TKeySym = 0x000006A7 # deprecated 
-    XK_Cyrillic_je*: TKeySym = 0x000006A8
-    XK_Serbian_je*: TKeySym = 0x000006A8 # deprecated 
-    XK_Cyrillic_lje*: TKeySym = 0x000006A9
-    XK_Serbian_lje*: TKeySym = 0x000006A9 # deprecated 
-    XK_Cyrillic_nje*: TKeySym = 0x000006AA
-    XK_Serbian_nje*: TKeySym = 0x000006AA # deprecated 
-    XK_Serbian_tshe*: TKeySym = 0x000006AB
-    XK_Macedonia_kje*: TKeySym = 0x000006AC
-    XK_Ukrainian_ghe_with_upturn*: TKeySym = 0x000006AD
-    XK_Byelorussian_shortu*: TKeySym = 0x000006AE
-    XK_Cyrillic_dzhe*: TKeySym = 0x000006AF
-    XK_Serbian_dze*: TKeySym = 0x000006AF # deprecated 
-    XK_numerosign*: TKeySym = 0x000006B0
-    XKc_Serbian_DJE*: TKeySym = 0x000006B1
-    XKc_Macedonia_GJE*: TKeySym = 0x000006B2
-    XKc_Cyrillic_IO*: TKeySym = 0x000006B3
-    XKc_Ukrainian_IE*: TKeySym = 0x000006B4
-    XKc_Ukranian_JE*: TKeySym = 0x000006B4 # deprecated 
-    XKc_Macedonia_DSE*: TKeySym = 0x000006B5
-    XKc_Ukrainian_I*: TKeySym = 0x000006B6
-    XKc_Ukranian_I*: TKeySym = 0x000006B6 # deprecated 
-    XKc_Ukrainian_YI*: TKeySym = 0x000006B7
-    XKc_Ukranian_YI*: TKeySym = 0x000006B7 # deprecated 
-    XKc_Cyrillic_JE*: TKeySym = 0x000006B8
-    XKc_Serbian_JE*: TKeySym = 0x000006B8 # deprecated 
-    XKc_Cyrillic_LJE*: TKeySym = 0x000006B9
-    XKc_Serbian_LJE*: TKeySym = 0x000006B9 # deprecated 
-    XKc_Cyrillic_NJE*: TKeySym = 0x000006BA
-    XKc_Serbian_NJE*: TKeySym = 0x000006BA # deprecated 
-    XKc_Serbian_TSHE*: TKeySym = 0x000006BB
-    XKc_Macedonia_KJE*: TKeySym = 0x000006BC
-    XKc_Ukrainian_GHE_WITH_UPTURN*: TKeySym = 0x000006BD
-    XKc_Byelorussian_SHORTU*: TKeySym = 0x000006BE
-    XKc_Cyrillic_DZHE*: TKeySym = 0x000006BF
-    XKc_Serbian_DZE*: TKeySym = 0x000006BF # deprecated 
-    XK_Cyrillic_yu*: TKeySym = 0x000006C0
-    XK_Cyrillic_a*: TKeySym = 0x000006C1
-    XK_Cyrillic_be*: TKeySym = 0x000006C2
-    XK_Cyrillic_tse*: TKeySym = 0x000006C3
-    XK_Cyrillic_de*: TKeySym = 0x000006C4
-    XK_Cyrillic_ie*: TKeySym = 0x000006C5
-    XK_Cyrillic_ef*: TKeySym = 0x000006C6
-    XK_Cyrillic_ghe*: TKeySym = 0x000006C7
-    XK_Cyrillic_ha*: TKeySym = 0x000006C8
-    XK_Cyrillic_i*: TKeySym = 0x000006C9
-    XK_Cyrillic_shorti*: TKeySym = 0x000006CA
-    XK_Cyrillic_ka*: TKeySym = 0x000006CB
-    XK_Cyrillic_el*: TKeySym = 0x000006CC
-    XK_Cyrillic_em*: TKeySym = 0x000006CD
-    XK_Cyrillic_en*: TKeySym = 0x000006CE
-    XK_Cyrillic_o*: TKeySym = 0x000006CF
-    XK_Cyrillic_pe*: TKeySym = 0x000006D0
-    XK_Cyrillic_ya*: TKeySym = 0x000006D1
-    XK_Cyrillic_er*: TKeySym = 0x000006D2
-    XK_Cyrillic_es*: TKeySym = 0x000006D3
-    XK_Cyrillic_te*: TKeySym = 0x000006D4
-    XK_Cyrillic_u*: TKeySym = 0x000006D5
-    XK_Cyrillic_zhe*: TKeySym = 0x000006D6
-    XK_Cyrillic_ve*: TKeySym = 0x000006D7
-    XK_Cyrillic_softsign*: TKeySym = 0x000006D8
-    XK_Cyrillic_yeru*: TKeySym = 0x000006D9
-    XK_Cyrillic_ze*: TKeySym = 0x000006DA
-    XK_Cyrillic_sha*: TKeySym = 0x000006DB
-    XK_Cyrillic_e*: TKeySym = 0x000006DC
-    XK_Cyrillic_shcha*: TKeySym = 0x000006DD
-    XK_Cyrillic_che*: TKeySym = 0x000006DE
-    XK_Cyrillic_hardsign*: TKeySym = 0x000006DF
-    XKc_Cyrillic_YU*: TKeySym = 0x000006E0
-    XKc_Cyrillic_A*: TKeySym = 0x000006E1
-    XKc_Cyrillic_BE*: TKeySym = 0x000006E2
-    XKc_Cyrillic_TSE*: TKeySym = 0x000006E3
-    XKc_Cyrillic_DE*: TKeySym = 0x000006E4
-    XKc_Cyrillic_IE*: TKeySym = 0x000006E5
-    XKc_Cyrillic_EF*: TKeySym = 0x000006E6
-    XKc_Cyrillic_GHE*: TKeySym = 0x000006E7
-    XKc_Cyrillic_HA*: TKeySym = 0x000006E8
-    XKc_Cyrillic_I*: TKeySym = 0x000006E9
-    XKc_Cyrillic_SHORTI*: TKeySym = 0x000006EA
-    XKc_Cyrillic_KA*: TKeySym = 0x000006EB
-    XKc_Cyrillic_EL*: TKeySym = 0x000006EC
-    XKc_Cyrillic_EM*: TKeySym = 0x000006ED
-    XKc_Cyrillic_EN*: TKeySym = 0x000006EE
-    XKc_Cyrillic_O*: TKeySym = 0x000006EF
-    XKc_Cyrillic_PE*: TKeySym = 0x000006F0
-    XKc_Cyrillic_YA*: TKeySym = 0x000006F1
-    XKc_Cyrillic_ER*: TKeySym = 0x000006F2
-    XKc_Cyrillic_ES*: TKeySym = 0x000006F3
-    XKc_Cyrillic_TE*: TKeySym = 0x000006F4
-    XKc_Cyrillic_U*: TKeySym = 0x000006F5
-    XKc_Cyrillic_ZHE*: TKeySym = 0x000006F6
-    XKc_Cyrillic_VE*: TKeySym = 0x000006F7
-    XKc_Cyrillic_SOFTSIGN*: TKeySym = 0x000006F8
-    XKc_Cyrillic_YERU*: TKeySym = 0x000006F9
-    XKc_Cyrillic_ZE*: TKeySym = 0x000006FA
-    XKc_Cyrillic_SHA*: TKeySym = 0x000006FB
-    XKc_Cyrillic_E*: TKeySym = 0x000006FC
-    XKc_Cyrillic_SHCHA*: TKeySym = 0x000006FD
-    XKc_Cyrillic_CHE*: TKeySym = 0x000006FE
-    XKc_Cyrillic_HARDSIGN*: TKeySym = 0x000006FF
-# XK_CYRILLIC 
-#*
-# * Greek
-# * Byte 3 = 7
-# *
-
-when defined(XK_GREEK) or true: 
-  const
-    XKc_Greek_ALPHAaccent*: TKeySym = 0x000007A1
-    XKc_Greek_EPSILONaccent*: TKeySym = 0x000007A2
-    XKc_Greek_ETAaccent*: TKeySym = 0x000007A3
-    XKc_Greek_IOTAaccent*: TKeySym = 0x000007A4
-    XKc_Greek_IOTAdieresis*: TKeySym = 0x000007A5
-    XKc_Greek_IOTAdiaeresis*: TKeySym = XKc_Greek_IOTAdieresis # old typo 
-    XKc_Greek_OMICRONaccent*: TKeySym = 0x000007A7
-    XKc_Greek_UPSILONaccent*: TKeySym = 0x000007A8
-    XKc_Greek_UPSILONdieresis*: TKeySym = 0x000007A9
-    XKc_Greek_OMEGAaccent*: TKeySym = 0x000007AB
-    XK_Greek_accentdieresis*: TKeySym = 0x000007AE
-    XK_Greek_horizbar*: TKeySym = 0x000007AF
-    XK_Greek_alphaaccent*: TKeySym = 0x000007B1
-    XK_Greek_epsilonaccent*: TKeySym = 0x000007B2
-    XK_Greek_etaaccent*: TKeySym = 0x000007B3
-    XK_Greek_iotaaccent*: TKeySym = 0x000007B4
-    XK_Greek_iotadieresis*: TKeySym = 0x000007B5
-    XK_Greek_iotaaccentdieresis*: TKeySym = 0x000007B6
-    XK_Greek_omicronaccent*: TKeySym = 0x000007B7
-    XK_Greek_upsilonaccent*: TKeySym = 0x000007B8
-    XK_Greek_upsilondieresis*: TKeySym = 0x000007B9
-    XK_Greek_upsilonaccentdieresis*: TKeySym = 0x000007BA
-    XK_Greek_omegaaccent*: TKeySym = 0x000007BB
-    XKc_Greek_ALPHA*: TKeySym = 0x000007C1
-    XKc_Greek_BETA*: TKeySym = 0x000007C2
-    XKc_Greek_GAMMA*: TKeySym = 0x000007C3
-    XKc_Greek_DELTA*: TKeySym = 0x000007C4
-    XKc_Greek_EPSILON*: TKeySym = 0x000007C5
-    XKc_Greek_ZETA*: TKeySym = 0x000007C6
-    XKc_Greek_ETA*: TKeySym = 0x000007C7
-    XKc_Greek_THETA*: TKeySym = 0x000007C8
-    XKc_Greek_IOTA*: TKeySym = 0x000007C9
-    XKc_Greek_KAPPA*: TKeySym = 0x000007CA
-    XKc_Greek_LAMDA*: TKeySym = 0x000007CB
-    XKc_Greek_LAMBDA*: TKeySym = 0x000007CB
-    XKc_Greek_MU*: TKeySym = 0x000007CC
-    XKc_Greek_NU*: TKeySym = 0x000007CD
-    XKc_Greek_XI*: TKeySym = 0x000007CE
-    XKc_Greek_OMICRON*: TKeySym = 0x000007CF
-    XKc_Greek_PI*: TKeySym = 0x000007D0
-    XKc_Greek_RHO*: TKeySym = 0x000007D1
-    XKc_Greek_SIGMA*: TKeySym = 0x000007D2
-    XKc_Greek_TAU*: TKeySym = 0x000007D4
-    XKc_Greek_UPSILON*: TKeySym = 0x000007D5
-    XKc_Greek_PHI*: TKeySym = 0x000007D6
-    XKc_Greek_CHI*: TKeySym = 0x000007D7
-    XKc_Greek_PSI*: TKeySym = 0x000007D8
-    XKc_Greek_OMEGA*: TKeySym = 0x000007D9
-    XK_Greek_alpha*: TKeySym = 0x000007E1
-    XK_Greek_beta*: TKeySym = 0x000007E2
-    XK_Greek_gamma*: TKeySym = 0x000007E3
-    XK_Greek_delta*: TKeySym = 0x000007E4
-    XK_Greek_epsilon*: TKeySym = 0x000007E5
-    XK_Greek_zeta*: TKeySym = 0x000007E6
-    XK_Greek_eta*: TKeySym = 0x000007E7
-    XK_Greek_theta*: TKeySym = 0x000007E8
-    XK_Greek_iota*: TKeySym = 0x000007E9
-    XK_Greek_kappa*: TKeySym = 0x000007EA
-    XK_Greek_lamda*: TKeySym = 0x000007EB
-    XK_Greek_lambda*: TKeySym = 0x000007EB
-    XK_Greek_mu*: TKeySym = 0x000007EC
-    XK_Greek_nu*: TKeySym = 0x000007ED
-    XK_Greek_xi*: TKeySym = 0x000007EE
-    XK_Greek_omicron*: TKeySym = 0x000007EF
-    XK_Greek_pi*: TKeySym = 0x000007F0
-    XK_Greek_rho*: TKeySym = 0x000007F1
-    XK_Greek_sigma*: TKeySym = 0x000007F2
-    XK_Greek_finalsmallsigma*: TKeySym = 0x000007F3
-    XK_Greek_tau*: TKeySym = 0x000007F4
-    XK_Greek_upsilon*: TKeySym = 0x000007F5
-    XK_Greek_phi*: TKeySym = 0x000007F6
-    XK_Greek_chi*: TKeySym = 0x000007F7
-    XK_Greek_psi*: TKeySym = 0x000007F8
-    XK_Greek_omega*: TKeySym = 0x000007F9
-    XK_Greek_switch*: TKeySym = 0x0000FF7E # Alias for mode_switch 
-# XK_GREEK 
-#*
-# * Technical
-# * Byte 3 = 8
-# *
-
-when defined(XK_TECHNICAL) or true: 
-  const
-    XK_leftradical*: TKeySym = 0x000008A1
-    XK_topleftradical*: TKeySym = 0x000008A2
-    XK_horizconnector*: TKeySym = 0x000008A3
-    XK_topintegral*: TKeySym = 0x000008A4
-    XK_botintegral*: TKeySym = 0x000008A5
-    XK_vertconnector*: TKeySym = 0x000008A6
-    XK_topleftsqbracket*: TKeySym = 0x000008A7
-    XK_botleftsqbracket*: TKeySym = 0x000008A8
-    XK_toprightsqbracket*: TKeySym = 0x000008A9
-    XK_botrightsqbracket*: TKeySym = 0x000008AA
-    XK_topleftparens*: TKeySym = 0x000008AB
-    XK_botleftparens*: TKeySym = 0x000008AC
-    XK_toprightparens*: TKeySym = 0x000008AD
-    XK_botrightparens*: TKeySym = 0x000008AE
-    XK_leftmiddlecurlybrace*: TKeySym = 0x000008AF
-    XK_rightmiddlecurlybrace*: TKeySym = 0x000008B0
-    XK_topleftsummation*: TKeySym = 0x000008B1
-    XK_botleftsummation*: TKeySym = 0x000008B2
-    XK_topvertsummationconnector*: TKeySym = 0x000008B3
-    XK_botvertsummationconnector*: TKeySym = 0x000008B4
-    XK_toprightsummation*: TKeySym = 0x000008B5
-    XK_botrightsummation*: TKeySym = 0x000008B6
-    XK_rightmiddlesummation*: TKeySym = 0x000008B7
-    XK_lessthanequal*: TKeySym = 0x000008BC
-    XK_notequal*: TKeySym = 0x000008BD
-    XK_greaterthanequal*: TKeySym = 0x000008BE
-    XK_integral*: TKeySym = 0x000008BF
-    XK_therefore*: TKeySym = 0x000008C0
-    XK_variation*: TKeySym = 0x000008C1
-    XK_infinity*: TKeySym = 0x000008C2
-    XK_nabla*: TKeySym = 0x000008C5
-    XK_approximate*: TKeySym = 0x000008C8
-    XK_similarequal*: TKeySym = 0x000008C9
-    XK_ifonlyif*: TKeySym = 0x000008CD
-    XK_implies*: TKeySym = 0x000008CE
-    XK_identical*: TKeySym = 0x000008CF
-    XK_radical*: TKeySym = 0x000008D6
-    XK_includedin*: TKeySym = 0x000008DA
-    XK_includes*: TKeySym = 0x000008DB
-    XK_intersection*: TKeySym = 0x000008DC
-    XK_union*: TKeySym = 0x000008DD
-    XK_logicaland*: TKeySym = 0x000008DE
-    XK_logicalor*: TKeySym = 0x000008DF
-    XK_partialderivative*: TKeySym = 0x000008EF
-    XK_function*: TKeySym = 0x000008F6
-    XK_leftarrow*: TKeySym = 0x000008FB
-    XK_uparrow*: TKeySym = 0x000008FC
-    XK_rightarrow*: TKeySym = 0x000008FD
-    XK_downarrow*: TKeySym = 0x000008FE
-# XK_TECHNICAL 
-#*
-# *  Special
-# *  Byte 3 = 9
-# *
-
-when defined(XK_SPECIAL): 
-  const
-    XK_blank*: TKeySym = 0x000009DF
-    XK_soliddiamond*: TKeySym = 0x000009E0
-    XK_checkerboard*: TKeySym = 0x000009E1
-    XK_ht*: TKeySym = 0x000009E2
-    XK_ff*: TKeySym = 0x000009E3
-    XK_cr*: TKeySym = 0x000009E4
-    XK_lf*: TKeySym = 0x000009E5
-    XK_nl*: TKeySym = 0x000009E8
-    XK_vt*: TKeySym = 0x000009E9
-    XK_lowrightcorner*: TKeySym = 0x000009EA
-    XK_uprightcorner*: TKeySym = 0x000009EB
-    XK_upleftcorner*: TKeySym = 0x000009EC
-    XK_lowleftcorner*: TKeySym = 0x000009ED
-    XK_crossinglines*: TKeySym = 0x000009EE
-    XK_horizlinescan1*: TKeySym = 0x000009EF
-    XK_horizlinescan3*: TKeySym = 0x000009F0
-    XK_horizlinescan5*: TKeySym = 0x000009F1
-    XK_horizlinescan7*: TKeySym = 0x000009F2
-    XK_horizlinescan9*: TKeySym = 0x000009F3
-    XK_leftt*: TKeySym = 0x000009F4
-    XK_rightt*: TKeySym = 0x000009F5
-    XK_bott*: TKeySym = 0x000009F6
-    XK_topt*: TKeySym = 0x000009F7
-    XK_vertbar*: TKeySym = 0x000009F8
-# XK_SPECIAL 
-#*
-# *  Publishing
-# *  Byte 3 = a
-# *
-
-when defined(XK_PUBLISHING) or true: 
-  const
-    XK_emspace*: TKeySym = 0x00000AA1
-    XK_enspace*: TKeySym = 0x00000AA2
-    XK_em3space*: TKeySym = 0x00000AA3
-    XK_em4space*: TKeySym = 0x00000AA4
-    XK_digitspace*: TKeySym = 0x00000AA5
-    XK_punctspace*: TKeySym = 0x00000AA6
-    XK_thinspace*: TKeySym = 0x00000AA7
-    XK_hairspace*: TKeySym = 0x00000AA8
-    XK_emdash*: TKeySym = 0x00000AA9
-    XK_endash*: TKeySym = 0x00000AAA
-    XK_signifblank*: TKeySym = 0x00000AAC
-    XK_ellipsis*: TKeySym = 0x00000AAE
-    XK_doubbaselinedot*: TKeySym = 0x00000AAF
-    XK_onethird*: TKeySym = 0x00000AB0
-    XK_twothirds*: TKeySym = 0x00000AB1
-    XK_onefifth*: TKeySym = 0x00000AB2
-    XK_twofifths*: TKeySym = 0x00000AB3
-    XK_threefifths*: TKeySym = 0x00000AB4
-    XK_fourfifths*: TKeySym = 0x00000AB5
-    XK_onesixth*: TKeySym = 0x00000AB6
-    XK_fivesixths*: TKeySym = 0x00000AB7
-    XK_careof*: TKeySym = 0x00000AB8
-    XK_figdash*: TKeySym = 0x00000ABB
-    XK_leftanglebracket*: TKeySym = 0x00000ABC
-    XK_decimalpoint*: TKeySym = 0x00000ABD
-    XK_rightanglebracket*: TKeySym = 0x00000ABE
-    XK_marker*: TKeySym = 0x00000ABF
-    XK_oneeighth*: TKeySym = 0x00000AC3
-    XK_threeeighths*: TKeySym = 0x00000AC4
-    XK_fiveeighths*: TKeySym = 0x00000AC5
-    XK_seveneighths*: TKeySym = 0x00000AC6
-    XK_trademark*: TKeySym = 0x00000AC9
-    XK_signaturemark*: TKeySym = 0x00000ACA
-    XK_trademarkincircle*: TKeySym = 0x00000ACB
-    XK_leftopentriangle*: TKeySym = 0x00000ACC
-    XK_rightopentriangle*: TKeySym = 0x00000ACD
-    XK_emopencircle*: TKeySym = 0x00000ACE
-    XK_emopenrectangle*: TKeySym = 0x00000ACF
-    XK_leftsinglequotemark*: TKeySym = 0x00000AD0
-    XK_rightsinglequotemark*: TKeySym = 0x00000AD1
-    XK_leftdoublequotemark*: TKeySym = 0x00000AD2
-    XK_rightdoublequotemark*: TKeySym = 0x00000AD3
-    XK_prescription*: TKeySym = 0x00000AD4
-    XK_minutes*: TKeySym = 0x00000AD6
-    XK_seconds*: TKeySym = 0x00000AD7
-    XK_latincross*: TKeySym = 0x00000AD9
-    XK_hexagram*: TKeySym = 0x00000ADA
-    XK_filledrectbullet*: TKeySym = 0x00000ADB
-    XK_filledlefttribullet*: TKeySym = 0x00000ADC
-    XK_filledrighttribullet*: TKeySym = 0x00000ADD
-    XK_emfilledcircle*: TKeySym = 0x00000ADE
-    XK_emfilledrect*: TKeySym = 0x00000ADF
-    XK_enopencircbullet*: TKeySym = 0x00000AE0
-    XK_enopensquarebullet*: TKeySym = 0x00000AE1
-    XK_openrectbullet*: TKeySym = 0x00000AE2
-    XK_opentribulletup*: TKeySym = 0x00000AE3
-    XK_opentribulletdown*: TKeySym = 0x00000AE4
-    XK_openstar*: TKeySym = 0x00000AE5
-    XK_enfilledcircbullet*: TKeySym = 0x00000AE6
-    XK_enfilledsqbullet*: TKeySym = 0x00000AE7
-    XK_filledtribulletup*: TKeySym = 0x00000AE8
-    XK_filledtribulletdown*: TKeySym = 0x00000AE9
-    XK_leftpointer*: TKeySym = 0x00000AEA
-    XK_rightpointer*: TKeySym = 0x00000AEB
-    XK_club*: TKeySym = 0x00000AEC
-    XK_diamond*: TKeySym = 0x00000AED
-    XK_heart*: TKeySym = 0x00000AEE
-    XK_maltesecross*: TKeySym = 0x00000AF0
-    XK_dagger*: TKeySym = 0x00000AF1
-    XK_doubledagger*: TKeySym = 0x00000AF2
-    XK_checkmark*: TKeySym = 0x00000AF3
-    XK_ballotcross*: TKeySym = 0x00000AF4
-    XK_musicalsharp*: TKeySym = 0x00000AF5
-    XK_musicalflat*: TKeySym = 0x00000AF6
-    XK_malesymbol*: TKeySym = 0x00000AF7
-    XK_femalesymbol*: TKeySym = 0x00000AF8
-    XK_telephone*: TKeySym = 0x00000AF9
-    XK_telephonerecorder*: TKeySym = 0x00000AFA
-    XK_phonographcopyright*: TKeySym = 0x00000AFB
-    XK_caret*: TKeySym = 0x00000AFC
-    XK_singlelowquotemark*: TKeySym = 0x00000AFD
-    XK_doublelowquotemark*: TKeySym = 0x00000AFE
-    XK_cursor*: TKeySym = 0x00000AFF
-# XK_PUBLISHING 
-#*
-# *  APL
-# *  Byte 3 = b
-# *
-
-when defined(XK_APL) or true: 
-  const
-    XK_leftcaret*: TKeySym = 0x00000BA3
-    XK_rightcaret*: TKeySym = 0x00000BA6
-    XK_downcaret*: TKeySym = 0x00000BA8
-    XK_upcaret*: TKeySym = 0x00000BA9
-    XK_overbar*: TKeySym = 0x00000BC0
-    XK_downtack*: TKeySym = 0x00000BC2
-    XK_upshoe*: TKeySym = 0x00000BC3
-    XK_downstile*: TKeySym = 0x00000BC4
-    XK_underbar*: TKeySym = 0x00000BC6
-    XK_jot*: TKeySym = 0x00000BCA
-    XK_quad*: TKeySym = 0x00000BCC
-    XK_uptack*: TKeySym = 0x00000BCE
-    XK_circle*: TKeySym = 0x00000BCF
-    XK_upstile*: TKeySym = 0x00000BD3
-    XK_downshoe*: TKeySym = 0x00000BD6
-    XK_rightshoe*: TKeySym = 0x00000BD8
-    XK_leftshoe*: TKeySym = 0x00000BDA
-    XK_lefttack*: TKeySym = 0x00000BDC
-    XK_righttack*: TKeySym = 0x00000BFC
-# XK_APL 
-#*
-# * Hebrew
-# * Byte 3 = c
-# *
-
-when defined(XK_HEBREW) or true: 
-  const
-    XK_hebrew_doublelowline*: TKeySym = 0x00000CDF
-    XK_hebrew_aleph*: TKeySym = 0x00000CE0
-    XK_hebrew_bet*: TKeySym = 0x00000CE1
-    XK_hebrew_beth*: TKeySym = 0x00000CE1 # deprecated 
-    XK_hebrew_gimel*: TKeySym = 0x00000CE2
-    XK_hebrew_gimmel*: TKeySym = 0x00000CE2 # deprecated 
-    XK_hebrew_dalet*: TKeySym = 0x00000CE3
-    XK_hebrew_daleth*: TKeySym = 0x00000CE3 # deprecated 
-    XK_hebrew_he*: TKeySym = 0x00000CE4
-    XK_hebrew_waw*: TKeySym = 0x00000CE5
-    XK_hebrew_zain*: TKeySym = 0x00000CE6
-    XK_hebrew_zayin*: TKeySym = 0x00000CE6 # deprecated 
-    XK_hebrew_chet*: TKeySym = 0x00000CE7
-    XK_hebrew_het*: TKeySym = 0x00000CE7 # deprecated 
-    XK_hebrew_tet*: TKeySym = 0x00000CE8
-    XK_hebrew_teth*: TKeySym = 0x00000CE8 # deprecated 
-    XK_hebrew_yod*: TKeySym = 0x00000CE9
-    XK_hebrew_finalkaph*: TKeySym = 0x00000CEA
-    XK_hebrew_kaph*: TKeySym = 0x00000CEB
-    XK_hebrew_lamed*: TKeySym = 0x00000CEC
-    XK_hebrew_finalmem*: TKeySym = 0x00000CED
-    XK_hebrew_mem*: TKeySym = 0x00000CEE
-    XK_hebrew_finalnun*: TKeySym = 0x00000CEF
-    XK_hebrew_nun*: TKeySym = 0x00000CF0
-    XK_hebrew_samech*: TKeySym = 0x00000CF1
-    XK_hebrew_samekh*: TKeySym = 0x00000CF1 # deprecated 
-    XK_hebrew_ayin*: TKeySym = 0x00000CF2
-    XK_hebrew_finalpe*: TKeySym = 0x00000CF3
-    XK_hebrew_pe*: TKeySym = 0x00000CF4
-    XK_hebrew_finalzade*: TKeySym = 0x00000CF5
-    XK_hebrew_finalzadi*: TKeySym = 0x00000CF5 # deprecated 
-    XK_hebrew_zade*: TKeySym = 0x00000CF6
-    XK_hebrew_zadi*: TKeySym = 0x00000CF6 # deprecated 
-    XK_hebrew_qoph*: TKeySym = 0x00000CF7
-    XK_hebrew_kuf*: TKeySym = 0x00000CF7 # deprecated 
-    XK_hebrew_resh*: TKeySym = 0x00000CF8
-    XK_hebrew_shin*: TKeySym = 0x00000CF9
-    XK_hebrew_taw*: TKeySym = 0x00000CFA
-    XK_hebrew_taf*: TKeySym = 0x00000CFA # deprecated 
-    XK_Hebrew_switch*: TKeySym = 0x0000FF7E # Alias for mode_switch 
-# XK_HEBREW 
-#*
-# * Thai
-# * Byte 3 = d
-# *
-
-when defined(XK_THAI) or true: 
-  const
-    XK_Thai_kokai*: TKeySym = 0x00000DA1
-    XK_Thai_khokhai*: TKeySym = 0x00000DA2
-    XK_Thai_khokhuat*: TKeySym = 0x00000DA3
-    XK_Thai_khokhwai*: TKeySym = 0x00000DA4
-    XK_Thai_khokhon*: TKeySym = 0x00000DA5
-    XK_Thai_khorakhang*: TKeySym = 0x00000DA6
-    XK_Thai_ngongu*: TKeySym = 0x00000DA7
-    XK_Thai_chochan*: TKeySym = 0x00000DA8
-    XK_Thai_choching*: TKeySym = 0x00000DA9
-    XK_Thai_chochang*: TKeySym = 0x00000DAA
-    XK_Thai_soso*: TKeySym = 0x00000DAB
-    XK_Thai_chochoe*: TKeySym = 0x00000DAC
-    XK_Thai_yoying*: TKeySym = 0x00000DAD
-    XK_Thai_dochada*: TKeySym = 0x00000DAE
-    XK_Thai_topatak*: TKeySym = 0x00000DAF
-    XK_Thai_thothan*: TKeySym = 0x00000DB0
-    XK_Thai_thonangmontho*: TKeySym = 0x00000DB1
-    XK_Thai_thophuthao*: TKeySym = 0x00000DB2
-    XK_Thai_nonen*: TKeySym = 0x00000DB3
-    XK_Thai_dodek*: TKeySym = 0x00000DB4
-    XK_Thai_totao*: TKeySym = 0x00000DB5
-    XK_Thai_thothung*: TKeySym = 0x00000DB6
-    XK_Thai_thothahan*: TKeySym = 0x00000DB7
-    XK_Thai_thothong*: TKeySym = 0x00000DB8
-    XK_Thai_nonu*: TKeySym = 0x00000DB9
-    XK_Thai_bobaimai*: TKeySym = 0x00000DBA
-    XK_Thai_popla*: TKeySym = 0x00000DBB
-    XK_Thai_phophung*: TKeySym = 0x00000DBC
-    XK_Thai_fofa*: TKeySym = 0x00000DBD
-    XK_Thai_phophan*: TKeySym = 0x00000DBE
-    XK_Thai_fofan*: TKeySym = 0x00000DBF
-    XK_Thai_phosamphao*: TKeySym = 0x00000DC0
-    XK_Thai_moma*: TKeySym = 0x00000DC1
-    XK_Thai_yoyak*: TKeySym = 0x00000DC2
-    XK_Thai_rorua*: TKeySym = 0x00000DC3
-    XK_Thai_ru*: TKeySym = 0x00000DC4
-    XK_Thai_loling*: TKeySym = 0x00000DC5
-    XK_Thai_lu*: TKeySym = 0x00000DC6
-    XK_Thai_wowaen*: TKeySym = 0x00000DC7
-    XK_Thai_sosala*: TKeySym = 0x00000DC8
-    XK_Thai_sorusi*: TKeySym = 0x00000DC9
-    XK_Thai_sosua*: TKeySym = 0x00000DCA
-    XK_Thai_hohip*: TKeySym = 0x00000DCB
-    XK_Thai_lochula*: TKeySym = 0x00000DCC
-    XK_Thai_oang*: TKeySym = 0x00000DCD
-    XK_Thai_honokhuk*: TKeySym = 0x00000DCE
-    XK_Thai_paiyannoi*: TKeySym = 0x00000DCF
-    XK_Thai_saraa*: TKeySym = 0x00000DD0
-    XK_Thai_maihanakat*: TKeySym = 0x00000DD1
-    XK_Thai_saraaa*: TKeySym = 0x00000DD2
-    XK_Thai_saraam*: TKeySym = 0x00000DD3
-    XK_Thai_sarai*: TKeySym = 0x00000DD4
-    XK_Thai_saraii*: TKeySym = 0x00000DD5
-    XK_Thai_saraue*: TKeySym = 0x00000DD6
-    XK_Thai_sarauee*: TKeySym = 0x00000DD7
-    XK_Thai_sarau*: TKeySym = 0x00000DD8
-    XK_Thai_sarauu*: TKeySym = 0x00000DD9
-    XK_Thai_phinthu*: TKeySym = 0x00000DDA
-    XK_Thai_maihanakat_maitho*: TKeySym = 0x00000DDE
-    XK_Thai_baht*: TKeySym = 0x00000DDF
-    XK_Thai_sarae*: TKeySym = 0x00000DE0
-    XK_Thai_saraae*: TKeySym = 0x00000DE1
-    XK_Thai_sarao*: TKeySym = 0x00000DE2
-    XK_Thai_saraaimaimuan*: TKeySym = 0x00000DE3
-    XK_Thai_saraaimaimalai*: TKeySym = 0x00000DE4
-    XK_Thai_lakkhangyao*: TKeySym = 0x00000DE5
-    XK_Thai_maiyamok*: TKeySym = 0x00000DE6
-    XK_Thai_maitaikhu*: TKeySym = 0x00000DE7
-    XK_Thai_maiek*: TKeySym = 0x00000DE8
-    XK_Thai_maitho*: TKeySym = 0x00000DE9
-    XK_Thai_maitri*: TKeySym = 0x00000DEA
-    XK_Thai_maichattawa*: TKeySym = 0x00000DEB
-    XK_Thai_thanthakhat*: TKeySym = 0x00000DEC
-    XK_Thai_nikhahit*: TKeySym = 0x00000DED
-    XK_Thai_leksun*: TKeySym = 0x00000DF0
-    XK_Thai_leknung*: TKeySym = 0x00000DF1
-    XK_Thai_leksong*: TKeySym = 0x00000DF2
-    XK_Thai_leksam*: TKeySym = 0x00000DF3
-    XK_Thai_leksi*: TKeySym = 0x00000DF4
-    XK_Thai_lekha*: TKeySym = 0x00000DF5
-    XK_Thai_lekhok*: TKeySym = 0x00000DF6
-    XK_Thai_lekchet*: TKeySym = 0x00000DF7
-    XK_Thai_lekpaet*: TKeySym = 0x00000DF8
-    XK_Thai_lekkao*: TKeySym = 0x00000DF9
-# XK_THAI 
-#*
-# *   Korean
-# *   Byte 3 = e
-# *
-
-when defined(XK_KOREAN) or true: 
-  const
-    XK_Hangul*: TKeySym = 0x0000FF31     # Hangul start/stop(toggle) 
-    XK_Hangul_Start*: TKeySym = 0x0000FF32 # Hangul start 
-    XK_Hangul_End*: TKeySym = 0x0000FF33 # Hangul end, English start 
-    XK_Hangul_Hanja*: TKeySym = 0x0000FF34 # Start Hangul->Hanja Conversion 
-    XK_Hangul_Jamo*: TKeySym = 0x0000FF35 # Hangul Jamo mode 
-    XK_Hangul_Romaja*: TKeySym = 0x0000FF36 # Hangul Romaja mode 
-    XK_Hangul_Codeinput*: TKeySym = 0x0000FF37 # Hangul code input mode 
-    XK_Hangul_Jeonja*: TKeySym = 0x0000FF38 # Jeonja mode 
-    XK_Hangul_Banja*: TKeySym = 0x0000FF39 # Banja mode 
-    XK_Hangul_PreHanja*: TKeySym = 0x0000FF3A # Pre Hanja conversion 
-    XK_Hangul_PostHanja*: TKeySym = 0x0000FF3B # Post Hanja conversion 
-    XK_Hangul_SingleCandidate*: TKeySym = 0x0000FF3C # Single candidate 
-    XK_Hangul_MultipleCandidate*: TKeySym = 0x0000FF3D # Multiple candidate 
-    XK_Hangul_PreviousCandidate*: TKeySym = 0x0000FF3E # Previous candidate 
-    XK_Hangul_Special*: TKeySym = 0x0000FF3F # Special symbols 
-    XK_Hangul_switch*: TKeySym = 0x0000FF7E # Alias for mode_switch \
-                                   # Hangul Consonant Characters 
-    XK_Hangul_Kiyeog*: TKeySym = 0x00000EA1
-    XK_Hangul_SsangKiyeog*: TKeySym = 0x00000EA2
-    XK_Hangul_KiyeogSios*: TKeySym = 0x00000EA3
-    XK_Hangul_Nieun*: TKeySym = 0x00000EA4
-    XK_Hangul_NieunJieuj*: TKeySym = 0x00000EA5
-    XK_Hangul_NieunHieuh*: TKeySym = 0x00000EA6
-    XK_Hangul_Dikeud*: TKeySym = 0x00000EA7
-    XK_Hangul_SsangDikeud*: TKeySym = 0x00000EA8
-    XK_Hangul_Rieul*: TKeySym = 0x00000EA9
-    XK_Hangul_RieulKiyeog*: TKeySym = 0x00000EAA
-    XK_Hangul_RieulMieum*: TKeySym = 0x00000EAB
-    XK_Hangul_RieulPieub*: TKeySym = 0x00000EAC
-    XK_Hangul_RieulSios*: TKeySym = 0x00000EAD
-    XK_Hangul_RieulTieut*: TKeySym = 0x00000EAE
-    XK_Hangul_RieulPhieuf*: TKeySym = 0x00000EAF
-    XK_Hangul_RieulHieuh*: TKeySym = 0x00000EB0
-    XK_Hangul_Mieum*: TKeySym = 0x00000EB1
-    XK_Hangul_Pieub*: TKeySym = 0x00000EB2
-    XK_Hangul_SsangPieub*: TKeySym = 0x00000EB3
-    XK_Hangul_PieubSios*: TKeySym = 0x00000EB4
-    XK_Hangul_Sios*: TKeySym = 0x00000EB5
-    XK_Hangul_SsangSios*: TKeySym = 0x00000EB6
-    XK_Hangul_Ieung*: TKeySym = 0x00000EB7
-    XK_Hangul_Jieuj*: TKeySym = 0x00000EB8
-    XK_Hangul_SsangJieuj*: TKeySym = 0x00000EB9
-    XK_Hangul_Cieuc*: TKeySym = 0x00000EBA
-    XK_Hangul_Khieuq*: TKeySym = 0x00000EBB
-    XK_Hangul_Tieut*: TKeySym = 0x00000EBC
-    XK_Hangul_Phieuf*: TKeySym = 0x00000EBD
-    XK_Hangul_Hieuh*: TKeySym = 0x00000EBE # Hangul Vowel Characters 
-    XK_Hangul_A*: TKeySym = 0x00000EBF
-    XK_Hangul_AE*: TKeySym = 0x00000EC0
-    XK_Hangul_YA*: TKeySym = 0x00000EC1
-    XK_Hangul_YAE*: TKeySym = 0x00000EC2
-    XK_Hangul_EO*: TKeySym = 0x00000EC3
-    XK_Hangul_E*: TKeySym = 0x00000EC4
-    XK_Hangul_YEO*: TKeySym = 0x00000EC5
-    XK_Hangul_YE*: TKeySym = 0x00000EC6
-    XK_Hangul_O*: TKeySym = 0x00000EC7
-    XK_Hangul_WA*: TKeySym = 0x00000EC8
-    XK_Hangul_WAE*: TKeySym = 0x00000EC9
-    XK_Hangul_OE*: TKeySym = 0x00000ECA
-    XK_Hangul_YO*: TKeySym = 0x00000ECB
-    XK_Hangul_U*: TKeySym = 0x00000ECC
-    XK_Hangul_WEO*: TKeySym = 0x00000ECD
-    XK_Hangul_WE*: TKeySym = 0x00000ECE
-    XK_Hangul_WI*: TKeySym = 0x00000ECF
-    XK_Hangul_YU*: TKeySym = 0x00000ED0
-    XK_Hangul_EU*: TKeySym = 0x00000ED1
-    XK_Hangul_YI*: TKeySym = 0x00000ED2
-    XK_Hangul_I*: TKeySym = 0x00000ED3   # Hangul syllable-final (JongSeong) Characters 
-    XK_Hangul_J_Kiyeog*: TKeySym = 0x00000ED4
-    XK_Hangul_J_SsangKiyeog*: TKeySym = 0x00000ED5
-    XK_Hangul_J_KiyeogSios*: TKeySym = 0x00000ED6
-    XK_Hangul_J_Nieun*: TKeySym = 0x00000ED7
-    XK_Hangul_J_NieunJieuj*: TKeySym = 0x00000ED8
-    XK_Hangul_J_NieunHieuh*: TKeySym = 0x00000ED9
-    XK_Hangul_J_Dikeud*: TKeySym = 0x00000EDA
-    XK_Hangul_J_Rieul*: TKeySym = 0x00000EDB
-    XK_Hangul_J_RieulKiyeog*: TKeySym = 0x00000EDC
-    XK_Hangul_J_RieulMieum*: TKeySym = 0x00000EDD
-    XK_Hangul_J_RieulPieub*: TKeySym = 0x00000EDE
-    XK_Hangul_J_RieulSios*: TKeySym = 0x00000EDF
-    XK_Hangul_J_RieulTieut*: TKeySym = 0x00000EE0
-    XK_Hangul_J_RieulPhieuf*: TKeySym = 0x00000EE1
-    XK_Hangul_J_RieulHieuh*: TKeySym = 0x00000EE2
-    XK_Hangul_J_Mieum*: TKeySym = 0x00000EE3
-    XK_Hangul_J_Pieub*: TKeySym = 0x00000EE4
-    XK_Hangul_J_PieubSios*: TKeySym = 0x00000EE5
-    XK_Hangul_J_Sios*: TKeySym = 0x00000EE6
-    XK_Hangul_J_SsangSios*: TKeySym = 0x00000EE7
-    XK_Hangul_J_Ieung*: TKeySym = 0x00000EE8
-    XK_Hangul_J_Jieuj*: TKeySym = 0x00000EE9
-    XK_Hangul_J_Cieuc*: TKeySym = 0x00000EEA
-    XK_Hangul_J_Khieuq*: TKeySym = 0x00000EEB
-    XK_Hangul_J_Tieut*: TKeySym = 0x00000EEC
-    XK_Hangul_J_Phieuf*: TKeySym = 0x00000EED
-    XK_Hangul_J_Hieuh*: TKeySym = 0x00000EEE # Ancient Hangul Consonant Characters 
-    XK_Hangul_RieulYeorinHieuh*: TKeySym = 0x00000EEF
-    XK_Hangul_SunkyeongeumMieum*: TKeySym = 0x00000EF0
-    XK_Hangul_SunkyeongeumPieub*: TKeySym = 0x00000EF1
-    XK_Hangul_PanSios*: TKeySym = 0x00000EF2
-    XK_Hangul_KkogjiDalrinIeung*: TKeySym = 0x00000EF3
-    XK_Hangul_SunkyeongeumPhieuf*: TKeySym = 0x00000EF4
-    XK_Hangul_YeorinHieuh*: TKeySym = 0x00000EF5 # Ancient Hangul Vowel Characters 
-    XK_Hangul_AraeA*: TKeySym = 0x00000EF6
-    XK_Hangul_AraeAE*: TKeySym = 0x00000EF7 # Ancient Hangul syllable-final (JongSeong) Characters 
-    XK_Hangul_J_PanSios*: TKeySym = 0x00000EF8
-    XK_Hangul_J_KkogjiDalrinIeung*: TKeySym = 0x00000EF9
-    XK_Hangul_J_YeorinHieuh*: TKeySym = 0x00000EFA # Korean currency symbol 
-    XK_Korean_Won*: TKeySym = 0x00000EFF
-# XK_KOREAN 
-#*
-# *   Armenian
-# *   Byte 3 = = $14
-# *
-
-when defined(XK_ARMENIAN) or true: 
-  const
-    XK_Armenian_eternity*: TKeySym = 0x000014A1
-    XK_Armenian_ligature_ew*: TKeySym = 0x000014A2
-    XK_Armenian_full_stop*: TKeySym = 0x000014A3
-    XK_Armenian_verjaket*: TKeySym = 0x000014A3
-    XK_Armenian_parenright*: TKeySym = 0x000014A4
-    XK_Armenian_parenleft*: TKeySym = 0x000014A5
-    XK_Armenian_guillemotright*: TKeySym = 0x000014A6
-    XK_Armenian_guillemotleft*: TKeySym = 0x000014A7
-    XK_Armenian_em_dash*: TKeySym = 0x000014A8
-    XK_Armenian_dot*: TKeySym = 0x000014A9
-    XK_Armenian_mijaket*: TKeySym = 0x000014A9
-    XK_Armenian_separation_mark*: TKeySym = 0x000014AA
-    XK_Armenian_but*: TKeySym = 0x000014AA
-    XK_Armenian_comma*: TKeySym = 0x000014AB
-    XK_Armenian_en_dash*: TKeySym = 0x000014AC
-    XK_Armenian_hyphen*: TKeySym = 0x000014AD
-    XK_Armenian_yentamna*: TKeySym = 0x000014AD
-    XK_Armenian_ellipsis*: TKeySym = 0x000014AE
-    XK_Armenian_exclam*: TKeySym = 0x000014AF
-    XK_Armenian_amanak*: TKeySym = 0x000014AF
-    XK_Armenian_accent*: TKeySym = 0x000014B0
-    XK_Armenian_shesht*: TKeySym = 0x000014B0
-    XK_Armenian_question*: TKeySym = 0x000014B1
-    XK_Armenian_paruyk*: TKeySym = 0x000014B1
-    XKc_Armenian_AYB*: TKeySym = 0x000014B2
-    XK_Armenian_ayb*: TKeySym = 0x000014B3
-    XKc_Armenian_BEN*: TKeySym = 0x000014B4
-    XK_Armenian_ben*: TKeySym = 0x000014B5
-    XKc_Armenian_GIM*: TKeySym = 0x000014B6
-    XK_Armenian_gim*: TKeySym = 0x000014B7
-    XKc_Armenian_DA*: TKeySym = 0x000014B8
-    XK_Armenian_da*: TKeySym = 0x000014B9
-    XKc_Armenian_YECH*: TKeySym = 0x000014BA
-    XK_Armenian_yech*: TKeySym = 0x000014BB
-    XKc_Armenian_ZA*: TKeySym = 0x000014BC
-    XK_Armenian_za*: TKeySym = 0x000014BD
-    XKc_Armenian_E*: TKeySym = 0x000014BE
-    XK_Armenian_e*: TKeySym = 0x000014BF
-    XKc_Armenian_AT*: TKeySym = 0x000014C0
-    XK_Armenian_at*: TKeySym = 0x000014C1
-    XKc_Armenian_TO*: TKeySym = 0x000014C2
-    XK_Armenian_to*: TKeySym = 0x000014C3
-    XKc_Armenian_ZHE*: TKeySym = 0x000014C4
-    XK_Armenian_zhe*: TKeySym = 0x000014C5
-    XKc_Armenian_INI*: TKeySym = 0x000014C6
-    XK_Armenian_ini*: TKeySym = 0x000014C7
-    XKc_Armenian_LYUN*: TKeySym = 0x000014C8
-    XK_Armenian_lyun*: TKeySym = 0x000014C9
-    XKc_Armenian_KHE*: TKeySym = 0x000014CA
-    XK_Armenian_khe*: TKeySym = 0x000014CB
-    XKc_Armenian_TSA*: TKeySym = 0x000014CC
-    XK_Armenian_tsa*: TKeySym = 0x000014CD
-    XKc_Armenian_KEN*: TKeySym = 0x000014CE
-    XK_Armenian_ken*: TKeySym = 0x000014CF
-    XKc_Armenian_HO*: TKeySym = 0x000014D0
-    XK_Armenian_ho*: TKeySym = 0x000014D1
-    XKc_Armenian_DZA*: TKeySym = 0x000014D2
-    XK_Armenian_dza*: TKeySym = 0x000014D3
-    XKc_Armenian_GHAT*: TKeySym = 0x000014D4
-    XK_Armenian_ghat*: TKeySym = 0x000014D5
-    XKc_Armenian_TCHE*: TKeySym = 0x000014D6
-    XK_Armenian_tche*: TKeySym = 0x000014D7
-    XKc_Armenian_MEN*: TKeySym = 0x000014D8
-    XK_Armenian_men*: TKeySym = 0x000014D9
-    XKc_Armenian_HI*: TKeySym = 0x000014DA
-    XK_Armenian_hi*: TKeySym = 0x000014DB
-    XKc_Armenian_NU*: TKeySym = 0x000014DC
-    XK_Armenian_nu*: TKeySym = 0x000014DD
-    XKc_Armenian_SHA*: TKeySym = 0x000014DE
-    XK_Armenian_sha*: TKeySym = 0x000014DF
-    XKc_Armenian_VO*: TKeySym = 0x000014E0
-    XK_Armenian_vo*: TKeySym = 0x000014E1
-    XKc_Armenian_CHA*: TKeySym = 0x000014E2
-    XK_Armenian_cha*: TKeySym = 0x000014E3
-    XKc_Armenian_PE*: TKeySym = 0x000014E4
-    XK_Armenian_pe*: TKeySym = 0x000014E5
-    XKc_Armenian_JE*: TKeySym = 0x000014E6
-    XK_Armenian_je*: TKeySym = 0x000014E7
-    XKc_Armenian_RA*: TKeySym = 0x000014E8
-    XK_Armenian_ra*: TKeySym = 0x000014E9
-    XKc_Armenian_SE*: TKeySym = 0x000014EA
-    XK_Armenian_se*: TKeySym = 0x000014EB
-    XKc_Armenian_VEV*: TKeySym = 0x000014EC
-    XK_Armenian_vev*: TKeySym = 0x000014ED
-    XKc_Armenian_TYUN*: TKeySym = 0x000014EE
-    XK_Armenian_tyun*: TKeySym = 0x000014EF
-    XKc_Armenian_RE*: TKeySym = 0x000014F0
-    XK_Armenian_re*: TKeySym = 0x000014F1
-    XKc_Armenian_TSO*: TKeySym = 0x000014F2
-    XK_Armenian_tso*: TKeySym = 0x000014F3
-    XKc_Armenian_VYUN*: TKeySym = 0x000014F4
-    XK_Armenian_vyun*: TKeySym = 0x000014F5
-    XKc_Armenian_PYUR*: TKeySym = 0x000014F6
-    XK_Armenian_pyur*: TKeySym = 0x000014F7
-    XKc_Armenian_KE*: TKeySym = 0x000014F8
-    XK_Armenian_ke*: TKeySym = 0x000014F9
-    XKc_Armenian_O*: TKeySym = 0x000014FA
-    XK_Armenian_o*: TKeySym = 0x000014FB
-    XKc_Armenian_FE*: TKeySym = 0x000014FC
-    XK_Armenian_fe*: TKeySym = 0x000014FD
-    XK_Armenian_apostrophe*: TKeySym = 0x000014FE
-    XK_Armenian_section_sign*: TKeySym = 0x000014FF
-# XK_ARMENIAN 
-#*
-# *   Georgian
-# *   Byte 3 = = $15
-# *
-
-when defined(XK_GEORGIAN) or true: 
-  const
-    XK_Georgian_an*: TKeySym = 0x000015D0
-    XK_Georgian_ban*: TKeySym = 0x000015D1
-    XK_Georgian_gan*: TKeySym = 0x000015D2
-    XK_Georgian_don*: TKeySym = 0x000015D3
-    XK_Georgian_en*: TKeySym = 0x000015D4
-    XK_Georgian_vin*: TKeySym = 0x000015D5
-    XK_Georgian_zen*: TKeySym = 0x000015D6
-    XK_Georgian_tan*: TKeySym = 0x000015D7
-    XK_Georgian_in*: TKeySym = 0x000015D8
-    XK_Georgian_kan*: TKeySym = 0x000015D9
-    XK_Georgian_las*: TKeySym = 0x000015DA
-    XK_Georgian_man*: TKeySym = 0x000015DB
-    XK_Georgian_nar*: TKeySym = 0x000015DC
-    XK_Georgian_on*: TKeySym = 0x000015DD
-    XK_Georgian_par*: TKeySym = 0x000015DE
-    XK_Georgian_zhar*: TKeySym = 0x000015DF
-    XK_Georgian_rae*: TKeySym = 0x000015E0
-    XK_Georgian_san*: TKeySym = 0x000015E1
-    XK_Georgian_tar*: TKeySym = 0x000015E2
-    XK_Georgian_un*: TKeySym = 0x000015E3
-    XK_Georgian_phar*: TKeySym = 0x000015E4
-    XK_Georgian_khar*: TKeySym = 0x000015E5
-    XK_Georgian_ghan*: TKeySym = 0x000015E6
-    XK_Georgian_qar*: TKeySym = 0x000015E7
-    XK_Georgian_shin*: TKeySym = 0x000015E8
-    XK_Georgian_chin*: TKeySym = 0x000015E9
-    XK_Georgian_can*: TKeySym = 0x000015EA
-    XK_Georgian_jil*: TKeySym = 0x000015EB
-    XK_Georgian_cil*: TKeySym = 0x000015EC
-    XK_Georgian_char*: TKeySym = 0x000015ED
-    XK_Georgian_xan*: TKeySym = 0x000015EE
-    XK_Georgian_jhan*: TKeySym = 0x000015EF
-    XK_Georgian_hae*: TKeySym = 0x000015F0
-    XK_Georgian_he*: TKeySym = 0x000015F1
-    XK_Georgian_hie*: TKeySym = 0x000015F2
-    XK_Georgian_we*: TKeySym = 0x000015F3
-    XK_Georgian_har*: TKeySym = 0x000015F4
-    XK_Georgian_hoe*: TKeySym = 0x000015F5
-    XK_Georgian_fi*: TKeySym = 0x000015F6
-# XK_GEORGIAN 
-#*
-# * Azeri (and other Turkic or Caucasian languages of ex-USSR)
-# * Byte 3 = = $16
-# *
-
-when defined(XK_CAUCASUS) or true: 
-  # latin 
-  const
-    XKc_Ccedillaabovedot*: TKeySym = 0x000016A2
-    XKc_Xabovedot*: TKeySym = 0x000016A3
-    XKc_Qabovedot*: TKeySym = 0x000016A5
-    XKc_Ibreve*: TKeySym = 0x000016A6
-    XKc_IE*: TKeySym = 0x000016A7
-    XKc_UO*: TKeySym = 0x000016A8
-    XKc_Zstroke*: TKeySym = 0x000016A9
-    XKc_Gcaron*: TKeySym = 0x000016AA
-    XKc_Obarred*: TKeySym = 0x000016AF
-    XK_ccedillaabovedot*: TKeySym = 0x000016B2
-    XK_xabovedot*: TKeySym = 0x000016B3
-    XKc_Ocaron*: TKeySym = 0x000016B4
-    XK_qabovedot*: TKeySym = 0x000016B5
-    XK_ibreve*: TKeySym = 0x000016B6
-    XK_ie*: TKeySym = 0x000016B7
-    XK_uo*: TKeySym = 0x000016B8
-    XK_zstroke*: TKeySym = 0x000016B9
-    XK_gcaron*: TKeySym = 0x000016BA
-    XK_ocaron*: TKeySym = 0x000016BD
-    XK_obarred*: TKeySym = 0x000016BF
-    XKc_SCHWA*: TKeySym = 0x000016C6
-    XK_schwa*: TKeySym = 0x000016F6 # those are not really Caucasus, but I put them here for now\ 
-                           # For Inupiak 
-    XKc_Lbelowdot*: TKeySym = 0x000016D1
-    XKc_Lstrokebelowdot*: TKeySym = 0x000016D2
-    XK_lbelowdot*: TKeySym = 0x000016E1
-    XK_lstrokebelowdot*: TKeySym = 0x000016E2 # For Guarani 
-    XKc_Gtilde*: TKeySym = 0x000016D3
-    XK_gtilde*: TKeySym = 0x000016E3
-# XK_CAUCASUS 
-#*
-# *   Vietnamese
-# *   Byte 3 = = $1e
-# *
-
-when defined(XK_VIETNAMESE) or true:
-  const 
-    XKc_Abelowdot*: TKeySym = 0x00001EA0
-    XK_abelowdot*: TKeySym = 0x00001EA1
-    XKc_Ahook*: TKeySym = 0x00001EA2
-    XK_ahook*: TKeySym = 0x00001EA3
-    XKc_Acircumflexacute*: TKeySym = 0x00001EA4
-    XK_acircumflexacute*: TKeySym = 0x00001EA5
-    XKc_Acircumflexgrave*: TKeySym = 0x00001EA6
-    XK_acircumflexgrave*: TKeySym = 0x00001EA7
-    XKc_Acircumflexhook*: TKeySym = 0x00001EA8
-    XK_acircumflexhook*: TKeySym = 0x00001EA9
-    XKc_Acircumflextilde*: TKeySym = 0x00001EAA
-    XK_acircumflextilde*: TKeySym = 0x00001EAB
-    XKc_Acircumflexbelowdot*: TKeySym = 0x00001EAC
-    XK_acircumflexbelowdot*: TKeySym = 0x00001EAD
-    XKc_Abreveacute*: TKeySym = 0x00001EAE
-    XK_abreveacute*: TKeySym = 0x00001EAF
-    XKc_Abrevegrave*: TKeySym = 0x00001EB0
-    XK_abrevegrave*: TKeySym = 0x00001EB1
-    XKc_Abrevehook*: TKeySym = 0x00001EB2
-    XK_abrevehook*: TKeySym = 0x00001EB3
-    XKc_Abrevetilde*: TKeySym = 0x00001EB4
-    XK_abrevetilde*: TKeySym = 0x00001EB5
-    XKc_Abrevebelowdot*: TKeySym = 0x00001EB6
-    XK_abrevebelowdot*: TKeySym = 0x00001EB7
-    XKc_Ebelowdot*: TKeySym = 0x00001EB8
-    XK_ebelowdot*: TKeySym = 0x00001EB9
-    XKc_Ehook*: TKeySym = 0x00001EBA
-    XK_ehook*: TKeySym = 0x00001EBB
-    XKc_Etilde*: TKeySym = 0x00001EBC
-    XK_etilde*: TKeySym = 0x00001EBD
-    XKc_Ecircumflexacute*: TKeySym = 0x00001EBE
-    XK_ecircumflexacute*: TKeySym = 0x00001EBF
-    XKc_Ecircumflexgrave*: TKeySym = 0x00001EC0
-    XK_ecircumflexgrave*: TKeySym = 0x00001EC1
-    XKc_Ecircumflexhook*: TKeySym = 0x00001EC2
-    XK_ecircumflexhook*: TKeySym = 0x00001EC3
-    XKc_Ecircumflextilde*: TKeySym = 0x00001EC4
-    XK_ecircumflextilde*: TKeySym = 0x00001EC5
-    XKc_Ecircumflexbelowdot*: TKeySym = 0x00001EC6
-    XK_ecircumflexbelowdot*: TKeySym = 0x00001EC7
-    XKc_Ihook*: TKeySym = 0x00001EC8
-    XK_ihook*: TKeySym = 0x00001EC9
-    XKc_Ibelowdot*: TKeySym = 0x00001ECA
-    XK_ibelowdot*: TKeySym = 0x00001ECB
-    XKc_Obelowdot*: TKeySym = 0x00001ECC
-    XK_obelowdot*: TKeySym = 0x00001ECD
-    XKc_Ohook*: TKeySym = 0x00001ECE
-    XK_ohook*: TKeySym = 0x00001ECF
-    XKc_Ocircumflexacute*: TKeySym = 0x00001ED0
-    XK_ocircumflexacute*: TKeySym = 0x00001ED1
-    XKc_Ocircumflexgrave*: TKeySym = 0x00001ED2
-    XK_ocircumflexgrave*: TKeySym = 0x00001ED3
-    XKc_Ocircumflexhook*: TKeySym = 0x00001ED4
-    XK_ocircumflexhook*: TKeySym = 0x00001ED5
-    XKc_Ocircumflextilde*: TKeySym = 0x00001ED6
-    XK_ocircumflextilde*: TKeySym = 0x00001ED7
-    XKc_Ocircumflexbelowdot*: TKeySym = 0x00001ED8
-    XK_ocircumflexbelowdot*: TKeySym = 0x00001ED9
-    XKc_Ohornacute*: TKeySym = 0x00001EDA
-    XK_ohornacute*: TKeySym = 0x00001EDB
-    XKc_Ohorngrave*: TKeySym = 0x00001EDC
-    XK_ohorngrave*: TKeySym = 0x00001EDD
-    XKc_Ohornhook*: TKeySym = 0x00001EDE
-    XK_ohornhook*: TKeySym = 0x00001EDF
-    XKc_Ohorntilde*: TKeySym = 0x00001EE0
-    XK_ohorntilde*: TKeySym = 0x00001EE1
-    XKc_Ohornbelowdot*: TKeySym = 0x00001EE2
-    XK_ohornbelowdot*: TKeySym = 0x00001EE3
-    XKc_Ubelowdot*: TKeySym = 0x00001EE4
-    XK_ubelowdot*: TKeySym = 0x00001EE5
-    XKc_Uhook*: TKeySym = 0x00001EE6
-    XK_uhook*: TKeySym = 0x00001EE7
-    XKc_Uhornacute*: TKeySym = 0x00001EE8
-    XK_uhornacute*: TKeySym = 0x00001EE9
-    XKc_Uhorngrave*: TKeySym = 0x00001EEA
-    XK_uhorngrave*: TKeySym = 0x00001EEB
-    XKc_Uhornhook*: TKeySym = 0x00001EEC
-    XK_uhornhook*: TKeySym = 0x00001EED
-    XKc_Uhorntilde*: TKeySym = 0x00001EEE
-    XK_uhorntilde*: TKeySym = 0x00001EEF
-    XKc_Uhornbelowdot*: TKeySym = 0x00001EF0
-    XK_uhornbelowdot*: TKeySym = 0x00001EF1
-    XKc_Ybelowdot*: TKeySym = 0x00001EF4
-    XK_ybelowdot*: TKeySym = 0x00001EF5
-    XKc_Yhook*: TKeySym = 0x00001EF6
-    XK_yhook*: TKeySym = 0x00001EF7
-    XKc_Ytilde*: TKeySym = 0x00001EF8
-    XK_ytilde*: TKeySym = 0x00001EF9
-    XKc_Ohorn*: TKeySym = 0x00001EFA     # U+01a0 
-    XK_ohorn*: TKeySym = 0x00001EFB      # U+01a1 
-    XKc_Uhorn*: TKeySym = 0x00001EFC     # U+01af 
-    XK_uhorn*: TKeySym = 0x00001EFD      # U+01b0 
-    XK_combining_tilde*: TKeySym = 0x00001E9F # U+0303 
-    XK_combining_grave*: TKeySym = 0x00001EF2 # U+0300 
-    XK_combining_acute*: TKeySym = 0x00001EF3 # U+0301 
-    XK_combining_hook*: TKeySym = 0x00001EFE # U+0309 
-    XK_combining_belowdot*: TKeySym = 0x00001EFF # U+0323 
-# XK_VIETNAMESE 
-
-when defined(XK_CURRENCY) or true: 
-  const
-    XK_EcuSign*: TKeySym = 0x000020A0
-    XK_ColonSign*: TKeySym = 0x000020A1
-    XK_CruzeiroSign*: TKeySym = 0x000020A2
-    XK_FFrancSign*: TKeySym = 0x000020A3
-    XK_LiraSign*: TKeySym = 0x000020A4
-    XK_MillSign*: TKeySym = 0x000020A5
-    XK_NairaSign*: TKeySym = 0x000020A6
-    XK_PesetaSign*: TKeySym = 0x000020A7
-    XK_RupeeSign*: TKeySym = 0x000020A8
-    XK_WonSign*: TKeySym = 0x000020A9
-    XK_NewSheqelSign*: TKeySym = 0x000020AA
-    XK_DongSign*: TKeySym = 0x000020AB
-    XK_EuroSign*: TKeySym = 0x000020AC
-# implementation
diff --git a/tests/deps/x11-1.0/x.nim b/tests/deps/x11-1.0/x.nim
deleted file mode 100644
index 9d9df48bd..000000000
--- a/tests/deps/x11-1.0/x.nim
+++ /dev/null
@@ -1,400 +0,0 @@
-
-#
-#  Automatically converted by H2Pas 0.99.15 from x.h
-#  The following command line parameters were used:
-#    -p
-#    -T
-#    -S
-#    -d
-#    -c
-#    x.h
-#
-# Pointers to basic pascal types, inserted by h2pas conversion program.
-
-const
-  X_PROTOCOL* = 11
-  X_PROTOCOL_REVISION* = 0
-
-type
-  PXID* = ptr TXID
-  TXID* = culong
-  PMask* = ptr TMask
-  TMask* = culong
-  PPAtom* = ptr PAtom
-  PAtom* = ptr TAtom
-  TAtom* = culong
-  PVisualID* = ptr TVisualID
-  TVisualID* = culong
-  PTime* = ptr TTime
-  TTime* = culong
-  PPWindow* = ptr PWindow
-  PWindow* = ptr TWindow
-  TWindow* = TXID
-  PDrawable* = ptr TDrawable
-  TDrawable* = TXID
-  PFont* = ptr TFont
-  TFont* = TXID
-  PPixmap* = ptr TPixmap
-  TPixmap* = TXID
-  PCursor* = ptr TCursor
-  TCursor* = TXID
-  PColormap* = ptr TColormap
-  TColormap* = TXID
-  PGContext* = ptr TGContext
-  TGContext* = TXID
-  PKeySym* = ptr TKeySym
-  TKeySym* = TXID
-  PKeyCode* = ptr TKeyCode
-  TKeyCode* = cuchar
-
-proc `==`*(a, b: TAtom): bool =
-    return system.`==`(a,b)
-
-const
-  None* = 0
-  ParentRelative* = 1
-  CopyFromParent* = 0
-  PointerWindow* = 0
-  InputFocus* = 1
-  PointerRoot* = 1
-  AnyPropertyType* = 0
-  AnyKey* = 0
-  AnyButton* = 0
-  AllTemporary* = 0
-  CurrentTime* = 0
-  NoSymbol* = 0
-  NoEventMask* = 0
-  KeyPressMask* = 1 shl 0
-  KeyReleaseMask* = 1 shl 1
-  ButtonPressMask* = 1 shl 2
-  ButtonReleaseMask* = 1 shl 3
-  EnterWindowMask* = 1 shl 4
-  LeaveWindowMask* = 1 shl 5
-  PointerMotionMask* = 1 shl 6
-  PointerMotionHintMask* = 1 shl 7
-  Button1MotionMask* = 1 shl 8
-  Button2MotionMask* = 1 shl 9
-  Button3MotionMask* = 1 shl 10
-  Button4MotionMask* = 1 shl 11
-  Button5MotionMask* = 1 shl 12
-  ButtonMotionMask* = 1 shl 13
-  KeymapStateMask* = 1 shl 14
-  ExposureMask* = 1 shl 15
-  VisibilityChangeMask* = 1 shl 16
-  StructureNotifyMask* = 1 shl 17
-  ResizeRedirectMask* = 1 shl 18
-  SubstructureNotifyMask* = 1 shl 19
-  SubstructureRedirectMask* = 1 shl 20
-  FocusChangeMask* = 1 shl 21
-  PropertyChangeMask* = 1 shl 22
-  ColormapChangeMask* = 1 shl 23
-  OwnerGrabButtonMask* = 1 shl 24
-  KeyPress* = 2
-  KeyRelease* = 3
-  ButtonPress* = 4
-  ButtonRelease* = 5
-  MotionNotify* = 6
-  EnterNotify* = 7
-  LeaveNotify* = 8
-  FocusIn* = 9
-  FocusOut* = 10
-  KeymapNotify* = 11
-  Expose* = 12
-  GraphicsExpose* = 13
-  NoExpose* = 14
-  VisibilityNotify* = 15
-  CreateNotify* = 16
-  DestroyNotify* = 17
-  UnmapNotify* = 18
-  MapNotify* = 19
-  MapRequest* = 20
-  ReparentNotify* = 21
-  ConfigureNotify* = 22
-  ConfigureRequest* = 23
-  GravityNotify* = 24
-  ResizeRequest* = 25
-  CirculateNotify* = 26
-  CirculateRequest* = 27
-  PropertyNotify* = 28
-  SelectionClear* = 29
-  SelectionRequest* = 30
-  SelectionNotify* = 31
-  ColormapNotify* = 32
-  ClientMessage* = 33
-  MappingNotify* = 34
-  LASTEvent* = 35
-  ShiftMask* = 1 shl 0
-  LockMask* = 1 shl 1
-  ControlMask* = 1 shl 2
-  Mod1Mask* = 1 shl 3
-  Mod2Mask* = 1 shl 4
-  Mod3Mask* = 1 shl 5
-  Mod4Mask* = 1 shl 6
-  Mod5Mask* = 1 shl 7
-  ShiftMapIndex* = 0
-  LockMapIndex* = 1
-  ControlMapIndex* = 2
-  Mod1MapIndex* = 3
-  Mod2MapIndex* = 4
-  Mod3MapIndex* = 5
-  Mod4MapIndex* = 6
-  Mod5MapIndex* = 7
-  Button1Mask* = 1 shl 8
-  Button2Mask* = 1 shl 9
-  Button3Mask* = 1 shl 10
-  Button4Mask* = 1 shl 11
-  Button5Mask* = 1 shl 12
-  AnyModifier* = 1 shl 15
-  Button1* = 1
-  Button2* = 2
-  Button3* = 3
-  Button4* = 4
-  Button5* = 5
-  NotifyNormal* = 0
-  NotifyGrab* = 1
-  NotifyUngrab* = 2
-  NotifyWhileGrabbed* = 3
-  NotifyHint* = 1
-  NotifyAncestor* = 0
-  NotifyVirtual* = 1
-  NotifyInferior* = 2
-  NotifyNonlinear* = 3
-  NotifyNonlinearVirtual* = 4
-  NotifyPointer* = 5
-  NotifyPointerRoot* = 6
-  NotifyDetailNone* = 7
-  VisibilityUnobscured* = 0
-  VisibilityPartiallyObscured* = 1
-  VisibilityFullyObscured* = 2
-  PlaceOnTop* = 0
-  PlaceOnBottom* = 1
-  FamilyInternet* = 0
-  FamilyDECnet* = 1
-  FamilyChaos* = 2
-  FamilyInternet6* = 6
-  FamilyServerInterpreted* = 5
-  PropertyNewValue* = 0
-  PropertyDelete* = 1
-  ColormapUninstalled* = 0
-  ColormapInstalled* = 1
-  GrabModeSync* = 0
-  GrabModeAsync* = 1
-  GrabSuccess* = 0
-  AlreadyGrabbed* = 1
-  GrabInvalidTime* = 2
-  GrabNotViewable* = 3
-  GrabFrozen* = 4
-  AsyncPointer* = 0
-  SyncPointer* = 1
-  ReplayPointer* = 2
-  AsyncKeyboard* = 3
-  SyncKeyboard* = 4
-  ReplayKeyboard* = 5
-  AsyncBoth* = 6
-  SyncBoth* = 7
-  RevertToNone* = None
-  RevertToPointerRoot* = PointerRoot
-  RevertToParent* = 2
-  Success* = 0
-  BadRequest* = 1
-  BadValue* = 2
-  BadWindow* = 3
-  BadPixmap* = 4
-  BadAtom* = 5
-  BadCursor* = 6
-  BadFont* = 7
-  BadMatch* = 8
-  BadDrawable* = 9
-  BadAccess* = 10
-  BadAlloc* = 11
-  BadColor* = 12
-  BadGC* = 13
-  BadIDChoice* = 14
-  BadName* = 15
-  BadLength* = 16
-  BadImplementation* = 17
-  FirstExtensionError* = 128
-  LastExtensionError* = 255
-  InputOutput* = 1
-  InputOnly* = 2
-  CWBackPixmap* = 1 shl 0
-  CWBackPixel* = 1 shl 1
-  CWBorderPixmap* = 1 shl 2
-  CWBorderPixel* = 1 shl 3
-  CWBitGravity* = 1 shl 4
-  CWWinGravity* = 1 shl 5
-  CWBackingStore* = 1 shl 6
-  CWBackingPlanes* = 1 shl 7
-  CWBackingPixel* = 1 shl 8
-  CWOverrideRedirect* = 1 shl 9
-  CWSaveUnder* = 1 shl 10
-  CWEventMask* = 1 shl 11
-  CWDontPropagate* = 1 shl 12
-  CWColormap* = 1 shl 13
-  CWCursor* = 1 shl 14
-  CWX* = 1 shl 0
-  CWY* = 1 shl 1
-  CWWidth* = 1 shl 2
-  CWHeight* = 1 shl 3
-  CWBorderWidth* = 1 shl 4
-  CWSibling* = 1 shl 5
-  CWStackMode* = 1 shl 6
-  ForgetGravity* = 0
-  NorthWestGravity* = 1
-  NorthGravity* = 2
-  NorthEastGravity* = 3
-  WestGravity* = 4
-  CenterGravity* = 5
-  EastGravity* = 6
-  SouthWestGravity* = 7
-  SouthGravity* = 8
-  SouthEastGravity* = 9
-  StaticGravity* = 10
-  UnmapGravity* = 0
-  NotUseful* = 0
-  WhenMapped* = 1
-  Always* = 2
-  IsUnmapped* = 0
-  IsUnviewable* = 1
-  IsViewable* = 2
-  SetModeInsert* = 0
-  SetModeDelete* = 1
-  DestroyAll* = 0
-  RetainPermanent* = 1
-  RetainTemporary* = 2
-  Above* = 0
-  Below* = 1
-  TopIf* = 2
-  BottomIf* = 3
-  Opposite* = 4
-  RaiseLowest* = 0
-  LowerHighest* = 1
-  PropModeReplace* = 0
-  PropModePrepend* = 1
-  PropModeAppend* = 2
-  GXclear* = 0x00000000
-  GXand* = 0x00000001
-  GXandReverse* = 0x00000002
-  GXcopy* = 0x00000003
-  GXandInverted* = 0x00000004
-  GXnoop* = 0x00000005
-  GXxor* = 0x00000006
-  GXor* = 0x00000007
-  GXnor* = 0x00000008
-  GXequiv* = 0x00000009
-  GXinvert* = 0x0000000A
-  GXorReverse* = 0x0000000B
-  GXcopyInverted* = 0x0000000C
-  GXorInverted* = 0x0000000D
-  GXnand* = 0x0000000E
-  GXset* = 0x0000000F
-  LineSolid* = 0
-  LineOnOffDash* = 1
-  LineDoubleDash* = 2
-  CapNotLast* = 0
-  CapButt* = 1
-  CapRound* = 2
-  CapProjecting* = 3
-  JoinMiter* = 0
-  JoinRound* = 1
-  JoinBevel* = 2
-  FillSolid* = 0
-  FillTiled* = 1
-  FillStippled* = 2
-  FillOpaqueStippled* = 3
-  EvenOddRule* = 0
-  WindingRule* = 1
-  ClipByChildren* = 0
-  IncludeInferiors* = 1
-  Unsorted* = 0
-  YSorted* = 1
-  YXSorted* = 2
-  YXBanded* = 3
-  CoordModeOrigin* = 0
-  CoordModePrevious* = 1
-  Complex* = 0
-  Nonconvex* = 1
-  Convex* = 2
-  ArcChord* = 0
-  ArcPieSlice* = 1
-  GCFunction* = 1 shl 0
-  GCPlaneMask* = 1 shl 1
-  GCForeground* = 1 shl 2
-  GCBackground* = 1 shl 3
-  GCLineWidth* = 1 shl 4
-  GCLineStyle* = 1 shl 5
-  GCCapStyle* = 1 shl 6
-  GCJoinStyle* = 1 shl 7
-  GCFillStyle* = 1 shl 8
-  GCFillRule* = 1 shl 9
-  GCTile* = 1 shl 10
-  GCStipple* = 1 shl 11
-  GCTileStipXOrigin* = 1 shl 12
-  GCTileStipYOrigin* = 1 shl 13
-  GCFont* = 1 shl 14
-  GCSubwindowMode* = 1 shl 15
-  GCGraphicsExposures* = 1 shl 16
-  GCClipXOrigin* = 1 shl 17
-  GCClipYOrigin* = 1 shl 18
-  GCClipMask* = 1 shl 19
-  GCDashOffset* = 1 shl 20
-  GCDashList* = 1 shl 21
-  GCArcMode* = 1 shl 22
-  GCLastBit* = 22
-  FontLeftToRight* = 0
-  FontRightToLeft* = 1
-  FontChange* = 255
-  XYBitmap* = 0
-  XYPixmap* = 1
-  ZPixmap* = 2
-  AllocNone* = 0
-  AllocAll* = 1
-  DoRed* = 1 shl 0
-  DoGreen* = 1 shl 1
-  DoBlue* = 1 shl 2
-  CursorShape* = 0
-  TileShape* = 1
-  StippleShape* = 2
-  AutoRepeatModeOff* = 0
-  AutoRepeatModeOn* = 1
-  AutoRepeatModeDefault* = 2
-  LedModeOff* = 0
-  LedModeOn* = 1
-  KBKeyClickPercent* = 1 shl 0
-  KBBellPercent* = 1 shl 1
-  KBBellPitch* = 1 shl 2
-  KBBellDuration* = 1 shl 3
-  KBLed* = 1 shl 4
-  KBLedMode* = 1 shl 5
-  KBKey* = 1 shl 6
-  KBAutoRepeatMode* = 1 shl 7
-  MappingSuccess* = 0
-  MappingBusy* = 1
-  MappingFailed* = 2
-  MappingModifier* = 0
-  MappingKeyboard* = 1
-  MappingPointer* = 2
-  DontPreferBlanking* = 0
-  PreferBlanking* = 1
-  DefaultBlanking* = 2
-  DisableScreenSaver* = 0
-  DisableScreenInterval* = 0
-  DontAllowExposures* = 0
-  AllowExposures* = 1
-  DefaultExposures* = 2
-  ScreenSaverReset* = 0
-  ScreenSaverActive* = 1
-  HostInsert* = 0
-  HostDelete* = 1
-  EnableAccess* = 1
-  DisableAccess* = 0
-  StaticGray* = 0
-  GrayScale* = 1
-  StaticColor* = 2
-  PseudoColor* = 3
-  TrueColor* = 4
-  DirectColor* = 5
-  LSBFirst* = 0
-  MSBFirst* = 1
-
-# implementation
diff --git a/tests/deps/x11-1.0/x11.nimble b/tests/deps/x11-1.0/x11.nimble
deleted file mode 100644
index 2f4385100..000000000
--- a/tests/deps/x11-1.0/x11.nimble
+++ /dev/null
@@ -1,11 +0,0 @@
-[Package]
-name: "x11"
-version: "1.0"
-author: "Andreas Rumpf"
-description: "Wrapper for X11"
-license: "MIT"
-
-srcDir: "src"
-
-[Deps]
-requires: "nimrod > 0.9.2"
diff --git a/tests/deps/x11-1.0/x11pragma.nim b/tests/deps/x11-1.0/x11pragma.nim
deleted file mode 100644
index b4c876cf0..000000000
--- a/tests/deps/x11-1.0/x11pragma.nim
+++ /dev/null
@@ -1,20 +0,0 @@
-# included from xlib bindings
-
-
-when defined(use_pkg_config) or defined(use_pkg_config_static):
-    {.pragma: libx11, cdecl, importc.}
-    {.pragma: libx11c, cdecl.}
-    when defined(use_pkg_config_static):
-        {.passl: gorge("pkg-config x11 --static --libs").}
-    else:
-        {.passl: gorge("pkg-config x11 --libs").}
-else:
-    when defined(macosx):
-        const
-          libX11* = "libX11.dylib"
-    else:
-        const
-          libX11* = "libX11.so(|.6)"
-
-    {.pragma: libx11, cdecl, dynlib: libX11, importc.}
-    {.pragma: libx11c, cdecl, dynlib: libX11.}
diff --git a/tests/deps/x11-1.0/xatom.nim b/tests/deps/x11-1.0/xatom.nim
deleted file mode 100644
index b2e1dca91..000000000
--- a/tests/deps/x11-1.0/xatom.nim
+++ /dev/null
@@ -1,81 +0,0 @@
-#
-# THIS IS A GENERATED FILE
-#
-# Do not change!  Changing this file implies a protocol change!
-#
-
-import  
-  X
-
-const 
-  XA_PRIMARY* = TAtom(1)
-  XA_SECONDARY* = TAtom(2)
-  XA_ARC* = TAtom(3)
-  XA_ATOM* = TAtom(4)
-  XA_BITMAP* = TAtom(5)
-  XA_CARDINAL* = TAtom(6)
-  XA_COLORMAP* = TAtom(7)
-  XA_CURSOR* = TAtom(8)
-  XA_CUT_BUFFER0* = TAtom(9)
-  XA_CUT_BUFFER1* = TAtom(10)
-  XA_CUT_BUFFER2* = TAtom(11)
-  XA_CUT_BUFFER3* = TAtom(12)
-  XA_CUT_BUFFER4* = TAtom(13)
-  XA_CUT_BUFFER5* = TAtom(14)
-  XA_CUT_BUFFER6* = TAtom(15)
-  XA_CUT_BUFFER7* = TAtom(16)
-  XA_DRAWABLE* = TAtom(17)
-  XA_FONT* = TAtom(18)
-  XA_INTEGER* = TAtom(19)
-  XA_PIXMAP* = TAtom(20)
-  XA_POINT* = TAtom(21)
-  XA_RECTANGLE* = TAtom(22)
-  XA_RESOURCE_MANAGER* = TAtom(23)
-  XA_RGB_COLOR_MAP* = TAtom(24)
-  XA_RGB_BEST_MAP* = TAtom(25)
-  XA_RGB_BLUE_MAP* = TAtom(26)
-  XA_RGB_DEFAULT_MAP* = TAtom(27)
-  XA_RGB_GRAY_MAP* = TAtom(28)
-  XA_RGB_GREEN_MAP* = TAtom(29)
-  XA_RGB_RED_MAP* = TAtom(30)
-  XA_STRING* = TAtom(31)
-  XA_VISUALID* = TAtom(32)
-  XA_WINDOW* = TAtom(33)
-  XA_WM_COMMAND* = TAtom(34)
-  XA_WM_HINTS* = TAtom(35)
-  XA_WM_CLIENT_MACHINE* = TAtom(36)
-  XA_WM_ICON_NAME* = TAtom(37)
-  XA_WM_ICON_SIZE* = TAtom(38)
-  XA_WM_NAME* = TAtom(39)
-  XA_WM_NORMAL_HINTS* = TAtom(40)
-  XA_WM_SIZE_HINTS* = TAtom(41)
-  XA_WM_ZOOM_HINTS* = TAtom(42)
-  XA_MIN_SPACE* = TAtom(43)
-  XA_NORM_SPACE* = TAtom(44)
-  XA_MAX_SPACE* = TAtom(45)
-  XA_END_SPACE* = TAtom(46)
-  XA_SUPERSCRIPT_X* = TAtom(47)
-  XA_SUPERSCRIPT_Y* = TAtom(48)
-  XA_SUBSCRIPT_X* = TAtom(49)
-  XA_SUBSCRIPT_Y* = TAtom(50)
-  XA_UNDERLINE_POSITION* = TAtom(51)
-  XA_UNDERLINE_THICKNESS* = TAtom(52)
-  XA_STRIKEOUT_ASCENT* = TAtom(53)
-  XA_STRIKEOUT_DESCENT* = TAtom(54)
-  XA_ITALIC_ANGLE* = TAtom(55)
-  XA_X_HEIGHT* = TAtom(56)
-  XA_QUAD_WIDTH* = TAtom(57)
-  XA_WEIGHT* = TAtom(58)
-  XA_POINT_SIZE* = TAtom(59)
-  XA_RESOLUTION* = TAtom(60)
-  XA_COPYRIGHT* = TAtom(61)
-  XA_NOTICE* = TAtom(62)
-  XA_FONT_NAME* = TAtom(63)
-  XA_FAMILY_NAME* = TAtom(64)
-  XA_FULL_NAME* = TAtom(65)
-  XA_CAP_HEIGHT* = TAtom(66)
-  XA_WM_CLASS* = TAtom(67)
-  XA_WM_TRANSIENT_FOR* = TAtom(68)
-  XA_LAST_PREDEFINED* = TAtom(68)
-
-# implementation
diff --git a/tests/deps/x11-1.0/xcms.nim b/tests/deps/x11-1.0/xcms.nim
deleted file mode 100644
index 659676c45..000000000
--- a/tests/deps/x11-1.0/xcms.nim
+++ /dev/null
@@ -1,389 +0,0 @@
-
-import 
-  x, xlib
-
-#const 
-#  libX11* = "X11" 
-
-#
-#  Automatically converted by H2Pas 0.99.15 from xcms.h
-#  The following command line parameters were used:
-#    -p
-#    -T
-#    -S
-#    -d
-#    -c
-#    xcms.h
-#
-
-const 
-  XcmsFailure* = 0
-  XcmsSuccess* = 1
-  XcmsSuccessWithCompression* = 2
-
-type 
-  PXcmsColorFormat* = ptr TXcmsColorFormat
-  TXcmsColorFormat* = int32
-
-proc XcmsUndefinedFormat*(): TXcmsColorFormat
-proc XcmsCIEXYZFormat*(): TXcmsColorFormat
-proc XcmsCIEuvYFormat*(): TXcmsColorFormat
-proc XcmsCIExyYFormat*(): TXcmsColorFormat
-proc XcmsCIELabFormat*(): TXcmsColorFormat
-proc XcmsCIELuvFormat*(): TXcmsColorFormat
-proc XcmsTekHVCFormat*(): TXcmsColorFormat
-proc XcmsRGBFormat*(): TXcmsColorFormat
-proc XcmsRGBiFormat*(): TXcmsColorFormat
-const 
-  XcmsInitNone* = 0x00000000
-  XcmsInitSuccess* = 0x00000001
-  XcmsInitFailure* = 0x000000FF
-
-type 
-  PXcmsFloat* = ptr TXcmsFloat
-  TXcmsFloat* = float64
-  PXcmsRGB* = ptr TXcmsRGB
-  TXcmsRGB*{.final.} = object 
-    red*: int16
-    green*: int16
-    blue*: int16
-
-  PXcmsRGBi* = ptr TXcmsRGBi
-  TXcmsRGBi*{.final.} = object 
-    red*: TXcmsFloat
-    green*: TXcmsFloat
-    blue*: TXcmsFloat
-
-  PXcmsCIEXYZ* = ptr TXcmsCIEXYZ
-  TXcmsCIEXYZ*{.final.} = object 
-    X*: TXcmsFloat
-    Y*: TXcmsFloat
-    Z*: TXcmsFloat
-
-  PXcmsCIEuvY* = ptr TXcmsCIEuvY
-  TXcmsCIEuvY*{.final.} = object 
-    u_prime*: TXcmsFloat
-    v_prime*: TXcmsFloat
-    Y*: TXcmsFloat
-
-  PXcmsCIExyY* = ptr TXcmsCIExyY
-  TXcmsCIExyY*{.final.} = object 
-    x*: TXcmsFloat
-    y*: TXcmsFloat
-    theY*: TXcmsFloat
-
-  PXcmsCIELab* = ptr TXcmsCIELab
-  TXcmsCIELab*{.final.} = object 
-    L_star*: TXcmsFloat
-    a_star*: TXcmsFloat
-    b_star*: TXcmsFloat
-
-  PXcmsCIELuv* = ptr TXcmsCIELuv
-  TXcmsCIELuv*{.final.} = object 
-    L_star*: TXcmsFloat
-    u_star*: TXcmsFloat
-    v_star*: TXcmsFloat
-
-  PXcmsTekHVC* = ptr TXcmsTekHVC
-  TXcmsTekHVC*{.final.} = object 
-    H*: TXcmsFloat
-    V*: TXcmsFloat
-    C*: TXcmsFloat
-
-  PXcmsPad* = ptr TXcmsPad
-  TXcmsPad*{.final.} = object 
-    pad0*: TXcmsFloat
-    pad1*: TXcmsFloat
-    pad2*: TXcmsFloat
-    pad3*: TXcmsFloat
-
-  PXcmsColor* = ptr TXcmsColor
-  TXcmsColor*{.final.} = object  # spec : record
-                                 #            case longint of
-                                 #               0 : ( RGB : TXcmsRGB );
-                                 #               1 : ( RGBi : TXcmsRGBi );
-                                 #               2 : ( CIEXYZ : TXcmsCIEXYZ );
-                                 #               3 : ( CIEuvY : TXcmsCIEuvY );
-                                 #               4 : ( CIExyY : TXcmsCIExyY );
-                                 #               5 : ( CIELab : TXcmsCIELab );
-                                 #               6 : ( CIELuv : TXcmsCIELuv );
-                                 #               7 : ( TekHVC : TXcmsTekHVC );
-                                 #               8 : ( Pad : TXcmsPad ); 
-                                 #            end; 
-    pad*: TXcmsPad
-    pixel*: int32
-    format*: TXcmsColorFormat
-
-  PXcmsPerScrnInfo* = ptr TXcmsPerScrnInfo
-  TXcmsPerScrnInfo*{.final.} = object 
-    screenWhitePt*: TXcmsColor
-    functionSet*: TXPointer
-    screenData*: TXPointer
-    state*: int8
-    pad*: array[0..2, char]
-
-  PXcmsCCC* = ptr TXcmsCCC
-  TXcmsCompressionProc* = proc (para1: PXcmsCCC, para2: PXcmsColor, 
-                                para3: int32, para4: int32, para5: PBool): TStatus{.
-      cdecl.}
-  TXcmsWhiteAdjustProc* = proc (para1: PXcmsCCC, para2: PXcmsColor, 
-                                para3: PXcmsColor, para4: TXcmsColorFormat, 
-                                para5: PXcmsColor, para6: int32, para7: PBool): TStatus{.
-      cdecl.}
-  TXcmsCCC*{.final.} = object 
-    dpy*: PDisplay
-    screenNumber*: int32
-    visual*: PVisual
-    clientWhitePt*: TXcmsColor
-    gamutCompProc*: TXcmsCompressionProc
-    gamutCompClientData*: TXPointer
-    whitePtAdjProc*: TXcmsWhiteAdjustProc
-    whitePtAdjClientData*: TXPointer
-    pPerScrnInfo*: PXcmsPerScrnInfo
-
-  TXcmsCCCRec* = TXcmsCCC
-  PXcmsCCCRec* = ptr TXcmsCCCRec
-  TXcmsScreenInitProc* = proc (para1: PDisplay, para2: int32, 
-                               para3: PXcmsPerScrnInfo): TStatus{.cdecl.}
-  TXcmsScreenFreeProc* = proc (para1: TXPointer){.cdecl.}
-  TXcmsConversionProc* = proc (){.cdecl.}
-  PXcmsFuncListPtr* = ptr TXcmsFuncListPtr
-  TXcmsFuncListPtr* = TXcmsConversionProc
-  TXcmsParseStringProc* = proc (para1: cstring, para2: PXcmsColor): int32{.cdecl.}
-  PXcmsColorSpace* = ptr TXcmsColorSpace
-  TXcmsColorSpace*{.final.} = object 
-    prefix*: cstring
-    id*: TXcmsColorFormat
-    parseString*: TXcmsParseStringProc
-    to_CIEXYZ*: TXcmsFuncListPtr
-    from_CIEXYZ*: TXcmsFuncListPtr
-    inverse_flag*: int32
-
-  PXcmsFunctionSet* = ptr TXcmsFunctionSet
-  TXcmsFunctionSet*{.final.} = object  # error
-                                       #extern Status XcmsAddColorSpace (
-                                       #in declaration at line 323 
-    DDColorSpaces*: ptr PXcmsColorSpace
-    screenInitProc*: TXcmsScreenInitProc
-    screenFreeProc*: TXcmsScreenFreeProc
-
-
-proc XcmsAddFunctionSet*(para1: PXcmsFunctionSet): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsAllocColor*(para1: PDisplay, para2: TColormap, para3: PXcmsColor, 
-                     para4: TXcmsColorFormat): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsAllocNamedColor*(para1: PDisplay, para2: TColormap, para3: cstring, 
-                          para4: PXcmsColor, para5: PXcmsColor, 
-                          para6: TXcmsColorFormat): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCCCOfColormap*(para1: PDisplay, para2: TColormap): TXcmsCCC{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCIELabClipab*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                       para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCIELabClipL*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                      para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCIELabClipLab*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                        para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCIELabQueryMaxC*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsCIELabQueryMaxL*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsCIELabQueryMaxLC*(para1: TXcmsCCC, para2: TXcmsFloat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsCIELabQueryMinL*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsCIELabToCIEXYZ*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIELabWhiteShiftColors*(para1: TXcmsCCC, para2: PXcmsColor, 
-                                 para3: PXcmsColor, para4: TXcmsColorFormat, 
-                                 para5: PXcmsColor, para6: int32, para7: PBool): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsCIELuvClipL*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                      para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCIELuvClipLuv*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                        para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCIELuvClipuv*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                       para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCIELuvQueryMaxC*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsCIELuvQueryMaxL*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsCIELuvQueryMaxLC*(para1: TXcmsCCC, para2: TXcmsFloat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsCIELuvQueryMinL*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsCIELuvToCIEuvY*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIELuvWhiteShiftColors*(para1: TXcmsCCC, para2: PXcmsColor, 
-                                 para3: PXcmsColor, para4: TXcmsColorFormat, 
-                                 para5: PXcmsColor, para6: int32, para7: PBool): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsCIEXYZToCIELab*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIEXYZToCIEuvY*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIEXYZToCIExyY*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIEXYZToRGBi*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                       para4: PBool): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIEuvYToCIELuv*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIEuvYToCIEXYZ*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIEuvYToTekHVC*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsCIExyYToCIEXYZ*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsClientWhitePointOfCCC*(para1: TXcmsCCC): PXcmsColor{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsConvertColors*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                        para4: TXcmsColorFormat, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsCreateCCC*(para1: PDisplay, para2: int32, para3: PVisual, 
-                    para4: PXcmsColor, para5: TXcmsCompressionProc, 
-                    para6: TXPointer, para7: TXcmsWhiteAdjustProc, 
-                    para8: TXPointer): TXcmsCCC{.cdecl, dynlib: libX11, importc.}
-proc XcmsDefaultCCC*(para1: PDisplay, para2: int32): TXcmsCCC{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsDisplayOfCCC*(para1: TXcmsCCC): PDisplay{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsFormatOfPrefix*(para1: cstring): TXcmsColorFormat{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsFreeCCC*(para1: TXcmsCCC){.cdecl, dynlib: libX11, importc.}
-proc XcmsLookupColor*(para1: PDisplay, para2: TColormap, para3: cstring, 
-                      para4: PXcmsColor, para5: PXcmsColor, 
-                      para6: TXcmsColorFormat): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsPrefixOfFormat*(para1: TXcmsColorFormat): cstring{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsQueryBlack*(para1: TXcmsCCC, para2: TXcmsColorFormat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsQueryBlue*(para1: TXcmsCCC, para2: TXcmsColorFormat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsQueryColor*(para1: PDisplay, para2: TColormap, para3: PXcmsColor, 
-                     para4: TXcmsColorFormat): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsQueryColors*(para1: PDisplay, para2: TColormap, para3: PXcmsColor, 
-                      para4: int32, para5: TXcmsColorFormat): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsQueryGreen*(para1: TXcmsCCC, para2: TXcmsColorFormat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsQueryRed*(para1: TXcmsCCC, para2: TXcmsColorFormat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsQueryWhite*(para1: TXcmsCCC, para2: TXcmsColorFormat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsRGBiToCIEXYZ*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                       para4: PBool): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsRGBiToRGB*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                    para4: PBool): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsRGBToRGBi*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                    para4: PBool): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsScreenNumberOfCCC*(para1: TXcmsCCC): int32{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsScreenWhitePointOfCCC*(para1: TXcmsCCC): PXcmsColor{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsSetCCCOfColormap*(para1: PDisplay, para2: TColormap, para3: TXcmsCCC): TXcmsCCC{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsSetCompressionProc*(para1: TXcmsCCC, para2: TXcmsCompressionProc, 
-                             para3: TXPointer): TXcmsCompressionProc{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsSetWhiteAdjustProc*(para1: TXcmsCCC, para2: TXcmsWhiteAdjustProc, 
-                             para3: TXPointer): TXcmsWhiteAdjustProc{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsSetWhitePoint*(para1: TXcmsCCC, para2: PXcmsColor): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsStoreColor*(para1: PDisplay, para2: TColormap, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsStoreColors*(para1: PDisplay, para2: TColormap, para3: PXcmsColor, 
-                      para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsTekHVCClipC*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                      para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsTekHVCClipV*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                      para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsTekHVCClipVC*(para1: TXcmsCCC, para2: PXcmsColor, para3: int32, 
-                       para4: int32, para5: PBool): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XcmsTekHVCQueryMaxC*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsTekHVCQueryMaxV*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsTekHVCQueryMaxVC*(para1: TXcmsCCC, para2: TXcmsFloat, para3: PXcmsColor): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsTekHVCQueryMaxVSamples*(para1: TXcmsCCC, para2: TXcmsFloat, 
-                                 para3: PXcmsColor, para4: int32): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsTekHVCQueryMinV*(para1: TXcmsCCC, para2: TXcmsFloat, para3: TXcmsFloat, 
-                          para4: PXcmsColor): TStatus{.cdecl, dynlib: libX11, 
-    importc.}
-proc XcmsTekHVCToCIEuvY*(para1: TXcmsCCC, para2: PXcmsColor, para3: PXcmsColor, 
-                         para4: int32): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XcmsTekHVCWhiteShiftColors*(para1: TXcmsCCC, para2: PXcmsColor, 
-                                 para3: PXcmsColor, para4: TXcmsColorFormat, 
-                                 para5: PXcmsColor, para6: int32, para7: PBool): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XcmsVisualOfCCC*(para1: TXcmsCCC): PVisual{.cdecl, dynlib: libX11, importc.}
-# implementation
-
-proc XcmsUndefinedFormat(): TXcmsColorFormat = 
-  result = 0x00000000'i32
-
-proc XcmsCIEXYZFormat(): TXcmsColorFormat = 
-  result = 0x00000001'i32
-
-proc XcmsCIEuvYFormat(): TXcmsColorFormat = 
-  result = 0x00000002'i32
-
-proc XcmsCIExyYFormat(): TXcmsColorFormat = 
-  result = 0x00000003'i32
-
-proc XcmsCIELabFormat(): TXcmsColorFormat = 
-  result = 0x00000004'i32
-
-proc XcmsCIELuvFormat(): TXcmsColorFormat = 
-  result = 0x00000005'i32
-
-proc XcmsTekHVCFormat(): TXcmsColorFormat = 
-  result = 0x00000006'i32
-
-proc XcmsRGBFormat(): TXcmsColorFormat = 
-  result = 0x80000000'i32
-
-proc XcmsRGBiFormat(): TXcmsColorFormat = 
-  result = 0x80000001'i32
-
-#when defined(MACROS): 
-proc DisplayOfCCC(ccc: TXcmsCCC): PDisplay = 
-  result = ccc.dpy
-
-proc ScreenNumberOfCCC(ccc: TXcmsCCC): int32 = 
-  result = ccc.screenNumber
-
-proc VisualOfCCC(ccc: TXcmsCCC): PVisual = 
-  result = ccc.visual
-
-proc ClientWhitePointOfCCC(ccc: var TXcmsCCC): ptr TXcmsColor = 
-  result = addr(ccc.clientWhitePt)
-
-proc ScreenWhitePointOfCCC(ccc: var TXcmsCCC): ptr TXcmsColor = 
-  result = addr(ccc.pPerScrnInfo.screenWhitePt)
-
-proc FunctionSetOfCCC(ccc: TXcmsCCC): TXpointer =
-  result = ccc.pPerScrnInfo.functionSet
diff --git a/tests/deps/x11-1.0/xf86dga.nim b/tests/deps/x11-1.0/xf86dga.nim
deleted file mode 100644
index 65e26df22..000000000
--- a/tests/deps/x11-1.0/xf86dga.nim
+++ /dev/null
@@ -1,235 +0,0 @@
-#
-#   Copyright (c) 1999  XFree86 Inc
-#
-# $XFree86: xc/include/extensions/xf86dga.h,v 3.20 1999/10/13 04:20:48 dawes Exp $
-
-import
-  x, xlib
-
-const
-  libXxf86dga* = "libXxf86dga.so"
-
-#type
-#  cfloat* = float32
-
-# $XFree86: xc/include/extensions/xf86dga1.h,v 1.2 1999/04/17 07:05:41 dawes Exp $
-#
-#
-#Copyright (c) 1995  Jon Tombs
-#Copyright (c) 1995  XFree86 Inc
-#
-#
-#************************************************************************
-#
-#   THIS IS THE OLD DGA API AND IS OBSOLETE.  PLEASE DO NOT USE IT ANYMORE
-#
-#************************************************************************
-
-type
-  PPcchar* = ptr ptr cstring
-
-const
-  X_XF86DGAQueryVersion* = 0
-  X_XF86DGAGetVideoLL* = 1
-  X_XF86DGADirectVideo* = 2
-  X_XF86DGAGetViewPortSize* = 3
-  X_XF86DGASetViewPort* = 4
-  X_XF86DGAGetVidPage* = 5
-  X_XF86DGASetVidPage* = 6
-  X_XF86DGAInstallColormap* = 7
-  X_XF86DGAQueryDirectVideo* = 8
-  X_XF86DGAViewPortChanged* = 9
-  XF86DGADirectPresent* = 0x00000001
-  XF86DGADirectGraphics* = 0x00000002
-  XF86DGADirectMouse* = 0x00000004
-  XF86DGADirectKeyb* = 0x00000008
-  XF86DGAHasColormap* = 0x00000100
-  XF86DGADirectColormap* = 0x00000200
-
-proc XF86DGAQueryVersion*(dpy: PDisplay, majorVersion: Pcint,
-                          minorVersion: Pcint): TBool{.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XF86DGAQueryExtension*(dpy: PDisplay, event_base: Pcint, error_base: Pcint): TBool{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAGetVideoLL*(dpy: PDisplay, screen: cint, base_addr: Pcint,
-                        width: Pcint, bank_size: Pcint, ram_size: Pcint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAGetVideo*(dpy: PDisplay, screen: cint, base_addr: PPcchar,
-                      width: Pcint, bank_size: Pcint, ram_size: Pcint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGADirectVideo*(dpy: PDisplay, screen: cint, enable: cint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGADirectVideoLL*(dpy: PDisplay, screen: cint, enable: cint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAGetViewPortSize*(dpy: PDisplay, screen: cint, width: Pcint,
-                             height: Pcint): TStatus{.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XF86DGASetViewPort*(dpy: PDisplay, screen: cint, x: cint, y: cint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAGetVidPage*(dpy: PDisplay, screen: cint, vid_page: Pcint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGASetVidPage*(dpy: PDisplay, screen: cint, vid_page: cint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAInstallColormap*(dpy: PDisplay, screen: cint, Colormap: TColormap): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAForkApp*(screen: cint): cint{.cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAQueryDirectVideo*(dpy: PDisplay, screen: cint, flags: Pcint): TStatus{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XF86DGAViewPortChanged*(dpy: PDisplay, screen: cint, n: cint): TBool{.
-    cdecl, dynlib: libXxf86dga, importc.}
-const
-  X_XDGAQueryVersion* = 0     # 1 through 9 are in xf86dga1.pp
-                              # 10 and 11 are reserved to avoid conflicts with rogue DGA extensions
-  X_XDGAQueryModes* = 12
-  X_XDGASetMode* = 13
-  X_XDGASetViewport* = 14
-  X_XDGAInstallColormap* = 15
-  X_XDGASelectInput* = 16
-  X_XDGAFillRectangle* = 17
-  X_XDGACopyArea* = 18
-  X_XDGACopyTransparentArea* = 19
-  X_XDGAGetViewportStatus* = 20
-  X_XDGASync* = 21
-  X_XDGAOpenFramebuffer* = 22
-  X_XDGACloseFramebuffer* = 23
-  X_XDGASetClientVersion* = 24
-  X_XDGAChangePixmapMode* = 25
-  X_XDGACreateColormap* = 26
-  XDGAConcurrentAccess* = 0x00000001
-  XDGASolidFillRect* = 0x00000002
-  XDGABlitRect* = 0x00000004
-  XDGABlitTransRect* = 0x00000008
-  XDGAPixmap* = 0x00000010
-  XDGAInterlaced* = 0x00010000
-  XDGADoublescan* = 0x00020000
-  XDGAFlipImmediate* = 0x00000001
-  XDGAFlipRetrace* = 0x00000002
-  XDGANeedRoot* = 0x00000001
-  XF86DGANumberEvents* = 7
-  XDGAPixmapModeLarge* = 0
-  XDGAPixmapModeSmall* = 1
-  XF86DGAClientNotLocal* = 0
-  XF86DGANoDirectVideoMode* = 1
-  XF86DGAScreenNotActive* = 2
-  XF86DGADirectNotActivated* = 3
-  XF86DGAOperationNotSupported* = 4
-  XF86DGANumberErrors* = (XF86DGAOperationNotSupported + 1)
-
-type
-  PXDGAMode* = ptr TXDGAMode
-  TXDGAMode*{.final.} = object
-    num*: cint                # A unique identifier for the mode (num > 0)
-    name*: cstring            # name of mode given in the XF86Config
-    verticalRefresh*: cfloat
-    flags*: cint              # DGA_CONCURRENT_ACCESS, etc...
-    imageWidth*: cint         # linear accessible portion (pixels)
-    imageHeight*: cint
-    pixmapWidth*: cint        # Xlib accessible portion (pixels)
-    pixmapHeight*: cint       # both fields ignored if no concurrent access
-    bytesPerScanline*: cint
-    byteOrder*: cint          # MSBFirst, LSBFirst
-    depth*: cint
-    bitsPerPixel*: cint
-    redMask*: culong
-    greenMask*: culong
-    blueMask*: culong
-    visualClass*: cshort
-    viewportWidth*: cint
-    viewportHeight*: cint
-    xViewportStep*: cint      # viewport position granularity
-    yViewportStep*: cint
-    maxViewportX*: cint       # max viewport origin
-    maxViewportY*: cint
-    viewportFlags*: cint      # types of page flipping possible
-    reserved1*: cint
-    reserved2*: cint
-
-  PXDGADevice* = ptr TXDGADevice
-  TXDGADevice*{.final.} = object
-    mode*: TXDGAMode
-    data*: Pcuchar
-    pixmap*: TPixmap
-
-  PXDGAButtonEvent* = ptr TXDGAButtonEvent
-  TXDGAButtonEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    display*: PDisplay
-    screen*: cint
-    time*: TTime
-    state*: cuint
-    button*: cuint
-
-  PXDGAKeyEvent* = ptr TXDGAKeyEvent
-  TXDGAKeyEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    display*: PDisplay
-    screen*: cint
-    time*: TTime
-    state*: cuint
-    keycode*: cuint
-
-  PXDGAMotionEvent* = ptr TXDGAMotionEvent
-  TXDGAMotionEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    display*: PDisplay
-    screen*: cint
-    time*: TTime
-    state*: cuint
-    dx*: cint
-    dy*: cint
-
-  PXDGAEvent* = ptr TXDGAEvent
-  TXDGAEvent*{.final.} = object
-    pad*: array[0..23, clong] # sorry you have to cast if you want access
-                              #Case LongInt Of
-                              #      0 : (_type : cint);
-                              #      1 : (xbutton : TXDGAButtonEvent);
-                              #      2 : (xkey : TXDGAKeyEvent);
-                              #      3 : (xmotion : TXDGAMotionEvent);
-                              #      4 : (pad : Array[0..23] Of clong);
-
-
-proc XDGAQueryExtension*(dpy: PDisplay, eventBase: Pcint, erroBase: Pcint): TBool{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XDGAQueryVersion*(dpy: PDisplay, majorVersion: Pcint, minorVersion: Pcint): TBool{.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XDGAQueryModes*(dpy: PDisplay, screen: cint, num: Pcint): PXDGAMode{.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGASetMode*(dpy: PDisplay, screen: cint, mode: cint): PXDGADevice{.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGAOpenFramebuffer*(dpy: PDisplay, screen: cint): TBool{.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGACloseFramebuffer*(dpy: PDisplay, screen: cint){.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGASetViewport*(dpy: PDisplay, screen: cint, x: cint, y: cint, flags: cint){.
-    cdecl, dynlib: libXxf86dga, importc.}
-proc XDGAInstallColormap*(dpy: PDisplay, screen: cint, cmap: TColormap){.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGACreateColormap*(dpy: PDisplay, screen: cint, device: PXDGADevice,
-                         alloc: cint): TColormap{.cdecl, dynlib: libXxf86dga,
-    importc.}
-proc XDGASelectInput*(dpy: PDisplay, screen: cint, event_mask: clong){.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGAFillRectangle*(dpy: PDisplay, screen: cint, x: cint, y: cint,
-                        width: cuint, height: cuint, color: culong){.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGACopyArea*(dpy: PDisplay, screen: cint, srcx: cint, srcy: cint,
-                   width: cuint, height: cuint, dstx: cint, dsty: cint){.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGACopyTransparentArea*(dpy: PDisplay, screen: cint, srcx: cint,
-                              srcy: cint, width: cuint, height: cuint,
-                              dstx: cint, dsty: cint, key: culong){.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGAGetViewportStatus*(dpy: PDisplay, screen: cint): cint{.cdecl,
-    dynlib: libXxf86dga, importc.}
-proc XDGASync*(dpy: PDisplay, screen: cint){.cdecl, dynlib: libXxf86dga, importc.}
-proc XDGASetClientVersion*(dpy: PDisplay): TBool{.cdecl, dynlib: libXxf86dga,
-    importc.}
-proc XDGAChangePixmapMode*(dpy: PDisplay, screen: cint, x: Pcint, y: Pcint,
-                           mode: cint){.cdecl, dynlib: libXxf86dga, importc.}
-proc XDGAKeyEventToXKeyEvent*(dk: PXDGAKeyEvent, xk: PXKeyEvent){.cdecl,
-    dynlib: libXxf86dga, importc.}
-# implementation
diff --git a/tests/deps/x11-1.0/xf86vmode.nim b/tests/deps/x11-1.0/xf86vmode.nim
deleted file mode 100644
index 547f5cbd2..000000000
--- a/tests/deps/x11-1.0/xf86vmode.nim
+++ /dev/null
@@ -1,229 +0,0 @@
-# $XFree86: xc/include/extensions/xf86vmode.h,v 3.30 2001/05/07 20:09:50 mvojkovi Exp $
-#
-#
-#Copyright 1995  Kaleb S. KEITHLEY
-#
-#Permission is hereby granted, free of charge, to any person obtaining
-#a copy of this software and associated documentation files (the
-#"Software"), to deal in the Software without restriction, including
-#without limitation the rights to use, copy, modify, merge, publish,
-#distribute, sublicense, and/or sell copies of the Software, and to
-#permit persons to whom the Software is furnished to do so, subject to
-#the following conditions:
-#
-#The above copyright notice and this permission notice shall be
-#included in all copies or substantial portions of the Software.
-#
-#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
-#EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-#MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
-#IN NO EVENT SHALL Kaleb S. KEITHLEY BE LIABLE FOR ANY CLAIM, DAMAGES
-#OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
-#ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
-#OTHER DEALINGS IN THE SOFTWARE.
-#
-#Except as contained in this notice, the name of Kaleb S. KEITHLEY
-#shall not be used in advertising or otherwise to promote the sale, use
-#or other dealings in this Software without prior written authorization
-#from Kaleb S. KEITHLEY
-#
-#
-# $Xorg: xf86vmode.h,v 1.3 2000/08/18 04:05:46 coskrey Exp $
-# THIS IS NOT AN X CONSORTIUM STANDARD OR AN X PROJECT TEAM SPECIFICATION
-
-import
-  x, xlib
-
-const
-  libXxf86vm* = "libXxf86vm.so"
-
-type
-  PINT32* = ptr int32
-
-const
-  X_XF86VidModeQueryVersion* = 0
-  X_XF86VidModeGetModeLine* = 1
-  X_XF86VidModeModModeLine* = 2
-  X_XF86VidModeSwitchMode* = 3
-  X_XF86VidModeGetMonitor* = 4
-  X_XF86VidModeLockModeSwitch* = 5
-  X_XF86VidModeGetAllModeLines* = 6
-  X_XF86VidModeAddModeLine* = 7
-  X_XF86VidModeDeleteModeLine* = 8
-  X_XF86VidModeValidateModeLine* = 9
-  X_XF86VidModeSwitchToMode* = 10
-  X_XF86VidModeGetViewPort* = 11
-  X_XF86VidModeSetViewPort* = 12 # new for version 2.x of this extension
-  X_XF86VidModeGetDotClocks* = 13
-  X_XF86VidModeSetClientVersion* = 14
-  X_XF86VidModeSetGamma* = 15
-  X_XF86VidModeGetGamma* = 16
-  X_XF86VidModeGetGammaRamp* = 17
-  X_XF86VidModeSetGammaRamp* = 18
-  X_XF86VidModeGetGammaRampSize* = 19
-  X_XF86VidModeGetPermissions* = 20
-  CLKFLAG_PROGRAMABLE* = 1
-
-when defined(XF86VIDMODE_EVENTS):
-  const
-    XF86VidModeNotify* = 0
-    XF86VidModeNumberEvents* = (XF86VidModeNotify + 1)
-    XF86VidModeNotifyMask* = 0x00000001
-    XF86VidModeNonEvent* = 0
-    XF86VidModeModeChange* = 1
-else:
-  const
-    XF86VidModeNumberEvents* = 0
-const
-  XF86VidModeBadClock* = 0
-  XF86VidModeBadHTimings* = 1
-  XF86VidModeBadVTimings* = 2
-  XF86VidModeModeUnsuitable* = 3
-  XF86VidModeExtensionDisabled* = 4
-  XF86VidModeClientNotLocal* = 5
-  XF86VidModeZoomLocked* = 6
-  XF86VidModeNumberErrors* = (XF86VidModeZoomLocked + 1)
-  XF86VM_READ_PERMISSION* = 1
-  XF86VM_WRITE_PERMISSION* = 2
-
-type
-  PXF86VidModeModeLine* = ptr TXF86VidModeModeLine
-  TXF86VidModeModeLine*{.final.} = object
-    hdisplay*: cushort
-    hsyncstart*: cushort
-    hsyncend*: cushort
-    htotal*: cushort
-    hskew*: cushort
-    vdisplay*: cushort
-    vsyncstart*: cushort
-    vsyncend*: cushort
-    vtotal*: cushort
-    flags*: cuint
-    privsize*: cint
-    c_private*: PINT32
-
-  PPPXF86VidModeModeInfo* = ptr PPXF86VidModeModeInfo
-  PPXF86VidModeModeInfo* = ptr PXF86VidModeModeInfo
-  PXF86VidModeModeInfo* = ptr TXF86VidModeModeInfo
-  TXF86VidModeModeInfo*{.final.} = object
-    dotclock*: cuint
-    hdisplay*: cushort
-    hsyncstart*: cushort
-    hsyncend*: cushort
-    htotal*: cushort
-    hskew*: cushort
-    vdisplay*: cushort
-    vsyncstart*: cushort
-    vsyncend*: cushort
-    vtotal*: cushort
-    flags*: cuint
-    privsize*: cint
-    c_private*: PINT32
-
-  PXF86VidModeSyncRange* = ptr TXF86VidModeSyncRange
-  TXF86VidModeSyncRange*{.final.} = object
-    hi*: cfloat
-    lo*: cfloat
-
-  PXF86VidModeMonitor* = ptr TXF86VidModeMonitor
-  TXF86VidModeMonitor*{.final.} = object
-    vendor*: cstring
-    model*: cstring
-    EMPTY*: cfloat
-    nhsync*: cuchar
-    hsync*: PXF86VidModeSyncRange
-    nvsync*: cuchar
-    vsync*: PXF86VidModeSyncRange
-
-  PXF86VidModeNotifyEvent* = ptr TXF86VidModeNotifyEvent
-  TXF86VidModeNotifyEvent*{.final.} = object
-    theType*: cint            # of event
-    serial*: culong           # # of last request processed by server
-    send_event*: TBool        # true if this came from a SendEvent req
-    display*: PDisplay        # Display the event was read from
-    root*: TWindow            # root window of event screen
-    state*: cint              # What happened
-    kind*: cint               # What happened
-    forced*: TBool            # extents of new region
-    time*: TTime              # event timestamp
-
-  PXF86VidModeGamma* = ptr TXF86VidModeGamma
-  TXF86VidModeGamma*{.final.} = object
-    red*: cfloat              # Red Gamma value
-    green*: cfloat            # Green Gamma value
-    blue*: cfloat             # Blue Gamma value
-
-
-when defined(MACROS):
-  proc XF86VidModeSelectNextMode*(disp: PDisplay, scr: cint): TBool
-  proc XF86VidModeSelectPrevMode*(disp: PDisplay, scr: cint): TBool
-proc XF86VidModeQueryVersion*(dpy: PDisplay, majorVersion: Pcint,
-                              minorVersion: Pcint): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeQueryExtension*(dpy: PDisplay, event_base: Pcint,
-                                error_base: Pcint): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeSetClientVersion*(dpy: PDisplay): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetModeLine*(dpy: PDisplay, screen: cint, dotclock: Pcint,
-                             modeline: PXF86VidModeModeLine): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetAllModeLines*(dpy: PDisplay, screen: cint, modecount: Pcint,
-                                 modelinesPtr: PPPXF86VidModeModeInfo): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeAddModeLine*(dpy: PDisplay, screen: cint,
-                             new_modeline: PXF86VidModeModeInfo,
-                             after_modeline: PXF86VidModeModeInfo): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeDeleteModeLine*(dpy: PDisplay, screen: cint,
-                                modeline: PXF86VidModeModeInfo): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeModModeLine*(dpy: PDisplay, screen: cint,
-                             modeline: PXF86VidModeModeLine): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeValidateModeLine*(dpy: PDisplay, screen: cint,
-                                  modeline: PXF86VidModeModeInfo): TStatus{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeSwitchMode*(dpy: PDisplay, screen: cint, zoom: cint): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeSwitchToMode*(dpy: PDisplay, screen: cint,
-                              modeline: PXF86VidModeModeInfo): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeLockModeSwitch*(dpy: PDisplay, screen: cint, lock: cint): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetMonitor*(dpy: PDisplay, screen: cint,
-                            monitor: PXF86VidModeMonitor): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetViewPort*(dpy: PDisplay, screen: cint, x_return: Pcint,
-                             y_return: Pcint): TBool{.cdecl, dynlib: libXxf86vm,
-    importc.}
-proc XF86VidModeSetViewPort*(dpy: PDisplay, screen: cint, x: cint, y: cint): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetDotClocks*(dpy: PDisplay, screen: cint, flags_return: Pcint,
-                              number_of_clocks_return: Pcint,
-                              max_dot_clock_return: Pcint, clocks_return: PPcint): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetGamma*(dpy: PDisplay, screen: cint, Gamma: PXF86VidModeGamma): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeSetGamma*(dpy: PDisplay, screen: cint, Gamma: PXF86VidModeGamma): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeSetGammaRamp*(dpy: PDisplay, screen: cint, size: cint,
-                              red_array: Pcushort, green_array: Pcushort,
-                              blue_array: Pcushort): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetGammaRamp*(dpy: PDisplay, screen: cint, size: cint,
-                              red_array: Pcushort, green_array: Pcushort,
-                              blue_array: Pcushort): TBool{.cdecl,
-    dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetGammaRampSize*(dpy: PDisplay, screen: cint, size: Pcint): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-proc XF86VidModeGetPermissions*(dpy: PDisplay, screen: cint, permissions: Pcint): TBool{.
-    cdecl, dynlib: libXxf86vm, importc.}
-# implementation
-
-#when defined(MACROS):
-proc XF86VidModeSelectNextMode(disp: PDisplay, scr: cint): TBool =
-  XF86VidModeSwitchMode(disp, scr, 1)
-
-proc XF86VidModeSelectPrevMode(disp: PDisplay, scr: cint): TBool =
-  XF86VidModeSwitchMode(disp, scr, - 1)
diff --git a/tests/deps/x11-1.0/xi.nim b/tests/deps/x11-1.0/xi.nim
deleted file mode 100644
index d1b9f7846..000000000
--- a/tests/deps/x11-1.0/xi.nim
+++ /dev/null
@@ -1,307 +0,0 @@
-#
-# $Xorg: XI.h,v 1.4 2001/02/09 02:03:23 xorgcvs Exp $
-#
-#************************************************************
-#
-#Copyright 1989, 1998  The Open Group
-#
-#Permission to use, copy, modify, distribute, and sell this software and its
-#documentation for any purpose is hereby granted without fee, provided that
-#the above copyright notice appear in all copies and that both that
-#copyright notice and this permission notice appear in supporting
-#documentation.
-#
-#The above copyright notice and this permission notice shall be included in
-#all copies or substantial portions of the Software.
-#
-#THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-#IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-#FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
-#OPEN GROUP BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
-#AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
-#CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-#
-#Except as contained in this notice, the name of The Open Group shall not be
-#used in advertising or otherwise to promote the sale, use or other dealings
-#in this Software without prior written authorization from The Open Group.
-#
-#Copyright 1989 by Hewlett-Packard Company, Palo Alto, California.
-#
-#                        All Rights Reserved
-#
-#Permission to use, copy, modify, and distribute this software and its
-#documentation for any purpose and without fee is hereby granted,
-#provided that the above copyright notice appear in all copies and that
-#both that copyright notice and this permission notice appear in
-#supporting documentation, and that the name of Hewlett-Packard not be
-#used in advertising or publicity pertaining to distribution of the
-#software without specific, written prior permission.
-#
-#HEWLETT-PACKARD DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-#ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-#HEWLETT-PACKARD BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-#ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-#WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-#ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-#SOFTWARE.
-#
-#********************************************************/
-# $XFree86: xc/include/extensions/XI.h,v 1.5 2001/12/14 19:53:28 dawes Exp $
-#
-# Definitions used by the server, library and client
-#
-#        Pascal Convertion was made by Ido Kannner - kanerido@actcom.net.il
-#
-#Histroy:
-#        2004/10/15 - Fixed a bug of accessing second based records by removing "paced record" and chnaged it to
-#                     "reocrd" only.
-#        2004/10/07 - Removed the "uses X;" line. The unit does not need it.
-#        2004/10/03 - Conversion from C header to Pascal unit.
-#
-
-const 
-  sz_xGetExtensionVersionReq* = 8
-  sz_xGetExtensionVersionReply* = 32
-  sz_xListInputDevicesReq* = 4
-  sz_xListInputDevicesReply* = 32
-  sz_xOpenDeviceReq* = 8
-  sz_xOpenDeviceReply* = 32
-  sz_xCloseDeviceReq* = 8
-  sz_xSetDeviceModeReq* = 8
-  sz_xSetDeviceModeReply* = 32
-  sz_xSelectExtensionEventReq* = 12
-  sz_xGetSelectedExtensionEventsReq* = 8
-  sz_xGetSelectedExtensionEventsReply* = 32
-  sz_xChangeDeviceDontPropagateListReq* = 12
-  sz_xGetDeviceDontPropagateListReq* = 8
-  sz_xGetDeviceDontPropagateListReply* = 32
-  sz_xGetDeviceMotionEventsReq* = 16
-  sz_xGetDeviceMotionEventsReply* = 32
-  sz_xChangeKeyboardDeviceReq* = 8
-  sz_xChangeKeyboardDeviceReply* = 32
-  sz_xChangePointerDeviceReq* = 8
-  sz_xChangePointerDeviceReply* = 32
-  sz_xGrabDeviceReq* = 20
-  sz_xGrabDeviceReply* = 32
-  sz_xUngrabDeviceReq* = 12
-  sz_xGrabDeviceKeyReq* = 20
-  sz_xGrabDeviceKeyReply* = 32
-  sz_xUngrabDeviceKeyReq* = 16
-  sz_xGrabDeviceButtonReq* = 20
-  sz_xGrabDeviceButtonReply* = 32
-  sz_xUngrabDeviceButtonReq* = 16
-  sz_xAllowDeviceEventsReq* = 12
-  sz_xGetDeviceFocusReq* = 8
-  sz_xGetDeviceFocusReply* = 32
-  sz_xSetDeviceFocusReq* = 16
-  sz_xGetFeedbackControlReq* = 8
-  sz_xGetFeedbackControlReply* = 32
-  sz_xChangeFeedbackControlReq* = 12
-  sz_xGetDeviceKeyMappingReq* = 8
-  sz_xGetDeviceKeyMappingReply* = 32
-  sz_xChangeDeviceKeyMappingReq* = 8
-  sz_xGetDeviceModifierMappingReq* = 8
-  sz_xSetDeviceModifierMappingReq* = 8
-  sz_xSetDeviceModifierMappingReply* = 32
-  sz_xGetDeviceButtonMappingReq* = 8
-  sz_xGetDeviceButtonMappingReply* = 32
-  sz_xSetDeviceButtonMappingReq* = 8
-  sz_xSetDeviceButtonMappingReply* = 32
-  sz_xQueryDeviceStateReq* = 8
-  sz_xQueryDeviceStateReply* = 32
-  sz_xSendExtensionEventReq* = 16
-  sz_xDeviceBellReq* = 8
-  sz_xSetDeviceValuatorsReq* = 8
-  sz_xSetDeviceValuatorsReply* = 32
-  sz_xGetDeviceControlReq* = 8
-  sz_xGetDeviceControlReply* = 32
-  sz_xChangeDeviceControlReq* = 8
-  sz_xChangeDeviceControlReply* = 32
-
-const 
-  INAME* = "XInputExtension"
-
-const 
-  XI_KEYBOARD* = "KEYBOARD"
-  XI_MOUSE* = "MOUSE"
-  XI_TABLET* = "TABLET"
-  XI_TOUCHSCREEN* = "TOUCHSCREEN"
-  XI_TOUCHPAD* = "TOUCHPAD"
-  XI_BARCODE* = "BARCODE"
-  XI_BUTTONBOX* = "BUTTONBOX"
-  XI_KNOB_BOX* = "KNOB_BOX"
-  XI_ONE_KNOB* = "ONE_KNOB"
-  XI_NINE_KNOB* = "NINE_KNOB"
-  XI_TRACKBALL* = "TRACKBALL"
-  XI_QUADRATURE* = "QUADRATURE"
-  XI_ID_MODULE* = "ID_MODULE"
-  XI_SPACEBALL* = "SPACEBALL"
-  XI_DATAGLOVE* = "DATAGLOVE"
-  XI_EYETRACKER* = "EYETRACKER"
-  XI_CURSORKEYS* = "CURSORKEYS"
-  XI_FOOTMOUSE* = "FOOTMOUSE"
-
-const 
-  Dont_Check* = 0
-  XInput_Initial_Release* = 1
-  XInput_Add_XDeviceBell* = 2
-  XInput_Add_XSetDeviceValuators* = 3
-  XInput_Add_XChangeDeviceControl* = 4
-
-const 
-  XI_Absent* = 0
-  XI_Present* = 1
-
-const 
-  XI_Initial_Release_Major* = 1
-  XI_Initial_Release_Minor* = 0
-
-const 
-  XI_Add_XDeviceBell_Major* = 1
-  XI_Add_XDeviceBell_Minor* = 1
-
-const 
-  XI_Add_XSetDeviceValuators_Major* = 1
-  XI_Add_XSetDeviceValuators_Minor* = 2
-
-const 
-  XI_Add_XChangeDeviceControl_Major* = 1
-  XI_Add_XChangeDeviceControl_Minor* = 3
-
-const 
-  DEVICE_RESOLUTION* = 1
-
-const 
-  NoSuchExtension* = 1
-
-const 
-  COUNT* = 0
-  CREATE* = 1
-
-const 
-  NewPointer* = 0
-  NewKeyboard* = 1
-
-const 
-  XPOINTER* = 0
-  XKEYBOARD* = 1
-
-const 
-  UseXKeyboard* = 0x000000FF
-
-const 
-  IsXPointer* = 0
-  IsXKeyboard* = 1
-  IsXExtensionDevice* = 2
-
-const 
-  AsyncThisDevice* = 0
-  SyncThisDevice* = 1
-  ReplayThisDevice* = 2
-  AsyncOtherDevices* = 3
-  AsyncAll* = 4
-  SyncAll* = 5
-
-const 
-  FollowKeyboard* = 3
-  RevertToFollowKeyboard* = 3
-
-const 
-  DvAccelNum* = int(1) shl 0
-  DvAccelDenom* = int(1) shl 1
-  DvThreshold* = int(1) shl 2
-
-const 
-  DvKeyClickPercent* = int(1) shl 0
-  DvPercent* = int(1) shl 1
-  DvPitch* = int(1) shl 2
-  DvDuration* = int(1) shl 3
-  DvLed* = int(1) shl 4
-  DvLedMode* = int(1) shl 5
-  DvKey* = int(1) shl 6
-  DvAutoRepeatMode* = 1 shl 7
-
-const 
-  DvString* = int(1) shl 0
-
-const 
-  DvInteger* = int(1) shl 0
-
-const 
-  DeviceMode* = int(1) shl 0
-  Relative* = 0
-  Absolute* = 1               # Merged from Metrolink tree for XINPUT stuff 
-  TS_Raw* = 57
-  TS_Scaled* = 58
-  SendCoreEvents* = 59
-  DontSendCoreEvents* = 60    # End of merged section 
-
-const 
-  ProximityState* = int(1) shl 1
-  InProximity* = int(0) shl 1
-  OutOfProximity* = int(1) shl 1
-
-const 
-  AddToList* = 0
-  DeleteFromList* = 1
-
-const 
-  KeyClass* = 0
-  ButtonClass* = 1
-  ValuatorClass* = 2
-  FeedbackClass* = 3
-  ProximityClass* = 4
-  FocusClass* = 5
-  OtherClass* = 6
-
-const 
-  KbdFeedbackClass* = 0
-  PtrFeedbackClass* = 1
-  StringFeedbackClass* = 2
-  IntegerFeedbackClass* = 3
-  LedFeedbackClass* = 4
-  BellFeedbackClass* = 5
-
-const 
-  devicePointerMotionHint* = 0
-  deviceButton1Motion* = 1
-  deviceButton2Motion* = 2
-  deviceButton3Motion* = 3
-  deviceButton4Motion* = 4
-  deviceButton5Motion* = 5
-  deviceButtonMotion* = 6
-  deviceButtonGrab* = 7
-  deviceOwnerGrabButton* = 8
-  noExtensionEvent* = 9
-
-const 
-  XI_BadDevice* = 0
-  XI_BadEvent* = 1
-  XI_BadMode* = 2
-  XI_DeviceBusy* = 3
-  XI_BadClass* = 4 # Make XEventClass be a CARD32 for 64 bit servers.  Don't affect client
-                   #  definition of XEventClass since that would be a library interface change.
-                   #  See the top of X.h for more _XSERVER64 magic.
-                   #
-
-when defined(XSERVER64): 
-  type 
-    XEventClass* = CARD32
-else: 
-  type 
-    XEventClass* = int32
-#******************************************************************
-# *
-# * Extension version structure.
-# *
-# 
-
-type 
-  PXExtensionVersion* = ptr TXExtensionVersion
-  TXExtensionVersion*{.final.} = object 
-    present*: int16
-    major_version*: int16
-    minor_version*: int16
-
-
-# implementation
diff --git a/tests/deps/x11-1.0/xinerama.nim b/tests/deps/x11-1.0/xinerama.nim
deleted file mode 100644
index 96f5d7da3..000000000
--- a/tests/deps/x11-1.0/xinerama.nim
+++ /dev/null
@@ -1,25 +0,0 @@
-# Converted from X11/Xinerama.h 
-import                        
-  xlib
-
-const
-  xineramaLib = "libXinerama.so"
-
-type 
-  PXineramaScreenInfo* = ptr TXineramaScreenInfo
-  TXineramaScreenInfo*{.final.} = object 
-    screen_number*: cint
-    x_org*: int16
-    y_org*: int16
-    width*: int16
-    height*: int16
-
-
-proc XineramaQueryExtension*(dpy: PDisplay, event_base: Pcint, error_base: Pcint): TBool{.
-    cdecl, dynlib: xineramaLib, importc.}
-proc XineramaQueryVersion*(dpy: PDisplay, major: Pcint, minor: Pcint): TStatus{.
-    cdecl, dynlib: xineramaLib, importc.}
-proc XineramaIsActive*(dpy: PDisplay): TBool{.cdecl, dynlib: xineramaLib, importc.}
-proc XineramaQueryScreens*(dpy: PDisplay, number: Pcint): PXineramaScreenInfo{.
-    cdecl, dynlib: xineramaLib, importc.}
-
diff --git a/tests/deps/x11-1.0/xkb.nim b/tests/deps/x11-1.0/xkb.nim
deleted file mode 100644
index 2ecf17026..000000000
--- a/tests/deps/x11-1.0/xkb.nim
+++ /dev/null
@@ -1,2387 +0,0 @@
-#
-# $Xorg: XKB.h,v 1.3 2000/08/18 04:05:45 coskrey Exp $
-#************************************************************
-# $Xorg: XKBstr.h,v 1.3 2000/08/18 04:05:45 coskrey Exp $
-#************************************************************
-# $Xorg: XKBgeom.h,v 1.3 2000/08/18 04:05:45 coskrey Exp $
-#************************************************************
-#
-#Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.
-#
-#Permission to use, copy, modify, and distribute this
-#software and its documentation for any purpose and without
-#fee is hereby granted, provided that the above copyright
-#notice appear in all copies and that both that copyright
-#notice and this permission notice appear in supporting
-#documentation, and that the name of Silicon Graphics not be
-#used in advertising or publicity pertaining to distribution
-#of the software without specific prior written permission.
-#Silicon Graphics makes no representation about the suitability
-#of this software for any purpose. It is provided "as is"
-#without any express or implied warranty.
-#
-#SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-#SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-#AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-#GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-#DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE,
-#DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-#OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-#THE USE OR PERFORMANCE OF THIS SOFTWARE.
-#
-#********************************************************
-# $XFree86: xc/include/extensions/XKB.h,v 1.5 2002/11/20 04:49:01 dawes Exp $
-# $XFree86: xc/include/extensions/XKBgeom.h,v 3.9 2002/09/18 17:11:40 tsi Exp $
-#
-# Pascal Convertion was made by Ido Kannner - kanerido@actcom.net.il
-#
-#Thanks:
-#         I want to thanks to oliebol for putting up with all of the problems that was found
-#         while translating this code. ;)
-#
-#         I want to thanks #fpc channel in freenode irc, for helping me, and to put up with my
-#         weird questions ;)
-#
-#         Thanks for mmc in #xlib on freenode irc And so for the channel itself for the helping me to
-#         understanding some of the problems I had converting this headers and pointing me to resources
-#         that helped translating this headers.
-#
-# Ido
-#
-#History:
-#        2004/10/15           - Fixed a bug of accessing second based records by removing "paced record" and
-#                               chnaged it to "reocrd" only.
-#        2004/10/04 - 06      - Convertion from the c header of XKBgeom.h.
-#        2004/10/03           - Removed the XKBstr_UNIT compiler decleration. Afther the joined files,
-#                                                                                     There is no need for it anymore.
-#                                                                             - There is a need to define (for now) XKBgeom (compiler define) in order
-#                                                                               to use the code of it. At this moment, I did not yet converted it to Pascal.
-#
-#        2004/09/17 - 10/04   - Convertion from the c header of XKBstr.
-#
-#        2004/10/03           - Joined xkbstr.pas into xkb.pas because of the circular calls problems.
-#                             - Added the history of xkbstr.pas above this addition.
-#
-#        2004/09/17           - Fixed a wrong convertion number of XkbPerKeyBitArraySize, instead
-#                               of float, it's now converted into integer (as it should have been).
-#
-#        2004/09/15 - 16      - Convertion from the c header of XKB.h.
-#
-
-import
-  X, Xlib
-
-include "x11pragma.nim"
-
-proc XkbcharToInt*(v: int8): int16
-proc XkbIntTo2chars*(i: int16, h, L: var int8)
-proc Xkb2charsToInt*(h, L: int8): int16
-  #
-  #          Common data structures and access macros
-  #
-type
-  PWord* = ptr array[0..64_000, int16]
-  PByte* = ptr byte
-  PXkbStatePtr* = ptr TXkbStateRec
-  TXkbStateRec*{.final.} = object
-    group*: int8
-    locked_group*: int8
-    base_group*: int16
-    latched_group*: int16
-    mods*: int8
-    base_mods*: int8
-    latched_mods*: int8
-    locked_mods*: int8
-    compat_state*: int8
-    grab_mods*: int8
-    compat_grab_mods*: int8
-    lookup_mods*: int8
-    compat_lookup_mods*: int8
-    ptr_buttons*: int16
-
-
-proc XkbModLocks*(s: PXkbStatePtr): int8
-proc XkbStateMods*(s: PXkbStatePtr): int16
-proc XkbGroupLock*(s: PXkbStatePtr): int8
-proc XkbStateGroup*(s: PXkbStatePtr): int16
-proc XkbStateFieldFromRec*(s: PXkbStatePtr): int
-proc XkbGrabStateFromRec*(s: PXkbStatePtr): int
-type
-  PXkbModsPtr* = ptr TXkbModsRec
-  TXkbModsRec*{.final.} = object
-    mask*: int8               # effective mods
-    real_mods*: int8
-    vmods*: int16
-
-
-type
-  PXkbKTMapEntryPtr* = ptr TXkbKTMapEntryRec
-  TXkbKTMapEntryRec*{.final.} = object
-    active*: bool
-    level*: int8
-    mods*: TXkbModsRec
-
-
-type
-  PXkbKeyTypePtr* = ptr TXkbKeyTypeRec
-  TXkbKeyTypeRec*{.final.} = object
-    mods*: TXkbModsRec
-    num_levels*: int8
-    map_count*: int8
-    map*: PXkbKTMapEntryPtr
-    preserve*: PXkbModsPtr
-    name*: TAtom
-    level_names*: TAtom
-
-
-proc XkbNumGroups*(g: int16): int16
-proc XkbOutOfRangeGroupInfo*(g: int16): int16
-proc XkbOutOfRangeGroupAction*(g: int16): int16
-proc XkbOutOfRangeGroupNumber*(g: int16): int16
-proc XkbSetGroupInfo*(g, w, n: int16): int16
-proc XkbSetNumGroups*(g, n: int16): int16
-  #
-  #          Structures and access macros used primarily by the server
-  #
-type
-  PXkbBehavior* = ptr TXkbBehavior
-  TXkbBehavior*{.final.} = object
-    theType*: int8
-    data*: int8
-
-
-type
-  PXkbModAction* = ptr TXkbModAction
-  TXkbModAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    mask*: int8
-    real_mods*: int8
-    vmods1*: int8
-    vmods2*: int8
-
-
-proc XkbModActionVMods*(a: PXkbModAction): int16
-proc XkbSetModActionVMods*(a: PXkbModAction, v: int8)
-type
-  PXkbGroupAction* = ptr TXkbGroupAction
-  TXkbGroupAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    group_XXX*: int8
-
-
-proc XkbSAGroup*(a: PXkbGroupAction): int8
-proc XkbSASetGroupProc*(a: PXkbGroupAction, g: int8)
-type
-  PXkbISOAction* = ptr TXkbISOAction
-  TXkbISOAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    mask*: int8
-    real_mods*: int8
-    group_XXX*: int8
-    affect*: int8
-    vmods1*: int8
-    vmods2*: int8
-
-
-type
-  PXkbPtrAction* = ptr TXkbPtrAction
-  TXkbPtrAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    high_XXX*: int8
-    low_XXX*: int8
-    high_YYY*: int8
-    low_YYY*: int8
-
-
-proc XkbPtrActionX*(a: PXkbPtrAction): int16
-proc XkbPtrActionY*(a: PXkbPtrAction): int16
-proc XkbSetPtrActionX*(a: PXkbPtrAction, x: int8)
-proc XkbSetPtrActionY*(a: PXkbPtrAction, y: int8)
-type
-  PXkbPtrBtnAction* = ptr TXkbPtrBtnAction
-  TXkbPtrBtnAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    count*: int8
-    button*: int8
-
-
-type
-  PXkbPtrDfltAction* = ptr TXkbPtrDfltAction
-  TXkbPtrDfltAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    affect*: int8
-    valueXXX*: int8
-
-
-proc XkbSAPtrDfltValue*(a: PXkbPtrDfltAction): int8
-proc XkbSASetPtrDfltValue*(a: PXkbPtrDfltAction, c: pointer)
-type
-  PXkbSwitchScreenAction* = ptr TXkbSwitchScreenAction
-  TXkbSwitchScreenAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    screenXXX*: int8
-
-
-proc XkbSAScreen*(a: PXkbSwitchScreenAction): int8
-proc XkbSASetScreen*(a: PXkbSwitchScreenAction, s: pointer)
-type
-  PXkbCtrlsAction* = ptr TXkbCtrlsAction
-  TXkbCtrlsAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    ctrls3*: int8
-    ctrls2*: int8
-    ctrls1*: int8
-    ctrls0*: int8
-
-
-proc XkbActionSetCtrls*(a: PXkbCtrlsAction, c: int8)
-proc XkbActionCtrls*(a: PXkbCtrlsAction): int16
-type
-  PXkbMessageAction* = ptr TXkbMessageAction
-  TXkbMessageAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    message*: array[0..5, char]
-
-
-type
-  PXkbRedirectKeyAction* = ptr TXkbRedirectKeyAction
-  TXkbRedirectKeyAction*{.final.} = object
-    theType*: int8
-    new_key*: int8
-    mods_mask*: int8
-    mods*: int8
-    vmods_mask0*: int8
-    vmods_mask1*: int8
-    vmods0*: int8
-    vmods1*: int8
-
-
-proc XkbSARedirectVMods*(a: PXkbRedirectKeyAction): int16
-proc XkbSARedirectSetVMods*(a: PXkbRedirectKeyAction, m: int8)
-proc XkbSARedirectVModsMask*(a: PXkbRedirectKeyAction): int16
-proc XkbSARedirectSetVModsMask*(a: PXkbRedirectKeyAction, m: int8)
-type
-  PXkbDeviceBtnAction* = ptr TXkbDeviceBtnAction
-  TXkbDeviceBtnAction*{.final.} = object
-    theType*: int8
-    flags*: int8
-    count*: int8
-    button*: int8
-    device*: int8
-
-
-type
-  PXkbDeviceValuatorAction* = ptr TXkbDeviceValuatorAction
-  TXkbDeviceValuatorAction*{.final.} = object  #
-                                               #      Macros to classify key actions
-                                               #
-    theType*: int8
-    device*: int8
-    v1_what*: int8
-    v1_ndx*: int8
-    v1_value*: int8
-    v2_what*: int8
-    v2_ndx*: int8
-    v2_value*: int8
-
-
-const
-  XkbAnyActionDataSize* = 7
-
-type
-  PXkbAnyAction* = ptr TXkbAnyAction
-  TXkbAnyAction*{.final.} = object
-    theType*: int8
-    data*: array[0..XkbAnyActionDataSize - 1, int8]
-
-
-proc XkbIsModAction*(a: PXkbAnyAction): bool
-proc XkbIsGroupAction*(a: PXkbAnyAction): bool
-proc XkbIsPtrAction*(a: PXkbAnyAction): bool
-type
-  PXkbAction* = ptr TXkbAction
-  TXkbAction*{.final.} = object  #
-                                 #      XKB request codes, used in:
-                                 #      -  xkbReqType field of all requests
-                                 #      -  requestMinor field of some events
-                                 #
-    any*: TXkbAnyAction
-    mods*: TXkbModAction
-    group*: TXkbGroupAction
-    iso*: TXkbISOAction
-    thePtr*: TXkbPtrAction
-    btn*: TXkbPtrBtnAction
-    dflt*: TXkbPtrDfltAction
-    screen*: TXkbSwitchScreenAction
-    ctrls*: TXkbCtrlsAction
-    msg*: TXkbMessageAction
-    redirect*: TXkbRedirectKeyAction
-    devbtn*: TXkbDeviceBtnAction
-    devval*: TXkbDeviceValuatorAction
-    theType*: int8
-
-
-const
-  X_kbUseExtension* = 0
-  X_kbSelectEvents* = 1
-  X_kbBell* = 3
-  X_kbGetState* = 4
-  X_kbLatchLockState* = 5
-  X_kbGetControls* = 6
-  X_kbSetControls* = 7
-  X_kbGetMap* = 8
-  X_kbSetMap* = 9
-  X_kbGetCompatMap* = 10
-  X_kbSetCompatMap* = 11
-  X_kbGetIndicatorState* = 12
-  X_kbGetIndicatorMap* = 13
-  X_kbSetIndicatorMap* = 14
-  X_kbGetNamedIndicator* = 15
-  X_kbSetNamedIndicator* = 16
-  X_kbGetNames* = 17
-  X_kbSetNames* = 18
-  X_kbGetGeometry* = 19
-  X_kbSetGeometry* = 20
-  X_kbPerClientFlags* = 21
-  X_kbListComponents* = 22
-  X_kbGetKbdByName* = 23
-  X_kbGetDeviceInfo* = 24
-  X_kbSetDeviceInfo* = 25
-  X_kbSetDebuggingFlags* = 101 #
-                               #      In the X sense, XKB reports only one event.
-                               #      The type field of all XKB events is XkbEventCode
-                               #
-
-const
-  XkbEventCode* = 0
-  XkbNumberEvents* = XkbEventCode + 1 #
-                                      #      XKB has a minor event code so it can use one X event code for
-                                      #      multiple purposes.
-                                      #       - reported in the xkbType field of all XKB events.
-                                      #       - XkbSelectEventDetails: Indicates the event for which event details
-                                      #         are being changed
-                                      #
-
-const
-  XkbNewKeyboardNotify* = 0
-  XkbMapNotify* = 1
-  XkbStateNotify* = 2
-  XkbControlsNotify* = 3
-  XkbIndicatorStateNotify* = 4
-  XkbIndicatorMapNotify* = 5
-  XkbNamesNotify* = 6
-  XkbCompatMapNotify* = 7
-  XkbBellNotify* = 8
-  XkbActionMessage* = 9
-  XkbAccessXNotify* = 10
-  XkbExtensionDeviceNotify* = 11 #
-                                 #      Event Mask:
-                                 #       - XkbSelectEvents:  Specifies event interest.
-                                 #
-
-const
-  XkbNewKeyboardNotifyMask* = int(1) shl 0
-  XkbMapNotifyMask* = int(1) shl 1
-  XkbStateNotifyMask* = int(1) shl 2
-  XkbControlsNotifyMask* = int(1) shl 3
-  XkbIndicatorStateNotifyMask* = int(1) shl 4
-  XkbIndicatorMapNotifyMask* = int(1) shl 5
-  XkbNamesNotifyMask* = int(1) shl 6
-  XkbCompatMapNotifyMask* = int(1) shl 7
-  XkbBellNotifyMask* = int(1) shl 8
-  XkbActionMessageMask* = int(1) shl 9
-  XkbAccessXNotifyMask* = int(1) shl 10
-  XkbExtensionDeviceNotifyMask* = int(1) shl 11
-  XkbAllEventsMask* = 0x00000FFF #
-                                 #      NewKeyboardNotify event details:
-                                 #
-
-const
-  XkbNKN_KeycodesMask* = int(1) shl 0
-  XkbNKN_GeometryMask* = int(1) shl 1
-  XkbNKN_DeviceIDMask* = int(1) shl 2
-  XkbAllNewKeyboardEventsMask* = 0x00000007 #
-                                            #      AccessXNotify event types:
-                                            #       - The 'what' field of AccessXNotify events reports the
-                                            #         reason that the event was generated.
-                                            #
-
-const
-  XkbAXN_SKPress* = 0
-  XkbAXN_SKAccept* = 1
-  XkbAXN_SKReject* = 2
-  XkbAXN_SKRelease* = 3
-  XkbAXN_BKAccept* = 4
-  XkbAXN_BKReject* = 5
-  XkbAXN_AXKWarning* = 6 #
-                         #      AccessXNotify details:
-                         #      - Used as an event detail mask to limit the conditions under which
-                         #        AccessXNotify events are reported
-                         #
-
-const
-  XkbAXN_SKPressMask* = int(1) shl 0
-  XkbAXN_SKAcceptMask* = int(1) shl 1
-  XkbAXN_SKRejectMask* = int(1) shl 2
-  XkbAXN_SKReleaseMask* = int(1) shl 3
-  XkbAXN_BKAcceptMask* = int(1) shl 4
-  XkbAXN_BKRejectMask* = int(1) shl 5
-  XkbAXN_AXKWarningMask* = int(1) shl 6
-  XkbAllAccessXEventsMask* = 0x0000000F #
-                                        #      State detail mask:
-                                        #       - The 'changed' field of StateNotify events reports which of
-                                        #         the keyboard state components have changed.
-                                        #       - Used as an event detail mask to limit the conditions under
-                                        #         which StateNotify events are reported.
-                                        #
-
-const
-  XkbModifierStateMask* = int(1) shl 0
-  XkbModifierBaseMask* = int(1) shl 1
-  XkbModifierLatchMask* = int(1) shl 2
-  XkbModifierLockMask* = int(1) shl 3
-  XkbGroupStateMask* = int(1) shl 4
-  XkbGroupBaseMask* = int(1) shl 5
-  XkbGroupLatchMask* = int(1) shl 6
-  XkbGroupLockMask* = int(1) shl 7
-  XkbCompatStateMask* = int(1) shl 8
-  XkbGrabModsMask* = int(1) shl 9
-  XkbCompatGrabModsMask* = int(1) shl 10
-  XkbLookupModsMask* = int(1) shl 11
-  XkbCompatLookupModsMask* = int(1) shl 12
-  XkbPointerButtonMask* = int(1) shl 13
-  XkbAllStateComponentsMask* = 0x00003FFF #
-                                          #      Controls detail masks:
-                                          #       The controls specified in XkbAllControlsMask:
-                                          #       - The 'changed' field of ControlsNotify events reports which of
-                                          #         the keyboard controls have changed.
-                                          #       - The 'changeControls' field of the SetControls request specifies
-                                          #         the controls for which values are to be changed.
-                                          #       - Used as an event detail mask to limit the conditions under
-                                          #         which ControlsNotify events are reported.
-                                          #
-                                          #       The controls specified in the XkbAllBooleanCtrlsMask:
-                                          #       - The 'enabledControls' field of ControlsNotify events reports the
-                                          #         current status of the boolean controls.
-                                          #       - The 'enabledControlsChanges' field of ControlsNotify events reports
-                                          #         any boolean controls that have been turned on or off.
-                                          #       - The 'affectEnabledControls' and 'enabledControls' fields of the
-                                          #         kbSetControls request change the set of enabled controls.
-                                          #       - The 'accessXTimeoutMask' and 'accessXTimeoutValues' fields of
-                                          #         an XkbControlsRec specify the controls to be changed if the keyboard
-                                          #         times out and the values to which they should be changed.
-                                          #       - The 'autoCtrls' and 'autoCtrlsValues' fields of the PerClientFlags
-                                          #         request specifies the specify the controls to be reset when the
-                                          #         client exits and the values to which they should be reset.
-                                          #       - The 'ctrls' field of an indicator map specifies the controls
-                                          #         that drive the indicator.
-                                          #       - Specifies the boolean controls affected by the SetControls and
-                                          #         LockControls key actions.
-                                          #
-
-const
-  XkbRepeatKeysMask* = int(1) shl 0
-  XkbSlowKeysMask* = int(1) shl 1
-  XkbBounceKeysMask* = int(1) shl 2
-  XkbStickyKeysMask* = int(1) shl 3
-  XkbMouseKeysMask* = int(1) shl 4
-  XkbMouseKeysAccelMask* = int(1) shl 5
-  XkbAccessXKeysMask* = int(1) shl 6
-  XkbAccessXTimeoutMask* = int(1) shl 7
-  XkbAccessXFeedbackMask* = int(1) shl 8
-  XkbAudibleBellMask* = int(1) shl 9
-  XkbOverlay1Mask* = int(1) shl 10
-  XkbOverlay2Mask* = int(1) shl 11
-  XkbIgnoreGroupLockMask* = int(1) shl 12
-  XkbGroupsWrapMask* = int(1) shl 27
-  XkbInternalModsMask* = int(1) shl 28
-  XkbIgnoreLockModsMask* = int(1) shl 29
-  XkbPerKeyRepeatMask* = int(1) shl 30
-  XkbControlsEnabledMask* = int(1) shl 31
-  XkbAccessXOptionsMask* = XkbStickyKeysMask or XkbAccessXFeedbackMask
-  XkbAllBooleanCtrlsMask* = 0x00001FFF
-  XkbAllControlsMask* = 0xF8001FFF #
-                                   #      Compatibility Map Compontents:
-                                   #       - Specifies the components to be allocated in XkbAllocCompatMap.
-                                   #
-
-const
-  XkbSymInterpMask* = 1 shl 0
-  XkbGroupCompatMask* = 1 shl 1
-  XkbAllCompatMask* = 0x00000003 #
-                                 #      Assorted constants and limits.
-                                 #
-
-const
-  XkbAllIndicatorsMask* = 0xFFFFFFFF #
-                                     #      Map components masks:
-                                     #      Those in AllMapComponentsMask:
-                                     #       - Specifies the individual fields to be loaded or changed for the
-                                     #         GetMap and SetMap requests.
-                                     #      Those in ClientInfoMask:
-                                     #       - Specifies the components to be allocated by XkbAllocClientMap.
-                                     #      Those in ServerInfoMask:
-                                     #       - Specifies the components to be allocated by XkbAllocServerMap.
-                                     #
-
-const
-  XkbKeyTypesMask* = 1 shl 0
-  XkbKeySymsMask* = 1 shl 1
-  XkbModifierMapMask* = 1 shl 2
-  XkbExplicitComponentsMask* = 1 shl 3
-  XkbKeyActionsMask* = 1 shl 4
-  XkbKeyBehaviorsMask* = 1 shl 5
-  XkbVirtualModsMask* = 1 shl 6
-  XkbVirtualModMapMask* = 1 shl 7
-  XkbAllClientInfoMask* = XkbKeyTypesMask or XkbKeySymsMask or
-      XkbModifierMapMask
-  XkbAllServerInfoMask* = XkbExplicitComponentsMask or XkbKeyActionsMask or
-      XkbKeyBehaviorsMask or XkbVirtualModsMask or XkbVirtualModMapMask
-  XkbAllMapComponentsMask* = XkbAllClientInfoMask or XkbAllServerInfoMask #
-                                                                          #      Names component mask:
-                                                                          #       - Specifies the names to be loaded or changed for the GetNames and
-                                                                          #         SetNames requests.
-                                                                          #       - Specifies the names that have changed in a NamesNotify event.
-                                                                          #       - Specifies the names components to be allocated by XkbAllocNames.
-                                                                          #
-
-const
-  XkbKeycodesNameMask* = 1 shl 0
-  XkbGeometryNameMask* = 1 shl 1
-  XkbSymbolsNameMask* = 1 shl 2
-  XkbPhysSymbolsNameMask* = 1 shl 3
-  XkbTypesNameMask* = 1 shl 4
-  XkbCompatNameMask* = 1 shl 5
-  XkbKeyTypeNamesMask* = 1 shl 6
-  XkbKTLevelNamesMask* = 1 shl 7
-  XkbIndicatorNamesMask* = 1 shl 8
-  XkbKeyNamesMask* = 1 shl 9
-  XkbKeyAliasesMask* = 1 shl 10
-  XkbVirtualModNamesMask* = 1 shl 11
-  XkbGroupNamesMask* = 1 shl 12
-  XkbRGNamesMask* = 1 shl 13
-  XkbComponentNamesMask* = 0x0000003F
-  XkbAllNamesMask* = 0x00003FFF #
-                                #      Miscellaneous event details:
-                                #      - event detail masks for assorted events that don't reall
-                                #        have any details.
-                                #
-
-const
-  XkbAllStateEventsMask* = XkbAllStateComponentsMask
-  XkbAllMapEventsMask* = XkbAllMapComponentsMask
-  XkbAllControlEventsMask* = XkbAllControlsMask
-  XkbAllIndicatorEventsMask* = XkbAllIndicatorsMask
-  XkbAllNameEventsMask* = XkbAllNamesMask
-  XkbAllCompatMapEventsMask* = XkbAllCompatMask
-  XkbAllBellEventsMask* = int(1) shl 0
-  XkbAllActionMessagesMask* = int(1) shl 0 #
-                                           #      XKB reports one error:  BadKeyboard
-                                           #      A further reason for the error is encoded into to most significant
-                                           #      byte of the resourceID for the error:
-                                           #         XkbErr_BadDevice - the device in question was not found
-                                           #         XkbErr_BadClass  - the device was found but it doesn't belong to
-                                           #                            the appropriate class.
-                                           #         XkbErr_BadId     - the device was found and belongs to the right
-                                           #                            class, but not feedback with a matching id was
-                                           #                            found.
-                                           #      The low byte of the resourceID for this error contains the device
-                                           #      id, class specifier or feedback id that failed.
-                                           #
-
-const
-  XkbKeyboard* = 0
-  XkbNumberErrors* = 1
-  XkbErr_BadDevice* = 0x000000FF
-  XkbErr_BadClass* = 0x000000FE
-  XkbErr_BadId* = 0x000000FD #
-                             #      Keyboard Components Mask:
-                             #      - Specifies the components that follow a GetKeyboardByNameReply
-                             #
-
-const
-  XkbClientMapMask* = int(1) shl 0
-  XkbServerMapMask* = int(1) shl 1
-  XkbCompatMapMask* = int(1) shl 2
-  XkbIndicatorMapMask* = int(1) shl 3
-  XkbNamesMask* = int(1) shl 4
-  XkbGeometryMask* = int(1) shl 5
-  XkbControlsMask* = int(1) shl 6
-  XkbAllComponentsMask* = 0x0000007F #
-                                     #      AccessX Options Mask
-                                     #       - The 'accessXOptions' field of an XkbControlsRec specifies the
-                                     #         AccessX options that are currently in effect.
-                                     #       - The 'accessXTimeoutOptionsMask' and 'accessXTimeoutOptionsValues'
-                                     #         fields of an XkbControlsRec specify the Access X options to be
-                                     #         changed if the keyboard times out and the values to which they
-                                     #         should be changed.
-                                     #
-
-const
-  XkbAX_SKPressFBMask* = int(1) shl 0
-  XkbAX_SKAcceptFBMask* = int(1) shl 1
-  XkbAX_FeatureFBMask* = int(1) shl 2
-  XkbAX_SlowWarnFBMask* = int(1) shl 3
-  XkbAX_IndicatorFBMask* = int(1) shl 4
-  XkbAX_StickyKeysFBMask* = int(1) shl 5
-  XkbAX_TwoKeysMask* = int(1) shl 6
-  XkbAX_LatchToLockMask* = int(1) shl 7
-  XkbAX_SKReleaseFBMask* = int(1) shl 8
-  XkbAX_SKRejectFBMask* = int(1) shl 9
-  XkbAX_BKRejectFBMask* = int(1) shl 10
-  XkbAX_DumbBellFBMask* = int(1) shl 11
-  XkbAX_FBOptionsMask* = 0x00000F3F
-  XkbAX_SKOptionsMask* = 0x000000C0
-  XkbAX_AllOptionsMask* = 0x00000FFF #
-                                     #      XkbUseCoreKbd is used to specify the core keyboard without having
-                                     #                        to look up its X input extension identifier.
-                                     #      XkbUseCorePtr is used to specify the core pointer without having
-                                     #                        to look up its X input extension identifier.
-                                     #      XkbDfltXIClass is used to specify "don't care" any place that the
-                                     #                        XKB protocol is looking for an X Input Extension
-                                     #                        device class.
-                                     #      XkbDfltXIId is used to specify "don't care" any place that the
-                                     #                        XKB protocol is looking for an X Input Extension
-                                     #                        feedback identifier.
-                                     #      XkbAllXIClasses is used to get information about all device indicators,
-                                     #                        whether they're part of the indicator feedback class
-                                     #                        or the keyboard feedback class.
-                                     #      XkbAllXIIds is used to get information about all device indicator
-                                     #                        feedbacks without having to list them.
-                                     #      XkbXINone is used to indicate that no class or id has been specified.
-                                     #      XkbLegalXILedClass(c)  True if 'c' specifies a legal class with LEDs
-                                     #      XkbLegalXIBellClass(c) True if 'c' specifies a legal class with bells
-                                     #      XkbExplicitXIDevice(d) True if 'd' explicitly specifies a device
-                                     #      XkbExplicitXIClass(c)  True if 'c' explicitly specifies a device class
-                                     #      XkbExplicitXIId(c)     True if 'i' explicitly specifies a device id
-                                     #      XkbSingleXIClass(c)    True if 'c' specifies exactly one device class,
-                                     #                             including the default.
-                                     #      XkbSingleXIId(i)       True if 'i' specifies exactly one device
-                                     #                              identifier, including the default.
-                                     #
-
-const
-  XkbUseCoreKbd* = 0x00000100
-  XkbUseCorePtr* = 0x00000200
-  XkbDfltXIClass* = 0x00000300
-  XkbDfltXIId* = 0x00000400
-  XkbAllXIClasses* = 0x00000500
-  XkbAllXIIds* = 0x00000600
-  XkbXINone* = 0x0000FF00
-
-proc XkbLegalXILedClass*(c: int): bool
-proc XkbLegalXIBellClass*(c: int): bool
-proc XkbExplicitXIDevice*(c: int): bool
-proc XkbExplicitXIClass*(c: int): bool
-proc XkbExplicitXIId*(c: int): bool
-proc XkbSingleXIClass*(c: int): bool
-proc XkbSingleXIId*(c: int): bool
-const
-  XkbNoModifier* = 0x000000FF
-  XkbNoShiftLevel* = 0x000000FF
-  XkbNoShape* = 0x000000FF
-  XkbNoIndicator* = 0x000000FF
-  XkbNoModifierMask* = 0
-  XkbAllModifiersMask* = 0x000000FF
-  XkbAllVirtualModsMask* = 0x0000FFFF
-  XkbNumKbdGroups* = 4
-  XkbMaxKbdGroup* = XkbNumKbdGroups - 1
-  XkbMaxMouseKeysBtn* = 4 #
-                          #      Group Index and Mask:
-                          #       - Indices into the kt_index array of a key type.
-                          #       - Mask specifies types to be changed for XkbChangeTypesOfKey
-                          #
-
-const
-  XkbGroup1Index* = 0
-  XkbGroup2Index* = 1
-  XkbGroup3Index* = 2
-  XkbGroup4Index* = 3
-  XkbAnyGroup* = 254
-  XkbAllGroups* = 255
-  XkbGroup1Mask* = 1 shl 0
-  XkbGroup2Mask* = 1 shl 1
-  XkbGroup3Mask* = 1 shl 2
-  XkbGroup4Mask* = 1 shl 3
-  XkbAnyGroupMask* = 1 shl 7
-  XkbAllGroupsMask* = 0x0000000F #
-                                 #      BuildCoreState: Given a keyboard group and a modifier state,
-                                 #                      construct the value to be reported an event.
-                                 #      GroupForCoreState:  Given the state reported in an event,
-                                 #                      determine the keyboard group.
-                                 #      IsLegalGroup:   Returns TRUE if 'g' is a valid group index.
-                                 #
-
-proc XkbBuildCoreState*(m, g: int): int
-proc XkbGroupForCoreState*(s: int): int
-proc XkbIsLegalGroup*(g: int): bool
-  #
-  #      GroupsWrap values:
-  #       - The 'groupsWrap' field of an XkbControlsRec specifies the
-  #         treatment of out of range groups.
-  #       - Bits 6 and 7 of the group info field of a key symbol map
-  #         specify the interpretation of out of range groups for the
-  #         corresponding key.
-  #
-const
-  XkbWrapIntoRange* = 0x00000000
-  XkbClampIntoRange* = 0x00000040
-  XkbRedirectIntoRange* = 0x00000080 #
-                                     #      Action flags:  Reported in the 'flags' field of most key actions.
-                                     #      Interpretation depends on the type of the action; not all actions
-                                     #      accept all flags.
-                                     #
-                                     #      Option                    Used for Actions
-                                     #      ------                    ----------------
-                                     #      ClearLocks                SetMods, LatchMods, SetGroup, LatchGroup
-                                     #      LatchToLock               SetMods, LatchMods, SetGroup, LatchGroup
-                                     #      LockNoLock                LockMods, ISOLock, LockPtrBtn, LockDeviceBtn
-                                     #      LockNoUnlock              LockMods, ISOLock, LockPtrBtn, LockDeviceBtn
-                                     #      UseModMapMods             SetMods, LatchMods, LockMods, ISOLock
-                                     #      GroupAbsolute             SetGroup, LatchGroup, LockGroup, ISOLock
-                                     #      UseDfltButton             PtrBtn, LockPtrBtn
-                                     #      NoAcceleration            MovePtr
-                                     #      MoveAbsoluteX             MovePtr
-                                     #      MoveAbsoluteY             MovePtr
-                                     #      ISODfltIsGroup            ISOLock
-                                     #      ISONoAffectMods           ISOLock
-                                     #      ISONoAffectGroup          ISOLock
-                                     #      ISONoAffectPtr            ISOLock
-                                     #      ISONoAffectCtrls          ISOLock
-                                     #      MessageOnPress            ActionMessage
-                                     #      MessageOnRelease          ActionMessage
-                                     #      MessageGenKeyEvent        ActionMessage
-                                     #      AffectDfltBtn             SetPtrDflt
-                                     #      DfltBtnAbsolute           SetPtrDflt
-                                     #      SwitchApplication SwitchScreen
-                                     #      SwitchAbsolute            SwitchScreen
-                                     #
-
-const
-  XkbSA_ClearLocks* = int(1) shl 0
-  XkbSA_LatchToLock* = int(1) shl 1
-  XkbSA_LockNoLock* = int(1) shl 0
-  XkbSA_LockNoUnlock* = int(1) shl 1
-  XkbSA_UseModMapMods* = int(1) shl 2
-  XkbSA_GroupAbsolute* = int(1) shl 2
-  XkbSA_UseDfltButton* = 0
-  XkbSA_NoAcceleration* = int(1) shl 0
-  XkbSA_MoveAbsoluteX* = int(1) shl 1
-  XkbSA_MoveAbsoluteY* = int(1) shl 2
-  XkbSA_ISODfltIsGroup* = int(1) shl 7
-  XkbSA_ISONoAffectMods* = int(1) shl 6
-  XkbSA_ISONoAffectGroup* = int(1) shl 5
-  XkbSA_ISONoAffectPtr* = int(1) shl 4
-  XkbSA_ISONoAffectCtrls* = int(1) shl 3
-  XkbSA_ISOAffectMask* = 0x00000078
-  XkbSA_MessageOnPress* = int(1) shl 0
-  XkbSA_MessageOnRelease* = int(1) shl 1
-  XkbSA_MessageGenKeyEvent* = int(1) shl 2
-  XkbSA_AffectDfltBtn* = 1
-  XkbSA_DfltBtnAbsolute* = int(1) shl 2
-  XkbSA_SwitchApplication* = int(1) shl 0
-  XkbSA_SwitchAbsolute* = int(1) shl 2 #
-                                       #      The following values apply to the SA_DeviceValuator
-                                       #      action only.  Valuator operations specify the action
-                                       #      to be taken.   Values specified in the action are
-                                       #      multiplied by 2^scale before they are applied.
-                                       #
-
-const
-  XkbSA_IgnoreVal* = 0x00000000
-  XkbSA_SetValMin* = 0x00000010
-  XkbSA_SetValCenter* = 0x00000020
-  XkbSA_SetValMax* = 0x00000030
-  XkbSA_SetValRelative* = 0x00000040
-  XkbSA_SetValAbsolute* = 0x00000050
-  XkbSA_ValOpMask* = 0x00000070
-  XkbSA_ValScaleMask* = 0x00000007
-
-proc XkbSA_ValOp*(a: int): int
-proc XkbSA_ValScale*(a: int): int
-  #
-  #      Action types: specifies the type of a key action.  Reported in the
-  #      type field of all key actions.
-  #
-const
-  XkbSA_NoAction* = 0x00000000
-  XkbSA_SetMods* = 0x00000001
-  XkbSA_LatchMods* = 0x00000002
-  XkbSA_LockMods* = 0x00000003
-  XkbSA_SetGroup* = 0x00000004
-  XkbSA_LatchGroup* = 0x00000005
-  XkbSA_LockGroup* = 0x00000006
-  XkbSA_MovePtr* = 0x00000007
-  XkbSA_PtrBtn* = 0x00000008
-  XkbSA_LockPtrBtn* = 0x00000009
-  XkbSA_SetPtrDflt* = 0x0000000A
-  XkbSA_ISOLock* = 0x0000000B
-  XkbSA_Terminate* = 0x0000000C
-  XkbSA_SwitchScreen* = 0x0000000D
-  XkbSA_SetControls* = 0x0000000E
-  XkbSA_LockControls* = 0x0000000F
-  XkbSA_ActionMessage* = 0x00000010
-  XkbSA_RedirectKey* = 0x00000011
-  XkbSA_DeviceBtn* = 0x00000012
-  XkbSA_LockDeviceBtn* = 0x00000013
-  XkbSA_DeviceValuator* = 0x00000014
-  XkbSA_LastAction* = XkbSA_DeviceValuator
-  XkbSA_NumActions* = XkbSA_LastAction + 1
-
-const
-  XkbSA_XFree86Private* = 0x00000086
-#
-#      Specifies the key actions that clear latched groups or modifiers.
-#
-
-const  ##define        XkbSA_BreakLatch \
-       #        ((1<<XkbSA_NoAction)|(1<<XkbSA_PtrBtn)|(1<<XkbSA_LockPtrBtn)|\
-       #        (1<<XkbSA_Terminate)|(1<<XkbSA_SwitchScreen)|(1<<XkbSA_SetControls)|\
-       #        (1<<XkbSA_LockControls)|(1<<XkbSA_ActionMessage)|\
-       #        (1<<XkbSA_RedirectKey)|(1<<XkbSA_DeviceBtn)|(1<<XkbSA_LockDeviceBtn))
-       #
-  XkbSA_BreakLatch* = (1 shl XkbSA_PtrBtn) or (1 shl XkbSA_LockPtrBtn) or
-      (1 shl XkbSA_Terminate) or (1 shl XkbSA_SwitchScreen) or
-      (1 shl XkbSA_SetControls) or (1 shl XkbSA_LockControls) or
-      (1 shl XkbSA_ActionMessage) or (1 shl XkbSA_RedirectKey) or
-      (1 shl XkbSA_DeviceBtn) or (1 shl XkbSA_LockDeviceBtn) #
-                                                             #      Key Behavior Qualifier:
-                                                             #         KB_Permanent indicates that the behavior describes an unalterable
-                                                             #         characteristic of the keyboard, not an XKB software-simulation of
-                                                             #         the listed behavior.
-                                                             #      Key Behavior Types:
-                                                             #         Specifies the behavior of the underlying key.
-                                                             #
-
-const
-  XkbKB_Permanent* = 0x00000080
-  XkbKB_OpMask* = 0x0000007F
-  XkbKB_Default* = 0x00000000
-  XkbKB_Lock* = 0x00000001
-  XkbKB_RadioGroup* = 0x00000002
-  XkbKB_Overlay1* = 0x00000003
-  XkbKB_Overlay2* = 0x00000004
-  XkbKB_RGAllowNone* = 0x00000080 #
-                                  #      Various macros which describe the range of legal keycodes.
-                                  #
-
-const
-  XkbMinLegalKeyCode* = 8
-  XkbMaxLegalKeyCode* = 255
-  XkbMaxKeyCount* = XkbMaxLegalKeyCode - XkbMinLegalKeyCode + 1
-  XkbPerKeyBitArraySize* = (XkbMaxLegalKeyCode + 1) div 8
-
-proc XkbIsLegalKeycode*(k: int): bool
-type
-  PXkbControlsPtr* = ptr TXkbControlsRec
-  TXkbControlsRec*{.final.} = object
-    mk_dflt_btn*: int8
-    num_groups*: int8
-    groups_wrap*: int8
-    internal*: TXkbModsRec
-    ignore_lock*: TXkbModsRec
-    enabled_ctrls*: int16
-    repeat_delay*: int16
-    repeat_interval*: int16
-    slow_keys_delay*: int16
-    debounce_delay*: int16
-    mk_delay*: int16
-    mk_interval*: int16
-    mk_time_to_max*: int16
-    mk_max_speed*: int16
-    mk_curve*: int16
-    ax_options*: int16
-    ax_timeout*: int16
-    axt_opts_mask*: int16
-    axt_opts_values*: int16
-    axt_ctrls_mask*: int16
-    axt_ctrls_values*: int16
-    per_key_repeat*: array[0..XkbPerKeyBitArraySize - 1, int8]
-
-
-proc XkbAX_AnyFeedback*(c: PXkbControlsPtr): int16
-proc XkbAX_NeedOption*(c: PXkbControlsPtr, w: int16): int16
-proc XkbAX_NeedFeedback*(c: PXkbControlsPtr, w: int16): bool
-  #
-  #      Assorted constants and limits.
-  #
-const
-  XkbNumModifiers* = 8
-  XkbNumVirtualMods* = 16
-  XkbNumIndicators* = 32
-  XkbMaxRadioGroups* = 32
-  XkbAllRadioGroupsMask* = 0xFFFFFFFF
-  XkbMaxShiftLevel* = 63
-  XkbMaxSymsPerKey* = XkbMaxShiftLevel * XkbNumKbdGroups
-  XkbRGMaxMembers* = 12
-  XkbActionMessageLength* = 6
-  XkbKeyNameLength* = 4
-  XkbMaxRedirectCount* = 8
-  XkbGeomPtsPerMM* = 10
-  XkbGeomMaxColors* = 32
-  XkbGeomMaxLabelColors* = 3
-  XkbGeomMaxPriority* = 255
-
-type
-  PXkbServerMapPtr* = ptr TXkbServerMapRec
-  TXkbServerMapRec*{.final.} = object
-    num_acts*: int16
-    size_acts*: int16
-    acts*: ptr array[0..0xfff, TXkbAction]
-    behaviors*: PXkbBehavior
-    key_acts*: PWord
-    explicit*: PByte
-    vmods*: array[0..XkbNumVirtualMods - 1, int8]
-    vmodmap*: PWord
-
-
-proc XkbSMKeyActionsPtr*(m: PXkbServerMapPtr, k: int16): PXkbAction
-  #
-  #          Structures and access macros used primarily by clients
-  #
-type
-  PXkbSymMapPtr* = ptr TXkbSymMapRec
-  TXkbSymMapRec*{.final.} = object
-    kt_index*: array[0..XkbNumKbdGroups - 1, int8]
-    group_info*: int8
-    width*: int8
-    offset*: int8
-
-
-type
-  PXkbClientMapPtr* = ptr TXkbClientMapRec
-  TXkbClientMapRec*{.final.} = object
-    size_types*: int8
-    num_types*: int8
-    types*: ptr array[0..0xffff, TXkbKeyTypeRec]
-    size_syms*: int16
-    num_syms*: int16
-    syms*: ptr array[0..0xffff, TKeySym]
-    key_sym_map*: ptr array[0..0xffff, TXkbSymMapRec]
-    modmap*: PByte
-
-
-proc XkbCMKeyGroupInfo*(m: PXkbClientMapPtr, k: int16): int8
-proc XkbCMKeyNumGroups*(m: PXkbClientMapPtr, k: int16): int8
-proc XkbCMKeyGroupWidth*(m: PXkbClientMapPtr, k: int16, g: int8): int8
-proc XkbCMKeyGroupsWidth*(m: PXkbClientMapPtr, k: int16): int8
-proc XkbCMKeyTypeIndex*(m: PXkbClientMapPtr, k: int16, g: int8): int8
-proc XkbCMKeyType*(m: PXkbClientMapPtr, k: int16, g: int8): PXkbKeyTypePtr
-proc XkbCMKeyNumSyms*(m: PXkbClientMapPtr, k: int16): int16
-proc XkbCMKeySymsOffset*(m: PXkbClientMapPtr, k: int16): int8
-  #
-  #          Compatibility structures and access macros
-  #
-type
-  PXkbSymInterpretPtr* = ptr TXkbSymInterpretRec
-  TXkbSymInterpretRec*{.final.} = object
-    sym*: TKeySym
-    flags*: int8
-    match*: int8
-    mods*: int8
-    virtual_mod*: int8
-    act*: TXkbAnyAction
-
-
-type
-  PXkbCompatMapPtr* = ptr TXkbCompatMapRec
-  TXkbCompatMapRec*{.final.} = object
-    sym_interpret*: PXkbSymInterpretPtr
-    groups*: array[0..XkbNumKbdGroups - 1, TXkbModsRec]
-    num_si*: int16
-    size_si*: int16
-
-
-type
-  PXkbIndicatorMapPtr* = ptr TXkbIndicatorMapRec
-  TXkbIndicatorMapRec*{.final.} = object
-    flags*: int8
-    which_groups*: int8
-    groups*: int8
-    which_mods*: int8
-    mods*: TXkbModsRec
-    ctrls*: int16
-
-
-proc XkbIM_IsAuto*(i: PXkbIndicatorMapPtr): bool
-proc XkbIM_InUse*(i: PXkbIndicatorMapPtr): bool
-type
-  PXkbIndicatorPtr* = ptr TXkbIndicatorRec
-  TXkbIndicatorRec*{.final.} = object
-    phys_indicators*: int32
-    maps*: array[0..XkbNumIndicators - 1, TXkbIndicatorMapRec]
-
-
-type
-  PXkbKeyNamePtr* = ptr TXkbKeyNameRec
-  TXkbKeyNameRec*{.final.} = object
-    name*: array[0..XkbKeyNameLength - 1, char]
-
-
-type
-  PXkbKeyAliasPtr* = ptr TXkbKeyAliasRec
-  TXkbKeyAliasRec*{.final.} = object  #
-                                      #          Names for everything
-                                      #
-    float*: array[0..XkbKeyNameLength - 1, char]
-    alias*: array[0..XkbKeyNameLength - 1, char]
-
-
-type
-  PXkbNamesPtr* = ptr TXkbNamesRec
-  TXkbNamesRec*{.final.} = object  #
-                                   #      Key Type index and mask for the four standard key types.
-                                   #
-    keycodes*: TAtom
-    geometry*: TAtom
-    symbols*: TAtom
-    types*: TAtom
-    compat*: TAtom
-    vmods*: array[0..XkbNumVirtualMods - 1, TAtom]
-    indicators*: array[0..XkbNumIndicators - 1, TAtom]
-    groups*: array[0..XkbNumKbdGroups - 1, TAtom]
-    keys*: PXkbKeyNamePtr
-    key_aliases*: PXkbKeyAliasPtr
-    radio_groups*: PAtom
-    phys_symbols*: TAtom
-    num_keys*: int8
-    num_key_aliases*: int8
-    num_rg*: int16
-
-
-const
-  XkbOneLevelIndex* = 0
-  XkbTwoLevelIndex* = 1
-  XkbAlphabeticIndex* = 2
-  XkbKeypadIndex* = 3
-  XkbLastRequiredType* = XkbKeypadIndex
-  XkbNumRequiredTypes* = XkbLastRequiredType + 1
-  XkbMaxKeyTypes* = 255
-  XkbOneLevelMask* = 1 shl 0
-  XkbTwoLevelMask* = 1 shl 1
-  XkbAlphabeticMask* = 1 shl 2
-  XkbKeypadMask* = 1 shl 3
-  XkbAllRequiredTypes* = 0x0000000F
-
-proc XkbShiftLevel*(n: int8): int8
-proc XkbShiftLevelMask*(n: int8): int8
-  #
-  #      Extension name and version information
-  #
-const
-  XkbName* = "XKEYBOARD"
-  XkbMajorVersion* = 1
-  XkbMinorVersion* = 0 #
-                       #      Explicit map components:
-                       #       - Used in the 'explicit' field of an XkbServerMap.  Specifies
-                       #         the keyboard components that should _not_ be updated automatically
-                       #         in response to core protocol keyboard mapping requests.
-                       #
-
-const
-  XkbExplicitKeyTypesMask* = 0x0000000F
-  XkbExplicitKeyType1Mask* = 1 shl 0
-  XkbExplicitKeyType2Mask* = 1 shl 1
-  XkbExplicitKeyType3Mask* = 1 shl 2
-  XkbExplicitKeyType4Mask* = 1 shl 3
-  XkbExplicitInterpretMask* = 1 shl 4
-  XkbExplicitAutoRepeatMask* = 1 shl 5
-  XkbExplicitBehaviorMask* = 1 shl 6
-  XkbExplicitVModMapMask* = 1 shl 7
-  XkbAllExplicitMask* = 0x000000FF #
-                                   #      Symbol interpretations flags:
-                                   #       - Used in the flags field of a symbol interpretation
-                                   #
-
-const
-  XkbSI_AutoRepeat* = 1 shl 0
-  XkbSI_LockingKey* = 1 shl 1 #
-                              #      Symbol interpretations match specification:
-                              #       - Used in the match field of a symbol interpretation to specify
-                              #         the conditions under which an interpretation is used.
-                              #
-
-const
-  XkbSI_LevelOneOnly* = 0x00000080
-  XkbSI_OpMask* = 0x0000007F
-  XkbSI_NoneOf* = 0
-  XkbSI_AnyOfOrNone* = 1
-  XkbSI_AnyOf* = 2
-  XkbSI_AllOf* = 3
-  XkbSI_Exactly* = 4 #
-                     #      Indicator map flags:
-                     #       - Used in the flags field of an indicator map to indicate the
-                     #         conditions under which and indicator can be changed and the
-                     #         effects of changing the indicator.
-                     #
-
-const
-  XkbIM_NoExplicit* = int(1) shl 7
-  XkbIM_NoAutomatic* = int(1) shl 6
-  XkbIM_LEDDrivesKB* = int(1) shl 5 #
-                                    #      Indicator map component specifications:
-                                    #       - Used by the 'which_groups' and 'which_mods' fields of an indicator
-                                    #         map to specify which keyboard components should be used to drive
-                                    #         the indicator.
-                                    #
-
-const
-  XkbIM_UseBase* = int(1) shl 0
-  XkbIM_UseLatched* = int(1) shl 1
-  XkbIM_UseLocked* = int(1) shl 2
-  XkbIM_UseEffective* = int(1) shl 3
-  XkbIM_UseCompat* = int(1) shl 4
-  XkbIM_UseNone* = 0
-  XkbIM_UseAnyGroup* = XkbIM_UseBase or XkbIM_UseLatched or XkbIM_UseLocked or
-      XkbIM_UseEffective
-  XkbIM_UseAnyMods* = XkbIM_UseAnyGroup or XkbIM_UseCompat #
-                                                           #      GetByName components:
-                                                           #       - Specifies desired or necessary components to GetKbdByName request.
-                                                           #       - Reports the components that were found in a GetKbdByNameReply
-                                                           #
-
-const
-  XkbGBN_TypesMask* = int(1) shl 0
-  XkbGBN_CompatMapMask* = int(1) shl 1
-  XkbGBN_ClientSymbolsMask* = int(1) shl 2
-  XkbGBN_ServerSymbolsMask* = int(1) shl 3
-  XkbGBN_SymbolsMask* = XkbGBN_ClientSymbolsMask or XkbGBN_ServerSymbolsMask
-  XkbGBN_IndicatorMapMask* = int(1) shl 4
-  XkbGBN_KeyNamesMask* = int(1) shl 5
-  XkbGBN_GeometryMask* = int(1) shl 6
-  XkbGBN_OtherNamesMask* = int(1) shl 7
-  XkbGBN_AllComponentsMask* = 0x000000FF #
-                                         #       ListComponents flags
-                                         #
-
-const
-  XkbLC_Hidden* = int(1) shl 0
-  XkbLC_Default* = int(1) shl 1
-  XkbLC_Partial* = int(1) shl 2
-  XkbLC_AlphanumericKeys* = int(1) shl 8
-  XkbLC_ModifierKeys* = int(1) shl 9
-  XkbLC_KeypadKeys* = int(1) shl 10
-  XkbLC_FunctionKeys* = int(1) shl 11
-  XkbLC_AlternateGroup* = int(1) shl 12 #
-                                        #      X Input Extension Interactions
-                                        #      - Specifies the possible interactions between XKB and the X input
-                                        #        extension
-                                        #      - Used to request (XkbGetDeviceInfo) or change (XKbSetDeviceInfo)
-                                        #        XKB information about an extension device.
-                                        #      - Reports the list of supported optional features in the reply to
-                                        #        XkbGetDeviceInfo or in an XkbExtensionDeviceNotify event.
-                                        #      XkbXI_UnsupportedFeature is reported in XkbExtensionDeviceNotify
-                                        #      events to indicate an attempt to use an unsupported feature.
-                                        #
-
-const
-  XkbXI_KeyboardsMask* = int(1) shl 0
-  XkbXI_ButtonActionsMask* = int(1) shl 1
-  XkbXI_IndicatorNamesMask* = int(1) shl 2
-  XkbXI_IndicatorMapsMask* = int(1) shl 3
-  XkbXI_IndicatorStateMask* = int(1) shl 4
-  XkbXI_UnsupportedFeatureMask* = int(1) shl 15
-  XkbXI_AllFeaturesMask* = 0x0000001F
-  XkbXI_AllDeviceFeaturesMask* = 0x0000001E
-  XkbXI_IndicatorsMask* = 0x0000001C
-  XkbAllExtensionDeviceEventsMask* = 0x0000801F #
-                                                #      Per-Client Flags:
-                                                #       - Specifies flags to be changed by the PerClientFlags request.
-                                                #
-
-const
-  XkbPCF_DetectableAutoRepeatMask* = int(1) shl 0
-  XkbPCF_GrabsUseXKBStateMask* = int(1) shl 1
-  XkbPCF_AutoResetControlsMask* = int(1) shl 2
-  XkbPCF_LookupStateWhenGrabbed* = int(1) shl 3
-  XkbPCF_SendEventUsesXKBState* = int(1) shl 4
-  XkbPCF_AllFlagsMask* = 0x0000001F #
-                                    #      Debugging flags and controls
-                                    #
-
-const
-  XkbDF_DisableLocks* = 1 shl 0
-
-type
-  PXkbPropertyPtr* = ptr TXkbPropertyRec
-  TXkbPropertyRec*{.final.} = object
-    name*: cstring
-    value*: cstring
-
-
-type
-  PXkbColorPtr* = ptr TXkbColorRec
-  TXkbColorRec*{.final.} = object
-    pixel*: int16
-    spec*: cstring
-
-
-type
-  PXkbPointPtr* = ptr TXkbPointRec
-  TXkbPointRec*{.final.} = object
-    x*: int16
-    y*: int16
-
-
-type
-  PXkbBoundsPtr* = ptr TXkbBoundsRec
-  TXkbBoundsRec*{.final.} = object
-    x1*: int16
-    y1*: int16
-    x2*: int16
-    y2*: int16
-
-
-proc XkbBoundsWidth*(b: PXkbBoundsPtr): int16
-proc XkbBoundsHeight*(b: PXkbBoundsPtr): int16
-type
-  PXkbOutlinePtr* = ptr TXkbOutlineRec
-  TXkbOutlineRec*{.final.} = object
-    num_points*: int16
-    sz_points*: int16
-    corner_radius*: int16
-    points*: PXkbPointPtr
-
-
-type
-  PXkbShapePtr* = ptr TXkbShapeRec
-  TXkbShapeRec*{.final.} = object
-    name*: TAtom
-    num_outlines*: int16
-    sz_outlines*: int16
-    outlines*: ptr array [0..0xffff, TXkbOutlineRec]
-    approx*: ptr array[0..0xffff, TXkbOutlineRec]
-    primary*: ptr array[0..0xffff, TXkbOutlineRec]
-    bounds*: TXkbBoundsRec
-
-
-proc XkbOutlineIndex*(s: PXkbShapePtr, o: PXkbOutlinePtr): int32
-type
-  PXkbShapeDoodadPtr* = ptr TXkbShapeDoodadRec
-  TXkbShapeDoodadRec*{.final.} = object
-    name*: TAtom
-    theType*: int8
-    priority*: int8
-    top*: int16
-    left*: int16
-    angle*: int16
-    color_ndx*: int16
-    shape_ndx*: int16
-
-
-type
-  PXkbTextDoodadPtr* = ptr TXkbTextDoodadRec
-  TXkbTextDoodadRec*{.final.} = object
-    name*: TAtom
-    theType*: int8
-    priority*: int8
-    top*: int16
-    left*: int16
-    angle*: int16
-    width*: int16
-    height*: int16
-    color_ndx*: int16
-    text*: cstring
-    font*: cstring
-
-
-type
-  PXkbIndicatorDoodadPtr* = ptr TXkbIndicatorDoodadRec
-  TXkbIndicatorDoodadRec*{.final.} = object
-    name*: TAtom
-    theType*: int8
-    priority*: int8
-    top*: int16
-    left*: int16
-    angle*: int16
-    shape_ndx*: int16
-    on_color_ndx*: int16
-    off_color_ndx*: int16
-
-
-type
-  PXkbLogoDoodadPtr* = ptr TXkbLogoDoodadRec
-  TXkbLogoDoodadRec*{.final.} = object
-    name*: TAtom
-    theType*: int8
-    priority*: int8
-    top*: int16
-    left*: int16
-    angle*: int16
-    color_ndx*: int16
-    shape_ndx*: int16
-    logo_name*: cstring
-
-
-type
-  PXkbAnyDoodadPtr* = ptr TXkbAnyDoodadRec
-  TXkbAnyDoodadRec*{.final.} = object
-    name*: TAtom
-    theType*: int8
-    priority*: int8
-    top*: int16
-    left*: int16
-    angle*: int16
-
-
-type
-  PXkbDoodadPtr* = ptr TXkbDoodadRec
-  TXkbDoodadRec*{.final.} = object
-    any*: TXkbAnyDoodadRec
-    shape*: TXkbShapeDoodadRec
-    text*: TXkbTextDoodadRec
-    indicator*: TXkbIndicatorDoodadRec
-    logo*: TXkbLogoDoodadRec
-
-
-const
-  XkbUnknownDoodad* = 0
-  XkbOutlineDoodad* = 1
-  XkbSolidDoodad* = 2
-  XkbTextDoodad* = 3
-  XkbIndicatorDoodad* = 4
-  XkbLogoDoodad* = 5
-
-type
-  PXkbKeyPtr* = ptr TXkbKeyRec
-  TXkbKeyRec*{.final.} = object
-    name*: TXkbKeyNameRec
-    gap*: int16
-    shape_ndx*: int8
-    color_ndx*: int8
-
-
-type
-  PXkbRowPtr* = ptr TXkbRowRec
-  TXkbRowRec*{.final.} = object
-    top*: int16
-    left*: int16
-    num_keys*: int16
-    sz_keys*: int16
-    vertical*: int16
-    Keys*: PXkbKeyPtr
-    bounds*: TXkbBoundsRec
-
-
-type
-  PXkbOverlayPtr* = ptr TXkbOverlayRec #forward for TXkbSectionRec use.
-                                       #Do not add more "type"
-  PXkbSectionPtr* = ptr TXkbSectionRec
-  TXkbSectionRec*{.final.} = object  #Do not add more "type"
-    name*: TAtom
-    priority*: int8
-    top*: int16
-    left*: int16
-    width*: int16
-    height*: int16
-    angle*: int16
-    num_rows*: int16
-    num_doodads*: int16
-    num_overlays*: int16
-    rows*: PXkbRowPtr
-    doodads*: PXkbDoodadPtr
-    bounds*: TXkbBoundsRec
-    overlays*: PXkbOverlayPtr
-
-  PXkbOverlayKeyPtr* = ptr TXkbOverlayKeyRec
-  TXkbOverlayKeyRec*{.final.} = object  #Do not add more "type"
-    over*: TXkbKeyNameRec
-    under*: TXkbKeyNameRec
-
-  PXkbOverlayRowPtr* = ptr TXkbOverlayRowRec
-  TXkbOverlayRowRec*{.final.} = object  #Do not add more "type"
-    row_under*: int16
-    num_keys*: int16
-    sz_keys*: int16
-    keys*: PXkbOverlayKeyPtr
-
-  TXkbOverlayRec*{.final.} = object
-    name*: TAtom
-    section_under*: PXkbSectionPtr
-    num_rows*: int16
-    sz_rows*: int16
-    rows*: PXkbOverlayRowPtr
-    bounds*: PXkbBoundsPtr
-
-
-type
-  PXkbGeometryRec* = ptr TXkbGeometryRec
-  PXkbGeometryPtr* = PXkbGeometryRec
-  TXkbGeometryRec*{.final.} = object
-    name*: TAtom
-    width_mm*: int16
-    height_mm*: int16
-    label_font*: cstring
-    label_color*: PXkbColorPtr
-    base_color*: PXkbColorPtr
-    sz_properties*: int16
-    sz_colors*: int16
-    sz_shapes*: int16
-    sz_sections*: int16
-    sz_doodads*: int16
-    sz_key_aliases*: int16
-    num_properties*: int16
-    num_colors*: int16
-    num_shapes*: int16
-    num_sections*: int16
-    num_doodads*: int16
-    num_key_aliases*: int16
-    properties*: ptr array[0..0xffff, TXkbPropertyRec]
-    colors*: ptr array[0..0xffff, TXkbColorRec]
-    shapes*: ptr array[0..0xffff, TXkbShapeRec]
-    sections*: ptr array[0..0xffff, TXkbSectionRec]
-    key_aliases*: ptr array[0..0xffff, TXkbKeyAliasRec]
-
-
-const
-  XkbGeomPropertiesMask* = 1 shl 0
-  XkbGeomColorsMask* = 1 shl 1
-  XkbGeomShapesMask* = 1 shl 2
-  XkbGeomSectionsMask* = 1 shl 3
-  XkbGeomDoodadsMask* = 1 shl 4
-  XkbGeomKeyAliasesMask* = 1 shl 5
-  XkbGeomAllMask* = 0x0000003F
-
-type
-  PXkbGeometrySizesPtr* = ptr TXkbGeometrySizesRec
-  TXkbGeometrySizesRec*{.final.} = object  #
-                                           #          Tie it all together into one big keyboard description
-                                           #
-    which*: int16
-    num_properties*: int16
-    num_colors*: int16
-    num_shapes*: int16
-    num_sections*: int16
-    num_doodads*: int16
-    num_key_aliases*: int16
-
-
-type
-  PXkbDescPtr* = ptr TXkbDescRec
-  TXkbDescRec*{.final.} = object
-    dpy*: PDisplay
-    flags*: int16
-    device_spec*: int16
-    min_key_code*: TKeyCode
-    max_key_code*: TKeyCode
-    ctrls*: PXkbControlsPtr
-    server*: PXkbServerMapPtr
-    map*: PXkbClientMapPtr
-    indicators*: PXkbIndicatorPtr
-    names*: PXkbNamesPtr
-    compat*: PXkbCompatMapPtr
-    geom*: PXkbGeometryPtr
-
-
-proc XkbKeyKeyTypeIndex*(d: PXkbDescPtr, k: int16, g: int8): int8
-proc XkbKeyKeyType*(d: PXkbDescPtr, k: int16, g: int8): PXkbKeyTypePtr
-proc XkbKeyGroupWidth*(d: PXkbDescPtr, k: int16, g: int8): int8
-proc XkbKeyGroupsWidth*(d: PXkbDescPtr, k: int16): int8
-proc XkbKeyGroupInfo*(d: PXkbDescPtr, k: int16): int8
-proc XkbKeyNumGroups*(d: PXkbDescPtr, k: int16): int8
-proc XkbKeyNumSyms*(d: PXkbDescPtr, k: int16): int16
-proc XkbKeySym*(d: PXkbDescPtr, k: int16, n: int16): TKeySym
-proc XkbKeySymEntry*(d: PXkbDescPtr, k: int16, sl: int16, g: int8): TKeySym
-proc XkbKeyAction*(d: PXkbDescPtr, k: int16, n: int16): PXkbAction
-proc XkbKeyActionEntry*(d: PXkbDescPtr, k: int16, sl: int16, g: int8): int8
-proc XkbKeyHasActions*(d: PXkbDescPtr, k: int16): bool
-proc XkbKeyNumActions*(d: PXkbDescPtr, k: int16): int16
-proc XkbKeyActionsPtr*(d: PXkbDescPtr, k: int16): PXkbAction
-proc XkbKeycodeInRange*(d: PXkbDescPtr, k: int16): bool
-proc XkbNumKeys*(d: PXkbDescPtr): int8
-  #
-  #          The following structures can be used to track changes
-  #          to a keyboard device
-  #
-type
-  PXkbMapChangesPtr* = ptr TXkbMapChangesRec
-  TXkbMapChangesRec*{.final.} = object
-    changed*: int16
-    min_key_code*: TKeyCode
-    max_key_code*: TKeyCode
-    first_type*: int8
-    num_types*: int8
-    first_key_sym*: TKeyCode
-    num_key_syms*: int8
-    first_key_act*: TKeyCode
-    num_key_acts*: int8
-    first_key_behavior*: TKeyCode
-    num_key_behaviors*: int8
-    first_key_explicit*: TKeyCode
-    num_key_explicit*: int8
-    first_modmap_key*: TKeyCode
-    num_modmap_keys*: int8
-    first_vmodmap_key*: TKeyCode
-    num_vmodmap_keys*: int8
-    pad*: int8
-    vmods*: int16
-
-
-type
-  PXkbControlsChangesPtr* = ptr TXkbControlsChangesRec
-  TXkbControlsChangesRec*{.final.} = object
-    changed_ctrls*: int16
-    enabled_ctrls_changes*: int16
-    num_groups_changed*: bool
-
-
-type
-  PXkbIndicatorChangesPtr* = ptr TXkbIndicatorChangesRec
-  TXkbIndicatorChangesRec*{.final.} = object
-    state_changes*: int16
-    map_changes*: int16
-
-
-type
-  PXkbNameChangesPtr* = ptr TXkbNameChangesRec
-  TXkbNameChangesRec*{.final.} = object
-    changed*: int16
-    first_type*: int8
-    num_types*: int8
-    first_lvl*: int8
-    num_lvls*: int8
-    num_aliases*: int8
-    num_rg*: int8
-    first_key*: int8
-    num_keys*: int8
-    changed_vmods*: int16
-    changed_indicators*: int32
-    changed_groups*: int8
-
-
-type
-  PXkbCompatChangesPtr* = ptr TXkbCompatChangesRec
-  TXkbCompatChangesRec*{.final.} = object
-    changed_groups*: int8
-    first_si*: int16
-    num_si*: int16
-
-
-type
-  PXkbChangesPtr* = ptr TXkbChangesRec
-  TXkbChangesRec*{.final.} = object  #
-                                     #          These data structures are used to construct a keymap from
-                                     #          a set of components or to list components in the server
-                                     #          database.
-                                     #
-    device_spec*: int16
-    state_changes*: int16
-    map*: TXkbMapChangesRec
-    ctrls*: TXkbControlsChangesRec
-    indicators*: TXkbIndicatorChangesRec
-    names*: TXkbNameChangesRec
-    compat*: TXkbCompatChangesRec
-
-
-type
-  PXkbComponentNamesPtr* = ptr TXkbComponentNamesRec
-  TXkbComponentNamesRec*{.final.} = object
-    keymap*: ptr int16
-    keycodes*: ptr int16
-    types*: ptr int16
-    compat*: ptr int16
-    symbols*: ptr int16
-    geometry*: ptr int16
-
-
-type
-  PXkbComponentNamePtr* = ptr TXkbComponentNameRec
-  TXkbComponentNameRec*{.final.} = object
-    flags*: int16
-    name*: cstring
-
-
-type
-  PXkbComponentListPtr* = ptr TXkbComponentListRec
-  TXkbComponentListRec*{.final.} = object  #
-                                           #          The following data structures describe and track changes to a
-                                           #          non-keyboard extension device
-                                           #
-    num_keymaps*: int16
-    num_keycodes*: int16
-    num_types*: int16
-    num_compat*: int16
-    num_symbols*: int16
-    num_geometry*: int16
-    keymaps*: PXkbComponentNamePtr
-    keycodes*: PXkbComponentNamePtr
-    types*: PXkbComponentNamePtr
-    compat*: PXkbComponentNamePtr
-    symbols*: PXkbComponentNamePtr
-    geometry*: PXkbComponentNamePtr
-
-
-type
-  PXkbDeviceLedInfoPtr* = ptr TXkbDeviceLedInfoRec
-  TXkbDeviceLedInfoRec*{.final.} = object
-    led_class*: int16
-    led_id*: int16
-    phys_indicators*: int16
-    maps_present*: int16
-    names_present*: int16
-    state*: int16
-    names*: array[0..XkbNumIndicators - 1, TAtom]
-    maps*: array[0..XkbNumIndicators - 1, TXkbIndicatorMapRec]
-
-
-type
-  PXkbDeviceInfoPtr* = ptr TXkbDeviceInfoRec
-  TXkbDeviceInfoRec*{.final.} = object
-    name*: cstring
-    theType*: TAtom
-    device_spec*: int16
-    has_own_state*: bool
-    supported*: int16
-    unsupported*: int16
-    num_btns*: int16
-    btn_acts*: PXkbAction
-    sz_leds*: int16
-    num_leds*: int16
-    dflt_kbd_fb*: int16
-    dflt_led_fb*: int16
-    leds*: PXkbDeviceLedInfoPtr
-
-
-proc XkbXI_DevHasBtnActs*(d: PXkbDeviceInfoPtr): bool
-proc XkbXI_LegalDevBtn*(d: PXkbDeviceInfoPtr, b: int16): bool
-proc XkbXI_DevHasLeds*(d: PXkbDeviceInfoPtr): bool
-type
-  PXkbDeviceLedChangesPtr* = ptr TXkbDeviceLedChangesRec
-  TXkbDeviceLedChangesRec*{.final.} = object
-    led_class*: int16
-    led_id*: int16
-    defined*: int16           #names or maps changed
-    next*: PXkbDeviceLedChangesPtr
-
-
-type
-  PXkbDeviceChangesPtr* = ptr TXkbDeviceChangesRec
-  TXkbDeviceChangesRec*{.final.} = object
-    changed*: int16
-    first_btn*: int16
-    num_btns*: int16
-    leds*: TXkbDeviceLedChangesRec
-
-
-proc XkbShapeDoodadColor*(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr): PXkbColorPtr
-proc XkbShapeDoodadShape*(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr): PXkbShapePtr
-proc XkbSetShapeDoodadColor*(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr,
-                             c: PXkbColorPtr)
-proc XkbSetShapeDoodadShape*(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr,
-                             s: PXkbShapePtr)
-proc XkbTextDoodadColor*(g: PXkbGeometryPtr, d: PXkbTextDoodadPtr): PXkbColorPtr
-proc XkbSetTextDoodadColor*(g: PXkbGeometryPtr, d: PXkbTextDoodadPtr,
-                            c: PXkbColorPtr)
-proc XkbIndicatorDoodadShape*(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr): PXkbShapeDoodadPtr
-proc XkbIndicatorDoodadOnColor*(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr): PXkbColorPtr
-proc XkbIndicatorDoodadOffColor*(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr): PXkbColorPtr
-proc XkbSetIndicatorDoodadOnColor*(g: PXkbGeometryPtr,
-                                   d: PXkbIndicatorDoodadPtr, c: PXkbColorPtr)
-proc XkbSetIndicatorDoodadOffColor*(g: PXkbGeometryPtr,
-                                    d: PXkbIndicatorDoodadPtr, c: PXkbColorPtr)
-proc XkbSetIndicatorDoodadShape*(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr,
-                                 s: PXkbShapeDoodadPtr)
-proc XkbLogoDoodadColor*(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr): PXkbColorPtr
-proc XkbLogoDoodadShape*(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr): PXkbShapeDoodadPtr
-proc XkbSetLogoDoodadColor*(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr,
-                            c: PXkbColorPtr)
-proc XkbSetLogoDoodadShape*(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr,
-                            s: PXkbShapeDoodadPtr)
-proc XkbKeyShape*(g: PXkbGeometryPtr, k: PXkbKeyPtr): PXkbShapeDoodadPtr
-proc XkbKeyColor*(g: PXkbGeometryPtr, k: PXkbKeyPtr): PXkbColorPtr
-proc XkbSetKeyShape*(g: PXkbGeometryPtr, k: PXkbKeyPtr, s: PXkbShapeDoodadPtr)
-proc XkbSetKeyColor*(g: PXkbGeometryPtr, k: PXkbKeyPtr, c: PXkbColorPtr)
-proc XkbGeomColorIndex*(g: PXkbGeometryPtr, c: PXkbColorPtr): int32
-proc XkbAddGeomProperty*(geom: PXkbGeometryPtr, name: cstring, value: cstring): PXkbPropertyPtr{.
-    libx11c, importc: "XkbAddGeomProperty".}
-proc XkbAddGeomKeyAlias*(geom: PXkbGeometryPtr, alias: cstring, float: cstring): PXkbKeyAliasPtr{.
-    libx11c, importc: "XkbAddGeomKeyAlias".}
-proc XkbAddGeomColor*(geom: PXkbGeometryPtr, spec: cstring, pixel: int16): PXkbColorPtr{.
-    libx11c, importc: "XkbAddGeomColor".}
-proc XkbAddGeomOutline*(shape: PXkbShapePtr, sz_points: int16): PXkbOutlinePtr{.
-    libx11c, importc: "XkbAddGeomOutline".}
-proc XkbAddGeomShape*(geom: PXkbGeometryPtr, name: TAtom, sz_outlines: int16): PXkbShapePtr{.
-    libx11c, importc: "XkbAddGeomShape".}
-proc XkbAddGeomKey*(row: PXkbRowPtr): PXkbKeyPtr{.libx11c,
-    importc: "XkbAddGeomKey".}
-proc XkbAddGeomRow*(section: PXkbSectionPtr, sz_keys: int16): PXkbRowPtr{.libx11c, importc: "XkbAddGeomRow".}
-proc XkbAddGeomSection*(geom: PXkbGeometryPtr, name: TAtom, sz_rows: int16,
-                        sz_doodads: int16, sz_overlays: int16): PXkbSectionPtr{.
-    libx11c, importc: "XkbAddGeomSection".}
-proc XkbAddGeomOverlay*(section: PXkbSectionPtr, name: TAtom, sz_rows: int16): PXkbOverlayPtr{.
-    libx11c, importc: "XkbAddGeomOverlay".}
-proc XkbAddGeomOverlayRow*(overlay: PXkbOverlayPtr, row_under: int16,
-                           sz_keys: int16): PXkbOverlayRowPtr{.libx11c, importc: "XkbAddGeomOverlayRow".}
-proc XkbAddGeomOverlayKey*(overlay: PXkbOverlayPtr, row: PXkbOverlayRowPtr,
-                           over: cstring, under: cstring): PXkbOverlayKeyPtr{.
-    libx11c, importc: "XkbAddGeomOverlayKey".}
-proc XkbAddGeomDoodad*(geom: PXkbGeometryPtr, section: PXkbSectionPtr,
-                       name: TAtom): PXkbDoodadPtr{.libx11c,
-    importc: "XkbAddGeomDoodad".}
-proc XkbFreeGeomKeyAliases*(geom: PXkbGeometryPtr, first: int16, count: int16,
-                            freeAll: bool){.libx11c,
-    importc: "XkbFreeGeomKeyAliases".}
-proc XkbFreeGeomColors*(geom: PXkbGeometryPtr, first: int16, count: int16,
-                        freeAll: bool){.libx11c,
-                                        importc: "XkbFreeGeomColors".}
-proc XkbFreeGeomDoodads*(doodads: PXkbDoodadPtr, nDoodads: int16, freeAll: bool){.
-    libx11c, importc: "XkbFreeGeomDoodads".}
-proc XkbFreeGeomProperties*(geom: PXkbGeometryPtr, first: int16, count: int16,
-                            freeAll: bool){.libx11c,
-    importc: "XkbFreeGeomProperties".}
-proc XkbFreeGeomOverlayKeys*(row: PXkbOverlayRowPtr, first: int16, count: int16,
-                             freeAll: bool){.libx11c,
-    importc: "XkbFreeGeomOverlayKeys".}
-proc XkbFreeGeomOverlayRows*(overlay: PXkbOverlayPtr, first: int16,
-                             count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomOverlayRows".}
-proc XkbFreeGeomOverlays*(section: PXkbSectionPtr, first: int16, count: int16,
-                          freeAll: bool){.libx11c,
-    importc: "XkbFreeGeomOverlays".}
-proc XkbFreeGeomKeys*(row: PXkbRowPtr, first: int16, count: int16, freeAll: bool){.
-    libx11c, importc: "XkbFreeGeomKeys".}
-proc XkbFreeGeomRows*(section: PXkbSectionPtr, first: int16, count: int16,
-                      freeAll: bool){.libx11c,
-                                      importc: "XkbFreeGeomRows".}
-proc XkbFreeGeomSections*(geom: PXkbGeometryPtr, first: int16, count: int16,
-                          freeAll: bool){.libx11c,
-    importc: "XkbFreeGeomSections".}
-proc XkbFreeGeomPoints*(outline: PXkbOutlinePtr, first: int16, count: int16,
-                        freeAll: bool){.libx11c,
-                                        importc: "XkbFreeGeomPoints".}
-proc XkbFreeGeomOutlines*(shape: PXkbShapePtr, first: int16, count: int16,
-                          freeAll: bool){.libx11c,
-    importc: "XkbFreeGeomOutlines".}
-proc XkbFreeGeomShapes*(geom: PXkbGeometryPtr, first: int16, count: int16,
-                        freeAll: bool){.libx11c,
-                                        importc: "XkbFreeGeomShapes".}
-proc XkbFreeGeometry*(geom: PXkbGeometryPtr, which: int16, freeMap: bool){.
-    libx11c, importc: "XkbFreeGeometry".}
-proc XkbAllocGeomProps*(geom: PXkbGeometryPtr, nProps: int16): TStatus{.libx11c, importc: "XkbAllocGeomProps".}
-proc XkbAllocGeomKeyAliases*(geom: PXkbGeometryPtr, nAliases: int16): TStatus{.
-    libx11c, importc: "XkbAllocGeomKeyAliases".}
-proc XkbAllocGeomColors*(geom: PXkbGeometryPtr, nColors: int16): TStatus{.libx11c, importc: "XkbAllocGeomColors".}
-proc XkbAllocGeomShapes*(geom: PXkbGeometryPtr, nShapes: int16): TStatus{.libx11c, importc: "XkbAllocGeomShapes".}
-proc XkbAllocGeomSections*(geom: PXkbGeometryPtr, nSections: int16): TStatus{.
-    libx11c, importc: "XkbAllocGeomSections".}
-proc XkbAllocGeomOverlays*(section: PXkbSectionPtr, num_needed: int16): TStatus{.
-    libx11c, importc: "XkbAllocGeomOverlays".}
-proc XkbAllocGeomOverlayRows*(overlay: PXkbOverlayPtr, num_needed: int16): TStatus{.
-    libx11c, importc: "XkbAllocGeomOverlayRows".}
-proc XkbAllocGeomOverlayKeys*(row: PXkbOverlayRowPtr, num_needed: int16): TStatus{.
-    libx11c, importc: "XkbAllocGeomOverlayKeys".}
-proc XkbAllocGeomDoodads*(geom: PXkbGeometryPtr, nDoodads: int16): TStatus{.
-    libx11c, importc: "XkbAllocGeomDoodads".}
-proc XkbAllocGeomSectionDoodads*(section: PXkbSectionPtr, nDoodads: int16): TStatus{.
-    libx11c, importc: "XkbAllocGeomSectionDoodads".}
-proc XkbAllocGeomOutlines*(shape: PXkbShapePtr, nOL: int16): TStatus{.libx11c, importc: "XkbAllocGeomOutlines".}
-proc XkbAllocGeomRows*(section: PXkbSectionPtr, nRows: int16): TStatus{.libx11c, importc: "XkbAllocGeomRows".}
-proc XkbAllocGeomPoints*(ol: PXkbOutlinePtr, nPts: int16): TStatus{.libx11c, importc: "XkbAllocGeomPoints".}
-proc XkbAllocGeomKeys*(row: PXkbRowPtr, nKeys: int16): TStatus{.libx11c, importc: "XkbAllocGeomKeys".}
-proc XkbAllocGeometry*(xkb: PXkbDescPtr, sizes: PXkbGeometrySizesPtr): TStatus{.
-    libx11c, importc: "XkbAllocGeometry".}
-proc XkbSetGeometryProc*(dpy: PDisplay, deviceSpec: int16, geom: PXkbGeometryPtr): TStatus{.
-    libx11c, importc: "XkbSetGeometry".}
-proc XkbComputeShapeTop*(shape: PXkbShapePtr, bounds: PXkbBoundsPtr): bool{.
-    libx11c, importc: "XkbComputeShapeTop".}
-proc XkbComputeShapeBounds*(shape: PXkbShapePtr): bool{.libx11c,
-    importc: "XkbComputeShapeBounds".}
-proc XkbComputeRowBounds*(geom: PXkbGeometryPtr, section: PXkbSectionPtr,
-                          row: PXkbRowPtr): bool{.libx11c,
-    importc: "XkbComputeRowBounds".}
-proc XkbComputeSectionBounds*(geom: PXkbGeometryPtr, section: PXkbSectionPtr): bool{.
-    libx11c, importc: "XkbComputeSectionBounds".}
-proc XkbFindOverlayForKey*(geom: PXkbGeometryPtr, wanted: PXkbSectionPtr,
-                           under: cstring): cstring{.libx11c,
-    importc: "XkbFindOverlayForKey".}
-proc XkbGetGeometryProc*(dpy: PDisplay, xkb: PXkbDescPtr): TStatus{.libx11c, importc: "XkbGetGeometry".}
-proc XkbGetNamedGeometry*(dpy: PDisplay, xkb: PXkbDescPtr, name: TAtom): TStatus{.
-    libx11c, importc: "XkbGetNamedGeometry".}
-when defined(XKB_IN_SERVER):
-  proc SrvXkbAddGeomKeyAlias*(geom: PXkbGeometryPtr, alias: cstring,
-                              float: cstring): PXkbKeyAliasPtr{.libx11c, importc: "XkbAddGeomKeyAlias".}
-  proc SrvXkbAddGeomColor*(geom: PXkbGeometryPtr, spec: cstring, pixel: int16): PXkbColorPtr{.
-      libx11c, importc: "XkbAddGeomColor".}
-  proc SrvXkbAddGeomDoodad*(geom: PXkbGeometryPtr, section: PXkbSectionPtr,
-                            name: TAtom): PXkbDoodadPtr{.libx11c,
-      importc: "XkbAddGeomDoodad".}
-  proc SrvXkbAddGeomKey*(geom: PXkbGeometryPtr, alias: cstring, float: cstring): PXkbKeyAliasPtr{.
-      libx11c, importc: "XkbAddGeomKeyAlias".}
-  proc SrvXkbAddGeomOutline*(shape: PXkbShapePtr, sz_points: int16): PXkbOutlinePtr{.
-      libx11c, importc: "XkbAddGeomOutline".}
-  proc SrvXkbAddGeomOverlay*(overlay: PXkbOverlayPtr, row: PXkbOverlayRowPtr,
-                             over: cstring, under: cstring): PXkbOverlayKeyPtr{.
-      libx11c, importc: "XkbAddGeomOverlayKey".}
-  proc SrvXkbAddGeomOverlayRow*(overlay: PXkbOverlayPtr, row_under: int16,
-                                sz_keys: int16): PXkbOverlayRowPtr{.libx11c, importc: "XkbAddGeomOverlayRow".}
-  proc SrvXkbAddGeomOverlayKey*(overlay: PXkbOverlayPtr, row: PXkbOverlayRowPtr,
-                                over: cstring, under: cstring): PXkbOverlayKeyPtr{.
-      libx11c, importc: "XkbAddGeomOverlayKey".}
-  proc SrvXkbAddGeomProperty*(geom: PXkbGeometryPtr, name: cstring,
-                              value: cstring): PXkbPropertyPtr{.libx11c, importc: "XkbAddGeomProperty".}
-  proc SrvXkbAddGeomRow*(section: PXkbSectionPtr, sz_keys: int16): PXkbRowPtr{.
-      libx11c, importc: "XkbAddGeomRow".}
-  proc SrvXkbAddGeomSection*(geom: PXkbGeometryPtr, name: TAtom, sz_rows: int16,
-                             sz_doodads: int16, sz_overlays: int16): PXkbSectionPtr{.
-      libx11c, importc: "XkbAddGeomSection".}
-  proc SrvXkbAddGeomShape*(geom: PXkbGeometryPtr, name: TAtom,
-                           sz_outlines: int16): PXkbShapePtr{.libx11c, importc: "XkbAddGeomShape".}
-  proc SrvXkbAllocGeomKeyAliases*(geom: PXkbGeometryPtr, nAliases: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomKeyAliases".}
-  proc SrvXkbAllocGeomColors*(geom: PXkbGeometryPtr, nColors: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomColors".}
-  proc SrvXkbAllocGeomDoodads*(geom: PXkbGeometryPtr, nDoodads: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomDoodads".}
-  proc SrvXkbAllocGeomKeys*(row: PXkbRowPtr, nKeys: int16): TStatus{.libx11c, importc: "XkbAllocGeomKeys".}
-  proc SrvXkbAllocGeomOutlines*(shape: PXkbShapePtr, nOL: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomOutlines".}
-  proc SrvXkbAllocGeomPoints*(ol: PXkbOutlinePtr, nPts: int16): TStatus{.libx11c, importc: "XkbAllocGeomPoints".}
-  proc SrvXkbAllocGeomProps*(geom: PXkbGeometryPtr, nProps: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomProps".}
-  proc SrvXkbAllocGeomRows*(section: PXkbSectionPtr, nRows: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomRows".}
-  proc SrvXkbAllocGeomSectionDoodads*(section: PXkbSectionPtr, nDoodads: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomSectionDoodads".}
-  proc SrvXkbAllocGeomSections*(geom: PXkbGeometryPtr, nSections: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomSections".}
-  proc SrvXkbAllocGeomOverlays*(section: PXkbSectionPtr, num_needed: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomOverlays".}
-  proc SrvXkbAllocGeomOverlayRows*(overlay: PXkbOverlayPtr, num_needed: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomOverlayRows".}
-  proc SrvXkbAllocGeomOverlayKeys*(row: PXkbOverlayRowPtr, num_needed: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomOverlayKeys".}
-  proc SrvXkbAllocGeomShapes*(geom: PXkbGeometryPtr, nShapes: int16): TStatus{.
-      libx11c, importc: "XkbAllocGeomShapes".}
-  proc SrvXkbAllocGeometry*(xkb: PXkbDescPtr, sizes: PXkbGeometrySizesPtr): TStatus{.
-      libx11c, importc: "XkbAllocGeometry".}
-  proc SrvXkbFreeGeomKeyAliases*(geom: PXkbGeometryPtr, first: int16,
-                                 count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomKeyAliases".}
-  proc SrvXkbFreeGeomColors*(geom: PXkbGeometryPtr, first: int16, count: int16,
-                             freeAll: bool){.libx11c,
-      importc: "XkbFreeGeomColors".}
-  proc SrvXkbFreeGeomDoodads*(doodads: PXkbDoodadPtr, nDoodads: int16,
-                              freeAll: bool){.libx11c,
-      importc: "XkbFreeGeomDoodads".}
-  proc SrvXkbFreeGeomProperties*(geom: PXkbGeometryPtr, first: int16,
-                                 count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomProperties".}
-  proc SrvXkbFreeGeomOverlayKeys*(row: PXkbOverlayRowPtr, first: int16,
-                                  count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomOverlayKeys".}
-  proc SrvXkbFreeGeomOverlayRows*(overlay: PXkbOverlayPtr, first: int16,
-                                  count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomOverlayRows".}
-  proc SrvXkbFreeGeomOverlays*(section: PXkbSectionPtr, first: int16,
-                               count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomOverlays".}
-  proc SrvXkbFreeGeomKeys*(row: PXkbRowPtr, first: int16, count: int16,
-                           freeAll: bool){.libx11c,
-      importc: "XkbFreeGeomKeys".}
-  proc SrvXkbFreeGeomRows*(section: PXkbSectionPtr, first: int16, count: int16,
-                           freeAll: bool){.libx11c,
-      importc: "XkbFreeGeomRows".}
-  proc SrvXkbFreeGeomSections*(geom: PXkbGeometryPtr, first: int16,
-                               count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomSections".}
-  proc SrvXkbFreeGeomPoints*(outline: PXkbOutlinePtr, first: int16,
-                             count: int16, freeAll: bool){.libx11c, importc: "XkbFreeGeomPoints".}
-  proc SrvXkbFreeGeomOutlines*(shape: PXkbShapePtr, first: int16, count: int16,
-                               freeAll: bool){.libx11c,
-      importc: "XkbFreeGeomOutlines".}
-  proc SrvXkbFreeGeomShapes*(geom: PXkbGeometryPtr, first: int16, count: int16,
-                             freeAll: bool){.libx11c,
-      importc: "XkbFreeGeomShapes".}
-  proc SrvXkbFreeGeometry*(geom: PXkbGeometryPtr, which: int16, freeMap: bool){.
-      libx11c, importc: "XkbFreeGeometry".}
-# implementation
-
-import                        #************************************ xkb ************************************
-  xi
-
-proc XkbLegalXILedClass(c: int): bool =
-  ##define XkbLegalXILedClass(c) (((c)==KbdFeedbackClass)||((c)==LedFeedbackClass)||
-  #                                ((c)==XkbDfltXIClass)||((c)==XkbAllXIClasses))
-  result = (c == KbdFeedbackClass) or (c == LedFeedbackClass) or
-      (c == XkbDfltXIClass) or (c == XkbAllXIClasses)
-
-proc XkbLegalXIBellClass(c: int): bool =
-  ##define XkbLegalXIBellClass(c) (((c)==KbdFeedbackClass)||((c)==BellFeedbackClass)||
-  #                                 ((c)==XkbDfltXIClass)||((c)==XkbAllXIClasses))
-  result = (c == KbdFeedbackClass) or (c == BellFeedbackClass) or
-      (c == XkbDfltXIClass) or (c == XkbAllXIClasses)
-
-proc XkbExplicitXIDevice(c: int): bool =
-  ##define XkbExplicitXIDevice(c) (((c)&(~0xff))==0)
-  result = (c and (not 0x000000FF)) == 0
-
-proc XkbExplicitXIClass(c: int): bool =
-  ##define XkbExplicitXIClass(c) (((c)&(~0xff))==0)
-  result = (c and (not 0x000000FF)) == 0
-
-proc XkbExplicitXIId(c: int): bool =
-  ##define XkbExplicitXIId(c) (((c)&(~0xff))==0)
-  result = (c and (not 0x000000FF)) == 0
-
-proc XkbSingleXIClass(c: int): bool =
-  ##define XkbSingleXIClass(c) ((((c)&(~0xff))==0)||((c)==XkbDfltXIClass))
-  result = ((c and (not 0x000000FF)) == 0) or (c == XkbDfltXIClass)
-
-proc XkbSingleXIId(c: int): bool =
-  ##define XkbSingleXIId(c) ((((c)&(~0xff))==0)||((c)==XkbDfltXIId))
-  result = ((c and (not 0x000000FF)) == 0) or (c == XkbDfltXIId)
-
-proc XkbBuildCoreState(m, g: int): int =
-  ##define XkbBuildCoreState(m,g) ((((g)&0x3)<<13)|((m)&0xff))
-  result = ((g and 0x00000003) shl 13) or (m and 0x000000FF)
-
-proc XkbGroupForCoreState(s: int): int =
-  ##define XkbGroupForCoreState(s) (((s)>>13)&0x3)
-  result = (s shr 13) and 0x00000003
-
-proc XkbIsLegalGroup(g: int): bool =
-  ##define XkbIsLegalGroup(g) (((g)>=0)&&((g)<XkbNumKbdGroups))
-  result = (g >= 0) and (g < XkbNumKbdGroups)
-
-proc XkbSA_ValOp(a: int): int =
-  ##define XkbSA_ValOp(a) ((a)&XkbSA_ValOpMask)
-  result = a and XkbSA_ValOpMask
-
-proc XkbSA_ValScale(a: int): int =
-  ##define XkbSA_ValScale(a) ((a)&XkbSA_ValScaleMask)
-  result = a and XkbSA_ValScaleMask
-
-proc XkbIsModAction(a: PXkbAnyAction): bool =
-  ##define XkbIsModAction(a) (((a)->type>=Xkb_SASetMods)&&((a)->type<=XkbSA_LockMods))
-  result = (ze(a.theType) >= XkbSA_SetMods) and (ze(a.theType) <= XkbSA_LockMods)
-
-proc XkbIsGroupAction(a: PXkbAnyAction): bool =
-  ##define XkbIsGroupAction(a) (((a)->type>=XkbSA_SetGroup)&&((a)->type<=XkbSA_LockGroup))
-  result = (ze(a.theType) >= XkbSA_SetGroup) or (ze(a.theType) <= XkbSA_LockGroup)
-
-proc XkbIsPtrAction(a: PXkbAnyAction): bool =
-  ##define XkbIsPtrAction(a) (((a)->type>=XkbSA_MovePtr)&&((a)->type<=XkbSA_SetPtrDflt))
-  result = (ze(a.theType) >= XkbSA_MovePtr) and
-      (ze(a.theType) <= XkbSA_SetPtrDflt)
-
-proc XkbIsLegalKeycode(k: int): bool =
-  ##define        XkbIsLegalKeycode(k)    (((k)>=XkbMinLegalKeyCode)&&((k)<=XkbMaxLegalKeyCode))
-  result = (k >= XkbMinLegalKeyCode) and (k <= XkbMaxLegalKeyCode)
-
-proc XkbShiftLevel(n: int8): int8 =
-  ##define XkbShiftLevel(n) ((n)-1)
-  result = n - 1'i8
-
-proc XkbShiftLevelMask(n: int8): int8 =
-  ##define XkbShiftLevelMask(n) (1<<((n)-1))
-  result = 1'i8 shl (n - 1'i8)
-
-proc XkbcharToInt(v: int8): int16 =
-  ##define XkbcharToInt(v) ((v)&0x80?(int)((v)|(~0xff)):(int)((v)&0x7f))
-  if ((v and 0x80'i8) != 0'i8): result = v or (not 0xFF'i16)
-  else: result = int16(v and 0x7F'i8)
-
-proc XkbIntTo2chars(i: int16, h, L: var int8) =
-  ##define XkbIntTo2chars(i,h,l) (((h)=((i>>8)&0xff)),((l)=((i)&0xff)))
-  h = toU8((i shr 8'i16) and 0x00FF'i16)
-  L = toU8(i and 0xFF'i16)
-
-proc Xkb2charsToInt(h, L: int8): int16 =
-  when defined(cpu64):
-    ##define Xkb2charsToInt(h,l) ((h)&0x80?(int)(((h)<<8)|(l)|(~0xffff)): (int)(((h)<<8)|(l)&0x7fff))
-    if (h and 0x80'i8) != 0'i8:
-      result = toU16((ze(h) shl 8) or ze(L) or not 0x0000FFFF)
-    else:
-      result = toU16((ze(h) shl 8) or ze(L) and 0x00007FFF)
-  else:
-    ##define Xkb2charsToInt(h,l) ((short)(((h)<<8)|(l)))
-    result = toU16(ze(h) shl 8 or ze(L))
-
-proc XkbModLocks(s: PXkbStatePtr): int8 =
-  ##define XkbModLocks(s) ((s)->locked_mods)
-  result = s.locked_mods
-
-proc XkbStateMods(s: PXkbStatePtr): int16 =
-  ##define XkbStateMods(s) ((s)->base_mods|(s)->latched_mods|XkbModLocks(s))
-  result = s.base_mods or s.latched_mods or XkbModLocks(s)
-
-proc XkbGroupLock(s: PXkbStatePtr): int8 =
-  ##define XkbGroupLock(s) ((s)->locked_group)
-  result = s.locked_group
-
-proc XkbStateGroup(s: PXkbStatePtr): int16 =
-  ##define XkbStateGroup(s) ((s)->base_group+(s)->latched_group+XkbGroupLock(s))
-  result = s.base_group + (s.latched_group) + XkbGroupLock(s)
-
-proc XkbStateFieldFromRec(s: PXkbStatePtr): int =
-  ##define XkbStateFieldFromRec(s) XkbBuildCoreState((s)->lookup_mods,(s)->group)
-  result = XkbBuildCoreState(s.lookup_mods, s.group)
-
-proc XkbGrabStateFromRec(s: PXkbStatePtr): int =
-  ##define XkbGrabStateFromRec(s) XkbBuildCoreState((s)->grab_mods,(s)->group)
-  result = XkbBuildCoreState(s.grab_mods, s.group)
-
-proc XkbNumGroups(g: int16): int16 =
-  ##define XkbNumGroups(g) ((g)&0x0f)
-  result = g and 0x0000000F'i16
-
-proc XkbOutOfRangeGroupInfo(g: int16): int16 =
-  ##define XkbOutOfRangeGroupInfo(g) ((g)&0xf0)
-  result = g and 0x000000F0'i16
-
-proc XkbOutOfRangeGroupAction(g: int16): int16 =
-  ##define XkbOutOfRangeGroupAction(g) ((g)&0xc0)
-  result = g and 0x000000C0'i16
-
-proc XkbOutOfRangeGroupNumber(g: int16): int16 =
-  ##define XkbOutOfRangeGroupNumber(g) (((g)&0x30)>>4)
-  result = (g and 0x00000030'i16) shr 4'i16
-
-proc XkbSetGroupInfo(g, w, n: int16): int16 =
-  ##define XkbSetGroupInfo(g,w,n) (((w)&0xc0)|(((n)&3)<<4)|((g)&0x0f))
-  result = (w and 0x000000C0'i16) or
-    ((n and 3'i16) shl 4'i16) or (g and 0x0000000F'i16)
-
-proc XkbSetNumGroups(g, n: int16): int16 =
-  ##define XkbSetNumGroups(g,n) (((g)&0xf0)|((n)&0x0f))
-  result = (g and 0x000000F0'i16) or (n and 0x0000000F'i16)
-
-proc XkbModActionVMods(a: PXkbModAction): int16 =
-  ##define XkbModActionVMods(a) ((short)(((a)->vmods1<<8)|((a)->vmods2)))
-  result = toU16((ze(a.vmods1) shl 8) or ze(a.vmods2))
-
-proc XkbSetModActionVMods(a: PXkbModAction, v: int8) =
-  ##define XkbSetModActionVMods(a,v) (((a)->vmods1=(((v)>>8)&0xff)),(a)->vmods2=((v)&0xff))
-  a.vmods1 = toU8((ze(v) shr 8) and 0x000000FF)
-  a.vmods2 = toU8(ze(v) and 0x000000FF)
-
-proc XkbSAGroup(a: PXkbGroupAction): int8 =
-  ##define XkbSAGroup(a) (XkbcharToInt((a)->group_XXX))
-  result = int8(XkbcharToInt(a.group_XXX))
-
-proc XkbSASetGroupProc(a: PXkbGroupAction, g: int8) =
-  ##define XkbSASetGroup(a,g) ((a)->group_XXX=(g))
-  a.group_XXX = g
-
-proc XkbPtrActionX(a: PXkbPtrAction): int16 =
-  ##define XkbPtrActionX(a) (Xkb2charsToInt((a)->high_XXX,(a)->low_XXX))
-  result = int16(Xkb2charsToInt(a.high_XXX, a.low_XXX))
-
-proc XkbPtrActionY(a: PXkbPtrAction): int16 =
-  ##define XkbPtrActionY(a) (Xkb2charsToInt((a)->high_YYY,(a)->low_YYY))
-  result = int16(Xkb2charsToInt(a.high_YYY, a.low_YYY))
-
-proc XkbSetPtrActionX(a: PXkbPtrAction, x: int8) =
-  ##define XkbSetPtrActionX(a,x) (XkbIntTo2chars(x,(a)->high_XXX,(a)->low_XXX))
-  XkbIntTo2chars(x, a.high_XXX, a.low_XXX)
-
-proc XkbSetPtrActionY(a: PXkbPtrAction, y: int8) =
-  ##define XkbSetPtrActionY(a,y) (XkbIntTo2chars(y,(a)->high_YYY,(a)->low_YYY))
-  XkbIntTo2chars(y, a.high_YYY, a.low_YYY)
-
-proc XkbSAPtrDfltValue(a: PXkbPtrDfltAction): int8 =
-  ##define XkbSAPtrDfltValue(a) (XkbcharToInt((a)->valueXXX))
-  result = int8(XkbcharToInt(a.valueXXX))
-
-proc XkbSASetPtrDfltValue(a: PXkbPtrDfltAction, c: pointer) =
-  ##define XkbSASetPtrDfltValue(a,c) ((a)->valueXXX= ((c)&0xff))
-  a.valueXXX = toU8(cast[int](c))
-
-proc XkbSAScreen(a: PXkbSwitchScreenAction): int8 =
-  ##define XkbSAScreen(a) (XkbcharToInt((a)->screenXXX))
-  result = toU8(XkbcharToInt(a.screenXXX))
-
-proc XkbSASetScreen(a: PXkbSwitchScreenAction, s: pointer) =
-  ##define XkbSASetScreen(a,s) ((a)->screenXXX= ((s)&0xff))
-  a.screenXXX = toU8(cast[int](s))
-
-proc XkbActionSetCtrls(a: PXkbCtrlsAction, c: int8) =
-  ##define XkbActionSetCtrls(a,c) (((a)->ctrls3=(((c)>>24)&0xff)),((a)->ctrls2=(((c)>>16)&0xff)),
-  #                                 ((a)->ctrls1=(((c)>>8)&0xff)),((a)->ctrls0=((c)&0xff)))
-  a.ctrls3 = toU8((ze(c) shr 24) and 0x000000FF)
-  a.ctrls2 = toU8((ze(c) shr 16) and 0x000000FF)
-  a.ctrls1 = toU8((ze(c) shr 8) and 0x000000FF)
-  a.ctrls0 = toU8(ze(c) and 0x000000FF)
-
-proc XkbActionCtrls(a: PXkbCtrlsAction): int16 =
-  ##define XkbActionCtrls(a) ((((unsigned int)(a)->ctrls3)<<24)|(((unsigned int)(a)->ctrls2)<<16)|
-  #                            (((unsigned int)(a)->ctrls1)<<8)|((unsigned int)((a)->ctrls0)))
-  result = toU16((ze(a.ctrls3) shl 24) or (ze(a.ctrls2) shl 16) or
-     (ze(a.ctrls1) shl 8) or ze(a.ctrls0))
-
-proc XkbSARedirectVMods(a: PXkbRedirectKeyAction): int16 =
-  ##define XkbSARedirectVMods(a) ((((unsigned int)(a)->vmods1)<<8)|((unsigned int)(a)->vmods0))
-  result = toU16((ze(a.vmods1) shl 8) or ze(a.vmods0))
-
-proc XkbSARedirectSetVMods(a: PXkbRedirectKeyAction, m: int8) =
-  ##define XkbSARedirectSetVMods(a,m) (((a)->vmods_mask1=(((m)>>8)&0xff)),((a)->vmods_mask0=((m)&0xff)))
-  a.vmods_mask1 = toU8((ze(m) shr 8) and 0x000000FF)
-  a.vmods_mask0 = toU8(ze(m) or 0x000000FF)
-
-proc XkbSARedirectVModsMask(a: PXkbRedirectKeyAction): int16 =
-  ##define XkbSARedirectVModsMask(a) ((((unsigned int)(a)->vmods_mask1)<<8)|
-  #                                     ((unsigned int)(a)->vmods_mask0))
-  result = toU16((ze(a.vmods_mask1) shl 8) or ze(a.vmods_mask0))
-
-proc XkbSARedirectSetVModsMask(a: PXkbRedirectKeyAction, m: int8) =
-  ##define XkbSARedirectSetVModsMask(a,m) (((a)->vmods_mask1=(((m)>>8)&0xff)),((a)->vmods_mask0=((m)&0xff)))
-  a.vmods_mask1 = toU8(ze(m) shr 8 and 0x000000FF)
-  a.vmods_mask0 = toU8(ze(m) and 0x000000FF)
-
-proc XkbAX_AnyFeedback(c: PXkbControlsPtr): int16 =
-  ##define XkbAX_AnyFeedback(c) ((c)->enabled_ctrls&XkbAccessXFeedbackMask)
-  result = toU16(ze(c.enabled_ctrls) and XkbAccessXFeedbackMask)
-
-proc XkbAX_NeedOption(c: PXkbControlsPtr, w: int16): int16 =
-  ##define XkbAX_NeedOption(c,w) ((c)->ax_options&(w))
-  result = toU16(ze(c.ax_options) and ze(w))
-
-proc XkbAX_NeedFeedback(c: PXkbControlsPtr, w: int16): bool =
-  ##define XkbAX_NeedFeedback(c,w) (XkbAX_AnyFeedback(c)&&XkbAX_NeedOption(c,w))
-  result = (XkbAX_AnyFeedback(c) > 0'i16) and (XkbAX_NeedOption(c, w) > 0'i16)
-
-proc XkbSMKeyActionsPtr(m: PXkbServerMapPtr, k: int16): PXkbAction =
-  ##define XkbSMKeyActionsPtr(m,k) (&(m)->acts[(m)->key_acts[k]])
-  result = addr(m.acts[ze(m.key_acts[ze(k)])])
-
-proc XkbCMKeyGroupInfo(m: PXkbClientMapPtr, k: int16): int8 =
-  ##define XkbCMKeyGroupInfo(m,k) ((m)->key_sym_map[k].group_info)
-  result = m.key_sym_map[ze(k)].group_info
-
-proc XkbCMKeyNumGroups(m: PXkbClientMapPtr, k: int16): int8 =
-  ##define XkbCMKeyNumGroups(m,k) (XkbNumGroups((m)->key_sym_map[k].group_info))
-  result = toU8(XkbNumGroups(m.key_sym_map[ze(k)].group_info))
-
-proc XkbCMKeyGroupWidth(m: PXkbClientMapPtr, k: int16, g: int8): int8 =
-  ##define XkbCMKeyGroupWidth(m,k,g) (XkbCMKeyType(m,k,g)->num_levels)
-  result = XkbCMKeyType(m, k, g).num_levels
-
-proc XkbCMKeyGroupsWidth(m: PXkbClientMapPtr, k: int16): int8 =
-  ##define XkbCMKeyGroupsWidth(m,k) ((m)->key_sym_map[k].width)
-  result = m.key_sym_map[ze(k)].width
-
-proc XkbCMKeyTypeIndex(m: PXkbClientMapPtr, k: int16, g: int8): int8 =
-  ##define XkbCMKeyTypeIndex(m,k,g) ((m)->key_sym_map[k].kt_index[g&0x3])
-  result = m.key_sym_map[ze(k)].kt_index[ze(g) and 0x00000003]
-
-proc XkbCMKeyType(m: PXkbClientMapPtr, k: int16, g: int8): PXkbKeyTypePtr =
-  ##define XkbCMKeyType(m,k,g) (&(m)->types[XkbCMKeyTypeIndex(m,k,g)])
-  result = addr(m.types[ze(XkbCMKeyTypeIndex(m, k, g))])
-
-proc XkbCMKeyNumSyms(m: PXkbClientMapPtr, k: int16): int16 =
-  ##define XkbCMKeyNumSyms(m,k) (XkbCMKeyGroupsWidth(m,k)*XkbCMKeyNumGroups(m,k))
-  result = toU16(ze(XkbCMKeyGroupsWidth(m, k)) or ze(XkbCMKeyNumGroups(m, k)))
-
-proc XkbCMKeySymsOffset(m: PXkbClientMapPtr, k: int16): int8 =
-  ##define XkbCMKeySymsOffset(m,k) ((m)->key_sym_map[k].offset)
-  result = m.key_sym_map[ze(k)].offset
-
-proc XkbCMKeySymsPtr*(m: PXkbClientMapPtr, k: int16): PKeySym =
-  ##define XkbCMKeySymsPtr(m,k) (&(m)->syms[XkbCMKeySymsOffset(m,k)])
-  result = addr(m.syms[ze(XkbCMKeySymsOffset(m, k))])
-
-proc XkbIM_IsAuto(i: PXkbIndicatorMapPtr): bool =
-  ##define XkbIM_IsAuto(i) ((((i)->flags&XkbIM_NoAutomatic)==0)&&(((i)->which_groups&&(i)->groups)||
-  #                           ((i)->which_mods&&(i)->mods.mask)||  ((i)->ctrls)))
-  result = ((ze(i.flags) and XkbIM_NoAutomatic) == 0) and
-      (((i.which_groups > 0'i8) and (i.groups > 0'i8)) or
-      ((i.which_mods > 0'i8) and (i.mods.mask > 0'i8)) or (i.ctrls > 0'i8))
-
-proc XkbIM_InUse(i: PXkbIndicatorMapPtr): bool =
-  ##define XkbIM_InUse(i) (((i)->flags)||((i)->which_groups)||((i)->which_mods)||((i)->ctrls))
-  result = (i.flags > 0'i8) or (i.which_groups > 0'i8) or (i.which_mods > 0'i8) or
-      (i.ctrls > 0'i8)
-
-proc XkbKeyKeyTypeIndex(d: PXkbDescPtr, k: int16, g: int8): int8 =
-  ##define XkbKeyKeyTypeIndex(d,k,g)      (XkbCMKeyTypeIndex((d)->map,k,g))
-  result = XkbCMKeyTypeIndex(d.map, k, g)
-
-proc XkbKeyKeyType(d: PXkbDescPtr, k: int16, g: int8): PXkbKeyTypePtr =
-  ##define XkbKeyKeyType(d,k,g) (XkbCMKeyType((d)->map,k,g))
-  result = XkbCMKeyType(d.map, k, g)
-
-proc XkbKeyGroupWidth(d: PXkbDescPtr, k: int16, g: int8): int8 =
-  ##define XkbKeyGroupWidth(d,k,g) (XkbCMKeyGroupWidth((d)->map,k,g))
-  result = XkbCMKeyGroupWidth(d.map, k, g)
-
-proc XkbKeyGroupsWidth(d: PXkbDescPtr, k: int16): int8 =
-  ##define XkbKeyGroupsWidth(d,k) (XkbCMKeyGroupsWidth((d)->map,k))
-  result = XkbCMKeyGroupsWidth(d.map, k)
-
-proc XkbKeyGroupInfo(d: PXkbDescPtr, k: int16): int8 =
-  ##define XkbKeyGroupInfo(d,k) (XkbCMKeyGroupInfo((d)->map,(k)))
-  result = XkbCMKeyGroupInfo(d.map, k)
-
-proc XkbKeyNumGroups(d: PXkbDescPtr, k: int16): int8 =
-  ##define XkbKeyNumGroups(d,k) (XkbCMKeyNumGroups((d)->map,(k)))
-  result = XkbCMKeyNumGroups(d.map, k)
-
-proc XkbKeyNumSyms(d: PXkbDescPtr, k: int16): int16 =
-  ##define XkbKeyNumSyms(d,k) (XkbCMKeyNumSyms((d)->map,(k)))
-  result = XkbCMKeyNumSyms(d.map, k)
-
-proc XkbKeySymsPtr*(d: PXkbDescPtr, k: int16): PKeySym =
-  ##define XkbKeySymsPtr(d,k) (XkbCMKeySymsPtr((d)->map,(k)))
-  result = XkbCMKeySymsPtr(d.map, k)
-
-proc XkbKeySym(d: PXkbDescPtr, k: int16, n: int16): TKeySym =
-  ##define XkbKeySym(d,k,n) (XkbKeySymsPtr(d,k)[n])
-  result = cast[ptr array[0..0xffff, TKeySym]](XkbKeySymsPtr(d, k))[ze(n)] # XXX: this seems strange!
-
-proc XkbKeySymEntry(d: PXkbDescPtr, k: int16, sl: int16, g: int8): TKeySym =
-  ##define XkbKeySymEntry(d,k,sl,g) (XkbKeySym(d,k,((XkbKeyGroupsWidth(d,k)*(g))+(sl))))
-  result = XkbKeySym(d, k, toU16(ze(XkbKeyGroupsWidth(d, k)) * ze(g) + ze(sl)))
-
-proc XkbKeyAction(d: PXkbDescPtr, k: int16, n: int16): PXkbAction =
-  ##define XkbKeyAction(d,k,n) (XkbKeyHasActions(d,k)?&XkbKeyActionsPtr(d,k)[n]:NULL)
-  #if (XkbKeyHasActions(d, k)):
-  #  result = XkbKeyActionsPtr(d, k)[ze(n)] #Buggy !!!
-  assert(false)
-  result = nil
-
-proc XkbKeyActionEntry(d: PXkbDescPtr, k: int16, sl: int16, g: int8): int8 =
-  ##define XkbKeyActionEntry(d,k,sl,g) (XkbKeyHasActions(d,k) ?
-  #                                      XkbKeyAction(d, k, ((XkbKeyGroupsWidth(d, k) * (g))+(sl))):NULL)
-  if XkbKeyHasActions(d, k):
-    result = XkbKeyGroupsWidth(d, k) *% g +% toU8(sl)
-  else:
-    result = 0'i8
-
-proc XkbKeyHasActions(d: PXkbDescPtr, k: int16): bool =
-  ##define XkbKeyHasActions(d,k) ((d)->server->key_acts[k]!=0)
-  result = d.server.key_acts[ze(k)] != 0'i16
-
-proc XkbKeyNumActions(d: PXkbDescPtr, k: int16): int16 =
-  ##define XkbKeyNumActions(d,k) (XkbKeyHasActions(d,k)?XkbKeyNumSyms(d,k):1)
-  if (XkbKeyHasActions(d, k)): result = XkbKeyNumSyms(d, k)
-  else: result = 1'i16
-
-proc XkbKeyActionsPtr(d: PXkbDescPtr, k: int16): PXkbAction =
-  ##define XkbKeyActionsPtr(d,k) (XkbSMKeyActionsPtr((d)->server,k))
-  result = XkbSMKeyActionsPtr(d.server, k)
-
-proc XkbKeycodeInRange(d: PXkbDescPtr, k: int16): bool =
-  ##define XkbKeycodeInRange(d,k) (((k)>=(d)->min_key_code)&& ((k)<=(d)->max_key_code))
-  result = (char(toU8(k)) >= d.min_key_code) and (char(toU8(k)) <= d.max_key_code)
-
-proc XkbNumKeys(d: PXkbDescPtr): int8 =
-  ##define XkbNumKeys(d) ((d)->max_key_code-(d)->min_key_code+1)
-  result = toU8(ord(d.max_key_code) - ord(d.min_key_code) + 1)
-
-proc XkbXI_DevHasBtnActs(d: PXkbDeviceInfoPtr): bool =
-  ##define XkbXI_DevHasBtnActs(d) (((d)->num_btns>0)&&((d)->btn_acts!=NULL))
-  result = (d.num_btns > 0'i16) and (not (d.btn_acts == nil))
-
-proc XkbXI_LegalDevBtn(d: PXkbDeviceInfoPtr, b: int16): bool =
-  ##define XkbXI_LegalDevBtn(d,b) (XkbXI_DevHasBtnActs(d)&&((b)<(d)->num_btns))
-  result = XkbXI_DevHasBtnActs(d) and (b <% d.num_btns)
-
-proc XkbXI_DevHasLeds(d: PXkbDeviceInfoPtr): bool =
-  ##define XkbXI_DevHasLeds(d) (((d)->num_leds>0)&&((d)->leds!=NULL))
-  result = (d.num_leds > 0'i16) and (not (d.leds == nil))
-
-proc XkbBoundsWidth(b: PXkbBoundsPtr): int16 =
-  ##define XkbBoundsWidth(b) (((b)->x2)-((b)->x1))
-  result = (b.x2) - b.x1
-
-proc XkbBoundsHeight(b: PXkbBoundsPtr): int16 =
-  ##define XkbBoundsHeight(b) (((b)->y2)-((b)->y1))
-  result = (b.y2) - b.y1
-
-proc XkbOutlineIndex(s: PXkbShapePtr, o: PXkbOutlinePtr): int32 =
-  ##define XkbOutlineIndex(s,o) ((int)((o)-&(s)->outlines[0]))
-  result = int32((cast[TAddress](o) - cast[TAddress](addr(s.outlines[0]))) div sizeof(PXkbOutlinePtr))
-
-proc XkbShapeDoodadColor(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr): PXkbColorPtr =
-  ##define XkbShapeDoodadColor(g,d) (&(g)->colors[(d)->color_ndx])
-  result = addr((g.colors[ze(d.color_ndx)]))
-
-proc XkbShapeDoodadShape(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr): PXkbShapePtr =
-  ##define XkbShapeDoodadShape(g,d) (&(g)->shapes[(d)->shape_ndx])
-  result = addr(g.shapes[ze(d.shape_ndx)])
-
-proc XkbSetShapeDoodadColor(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr,
-                            c: PXkbColorPtr) =
-  ##define XkbSetShapeDoodadColor(g,d,c) ((d)->color_ndx= (c)-&(g)->colors[0])
-  d.color_ndx = toU16((cast[TAddress](c) - cast[TAddress](addr(g.colors[0]))) div sizeof(TXkbColorRec))
-
-proc XkbSetShapeDoodadShape(g: PXkbGeometryPtr, d: PXkbShapeDoodadPtr,
-                            s: PXkbShapePtr) =
-  ##define XkbSetShapeDoodadShape(g,d,s) ((d)->shape_ndx= (s)-&(g)->shapes[0])
-  d.shape_ndx = toU16((cast[TAddress](s) - cast[TAddress](addr(g.shapes[0]))) div sizeof(TXkbShapeRec))
-
-proc XkbTextDoodadColor(g: PXkbGeometryPtr, d: PXkbTextDoodadPtr): PXkbColorPtr =
-  ##define XkbTextDoodadColor(g,d) (&(g)->colors[(d)->color_ndx])
-  result = addr(g.colors[ze(d.color_ndx)])
-
-proc XkbSetTextDoodadColor(g: PXkbGeometryPtr, d: PXkbTextDoodadPtr,
-                           c: PXkbColorPtr) =
-  ##define XkbSetTextDoodadColor(g,d,c) ((d)->color_ndx= (c)-&(g)->colors[0])
-  d.color_ndx = toU16((cast[TAddress](c) - cast[TAddress](addr(g.colors[0]))) div sizeof(TXkbColorRec))
-
-proc XkbIndicatorDoodadShape(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr): PXkbShapeDoodadPtr =
-  ##define XkbIndicatorDoodadShape(g,d) (&(g)->shapes[(d)->shape_ndx])
-  result = cast[PXkbShapeDoodadPtr](addr(g.shapes[ze(d.shape_ndx)]))
-
-proc XkbIndicatorDoodadOnColor(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr): PXkbColorPtr =
-  ##define XkbIndicatorDoodadOnColor(g,d) (&(g)->colors[(d)->on_color_ndx])
-  result = addr(g.colors[ze(d.on_color_ndx)])
-
-proc XkbIndicatorDoodadOffColor(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr): PXkbColorPtr =
-  ##define XkbIndicatorDoodadOffColor(g,d) (&(g)->colors[(d)->off_color_ndx])
-  result = addr(g.colors[ze(d.off_color_ndx)])
-
-proc XkbSetIndicatorDoodadOnColor(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr,
-                                  c: PXkbColorPtr) =
-  ##define XkbSetIndicatorDoodadOnColor(g,d,c) ((d)->on_color_ndx= (c)-&(g)->colors[0])
-  d.on_color_ndx = toU16((cast[TAddress](c) - cast[TAddress](addr(g.colors[0]))) div sizeof(TXkbColorRec))
-
-proc XkbSetIndicatorDoodadOffColor(g: PXkbGeometryPtr,
-                                   d: PXkbIndicatorDoodadPtr, c: PXkbColorPtr) =
-  ##define        XkbSetIndicatorDoodadOffColor(g,d,c) ((d)->off_color_ndx= (c)-&(g)->colors[0])
-  d.off_color_ndx = toU16((cast[TAddress](c) - cast[TAddress](addr(g.colors[0]))) div sizeof(TxkbColorRec))
-
-proc XkbSetIndicatorDoodadShape(g: PXkbGeometryPtr, d: PXkbIndicatorDoodadPtr,
-                                s: PXkbShapeDoodadPtr) =
-  ##define XkbSetIndicatorDoodadShape(g,d,s) ((d)->shape_ndx= (s)-&(g)->shapes[0])
-  d.shape_ndx = toU16((cast[TAddress](s) - (cast[TAddress](addr(g.shapes[0])))) div sizeof(TXkbShapeRec))
-
-proc XkbLogoDoodadColor(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr): PXkbColorPtr =
-  ##define XkbLogoDoodadColor(g,d) (&(g)->colors[(d)->color_ndx])
-  result = addr(g.colors[ze(d.color_ndx)])
-
-proc XkbLogoDoodadShape(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr): PXkbShapeDoodadPtr =
-  ##define XkbLogoDoodadShape(g,d) (&(g)->shapes[(d)->shape_ndx])
-  result = cast[PXkbShapeDoodadPtr](addr(g.shapes[ze(d.shape_ndx)]))
-
-proc XkbSetLogoDoodadColor(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr,
-                           c: PXkbColorPtr) =
-  ##define XkbSetLogoDoodadColor(g,d,c) ((d)->color_ndx= (c)-&(g)->colors[0])
-  d.color_ndx = toU16((cast[TAddress](c) - cast[TAddress](addr(g.colors[0]))) div sizeof(TXkbColorRec))
-
-proc XkbSetLogoDoodadShape(g: PXkbGeometryPtr, d: PXkbLogoDoodadPtr,
-                           s: PXkbShapeDoodadPtr) =
-  ##define XkbSetLogoDoodadShape(g,d,s) ((d)->shape_ndx= (s)-&(g)->shapes[0])
-  d.shape_ndx = toU16((cast[TAddress](s) - cast[TAddress](addr(g.shapes[0]))) div sizeof(TXkbShapeRec))
-
-proc XkbKeyShape(g: PXkbGeometryPtr, k: PXkbKeyPtr): PXkbShapeDoodadPtr =
-  ##define XkbKeyShape(g,k) (&(g)->shapes[(k)->shape_ndx])
-  result = cast[PXkbShapeDoodadPtr](addr(g.shapes[ze(k.shape_ndx)]))
-
-proc XkbKeyColor(g: PXkbGeometryPtr, k: PXkbKeyPtr): PXkbColorPtr =
-  ##define XkbKeyColor(g,k) (&(g)->colors[(k)->color_ndx])
-  result = addr(g.colors[ze(k.color_ndx)])
-
-proc XkbSetKeyShape(g: PXkbGeometryPtr, k: PXkbKeyPtr, s: PXkbShapeDoodadPtr) =
-  ##define XkbSetKeyShape(g,k,s) ((k)->shape_ndx= (s)-&(g)->shapes[0])
-  k.shape_ndx = toU8((cast[TAddress](s) - cast[TAddress](addr(g.shapes[0]))) div sizeof(TXkbShapeRec))
-
-proc XkbSetKeyColor(g: PXkbGeometryPtr, k: PXkbKeyPtr, c: PXkbColorPtr) =
-  ##define XkbSetKeyColor(g,k,c) ((k)->color_ndx= (c)-&(g)->colors[0])
-  k.color_ndx = toU8((cast[TAddress](c) - cast[TAddress](addr(g.colors[0]))) div sizeof(TxkbColorRec))
-
-proc XkbGeomColorIndex(g: PXkbGeometryPtr, c: PXkbColorPtr): int32 =
-  ##define XkbGeomColorIndex(g,c) ((int)((c)-&(g)->colors[0]))
-  result = toU16((cast[TAddress](c) - (cast[TAddress](addr(g.colors[0])))) div sizeof(TxkbColorRec))
diff --git a/tests/deps/x11-1.0/xkblib.nim b/tests/deps/x11-1.0/xkblib.nim
deleted file mode 100644
index 2366b0971..000000000
--- a/tests/deps/x11-1.0/xkblib.nim
+++ /dev/null
@@ -1,661 +0,0 @@
-# $Xorg: XKBlib.h,v 1.6 2000/08/17 19:45:03 cpqbld Exp $
-#************************************************************
-#Copyright (c) 1993 by Silicon Graphics Computer Systems, Inc.
-#
-#Permission to use, copy, modify, and distribute this
-#software and its documentation for any purpose and without
-#fee is hereby granted, provided that the above copyright
-#notice appear in all copies and that both that copyright
-#notice and this permission notice appear in supporting
-#documentation, and that the name of Silicon Graphics not be
-#used in advertising or publicity pertaining to distribution
-#of the software without specific prior written permission.
-#Silicon Graphics makes no representation about the suitability
-#of this software for any purpose. It is provided "as is"
-#without any express or implied warranty.
-#
-#SILICON GRAPHICS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS
-#SOFTWARE, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
-#AND FITNESS FOR A PARTICULAR PURPOSE. IN NO EVENT SHALL SILICON
-#GRAPHICS BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL
-#DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING `from` LOSS OF USE,
-#DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE
-#OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION  WITH
-#THE USE OR PERFORMANCE OF THIS SOFTWARE.
-#
-#********************************************************/
-# $XFree86: xc/lib/X11/XKBlib.h,v 3.3 2001/08/01 00:44:38 tsi Exp $
-#
-# Pascal Convertion was made by Ido Kannner - kanerido@actcom.net.il
-#
-#Thanks:
-#         I want to thanks to oliebol for putting up with all of the problems that was found
-#         while translating this code. ;)
-#
-#         I want to thanks #fpc channel in freenode irc, for helping me, and to put up with my
-#         weird questions ;)
-#
-#         Thanks for mmc in #xlib on freenode irc And so for the channel itself for the helping me to
-#         understanding some of the problems I had converting this headers and pointing me to resources
-#         that helped translating this headers.
-#
-# Ido
-#
-#History:
-#        2004/10/15        - Fixed a bug of accessing second based records by removing "paced record" and
-#                            chnaged it to "reocrd" only.
-#        2004/10/10        - Added to TXkbGetAtomNameFunc and TXkbInternAtomFunc the cdecl call.
-#        2004/10/06 - 09   - Convertion `from` the c header of XKBlib.h
-#
-#
-
-import
-  X, Xlib, XKB
-
-
-include "x11pragma.nim"
-
-
-type
-  PXkbAnyEvent* = ptr TXkbAnyEvent
-  TXkbAnyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds;
-    xkb_type*: int16          # XKB event minor code
-    device*: int16            # device ID
-
-
-type
-  PXkbNewKeyboardNotifyEvent* = ptr TXkbNewKeyboardNotifyEvent
-  TXkbNewKeyboardNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbNewKeyboardNotify
-    device*: int16            # device ID
-    old_device*: int16        # device ID of previous keyboard
-    min_key_code*: int16      # minimum key code
-    max_key_code*: int16      # maximum key code
-    old_min_key_code*: int16  # min key code of previous kbd
-    old_max_key_code*: int16  # max key code of previous kbd
-    changed*: int16           # changed aspects of the keyboard
-    req_major*: int8          # major and minor opcode of req
-    req_minor*: int8          # that caused change, if applicable
-
-
-type
-  PXkbMapNotifyEvent* = ptr TXkbMapNotifyEvent
-  TXkbMapNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbMapNotify
-    device*: int16            # device ID
-    changed*: int16           # fields which have been changed
-    flags*: int16             # reserved
-    first_type*: int16        # first changed key type
-    num_types*: int16         # number of changed key types
-    min_key_code*: TKeyCode
-    max_key_code*: TKeyCode
-    first_key_sym*: TKeyCode
-    first_key_act*: TKeyCode
-    first_key_behavior*: TKeyCode
-    first_key_explicit*: TKeyCode
-    first_modmap_key*: TKeyCode
-    first_vmodmap_key*: TKeyCode
-    num_key_syms*: int16
-    num_key_acts*: int16
-    num_key_behaviors*: int16
-    num_key_explicit*: int16
-    num_modmap_keys*: int16
-    num_vmodmap_keys*: int16
-    vmods*: int16             # mask of changed virtual mods
-
-
-type
-  PXkbStateNotifyEvent* = ptr TXkbStateNotifyEvent
-  TXkbStateNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbStateNotify
-    device*: int16            # device ID
-    changed*: int16           # mask of changed state components
-    group*: int16             # keyboard group
-    base_group*: int16        # base keyboard group
-    latched_group*: int16     # latched keyboard group
-    locked_group*: int16      # locked keyboard group
-    mods*: int16              # modifier state
-    base_mods*: int16         # base modifier state
-    latched_mods*: int16      # latched modifiers
-    locked_mods*: int16       # locked modifiers
-    compat_state*: int16      # compatibility state
-    grab_mods*: int8          # mods used for grabs
-    compat_grab_mods*: int8   # grab mods for non-XKB clients
-    lookup_mods*: int8        # mods sent to clients
-    compat_lookup_mods*: int8 # mods sent to non-XKB clients
-    ptr_buttons*: int16       # pointer button state
-    keycode*: TKeyCode        # keycode that caused the change
-    event_type*: int8         # KeyPress or KeyRelease
-    req_major*: int8          # Major opcode of request
-    req_minor*: int8          # Minor opcode of request
-
-
-type
-  PXkbControlsNotifyEvent* = ptr TXkbControlsNotifyEvent
-  TXkbControlsNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbControlsNotify
-    device*: int16            # device ID
-    changed_ctrls*: int16     # controls with changed sub-values
-    enabled_ctrls*: int16     # controls currently enabled
-    enabled_ctrl_changes*: int16 # controls just {en,dis}abled
-    num_groups*: int16        # total groups on keyboard
-    keycode*: TKeyCode        # key that caused change or 0
-    event_type*: int8         # type of event that caused change
-    req_major*: int8          # if keycode==0, major and minor
-    req_minor*: int8          # opcode of req that caused change
-
-
-type
-  PXkbIndicatorNotifyEvent* = ptr TXkbIndicatorNotifyEvent
-  TXkbIndicatorNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbIndicatorNotify
-    device*: int16            # device
-    changed*: int16           # indicators with new state or map
-    state*: int16             # current state of all indicators
-
-
-type
-  PXkbNamesNotifyEvent* = ptr TXkbNamesNotifyEvent
-  TXkbNamesNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbNamesNotify
-    device*: int16            # device ID
-    changed*: int32           # names that have changed
-    first_type*: int16        # first key type with new name
-    num_types*: int16         # number of key types with new names
-    first_lvl*: int16         # first key type new new level names
-    num_lvls*: int16          # # of key types w/new level names
-    num_aliases*: int16       # total number of key aliases
-    num_radio_groups*: int16  # total number of radio groups
-    changed_vmods*: int16     # virtual modifiers with new names
-    changed_groups*: int16    # groups with new names
-    changed_indicators*: int16 # indicators with new names
-    first_key*: int16         # first key with new name
-    num_keys*: int16          # number of keys with new names
-
-
-type
-  PXkbCompatMapNotifyEvent* = ptr TXkbCompatMapNotifyEvent
-  TXkbCompatMapNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbCompatMapNotify
-    device*: int16            # device ID
-    changed_groups*: int16    # groups with new compat maps
-    first_si*: int16          # first new symbol interp
-    num_si*: int16            # number of new symbol interps
-    num_total_si*: int16      # total # of symbol interps
-
-
-type
-  PXkbBellNotifyEvent* = ptr TXkbBellNotifyEvent
-  TXkbBellNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbBellNotify
-    device*: int16            # device ID
-    percent*: int16           # requested volume as a % of maximum
-    pitch*: int16             # requested pitch in Hz
-    duration*: int16          # requested duration in useconds
-    bell_class*: int16        # (input extension) feedback class
-    bell_id*: int16           # (input extension) ID of feedback
-    name*: TAtom              # "name" of requested bell
-    window*: TWindow          # window associated with event
-    event_only*: bool         # "event only" requested
-
-
-type
-  PXkbActionMessageEvent* = ptr TXkbActionMessageEvent
-  TXkbActionMessageEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbActionMessage
-    device*: int16            # device ID
-    keycode*: TKeyCode        # key that generated the event
-    press*: bool              # true if act caused by key press
-    key_event_follows*: bool  # true if key event also generated
-    group*: int16             # effective group
-    mods*: int16              # effective mods
-    message*: array[0..XkbActionMessageLength, char] # message -- leave space for NUL
-
-
-type
-  PXkbAccessXNotifyEvent* = ptr TXkbAccessXNotifyEvent
-  TXkbAccessXNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbAccessXNotify
-    device*: int16            # device ID
-    detail*: int16            # XkbAXN_*
-    keycode*: int16           # key of event
-    sk_delay*: int16          # current slow keys delay
-    debounce_delay*: int16    # current debounce delay
-
-
-type
-  PXkbExtensionDeviceNotifyEvent* = ptr TXkbExtensionDeviceNotifyEvent
-  TXkbExtensionDeviceNotifyEvent*{.final.} = object
-    theType*: int16           # XkbAnyEvent
-    serial*: int32            # of last req processed by server
-    send_event*: bool         # is this `from` a SendEvent request?
-    display*: PDisplay        # Display the event was read `from`
-    time*: TTime              # milliseconds
-    xkb_type*: int16          # XkbExtensionDeviceNotify
-    device*: int16            # device ID
-    reason*: int16            # reason for the event
-    supported*: int16         # mask of supported features
-    unsupported*: int16       # mask of unsupported features
-                              # that some app tried to use
-    first_btn*: int16         # first button that changed
-    num_btns*: int16          # range of buttons changed
-    leds_defined*: int16      # indicators with names or maps
-    led_state*: int16         # current state of the indicators
-    led_class*: int16         # feedback class for led changes
-    led_id*: int16            # feedback id for led changes
-
-
-type
-  PXkbEvent* = ptr TXkbEvent
-  TXkbEvent*{.final.} = object
-    theType*: int16
-    any*: TXkbAnyEvent
-    new_kbd*: TXkbNewKeyboardNotifyEvent
-    map*: TXkbMapNotifyEvent
-    state*: TXkbStateNotifyEvent
-    ctrls*: TXkbControlsNotifyEvent
-    indicators*: TXkbIndicatorNotifyEvent
-    names*: TXkbNamesNotifyEvent
-    compat*: TXkbCompatMapNotifyEvent
-    bell*: TXkbBellNotifyEvent
-    message*: TXkbActionMessageEvent
-    accessx*: TXkbAccessXNotifyEvent
-    device*: TXkbExtensionDeviceNotifyEvent
-    core*: TXEvent
-
-
-type
-  PXkbKbdDpyStatePtr* = ptr TXkbKbdDpyStateRec
-  TXkbKbdDpyStateRec*{.final.} = object  # XkbOpenDisplay error codes
-
-const
-  XkbOD_Success* = 0
-  XkbOD_BadLibraryVersion* = 1
-  XkbOD_ConnectionRefused* = 2
-  XkbOD_NonXkbServer* = 3
-  XkbOD_BadServerVersion* = 4 # Values for XlibFlags
-
-const
-  XkbLC_ForceLatin1Lookup* = 1 shl 0
-  XkbLC_ConsumeLookupMods* = 1 shl 1
-  XkbLC_AlwaysConsumeShiftAndLock* = 1 shl 2
-  XkbLC_IgnoreNewKeyboards* = 1 shl 3
-  XkbLC_ControlFallback* = 1 shl 4
-  XkbLC_ConsumeKeysOnComposeFail* = 1 shl 29
-  XkbLC_ComposeLED* = 1 shl 30
-  XkbLC_BeepOnComposeFail* = 1 shl 31
-  XkbLC_AllComposeControls* = 0xC0000000
-  XkbLC_AllControls* = 0xC000001F
-
-proc XkbIgnoreExtension*(ignore: bool): bool{.libx11c,
-    importc: "XkbIgnoreExtension".}
-proc XkbOpenDisplay*(name: cstring, ev_rtrn, err_rtrn, major_rtrn, minor_rtrn,
-                                    reason: ptr int16): PDisplay{.libx11c, importc: "XkbOpenDisplay".}
-proc XkbQueryExtension*(dpy: PDisplay, opcodeReturn, eventBaseReturn,
-                                       errorBaseReturn, majorRtrn, minorRtrn: ptr int16): bool{.
-    libx11c, importc: "XkbQueryExtension".}
-proc XkbUseExtension*(dpy: PDisplay, major_rtrn, minor_rtrn: ptr int16): bool{.
-    libx11c, importc: "XkbUseExtension".}
-proc XkbLibraryVersion*(libMajorRtrn, libMinorRtrn: ptr int16): bool{.libx11c, importc: "XkbLibraryVersion".}
-proc XkbSetXlibControls*(dpy: PDisplay, affect, values: int16): int16{.libx11c, importc: "XkbSetXlibControls".}
-proc XkbGetXlibControls*(dpy: PDisplay): int16{.libx11c,
-    importc: "XkbGetXlibControls".}
-type
-  TXkbInternAtomFunc* = proc (dpy: PDisplay, name: cstring, only_if_exists: bool): TAtom{.
-      cdecl.}
-
-type
-  TXkbGetAtomNameFunc* = proc (dpy: PDisplay, atom: TAtom): cstring{.cdecl.}
-
-proc XkbSetAtomFuncs*(getAtom: TXkbInternAtomFunc, getName: TXkbGetAtomNameFunc){.
-    libx11c, importc: "XkbSetAtomFuncs".}
-proc XkbKeycodeToKeysym*(dpy: PDisplay, kc: TKeyCode, group, level: int16): TKeySym{.
-    libx11c, importc: "XkbKeycodeToKeysym".}
-proc XkbKeysymToModifiers*(dpy: PDisplay, ks: TKeySym): int16{.libx11c, importc: "XkbKeysymToModifiers".}
-proc XkbLookupKeySym*(dpy: PDisplay, keycode: TKeyCode,
-                      modifiers, modifiers_return: int16, keysym_return: PKeySym): bool{.
-    libx11c, importc: "XkbLookupKeySym".}
-proc XkbLookupKeyBinding*(dpy: PDisplay, sym_rtrn: TKeySym, mods: int16,
-                          buffer: cstring, nbytes: int16, extra_rtrn: ptr int16): int16{.
-    libx11c, importc: "XkbLookupKeyBinding".}
-proc XkbTranslateKeyCode*(xkb: PXkbDescPtr, keycode: TKeyCode,
-                          modifiers, modifiers_return: int16,
-                          keysym_return: PKeySym): bool{.libx11c,
-    importc: "XkbTranslateKeyCode".}
-proc XkbTranslateKeySym*(dpy: PDisplay, sym_return: TKeySym, modifiers: int16,
-                         buffer: cstring, nbytes: int16, extra_rtrn: ptr int16): int16{.
-    libx11c, importc: "XkbTranslateKeySym".}
-proc XkbSetAutoRepeatRate*(dpy: PDisplay, deviceSpec, delay, interval: int16): bool{.
-    libx11c, importc: "XkbSetAutoRepeatRate".}
-proc XkbGetAutoRepeatRate*(dpy: PDisplay, deviceSpec: int16,
-                           delayRtrn, intervalRtrn: PWord): bool{.libx11c, importc: "XkbGetAutoRepeatRate".}
-proc XkbChangeEnabledControls*(dpy: PDisplay, deviceSpec, affect, values: int16): bool{.
-    libx11c, importc: "XkbChangeEnabledControls".}
-proc XkbDeviceBell*(dpy: PDisplay, win: TWindow,
-                    deviceSpec, bellClass, bellID, percent: int16, name: TAtom): bool{.
-    libx11c, importc: "XkbDeviceBell".}
-proc XkbForceDeviceBell*(dpy: PDisplay,
-                         deviceSpec, bellClass, bellID, percent: int16): bool{.
-    libx11c, importc: "XkbForceDeviceBell".}
-proc XkbDeviceBellEvent*(dpy: PDisplay, win: TWindow,
-                         deviceSpec, bellClass, bellID, percent: int16,
-                         name: TAtom): bool{.libx11c,
-    importc: "XkbDeviceBellEvent".}
-proc XkbBell*(dpy: PDisplay, win: TWindow, percent: int16, name: TAtom): bool{.
-    libx11c, importc: "XkbBell".}
-proc XkbForceBell*(dpy: PDisplay, percent: int16): bool{.libx11c,
-    importc: "XkbForceBell".}
-proc XkbBellEvent*(dpy: PDisplay, win: TWindow, percent: int16, name: TAtom): bool{.
-    libx11c, importc: "XkbBellEvent".}
-proc XkbSelectEvents*(dpy: PDisplay, deviceID, affect, values: int16): bool{.
-    libx11c, importc: "XkbSelectEvents".}
-proc XkbSelectEventDetails*(dpy: PDisplay, deviceID, eventType: int16,
-                            affect, details: int32): bool{.libx11c, importc: "XkbSelectEventDetails".}
-proc XkbNoteMapChanges*(old: PXkbMapChangesPtr, new: PXkbMapNotifyEvent,
-                        wanted: int16){.libx11c,
-                                        importc: "XkbNoteMapChanges".}
-proc XkbNoteNameChanges*(old: PXkbNameChangesPtr, new: PXkbNamesNotifyEvent,
-                         wanted: int16){.libx11c,
-    importc: "XkbNoteNameChanges".}
-proc XkbGetIndicatorState*(dpy: PDisplay, deviceSpec: int16, pStateRtrn: PWord): TStatus{.
-    libx11c, importc: "XkbGetIndicatorState".}
-proc XkbGetDeviceIndicatorState*(dpy: PDisplay,
-                                 deviceSpec, ledClass, ledID: int16,
-                                 pStateRtrn: PWord): TStatus{.libx11c, importc: "XkbGetDeviceIndicatorState".}
-proc XkbGetIndicatorMap*(dpy: PDisplay, which: int32, desc: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetIndicatorMap".}
-proc XkbSetIndicatorMap*(dpy: PDisplay, which: int32, desc: PXkbDescPtr): bool{.
-    libx11c, importc: "XkbSetIndicatorMap".}
-proc XkbNoteIndicatorMapChanges*(o, n: PXkbIndicatorChangesPtr, w: int16)
-proc XkbNoteIndicatorStateChanges*(o, n: PXkbIndicatorChangesPtr, w: int16)
-proc XkbGetIndicatorMapChanges*(d: PDisplay, x: PXkbDescPtr,
-                                c: PXkbIndicatorChangesPtr): TStatus
-proc XkbChangeIndicatorMaps*(d: PDisplay, x: PXkbDescPtr,
-                             c: PXkbIndicatorChangesPtr): bool
-proc XkbGetNamedIndicator*(dpy: PDisplay, name: TAtom, pNdxRtrn: ptr int16,
-                           pStateRtrn: ptr bool, pMapRtrn: PXkbIndicatorMapPtr,
-                           pRealRtrn: ptr bool): bool{.libx11c,
-    importc: "XkbGetNamedIndicator".}
-proc XkbGetNamedDeviceIndicator*(dpy: PDisplay,
-                                 deviceSpec, ledClass, ledID: int16,
-                                 name: TAtom, pNdxRtrn: ptr int16,
-                                 pStateRtrn: ptr bool,
-                                 pMapRtrn: PXkbIndicatorMapPtr,
-                                 pRealRtrn: ptr bool): bool{.libx11c, importc: "XkbGetNamedDeviceIndicator".}
-proc XkbSetNamedIndicator*(dpy: PDisplay, name: TAtom,
-                           changeState, state, createNewMap: bool,
-                           pMap: PXkbIndicatorMapPtr): bool{.libx11c, importc: "XkbSetNamedIndicator".}
-proc XkbSetNamedDeviceIndicator*(dpy: PDisplay,
-                                 deviceSpec, ledClass, ledID: int16,
-                                 name: TAtom,
-                                 changeState, state, createNewMap: bool,
-                                 pMap: PXkbIndicatorMapPtr): bool{.libx11c, importc: "XkbSetNamedDeviceIndicator".}
-proc XkbLockModifiers*(dpy: PDisplay, deviceSpec, affect, values: int16): bool{.
-    libx11c, importc: "XkbLockModifiers".}
-proc XkbLatchModifiers*(dpy: PDisplay, deviceSpec, affect, values: int16): bool{.
-    libx11c, importc: "XkbLatchModifiers".}
-proc XkbLockGroup*(dpy: PDisplay, deviceSpec, group: int16): bool{.libx11c, importc: "XkbLockGroup".}
-proc XkbLatchGroup*(dpy: PDisplay, deviceSpec, group: int16): bool{.libx11c, importc: "XkbLatchGroup".}
-proc XkbSetServerInternalMods*(dpy: PDisplay, deviceSpec, affectReal,
-    realValues, affectVirtual, virtualValues: int16): bool{.libx11c, importc: "XkbSetServerInternalMods".}
-proc XkbSetIgnoreLockMods*(dpy: PDisplay, deviceSpec, affectReal, realValues,
-    affectVirtual, virtualValues: int16): bool{.libx11c,
-    importc: "XkbSetIgnoreLockMods".}
-proc XkbVirtualModsToReal*(dpy: PDisplay, virtual_mask: int16, mask_rtrn: PWord): bool{.
-    libx11c, importc: "XkbVirtualModsToReal".}
-proc XkbComputeEffectiveMap*(xkb: PXkbDescPtr, theType: PXkbKeyTypePtr,
-                             map_rtrn: PByte): bool{.libx11c,
-    importc: "XkbComputeEffectiveMap".}
-proc XkbInitCanonicalKeyTypes*(xkb: PXkbDescPtr, which: int16, keypadVMod: int16): TStatus{.
-    libx11c, importc: "XkbInitCanonicalKeyTypes".}
-proc XkbAllocKeyboard*(): PXkbDescPtr{.libx11c,
-                                       importc: "XkbAllocKeyboard".}
-proc XkbFreeKeyboard*(xkb: PXkbDescPtr, which: int16, freeDesc: bool){.libx11c, importc: "XkbFreeKeyboard".}
-proc XkbAllocClientMap*(xkb: PXkbDescPtr, which, nTypes: int16): TStatus{.libx11c, importc: "XkbAllocClientMap".}
-proc XkbAllocServerMap*(xkb: PXkbDescPtr, which, nActions: int16): TStatus{.
-    libx11c, importc: "XkbAllocServerMap".}
-proc XkbFreeClientMap*(xkb: PXkbDescPtr, what: int16, freeMap: bool){.libx11c, importc: "XkbFreeClientMap".}
-proc XkbFreeServerMap*(xkb: PXkbDescPtr, what: int16, freeMap: bool){.libx11c, importc: "XkbFreeServerMap".}
-proc XkbAddKeyType*(xkb: PXkbDescPtr, name: TAtom, map_count: int16,
-                    want_preserve: bool, num_lvls: int16): PXkbKeyTypePtr{.
-    libx11c, importc: "XkbAddKeyType".}
-proc XkbAllocIndicatorMaps*(xkb: PXkbDescPtr): TStatus{.libx11c,
-    importc: "XkbAllocIndicatorMaps".}
-proc XkbFreeIndicatorMaps*(xkb: PXkbDescPtr){.libx11c,
-    importc: "XkbFreeIndicatorMaps".}
-proc XkbGetMap*(dpy: PDisplay, which, deviceSpec: int16): PXkbDescPtr{.libx11c, importc: "XkbGetMap".}
-proc XkbGetUpdatedMap*(dpy: PDisplay, which: int16, desc: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetUpdatedMap".}
-proc XkbGetMapChanges*(dpy: PDisplay, xkb: PXkbDescPtr,
-                       changes: PXkbMapChangesPtr): TStatus{.libx11c, importc: "XkbGetMapChanges".}
-proc XkbRefreshKeyboardMapping*(event: PXkbMapNotifyEvent): TStatus{.libx11c, importc: "XkbRefreshKeyboardMapping".}
-proc XkbGetKeyTypes*(dpy: PDisplay, first, num: int16, xkb: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetKeyTypes".}
-proc XkbGetKeySyms*(dpy: PDisplay, first, num: int16, xkb: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetKeySyms".}
-proc XkbGetKeyActions*(dpy: PDisplay, first, num: int16, xkb: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetKeyActions".}
-proc XkbGetKeyBehaviors*(dpy: PDisplay, firstKey, nKeys: int16,
-                         desc: PXkbDescPtr): TStatus{.libx11c,
-    importc: "XkbGetKeyBehaviors".}
-proc XkbGetVirtualMods*(dpy: PDisplay, which: int16, desc: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetVirtualMods".}
-proc XkbGetKeyExplicitComponents*(dpy: PDisplay, firstKey, nKeys: int16,
-                                  desc: PXkbDescPtr): TStatus{.libx11c, importc: "XkbGetKeyExplicitComponents".}
-proc XkbGetKeyModifierMap*(dpy: PDisplay, firstKey, nKeys: int16,
-                           desc: PXkbDescPtr): TStatus{.libx11c,
-    importc: "XkbGetKeyModifierMap".}
-proc XkbAllocControls*(xkb: PXkbDescPtr, which: int16): TStatus{.libx11c, importc: "XkbAllocControls".}
-proc XkbFreeControls*(xkb: PXkbDescPtr, which: int16, freeMap: bool){.libx11c, importc: "XkbFreeControls".}
-proc XkbGetControls*(dpy: PDisplay, which: int32, desc: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetControls".}
-proc XkbSetControls*(dpy: PDisplay, which: int32, desc: PXkbDescPtr): bool{.
-    libx11c, importc: "XkbSetControls".}
-proc XkbNoteControlsChanges*(old: PXkbControlsChangesPtr,
-                             new: PXkbControlsNotifyEvent, wanted: int16){.
-    libx11c, importc: "XkbNoteControlsChanges".}
-proc XkbGetControlsChanges*(d: PDisplay, x: PXkbDescPtr,
-                            c: PXkbControlsChangesPtr): TStatus
-proc XkbChangeControls*(d: PDisplay, x: PXkbDescPtr, c: PXkbControlsChangesPtr): bool
-proc XkbAllocCompatMap*(xkb: PXkbDescPtr, which, nInterpret: int16): TStatus{.
-    libx11c, importc: "XkbAllocCompatMap".}
-proc XkbFreeCompatMap*(xkib: PXkbDescPtr, which: int16, freeMap: bool){.libx11c, importc: "XkbFreeCompatMap".}
-proc XkbGetCompatMap*(dpy: PDisplay, which: int16, xkb: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetCompatMap".}
-proc XkbSetCompatMap*(dpy: PDisplay, which: int16, xkb: PXkbDescPtr,
-                      updateActions: bool): bool{.libx11c,
-    importc: "XkbSetCompatMap".}
-proc XkbAddSymInterpret*(xkb: PXkbDescPtr, si: PXkbSymInterpretPtr,
-                         updateMap: bool, changes: PXkbChangesPtr): PXkbSymInterpretPtr{.
-    libx11c, importc: "XkbAddSymInterpret".}
-proc XkbAllocNames*(xkb: PXkbDescPtr, which: int16,
-                    nTotalRG, nTotalAliases: int16): TStatus{.libx11c, importc: "XkbAllocNames".}
-proc XkbGetNames*(dpy: PDisplay, which: int16, desc: PXkbDescPtr): TStatus{.
-    libx11c, importc: "XkbGetNames".}
-proc XkbSetNames*(dpy: PDisplay, which, firstType, nTypes: int16,
-                  desc: PXkbDescPtr): bool{.libx11c,
-    importc: "XkbSetNames".}
-proc XkbChangeNames*(dpy: PDisplay, xkb: PXkbDescPtr,
-                     changes: PXkbNameChangesPtr): bool{.libx11c,
-    importc: "XkbChangeNames".}
-proc XkbFreeNames*(xkb: PXkbDescPtr, which: int16, freeMap: bool){.libx11c, importc: "XkbFreeNames".}
-proc XkbGetState*(dpy: PDisplay, deviceSpec: int16, rtrnState: PXkbStatePtr): TStatus{.
-    libx11c, importc: "XkbGetState".}
-proc XkbSetMap*(dpy: PDisplay, which: int16, desc: PXkbDescPtr): bool{.libx11c, importc: "XkbSetMap".}
-proc XkbChangeMap*(dpy: PDisplay, desc: PXkbDescPtr, changes: PXkbMapChangesPtr): bool{.
-    libx11c, importc: "XkbChangeMap".}
-proc XkbSetDetectableAutoRepeat*(dpy: PDisplay, detectable: bool,
-                                 supported: ptr bool): bool{.libx11c, importc: "XkbSetDetectableAutoRepeat".}
-proc XkbGetDetectableAutoRepeat*(dpy: PDisplay, supported: ptr bool): bool{.
-    libx11c, importc: "XkbGetDetectableAutoRepeat".}
-proc XkbSetAutoResetControls*(dpy: PDisplay, changes: int16,
-                              auto_ctrls, auto_values: PWord): bool{.libx11c, importc: "XkbSetAutoResetControls".}
-proc XkbGetAutoResetControls*(dpy: PDisplay, auto_ctrls, auto_ctrl_values: PWord): bool{.
-    libx11c, importc: "XkbGetAutoResetControls".}
-proc XkbSetPerClientControls*(dpy: PDisplay, change: int16, values: PWord): bool{.
-    libx11c, importc: "XkbSetPerClientControls".}
-proc XkbGetPerClientControls*(dpy: PDisplay, ctrls: PWord): bool{.libx11c, importc: "XkbGetPerClientControls".}
-proc XkbCopyKeyType*(`from`, into: PXkbKeyTypePtr): TStatus{.libx11c, importc: "XkbCopyKeyType".}
-proc XkbCopyKeyTypes*(`from`, into: PXkbKeyTypePtr, num_types: int16): TStatus{.
-    libx11c, importc: "XkbCopyKeyTypes".}
-proc XkbResizeKeyType*(xkb: PXkbDescPtr, type_ndx, map_count: int16,
-                       want_preserve: bool, new_num_lvls: int16): TStatus{.
-    libx11c, importc: "XkbResizeKeyType".}
-proc XkbResizeKeySyms*(desc: PXkbDescPtr, forKey, symsNeeded: int16): PKeySym{.
-    libx11c, importc: "XkbResizeKeySyms".}
-proc XkbResizeKeyActions*(desc: PXkbDescPtr, forKey, actsNeeded: int16): PXkbAction{.
-    libx11c, importc: "XkbResizeKeyActions".}
-proc XkbChangeTypesOfKey*(xkb: PXkbDescPtr, key, num_groups: int16,
-                          groups: int16, newTypes: ptr int16,
-                          pChanges: PXkbMapChangesPtr): TStatus{.libx11c, importc: "XkbChangeTypesOfKey".}
-
-proc XkbListComponents*(dpy: PDisplay, deviceSpec: int16,
-                        ptrns: PXkbComponentNamesPtr, max_inout: ptr int16): PXkbComponentListPtr{.
-    libx11c, importc: "XkbListComponents".}
-proc XkbFreeComponentList*(list: PXkbComponentListPtr){.libx11c,
-    importc: "XkbFreeComponentList".}
-proc XkbGetKeyboard*(dpy: PDisplay, which, deviceSpec: int16): PXkbDescPtr{.
-    libx11c, importc: "XkbGetKeyboard".}
-proc XkbGetKeyboardByName*(dpy: PDisplay, deviceSpec: int16,
-                           names: PXkbComponentNamesPtr, want, need: int16,
-                           load: bool): PXkbDescPtr{.libx11c,
-    importc: "XkbGetKeyboardByName".}
-
-proc XkbKeyTypesForCoreSymbols*(xkb: PXkbDescPtr,
-                                map_width: int16,  # keyboard device
-                                core_syms: PKeySym,  # always mapWidth symbols
-                                protected: int16,  # explicit key types
-                                types_inout: ptr int16,  # always four type indices
-                                xkb_syms_rtrn: PKeySym): int16{.libx11c, importc: "XkbKeyTypesForCoreSymbols".}
-  # must have enough space
-proc XkbApplyCompatMapToKey*(xkb: PXkbDescPtr,
-                             key: TKeyCode,  # key to be updated
-                             changes: PXkbChangesPtr): bool{.libx11c, importc: "XkbApplyCompatMapToKey".}
-  # resulting changes to map
-proc XkbUpdateMapFromCore*(xkb: PXkbDescPtr,
-                           first_key: TKeyCode,  # first changed key
-                           num_keys,
-                           map_width: int16,
-                           core_keysyms: PKeySym,  # symbols `from` core keymap
-                           changes: PXkbChangesPtr): bool{.libx11c, importc: "XkbUpdateMapFromCore".}
-
-proc XkbAddDeviceLedInfo*(devi: PXkbDeviceInfoPtr, ledClass, ledId: int16): PXkbDeviceLedInfoPtr{.
-    libx11c, importc: "XkbAddDeviceLedInfo".}
-proc XkbResizeDeviceButtonActions*(devi: PXkbDeviceInfoPtr, newTotal: int16): TStatus{.
-    libx11c, importc: "XkbResizeDeviceButtonActions".}
-proc XkbAllocDeviceInfo*(deviceSpec, nButtons, szLeds: int16): PXkbDeviceInfoPtr{.
-    libx11c, importc: "XkbAllocDeviceInfo".}
-proc XkbFreeDeviceInfo*(devi: PXkbDeviceInfoPtr, which: int16, freeDevI: bool){.
-    libx11c, importc: "XkbFreeDeviceInfo".}
-proc XkbNoteDeviceChanges*(old: PXkbDeviceChangesPtr,
-                           new: PXkbExtensionDeviceNotifyEvent, wanted: int16){.
-    libx11c, importc: "XkbNoteDeviceChanges".}
-proc XkbGetDeviceInfo*(dpy: PDisplay, which, deviceSpec, ledClass, ledID: int16): PXkbDeviceInfoPtr{.
-    libx11c, importc: "XkbGetDeviceInfo".}
-proc XkbGetDeviceInfoChanges*(dpy: PDisplay, devi: PXkbDeviceInfoPtr,
-                              changes: PXkbDeviceChangesPtr): TStatus{.libx11c, importc: "XkbGetDeviceInfoChanges".}
-proc XkbGetDeviceButtonActions*(dpy: PDisplay, devi: PXkbDeviceInfoPtr,
-                                all: bool, first, nBtns: int16): TStatus{.libx11c, importc: "XkbGetDeviceButtonActions".}
-proc XkbGetDeviceLedInfo*(dpy: PDisplay, devi: PXkbDeviceInfoPtr,
-                          ledClass, ledId, which: int16): TStatus{.libx11c, importc: "XkbGetDeviceLedInfo".}
-proc XkbSetDeviceInfo*(dpy: PDisplay, which: int16, devi: PXkbDeviceInfoPtr): bool{.
-    libx11c, importc: "XkbSetDeviceInfo".}
-proc XkbChangeDeviceInfo*(dpy: PDisplay, desc: PXkbDeviceInfoPtr,
-                          changes: PXkbDeviceChangesPtr): bool{.libx11c, importc: "XkbChangeDeviceInfo".}
-proc XkbSetDeviceLedInfo*(dpy: PDisplay, devi: PXkbDeviceInfoPtr,
-                          ledClass, ledID, which: int16): bool{.libx11c, importc: "XkbSetDeviceLedInfo".}
-proc XkbSetDeviceButtonActions*(dpy: PDisplay, devi: PXkbDeviceInfoPtr,
-                                first, nBtns: int16): bool{.libx11c, importc: "XkbSetDeviceButtonActions".}
-
-proc XkbToControl*(c: int8): int8{.libx11c,
-                                   importc: "XkbToControl".}
-
-proc XkbSetDebuggingFlags*(dpy: PDisplay, mask, flags: int16, msg: cstring,
-                           ctrls_mask, ctrls, rtrn_flags, rtrn_ctrls: int16): bool{.
-    libx11c, importc: "XkbSetDebuggingFlags".}
-proc XkbApplyVirtualModChanges*(xkb: PXkbDescPtr, changed: int16,
-                                changes: PXkbChangesPtr): bool{.libx11c, importc: "XkbApplyVirtualModChanges".}
-
-# implementation
-
-proc XkbNoteIndicatorMapChanges(o, n: PXkbIndicatorChangesPtr, w: int16) =
-  ##define XkbNoteIndicatorMapChanges(o,n,w) ((o)->map_changes|=((n)->map_changes&(w)))
-  o.map_changes = o.map_changes or (n.map_changes and w)
-
-proc XkbNoteIndicatorStateChanges(o, n: PXkbIndicatorChangesPtr, w: int16) =
-  ##define XkbNoteIndicatorStateChanges(o,n,w) ((o)->state_changes|=((n)->state_changes&(w)))
-  o.state_changes = o.state_changes or (n.state_changes and (w))
-
-proc XkbGetIndicatorMapChanges(d: PDisplay, x: PXkbDescPtr,
-                               c: PXkbIndicatorChangesPtr): TStatus =
-  ##define XkbGetIndicatorMapChanges(d,x,c) (XkbGetIndicatorMap((d),(c)->map_changes,x)
-  result = XkbGetIndicatorMap(d, c.map_changes, x)
-
-proc XkbChangeIndicatorMaps(d: PDisplay, x: PXkbDescPtr,
-                            c: PXkbIndicatorChangesPtr): bool =
-  ##define XkbChangeIndicatorMaps(d,x,c) (XkbSetIndicatorMap((d),(c)->map_changes,x))
-  result = XkbSetIndicatorMap(d, c.map_changes, x)
-
-proc XkbGetControlsChanges(d: PDisplay, x: PXkbDescPtr,
-                           c: PXkbControlsChangesPtr): TStatus =
-  ##define XkbGetControlsChanges(d,x,c) XkbGetControls(d,(c)->changed_ctrls,x)
-  result = XkbGetControls(d, c.changed_ctrls, x)
-
-proc XkbChangeControls(d: PDisplay, x: PXkbDescPtr, c: PXkbControlsChangesPtr): bool =
-  ##define XkbChangeControls(d,x,c) XkbSetControls(d,(c)->changed_ctrls,x)
-  result = XkbSetControls(d, c.changed_ctrls, x)
diff --git a/tests/deps/x11-1.0/xlib.nim b/tests/deps/x11-1.0/xlib.nim
deleted file mode 100644
index e9f211936..000000000
--- a/tests/deps/x11-1.0/xlib.nim
+++ /dev/null
@@ -1,2026 +0,0 @@
-
-import
-  x
-
-include "x11pragma.nim"
-
-type
-  cunsigned* = cint
-  Pcint* = ptr cint
-  PPcint* = ptr Pcint
-  PPcuchar* = ptr ptr cuchar
-  PWideChar* = ptr int16
-  PPChar* = ptr cstring
-  PPPChar* = ptr ptr cstring
-  Pculong* = ptr culong
-  Pcuchar* = cstring
-  Pcuint* = ptr cuint
-  Pcushort* = ptr uint16
-#  Automatically converted by H2Pas 0.99.15 from xlib.h
-#  The following command line parameters were used:
-#    -p
-#    -T
-#    -S
-#    -d
-#    -c
-#    xlib.h
-
-const
-  XlibSpecificationRelease* = 6
-
-type
-  PXPointer* = ptr TXPointer
-  TXPointer* = ptr char
-  PBool* = ptr TBool
-  TBool* = int           #cint?
-  PStatus* = ptr TStatus
-  TStatus* = cint
-
-const
-  QueuedAlready* = 0
-  QueuedAfterReading* = 1
-  QueuedAfterFlush* = 2
-
-type
-  PPXExtData* = ptr PXExtData
-  PXExtData* = ptr TXExtData
-  TXExtData*{.final.} = object
-    number*: cint
-    next*: PXExtData
-    free_private*: proc (extension: PXExtData): cint{.cdecl.}
-    private_data*: TXPointer
-
-  PXExtCodes* = ptr TXExtCodes
-  TXExtCodes*{.final.} = object
-    extension*: cint
-    major_opcode*: cint
-    first_event*: cint
-    first_error*: cint
-
-  PXPixmapFormatValues* = ptr TXPixmapFormatValues
-  TXPixmapFormatValues*{.final.} = object
-    depth*: cint
-    bits_per_pixel*: cint
-    scanline_pad*: cint
-
-  PXGCValues* = ptr TXGCValues
-  TXGCValues*{.final.} = object
-    function*: cint
-    plane_mask*: culong
-    foreground*: culong
-    background*: culong
-    line_width*: cint
-    line_style*: cint
-    cap_style*: cint
-    join_style*: cint
-    fill_style*: cint
-    fill_rule*: cint
-    arc_mode*: cint
-    tile*: TPixmap
-    stipple*: TPixmap
-    ts_x_origin*: cint
-    ts_y_origin*: cint
-    font*: TFont
-    subwindow_mode*: cint
-    graphics_exposures*: TBool
-    clip_x_origin*: cint
-    clip_y_origin*: cint
-    clip_mask*: TPixmap
-    dash_offset*: cint
-    dashes*: cchar
-
-  PXGC* = ptr TXGC
-  TXGC*{.final.} = object
-  TGC* = PXGC
-  PGC* = ptr TGC
-  PVisual* = ptr TVisual
-  TVisual*{.final.} = object
-    ext_data*: PXExtData
-    visualid*: TVisualID
-    c_class*: cint
-    red_mask*, green_mask*, blue_mask*: culong
-    bits_per_rgb*: cint
-    map_entries*: cint
-
-  PDepth* = ptr TDepth
-  TDepth*{.final.} = object
-    depth*: cint
-    nvisuals*: cint
-    visuals*: PVisual
-
-  PXDisplay* = ptr TXDisplay
-  TXDisplay*{.final.} = object
-  PScreen* = ptr TScreen
-  TScreen*{.final.} = object
-    ext_data*: PXExtData
-    display*: PXDisplay
-    root*: TWindow
-    width*, height*: cint
-    mwidth*, mheight*: cint
-    ndepths*: cint
-    depths*: PDepth
-    root_depth*: cint
-    root_visual*: PVisual
-    default_gc*: TGC
-    cmap*: TColormap
-    white_pixel*: culong
-    black_pixel*: culong
-    max_maps*, min_maps*: cint
-    backing_store*: cint
-    save_unders*: TBool
-    root_input_mask*: clong
-
-  PScreenFormat* = ptr TScreenFormat
-  TScreenFormat*{.final.} = object
-    ext_data*: PXExtData
-    depth*: cint
-    bits_per_pixel*: cint
-    scanline_pad*: cint
-
-  PXSetWindowAttributes* = ptr TXSetWindowAttributes
-  TXSetWindowAttributes*{.final.} = object
-    background_pixmap*: TPixmap
-    background_pixel*: culong
-    border_pixmap*: TPixmap
-    border_pixel*: culong
-    bit_gravity*: cint
-    win_gravity*: cint
-    backing_store*: cint
-    backing_planes*: culong
-    backing_pixel*: culong
-    save_under*: TBool
-    event_mask*: clong
-    do_not_propagate_mask*: clong
-    override_redirect*: TBool
-    colormap*: TColormap
-    cursor*: TCursor
-
-  PXWindowAttributes* = ptr TXWindowAttributes
-  TXWindowAttributes*{.final.} = object
-    x*, y*: cint
-    width*, height*: cint
-    border_width*: cint
-    depth*: cint
-    visual*: PVisual
-    root*: TWindow
-    c_class*: cint
-    bit_gravity*: cint
-    win_gravity*: cint
-    backing_store*: cint
-    backing_planes*: culong
-    backing_pixel*: culong
-    save_under*: TBool
-    colormap*: TColormap
-    map_installed*: TBool
-    map_state*: cint
-    all_event_masks*: clong
-    your_event_mask*: clong
-    do_not_propagate_mask*: clong
-    override_redirect*: TBool
-    screen*: PScreen
-
-  PXHostAddress* = ptr TXHostAddress
-  TXHostAddress*{.final.} = object
-    family*: cint
-    len*: cint
-    address*: cstring
-
-  PXServerInterpretedAddress* = ptr TXServerInterpretedAddress
-  TXServerInterpretedAddress*{.final.} = object
-    typelength*: cint
-    valuelength*: cint
-    theType*: cstring
-    value*: cstring
-
-  PXImage* = ptr TXImage
-  TF*{.final.} = object
-    create_image*: proc (para1: PXDisplay, para2: PVisual, para3: cuint,
-                         para4: cint, para5: cint, para6: cstring, para7: cuint,
-                         para8: cuint, para9: cint, para10: cint): PXImage{.
-        cdecl.}
-    destroy_image*: proc (para1: PXImage): cint{.cdecl.}
-    get_pixel*: proc (para1: PXImage, para2: cint, para3: cint): culong{.cdecl.}
-    put_pixel*: proc (para1: PXImage, para2: cint, para3: cint, para4: culong): cint{.
-        cdecl.}
-    sub_image*: proc (para1: PXImage, para2: cint, para3: cint, para4: cuint,
-                      para5: cuint): PXImage{.cdecl.}
-    add_pixel*: proc (para1: PXImage, para2: clong): cint{.cdecl.}
-
-  TXImage*{.final.} = object
-    width*, height*: cint
-    xoffset*: cint
-    format*: cint
-    data*: cstring
-    byte_order*: cint
-    bitmap_unit*: cint
-    bitmap_bit_order*: cint
-    bitmap_pad*: cint
-    depth*: cint
-    bytes_per_line*: cint
-    bits_per_pixel*: cint
-    red_mask*: culong
-    green_mask*: culong
-    blue_mask*: culong
-    obdata*: TXPointer
-    f*: TF
-
-  PXWindowChanges* = ptr TXWindowChanges
-  TXWindowChanges*{.final.} = object
-    x*, y*: cint
-    width*, height*: cint
-    border_width*: cint
-    sibling*: TWindow
-    stack_mode*: cint
-
-  PXColor* = ptr TXColor
-  TXColor*{.final.} = object
-    pixel*: culong
-    red*, green*, blue*: cushort
-    flags*: cchar
-    pad*: cchar
-
-  PXSegment* = ptr TXSegment
-  TXSegment*{.final.} = object
-    x1*, y1*, x2*, y2*: cshort
-
-  PXPoint* = ptr TXPoint
-  TXPoint*{.final.} = object
-    x*, y*: cshort
-
-  PXRectangle* = ptr TXRectangle
-  TXRectangle*{.final.} = object
-    x*, y*: cshort
-    width*, height*: cushort
-
-  PXArc* = ptr TXArc
-  TXArc*{.final.} = object
-    x*, y*: cshort
-    width*, height*: cushort
-    angle1*, angle2*: cshort
-
-  PXKeyboardControl* = ptr TXKeyboardControl
-  TXKeyboardControl*{.final.} = object
-    key_click_percent*: cint
-    bell_percent*: cint
-    bell_pitch*: cint
-    bell_duration*: cint
-    led*: cint
-    led_mode*: cint
-    key*: cint
-    auto_repeat_mode*: cint
-
-  PXKeyboardState* = ptr TXKeyboardState
-  TXKeyboardState*{.final.} = object
-    key_click_percent*: cint
-    bell_percent*: cint
-    bell_pitch*, bell_duration*: cuint
-    led_mask*: culong
-    global_auto_repeat*: cint
-    auto_repeats*: array[0..31, cchar]
-
-  PXTimeCoord* = ptr TXTimeCoord
-  TXTimeCoord*{.final.} = object
-    time*: TTime
-    x*, y*: cshort
-
-  PXModifierKeymap* = ptr TXModifierKeymap
-  TXModifierKeymap*{.final.} = object
-    max_keypermod*: cint
-    modifiermap*: PKeyCode
-
-  PDisplay* = ptr TDisplay
-  TDisplay* = TXDisplay
-  PXPrivate* = ptr TXPrivate
-  TXPrivate*{.final.} = object
-  PXrmHashBucketRec* = ptr TXrmHashBucketRec
-  TXrmHashBucketRec*{.final.} = object
-  PXPrivDisplay* = ptr TXPrivDisplay
-  TXPrivDisplay*{.final.} = object
-    ext_data*: PXExtData
-    private1*: PXPrivate
-    fd*: cint
-    private2*: cint
-    proto_major_version*: cint
-    proto_minor_version*: cint
-    vendor*: cstring
-    private3*: TXID
-    private4*: TXID
-    private5*: TXID
-    private6*: cint
-    resource_alloc*: proc (para1: PXDisplay): TXID{.cdecl.}
-    byte_order*: cint
-    bitmap_unit*: cint
-    bitmap_pad*: cint
-    bitmap_bit_order*: cint
-    nformats*: cint
-    pixmap_format*: PScreenFormat
-    private8*: cint
-    release*: cint
-    private9*, private10*: PXPrivate
-    qlen*: cint
-    last_request_read*: culong
-    request*: culong
-    private11*: TXPointer
-    private12*: TXPointer
-    private13*: TXPointer
-    private14*: TXPointer
-    max_request_size*: cunsigned
-    db*: PXrmHashBucketRec
-    private15*: proc (para1: PXDisplay): cint{.cdecl.}
-    display_name*: cstring
-    default_screen*: cint
-    nscreens*: cint
-    screens*: PScreen
-    motion_buffer*: culong
-    private16*: culong
-    min_keycode*: cint
-    max_keycode*: cint
-    private17*: TXPointer
-    private18*: TXPointer
-    private19*: cint
-    xdefaults*: cstring
-
-  PXKeyEvent* = ptr TXKeyEvent
-  TXKeyEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    root*: TWindow
-    subwindow*: TWindow
-    time*: TTime
-    x*, y*: cint
-    x_root*, y_root*: cint
-    state*: cuint
-    keycode*: cuint
-    same_screen*: TBool
-
-  PXKeyPressedEvent* = ptr TXKeyPressedEvent
-  TXKeyPressedEvent* = TXKeyEvent
-  PXKeyReleasedEvent* = ptr TXKeyReleasedEvent
-  TXKeyReleasedEvent* = TXKeyEvent
-  PXButtonEvent* = ptr TXButtonEvent
-  TXButtonEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    root*: TWindow
-    subwindow*: TWindow
-    time*: TTime
-    x*, y*: cint
-    x_root*, y_root*: cint
-    state*: cuint
-    button*: cuint
-    same_screen*: TBool
-
-  PXButtonPressedEvent* = ptr TXButtonPressedEvent
-  TXButtonPressedEvent* = TXButtonEvent
-  PXButtonReleasedEvent* = ptr TXButtonReleasedEvent
-  TXButtonReleasedEvent* = TXButtonEvent
-  PXMotionEvent* = ptr TXMotionEvent
-  TXMotionEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    root*: TWindow
-    subwindow*: TWindow
-    time*: TTime
-    x*, y*: cint
-    x_root*, y_root*: cint
-    state*: cuint
-    is_hint*: cchar
-    same_screen*: TBool
-
-  PXPointerMovedEvent* = ptr TXPointerMovedEvent
-  TXPointerMovedEvent* = TXMotionEvent
-  PXCrossingEvent* = ptr TXCrossingEvent
-  TXCrossingEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    root*: TWindow
-    subwindow*: TWindow
-    time*: TTime
-    x*, y*: cint
-    x_root*, y_root*: cint
-    mode*: cint
-    detail*: cint
-    same_screen*: TBool
-    focus*: TBool
-    state*: cuint
-
-  PXEnterWindowEvent* = ptr TXEnterWindowEvent
-  TXEnterWindowEvent* = TXCrossingEvent
-  PXLeaveWindowEvent* = ptr TXLeaveWindowEvent
-  TXLeaveWindowEvent* = TXCrossingEvent
-  PXFocusChangeEvent* = ptr TXFocusChangeEvent
-  TXFocusChangeEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    mode*: cint
-    detail*: cint
-
-  PXFocusInEvent* = ptr TXFocusInEvent
-  TXFocusInEvent* = TXFocusChangeEvent
-  PXFocusOutEvent* = ptr TXFocusOutEvent
-  TXFocusOutEvent* = TXFocusChangeEvent
-  PXKeymapEvent* = ptr TXKeymapEvent
-  TXKeymapEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    key_vector*: array[0..31, cchar]
-
-  PXExposeEvent* = ptr TXExposeEvent
-  TXExposeEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    x*, y*: cint
-    width*, height*: cint
-    count*: cint
-
-  PXGraphicsExposeEvent* = ptr TXGraphicsExposeEvent
-  TXGraphicsExposeEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    drawable*: TDrawable
-    x*, y*: cint
-    width*, height*: cint
-    count*: cint
-    major_code*: cint
-    minor_code*: cint
-
-  PXNoExposeEvent* = ptr TXNoExposeEvent
-  TXNoExposeEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    drawable*: TDrawable
-    major_code*: cint
-    minor_code*: cint
-
-  PXVisibilityEvent* = ptr TXVisibilityEvent
-  TXVisibilityEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    state*: cint
-
-  PXCreateWindowEvent* = ptr TXCreateWindowEvent
-  TXCreateWindowEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    parent*: TWindow
-    window*: TWindow
-    x*, y*: cint
-    width*, height*: cint
-    border_width*: cint
-    override_redirect*: TBool
-
-  PXDestroyWindowEvent* = ptr TXDestroyWindowEvent
-  TXDestroyWindowEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    event*: TWindow
-    window*: TWindow
-
-  PXUnmapEvent* = ptr TXUnmapEvent
-  TXUnmapEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    event*: TWindow
-    window*: TWindow
-    from_configure*: TBool
-
-  PXMapEvent* = ptr TXMapEvent
-  TXMapEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    event*: TWindow
-    window*: TWindow
-    override_redirect*: TBool
-
-  PXMapRequestEvent* = ptr TXMapRequestEvent
-  TXMapRequestEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    parent*: TWindow
-    window*: TWindow
-
-  PXReparentEvent* = ptr TXReparentEvent
-  TXReparentEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    event*: TWindow
-    window*: TWindow
-    parent*: TWindow
-    x*, y*: cint
-    override_redirect*: TBool
-
-  PXConfigureEvent* = ptr TXConfigureEvent
-  TXConfigureEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    event*: TWindow
-    window*: TWindow
-    x*, y*: cint
-    width*, height*: cint
-    border_width*: cint
-    above*: TWindow
-    override_redirect*: TBool
-
-  PXGravityEvent* = ptr TXGravityEvent
-  TXGravityEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    event*: TWindow
-    window*: TWindow
-    x*, y*: cint
-
-  PXResizeRequestEvent* = ptr TXResizeRequestEvent
-  TXResizeRequestEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    width*, height*: cint
-
-  PXConfigureRequestEvent* = ptr TXConfigureRequestEvent
-  TXConfigureRequestEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    parent*: TWindow
-    window*: TWindow
-    x*, y*: cint
-    width*, height*: cint
-    border_width*: cint
-    above*: TWindow
-    detail*: cint
-    value_mask*: culong
-
-  PXCirculateEvent* = ptr TXCirculateEvent
-  TXCirculateEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    event*: TWindow
-    window*: TWindow
-    place*: cint
-
-  PXCirculateRequestEvent* = ptr TXCirculateRequestEvent
-  TXCirculateRequestEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    parent*: TWindow
-    window*: TWindow
-    place*: cint
-
-  PXPropertyEvent* = ptr TXPropertyEvent
-  TXPropertyEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    atom*: TAtom
-    time*: TTime
-    state*: cint
-
-  PXSelectionClearEvent* = ptr TXSelectionClearEvent
-  TXSelectionClearEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    selection*: TAtom
-    time*: TTime
-
-  PXSelectionRequestEvent* = ptr TXSelectionRequestEvent
-  TXSelectionRequestEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    owner*: TWindow
-    requestor*: TWindow
-    selection*: TAtom
-    target*: TAtom
-    property*: TAtom
-    time*: TTime
-
-  PXSelectionEvent* = ptr TXSelectionEvent
-  TXSelectionEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    requestor*: TWindow
-    selection*: TAtom
-    target*: TAtom
-    property*: TAtom
-    time*: TTime
-
-  PXColormapEvent* = ptr TXColormapEvent
-  TXColormapEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    colormap*: TColormap
-    c_new*: TBool
-    state*: cint
-
-  PXClientMessageEvent* = ptr TXClientMessageEvent
-  TXClientMessageEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    message_type*: TAtom
-    format*: cint
-    data*: array[0..4, clong] # using clong here to be 32/64-bit dependent
-        # as the original C union
-
-  PXMappingEvent* = ptr TXMappingEvent
-  TXMappingEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-    request*: cint
-    first_keycode*: cint
-    count*: cint
-
-  PXErrorEvent* = ptr TXErrorEvent
-  TXErrorEvent*{.final.} = object
-    theType*: cint
-    display*: PDisplay
-    resourceid*: TXID
-    serial*: culong
-    error_code*: cuchar
-    request_code*: cuchar
-    minor_code*: cuchar
-
-  PXAnyEvent* = ptr TXAnyEvent
-  TXAnyEvent*{.final.} = object
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    window*: TWindow
-
-  PXEvent* = ptr TXEvent
-  TXEvent*{.final.} = object
-    theType*: cint
-    pad*: array[0..22, clong] #
-                              #       case longint of
-                              #          0 : ( theType : cint );
-                              #          1 : ( xany : TXAnyEvent );
-                              #          2 : ( xkey : TXKeyEvent );
-                              #          3 : ( xbutton : TXButtonEvent );
-                              #          4 : ( xmotion : TXMotionEvent );
-                              #          5 : ( xcrossing : TXCrossingEvent );
-                              #          6 : ( xfocus : TXFocusChangeEvent );
-                              #          7 : ( xexpose : TXExposeEvent );
-                              #          8 : ( xgraphicsexpose : TXGraphicsExposeEvent );
-                              #          9 : ( xnoexpose : TXNoExposeEvent );
-                              #          10 : ( xvisibility : TXVisibilityEvent );
-                              #          11 : ( xcreatewindow : TXCreateWindowEvent );
-                              #          12 : ( xdestroywindow : TXDestroyWindowEvent );
-                              #          13 : ( xunmap : TXUnmapEvent );
-                              #          14 : ( xmap : TXMapEvent );
-                              #          15 : ( xmaprequest : TXMapRequestEvent );
-                              #          16 : ( xreparent : TXReparentEvent );
-                              #          17 : ( xconfigure : TXConfigureEvent );
-                              #          18 : ( xgravity : TXGravityEvent );
-                              #          19 : ( xresizerequest : TXResizeRequestEvent );
-                              #          20 : ( xconfigurerequest : TXConfigureRequestEvent );
-                              #          21 : ( xcirculate : TXCirculateEvent );
-                              #          22 : ( xcirculaterequest : TXCirculateRequestEvent );
-                              #          23 : ( xproperty : TXPropertyEvent );
-                              #          24 : ( xselectionclear : TXSelectionClearEvent );
-                              #          25 : ( xselectionrequest : TXSelectionRequestEvent );
-                              #          26 : ( xselection : TXSelectionEvent );
-                              #          27 : ( xcolormap : TXColormapEvent );
-                              #          28 : ( xclient : TXClientMessageEvent );
-                              #          29 : ( xmapping : TXMappingEvent );
-                              #          30 : ( xerror : TXErrorEvent );
-                              #          31 : ( xkeymap : TXKeymapEvent );
-                              #          32 : ( pad : array[0..23] of clong );
-                              #
-
-
-proc xclient*(e: PXEvent): PXClientMessageEvent =
-    ## Treats XEvent as XClientMessageEvent
-    return cast[PXClientMessageEvent](e)
-
-proc xclient*(e: var TXEvent): PXClientMessageEvent =
-    return xclient(PXEvent(e.addr))
-
-type
-  PXCharStruct* = ptr TXCharStruct
-  TXCharStruct*{.final.} = object
-    lbearing*: cshort
-    rbearing*: cshort
-    width*: cshort
-    ascent*: cshort
-    descent*: cshort
-    attributes*: cushort
-
-  PXFontProp* = ptr TXFontProp
-  TXFontProp*{.final.} = object
-    name*: TAtom
-    card32*: culong
-
-  PPPXFontStruct* = ptr PPXFontStruct
-  PPXFontStruct* = ptr PXFontStruct
-  PXFontStruct* = ptr TXFontStruct
-  TXFontStruct*{.final.} = object
-    ext_data*: PXExtData
-    fid*: TFont
-    direction*: cunsigned
-    min_char_or_byte2*: cunsigned
-    max_char_or_byte2*: cunsigned
-    min_byte1*: cunsigned
-    max_byte1*: cunsigned
-    all_chars_exist*: TBool
-    default_char*: cunsigned
-    n_properties*: cint
-    properties*: PXFontProp
-    min_bounds*: TXCharStruct
-    max_bounds*: TXCharStruct
-    per_char*: PXCharStruct
-    ascent*: cint
-    descent*: cint
-
-  PXTextItem* = ptr TXTextItem
-  TXTextItem*{.final.} = object
-    chars*: cstring
-    nchars*: cint
-    delta*: cint
-    font*: TFont
-
-  PXChar2b* = ptr TXChar2b
-  TXChar2b*{.final.} = object
-    byte1*: cuchar
-    byte2*: cuchar
-
-  PXTextItem16* = ptr TXTextItem16
-  TXTextItem16*{.final.} = object
-    chars*: PXChar2b
-    nchars*: cint
-    delta*: cint
-    font*: TFont
-
-  PXEDataObject* = ptr TXEDataObject
-  TXEDataObject*{.final.} = object
-    display*: PDisplay        #case longint of
-                              #          0 : ( display : PDisplay );
-                              #          1 : ( gc : TGC );
-                              #          2 : ( visual : PVisual );
-                              #          3 : ( screen : PScreen );
-                              #          4 : ( pixmap_format : PScreenFormat );
-                              #          5 : ( font : PXFontStruct );
-
-  PXFontSetExtents* = ptr TXFontSetExtents
-  TXFontSetExtents*{.final.} = object
-    max_ink_extent*: TXRectangle
-    max_logical_extent*: TXRectangle
-
-  PXOM* = ptr TXOM
-  TXOM*{.final.} = object
-  PXOC* = ptr TXOC
-  TXOC*{.final.} = object
-  TXFontSet* = PXOC
-  PXFontSet* = ptr TXFontSet
-  PXmbTextItem* = ptr TXmbTextItem
-  TXmbTextItem*{.final.} = object
-    chars*: cstring
-    nchars*: cint
-    delta*: cint
-    font_set*: TXFontSet
-
-  PXwcTextItem* = ptr TXwcTextItem
-  TXwcTextItem*{.final.} = object
-    chars*: PWideChar         #wchar_t*
-    nchars*: cint
-    delta*: cint
-    font_set*: TXFontSet
-
-
-const
-  XNRequiredCharSet* = "requiredCharSet"
-  XNQueryOrientation* = "queryOrientation"
-  XNBaseFontName* = "baseFontName"
-  XNOMAutomatic* = "omAutomatic"
-  XNMissingCharSet* = "missingCharSet"
-  XNDefaultString* = "defaultString"
-  XNOrientation* = "orientation"
-  XNDirectionalDependentDrawing* = "directionalDependentDrawing"
-  XNContextualDrawing* = "contextualDrawing"
-  XNFontInfo* = "fontInfo"
-
-type
-  PXOMCharSetList* = ptr TXOMCharSetList
-  TXOMCharSetList*{.final.} = object
-    charset_count*: cint
-    charset_list*: PPChar
-
-  PXOrientation* = ptr TXOrientation
-  TXOrientation* = enum
-    XOMOrientation_LTR_TTB, XOMOrientation_RTL_TTB, XOMOrientation_TTB_LTR,
-    XOMOrientation_TTB_RTL, XOMOrientation_Context
-  PXOMOrientation* = ptr TXOMOrientation
-  TXOMOrientation*{.final.} = object
-    num_orientation*: cint
-    orientation*: PXOrientation
-
-  PXOMFontInfo* = ptr TXOMFontInfo
-  TXOMFontInfo*{.final.} = object
-    num_font*: cint
-    font_struct_list*: ptr PXFontStruct
-    font_name_list*: PPChar
-
-  PXIM* = ptr TXIM
-  TXIM*{.final.} = object
-  PXIC* = ptr TXIC
-  TXIC*{.final.} = object
-  TXIMProc* = proc (para1: TXIM, para2: TXPointer, para3: TXPointer){.cdecl.}
-  TXICProc* = proc (para1: TXIC, para2: TXPointer, para3: TXPointer): TBool{.
-      cdecl.}
-  TXIDProc* = proc (para1: PDisplay, para2: TXPointer, para3: TXPointer){.cdecl.}
-  PXIMStyle* = ptr TXIMStyle
-  TXIMStyle* = culong
-  PXIMStyles* = ptr TXIMStyles
-  TXIMStyles*{.final.} = object
-    count_styles*: cushort
-    supported_styles*: PXIMStyle
-
-
-const
-  XIMPreeditArea* = 0x00000001
-  XIMPreeditCallbacks* = 0x00000002
-  XIMPreeditPosition* = 0x00000004
-  XIMPreeditNothing* = 0x00000008
-  XIMPreeditNone* = 0x00000010
-  XIMStatusArea* = 0x00000100
-  XIMStatusCallbacks* = 0x00000200
-  XIMStatusNothing* = 0x00000400
-  XIMStatusNone* = 0x00000800
-  XNVaNestedList* = "XNVaNestedList"
-  XNQueryInputStyle* = "queryInputStyle"
-  XNClientWindow* = "clientWindow"
-  XNInputStyle* = "inputStyle"
-  XNFocusWindow* = "focusWindow"
-  XNResourceName* = "resourceName"
-  XNResourceClass* = "resourceClass"
-  XNGeometryCallback* = "geometryCallback"
-  XNDestroyCallback* = "destroyCallback"
-  XNFilterEvents* = "filterEvents"
-  XNPreeditStartCallback* = "preeditStartCallback"
-  XNPreeditDoneCallback* = "preeditDoneCallback"
-  XNPreeditDrawCallback* = "preeditDrawCallback"
-  XNPreeditCaretCallback* = "preeditCaretCallback"
-  XNPreeditStateNotifyCallback* = "preeditStateNotifyCallback"
-  XNPreeditAttributes* = "preeditAttributes"
-  XNStatusStartCallback* = "statusStartCallback"
-  XNStatusDoneCallback* = "statusDoneCallback"
-  XNStatusDrawCallback* = "statusDrawCallback"
-  XNStatusAttributes* = "statusAttributes"
-  XNArea* = "area"
-  XNAreaNeeded* = "areaNeeded"
-  XNSpotLocation* = "spotLocation"
-  XNColormap* = "colorMap"
-  XNStdColormap* = "stdColorMap"
-  XNForeground* = "foreground"
-  XNBackground* = "background"
-  XNBackgroundPixmap* = "backgroundPixmap"
-  XNFontSet* = "fontSet"
-  XNLineSpace* = "lineSpace"
-  XNCursor* = "cursor"
-  XNQueryIMValuesList* = "queryIMValuesList"
-  XNQueryICValuesList* = "queryICValuesList"
-  XNVisiblePosition* = "visiblePosition"
-  XNR6PreeditCallback* = "r6PreeditCallback"
-  XNStringConversionCallback* = "stringConversionCallback"
-  XNStringConversion* = "stringConversion"
-  XNResetState* = "resetState"
-  XNHotKey* = "hotKey"
-  XNHotKeyState* = "hotKeyState"
-  XNPreeditState* = "preeditState"
-  XNSeparatorofNestedList* = "separatorofNestedList"
-  XBufferOverflow* = - (1)
-  XLookupNone* = 1
-  XLookupChars* = 2
-  XLookupKeySymVal* = 3
-  XLookupBoth* = 4
-
-type
-  PXVaNestedList* = ptr TXVaNestedList
-  TXVaNestedList* = pointer
-  PXIMCallback* = ptr TXIMCallback
-  TXIMCallback*{.final.} = object
-    client_data*: TXPointer
-    callback*: TXIMProc
-
-  PXICCallback* = ptr TXICCallback
-  TXICCallback*{.final.} = object
-    client_data*: TXPointer
-    callback*: TXICProc
-
-  PXIMFeedback* = ptr TXIMFeedback
-  TXIMFeedback* = culong
-
-const
-  XIMReverse* = 1
-  XIMUnderline* = 1 shl 1
-  XIMHighlight* = 1 shl 2
-  XIMPrimary* = 1 shl 5
-  XIMSecondary* = 1 shl 6
-  XIMTertiary* = 1 shl 7
-  XIMVisibleToForward* = 1 shl 8
-  XIMVisibleToBackword* = 1 shl 9
-  XIMVisibleToCenter* = 1 shl 10
-
-type
-  PXIMText* = ptr TXIMText
-  TXIMText*{.final.} = object
-    len*: cushort
-    feedback*: PXIMFeedback
-    encoding_is_wchar*: TBool
-    multi_byte*: cstring
-
-  PXIMPreeditState* = ptr TXIMPreeditState
-  TXIMPreeditState* = culong
-
-const
-  XIMPreeditUnKnown* = 0
-  XIMPreeditEnable* = 1
-  XIMPreeditDisable* = 1 shl 1
-
-type
-  PXIMPreeditStateNotifyCallbackStruct* = ptr TXIMPreeditStateNotifyCallbackStruct
-  TXIMPreeditStateNotifyCallbackStruct*{.final.} = object
-    state*: TXIMPreeditState
-
-  PXIMResetState* = ptr TXIMResetState
-  TXIMResetState* = culong
-
-const
-  XIMInitialState* = 1
-  XIMPreserveState* = 1 shl 1
-
-type
-  PXIMStringConversionFeedback* = ptr TXIMStringConversionFeedback
-  TXIMStringConversionFeedback* = culong
-
-const
-  XIMStringConversionLeftEdge* = 0x00000001
-  XIMStringConversionRightEdge* = 0x00000002
-  XIMStringConversionTopEdge* = 0x00000004
-  XIMStringConversionBottomEdge* = 0x00000008
-  XIMStringConversionConcealed* = 0x00000010
-  XIMStringConversionWrapped* = 0x00000020
-
-type
-  PXIMStringConversionText* = ptr TXIMStringConversionText
-  TXIMStringConversionText*{.final.} = object
-    len*: cushort
-    feedback*: PXIMStringConversionFeedback
-    encoding_is_wchar*: TBool
-    mbs*: cstring
-
-  PXIMStringConversionPosition* = ptr TXIMStringConversionPosition
-  TXIMStringConversionPosition* = cushort
-  PXIMStringConversionType* = ptr TXIMStringConversionType
-  TXIMStringConversionType* = cushort
-
-const
-  XIMStringConversionBuffer* = 0x00000001
-  XIMStringConversionLine* = 0x00000002
-  XIMStringConversionWord* = 0x00000003
-  XIMStringConversionChar* = 0x00000004
-
-type
-  PXIMStringConversionOperation* = ptr TXIMStringConversionOperation
-  TXIMStringConversionOperation* = cushort
-
-const
-  XIMStringConversionSubstitution* = 0x00000001
-  XIMStringConversionRetrieval* = 0x00000002
-
-type
-  PXIMCaretDirection* = ptr TXIMCaretDirection
-  TXIMCaretDirection* = enum
-    XIMForwardChar, XIMBackwardChar, XIMForwardWord, XIMBackwardWord,
-    XIMCaretUp, XIMCaretDown, XIMNextLine, XIMPreviousLine, XIMLineStart,
-    XIMLineEnd, XIMAbsolutePosition, XIMDontChange
-  PXIMStringConversionCallbackStruct* = ptr TXIMStringConversionCallbackStruct
-  TXIMStringConversionCallbackStruct*{.final.} = object
-    position*: TXIMStringConversionPosition
-    direction*: TXIMCaretDirection
-    operation*: TXIMStringConversionOperation
-    factor*: cushort
-    text*: PXIMStringConversionText
-
-  PXIMPreeditDrawCallbackStruct* = ptr TXIMPreeditDrawCallbackStruct
-  TXIMPreeditDrawCallbackStruct*{.final.} = object
-    caret*: cint
-    chg_first*: cint
-    chg_length*: cint
-    text*: PXIMText
-
-  PXIMCaretStyle* = ptr TXIMCaretStyle
-  TXIMCaretStyle* = enum
-    XIMIsInvisible, XIMIsPrimary, XIMIsSecondary
-  PXIMPreeditCaretCallbackStruct* = ptr TXIMPreeditCaretCallbackStruct
-  TXIMPreeditCaretCallbackStruct*{.final.} = object
-    position*: cint
-    direction*: TXIMCaretDirection
-    style*: TXIMCaretStyle
-
-  PXIMStatusDataType* = ptr TXIMStatusDataType
-  TXIMStatusDataType* = enum
-    XIMTextType, XIMBitmapType
-  PXIMStatusDrawCallbackStruct* = ptr TXIMStatusDrawCallbackStruct
-  TXIMStatusDrawCallbackStruct*{.final.} = object
-    theType*: TXIMStatusDataType
-    bitmap*: TPixmap
-
-  PXIMHotKeyTrigger* = ptr TXIMHotKeyTrigger
-  TXIMHotKeyTrigger*{.final.} = object
-    keysym*: TKeySym
-    modifier*: cint
-    modifier_mask*: cint
-
-  PXIMHotKeyTriggers* = ptr TXIMHotKeyTriggers
-  TXIMHotKeyTriggers*{.final.} = object
-    num_hot_key*: cint
-    key*: PXIMHotKeyTrigger
-
-  PXIMHotKeyState* = ptr TXIMHotKeyState
-  TXIMHotKeyState* = culong
-
-const
-  XIMHotKeyStateON* = 0x00000001
-  XIMHotKeyStateOFF* = 0x00000002
-
-type
-  PXIMValuesList* = ptr TXIMValuesList
-  TXIMValuesList*{.final.} = object
-    count_values*: cushort
-    supported_values*: PPChar
-
-
-type
-  funcdisp* = proc (display: PDisplay): cint{.cdecl.}
-  funcifevent* = proc (display: PDisplay, event: PXEvent, p: TXPointer): TBool{.
-      cdecl.}
-  chararr32* = array[0..31, char]
-
-const
-  AllPlanes*: culong = culong(not 0)
-
-proc XLoadQueryFont*(para1: PDisplay, para2: cstring): PXFontStruct{.libx11.}
-proc XQueryFont*(para1: PDisplay, para2: TXID): PXFontStruct{.libx11.}
-proc XGetMotionEvents*(para1: PDisplay, para2: TWindow, para3: TTime,
-                       para4: TTime, para5: Pcint): PXTimeCoord{.libx11.}
-proc XDeleteModifiermapEntry*(para1: PXModifierKeymap, para2: TKeyCode,
-                              para3: cint): PXModifierKeymap{.libx11.}
-proc XGetModifierMapping*(para1: PDisplay): PXModifierKeymap{.libx11.}
-proc XInsertModifiermapEntry*(para1: PXModifierKeymap, para2: TKeyCode,
-                              para3: cint): PXModifierKeymap{.libx11.}
-proc XNewModifiermap*(para1: cint): PXModifierKeymap{.libx11.}
-proc XCreateImage*(para1: PDisplay, para2: PVisual, para3: cuint, para4: cint,
-                   para5: cint, para6: cstring, para7: cuint, para8: cuint,
-                   para9: cint, para10: cint): PXImage{.libx11.}
-proc XInitImage*(para1: PXImage): TStatus{.libx11.}
-proc XGetImage*(para1: PDisplay, para2: TDrawable, para3: cint, para4: cint,
-                para5: cuint, para6: cuint, para7: culong, para8: cint): PXImage{.
-    libx11.}
-proc XGetSubImage*(para1: PDisplay, para2: TDrawable, para3: cint, para4: cint,
-                   para5: cuint, para6: cuint, para7: culong, para8: cint,
-                   para9: PXImage, para10: cint, para11: cint): PXImage{.libx11.}
-proc XOpenDisplay*(para1: cstring): PDisplay{.libx11.}
-proc XrmInitialize*(){.libx11.}
-proc XFetchBytes*(para1: PDisplay, para2: Pcint): cstring{.libx11.}
-proc XFetchBuffer*(para1: PDisplay, para2: Pcint, para3: cint): cstring{.libx11.}
-proc XGetAtomName*(para1: PDisplay, para2: TAtom): cstring{.libx11.}
-proc XGetAtomNames*(para1: PDisplay, para2: PAtom, para3: cint, para4: PPchar): TStatus{.
-    libx11.}
-proc XGetDefault*(para1: PDisplay, para2: cstring, para3: cstring): cstring{.
-    libx11.}
-proc XDisplayName*(para1: cstring): cstring{.libx11.}
-proc XKeysymToString*(para1: TKeySym): cstring{.libx11.}
-proc XSynchronize*(para1: PDisplay, para2: TBool): funcdisp{.libx11.}
-proc XSetAfterFunction*(para1: PDisplay, para2: funcdisp): funcdisp{.libx11.}
-proc XInternAtom*(para1: PDisplay, para2: cstring, para3: TBool): TAtom{.libx11.}
-proc XInternAtoms*(para1: PDisplay, para2: PPchar, para3: cint, para4: TBool,
-                   para5: PAtom): TStatus{.libx11.}
-proc XCopyColormapAndFree*(para1: PDisplay, para2: TColormap): TColormap{.libx11.}
-proc XCreateColormap*(para1: PDisplay, para2: TWindow, para3: PVisual,
-                      para4: cint): TColormap{.libx11.}
-proc XCreatePixmapCursor*(para1: PDisplay, para2: TPixmap, para3: TPixmap,
-                          para4: PXColor, para5: PXColor, para6: cuint,
-                          para7: cuint): TCursor{.libx11.}
-proc XCreateGlyphCursor*(para1: PDisplay, para2: TFont, para3: TFont,
-                         para4: cuint, para5: cuint, para6: PXColor,
-                         para7: PXColor): TCursor{.libx11.}
-proc XCreateFontCursor*(para1: PDisplay, para2: cuint): TCursor{.libx11.}
-proc XLoadFont*(para1: PDisplay, para2: cstring): TFont{.libx11.}
-proc XCreateGC*(para1: PDisplay, para2: TDrawable, para3: culong,
-                para4: PXGCValues): TGC{.libx11.}
-proc XGContextFromGC*(para1: TGC): TGContext{.libx11.}
-proc XFlushGC*(para1: PDisplay, para2: TGC){.libx11.}
-proc XCreatePixmap*(para1: PDisplay, para2: TDrawable, para3: cuint,
-                    para4: cuint, para5: cuint): TPixmap{.libx11.}
-proc XCreateBitmapFromData*(para1: PDisplay, para2: TDrawable, para3: cstring,
-                            para4: cuint, para5: cuint): TPixmap{.libx11.}
-proc XCreatePixmapFromBitmapData*(para1: PDisplay, para2: TDrawable,
-                                  para3: cstring, para4: cuint, para5: cuint,
-                                  para6: culong, para7: culong, para8: cuint): TPixmap{.
-    libx11.}
-proc XCreateSimpleWindow*(para1: PDisplay, para2: TWindow, para3: cint,
-                          para4: cint, para5: cuint, para6: cuint, para7: cuint,
-                          para8: culong, para9: culong): TWindow{.libx11.}
-proc XGetSelectionOwner*(para1: PDisplay, para2: TAtom): TWindow{.libx11.}
-proc XCreateWindow*(para1: PDisplay, para2: TWindow, para3: cint, para4: cint,
-                    para5: cuint, para6: cuint, para7: cuint, para8: cint,
-                    para9: cuint, para10: PVisual, para11: culong,
-                    para12: PXSetWindowAttributes): TWindow{.libx11.}
-proc XListInstalledColormaps*(para1: PDisplay, para2: TWindow, para3: Pcint): PColormap{.
-    libx11.}
-proc XListFonts*(para1: PDisplay, para2: cstring, para3: cint, para4: Pcint): PPChar{.
-    libx11.}
-proc XListFontsWithInfo*(para1: PDisplay, para2: cstring, para3: cint,
-                         para4: Pcint, para5: PPXFontStruct): PPChar{.libx11.}
-proc XGetFontPath*(para1: PDisplay, para2: Pcint): PPChar{.libx11.}
-proc XListExtensions*(para1: PDisplay, para2: Pcint): PPChar{.libx11.}
-proc XListProperties*(para1: PDisplay, para2: TWindow, para3: Pcint): PAtom{.
-    libx11.}
-proc XListHosts*(para1: PDisplay, para2: Pcint, para3: PBool): PXHostAddress{.
-    libx11.}
-proc XKeycodeToKeysym*(para1: PDisplay, para2: TKeyCode, para3: cint): TKeySym{.
-    libx11.}
-proc XLookupKeysym*(para1: PXKeyEvent, para2: cint): TKeySym{.libx11.}
-proc XGetKeyboardMapping*(para1: PDisplay, para2: TKeyCode, para3: cint,
-                          para4: Pcint): PKeySym{.libx11.}
-proc XStringToKeysym*(para1: cstring): TKeySym{.libx11.}
-proc XMaxRequestSize*(para1: PDisplay): clong{.libx11.}
-proc XExtendedMaxRequestSize*(para1: PDisplay): clong{.libx11.}
-proc XResourceManagerString*(para1: PDisplay): cstring{.libx11.}
-proc XScreenResourceString*(para1: PScreen): cstring{.libx11.}
-proc XDisplayMotionBufferSize*(para1: PDisplay): culong{.libx11.}
-proc XVisualIDFromVisual*(para1: PVisual): TVisualID{.libx11.}
-proc XInitThreads*(): TStatus{.libx11.}
-proc XLockDisplay*(para1: PDisplay){.libx11.}
-proc XUnlockDisplay*(para1: PDisplay){.libx11.}
-proc XInitExtension*(para1: PDisplay, para2: cstring): PXExtCodes{.libx11.}
-proc XAddExtension*(para1: PDisplay): PXExtCodes{.libx11.}
-proc XFindOnExtensionList*(para1: PPXExtData, para2: cint): PXExtData{.libx11.}
-proc XEHeadOfExtensionList*(para1: TXEDataObject): PPXExtData{.libx11.}
-proc XRootWindow*(para1: PDisplay, para2: cint): TWindow{.libx11.}
-proc XDefaultRootWindow*(para1: PDisplay): TWindow{.libx11.}
-proc XRootWindowOfScreen*(para1: PScreen): TWindow{.libx11.}
-proc XDefaultVisual*(para1: PDisplay, para2: cint): PVisual{.libx11.}
-proc XDefaultVisualOfScreen*(para1: PScreen): PVisual{.libx11.}
-proc XDefaultGC*(para1: PDisplay, para2: cint): TGC{.libx11.}
-proc XDefaultGCOfScreen*(para1: PScreen): TGC{.libx11.}
-proc XBlackPixel*(para1: PDisplay, para2: cint): culong{.libx11.}
-proc XWhitePixel*(para1: PDisplay, para2: cint): culong{.libx11.}
-proc XAllPlanes*(): culong{.libx11.}
-proc XBlackPixelOfScreen*(para1: PScreen): culong{.libx11.}
-proc XWhitePixelOfScreen*(para1: PScreen): culong{.libx11.}
-proc XNextRequest*(para1: PDisplay): culong{.libx11.}
-proc XLastKnownRequestProcessed*(para1: PDisplay): culong{.libx11.}
-proc XServerVendor*(para1: PDisplay): cstring{.libx11.}
-proc XDisplayString*(para1: PDisplay): cstring{.libx11.}
-proc XDefaultColormap*(para1: PDisplay, para2: cint): TColormap{.libx11.}
-proc XDefaultColormapOfScreen*(para1: PScreen): TColormap{.libx11.}
-proc XDisplayOfScreen*(para1: PScreen): PDisplay{.libx11.}
-proc XScreenOfDisplay*(para1: PDisplay, para2: cint): PScreen{.libx11.}
-proc XDefaultScreenOfDisplay*(para1: PDisplay): PScreen{.libx11.}
-proc XEventMaskOfScreen*(para1: PScreen): clong{.libx11.}
-proc XScreenNumberOfScreen*(para1: PScreen): cint{.libx11.}
-type
-  TXErrorHandler* = proc (para1: PDisplay, para2: PXErrorEvent): cint{.cdecl.}
-
-proc XSetErrorHandler*(para1: TXErrorHandler): TXErrorHandler{.libx11.}
-type
-  TXIOErrorHandler* = proc (para1: PDisplay): cint{.cdecl.}
-
-proc XSetIOErrorHandler*(para1: TXIOErrorHandler): TXIOErrorHandler{.libx11.}
-proc XListPixmapFormats*(para1: PDisplay, para2: Pcint): PXPixmapFormatValues{.
-    libx11.}
-proc XListDepths*(para1: PDisplay, para2: cint, para3: Pcint): Pcint{.libx11.}
-proc XReconfigureWMWindow*(para1: PDisplay, para2: TWindow, para3: cint,
-                           para4: cuint, para5: PXWindowChanges): TStatus{.
-    libx11.}
-proc XGetWMProtocols*(para1: PDisplay, para2: TWindow, para3: PPAtom,
-                      para4: Pcint): TStatus{.libx11.}
-proc XSetWMProtocols*(para1: PDisplay, para2: TWindow, para3: PAtom, para4: cint): TStatus{.
-    libx11.}
-proc XIconifyWindow*(para1: PDisplay, para2: TWindow, para3: cint): TStatus{.
-    libx11.}
-proc XWithdrawWindow*(para1: PDisplay, para2: TWindow, para3: cint): TStatus{.
-    libx11.}
-proc XGetCommand*(para1: PDisplay, para2: TWindow, para3: PPPchar, para4: Pcint): TStatus{.
-    libx11.}
-proc XGetWMColormapWindows*(para1: PDisplay, para2: TWindow, para3: PPWindow,
-                            para4: Pcint): TStatus{.libx11.}
-proc XSetWMColormapWindows*(para1: PDisplay, para2: TWindow, para3: PWindow,
-                            para4: cint): TStatus{.libx11.}
-proc XFreeStringList*(para1: PPchar){.libx11.}
-proc XSetTransientForHint*(para1: PDisplay, para2: TWindow, para3: TWindow): cint{.
-    libx11.}
-proc XActivateScreenSaver*(para1: PDisplay): cint{.libx11.}
-proc XAddHost*(para1: PDisplay, para2: PXHostAddress): cint{.libx11.}
-proc XAddHosts*(para1: PDisplay, para2: PXHostAddress, para3: cint): cint{.
-    libx11.}
-proc XAddToExtensionList*(para1: PPXExtData, para2: PXExtData): cint{.libx11.}
-proc XAddToSaveSet*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XAllocColor*(para1: PDisplay, para2: TColormap, para3: PXColor): TStatus{.
-    libx11.}
-proc XAllocColorCells*(para1: PDisplay, para2: TColormap, para3: TBool,
-                       para4: Pculong, para5: cuint, para6: Pculong,
-                       para7: cuint): TStatus{.libx11.}
-proc XAllocColorPlanes*(para1: PDisplay, para2: TColormap, para3: TBool,
-                        para4: Pculong, para5: cint, para6: cint, para7: cint,
-                        para8: cint, para9: Pculong, para10: Pculong,
-                        para11: Pculong): TStatus{.libx11.}
-proc XAllocNamedColor*(para1: PDisplay, para2: TColormap, para3: cstring,
-                       para4: PXColor, para5: PXColor): TStatus{.libx11.}
-proc XAllowEvents*(para1: PDisplay, para2: cint, para3: TTime): cint{.libx11.}
-proc XAutoRepeatOff*(para1: PDisplay): cint{.libx11.}
-proc XAutoRepeatOn*(para1: PDisplay): cint{.libx11.}
-proc XBell*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XBitmapBitOrder*(para1: PDisplay): cint{.libx11.}
-proc XBitmapPad*(para1: PDisplay): cint{.libx11.}
-proc XBitmapUnit*(para1: PDisplay): cint{.libx11.}
-proc XCellsOfScreen*(para1: PScreen): cint{.libx11.}
-proc XChangeActivePointerGrab*(para1: PDisplay, para2: cuint, para3: TCursor,
-                               para4: TTime): cint{.libx11.}
-proc XChangeGC*(para1: PDisplay, para2: TGC, para3: culong, para4: PXGCValues): cint{.
-    libx11.}
-proc XChangeKeyboardControl*(para1: PDisplay, para2: culong,
-                             para3: PXKeyboardControl): cint{.libx11.}
-proc XChangeKeyboardMapping*(para1: PDisplay, para2: cint, para3: cint,
-                             para4: PKeySym, para5: cint): cint{.libx11.}
-proc XChangePointerControl*(para1: PDisplay, para2: TBool, para3: TBool,
-                            para4: cint, para5: cint, para6: cint): cint{.libx11.}
-proc XChangeProperty*(para1: PDisplay, para2: TWindow, para3: TAtom,
-                      para4: TAtom, para5: cint, para6: cint, para7: Pcuchar,
-                      para8: cint): cint{.libx11.}
-proc XChangeSaveSet*(para1: PDisplay, para2: TWindow, para3: cint): cint{.libx11.}
-proc XChangeWindowAttributes*(para1: PDisplay, para2: TWindow, para3: culong,
-                              para4: PXSetWindowAttributes): cint{.libx11.}
-proc XCheckIfEvent*(para1: PDisplay, para2: PXEvent, para3: funcifevent,
-                    para4: TXPointer): TBool{.libx11.}
-proc XCheckMaskEvent*(para1: PDisplay, para2: clong, para3: PXEvent): TBool{.
-    libx11.}
-proc XCheckTypedEvent*(para1: PDisplay, para2: cint, para3: PXEvent): TBool{.
-    libx11.}
-proc XCheckTypedWindowEvent*(para1: PDisplay, para2: TWindow, para3: cint,
-                             para4: PXEvent): TBool{.libx11.}
-proc XCheckWindowEvent*(para1: PDisplay, para2: TWindow, para3: clong,
-                        para4: PXEvent): TBool{.libx11.}
-proc XCirculateSubwindows*(para1: PDisplay, para2: TWindow, para3: cint): cint{.
-    libx11.}
-proc XCirculateSubwindowsDown*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XCirculateSubwindowsUp*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XClearArea*(para1: PDisplay, para2: TWindow, para3: cint, para4: cint,
-                 para5: cuint, para6: cuint, para7: TBool): cint{.libx11.}
-proc XClearWindow*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XCloseDisplay*(para1: PDisplay): cint{.libx11.}
-proc XConfigureWindow*(para1: PDisplay, para2: TWindow, para3: cuint,
-                       para4: PXWindowChanges): cint{.libx11.}
-proc XConnectionNumber*(para1: PDisplay): cint{.libx11.}
-proc XConvertSelection*(para1: PDisplay, para2: TAtom, para3: TAtom,
-                        para4: TAtom, para5: TWindow, para6: TTime): cint{.
-    libx11.}
-proc XCopyArea*(para1: PDisplay, para2: TDrawable, para3: TDrawable, para4: TGC,
-                para5: cint, para6: cint, para7: cuint, para8: cuint,
-                para9: cint, para10: cint): cint{.libx11.}
-proc XCopyGC*(para1: PDisplay, para2: TGC, para3: culong, para4: TGC): cint{.
-    libx11.}
-proc XCopyPlane*(para1: PDisplay, para2: TDrawable, para3: TDrawable,
-                 para4: TGC, para5: cint, para6: cint, para7: cuint,
-                 para8: cuint, para9: cint, para10: cint, para11: culong): cint{.
-    libx11.}
-proc XDefaultDepth*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XDefaultDepthOfScreen*(para1: PScreen): cint{.libx11.}
-proc XDefaultScreen*(para1: PDisplay): cint{.libx11.}
-proc XDefineCursor*(para1: PDisplay, para2: TWindow, para3: TCursor): cint{.
-    libx11.}
-proc XDeleteProperty*(para1: PDisplay, para2: TWindow, para3: TAtom): cint{.
-    libx11.}
-proc XDestroyWindow*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XDestroySubwindows*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XDoesBackingStore*(para1: PScreen): cint{.libx11.}
-proc XDoesSaveUnders*(para1: PScreen): TBool{.libx11.}
-proc XDisableAccessControl*(para1: PDisplay): cint{.libx11.}
-proc XDisplayCells*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XDisplayHeight*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XDisplayHeightMM*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XDisplayKeycodes*(para1: PDisplay, para2: Pcint, para3: Pcint): cint{.
-    libx11.}
-proc XDisplayPlanes*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XDisplayWidth*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XDisplayWidthMM*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XDrawArc*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-               para5: cint, para6: cuint, para7: cuint, para8: cint, para9: cint): cint{.
-    libx11.}
-proc XDrawArcs*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: PXArc,
-                para5: cint): cint{.libx11.}
-proc XDrawImageString*(para1: PDisplay, para2: TDrawable, para3: TGC,
-                       para4: cint, para5: cint, para6: cstring, para7: cint): cint{.
-    libx11.}
-proc XDrawImageString16*(para1: PDisplay, para2: TDrawable, para3: TGC,
-                         para4: cint, para5: cint, para6: PXChar2b, para7: cint): cint{.
-    libx11.}
-proc XDrawLine*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                para5: cint, para6: cint, para7: cint): cint{.libx11.}
-proc XDrawLines*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: PXPoint,
-                 para5: cint, para6: cint): cint{.libx11.}
-proc XDrawPoint*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                 para5: cint): cint{.libx11.}
-proc XDrawPoints*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: PXPoint,
-                  para5: cint, para6: cint): cint{.libx11.}
-proc XDrawRectangle*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                     para5: cint, para6: cuint, para7: cuint): cint{.libx11.}
-proc XDrawRectangles*(para1: PDisplay, para2: TDrawable, para3: TGC,
-                      para4: PXRectangle, para5: cint): cint{.libx11.}
-proc XDrawSegments*(para1: PDisplay, para2: TDrawable, para3: TGC,
-                    para4: PXSegment, para5: cint): cint{.libx11.}
-proc XDrawString*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                  para5: cint, para6: cstring, para7: cint): cint{.libx11.}
-proc XDrawString16*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                    para5: cint, para6: PXChar2b, para7: cint): cint{.libx11.}
-proc XDrawText*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                para5: cint, para6: PXTextItem, para7: cint): cint{.libx11.}
-proc XDrawText16*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                  para5: cint, para6: PXTextItem16, para7: cint): cint{.libx11.}
-proc XEnableAccessControl*(para1: PDisplay): cint{.libx11.}
-proc XEventsQueued*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XFetchName*(para1: PDisplay, para2: TWindow, para3: PPchar): TStatus{.
-    libx11.}
-proc XFillArc*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-               para5: cint, para6: cuint, para7: cuint, para8: cint, para9: cint): cint{.
-    libx11.}
-proc XFillArcs*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: PXArc,
-                para5: cint): cint{.libx11.}
-proc XFillPolygon*(para1: PDisplay, para2: TDrawable, para3: TGC,
-                   para4: PXPoint, para5: cint, para6: cint, para7: cint): cint{.
-    libx11.}
-proc XFillRectangle*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                     para5: cint, para6: cuint, para7: cuint): cint{.libx11.}
-proc XFillRectangles*(para1: PDisplay, para2: TDrawable, para3: TGC,
-                      para4: PXRectangle, para5: cint): cint{.libx11.}
-proc XFlush*(para1: PDisplay): cint{.libx11.}
-proc XForceScreenSaver*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XFree*(para1: pointer): cint{.libx11.}
-proc XFreeColormap*(para1: PDisplay, para2: TColormap): cint{.libx11.}
-proc XFreeColors*(para1: PDisplay, para2: TColormap, para3: Pculong,
-                  para4: cint, para5: culong): cint{.libx11.}
-proc XFreeCursor*(para1: PDisplay, para2: TCursor): cint{.libx11.}
-proc XFreeExtensionList*(para1: PPchar): cint{.libx11.}
-proc XFreeFont*(para1: PDisplay, para2: PXFontStruct): cint{.libx11.}
-proc XFreeFontInfo*(para1: PPchar, para2: PXFontStruct, para3: cint): cint{.
-    libx11.}
-proc XFreeFontNames*(para1: PPchar): cint{.libx11.}
-proc XFreeFontPath*(para1: PPchar): cint{.libx11.}
-proc XFreeGC*(para1: PDisplay, para2: TGC): cint{.libx11.}
-proc XFreeModifiermap*(para1: PXModifierKeymap): cint{.libx11.}
-proc XFreePixmap*(para1: PDisplay, para2: TPixmap): cint{.libx11.}
-proc XGeometry*(para1: PDisplay, para2: cint, para3: cstring, para4: cstring,
-                para5: cuint, para6: cuint, para7: cuint, para8: cint,
-                para9: cint, para10: Pcint, para11: Pcint, para12: Pcint,
-                para13: Pcint): cint{.libx11.}
-proc XGetErrorDatabaseText*(para1: PDisplay, para2: cstring, para3: cstring,
-                            para4: cstring, para5: cstring, para6: cint): cint{.
-    libx11.}
-proc XGetErrorText*(para1: PDisplay, para2: cint, para3: cstring, para4: cint): cint{.
-    libx11.}
-proc XGetFontProperty*(para1: PXFontStruct, para2: TAtom, para3: Pculong): TBool{.
-    libx11.}
-proc XGetGCValues*(para1: PDisplay, para2: TGC, para3: culong, para4: PXGCValues): TStatus{.
-    libx11.}
-proc XGetGeometry*(para1: PDisplay, para2: TDrawable, para3: PWindow,
-                   para4: Pcint, para5: Pcint, para6: Pcuint, para7: Pcuint,
-                   para8: Pcuint, para9: Pcuint): TStatus{.libx11.}
-proc XGetIconName*(para1: PDisplay, para2: TWindow, para3: PPchar): TStatus{.
-    libx11.}
-proc XGetInputFocus*(para1: PDisplay, para2: PWindow, para3: Pcint): cint{.
-    libx11.}
-proc XGetKeyboardControl*(para1: PDisplay, para2: PXKeyboardState): cint{.libx11.}
-proc XGetPointerControl*(para1: PDisplay, para2: Pcint, para3: Pcint,
-                         para4: Pcint): cint{.libx11.}
-proc XGetPointerMapping*(para1: PDisplay, para2: Pcuchar, para3: cint): cint{.
-    libx11.}
-proc XGetScreenSaver*(para1: PDisplay, para2: Pcint, para3: Pcint, para4: Pcint,
-                      para5: Pcint): cint{.libx11.}
-proc XGetTransientForHint*(para1: PDisplay, para2: TWindow, para3: PWindow): TStatus{.
-    libx11.}
-proc XGetWindowProperty*(para1: PDisplay, para2: TWindow, para3: TAtom,
-                         para4: clong, para5: clong, para6: TBool, para7: TAtom,
-                         para8: PAtom, para9: Pcint, para10: Pculong,
-                         para11: Pculong, para12: PPcuchar): cint{.libx11.}
-proc XGetWindowAttributes*(para1: PDisplay, para2: TWindow,
-                           para3: PXWindowAttributes): TStatus{.libx11.}
-proc XGrabButton*(para1: PDisplay, para2: cuint, para3: cuint, para4: TWindow,
-                  para5: TBool, para6: cuint, para7: cint, para8: cint,
-                  para9: TWindow, para10: TCursor): cint{.libx11.}
-proc XGrabKey*(para1: PDisplay, para2: cint, para3: cuint, para4: TWindow,
-               para5: TBool, para6: cint, para7: cint): cint{.libx11.}
-proc XGrabKeyboard*(para1: PDisplay, para2: TWindow, para3: TBool, para4: cint,
-                    para5: cint, para6: TTime): cint{.libx11.}
-proc XGrabPointer*(para1: PDisplay, para2: TWindow, para3: TBool, para4: cuint,
-                   para5: cint, para6: cint, para7: TWindow, para8: TCursor,
-                   para9: TTime): cint{.libx11.}
-proc XGrabServer*(para1: PDisplay): cint{.libx11.}
-proc XHeightMMOfScreen*(para1: PScreen): cint{.libx11.}
-proc XHeightOfScreen*(para1: PScreen): cint{.libx11.}
-proc XIfEvent*(para1: PDisplay, para2: PXEvent, para3: funcifevent,
-               para4: TXPointer): cint{.libx11.}
-proc XImageByteOrder*(para1: PDisplay): cint{.libx11.}
-proc XInstallColormap*(para1: PDisplay, para2: TColormap): cint{.libx11.}
-proc XKeysymToKeycode*(para1: PDisplay, para2: TKeySym): TKeyCode{.libx11.}
-proc XKillClient*(para1: PDisplay, para2: TXID): cint{.libx11.}
-proc XLookupColor*(para1: PDisplay, para2: TColormap, para3: cstring,
-                   para4: PXColor, para5: PXColor): TStatus{.libx11.}
-proc XLowerWindow*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XMapRaised*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XMapSubwindows*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XMapWindow*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XMaskEvent*(para1: PDisplay, para2: clong, para3: PXEvent): cint{.libx11.}
-proc XMaxCmapsOfScreen*(para1: PScreen): cint{.libx11.}
-proc XMinCmapsOfScreen*(para1: PScreen): cint{.libx11.}
-proc XMoveResizeWindow*(para1: PDisplay, para2: TWindow, para3: cint,
-                        para4: cint, para5: cuint, para6: cuint): cint{.libx11.}
-proc XMoveWindow*(para1: PDisplay, para2: TWindow, para3: cint, para4: cint): cint{.
-    libx11.}
-proc XNextEvent*(para1: PDisplay, para2: PXEvent): cint{.libx11.}
-proc XNoOp*(para1: PDisplay): cint{.libx11.}
-proc XParseColor*(para1: PDisplay, para2: TColormap, para3: cstring,
-                  para4: PXColor): TStatus{.libx11.}
-proc XParseGeometry*(para1: cstring, para2: Pcint, para3: Pcint, para4: Pcuint,
-                     para5: Pcuint): cint{.libx11.}
-proc XPeekEvent*(para1: PDisplay, para2: PXEvent): cint{.libx11.}
-proc XPeekIfEvent*(para1: PDisplay, para2: PXEvent, para3: funcifevent,
-                   para4: TXPointer): cint{.libx11.}
-proc XPending*(para1: PDisplay): cint{.libx11.}
-proc XPlanesOfScreen*(para1: PScreen): cint{.libx11.}
-proc XProtocolRevision*(para1: PDisplay): cint{.libx11.}
-proc XProtocolVersion*(para1: PDisplay): cint{.libx11.}
-proc XPutBackEvent*(para1: PDisplay, para2: PXEvent): cint{.libx11.}
-proc XPutImage*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: PXImage,
-                para5: cint, para6: cint, para7: cint, para8: cint,
-                para9: cuint, para10: cuint): cint{.libx11.}
-proc XQLength*(para1: PDisplay): cint{.libx11.}
-proc XQueryBestCursor*(para1: PDisplay, para2: TDrawable, para3: cuint,
-                       para4: cuint, para5: Pcuint, para6: Pcuint): TStatus{.
-    libx11.}
-proc XQueryBestSize*(para1: PDisplay, para2: cint, para3: TDrawable,
-                     para4: cuint, para5: cuint, para6: Pcuint, para7: Pcuint): TStatus{.
-    libx11.}
-proc XQueryBestStipple*(para1: PDisplay, para2: TDrawable, para3: cuint,
-                        para4: cuint, para5: Pcuint, para6: Pcuint): TStatus{.
-    libx11.}
-proc XQueryBestTile*(para1: PDisplay, para2: TDrawable, para3: cuint,
-                     para4: cuint, para5: Pcuint, para6: Pcuint): TStatus{.
-    libx11.}
-proc XQueryColor*(para1: PDisplay, para2: TColormap, para3: PXColor): cint{.
-    libx11.}
-proc XQueryColors*(para1: PDisplay, para2: TColormap, para3: PXColor,
-                   para4: cint): cint{.libx11.}
-proc XQueryExtension*(para1: PDisplay, para2: cstring, para3: Pcint,
-                      para4: Pcint, para5: Pcint): TBool{.libx11.}
-  #?
-proc XQueryKeymap*(para1: PDisplay, para2: chararr32): cint{.libx11.}
-proc XQueryPointer*(para1: PDisplay, para2: TWindow, para3: PWindow,
-                    para4: PWindow, para5: Pcint, para6: Pcint, para7: Pcint,
-                    para8: Pcint, para9: Pcuint): TBool{.libx11.}
-proc XQueryTextExtents*(para1: PDisplay, para2: TXID, para3: cstring,
-                        para4: cint, para5: Pcint, para6: Pcint, para7: Pcint,
-                        para8: PXCharStruct): cint{.libx11.}
-proc XQueryTextExtents16*(para1: PDisplay, para2: TXID, para3: PXChar2b,
-                          para4: cint, para5: Pcint, para6: Pcint, para7: Pcint,
-                          para8: PXCharStruct): cint{.libx11.}
-proc XQueryTree*(para1: PDisplay, para2: TWindow, para3: PWindow,
-                 para4: PWindow, para5: PPWindow, para6: Pcuint): TStatus{.
-    libx11.}
-proc XRaiseWindow*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XReadBitmapFile*(para1: PDisplay, para2: TDrawable, para3: cstring,
-                      para4: Pcuint, para5: Pcuint, para6: PPixmap,
-                      para7: Pcint, para8: Pcint): cint{.libx11.}
-proc XReadBitmapFileData*(para1: cstring, para2: Pcuint, para3: Pcuint,
-                          para4: PPcuchar, para5: Pcint, para6: Pcint): cint{.
-    libx11.}
-proc XRebindKeysym*(para1: PDisplay, para2: TKeySym, para3: PKeySym,
-                    para4: cint, para5: Pcuchar, para6: cint): cint{.libx11.}
-proc XRecolorCursor*(para1: PDisplay, para2: TCursor, para3: PXColor,
-                     para4: PXColor): cint{.libx11.}
-proc XRefreshKeyboardMapping*(para1: PXMappingEvent): cint{.libx11.}
-proc XRemoveFromSaveSet*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XRemoveHost*(para1: PDisplay, para2: PXHostAddress): cint{.libx11.}
-proc XRemoveHosts*(para1: PDisplay, para2: PXHostAddress, para3: cint): cint{.
-    libx11.}
-proc XReparentWindow*(para1: PDisplay, para2: TWindow, para3: TWindow,
-                      para4: cint, para5: cint): cint{.libx11.}
-proc XResetScreenSaver*(para1: PDisplay): cint{.libx11.}
-proc XResizeWindow*(para1: PDisplay, para2: TWindow, para3: cuint, para4: cuint): cint{.
-    libx11.}
-proc XRestackWindows*(para1: PDisplay, para2: PWindow, para3: cint): cint{.
-    libx11.}
-proc XRotateBuffers*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XRotateWindowProperties*(para1: PDisplay, para2: TWindow, para3: PAtom,
-                              para4: cint, para5: cint): cint{.libx11.}
-proc XScreenCount*(para1: PDisplay): cint{.libx11.}
-proc XSelectInput*(para1: PDisplay, para2: TWindow, para3: clong): cint{.libx11.}
-proc XSendEvent*(para1: PDisplay, para2: TWindow, para3: TBool, para4: clong,
-                 para5: PXEvent): TStatus{.libx11.}
-proc XSetAccessControl*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XSetArcMode*(para1: PDisplay, para2: TGC, para3: cint): cint{.libx11.}
-proc XSetBackground*(para1: PDisplay, para2: TGC, para3: culong): cint{.libx11.}
-proc XSetClipMask*(para1: PDisplay, para2: TGC, para3: TPixmap): cint{.libx11.}
-proc XSetClipOrigin*(para1: PDisplay, para2: TGC, para3: cint, para4: cint): cint{.
-    libx11.}
-proc XSetClipRectangles*(para1: PDisplay, para2: TGC, para3: cint, para4: cint,
-                         para5: PXRectangle, para6: cint, para7: cint): cint{.
-    libx11.}
-proc XSetCloseDownMode*(para1: PDisplay, para2: cint): cint{.libx11.}
-proc XSetCommand*(para1: PDisplay, para2: TWindow, para3: PPchar, para4: cint): cint{.
-    libx11.}
-proc XSetDashes*(para1: PDisplay, para2: TGC, para3: cint, para4: cstring,
-                 para5: cint): cint{.libx11.}
-proc XSetFillRule*(para1: PDisplay, para2: TGC, para3: cint): cint{.libx11.}
-proc XSetFillStyle*(para1: PDisplay, para2: TGC, para3: cint): cint{.libx11.}
-proc XSetFont*(para1: PDisplay, para2: TGC, para3: TFont): cint{.libx11.}
-proc XSetFontPath*(para1: PDisplay, para2: PPchar, para3: cint): cint{.libx11.}
-proc XSetForeground*(para1: PDisplay, para2: TGC, para3: culong): cint{.libx11.}
-proc XSetFunction*(para1: PDisplay, para2: TGC, para3: cint): cint{.libx11.}
-proc XSetGraphicsExposures*(para1: PDisplay, para2: TGC, para3: TBool): cint{.
-    libx11.}
-proc XSetIconName*(para1: PDisplay, para2: TWindow, para3: cstring): cint{.
-    libx11.}
-proc XSetInputFocus*(para1: PDisplay, para2: TWindow, para3: cint, para4: TTime): cint{.
-    libx11.}
-proc XSetLineAttributes*(para1: PDisplay, para2: TGC, para3: cuint, para4: cint,
-                         para5: cint, para6: cint): cint{.libx11.}
-proc XSetModifierMapping*(para1: PDisplay, para2: PXModifierKeymap): cint{.
-    libx11.}
-proc XSetPlaneMask*(para1: PDisplay, para2: TGC, para3: culong): cint{.libx11.}
-proc XSetPointerMapping*(para1: PDisplay, para2: Pcuchar, para3: cint): cint{.
-    libx11.}
-proc XSetScreenSaver*(para1: PDisplay, para2: cint, para3: cint, para4: cint,
-                      para5: cint): cint{.libx11.}
-proc XSetSelectionOwner*(para1: PDisplay, para2: TAtom, para3: TWindow,
-                         para4: TTime): cint{.libx11.}
-proc XSetState*(para1: PDisplay, para2: TGC, para3: culong, para4: culong,
-                para5: cint, para6: culong): cint{.libx11.}
-proc XSetStipple*(para1: PDisplay, para2: TGC, para3: TPixmap): cint{.libx11.}
-proc XSetSubwindowMode*(para1: PDisplay, para2: TGC, para3: cint): cint{.libx11.}
-proc XSetTSOrigin*(para1: PDisplay, para2: TGC, para3: cint, para4: cint): cint{.
-    libx11.}
-proc XSetTile*(para1: PDisplay, para2: TGC, para3: TPixmap): cint{.libx11.}
-proc XSetWindowBackground*(para1: PDisplay, para2: TWindow, para3: culong): cint{.
-    libx11.}
-proc XSetWindowBackgroundPixmap*(para1: PDisplay, para2: TWindow, para3: TPixmap): cint{.
-    libx11.}
-proc XSetWindowBorder*(para1: PDisplay, para2: TWindow, para3: culong): cint{.
-    libx11.}
-proc XSetWindowBorderPixmap*(para1: PDisplay, para2: TWindow, para3: TPixmap): cint{.
-    libx11.}
-proc XSetWindowBorderWidth*(para1: PDisplay, para2: TWindow, para3: cuint): cint{.
-    libx11.}
-proc XSetWindowColormap*(para1: PDisplay, para2: TWindow, para3: TColormap): cint{.
-    libx11.}
-proc XStoreBuffer*(para1: PDisplay, para2: cstring, para3: cint, para4: cint): cint{.
-    libx11.}
-proc XStoreBytes*(para1: PDisplay, para2: cstring, para3: cint): cint{.libx11.}
-proc XStoreColor*(para1: PDisplay, para2: TColormap, para3: PXColor): cint{.
-    libx11.}
-proc XStoreColors*(para1: PDisplay, para2: TColormap, para3: PXColor,
-                   para4: cint): cint{.libx11.}
-proc XStoreName*(para1: PDisplay, para2: TWindow, para3: cstring): cint{.libx11.}
-proc XStoreNamedColor*(para1: PDisplay, para2: TColormap, para3: cstring,
-                       para4: culong, para5: cint): cint{.libx11.}
-proc XSync*(para1: PDisplay, para2: TBool): cint{.libx11.}
-proc XTextExtents*(para1: PXFontStruct, para2: cstring, para3: cint,
-                   para4: Pcint, para5: Pcint, para6: Pcint, para7: PXCharStruct): cint{.
-    libx11.}
-proc XTextExtents16*(para1: PXFontStruct, para2: PXChar2b, para3: cint,
-                     para4: Pcint, para5: Pcint, para6: Pcint,
-                     para7: PXCharStruct): cint{.libx11.}
-proc XTextWidth*(para1: PXFontStruct, para2: cstring, para3: cint): cint{.libx11.}
-proc XTextWidth16*(para1: PXFontStruct, para2: PXChar2b, para3: cint): cint{.
-    libx11.}
-proc XTranslateCoordinates*(para1: PDisplay, para2: TWindow, para3: TWindow,
-                            para4: cint, para5: cint, para6: Pcint,
-                            para7: Pcint, para8: PWindow): TBool{.libx11.}
-proc XUndefineCursor*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XUngrabButton*(para1: PDisplay, para2: cuint, para3: cuint, para4: TWindow): cint{.
-    libx11.}
-proc XUngrabKey*(para1: PDisplay, para2: cint, para3: cuint, para4: TWindow): cint{.
-    libx11.}
-proc XUngrabKeyboard*(para1: PDisplay, para2: TTime): cint{.libx11.}
-proc XUngrabPointer*(para1: PDisplay, para2: TTime): cint{.libx11.}
-proc XUngrabServer*(para1: PDisplay): cint{.libx11.}
-proc XUninstallColormap*(para1: PDisplay, para2: TColormap): cint{.libx11.}
-proc XUnloadFont*(para1: PDisplay, para2: TFont): cint{.libx11.}
-proc XUnmapSubwindows*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XUnmapWindow*(para1: PDisplay, para2: TWindow): cint{.libx11.}
-proc XVendorRelease*(para1: PDisplay): cint{.libx11.}
-proc XWarpPointer*(para1: PDisplay, para2: TWindow, para3: TWindow, para4: cint,
-                   para5: cint, para6: cuint, para7: cuint, para8: cint,
-                   para9: cint): cint{.libx11.}
-proc XWidthMMOfScreen*(para1: PScreen): cint{.libx11.}
-proc XWidthOfScreen*(para1: PScreen): cint{.libx11.}
-proc XWindowEvent*(para1: PDisplay, para2: TWindow, para3: clong, para4: PXEvent): cint{.
-    libx11.}
-proc XWriteBitmapFile*(para1: PDisplay, para2: cstring, para3: TPixmap,
-                       para4: cuint, para5: cuint, para6: cint, para7: cint): cint{.
-    libx11.}
-proc XSupportsLocale*(): TBool{.libx11.}
-proc XSetLocaleModifiers*(para1: cstring): cstring{.libx11.}
-proc XOpenOM*(para1: PDisplay, para2: PXrmHashBucketRec, para3: cstring,
-              para4: cstring): TXOM{.libx11.}
-proc XCloseOM*(para1: TXOM): TStatus{.libx11.}
-proc XSetOMValues*(para1: TXOM): cstring{.varargs, libx11.}
-proc XGetOMValues*(para1: TXOM): cstring{.varargs, libx11.}
-proc XDisplayOfOM*(para1: TXOM): PDisplay{.libx11.}
-proc XLocaleOfOM*(para1: TXOM): cstring{.libx11.}
-proc XCreateOC*(para1: TXOM): TXOC{.varargs, libx11.}
-proc XDestroyOC*(para1: TXOC){.libx11.}
-proc XOMOfOC*(para1: TXOC): TXOM{.libx11.}
-proc XSetOCValues*(para1: TXOC): cstring{.varargs, libx11.}
-proc XGetOCValues*(para1: TXOC): cstring{.varargs, libx11.}
-proc XCreateFontSet*(para1: PDisplay, para2: cstring, para3: PPPchar,
-                     para4: Pcint, para5: PPchar): TXFontSet{.libx11.}
-proc XFreeFontSet*(para1: PDisplay, para2: TXFontSet){.libx11.}
-proc XFontsOfFontSet*(para1: TXFontSet, para2: PPPXFontStruct, para3: PPPchar): cint{.
-    libx11.}
-proc XBaseFontNameListOfFontSet*(para1: TXFontSet): cstring{.libx11.}
-proc XLocaleOfFontSet*(para1: TXFontSet): cstring{.libx11.}
-proc XContextDependentDrawing*(para1: TXFontSet): TBool{.libx11.}
-proc XDirectionalDependentDrawing*(para1: TXFontSet): TBool{.libx11.}
-proc XContextualDrawing*(para1: TXFontSet): TBool{.libx11.}
-proc XExtentsOfFontSet*(para1: TXFontSet): PXFontSetExtents{.libx11.}
-proc XmbTextEscapement*(para1: TXFontSet, para2: cstring, para3: cint): cint{.
-    libx11.}
-proc XwcTextEscapement*(para1: TXFontSet, para2: PWideChar, para3: cint): cint{.
-    libx11.}
-proc Xutf8TextEscapement*(para1: TXFontSet, para2: cstring, para3: cint): cint{.
-    libx11.}
-proc XmbTextExtents*(para1: TXFontSet, para2: cstring, para3: cint,
-                     para4: PXRectangle, para5: PXRectangle): cint{.libx11.}
-proc XwcTextExtents*(para1: TXFontSet, para2: PWideChar, para3: cint,
-                     para4: PXRectangle, para5: PXRectangle): cint{.libx11.}
-proc Xutf8TextExtents*(para1: TXFontSet, para2: cstring, para3: cint,
-                       para4: PXRectangle, para5: PXRectangle): cint{.libx11.}
-proc XmbTextPerCharExtents*(para1: TXFontSet, para2: cstring, para3: cint,
-                            para4: PXRectangle, para5: PXRectangle, para6: cint,
-                            para7: Pcint, para8: PXRectangle, para9: PXRectangle): TStatus{.
-    libx11.}
-proc XwcTextPerCharExtents*(para1: TXFontSet, para2: PWideChar, para3: cint,
-                            para4: PXRectangle, para5: PXRectangle, para6: cint,
-                            para7: Pcint, para8: PXRectangle, para9: PXRectangle): TStatus{.
-    libx11.}
-proc Xutf8TextPerCharExtents*(para1: TXFontSet, para2: cstring, para3: cint,
-                              para4: PXRectangle, para5: PXRectangle,
-                              para6: cint, para7: Pcint, para8: PXRectangle,
-                              para9: PXRectangle): TStatus{.libx11.}
-proc XmbDrawText*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                  para5: cint, para6: PXmbTextItem, para7: cint){.libx11.}
-proc XwcDrawText*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                  para5: cint, para6: PXwcTextItem, para7: cint){.libx11.}
-proc Xutf8DrawText*(para1: PDisplay, para2: TDrawable, para3: TGC, para4: cint,
-                    para5: cint, para6: PXmbTextItem, para7: cint){.libx11.}
-proc XmbDrawString*(para1: PDisplay, para2: TDrawable, para3: TXFontSet,
-                    para4: TGC, para5: cint, para6: cint, para7: cstring,
-                    para8: cint){.libx11.}
-proc XwcDrawString*(para1: PDisplay, para2: TDrawable, para3: TXFontSet,
-                    para4: TGC, para5: cint, para6: cint, para7: PWideChar,
-                    para8: cint){.libx11.}
-proc Xutf8DrawString*(para1: PDisplay, para2: TDrawable, para3: TXFontSet,
-                      para4: TGC, para5: cint, para6: cint, para7: cstring,
-                      para8: cint){.libx11.}
-proc XmbDrawImageString*(para1: PDisplay, para2: TDrawable, para3: TXFontSet,
-                         para4: TGC, para5: cint, para6: cint, para7: cstring,
-                         para8: cint){.libx11.}
-proc XwcDrawImageString*(para1: PDisplay, para2: TDrawable, para3: TXFontSet,
-                         para4: TGC, para5: cint, para6: cint, para7: PWideChar,
-                         para8: cint){.libx11.}
-proc Xutf8DrawImageString*(para1: PDisplay, para2: TDrawable, para3: TXFontSet,
-                           para4: TGC, para5: cint, para6: cint, para7: cstring,
-                           para8: cint){.libx11.}
-proc XOpenIM*(para1: PDisplay, para2: PXrmHashBucketRec, para3: cstring,
-              para4: cstring): TXIM{.libx11.}
-proc XCloseIM*(para1: TXIM): TStatus{.libx11.}
-proc XGetIMValues*(para1: TXIM): cstring{.varargs, libx11.}
-proc XSetIMValues*(para1: TXIM): cstring{.varargs, libx11.}
-proc XDisplayOfIM*(para1: TXIM): PDisplay{.libx11.}
-proc XLocaleOfIM*(para1: TXIM): cstring{.libx11.}
-proc XCreateIC*(para1: TXIM): TXIC{.varargs, libx11.}
-proc XDestroyIC*(para1: TXIC){.libx11.}
-proc XSetICFocus*(para1: TXIC){.libx11.}
-proc XUnsetICFocus*(para1: TXIC){.libx11.}
-proc XwcResetIC*(para1: TXIC): PWideChar{.libx11.}
-proc XmbResetIC*(para1: TXIC): cstring{.libx11.}
-proc Xutf8ResetIC*(para1: TXIC): cstring{.libx11.}
-proc XSetICValues*(para1: TXIC): cstring{.varargs, libx11.}
-proc XGetICValues*(para1: TXIC): cstring{.varargs, libx11.}
-proc XIMOfIC*(para1: TXIC): TXIM{.libx11.}
-proc XFilterEvent*(para1: PXEvent, para2: TWindow): TBool{.libx11.}
-proc XmbLookupString*(para1: TXIC, para2: PXKeyPressedEvent, para3: cstring,
-                      para4: cint, para5: PKeySym, para6: PStatus): cint{.libx11.}
-proc XwcLookupString*(para1: TXIC, para2: PXKeyPressedEvent, para3: PWideChar,
-                      para4: cint, para5: PKeySym, para6: PStatus): cint{.libx11.}
-proc Xutf8LookupString*(para1: TXIC, para2: PXKeyPressedEvent, para3: cstring,
-                        para4: cint, para5: PKeySym, para6: PStatus): cint{.
-    libx11.}
-proc XVaCreateNestedList*(unused: cint): TXVaNestedList{.varargs, libx11.}
-proc XRegisterIMInstantiateCallback*(para1: PDisplay, para2: PXrmHashBucketRec,
-                                     para3: cstring, para4: cstring,
-                                     para5: TXIDProc, para6: TXPointer): TBool{.
-    libx11.}
-proc XUnregisterIMInstantiateCallback*(para1: PDisplay,
-                                       para2: PXrmHashBucketRec, para3: cstring,
-                                       para4: cstring, para5: TXIDProc,
-                                       para6: TXPointer): TBool{.libx11.}
-type
-  TXConnectionWatchProc* = proc (para1: PDisplay, para2: TXPointer, para3: cint,
-                                 para4: TBool, para5: PXPointer){.cdecl.}
-
-proc XInternalConnectionNumbers*(para1: PDisplay, para2: PPcint, para3: Pcint): TStatus{.
-    libx11.}
-proc XProcessInternalConnection*(para1: PDisplay, para2: cint){.libx11.}
-proc XAddConnectionWatch*(para1: PDisplay, para2: TXConnectionWatchProc,
-                          para3: TXPointer): TStatus{.libx11.}
-proc XRemoveConnectionWatch*(para1: PDisplay, para2: TXConnectionWatchProc,
-                             para3: TXPointer){.libx11.}
-proc XSetAuthorization*(para1: cstring, para2: cint, para3: cstring, para4: cint){.
-    libx11.}
-  #
-  #  _Xmbtowc?
-  #  _Xwctomb?
-  #
-#when defined(MACROS):
-proc ConnectionNumber*(dpy: PDisplay): cint
-proc RootWindow*(dpy: PDisplay, scr: cint): TWindow
-proc DefaultScreen*(dpy: PDisplay): cint
-proc DefaultRootWindow*(dpy: PDisplay): TWindow
-proc DefaultVisual*(dpy: PDisplay, scr: cint): PVisual
-proc DefaultGC*(dpy: PDisplay, scr: cint): TGC
-proc BlackPixel*(dpy: PDisplay, scr: cint): culong
-proc WhitePixel*(dpy: PDisplay, scr: cint): culong
-proc QLength*(dpy: PDisplay): cint
-proc DisplayWidth*(dpy: PDisplay, scr: cint): cint
-proc DisplayHeight*(dpy: PDisplay, scr: cint): cint
-proc DisplayWidthMM*(dpy: PDisplay, scr: cint): cint
-proc DisplayHeightMM*(dpy: PDisplay, scr: cint): cint
-proc DisplayPlanes*(dpy: PDisplay, scr: cint): cint
-proc DisplayCells*(dpy: PDisplay, scr: cint): cint
-proc ScreenCount*(dpy: PDisplay): cint
-proc ServerVendor*(dpy: PDisplay): cstring
-proc ProtocolVersion*(dpy: PDisplay): cint
-proc ProtocolRevision*(dpy: PDisplay): cint
-proc VendorRelease*(dpy: PDisplay): cint
-proc DisplayString*(dpy: PDisplay): cstring
-proc DefaultDepth*(dpy: PDisplay, scr: cint): cint
-proc DefaultColormap*(dpy: PDisplay, scr: cint): TColormap
-proc BitmapUnit*(dpy: PDisplay): cint
-proc BitmapBitOrder*(dpy: PDisplay): cint
-proc BitmapPad*(dpy: PDisplay): cint
-proc ImageByteOrder*(dpy: PDisplay): cint
-proc NextRequest*(dpy: PDisplay): culong
-proc LastKnownRequestProcessed*(dpy: PDisplay): culong
-proc ScreenOfDisplay*(dpy: PDisplay, scr: cint): PScreen
-proc DefaultScreenOfDisplay*(dpy: PDisplay): PScreen
-proc DisplayOfScreen*(s: PScreen): PDisplay
-proc RootWindowOfScreen*(s: PScreen): TWindow
-proc BlackPixelOfScreen*(s: PScreen): culong
-proc WhitePixelOfScreen*(s: PScreen): culong
-proc DefaultColormapOfScreen*(s: PScreen): TColormap
-proc DefaultDepthOfScreen*(s: PScreen): cint
-proc DefaultGCOfScreen*(s: PScreen): TGC
-proc DefaultVisualOfScreen*(s: PScreen): PVisual
-proc WidthOfScreen*(s: PScreen): cint
-proc HeightOfScreen*(s: PScreen): cint
-proc WidthMMOfScreen*(s: PScreen): cint
-proc HeightMMOfScreen*(s: PScreen): cint
-proc PlanesOfScreen*(s: PScreen): cint
-proc CellsOfScreen*(s: PScreen): cint
-proc MinCmapsOfScreen*(s: PScreen): cint
-proc MaxCmapsOfScreen*(s: PScreen): cint
-proc DoesSaveUnders*(s: PScreen): TBool
-proc DoesBackingStore*(s: PScreen): cint
-proc EventMaskOfScreen*(s: PScreen): clong
-proc XAllocID*(dpy: PDisplay): TXID
-# implementation
-
-#when defined(MACROS):
-template privDisp : expr = cast[PXPrivDisplay](dpy)
-
-proc ConnectionNumber(dpy: PDisplay): cint =
-  privDisp.fd
-
-proc RootWindow(dpy: PDisplay, scr: cint): TWindow =
-  ScreenOfDisplay(dpy, scr).root
-
-proc DefaultScreen(dpy: PDisplay): cint =
-  privDisp.default_screen
-
-proc DefaultRootWindow(dpy: PDisplay): TWindow =
-  ScreenOfDisplay(dpy, DefaultScreen(dpy)).root
-
-proc DefaultVisual(dpy: PDisplay, scr: cint): PVisual =
-  ScreenOfDisplay(dpy, scr).root_visual
-
-proc DefaultGC(dpy: PDisplay, scr: cint): TGC =
-  ScreenOfDisplay(dpy, scr).default_gc
-
-proc BlackPixel(dpy: PDisplay, scr: cint): culong =
-  ScreenOfDisplay(dpy, scr).black_pixel
-
-proc WhitePixel(dpy: PDisplay, scr: cint): culong =
-  ScreenOfDisplay(dpy, scr).white_pixel
-
-proc QLength(dpy: PDisplay): cint =
-  privDisp.qlen
-
-proc DisplayWidth(dpy: PDisplay, scr: cint): cint =
-  ScreenOfDisplay(dpy, scr).width
-
-proc DisplayHeight(dpy: PDisplay, scr: cint): cint =
-  ScreenOfDisplay(dpy, scr).height
-
-proc DisplayWidthMM(dpy: PDisplay, scr: cint): cint =
-  ScreenOfDisplay(dpy, scr).mwidth
-
-proc DisplayHeightMM(dpy: PDisplay, scr: cint): cint =
-  ScreenOfDisplay(dpy, scr).mheight
-
-proc DisplayPlanes(dpy: PDisplay, scr: cint): cint =
-  ScreenOfDisplay(dpy, scr).root_depth
-
-proc DisplayCells(dpy: PDisplay, scr: cint): cint =
-  DefaultVisual(dpy, scr).map_entries
-
-proc ScreenCount(dpy: PDisplay): cint =
-  privDisp.nscreens
-
-proc ServerVendor(dpy: PDisplay): cstring =
-  privDisp.vendor
-
-proc ProtocolVersion(dpy: PDisplay): cint =
-  privDisp.proto_major_version
-
-proc ProtocolRevision(dpy: PDisplay): cint =
-  privDisp.proto_minor_version
-
-proc VendorRelease(dpy: PDisplay): cint =
-  privDisp.release
-
-proc DisplayString(dpy: PDisplay): cstring =
-  privDisp.display_name
-
-proc DefaultDepth(dpy: PDisplay, scr: cint): cint =
-  ScreenOfDisplay(dpy, scr).root_depth
-
-proc DefaultColormap(dpy: PDisplay, scr: cint): TColormap =
-  ScreenOfDisplay(dpy, scr).cmap
-
-proc BitmapUnit(dpy: PDisplay): cint =
-  privDisp.bitmap_unit
-
-proc BitmapBitOrder(dpy: PDisplay): cint =
-  privDisp.bitmap_bit_order
-
-proc BitmapPad(dpy: PDisplay): cint =
-  privDisp.bitmap_pad
-
-proc ImageByteOrder(dpy: PDisplay): cint =
-  privDisp.byte_order
-
-proc NextRequest(dpy: PDisplay): culong =
-  privDisp.request + 1.culong
-
-proc LastKnownRequestProcessed(dpy: PDisplay): culong =
-  privDisp.last_request_read
-
-# from fowltek/pointer_arithm, required for ScreenOfDisplay()
-proc offset[A] (some: ptr A; b: int): ptr A =
-  cast[ptr A](cast[int](some) + (b * sizeof(A)))
-proc ScreenOfDisplay(dpy: PDisplay, scr: cint): PScreen =
-  #addr(((privDisp.screens)[scr]))
-  privDisp.screens.offset(scr.int)
-
-proc DefaultScreenOfDisplay(dpy: PDisplay): PScreen =
-  ScreenOfDisplay(dpy, DefaultScreen(dpy))
-
-proc DisplayOfScreen(s: PScreen): PDisplay =
-  s.display
-
-proc RootWindowOfScreen(s: PScreen): TWindow =
-  s.root
-
-proc BlackPixelOfScreen(s: PScreen): culong =
-  s.black_pixel
-
-proc WhitePixelOfScreen(s: PScreen): culong =
-  s.white_pixel
-
-proc DefaultColormapOfScreen(s: PScreen): TColormap =
-  s.cmap
-
-proc DefaultDepthOfScreen(s: PScreen): cint =
-  s.root_depth
-
-proc DefaultGCOfScreen(s: PScreen): TGC =
-  s.default_gc
-
-proc DefaultVisualOfScreen(s: PScreen): PVisual =
-  s.root_visual
-
-proc WidthOfScreen(s: PScreen): cint =
-  s.width
-
-proc HeightOfScreen(s: PScreen): cint =
-  s.height
-
-proc WidthMMOfScreen(s: PScreen): cint =
-  s.mwidth
-
-proc HeightMMOfScreen(s: PScreen): cint =
-  s.mheight
-
-proc PlanesOfScreen(s: PScreen): cint =
-  s.root_depth
-
-proc CellsOfScreen(s: PScreen): cint =
-  DefaultVisualOfScreen(s).map_entries
-
-proc MinCmapsOfScreen(s: PScreen): cint =
-  s.min_maps
-
-proc MaxCmapsOfScreen(s: PScreen): cint =
-  s.max_maps
-
-proc DoesSaveUnders(s: PScreen): TBool =
-  s.save_unders
-
-proc DoesBackingStore(s: PScreen): cint =
-  s.backing_store
-
-proc EventMaskOfScreen(s: PScreen): clong =
-  s.root_input_mask
-
-proc XAllocID(dpy: PDisplay): TXID =
-  privDisp.resource_alloc(dpy)
diff --git a/tests/deps/x11-1.0/xrandr.nim b/tests/deps/x11-1.0/xrandr.nim
deleted file mode 100644
index ee6f1705b..000000000
--- a/tests/deps/x11-1.0/xrandr.nim
+++ /dev/null
@@ -1,194 +0,0 @@
-#
-#  $XFree86: xc/lib/Xrandr/Xrandr.h,v 1.9 2002/09/29 23:39:44 keithp Exp $
-# 
-#  Copyright (C) 2000 Compaq Computer Corporation, Inc.
-#  Copyright (C) 2002 Hewlett-Packard Company, Inc.
-# 
-#  Permission to use, copy, modify, distribute, and sell this software and its
-#  documentation for any purpose is hereby granted without fee, provided that
-#  the above copyright notice appear in all copies and that both that
-#  copyright notice and this permission notice appear in supporting
-#  documentation, and that the name of Compaq not be used in advertising or
-#  publicity pertaining to distribution of the software without specific,
-#  written prior permission.  HP makes no representations about the
-#  suitability of this software for any purpose.  It is provided "as is"
-#  without express or implied warranty.
-# 
-#  HP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
-#  IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL COMPAQ
-#  BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-#  WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
-#  OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
-#  CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-# 
-#  Author:  Jim Gettys, HP Labs, HP.
-#
-
-import 
-  x, xlib
-
-const 
-  libXrandr* = "libXrandr.so"
-  
-# * $XFree86: xc/include/extensions/randr.h,v 1.4 2001/11/24 07:24:58 keithp Exp $
-# *
-# * Copyright (C) 2000, Compaq Computer Corporation, 
-# * Copyright (C) 2002, Hewlett Packard, Inc.
-# *
-# * Permission to use, copy, modify, distribute, and sell this software and its
-# * documentation for any purpose is hereby granted without fee, provided that
-# * the above copyright notice appear in all copies and that both that
-# * copyright notice and this permission notice appear in supporting
-# * documentation, and that the name of Compaq or HP not be used in advertising
-# * or publicity pertaining to distribution of the software without specific,
-# * written prior permission.  HP makes no representations about the
-# * suitability of this software for any purpose.  It is provided "as is"
-# * without express or implied warranty.
-# *
-# * HP DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING ALL
-# * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL HP
-# * BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
-# * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
-# * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN 
-# * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
-# *
-# * Author:  Jim Gettys, HP Labs, Hewlett-Packard, Inc.
-# *
-
-type 
-  PRotation* = ptr TRotation
-  TRotation* = cushort
-  PSizeID* = ptr TSizeID
-  TSizeID* = cushort
-  PSubpixelOrder* = ptr TSubpixelOrder
-  TSubpixelOrder* = cushort
-
-const 
-  RANDR_NAME* = "RANDR"
-  RANDR_MAJOR* = 1
-  RANDR_MINOR* = 1
-  RRNumberErrors* = 0
-  RRNumberEvents* = 1
-  constX_RRQueryVersion* = 0 # we skip 1 to make old clients fail pretty immediately 
-  X_RROldGetScreenInfo* = 1
-  X_RR1_0SetScreenConfig* = 2 # V1.0 apps share the same set screen config request id 
-  constX_RRSetScreenConfig* = 2
-  X_RROldScreenChangeSelectInput* = 3 # 3 used to be ScreenChangeSelectInput; deprecated 
-  constX_RRSelectInput* = 4
-  constX_RRGetScreenInfo* = 5      # used in XRRSelectInput 
-  RRScreenChangeNotifyMask* = 1 shl 0
-  RRScreenChangeNotify* = 0   # used in the rotation field; rotation and reflection in 0.1 proto. 
-  RR_Rotate_0* = 1
-  RR_Rotate_90* = 2
-  RR_Rotate_180* = 4
-  RR_Rotate_270* = 8          # new in 1.0 protocol, to allow reflection of screen 
-  RR_Reflect_X* = 16
-  RR_Reflect_Y* = 32
-  RRSetConfigSuccess* = 0
-  RRSetConfigInvalidConfigTime* = 1
-  RRSetConfigInvalidTime* = 2
-  RRSetConfigFailed* = 3
-
-type 
-  PXRRScreenSize* = ptr TXRRScreenSize
-  TXRRScreenSize*{.final.} = object  #
-                                     #   Events.
-                                     #
-    width*, height*: cint
-    mwidth*, mheight*: cint
-
-  TXRRScreenChangeNotifyEvent*{.final.} = object  # internal representation is private to the library 
-    typ*: cint                # event base 
-    serial*: culong           # # of last request processed by server 
-    send_event*: TBool        # true if this came from a SendEvent request 
-    display*: PDisplay        # Display the event was read from 
-    window*: TWindow          # window which selected for this event 
-    root*: TWindow            # Root window for changed screen 
-    timestamp*: TTime         # when the screen change occurred 
-    config_timestamp*: TTime  # when the last configuration change 
-    size_index*: TSizeID
-    subpixel_order*: TSubpixelOrder
-    rotation*: TRotation
-    width*: cint
-    height*: cint
-    mwidth*: cint
-    mheight*: cint
-
-  PXRRScreenConfiguration* = ptr TXRRScreenConfiguration
-  TXRRScreenConfiguration*{.final.} = object 
-
-proc XRRQueryExtension*(dpy: PDisplay, event_basep, error_basep: Pcint): TBool{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRQueryVersion*(dpy: PDisplay, major_versionp: Pcint, 
-                      minor_versionp: Pcint): TStatus{.cdecl, dynlib: libXrandr, 
-    importc.}
-proc XRRGetScreenInfo*(dpy: PDisplay, draw: TDrawable): PXRRScreenConfiguration{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRFreeScreenConfigInfo*(config: PXRRScreenConfiguration){.cdecl, 
-    dynlib: libXrandr, importc.}
-  #
-  #  Note that screen configuration changes are only permitted if the client can
-  #  prove it has up to date configuration information.  We are trying to
-  #  insist that it become possible for screens to change dynamically, so
-  #  we want to ensure the client knows what it is talking about when requesting
-  #  changes.
-  #
-proc XRRSetScreenConfig*(dpy: PDisplay, config: PXRRScreenConfiguration, 
-                         draw: TDrawable, size_index: cint, rotation: TRotation, 
-                         timestamp: TTime): TStatus{.cdecl, dynlib: libXrandr, 
-    importc.}
-  # added in v1.1, sorry for the lame name 
-proc XRRSetScreenConfigAndRate*(dpy: PDisplay, config: PXRRScreenConfiguration, 
-                                draw: TDrawable, size_index: cint, 
-                                rotation: TRotation, rate: cshort, 
-                                timestamp: TTime): TStatus{.cdecl, 
-    dynlib: libXrandr, importc.}
-proc XRRConfigRotations*(config: PXRRScreenConfiguration, 
-                         current_rotation: PRotation): TRotation{.cdecl, 
-    dynlib: libXrandr, importc.}
-proc XRRConfigTimes*(config: PXRRScreenConfiguration, config_timestamp: PTime): TTime{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRConfigSizes*(config: PXRRScreenConfiguration, nsizes: Pcint): PXRRScreenSize{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRConfigRates*(config: PXRRScreenConfiguration, sizeID: cint, 
-                     nrates: Pcint): ptr int16{.cdecl, dynlib: libXrandr, importc.}
-proc XRRConfigCurrentConfiguration*(config: PXRRScreenConfiguration, 
-                                    rotation: PRotation): TSizeID{.cdecl, 
-    dynlib: libXrandr, importc.}
-proc XRRConfigCurrentRate*(config: PXRRScreenConfiguration): cshort{.cdecl, 
-    dynlib: libXrandr, importc.}
-proc XRRRootToScreen*(dpy: PDisplay, root: TWindow): cint{.cdecl, 
-    dynlib: libXrandr, importc.}
-  #
-  #  returns the screen configuration for the specified screen; does a lazy
-  #  evalution to delay getting the information, and caches the result.
-  #  These routines should be used in preference to XRRGetScreenInfo
-  #  to avoid unneeded round trips to the X server.  These are new
-  #  in protocol version 0.1.
-  #
-proc XRRScreenConfig*(dpy: PDisplay, screen: cint): PXRRScreenConfiguration{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRConfig*(screen: PScreen): PXRRScreenConfiguration{.cdecl, 
-    dynlib: libXrandr, importc.}
-proc XRRSelectInput*(dpy: PDisplay, window: TWindow, mask: cint){.cdecl, 
-    dynlib: libXrandr, importc.}
-  #
-  #  the following are always safe to call, even if RandR is not implemented 
-  #  on a screen 
-  #
-proc XRRRotations*(dpy: PDisplay, screen: cint, current_rotation: PRotation): TRotation{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRSizes*(dpy: PDisplay, screen: cint, nsizes: Pcint): PXRRScreenSize{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRRates*(dpy: PDisplay, screen: cint, sizeID: cint, nrates: Pcint): ptr int16{.
-    cdecl, dynlib: libXrandr, importc.}
-proc XRRTimes*(dpy: PDisplay, screen: cint, config_timestamp: PTime): TTime{.
-    cdecl, dynlib: libXrandr, importc.}
-  #
-  #  intended to take RRScreenChangeNotify,  or 
-  #  ConfigureNotify (on the root window)
-  #  returns 1 if it is an event type it understands, 0 if not
-  #
-proc XRRUpdateConfiguration*(event: PXEvent): cint{.cdecl, dynlib: libXrandr, 
-    importc.}
-# implementation
diff --git a/tests/deps/x11-1.0/xrender.nim b/tests/deps/x11-1.0/xrender.nim
deleted file mode 100644
index c4b2b364d..000000000
--- a/tests/deps/x11-1.0/xrender.nim
+++ /dev/null
@@ -1,241 +0,0 @@
-
-import 
-  x, xlib
-
-when defined(use_pkg_config) or defined(use_pkg_config_static):
-    {.pragma: libxrender, cdecl, importc.}
-    when defined(use_pkg_config):
-        {.passl: gorge("pkg-config xrender --libs").}
-    else:
-        {.passl: gorge("pkg-config xrender --static --libs").}
-else:
-    when defined(macosx):
-        const 
-          libXrender* = "libXrender.dylib"
-    else:
-        const 
-          libXrender* = "libXrender.so"
-
-    
-    {.pragma: libxrender, dynlib: libXrender, cdecl, importc.}
-#const 
-#  libXrender* = "libXrender.so"
-
-#
-#  Automatically converted by H2Pas 0.99.15 from xrender.h
-#  The following command line parameters were used:
-#    -p
-#    -T
-#    -S
-#    -d
-#    -c
-#    xrender.h
-#
-
-type 
-  PGlyph* = ptr TGlyph
-  TGlyph* = int32
-  PGlyphSet* = ptr TGlyphSet
-  TGlyphSet* = int32
-  PPicture* = ptr TPicture
-  TPicture* = int32
-  PPictFormat* = ptr TPictFormat
-  TPictFormat* = int32
-
-const 
-  RENDER_NAME* = "RENDER"
-  RENDER_MAJOR* = 0
-  RENDER_MINOR* = 0
-  constX_RenderQueryVersion* = 0
-  X_RenderQueryPictFormats* = 1
-  X_RenderQueryPictIndexValues* = 2
-  X_RenderQueryDithers* = 3
-  constX_RenderCreatePicture* = 4
-  constX_RenderChangePicture* = 5
-  X_RenderSetPictureClipRectangles* = 6
-  constX_RenderFreePicture* = 7
-  constX_RenderComposite* = 8
-  X_RenderScale* = 9
-  X_RenderTrapezoids* = 10
-  X_RenderTriangles* = 11
-  X_RenderTriStrip* = 12
-  X_RenderTriFan* = 13
-  X_RenderColorTrapezoids* = 14
-  X_RenderColorTriangles* = 15
-  X_RenderTransform* = 16
-  constX_RenderCreateGlyphSet* = 17
-  constX_RenderReferenceGlyphSet* = 18
-  constX_RenderFreeGlyphSet* = 19
-  constX_RenderAddGlyphs* = 20
-  constX_RenderAddGlyphsFromPicture* = 21
-  constX_RenderFreeGlyphs* = 22
-  constX_RenderCompositeGlyphs8* = 23
-  constX_RenderCompositeGlyphs16* = 24
-  constX_RenderCompositeGlyphs32* = 25
-  BadPictFormat* = 0
-  BadPicture* = 1
-  BadPictOp* = 2
-  BadGlyphSet* = 3
-  BadGlyph* = 4
-  RenderNumberErrors* = BadGlyph + 1
-  PictTypeIndexed* = 0
-  PictTypeDirect* = 1
-  PictOpClear* = 0
-  PictOpSrc* = 1
-  PictOpDst* = 2
-  PictOpOver* = 3
-  PictOpOverReverse* = 4
-  PictOpIn* = 5
-  PictOpInReverse* = 6
-  PictOpOut* = 7
-  PictOpOutReverse* = 8
-  PictOpAtop* = 9
-  PictOpAtopReverse* = 10
-  PictOpXor* = 11
-  PictOpAdd* = 12
-  PictOpSaturate* = 13
-  PictOpMaximum* = 13
-  PolyEdgeSharp* = 0
-  PolyEdgeSmooth* = 1
-  PolyModePrecise* = 0
-  PolyModeImprecise* = 1
-  CPRepeat* = 1 shl 0
-  CPAlphaMap* = 1 shl 1
-  CPAlphaXOrigin* = 1 shl 2
-  CPAlphaYOrigin* = 1 shl 3
-  CPClipXOrigin* = 1 shl 4
-  CPClipYOrigin* = 1 shl 5
-  CPClipMask* = 1 shl 6
-  CPGraphicsExposure* = 1 shl 7
-  CPSubwindowMode* = 1 shl 8
-  CPPolyEdge* = 1 shl 9
-  CPPolyMode* = 1 shl 10
-  CPDither* = 1 shl 11
-  CPLastBit* = 11
-
-type 
-  PXRenderDirectFormat* = ptr TXRenderDirectFormat
-  TXRenderDirectFormat*{.final.} = object 
-    red*: int16
-    redMask*: int16
-    green*: int16
-    greenMask*: int16
-    blue*: int16
-    blueMask*: int16
-    alpha*: int16
-    alphaMask*: int16
-
-  PXRenderPictFormat* = ptr TXRenderPictFormat
-  TXRenderPictFormat*{.final.} = object 
-    id*: TPictFormat
-    thetype*: int32
-    depth*: int32
-    direct*: TXRenderDirectFormat
-    colormap*: TColormap
-
-
-const 
-  PictFormatID* = 1 shl 0
-  PictFormatType* = 1 shl 1
-  PictFormatDepth* = 1 shl 2
-  PictFormatRed* = 1 shl 3
-  PictFormatRedMask* = 1 shl 4
-  PictFormatGreen* = 1 shl 5
-  PictFormatGreenMask* = 1 shl 6
-  PictFormatBlue* = 1 shl 7
-  PictFormatBlueMask* = 1 shl 8
-  PictFormatAlpha* = 1 shl 9
-  PictFormatAlphaMask* = 1 shl 10
-  PictFormatColormap* = 1 shl 11
-
-type 
-  PXRenderVisual* = ptr TXRenderVisual
-  TXRenderVisual*{.final.} = object 
-    visual*: PVisual
-    format*: PXRenderPictFormat
-
-  PXRenderDepth* = ptr TXRenderDepth
-  TXRenderDepth*{.final.} = object 
-    depth*: int32
-    nvisuals*: int32
-    visuals*: PXRenderVisual
-
-  PXRenderScreen* = ptr TXRenderScreen
-  TXRenderScreen*{.final.} = object 
-    depths*: PXRenderDepth
-    ndepths*: int32
-    fallback*: PXRenderPictFormat
-
-  PXRenderInfo* = ptr TXRenderInfo
-  TXRenderInfo*{.final.} = object 
-    format*: PXRenderPictFormat
-    nformat*: int32
-    screen*: PXRenderScreen
-    nscreen*: int32
-    depth*: PXRenderDepth
-    ndepth*: int32
-    visual*: PXRenderVisual
-    nvisual*: int32
-
-  PXRenderPictureAttributes* = ptr TXRenderPictureAttributes
-  TXRenderPictureAttributes*{.final.} = object 
-    repeat*: TBool
-    alpha_map*: TPicture
-    alpha_x_origin*: int32
-    alpha_y_origin*: int32
-    clip_x_origin*: int32
-    clip_y_origin*: int32
-    clip_mask*: TPixmap
-    graphics_exposures*: TBool
-    subwindow_mode*: int32
-    poly_edge*: int32
-    poly_mode*: int32
-    dither*: TAtom
-
-  PXGlyphInfo* = ptr TXGlyphInfo
-  TXGlyphInfo*{.final.} = object 
-    width*: int16
-    height*: int16
-    x*: int16
-    y*: int16
-    xOff*: int16
-    yOff*: int16
-
-
-proc XRenderQueryExtension*(dpy: PDisplay, event_basep: ptr int32, 
-                            error_basep: ptr int32): TBool{.libxrender.}
-proc XRenderQueryVersion*(dpy: PDisplay, major_versionp: ptr int32, 
-                          minor_versionp: ptr int32): TStatus{.libxrender.}
-proc XRenderQueryFormats*(dpy: PDisplay): TStatus{.libxrender.}
-proc XRenderFindVisualFormat*(dpy: PDisplay, visual: PVisual): PXRenderPictFormat{.
-    libxrender.}
-proc XRenderFindFormat*(dpy: PDisplay, mask: int32, 
-                        `template`: PXRenderPictFormat, count: int32): PXRenderPictFormat{.
-    libxrender.}
-proc XRenderCreatePicture*(dpy: PDisplay, drawable: TDrawable, 
-                           format: PXRenderPictFormat, valuemask: int32, 
-                           attributes: PXRenderPictureAttributes): TPicture{.
-    libxrender.}
-proc XRenderChangePicture*(dpy: PDisplay, picture: TPicture, valuemask: int32, 
-                           attributes: PXRenderPictureAttributes){.libxrender.}
-proc XRenderFreePicture*(dpy: PDisplay, picture: TPicture){.libxrender.}
-proc XRenderComposite*(dpy: PDisplay, op: int32, src: TPicture, mask: TPicture, 
-                       dst: TPicture, src_x: int32, src_y: int32, mask_x: int32, 
-                       mask_y: int32, dst_x: int32, dst_y: int32, width: int32, 
-                       height: int32){.libxrender.}
-proc XRenderCreateGlyphSet*(dpy: PDisplay, format: PXRenderPictFormat): TGlyphSet{.
-    libxrender.}
-proc XRenderReferenceGlyphSet*(dpy: PDisplay, existing: TGlyphSet): TGlyphSet{.
-    libxrender.}
-proc XRenderFreeGlyphSet*(dpy: PDisplay, glyphset: TGlyphSet){.libxrender.}
-proc XRenderAddGlyphs*(dpy: PDisplay, glyphset: TGlyphSet, gids: PGlyph, 
-                       glyphs: PXGlyphInfo, nglyphs: int32, images: cstring, 
-                       nbyte_images: int32){.libxrender.}
-proc XRenderFreeGlyphs*(dpy: PDisplay, glyphset: TGlyphSet, gids: PGlyph, 
-                        nglyphs: int32){.libxrender.}
-proc XRenderCompositeString8*(dpy: PDisplay, op: int32, src: TPicture, 
-                              dst: TPicture, maskFormat: PXRenderPictFormat, 
-                              glyphset: TGlyphSet, xSrc: int32, ySrc: int32, 
-                              xDst: int32, yDst: int32, str: cstring, 
-                              nchar: int32){.libxrender.}
-# implementation
diff --git a/tests/deps/x11-1.0/xresource.nim b/tests/deps/x11-1.0/xresource.nim
deleted file mode 100644
index c96fbbb52..000000000
--- a/tests/deps/x11-1.0/xresource.nim
+++ /dev/null
@@ -1,201 +0,0 @@
-
-import 
-  x, xlib
-
-#const 
-#  libX11* = "libX11.so"
-
-#
-#  Automatically converted by H2Pas 0.99.15 from xresource.h
-#  The following command line parameters were used:
-#    -p
-#    -T
-#    -S
-#    -d
-#    -c
-#    xresource.h
-#
-
-proc Xpermalloc*(para1: int32): cstring{.cdecl, dynlib: libX11, importc.}
-type 
-  PXrmQuark* = ptr TXrmQuark
-  TXrmQuark* = int32
-  TXrmQuarkList* = PXrmQuark
-  PXrmQuarkList* = ptr TXrmQuarkList
-
-proc NULLQUARK*(): TXrmQuark
-type 
-  PXrmString* = ptr TXrmString
-  TXrmString* = ptr char
-
-proc NULLSTRING*(): TXrmString
-proc XrmStringToQuark*(para1: cstring): TXrmQuark{.cdecl, dynlib: libX11, 
-    importc.}
-proc XrmPermStringToQuark*(para1: cstring): TXrmQuark{.cdecl, dynlib: libX11, 
-    importc.}
-proc XrmQuarkToString*(para1: TXrmQuark): TXrmString{.cdecl, dynlib: libX11, 
-    importc.}
-proc XrmUniqueQuark*(): TXrmQuark{.cdecl, dynlib: libX11, importc.}
-#when defined(MACROS): 
-proc XrmStringsEqual*(a1, a2: cstring): bool
-type 
-  PXrmBinding* = ptr TXrmBinding
-  TXrmBinding* = enum 
-    XrmBindTightly, XrmBindLoosely
-  TXrmBindingList* = PXrmBinding
-  PXrmBindingList* = ptr TXrmBindingList
-
-proc XrmStringToQuarkList*(para1: cstring, para2: TXrmQuarkList){.cdecl, 
-    dynlib: libX11, importc.}
-proc XrmStringToBindingQuarkList*(para1: cstring, para2: TXrmBindingList, 
-                                  para3: TXrmQuarkList){.cdecl, dynlib: libX11, 
-    importc.}
-type 
-  PXrmName* = ptr TXrmName
-  TXrmName* = TXrmQuark
-  PXrmNameList* = ptr TXrmNameList
-  TXrmNameList* = TXrmQuarkList
-
-#when defined(MACROS): 
-proc XrmNameToString*(name: int32): TXrmString
-proc XrmStringToName*(str: cstring): int32
-proc XrmStringToNameList*(str: cstring, name: PXrmQuark)
-type 
-  PXrmClass* = ptr TXrmClass
-  TXrmClass* = TXrmQuark
-  PXrmClassList* = ptr TXrmClassList
-  TXrmClassList* = TXrmQuarkList
-
-#when defined(MACROS): 
-proc XrmClassToString*(c_class: int32): TXrmString
-proc XrmStringToClass*(c_class: cstring): int32
-proc XrmStringToClassList*(str: cstring, c_class: PXrmQuark)
-type 
-  PXrmRepresentation* = ptr TXrmRepresentation
-  TXrmRepresentation* = TXrmQuark
-
-#when defined(MACROS): 
-proc XrmStringToRepresentation*(str: cstring): int32
-proc XrmRepresentationToString*(thetype: int32): TXrmString
-type 
-  PXrmValue* = ptr TXrmValue
-  TXrmValue*{.final.} = object 
-    size*: int32
-    address*: TXPointer
-
-  TXrmValuePtr* = PXrmValue
-  PXrmValuePtr* = ptr TXrmValuePtr
-  PXrmHashBucketRec* = ptr TXrmHashBucketRec
-  TXrmHashBucketRec*{.final.} = object 
-  TXrmHashBucket* = PXrmHashBucketRec
-  PXrmHashBucket* = ptr TXrmHashBucket
-  PXrmHashTable* = ptr TXrmHashTable
-  TXrmHashTable* = ptr TXrmHashBucket
-  TXrmDatabase* = PXrmHashBucketRec
-  PXrmDatabase* = ptr TXrmDatabase
-
-proc XrmDestroyDatabase*(para1: TXrmDatabase){.cdecl, dynlib: libX11, importc.}
-proc XrmQPutResource*(para1: PXrmDatabase, para2: TXrmBindingList, 
-                      para3: TXrmQuarkList, para4: TXrmRepresentation, 
-                      para5: PXrmValue){.cdecl, dynlib: libX11, importc.}
-proc XrmPutResource*(para1: PXrmDatabase, para2: cstring, para3: cstring, 
-                     para4: PXrmValue){.cdecl, dynlib: libX11, importc.}
-proc XrmQPutStringResource*(para1: PXrmDatabase, para2: TXrmBindingList, 
-                            para3: TXrmQuarkList, para4: cstring){.cdecl, 
-    dynlib: libX11, importc.}
-proc XrmPutStringResource*(para1: PXrmDatabase, para2: cstring, para3: cstring){.
-    cdecl, dynlib: libX11, importc.}
-proc XrmPutLineResource*(para1: PXrmDatabase, para2: cstring){.cdecl, 
-    dynlib: libX11, importc.}
-proc XrmQGetResource*(para1: TXrmDatabase, para2: TXrmNameList, 
-                      para3: TXrmClassList, para4: PXrmRepresentation, 
-                      para5: PXrmValue): TBool{.cdecl, dynlib: libX11, importc.}
-proc XrmGetResource*(para1: TXrmDatabase, para2: cstring, para3: cstring, 
-                     para4: PPchar, para5: PXrmValue): TBool{.cdecl, 
-    dynlib: libX11, importc.}
-  # There is no definition of TXrmSearchList 
-  #function XrmQGetSearchList(para1:TXrmDatabase; para2:TXrmNameList; para3:TXrmClassList; para4:TXrmSearchList; para5:longint):TBool;cdecl;external libX11;
-  #function XrmQGetSearchResource(para1:TXrmSearchList; para2:TXrmName; para3:TXrmClass; para4:PXrmRepresentation; para5:PXrmValue):TBool;cdecl;external libX11;
-proc XrmSetDatabase*(para1: PDisplay, para2: TXrmDatabase){.cdecl, 
-    dynlib: libX11, importc.}
-proc XrmGetDatabase*(para1: PDisplay): TXrmDatabase{.cdecl, dynlib: libX11, 
-    importc.}
-proc XrmGetFileDatabase*(para1: cstring): TXrmDatabase{.cdecl, dynlib: libX11, 
-    importc.}
-proc XrmCombineFileDatabase*(para1: cstring, para2: PXrmDatabase, para3: TBool): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XrmGetStringDatabase*(para1: cstring): TXrmDatabase{.cdecl, dynlib: libX11, 
-    importc.}
-proc XrmPutFileDatabase*(para1: TXrmDatabase, para2: cstring){.cdecl, 
-    dynlib: libX11, importc.}
-proc XrmMergeDatabases*(para1: TXrmDatabase, para2: PXrmDatabase){.cdecl, 
-    dynlib: libX11, importc.}
-proc XrmCombineDatabase*(para1: TXrmDatabase, para2: PXrmDatabase, para3: TBool){.
-    cdecl, dynlib: libX11, importc.}
-const 
-  XrmEnumAllLevels* = 0
-  XrmEnumOneLevel* = 1
-
-type 
-  funcbool* = proc (): TBool {.cdecl.}
-
-proc XrmEnumerateDatabase*(para1: TXrmDatabase, para2: TXrmNameList, 
-                           para3: TXrmClassList, para4: int32, para5: funcbool, 
-                           para6: TXPointer): TBool{.cdecl, dynlib: libX11, 
-    importc.}
-proc XrmLocaleOfDatabase*(para1: TXrmDatabase): cstring{.cdecl, dynlib: libX11, 
-    importc.}
-type 
-  PXrmOptionKind* = ptr TXrmOptionKind
-  TXrmOptionKind* = enum 
-    XrmoptionNoArg, XrmoptionIsArg, XrmoptionStickyArg, XrmoptionSepArg, 
-    XrmoptionResArg, XrmoptionSkipArg, XrmoptionSkipLine, XrmoptionSkipNArgs
-  PXrmOptionDescRec* = ptr TXrmOptionDescRec
-  TXrmOptionDescRec*{.final.} = object 
-    option*: cstring
-    specifier*: cstring
-    argKind*: TXrmOptionKind
-    value*: TXPointer
-
-  TXrmOptionDescList* = PXrmOptionDescRec
-  PXrmOptionDescList* = ptr TXrmOptionDescList
-
-proc XrmParseCommand*(para1: PXrmDatabase, para2: TXrmOptionDescList, 
-                      para3: int32, para4: cstring, para5: ptr int32, 
-                      para6: PPchar){.cdecl, dynlib: libX11, importc.}
-# implementation
-
-proc NULLQUARK(): TXrmQuark = 
-  result = TXrmQuark(0)
-
-proc NULLSTRING(): TXrmString = 
-  result = nil
-
-#when defined(MACROS): 
-proc XrmStringsEqual(a1, a2: cstring): bool = 
-  #result = (strcomp(a1, a2)) == 0
-  $a1 == $a2
-
-proc XrmNameToString(name: int32): TXrmString = 
-  result = XrmQuarkToString(name)
-
-proc XrmStringToName(str: cstring): int32 = 
-  result = XrmStringToQuark(str)
-
-proc XrmStringToNameList(str: cstring, name: PXrmQuark) = 
-  XrmStringToQuarkList(str, name)
-
-proc XrmClassToString(c_class: int32): TXrmString = 
-  result = XrmQuarkToString(c_class)
-
-proc XrmStringToClass(c_class: cstring): int32 = 
-  result = XrmStringToQuark(c_class)
-
-proc XrmStringToClassList(str: cstring, c_class: PXrmQuark) = 
-  XrmStringToQuarkList(str, c_class)
-
-proc XrmStringToRepresentation(str: cstring): int32 = 
-  result = XrmStringToQuark(str)
-
-proc XrmRepresentationToString(thetype: int32): TXrmString = 
-  result = XrmQuarkToString(thetype)
diff --git a/tests/deps/x11-1.0/xshm.nim b/tests/deps/x11-1.0/xshm.nim
deleted file mode 100644
index e56bd87b1..000000000
--- a/tests/deps/x11-1.0/xshm.nim
+++ /dev/null
@@ -1,77 +0,0 @@
-
-import 
-  x, xlib
-
-#const 
-#  libX11* = "libX11.so"
-
-#
-#  Automatically converted by H2Pas 0.99.15 from xshm.h
-#  The following command line parameters were used:
-#    -p
-#    -T
-#    -S
-#    -d
-#    -c
-#    xshm.h
-#
-
-const 
-  constX_ShmQueryVersion* = 0
-  constX_ShmAttach* = 1
-  constX_ShmDetach* = 2
-  constX_ShmPutImage* = 3
-  constX_ShmGetImage* = 4
-  constX_ShmCreatePixmap* = 5
-  ShmCompletion* = 0
-  ShmNumberEvents* = ShmCompletion + 1
-  BadShmSeg* = 0
-  ShmNumberErrors* = BadShmSeg + 1
-
-type 
-  PShmSeg* = ptr TShmSeg
-  TShmSeg* = culong
-  PXShmCompletionEvent* = ptr TXShmCompletionEvent
-  TXShmCompletionEvent*{.final.} = object 
-    theType*: cint
-    serial*: culong
-    send_event*: TBool
-    display*: PDisplay
-    drawable*: TDrawable
-    major_code*: cint
-    minor_code*: cint
-    shmseg*: TShmSeg
-    offset*: culong
-
-  PXShmSegmentInfo* = ptr TXShmSegmentInfo
-  TXShmSegmentInfo*{.final.} = object 
-    shmseg*: TShmSeg
-    shmid*: cint
-    shmaddr*: cstring
-    readOnly*: TBool
-
-
-proc XShmQueryExtension*(para1: PDisplay): TBool{.cdecl, dynlib: libX11, importc.}
-proc XShmGetEventBase*(para1: PDisplay): cint{.cdecl, dynlib: libX11, importc.}
-proc XShmQueryVersion*(para1: PDisplay, para2: Pcint, para3: Pcint, para4: PBool): TBool{.
-    cdecl, dynlib: libX11, importc.}
-proc XShmPixmapFormat*(para1: PDisplay): cint{.cdecl, dynlib: libX11, importc.}
-proc XShmAttach*(para1: PDisplay, para2: PXShmSegmentInfo): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XShmDetach*(para1: PDisplay, para2: PXShmSegmentInfo): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XShmPutImage*(para1: PDisplay, para2: TDrawable, para3: TGC, 
-                   para4: PXImage, para5: cint, para6: cint, para7: cint, 
-                   para8: cint, para9: cuint, para10: cuint, para11: TBool): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XShmGetImage*(para1: PDisplay, para2: TDrawable, para3: PXImage, 
-                   para4: cint, para5: cint, para6: culong): TStatus{.cdecl, 
-    dynlib: libX11, importc.}
-proc XShmCreateImage*(para1: PDisplay, para2: PVisual, para3: cuint, 
-                      para4: cint, para5: cstring, para6: PXShmSegmentInfo, 
-                      para7: cuint, para8: cuint): PXImage{.cdecl, 
-    dynlib: libX11, importc.}
-proc XShmCreatePixmap*(para1: PDisplay, para2: TDrawable, para3: cstring, 
-                       para4: PXShmSegmentInfo, para5: cuint, para6: cuint, 
-                       para7: cuint): TPixmap{.cdecl, dynlib: libX11, importc.}
-# implementation
diff --git a/tests/deps/x11-1.0/xutil.nim b/tests/deps/x11-1.0/xutil.nim
deleted file mode 100644
index b7de0ae3e..000000000
--- a/tests/deps/x11-1.0/xutil.nim
+++ /dev/null
@@ -1,412 +0,0 @@
-
-import
-  x, xlib, keysym
-
-#const
-#  libX11* = "libX11.so"
-
-#
-#  Automatically converted by H2Pas 0.99.15 from xutil.h
-#  The following command line parameters were used:
-#    -p
-#    -T
-#    -S
-#    -d
-#    -c
-#    xutil.h
-#
-
-const
-  NoValue* = 0x00000000
-  XValue* = 0x00000001
-  YValue* = 0x00000002
-  WidthValue* = 0x00000004
-  HeightValue* = 0x00000008
-  AllValues* = 0x0000000F
-  XNegative* = 0x00000010
-  YNegative* = 0x00000020
-
-type
-  TCPoint*{.final.} = object
-    x*: cint
-    y*: cint
-
-  PXSizeHints* = ptr TXSizeHints
-  TXSizeHints*{.final.} = object
-    flags*: clong
-    x*, y*: cint
-    width*, height*: cint
-    min_width*, min_height*: cint
-    max_width*, max_height*: cint
-    width_inc*, height_inc*: cint
-    min_aspect*, max_aspect*: TCPoint
-    base_width*, base_height*: cint
-    win_gravity*: cint
-
-
-const
-  USPosition* = 1 shl 0
-  USSize* = 1 shl 1
-  PPosition* = 1 shl 2
-  PSize* = 1 shl 3
-  PMinSize* = 1 shl 4
-  PMaxSize* = 1 shl 5
-  PResizeInc* = 1 shl 6
-  PAspect* = 1 shl 7
-  PBaseSize* = 1 shl 8
-  PWinGravity* = 1 shl 9
-  PAllHints* = PPosition or PSize or PMinSize or PMaxSize or PResizeInc or
-      PAspect
-
-type
-  PXWMHints* = ptr TXWMHints
-  TXWMHints*{.final.} = object
-    flags*: clong
-    input*: TBool
-    initial_state*: cint
-    icon_pixmap*: TPixmap
-    icon_window*: TWindow
-    icon_x*, icon_y*: cint
-    icon_mask*: TPixmap
-    window_group*: TXID
-
-
-const
-  InputHint* = 1 shl 0
-  StateHint* = 1 shl 1
-  IconPixmapHint* = 1 shl 2
-  IconWindowHint* = 1 shl 3
-  IconPositionHint* = 1 shl 4
-  IconMaskHint* = 1 shl 5
-  WindowGroupHint* = 1 shl 6
-  AllHints* = InputHint or StateHint or IconPixmapHint or IconWindowHint or
-      IconPositionHint or IconMaskHint or WindowGroupHint
-  XUrgencyHint* = 1 shl 8
-  WithdrawnState* = 0
-  NormalState* = 1
-  IconicState* = 3
-  DontCareState* = 0
-  ZoomState* = 2
-  InactiveState* = 4
-
-type
-  PXTextProperty* = ptr TXTextProperty
-  TXTextProperty*{.final.} = object
-    value*: Pcuchar
-    encoding*: TAtom
-    format*: cint
-    nitems*: culong
-
-
-const
-  XNoMemory* = - 1
-  XLocaleNotSupported* = - 2
-  XConverterNotFound* = - 3
-
-type
-  PXICCEncodingStyle* = ptr TXICCEncodingStyle
-  TXICCEncodingStyle* = enum
-    XStringStyle, XCompoundTextStyle, XTextStyle, XStdICCTextStyle,
-    XUTF8StringStyle
-  PPXIconSize* = ptr PXIconSize
-  PXIconSize* = ptr TXIconSize
-  TXIconSize*{.final.} = object
-    min_width*, min_height*: cint
-    max_width*, max_height*: cint
-    width_inc*, height_inc*: cint
-
-  PXClassHint* = ptr TXClassHint
-  TXClassHint*{.final.} = object
-    res_name*: cstring
-    res_class*: cstring
-
-
-type
-  PXComposeStatus* = ptr TXComposeStatus
-  TXComposeStatus*{.final.} = object
-    compose_ptr*: TXPointer
-    chars_matched*: cint
-
-
-type
-  PXRegion* = ptr TXRegion
-  TXRegion*{.final.} = object
-  TRegion* = PXRegion
-  PRegion* = ptr TRegion
-
-const
-  RectangleOut* = 0
-  RectangleIn* = 1
-  RectanglePart* = 2
-
-type
-  PXVisualInfo* = ptr TXVisualInfo
-  TXVisualInfo*{.final.} = object
-    visual*: PVisual
-    visualid*: TVisualID
-    screen*: cint
-    depth*: cint
-    class*: cint
-    red_mask*: culong
-    green_mask*: culong
-    blue_mask*: culong
-    colormap_size*: cint
-    bits_per_rgb*: cint
-
-
-const
-  VisualNoMask* = 0x00000000
-  VisualIDMask* = 0x00000001
-  VisualScreenMask* = 0x00000002
-  VisualDepthMask* = 0x00000004
-  VisualClassMask* = 0x00000008
-  VisualRedMaskMask* = 0x00000010
-  VisualGreenMaskMask* = 0x00000020
-  VisualBlueMaskMask* = 0x00000040
-  VisualColormapSizeMask* = 0x00000080
-  VisualBitsPerRGBMask* = 0x00000100
-  VisualAllMask* = 0x000001FF
-
-type
-  PPXStandardColormap* = ptr PXStandardColormap
-  PXStandardColormap* = ptr TXStandardColormap
-  TXStandardColormap*{.final.} = object
-    colormap*: TColormap
-    red_max*: culong
-    red_mult*: culong
-    green_max*: culong
-    green_mult*: culong
-    blue_max*: culong
-    blue_mult*: culong
-    base_pixel*: culong
-    visualid*: TVisualID
-    killid*: TXID
-
-
-const
-  BitmapSuccess* = 0
-  BitmapOpenFailed* = 1
-  BitmapFileInvalid* = 2
-  BitmapNoMemory* = 3
-  XCSUCCESS* = 0
-  XCNOMEM* = 1
-  XCNOENT* = 2
-  ReleaseByFreeingColormap*: TXID = TXID(1)
-
-type
-  PXContext* = ptr TXContext
-  TXContext* = cint
-
-proc XAllocClassHint*(): PXClassHint{.cdecl, dynlib: libX11, importc.}
-proc XAllocIconSize*(): PXIconSize{.cdecl, dynlib: libX11, importc.}
-proc XAllocSizeHints*(): PXSizeHints{.cdecl, dynlib: libX11, importc.}
-proc XAllocStandardColormap*(): PXStandardColormap{.cdecl, dynlib: libX11,
-    importc.}
-proc XAllocWMHints*(): PXWMHints{.cdecl, dynlib: libX11, importc.}
-proc XClipBox*(para1: TRegion, para2: PXRectangle): cint{.cdecl, dynlib: libX11,
-    importc.}
-proc XCreateRegion*(): TRegion{.cdecl, dynlib: libX11, importc.}
-proc XDefaultString*(): cstring{.cdecl, dynlib: libX11, importc.}
-proc XDeleteContext*(para1: PDisplay, para2: TXID, para3: TXContext): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XDestroyRegion*(para1: TRegion): cint{.cdecl, dynlib: libX11, importc.}
-proc XEmptyRegion*(para1: TRegion): cint{.cdecl, dynlib: libX11, importc.}
-proc XEqualRegion*(para1: TRegion, para2: TRegion): cint{.cdecl, dynlib: libX11,
-    importc.}
-proc XFindContext*(para1: PDisplay, para2: TXID, para3: TXContext,
-                   para4: PXPointer): cint{.cdecl, dynlib: libX11, importc.}
-proc XGetClassHint*(para1: PDisplay, para2: TWindow, para3: PXClassHint): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XGetIconSizes*(para1: PDisplay, para2: TWindow, para3: PPXIconSize,
-                    para4: Pcint): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XGetNormalHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XGetRGBColormaps*(para1: PDisplay, para2: TWindow,
-                       para3: PPXStandardColormap, para4: Pcint, para5: TAtom): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XGetSizeHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints,
-                    para4: TAtom): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XGetStandardColormap*(para1: PDisplay, para2: TWindow,
-                           para3: PXStandardColormap, para4: TAtom): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XGetTextProperty*(para1: PDisplay, para2: TWindow, para3: PXTextProperty,
-                       para4: TAtom): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XGetVisualInfo*(para1: PDisplay, para2: clong, para3: PXVisualInfo,
-                     para4: Pcint): PXVisualInfo{.cdecl, dynlib: libX11, importc.}
-proc XGetWMClientMachine*(para1: PDisplay, para2: TWindow, para3: PXTextProperty): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XGetWMHints*(para1: PDisplay, para2: TWindow): PXWMHints{.cdecl,
-    dynlib: libX11, importc.}
-proc XGetWMIconName*(para1: PDisplay, para2: TWindow, para3: PXTextProperty): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XGetWMName*(para1: PDisplay, para2: TWindow, para3: PXTextProperty): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XGetWMNormalHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints,
-                        para4: ptr int): TStatus{.cdecl, dynlib: libX11, importc.}
-proc XGetWMSizeHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints,
-                      para4: ptr int, para5: TAtom): TStatus{.cdecl,
-    dynlib: libX11, importc.}
-proc XGetZoomHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints): TStatus{.
-    cdecl, dynlib: libX11, importc.}
-proc XIntersectRegion*(para1: TRegion, para2: TRegion, para3: TRegion): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XConvertCase*(para1: TKeySym, para2: PKeySym, para3: PKeySym){.cdecl,
-    dynlib: libX11, importc.}
-proc XLookupString*(para1: PXKeyEvent, para2: cstring, para3: cint,
-                    para4: PKeySym, para5: PXComposeStatus): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XMatchVisualInfo*(para1: PDisplay, para2: cint, para3: cint, para4: cint,
-                       para5: PXVisualInfo): TStatus{.cdecl, dynlib: libX11,
-    importc.}
-proc XOffsetRegion*(para1: TRegion, para2: cint, para3: cint): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XPointInRegion*(para1: TRegion, para2: cint, para3: cint): TBool{.cdecl,
-    dynlib: libX11, importc.}
-proc XPolygonRegion*(para1: PXPoint, para2: cint, para3: cint): TRegion{.cdecl,
-    dynlib: libX11, importc.}
-proc XRectInRegion*(para1: TRegion, para2: cint, para3: cint, para4: cuint,
-                    para5: cuint): cint{.cdecl, dynlib: libX11, importc.}
-proc XSaveContext*(para1: PDisplay, para2: TXID, para3: TXContext,
-                   para4: cstring): cint{.cdecl, dynlib: libX11, importc.}
-proc XSetClassHint*(para1: PDisplay, para2: TWindow, para3: PXClassHint): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XSetIconSizes*(para1: PDisplay, para2: TWindow, para3: PXIconSize,
-                    para4: cint): cint{.cdecl, dynlib: libX11, importc.}
-proc XSetNormalHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XSetRGBColormaps*(para1: PDisplay, para2: TWindow,
-                       para3: PXStandardColormap, para4: cint, para5: TAtom){.
-    cdecl, dynlib: libX11, importc.}
-proc XSetSizeHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints,
-                    para4: TAtom): cint{.cdecl, dynlib: libX11, importc.}
-proc XSetStandardProperties*(para1: PDisplay, para2: TWindow, para3: cstring,
-                             para4: cstring, para5: TPixmap, para6: PPchar,
-                             para7: cint, para8: PXSizeHints): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XSetTextProperty*(para1: PDisplay, para2: TWindow, para3: PXTextProperty,
-                       para4: TAtom){.cdecl, dynlib: libX11, importc.}
-proc XSetWMClientMachine*(para1: PDisplay, para2: TWindow, para3: PXTextProperty){.
-    cdecl, dynlib: libX11, importc.}
-proc XSetWMHints*(para1: PDisplay, para2: TWindow, para3: PXWMHints): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XSetWMIconName*(para1: PDisplay, para2: TWindow, para3: PXTextProperty){.
-    cdecl, dynlib: libX11, importc.}
-proc XSetWMName*(para1: PDisplay, para2: TWindow, para3: PXTextProperty){.cdecl,
-    dynlib: libX11, importc.}
-proc XSetWMNormalHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints){.
-    cdecl, dynlib: libX11, importc.}
-proc XSetWMProperties*(para1: PDisplay, para2: TWindow, para3: PXTextProperty,
-                       para4: PXTextProperty, para5: PPchar, para6: cint,
-                       para7: PXSizeHints, para8: PXWMHints, para9: PXClassHint){.
-    cdecl, dynlib: libX11, importc.}
-proc XmbSetWMProperties*(para1: PDisplay, para2: TWindow, para3: cstring,
-                         para4: cstring, para5: PPchar, para6: cint,
-                         para7: PXSizeHints, para8: PXWMHints,
-                         para9: PXClassHint){.cdecl, dynlib: libX11, importc.}
-proc Xutf8SetWMProperties*(para1: PDisplay, para2: TWindow, para3: cstring,
-                           para4: cstring, para5: PPchar, para6: cint,
-                           para7: PXSizeHints, para8: PXWMHints,
-                           para9: PXClassHint){.cdecl, dynlib: libX11, importc.}
-proc XSetWMSizeHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints,
-                      para4: TAtom){.cdecl, dynlib: libX11, importc.}
-proc XSetRegion*(para1: PDisplay, para2: TGC, para3: TRegion): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XSetStandardColormap*(para1: PDisplay, para2: TWindow,
-                           para3: PXStandardColormap, para4: TAtom){.cdecl,
-    dynlib: libX11, importc.}
-proc XSetZoomHints*(para1: PDisplay, para2: TWindow, para3: PXSizeHints): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XShrinkRegion*(para1: TRegion, para2: cint, para3: cint): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XStringListToTextProperty*(para1: PPchar, para2: cint,
-                                para3: PXTextProperty): TStatus{.cdecl,
-    dynlib: libX11, importc.}
-proc XSubtractRegion*(para1: TRegion, para2: TRegion, para3: TRegion): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XmbTextListToTextProperty*(para1: PDisplay, para2: PPchar, para3: cint,
-                                para4: TXICCEncodingStyle, para5: PXTextProperty): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XwcTextListToTextProperty*(para1: PDisplay, para2: ptr ptr int16, para3: cint,
-                                para4: TXICCEncodingStyle, para5: PXTextProperty): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc Xutf8TextListToTextProperty*(para1: PDisplay, para2: PPchar, para3: cint,
-                                  para4: TXICCEncodingStyle,
-                                  para5: PXTextProperty): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XwcFreeStringList*(para1: ptr ptr int16){.cdecl, dynlib: libX11, importc.}
-proc XTextPropertyToStringList*(para1: PXTextProperty, para2: PPPchar,
-                                para3: Pcint): TStatus{.cdecl, dynlib: libX11,
-    importc.}
-proc XmbTextPropertyToTextList*(para1: PDisplay, para2: PXTextProperty,
-                                para3: PPPchar, para4: Pcint): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XwcTextPropertyToTextList*(para1: PDisplay, para2: PXTextProperty,
-                                para3: ptr ptr ptr int16, para4: Pcint): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc Xutf8TextPropertyToTextList*(para1: PDisplay, para2: PXTextProperty,
-                                  para3: PPPchar, para4: Pcint): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XUnionRectWithRegion*(para1: PXRectangle, para2: TRegion, para3: TRegion): cint{.
-    cdecl, dynlib: libX11, importc.}
-proc XUnionRegion*(para1: TRegion, para2: TRegion, para3: TRegion): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XWMGeometry*(para1: PDisplay, para2: cint, para3: cstring, para4: cstring,
-                  para5: cuint, para6: PXSizeHints, para7: Pcint, para8: Pcint,
-                  para9: Pcint, para10: Pcint, para11: Pcint): cint{.cdecl,
-    dynlib: libX11, importc.}
-proc XXorRegion*(para1: TRegion, para2: TRegion, para3: TRegion): cint{.cdecl,
-    dynlib: libX11, importc.}
-#when defined(MACROS):
-proc XDestroyImage*(ximage: PXImage): cint
-proc XGetPixel*(ximage: PXImage, x, y: cint): culong
-proc XPutPixel*(ximage: PXImage, x, y: cint, pixel: culong): cint
-proc XSubImage*(ximage: PXImage, x, y: cint, width, height: cuint): PXImage
-proc XAddPixel*(ximage: PXImage, value: clong): cint
-proc IsKeypadKey*(keysym: TKeySym): bool
-proc IsPrivateKeypadKey*(keysym: TKeySym): bool
-proc IsCursorKey*(keysym: TKeySym): bool
-proc IsPFKey*(keysym: TKeySym): bool
-proc IsFunctionKey*(keysym: TKeySym): bool
-proc IsMiscFunctionKey*(keysym: TKeySym): bool
-proc IsModifierKey*(keysym: TKeySym): bool
-  #function XUniqueContext : TXContext;
-  #function XStringToContext(_string : Pchar) : TXContext;
-# implementation
-
-#when defined(MACROS):
-proc XDestroyImage(ximage: PXImage): cint =
-  ximage.f.destroy_image(ximage)
-
-proc XGetPixel(ximage: PXImage, x, y: cint): culong =
-  ximage.f.get_pixel(ximage, x, y)
-
-proc XPutPixel(ximage: PXImage, x, y: cint, pixel: culong): cint =
-  ximage.f.put_pixel(ximage, x, y, pixel)
-
-proc XSubImage(ximage: PXImage, x, y: cint, width, height: cuint): PXImage =
-  ximage.f.sub_image(ximage, x, y, width, height)
-
-proc XAddPixel(ximage: PXImage, value: clong): cint =
-  ximage.f.add_pixel(ximage, value)
-
-proc IsKeypadKey(keysym: TKeySym): bool =
-  (keysym >= XK_KP_Space) and (keysym <= XK_KP_Equal)
-
-proc IsPrivateKeypadKey(keysym: TKeySym): bool =
-  (keysym >= 0x11000000.TKeySym) and (keysym <= 0x1100FFFF.TKeySym)
-
-proc IsCursorKey(keysym: TKeySym): bool =
-  (keysym >= XK_Home) and (keysym < XK_Select)
-
-proc IsPFKey(keysym: TKeySym): bool =
-  (keysym >= XK_KP_F1) and (keysym <= XK_KP_F4)
-
-proc IsFunctionKey(keysym: TKeySym): bool =
-  (keysym >= XK_F1) and (keysym <= XK_F35)
-
-proc IsMiscFunctionKey(keysym: TKeySym): bool =
-  (keysym >= XK_Select) and (keysym <= XK_Break)
-
-proc IsModifierKey(keysym: TKeySym): bool =
-  ((keysym >= XK_Shift_L) and (keysym <= XK_Hyper_R)) or
-      (keysym == XK_Mode_switch) or (keysym == XK_Num_Lock)
diff --git a/tests/deps/x11-1.0/xv.nim b/tests/deps/x11-1.0/xv.nim
deleted file mode 100644
index 45ab61418..000000000
--- a/tests/deps/x11-1.0/xv.nim
+++ /dev/null
@@ -1,84 +0,0 @@
-#***********************************************************
-#Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts,
-#and the Massachusetts Institute of Technology, Cambridge, Massachusetts.
-#
-#                        All Rights Reserved
-#
-#Permission to use, copy, modify, and distribute this software and its 
-#documentation for any purpose and without fee is hereby granted, 
-#provided that the above copyright notice appear in all copies and that
-#both that copyright notice and this permission notice appear in 
-#supporting documentation, and that the names of Digital or MIT not be
-#used in advertising or publicity pertaining to distribution of the
-#software without specific, written prior permission.  
-#
-#DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-#ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-#DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-#ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-#WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-#ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-#SOFTWARE.
-#
-#******************************************************************
-# $XFree86: xc/include/extensions/Xv.h,v 1.3 1999/05/23 06:33:22 dawes Exp $ 
-
-import 
-  x
-
-const 
-  XvName* = "libXVideo.so"
-  XvVersion* = 2
-  XvRevision* = 2             # Symbols 
-
-type 
-  TXvPortID* = TXID
-  TXvEncodingID* = TXID
-
-const 
-  XvNone* = 0
-  XvInput* = 0
-  XvOutput* = 1
-  XvInputMask* = 1 shl XvInput
-  XvOutputMask* = 1 shl XvOutput
-  XvVideoMask* = 0x00000004
-  XvStillMask* = 0x00000008
-  XvImageMask* = 0x00000010   # These two are not client viewable 
-  XvPixmapMask* = 0x00010000
-  XvWindowMask* = 0x00020000
-  XvGettable* = 0x00000001
-  XvSettable* = 0x00000002
-  XvRGB* = 0
-  XvYUV* = 1
-  XvPacked* = 0
-  XvPlanar* = 1
-  XvTopToBottom* = 0
-  XvBottomToTop* = 1          # Events 
-  XvVideoNotify* = 0
-  XvPortNotify* = 1
-  XvNumEvents* = 2            # Video Notify Reasons 
-  XvStarted* = 0
-  XvStopped* = 1
-  XvBusy* = 2
-  XvPreempted* = 3
-  XvHardError* = 4
-  XvLastReason* = 4
-  XvNumReasons* = XvLastReason + 1
-  XvStartedMask* = 1 shl XvStarted
-  XvStoppedMask* = 1 shl XvStopped
-  XvBusyMask* = 1 shl XvBusy
-  XvPreemptedMask* = 1 shl XvPreempted
-  XvHardErrorMask* = 1 shl XvHardError
-  XvAnyReasonMask* = (1 shl XvNumReasons) - 1
-  XvNoReasonMask* = 0         # Errors 
-  XvBadPort* = 0
-  XvBadEncoding* = 1
-  XvBadControl* = 2
-  XvNumErrors* = 3            # Status 
-  XvBadExtension* = 1
-  XvAlreadyGrabbed* = 2
-  XvInvalidTime* = 3
-  XvBadReply* = 4
-  XvBadAlloc* = 5
-
-# implementation
diff --git a/tests/deps/x11-1.0/xvlib.nim b/tests/deps/x11-1.0/xvlib.nim
deleted file mode 100644
index e642cb350..000000000
--- a/tests/deps/x11-1.0/xvlib.nim
+++ /dev/null
@@ -1,234 +0,0 @@
-#***********************************************************
-#Copyright 1991 by Digital Equipment Corporation, Maynard, Massachusetts,
-#and the Massachusetts Institute of Technology, Cambridge, Massachusetts.
-#
-#                        All Rights Reserved
-#
-#Permission to use, copy, modify, and distribute this software and its
-#documentation for any purpose and without fee is hereby granted,
-#provided that the above copyright notice appear in all copies and that
-#both that copyright notice and this permission notice appear in
-#supporting documentation, and that the names of Digital or MIT not be
-#used in advertising or publicity pertaining to distribution of the
-#software without specific, written prior permission.
-#
-#DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
-#ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
-#DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
-#ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
-#WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
-#ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
-#SOFTWARE.
-#
-#******************************************************************
-# $XFree86: xc/include/extensions/Xvlib.h,v 1.3 1999/12/11 19:28:48 mvojkovi Exp $
-#*
-#** File:
-#**
-#**   Xvlib.h --- Xv library public header file
-#**
-#** Author:
-#**
-#**   David Carver (Digital Workstation Engineering/Project Athena)
-#**
-#** Revisions:
-#**
-#**   26.06.91 Carver
-#**     - changed XvFreeAdaptors to XvFreeAdaptorInfo
-#**     - changed XvFreeEncodings to XvFreeEncodingInfo
-#**
-#**   11.06.91 Carver
-#**     - changed SetPortControl to SetPortAttribute
-#**     - changed GetPortControl to GetPortAttribute
-#**     - changed QueryBestSize
-#**
-#**   05.15.91 Carver
-#**     - version 2.0 upgrade
-#**
-#**   01.24.91 Carver
-#**     - version 1.4 upgrade
-#**
-#*
-
-import
-  x, xlib, xshm, xv
-
-const
-  libXv* = "libXv.so"
-
-type
-  PXvRational* = ptr TXvRational
-  TXvRational*{.final.} = object
-    numerator*: cint
-    denominator*: cint
-
-  PXvAttribute* = ptr TXvAttribute
-  TXvAttribute*{.final.} = object
-    flags*: cint              # XvGettable, XvSettable
-    min_value*: cint
-    max_value*: cint
-    name*: cstring
-
-  PPXvEncodingInfo* = ptr PXvEncodingInfo
-  PXvEncodingInfo* = ptr TXvEncodingInfo
-  TXvEncodingInfo*{.final.} = object
-    encoding_id*: TXvEncodingID
-    name*: cstring
-    width*: culong
-    height*: culong
-    rate*: TXvRational
-    num_encodings*: culong
-
-  PXvFormat* = ptr TXvFormat
-  TXvFormat*{.final.} = object
-    depth*: cchar
-    visual_id*: culong
-
-  PPXvAdaptorInfo* = ptr PXvAdaptorInfo
-  PXvAdaptorInfo* = ptr TXvAdaptorInfo
-  TXvAdaptorInfo*{.final.} = object
-    base_id*: TXvPortID
-    num_ports*: culong
-    thetype*: cchar
-    name*: cstring
-    num_formats*: culong
-    formats*: PXvFormat
-    num_adaptors*: culong
-
-  PXvVideoNotifyEvent* = ptr TXvVideoNotifyEvent
-  TXvVideoNotifyEvent*{.final.} = object
-    theType*: cint
-    serial*: culong           # # of last request processed by server
-    send_event*: TBool        # true if this came from a SendEvent request
-    display*: PDisplay        # Display the event was read from
-    drawable*: TDrawable      # drawable
-    reason*: culong           # what generated this event
-    port_id*: TXvPortID       # what port
-    time*: TTime              # milliseconds
-
-  PXvPortNotifyEvent* = ptr TXvPortNotifyEvent
-  TXvPortNotifyEvent*{.final.} = object
-    theType*: cint
-    serial*: culong           # # of last request processed by server
-    send_event*: TBool        # true if this came from a SendEvent request
-    display*: PDisplay        # Display the event was read from
-    port_id*: TXvPortID       # what port
-    time*: TTime              # milliseconds
-    attribute*: TAtom         # atom that identifies attribute
-    value*: clong             # value of attribute
-
-  PXvEvent* = ptr TXvEvent
-  TXvEvent*{.final.} = object
-    pad*: array[0..23, clong] #case longint of
-                              #      0 : (
-                              #            theType : cint;
-                              #	  );
-                              #      1 : (
-                              #            xvvideo : TXvVideoNotifyEvent;
-                              #          );
-                              #      2 : (
-                              #            xvport : TXvPortNotifyEvent;
-                              #          );
-                              #      3 : (
-                              #
-                              #          );
-
-  PXvImageFormatValues* = ptr TXvImageFormatValues
-  TXvImageFormatValues*{.final.} = object
-    id*: cint                 # Unique descriptor for the format
-    theType*: cint            # XvRGB, XvYUV
-    byte_order*: cint         # LSBFirst, MSBFirst
-    guid*: array[0..15, cchar] # Globally Unique IDentifier
-    bits_per_pixel*: cint
-    format*: cint             # XvPacked, XvPlanar
-    num_planes*: cint         # for RGB formats only
-    depth*: cint
-    red_mask*: cuint
-    green_mask*: cuint
-    blue_mask*: cuint         # for YUV formats only
-    y_sample_bits*: cuint
-    u_sample_bits*: cuint
-    v_sample_bits*: cuint
-    horz_y_period*: cuint
-    horz_u_period*: cuint
-    horz_v_period*: cuint
-    vert_y_period*: cuint
-    vert_u_period*: cuint
-    vert_v_period*: cuint
-    component_order*: array[0..31, char] # eg. UYVY
-    scanline_order*: cint     # XvTopToBottom, XvBottomToTop
-
-  PXvImage* = ptr TXvImage
-  TXvImage*{.final.} = object
-    id*: cint
-    width*, height*: cint
-    data_size*: cint          # bytes
-    num_planes*: cint
-    pitches*: cint           # bytes
-    offsets*: cint           # bytes
-    data*: pointer
-    obdata*: TXPointer
-
-
-proc XvQueryExtension*(display: PDisplay, p_version, p_revision, p_requestBase,
-    p_eventBase, p_errorBase: cuint): cint{.cdecl, dynlib: libXv, importc.}
-proc XvQueryAdaptors*(display: PDisplay, window: TWindow, p_nAdaptors: cuint,
-                      p_pAdaptors: PPXvAdaptorInfo): cint{.cdecl, dynlib: libXv,
-    importc.}
-proc XvQueryEncodings*(display: PDisplay, port: TXvPortID, p_nEncoding: cuint,
-                       p_pEncoding: PPXvEncodingInfo): cint{.cdecl,
-    dynlib: libXv, importc.}
-proc XvPutVideo*(display: PDisplay, port: TXvPortID, d: TDrawable, gc: TGC,
-                 vx, vy: cint, vw, vh: cuint, dx, dy: cint, dw, dh: cuint): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvPutStill*(display: PDisplay, port: TXvPortID, d: TDrawable, gc: TGC,
-                 vx, vy: cint, vw, vh: cuint, dx, dy: cint, dw, dh: cuint): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvGetVideo*(display: PDisplay, port: TXvPortID, d: TDrawable, gc: TGC,
-                 vx, vy: cint, vw, vh: cuint, dx, dy: cint, dw, dh: cuint): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvGetStill*(display: PDisplay, port: TXvPortID, d: TDrawable, gc: TGC,
-                 vx, vy: cint, vw, vh: cuint, dx, dy: cint, dw, dh: cuint): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvStopVideo*(display: PDisplay, port: TXvPortID, drawable: TDrawable): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvGrabPort*(display: PDisplay, port: TXvPortID, time: TTime): cint{.cdecl,
-    dynlib: libXv, importc.}
-proc XvUngrabPort*(display: PDisplay, port: TXvPortID, time: TTime): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvSelectVideoNotify*(display: PDisplay, drawable: TDrawable, onoff: TBool): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvSelectPortNotify*(display: PDisplay, port: TXvPortID, onoff: TBool): cint{.
-    cdecl, dynlib: libXv, importc.}
-proc XvSetPortAttribute*(display: PDisplay, port: TXvPortID, attribute: TAtom,
-                         value: cint): cint{.cdecl, dynlib: libXv, importc.}
-proc XvGetPortAttribute*(display: PDisplay, port: TXvPortID, attribute: TAtom,
-                         p_value: cint): cint{.cdecl, dynlib: libXv, importc.}
-proc XvQueryBestSize*(display: PDisplay, port: TXvPortID, motion: TBool,
-                      vid_w, vid_h, drw_w, drw_h: cuint,
-                      p_actual_width, p_actual_height: cuint): cint{.cdecl,
-    dynlib: libXv, importc.}
-proc XvQueryPortAttributes*(display: PDisplay, port: TXvPortID, number: cint): PXvAttribute{.
-    cdecl, dynlib: libXv, importc.}
-proc XvFreeAdaptorInfo*(adaptors: PXvAdaptorInfo){.cdecl, dynlib: libXv, importc.}
-proc XvFreeEncodingInfo*(encodings: PXvEncodingInfo){.cdecl, dynlib: libXv,
-    importc.}
-proc XvListImageFormats*(display: PDisplay, port_id: TXvPortID,
-                         count_return: cint): PXvImageFormatValues{.cdecl,
-    dynlib: libXv, importc.}
-proc XvCreateImage*(display: PDisplay, port: TXvPortID, id: cint, data: pointer,
-                    width, height: cint): PXvImage{.cdecl, dynlib: libXv,
-    importc.}
-proc XvPutImage*(display: PDisplay, id: TXvPortID, d: TDrawable, gc: TGC,
-                 image: PXvImage, src_x, src_y: cint, src_w, src_h: cuint,
-                 dest_x, dest_y: cint, dest_w, dest_h: cuint): cint{.cdecl,
-    dynlib: libXv, importc.}
-proc XvShmPutImage*(display: PDisplay, id: TXvPortID, d: TDrawable, gc: TGC,
-                    image: PXvImage, src_x, src_y: cint, src_w, src_h: cuint,
-                    dest_x, dest_y: cint, dest_w, dest_h: cuint,
-                    send_event: TBool): cint{.cdecl, dynlib: libXv, importc.}
-proc XvShmCreateImage*(display: PDisplay, port: TXvPortID, id: cint,
-                       data: pointer, width, height: cint,
-                       shminfo: PXShmSegmentInfo): PXvImage{.cdecl,
-    dynlib: libXv, importc.}
-# implementation
diff --git a/tests/deps/zip-0.2.1/zip.nimble b/tests/deps/zip-0.2.1/zip.nimble
deleted file mode 100644
index 561f1b9c9..000000000
--- a/tests/deps/zip-0.2.1/zip.nimble
+++ /dev/null
@@ -1,18 +0,0 @@
-# Package
-
-version       = "0.2.1"
-author        = "Anonymous"
-description   = "Wrapper for the zip library"
-license       = "MIT"
-
-skipDirs = @["tests"]
-
-# Dependencies
-
-requires "nim >= 0.10.0"
-
-task tests, "Run lib tests":
-  withDir "tests":
-    exec "nim c -r ziptests"
-    exec "nim c -r zlibtests"
-    exec "nim c -r gziptests"
diff --git a/tests/deps/zip-0.2.1/zip/gzipfiles.nim b/tests/deps/zip-0.2.1/zip/gzipfiles.nim
deleted file mode 100644
index 82c412bc3..000000000
--- a/tests/deps/zip-0.2.1/zip/gzipfiles.nim
+++ /dev/null
@@ -1,97 +0,0 @@
-import os
-import zlib
-import streams
-export streams
-
-## This module implements a gzipfile stream for reading, writing, appending.
-
-type
-    GzFileStream* = ref object of Stream
-        mode: FileMode
-        f: GzFile
-
-const SEEK_SET = 0.int32 # Seek from beginning of file.
-
-proc fsClose(s: Stream) =
-    if not GzFileStream(s).f.isNil:
-      discard gzclose(GzFileStream(s).f)
-      GzFileStream(s).f = nil
-
-proc fsFlush(s: Stream) =
-    # compiler flushFile also discard c_fflush
-    discard gzflush(GzFileStream(s).f, Z_FINISH)
-
-proc fsAtEnd(s: Stream): bool =
-    result = gzeof(GzFileStream(s).f) == 1
-
-proc fsSetPosition(s: Stream, pos: int) =
-    if gzseek(GzFileStream(s).f, pos.ZOffT, SEEK_SET) == -1:
-        if GzFileStream(s).mode in {fmWrite, fmAppend}:
-            raise newException(IOError, "error in gzip stream while seeking! (file is in write/append mode!")
-        else:
-            raise newException(IOError, "error in gzip stream while seeking!")
-
-proc fsGetPosition(s: Stream): int =
-    result = gztell(GzFileStream(s).f).int
-
-proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int =
-    result = gzread(GzFileStream(s).f, buffer, bufLen).int
-    if result == -1:
-        if GzFileStream(s).mode in {fmWrite, fmAppend}:
-            raise newException(IOError, "cannot read data from write-only gzip stream!")
-        else:
-            raise newException(IOError, "cannot read from stream!")
-
-proc fsPeekData(s: Stream, buffer: pointer, bufLen: int): int =
-    let gz = GzFileStream(s)
-    if gz.mode in {fmWrite, fmAppend}:
-        raise newException(IOError, "cannot peek data from write-only gzip stream!")
-    let pos = int(gztell(gz.f))
-    result = fsReadData(s, buffer, bufLen)
-    fsSetPosition(s, pos)
-
-proc fsWriteData(s: Stream, buffer: pointer, bufLen: int) =
-    if gzwrite(GzFileStream(s).f, buffer, bufLen).int != bufLen:
-        if GzFileStream(s).mode in {fmWrite, fmAppend}:
-            raise newException(IOError, "cannot write data to gzip stream!")
-        else:
-            raise newException(IOError, "cannot write data to read-only gzip stream!")
-
-
-proc newGzFileStream*(filename: string; mode=fmRead; level=Z_DEFAULT_COMPRESSION): GzFileStream =
-    ## Opens a Gzipfile as a file stream. `mode` can be
-    ## ``fmRead``, ``fmWrite`` or ``fmAppend``.
-    ##
-    ## Compression level can be set with ``level`` argument. Currently
-    ## ``Z_DEFAULT_COMPRESSION`` is 6.
-    ##
-    ## Note: ``level`` is ignored if ``mode`` is `fmRead`
-    ##
-    ## Note: There is only partial support for file seeking
-    ##  - in fmRead mode, seeking randomly inside the gzip
-    ## file will lead to poor performance.
-    ##  - in fmWrite, fmAppend mode, only forward seeking
-    ## is supported.
-    new(result)
-    case mode
-    of fmRead: result.f = gzopen(filename, "rb")
-    of fmWrite: result.f = gzopen(filename, "wb")
-    of fmAppend: result.f = gzopen(filename, "ab")
-    else: raise newException(IOError, "unsupported file mode '" & $mode &
-                            "' for GzFileStream!")
-    if result.f.isNil:
-        let err = osLastError()
-        if err != OSErrorCode(0'i32):
-            raiseOSError(err)
-    if mode in {fmWrite, fmAppend}:
-        discard gzsetparams(result.f, level.int32, Z_DEFAULT_STRATEGY.int32)
-
-    result.mode = mode
-    result.closeImpl = fsClose
-    result.atEndImpl = fsAtEnd
-    result.setPositionImpl = fsSetPosition
-    result.getPositionImpl = fsGetPosition
-    result.readDataImpl = fsReadData
-    result.peekDataImpl = fsPeekData
-    result.writeDataImpl = fsWriteData
-    result.flushImpl = fsFlush
diff --git a/tests/deps/zip-0.2.1/zip/libzip.nim b/tests/deps/zip-0.2.1/zip/libzip.nim
deleted file mode 100644
index a2904cd2c..000000000
--- a/tests/deps/zip-0.2.1/zip/libzip.nim
+++ /dev/null
@@ -1,252 +0,0 @@
-#
-#
-#            Nim's Runtime Library
-#        (c) Copyright 2013 Andreas Rumpf
-#
-#    See the file "copying.txt", included in this
-#    distribution, for details about the copyright.
-#
-
-## Interface to the `libzip <http://www.nih.at/libzip/index.html>`_ library by
-## Dieter Baron and Thomas Klausner. This version links
-## against ``libzip2.so.2`` unless you define the symbol ``useLibzipSrc``; then
-## it is compiled against some old ``libizp_all.c`` file.
-
-#
-#  zip.h -- exported declarations.
-#  Copyright (C) 1999-2008 Dieter Baron and Thomas Klausner
-#
-#  This file is part of libzip, a library to manipulate ZIP archives.
-#  The authors can be contacted at <libzip@nih.at>
-#
-#  Redistribution and use in source and binary forms, with or without
-#  modification, are permitted provided that the following conditions
-#  are met:
-#  1. Redistributions of source code must retain the above copyright
-#     notice, this list of conditions and the following disclaimer.
-#  2. Redistributions in binary form must reproduce the above copyright
-#     notice, this list of conditions and the following disclaimer in
-#     the documentation and/or other materials provided with the
-#     distribution.
-#  3. The names of the authors may not be used to endorse or promote
-#     products derived from this software without specific prior
-#     written permission.
-#
-#  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
-#  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-#  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-#  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
-#  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-#  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
-#  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-#  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
-#  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-#  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
-#  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-#
-
-import times
-
-when defined(unix) and not defined(useLibzipSrc):
-  when defined(macosx):
-    {.pragma: mydll, dynlib: "libzip(|2|4).dylib".}
-  else:
-    {.pragma: mydll, dynlib: "libzip(|2).so(|.4|.2|.1|.0)".}
-else:
-  when defined(unix):
-    {.passl: "-lz".}
-  {.compile: "zip/private/libzip_all.c".}
-  {.pragma: mydll.}
-
-type
-  ZipSourceCmd* = int32
-
-  ZipSourceCallback* = proc (state: pointer, data: pointer, length: int,
-                              cmd: ZipSourceCmd): int {.cdecl.}
-  PZipStat* = ptr ZipStat
-  ZipStat* = object           ## the 'zip_stat' struct
-    name*: cstring            ## name of the file
-    index*: int32             ## index within archive
-    crc*: int32               ## crc of file data
-    mtime*: Time              ## modification time
-    size*: int                ## size of file (uncompressed)
-    compSize*: int            ## size of file (compressed)
-    compMethod*: int16        ## compression method used
-    encryptionMethod*: int16  ## encryption method used
-
-  Zip = object
-  ZipSource = object
-  ZipFile = object
-
-  PZip* = ptr Zip ## represents a zip archive
-  PZipFile* = ptr ZipFile ## represents a file within an archive
-  PZipSource* = ptr ZipSource ## represents a source for an archive
-{.deprecated: [TZipSourceCmd: ZipSourceCmd, TZipStat: ZipStat, TZip: Zip,
-              TZipSourceCallback: ZipSourceCallback, TZipSource: ZipSource,
-              TZipFile: ZipFile].}
-
-# flags for zip_name_locate, zip_fopen, zip_stat, ...
-const
-  ZIP_CREATE* = 1'i32
-  ZIP_EXCL* = 2'i32
-  ZIP_CHECKCONS* = 4'i32
-  ZIP_FL_NOCASE* = 1'i32        ## ignore case on name lookup
-  ZIP_FL_NODIR* = 2'i32         ## ignore directory component
-  ZIP_FL_COMPRESSED* = 4'i32    ## read compressed data
-  ZIP_FL_UNCHANGED* = 8'i32     ## use original data, ignoring changes
-  ZIP_FL_RECOMPRESS* = 16'i32   ## force recompression of data
-
-const  # archive global flags flags
-  ZIP_AFL_TORRENT* = 1'i32      ##  torrent zipped
-
-const # libzip error codes
-  ZIP_ER_OK* = 0'i32            ## N No error
-  ZIP_ER_MULTIDISK* = 1'i32     ## N Multi-disk zip archives not supported
-  ZIP_ER_RENAME* = 2'i32        ## S Renaming temporary file failed
-  ZIP_ER_CLOSE* = 3'i32         ## S Closing zip archive failed
-  ZIP_ER_SEEK* = 4'i32          ## S Seek error
-  ZIP_ER_READ* = 5'i32          ## S Read error
-  ZIP_ER_WRITE* = 6'i32         ## S Write error
-  ZIP_ER_CRC* = 7'i32           ## N CRC error
-  ZIP_ER_ZIPCLOSED* = 8'i32     ## N Containing zip archive was closed
-  ZIP_ER_NOENT* = 9'i32         ## N No such file
-  ZIP_ER_EXISTS* = 10'i32       ## N File already exists
-  ZIP_ER_OPEN* = 11'i32         ## S Can't open file
-  ZIP_ER_TMPOPEN* = 12'i32      ## S Failure to create temporary file
-  ZIP_ER_ZLIB* = 13'i32         ## Z Zlib error
-  ZIP_ER_MEMORY* = 14'i32       ## N Malloc failure
-  ZIP_ER_CHANGED* = 15'i32      ## N Entry has been changed
-  ZIP_ER_COMPNOTSUPP* = 16'i32  ## N Compression method not supported
-  ZIP_ER_EOF* = 17'i32          ## N Premature EOF
-  ZIP_ER_INVAL* = 18'i32        ## N Invalid argument
-  ZIP_ER_NOZIP* = 19'i32        ## N Not a zip archive
-  ZIP_ER_INTERNAL* = 20'i32     ## N Internal error
-  ZIP_ER_INCONS* = 21'i32       ## N Zip archive inconsistent
-  ZIP_ER_REMOVE* = 22'i32       ## S Can't remove file
-  ZIP_ER_DELETED* = 23'i32      ## N Entry has been deleted
-
-const # type of system error value
-  ZIP_ET_NONE* = 0'i32          ## sys_err unused
-  ZIP_ET_SYS* = 1'i32           ## sys_err is errno
-  ZIP_ET_ZLIB* = 2'i32          ## sys_err is zlib error code
-
-const # compression methods
-  ZIP_CM_DEFAULT* = -1'i32      ## better of deflate or store
-  ZIP_CM_STORE* = 0'i32         ## stored (uncompressed)
-  ZIP_CM_SHRINK* = 1'i32        ## shrunk
-  ZIP_CM_REDUCE_1* = 2'i32      ## reduced with factor 1
-  ZIP_CM_REDUCE_2* = 3'i32      ## reduced with factor 2
-  ZIP_CM_REDUCE_3* = 4'i32      ## reduced with factor 3
-  ZIP_CM_REDUCE_4* = 5'i32      ## reduced with factor 4
-  ZIP_CM_IMPLODE* = 6'i32       ## imploded
-                                ## 7 - Reserved for Tokenizing compression algorithm
-  ZIP_CM_DEFLATE* = 8'i32       ## deflated
-  ZIP_CM_DEFLATE64* = 9'i32     ## deflate64
-  ZIP_CM_PKWARE_IMPLODE* = 10'i32 ## PKWARE imploding
-                                  ## 11 - Reserved by PKWARE
-  ZIP_CM_BZIP2* = 12'i32        ## compressed using BZIP2 algorithm
-                                ## 13 - Reserved by PKWARE
-  ZIP_CM_LZMA* = 14'i32         ## LZMA (EFS)
-                                ## 15-17 - Reserved by PKWARE
-  ZIP_CM_TERSE* = 18'i32        ## compressed using IBM TERSE (new)
-  ZIP_CM_LZ77* = 19'i32         ## IBM LZ77 z Architecture (PFS)
-  ZIP_CM_WAVPACK* = 97'i32      ## WavPack compressed data
-  ZIP_CM_PPMD* = 98'i32         ## PPMd version I, Rev 1
-
-const  # encryption methods
-  ZIP_EM_NONE* = 0'i32            ## not encrypted
-  ZIP_EM_TRAD_PKWARE* = 1'i32     ## traditional PKWARE encryption
-
-const
-  ZIP_EM_UNKNOWN* = 0x0000FFFF'i32 ## unknown algorithm
-
-const
-  ZIP_SOURCE_OPEN* = 0'i32        ## prepare for reading
-  ZIP_SOURCE_READ* = 1'i32        ## read data
-  ZIP_SOURCE_CLOSE* = 2'i32       ## reading is done
-  ZIP_SOURCE_STAT* = 3'i32        ## get meta information
-  ZIP_SOURCE_ERROR* = 4'i32       ## get error information
-  constZIP_SOURCE_FREE* = 5'i32   ## cleanup and free resources
-  ZIP_SOURCE_SUPPORTS* = 14'i32   ## check supported commands
-
-proc zip_add*(para1: PZip, para2: cstring, para3: PZipSource): int32 {.cdecl,
-    importc: "zip_add", mydll.}
-proc zip_add_dir*(para1: PZip, para2: cstring): int32 {.cdecl,
-    importc: "zip_add_dir", mydll.}
-proc zip_close*(para1: PZip) {.cdecl, importc: "zip_close", mydll.}
-proc zip_delete*(para1: PZip, para2: int32): int32 {.cdecl, mydll,
-    importc: "zip_delete".}
-proc zip_error_clear*(para1: PZip) {.cdecl, importc: "zip_error_clear", mydll.}
-proc zip_error_get*(para1: PZip, para2: ptr int32, para3: ptr int32) {.cdecl,
-    importc: "zip_error_get", mydll.}
-proc zip_error_get_sys_type*(para1: int32): int32 {.cdecl, mydll,
-    importc: "zip_error_get_sys_type".}
-proc zip_error_to_str*(para1: cstring, para2: int, para3: int32,
-                       para4: int32): int32 {.cdecl, mydll,
-    importc: "zip_error_to_str".}
-proc zip_fclose*(para1: PZipFile) {.cdecl, mydll,
-    importc: "zip_fclose".}
-proc zip_file_error_clear*(para1: PZipFile) {.cdecl, mydll,
-    importc: "zip_file_error_clear".}
-proc zip_file_error_get*(para1: PZipFile, para2: ptr int32, para3: ptr int32) {.
-    cdecl, mydll, importc: "zip_file_error_get".}
-proc zip_file_strerror*(para1: PZipFile): cstring {.cdecl, mydll,
-    importc: "zip_file_strerror".}
-proc zip_fopen*(para1: PZip, para2: cstring, para3: int32): PZipFile {.cdecl,
-    mydll, importc: "zip_fopen".}
-proc zip_fopen_index*(para1: PZip, para2: int32, para3: int32): PZipFile {.
-    cdecl, mydll, importc: "zip_fopen_index".}
-proc zip_fread*(para1: PZipFile, para2: pointer, para3: int): int {.
-    cdecl, mydll, importc: "zip_fread".}
-proc zip_get_archive_comment*(para1: PZip, para2: ptr int32, para3: int32): cstring {.
-    cdecl, mydll, importc: "zip_get_archive_comment".}
-proc zip_get_archive_flag*(para1: PZip, para2: int32, para3: int32): int32 {.
-    cdecl, mydll, importc: "zip_get_archive_flag".}
-proc zip_get_file_comment*(para1: PZip, para2: int32, para3: ptr int32,
-                           para4: int32): cstring {.cdecl, mydll,
-    importc: "zip_get_file_comment".}
-proc zip_get_name*(para1: PZip, para2: int32, para3: int32): cstring {.cdecl,
-    mydll, importc: "zip_get_name".}
-proc zip_get_num_files*(para1: PZip): int32 {.cdecl,
-    mydll, importc: "zip_get_num_files".}
-proc zip_name_locate*(para1: PZip, para2: cstring, para3: int32): int32 {.cdecl,
-    mydll, importc: "zip_name_locate".}
-proc zip_open*(para1: cstring, para2: int32, para3: ptr int32): PZip {.cdecl,
-    mydll, importc: "zip_open".}
-proc zip_rename*(para1: PZip, para2: int32, para3: cstring): int32 {.cdecl,
-    mydll, importc: "zip_rename".}
-proc zip_replace*(para1: PZip, para2: int32, para3: PZipSource): int32 {.cdecl,
-    mydll, importc: "zip_replace".}
-proc zip_set_archive_comment*(para1: PZip, para2: cstring, para3: int32): int32 {.
-    cdecl, mydll, importc: "zip_set_archive_comment".}
-proc zip_set_archive_flag*(para1: PZip, para2: int32, para3: int32): int32 {.
-    cdecl, mydll, importc: "zip_set_archive_flag".}
-proc zip_set_file_comment*(para1: PZip, para2: int32, para3: cstring,
-                           para4: int32): int32 {.cdecl, mydll,
-    importc: "zip_set_file_comment".}
-proc zip_source_buffer*(para1: PZip, para2: pointer, para3: int, para4: int32): PZipSource {.
-    cdecl, mydll, importc: "zip_source_buffer".}
-proc zip_source_file*(para1: PZip, para2: cstring, para3: int, para4: int): PZipSource {.
-    cdecl, mydll, importc: "zip_source_file".}
-proc zip_source_filep*(para1: PZip, para2: File, para3: int, para4: int): PZipSource {.
-    cdecl, mydll, importc: "zip_source_filep".}
-proc zip_source_free*(para1: PZipSource) {.cdecl, mydll,
-    importc: "zip_source_free".}
-proc zip_source_function*(para1: PZip, para2: ZipSourceCallback,
-                          para3: pointer): PZipSource {.cdecl, mydll,
-    importc: "zip_source_function".}
-proc zip_source_zip*(para1: PZip, para2: PZip, para3: int32, para4: int32,
-                     para5: int, para6: int): PZipSource {.cdecl, mydll,
-    importc: "zip_source_zip".}
-proc zip_stat*(para1: PZip, para2: cstring, para3: int32, para4: PZipStat): int32 {.
-    cdecl, mydll, importc: "zip_stat".}
-proc zip_stat_index*(para1: PZip, para2: int32, para3: int32, para4: PZipStat): int32 {.
-    cdecl, mydll, importc: "zip_stat_index".}
-proc zip_stat_init*(para1: PZipStat) {.cdecl, mydll, importc: "zip_stat_init".}
-proc zip_strerror*(para1: PZip): cstring {.cdecl, mydll, importc: "zip_strerror".}
-proc zip_unchange*(para1: PZip, para2: int32): int32 {.cdecl, mydll,
-    importc: "zip_unchange".}
-proc zip_unchange_all*(para1: PZip): int32 {.cdecl, mydll,
-    importc: "zip_unchange_all".}
-proc zip_unchange_archive*(para1: PZip): int32 {.cdecl, mydll,
-    importc: "zip_unchange_archive".}
diff --git a/tests/deps/zip-0.2.1/zip/private/libzip_all.c b/tests/deps/zip-0.2.1/zip/private/libzip_all.c
deleted file mode 100644
index e0627a7eb..000000000
--- a/tests/deps/zip-0.2.1/zip/private/libzip_all.c
+++ /dev/null
@@ -1,4193 +0,0 @@
-/*
-  zipint.h -- internal declarations.
-  Copyright (C) 1999-2008 Dieter Baron and Thomas Klausner
-
-  This file is part of libzip, a library to manipulate ZIP archives.
-  The authors can be contacted at <libzip@nih.at>
-
-  Redistribution and use in source and binary forms, with or without
-  modification, are permitted provided that the following conditions
-  are met:
-  1. Redistributions of source code must retain the above copyright
-     notice, this list of conditions and the following disclaimer.
-  2. Redistributions in binary form must reproduce the above copyright
-     notice, this list of conditions and the following disclaimer in
-     the documentation and/or other materials provided with the
-     distribution.
-  3. The names of the authors may not be used to endorse or promote
-     products derived from this software without specific prior
-     written permission.
-
-  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
-  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
-  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
-  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
-  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
-  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-#include <zlib.h>
-
-/*
-#ifdef _MSC_VER
-#define ZIP_EXTERN __declspec(dllimport)
-#endif
-*/
-
-/*
-  zip.h -- exported declarations.
-  Copyright (C) 1999-2008 Dieter Baron and Thomas Klausner
-
-  This file is part of libzip, a library to manipulate ZIP archives.
-  The authors can be contacted at <libzip@nih.at>
-
-  Redistribution and use in source and binary forms, with or without
-  modification, are permitted provided that the following conditions
-  are met:
-  1. Redistributions of source code must retain the above copyright
-     notice, this list of conditions and the following disclaimer.
-  2. Redistributions in binary form must reproduce the above copyright
-     notice, this list of conditions and the following disclaimer in
-     the documentation and/or other materials provided with the
-     distribution.
-  3. The names of the authors may not be used to endorse or promote
-     products derived from this software without specific prior
-     written permission.
-
-  THIS SOFTWARE IS PROVIDED BY THE AUTHORS ``AS IS'' AND ANY EXPRESS
-  OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
-  ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY
-  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-  DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE
-  GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
-  INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
-  IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
-  OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
-  IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
-*/
-
-
-#ifndef ZIP_EXTERN
-#define ZIP_EXTERN
-#endif
-
-#ifdef __cplusplus
-extern "C" {
-#endif
-
-#include <sys/types.h>
-#include <stdio.h>
-#include <time.h>
-
-/* flags for zip_open */
-
-#define ZIP_CREATE           1
-#define ZIP_EXCL             2
-#define ZIP_CHECKCONS        4
-
-
-/* flags for zip_name_locate, zip_fopen, zip_stat, ... */
-
-#define ZIP_FL_NOCASE                1 /* ignore case on name lookup */
-#define ZIP_FL_NODIR                2 /* ignore directory component */
-#define ZIP_FL_COMPRESSED        4 /* read compressed data */
-#define ZIP_FL_UNCHANGED        8 /* use original data, ignoring changes */
-#define ZIP_FL_RECOMPRESS      16 /* force recompression of data */
-
-/* archive global flags flags */
-
-#define ZIP_AFL_TORRENT                1 /* torrent zipped */
-
-/* libzip error codes */
-
-#define ZIP_ER_OK             0  /* N No error */
-#define ZIP_ER_MULTIDISK      1  /* N Multi-disk zip archives not supported */
-#define ZIP_ER_RENAME         2  /* S Renaming temporary file failed */
-#define ZIP_ER_CLOSE          3  /* S Closing zip archive failed */
-#define ZIP_ER_SEEK           4  /* S Seek error */
-#define ZIP_ER_READ           5  /* S Read error */
-#define ZIP_ER_WRITE          6  /* S Write error */
-#define ZIP_ER_CRC            7  /* N CRC error */
-#define ZIP_ER_ZIPCLOSED      8  /* N Containing zip archive was closed */
-#define ZIP_ER_NOENT          9  /* N No such file */
-#define ZIP_ER_EXISTS        10  /* N File already exists */
-#define ZIP_ER_OPEN          11  /* S Can't open file */
-#define ZIP_ER_TMPOPEN       12  /* S Failure to create temporary file */
-#define ZIP_ER_ZLIB          13  /* Z Zlib error */
-#define ZIP_ER_MEMORY        14  /* N Malloc failure */
-#define ZIP_ER_CHANGED       15  /* N Entry has been changed */
-#define ZIP_ER_COMPNOTSUPP   16  /* N Compression method not supported */
-#define ZIP_ER_EOF           17  /* N Premature EOF */
-#define ZIP_ER_INVAL         18  /* N Invalid argument */
-#define ZIP_ER_NOZIP         19  /* N Not a zip archive */
-#define ZIP_ER_INTERNAL      20  /* N Internal error */
-#define ZIP_ER_INCONS        21  /* N Zip archive inconsistent */
-#define ZIP_ER_REMOVE        22  /* S Can't remove file */
-#define ZIP_ER_DELETED       23  /* N Entry has been deleted */
-
-
-/* type of system error value */
-
-#define ZIP_ET_NONE              0  /* sys_err unused */
-#define ZIP_ET_SYS              1  /* sys_err is errno */
-#define ZIP_ET_ZLIB              2  /* sys_err is zlib error code */
-
-/* compression methods */
-
-#define ZIP_CM_DEFAULT              -1  /* better of deflate or store */
-#define ZIP_CM_STORE               0  /* stored (uncompressed) */
-#define ZIP_CM_SHRINK               1  /* shrunk */
-#define ZIP_CM_REDUCE_1               2  /* reduced with factor 1 */
-#define ZIP_CM_REDUCE_2               3  /* reduced with factor 2 */
-#define ZIP_CM_REDUCE_3               4  /* reduced with factor 3 */
-#define ZIP_CM_REDUCE_4               5  /* reduced with factor 4 */
-#define ZIP_CM_IMPLODE               6  /* imploded */
-/* 7 - Reserved for Tokenizing compression algorithm */
-#define ZIP_CM_DEFLATE               8  /* deflated */
-#define ZIP_CM_DEFLATE64       9  /* deflate64 */
-#define ZIP_CM_PKWARE_IMPLODE 10  /* PKWARE imploding */
-/* 11 - Reserved by PKWARE */
-#define ZIP_CM_BZIP2          12  /* compressed using BZIP2 algorithm */
-/* 13 - Reserved by PKWARE */
-#define ZIP_CM_LZMA              14  /* LZMA (EFS) */
-/* 15-17 - Reserved by PKWARE */
-#define ZIP_CM_TERSE              18  /* compressed using IBM TERSE (new) */
-#define ZIP_CM_LZ77           19  /* IBM LZ77 z Architecture (PFS) */
-#define ZIP_CM_WAVPACK              97  /* WavPack compressed data */
-#define ZIP_CM_PPMD              98  /* PPMd version I, Rev 1 */
-
-/* encryption methods */
-
-#define ZIP_EM_NONE               0  /* not encrypted */
-#define ZIP_EM_TRAD_PKWARE     1  /* traditional PKWARE encryption */
-#if 0 /* Strong Encryption Header not parsed yet */
-#define ZIP_EM_DES        0x6601  /* strong encryption: DES */
-#define ZIP_EM_RC2_OLD    0x6602  /* strong encryption: RC2, version < 5.2 */
-#define ZIP_EM_3DES_168   0x6603
-#define ZIP_EM_3DES_112   0x6609
-#define ZIP_EM_AES_128    0x660e
-#define ZIP_EM_AES_192    0x660f
-#define ZIP_EM_AES_256    0x6610
-#define ZIP_EM_RC2        0x6702  /* strong encryption: RC2, version >= 5.2 */
-#define ZIP_EM_RC4        0x6801
-#endif
-#define ZIP_EM_UNKNOWN    0xffff  /* unknown algorithm */
-
-typedef long myoff_t; /* XXX: 64 bit support */
-
-enum zip_source_cmd {
-    ZIP_SOURCE_OPEN,        /* prepare for reading */
-    ZIP_SOURCE_READ,         /* read data */
-    ZIP_SOURCE_CLOSE,        /* reading is done */
-    ZIP_SOURCE_STAT,        /* get meta information */
-    ZIP_SOURCE_ERROR,        /* get error information */
-    ZIP_SOURCE_FREE        /* cleanup and free resources */
-};
-
-typedef ssize_t (*zip_source_callback)(void *state, void *data,
-                                       size_t len, enum zip_source_cmd cmd);
-
-struct zip_stat {
-    const char *name;                        /* name of the file */
-    int index;                                /* index within archive */
-    unsigned int crc;                        /* crc of file data */
-    time_t mtime;                        /* modification time */
-    myoff_t size;                                /* size of file (uncompressed) */
-    myoff_t comp_size;                        /* size of file (compressed) */
-    unsigned short comp_method;                /* compression method used */
-    unsigned short encryption_method;        /* encryption method used */
-};
-
-struct zip;
-struct zip_file;
-struct zip_source;
-
-
-ZIP_EXTERN int zip_add(struct zip *, const char *, struct zip_source *);
-ZIP_EXTERN int zip_add_dir(struct zip *, const char *);
-ZIP_EXTERN int zip_close(struct zip *);
-ZIP_EXTERN int zip_delete(struct zip *, int);
-ZIP_EXTERN void zip_error_clear(struct zip *);
-ZIP_EXTERN void zip_error_get(struct zip *, int *, int *);
-ZIP_EXTERN int zip_error_get_sys_type(int);
-ZIP_EXTERN int zip_error_to_str(char *, size_t, int, int);
-ZIP_EXTERN int zip_fclose(struct zip_file *);
-ZIP_EXTERN void zip_file_error_clear(struct zip_file *);
-ZIP_EXTERN void zip_file_error_get(struct zip_file *, int *, int *);
-ZIP_EXTERN const char *zip_file_strerror(struct zip_file *);
-ZIP_EXTERN struct zip_file *zip_fopen(struct zip *, const char *, int);
-ZIP_EXTERN struct zip_file *zip_fopen_index(struct zip *, int, int);
-ZIP_EXTERN ssize_t zip_fread(struct zip_file *, void *, size_t);
-ZIP_EXTERN const char *zip_get_archive_comment(struct zip *, int *, int);
-ZIP_EXTERN int zip_get_archive_flag(struct zip *, int, int);
-ZIP_EXTERN const char *zip_get_file_comment(struct zip *, int, int *, int);
-ZIP_EXTERN const char *zip_get_name(struct zip *, int, int);
-ZIP_EXTERN int zip_get_num_files(struct zip *);
-ZIP_EXTERN int zip_name_locate(struct zip *, const char *, int);
-ZIP_EXTERN struct zip *zip_open(const char *, int, int *);
-ZIP_EXTERN int zip_rename(struct zip *, int, const char *);
-ZIP_EXTERN int zip_replace(struct zip *, int, struct zip_source *);
-ZIP_EXTERN int zip_set_archive_comment(struct zip *, const char *, int);
-ZIP_EXTERN int zip_set_archive_flag(struct zip *, int, int);
-ZIP_EXTERN int zip_set_file_comment(struct zip *, int, const char *, int);
-ZIP_EXTERN struct zip_source *zip_source_buffer(struct zip *, const void *,
-                                                myoff_t, int);
-ZIP_EXTERN struct zip_source *zip_source_file(struct zip *, const char *,
-                                              myoff_t, myoff_t);
-ZIP_EXTERN struct zip_source *zip_source_filep(struct zip *, FILE *,
-                                               myoff_t, myoff_t);
-ZIP_EXTERN void zip_source_free(struct zip_source *);
-ZIP_EXTERN struct zip_source *zip_source_function(struct zip *,
-                                                  zip_source_callback, void *);
-ZIP_EXTERN struct zip_source *zip_source_zip(struct zip *, struct zip *,
-                                             int, int, myoff_t, myoff_t);
-ZIP_EXTERN int zip_stat(struct zip *, const char *, int, struct zip_stat *);
-ZIP_EXTERN int zip_stat_index(struct zip *, int, int, struct zip_stat *);
-ZIP_EXTERN void zip_stat_init(struct zip_stat *);
-ZIP_EXTERN const char *zip_strerror(struct zip *);
-ZIP_EXTERN int zip_unchange(struct zip *, int);
-ZIP_EXTERN int zip_unchange_all(struct zip *);
-ZIP_EXTERN int zip_unchange_archive(struct zip *);
-
-#ifdef __cplusplus
-}
-#endif
-
-
-/* config.h.  Generated from config.h.in by configure.  */
-/* config.h.in.  Generated from configure.ac by autoheader.  */
-
-/* Define to 1 if you have the declaration of `tzname', and to 0 if you don't.
-   */
-/* #undef HAVE_DECL_TZNAME */
-
-#define HAVE_CONFIG_H 1
-
-/* Define to 1 if you have the <dlfcn.h> header file. */
-#define HAVE_DLFCN_H 1
-
-/* Define to 1 if you have the `fseeko' function. */
-#define HAVE_FSEEKO 1
-
-/* Define to 1 if you have the `ftello' function. */
-#define HAVE_FTELLO 1
-
-/* Define to 1 if you have the <inttypes.h> header file. */
-#define HAVE_INTTYPES_H 1
-
-/* Define to 1 if you have the `z' library (-lz). */
-#define HAVE_LIBZ 1
-
-/* Define to 1 if you have the <memory.h> header file. */
-#define HAVE_MEMORY_H 1
-
-/* Define to 1 if you have the `mkstemp' function. */
-#define HAVE_MKSTEMP 1
-
-/* Define to 1 if you have the `MoveFileExA' function. */
-/* #undef HAVE_MOVEFILEEXA */
-
-/* Define to 1 if you have the <stdint.h> header file. */
-#define HAVE_STDINT_H 1
-
-/* Define to 1 if you have the <stdlib.h> header file. */
-#define HAVE_STDLIB_H 1
-
-/* Define to 1 if you have the <strings.h> header file. */
-#define HAVE_STRINGS_H 1
-
-/* Define to 1 if you have the <string.h> header file. */
-#define HAVE_STRING_H 1
-
-/* Define to 1 if `tm_zone' is member of `struct tm'. */
-#ifdef WIN32
-#undef HAVE_STRUCT_TM_TM_ZONE
-#else
-#define HAVE_STRUCT_TM_TM_ZONE 1
-#endif
-
-/* Define to 1 if you have the <sys/stat.h> header file. */
-#define HAVE_SYS_STAT_H 1
-
-/* Define to 1 if you have the <sys/types.h> header file. */
-#define HAVE_SYS_TYPES_H 1
-
-/* Define to 1 if your `struct tm' has `tm_zone'. Deprecated, use
-   `HAVE_STRUCT_TM_TM_ZONE' instead. */
-#define HAVE_TM_ZONE 1
-
-/* Define to 1 if you don't have `tm_zone' but do have the external array
-   `tzname'. */
-/* #undef HAVE_TZNAME */
-
-/* Define to 1 if you have the <unistd.h> header file. */
-#define HAVE_UNISTD_H 1
-
-/* Define to 1 if your C compiler doesn't accept -c and -o together. */
-/* #undef NO_MINUS_C_MINUS_O */
-
-/* Name of package */
-#define PACKAGE "libzip"
-
-/* Define to the address where bug reports for this package should be sent. */
-#define PACKAGE_BUGREPORT "libzip@nih.at"
-
-/* Define to the full name of this package. */
-#define PACKAGE_NAME "libzip"
-
-/* Define to the full name and version of this package. */
-#define PACKAGE_STRING "libzip 0.9"
-
-/* Define to the one symbol short name of this package. */
-#define PACKAGE_TARNAME "libzip"
-
-/* Define to the version of this package. */
-#define PACKAGE_VERSION "0.9"
-
-/* Define to 1 if you have the ANSI C header files. */
-#define STDC_HEADERS 1
-
-/* Define to 1 if your <sys/time.h> declares `struct tm'. */
-/* #undef TM_IN_SYS_TIME */
-
-/* Version number of package */
-#define VERSION "0.9"
-
-
-#ifndef HAVE_MKSTEMP
-int _zip_mkstemp(char *);
-#define mkstemp _zip_mkstemp
-#endif
-
-#ifdef HAVE_MOVEFILEEXA
-#include <windows.h>
-#define _zip_rename(s, t)                                                \
-        (!MoveFileExA((s), (t),                                                \
-                     MOVEFILE_COPY_ALLOWED|MOVEFILE_REPLACE_EXISTING))
-#else
-#define _zip_rename        rename
-#endif
-
-#ifndef HAVE_FSEEKO
-#define fseeko(s, o, w)        (fseek((s), (long int)(o), (w)))
-#endif
-#ifndef HAVE_FTELLO
-#define ftello(s)        ((long)ftell((s)))
-#endif
-
-
-#define CENTRAL_MAGIC "PK\1\2"
-#define LOCAL_MAGIC   "PK\3\4"
-#define EOCD_MAGIC    "PK\5\6"
-#define DATADES_MAGIC "PK\7\8"
-#define TORRENT_SIG        "TORRENTZIPPED-"
-#define TORRENT_SIG_LEN        14
-#define TORRENT_CRC_LEN 8
-#define TORRENT_MEM_LEVEL        8
-#define CDENTRYSIZE         46u
-#define LENTRYSIZE          30
-#define MAXCOMLEN        65536
-#define EOCDLEN             22
-#define CDBUFSIZE       (MAXCOMLEN+EOCDLEN)
-#define BUFSIZE                8192
-
-
-/* state of change of a file in zip archive */
-
-enum zip_state { ZIP_ST_UNCHANGED, ZIP_ST_DELETED, ZIP_ST_REPLACED,
-                 ZIP_ST_ADDED, ZIP_ST_RENAMED };
-
-/* constants for struct zip_file's member flags */
-
-#define ZIP_ZF_EOF        1 /* EOF reached */
-#define ZIP_ZF_DECOMP        2 /* decompress data */
-#define ZIP_ZF_CRC        4 /* compute and compare CRC */
-
-/* directory entry: general purpose bit flags */
-
-#define ZIP_GPBF_ENCRYPTED                0x0001        /* is encrypted */
-#define ZIP_GPBF_DATA_DESCRIPTOR        0x0008        /* crc/size after file data */
-#define ZIP_GPBF_STRONG_ENCRYPTION        0x0040  /* uses strong encryption */
-
-/* error information */
-
-struct zip_error {
-    int zip_err;        /* libzip error code (ZIP_ER_*) */
-    int sys_err;        /* copy of errno (E*) or zlib error code */
-    char *str;                /* string representation or NULL */
-};
-
-/* zip archive, part of API */
-
-struct zip {
-    char *zn;                        /* file name */
-    FILE *zp;                        /* file */
-    struct zip_error error;        /* error information */
-
-    unsigned int flags;                /* archive global flags */
-    unsigned int ch_flags;        /* changed archive global flags */
-
-    struct zip_cdir *cdir;        /* central directory */
-    char *ch_comment;                /* changed archive comment */
-    int ch_comment_len;                /* length of changed zip archive
-                                 * comment, -1 if unchanged */
-    int nentry;                        /* number of entries */
-    int nentry_alloc;                /* number of entries allocated */
-    struct zip_entry *entry;        /* entries */
-    int nfile;                        /* number of opened files within archive */
-    int nfile_alloc;                /* number of files allocated */
-    struct zip_file **file;        /* opened files within archive */
-};
-
-/* file in zip archive, part of API */
-
-struct zip_file {
-    struct zip *za;                /* zip archive containing this file */
-    struct zip_error error;        /* error information */
-    int flags;                        /* -1: eof, >0: error */
-
-    int method;                        /* compression method */
-    myoff_t fpos;                        /* position within zip file (fread/fwrite) */
-    unsigned long bytes_left;        /* number of bytes left to read */
-    unsigned long cbytes_left;  /* number of bytes of compressed data left */
-
-    unsigned long crc;                /* CRC so far */
-    unsigned long crc_orig;        /* CRC recorded in archive */
-
-    char *buffer;
-    z_stream *zstr;
-};
-
-/* zip archive directory entry (central or local) */
-
-struct zip_dirent {
-    unsigned short version_madeby;        /* (c)  version of creator */
-    unsigned short version_needed;        /* (cl) version needed to extract */
-    unsigned short bitflags;                /* (cl) general purpose bit flag */
-    unsigned short comp_method;                /* (cl) compression method used */
-    time_t last_mod;                        /* (cl) time of last modification */
-    unsigned int crc;                        /* (cl) CRC-32 of uncompressed data */
-    unsigned int comp_size;                /* (cl) size of commpressed data */
-    unsigned int uncomp_size;                /* (cl) size of uncommpressed data */
-    char *filename;                        /* (cl) file name (NUL-terminated) */
-    unsigned short filename_len;        /* (cl) length of filename (w/o NUL) */
-    char *extrafield;                        /* (cl) extra field */
-    unsigned short extrafield_len;        /* (cl) length of extra field */
-    char *comment;                        /* (c)  file comment */
-    unsigned short comment_len;                /* (c)  length of file comment */
-    unsigned short disk_number;                /* (c)  disk number start */
-    unsigned short int_attrib;                /* (c)  internal file attributes */
-    unsigned int ext_attrib;                /* (c)  external file attributes */
-    unsigned int offset;                /* (c)  offset of local header  */
-};
-
-/* zip archive central directory */
-
-struct zip_cdir {
-    struct zip_dirent *entry;        /* directory entries */
-    int nentry;                        /* number of entries */
-
-    unsigned int size;                /* size of central direcotry */
-    unsigned int offset;        /* offset of central directory in file */
-    char *comment;                /* zip archive comment */
-    unsigned short comment_len;        /* length of zip archive comment */
-};
-
-
-
-struct zip_source {
-    zip_source_callback f;
-    void *ud;
-};
-
-/* entry in zip archive directory */
-
-struct zip_entry {
-    enum zip_state state;
-    struct zip_source *source;
-    char *ch_filename;
-    char *ch_comment;
-    int ch_comment_len;
-};
-
-
-
-extern const char * const _zip_err_str[];
-extern const int _zip_nerr_str;
-extern const int _zip_err_type[];
-
-
-
-#define ZIP_ENTRY_DATA_CHANGED(x)        \
-                        ((x)->state == ZIP_ST_REPLACED  \
-                         || (x)->state == ZIP_ST_ADDED)
-
-
-
-int _zip_cdir_compute_crc(struct zip *, uLong *);
-void _zip_cdir_free(struct zip_cdir *);
-struct zip_cdir *_zip_cdir_new(int, struct zip_error *);
-int _zip_cdir_write(struct zip_cdir *, FILE *, struct zip_error *);
-
-void _zip_dirent_finalize(struct zip_dirent *);
-void _zip_dirent_init(struct zip_dirent *);
-int _zip_dirent_read(struct zip_dirent *, FILE *,
-                     unsigned char **, unsigned int, int, struct zip_error *);
-void _zip_dirent_torrent_normalize(struct zip_dirent *);
-int _zip_dirent_write(struct zip_dirent *, FILE *, int, struct zip_error *);
-
-void _zip_entry_free(struct zip_entry *);
-void _zip_entry_init(struct zip *, int);
-struct zip_entry *_zip_entry_new(struct zip *);
-
-void _zip_error_clear(struct zip_error *);
-void _zip_error_copy(struct zip_error *, struct zip_error *);
-void _zip_error_fini(struct zip_error *);
-void _zip_error_get(struct zip_error *, int *, int *);
-void _zip_error_init(struct zip_error *);
-void _zip_error_set(struct zip_error *, int, int);
-const char *_zip_error_strerror(struct zip_error *);
-
-int _zip_file_fillbuf(void *, size_t, struct zip_file *);
-unsigned int _zip_file_get_offset(struct zip *, int);
-
-int _zip_filerange_crc(FILE *, myoff_t, myoff_t, uLong *, struct zip_error *);
-
-struct zip_source *_zip_source_file_or_p(struct zip *, const char *, FILE *,
-                                         myoff_t, myoff_t);
-
-void _zip_free(struct zip *);
-const char *_zip_get_name(struct zip *, int, int, struct zip_error *);
-int _zip_local_header_read(struct zip *, int);
-void *_zip_memdup(const void *, size_t, struct zip_error *);
-int _zip_name_locate(struct zip *, const char *, int, struct zip_error *);
-struct zip *_zip_new(struct zip_error *);
-unsigned short _zip_read2(unsigned char **);
-unsigned int _zip_read4(unsigned char **);
-int _zip_replace(struct zip *, int, const char *, struct zip_source *);
-int _zip_set_name(struct zip *, int, const char *);
-int _zip_unchange(struct zip *, int, int);
-void _zip_unchange_data(struct zip_entry *);
-
-
-#include <errno.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-const char *
-_zip_error_strerror(struct zip_error *err)
-{
-    const char *zs, *ss;
-    char buf[128], *s;
-
-    _zip_error_fini(err);
-
-    if (err->zip_err < 0 || err->zip_err >= _zip_nerr_str) {
-        sprintf(buf, "Unknown error %d", err->zip_err);
-        zs = NULL;
-        ss = buf;
-    }
-    else {
-        zs = _zip_err_str[err->zip_err];
-
-        switch (_zip_err_type[err->zip_err]) {
-        case ZIP_ET_SYS:
-            ss = strerror(err->sys_err);
-            break;
-
-        case ZIP_ET_ZLIB:
-            ss = zError(err->sys_err);
-            break;
-
-        default:
-            ss = NULL;
-        }
-    }
-
-    if (ss == NULL)
-        return zs;
-    else {
-        if ((s=(char *)malloc(strlen(ss)
-                              + (zs ? strlen(zs)+2 : 0) + 1)) == NULL)
-            return _zip_err_str[ZIP_ER_MEMORY];
-
-        sprintf(s, "%s%s%s",
-                (zs ? zs : ""),
-                (zs ? ": " : ""),
-                ss);
-        err->str = s;
-
-        return s;
-    }
-}
-
-#include <stdlib.h>
-
-
-
-void
-_zip_error_clear(struct zip_error *err)
-{
-    err->zip_err = ZIP_ER_OK;
-    err->sys_err = 0;
-}
-
-
-
-void
-_zip_error_copy(struct zip_error *dst, struct zip_error *src)
-{
-    dst->zip_err = src->zip_err;
-    dst->sys_err = src->sys_err;
-}
-
-
-
-void
-_zip_error_fini(struct zip_error *err)
-{
-    free(err->str);
-    err->str = NULL;
-}
-
-
-
-void
-_zip_error_get(struct zip_error *err, int *zep, int *sep)
-{
-    if (zep)
-        *zep = err->zip_err;
-    if (sep) {
-        if (zip_error_get_sys_type(err->zip_err) != ZIP_ET_NONE)
-            *sep = err->sys_err;
-        else
-            *sep = 0;
-    }
-}
-
-
-
-void
-_zip_error_init(struct zip_error *err)
-{
-    err->zip_err = ZIP_ER_OK;
-    err->sys_err = 0;
-    err->str = NULL;
-}
-
-
-
-void
-_zip_error_set(struct zip_error *err, int ze, int se)
-{
-    if (err) {
-        err->zip_err = ze;
-        err->sys_err = se;
-    }
-}
-
-
-#include <sys/types.h>
-#include <sys/stat.h>
-
-#include <assert.h>
-#include <ctype.h>
-#include <errno.h>
-#include <fcntl.h>
-#include <stdio.h>
-#include <stdlib.h>
-
-#ifndef O_BINARY
-#define O_BINARY 0
-#endif
-
-
-
-int
-_zip_mkstemp(char *path)
-{
-        int fd;
-        char *start, *trv;
-        struct stat sbuf;
-        pid_t pid;
-
-        /* To guarantee multiple calls generate unique names even if
-           the file is not created. 676 different possibilities with 7
-           or more X's, 26 with 6 or less. */
-        static char xtra[2] = "aa";
-        int xcnt = 0;
-
-        pid = getpid();
-
-        /* Move to end of path and count trailing X's. */
-        for (trv = path; *trv; ++trv)
-                if (*trv == 'X')
-                        xcnt++;
-                else
-                        xcnt = 0;
-
-        /* Use at least one from xtra.  Use 2 if more than 6 X's. */
-        if (*(trv - 1) == 'X')
-                *--trv = xtra[0];
-        if (xcnt > 6 && *(trv - 1) == 'X')
-                *--trv = xtra[1];
-
-        /* Set remaining X's to pid digits with 0's to the left. */
-        while (*--trv == 'X') {
-                *trv = (pid % 10) + '0';
-                pid /= 10;
-        }
-
-        /* update xtra for next call. */
-        if (xtra[0] != 'z')
-                xtra[0]++;
-        else {
-                xtra[0] = 'a';
-                if (xtra[1] != 'z')
-                        xtra[1]++;
-                else
-                        xtra[1] = 'a';
-        }
-
-        /*
-         * check the target directory; if you have six X's and it
-         * doesn't exist this runs for a *very* long time.
-         */
-        for (start = trv + 1;; --trv) {
-                if (trv <= path)
-                        break;
-                if (*trv == '/') {
-                        *trv = '\0';
-                        if (stat(path, &sbuf))
-                                return (0);
-                        if (!S_ISDIR(sbuf.st_mode)) {
-                                errno = ENOTDIR;
-                                return (0);
-                        }
-                        *trv = '/';
-                        break;
-                }
-        }
-
-        for (;;) {
-                if ((fd=open(path, O_CREAT|O_EXCL|O_RDWR|O_BINARY, 0600)) >= 0)
-                        return (fd);
-                if (errno != EEXIST)
-                        return (0);
-
-                /* tricky little algorithm for backward compatibility */
-                for (trv = start;;) {
-                        if (!*trv)
-                                return (0);
-                        if (*trv == 'z')
-                                *trv++ = 'a';
-                        else {
-                                if (isdigit((unsigned char)*trv))
-                                        *trv = 'a';
-                                else
-                                        ++*trv;
-                                break;
-                        }
-                }
-        }
-        /*NOTREACHED*/
-}
-
-
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <errno.h>
-#include <sys/types.h>
-#include <sys/stat.h>
-
-static time_t _zip_d2u_time(int, int);
-static char *_zip_readfpstr(FILE *, unsigned int, int, struct zip_error *);
-static char *_zip_readstr(unsigned char **, int, int, struct zip_error *);
-static void _zip_u2d_time(time_t, unsigned short *, unsigned short *);
-static void _zip_write2(unsigned short, FILE *);
-static void _zip_write4(unsigned int, FILE *);
-
-
-
-void
-_zip_cdir_free(struct zip_cdir *cd)
-{
-    int i;
-
-    if (!cd)
-        return;
-
-    for (i=0; i<cd->nentry; i++)
-        _zip_dirent_finalize(cd->entry+i);
-    free(cd->comment);
-    free(cd->entry);
-    free(cd);
-}
-
-
-
-struct zip_cdir *
-_zip_cdir_new(int nentry, struct zip_error *error)
-{
-    struct zip_cdir *cd;
-
-    if ((cd=(struct zip_cdir *)malloc(sizeof(*cd))) == NULL) {
-        _zip_error_set(error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    if ((cd->entry=(struct zip_dirent *)malloc(sizeof(*(cd->entry))*nentry))
-        == NULL) {
-        _zip_error_set(error, ZIP_ER_MEMORY, 0);
-        free(cd);
-        return NULL;
-    }
-
-    /* entries must be initialized by caller */
-
-    cd->nentry = nentry;
-    cd->size = cd->offset = 0;
-    cd->comment = NULL;
-    cd->comment_len = 0;
-
-    return cd;
-}
-
-
-
-int
-_zip_cdir_write(struct zip_cdir *cd, FILE *fp, struct zip_error *error)
-{
-    int i;
-
-    cd->offset = ftello(fp);
-
-    for (i=0; i<cd->nentry; i++) {
-        if (_zip_dirent_write(cd->entry+i, fp, 0, error) != 0)
-            return -1;
-    }
-
-    cd->size = ftello(fp) - cd->offset;
-
-    /* clearerr(fp); */
-    fwrite(EOCD_MAGIC, 1, 4, fp);
-    _zip_write4(0, fp);
-    _zip_write2((unsigned short)cd->nentry, fp);
-    _zip_write2((unsigned short)cd->nentry, fp);
-    _zip_write4(cd->size, fp);
-    _zip_write4(cd->offset, fp);
-    _zip_write2(cd->comment_len, fp);
-    fwrite(cd->comment, 1, cd->comment_len, fp);
-
-    if (ferror(fp)) {
-        _zip_error_set(error, ZIP_ER_WRITE, errno);
-        return -1;
-    }
-
-    return 0;
-}
-
-
-
-void
-_zip_dirent_finalize(struct zip_dirent *zde)
-{
-    free(zde->filename);
-    zde->filename = NULL;
-    free(zde->extrafield);
-    zde->extrafield = NULL;
-    free(zde->comment);
-    zde->comment = NULL;
-}
-
-
-
-void
-_zip_dirent_init(struct zip_dirent *de)
-{
-    de->version_madeby = 0;
-    de->version_needed = 20; /* 2.0 */
-    de->bitflags = 0;
-    de->comp_method = 0;
-    de->last_mod = 0;
-    de->crc = 0;
-    de->comp_size = 0;
-    de->uncomp_size = 0;
-    de->filename = NULL;
-    de->filename_len = 0;
-    de->extrafield = NULL;
-    de->extrafield_len = 0;
-    de->comment = NULL;
-    de->comment_len = 0;
-    de->disk_number = 0;
-    de->int_attrib = 0;
-    de->ext_attrib = 0;
-    de->offset = 0;
-}
-
-
-
-/* _zip_dirent_read(zde, fp, bufp, left, localp, error):
-   Fills the zip directory entry zde.
-
-   If bufp is non-NULL, data is taken from there and bufp is advanced
-   by the amount of data used; no more than left bytes are used.
-   Otherwise data is read from fp as needed.
-
-   If localp != 0, it reads a local header instead of a central
-   directory entry.
-
-   Returns 0 if successful. On error, error is filled in and -1 is
-   returned.
-*/
-
-int
-_zip_dirent_read(struct zip_dirent *zde, FILE *fp,
-                 unsigned char **bufp, unsigned int left, int localp,
-                 struct zip_error *error)
-{
-    unsigned char buf[CDENTRYSIZE];
-    unsigned char *cur;
-    unsigned short dostime, dosdate;
-    unsigned int size;
-
-    if (localp)
-        size = LENTRYSIZE;
-    else
-        size = CDENTRYSIZE;
-
-    if (bufp) {
-        /* use data from buffer */
-        cur = *bufp;
-        if (left < size) {
-            _zip_error_set(error, ZIP_ER_NOZIP, 0);
-            return -1;
-        }
-    }
-    else {
-        /* read entry from disk */
-        if ((fread(buf, 1, size, fp)<size)) {
-            _zip_error_set(error, ZIP_ER_READ, errno);
-            return -1;
-        }
-        left = size;
-        cur = buf;
-    }
-
-    if (memcmp(cur, (localp ? LOCAL_MAGIC : CENTRAL_MAGIC), 4) != 0) {
-        _zip_error_set(error, ZIP_ER_NOZIP, 0);
-        return -1;
-    }
-    cur += 4;
-
-
-    /* convert buffercontents to zip_dirent */
-
-    if (!localp)
-        zde->version_madeby = _zip_read2(&cur);
-    else
-        zde->version_madeby = 0;
-    zde->version_needed = _zip_read2(&cur);
-    zde->bitflags = _zip_read2(&cur);
-    zde->comp_method = _zip_read2(&cur);
-
-    /* convert to time_t */
-    dostime = _zip_read2(&cur);
-    dosdate = _zip_read2(&cur);
-    zde->last_mod = _zip_d2u_time(dostime, dosdate);
-
-    zde->crc = _zip_read4(&cur);
-    zde->comp_size = _zip_read4(&cur);
-    zde->uncomp_size = _zip_read4(&cur);
-
-    zde->filename_len = _zip_read2(&cur);
-    zde->extrafield_len = _zip_read2(&cur);
-
-    if (localp) {
-        zde->comment_len = 0;
-        zde->disk_number = 0;
-        zde->int_attrib = 0;
-        zde->ext_attrib = 0;
-        zde->offset = 0;
-    } else {
-        zde->comment_len = _zip_read2(&cur);
-        zde->disk_number = _zip_read2(&cur);
-        zde->int_attrib = _zip_read2(&cur);
-        zde->ext_attrib = _zip_read4(&cur);
-        zde->offset = _zip_read4(&cur);
-    }
-
-    zde->filename = NULL;
-    zde->extrafield = NULL;
-    zde->comment = NULL;
-
-    if (bufp) {
-        if (left < CDENTRYSIZE + (zde->filename_len+zde->extrafield_len
-                                  +zde->comment_len)) {
-            _zip_error_set(error, ZIP_ER_NOZIP, 0);
-            return -1;
-        }
-
-        if (zde->filename_len) {
-            zde->filename = _zip_readstr(&cur, zde->filename_len, 1, error);
-            if (!zde->filename)
-                    return -1;
-        }
-
-        if (zde->extrafield_len) {
-            zde->extrafield = _zip_readstr(&cur, zde->extrafield_len, 0,
-                                           error);
-            if (!zde->extrafield)
-                return -1;
-        }
-
-        if (zde->comment_len) {
-            zde->comment = _zip_readstr(&cur, zde->comment_len, 0, error);
-            if (!zde->comment)
-                return -1;
-        }
-    }
-    else {
-        if (zde->filename_len) {
-            zde->filename = _zip_readfpstr(fp, zde->filename_len, 1, error);
-            if (!zde->filename)
-                    return -1;
-        }
-
-        if (zde->extrafield_len) {
-            zde->extrafield = _zip_readfpstr(fp, zde->extrafield_len, 0,
-                                             error);
-            if (!zde->extrafield)
-                return -1;
-        }
-
-        if (zde->comment_len) {
-            zde->comment = _zip_readfpstr(fp, zde->comment_len, 0, error);
-            if (!zde->comment)
-                return -1;
-        }
-    }
-
-    if (bufp)
-      *bufp = cur;
-
-    return 0;
-}
-
-
-
-/* _zip_dirent_torrent_normalize(de);
-   Set values suitable for torrentzip.
-*/
-
-void
-_zip_dirent_torrent_normalize(struct zip_dirent *de)
-{
-    static struct tm torrenttime;
-    static time_t last_mod = 0;
-
-    if (last_mod == 0) {
-#ifdef HAVE_STRUCT_TM_TM_ZONE
-        time_t now;
-        struct tm *l;
-#endif
-
-        torrenttime.tm_sec = 0;
-        torrenttime.tm_min = 32;
-        torrenttime.tm_hour = 23;
-        torrenttime.tm_mday = 24;
-        torrenttime.tm_mon = 11;
-        torrenttime.tm_year = 96;
-        torrenttime.tm_wday = 0;
-        torrenttime.tm_yday = 0;
-        torrenttime.tm_isdst = 0;
-
-#ifdef HAVE_STRUCT_TM_TM_ZONE
-        time(&now);
-        l = localtime(&now);
-        torrenttime.tm_gmtoff = l->tm_gmtoff;
-        torrenttime.tm_zone = l->tm_zone;
-#endif
-
-        last_mod = mktime(&torrenttime);
-    }
-
-    de->version_madeby = 0;
-    de->version_needed = 20; /* 2.0 */
-    de->bitflags = 2; /* maximum compression */
-    de->comp_method = ZIP_CM_DEFLATE;
-    de->last_mod = last_mod;
-
-    de->disk_number = 0;
-    de->int_attrib = 0;
-    de->ext_attrib = 0;
-    de->offset = 0;
-
-    free(de->extrafield);
-    de->extrafield = NULL;
-    de->extrafield_len = 0;
-    free(de->comment);
-    de->comment = NULL;
-    de->comment_len = 0;
-}
-
-
-
-/* _zip_dirent_write(zde, fp, localp, error):
-   Writes zip directory entry zde to file fp.
-
-   If localp != 0, it writes a local header instead of a central
-   directory entry.
-
-   Returns 0 if successful. On error, error is filled in and -1 is
-   returned.
-*/
-
-int
-_zip_dirent_write(struct zip_dirent *zde, FILE *fp, int localp,
-                  struct zip_error *error)
-{
-    unsigned short dostime, dosdate;
-
-    fwrite(localp ? LOCAL_MAGIC : CENTRAL_MAGIC, 1, 4, fp);
-
-    if (!localp)
-        _zip_write2(zde->version_madeby, fp);
-    _zip_write2(zde->version_needed, fp);
-    _zip_write2(zde->bitflags, fp);
-    _zip_write2(zde->comp_method, fp);
-
-    _zip_u2d_time(zde->last_mod, &dostime, &dosdate);
-    _zip_write2(dostime, fp);
-    _zip_write2(dosdate, fp);
-
-    _zip_write4(zde->crc, fp);
-    _zip_write4(zde->comp_size, fp);
-    _zip_write4(zde->uncomp_size, fp);
-
-    _zip_write2(zde->filename_len, fp);
-    _zip_write2(zde->extrafield_len, fp);
-
-    if (!localp) {
-        _zip_write2(zde->comment_len, fp);
-        _zip_write2(zde->disk_number, fp);
-        _zip_write2(zde->int_attrib, fp);
-        _zip_write4(zde->ext_attrib, fp);
-        _zip_write4(zde->offset, fp);
-    }
-
-    if (zde->filename_len)
-        fwrite(zde->filename, 1, zde->filename_len, fp);
-
-    if (zde->extrafield_len)
-        fwrite(zde->extrafield, 1, zde->extrafield_len, fp);
-
-    if (!localp) {
-        if (zde->comment_len)
-            fwrite(zde->comment, 1, zde->comment_len, fp);
-    }
-
-    if (ferror(fp)) {
-        _zip_error_set(error, ZIP_ER_WRITE, errno);
-        return -1;
-    }
-
-    return 0;
-}
-
-
-
-static time_t
-_zip_d2u_time(int dtime, int ddate)
-{
-    struct tm *tm;
-    time_t now;
-
-    now = time(NULL);
-    tm = localtime(&now);
-    /* let mktime decide if DST is in effect */
-    tm->tm_isdst = -1;
-
-    tm->tm_year = ((ddate>>9)&127) + 1980 - 1900;
-    tm->tm_mon = ((ddate>>5)&15) - 1;
-    tm->tm_mday = ddate&31;
-
-    tm->tm_hour = (dtime>>11)&31;
-    tm->tm_min = (dtime>>5)&63;
-    tm->tm_sec = (dtime<<1)&62;
-
-    return mktime(tm);
-}
-
-
-
-unsigned short
-_zip_read2(unsigned char **a)
-{
-    unsigned short ret;
-
-    ret = (*a)[0]+((*a)[1]<<8);
-    *a += 2;
-
-    return ret;
-}
-
-
-
-unsigned int
-_zip_read4(unsigned char **a)
-{
-    unsigned int ret;
-
-    ret = ((((((*a)[3]<<8)+(*a)[2])<<8)+(*a)[1])<<8)+(*a)[0];
-    *a += 4;
-
-    return ret;
-}
-
-
-
-static char *
-_zip_readfpstr(FILE *fp, unsigned int len, int nulp, struct zip_error *error)
-{
-    char *r, *o;
-
-    r = (char *)malloc(nulp ? len+1 : len);
-    if (!r) {
-        _zip_error_set(error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    if (fread(r, 1, len, fp)<len) {
-        free(r);
-        _zip_error_set(error, ZIP_ER_READ, errno);
-        return NULL;
-    }
-
-    if (nulp) {
-        /* replace any in-string NUL characters with spaces */
-        r[len] = 0;
-        for (o=r; o<r+len; o++)
-            if (*o == '\0')
-                *o = ' ';
-    }
-
-    return r;
-}
-
-
-
-static char *
-_zip_readstr(unsigned char **buf, int len, int nulp, struct zip_error *error)
-{
-    char *r, *o;
-
-    r = (char *)malloc(nulp ? len+1 : len);
-    if (!r) {
-        _zip_error_set(error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    memcpy(r, *buf, len);
-    *buf += len;
-
-    if (nulp) {
-        /* replace any in-string NUL characters with spaces */
-        r[len] = 0;
-        for (o=r; o<r+len; o++)
-            if (*o == '\0')
-                *o = ' ';
-    }
-
-    return r;
-}
-
-
-
-static void
-_zip_write2(unsigned short i, FILE *fp)
-{
-    putc(i&0xff, fp);
-    putc((i>>8)&0xff, fp);
-
-    return;
-}
-
-
-
-static void
-_zip_write4(unsigned int i, FILE *fp)
-{
-    putc(i&0xff, fp);
-    putc((i>>8)&0xff, fp);
-    putc((i>>16)&0xff, fp);
-    putc((i>>24)&0xff, fp);
-
-    return;
-}
-
-
-
-static void
-_zip_u2d_time(time_t time, unsigned short *dtime, unsigned short *ddate)
-{
-    struct tm *tm;
-
-    tm = localtime(&time);
-    *ddate = ((tm->tm_year+1900-1980)<<9) + ((tm->tm_mon+1)<<5)
-        + tm->tm_mday;
-    *dtime = ((tm->tm_hour)<<11) + ((tm->tm_min)<<5)
-        + ((tm->tm_sec)>>1);
-
-    return;
-}
-
-
-
-ZIP_EXTERN int
-zip_delete(struct zip *za, int idx)
-{
-    if (idx < 0 || idx >= za->nentry) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    /* allow duplicate file names, because the file will
-     * be removed directly afterwards */
-    if (_zip_unchange(za, idx, 1) != 0)
-        return -1;
-
-    za->entry[idx].state = ZIP_ST_DELETED;
-
-    return 0;
-}
-
-
-
-ZIP_EXTERN void
-zip_error_clear(struct zip *za)
-{
-    _zip_error_clear(&za->error);
-}
-
-
-ZIP_EXTERN int
-zip_add(struct zip *za, const char *name, struct zip_source *source)
-{
-    if (name == NULL || source == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    return _zip_replace(za, -1, name, source);
-}
-
-
-ZIP_EXTERN int
-zip_error_get_sys_type(int ze)
-{
-    if (ze < 0 || ze >= _zip_nerr_str)
-        return 0;
-
-    return _zip_err_type[ze];
-}
-
-
-ZIP_EXTERN void
-zip_error_get(struct zip *za, int *zep, int *sep)
-{
-    _zip_error_get(&za->error, zep, sep);
-}
-
-
-const char * const _zip_err_str[] = {
-    "No error",
-    "Multi-disk zip archives not supported",
-    "Renaming temporary file failed",
-    "Closing zip archive failed",
-    "Seek error",
-    "Read error",
-    "Write error",
-    "CRC error",
-    "Containing zip archive was closed",
-    "No such file",
-    "File already exists",
-    "Can't open file",
-    "Failure to create temporary file",
-    "Zlib error",
-    "Malloc failure",
-    "Entry has been changed",
-    "Compression method not supported",
-    "Premature EOF",
-    "Invalid argument",
-    "Not a zip archive",
-    "Internal error",
-    "Zip archive inconsistent",
-    "Can't remove file",
-    "Entry has been deleted",
-};
-
-const int _zip_nerr_str = sizeof(_zip_err_str)/sizeof(_zip_err_str[0]);
-
-#define N ZIP_ET_NONE
-#define S ZIP_ET_SYS
-#define Z ZIP_ET_ZLIB
-
-const int _zip_err_type[] = {
-    N,
-    N,
-    S,
-    S,
-    S,
-    S,
-    S,
-    N,
-    N,
-    N,
-    N,
-    S,
-    S,
-    Z,
-    N,
-    N,
-    N,
-    N,
-    N,
-    N,
-    N,
-    N,
-    S,
-    N,
-};
-
-
-struct zip_entry *
-_zip_entry_new(struct zip *za)
-{
-    struct zip_entry *ze;
-    if (!za) {
-        ze = (struct zip_entry *)malloc(sizeof(struct zip_entry));
-        if (!ze) {
-            _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-            return NULL;
-        }
-    }
-    else {
-        if (za->nentry >= za->nentry_alloc-1) {
-            za->nentry_alloc += 16;
-            za->entry = (struct zip_entry *)realloc(za->entry,
-                                                    sizeof(struct zip_entry)
-                                                    * za->nentry_alloc);
-            if (!za->entry) {
-                _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-                return NULL;
-            }
-        }
-        ze = za->entry+za->nentry;
-    }
-
-    ze->state = ZIP_ST_UNCHANGED;
-
-    ze->ch_filename = NULL;
-    ze->ch_comment = NULL;
-    ze->ch_comment_len = -1;
-    ze->source = NULL;
-
-    if (za)
-        za->nentry++;
-
-    return ze;
-}
-
-
-void
-_zip_entry_free(struct zip_entry *ze)
-{
-    free(ze->ch_filename);
-    ze->ch_filename = NULL;
-    free(ze->ch_comment);
-    ze->ch_comment = NULL;
-    ze->ch_comment_len = -1;
-
-    _zip_unchange_data(ze);
-}
-
-
-static int add_data(struct zip *, struct zip_source *, struct zip_dirent *,
-                    FILE *);
-static int add_data_comp(zip_source_callback, void *, struct zip_stat *,
-                         FILE *, struct zip_error *);
-static int add_data_uncomp(struct zip *, zip_source_callback, void *,
-                           struct zip_stat *, FILE *);
-static void ch_set_error(struct zip_error *, zip_source_callback, void *);
-static int copy_data(FILE *, myoff_t, FILE *, struct zip_error *);
-static int write_cdir(struct zip *, struct zip_cdir *, FILE *);
-static int _zip_cdir_set_comment(struct zip_cdir *, struct zip *);
-static int _zip_changed(struct zip *, int *);
-static char *_zip_create_temp_output(struct zip *, FILE **);
-static int _zip_torrentzip_cmp(const void *, const void *);
-
-
-
-struct filelist {
-    int idx;
-    const char *name;
-};
-
-
-
-ZIP_EXTERN int
-zip_close(struct zip *za)
-{
-    int survivors;
-    int i, j, error;
-    char *temp;
-    FILE *out;
-    mode_t mask;
-    struct zip_cdir *cd;
-    struct zip_dirent de;
-    struct filelist *filelist;
-    int reopen_on_error;
-    int new_torrentzip;
-
-    reopen_on_error = 0;
-
-    if (za == NULL)
-        return -1;
-
-    if (!_zip_changed(za, &survivors)) {
-        _zip_free(za);
-        return 0;
-    }
-
-    /* don't create zip files with no entries */
-    if (survivors == 0) {
-        if (za->zn && za->zp) {
-            if (remove(za->zn) != 0) {
-                _zip_error_set(&za->error, ZIP_ER_REMOVE, errno);
-                return -1;
-            }
-        }
-        _zip_free(za);
-        return 0;
-    }
-
-    if ((filelist=(struct filelist *)malloc(sizeof(filelist[0])*survivors))
-        == NULL)
-        return -1;
-
-    if ((cd=_zip_cdir_new(survivors, &za->error)) == NULL) {
-        free(filelist);
-        return -1;
-    }
-
-    for (i=0; i<survivors; i++)
-        _zip_dirent_init(&cd->entry[i]);
-
-    /* archive comment is special for torrentzip */
-    if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0)) {
-        cd->comment = _zip_memdup(TORRENT_SIG "XXXXXXXX",
-                                  TORRENT_SIG_LEN + TORRENT_CRC_LEN,
-                                  &za->error);
-        if (cd->comment == NULL) {
-            _zip_cdir_free(cd);
-            free(filelist);
-            return -1;
-        }
-        cd->comment_len = TORRENT_SIG_LEN + TORRENT_CRC_LEN;
-    }
-    else if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, ZIP_FL_UNCHANGED) == 0) {
-        if (_zip_cdir_set_comment(cd, za) == -1) {
-            _zip_cdir_free(cd);
-            free(filelist);
-            return -1;
-        }
-    }
-
-    if ((temp=_zip_create_temp_output(za, &out)) == NULL) {
-        _zip_cdir_free(cd);
-        return -1;
-    }
-
-
-    /* create list of files with index into original archive  */
-    for (i=j=0; i<za->nentry; i++) {
-        if (za->entry[i].state == ZIP_ST_DELETED)
-            continue;
-
-        filelist[j].idx = i;
-        filelist[j].name = zip_get_name(za, i, 0);
-        j++;
-    }
-    if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0))
-        qsort(filelist, survivors, sizeof(filelist[0]),
-              _zip_torrentzip_cmp);
-
-    new_torrentzip = (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0) == 1
-                      && zip_get_archive_flag(za, ZIP_AFL_TORRENT,
-                                              ZIP_FL_UNCHANGED) == 0);
-    error = 0;
-    for (j=0; j<survivors; j++) {
-        i = filelist[j].idx;
-
-        /* create new local directory entry */
-        if (ZIP_ENTRY_DATA_CHANGED(za->entry+i) || new_torrentzip) {
-            _zip_dirent_init(&de);
-
-            if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0))
-                _zip_dirent_torrent_normalize(&de);
-
-            /* use it as central directory entry */
-            memcpy(cd->entry+j, &de, sizeof(cd->entry[j]));
-
-            /* set/update file name */
-            if (za->entry[i].ch_filename == NULL) {
-                if (za->entry[i].state == ZIP_ST_ADDED) {
-                    de.filename = strdup("-");
-                    de.filename_len = 1;
-                    cd->entry[j].filename = "-";
-                }
-                else {
-                    de.filename = strdup(za->cdir->entry[i].filename);
-                    de.filename_len = strlen(de.filename);
-                    cd->entry[j].filename = za->cdir->entry[i].filename;
-                    cd->entry[j].filename_len = de.filename_len;
-                }
-            }
-        }
-        else {
-            /* copy existing directory entries */
-            if (fseeko(za->zp, za->cdir->entry[i].offset, SEEK_SET) != 0) {
-                _zip_error_set(&za->error, ZIP_ER_SEEK, errno);
-                error = 1;
-                break;
-            }
-            if (_zip_dirent_read(&de, za->zp, NULL, 0, 1, &za->error) != 0) {
-                error = 1;
-                break;
-            }
-            if (de.bitflags & ZIP_GPBF_DATA_DESCRIPTOR) {
-                de.crc = za->cdir->entry[i].crc;
-                de.comp_size = za->cdir->entry[i].comp_size;
-                de.uncomp_size = za->cdir->entry[i].uncomp_size;
-                de.bitflags &= ~ZIP_GPBF_DATA_DESCRIPTOR;
-            }
-            memcpy(cd->entry+j, za->cdir->entry+i, sizeof(cd->entry[j]));
-        }
-
-        if (za->entry[i].ch_filename) {
-            free(de.filename);
-            if ((de.filename=strdup(za->entry[i].ch_filename)) == NULL) {
-                error = 1;
-                break;
-            }
-            de.filename_len = strlen(de.filename);
-            cd->entry[j].filename = za->entry[i].ch_filename;
-            cd->entry[j].filename_len = de.filename_len;
-        }
-
-        if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0) == 0
-            && za->entry[i].ch_comment_len != -1) {
-            /* as the rest of cd entries, its malloc/free is done by za */
-            cd->entry[j].comment = za->entry[i].ch_comment;
-            cd->entry[j].comment_len = za->entry[i].ch_comment_len;
-        }
-
-        cd->entry[j].offset = ftello(out);
-
-        if (ZIP_ENTRY_DATA_CHANGED(za->entry+i) || new_torrentzip) {
-            struct zip_source *zs;
-
-            zs = NULL;
-            if (!ZIP_ENTRY_DATA_CHANGED(za->entry+i)) {
-                if ((zs=zip_source_zip(za, za, i, ZIP_FL_RECOMPRESS, 0, -1))
-                    == NULL) {
-                    error = 1;
-                    break;
-                }
-            }
-
-            if (add_data(za, zs ? zs : za->entry[i].source, &de, out) < 0) {
-                error = 1;
-                break;
-            }
-            cd->entry[j].last_mod = de.last_mod;
-            cd->entry[j].comp_method = de.comp_method;
-            cd->entry[j].comp_size = de.comp_size;
-            cd->entry[j].uncomp_size = de.uncomp_size;
-            cd->entry[j].crc = de.crc;
-        }
-        else {
-            if (_zip_dirent_write(&de, out, 1, &za->error) < 0) {
-                error = 1;
-                break;
-            }
-            /* we just read the local dirent, file is at correct position */
-            if (copy_data(za->zp, cd->entry[j].comp_size, out,
-                          &za->error) < 0) {
-                error = 1;
-                break;
-            }
-        }
-
-        _zip_dirent_finalize(&de);
-    }
-
-    if (!error) {
-        if (write_cdir(za, cd, out) < 0)
-            error = 1;
-    }
-
-    /* pointers in cd entries are owned by za */
-    cd->nentry = 0;
-    _zip_cdir_free(cd);
-
-    if (error) {
-        _zip_dirent_finalize(&de);
-        fclose(out);
-        remove(temp);
-        free(temp);
-        return -1;
-    }
-
-    if (fclose(out) != 0) {
-        _zip_error_set(&za->error, ZIP_ER_CLOSE, errno);
-        remove(temp);
-        free(temp);
-        return -1;
-    }
-
-    if (za->zp) {
-        fclose(za->zp);
-        za->zp = NULL;
-        reopen_on_error = 1;
-    }
-    if (_zip_rename(temp, za->zn) != 0) {
-        _zip_error_set(&za->error, ZIP_ER_RENAME, errno);
-        remove(temp);
-        free(temp);
-        if (reopen_on_error) {
-            /* ignore errors, since we're already in an error case */
-            za->zp = fopen(za->zn, "rb");
-        }
-        return -1;
-    }
-    mask = umask(0);
-    umask(mask);
-    chmod(za->zn, 0666&~mask);
-
-    _zip_free(za);
-    free(temp);
-
-    return 0;
-}
-
-
-
-static int
-add_data(struct zip *za, struct zip_source *zs, struct zip_dirent *de, FILE *ft)
-{
-    myoff_t offstart, offend;
-    zip_source_callback cb;
-    void *ud;
-    struct zip_stat st;
-
-    cb = zs->f;
-    ud = zs->ud;
-
-    if (cb(ud, &st, sizeof(st), ZIP_SOURCE_STAT) < (ssize_t)sizeof(st)) {
-        ch_set_error(&za->error, cb, ud);
-        return -1;
-    }
-
-    if (cb(ud, NULL, 0, ZIP_SOURCE_OPEN) < 0) {
-        ch_set_error(&za->error, cb, ud);
-        return -1;
-    }
-
-    offstart = ftello(ft);
-
-    if (_zip_dirent_write(de, ft, 1, &za->error) < 0)
-        return -1;
-
-    if (st.comp_method != ZIP_CM_STORE) {
-        if (add_data_comp(cb, ud, &st, ft, &za->error) < 0)
-            return -1;
-    }
-    else {
-        if (add_data_uncomp(za, cb, ud, &st, ft) < 0)
-            return -1;
-    }
-
-    if (cb(ud, NULL, 0, ZIP_SOURCE_CLOSE) < 0) {
-        ch_set_error(&za->error, cb, ud);
-        return -1;
-    }
-
-    offend = ftello(ft);
-
-    if (fseeko(ft, offstart, SEEK_SET) < 0) {
-        _zip_error_set(&za->error, ZIP_ER_SEEK, errno);
-        return -1;
-    }
-
-
-    de->last_mod = st.mtime;
-    de->comp_method = st.comp_method;
-    de->crc = st.crc;
-    de->uncomp_size = st.size;
-    de->comp_size = st.comp_size;
-
-    if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0))
-        _zip_dirent_torrent_normalize(de);
-
-    if (_zip_dirent_write(de, ft, 1, &za->error) < 0)
-        return -1;
-
-    if (fseeko(ft, offend, SEEK_SET) < 0) {
-        _zip_error_set(&za->error, ZIP_ER_SEEK, errno);
-        return -1;
-    }
-
-    return 0;
-}
-
-
-
-static int
-add_data_comp(zip_source_callback cb, void *ud, struct zip_stat *st,FILE *ft,
-              struct zip_error *error)
-{
-    char buf[BUFSIZE];
-    ssize_t n;
-
-    st->comp_size = 0;
-    while ((n=cb(ud, buf, sizeof(buf), ZIP_SOURCE_READ)) > 0) {
-        if (fwrite(buf, 1, n, ft) != (size_t)n) {
-            _zip_error_set(error, ZIP_ER_WRITE, errno);
-            return -1;
-        }
-
-        st->comp_size += n;
-    }
-    if (n < 0) {
-        ch_set_error(error, cb, ud);
-        return -1;
-    }
-
-    return 0;
-}
-
-
-
-static int
-add_data_uncomp(struct zip *za, zip_source_callback cb, void *ud,
-                struct zip_stat *st, FILE *ft)
-{
-    char b1[BUFSIZE], b2[BUFSIZE];
-    int end, flush, ret;
-    ssize_t n;
-    size_t n2;
-    z_stream zstr;
-    int mem_level;
-
-    st->comp_method = ZIP_CM_DEFLATE;
-    st->comp_size = st->size = 0;
-    st->crc = crc32(0, NULL, 0);
-
-    zstr.zalloc = Z_NULL;
-    zstr.zfree = Z_NULL;
-    zstr.opaque = NULL;
-    zstr.avail_in = 0;
-    zstr.avail_out = 0;
-
-    if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0))
-        mem_level = TORRENT_MEM_LEVEL;
-    else
-        mem_level = MAX_MEM_LEVEL;
-
-    /* -MAX_WBITS: undocumented feature of zlib to _not_ write a zlib header */
-    deflateInit2(&zstr, Z_BEST_COMPRESSION, Z_DEFLATED, -MAX_WBITS, mem_level,
-                 Z_DEFAULT_STRATEGY);
-
-    zstr.next_out = (Bytef *)b2;
-    zstr.avail_out = sizeof(b2);
-    zstr.avail_in = 0;
-
-    flush = 0;
-    end = 0;
-    while (!end) {
-        if (zstr.avail_in == 0 && !flush) {
-            if ((n=cb(ud, b1, sizeof(b1), ZIP_SOURCE_READ)) < 0) {
-                ch_set_error(&za->error, cb, ud);
-                deflateEnd(&zstr);
-                return -1;
-            }
-            if (n > 0) {
-                zstr.avail_in = n;
-                zstr.next_in = (Bytef *)b1;
-                st->size += n;
-                st->crc = crc32(st->crc, (Bytef *)b1, n);
-            }
-            else
-                flush = Z_FINISH;
-        }
-
-        ret = deflate(&zstr, flush);
-        if (ret != Z_OK && ret != Z_STREAM_END) {
-            _zip_error_set(&za->error, ZIP_ER_ZLIB, ret);
-            return -1;
-        }
-
-        if (zstr.avail_out != sizeof(b2)) {
-            n2 = sizeof(b2) - zstr.avail_out;
-
-            if (fwrite(b2, 1, n2, ft) != n2) {
-                _zip_error_set(&za->error, ZIP_ER_WRITE, errno);
-                return -1;
-            }
-
-            zstr.next_out = (Bytef *)b2;
-            zstr.avail_out = sizeof(b2);
-            st->comp_size += n2;
-        }
-
-        if (ret == Z_STREAM_END) {
-            deflateEnd(&zstr);
-            end = 1;
-        }
-    }
-
-    return 0;
-}
-
-
-
-static void
-ch_set_error(struct zip_error *error, zip_source_callback cb, void *ud)
-{
-    int e[2];
-
-    if ((cb(ud, e, sizeof(e), ZIP_SOURCE_ERROR)) < (ssize_t)sizeof(e)) {
-        error->zip_err = ZIP_ER_INTERNAL;
-        error->sys_err = 0;
-    }
-    else {
-        error->zip_err = e[0];
-        error->sys_err = e[1];
-    }
-}
-
-
-
-static int
-copy_data(FILE *fs, myoff_t len, FILE *ft, struct zip_error *error)
-{
-    char buf[BUFSIZE];
-    int n, nn;
-
-    if (len == 0)
-        return 0;
-
-    while (len > 0) {
-        nn = len > sizeof(buf) ? sizeof(buf) : len;
-        if ((n=fread(buf, 1, nn, fs)) < 0) {
-            _zip_error_set(error, ZIP_ER_READ, errno);
-            return -1;
-        }
-        else if (n == 0) {
-            _zip_error_set(error, ZIP_ER_EOF, 0);
-            return -1;
-        }
-
-        if (fwrite(buf, 1, n, ft) != (size_t)n) {
-            _zip_error_set(error, ZIP_ER_WRITE, errno);
-            return -1;
-        }
-
-        len -= n;
-    }
-
-    return 0;
-}
-
-
-
-static int
-write_cdir(struct zip *za, struct zip_cdir *cd, FILE *out)
-{
-    myoff_t offset;
-    uLong crc;
-    char buf[TORRENT_CRC_LEN+1];
-
-    if (_zip_cdir_write(cd, out, &za->error) < 0)
-        return -1;
-
-    if (zip_get_archive_flag(za, ZIP_AFL_TORRENT, 0) == 0)
-        return 0;
-
-
-    /* fix up torrentzip comment */
-
-    offset = ftello(out);
-
-    if (_zip_filerange_crc(out, cd->offset, cd->size, &crc, &za->error) < 0)
-        return -1;
-
-    snprintf(buf, sizeof(buf), "%08lX", (long)crc);
-
-    if (fseeko(out, offset-TORRENT_CRC_LEN, SEEK_SET) < 0) {
-        _zip_error_set(&za->error, ZIP_ER_SEEK, errno);
-        return -1;
-    }
-
-    if (fwrite(buf, TORRENT_CRC_LEN, 1, out) != 1) {
-        _zip_error_set(&za->error, ZIP_ER_WRITE, errno);
-        return -1;
-    }
-
-    return 0;
-}
-
-
-
-static int
-_zip_cdir_set_comment(struct zip_cdir *dest, struct zip *src)
-{
-    if (src->ch_comment_len != -1) {
-        dest->comment = _zip_memdup(src->ch_comment,
-                                    src->ch_comment_len, &src->error);
-        if (dest->comment == NULL)
-            return -1;
-        dest->comment_len = src->ch_comment_len;
-    } else {
-        if (src->cdir && src->cdir->comment) {
-            dest->comment = _zip_memdup(src->cdir->comment,
-                                        src->cdir->comment_len, &src->error);
-            if (dest->comment == NULL)
-                return -1;
-            dest->comment_len = src->cdir->comment_len;
-        }
-    }
-
-    return 0;
-}
-
-
-
-static int
-_zip_changed(struct zip *za, int *survivorsp)
-{
-    int changed, i, survivors;
-
-    changed = survivors = 0;
-
-    if (za->ch_comment_len != -1
-        || za->ch_flags != za->flags)
-        changed = 1;
-
-    for (i=0; i<za->nentry; i++) {
-        if ((za->entry[i].state != ZIP_ST_UNCHANGED)
-            || (za->entry[i].ch_comment_len != -1))
-            changed = 1;
-        if (za->entry[i].state != ZIP_ST_DELETED)
-            survivors++;
-    }
-
-    *survivorsp = survivors;
-
-    return changed;
-}
-
-
-
-static char *
-_zip_create_temp_output(struct zip *za, FILE **outp)
-{
-    char *temp;
-    int tfd;
-    FILE *tfp;
-
-    if ((temp=(char *)malloc(strlen(za->zn)+8)) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    sprintf(temp, "%s.XXXXXX", za->zn);
-
-    if ((tfd=mkstemp(temp)) == -1) {
-        _zip_error_set(&za->error, ZIP_ER_TMPOPEN, errno);
-        free(temp);
-        return NULL;
-    }
-
-    if ((tfp=fdopen(tfd, "r+b")) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_TMPOPEN, errno);
-        close(tfd);
-        remove(temp);
-        free(temp);
-        return NULL;
-    }
-
-    *outp = tfp;
-    return temp;
-}
-
-
-
-static int
-_zip_torrentzip_cmp(const void *a, const void *b)
-{
-    return strcasecmp(((const struct filelist *)a)->name,
-                      ((const struct filelist *)b)->name);
-}
-
-
-
-ZIP_EXTERN int
-zip_add_dir(struct zip *za, const char *name)
-{
-    int len, ret;
-    char *s;
-    struct zip_source *source;
-
-    if (name == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    s = NULL;
-    len = strlen(name);
-
-    if (name[len-1] != '/') {
-        if ((s=(char *)malloc(len+2)) == NULL) {
-            _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-            return -1;
-        }
-        strcpy(s, name);
-        s[len] = '/';
-        s[len+1] = '\0';
-    }
-
-    if ((source=zip_source_buffer(za, NULL, 0, 0)) == NULL) {
-        free(s);
-        return -1;
-    }
-
-    ret = _zip_replace(za, -1, s ? s : name, source);
-
-    free(s);
-    if (ret < 0)
-        zip_source_free(source);
-
-    return ret;
-}
-
-
-ZIP_EXTERN int
-zip_error_to_str(char *buf, size_t len, int ze, int se)
-{
-    const char *zs, *ss;
-
-    if (ze < 0 || ze >= _zip_nerr_str)
-        return snprintf(buf, len, "Unknown error %d", ze);
-
-    zs = _zip_err_str[ze];
-
-    switch (_zip_err_type[ze]) {
-    case ZIP_ET_SYS:
-        ss = strerror(se);
-        break;
-
-    case ZIP_ET_ZLIB:
-        ss = zError(se);
-        break;
-
-    default:
-        ss = NULL;
-    }
-
-    return snprintf(buf, len, "%s%s%s",
-                    zs, (ss ? ": " : ""), (ss ? ss : ""));
-}
-
-
-ZIP_EXTERN void
-zip_file_error_clear(struct zip_file *zf)
-{
-    _zip_error_clear(&zf->error);
-}
-
-
-ZIP_EXTERN int
-zip_fclose(struct zip_file *zf)
-{
-    int i, ret;
-
-    if (zf->zstr)
-        inflateEnd(zf->zstr);
-    free(zf->buffer);
-    free(zf->zstr);
-
-    for (i=0; i<zf->za->nfile; i++) {
-        if (zf->za->file[i] == zf) {
-            zf->za->file[i] = zf->za->file[zf->za->nfile-1];
-            zf->za->nfile--;
-            break;
-        }
-    }
-
-    ret = 0;
-    if (zf->error.zip_err)
-        ret = zf->error.zip_err;
-    else if ((zf->flags & ZIP_ZF_CRC) && (zf->flags & ZIP_ZF_EOF)) {
-        /* if EOF, compare CRC */
-        if (zf->crc_orig != zf->crc)
-            ret = ZIP_ER_CRC;
-    }
-
-    free(zf);
-    return ret;
-}
-
-
-int
-_zip_filerange_crc(FILE *fp, myoff_t start, myoff_t len, uLong *crcp,
-                   struct zip_error *errp)
-{
-    Bytef buf[BUFSIZE];
-    size_t n;
-
-    *crcp = crc32(0L, Z_NULL, 0);
-
-    if (fseeko(fp, start, SEEK_SET) != 0) {
-        _zip_error_set(errp, ZIP_ER_SEEK, errno);
-        return -1;
-    }
-
-    while (len > 0) {
-        n = len > BUFSIZE ? BUFSIZE : len;
-        if ((n=fread(buf, 1, n, fp)) <= 0) {
-            _zip_error_set(errp, ZIP_ER_READ, errno);
-            return -1;
-        }
-
-        *crcp = crc32(*crcp, buf, n);
-
-        len-= n;
-    }
-
-    return 0;
-}
-
-
-ZIP_EXTERN const char *
-zip_file_strerror(struct zip_file *zf)
-{
-    return _zip_error_strerror(&zf->error);
-}
-
-
-/* _zip_file_get_offset(za, ze):
-   Returns the offset of the file data for entry ze.
-
-   On error, fills in za->error and returns 0.
-*/
-
-unsigned int
-_zip_file_get_offset(struct zip *za, int idx)
-{
-    struct zip_dirent de;
-    unsigned int offset;
-
-    offset = za->cdir->entry[idx].offset;
-
-    if (fseeko(za->zp, offset, SEEK_SET) != 0) {
-        _zip_error_set(&za->error, ZIP_ER_SEEK, errno);
-        return 0;
-    }
-
-    if (_zip_dirent_read(&de, za->zp, NULL, 0, 1, &za->error) != 0)
-        return 0;
-
-    offset += LENTRYSIZE + de.filename_len + de.extrafield_len;
-
-    _zip_dirent_finalize(&de);
-
-    return offset;
-}
-
-
-ZIP_EXTERN void
-zip_file_error_get(struct zip_file *zf, int *zep, int *sep)
-{
-    _zip_error_get(&zf->error, zep, sep);
-}
-
-
-static struct zip_file *_zip_file_new(struct zip *za);
-
-
-
-ZIP_EXTERN struct zip_file *
-zip_fopen_index(struct zip *za, int fileno, int flags)
-{
-    int len, ret;
-    int zfflags;
-    struct zip_file *zf;
-
-    if ((fileno < 0) || (fileno >= za->nentry)) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    if ((flags & ZIP_FL_UNCHANGED) == 0
-        && ZIP_ENTRY_DATA_CHANGED(za->entry+fileno)) {
-        _zip_error_set(&za->error, ZIP_ER_CHANGED, 0);
-        return NULL;
-    }
-
-    if (fileno >= za->cdir->nentry) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    zfflags = 0;
-    switch (za->cdir->entry[fileno].comp_method) {
-    case ZIP_CM_STORE:
-        zfflags |= ZIP_ZF_CRC;
-        break;
-
-    case ZIP_CM_DEFLATE:
-        if ((flags & ZIP_FL_COMPRESSED) == 0)
-            zfflags |= ZIP_ZF_CRC | ZIP_ZF_DECOMP;
-        break;
-    default:
-        if ((flags & ZIP_FL_COMPRESSED) == 0) {
-            _zip_error_set(&za->error, ZIP_ER_COMPNOTSUPP, 0);
-            return NULL;
-        }
-        break;
-    }
-
-    zf = _zip_file_new(za);
-
-    zf->flags = zfflags;
-    /* zf->name = za->cdir->entry[fileno].filename; */
-    zf->method = za->cdir->entry[fileno].comp_method;
-    zf->bytes_left = za->cdir->entry[fileno].uncomp_size;
-    zf->cbytes_left = za->cdir->entry[fileno].comp_size;
-    zf->crc_orig = za->cdir->entry[fileno].crc;
-
-    if ((zf->fpos=_zip_file_get_offset(za, fileno)) == 0) {
-        zip_fclose(zf);
-        return NULL;
-    }
-
-    if ((zf->flags & ZIP_ZF_DECOMP) == 0)
-        zf->bytes_left = zf->cbytes_left;
-    else {
-        if ((zf->buffer=(char *)malloc(BUFSIZE)) == NULL) {
-            _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-            zip_fclose(zf);
-            return NULL;
-        }
-
-        len = _zip_file_fillbuf(zf->buffer, BUFSIZE, zf);
-        if (len <= 0) {
-            _zip_error_copy(&za->error, &zf->error);
-            zip_fclose(zf);
-        return NULL;
-        }
-
-        if ((zf->zstr = (z_stream *)malloc(sizeof(z_stream))) == NULL) {
-            _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-            zip_fclose(zf);
-            return NULL;
-        }
-        zf->zstr->zalloc = Z_NULL;
-        zf->zstr->zfree = Z_NULL;
-        zf->zstr->opaque = NULL;
-        zf->zstr->next_in = (Bytef *)zf->buffer;
-        zf->zstr->avail_in = len;
-
-        /* negative value to tell zlib that there is no header */
-        if ((ret=inflateInit2(zf->zstr, -MAX_WBITS)) != Z_OK) {
-            _zip_error_set(&za->error, ZIP_ER_ZLIB, ret);
-            zip_fclose(zf);
-            return NULL;
-        }
-    }
-
-    return zf;
-}
-
-
-
-int
-_zip_file_fillbuf(void *buf, size_t buflen, struct zip_file *zf)
-{
-    int i, j;
-
-    if (zf->error.zip_err != ZIP_ER_OK)
-        return -1;
-
-    if ((zf->flags & ZIP_ZF_EOF) || zf->cbytes_left <= 0 || buflen <= 0)
-        return 0;
-
-    if (fseeko(zf->za->zp, zf->fpos, SEEK_SET) < 0) {
-        _zip_error_set(&zf->error, ZIP_ER_SEEK, errno);
-        return -1;
-    }
-    if (buflen < zf->cbytes_left)
-        i = buflen;
-    else
-        i = zf->cbytes_left;
-
-    j = fread(buf, 1, i, zf->za->zp);
-    if (j == 0) {
-        _zip_error_set(&zf->error, ZIP_ER_EOF, 0);
-        j = -1;
-    }
-    else if (j < 0)
-        _zip_error_set(&zf->error, ZIP_ER_READ, errno);
-    else {
-        zf->fpos += j;
-        zf->cbytes_left -= j;
-    }
-
-    return j;
-}
-
-
-
-static struct zip_file *
-_zip_file_new(struct zip *za)
-{
-    struct zip_file *zf, **file;
-    int n;
-
-    if ((zf=(struct zip_file *)malloc(sizeof(struct zip_file))) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    if (za->nfile >= za->nfile_alloc-1) {
-        n = za->nfile_alloc + 10;
-        file = (struct zip_file **)realloc(za->file,
-                                           n*sizeof(struct zip_file *));
-        if (file == NULL) {
-            _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-            free(zf);
-            return NULL;
-        }
-        za->nfile_alloc = n;
-        za->file = file;
-    }
-
-    za->file[za->nfile++] = zf;
-
-    zf->za = za;
-    _zip_error_init(&zf->error);
-    zf->flags = 0;
-    zf->crc = crc32(0L, Z_NULL, 0);
-    zf->crc_orig = 0;
-    zf->method = -1;
-    zf->bytes_left = zf->cbytes_left = 0;
-    zf->fpos = 0;
-    zf->buffer = NULL;
-    zf->zstr = NULL;
-
-    return zf;
-}
-
-
-ZIP_EXTERN struct zip_file *
-zip_fopen(struct zip *za, const char *fname, int flags)
-{
-    int idx;
-
-    if ((idx=zip_name_locate(za, fname, flags)) < 0)
-        return NULL;
-
-    return zip_fopen_index(za, idx, flags);
-}
-
-
-ZIP_EXTERN int
-zip_set_file_comment(struct zip *za, int idx, const char *comment, int len)
-{
-    char *tmpcom;
-
-    if (idx < 0 || idx >= za->nentry
-        || len < 0 || len > MAXCOMLEN
-        || (len > 0 && comment == NULL)) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    if (len > 0) {
-        if ((tmpcom=(char *)_zip_memdup(comment, len, &za->error)) == NULL)
-            return -1;
-    }
-    else
-        tmpcom = NULL;
-
-    free(za->entry[idx].ch_comment);
-    za->entry[idx].ch_comment = tmpcom;
-    za->entry[idx].ch_comment_len = len;
-
-    return 0;
-}
-
-
-ZIP_EXTERN struct zip_source *
-zip_source_file(struct zip *za, const char *fname, myoff_t start, myoff_t len)
-{
-    if (za == NULL)
-        return NULL;
-
-    if (fname == NULL || start < 0 || len < -1) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    return _zip_source_file_or_p(za, fname, NULL, start, len);
-}
-
-
-struct read_data {
-    const char *buf, *data, *end;
-    time_t mtime;
-    int freep;
-};
-
-static ssize_t read_data(void *state, void *data, size_t len,
-                         enum zip_source_cmd cmd);
-
-
-
-ZIP_EXTERN struct zip_source *
-zip_source_buffer(struct zip *za, const void *data, myoff_t len, int freep)
-{
-    struct read_data *f;
-    struct zip_source *zs;
-
-    if (za == NULL)
-        return NULL;
-
-    if (len < 0 || (data == NULL && len > 0)) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    if ((f=(struct read_data *)malloc(sizeof(*f))) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    f->data = (const char *)data;
-    f->end = ((const char *)data)+len;
-    f->freep = freep;
-    f->mtime = time(NULL);
-
-    if ((zs=zip_source_function(za, read_data, f)) == NULL) {
-        free(f);
-        return NULL;
-    }
-
-    return zs;
-}
-
-
-
-static ssize_t
-read_data(void *state, void *data, size_t len, enum zip_source_cmd cmd)
-{
-    struct read_data *z;
-    char *buf;
-    size_t n;
-
-    z = (struct read_data *)state;
-    buf = (char *)data;
-
-    switch (cmd) {
-    case ZIP_SOURCE_OPEN:
-        z->buf = z->data;
-        return 0;
-
-    case ZIP_SOURCE_READ:
-        n = z->end - z->buf;
-        if (n > len)
-            n = len;
-
-        if (n) {
-            memcpy(buf, z->buf, n);
-            z->buf += n;
-        }
-
-        return n;
-
-    case ZIP_SOURCE_CLOSE:
-        return 0;
-
-    case ZIP_SOURCE_STAT:
-        {
-            struct zip_stat *st;
-
-            if (len < sizeof(*st))
-                return -1;
-
-            st = (struct zip_stat *)data;
-
-            zip_stat_init(st);
-            st->mtime = z->mtime;
-            st->size = z->end - z->data;
-
-            return sizeof(*st);
-        }
-
-    case ZIP_SOURCE_ERROR:
-        {
-            int *e;
-
-            if (len < sizeof(int)*2)
-                return -1;
-
-            e = (int *)data;
-            e[0] = e[1] = 0;
-        }
-        return sizeof(int)*2;
-
-    case ZIP_SOURCE_FREE:
-        if (z->freep) {
-            free((void *)z->data);
-            z->data = NULL;
-        }
-        free(z);
-        return 0;
-
-    default:
-        ;
-    }
-
-    return -1;
-}
-
-
-int
-_zip_set_name(struct zip *za, int idx, const char *name)
-{
-    char *s;
-    int i;
-
-    if (idx < 0 || idx >= za->nentry || name == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    if ((i=_zip_name_locate(za, name, 0, NULL)) != -1 && i != idx) {
-        _zip_error_set(&za->error, ZIP_ER_EXISTS, 0);
-        return -1;
-    }
-
-    /* no effective name change */
-    if (i == idx)
-        return 0;
-
-    if ((s=strdup(name)) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-        return -1;
-    }
-
-    if (za->entry[idx].state == ZIP_ST_UNCHANGED)
-        za->entry[idx].state = ZIP_ST_RENAMED;
-
-    free(za->entry[idx].ch_filename);
-    za->entry[idx].ch_filename = s;
-
-    return 0;
-}
-
-
-ZIP_EXTERN int
-zip_set_archive_flag(struct zip *za, int flag, int value)
-{
-    if (value)
-        za->ch_flags |= flag;
-    else
-        za->ch_flags &= ~flag;
-
-    return 0;
-}
-
-
-void
-_zip_unchange_data(struct zip_entry *ze)
-{
-    if (ze->source) {
-        (void)ze->source->f(ze->source->ud, NULL, 0, ZIP_SOURCE_FREE);
-        free(ze->source);
-        ze->source = NULL;
-    }
-
-    ze->state = ze->ch_filename ? ZIP_ST_RENAMED : ZIP_ST_UNCHANGED;
-}
-
-
-ZIP_EXTERN int
-zip_unchange_archive(struct zip *za)
-{
-    free(za->ch_comment);
-    za->ch_comment = NULL;
-    za->ch_comment_len = -1;
-
-    za->ch_flags = za->flags;
-
-    return 0;
-}
-
-ZIP_EXTERN int
-zip_unchange(struct zip *za, int idx)
-{
-    return _zip_unchange(za, idx, 0);
-}
-
-
-
-int
-_zip_unchange(struct zip *za, int idx, int allow_duplicates)
-{
-    int i;
-
-    if (idx < 0 || idx >= za->nentry) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    if (za->entry[idx].ch_filename) {
-        if (!allow_duplicates) {
-            i = _zip_name_locate(za,
-                         _zip_get_name(za, idx, ZIP_FL_UNCHANGED, NULL),
-                                 0, NULL);
-            if (i != -1 && i != idx) {
-                _zip_error_set(&za->error, ZIP_ER_EXISTS, 0);
-                return -1;
-            }
-        }
-
-        free(za->entry[idx].ch_filename);
-        za->entry[idx].ch_filename = NULL;
-    }
-
-    free(za->entry[idx].ch_comment);
-    za->entry[idx].ch_comment = NULL;
-    za->entry[idx].ch_comment_len = -1;
-
-    _zip_unchange_data(za->entry+idx);
-
-    return 0;
-}
-
-ZIP_EXTERN int
-zip_unchange_all(struct zip *za)
-{
-    int ret, i;
-
-    ret = 0;
-    for (i=0; i<za->nentry; i++)
-        ret |= _zip_unchange(za, i, 1);
-
-    ret |= zip_unchange_archive(za);
-
-    return ret;
-}
-
-
-ZIP_EXTERN int
-zip_set_archive_comment(struct zip *za, const char *comment, int len)
-{
-    char *tmpcom;
-
-    if (len < 0 || len > MAXCOMLEN
-        || (len > 0 && comment == NULL)) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    if (len > 0) {
-        if ((tmpcom=(char *)_zip_memdup(comment, len, &za->error)) == NULL)
-            return -1;
-    }
-    else
-        tmpcom = NULL;
-
-    free(za->ch_comment);
-    za->ch_comment = tmpcom;
-    za->ch_comment_len = len;
-
-    return 0;
-}
-
-
-ZIP_EXTERN int
-zip_replace(struct zip *za, int idx, struct zip_source *source)
-{
-    if (idx < 0 || idx >= za->nentry || source == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    if (_zip_replace(za, idx, NULL, source) == -1)
-        return -1;
-
-    return 0;
-}
-
-
-
-
-int
-_zip_replace(struct zip *za, int idx, const char *name,
-             struct zip_source *source)
-{
-    if (idx == -1) {
-        if (_zip_entry_new(za) == NULL)
-            return -1;
-
-        idx = za->nentry - 1;
-    }
-
-    _zip_unchange_data(za->entry+idx);
-
-    if (name && _zip_set_name(za, idx, name) != 0)
-        return -1;
-
-    za->entry[idx].state = ((za->cdir == NULL || idx >= za->cdir->nentry)
-                            ? ZIP_ST_ADDED : ZIP_ST_REPLACED);
-    za->entry[idx].source = source;
-
-    return idx;
-}
-
-
-ZIP_EXTERN int
-zip_rename(struct zip *za, int idx, const char *name)
-{
-    const char *old_name;
-    int old_is_dir, new_is_dir;
-
-    if (idx >= za->nentry || idx < 0 || name[0] == '\0') {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    if ((old_name=zip_get_name(za, idx, 0)) == NULL)
-        return -1;
-
-    new_is_dir = (name[strlen(name)-1] == '/');
-    old_is_dir = (old_name[strlen(old_name)-1] == '/');
-
-    if (new_is_dir != old_is_dir) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    return _zip_set_name(za, idx, name);
-}
-
-#include <sys/stat.h>
-#include <errno.h>
-#include <limits.h>
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-
-static void set_error(int *, struct zip_error *, int);
-static struct zip *_zip_allocate_new(const char *, int *);
-static int _zip_checkcons(FILE *, struct zip_cdir *, struct zip_error *);
-static void _zip_check_torrentzip(struct zip *);
-static struct zip_cdir *_zip_find_central_dir(FILE *, int, int *, myoff_t);
-static int _zip_file_exists(const char *, int, int *);
-static int _zip_headercomp(struct zip_dirent *, int,
-                           struct zip_dirent *, int);
-static unsigned char *_zip_memmem(const unsigned char *, int,
-                                  const unsigned char *, int);
-static struct zip_cdir *_zip_readcdir(FILE *, unsigned char *, unsigned char *,
-                                 int, int, struct zip_error *);
-
-
-
-ZIP_EXTERN struct zip *
-zip_open(const char *fn, int flags, int *zep)
-{
-    FILE *fp;
-    struct zip *za;
-    struct zip_cdir *cdir;
-    int i;
-    myoff_t len;
-
-    switch (_zip_file_exists(fn, flags, zep)) {
-    case -1:
-        return NULL;
-    case 0:
-        return _zip_allocate_new(fn, zep);
-    default:
-        break;
-    }
-
-    if ((fp=fopen(fn, "rb")) == NULL) {
-        set_error(zep, NULL, ZIP_ER_OPEN);
-        return NULL;
-    }
-
-    fseeko(fp, 0, SEEK_END);
-    len = ftello(fp);
-
-    /* treat empty files as empty archives */
-    if (len == 0) {
-        if ((za=_zip_allocate_new(fn, zep)) == NULL)
-            fclose(fp);
-        else
-            za->zp = fp;
-        return za;
-    }
-
-    cdir = _zip_find_central_dir(fp, flags, zep, len);
-    if (cdir == NULL) {
-        fclose(fp);
-        return NULL;
-    }
-
-    if ((za=_zip_allocate_new(fn, zep)) == NULL) {
-        _zip_cdir_free(cdir);
-        fclose(fp);
-        return NULL;
-    }
-
-    za->cdir = cdir;
-    za->zp = fp;
-
-    if ((za->entry=(struct zip_entry *)malloc(sizeof(*(za->entry))
-                                              * cdir->nentry)) == NULL) {
-        set_error(zep, NULL, ZIP_ER_MEMORY);
-        _zip_free(za);
-        return NULL;
-    }
-    for (i=0; i<cdir->nentry; i++)
-        _zip_entry_new(za);
-
-    _zip_check_torrentzip(za);
-    za->ch_flags = za->flags;
-
-    return za;
-}
-
-
-
-static void
-set_error(int *zep, struct zip_error *err, int ze)
-{
-    int se;
-
-    if (err) {
-        _zip_error_get(err, &ze, &se);
-        if (zip_error_get_sys_type(ze) == ZIP_ET_SYS)
-            errno = se;
-    }
-
-    if (zep)
-        *zep = ze;
-}
-
-
-
-/* _zip_readcdir:
-   tries to find a valid end-of-central-directory at the beginning of
-   buf, and then the corresponding central directory entries.
-   Returns a struct zip_cdir which contains the central directory
-   entries, or NULL if unsuccessful. */
-
-static struct zip_cdir *
-_zip_readcdir(FILE *fp, unsigned char *buf, unsigned char *eocd, int buflen,
-              int flags, struct zip_error *error)
-{
-    struct zip_cdir *cd;
-    unsigned char *cdp, **bufp;
-    int i, comlen, nentry;
-
-    comlen = buf + buflen - eocd - EOCDLEN;
-    if (comlen < 0) {
-        /* not enough bytes left for comment */
-        _zip_error_set(error, ZIP_ER_NOZIP, 0);
-        return NULL;
-    }
-
-    /* check for end-of-central-dir magic */
-    if (memcmp(eocd, EOCD_MAGIC, 4) != 0) {
-        _zip_error_set(error, ZIP_ER_NOZIP, 0);
-        return NULL;
-    }
-
-    if (memcmp(eocd+4, "\0\0\0\0", 4) != 0) {
-        _zip_error_set(error, ZIP_ER_MULTIDISK, 0);
-        return NULL;
-    }
-
-    cdp = eocd + 8;
-    /* number of cdir-entries on this disk */
-    i = _zip_read2(&cdp);
-    /* number of cdir-entries */
-    nentry = _zip_read2(&cdp);
-
-    if ((cd=_zip_cdir_new(nentry, error)) == NULL)
-        return NULL;
-
-    cd->size = _zip_read4(&cdp);
-    cd->offset = _zip_read4(&cdp);
-    cd->comment = NULL;
-    cd->comment_len = _zip_read2(&cdp);
-
-    if ((comlen < cd->comment_len) || (cd->nentry != i)) {
-        _zip_error_set(error, ZIP_ER_NOZIP, 0);
-        free(cd);
-        return NULL;
-    }
-    if ((flags & ZIP_CHECKCONS) && comlen != cd->comment_len) {
-        _zip_error_set(error, ZIP_ER_INCONS, 0);
-        free(cd);
-        return NULL;
-    }
-
-    if (cd->comment_len) {
-        if ((cd->comment=(char *)_zip_memdup(eocd+EOCDLEN,
-                                             cd->comment_len, error))
-            == NULL) {
-            free(cd);
-            return NULL;
-        }
-    }
-
-    cdp = eocd;
-    if (cd->size < (unsigned int)(eocd-buf)) {
-        /* if buffer already read in, use it */
-        cdp = eocd - cd->size;
-        bufp = &cdp;
-    }
-    else {
-        /* go to start of cdir and read it entry by entry */
-        bufp = NULL;
-        clearerr(fp);
-        fseeko(fp, cd->offset, SEEK_SET);
-        /* possible consistency check: cd->offset =
-           len-(cd->size+cd->comment_len+EOCDLEN) ? */
-        if (ferror(fp) || ((unsigned long)ftello(fp) != cd->offset)) {
-            /* seek error or offset of cdir wrong */
-            if (ferror(fp))
-                _zip_error_set(error, ZIP_ER_SEEK, errno);
-            else
-                _zip_error_set(error, ZIP_ER_NOZIP, 0);
-            free(cd);
-            return NULL;
-        }
-    }
-
-    for (i=0; i<cd->nentry; i++) {
-        if ((_zip_dirent_read(cd->entry+i, fp, bufp, eocd-cdp, 0,
-                              error)) < 0) {
-            cd->nentry = i;
-            _zip_cdir_free(cd);
-            return NULL;
-        }
-    }
-
-    return cd;
-}
-
-
-
-/* _zip_checkcons:
-   Checks the consistency of the central directory by comparing central
-   directory entries with local headers and checking for plausible
-   file and header offsets. Returns -1 if not plausible, else the
-   difference between the lowest and the highest fileposition reached */
-
-static int
-_zip_checkcons(FILE *fp, struct zip_cdir *cd, struct zip_error *error)
-{
-    int i;
-    unsigned int min, max, j;
-    struct zip_dirent temp;
-
-    if (cd->nentry) {
-        max = cd->entry[0].offset;
-        min = cd->entry[0].offset;
-    }
-    else
-        min = max = 0;
-
-    for (i=0; i<cd->nentry; i++) {
-        if (cd->entry[i].offset < min)
-            min = cd->entry[i].offset;
-        if (min > cd->offset) {
-            _zip_error_set(error, ZIP_ER_NOZIP, 0);
-            return -1;
-        }
-
-        j = cd->entry[i].offset + cd->entry[i].comp_size
-            + cd->entry[i].filename_len + LENTRYSIZE;
-        if (j > max)
-            max = j;
-        if (max > cd->offset) {
-            _zip_error_set(error, ZIP_ER_NOZIP, 0);
-            return -1;
-        }
-
-        if (fseeko(fp, cd->entry[i].offset, SEEK_SET) != 0) {
-            _zip_error_set(error, ZIP_ER_SEEK, 0);
-            return -1;
-        }
-
-        if (_zip_dirent_read(&temp, fp, NULL, 0, 1, error) == -1)
-            return -1;
-
-        if (_zip_headercomp(cd->entry+i, 0, &temp, 1) != 0) {
-            _zip_error_set(error, ZIP_ER_INCONS, 0);
-            _zip_dirent_finalize(&temp);
-            return -1;
-        }
-        _zip_dirent_finalize(&temp);
-    }
-
-    return max - min;
-}
-
-
-
-/* _zip_check_torrentzip:
-   check wether ZA has a valid TORRENTZIP comment, i.e. is torrentzipped */
-
-static void
-_zip_check_torrentzip(struct zip *za)
-{
-    uLong crc_got, crc_should;
-    char buf[8+1];
-    char *end;
-
-    if (za->zp == NULL || za->cdir == NULL)
-        return;
-
-    if (za->cdir->comment_len != TORRENT_SIG_LEN+8
-        || strncmp(za->cdir->comment, TORRENT_SIG, TORRENT_SIG_LEN) != 0)
-        return;
-
-    memcpy(buf, za->cdir->comment+TORRENT_SIG_LEN, 8);
-    buf[8] = '\0';
-    errno = 0;
-    crc_should = strtoul(buf, &end, 16);
-    if ((crc_should == UINT_MAX && errno != 0) || (end && *end))
-        return;
-
-    if (_zip_filerange_crc(za->zp, za->cdir->offset, za->cdir->size,
-                           &crc_got, NULL) < 0)
-        return;
-
-    if (crc_got == crc_should)
-        za->flags |= ZIP_AFL_TORRENT;
-}
-
-
-
-
-/* _zip_headercomp:
-   compares two headers h1 and h2; if they are local headers, set
-   local1p or local2p respectively to 1, else 0. Return 0 if they
-   are identical, -1 if not. */
-
-static int
-_zip_headercomp(struct zip_dirent *h1, int local1p, struct zip_dirent *h2,
-           int local2p)
-{
-    if ((h1->version_needed != h2->version_needed)
-#if 0
-        /* some zip-files have different values in local
-           and global headers for the bitflags */
-        || (h1->bitflags != h2->bitflags)
-#endif
-        || (h1->comp_method != h2->comp_method)
-        || (h1->last_mod != h2->last_mod)
-        || (h1->filename_len != h2->filename_len)
-        || !h1->filename || !h2->filename
-        || strcmp(h1->filename, h2->filename))
-        return -1;
-
-    /* check that CRC and sizes are zero if data descriptor is used */
-    if ((h1->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) && local1p
-        && (h1->crc != 0
-            || h1->comp_size != 0
-            || h1->uncomp_size != 0))
-        return -1;
-    if ((h2->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) && local2p
-        && (h2->crc != 0
-            || h2->comp_size != 0
-            || h2->uncomp_size != 0))
-        return -1;
-
-    /* check that CRC and sizes are equal if no data descriptor is used */
-    if (((h1->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0 || local1p == 0)
-        && ((h2->bitflags & ZIP_GPBF_DATA_DESCRIPTOR) == 0 || local2p == 0)) {
-        if ((h1->crc != h2->crc)
-            || (h1->comp_size != h2->comp_size)
-            || (h1->uncomp_size != h2->uncomp_size))
-            return -1;
-    }
-
-    if ((local1p == local2p)
-        && ((h1->extrafield_len != h2->extrafield_len)
-            || (h1->extrafield_len && h2->extrafield
-                && memcmp(h1->extrafield, h2->extrafield,
-                          h1->extrafield_len))))
-        return -1;
-
-    /* if either is local, nothing more to check */
-    if (local1p || local2p)
-        return 0;
-
-    if ((h1->version_madeby != h2->version_madeby)
-        || (h1->disk_number != h2->disk_number)
-        || (h1->int_attrib != h2->int_attrib)
-        || (h1->ext_attrib != h2->ext_attrib)
-        || (h1->offset != h2->offset)
-        || (h1->comment_len != h2->comment_len)
-        || (h1->comment_len && h2->comment
-            && memcmp(h1->comment, h2->comment, h1->comment_len)))
-        return -1;
-
-    return 0;
-}
-
-
-
-static struct zip *
-_zip_allocate_new(const char *fn, int *zep)
-{
-    struct zip *za;
-    struct zip_error error;
-
-    if ((za=_zip_new(&error)) == NULL) {
-        set_error(zep, &error, 0);
-        return NULL;
-    }
-
-    za->zn = strdup(fn);
-    if (!za->zn) {
-        _zip_free(za);
-        set_error(zep, NULL, ZIP_ER_MEMORY);
-        return NULL;
-    }
-    return za;
-}
-
-
-
-static int
-_zip_file_exists(const char *fn, int flags, int *zep)
-{
-    struct stat st;
-
-    if (fn == NULL) {
-        set_error(zep, NULL, ZIP_ER_INVAL);
-        return -1;
-    }
-
-    if (stat(fn, &st) != 0) {
-        if (flags & ZIP_CREATE)
-            return 0;
-        else {
-            set_error(zep, NULL, ZIP_ER_OPEN);
-            return -1;
-        }
-    }
-    else if ((flags & ZIP_EXCL)) {
-        set_error(zep, NULL, ZIP_ER_EXISTS);
-        return -1;
-    }
-    /* ZIP_CREATE gets ignored if file exists and not ZIP_EXCL,
-       just like open() */
-
-    return 1;
-}
-
-
-
-static struct zip_cdir *
-_zip_find_central_dir(FILE *fp, int flags, int *zep, myoff_t len)
-{
-    struct zip_cdir *cdir, *cdirnew;
-    unsigned char *buf, *match;
-    int a, best, buflen, i;
-    struct zip_error zerr;
-
-    i = fseeko(fp, -(len < CDBUFSIZE ? len : CDBUFSIZE), SEEK_END);
-    if (i == -1 && errno != EFBIG) {
-        /* seek before start of file on my machine */
-        set_error(zep, NULL, ZIP_ER_SEEK);
-        return NULL;
-    }
-
-    /* 64k is too much for stack */
-    if ((buf=(unsigned char *)malloc(CDBUFSIZE)) == NULL) {
-        set_error(zep, NULL, ZIP_ER_MEMORY);
-        return NULL;
-    }
-
-    clearerr(fp);
-    buflen = fread(buf, 1, CDBUFSIZE, fp);
-
-    if (ferror(fp)) {
-        set_error(zep, NULL, ZIP_ER_READ);
-        free(buf);
-        return NULL;
-    }
-
-    best = -1;
-    cdir = NULL;
-    match = buf;
-    _zip_error_set(&zerr, ZIP_ER_NOZIP, 0);
-
-    while ((match=_zip_memmem(match, buflen-(match-buf)-18,
-                              (const unsigned char *)EOCD_MAGIC, 4))!=NULL) {
-        /* found match -- check, if good */
-        /* to avoid finding the same match all over again */
-        match++;
-        if ((cdirnew=_zip_readcdir(fp, buf, match-1, buflen, flags,
-                                   &zerr)) == NULL)
-            continue;
-
-        if (cdir) {
-            if (best <= 0)
-                best = _zip_checkcons(fp, cdir, &zerr);
-            a = _zip_checkcons(fp, cdirnew, &zerr);
-            if (best < a) {
-                _zip_cdir_free(cdir);
-                cdir = cdirnew;
-                best = a;
-            }
-            else
-                _zip_cdir_free(cdirnew);
-        }
-        else {
-            cdir = cdirnew;
-            if (flags & ZIP_CHECKCONS)
-                best = _zip_checkcons(fp, cdir, &zerr);
-            else
-                best = 0;
-        }
-        cdirnew = NULL;
-    }
-
-    free(buf);
-
-    if (best < 0) {
-        set_error(zep, &zerr, 0);
-        _zip_cdir_free(cdir);
-        return NULL;
-    }
-
-    return cdir;
-}
-
-
-
-static unsigned char *
-_zip_memmem(const unsigned char *big, int biglen, const unsigned char *little,
-       int littlelen)
-{
-    const unsigned char *p;
-
-    if ((biglen < littlelen) || (littlelen == 0))
-        return NULL;
-    p = big-1;
-    while ((p=(const unsigned char *)
-                memchr(p+1, little[0], (size_t)(big-(p+1)+biglen-littlelen+1)))
-           != NULL) {
-        if (memcmp(p+1, little+1, littlelen-1)==0)
-            return (unsigned char *)p;
-    }
-
-    return NULL;
-}
-
-
-/* _zip_new:
-   creates a new zipfile struct, and sets the contents to zero; returns
-   the new struct. */
-
-struct zip *
-_zip_new(struct zip_error *error)
-{
-    struct zip *za;
-
-    za = (struct zip *)malloc(sizeof(struct zip));
-    if (!za) {
-        _zip_error_set(error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    za->zn = NULL;
-    za->zp = NULL;
-    _zip_error_init(&za->error);
-    za->cdir = NULL;
-    za->ch_comment = NULL;
-    za->ch_comment_len = -1;
-    za->nentry = za->nentry_alloc = 0;
-    za->entry = NULL;
-    za->nfile = za->nfile_alloc = 0;
-    za->file = NULL;
-    za->flags = za->ch_flags = 0;
-
-    return za;
-}
-
-
-void *
-_zip_memdup(const void *mem, size_t len, struct zip_error *error)
-{
-    void *ret;
-
-    ret = malloc(len);
-    if (!ret) {
-        _zip_error_set(error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    memcpy(ret, mem, len);
-
-    return ret;
-}
-
-
-ZIP_EXTERN int
-zip_get_num_files(struct zip *za)
-{
-    if (za == NULL)
-        return -1;
-
-    return za->nentry;
-}
-
-ZIP_EXTERN const char *
-zip_get_name(struct zip *za, int idx, int flags)
-{
-    return _zip_get_name(za, idx, flags, &za->error);
-}
-
-
-
-const char *
-_zip_get_name(struct zip *za, int idx, int flags, struct zip_error *error)
-{
-    if (idx < 0 || idx >= za->nentry) {
-        _zip_error_set(error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    if ((flags & ZIP_FL_UNCHANGED) == 0) {
-        if (za->entry[idx].state == ZIP_ST_DELETED) {
-            _zip_error_set(error, ZIP_ER_DELETED, 0);
-            return NULL;
-        }
-        if (za->entry[idx].ch_filename)
-            return za->entry[idx].ch_filename;
-    }
-
-    if (za->cdir == NULL || idx >= za->cdir->nentry) {
-        _zip_error_set(error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    return za->cdir->entry[idx].filename;
-}
-
-
-ZIP_EXTERN const char *
-zip_get_file_comment(struct zip *za, int idx, int *lenp, int flags)
-{
-    if (idx < 0 || idx >= za->nentry) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    if ((flags & ZIP_FL_UNCHANGED)
-        || (za->entry[idx].ch_comment_len == -1)) {
-        if (lenp != NULL)
-            *lenp = za->cdir->entry[idx].comment_len;
-        return za->cdir->entry[idx].comment;
-    }
-
-    if (lenp != NULL)
-        *lenp = za->entry[idx].ch_comment_len;
-    return za->entry[idx].ch_comment;
-}
-
-
-ZIP_EXTERN int
-zip_get_archive_flag(struct zip *za, int flag, int flags)
-{
-    int fl;
-
-    fl = (flags & ZIP_FL_UNCHANGED) ? za->flags : za->ch_flags;
-
-    return (fl & flag) ? 1 : 0;
-}
-
-
-ZIP_EXTERN const char *
-zip_get_archive_comment(struct zip *za, int *lenp, int flags)
-{
-    if ((flags & ZIP_FL_UNCHANGED)
-        || (za->ch_comment_len == -1)) {
-        if (za->cdir) {
-            if (lenp != NULL)
-                *lenp = za->cdir->comment_len;
-            return za->cdir->comment;
-        }
-        else {
-            if (lenp != NULL)
-                *lenp = -1;
-            return NULL;
-        }
-    }
-
-    if (lenp != NULL)
-        *lenp = za->ch_comment_len;
-    return za->ch_comment;
-}
-
-
-/* _zip_free:
-   frees the space allocated to a zipfile struct, and closes the
-   corresponding file. */
-
-void
-_zip_free(struct zip *za)
-{
-    int i;
-
-    if (za == NULL)
-        return;
-
-    if (za->zn)
-        free(za->zn);
-
-    if (za->zp)
-        fclose(za->zp);
-
-    _zip_cdir_free(za->cdir);
-
-    if (za->entry) {
-        for (i=0; i<za->nentry; i++) {
-            _zip_entry_free(za->entry+i);
-        }
-        free(za->entry);
-    }
-
-    for (i=0; i<za->nfile; i++) {
-        if (za->file[i]->error.zip_err == ZIP_ER_OK) {
-            _zip_error_set(&za->file[i]->error, ZIP_ER_ZIPCLOSED, 0);
-            za->file[i]->za = NULL;
-        }
-    }
-
-    free(za->file);
-
-    free(za);
-
-    return;
-}
-
-
-ZIP_EXTERN ssize_t
-zip_fread(struct zip_file *zf, void *outbuf, size_t toread)
-{
-    int ret;
-    size_t out_before, len;
-    int i;
-
-    if (!zf)
-        return -1;
-
-    if (zf->error.zip_err != 0)
-        return -1;
-
-    if ((zf->flags & ZIP_ZF_EOF) || (toread == 0))
-        return 0;
-
-    if (zf->bytes_left == 0) {
-        zf->flags |= ZIP_ZF_EOF;
-        if (zf->flags & ZIP_ZF_CRC) {
-            if (zf->crc != zf->crc_orig) {
-                _zip_error_set(&zf->error, ZIP_ER_CRC, 0);
-                return -1;
-            }
-        }
-        return 0;
-    }
-
-    if ((zf->flags & ZIP_ZF_DECOMP) == 0) {
-        ret = _zip_file_fillbuf(outbuf, toread, zf);
-        if (ret > 0) {
-            if (zf->flags & ZIP_ZF_CRC)
-                zf->crc = crc32(zf->crc, (Bytef *)outbuf, ret);
-            zf->bytes_left -= ret;
-        }
-        return ret;
-    }
-
-    zf->zstr->next_out = (Bytef *)outbuf;
-    zf->zstr->avail_out = toread;
-    out_before = zf->zstr->total_out;
-
-    /* endless loop until something has been accomplished */
-    for (;;) {
-        ret = inflate(zf->zstr, Z_SYNC_FLUSH);
-
-        switch (ret) {
-        case Z_OK:
-        case Z_STREAM_END:
-            /* all ok */
-            /* Z_STREAM_END probably won't happen, since we didn't
-               have a header */
-            len = zf->zstr->total_out - out_before;
-            if (len >= zf->bytes_left || len >= toread) {
-                if (zf->flags & ZIP_ZF_CRC)
-                    zf->crc = crc32(zf->crc, (Bytef *)outbuf, len);
-                zf->bytes_left -= len;
-                return len;
-            }
-            break;
-
-        case Z_BUF_ERROR:
-            if (zf->zstr->avail_in == 0) {
-                i = _zip_file_fillbuf(zf->buffer, BUFSIZE, zf);
-                if (i == 0) {
-                    _zip_error_set(&zf->error, ZIP_ER_INCONS, 0);
-                    return -1;
-                }
-                else if (i < 0)
-                    return -1;
-                zf->zstr->next_in = (Bytef *)zf->buffer;
-                zf->zstr->avail_in = i;
-                continue;
-            }
-            /* fallthrough */
-        case Z_NEED_DICT:
-        case Z_DATA_ERROR:
-        case Z_STREAM_ERROR:
-        case Z_MEM_ERROR:
-            _zip_error_set(&zf->error, ZIP_ER_ZLIB, ret);
-            return -1;
-        }
-    }
-}
-
-
-ZIP_EXTERN const char *
-zip_strerror(struct zip *za)
-{
-    return _zip_error_strerror(&za->error);
-}
-
-
-ZIP_EXTERN void
-zip_stat_init(struct zip_stat *st)
-{
-    st->name = NULL;
-    st->index = -1;
-    st->crc = 0;
-    st->mtime = (time_t)-1;
-    st->size = -1;
-    st->comp_size = -1;
-    st->comp_method = ZIP_CM_STORE;
-    st->encryption_method = ZIP_EM_NONE;
-}
-
-
-ZIP_EXTERN int
-zip_stat_index(struct zip *za, int index, int flags, struct zip_stat *st)
-{
-    const char *name;
-
-    if (index < 0 || index >= za->nentry) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    if ((name=zip_get_name(za, index, flags)) == NULL)
-        return -1;
-
-
-    if ((flags & ZIP_FL_UNCHANGED) == 0
-        && ZIP_ENTRY_DATA_CHANGED(za->entry+index)) {
-        if (za->entry[index].source->f(za->entry[index].source->ud,
-                                     st, sizeof(*st), ZIP_SOURCE_STAT) < 0) {
-            _zip_error_set(&za->error, ZIP_ER_CHANGED, 0);
-            return -1;
-        }
-    }
-    else {
-        if (za->cdir == NULL || index >= za->cdir->nentry) {
-            _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-            return -1;
-        }
-
-        st->crc = za->cdir->entry[index].crc;
-        st->size = za->cdir->entry[index].uncomp_size;
-        st->mtime = za->cdir->entry[index].last_mod;
-        st->comp_size = za->cdir->entry[index].comp_size;
-        st->comp_method = za->cdir->entry[index].comp_method;
-        if (za->cdir->entry[index].bitflags & ZIP_GPBF_ENCRYPTED) {
-            if (za->cdir->entry[index].bitflags & ZIP_GPBF_STRONG_ENCRYPTION) {
-                /* XXX */
-                st->encryption_method = ZIP_EM_UNKNOWN;
-            }
-            else
-                st->encryption_method = ZIP_EM_TRAD_PKWARE;
-        }
-        else
-            st->encryption_method = ZIP_EM_NONE;
-        /* st->bitflags = za->cdir->entry[index].bitflags; */
-    }
-
-    st->index = index;
-    st->name = name;
-
-    return 0;
-}
-
-
-ZIP_EXTERN int
-zip_stat(struct zip *za, const char *fname, int flags, struct zip_stat *st)
-{
-    int idx;
-
-    if ((idx=zip_name_locate(za, fname, flags)) < 0)
-        return -1;
-
-    return zip_stat_index(za, idx, flags, st);
-}
-
-
-struct read_zip {
-    struct zip_file *zf;
-    struct zip_stat st;
-    myoff_t off, len;
-};
-
-static ssize_t read_zip(void *st, void *data, size_t len,
-                        enum zip_source_cmd cmd);
-
-
-
-ZIP_EXTERN struct zip_source *
-zip_source_zip(struct zip *za, struct zip *srcza, int srcidx, int flags,
-               myoff_t start, myoff_t len)
-{
-    struct zip_error error;
-    struct zip_source *zs;
-    struct read_zip *p;
-
-    /* XXX: ZIP_FL_RECOMPRESS */
-
-    if (za == NULL)
-        return NULL;
-
-    if (srcza == NULL || start < 0 || len < -1 || srcidx < 0 || srcidx >= srcza->nentry) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    if ((flags & ZIP_FL_UNCHANGED) == 0
-        && ZIP_ENTRY_DATA_CHANGED(srcza->entry+srcidx)) {
-        _zip_error_set(&za->error, ZIP_ER_CHANGED, 0);
-        return NULL;
-    }
-
-    if (len == 0)
-        len = -1;
-
-    if (start == 0 && len == -1 && (flags & ZIP_FL_RECOMPRESS) == 0)
-        flags |= ZIP_FL_COMPRESSED;
-    else
-        flags &= ~ZIP_FL_COMPRESSED;
-
-    if ((p=(struct read_zip *)malloc(sizeof(*p))) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    _zip_error_copy(&error, &srcza->error);
-
-    if (zip_stat_index(srcza, srcidx, flags, &p->st) < 0
-        || (p->zf=zip_fopen_index(srcza, srcidx, flags)) == NULL) {
-        free(p);
-        _zip_error_copy(&za->error, &srcza->error);
-        _zip_error_copy(&srcza->error, &error);
-
-        return NULL;
-    }
-    p->off = start;
-    p->len = len;
-
-    if ((flags & ZIP_FL_COMPRESSED) == 0) {
-        p->st.size = p->st.comp_size = len;
-        p->st.comp_method = ZIP_CM_STORE;
-        p->st.crc = 0;
-    }
-
-    if ((zs=zip_source_function(za, read_zip, p)) == NULL) {
-        free(p);
-        return NULL;
-    }
-
-    return zs;
-}
-
-
-
-static ssize_t
-read_zip(void *state, void *data, size_t len, enum zip_source_cmd cmd)
-{
-    struct read_zip *z;
-    char b[8192], *buf;
-    int i, n;
-
-    z = (struct read_zip *)state;
-    buf = (char *)data;
-
-    switch (cmd) {
-    case ZIP_SOURCE_OPEN:
-        for (n=0; n<z->off; n+= i) {
-            i = (z->off-n > sizeof(b) ? sizeof(b) : z->off-n);
-            if ((i=zip_fread(z->zf, b, i)) < 0) {
-                zip_fclose(z->zf);
-                z->zf = NULL;
-                return -1;
-            }
-        }
-        return 0;
-
-    case ZIP_SOURCE_READ:
-        if (z->len != -1)
-            n = len > z->len ? z->len : len;
-        else
-            n = len;
-
-
-        if ((i=zip_fread(z->zf, buf, n)) < 0)
-            return -1;
-
-        if (z->len != -1)
-            z->len -= i;
-
-        return i;
-
-    case ZIP_SOURCE_CLOSE:
-        return 0;
-
-    case ZIP_SOURCE_STAT:
-        if (len < sizeof(z->st))
-            return -1;
-        len = sizeof(z->st);
-
-        memcpy(data, &z->st, len);
-        return len;
-
-    case ZIP_SOURCE_ERROR:
-        {
-            int *e;
-
-            if (len < sizeof(int)*2)
-                return -1;
-
-            e = (int *)data;
-            zip_file_error_get(z->zf, e, e+1);
-        }
-        return sizeof(int)*2;
-
-    case ZIP_SOURCE_FREE:
-        zip_fclose(z->zf);
-        free(z);
-        return 0;
-
-    default:
-        ;
-    }
-
-    return -1;
-}
-
-
-ZIP_EXTERN struct zip_source *
-zip_source_function(struct zip *za, zip_source_callback zcb, void *ud)
-{
-    struct zip_source *zs;
-
-    if (za == NULL)
-        return NULL;
-
-    if ((zs=(struct zip_source *)malloc(sizeof(*zs))) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    zs->f = zcb;
-    zs->ud = ud;
-
-    return zs;
-}
-
-
-ZIP_EXTERN void
-zip_source_free(struct zip_source *source)
-{
-    if (source == NULL)
-        return;
-
-    (void)source->f(source->ud, NULL, 0, ZIP_SOURCE_FREE);
-
-    free(source);
-}
-
-
-struct read_file {
-    char *fname;        /* name of file to copy from */
-    FILE *f;                /* file to copy from */
-    myoff_t off;                /* start offset of */
-    myoff_t len;                /* lengt of data to copy */
-    myoff_t remain;        /* bytes remaining to be copied */
-    int e[2];                /* error codes */
-};
-
-static ssize_t read_file(void *state, void *data, size_t len,
-                     enum zip_source_cmd cmd);
-
-
-
-ZIP_EXTERN struct zip_source *
-zip_source_filep(struct zip *za, FILE *file, myoff_t start, myoff_t len)
-{
-    if (za == NULL)
-        return NULL;
-
-    if (file == NULL || start < 0 || len < -1) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    return _zip_source_file_or_p(za, NULL, file, start, len);
-}
-
-
-
-struct zip_source *
-_zip_source_file_or_p(struct zip *za, const char *fname, FILE *file,
-                      myoff_t start, myoff_t len)
-{
-    struct read_file *f;
-    struct zip_source *zs;
-
-    if (file == NULL && fname == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_INVAL, 0);
-        return NULL;
-    }
-
-    if ((f=(struct read_file *)malloc(sizeof(struct read_file))) == NULL) {
-        _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-        return NULL;
-    }
-
-    f->fname = NULL;
-    if (fname) {
-        if ((f->fname=strdup(fname)) == NULL) {
-            _zip_error_set(&za->error, ZIP_ER_MEMORY, 0);
-            free(f);
-            return NULL;
-        }
-    }
-    f->f = file;
-    f->off = start;
-    f->len = (len ? len : -1);
-
-    if ((zs=zip_source_function(za, read_file, f)) == NULL) {
-        free(f);
-        return NULL;
-    }
-
-    return zs;
-}
-
-
-
-static ssize_t
-read_file(void *state, void *data, size_t len, enum zip_source_cmd cmd)
-{
-    struct read_file *z;
-    char *buf;
-    int i, n;
-
-    z = (struct read_file *)state;
-    buf = (char *)data;
-
-    switch (cmd) {
-    case ZIP_SOURCE_OPEN:
-        if (z->fname) {
-            if ((z->f=fopen(z->fname, "rb")) == NULL) {
-                z->e[0] = ZIP_ER_OPEN;
-                z->e[1] = errno;
-                return -1;
-            }
-        }
-
-        if (fseeko(z->f, z->off, SEEK_SET) < 0) {
-            z->e[0] = ZIP_ER_SEEK;
-            z->e[1] = errno;
-            return -1;
-        }
-        z->remain = z->len;
-        return 0;
-
-    case ZIP_SOURCE_READ:
-        if (z->remain != -1)
-            n = len > z->remain ? z->remain : len;
-        else
-            n = len;
-
-        if ((i=fread(buf, 1, n, z->f)) < 0) {
-            z->e[0] = ZIP_ER_READ;
-            z->e[1] = errno;
-            return -1;
-        }
-
-        if (z->remain != -1)
-            z->remain -= i;
-
-        return i;
-
-    case ZIP_SOURCE_CLOSE:
-        if (z->fname) {
-            fclose(z->f);
-            z->f = NULL;
-        }
-        return 0;
-
-    case ZIP_SOURCE_STAT:
-        {
-            struct zip_stat *st;
-            struct stat fst;
-            int err;
-
-            if (len < sizeof(*st))
-                return -1;
-
-            if (z->f)
-                err = fstat(fileno(z->f), &fst);
-            else
-                err = stat(z->fname, &fst);
-
-            if (err != 0) {
-                z->e[0] = ZIP_ER_READ; /* best match */
-                z->e[1] = errno;
-                return -1;
-            }
-
-            st = (struct zip_stat *)data;
-
-            zip_stat_init(st);
-            st->mtime = fst.st_mtime;
-            if (z->len != -1)
-                st->size = z->len;
-            else if ((fst.st_mode&S_IFMT) == S_IFREG)
-                st->size = fst.st_size;
-
-            return sizeof(*st);
-        }
-
-    case ZIP_SOURCE_ERROR:
-        if (len < sizeof(int)*2)
-            return -1;
-
-        memcpy(data, z->e, sizeof(int)*2);
-        return sizeof(int)*2;
-
-    case ZIP_SOURCE_FREE:
-        free(z->fname);
-        if (z->f)
-            fclose(z->f);
-        free(z);
-        return 0;
-
-    default:
-        ;
-    }
-
-    return -1;
-}
-
-
-ZIP_EXTERN int
-zip_name_locate(struct zip *za, const char *fname, int flags)
-{
-    return _zip_name_locate(za, fname, flags, &za->error);
-}
-
-
-
-int
-_zip_name_locate(struct zip *za, const char *fname, int flags,
-                 struct zip_error *error)
-{
-    int (*cmp)(const char *, const char *);
-    const char *fn, *p;
-    int i, n;
-
-    if (fname == NULL) {
-        _zip_error_set(error, ZIP_ER_INVAL, 0);
-        return -1;
-    }
-
-    cmp = (flags & ZIP_FL_NOCASE) ? strcasecmp : strcmp;
-
-    n = (flags & ZIP_FL_UNCHANGED) ? za->cdir->nentry : za->nentry;
-    for (i=0; i<n; i++) {
-        if (flags & ZIP_FL_UNCHANGED)
-            fn = za->cdir->entry[i].filename;
-        else
-            fn = _zip_get_name(za, i, flags, error);
-
-        /* newly added (partially filled) entry */
-        if (fn == NULL)
-            continue;
-
-        if (flags & ZIP_FL_NODIR) {
-            p = strrchr(fn, '/');
-            if (p)
-                fn = p+1;
-        }
-
-        if (cmp(fname, fn) == 0)
-            return i;
-    }
-
-    _zip_error_set(error, ZIP_ER_NOENT, 0);
-    return -1;
-}
-
diff --git a/tests/deps/zip-0.2.1/zip/zipfiles.nim b/tests/deps/zip-0.2.1/zip/zipfiles.nim
deleted file mode 100644
index 274587df9..000000000
--- a/tests/deps/zip-0.2.1/zip/zipfiles.nim
+++ /dev/null
@@ -1,193 +0,0 @@
-#
-#
-#            Nim's Runtime Library
-#        (c) Copyright 2012 Andreas Rumpf
-#
-#    See the file "copying.txt", included in this
-#    distribution, for details about the copyright.
-#
-
-## This module implements a zip archive creator/reader/modifier.
-
-import
-  streams, libzip, times, os, strutils
-
-const BufSize = 8 * 1024
-
-type
-  ZipArchive* = object of RootObj ## represents a zip archive
-    mode: FileMode
-    w: PZip
-{.deprecated: [TZipArchive: ZipArchive].}
-
-proc zipError(z: var ZipArchive) =
-  var e: ref IOError
-  new(e)
-  e.msg = $zip_strerror(z.w)
-  raise e
-
-proc open*(z: var ZipArchive, filename: string, mode: FileMode = fmRead): bool =
-  ## Opens a zip file for reading, writing or appending. All file modes are
-  ## supported. Returns true iff successful, false otherwise.
-  var err, flags: int32
-  case mode
-  of fmRead, fmReadWriteExisting, fmAppend: flags = 0
-  of fmWrite:
-    if existsFile(filename): removeFile(filename)
-    flags = ZIP_CREATE or ZIP_EXCL
-  of fmReadWrite: flags = ZIP_CREATE
-  z.w = zip_open(filename, flags, addr(err))
-  z.mode = mode
-  result = z.w != nil
-
-proc close*(z: var ZipArchive) =
-  ## Closes a zip file.
-  zip_close(z.w)
-
-proc createDir*(z: var ZipArchive, dir: string) =
-  ## Creates a directory within the `z` archive. This does not fail if the
-  ## directory already exists. Note that for adding a file like
-  ## ``"path1/path2/filename"`` it is not necessary
-  ## to create the ``"path/path2"`` subdirectories - it will be done
-  ## automatically by ``addFile``.
-  assert(z.mode != fmRead)
-  discard zip_add_dir(z.w, dir)
-  zip_error_clear(z.w)
-
-proc addFile*(z: var ZipArchive, dest, src: string) =
-  ## Adds the file `src` to the archive `z` with the name `dest`. `dest`
-  ## may contain a path that will be created.
-  assert(z.mode != fmRead)
-  if not fileExists(src):
-    raise newException(IOError, "File '" & src & "' does not exist")
-  var zipsrc = zip_source_file(z.w, src, 0, -1)
-  if zipsrc == nil:
-    #echo("Dest: " & dest)
-    #echo("Src: " & src)
-    zipError(z)
-  if zip_add(z.w, dest, zipsrc) < 0'i32:
-    zip_source_free(zipsrc)
-    zipError(z)
-
-proc addFile*(z: var ZipArchive, file: string) =
-  ## A shortcut for ``addFile(z, file, file)``, i.e. the name of the source is
-  ## the name of the destination.
-  addFile(z, file, file)
-
-proc mySourceCallback(state, data: pointer, len: int,
-                      cmd: ZipSourceCmd): int {.cdecl.} =
-  var src = cast[Stream](state)
-  case cmd
-  of ZIP_SOURCE_OPEN:
-    if src.setPositionImpl != nil: setPosition(src, 0) # reset
-  of ZIP_SOURCE_READ:
-    result = readData(src, data, len)
-  of ZIP_SOURCE_CLOSE: close(src)
-  of ZIP_SOURCE_STAT:
-    var stat = cast[PZipStat](data)
-    zip_stat_init(stat)
-    stat.size = high(int32)-1 # we don't know the size
-    stat.mtime = getTime()
-    result = sizeof(ZipStat)
-  of ZIP_SOURCE_ERROR:
-    var err = cast[ptr array[0..1, cint]](data)
-    err[0] = ZIP_ER_INTERNAL
-    err[1] = 0
-    result = 2*sizeof(cint)
-  of constZIP_SOURCE_FREE: GC_unref(src)
-  of ZIP_SOURCE_SUPPORTS:
-    # By default a read-only source is supported, which suits us.
-    result = -1
-  else:
-    # An unknown command, failing
-    result = -1
-
-proc addFile*(z: var ZipArchive, dest: string, src: Stream) =
-  ## Adds a file named with `dest` to the archive `z`. `dest`
-  ## may contain a path. The file's content is read from the `src` stream.
-  assert(z.mode != fmRead)
-  GC_ref(src)
-  var zipsrc = zip_source_function(z.w, mySourceCallback, cast[pointer](src))
-  if zipsrc == nil: zipError(z)
-  if zip_add(z.w, dest, zipsrc) < 0'i32:
-    zip_source_free(zipsrc)
-    zipError(z)
-
-# -------------- zip file stream ---------------------------------------------
-
-type
-  TZipFileStream = object of StreamObj
-    f: PZipFile
-    atEnd: bool
-
-  PZipFileStream* =
-    ref TZipFileStream ## a reader stream of a file within a zip archive
-
-proc fsClose(s: Stream) = zip_fclose(PZipFileStream(s).f)
-proc fsAtEnd(s: Stream): bool = PZipFileStream(s).atEnd
-proc fsReadData(s: Stream, buffer: pointer, bufLen: int): int =
-  result = zip_fread(PZipFileStream(s).f, buffer, bufLen)
-  if result == 0:
-    PZipFileStream(s).atEnd = true
-
-proc newZipFileStream(f: PZipFile): PZipFileStream =
-  new(result)
-  result.f = f
-  result.atEnd = false
-  result.closeImpl = fsClose
-  result.readDataImpl = fsReadData
-  result.atEndImpl = fsAtEnd
-  # other methods are nil!
-
-# ----------------------------------------------------------------------------
-
-proc getStream*(z: var ZipArchive, filename: string): PZipFileStream =
-  ## returns a stream that can be used to read the file named `filename`
-  ## from the archive `z`. Returns nil in case of an error.
-  ## The returned stream does not support the `setPosition`, `getPosition`,
-  ## `writeData` or `atEnd` methods.
-  var x = zip_fopen(z.w, filename, 0'i32)
-  if x != nil: result = newZipFileStream(x)
-
-iterator walkFiles*(z: var ZipArchive): string =
-  ## walks over all files in the archive `z` and returns the filename
-  ## (including the path).
-  var i = 0'i32
-  var num = zip_get_num_files(z.w)
-  while i < num:
-    yield $zip_get_name(z.w, i, 0'i32)
-    inc(i)
-
-proc extractFile*(z: var ZipArchive, srcFile: string, dest: Stream) =
-  ## extracts a file from the zip archive `z` to the destination stream.
-  var buf: array[BufSize, byte]
-  var strm = getStream(z, srcFile)
-  while true:
-    let bytesRead = strm.readData(addr(buf[0]), buf.len)
-    if bytesRead <= 0: break
-    dest.writeData(addr(buf[0]), bytesRead)
-
-  dest.flush()
-  strm.close()
-
-proc extractFile*(z: var ZipArchive, srcFile: string, dest: string) =
-  ## extracts a file from the zip archive `z` to the destination filename.
-  var file = newFileStream(dest, fmWrite)
-  if file.isNil:
-    raise newException(IOError, "Failed to create output file: " & dest)
-  extractFile(z, srcFile, file)
-  file.close()
-
-proc extractAll*(z: var ZipArchive, dest: string) =
-  ## extracts all files from archive `z` to the destination directory.
-  createDir(dest)
-  for file in walkFiles(z):
-    if file.contains("/"):
-      createDir(dest / file[0..file.rfind("/")])
-    extractFile(z, file, dest / file)
-
-when not defined(testing) and true:
-  var zip: ZipArchive
-  if not zip.open("nim-0.11.0.zip"):
-    raise newException(IOError, "opening zip failed")
-  zip.extractAll("test")
diff --git a/tests/deps/zip-0.2.1/zip/zlib.nim b/tests/deps/zip-0.2.1/zip/zlib.nim
deleted file mode 100644
index f41ed5cfe..000000000
--- a/tests/deps/zip-0.2.1/zip/zlib.nim
+++ /dev/null
@@ -1,425 +0,0 @@
-# Converted from Pascal
-
-## Interface to the zlib http://www.zlib.net/ compression library.
-
-when defined(windows):
-  const libz = "zlib1.dll"
-elif defined(macosx):
-  const libz = "libz.dylib"
-else:
-  const libz = "libz.so.1"
-
-type
-  Uint* = int32
-  Ulong* = int
-  Ulongf* = int
-  Pulongf* = ptr Ulongf
-  ZOffT* = int32
-  Pbyte* = cstring
-  Pbytef* = cstring
-  Allocfunc* = proc (p: pointer, items: Uint, size: Uint): pointer{.cdecl.}
-  FreeFunc* = proc (p: pointer, address: pointer){.cdecl.}
-  InternalState*{.final, pure.} = object
-  PInternalState* = ptr InternalState
-  ZStream*{.final, pure.} = object
-    nextIn*: Pbytef
-    availIn*: Uint
-    totalIn*: Ulong
-    nextOut*: Pbytef
-    availOut*: Uint
-    totalOut*: Ulong
-    msg*: Pbytef
-    state*: PInternalState
-    zalloc*: Allocfunc
-    zfree*: FreeFunc
-    opaque*: pointer
-    dataType*: int32
-    adler*: Ulong
-    reserved*: Ulong
-
-  ZStreamRec* = ZStream
-  PZstream* = ptr ZStream
-  GzFile* = pointer
-  ZStreamHeader* = enum
-    DETECT_STREAM,
-    RAW_DEFLATE,
-    ZLIB_STREAM,
-    GZIP_STREAM
-
-  ZlibStreamError* = object of Exception
-
-{.deprecated: [TInternalState: InternalState, TAllocfunc: Allocfunc,
-              TFreeFunc: FreeFunc, TZStream: ZStream, TZStreamRec: ZStreamRec].}
-
-const
-  Z_NO_FLUSH* = 0
-  Z_PARTIAL_FLUSH* = 1
-  Z_SYNC_FLUSH* = 2
-  Z_FULL_FLUSH* = 3
-  Z_FINISH* = 4
-  Z_OK* = 0
-  Z_STREAM_END* = 1
-  Z_NEED_DICT* = 2
-  Z_ERRNO* = -1
-  Z_STREAM_ERROR* = -2
-  Z_DATA_ERROR* = -3
-  Z_MEM_ERROR* = -4
-  Z_BUF_ERROR* = -5
-  Z_VERSION_ERROR* = -6
-  Z_NO_COMPRESSION* = 0
-  Z_BEST_SPEED* = 1
-  Z_BEST_COMPRESSION* = 9
-  Z_DEFAULT_COMPRESSION* = -1
-  Z_FILTERED* = 1
-  Z_HUFFMAN_ONLY* = 2
-  Z_DEFAULT_STRATEGY* = 0
-  Z_BINARY* = 0
-  Z_ASCII* = 1
-  Z_UNKNOWN* = 2
-  Z_DEFLATED* = 8
-  Z_NULL* = 0
-  Z_MEM_LEVEL* = 8
-  MAX_WBITS* = 15
-
-proc zlibVersion*(): cstring{.cdecl, dynlib: libz, importc: "zlibVersion".}
-proc deflate*(strm: var ZStream, flush: int32): int32{.cdecl, dynlib: libz,
-    importc: "deflate".}
-proc deflateEnd*(strm: var ZStream): int32{.cdecl, dynlib: libz,
-    importc: "deflateEnd".}
-proc inflate*(strm: var ZStream, flush: int32): int32{.cdecl, dynlib: libz,
-    importc: "inflate".}
-proc inflateEnd*(strm: var ZStream): int32{.cdecl, dynlib: libz,
-    importc: "inflateEnd".}
-proc deflateSetDictionary*(strm: var ZStream, dictionary: Pbytef,
-                           dictLength: Uint): int32{.cdecl, dynlib: libz,
-    importc: "deflateSetDictionary".}
-proc deflateCopy*(dest, source: var ZStream): int32{.cdecl, dynlib: libz,
-    importc: "deflateCopy".}
-proc deflateReset*(strm: var ZStream): int32{.cdecl, dynlib: libz,
-    importc: "deflateReset".}
-proc deflateParams*(strm: var ZStream, level: int32, strategy: int32): int32{.
-    cdecl, dynlib: libz, importc: "deflateParams".}
-proc inflateSetDictionary*(strm: var ZStream, dictionary: Pbytef,
-                           dictLength: Uint): int32{.cdecl, dynlib: libz,
-    importc: "inflateSetDictionary".}
-proc inflateSync*(strm: var ZStream): int32{.cdecl, dynlib: libz,
-    importc: "inflateSync".}
-proc inflateReset*(strm: var ZStream): int32{.cdecl, dynlib: libz,
-    importc: "inflateReset".}
-proc compress*(dest: Pbytef, destLen: Pulongf, source: Pbytef, sourceLen: Ulong): cint{.
-    cdecl, dynlib: libz, importc: "compress".}
-proc compress2*(dest: Pbytef, destLen: Pulongf, source: Pbytef,
-                sourceLen: Ulong, level: cint): cint{.cdecl, dynlib: libz,
-    importc: "compress2".}
-proc uncompress*(dest: Pbytef, destLen: Pulongf, source: Pbytef,
-                 sourceLen: Ulong): cint{.cdecl, dynlib: libz,
-    importc: "uncompress".}
-proc compressBound*(sourceLen: Ulong): Ulong {.cdecl, dynlib: libz, importc.}
-proc gzopen*(path: cstring, mode: cstring): GzFile{.cdecl, dynlib: libz,
-    importc: "gzopen".}
-proc gzdopen*(fd: int32, mode: cstring): GzFile{.cdecl, dynlib: libz,
-    importc: "gzdopen".}
-proc gzsetparams*(thefile: GzFile, level: int32, strategy: int32): int32{.cdecl,
-    dynlib: libz, importc: "gzsetparams".}
-proc gzread*(thefile: GzFile, buf: pointer, length: int): int32{.cdecl,
-    dynlib: libz, importc: "gzread".}
-proc gzwrite*(thefile: GzFile, buf: pointer, length: int): int32{.cdecl,
-    dynlib: libz, importc: "gzwrite".}
-proc gzprintf*(thefile: GzFile, format: Pbytef): int32{.varargs, cdecl,
-    dynlib: libz, importc: "gzprintf".}
-proc gzputs*(thefile: GzFile, s: Pbytef): int32{.cdecl, dynlib: libz,
-    importc: "gzputs".}
-proc gzgets*(thefile: GzFile, buf: Pbytef, length: int32): Pbytef{.cdecl,
-    dynlib: libz, importc: "gzgets".}
-proc gzputc*(thefile: GzFile, c: char): char{.cdecl, dynlib: libz,
-    importc: "gzputc".}
-proc gzgetc*(thefile: GzFile): char{.cdecl, dynlib: libz, importc: "gzgetc".}
-proc gzflush*(thefile: GzFile, flush: int32): int32{.cdecl, dynlib: libz,
-    importc: "gzflush".}
-proc gzseek*(thefile: GzFile, offset: ZOffT, whence: int32): ZOffT{.cdecl,
-    dynlib: libz, importc: "gzseek".}
-proc gzrewind*(thefile: GzFile): int32{.cdecl, dynlib: libz, importc: "gzrewind".}
-proc gztell*(thefile: GzFile): ZOffT{.cdecl, dynlib: libz, importc: "gztell".}
-proc gzeof*(thefile: GzFile): int {.cdecl, dynlib: libz, importc: "gzeof".}
-proc gzclose*(thefile: GzFile): int32{.cdecl, dynlib: libz, importc: "gzclose".}
-proc gzerror*(thefile: GzFile, errnum: var int32): Pbytef{.cdecl, dynlib: libz,
-    importc: "gzerror".}
-proc adler32*(adler: Ulong, buf: Pbytef, length: Uint): Ulong{.cdecl,
-    dynlib: libz, importc: "adler32".}
-  ## **Warning**: Adler-32 requires at least a few hundred bytes to get rolling.
-proc crc32*(crc: Ulong, buf: Pbytef, length: Uint): Ulong{.cdecl, dynlib: libz,
-    importc: "crc32".}
-proc deflateInitu*(strm: var ZStream, level: int32, version: cstring,
-                   streamSize: int32): int32{.cdecl, dynlib: libz,
-    importc: "deflateInit_".}
-proc inflateInitu*(strm: var ZStream, version: cstring,
-                   streamSize: int32): int32 {.
-    cdecl, dynlib: libz, importc: "inflateInit_".}
-proc deflateInit*(strm: var ZStream, level: int32): int32
-proc inflateInit*(strm: var ZStream): int32
-proc deflateInit2u*(strm: var ZStream, level: int32, `method`: int32,
-                    windowBits: int32, memLevel: int32, strategy: int32,
-                    version: cstring, streamSize: int32): int32 {.cdecl,
-                    dynlib: libz, importc: "deflateInit2_".}
-proc inflateInit2u*(strm: var ZStream, windowBits: int32, version: cstring,
-                    streamSize: int32): int32{.cdecl, dynlib: libz,
-    importc: "inflateInit2_".}
-proc deflateInit2*(strm: var ZStream,
-                   level, `method`, windowBits, memLevel,
-                   strategy: int32): int32
-proc inflateInit2*(strm: var ZStream, windowBits: int32): int32
-proc zError*(err: int32): cstring{.cdecl, dynlib: libz, importc: "zError".}
-proc inflateSyncPoint*(z: PZstream): int32{.cdecl, dynlib: libz,
-    importc: "inflateSyncPoint".}
-proc getCrcTable*(): pointer{.cdecl, dynlib: libz, importc: "get_crc_table".}
-
-proc deflateBound*(strm: var ZStream, sourceLen: ULong): ULong {.cdecl,
-        dynlib: libz, importc: "deflateBound".}
-
-proc deflateInit(strm: var ZStream, level: int32): int32 =
-  result = deflateInitu(strm, level, zlibVersion(), sizeof(ZStream).cint)
-
-proc inflateInit(strm: var ZStream): int32 =
-  result = inflateInitu(strm, zlibVersion(), sizeof(ZStream).cint)
-
-proc deflateInit2(strm: var ZStream,
-                  level, `method`, windowBits, memLevel,
-                  strategy: int32): int32 =
-  result = deflateInit2u(strm, level, `method`, windowBits, memLevel,
-                         strategy, zlibVersion(), sizeof(ZStream).cint)
-
-proc inflateInit2(strm: var ZStream, windowBits: int32): int32 =
-  result = inflateInit2u(strm, windowBits, zlibVersion(),
-                         sizeof(ZStream).cint)
-
-proc zlibAllocMem*(appData: pointer, items, size: int): pointer {.cdecl.} =
-  result = alloc(items * size)
-
-proc zlibFreeMem*(appData, `block`: pointer) {.cdecl.} =
-  dealloc(`block`)
-
-
-proc compress*(sourceBuf: cstring; sourceLen: int; level=Z_DEFAULT_COMPRESSION; stream=GZIP_STREAM): string =
-  ## Given a cstring, returns its deflated version with an optional header.
-  ##
-  ## Valid argument for ``stream`` are
-  ##   - ``ZLIB_STREAM`` - add a zlib header and footer.
-  ##   - ``GZIP_STREAM`` - add a basic gzip header and footer.
-  ##   - ``RAW_DEFLATE`` - no header is generated.
-  ##
-  ## Passing a nil cstring will crash this proc in release mode and assert in
-  ## debug mode.
-  ##
-  ## Compression level can be set with ``level`` argument. Currently
-  ## ``Z_DEFAULT_COMPRESSION`` is 6.
-  ##
-  ## Returns "" on failure.
-  assert(not sourceBuf.isNil)
-  assert(sourceLen >= 0)
-
-  var z: ZStream
-  var windowBits = MAX_WBITS
-  case (stream)
-  of RAW_DEFLATE: windowBits = -MAX_WBITS
-  of GZIP_STREAM: windowBits = MAX_WBITS + 16
-  of ZLIB_STREAM, DETECT_STREAM:
-    discard # DETECT_STREAM defaults to ZLIB_STREAM
-
-  var status = deflateInit2(z, level.int32, Z_DEFLATED.int32,
-                               windowBits.int32, Z_MEM_LEVEL.int32,
-                               Z_DEFAULT_STRATEGY.int32)
-  case status
-  of Z_OK: discard
-  of Z_MEM_ERROR: raise newException(OutOfMemError, "")
-  of Z_STREAM_ERROR: raise newException(ZlibStreamError, "invalid zlib stream parameter!")
-  of Z_VERSION_ERROR: raise newException(ZlibStreamError, "zlib version mismatch!")
-  else: raise newException(ZlibStreamError, "Unkown error(" & $status & ") : " & $z.msg)
-
-  let space = deflateBound(z, sourceLen)
-  var compressed = newStringOfCap(space)
-  z.next_in = sourceBuf
-  z.avail_in = sourceLen.Uint
-  z.next_out = addr(compressed[0])
-  z.avail_out = space.Uint
-
-  status = deflate(z, Z_FINISH)
-  if status != Z_STREAM_END:
-    discard deflateEnd(z) # cleanup allocated ressources
-    raise newException(ZlibStreamError, "Invalid stream state(" & $status & ") : " & $z.msg)
-
-  status = deflateEnd(z)
-  if status != Z_OK: # cleanup allocated ressources
-    raise newException(ZlibStreamError, "Invalid stream state(" & $status & ") : " & $z.msg)
-
-  compressed.setLen(z.total_out)
-  swap(result, compressed)
-
-proc compress*(input: string; level=Z_DEFAULT_COMPRESSION; stream=GZIP_STREAM): string =
-  ## Given a string, returns its deflated version with an optional header.
-  ##
-  ## Valid arguments for ``stream`` are
-  ##  - ``ZLIB_STREAM`` - add a zlib header and footer.
-  ##  - ``GZIP_STREAM`` - add a basic gzip header and footer.
-  ##  - ``RAW_DEFLATE`` - no header is generated.
-  ##
-  ## Compression level can be set with ``level`` argument. Currently
-  ## ``Z_DEFAULT_COMPRESSION`` is 6.
-  ##
-  ## Returns "" on failure.
-  result = compress(input, input.len, level, stream)
-
-proc uncompress*(sourceBuf: cstring, sourceLen: Natural; stream=DETECT_STREAM): string =
-  ## Given a deflated buffer returns its inflated content as a string.
-  ##
-  ## Valid arguments for ``stream`` are
-  ##   - ``DETECT_STREAM`` - detect if zlib or gzip header is present
-  ##     and decompress stream. Fail on raw deflate stream.
-  ##   - ``ZLIB_STREAM`` - decompress a zlib stream.
-  ##   - ``GZIP_STREAM`` - decompress a gzip stream.
-  ##   - ``RAW_DEFLATE`` - decompress a raw deflate stream.
-  ##
-  ## Passing a nil cstring will crash this proc in release mode and assert in
-  ## debug mode.
-  ##
-  ## Returns "" on problems. Failure is a very loose concept, it could be you
-  ## passing a non deflated string, or it could mean not having enough memory
-  ## for the inflated version.
-  ##
-  ## The uncompression algorithm is based on http://zlib.net/zpipe.c.
-  assert(not sourceBuf.isNil)
-  assert(sourceLen >= 0)
-  var z: ZStream
-  var decompressed: string = ""
-  var sbytes = 0
-  var wbytes = 0
-  ##  allocate inflate state
-
-  z.availIn = 0
-  var wbits = case (stream)
-  of RAW_DEFLATE:  -MAX_WBITS
-  of ZLIB_STREAM:   MAX_WBITS
-  of GZIP_STREAM:   MAX_WBITS + 16
-  of DETECT_STREAM: MAX_WBITS + 32
-
-  var status = inflateInit2(z, wbits.int32)
-
-  case status
-  of Z_OK: discard
-  of Z_MEM_ERROR: raise newException(OutOfMemError, "")
-  of Z_STREAM_ERROR: raise newException(ZlibStreamError, "invalid zlib stream parameter!")
-  of Z_VERSION_ERROR: raise newException(ZlibStreamError, "zlib version mismatch!")
-  else: raise newException(ZlibStreamError, "Unkown error(" & $status & ") : " & $z.msg)
-
-  # run loop until all input is consumed.
-  # handle concatenated deflated stream with header.
-  while true:
-    z.availIn = (sourceLen - sbytes).int32
-
-    # no more input available
-    if (sourceLen - sbytes) <= 0: break
-    z.nextIn = sourceBuf[sbytes].unsafeaddr
-
-    #  run inflate() on available input until output buffer is full
-    while true:
-      # if written bytes >= output size : resize output
-      if wbytes >= decompressed.len:
-        let cur_outlen = decompressed.len
-        let new_outlen = if decompressed.len == 0: sourceLen*2 else: decompressed.len*2
-        if new_outlen < cur_outlen: # unsigned integer overflow, buffer too large
-          discard inflateEnd(z);
-          raise newException(OverflowError, "zlib stream decompressed size is too large! (size > " & $int.high & ")")
-
-        decompressed.setLen(new_outlen)
-
-      # available space for decompression
-      let space = decompressed.len - wbytes
-      z.availOut = space.Uint
-      z.nextOut = decompressed[wbytes].addr
-
-      status = inflate(z, Z_NO_FLUSH)
-      if status.int8 notin {Z_OK.int8, Z_STREAM_END.int8, Z_BUF_ERROR.int8}:
-        discard inflateEnd(z)
-        case status
-        of Z_MEM_ERROR: raise newException(OutOfMemError, "")
-        of Z_DATA_ERROR: raise newException(ZlibStreamError, "invalid zlib stream parameter!")
-        else: raise newException(ZlibStreamError, "Unkown error(" & $status & ") : " & $z.msg)
-
-      # add written bytes, if any.
-      wbytes += space - z.availOut.int
-
-      # may need more input
-      if not (z.availOut == 0): break
-
-    #  inflate() says stream is done
-    if (status == Z_STREAM_END):
-      # may have another stream concatenated
-      if z.availIn != 0:
-        sbytes = sourceLen - z.availIn # add consumed bytes
-        if inflateReset(z) != Z_OK: # reset zlib struct and try again
-          raise newException(ZlibStreamError, "Invalid stream state(" & $status & ") : " & $z.msg)
-      else:
-        break # end of decompression
-
-  #  clean up and don't care about any error
-  discard inflateEnd(z)
-
-  if status != Z_STREAM_END:
-    raise newException(ZlibStreamError, "Invalid stream state(" & $status & ") : " & $z.msg)
-
-  decompressed.setLen(wbytes)
-  swap(result, decompressed)
-
-
-proc uncompress*(sourceBuf: string; stream=DETECT_STREAM): string =
-  ## Given a GZIP-ed string return its inflated content.
-  ##
-  ## Valid arguments for ``stream`` are
-  ##   - ``DETECT_STREAM`` - detect if zlib or gzip header is present
-  ##     and decompress stream. Fail on raw deflate stream.
-  ##   - ``ZLIB_STREAM`` - decompress a zlib stream.
-  ##   - ``GZIP_STREAM`` - decompress a gzip stream.
-  ##   - ``RAW_DEFLATE`` - decompress a raw deflate stream.
-  ##
-  ## Returns "" on failure.
-  result = uncompress(sourceBuf, sourceBuf.len, stream)
-
-
-
-proc deflate*(buffer: var string; level=Z_DEFAULT_COMPRESSION; stream=GZIP_STREAM): bool {.discardable.} =
-  ## Convenience proc which deflates a string and insert an optional header/footer.
-  ##
-  ## Valid arguments for ``stream`` are
-  ##   - ``ZLIB_STREAM`` - add a zlib header and footer.
-  ##   - ``GZIP_STREAM`` - add a basic gzip header and footer.
-  ##   - ``RAW_DEFLATE`` - no header is generated.
-  ##
-  ## Compression level can be set with ``level`` argument. Currently
-  ## ``Z_DEFAULT_COMPRESSION`` is 6.
-  ##
-  ## Returns true if `buffer` was successfully deflated otherwise the buffer is untouched.
-
-  var temp = compress(addr(buffer[0]), buffer.len, level, stream)
-  if temp.len != 0:
-    swap(buffer, temp)
-    result = true
-
-proc inflate*(buffer: var string; stream=DETECT_STREAM): bool {.discardable.} =
-  ## Convenience proc which inflates a string containing compressed data
-  ## with an optional header.
-  ##
-  ## Valid argument for ``stream`` are:
-  ##   - ``DETECT_STREAM`` - detect if zlib or gzip header is present
-  ##     and decompress stream. Fail on raw deflate stream.
-  ##   - ``ZLIB_STREAM`` - decompress a zlib stream.
-  ##   - ``GZIP_STREAM`` - decompress a gzip stream.
-  ##   - ``RAW_DEFLATE`` - decompress a raw deflate stream.
-  ##
-  ## It is ok to pass a buffer which doesn't contain deflated data,
-  ## in this case the proc won't modify the buffer.
-  ##
-  ## Returns true if `buffer` was successfully inflated.
- 
-  var temp = uncompress(addr(buffer[0]), buffer.len, stream)
-  if temp.len != 0:
-    swap(buffer, temp)
-    result = true
diff --git a/tests/deps/zip-0.2.1/zip/zzip.nim b/tests/deps/zip-0.2.1/zip/zzip.nim
deleted file mode 100644
index 553970e0c..000000000
--- a/tests/deps/zip-0.2.1/zip/zzip.nim
+++ /dev/null
@@ -1,176 +0,0 @@
-#
-#
-#            Nim's Runtime Library
-#        (c) Copyright 2008 Andreas Rumpf
-#
-#    See the file "copying.txt", included in this
-#    distribution, for details about the copyright.
-#
-
-## This module is an interface to the zzip library.
-
-#   Author:
-#   Guido Draheim <guidod@gmx.de>
-#   Tomi Ollila <Tomi.Ollila@iki.fi>
-#   Copyright (c) 1999,2000,2001,2002,2003,2004 Guido Draheim
-#          All rights reserved,
-#             usage allowed under the restrictions of the
-#         Lesser GNU General Public License
-#             or alternatively the restrictions
-#             of the Mozilla Public License 1.1
-
-when defined(windows):
-  const
-    dllname = "zzip.dll"
-else:
-  const
-    dllname = "libzzip.so"
-
-type
-  TZZipError* = int32 # Name conflict if we drop the `T`
-
-const
-  ZZIP_ERROR* = -4096'i32
-  ZZIP_NO_ERROR* = 0'i32            # no error, may be used if user sets it.
-  ZZIP_OUTOFMEM* = ZZIP_ERROR - 20'i32  # out of memory
-  ZZIP_DIR_OPEN* = ZZIP_ERROR - 21'i32  # failed to open zipfile, see errno for details
-  ZZIP_DIR_STAT* = ZZIP_ERROR - 22'i32  # failed to fstat zipfile, see errno for details
-  ZZIP_DIR_SEEK* = ZZIP_ERROR - 23'i32  # failed to lseek zipfile, see errno for details
-  ZZIP_DIR_READ* = ZZIP_ERROR - 24'i32  # failed to read zipfile, see errno for details
-  ZZIP_DIR_TOO_SHORT* = ZZIP_ERROR - 25'i32
-  ZZIP_DIR_EDH_MISSING* = ZZIP_ERROR - 26'i32
-  ZZIP_DIRSIZE* = ZZIP_ERROR - 27'i32
-  ZZIP_ENOENT* = ZZIP_ERROR - 28'i32
-  ZZIP_UNSUPP_COMPR* = ZZIP_ERROR - 29'i32
-  ZZIP_CORRUPTED* = ZZIP_ERROR - 31'i32
-  ZZIP_UNDEF* = ZZIP_ERROR - 32'i32
-  ZZIP_DIR_LARGEFILE* = ZZIP_ERROR - 33'i32
-
-  ZZIP_CASELESS* = 1'i32 shl 12'i32
-  ZZIP_NOPATHS* = 1'i32 shl 13'i32
-  ZZIP_PREFERZIP* = 1'i32 shl 14'i32
-  ZZIP_ONLYZIP* = 1'i32 shl 16'i32
-  ZZIP_FACTORY* = 1'i32 shl 17'i32
-  ZZIP_ALLOWREAL* = 1'i32 shl 18'i32
-  ZZIP_THREADED* = 1'i32 shl 19'i32
-
-type
-  ZZipDir* {.final, pure.} = object
-  ZZipFile* {.final, pure.} = object
-  ZZipPluginIO* {.final, pure.} = object
-
-  ZZipDirent* {.final, pure.} = object
-    d_compr*: int32  ## compression method
-    d_csize*: int32  ## compressed size
-    st_size*: int32  ## file size / decompressed size
-    d_name*: cstring ## file name / strdupped name
-
-  ZZipStat* = ZZipDirent
-{.deprecated: [TZZipDir: ZzipDir, TZZipFile: ZzipFile,
-              TZZipPluginIO: ZzipPluginIO, TZZipDirent: ZzipDirent,
-              TZZipStat: ZZipStat].}
-
-proc zzip_strerror*(errcode: int32): cstring  {.cdecl, dynlib: dllname,
-    importc: "zzip_strerror".}
-proc zzip_strerror_of*(dir: ptr ZZipDir): cstring  {.cdecl, dynlib: dllname,
-    importc: "zzip_strerror_of".}
-proc zzip_errno*(errcode: int32): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_errno".}
-
-proc zzip_geterror*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_error".}
-proc zzip_seterror*(dir: ptr ZZipDir, errcode: int32) {.cdecl, dynlib: dllname,
-    importc: "zzip_seterror".}
-proc zzip_compr_str*(compr: int32): cstring {.cdecl, dynlib: dllname,
-    importc: "zzip_compr_str".}
-proc zzip_dirhandle*(fp: ptr ZZipFile): ptr ZZipDir {.cdecl, dynlib: dllname,
-    importc: "zzip_dirhandle".}
-proc zzip_dirfd*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_dirfd".}
-proc zzip_dir_real*(dir: ptr ZZipDir): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_dir_real".}
-proc zzip_file_real*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_file_real".}
-proc zzip_realdir*(dir: ptr ZZipDir): pointer {.cdecl, dynlib: dllname,
-    importc: "zzip_realdir".}
-proc zzip_realfd*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_realfd".}
-
-proc zzip_dir_alloc*(fileext: cstringArray): ptr ZZipDir {.cdecl,
-    dynlib: dllname, importc: "zzip_dir_alloc".}
-proc zzip_dir_free*(para1: ptr ZZipDir): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_dir_free".}
-
-proc zzip_dir_fdopen*(fd: int32, errcode_p: ptr TZZipError): ptr ZZipDir {.cdecl,
-    dynlib: dllname, importc: "zzip_dir_fdopen".}
-proc zzip_dir_open*(filename: cstring, errcode_p: ptr TZZipError): ptr ZZipDir {.
-    cdecl, dynlib: dllname, importc: "zzip_dir_open".}
-proc zzip_dir_close*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname,
-    importc: "zzip_dir_close".}
-proc zzip_dir_read*(dir: ptr ZZipDir, dirent: ptr ZZipDirent): int32 {.cdecl,
-    dynlib: dllname, importc: "zzip_dir_read".}
-
-proc zzip_opendir*(filename: cstring): ptr ZZipDir {.cdecl, dynlib: dllname,
-    importc: "zzip_opendir".}
-proc zzip_closedir*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname,
-    importc: "zzip_closedir".}
-proc zzip_readdir*(dir: ptr ZZipDir): ptr ZZipDirent {.cdecl, dynlib: dllname,
-    importc: "zzip_readdir".}
-proc zzip_rewinddir*(dir: ptr ZZipDir) {.cdecl, dynlib: dllname,
-                                      importc: "zzip_rewinddir".}
-proc zzip_telldir*(dir: ptr ZZipDir): int {.cdecl, dynlib: dllname,
-    importc: "zzip_telldir".}
-proc zzip_seekdir*(dir: ptr ZZipDir, offset: int) {.cdecl, dynlib: dllname,
-    importc: "zzip_seekdir".}
-
-proc zzip_file_open*(dir: ptr ZZipDir, name: cstring, flags: int32): ptr ZZipFile {.
-    cdecl, dynlib: dllname, importc: "zzip_file_open".}
-proc zzip_file_close*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname,
-    importc: "zzip_file_close".}
-proc zzip_file_read*(fp: ptr ZZipFile, buf: pointer, length: int): int {.
-    cdecl, dynlib: dllname, importc: "zzip_file_read".}
-proc zzip_open*(name: cstring, flags: int32): ptr ZZipFile {.cdecl,
-    dynlib: dllname, importc: "zzip_open".}
-proc zzip_close*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname,
-    importc: "zzip_close".}
-proc zzip_read*(fp: ptr ZZipFile, buf: pointer, length: int): int {.
-    cdecl, dynlib: dllname, importc: "zzip_read".}
-
-proc zzip_freopen*(name: cstring, mode: cstring, para3: ptr ZZipFile): ptr ZZipFile {.
-    cdecl, dynlib: dllname, importc: "zzip_freopen".}
-proc zzip_fopen*(name: cstring, mode: cstring): ptr ZZipFile {.cdecl,
-    dynlib: dllname, importc: "zzip_fopen".}
-proc zzip_fread*(p: pointer, size: int, nmemb: int,
-                 file: ptr ZZipFile): int {.cdecl, dynlib: dllname,
-    importc: "zzip_fread".}
-proc zzip_fclose*(fp: ptr ZZipFile) {.cdecl, dynlib: dllname,
-    importc: "zzip_fclose".}
-
-proc zzip_rewind*(fp: ptr ZZipFile): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_rewind".}
-proc zzip_seek*(fp: ptr ZZipFile, offset: int, whence: int32): int {.
-    cdecl, dynlib: dllname, importc: "zzip_seek".}
-proc zzip_tell*(fp: ptr ZZipFile): int {.cdecl, dynlib: dllname,
-    importc: "zzip_tell".}
-
-proc zzip_dir_stat*(dir: ptr ZZipDir, name: cstring, zs: ptr ZZipStat,
-                    flags: int32): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_dir_stat".}
-proc zzip_file_stat*(fp: ptr ZZipFile, zs: ptr ZZipStat): int32 {.cdecl,
-    dynlib: dllname, importc: "zzip_file_stat".}
-proc zzip_fstat*(fp: ptr ZZipFile, zs: ptr ZZipStat): int32 {.cdecl, dynlib: dllname,
-    importc: "zzip_fstat".}
-
-proc zzip_open_shared_io*(stream: ptr ZZipFile, name: cstring,
-                          o_flags: int32, o_modes: int32, ext: cstringArray,
-                          io: ptr ZZipPluginIO): ptr ZZipFile {.cdecl,
-    dynlib: dllname, importc: "zzip_open_shared_io".}
-proc zzip_open_ext_io*(name: cstring, o_flags: int32, o_modes: int32,
-                       ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipFile {.
-    cdecl, dynlib: dllname, importc: "zzip_open_ext_io".}
-proc zzip_opendir_ext_io*(name: cstring, o_modes: int32,
-                          ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipDir {.
-    cdecl, dynlib: dllname, importc: "zzip_opendir_ext_io".}
-proc zzip_dir_open_ext_io*(filename: cstring, errcode_p: ptr TZZipError,
-                           ext: cstringArray, io: ptr ZZipPluginIO): ptr ZZipDir {.
-    cdecl, dynlib: dllname, importc: "zzip_dir_open_ext_io".}
diff --git a/tests/destructor/const_smart_ptr.nim b/tests/destructor/const_smart_ptr.nim
index 4d8c7c9a3..25dd46500 100644
--- a/tests/destructor/const_smart_ptr.nim
+++ b/tests/destructor/const_smart_ptr.nim
@@ -2,13 +2,12 @@ type
   ConstPtr*[T] = object
     val: ptr T
 
-proc `=destroy`*[T](p: var ConstPtr[T]) =
+proc `=destroy`*[T](p: ConstPtr[T]) =
   if p.val != nil:
     `=destroy`(p.val[])
     dealloc(p.val)
-    p.val = nil
 
-proc `=`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.error.}
+proc `=copy`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.error.}
 
 proc `=sink`*[T](dest: var ConstPtr[T], src: ConstPtr[T]) {.inline.} =
   if dest.val != nil and dest.val != src.val:
@@ -31,12 +30,11 @@ type
     len: int
     data: ptr UncheckedArray[float]
 
-proc `=destroy`*(m: var MySeqNonCopyable) {.inline.} =
+proc `=destroy`*(m: MySeqNonCopyable) {.inline.} =
   if m.data != nil:
     deallocShared(m.data)
-    m.data = nil
 
-proc `=`*(m: var MySeqNonCopyable, m2: MySeqNonCopyable) {.error.}
+proc `=copy`*(m: var MySeqNonCopyable, m2: MySeqNonCopyable) {.error.}
 
 proc `=sink`*(m: var MySeqNonCopyable, m2: MySeqNonCopyable) {.inline.} =
   if m.data != m2.data:
diff --git a/tests/destructor/nim.cfg b/tests/destructor/nim.cfg
new file mode 100644
index 000000000..7c148b797
--- /dev/null
+++ b/tests/destructor/nim.cfg
@@ -0,0 +1 @@
+--sinkInference:on
diff --git a/tests/destructor/t12037.nim b/tests/destructor/t12037.nim
index 1a7d536cc..30266690f 100644
--- a/tests/destructor/t12037.nim
+++ b/tests/destructor/t12037.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: '''nim c --newruntime $file'''
+  cmd: '''nim c --gc:arc $file'''
   output: '''
 showing original type, length, and contents seq[int] 1 @[42]
 copy length and contents 1 @[42]
@@ -9,11 +9,11 @@ copy length and contents 1 @[42]
 proc test() =
   var sq1 = @[42]
   echo "showing original type, length, and contents ", sq1.typeof, " ", sq1.len, " ", sq1
-  doAssert cast[int](sq1[0].unsafeAddr) != 0
+  doAssert cast[int](sq1[0].addr) != 0
   var sq2 = sq1 # copy of original
   echo "copy length and contents ", sq2.len, " ", sq2
-  doAssert cast[int](sq2[0].unsafeAddr) != 0
-  doAssert cast[int](sq1[0].unsafeAddr) != 0
+  doAssert cast[int](sq2[0].addr) != 0
+  doAssert cast[int](sq1[0].addr) != 0
 
 test()
 
diff --git a/tests/destructor/t16607.nim b/tests/destructor/t16607.nim
new file mode 100644
index 000000000..f98a6d517
--- /dev/null
+++ b/tests/destructor/t16607.nim
@@ -0,0 +1,23 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+# bug #16607
+
+type
+  O {.requiresInit.} = object
+    initialized: bool
+
+proc `=destroy`(o: var O) =
+  doAssert o.initialized, "O was destroyed before initialization!"
+
+proc initO(): O =
+  O(initialized: true)
+
+proc pair(): tuple[a, b: O] =
+  result = (a: initO(), b: initO())
+
+proc main() =
+  discard pair()
+
+main()
diff --git a/tests/destructor/t17198.nim b/tests/destructor/t17198.nim
new file mode 100644
index 000000000..098db8245
--- /dev/null
+++ b/tests/destructor/t17198.nim
@@ -0,0 +1,32 @@
+discard """
+  cmd: '''nim c --gc:arc $file'''
+  output: '''
+other
+'''
+"""
+
+import std/macros
+
+macro bigCaseStmt(arg: untyped): untyped =
+  result = nnkCaseStmt.newTree(arg)
+
+  # try to change 2000 to a bigger value if it doesn't crash
+  for x in 0 ..< 2000:
+    result.add nnkOfBranch.newTree(newStrLitNode($x), newStrLitNode($x))
+
+  result.add nnkElse.newTree(newStrLitNode("other"))
+
+macro bigIfElseExpr(): untyped =
+  result = nnkIfExpr.newTree()
+
+  for x in 0 ..< 1000:
+    result.add nnkElifExpr.newTree(newLit(false), newStrLitNode($x))
+
+  result.add nnkElseExpr.newTree(newStrLitNode("other"))
+
+proc test(arg: string): string =
+  echo bigIfElseExpr()
+
+  result = bigCaseStmt(arg)
+
+discard test("test")
diff --git a/tests/destructor/t23748.nim b/tests/destructor/t23748.nim
new file mode 100644
index 000000000..a3738733e
--- /dev/null
+++ b/tests/destructor/t23748.nim
@@ -0,0 +1,31 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+  output: '''
+hello 42
+hello 42
+len = 2
+'''
+"""
+
+# bug #23748
+
+type
+  O = ref object
+    s: string
+    cb: seq[proc()]
+
+proc push1(o: O, i: int) =
+  let o = o
+  echo o.s, " ", i
+  o.cb.add(proc() = echo o.s, " ", i)
+
+proc push2(o: O, i: int) =
+  let o = o
+  echo o.s, " ", i
+  proc p() = echo o.s, " ", i
+  o.cb.add(p)
+
+let o = O(s: "hello", cb: @[])
+o.push1(42)
+o.push2(42)
+echo "len = ", o.cb.len
diff --git a/tests/destructor/t23837.nim b/tests/destructor/t23837.nim
new file mode 100644
index 000000000..e219dd6b5
--- /dev/null
+++ b/tests/destructor/t23837.nim
@@ -0,0 +1,51 @@
+discard """
+  output: '''
+Deallocating OwnedString
+HelloWorld
+'''
+  matrix: "--cursorinference:on; --cursorinference:off"
+  target: "c"
+"""
+
+# bug #23837
+{.
+  emit: [
+    """
+#include <stdlib.h>
+#include <string.h>
+char *allocCString() {
+    char *result = (char *) malloc(10 + 1);
+    strcpy(result, "HelloWorld");
+    return result;
+}
+
+"""
+  ]
+.}
+
+proc rawWrapper(): cstring {.importc: "allocCString", cdecl.}
+proc free(p: pointer) {.importc: "free", cdecl.}
+
+# -------------------------
+
+type OwnedString = distinct cstring
+
+proc `=destroy`(s: OwnedString) =
+  free(cstring s)
+  echo "Deallocating OwnedString"
+
+func `$`(s: OwnedString): string {.borrow.}
+
+proc leakyWrapper(): string =
+  let ostring = rawWrapper().OwnedString
+  $ostring
+
+# -------------------------
+
+proc main() =
+  # destructor not called - definitely lost: 11 bytes in 1 blocks
+  # doesn't leak with --cursorInference:off
+  let s = leakyWrapper()
+  echo s
+
+main()
\ No newline at end of file
diff --git a/tests/destructor/t5342.nim b/tests/destructor/t5342.nim
new file mode 100644
index 000000000..0acd5ef9d
--- /dev/null
+++ b/tests/destructor/t5342.nim
@@ -0,0 +1,24 @@
+discard """
+  matrix: "--mm:refc; --mm:arc"
+  targets: "c js"
+  output: '''
+1
+2
+here
+2
+1
+'''
+"""
+
+
+type
+  A = object
+    id: int
+  B = object
+    a: A
+proc `=destroy`(a: var A) = echo a.id
+var x = A(id: 1)
+var y = B(a: A(id: 2))
+`=destroy`(x)
+`=destroy`(y)
+echo "here"
\ No newline at end of file
diff --git a/tests/destructor/t7346.nim b/tests/destructor/t7346.nim
index 9e5292a61..3834d39ff 100644
--- a/tests/destructor/t7346.nim
+++ b/tests/destructor/t7346.nim
@@ -2,8 +2,7 @@ discard """
 joinable: false
 """
 
-when not defined(nimNewRuntime):
-  {.error: "This bug could only be reproduced with --newruntime".}
+# This bug could only be reproduced with --newruntime
 
 type
   Obj = object
diff --git a/tests/destructor/t9440.nim b/tests/destructor/t9440.nim
new file mode 100644
index 000000000..153bb303d
--- /dev/null
+++ b/tests/destructor/t9440.nim
@@ -0,0 +1,52 @@
+discard """
+  matrix: "--gc:refc; --gc:orc; --gc:arc"
+  output: '''
+()
+Destroyed
+()
+Destroyed
+()
+Destroyed
+end
+-------------------------
+()
+Destroyed
+end
+'''
+
+"""
+
+# bug #9440
+block:
+  type
+    X = object
+
+  proc `=destroy`(x: var X) =
+    echo "Destroyed"
+
+  proc main() =
+    for x in 0 .. 2:
+      var obj = X()
+      echo obj
+    # The destructor call is invoked after "end" is printed
+    echo "end"
+
+  main()
+
+echo "-------------------------"
+
+block:
+  type
+    X = object
+
+  proc `=destroy`(x: var X) =
+    echo "Destroyed"
+
+  proc main() =
+    block:
+      var obj = X()
+      echo obj
+      # The destructor is not called when obj goes out of scope
+    echo "end"
+
+  main()
diff --git a/tests/destructor/tarc.nim b/tests/destructor/tarc.nim
index 1acc95fad..54d75a410 100644
--- a/tests/destructor/tarc.nim
+++ b/tests/destructor/tarc.nim
@@ -6,7 +6,11 @@ Success
 Hello
 1
 2
-0'''
+0
+List
+@["4", "5", "6", "", "", "a", ""]
+@["", "", "a", ""]
+'''
   cmd: '''nim c --gc:arc $file'''
 """
 
@@ -145,3 +149,36 @@ proc bug13105 =
 bug13105()
 
 echo getOccupiedMem() - startMem
+
+
+#------------------------------------------------------------------------------
+# issue #14294
+
+import tables
+
+type
+  TagKind = enum
+    List = 0, Compound
+
+  Tag = object
+    case kind: TagKind
+    of List:
+      values: seq[Tag]
+    of Compound:
+      compound: Table[string, Tag]
+
+var a = Tag(kind: List)
+var b = a
+echo a.kind
+var c = a
+
+proc testAdd(i: int; yyy: openArray[string]) =
+  var x: seq[string]
+  x.add [$i, $(i+1), $(i+2)]
+  x.add yyy
+  echo x
+
+var y = newSeq[string](4)
+y[2] = "a"
+testAdd(4, y)
+echo y
diff --git a/tests/destructor/tarc2.nim b/tests/destructor/tarc2.nim
index bd6343b2f..a7d7b4945 100644
--- a/tests/destructor/tarc2.nim
+++ b/tests/destructor/tarc2.nim
@@ -13,9 +13,13 @@ proc create(): T = T(s: @[], data: "abc")
 proc addX(x: T; data: string) =
   x.data = data
 
+{.push sinkInference: off.}
+
 proc addX(x: T; child: T) =
   x.s.add child
 
+{.pop.}
+
 proc main(rootName: string) =
   var root = create()
   root.data = rootName
@@ -23,4 +27,5 @@ proc main(rootName: string) =
 
 let mem = getOccupiedMem()
 main("yeah")
+GC_fullCollect()
 echo "leak: ", getOccupiedMem() - mem > 0
diff --git a/tests/destructor/tarray_indexing.nim b/tests/destructor/tarray_indexing.nim
index 7efd5a00c..a9dfdf4ed 100644
--- a/tests/destructor/tarray_indexing.nim
+++ b/tests/destructor/tarray_indexing.nim
@@ -1,7 +1,7 @@
 discard """
   output: '''allocating 1048576 65536
 filling page from 1048576 len 65536'''
-  cmd: '''nim c --newruntime $file'''
+  cmd: '''nim c --gc:arc $file'''
 """
 
 # bug #12669
@@ -63,7 +63,7 @@ proc fillPages*(mem: UserProcessMemory, start: uint32, data: seq[byte]) =
         #echo cast[uint64](addr mem.pageAccess[i])
         let page = mem.pageAccess[i]
         assert page != nil
-        #copyMem(page, unsafeAddr data[i * 0x1000 - start], 0x1000)
+        #copyMem(page, addr data[i * 0x1000 - start], 0x1000)
 
 const base = 0x00100000
 
diff --git a/tests/destructor/tasync_prototype.nim b/tests/destructor/tasync_prototype.nim
index bd80adf0c..81fd824e9 100644
--- a/tests/destructor/tasync_prototype.nim
+++ b/tests/destructor/tasync_prototype.nim
@@ -32,7 +32,12 @@ proc serve(server: PAsyncHttpServer): PFutureBase =
       yield acceptAddrFut
       var fut = acceptAddrFut.value
 
+      # with the new scope based destruction, this cannot
+      # possibly work:
       var f {.cursor.} = processClient()
+      # It also seems to be the wrong way how to avoid the
+      # cycle. The cycle is caused by capturing the 'env'
+      # part from 'env.f'.
       when true:
         f.callback =
           proc () =
diff --git a/tests/destructor/tasync_prototype_cyclic.nim b/tests/destructor/tasync_prototype_cyclic.nim
index 136e0b676..8ba73a8fc 100644
--- a/tests/destructor/tasync_prototype_cyclic.nim
+++ b/tests/destructor/tasync_prototype_cyclic.nim
@@ -51,4 +51,5 @@ proc main =
   discard serve(PAsyncHttpServer(value: "asdas"))
 
 main()
+GC_fullCollect()
 echo "MEMORY ", getOccupiedMem() - mem
diff --git a/tests/destructor/tatomicptrs.nim b/tests/destructor/tatomicptrs.nim
index 7313afbf5..82870ac82 100644
--- a/tests/destructor/tatomicptrs.nim
+++ b/tests/destructor/tatomicptrs.nim
@@ -27,7 +27,7 @@ template decRef(x): untyped = atomicDec(x.refcount)
 
 proc makeShared*[T](x: sink T): SharedPtr[T] =
   # XXX could benefit from a macro that generates it.
-  result = cast[SharedPtr[T]](allocShared(sizeof(x)))
+  result = cast[SharedPtr[T]](allocShared0(sizeof(x)))
   result.x[] = x
   echo "allocating"
 
@@ -39,7 +39,7 @@ proc `=destroy`*[T](dest: var SharedPtr[T]) =
     echo "deallocating"
     dest.x = nil
 
-proc `=`*[T](dest: var SharedPtr[T]; src: SharedPtr[T]) =
+proc `=copy`*[T](dest: var SharedPtr[T]; src: SharedPtr[T]) =
   var s = src.x
   if s != nil: incRef(s)
   #atomicSwap(dest, s)
@@ -50,6 +50,9 @@ proc `=`*[T](dest: var SharedPtr[T]; src: SharedPtr[T]) =
     deallocShared(s)
     echo "deallocating"
 
+proc `=dup`*[T](src: SharedPtr[T]): SharedPtr[T] =
+  `=copy`(result, src)
+
 proc `=sink`*[T](dest: var SharedPtr[T]; src: SharedPtr[T]) =
   ## XXX make this an atomic store:
   if dest.x != src.x:
@@ -72,6 +75,7 @@ template `.=`*[T](s: SharedPtr[T]; field, value: untyped) =
 from macros import unpackVarargs
 
 template `.()`*[T](s: SharedPtr[T]; field: untyped, args: varargs[untyped]): untyped =
+  # xxx this isn't used, the test should be improved
   unpackVarargs(s.x.field, args)
 
 
@@ -119,7 +123,7 @@ proc `=destroy`*[T](m: var MySeq[T]) {.inline.} =
     deallocShared(m.data)
     m.data = nil
 
-proc `=`*[T](m: var MySeq[T], m2: MySeq[T]) =
+proc `=copy`*[T](m: var MySeq[T], m2: MySeq[T]) =
   if m.data == m2.data: return
   if m.data != nil:
     `=destroy`(m)
@@ -130,17 +134,22 @@ proc `=`*[T](m: var MySeq[T], m2: MySeq[T]) =
     m.data = cast[ptr UncheckedArray[T]](allocShared(bytes))
     copyMem(m.data, m2.data, bytes)
 
+proc `=dup`*[T](m: MySeq[T]): MySeq[T] =
+  `=copy`[T](result, m)
+
 proc `=sink`*[T](m: var MySeq[T], m2: MySeq[T]) {.inline.} =
   if m.data != m2.data:
     if m.data != nil:
       `=destroy`(m)
     m.len = m2.len
     m.data = m2.data
+    m.refcount = m2.refcount
 
 proc len*[T](m: MySeq[T]): int {.inline.} = m.len
 
 proc newMySeq*[T](size: int, initial_value: T): MySeq[T] =
   result.len = size
+  result.refcount = 1
   if size > 0:
     result.data = cast[ptr UncheckedArray[T]](allocShared(sizeof(T) * size))
 
diff --git a/tests/destructor/tbintree2.nim b/tests/destructor/tbintree2.nim
index e910f430a..d56c2850b 100644
--- a/tests/destructor/tbintree2.nim
+++ b/tests/destructor/tbintree2.nim
@@ -1,7 +1,7 @@
 discard """
   cmd: '''nim c -d:nimAllocStats --newruntime $file'''
   output: '''0
-(allocCount: 6, deallocCount: 6)'''
+(allocCount: 5, deallocCount: 5)'''
 """
 
 import system / ansi_c
@@ -21,21 +21,21 @@ proc merge(lower, greater: owned Node): owned Node =
   elif greater.isNil:
     result = lower
   elif lower.y < greater.y:
-    lower.right = merge(lower.right, greater)
+    lower.right = merge(move lower.right, greater)
     result = lower
   else:
-    greater.left = merge(lower, greater.left)
+    greater.left = merge(lower, move greater.left)
     result = greater
 
 proc splitBinary(orig: owned Node, value: int32): (owned Node, owned Node) =
   if orig.isNil:
     result = (nil, nil)
   elif orig.x < value:
-    let splitPair = splitBinary(orig.right, value)
+    let splitPair = splitBinary(move orig.right, value)
     orig.right = splitPair[0]
     result = (orig, splitPair[1])
   else:
-    let splitPair = splitBinary(orig.left, value)
+    let splitPair = splitBinary(move orig.left, value)
     orig.left = splitPair[1]
     result = (splitPair[0], orig)
 
@@ -57,7 +57,7 @@ proc `=destroy`(t: var Tree) {.nodestroy.} =
     let x = s.pop
     if x.left != nil: s.add(x.left)
     if x.right != nil: s.add(x.right)
-    dispose(x)
+    `=dispose`(x)
   `=destroy`(s)
 
 proc hasValue(self: var Tree, x: int32): bool =
diff --git a/tests/destructor/tcaseobj_transitions.nim b/tests/destructor/tcaseobj_transitions.nim
index 4e203f4ef..61464101f 100644
--- a/tests/destructor/tcaseobj_transitions.nim
+++ b/tests/destructor/tcaseobj_transitions.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: '''nim c --newruntime $file'''
+  cmd: '''nim c --gc:arc $file'''
   output: '''no crash'''
 """
 
diff --git a/tests/destructor/tcomplexobjconstr.nim b/tests/destructor/tcomplexobjconstr.nim
index fd112b6e2..aea0ad1fe 100644
--- a/tests/destructor/tcomplexobjconstr.nim
+++ b/tests/destructor/tcomplexobjconstr.nim
@@ -20,16 +20,16 @@ type
     of true: y*: float
 
 var x = new(MyObject2)
-assert x of MyObject2
-assert x.subobj of MyObject1
-assert x.more[2] of MyObject1
-assert x.more[2] of RootObj
+doAssert x of MyObject2
+doAssert x.subobj of MyObject1
+doAssert x.more[2] of MyObject1
+doAssert x.more[2] of RootObj
 
 var y: MyObject2
-assert y of MyObject2
-assert y.subobj of MyObject1
-assert y.more[2] of MyObject1
-assert y.more[2] of RootObj
+doAssert y of MyObject2
+doAssert y.subobj of MyObject1
+doAssert y.more[2] of MyObject1
+doAssert y.more[2] of RootObj
 
 echo "true"
 
diff --git a/tests/destructor/tconsume_twice.nim b/tests/destructor/tconsume_twice.nim
index 8687b3ce5..b0a039e9b 100644
--- a/tests/destructor/tconsume_twice.nim
+++ b/tests/destructor/tconsume_twice.nim
@@ -1,7 +1,7 @@
 discard """
   cmd: "nim c --newruntime $file"
-  errormsg: "sink parameter `a` is already consumed at tconsume_twice.nim(11, 10)"
-  line: 13
+  errormsg: "'=copy' is not available for type <owned Foo>; requires a copy because it's not the last read of 'a'; another read is done here: tconsume_twice.nim(13, 10); routine: consumeTwice"
+  line: 11
 """
 type
   Foo = ref object
diff --git a/tests/destructor/tcustomseqs.nim b/tests/destructor/tcustomseqs.nim
index 4087dc4a8..17a19f871 100644
--- a/tests/destructor/tcustomseqs.nim
+++ b/tests/destructor/tcustomseqs.nim
@@ -121,7 +121,7 @@ proc createSeq*[T](elems: varargs[T]): myseq[T] =
   result.data = cast[type(result.data)](alloc(result.cap * sizeof(T)))
   inc allocCount
   when supportsCopyMem(T):
-    copyMem(result.data, unsafeAddr(elems[0]), result.cap * sizeof(T))
+    copyMem(result.data, addr(elems[0]), result.cap * sizeof(T))
   else:
     for i in 0..<result.len:
       result.data[i] = elems[i]
diff --git a/tests/destructor/tcustomstrings.nim b/tests/destructor/tcustomstrings.nim
index 9ee2da33a..31891856b 100644
--- a/tests/destructor/tcustomstrings.nim
+++ b/tests/destructor/tcustomstrings.nim
@@ -8,8 +8,6 @@ after 20 20'''
 joinable: false
 """
 
-{.this: self.}
-
 type
   mystring = object
     len, cap: int
@@ -51,7 +49,7 @@ proc resize(self: var mystring) =
   if self.cap == 0: self.cap = 8
   else: self.cap = (self.cap * 3) shr 1
   if self.data == nil: inc allocCount
-  self.data = cast[type(data)](realloc(self.data, self.cap + 1))
+  self.data = cast[type(self.data)](realloc(self.data, self.cap + 1))
 
 proc add*(self: var mystring; c: char) =
   if self.len >= self.cap: resize(self)
@@ -60,22 +58,22 @@ proc add*(self: var mystring; c: char) =
   inc self.len
 
 proc ensure(self: var mystring; newLen: int) =
-  if newLen >= cap:
-    cap = max((cap * 3) shr 1, newLen)
-    if cap > 0:
-      if data == nil: inc allocCount
-      data = cast[type(data)](realloc(data, cap + 1))
+  if newLen >= self.cap:
+    self.cap = max((self.cap * 3) shr 1, newLen)
+    if self.cap > 0:
+      if self.data == nil: inc allocCount
+      self.data = cast[type(self.data)](realloc(self.data, self.cap + 1))
 
 proc add*(self: var mystring; y: mystring) =
-  let newLen = len + y.len
+  let newLen = self.len + y.len
   ensure(self, newLen)
-  copyMem(addr data[len], y.data, y.data.len + 1)
-  len = newLen
+  copyMem(addr self.data[self.len], y.data, y.data.len + 1)
+  self.len = newLen
 
 proc create*(lit: string): mystring =
   let newLen = lit.len
   ensure(result, newLen)
-  copyMem(addr result.data[result.len], unsafeAddr lit[0], newLen + 1)
+  copyMem(addr result.data[result.len], addr lit[0], newLen + 1)
   result.len = newLen
 
 proc `&`*(a, b: mystring): mystring =
diff --git a/tests/destructor/tcycle1.nim b/tests/destructor/tcycle1.nim
index c30977433..8dc552294 100644
--- a/tests/destructor/tcycle1.nim
+++ b/tests/destructor/tcycle1.nim
@@ -50,4 +50,5 @@ proc main =
 
 let mem = getOccupiedMem()
 main()
+GC_fullCollect()
 echo "MEM ", getOccupiedMem() - mem
diff --git a/tests/destructor/tcycle2.nim b/tests/destructor/tcycle2.nim
index c4b297559..7b03101fe 100644
--- a/tests/destructor/tcycle2.nim
+++ b/tests/destructor/tcycle2.nim
@@ -13,6 +13,24 @@ proc main(x: int) =
   let m = n
   n.kids.add m
 
+type
+  NodeA = ref object
+    s: char
+    a: array[3, NodeA]
+
+proc m: NodeA =
+  result = NodeA(s: 'a')
+  result.a[0] = result
+  result.a[1] = result
+  result.a[2] = result
+
+proc mainA =
+  for i in 0..10:
+    discard m()
+
 let mem = getOccupiedMem()
 main(90)
+mainA()
+GC_fullCollect()
+
 echo "MEM ", getOccupiedMem() - mem
diff --git a/tests/destructor/tcycle3.nim b/tests/destructor/tcycle3.nim
index a938ded01..8662136e7 100644
--- a/tests/destructor/tcycle3.nim
+++ b/tests/destructor/tcycle3.nim
@@ -2,6 +2,8 @@ discard """
   output: '''BEGIN
 END
 END 2
+cpu.nes false
+cpu step nes is nil? - false
 0'''
   cmd: '''nim c --gc:orc $file'''
 """
@@ -59,6 +61,38 @@ proc main =
   c.run
   echo "END 2"
 
+# bug #14159
+type
+  NES = ref object
+    cpu: CPU
+    apu: APU
+
+  CPU = ref object
+    nes: NES
+
+  APU = object
+    nes: NES
+    cpu: CPU
+
+proc initAPU(nes: sink NES): APU {.nosinks.} =
+  result.nes = nes
+  result.cpu = nes.cpu
+
+proc step(cpu: CPU): int =
+  echo "cpu.nes ", cpu.isNil
+  echo "cpu step nes is nil? - ", cpu.nes.isNil()
+
+proc newNES(): NES =
+  new result
+  result.cpu = CPU(nes: result)
+  result.apu = initAPU(result)
+
+proc bug14159 =
+  var nesConsole = newNES()
+  discard nesConsole.cpu.step()
+
 let mem = getOccupiedMem()
 main()
+bug14159()
+GC_fullCollect()
 echo getOccupiedMem() - mem
diff --git a/tests/destructor/tdestructor.nim b/tests/destructor/tdestructor.nim
index 5cfecea4e..e081eb251 100644
--- a/tests/destructor/tdestructor.nim
+++ b/tests/destructor/tdestructor.nim
@@ -1,27 +1,27 @@
 discard """
-  output: '''----
+  output: '''----1
 myobj constructed
 myobj destroyed
-----
+----2
 mygeneric1 constructed
 mygeneric1 destroyed
-----
+----3
 mygeneric2 constructed
 mygeneric2 destroyed
 myobj destroyed
-----
+----4
 mygeneric3 constructed
 mygeneric1 destroyed
-----
+----5
 mydistinctObj constructed
 myobj destroyed
 mygeneric2 destroyed
-------------------
-----
-----
-myobj destroyed
+------------------8
 mygeneric1 destroyed
----
+----6
+myobj destroyed
+----7
+---9
 myobj destroyed
 myobj destroyed
 '''
@@ -33,7 +33,7 @@ type
     p: pointer
 
 proc `=destroy`(o: var TMyObj) =
-  if o.p != nil: 
+  if o.p != nil:
     dealloc o.p
     o.p = nil
     echo "myobj destroyed"
@@ -114,19 +114,19 @@ proc mydistinctObj =
 
   echo "mydistinctObj constructed"
 
-echo "----"
+echo "----1"
 myobj()
 
-echo "----"
+echo "----2"
 mygeneric1()
 
-echo "----"
+echo "----3"
 mygeneric2[int](10)
 
-echo "----"
+echo "----4"
 mygeneric3()
 
-echo "----"
+echo "----5"
 mydistinctObj()
 
 proc caseobj =
@@ -134,16 +134,16 @@ proc caseobj =
     var o1 = TCaseObj(kind: A, x: TMyGeneric1[int](x: 10))
 
   block:
-    echo "----"
+    echo "----6"
     var o2 = TCaseObj(kind: B, y: open())
 
   block:
-    echo "----"
+    echo "----7"
     var o3 = TCaseObj(kind: D, innerKind: B, r: "test",
                       p: TMyGeneric3[int, float, string](x: 10, y: 1.0, z: "test"))
 
 
-echo "------------------"
+echo "------------------8"
 caseobj()
 
 proc caseobj_test_sink: TCaseObj =
@@ -153,5 +153,15 @@ proc caseobj_test_sink: TCaseObj =
   result = TCaseObj(kind: B, y: open())
 
 
-echo "---"
-discard caseobj_test_sink()
\ No newline at end of file
+echo "---9"
+discard caseobj_test_sink()
+
+# issue #14315
+
+type Vector*[T] = object
+  x1: int
+  # x2: T # uncomment will remove error
+
+# proc `=destroy`*(x: var Vector[int]) = discard # this will remove error
+proc `=destroy`*[T](x: var Vector[T]) = discard
+var a: Vector[int] # Error: unresolved generic parameter
diff --git a/tests/destructor/tdestructor3.nim b/tests/destructor/tdestructor3.nim
index b68aedce9..3f5eb2cc1 100644
--- a/tests/destructor/tdestructor3.nim
+++ b/tests/destructor/tdestructor3.nim
@@ -1,5 +1,6 @@
 discard """
-  output: '''assign
+  output: '''
+assign
 destroy
 destroy
 5
@@ -22,17 +23,18 @@ joinable: false
 type T = object
 
 proc `=`(lhs: var T, rhs: T) =
-    echo "assign"
+  echo "assign"
 
 proc `=destroy`(v: var T) =
-    echo "destroy"
+  echo "destroy"
 
 proc use(x: T) = discard
 
 proc usedToBeBlock =
-    var v1 : T
-    var v2 : T = v1
-    use v1
+  var v1 = T()
+  var v2: T = v1
+  discard addr(v2) # prevent cursorfication
+  use v1
 
 usedToBeBlock()
 
@@ -104,12 +106,12 @@ test()
 #------------------------------------------------------------
 # Issue #12883
 
-type 
+type
   TopObject = object
     internal: UniquePtr[int]
 
 proc deleteTop(p: ptr TopObject) =
-  if p != nil:    
+  if p != nil:
     `=destroy`(p[]) # !!! this operation used to leak the integer
     deallocshared(p)
 
@@ -117,12 +119,67 @@ proc createTop(): ptr TopObject =
   result = cast[ptr TopObject](allocShared0(sizeof(TopObject)))
   result.internal = newUniquePtr(1)
 
-proc test2() = 
+proc test2() =
   let x = createTop()
   echo $x.internal
   deleteTop(x)
 
-echo "---------------"  
+echo "---------------"
 echo "app begin"
 test2()
-echo "app end"
\ No newline at end of file
+echo "app end"
+
+# bug #14601
+
+when true: # D20200607T202043
+  type Foo2 = object
+    x: int
+    x2: array[10, int]
+
+  type Vec = object
+    vals: seq[Foo2]
+
+  proc `=destroy`*(a: var Foo2) {.inline.} =
+    discard
+
+  proc initFoo2(x: int): Foo2 = Foo2(x: x)
+
+  proc add2(v: var Vec, a: Foo2) = # ditto with `a: sink Foo2`
+    v.vals.add a
+
+  proc add3(v: var Vec, a: Foo2) = # ditto with `a: sink Foo2`
+    v.vals = @[a]
+
+  proc add4(v: var Vec, a: sink Foo2) = # ditto with `a: sink Foo2`
+    v.vals.add a
+
+  proc add5(v: var Vec, a: sink Foo2) = # ditto with `a: sink Foo2`
+    v.vals = @[a]
+
+  proc main2()=
+    var a: Vec
+    var b = Foo2(x: 10)
+    a.add2 b # ok
+    a.vals.add Foo2(x: 10) # ok
+    a.add2 initFoo2(x = 10) # ok
+    a.add2 Foo2(x: 10) # bug
+    a.add3 initFoo2(x = 10) # ok
+    a.add3 Foo2(x: 10) # bug
+    a.add4 initFoo2(x = 10) # ok
+    a.add4 Foo2(x: 10) # bug
+    a.add5 initFoo2(x = 10) # ok
+    a.add5 Foo2(x: 10) # bug
+  main2()
+
+
+
+#------------------------------------------------------------
+# Issue #15825
+
+type
+  Union = string | int | char
+
+proc run(a: sink Union) =
+  discard
+
+run("123")
diff --git a/tests/destructor/tdestructor_too_late.nim b/tests/destructor/tdestructor_too_late.nim
index d279280ba..76d1dde84 100644
--- a/tests/destructor/tdestructor_too_late.nim
+++ b/tests/destructor/tdestructor_too_late.nim
@@ -1,5 +1,5 @@
 discard """
-  errmsg: "cannot bind another '=destroy' to: Obj; previous declaration was constructed here implicitly: tdestructor_too_late.nim(7, 16)"
+  errormsg: "cannot bind another '=destroy' to: Obj; previous declaration was constructed here implicitly: tdestructor_too_late.nim(7, 16)"
 """
 type Obj* = object
   v*: int
diff --git a/tests/destructor/tdistinctseq.nim b/tests/destructor/tdistinctseq.nim
new file mode 100644
index 000000000..5a2ac5ead
--- /dev/null
+++ b/tests/destructor/tdistinctseq.nim
@@ -0,0 +1,8 @@
+discard """
+  matrix: "-u:nimPreviewNonVarDestructor;"
+"""
+type DistinctSeq* = distinct seq[int]
+
+# `=destroy`(cast[ptr DistinctSeq](0)[])
+var x = @[].DistinctSeq
+`=destroy`(x)
diff --git a/tests/destructor/tdont_return_unowned_from_owned.nim b/tests/destructor/tdont_return_unowned_from_owned.nim
index a726960c6..ffe87cd76 100644
--- a/tests/destructor/tdont_return_unowned_from_owned.nim
+++ b/tests/destructor/tdont_return_unowned_from_owned.nim
@@ -1,8 +1,12 @@
 discard """
   cmd: "nim check --newruntime --hints:off $file"
-  nimout: '''tdont_return_unowned_from_owned.nim(36, 10) Error: cannot return an owned pointer as an unowned pointer; use 'owned(Obj)' as the return type
-tdont_return_unowned_from_owned.nim(39, 10) Error: cannot return an owned pointer as an unowned pointer; use 'owned(Obj)' as the return type
-tdont_return_unowned_from_owned.nim(42, 6) Error: type mismatch: got <Obj>
+  nimout: '''
+tdont_return_unowned_from_owned.nim(26, 13) Error: assignment produces a dangling ref: the unowned ref lives longer than the owned ref
+tdont_return_unowned_from_owned.nim(27, 13) Error: assignment produces a dangling ref: the unowned ref lives longer than the owned ref
+tdont_return_unowned_from_owned.nim(31, 10) Error: cannot return an owned pointer as an unowned pointer; use 'owned(RootRef)' as the return type
+tdont_return_unowned_from_owned.nim(43, 10) Error: cannot return an owned pointer as an unowned pointer; use 'owned(Obj)' as the return type
+tdont_return_unowned_from_owned.nim(46, 10) Error: cannot return an owned pointer as an unowned pointer; use 'owned(Obj)' as the return type
+tdont_return_unowned_from_owned.nim(49, 6) Error: type mismatch: got <Obj>
 but expected one of:
 proc new[T](a: var ref T; finalizer: proc (x: ref T) {.nimcall.})
   first type mismatch at position: 2
@@ -10,18 +14,21 @@ proc new[T](a: var ref T; finalizer: proc (x: ref T) {.nimcall.})
 2 other mismatching symbols have been suppressed; compile with --showAllMismatches:on to see them
 
 expression: new(result)
-tdont_return_unowned_from_owned.nim(42, 6) Error: illformed AST:
-tdont_return_unowned_from_owned.nim(50, 13) Error: assignment produces a dangling ref: the unowned ref lives longer than the owned ref
-tdont_return_unowned_from_owned.nim(51, 13) Error: assignment produces a dangling ref: the unowned ref lives longer than the owned ref
-tdont_return_unowned_from_owned.nim(55, 10) Error: cannot return an owned pointer as an unowned pointer; use 'owned(RootRef)' as the return type
+tdont_return_unowned_from_owned.nim(49, 6) Error: illformed AST: 
 '''
-  errormsg: "cannot return an owned pointer as an unowned pointer; use 'owned(RootRef)' as the return type"
-  line: 55
+  errormsg: "illformed AST:"
 """
 
 
 
+proc testA(result: var (RootRef, RootRef)) =
+  let r: owned RootRef = RootRef()
+  result[0] = r
+  result[1] = RootRef()
 
+proc testB(): RootRef =
+  let r: owned RootRef = RootRef()
+  result = r
 
 
 
@@ -39,17 +46,11 @@ proc newObjB(): Obj =
   result = Obj()
 
 proc newObjC(): Obj =
-  new(result)
+  new(result) # illFormedAst raises GlobalError,
+              # without pipeline parsing, it needs to placed at the end
+              # in case that it disturbs other errors
 
 let a = newObjA()
 let b = newObjB()
 let c = newObjC()
 
-proc testA(result: var (RootRef, RootRef)) =
-  let r: owned RootRef = RootRef()
-  result[0] = r
-  result[1] = RootRef()
-
-proc testB(): RootRef =
-  let r: owned RootRef = RootRef()
-  result = r
diff --git a/tests/destructor/tfinalizer.nim b/tests/destructor/tfinalizer.nim
index 02a5cef7e..eb2cd09af 100644
--- a/tests/destructor/tfinalizer.nim
+++ b/tests/destructor/tfinalizer.nim
@@ -1,6 +1,6 @@
 discard """
   cmd: "nim c --gc:arc $file"
-  output: '''Foo(field: Dick Laurent, k: ka, x: 0.0)
+  output: '''Foo(field: "Dick Laurent", k: ka, x: 0.0)
 Nobody is dead
 Dick Laurent is dead'''
 """
diff --git a/tests/destructor/tgcdestructors.nim b/tests/destructor/tgcdestructors.nim
index 7169daaf1..07a3731a0 100644
--- a/tests/destructor/tgcdestructors.nim
+++ b/tests/destructor/tgcdestructors.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: '''nim c -d:nimAllocStats --newruntime $file'''
+  cmd: '''nim c -d:nimAllocStats --gc:arc $file'''
   output: '''hi
 ho
 ha
@@ -10,7 +10,7 @@ a: @[4, 2, 3]
 0
 30
 true
-(allocCount: 41, deallocCount: 41)'''
+(allocCount: 27, deallocCount: 27)'''
 """
 
 include system / ansi_c
diff --git a/tests/destructor/tglobaldestructor.nim b/tests/destructor/tglobaldestructor.nim
index 403f670a0..4d002a092 100644
--- a/tests/destructor/tglobaldestructor.nim
+++ b/tests/destructor/tglobaldestructor.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: '''nim c --newruntime $file'''
+  cmd: '''nim c --gc:arc $file'''
   output: '''(v: 42)
 igotdestroyed'''
 """
diff --git a/tests/destructor/tgotoexc_leak.nim b/tests/destructor/tgotoexc_leak.nim
new file mode 100644
index 000000000..c8a234085
--- /dev/null
+++ b/tests/destructor/tgotoexc_leak.nim
@@ -0,0 +1,19 @@
+discard """
+  output: '''0
+true'''
+  cmd: "nim c --gc:arc $file"
+"""
+
+# bug #22398
+
+for i in 0 ..< 10_000:
+  try:
+    try:
+      raise newException(ValueError, "")
+    except CatchableError:
+      discard
+      raise newException(ValueError, "") # or raise getCurrentException(), just raise works ok
+  except ValueError:
+    discard
+echo getOccupiedMem()
+echo getCurrentException() == nil
diff --git a/tests/destructor/tgotoexceptions4.nim b/tests/destructor/tgotoexceptions4.nim
index 918169084..b2b481256 100644
--- a/tests/destructor/tgotoexceptions4.nim
+++ b/tests/destructor/tgotoexceptions4.nim
@@ -4,7 +4,9 @@ discard """
 caught in fun
 caughtsome msgMyExcept
 in finally
-caught1'''
+caught1
+123
+123'''
 """
 
 when true:
@@ -38,3 +40,21 @@ when true:
     except CatchableError:
       echo "caught1"
   funB()
+
+# bug #13782
+
+import strutils
+var n = 123
+
+try: n = parseInt("xxx")
+except: discard
+
+echo n
+
+proc sameTestButForLocalVar =
+  var n = 123
+  try: n = parseInt("xxx")
+  except: discard
+  echo n
+
+sameTestButForLocalVar()
diff --git a/tests/destructor/tgotoexceptions5.nim b/tests/destructor/tgotoexceptions5.nim
new file mode 100644
index 000000000..695aab0a4
--- /dev/null
+++ b/tests/destructor/tgotoexceptions5.nim
@@ -0,0 +1,45 @@
+discard """
+  output: '''
+before
+swallowed
+before
+swallowed B
+'''
+  cmd: "nim c --gc:arc --exceptions:goto -d:ssl $file"
+"""
+
+# bug #13599
+proc main() =
+  try:
+    echo "before"
+    raise newException(CatchableError, "foo")
+  except AssertionDefect:
+    echo "caught"
+  echo "after"
+
+try:
+  main()
+except:
+  echo "swallowed"
+
+proc mainB() =
+  try:
+    echo "before"
+    raise newException(CatchableError, "foo")
+  # except CatchableError: # would work
+  except AssertionDefect:
+    echo "caught"
+  except:
+    raise
+  echo "after"
+
+try:
+  mainB()
+except:
+  echo "swallowed B"
+
+# bug #14647
+import httpclient
+
+newAsyncHttpClient().close()
+
diff --git a/tests/destructor/tgotoexceptions6.nim b/tests/destructor/tgotoexceptions6.nim
new file mode 100644
index 000000000..7c01f6a52
--- /dev/null
+++ b/tests/destructor/tgotoexceptions6.nim
@@ -0,0 +1,10 @@
+discard """
+  cmd: "nim c --gc:arc --exceptions:goto $file"
+  outputsub: "Error: unhandled exception: virus detected [ValueError]"
+  exitcode: "1"
+"""
+
+# bug #13436
+proc foo =
+  raise newException(ValueError, "virus detected")
+foo()
diff --git a/tests/destructor/tgotoexceptions7.nim b/tests/destructor/tgotoexceptions7.nim
new file mode 100644
index 000000000..c04bd6ba0
--- /dev/null
+++ b/tests/destructor/tgotoexceptions7.nim
@@ -0,0 +1,49 @@
+discard """
+  cmd: "nim c --gc:arc --exceptions:goto --panics:off $file"
+  output: '''prevented!
+caught
+AssertionDefect
+900'''
+"""
+
+type
+  E = enum
+    kindA, kindB
+  Obj = object
+    case kind: E
+    of kindA: s: string
+    of kindB: i: int
+
+  ObjA = ref object of RootObj
+  ObjB = ref object of ObjA
+
+proc takeRange(x: range[0..4]) = discard
+
+proc bplease(x: ObjB) = discard
+
+proc helper = doAssert(false)
+
+proc main(i: int) =
+  var obj = Obj(kind: kindA, s: "abc")
+  {.cast(uncheckedAssign).}:
+    obj.kind = kindB
+  obj.i = 2
+  try:
+    var objA = ObjA()
+    bplease(ObjB(objA))
+  except ObjectConversionDefect:
+    echo "prevented!"
+
+  try:
+    takeRange(i)
+  except RangeDefect:
+    echo "caught"
+
+  try:
+    helper()
+  except AssertionDefect:
+    echo "AssertionDefect"
+
+  echo i * i
+
+main(30)
diff --git a/tests/destructor/tgotoexceptions8.nim b/tests/destructor/tgotoexceptions8.nim
new file mode 100644
index 000000000..8ed2ed0ba
--- /dev/null
+++ b/tests/destructor/tgotoexceptions8.nim
@@ -0,0 +1,76 @@
+discard """
+  output: '''A
+B
+X
+inner finally
+Y
+outer finally
+msg1
+msg2
+finally2
+finally1
+true'''
+  cmd: "nim c --gc:arc $file"
+"""
+
+# bug #13668
+
+proc main =
+  try:
+    try:
+      raise newException(IOError, "IOError")
+
+    except:
+      echo "A"
+      raise newException(CatchableError, "CatchableError")
+
+  except:
+    echo "B"
+    #discard
+
+proc mainB =
+  try:
+    try:
+      raise newException(IOError, "IOError")
+
+    except:
+      echo "X"
+      raise newException(CatchableError, "CatchableError")
+    finally:
+      echo "inner finally"
+
+  except:
+    echo "Y"
+    #discard
+  finally:
+    echo "outer finally"
+
+main()
+mainB()
+
+when true:
+  #bug 7204
+  proc nested_finally =
+    try:
+      raise newException(KeyError, "msg1")
+    except KeyError as ex:
+      echo ex.msg
+      try:
+        # pop exception
+        raise newException(ValueError, "msg2") # push: exception stack (1 entry)
+      except:
+        echo getCurrentExceptionMsg()
+        # pop exception (except)
+      finally:
+        echo "finally2"
+      # pop exception (except KeyError as ex)
+    finally:
+      echo "finally1"
+
+  nested_finally()
+
+# bug #14925
+proc test(b: bool) =
+  echo b
+
+test(try: true except: false)
diff --git a/tests/destructor/tmatrix.nim b/tests/destructor/tmatrix.nim
index a3bd59df3..2fd5af789 100644
--- a/tests/destructor/tmatrix.nim
+++ b/tests/destructor/tmatrix.nim
@@ -31,7 +31,7 @@ proc `=sink`*(a: var Matrix; b: Matrix) =
   a.m = b.m
   a.n = b.n
 
-proc `=`*(a: var Matrix; b: Matrix) =
+proc `=copy`*(a: var Matrix; b: Matrix) =
   if a.data != nil and a.data != b.data:
     dealloc(a.data)
     deallocCount.inc
@@ -43,6 +43,9 @@ proc `=`*(a: var Matrix; b: Matrix) =
     allocCount.inc
     copyMem(a.data, b.data, b.m * b.n * sizeof(float))
 
+proc `=dup`*(a: Matrix): Matrix =
+  `=copy`(result, a)
+
 proc matrix*(m, n: int, s: float): Matrix =
   ## Construct an m-by-n constant matrix.
   result.m = m
@@ -96,14 +99,16 @@ proc info =
   allocCount = 0
   deallocCount = 0
 
+proc copy(a: Matrix): Matrix = a
+
 proc test1 =
   var a = matrix(5, 5, 1.0)
-  var b = a
+  var b = copy a
   var c = a + b
 
 proc test2 =
   var a = matrix(5, 5, 1.0)
-  var b = a
+  var b = copy a
   var c = -a
 
 proc test3 =
diff --git a/tests/destructor/tmisc_destructors.nim b/tests/destructor/tmisc_destructors.nim
index 53c67e34b..082cb0f78 100644
--- a/tests/destructor/tmisc_destructors.nim
+++ b/tests/destructor/tmisc_destructors.nim
@@ -21,11 +21,13 @@ proc `=sink`(dest: var Foo, src: Foo) =
 proc `=`(dest: var Foo, src: Foo) =
   assign_counter.inc
 
+proc createFoo(): Foo = Foo(boo: 0)
+
 proc test(): auto =
-  var a,b : Foo
+  var a, b = createFoo()
   return (a, b, Foo(boo: 5))
 
-var (a, b, _) = test()
+var (ag, bg, _) = test()
 
 doAssert assign_counter == 0
 doAssert sink_counter == 0
diff --git a/tests/destructor/tmove.nim b/tests/destructor/tmove.nim
new file mode 100644
index 000000000..2762aff90
--- /dev/null
+++ b/tests/destructor/tmove.nim
@@ -0,0 +1,18 @@
+discard """
+  targets: "c cpp"
+"""
+
+block:
+  var called = 0
+
+  proc bar(a: var int): var int =
+    inc called
+    result = a
+
+  proc foo =
+    var a = 2
+    var s = move bar(a)
+    doAssert called == 1
+    doAssert s == 2
+
+  foo()
diff --git a/tests/destructor/tmove_objconstr.nim b/tests/destructor/tmove_objconstr.nim
index 5b2198e51..cdc1eb1c0 100644
--- a/tests/destructor/tmove_objconstr.nim
+++ b/tests/destructor/tmove_objconstr.nim
@@ -8,7 +8,7 @@ test destroyed 0
 4
 Pony is dying!'''
 joinable: false
-target: "C"
+targets: "c"
 """
 
 # bug #4214
@@ -50,7 +50,7 @@ proc `=destroy`(o: var Pony) =
   echo "Pony is dying!"
 
 proc getPony: Pony =
-  result.name = "Sparkles"
+  result = Pony(name: "Sparkles")
 
 iterator items(p: Pony): int =
   for i in 1..4:
@@ -112,7 +112,7 @@ proc myfunc2(x, y: int): tuple[a: MySeqNonCopyable, b:int, c:MySeqNonCopyable] =
   var cc = newMySeq(y, 5.0)
   (a: case x:
     of 1:
-      let (z1, z2) = myfunc(x,y)
+      let (z1, z2) = myfunc(x, y)
       z2
     elif x > 5: raise newException(ValueError, "new error")
     else: newMySeq(x, 1.0),
@@ -137,28 +137,29 @@ doAssert seq3[0] == 1.0
 var seq4, seq5: MySeqNonCopyable
 (seq4, i, seq5) = myfunc2(2, 3)
 
-seq4 = block:
-  var tmp = newMySeq(4, 1.0)
-  tmp[0] = 3.0
-  tmp
+proc foo =
+  seq4 = block:
+    var tmp = newMySeq(4, 1.0)
+    tmp[0] = 3.0
+    tmp
 
-doAssert seq4[0] == 3.0
+  doAssert seq4[0] == 3.0
 
-import macros
 
-seq4 =
-  if i > 0: newMySeq(2, 5.0)
-  elif i < -100: raise newException(ValueError, "Parse Error")
-  else: newMySeq(2, 3.0)
+  seq4 =
+    if i > 0: newMySeq(2, 5.0)
+    elif i < -100: raise newException(ValueError, "Parse Error")
+    else: newMySeq(2, 3.0)
 
-seq4 =
-  case (char) i:
-    of 'A', {'W'..'Z'}: newMySeq(2, 5.0)
-    of 'B': quit(-1)
-    else:
-      let (x1, x2, x3) = myfunc2(2, 3)
-      x3
+  seq4 =
+    case (char) i:
+      of 'A', {'W'..'Z'}: newMySeq(2, 5.0)
+      of 'B': quit(-1)
+      else:
+        let (x1, x2, x3) = myfunc2(2, 3)
+        x3
 
+foo()
 
 #------------------------------------------------------------
 #-- Move into array constructor
@@ -178,7 +179,7 @@ proc myfuncLoop(x: int): MySeqNonCopyable =
 discard myfuncLoop(3)
 
 #------------------------------------------------------------
-# Move into table via openarray
+# Move into table via openArray
 #------------------------------------------------------------
 
 type
diff --git a/tests/destructor/tnewruntime_misc.nim b/tests/destructor/tnewruntime_misc.nim
index 263ea1bd4..21c70557d 100644
--- a/tests/destructor/tnewruntime_misc.nim
+++ b/tests/destructor/tnewruntime_misc.nim
@@ -7,7 +7,8 @@ axc
 ...
 destroying GenericObj[T] GenericObj[system.int]
 test
-(allocCount: 17, deallocCount: 15)'''
+(allocCount: 12, deallocCount: 10)
+3'''
 """
 
 import system / ansi_c
@@ -24,8 +25,13 @@ putEnv("HEAPTRASHING", "Indeed")
 
 let s1 = getAllocStats()
 
+
+proc newTableOwned[A, B](initialSize = defaultInitialSize): owned(TableRef[A, B]) =
+  new(result)
+  result[] = initTable[A, B](initialSize)
+
 proc main =
-  var w = newTable[string, owned Node]()
+  var w = newTableOwned[string, owned Node]()
   w["key"] = Node(field: "value")
   echo w["key"][]
   echo getEnv("HEAPTRASHING")
@@ -131,4 +137,19 @@ proc xx(xml: string): MyObject =
 
 
 discard xx("test")
-echo getAllocStats() - s1
+
+# Windows has 1 extra allocation in `getEnv` - there it allocates parameter to
+# `_wgetenv` (WideCString). Therefore subtract by 1 to match other OSes'
+# allocation.
+when defined(windows):
+  import std/importutils
+  privateAccess(AllocStats)
+  echo getAllocStats() - s1 - AllocStats(allocCount: 1, deallocCount: 1)
+else:
+  echo getAllocStats() - s1
+
+# bug #13457
+var s = "abcde"
+s.setLen(3)
+
+echo s.cstring.len
diff --git a/tests/destructor/tnewruntime_strutils.nim b/tests/destructor/tnewruntime_strutils.nim
index 9afb507f7..9c8d41973 100644
--- a/tests/destructor/tnewruntime_strutils.nim
+++ b/tests/destructor/tnewruntime_strutils.nim
@@ -1,8 +1,12 @@
 discard """
   valgrind: true
-  cmd: '''nim c -d:nimAllocStats --newruntime -d:useMalloc $file'''
+  cmd: '''nim c -d:nimAllocStats --gc:arc -d:useMalloc $file'''
   output: '''
-@[(input: @["KXSC", "BGMC"]), (input: @["PXFX"]), (input: @["WXRQ", "ZSCZD"])]'''
+@[(input: @["KXSC", "BGMC"]), (input: @["PXFX"]), (input: @["WXRQ", "ZSCZD"])]
+14
+First tasks completed.
+Second tasks completed.
+test1'''
 """
 
 import strutils, os, std / wordwrap
@@ -37,7 +41,7 @@ bug12899()
 
 proc nonStaticTests =
   doAssert formatBiggestFloat(1234.567, ffDecimal, -1) == "1234.567000"
-  doAssert formatBiggestFloat(1234.567, ffDecimal, 0) == "1235" # bugs 8242, 12586
+  doAssert formatBiggestFloat(1234.567, ffDecimal, 0) == "1235." # bugs 8242, 12586
   doAssert formatBiggestFloat(1234.567, ffDecimal, 1) == "1234.6"
   doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001"
   doAssert formatBiggestFloat(0.00000000001, ffScientific, 1, ',') in
@@ -211,3 +215,40 @@ staticTests()
 # bug #12965
 let xaa = @[""].join()
 let xbb = @["", ""].join()
+
+# bug #16365
+
+# Task 1:
+when true:
+  # Task 1_a:
+  var test_string_a = "name_something"
+  echo test_string_a.len()
+  let new_len_a = test_string_a.len - "_something".len()
+  test_string_a.setLen new_len_a
+
+  echo "First tasks completed."
+
+# Task 2:
+when true:
+  # Task 2_a
+  var test_string: string
+  let some_string = "something"
+  for i in some_string.items:
+    test_string.add $i
+
+  # Task 2_b
+  var test_string_b = "name_something"
+  let new_len_b = test_string_b.len - "_something".len()
+  test_string_b.setLen new_len_b
+
+  echo "Second tasks completed."
+
+# bug #17450
+proc main =
+  var i = 1
+  echo:
+    block:
+      "test" & $i
+
+main()
+
diff --git a/tests/destructor/tnonvardestructor.nim b/tests/destructor/tnonvardestructor.nim
new file mode 100644
index 000000000..1b4413790
--- /dev/null
+++ b/tests/destructor/tnonvardestructor.nim
@@ -0,0 +1,247 @@
+discard """

+  targets: "c cpp"

+  matrix: "--mm:arc; --mm:orc"

+"""

+

+block:

+  type

+    PublicKey = array[32, uint8]

+    PrivateKey = array[64, uint8]

+

+  proc ed25519_create_keypair(publicKey: ptr PublicKey; privateKey: ptr PrivateKey) =

+    publicKey[][0] = uint8(88)

+

+  type

+    KeyPair = object

+      public: PublicKey

+      private: PrivateKey

+

+  proc initKeyPair(): KeyPair =

+    ed25519_create_keypair(result.public.addr, result.private.addr)

+

+  let keys = initKeyPair()

+  doAssert keys.public[0] == 88

+

+

+template minIndexByIt: untyped =

+  var other = 3

+  other

+

+proc bug20303() =

+  var hlibs = @["hello", "world", "how", "are", "you"]

+  let res = hlibs[minIndexByIt()]

+  doAssert res == "are"

+

+bug20303()

+

+proc main() = # todo bug with templates

+  block: # bug #11267

+    var a: seq[char] = block: @[]

+    doAssert a == @[]

+    # 2

+    proc b: seq[string] =

+      discard

+      @[]

+    doAssert b() == @[]

+static: main()

+main()

+

+

+type Obj = tuple

+  value: int

+  arr: seq[int]

+

+proc bug(): seq[Obj] =

+  result.add (value: 0, arr: @[])

+  result[^1].value = 1

+  result[^1].arr.add 1

+

+# bug #19990

+let s = bug()

+doAssert s[0] == (value: 1, arr: @[1])

+

+block: # bug #21974

+  type Test[T] = ref object

+      values : seq[T]

+      counter: int

+

+  proc newTest[T](): Test[T] =

+      result         = new(Test[T])

+      result.values  = newSeq[T](16)

+      result.counter = 0

+

+  proc push[T](self: Test[T], value: T) =

+      self.counter += 1

+      if self.counter >= self.values.len:

+          self.values.setLen(self.values.len * 2)

+      self.values[self.counter - 1] = value

+

+  proc pop[T](self: Test[T]): T =

+      result         = self.values[0]

+      self.values[0] = self.values[self.counter - 1] # <--- This line

+      self.counter  -= 1

+

+

+  type X = tuple

+      priority: int

+      value   : string

+

+  var a = newTest[X]()

+  a.push((1, "One"))

+  doAssert a.pop.value == "One"

+

+# bug #21987

+

+type

+  EmbeddedImage* = distinct Image

+  Image = object

+    len: int

+

+proc imageCopy*(image: Image): Image {.nodestroy.}

+

+proc `=destroy`*(x: Image) =

+  discard

+

+proc `=sink`*(dest: var Image; source: Image) =

+  `=destroy`(dest)

+  wasMoved(dest)

+

+proc `=dup`*(source: Image): Image {.nodestroy.} =

+  result = imageCopy(source)

+

+proc `=copy`*(dest: var Image; source: Image) =

+  dest = imageCopy(source) # calls =sink implicitly

+

+proc `=destroy`*(x: EmbeddedImage) = discard

+

+proc `=dup`*(source: EmbeddedImage): EmbeddedImage {.nodestroy.} = source

+

+proc `=copy`*(dest: var EmbeddedImage; source: EmbeddedImage) {.nodestroy.} =

+  dest = source

+

+proc imageCopy*(image: Image): Image =

+  result = image

+

+proc main2 =

+  block:

+    var a = Image(len: 2).EmbeddedImage

+    var b = Image(len: 1).EmbeddedImage

+    b = a

+    doAssert Image(a).len == 2

+    doAssert Image(b).len == 2

+

+  block:

+    var a = Image(len: 2)

+    var b = Image(len: 1)

+    b = a

+    doAssert a.len == 2

+    doAssert b.len == 0

+

+main2()

+

+type

+  Edge = object

+    neighbor {.cursor.}: Node

+

+  NodeObj = object

+    neighbors: seq[Edge]

+    label: string

+    visited: bool

+  Node = ref NodeObj

+

+  Graph = object

+    nodes: seq[Node]

+

+proc `=destroy`(x: NodeObj) =

+  `=destroy`(x.neighbors)

+  `=destroy`(x.label)

+

+proc addNode(self: var Graph; label: string): Node =

+  self.nodes.add(Node(label: label))

+  result = self.nodes[^1]

+

+proc addEdge(self: Graph; source, neighbor: Node) =

+  source.neighbors.add(Edge(neighbor: neighbor))

+

+block:

+  proc main =

+    var graph: Graph

+    let nodeA = graph.addNode("a")

+    let nodeB = graph.addNode("b")

+    let nodeC = graph.addNode("c")

+

+    graph.addEdge(nodeA, neighbor = nodeB)

+    graph.addEdge(nodeA, neighbor = nodeC)

+

+  main()

+

+block:

+  type RefObj = ref object

+

+  proc `[]`(val: static[int]) = # works with different name/overload or without static arg

+    discard

+

+  template noRef(T: typedesc): typedesc = # works without template indirection

+    typeof(default(T)[])

+

+  proc `=destroy`(x: noRef(RefObj)) =

+    discard

+

+  proc foo =

+    var x = new RefObj

+    doAssert $(x[]) == "()"

+

+  # bug #11705

+  foo()

+

+block: # bug #22197

+  type

+    H5IdObj = object

+    H5Id = ref H5IdObj

+

+    FileID = distinct H5Id

+

+    H5GroupObj = object

+      file_id: FileID

+    H5Group = ref H5GroupObj

+

+  ## This would make it work!

+  #proc `=destroy`*(x: FileID) = `=destroy`(cast[H5Id](x))

+  ## If this does not exist, it also works!

+  proc newFileID(): FileID = FileID(H5Id())

+

+  proc `=destroy`(grp: H5GroupObj) =

+    ## Closes the group and resets all references to nil.

+    if cast[pointer](grp.fileId) != nil:

+      `=destroy`(grp.file_id)

+

+  var grp = H5Group()

+  reset(grp.file_id)

+  reset(grp)

+

+import std/tables

+

+block: # bug #22286

+  type

+    A = object

+    B = object

+      a: A

+    C = object

+      b: B

+

+  proc `=destroy`(self: A) =

+    echo "destroyed"

+

+  proc `=destroy`(self: C) =

+    `=destroy`(self.b)

+

+  var c = C()

+

+block: # https://forum.nim-lang.org/t/10642

+  type AObj = object

+    name: string

+    tableField: Table[string, string]

+

+  proc `=destroy`(x: AObj) =

+    `=destroy`(x.name)

+    `=destroy`(x.tableField)

diff --git a/tests/destructor/topttree.nim b/tests/destructor/topttree.nim
index fa5495689..8cf757e8b 100644
--- a/tests/destructor/topttree.nim
+++ b/tests/destructor/topttree.nim
@@ -1,4 +1,5 @@
 discard """
+  disabled: i386
   output: '''10.0
 60.0
 90.0
diff --git a/tests/destructor/towned_binary_tree.nim b/tests/destructor/towned_binary_tree.nim
index 3ec80badf..fb635e7c6 100644
--- a/tests/destructor/towned_binary_tree.nim
+++ b/tests/destructor/towned_binary_tree.nim
@@ -1,7 +1,7 @@
 discard """
-  cmd: '''nim c -d:nimAllocStats --newruntime $file'''
-  output: '''331665
-(allocCount: 333335, deallocCount: 333335)'''
+  cmd: '''nim c -d:nimAllocStats --gc:arc $file'''
+  output: '''31665
+(allocCount: 33334, deallocCount: 33334)'''
 """
 
 #  bug #11053
@@ -72,7 +72,7 @@ proc main() =
     cur = 5'i32
     res = 0
 
-  for i in 1 ..< 1000000:
+  for i in 1 ..< 100000:
     let a = i mod 3
     cur = (cur * 57 + 43) mod 10007
     case a:
diff --git a/tests/destructor/tprevent_assign.nim b/tests/destructor/tprevent_assign.nim
index 108ccc371..4c484ebc1 100644
--- a/tests/destructor/tprevent_assign.nim
+++ b/tests/destructor/tprevent_assign.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "'=' is not available for type <Foo>; requires a copy because it's not the last read of 'otherTree'"
+  errormsg: "'=copy' is not available for type <Foo>; requires a copy because it's not the last read of 'otherTree'"
   line: 29
 """
 
diff --git a/tests/destructor/tprevent_assign2.nim b/tests/destructor/tprevent_assign2.nim
index 0e4481710..eb5588b1a 100644
--- a/tests/destructor/tprevent_assign2.nim
+++ b/tests/destructor/tprevent_assign2.nim
@@ -1,7 +1,7 @@
 discard """
-  errormsg: "'=' is not available for type <Foo>; requires a copy because it's not the last read of 'otherTree'"
+  errormsg: "'=dup' is not available for type <Foo>, which is inferred from unavailable '=copy'; requires a copy because it's not the last read of 'otherTree'; another read is done here: tprevent_assign2.nim(51, 31); routine: preventThis"
   file: "tprevent_assign2.nim"
-  line: 48
+  line: 49
 """
 
 type
@@ -9,7 +9,8 @@ type
     x: int
 
 proc `=destroy`(f: var Foo) = f.x = 0
-proc `=`(a: var Foo; b: Foo) {.error.} # = a.x = b.x
+proc `=copy`(a: var Foo; b: Foo) {.error.} # = a.x = b.x
+
 proc `=sink`(a: var Foo; b: Foo) = a.x = b.x
 
 proc createTree(x: int): Foo =
@@ -18,7 +19,7 @@ proc createTree(x: int): Foo =
 proc take2(a, b: sink Foo) =
   echo a.x, " ", b.x
 
-proc allowThis() =
+when false:
   var otherTree: Foo
   try:
     for i in 0..3:
@@ -51,5 +52,5 @@ proc preventThis() =
       else:
         discard
 
-allowThis()
+#allowThis()
 preventThis()
diff --git a/tests/destructor/tprevent_assign3.nim b/tests/destructor/tprevent_assign3.nim
index a8a35ea5e..aa834a66c 100644
--- a/tests/destructor/tprevent_assign3.nim
+++ b/tests/destructor/tprevent_assign3.nim
@@ -1,7 +1,7 @@
 discard """
-  errormsg: "'=' is not available for type <Foo>; requires a copy because it's not the last read of 'otherTree'"
+  errormsg: "'=dup' is not available for type <Foo>; requires a copy because it's not the last read of 'otherTree'"
   file: "tprevent_assign3.nim"
-  line: 46
+  line: 47
 """
 
 type
@@ -9,7 +9,8 @@ type
     x: int
 
 proc `=destroy`(f: var Foo) = f.x = 0
-proc `=`(a: var Foo; b: Foo) {.error.} # = a.x = b.x
+proc `=copy`(a: var Foo; b: Foo) {.error.} # = a.x = b.x
+proc `=dup`(a: Foo): Foo {.error.}
 proc `=sink`(a: var Foo; b: Foo) = a.x = b.x
 
 proc createTree(x: int): Foo =
@@ -18,7 +19,7 @@ proc createTree(x: int): Foo =
 proc take2(a, b: sink Foo) =
   echo a.x, " ", b.x
 
-proc allowThis() =
+when false:
   var otherTree: Foo
   try:
     for i in 0..3:
@@ -47,7 +48,7 @@ proc preventThis2() =
   finally:
     echo otherTree
 
-allowThis()
+#allowThis()
 preventThis2()
 
 
diff --git a/tests/destructor/trecursive.nim b/tests/destructor/trecursive.nim
index 55e67f52a..e7afa6ba9 100644
--- a/tests/destructor/trecursive.nim
+++ b/tests/destructor/trecursive.nim
@@ -32,3 +32,29 @@ proc test1() =
   echo "test1 OK"
 
 test1()
+
+#------------------------------------------------------------------------------
+# issue #14217
+
+type
+  MyObject = object
+    p: ptr int
+
+proc `=destroy`(x: var MyObject) =
+  if x.p != nil:
+    deallocShared(x.p)
+
+proc `=`(x: var MyObject, y: MyObject) {.error.}
+
+proc newMyObject(i: int): MyObject = 
+  result.p = createShared(int)
+  result.p[] = i
+
+proc test: seq[MyObject] = 
+  for i in 0..3:
+    let x = newMyObject(i)
+    result.add x
+
+var x = test()
+for i in 0..3:
+  doAssert(x[i].p[] == i)
diff --git a/tests/destructor/tselect.nim b/tests/destructor/tselect.nim
index 9262b47d4..c22bf7203 100644
--- a/tests/destructor/tselect.nim
+++ b/tests/destructor/tselect.nim
@@ -1,6 +1,9 @@
 discard """
    output: '''abcsuffix
-xyzsuffix'''
+xyzsuffix
+destroy foo 2
+destroy foo 1
+'''
   cmd: '''nim c --gc:arc $file'''
 """
 
@@ -24,3 +27,24 @@ proc test(param: string; cond: bool) =
 
 test("suffix", true)
 test("suffix", false)
+
+
+
+#--------------------------------------------------------------------
+# issue #13659
+
+type
+  Foo = ref object
+    data: int
+    parent: Foo
+
+proc `=destroy`(self: var type(Foo()[])) =
+  echo "destroy foo ", self.data
+  for i in self.fields: i.reset
+
+proc getParent(self: Foo): Foo = self.parent
+
+var foo1 = Foo(data: 1)
+var foo2 = Foo(data: 2, parent: foo1)
+
+foo2.getParent.data = 1
\ No newline at end of file
diff --git a/tests/destructor/tsetjmp_raise.nim b/tests/destructor/tsetjmp_raise.nim
index b6078ada2..3a9803f39 100644
--- a/tests/destructor/tsetjmp_raise.nim
+++ b/tests/destructor/tsetjmp_raise.nim
@@ -1,5 +1,5 @@
 discard """
-  outputsub: "index 2 not in 0 .. 0 [IndexError]"
+  outputsub: "index 2 not in 0 .. 0 [IndexDefect]"
   exitcode: 1
   cmd: "nim c --gc:arc --exceptions:setjmp $file"
 """
diff --git a/tests/destructor/tsimpleclosure.nim b/tests/destructor/tsimpleclosure.nim
index 4916f4bab..9626dd6f8 100644
--- a/tests/destructor/tsimpleclosure.nim
+++ b/tests/destructor/tsimpleclosure.nim
@@ -1,11 +1,11 @@
 discard """
-  cmd: '''nim c -d:nimAllocStats --newruntime $file'''
+  cmd: '''nim c -d:nimAllocStats --gc:arc $file'''
   output: '''a b
 70
 hello
 hello
 hello
-(allocCount: 4, deallocCount: 4)'''
+(allocCount: 3, deallocCount: 3)'''
 """
 
 import system / ansi_c
diff --git a/tests/destructor/tsink.nim b/tests/destructor/tsink.nim
new file mode 100644
index 000000000..e8750ad7c
--- /dev/null
+++ b/tests/destructor/tsink.nim
@@ -0,0 +1,70 @@
+discard """
+  matrix: "--mm:arc"
+"""
+
+type AnObject = object of RootObj
+  value*: int
+
+proc mutate(shit: sink AnObject) =
+  shit.value = 1
+
+proc foo = # bug #23359
+  var bar = AnObject(value: 42)
+  mutate(bar)
+  doAssert bar.value == 42
+
+foo()
+
+block: # bug #23902
+  proc foo(a: sink string): auto = (a, a)
+
+  proc bar(a: sink int): auto = return a
+
+  proc foo(a: sink string) =
+    var x = (a, a)
+
+block: # bug #24175
+  block:
+    func mutate(o: sink string): string =
+      o[1] = '1'
+      result = o
+
+    static:
+      let s = "999"
+      let m = mutate(s)
+      doAssert s == "999"
+      doAssert m == "919"
+
+    func foo() =
+      let s = "999"
+      let m = mutate(s)
+      doAssert s == "999"
+      doAssert m == "919"
+
+    static:
+      foo()
+    foo()
+
+  block:
+    type O = object
+      a: int
+
+    func mutate(o: sink O): O =
+      o.a += 1
+      o
+
+    static:
+      let x = O(a: 1)
+      let y = mutate(x)
+      doAssert x.a == 1
+      doAssert y.a == 2
+
+    proc foo() =
+      let x = O(a: 1)
+      let y = mutate(x)
+      doAssert x.a == 1
+      doAssert y.a == 2
+
+    static:
+      foo()
+    foo()
diff --git a/tests/destructor/ttuple.nim b/tests/destructor/ttuple.nim
index 5a2126105..d0ea72c60 100644
--- a/tests/destructor/ttuple.nim
+++ b/tests/destructor/ttuple.nim
@@ -2,7 +2,7 @@
 discard """
    output: '''5.0 10.0
 =destroy
-=destroy   
+=destroy
 '''
 """
 
diff --git a/tests/destructor/tuse_ownedref_after_move.nim b/tests/destructor/tuse_ownedref_after_move.nim
index 46540837c..69348d530 100644
--- a/tests/destructor/tuse_ownedref_after_move.nim
+++ b/tests/destructor/tuse_ownedref_after_move.nim
@@ -1,6 +1,6 @@
 discard """
   cmd: '''nim c --newruntime $file'''
-  errormsg: "'=' is not available for type <owned Button>; requires a copy because it's not the last read of ':envAlt.b1'; another read is done here: tuse_ownedref_after_move.nim(52, 4)"
+  errormsg: "'=copy' is not available for type <owned Button>; requires a copy because it's not the last read of ':envAlt.b1'; routine: main"
   line: 48
 """
 
diff --git a/tests/destructor/tuse_result_prevents_sinks.nim b/tests/destructor/tuse_result_prevents_sinks.nim
index 37b5af9b2..e74c16da3 100644
--- a/tests/destructor/tuse_result_prevents_sinks.nim
+++ b/tests/destructor/tuse_result_prevents_sinks.nim
@@ -1,6 +1,6 @@
 discard """
   output: ""
-  target: "C"
+  targets: "c"
 """
 
 # bug #9594
@@ -17,15 +17,20 @@ proc `=sink`(self: var Foo; other: Foo) =
 
 proc `=destroy`(self: var Foo) = discard
 
+template preventCursorInference(x) =
+  let p = addr(x)
+
 proc test(): Foo =
   result = Foo()
   let temp = result
+  preventCursorInference temp
   doAssert temp.i > 0
   return result
 
 proc testB(): Foo =
   result = Foo()
   let temp = result
+  preventCursorInference temp
   doAssert temp.i > 0
 
 discard test()
diff --git a/tests/destructor/tv2_cast.nim b/tests/destructor/tv2_cast.nim
index 9c05b2ae1..48bdf67dd 100644
--- a/tests/destructor/tv2_cast.nim
+++ b/tests/destructor/tv2_cast.nim
@@ -1,10 +1,81 @@
 discard """
-  cmd: '''nim c --newruntime $file'''
   output: '''@[1]
 @[116, 101, 115, 116]
-@[1953719668, 875770417]'''
+@[1953719668, 875770417]
+destroying O1'''
+  cmd: '''nim c --mm:arc --expandArc:main --expandArc:main1 --expandArc:main2 --expandArc:main3 --hints:off --assertions:off $file'''
+  nimout: '''
+--expandArc: main
+
+var
+  data
+  :tmpD
+data = cast[string](encode(cast[seq[byte]](
+  :tmpD = newString(100)
+  :tmpD)))
+`=destroy`(:tmpD)
+`=destroy`(data)
+-- end of expandArc ------------------------
+--expandArc: main1
+
+var
+  s
+  data
+s = newString(100)
+data = cast[string](encode(toOpenArrayByte(s, 0, len(s) - 1)))
+`=destroy`(data)
+`=destroy`(s)
+-- end of expandArc ------------------------
+--expandArc: main2
+
+var
+  s
+  data
+s = newSeq(100)
+data = cast[string](encode(s))
+`=destroy`(data)
+`=destroy_1`(s)
+-- end of expandArc ------------------------
+--expandArc: main3
+
+var
+  data
+  :tmpD
+data = cast[string](encode do:
+  :tmpD = newSeq(100)
+  :tmpD)
+`=destroy`(:tmpD)
+`=destroy_1`(data)
+-- end of expandArc ------------------------
+'''
 """
 
+func encode*(src: openArray[byte]): seq[byte] =
+  result = newSeq[byte](src.len)
+
+template compress*(src: string): string =
+  cast[string](encode(cast[seq[byte]](src)))
+
+proc main =
+  let data = compress(newString(100))
+main()
+
+proc main1 =
+  var
+    s = newString(100)
+  let data = cast[string](encode(s.toOpenArrayByte(0, s.len-1)))
+main1()
+
+proc main2 =
+  var
+    s = newSeq[byte](100)
+  let data = cast[string](encode(s))
+main2()
+
+proc main3 =
+  let data = cast[string](encode(newSeq[byte](100)))
+main3()
+
 # bug #11018
 discard cast[seq[uint8]](@[1])
 discard cast[seq[uint8]]("test")
@@ -20,4 +91,26 @@ echo a
 
 #issue 11204
 var ac {.compileTime.} = @["a", "b"]
-const bc = ac.len
\ No newline at end of file
+const bc = ac.len
+
+
+type
+  O = object of RootRef
+    i: int
+
+  O1 = object of O
+  O2 = object of O
+
+proc `=destroy`(o: var O) =
+  echo "destroying O"
+
+proc `=destroy`(o: var O1) =
+  echo "destroying O1"
+
+proc `=destroy`(o: var O2) =
+  echo "destroying O2"
+
+proc test =
+  let o3 = cast[ref O2]((ref O1)())
+
+test()
diff --git a/tests/destructor/tv2_raise.nim b/tests/destructor/tv2_raise.nim
index 828d0a396..66b0aec30 100644
--- a/tests/destructor/tv2_raise.nim
+++ b/tests/destructor/tv2_raise.nim
@@ -2,7 +2,7 @@ discard """
   valgrind: true
   cmd: '''nim c -d:nimAllocStats --newruntime $file'''
   output: '''OK 3
-(allocCount: 8, deallocCount: 3)'''
+(allocCount: 7, deallocCount: 4)'''
 """
 
 import strutils, math
diff --git a/tests/destructor/twasmoved.nim b/tests/destructor/twasmoved.nim
new file mode 100644
index 000000000..566322702
--- /dev/null
+++ b/tests/destructor/twasmoved.nim
@@ -0,0 +1,14 @@
+type
+  Foo = object
+    id: int
+
+proc `=wasMoved`(x: var Foo) =
+  x.id = -1
+
+proc foo =
+  var s = Foo(id: 999)
+  var m = move s
+  doAssert s.id == -1
+  doAssert m.id == 999
+
+foo()
diff --git a/tests/destructor/twasmoved_error.nim b/tests/destructor/twasmoved_error.nim
new file mode 100644
index 000000000..1cd57e3df
--- /dev/null
+++ b/tests/destructor/twasmoved_error.nim
@@ -0,0 +1,37 @@
+discard """
+  cmd: '''nim c --mm:arc $file'''
+  errormsg: "'=wasMoved' is not available for type <Game>; routine: main"
+"""
+
+# bug #19291
+
+const
+  screenWidth = 800
+  screenHeight = 450
+
+var
+  ready = false
+type
+  Game = object
+
+proc `=destroy`(x: var Game) =
+  assert ready, "Window is already opened"
+  ready = false
+
+proc `=sink`(x: var Game; y: Game) {.error.}
+proc `=copy`(x: var Game; y: Game) {.error.}
+proc `=wasMoved`(x: var Game) {.error.}
+
+proc initGame(width, height: int32, title: string): Game =
+  assert not ready, "Window is already closed"
+  ready = true
+
+proc update(x: Game) = discard
+
+proc main =
+  var g = initGame(screenWidth, screenHeight, "Tetris raylib")
+  g.update()
+  var g2 = g
+  echo "hello"
+
+main()
diff --git a/tests/destructor/twidgets_unown.nim b/tests/destructor/twidgets_unown.nim
index 1d2f26f2a..8653d5c28 100644
--- a/tests/destructor/twidgets_unown.nim
+++ b/tests/destructor/twidgets_unown.nim
@@ -2,7 +2,7 @@ discard """
   cmd: '''nim c -d:nimAllocStats --newruntime $file'''
   output: '''button
 clicked!
-(allocCount: 9, deallocCount: 9)'''
+(allocCount: 6, deallocCount: 6)'''
 """
 
 import system / ansi_c
diff --git a/tests/discard/t23677.nim b/tests/discard/t23677.nim
new file mode 100644
index 000000000..1ed7386bd
--- /dev/null
+++ b/tests/discard/t23677.nim
@@ -0,0 +1,12 @@
+discard """
+  errormsg: "expression '0' is of type 'int literal(0)' and has to be used (or discarded); start of expression here: t23677.nim(1, 1)"
+  line: 10
+  column: 3
+"""
+
+# issue #23677
+
+if true:
+  0
+else: 
+  raise newException(ValueError, "err") 
diff --git a/tests/discard/tdiscardable.nim b/tests/discard/tdiscardable.nim
index 032050139..84b669ed8 100644
--- a/tests/discard/tdiscardable.nim
+++ b/tests/discard/tdiscardable.nim
@@ -5,6 +5,7 @@ tdiscardable
 1
 something defered
 something defered
+hi
 '''
 """
 
@@ -65,3 +66,110 @@ proc main2() =
 
 main1()
 main2()
+
+block: # bug #13583
+  block:
+    proc hello(): int {.discardable.} = 12
+
+    iterator test(): int {.closure.} =
+      while true:
+        hello()
+
+    let t = test
+
+  block:
+    proc hello(): int {.discardable.} = 12
+
+    iterator test(): int {.closure.} =
+      while true:
+        block:
+          yield 12
+          hello()
+
+    let t = test
+    doAssert t() == 12
+
+  block:
+    proc hello(): int {.discardable.} = 12
+
+    iterator test(): int {.closure.} =
+      while true:
+        yield 12
+        hello()
+
+    let t = test
+    doAssert t() == 12
+
+block:
+  proc bar(): string {.discardable.} =
+    "15"
+
+  proc foo(): int =
+    while true:
+      raise newException(ValueError, "check")
+    12
+
+  doAssertRaises(ValueError):
+    doAssert foo() == 12
+
+block: # issue #10440
+  proc x(): int {.discardable.} = discard
+  try:
+    x()
+  finally:
+    echo "hi"
+
+import macros
+
+block: # issue #14665
+  macro test(): untyped =   
+    let b = @[1, 2, 3, 4]
+
+    result = nnkStmtList.newTree()
+    var i = 0
+    while i < b.len:
+      if false:
+        # this quote do is mandatory, removing it fixes the problem
+        result.add quote do:
+          let testtest = 5
+      else:
+        result.add quote do:
+          let test = 6
+        inc i
+        # removing this continue fixes the problem too
+        continue
+      inc i
+  test()
+
+block: # bug #23775
+  proc retInt(): int {.discardable.} =
+    42
+
+  proc retString(): string {.discardable.} =
+    "text"
+
+  type
+    Enum = enum
+      A, B, C, D
+
+  proc doStuff(msg: Enum) =
+    case msg:
+    of A:
+      retString()
+    of B:
+      retInt()
+    of C:
+      discard retString()
+    else:
+      let _ = retString()
+
+  doStuff(C)
+
+block:
+  proc test(): (int, int) {.discardable.} =
+    discard
+
+  if true:
+    test()
+  else:
+    quit()
diff --git a/tests/discard/tfinallyerrmsg.nim b/tests/discard/tfinallyerrmsg.nim
new file mode 100644
index 000000000..fbc8140aa
--- /dev/null
+++ b/tests/discard/tfinallyerrmsg.nim
@@ -0,0 +1,19 @@
+discard """
+  cmd: "nim check $file"
+"""
+
+block: # issue #19672
+  try:
+    10 #[tt.Error
+    ^ expression '10' is of type 'int literal(10)' and has to be used (or discarded); start of expression here: tfinallyerrmsg.nim(5, 1)]#
+  finally:
+    echo "Finally block"
+
+block: # issue #13871
+  template t(body: int) =
+    try:
+      body
+    finally:
+      echo "expression"
+  t: 2 #[tt.Error
+     ^ expression '2' is of type 'int literal(2)' and has to be used (or discarded)]#
diff --git a/tests/discard/tillegaldiscardtypes.nim b/tests/discard/tillegaldiscardtypes.nim
new file mode 100644
index 000000000..b7877bcd2
--- /dev/null
+++ b/tests/discard/tillegaldiscardtypes.nim
@@ -0,0 +1,14 @@
+discard """
+  cmd: "nim check $file"
+  errormsg: "statement returns no value that can be discarded"
+  nimout: '''
+tillegaldiscardtypes.nim(11, 3) Error: statement returns no value that can be discarded
+tillegaldiscardtypes.nim(12, 3) Error: statement returns no value that can be discarded
+'''
+"""
+
+proc b(v: int) = # bug #21360
+  discard @[]
+  discard []
+
+b(0)
\ No newline at end of file
diff --git a/tests/discard/tneedsdiscard.nim b/tests/discard/tneedsdiscard.nim
index d9483947f..75cd9d2df 100644
--- a/tests/discard/tneedsdiscard.nim
+++ b/tests/discard/tneedsdiscard.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: '''expression 'open(f, "arg.txt", fmRead, -1)' is of type 'bool' and has to be discarded; start of expression here: tneedsdiscard.nim(7, 3)'''
+  errormsg: '''expression 'open(f, "arg.txt", fmRead, -1)' is of type 'bool' and has to be used (or discarded); start of expression here: tneedsdiscard.nim(7, 3)'''
   line: 10
 """
 
diff --git a/tests/discard/tneedsdiscard_in_for.nim b/tests/discard/tneedsdiscard_in_for.nim
index 499b06009..7685bd577 100644
--- a/tests/discard/tneedsdiscard_in_for.nim
+++ b/tests/discard/tneedsdiscard_in_for.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: '''expression 'premultiply(app.gradient[i])' is of type 'Rgba8' and has to be discarded'''
+  errormsg: '''expression 'premultiply(app.gradient[i])' is of type 'Rgba8' and has to be used (or discarded)'''
   line: 22
 """
 
@@ -8,7 +8,7 @@ type
   Rgba8 = object
 
 proc premultiply*(c: var Rgba8): var Rgba8 =
-  discard
+  return c
 
 type
   App = ref object
diff --git a/tests/discard/tvoidcontext.nim b/tests/discard/tvoidcontext.nim
index 25e0d4fdf..9e2b913ad 100644
--- a/tests/discard/tvoidcontext.nim
+++ b/tests/discard/tvoidcontext.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: '''expression '"invalid"' is of type 'string' and has to be discarded'''
+  errormsg: '''expression '"invalid"' is of type 'string' and has to be used (or discarded)'''
   line: 12
 """
 
diff --git a/tests/distinct/t7165.nim b/tests/distinct/t7165.nim
new file mode 100644
index 000000000..b16c29c0e
--- /dev/null
+++ b/tests/distinct/t7165.nim
@@ -0,0 +1,15 @@
+
+type
+  Table[K, V] = object
+    key: K
+    val: V
+
+  MyTable = distinct Table[string, int]
+  MyTableRef = ref MyTable
+
+proc newTable[K, V](): ref Table[K, V] = discard
+
+proc newMyTable: MyTableRef =
+  MyTableRef(newTable[string, int]()) # <--- error here
+
+discard newMyTable()
diff --git a/tests/distinct/tborrow.nim b/tests/distinct/tborrow.nim
new file mode 100644
index 000000000..e34248de5
--- /dev/null
+++ b/tests/distinct/tborrow.nim
@@ -0,0 +1,132 @@
+discard """
+  output: '''4887 true
+0.5'''
+"""
+
+# test the new borrow feature that works with generics:
+
+proc `++`*[T: int | float](a, b: T): T =
+  result = a + b
+
+type
+  DI = distinct int
+  DF = distinct float
+  DS = distinct string
+
+proc `++`(x, y: DI): DI {.borrow.}
+proc `++`(x, y: DF): DF {.borrow.}
+
+proc `$`(x: DI): string {.borrow.}
+proc `$`(x: DF): string {.borrow.}
+
+echo  4544.DI ++ 343.DI, " ", (4.5.DF ++ 0.5.DF).float == 5.0
+
+# issue #14440
+
+type Radians = distinct float64
+
+func `-=`(a: var Radians, b: Radians) {.borrow.}
+
+var a = Radians(1.5)
+let b = Radians(1.0)
+
+a -= b
+
+echo a.float64
+
+block: #14449
+  type 
+    Foo[T] = object
+      foo: T
+
+    Bar[T] {.borrow:`.`.} = distinct Foo[T]
+    SomeThing {.borrow:`.`.} = distinct Foo[float]
+    OtherThing {.borrow:`.`.} = distinct SomeThing
+
+  var
+    a: Bar[int]
+    b: SomeThing
+    c: OtherThing
+  a.foo = 300
+  b.foo = 400
+  c.foo = 42
+  assert a.foo == 300
+  assert b.foo == 400d
+  assert c.foo == 42d
+
+block: # Borrow from muliple aliasses #16666
+  type
+    AImpl = object
+      i: int
+    
+    A = AImpl
+  
+    B {.borrow: `.`.} = distinct A
+    C = B
+    D {.borrow: `.`.} = distinct C
+    E {.borrow: `.`.} = distinct D
+  
+  let
+    b = default(B)
+    d = default(D)
+    e = default(E)
+  
+  assert b.i == 0
+  assert d.i == 0
+  assert e.i == 0
+
+block: # Borrow from generic alias
+  type
+    AImpl[T] = object
+      i: T
+    B[T] = AImpl[T]
+    C {.borrow: `.`.} = distinct B[int]
+    D = B[float]
+    E {.borrow: `.`.} = distinct D
+
+  let
+    c = default(C)
+    e = default(E)
+  assert c.i == int(0)
+  assert e.i == 0d
+
+block: # issue #22069
+  type
+    Vehicle[C: static[int]] = object
+      color: array[C, int]
+    Car[C: static[int]] {.borrow: `.`.} = distinct Vehicle[C]
+    MuscleCar = Car[128]
+  var x: MuscleCar
+  doAssert x.color is array[128, int]
+
+block: # issue #22646
+  type
+    Vec[N : static[int], T: SomeNumber] = object
+      arr: array[N, T]
+    Vec3[T: SomeNumber] = Vec[3, T]
+
+  proc `[]=`[N,T](v: var Vec[N,T]; ix:int; c:T): void {.inline.} = v.arr[ix] = c
+  proc `[]`[N,T](v: Vec[N,T]; ix: int): T {.inline.} = v.arr[ix]
+
+  proc dot[N,T](u,v: Vec[N,T]): T {. inline .} = discard
+  proc length[N,T](v: Vec[N,T]): T = discard
+  proc cross[T](v1,v2:Vec[3,T]): Vec[3,T] = discard
+  proc normalizeWorks[T](v: Vec[3,T]): Vec[3,T] = discard ## <- Explicit size makes it work!
+  proc foo[N,T](u, v: Vec[N,T]): Vec[N,T] = discard ## <- broken
+  proc normalize[N,T](v: Vec[N,T]): Vec[N,T] = discard ## <- broken
+
+  type Color = distinct Vec3[float]
+
+  template borrowOps(typ: typedesc): untyped =
+    proc `[]=`(v: var typ; ix: int; c: float): void {.borrow.}
+    proc `[]`(v: typ; ix: int): float {.borrow.}
+    proc dot(v, u: typ): float {.borrow.}
+    proc cross(v, u: typ): typ {.borrow.}
+    proc length(v: typ): float {.borrow.}
+    proc normalizeWorks(v: typ): typ {.borrow.} ## Up to here everything works
+    proc foo(u, v: typ): typ {.borrow.} ## Broken
+    proc normalize(v: typ): typ {.borrow.} ## Broken
+  borrowOps(Color)
+  var x: Vec[3, float]
+  let y = Color(x)
+  doAssert Vec3[float](y) == x
diff --git a/tests/distinct/tcomplexaddressableconv.nim b/tests/distinct/tcomplexaddressableconv.nim
new file mode 100644
index 000000000..00e96bfeb
--- /dev/null
+++ b/tests/distinct/tcomplexaddressableconv.nim
@@ -0,0 +1,21 @@
+# issue #22523
+
+from std/typetraits import distinctBase
+
+type
+  V[p: static int] = distinct int
+  D[p: static int] = distinct int
+  T = V[1]
+
+proc f(y: var T) = discard
+
+var a: D[0]
+
+static:
+  doAssert distinctBase(T) is distinctBase(D[0])
+  doAssert distinctBase(T) is int
+  doAssert distinctBase(D[0]) is int
+  doAssert T(a) is T
+
+f(cast[ptr T](addr a)[])
+f(T(a))
diff --git a/tests/distinct/tdistinct.nim b/tests/distinct/tdistinct.nim
index 2c0196745..b6ba7aa99 100644
--- a/tests/distinct/tdistinct.nim
+++ b/tests/distinct/tdistinct.nim
@@ -1,4 +1,5 @@
 discard """
+  targets: "c js"
   output: '''
 tdistinct
 25
@@ -7,6 +8,7 @@ false
 false
 false
 Foo
+foo
 '''
 """
 
@@ -106,3 +108,120 @@ type FooD = distinct int
 proc `<=`(a, b: FooD): bool {.borrow.}
 
 for f in [FooD(0): "Foo"]: echo f
+
+block tRequiresInit:
+  template accept(x) =
+    static: doAssert compiles(x)
+
+  template reject(x) =
+    static: doAssert not compiles(x)
+
+  type
+    Foo = object
+      x: string
+
+    DistinctFoo {.requiresInit, borrow: `.`.} = distinct Foo
+    DistinctString {.requiresInit.} = distinct string
+
+  reject:
+    var foo: DistinctFoo
+    foo.x = "test"
+    doAssert foo.x == "test"
+
+  accept:
+    let foo = DistinctFoo(Foo(x: "test"))
+    doAssert foo.x == "test"
+
+  reject:
+    var s: DistinctString
+    s = "test"
+    doAssert string(s) == "test"
+
+  accept:
+    let s = DistinctString("test")
+    doAssert string(s) == "test"
+
+block: #17322
+  type
+    A[T] = distinct string
+
+  proc foo(a: var A) =
+    a.string.add "foo"
+
+  type
+    B = distinct A[int]
+
+  var b: B
+  foo(A[int](b))
+  echo A[int](b).string
+  b.string.add "bar"
+  assert b.string == "foobar"
+
+type Foo = distinct string
+
+proc main() = # proc instead of template because of MCS/UFCS.
+  # xxx put everything here to test under RT + VM
+  block: # bug #12282
+    block:
+      proc test() =
+        var s: Foo
+        s.string.add('c')
+        doAssert s.string == "c" # was failing
+      test()
+
+    block:
+      proc add(a: var Foo, b: char) {.borrow.}
+      proc test() =
+        var s: Foo
+        s.add('c')
+        doAssert s.string == "c" # was ok
+      test()
+
+    block:
+      proc add(a: var Foo, b: char) {.borrow.}
+      proc test() =
+        var s: string
+        s.Foo.add('c')
+        doAssert s.string == "c" # was failing
+      test()
+    block: #18061
+      type
+        A = distinct (0..100)
+        B = A(0) .. A(10)
+      proc test(b: B) = discard
+      let
+        a = A(10)
+        b = B(a)
+      test(b)
+
+      proc test(a: A) = discard
+      discard cast[B](A(1))
+      var c: B
+
+
+  block: # bug #9423
+    block:
+      type Foo = seq[int]
+      type Foo2 = distinct Foo
+      template fn() =
+        var a = Foo2(@[1])
+        a.Foo.add 2
+        doAssert a.Foo == @[1, 2]
+      fn()
+
+    block:
+      type Stack[T] = distinct seq[T]
+      proc newStack[T](): Stack[T] =
+        Stack[T](newSeq[T]())
+      proc push[T](stack: var Stack[T], elem: T) =
+        seq[T](stack).add(elem)
+      proc len[T](stack: Stack[T]): int =
+        seq[T](stack).len
+      proc fn() = 
+        var stack = newStack[int]()
+        stack.push(5)
+        doAssert stack.len == 1
+      fn()
+
+static: main()
+main()
diff --git a/tests/distinct/tdistinct_issues.nim b/tests/distinct/tdistinct_issues.nim
index ce71344d0..747cf0b8d 100644
--- a/tests/distinct/tdistinct_issues.nim
+++ b/tests/distinct/tdistinct_issues.nim
@@ -65,3 +65,17 @@ block t9322:
   proc mystr(s: string) =
     echo s
   mystr($Fix("apr"))
+
+
+block: # bug #13517
+  type MyUint64 = distinct uint64
+
+  proc `==`(a: MyUint64, b: uint64): bool = uint64(a) == b
+
+  block:
+    doAssert MyUint64.high is MyUint64
+    doAssert MyUint64.high == 18446744073709551615'u64
+
+  static:
+    doAssert MyUint64.high is MyUint64
+    doAssert MyUint64.high == 18446744073709551615'u64
diff --git a/tests/distinct/tinvalidborrow.nim b/tests/distinct/tinvalidborrow.nim
new file mode 100644
index 000000000..d4b19fa8d
--- /dev/null
+++ b/tests/distinct/tinvalidborrow.nim
@@ -0,0 +1,42 @@
+discard """
+  cmd: "nim check --hints:off --warnings:off $file"
+  action: "reject"
+  nimout:'''
+tinvalidborrow.nim(25, 3) Error: only a 'distinct' type can borrow `.`
+tinvalidborrow.nim(26, 3) Error: only a 'distinct' type can borrow `.`
+tinvalidborrow.nim(27, 1) Error: borrow proc without distinct type parameter is meaningless
+tinvalidborrow.nim(36, 1) Error: borrow with generic parameter is not supported
+tinvalidborrow.nim(41, 1) Error: borrow from proc return type mismatch: 'T'
+tinvalidborrow.nim(42, 1) Error: borrow from '[]=' is not supported
+'''
+"""
+
+
+
+
+
+# bug #516
+
+type
+  TAtom = culong
+  Test {.borrow:`.`.} = distinct int
+  Foo[T] = object
+    a: int
+  Bar[T] {.borrow:`.`.} = Foo[T]
+  OtherFoo {.borrow:`.`.} = Foo[int]
+proc `==`*(a, b: TAtom): bool {.borrow.}
+
+var
+  d, e: TAtom
+
+discard( $(d == e) )
+
+# issue #4121
+type HeapQueue[T] = distinct seq[T]
+proc len*[T](h: HeapQueue[T]): int {.borrow.}
+
+# issue #3564
+type vec4[T] = distinct array[4, float32]
+
+proc `[]`(v: vec4, i: int): float32 {.borrow.}
+proc `[]=`(v: vec4, i: int, va: float32) {.borrow.}
diff --git a/tests/distinct/tnil.nim b/tests/distinct/tnil.nim
index 5bdb97f37..b54c07432 100644
--- a/tests/distinct/tnil.nim
+++ b/tests/distinct/tnil.nim
@@ -1,29 +1,21 @@
-discard """
-output: '''
-1
-0
-0
-'''
-"""
 {.experimental: "notnil".}
 type
   MyPointer = distinct pointer
   MyString = distinct string
   MyInt = distinct int
 
-proc foo(a: MyPointer) =
+proc foo(a: MyPointer): int =
   # workaround a Windows 'repr' difference:
-  echo cast[int](a)
+  cast[int](a)
 
-foo(cast[MyPointer](1))
-foo(cast[MyPointer](nil))
-foo(nil)
+doAssert foo(cast[MyPointer](1)) == 1
+doAssert foo(cast[MyPointer](nil)) == 0
+doAssert foo(MyPointer(nil)) == 0
 
 var p: MyPointer
 p = cast[MyPointer](1)
 p = cast[MyPointer](nil)
 p = nil.MyPointer
-p = nil
 
 var i: MyInt
 i = 1.MyInt
diff --git a/tests/distinct/typeclassborrow.nim b/tests/distinct/typeclassborrow.nim
new file mode 100644
index 000000000..5e0c63953
--- /dev/null
+++ b/tests/distinct/typeclassborrow.nim
@@ -0,0 +1,56 @@
+import std/tables
+
+type
+  Foo = distinct seq[int]
+  Bar[N: static[int]] = distinct seq[int]
+  Baz = distinct Bar[10]
+
+proc newSeq(s: var Foo, n: Natural) {.borrow.}
+proc newSeq(s: var Bar, n: Natural) {.borrow.}
+proc newSeq(s: var Baz, n: Natural) {.borrow.}
+
+
+proc `$`(s: Foo): string {.borrow.}
+proc `$`(s: Bar): string {.borrow.}
+proc `$`(s: Baz): string {.borrow.}
+
+proc doThing(b: Bar) = discard
+proc doThing(b: Baz) {.borrow.}
+
+var
+  foo: Foo
+  bar: Bar[10]
+  baz: Baz
+
+newSeq(foo, 100)
+newSeq(bar, bar.N)
+newSeq(baz, 10)
+
+bar.doThing()
+baz.doThing()
+
+assert $seq[int](foo) == $foo
+assert $seq[int](bar) == $bar
+assert $seq[int](baz) == $baz
+
+type
+  Fine* = distinct string
+
+proc `==`*(x, y: Fine): bool {.borrow.} =
+  ## Here is the documentation
+  runnableExamples:
+    var x = Fine("1234")
+    var y = Fine("1234")
+    doAssert x == y
+  doAssert false
+
+
+var x = Fine("1234")
+var y = Fine("1234")
+doAssert x == y
+
+block: # bug #22902
+  type
+    DistinctTable = distinct Table[int, int]
+
+  proc `[]`(t: DistinctTable; key: int): lent int {.borrow.}
diff --git a/tests/dll/client.nim b/tests/dll/client.nim
index 90ca05149..62697569f 100644
--- a/tests/dll/client.nim
+++ b/tests/dll/client.nim
@@ -1,6 +1,4 @@
 discard """
-  output: "Done"
-  disabled: "freebsd"
   cmd: "nim $target --debuginfo --hints:on --define:useNimRtl $options $file"
 """
 
@@ -38,5 +36,8 @@ proc eval(n: PNode): int =
 for i in 0..100_000:
   discard eval(buildTree(2))
 
-echo "Done"
-
+# bug https://forum.nim-lang.org/t/8176; Error: ambiguous identifier: 'nimrtl'
+import std/strutils
+doAssert join(@[1, 2]) == "12"
+doAssert join(@[1.5, 2.5]) == "1.52.5"
+doAssert join(@["a", "bc"]) == "abc"
diff --git a/tests/dll/nimhcr_0_3.nim b/tests/dll/nimhcr_0_3.nim
index 56f66e08c..183424e11 100644
--- a/tests/dll/nimhcr_0_3.nim
+++ b/tests/dll/nimhcr_0_3.nim
@@ -14,5 +14,6 @@ let c = makeCounter()
 afterCodeReload:
   echo "   0: after - closure iterator: ", c()
   echo "   0: after - closure iterator: ", c()
+  echo "   0: after - c_2 = ", c_2
 
 proc getInt*(): int = return g_1 + g_2.len
diff --git a/tests/dll/nimhcr_2_1.nim b/tests/dll/nimhcr_2_1.nim
index faafb1f76..705ed6d5a 100644
--- a/tests/dll/nimhcr_2_1.nim
+++ b/tests/dll/nimhcr_2_1.nim
@@ -7,6 +7,8 @@ type
 
 let g_2* = @[Type2(data: 2), Type2(data: 3)][1..^1] # should have a length of 1
 
+const c_2* = [1, 2, 3] # testing that a complext const object is properly exported
+
 var a: tuple[str: string, i: int]
 a.str = "   2: random string"
 echo a.str
diff --git a/tests/dll/nimhcr_basic.nim b/tests/dll/nimhcr_basic.nim
new file mode 100644
index 000000000..2e1f39ae0
--- /dev/null
+++ b/tests/dll/nimhcr_basic.nim
@@ -0,0 +1,8 @@
+discard """
+  output: '''
+Hello world
+'''
+"""
+# for now orc only tests successful compilation
+
+echo "Hello world"
diff --git a/tests/dll/nimhcr_integration.nim b/tests/dll/nimhcr_integration.nim
index 64f6bb708..ac34f1f85 100644
--- a/tests/dll/nimhcr_integration.nim
+++ b/tests/dll/nimhcr_integration.nim
@@ -1,5 +1,5 @@
 discard """
-  disabled: "macosx"
+  disabled: "true"
   output: '''
 main: HELLO!
 main: hasAnyModuleChanged? true
@@ -35,6 +35,7 @@ max mutual recursion reached!
 bar
    0: after - closure iterator: 0
    0: after - closure iterator: 1
+   0: after - c_2 = [1, 2, 3]
 main: after
               The answer is: 9
 main: hasAnyModuleChanged? true
@@ -53,6 +54,20 @@ done
 '''
 """
 
+#[
+xxx disabled: "openbsd" because it would otherwise give:
+/home/build/Nim/lib/nimhcr.nim(532) hcrInit
+/home/build/Nim/lib/nimhcr.nim(503) initModules
+/home/build/Nim/lib/nimhcr.nim(463) initPointerData
+/home/build/Nim/lib/nimhcr.nim(346) hcrRegisterProc
+/home/build/Nim/lib/pure/reservedmem.nim(223) setLen
+/home/build/Nim/lib/pure/reservedmem.nim(97) setLen
+/home/build/Nim/lib/pure/includes/oserr.nim(94) raiseOSError
+Error: unhandled exception: Not supported [OSError]
+
+After instrumenting code, the stacktrace actually points to the call to `check mprotect`
+]#
+
 ## This is perhaps the most complex test in the nim test suite - calling the
 ## compiler on the file itself with the same set or arguments and reloading
 ## parts of the program at runtime! In the same folder there are a few modules
@@ -97,6 +112,7 @@ proc compileReloadExecute() =
   #   binary triggers rebuilding itself here it shouldn't rebuild the main module -
   #   that would lead to replacing the main binary executable which is running!
   let cmd = commandLineParams()[0..^1].join(" ").replace(" --forceBuild")
+  doAssert cmd.len > 0
   let (stdout, exitcode) = execCmdEx(cmd)
   if exitcode != 0:
     echo "COMPILATION ERROR!"
@@ -151,4 +167,4 @@ update 0
 update 1
 update 2
 
-echo "done"
+echo "done"
\ No newline at end of file
diff --git a/tests/dll/nimhcr_unit.nim b/tests/dll/nimhcr_unit.nim
index f539a53c8..249f3f9f1 100644
--- a/tests/dll/nimhcr_unit.nim
+++ b/tests/dll/nimhcr_unit.nim
@@ -1,4 +1,6 @@
 discard """
+disabled: "openbsd"
+disabled: "netbsd"
 output: '''
 fastcall_proc implementation #1 10
 11
@@ -104,14 +106,14 @@ macro carryOutTests(callingConv: untyped): untyped =
       echo `procName`, " implementation #1 ", x
       return x + 1
 
-    let fp1 = cast[F](hcrRegisterProc("dummy_module", `procName`, `p1`))
+    let fp1 = cast[F](hcrRegisterProc("dummy_module", `procName`, cast[pointer](`p1`)))
     echo fp1(10)
 
     proc `p2`(x: int): int {.placeholder.} =
       echo `procName`, " implementation #2 ", x
       return x + 2
 
-    let fp2 = cast[F](hcrRegisterProc("dummy_module", `procName`, `p2`))
+    let fp2 = cast[F](hcrRegisterProc("dummy_module", `procName`, cast[pointer](`p2`)))
     echo fp1(20)
     echo fp2(20)
 
@@ -119,7 +121,7 @@ macro carryOutTests(callingConv: untyped): untyped =
       echo `procName`, " implementation #3 ", x
       return x + 3
 
-    let fp3 = cast[F](hcrRegisterProc("dummy_module", `procName`, `p3`))
+    let fp3 = cast[F](hcrRegisterProc("dummy_module", `procName`, cast[pointer](`p3`)))
     echo fp1(30)
     echo fp2(30)
     echo fp3(30)
diff --git a/tests/dll/server.nim b/tests/dll/server.nim
index 2b7791d4b..dd4606298 100644
--- a/tests/dll/server.nim
+++ b/tests/dll/server.nim
@@ -1,6 +1,7 @@
 discard """
 action: compile
   cmd: "nim $target --debuginfo --hints:on --define:useNimRtl --app:lib $options $file"
+batchable: false
 """
 
 type
diff --git a/tests/effects/tcast_as_pragma.nim b/tests/effects/tcast_as_pragma.nim
new file mode 100644
index 000000000..1de61333e
--- /dev/null
+++ b/tests/effects/tcast_as_pragma.nim
@@ -0,0 +1,18 @@
+discard """
+  cmd: "nim c $file"
+  action: "compile"
+"""
+
+proc taggy() {.tags: RootEffect.} = discard
+
+proc m {.raises: [], tags: [].} =
+  {.cast(noSideEffect).}:
+    echo "hi"
+
+  {.cast(raises: []).}:
+    raise newException(ValueError, "bah")
+
+  {.cast(tags: []).}:
+    taggy()
+
+m()
diff --git a/tests/effects/tdiagnostic_messages.nim b/tests/effects/tdiagnostic_messages.nim
new file mode 100644
index 000000000..b1acf8c5c
--- /dev/null
+++ b/tests/effects/tdiagnostic_messages.nim
@@ -0,0 +1,37 @@
+discard """
+  nimoutFull: true
+  action: "reject"
+  cmd: "nim r --hint:Conf:off $file"
+  nimout: '''
+tdiagnostic_messages.nim(36, 6) Error: 'a' can have side effects
+> tdiagnostic_messages.nim(37, 30) Hint: 'a' calls `.sideEffect` 'callWithSideEffects'
+>> tdiagnostic_messages.nim(29, 6) Hint: 'callWithSideEffects' called by 'a'
+>>> tdiagnostic_messages.nim(31, 34) Hint: 'callWithSideEffects' calls `.sideEffect` 'indirectCallViaVarParam'
+>>>> tdiagnostic_messages.nim(25, 6) Hint: 'indirectCallViaVarParam' called by 'callWithSideEffects'
+>>>>> tdiagnostic_messages.nim(26, 7) Hint: 'indirectCallViaVarParam' calls routine via hidden pointer indirection
+>>> tdiagnostic_messages.nim(32, 33) Hint: 'callWithSideEffects' calls `.sideEffect` 'indirectCallViaPointer'
+>>>> tdiagnostic_messages.nim(27, 6) Hint: 'indirectCallViaPointer' called by 'callWithSideEffects'
+>>>>> tdiagnostic_messages.nim(28, 32) Hint: 'indirectCallViaPointer' calls routine via pointer indirection
+>>> tdiagnostic_messages.nim(33, 3) Hint: 'callWithSideEffects' calls `.sideEffect` 'myEcho'
+>>>> tdiagnostic_messages.nim(24, 6) Hint: 'myEcho' called by 'callWithSideEffects'
+>>> tdiagnostic_messages.nim(34, 3) Hint: 'callWithSideEffects' accesses global state 'globalVar'
+>>>> tdiagnostic_messages.nim(23, 5) Hint: 'globalVar' accessed by 'callWithSideEffects'
+
+'''
+"""
+
+var globalVar = 0
+proc myEcho(a: string) {.sideEffect.} = discard
+proc indirectCallViaVarParam(call: var proc(): int {.nimcall.}): int =
+  call()
+proc indirectCallViaPointer(call: pointer): int =
+  cast[ptr proc(): int](call)[]()
+proc callWithSideEffects(): int =
+  var p = proc (): int {.nimcall.} = 0
+  discard indirectCallViaVarParam(p)
+  discard indirectCallViaPointer(addr p)
+  myEcho ""
+  globalVar
+
+func a: int =
+  discard callWithSideEffects()
diff --git a/tests/effects/teffects1.nim b/tests/effects/teffects1.nim
index 8f827110c..1d267b5fa 100644
--- a/tests/effects/teffects1.nim
+++ b/tests/effects/teffects1.nim
@@ -1,8 +1,10 @@
 discard """
-  errormsg: "can raise an unlisted exception: ref IOError"
-  file: "io.nim"
+  cmd: "nim check --hint:Conf:off --hint:XDeclaredButNotUsed:off $file"
+  nimout: '''
+teffects1.nim(17, 28) template/generic instantiation from here
+'''
 """
-
+{.push warningAsError[Effect]: on.}
 type
   TObj {.pure, inheritable.} = object
   TObjB = object of TObj
@@ -12,8 +14,34 @@ type
 
 proc forw: int {. .}
 
-proc lier(): int {.raises: [IO2Error].} =
-  writeLine stdout, "arg"
+proc lier(): int {.raises: [IO2Error].} = #[tt.Hint
+                            ^ 'lier' cannot raise 'IO2Error' [XCannotRaiseY] ]#
+  writeLine stdout, "arg" #[tt.Error
+  ^ writeLine stdout, ["arg"] can raise an unlisted exception: ref IOError ]#
 
 proc forw: int =
   raise newException(IOError, "arg")
+
+block:
+  proc someProc(t: string) {.raises: [Defect].} =
+    discard
+  let vh: proc(topic: string) {.raises: [].} = someProc
+
+{.push raises: [Defect].}
+
+type
+  MyProcType* = proc(x: int): string #{.raises: [ValueError, Defect].}
+
+proc foo(x: int): string {.nimcall, raises: [ValueError].} =
+  if x > 9:
+    raise newException(ValueError, "Use single digit")
+  $x
+
+var p: MyProcType = foo #[tt.Error
+                    ^
+type mismatch: got <proc (x: int): string{.nimcall, raises: [ValueError], noSideEffect, gcsafe.}> but expected 'MyProcType = proc (x: int): string{.closure.}'
+  Calling convention mismatch: got '{.nimcall.}', but expected '{.closure.}'.
+.raise effects differ
+]#
+{.pop.}
+{.pop.}
diff --git a/tests/effects/teffects10.nim b/tests/effects/teffects10.nim
new file mode 100644
index 000000000..8193b394a
--- /dev/null
+++ b/tests/effects/teffects10.nim
@@ -0,0 +1,12 @@
+discard """
+action: compile
+"""
+
+# https://github.com/nim-lang/Nim/issues/15495
+
+proc f() {.raises: [].} =
+  var a: proc ()
+  var b: proc ()
+  swap(a, b)
+
+f()
diff --git a/tests/effects/teffects11.nim b/tests/effects/teffects11.nim
new file mode 100644
index 000000000..20b7026ab
--- /dev/null
+++ b/tests/effects/teffects11.nim
@@ -0,0 +1,21 @@
+discard """
+action: compile
+errormsg: "type mismatch: got <proc (x: int){.gcsafe.}>"
+line: 21
+"""
+
+type
+  Effect1 = object
+  Effect2 = object
+  Effect3 = object
+
+proc test(fnc: proc(x: int): void {.forbids: [Effect2].}) {.tags: [Effect1, Effect3, RootEffect].} =
+  fnc(1)
+
+proc t1(x: int): void = echo $x
+proc t2(x: int): void {.tags: [Effect2].} = echo $x
+proc t3(x: int): void {.tags: [Effect3].} = echo $x
+
+test(t1)
+test(t3)
+test(t2)
diff --git a/tests/effects/teffects12.nim b/tests/effects/teffects12.nim
new file mode 100644
index 000000000..5f5499c38
--- /dev/null
+++ b/tests/effects/teffects12.nim
@@ -0,0 +1,52 @@
+discard """
+action: compile
+"""
+
+import std/locks
+
+type
+  Test2Effect* = object
+  Test2* = object
+    value2*: int
+  Test1Effect* = object
+  Test1* = object
+    value1*: int
+  Main* = object
+    test1Lock: Lock
+    test1: Test1
+    test2Lock: Lock
+    test2: Test2
+
+proc `=copy`(obj1: var Test2, obj2: Test2) {.error.}
+proc `=copy`(obj1: var Test1, obj2: Test1) {.error.}
+proc `=copy`(obj1: var Main, obj2: Main) {.error.}
+
+proc withTest1(main: var Main,
+               fn: proc(test1: var Test1) {.gcsafe, forbids: [Test1Effect].}) {.gcsafe, tags: [Test1Effect, RootEffect].} =
+  withLock(main.test1Lock):
+    fn(main.test1)
+
+proc withTest2(main: var Main,
+               fn: proc(test1: var Test2) {.gcsafe, forbids: [Test2Effect].}) {.gcsafe, tags: [Test2Effect, RootEffect].} =
+  withLock(main.test2Lock):
+    fn(main.test2)
+
+proc newMain(): Main =
+  var test1lock: Lock
+  initLock(test1Lock)
+  var test2lock: Lock
+  initLock(test2Lock)
+  var main = Main(test1Lock: move(test1Lock), test1: Test1(value1: 1),
+                  test2Lock: move(test2Lock), test2: Test2(value2: 2))
+  main.withTest1(proc(test1: var Test1) = test1.value1 += 1)
+  main.withTest2(proc(test2: var Test2) = test2.value2 += 1)
+  move main
+
+var main = newMain()
+main.withTest1(proc(test1: var Test1) =
+  test1.value1 += 1
+  main.withTest2(proc(test2: var Test2) = test2.value2 += 1)
+)
+
+main.withTest1(proc(test1: var Test1) {.tags: [].} = echo $test1.value1)
+main.withTest2(proc(test2: var Test2) {.tags: [].} = echo $test2.value2)
diff --git a/tests/effects/teffects13.nim b/tests/effects/teffects13.nim
new file mode 100644
index 000000000..73082f997
--- /dev/null
+++ b/tests/effects/teffects13.nim
@@ -0,0 +1,19 @@
+discard """
+action: compile
+errormsg: "writeSomething() has an illegal effect: WriteIO"
+line: 19
+"""
+
+type
+  IO = object of RootEffect ## input/output effect
+  ReadIO = object of IO     ## input effect
+  WriteIO = object of IO    ## output effect
+
+proc readSomething(): string {.tags: [ReadIO].} = ""
+proc writeSomething(): void {.tags: [WriteIO].} = echo "..."
+
+proc noWritesPlease() {.forbids: [WriteIO].} =
+  # this is OK:
+  echo readSomething()
+  # the compiler prevents this:
+  writeSomething()
diff --git a/tests/effects/teffects14.nim b/tests/effects/teffects14.nim
new file mode 100644
index 000000000..6291d9569
--- /dev/null
+++ b/tests/effects/teffects14.nim
@@ -0,0 +1,15 @@
+discard """
+action: compile
+errormsg: "func1() has an illegal effect: IO"
+line: 15
+"""
+
+type IO = object ## input/output effect
+proc func1(): string {.tags: [IO].} = discard
+proc func2(): string = discard
+
+proc no_IO_please() {.forbids: [IO].} =
+  # this is OK because it didn't define any tag:
+  discard func2()
+  # the compiler prevents this:
+  let y = func1()
diff --git a/tests/effects/teffects15.nim b/tests/effects/teffects15.nim
new file mode 100644
index 000000000..c3079cdbc
--- /dev/null
+++ b/tests/effects/teffects15.nim
@@ -0,0 +1,18 @@
+discard """
+action: compile
+errormsg: "method1(c) has an illegal effect: IO"
+line: 18
+"""
+
+type
+  IO = object ## input/output effect
+  CustomObject* = object of RootObj
+    text: string
+
+method method1(obj: var CustomObject): string {.tags: [IO].} = obj.text & "."
+method method2(obj: var CustomObject): string = obj.text & ":"
+
+proc noIO() {.forbids: [IO].} =
+  var c = CustomObject(text: "a")
+  echo c.method2()
+  echo c.method1()
diff --git a/tests/effects/teffects16.nim b/tests/effects/teffects16.nim
new file mode 100644
index 000000000..ee8f782a3
--- /dev/null
+++ b/tests/effects/teffects16.nim
@@ -0,0 +1,20 @@
+discard """
+action: compile
+errormsg: "writeSomething(\"a\") can have an unlisted effect: WriteIO"
+line: 20
+"""
+
+type
+  IO = object of RootEffect ## input/output effect
+  ReadIO = object of IO     ## input effect
+  WriteIO = object of IO    ## output effect
+  LogIO = object of IO      ## another output effect
+
+proc readSomething(): string {.tags: [ReadIO].} = ""
+proc writeSomething(msg: string): void {.tags: [WriteIO].} = echo msg
+proc logSomething(msg: string): void {.tags: [LogIo].} = echo msg
+
+proc noWritesPlease() {.forbids: [WriteIO], tags: [LogIO, ReadIO].} =
+  echo readSomething()
+  logSomething("a")
+  writeSomething("a")
diff --git a/tests/effects/teffects17.nim b/tests/effects/teffects17.nim
new file mode 100644
index 000000000..5e6b83896
--- /dev/null
+++ b/tests/effects/teffects17.nim
@@ -0,0 +1,17 @@
+discard """
+action: compile
+errormsg: "writeSomething(\"a\") has an illegal effect: WriteIO"
+line: 17
+"""
+
+type
+  IO = object of RootEffect ## input/output effect
+  ReadIO = object of IO     ## input effect
+  WriteIO = object of IO    ## output effect
+
+proc readSomething(): string {.tags: [ReadIO].} = ""
+proc writeSomething(msg: string): void {.tags: [WriteIO].} = echo msg
+
+proc illegalEffectNegation() {.forbids: [WriteIO], tags: [ReadIO, WriteIO].} =
+  echo readSomething()
+  writeSomething("a")
diff --git a/tests/effects/teffects18.nim b/tests/effects/teffects18.nim
new file mode 100644
index 000000000..576e76635
--- /dev/null
+++ b/tests/effects/teffects18.nim
@@ -0,0 +1,19 @@
+discard """
+action: compile
+errormsg: "type mismatch: got <ProcType2>"
+line: 19
+"""
+
+type MyEffect = object
+type ProcType1 = proc (i: int): void {.forbids: [MyEffect].}
+type ProcType2 = proc (i: int): void
+
+proc testFunc(p: ProcType1): void = p(1)
+
+proc toBeCalled(i: int): void {.tags: [MyEffect].} = echo $i
+
+let emptyTags = proc(i: int): void {.tags: [].} = echo $i
+let noTags: ProcType2 = proc(i: int): void = toBeCalled(i)
+
+testFunc(emptyTags)
+testFunc(noTags)
diff --git a/tests/effects/teffects19.nim b/tests/effects/teffects19.nim
new file mode 100644
index 000000000..6b4ab0819
--- /dev/null
+++ b/tests/effects/teffects19.nim
@@ -0,0 +1,23 @@
+discard """
+action: compile
+errormsg: "type mismatch: got <proc (i: int){.gcsafe.}>"
+line: 23
+"""
+
+type MyEffect = object
+type ProcType1 = proc (i: int): void {.forbids: [MyEffect].}
+type ProcType2 = proc (i: int): void
+
+proc caller1(p: ProcType1): void = p(1)
+proc caller2(p: ProcType2): void = p(1)
+
+proc effectful(i: int): void {.tags: [MyEffect].} = echo $i
+proc effectless(i: int): void {.forbids: [MyEffect].} = echo $i
+
+proc toBeCalled1(i: int): void = effectful(i)
+proc toBeCalled2(i: int): void = effectless(i)
+
+caller1(toBeCalled2)
+caller2(toBeCalled1)
+caller2(toBeCalled2)
+caller1(toBeCalled1)
diff --git a/tests/effects/teffects2.nim b/tests/effects/teffects2.nim
index e4b50aba5..777a4cebc 100644
--- a/tests/effects/teffects2.nim
+++ b/tests/effects/teffects2.nim
@@ -2,9 +2,9 @@ discard """
   errormsg: "can raise an unlisted exception: ref IOError"
   line: 19
 """
-
+{.push warningAsError[Effect]: on.}
 type
-  TObj = object {.pure, inheritable.}
+  TObj {.pure, inheritable.} = object
   TObjB = object of TObj
     a, b, c: string
 
@@ -17,3 +17,4 @@ proc lier(): int {.raises: [IOError].} =
 
 proc forw: int =
   raise newException(IOError, "arg")
+{.pop.}
diff --git a/tests/effects/teffects3.nim b/tests/effects/teffects3.nim
index ee5470c47..4c050510a 100644
--- a/tests/effects/teffects3.nim
+++ b/tests/effects/teffects3.nim
@@ -4,7 +4,7 @@ discard """
 """
 
 type
-  TObj = object {.pure, inheritable.}
+  TObj {.pure, inheritable.} = object
   TObjB = object of TObj
     a, b, c: string
     fn: proc (): int {.tags: [].}
diff --git a/tests/effects/teffects4.nim b/tests/effects/teffects4.nim
index 88cc0efa9..b875754b6 100644
--- a/tests/effects/teffects4.nim
+++ b/tests/effects/teffects4.nim
@@ -4,7 +4,7 @@ discard """
 """
 
 type
-  TObj = object {.pure, inheritable.}
+  TObj {.pure, inheritable.} = object
   TObjB = object of TObj
     a, b, c: string
     fn: proc (): int {.tags: [ReadIOEffect].}
diff --git a/tests/effects/teffects6.nim b/tests/effects/teffects6.nim
index 6a4eea155..d3af22434 100644
--- a/tests/effects/teffects6.nim
+++ b/tests/effects/teffects6.nim
@@ -21,7 +21,7 @@ createMenuItem(s, "Go to definition...",
 )
 
 
-proc noRaise(x: proc()) {.raises: [].} =
+proc noRaise(x: proc()) {.raises: [], effectsOf: x.} =
   # unknown call that might raise anything, but valid:
   x()
 
@@ -34,3 +34,23 @@ proc use*() =
 
 
 use()
+
+# bug #12642
+import os
+
+proc raises() {.raises: Exception.} = discard
+proc harmless() {.raises: [].} = discard
+
+let x = if paramStr(1) == "true": harmless else: raises
+
+let
+  choice = 0
+
+proc withoutSideEffects(): int = 0
+proc withSideEffects(): int = echo "foo" # the echo causes the side effect
+
+let procPtr = case choice
+              of 0: withoutSideEffects
+              else: withSideEffects
+
+echo procPtr.repr
diff --git a/tests/effects/teffects7.nim b/tests/effects/teffects7.nim
index 1cd144459..9b7fbf5f0 100644
--- a/tests/effects/teffects7.nim
+++ b/tests/effects/teffects7.nim
@@ -1,14 +1,16 @@
 discard """
-  errormsg: "can raise an unlisted exception: ref FloatingPointError"
+  errormsg: "can raise an unlisted exception: ref ValueError"
   line: 10
 """
-
+{.push warningAsError[Effect]: on.}
 proc foo() {.raises: [].} =
   try:
     discard
   except KeyError:
-    raise newException(FloatingPointError, "foo")
+    raise newException(ValueError, "foo")
   except Exception:
     discard
 
 foo()
+
+{.pop.}
diff --git a/tests/effects/teffects8.nim b/tests/effects/teffects8.nim
index fb3c088d6..359b3a1df 100644
--- a/tests/effects/teffects8.nim
+++ b/tests/effects/teffects8.nim
@@ -2,7 +2,7 @@ discard """
   errormsg: "can raise an unlisted exception: Exception"
   line: 10
 """
-
+{.push warningAsError[Effect]: on.}
 proc foo() {.raises: [].} =
   try:
     discard
@@ -10,3 +10,4 @@ proc foo() {.raises: [].} =
     raise
 
 foo()
+{.pop.}
diff --git a/tests/effects/teffects9.nim b/tests/effects/teffects9.nim
new file mode 100644
index 000000000..d92668fe9
--- /dev/null
+++ b/tests/effects/teffects9.nim
@@ -0,0 +1,22 @@
+discard """
+  errormsg: "can raise an unlisted exception: ref Exception"
+  line: 16
+"""
+
+# bug #8481
+
+type
+  ParentObj = ref object of RootObj
+  DerivedObj = ref object of ParentObj
+
+method doSome(o: ParentObj) {.base, raises: [].} =
+  discard
+
+method doSome(o: DerivedObj) =
+  raise newException(Exception, "oops, this raised")
+
+proc thisRaises() {.raises: [].} =
+  let o = new(DerivedObj)
+  o.doSome()
+
+thisRaises()
diff --git a/tests/effects/teffectsmisc.nim b/tests/effects/teffectsmisc.nim
new file mode 100644
index 000000000..8fb95b275
--- /dev/null
+++ b/tests/effects/teffectsmisc.nim
@@ -0,0 +1,39 @@
+discard """
+  output: '''
+printing from adder
+'''
+"""
+
+import std/sugar
+
+block:
+  proc makeAdder(a: int): (int) -> void =
+    proc discard_adder(x: int) {.closure.} =
+      discard a + x
+
+    proc echo_adder(x: int) {.closure.} =
+      echo("printing from adder")
+
+    if a > 0:
+      discard_adder
+    else:
+      echo_adder
+
+  let newAdder = makeAdder(0)
+  newAdder(5)
+
+block:
+  proc makeAdder(a: int): (int) -> void =
+    proc discard_adder(x: int) {.closure.} =
+      discard a + x
+
+    proc echo_adder(x: int) {.closure.} =
+      echo("printing from adder")
+
+    if a > 0:
+      echo_adder
+    else:
+      discard_adder
+
+  let newAdder = makeAdder(0)
+  newAdder(5)
diff --git a/tests/effects/tfuncs_cannot_mutate.nim b/tests/effects/tfuncs_cannot_mutate.nim
new file mode 100644
index 000000000..9934d27a7
--- /dev/null
+++ b/tests/effects/tfuncs_cannot_mutate.nim
@@ -0,0 +1,35 @@
+discard """
+  errormsg: "cannot mutate location select(x, z).data within a strict func"
+  line: 35
+"""
+
+{.experimental: "strictFuncs".}
+
+type
+  Node = ref object
+    le, ri: Node
+    data: string
+
+func insert(x: var seq[Node]; yyy: Node) =
+  let L = x.len
+  x.setLen L + 1
+  x[L] = yyy
+
+func len(n: Node): int =
+  var it = n
+  while it != nil:
+    inc result
+    it = it.ri
+
+func doNotDistract(n: Node) =
+  var m = Node(data: "abc")
+
+func select(a, b: Node): Node = b
+
+func mutate(n: Node) =
+  var it = n
+  let x = it
+  let y = x
+  let z = y
+
+  select(x, z).data = "tricky"
diff --git a/tests/effects/tfuncs_cannot_mutate2.nim b/tests/effects/tfuncs_cannot_mutate2.nim
new file mode 100644
index 000000000..86f811017
--- /dev/null
+++ b/tests/effects/tfuncs_cannot_mutate2.nim
@@ -0,0 +1,24 @@
+discard """
+  errormsg: "cannot mutate location x[0].a within a strict func"
+  line: 12
+"""
+
+{.experimental: "strictFuncs".}
+
+func copy[T](x: var openArray[T]; y: openArray[T]) =
+  for i in 0..high(x):
+    x[i] = y[i]
+
+  x[0].a = nil
+
+type
+  R = ref object
+    a, b: R
+    data: string
+
+proc main =
+  var a, b: array[3, R]
+  b = [R(data: "a"), R(data: "b"), R(data: "c")]
+  copy a, b
+
+main()
diff --git a/tests/effects/tfuncs_cannot_mutate3.nim b/tests/effects/tfuncs_cannot_mutate3.nim
new file mode 100644
index 000000000..029152029
--- /dev/null
+++ b/tests/effects/tfuncs_cannot_mutate3.nim
@@ -0,0 +1,35 @@
+discard """
+  errormsg: "cannot mutate location kid.parent within a strict func"
+  line: 16
+"""
+
+{.experimental: "strictFuncs".}
+
+type
+  Node = ref object
+    name: string
+    kids: seq[Node]
+    parent: Node
+
+func initParents(tree: Node) =
+  for kid in tree.kids:
+    kid.parent = tree
+    initParents(kid)
+
+proc process(intro: Node): Node =
+  var tree = Node(name: "root", kids: @[
+    intro,
+    Node(name: "one", kids: @[
+      Node(name: "two"),
+      Node(name: "three"),
+    ]),
+    Node(name: "four"),
+  ])
+  initParents(tree)
+
+proc main() =
+  var intro = Node(name: "intro")
+  var tree = process(intro)
+  echo intro.parent.name
+
+main()
diff --git a/tests/effects/tfuncs_cannot_mutate_simple.nim b/tests/effects/tfuncs_cannot_mutate_simple.nim
new file mode 100644
index 000000000..0ae4a0db9
--- /dev/null
+++ b/tests/effects/tfuncs_cannot_mutate_simple.nim
@@ -0,0 +1,19 @@
+discard """
+  errormsg: '''cannot mutate location x.data within a strict func'''
+  line: 15
+"""
+
+{.experimental: "strictFuncs".}
+
+# bug #15508
+
+type
+  MyType = ref object
+    data: string
+
+func edit(x: MyType) =
+  x.data = "hello"
+
+let x = MyType()
+x.edit()
+echo x.data
diff --git a/tests/effects/tgcsafe.nim b/tests/effects/tgcsafe.nim
index 363624f19..cfac3ddd8 100644
--- a/tests/effects/tgcsafe.nim
+++ b/tests/effects/tgcsafe.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "'mainUnsafe' is not GC-safe"
+  errormsg: "'mainUnsafe' is not GC-safe as it performs an indirect call here"
   line: 26
   cmd: "nim $target --hints:on --threads:on $options $file"
 """
@@ -13,7 +13,7 @@ proc myproc(i: int) {.gcsafe.} =
   if isNil(global_proc):
     return
 
-proc mymap(x: proc ()) =
+proc mymap(x: proc ()) {.effectsOf: x.} =
   x()
 
 var
diff --git a/tests/effects/tgcsafe2.nim b/tests/effects/tgcsafe2.nim
index 07da4e3f8..6268592a9 100644
--- a/tests/effects/tgcsafe2.nim
+++ b/tests/effects/tgcsafe2.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: '''type mismatch: got <proc (s: string){.locks: 0.}>'''
+  errormsg: '''type mismatch: got <proc (s: string)>'''
   line: 11
 """
 #5620
diff --git a/tests/effects/tgcsafe3.nim b/tests/effects/tgcsafe3.nim
index 5137efe4c..36ea5112c 100644
--- a/tests/effects/tgcsafe3.nim
+++ b/tests/effects/tgcsafe3.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "'myproc' is not GC-safe as it accesses 'global_proc' which is a global using GC'ed memory"
+  errormsg: "'myproc' is not GC-safe as it calls 'global_proc'"
   line: 12
   cmd: "nim $target --hints:on --threads:on $options $file"
 """
diff --git a/tests/effects/thooks.nim b/tests/effects/thooks.nim
new file mode 100644
index 000000000..23cc005cd
--- /dev/null
+++ b/tests/effects/thooks.nim
@@ -0,0 +1,16 @@
+discard """
+  matrix: "--warningAsError:Effect"
+"""
+
+import std/isolation
+
+# bug #23129
+type
+  Thing = object
+    x: string
+
+proc send(x: string) =
+  let wrapper = Thing(x: x)
+  discard isolate(wrapper)
+
+send("la")
\ No newline at end of file
diff --git a/tests/effects/tlaxeffects.nim b/tests/effects/tlaxeffects.nim
new file mode 100644
index 000000000..7eedc372a
--- /dev/null
+++ b/tests/effects/tlaxeffects.nim
@@ -0,0 +1,11 @@
+discard """
+  cmd: "nim $target $options --legacy:laxEffects $file"
+"""
+
+
+type
+  Foo = object
+    bar: seq[Foo]
+
+proc `==`(a, b: Foo): bool =
+  a.bar == b.bar
diff --git a/tests/effects/tnestedprocs.nim b/tests/effects/tnestedprocs.nim
new file mode 100644
index 000000000..125896d44
--- /dev/null
+++ b/tests/effects/tnestedprocs.nim
@@ -0,0 +1,63 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  nimout: '''tnestedprocs.nim(27, 8) Error: 'inner' can have side effects
+> tnestedprocs.nim(29, 13) Hint: 'inner' calls `.sideEffect` 'outer2'
+>> tnestedprocs.nim(26, 6) Hint: 'outer2' called by 'inner'
+
+tnestedprocs.nim(45, 8) Error: 'inner' can have side effects
+> tnestedprocs.nim(47, 13) Hint: 'inner' calls `.sideEffect` 'outer6'
+>> tnestedprocs.nim(44, 6) Hint: 'outer6' called by 'inner'
+
+tnestedprocs.nim(58, 41) Error: type mismatch: got <proc ()> but expected 'proc (){.closure, noSideEffect.}'
+  Pragma mismatch: got '{..}', but expected '{.noSideEffect.}'.
+'''
+  errormsg: "type mismatch: got <proc ()> but expected 'proc (){.closure, noSideEffect.}'"
+"""
+{.experimental: "strictEffects".}
+proc outer {.noSideEffect.} =
+  proc inner(p: int) =
+    if p == 0:
+      outer()
+
+  inner(4)
+
+outer()
+
+proc outer2 =
+  proc inner(p: int) {.noSideEffect.} =
+    if p == 0:
+      outer2()
+
+  inner(4)
+
+outer2()
+
+proc outer3(p: int) {.noSideEffect.} =
+  proc inner(p: int) {.noSideEffect.} =
+    if p == 0:
+      p.outer3()
+
+  inner(4)
+
+outer3(5)
+
+proc outer6 =
+  proc inner(p: int) {.noSideEffect.} =
+    if p == 0:
+      outer6()
+
+  inner(4)
+  echo "bad"
+
+outer6()
+
+
+proc outer4 =
+  proc inner(p: int) {.noSideEffect.} =
+    if p == 0:
+      let x: proc () {.noSideEffect.} = outer4
+      x()
+
+  inner(4)
+
+outer4()
diff --git a/tests/effects/tnosideeffect.nim b/tests/effects/tnosideeffect.nim
new file mode 100644
index 000000000..9fc2f74d4
--- /dev/null
+++ b/tests/effects/tnosideeffect.nim
@@ -0,0 +1,24 @@
+block: # `.noSideEffect`
+  func foo(bar: proc(): int): int {.effectsOf: bar.} = bar()
+  var count = 0
+  proc fn1(): int = 1
+  proc fn2(): int = (count.inc; count)
+
+  template accept(body) =
+    doAssert compiles(block:
+      body)
+
+  template reject(body) =
+    doAssert not compiles(block:
+      body)
+
+  accept:
+    func fun1() = discard foo(fn1)
+  reject:
+    func fun1() = discard foo(fn2)
+
+  var foo2: type(foo) = foo
+  accept:
+    func main() = discard foo(fn1)
+  reject:
+    func main() = discard foo2(fn1)
diff --git a/tests/effects/tstrict_caseobjects.nim b/tests/effects/tstrict_caseobjects.nim
new file mode 100644
index 000000000..20bc810e0
--- /dev/null
+++ b/tests/effects/tstrict_caseobjects.nim
@@ -0,0 +1,47 @@
+discard """
+  errormsg: "field access outside of valid case branch: x.x"
+  line: 45
+"""
+
+{.experimental: "strictCaseObjects".}
+
+type
+  NodeKind = enum
+    nkParent,
+    nkChild
+  
+  Node {.acyclic.} = ref object
+    case kind: NodeKind
+    of nkParent:
+      children: seq[Node]
+    of nkChild:
+      name: string
+
+let list = @[Node(kind: nkParent, children: @[]), Node(kind: nkChild, name: "hello")]
+for node in list:
+  case node.kind
+  of nkChild: 
+    echo $node.name # here this time there is a warning
+  else: discard
+
+
+type
+  Foo = object
+    case b: bool
+    of false:
+      s: string
+    of true:
+      x: int
+
+var x = Foo(b: true, x: 4)
+case x.b
+of true:
+  echo x.x
+of false:
+  echo "no"
+
+case x.b
+of false:
+  echo x.x
+of true:
+  echo "no"
diff --git a/tests/effects/tstrict_effects.nim b/tests/effects/tstrict_effects.nim
new file mode 100644
index 000000000..eee8fb71a
--- /dev/null
+++ b/tests/effects/tstrict_effects.nim
@@ -0,0 +1,27 @@
+discard """
+  errormsg: "s1 can raise an unlisted exception: CatchableError"
+  line: 27
+"""
+
+{.push warningAsError[Effect]: on.}
+{.experimental: "strictEffects".}
+
+# bug #18376
+
+{.push raises: [Defect].}
+type Call = proc (x: int): int {.gcsafe, raises: [Defect, CatchableError].}
+
+type Bar* = object
+  foo*: Call
+
+proc passOn*(x: Call) = discard
+
+proc barCal(b: var Bar, s: string, s1: Call) =
+  #compiler complains that his line can throw CatchableError
+  passOn s1
+
+
+proc passOnB*(x: Call) {.effectsOf: x.} = discard
+
+proc barCal2(b: var Bar, s: string, s1: Call) =
+  passOnB s1
diff --git a/tests/effects/tstrict_effects2.nim b/tests/effects/tstrict_effects2.nim
new file mode 100644
index 000000000..acc0a0540
--- /dev/null
+++ b/tests/effects/tstrict_effects2.nim
@@ -0,0 +1,28 @@
+discard """
+  errormsg: "can raise an unlisted exception: Exception"
+  line: 23
+"""
+
+{.push warningAsError[Effect]: on.}
+{.experimental: "strictEffects".}
+
+# bug #13905
+
+proc atoi(v: cstring): cint {.importc: "atoi", cdecl, raises: [].}
+
+type Conv = proc(v: cstring): cint {.cdecl, raises: [].}
+
+var x: Conv = atoi
+
+# bug #17475
+
+type
+  Callback = proc()
+
+proc f(callback: Callback) {.raises: [].} =
+  callback()
+
+proc main =
+  f(proc () = raise newException(IOError, "IO"))
+
+main()
diff --git a/tests/effects/tstrict_effects3.nim b/tests/effects/tstrict_effects3.nim
new file mode 100644
index 000000000..0d98a0343
--- /dev/null
+++ b/tests/effects/tstrict_effects3.nim
@@ -0,0 +1,57 @@
+discard """
+  action: compile
+"""
+
+{.push warningAsError[Effect]: on.}
+
+{.experimental: "strictEffects".}
+
+proc fn(a: int, p1, p2: proc()) {.effectsOf: p1.} =
+  if a == 7:
+    p1()
+  if a<0:
+    raise newException(ValueError, $a)
+
+proc main() {.raises: [ValueError].} =
+  fn(1, proc()=discard, proc() = raise newException(IOError, "foo"))
+main()
+
+# bug #19159
+
+import macros
+
+func mkEnter() =
+  template helper =
+    discard
+  when defined pass:
+    helper()
+  else:
+    let ast = getAst(helper())
+
+
+# bug #6559
+type
+  SafeFn = proc (): void {. raises: [] }
+
+proc ok() {. raises: [] .} = discard
+proc fail() {. raises: [] .}
+
+let f1 : SafeFn = ok
+let f2 : SafeFn = fail
+
+
+proc fail() = discard
+f1()
+f2()
+
+import std/json
+
+# bug #22254
+proc senri(a, b: seq[JsonNode]) {.raises: [].} = discard a == b
+
+# bug #22253
+proc serika() {.raises: [].} = discard default(JsonNode) == nil
+
+senri(@[newJBool(true)], @[newJBool(false)])
+serika()
+
diff --git a/tests/effects/tstrict_effects_sort.nim b/tests/effects/tstrict_effects_sort.nim
new file mode 100644
index 000000000..8928ed0d3
--- /dev/null
+++ b/tests/effects/tstrict_effects_sort.nim
@@ -0,0 +1,27 @@
+discard """
+  errormsg: "cmpE can raise an unlisted exception: Exception"
+  line: 27
+"""
+
+{.push warningAsError[Effect]: on.}
+
+{.experimental: "strictEffects".}
+
+import algorithm
+
+type
+  MyInt = distinct int
+
+var toSort = @[MyInt 1, MyInt 2, MyInt 3]
+
+proc cmpN(a, b: MyInt): int =
+  cmp(a.int, b.int)
+
+proc harmless {.raises: [].} =
+  toSort.sort cmpN
+
+proc cmpE(a, b: MyInt): int {.raises: [Exception].} =
+  cmp(a.int, b.int)
+
+proc harmfull {.raises: [].} =
+  toSort.sort cmpE
diff --git a/tests/effects/tstrict_funcs.nim b/tests/effects/tstrict_funcs.nim
new file mode 100644
index 000000000..9d20f5d7e
--- /dev/null
+++ b/tests/effects/tstrict_funcs.nim
@@ -0,0 +1,46 @@
+discard """
+  cmd: "nim c --experimental:strictFuncs --experimental:views $file"
+"""
+
+import tables, streams, parsecsv
+
+type
+  Contig2Reads = TableRef[string, seq[string]]
+
+proc get_Contig2Reads(sin: Stream, fn: string, contig2len: TableRef[string, int]): Contig2Reads =
+  result = newTable[string, seq[string]]()
+  var parser: CsvParser
+  open(parser, sin, filename = fn, separator = ' ', skipInitialSpace = true)
+  while readRow(parser, 2):
+    if contig2len.haskey(parser.row[1]):
+      mgetOrPut(result, parser.row[1], @[]).add(parser.row[0])
+
+
+
+block:
+  # issue #15756
+  func `&&&`[T](x: var seq[T], y: sink T): seq[T] =
+    newSeq(result, x.len + 1)
+    for i in 0..x.len-1:
+      result[i] = move(x[i])
+    result[x.len] = move(y)
+
+  var x = @[0, 1]
+  let z = x &&& 2
+
+
+func copy[T](x: var openArray[T]; y: openArray[T]) =
+  for i in 0..high(x):
+    x[i] = y[i]
+
+type
+  R = ref object
+    a, b: R
+    data: string
+
+proc main =
+  var a, b: array[3, R]
+  b = [R(data: "a"), R(data: "b"), R(data: "c")]
+  copy a, b
+
+main()
diff --git a/tests/effects/tstrict_funcs_imports.nim b/tests/effects/tstrict_funcs_imports.nim
new file mode 100644
index 000000000..bf68b61b2
--- /dev/null
+++ b/tests/effects/tstrict_funcs_imports.nim
@@ -0,0 +1,176 @@
+discard """
+  cmd: "nim $target $options --hints:on --experimental:strictFuncs --experimental:views --threads:on -d:ssl -d:nimCoroutines $file"
+  targets: "c"
+"""
+{.warning[UnusedImport]: off.}
+
+when defined(linux):
+  import linenoise
+
+when defined(nimPreviewSlimSystem):
+  import std/[
+    assertions,
+    formatfloat,
+    objectdollar,
+    syncio,
+    widestrs,
+  ]
+
+import
+  algorithm,
+  asyncdispatch,
+  asyncfile,
+  asyncfutures,
+  asynchttpserver,
+  asyncmacro,
+  asyncnet,
+  asyncstreams,
+  atomics,
+  base64,
+  bitops,
+  browsers,
+  cgi,
+  chains,
+  colors,
+  complex,
+  cookies,
+  coro,
+  cpuinfo,
+  cpuload,
+  critbits,
+  cstrutils,
+  deques,
+  distros,
+  dynlib,
+  encodings,
+  endians,
+  epoll,
+  fenv,
+  hashes,
+  heapqueue,
+  hotcodereloading,
+  htmlgen,
+  htmlparser,
+  httpclient,
+  httpcore,
+  inotify,
+  intsets,
+  json,
+  kqueue,
+  lenientops,
+  lexbase,
+  lists,
+  locks,
+  logging,
+  macrocache,
+  macros,
+  marshal,
+  math,
+  memfiles,
+  mersenne,
+  mimetypes,
+  nativesockets,
+  net,
+  nimhcr,
+  # nimprof,
+  nre,
+  oids,
+  options,
+  os,
+  osproc,
+  parsecfg,
+  parsecsv,
+  parsejson,
+  parseopt,
+  parsesql,
+  parseutils,
+  parsexml,
+  pathnorm,
+  pegs,
+  posix_utils,
+  prelude,
+  random,
+  rationals,
+  rdstdin,
+  re,
+  registry,
+  reservedmem,
+  rlocks,
+  ropes,
+  rtarrays,
+  selectors,
+  sequtils,
+  sets,
+  sharedlist,
+  sharedtables,
+  ssl_certs,
+  ssl_config,
+  stats,
+  streams,
+  streamwrapper,
+  strformat,
+  strmisc,
+  strscans,
+  strtabs,
+  strutils,
+  sugar,
+  tables,
+  terminal,
+  threadpool,
+  times,
+  typeinfo,
+  typetraits,
+  unicode,
+  unidecode,
+  unittest,
+  uri,
+  volatile,
+  winlean,
+  xmlparser,
+  xmltree
+
+import experimental/[
+  diff,
+]
+
+import packages/docutils/[
+  highlite,
+  rst,
+  rstast,
+  rstgen,
+]
+
+import std/[
+  compilesettings,
+  decls,
+  editdistance,
+  effecttraits,
+  enumerate,
+  enumutils,
+  exitprocs,
+  isolation,
+  jsonutils,
+  logic,
+  monotimes,
+  packedsets,
+  setutils,
+  socketstreams,
+  stackframes,
+  sums,
+  time_t,
+  varints,
+  with,
+  wordwrap,
+  wrapnils,
+]
+
+import std/private/[
+  asciitables,
+  decode_helpers,
+  gitutils,
+  globs,
+  miscdollars,
+  since,
+  strimpl,
+  underscored_calls,
+]
diff --git a/tests/effects/tstrict_funcs_imports_js.nim b/tests/effects/tstrict_funcs_imports_js.nim
new file mode 100644
index 000000000..667887ff0
--- /dev/null
+++ b/tests/effects/tstrict_funcs_imports_js.nim
@@ -0,0 +1,20 @@
+discard """
+  cmd: "nim $target $options --hints:on --experimental:strictFuncs --experimental:views $file"
+  targets: "js"
+"""
+{.warning[UnusedImport]: off.}
+
+import
+  asyncjs,
+  dom,
+  jsconsole,
+  jsffi,
+  jsre
+
+import std/[
+  jsbigints,
+]
+
+import std/private/[
+  jsutils,
+]
diff --git a/tests/effects/tstrictfuncs_misc.nim b/tests/effects/tstrictfuncs_misc.nim
new file mode 100644
index 000000000..8c573bb3a
--- /dev/null
+++ b/tests/effects/tstrictfuncs_misc.nim
@@ -0,0 +1,65 @@
+discard """
+  action: compile
+"""
+
+{.experimental: "strictFuncs".}
+
+func sortedFake1[T](a: openArray[T]): seq[T] =
+  for i in 0 .. a.high: result.add a[i]
+func sortedFake2[T](a: openArray[T]): seq[T] =
+  result = newSeq[T](a.len)
+  for i in 0 .. a.high: result[i] = a[i]
+type Foo1 = object
+type Foo2 = ref object
+block:
+  let a1 = sortedFake1([Foo1()]) # ok
+  let a2 = sortedFake1([Foo2()]) # ok
+block:
+  let a1 = sortedFake2([Foo1()]) # ok
+  let a2 = sortedFake2([Foo2()]) # error: Error: 'sortedFake2' can have side effects
+
+
+import std/sequtils
+type Foob = ref object
+  x: int
+let a1 = zip(@[1,2], @[1,2]) # ok
+let a2 = zip(@[Foob(x: 1)], @[Foob(x: 2)]) # error in 1.6.0 RC2, but not 1.4.x
+
+
+# bug #20863
+type
+  Fooc = ref object
+
+func twice(foo: Fooc) =
+  var a = newSeq[Fooc](2)
+  a[0] = foo # No error.
+  a[1] = foo # Error: 'twice' can have side effects.
+
+let foo = Fooc()
+twice(foo)
+
+# bug #17387
+import json
+
+func parseColumn(columnNode: JsonNode) =
+  let columnName = columnNode["name"].str
+
+parseColumn(%*{"a": "b"})
+
+type
+  MyTable = object
+    data: seq[int]
+
+  JsonNode3 = ref object
+    fields: MyTable
+
+proc `[]`(t: MyTable, key: string): int =
+  result = t.data[0]
+
+proc `[]`(x: JsonNode3, key: string): int =
+  result = x.fields[key]
+
+func parseColumn(columnNode: JsonNode3) =
+  var columnName = columnNode["test"]
+
+parseColumn(JsonNode3())
diff --git a/tests/enum/m16462_1.nim b/tests/enum/m16462_1.nim
new file mode 100644
index 000000000..631c63256
--- /dev/null
+++ b/tests/enum/m16462_1.nim
@@ -0,0 +1,3 @@
+type
+  Scancode* {.pure.} = enum
+    SCANCODE_LEFT = 80
\ No newline at end of file
diff --git a/tests/enum/m16462_2.nim b/tests/enum/m16462_2.nim
new file mode 100644
index 000000000..631c63256
--- /dev/null
+++ b/tests/enum/m16462_2.nim
@@ -0,0 +1,3 @@
+type
+  Scancode* {.pure.} = enum
+    SCANCODE_LEFT = 80
\ No newline at end of file
diff --git a/tests/enum/mcrossmodule.nim b/tests/enum/mcrossmodule.nim
new file mode 100644
index 000000000..e534a202c
--- /dev/null
+++ b/tests/enum/mcrossmodule.nim
@@ -0,0 +1,6 @@
+
+type
+  OtherEnum* = enum
+    Success, Failed, More
+
+proc some*(x: OtherEnum): bool = x == Success
diff --git a/tests/enum/t16462.nim b/tests/enum/t16462.nim
new file mode 100644
index 000000000..9f38286bb
--- /dev/null
+++ b/tests/enum/t16462.nim
@@ -0,0 +1,5 @@
+import m16462_1 except Scancode
+import m16462_2
+
+# bug #16462
+let a = SCANCODE_LEFT
\ No newline at end of file
diff --git a/tests/enum/t21863.nim b/tests/enum/t21863.nim
new file mode 100644
index 000000000..d0d8b1fcd
--- /dev/null
+++ b/tests/enum/t21863.nim
@@ -0,0 +1,28 @@
+discard """
+cmd: "nim check --hints:off $file"
+action: reject
+nimout: '''
+t21863.nim(28, 16) Error: undeclared field: 'A' 
+  found 'A' [enumField declared in t21863.nim(24, 18)]
+  found 'A' [enumField declared in t21863.nim(25, 18)]
+t21863.nim(28, 16) Error: undeclared field: '.'
+t21863.nim(28, 16) Error: undeclared field: '.'
+t21863.nim(28, 16) Error: expression '' has no type (or is ambiguous)
+'''
+"""
+
+
+
+
+
+
+
+
+
+block:
+  type
+    EnumA = enum A, B
+    EnumB = enum A
+    EnumC = enum C
+
+  discard EnumC.A
diff --git a/tests/enum/tambiguousoverloads.nim b/tests/enum/tambiguousoverloads.nim
new file mode 100644
index 000000000..12c78c848
--- /dev/null
+++ b/tests/enum/tambiguousoverloads.nim
@@ -0,0 +1,26 @@
+discard """
+cmd: "nim check --hints:off $file"
+"""
+
+block: # bug #21887
+  type
+    EnumA = enum A = 300, B
+    EnumB = enum A = 10
+    EnumC = enum C
+
+  doAssert typeof(EnumC(A)) is EnumC #[tt.Error
+                        ^ ambiguous identifier: 'A' -- use one of the following:
+  EnumA.A: EnumA
+  EnumB.A: EnumB]#
+
+block: # issue #22598
+  type
+    A = enum
+      red
+    B = enum
+      red
+
+  let a = red #[tt.Error
+          ^ ambiguous identifier: 'red' -- use one of the following:
+  A.red: A
+  B.red: B]#
diff --git a/tests/enum/tcrossmodule.nim b/tests/enum/tcrossmodule.nim
new file mode 100644
index 000000000..c21072198
--- /dev/null
+++ b/tests/enum/tcrossmodule.nim
@@ -0,0 +1,15 @@
+import mcrossmodule
+
+type
+  MyEnum = enum
+    Success
+
+template t =
+  doAssert some(Success)
+
+t()
+
+block: # legacy support for behavior before overloadableEnums
+  # warning: ambiguous enum field 'Success' assumed to be of type MyEnum
+  let x = {Success}
+  doAssert x is set[MyEnum]
diff --git a/tests/enum/tenum.nim b/tests/enum/tenum.nim
index 8cc578d3c..a03019c5d 100644
--- a/tests/enum/tenum.nim
+++ b/tests/enum/tenum.nim
@@ -6,7 +6,7 @@ ABCDC
 foo
 first0second32third64
 my value A1my value Bconc2valueCabc4abc
-my value A0my value Bconc1valueCabc3valueC
+my value A0my value Bconc1valueCabc3abc
 '''
 """
 
@@ -124,25 +124,25 @@ block tnamedfields:
   # trick the optimizer with a variable:
   var x = valueD
   echo valueA, ord(valueA), valueB, ord(valueB), valueC, valueD, ord(valueD), x
+  doAssert $x == $valueD, $x
+  doAssert $x == "abc", $x
 
 
-
-block toptions:
+block tfakeOptions:
   type
-    # please make sure we have under 32 options (improves code efficiency!)
-    TOption = enum
-      optNone, optForceFullMake, optBoehmGC, optRefcGC, optRangeCheck,
-      optBoundsCheck, optOverflowCheck, optNilCheck, optAssert, optLineDir,
-      optWarns, optHints, optListCmd, optCompileOnly,
-      optSafeCode,             # only allow safe code
-      optStyleCheck, optOptimizeSpeed, optOptimizeSize, optGenDynLib,
-      optGenGuiApp, optStackTrace
+    TFakeOption = enum
+      fakeNone, fakeForceFullMake, fakeBoehmGC, fakeRefcGC, fakeRangeCheck,
+      fakeBoundsCheck, fakeOverflowCheck, fakeNilCheck, fakeAssert, fakeLineDir,
+      fakeWarns, fakeHints, fakeListCmd, fakeCompileOnly,
+      fakeSafeCode,             # only allow safe code
+      fakeStyleCheck, fakeOptimizeSpeed, fakeOptimizeSize, fakeGenDynLib,
+      fakeGenGuiApp, fakeStackTrace
 
-    TOptionset = set[TOption]
+    TFakeOptionset = set[TFakeOption]
 
   var
-    gOptions: TOptionset = {optRefcGC, optRangeCheck, optBoundsCheck,
-      optOverflowCheck, optAssert, optWarns, optHints, optLineDir, optStackTrace}
+    gFakeOptions: TFakeOptionset = {fakeRefcGC, fakeRangeCheck, fakeBoundsCheck,
+      fakeOverflowCheck, fakeAssert, fakeWarns, fakeHints, fakeLineDir, fakeStackTrace}
     compilerArgs: int
     gExitcode: int8
 
@@ -154,3 +154,114 @@ block nonzero: # bug #6959
     B
     C
   let slice = SomeEnum.low..SomeEnum.high
+
+block size_one_byte: # bug #15752
+  type
+    Flag = enum
+      Disabled = 0x00
+      Enabled = 0xFF
+
+  static:
+    assert 1 == sizeof(Flag)
+
+block: # bug #12589
+  when not defined(i386):
+    type
+      OGRwkbGeometryType {.size: sizeof(cuint).} = enum
+        wkbPoint25D = 0x80000001.cuint, wkbLineString25D = 0x80000002,
+        wkbPolygon25D = 0x80000003
+
+    proc typ(): OGRwkbGeometryType =
+      return wkbPoint25D
+
+    when not defined(gcRefc):
+      doAssert $typ() == "wkbPoint25D"
+
+    block: # bug #21280
+      type
+        Test = enum
+          B = 19
+          A = int64.high()
+
+      doAssert ord(A) == int64.high()
+
+import std/enumutils
+from std/sequtils import toSeq
+import std/macros
+
+block: # unordered enum
+  block:
+    type
+      unordered_enum = enum
+        a = 1
+        b = 0
+
+    doAssert (ord(a), ord(b)) == (1, 0)
+    doAssert unordered_enum.toSeq == @[a, b]
+
+  block:
+    type
+      unordered_enum = enum
+        a = 1
+        b = 0
+        c
+
+    doAssert (ord(a), ord(b), ord(c)) == (1, 0, 2)
+
+  block:
+    type
+      unordered_enum = enum
+        a = 100
+        b
+        c = 50
+        d
+
+    doAssert (ord(a), ord(b), ord(c), ord(d)) == (100, 101, 50, 51)
+
+  block:
+    type
+      unordered_enum = enum
+        a = 7
+        b = 6
+        c = 5
+        d
+
+    doAssert (ord(a), ord(b), ord(c), ord(d)) == (7, 6, 5, 8)
+    doAssert unordered_enum.toSeq == @[a, b, c, d]
+
+  block:
+    type
+      unordered_enum = enum
+        a = 100
+        b
+        c = 500
+        d
+        e
+        f = 50
+        g
+        h
+
+    doAssert (ord(a), ord(b), ord(c), ord(d), ord(e), ord(f), ord(g), ord(h)) == 
+             (100, 101, 500, 501, 502, 50, 51, 52)
+
+  block:
+    type
+      unordered_enum = enum
+        A
+        B
+        C = -1
+        D
+        E
+        G = -999
+
+    doAssert (ord(A), ord(B), ord(C), ord(D), ord(E), ord(G)) ==
+             (0, 1, -1, 2, 3, -999)
+
+  block:
+    type
+      SomeEnum = enum
+        seA = 3
+        seB = 2
+        seC = "foo"
+
+    doAssert (ord(seA), ord(seB), ord(seC)) == (3, 2, 4)
diff --git a/tests/enum/tenum_duplicate.nim b/tests/enum/tenum_duplicate.nim
new file mode 100644
index 000000000..4bcad7f6f
--- /dev/null
+++ b/tests/enum/tenum_duplicate.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "duplicate value in enum 'd'"
+"""
+
+type
+  unordered_enum = enum
+    a = 1
+    b = 0
+    c
+    d = 2
diff --git a/tests/enum/tenum_invalid.nim b/tests/enum/tenum_invalid.nim
new file mode 100644
index 000000000..8ae0a1057
--- /dev/null
+++ b/tests/enum/tenum_invalid.nim
@@ -0,0 +1,8 @@
+discard """
+cmd: "nim check $file"
+"""
+
+type
+  Test = enum
+    A = 9.0 #[tt.Error
+        ^ ordinal type expected; given: float]#
diff --git a/tests/enum/tenum_self.nim b/tests/enum/tenum_self.nim
new file mode 100644
index 000000000..27b1c3204
--- /dev/null
+++ b/tests/enum/tenum_self.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "1 can't be converted to ErrorFoo"
+"""
+
+
+type
+  Foo = enum
+    Bar = 0.Foo
+
+  ErrorFoo = enum
+    eBar = 1.ErrorFoo
diff --git a/tests/enum/toverloadable_enums.nim b/tests/enum/toverloadable_enums.nim
new file mode 100644
index 000000000..9bb551467
--- /dev/null
+++ b/tests/enum/toverloadable_enums.nim
@@ -0,0 +1,120 @@
+discard """
+  output: '''B
+0
+E2-B'''
+joinable: false
+"""
+
+{.experimental: "overloadableEnums".}
+
+type
+  E1 = enum
+    value1,
+    value2
+  E2 = enum
+    value1,
+    value2 = 4
+
+const
+  Lookuptable = [
+    E1.value1: "1",
+    value2: "2"
+  ]
+
+when false:
+  const
+    Lookuptable: array[E1, string] = [
+      value1: "1",
+      value2: "2"
+    ]
+
+
+proc p(e: E1): int =
+  # test that the 'case' statement is smart enough:
+  case e
+  of value1: echo "A"
+  of value2: echo "B"
+
+
+let v = p value2 # ERROR: ambiguous!
+# (value2|value2)  nkClosedSymChoice -> nkSym
+
+proc x(p: int) = discard
+proc x(p: string) = discard
+
+proc takeCallback(param: proc(p: int)) = discard
+
+takeCallback x
+
+echo ord v
+
+block: # https://github.com/nim-lang/RFCs/issues/8
+  type
+    Enum1 = enum
+      A, B, C
+    Enum2 = enum
+      A, Z
+
+  proc f(e: Enum1): int = ord(e)
+  proc g(e: Enum2): int = ord(e)
+
+  proc h(e: Enum1): int = ord(e)
+  proc h(e: Enum2): int = ord(e)
+
+  let fA = f(A) # Type of A is well defined
+  let gA = g(A) # Same as above
+
+  let hA1 = h(Enum1.A) # A requires disambiguation
+  let hA2 = h(Enum2.A) # Similarly
+  let hA3 = h(B)
+  let hA4 = h(B)
+  let x = ord(Enum1.A) # Also
+  doAssert fA == 0
+  doAssert gA == 0
+  doAssert hA1 == 0
+  doAssert hA2 == 0
+  doAssert x == 0
+  doAssert hA3 == 1
+  doAssert hA4 == 1
+
+# bug #18769
+proc g3[T](x: T, e: E2): int =
+  case e
+  of value1: echo "E2-A"        # Error: type mismatch: got 'E1' for 'value1' but expected 'E2 = enum'
+  of value2: echo "E2-B"
+
+let v5 = g3(99, E2.value2)
+
+block: # only allow enums to overload enums
+  # mirrors behavior without overloadableEnums
+  proc foo() = discard
+  block:
+    type Foo = enum foo
+    doAssert foo is Foo
+    foo()
+
+import macros
+block: # test with macros/templates
+  type
+    Enum1 = enum
+      value01, value02
+    Enum2 = enum
+      value01, value10
+
+  macro isOneM(a: untyped): bool =
+    result = newCall(bindSym"==", a, ident"value01")
+
+  macro isOneMS(a: untyped): bool =
+    result = newCall(bindSym"==", a, bindSym"value01")
+
+  template isOneT(a: untyped): bool =
+    a == value01
+
+  let e1 = Enum1.value01
+  let e2 = Enum2.value01
+  doAssert isOneM(e1)
+  doAssert isOneM(e2)
+  doAssert isOneMS(e1)
+  doAssert isOneMS(e2)
+  doAssert isOneT(e1)
+  doAssert isOneT(e2)
diff --git a/tests/enum/toverloadedname.nim b/tests/enum/toverloadedname.nim
new file mode 100644
index 000000000..d11b0fb83
--- /dev/null
+++ b/tests/enum/toverloadedname.nim
@@ -0,0 +1,7 @@
+block: # issue #23998
+  type
+    Enum {.pure.} = enum
+      a
+    Obj = object
+      a: Enum
+  proc test(a: Enum) = discard Obj(a: a)
diff --git a/tests/enum/tpure_enums_conflict.nim b/tests/enum/tpure_enums_conflict.nim
index 3c7528a72..3cf335440 100644
--- a/tests/enum/tpure_enums_conflict.nim
+++ b/tests/enum/tpure_enums_conflict.nim
@@ -1,6 +1,5 @@
 discard """
-  errormsg: "ambiguous identifier: 'amb'"
-  line: 19
+  matrix: "-d:testsConciseTypeMismatch"
 """
 
 # bug #8066
@@ -16,4 +15,13 @@ when true:
 
   echo valueA # MyEnum.valueA
   echo MyEnum.amb # OK.
-  echo amb    # Error: Unclear whether it's MyEnum.amb or OtherEnum.amb
+  echo amb #[tt.Error
+  ^ type mismatch
+Expression: echo amb
+  [1] amb: MyEnum | OtherEnum
+
+Expected one of (first mismatch at [position]):
+[1] proc echo(x: varargs[typed, `$$`])
+  ambiguous identifier: 'amb' -- use one of the following:
+    MyEnum.amb: MyEnum
+    OtherEnum.amb: OtherEnum]#
diff --git a/tests/enum/tpure_enums_conflict_legacy.nim b/tests/enum/tpure_enums_conflict_legacy.nim
new file mode 100644
index 000000000..e592925bc
--- /dev/null
+++ b/tests/enum/tpure_enums_conflict_legacy.nim
@@ -0,0 +1,25 @@
+# bug #8066
+
+when true:
+  type
+    MyEnum {.pure.} = enum
+      valueA, valueB, valueC, valueD, amb
+
+    OtherEnum {.pure.} = enum
+      valueX, valueY, valueZ, amb
+
+
+  echo valueA # MyEnum.valueA
+  echo MyEnum.amb # OK.
+  echo amb #[tt.Error
+  ^ type mismatch: got <MyEnum | OtherEnum>
+but expected one of:
+proc echo(x: varargs[typed, `$$`])
+  first type mismatch at position: 1
+  required type for x: varargs[typed]
+  but expression 'amb' is of type: None
+  ambiguous identifier: 'amb' -- use one of the following:
+    MyEnum.amb: MyEnum
+    OtherEnum.amb: OtherEnum
+
+expression: echo amb]#
diff --git a/tests/enum/tredefinition.nim b/tests/enum/tredefinition.nim
new file mode 100644
index 000000000..615ca6b1c
--- /dev/null
+++ b/tests/enum/tredefinition.nim
@@ -0,0 +1,9 @@
+discard """
+  cmd: '''nim check --hints:off $file'''
+  action: reject
+nimout: '''
+tredefinition.nim(9, 25) Error: redefinition of 'Key_a'; previous declaration here: tredefinition.nim(9, 18)
+'''
+"""
+
+type Key* = enum Key_A, Key_a
\ No newline at end of file
diff --git a/tests/enum/ttypenameconflict.nim b/tests/enum/ttypenameconflict.nim
new file mode 100644
index 000000000..b13bf00ce
--- /dev/null
+++ b/tests/enum/ttypenameconflict.nim
@@ -0,0 +1,13 @@
+# issue #23689
+
+type
+  MyEnum {.pure.} = enum
+    A, B, C, D
+
+  B = object
+    field: int
+
+let x: MyEnum = B
+doAssert $x == "B"
+doAssert typeof(x) is MyEnum
+doAssert x in {A, B}
diff --git a/tests/errmsgs/mambparam1.nim b/tests/errmsgs/mambparam1.nim
new file mode 100644
index 000000000..1a5133c3c
--- /dev/null
+++ b/tests/errmsgs/mambparam1.nim
@@ -0,0 +1 @@
+const test* = "foo"
diff --git a/tests/errmsgs/mambparam2.nim b/tests/errmsgs/mambparam2.nim
new file mode 100644
index 000000000..073e3f8c8
--- /dev/null
+++ b/tests/errmsgs/mambparam2.nim
@@ -0,0 +1,2 @@
+import mambparam1
+export test
diff --git a/tests/errmsgs/mambparam3.nim b/tests/errmsgs/mambparam3.nim
new file mode 100644
index 000000000..5469244e2
--- /dev/null
+++ b/tests/errmsgs/mambparam3.nim
@@ -0,0 +1 @@
+const test* = "bar"
diff --git a/tests/clearmsg/mb.nim b/tests/errmsgs/mb.nim
index 2d21e2396..2d21e2396 100644
--- a/tests/clearmsg/mb.nim
+++ b/tests/errmsgs/mb.nim
diff --git a/tests/clearmsg/mc.nim b/tests/errmsgs/mc.nim
index 79d7431df..79d7431df 100644
--- a/tests/clearmsg/mc.nim
+++ b/tests/errmsgs/mc.nim
diff --git a/tests/errmsgs/t10251.nim b/tests/errmsgs/t10251.nim
new file mode 100644
index 000000000..19adf02eb
--- /dev/null
+++ b/tests/errmsgs/t10251.nim
@@ -0,0 +1,19 @@
+discard """
+  action:reject
+  cmd: "nim check $options $file"
+  nimout: '''
+t10251.nim(19, 23) Error: redefinition of 'goo1'; previous declaration here: t10251.nim(19, 11)
+'''
+"""
+
+# line 10
+type
+  Enum1 = enum
+    foo, bar, baz
+  Enum2 = enum
+    foo, bar, baz
+
+
+type
+  Enum3 {.pure.} = enum # fixed (by accident?) in https://github.com/nim-lang/Nim/pull/18263
+    goo0, goo1, goo2, goo1
diff --git a/tests/errmsgs/t10376.nim b/tests/errmsgs/t10376.nim
index 2ce16d6a2..814c860dc 100644
--- a/tests/errmsgs/t10376.nim
+++ b/tests/errmsgs/t10376.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:refc"
   errormsg: "finalizer must be a direct reference to a proc"
-  line: 29
+  line: 30
 """
 
 type
diff --git a/tests/errmsgs/t10489_a.nim b/tests/errmsgs/t10489_a.nim
index 86659f7ac..c762ce876 100644
--- a/tests/errmsgs/t10489_a.nim
+++ b/tests/errmsgs/t10489_a.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "cannot assign macro 'm' to 'x1'. Did you mean to call the macro with '()'?"
+errormsg: "invalid type: 'macro (body: untyped): untyped{.noSideEffect, gcsafe.}' for let. Did you mean to call the macro with '()'?"
 line: 9
 """
 
diff --git a/tests/errmsgs/t10489_b.nim b/tests/errmsgs/t10489_b.nim
index 1182b4512..df05f0e6e 100644
--- a/tests/errmsgs/t10489_b.nim
+++ b/tests/errmsgs/t10489_b.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "cannot assign macro 'm' to 'x2'. Did you mean to call the macro with '()'?"
+errormsg: "invalid type: 'macro (body: untyped): untyped{.noSideEffect, gcsafe.}' for const. Did you mean to call the macro with '()'?"
 line: 9
 """
 
diff --git a/tests/errmsgs/t10542.nim b/tests/errmsgs/t10542.nim
new file mode 100644
index 000000000..b57dbf18b
--- /dev/null
+++ b/tests/errmsgs/t10542.nim
@@ -0,0 +1,24 @@
+discard """
+  matrix: "--hintaserror:ConvFromXtoItselfNotNeeded"
+"""
+
+# bug #10542
+
+proc f(args: varargs[string, string], length: int) =
+  doAssert args.len == length
+
+# main use case that requires type conversion (no warning here)
+f("a", "b", 2)
+f("a", 1)
+
+
+proc m(args: varargs[cstring, cstring]) =
+  doAssert args.len == 2
+
+# main use case that requires type conversion (no warning here)
+m("a", "b")
+
+# if an argument already is cstring there's a warning
+let x: cstring = "x"
+m("a", x)
+m(x, "a")
\ No newline at end of file
diff --git a/tests/errmsgs/t10594.nim b/tests/errmsgs/t10594.nim
index c9506c542..d27dd6433 100644
--- a/tests/errmsgs/t10594.nim
+++ b/tests/errmsgs/t10594.nim
@@ -3,5 +3,5 @@ discard """
   line: 7
 """
 
-template foo(v: varargs[int]) = unsafeAddr v 
+template foo(v: varargs[int]) = addr v 
 foo(1, 2)
diff --git a/tests/errmsgs/t10734.nim b/tests/errmsgs/t10734.nim
new file mode 100644
index 000000000..4e73db7cd
--- /dev/null
+++ b/tests/errmsgs/t10734.nim
@@ -0,0 +1,20 @@
+discard """
+  cmd: "nim check $file"
+  errormsg: ""
+  nimout: '''
+t10734.nim(19, 1) Error: invalid indentation
+t10734.nim(19, 6) Error: invalid indentation
+t10734.nim(20, 7) Error: expression expected, but found '[EOF]'
+t10734.nim(18, 5) Error: 'proc' is not a concrete type; for a callback without parameters use 'proc()'
+t10734.nim(19, 6) Error: undeclared identifier: 'p'
+t10734.nim(19, 6) Error: expression 'p' has no type (or is ambiguous)
+t10734.nim(19, 6) Error: 'p' cannot be assigned to
+t10734.nim(17, 3) Hint: 'T' is declared but not used [XDeclaredButNotUsed]
+'''
+"""
+
+type
+  T = object
+    a:
+proc p =
+  case
\ No newline at end of file
diff --git a/tests/errmsgs/t10735.nim b/tests/errmsgs/t10735.nim
new file mode 100644
index 000000000..a39cd196e
--- /dev/null
+++ b/tests/errmsgs/t10735.nim
@@ -0,0 +1,68 @@
+discard """
+  cmd: "nim check $file"
+  errormsg: "illformed AST: case buf[pos]"
+  nimout: '''
+t10735.nim(65, 5) Error: 'let' symbol requires an initialization
+t10735.nim(66, 10) Error: undeclared identifier: 'pos'
+t10735.nim(66, 10) Error: expression 'pos' has no type (or is ambiguous)
+t10735.nim(66, 10) Error: expression 'pos' has no type (or is ambiguous)
+t10735.nim(66, 9) Error: type mismatch: got <cstring, >
+but expected one of:
+proc `[]`(s: string; i: BackwardsIndex): char
+  first type mismatch at position: 1
+  required type for s: string
+  but expression 'buf' is of type: cstring
+proc `[]`(s: var string; i: BackwardsIndex): var char
+  first type mismatch at position: 1
+  required type for s: var string
+  but expression 'buf' is of type: cstring
+proc `[]`[I: Ordinal; T](a: T; i: I): T
+  first type mismatch at position: 0
+proc `[]`[Idx, T; U, V: Ordinal](a: array[Idx, T]; x: HSlice[U, V]): seq[T]
+  first type mismatch at position: 1
+  required type for a: array[Idx, T]
+  but expression 'buf' is of type: cstring
+proc `[]`[Idx, T](a: array[Idx, T]; i: BackwardsIndex): T
+  first type mismatch at position: 1
+  required type for a: array[Idx, T]
+  but expression 'buf' is of type: cstring
+proc `[]`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex): var T
+  first type mismatch at position: 1
+  required type for a: var array[Idx, T]
+  but expression 'buf' is of type: cstring
+proc `[]`[T, U: Ordinal](s: string; x: HSlice[T, U]): string
+  first type mismatch at position: 1
+  required type for s: string
+  but expression 'buf' is of type: cstring
+proc `[]`[T; U, V: Ordinal](s: openArray[T]; x: HSlice[U, V]): seq[T]
+  first type mismatch at position: 1
+  required type for s: openArray[T]
+  but expression 'buf' is of type: cstring
+proc `[]`[T](s: openArray[T]; i: BackwardsIndex): T
+  first type mismatch at position: 1
+  required type for s: openArray[T]
+  but expression 'buf' is of type: cstring
+proc `[]`[T](s: var openArray[T]; i: BackwardsIndex): var T
+  first type mismatch at position: 1
+  required type for s: var openArray[T]
+  but expression 'buf' is of type: cstring
+template `[]`(a: WideCStringObj; idx: int): Utf16Char
+  first type mismatch at position: 1
+  required type for a: WideCStringObj
+  but expression 'buf' is of type: cstring
+template `[]`(s: string; i: int): char
+  first type mismatch at position: 1
+  required type for s: string
+  but expression 'buf' is of type: cstring
+
+expression: buf[pos]
+t10735.nim(66, 9) Error: expression '' has no type (or is ambiguous)
+t10735.nim(68, 3) Error: illformed AST: case buf[pos]
+'''
+  joinable: false
+"""
+
+let buf: cstring
+case buf[pos]
+else:
+  case buf[pos]
diff --git a/tests/errmsgs/t12844.nim b/tests/errmsgs/t12844.nim
index 999d26255..a274b72b4 100644
--- a/tests/errmsgs/t12844.nim
+++ b/tests/errmsgs/t12844.nim
@@ -1,9 +1,9 @@
 discard """
 cmd: "nim check $file"
-errormsg: "cannot assign template 'z' to 'y'. Did you mean to call the template with '()'?"
+errormsg: "invalid type: 'template (args: varargs[string])' for var. Did you mean to call the template with '()'?"
 nimout: '''
-t12844.nim(11, 11) Error: cannot assign template 'z' to 'x'. Did you mean to call the template with '()'?
-t12844.nim(12, 9) Error: cannot assign template 'z' to 'y'. Did you mean to call the template with '()'?'''
+t12844.nim(11, 7) Error: invalid type: 'template (args: varargs[string])' for const. Did you mean to call the template with '()'?
+t12844.nim(12, 5) Error: invalid type: 'template (args: varargs[string])' for var. Did you mean to call the template with '()'?'''
 """
 
 template z*(args: varargs[string, `$`]) =
diff --git a/tests/errmsgs/t14444.nim b/tests/errmsgs/t14444.nim
new file mode 100644
index 000000000..27365236e
--- /dev/null
+++ b/tests/errmsgs/t14444.nim
@@ -0,0 +1,14 @@
+discard """
+  matrix: "--hints:off"
+  exitcode: "1"
+  output: '''
+t14444.nim(13)           t14444
+fatal.nim(53)            sysFatal
+Error: unhandled exception: index out of bounds, the container is empty [IndexDefect]
+'''
+"""
+
+when true: # bug #14444
+  var i: string
+  i[10] = 'j'
+  echo i
\ No newline at end of file
diff --git a/tests/errmsgs/t16654.nim b/tests/errmsgs/t16654.nim
new file mode 100644
index 000000000..b2b57619b
--- /dev/null
+++ b/tests/errmsgs/t16654.nim
@@ -0,0 +1,12 @@
+discard """
+  cmd: "nim check $options $file"
+  errormsg: "type mismatch: got <int literal(1), proc (r: GenericParam): auto>"
+"""
+
+when true: # bug #16654
+  func fn[T](a: T, op: proc(a: T): float) = discard
+  proc main() =
+    let v = 1
+    proc bar(r: auto): auto = v
+    fn(1, bar)
+  main()
diff --git a/tests/errmsgs/t17460.nim b/tests/errmsgs/t17460.nim
new file mode 100644
index 000000000..bb8e21198
--- /dev/null
+++ b/tests/errmsgs/t17460.nim
@@ -0,0 +1,19 @@
+discard """
+  cmd: "nim check $options $file"
+  errormsg: "tuple expected for tuple unpacking, but got 'array[0..2, int]'"
+"""
+
+iterator xclusters*[T](a: openArray[T]; s: static[int]): array[s, T] {.inline.} =
+  var result: array[s, T] # iterators have no default result variable
+  var i = 0
+  while i < len(a):
+    for j, x in mpairs(result):
+      x = a[(i + j) mod len(a)]
+    yield result
+    inc(i)
+
+proc m =
+  for (i, j, k) in xclusters([1, 2, 3, 4, 5], 3):
+    echo i, j, k
+
+m()
diff --git a/tests/errmsgs/t18327.nim b/tests/errmsgs/t18327.nim
new file mode 100644
index 000000000..686a1bd0c
--- /dev/null
+++ b/tests/errmsgs/t18327.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "parameter 'n' requires a type"
+"""
+
+proc fn3(n) = discard
\ No newline at end of file
diff --git a/tests/errmsgs/t18886.nim b/tests/errmsgs/t18886.nim
new file mode 100644
index 000000000..8ed160c64
--- /dev/null
+++ b/tests/errmsgs/t18886.nim
@@ -0,0 +1,18 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  errormsg: ""
+  nimout: '''
+t18886.nim(18, 24) Error: ambiguous identifier: 'bar' -- you need a helper proc to disambiguate the following:
+  t18886.bar: proc (i: ptr int){.noSideEffect, gcsafe.}
+  t18886.bar: proc (i: ptr char){.noSideEffect, gcsafe.}
+'''
+"""
+
+type Foo = (proc(_: pointer): void)
+
+
+proc bar(i: ptr[int]) = discard
+proc bar(i: ptr[char]) = discard
+
+
+let fooBar = cast[Foo](bar)
\ No newline at end of file
diff --git a/tests/errmsgs/t18983.nim b/tests/errmsgs/t18983.nim
new file mode 100644
index 000000000..3451875cb
--- /dev/null
+++ b/tests/errmsgs/t18983.nim
@@ -0,0 +1,7 @@
+discard """
+  errormsg: "illegal recursion in type 'A'"
+"""
+
+type
+  A* = A
+  B = (A,)
diff --git a/tests/errmsgs/t19224.nim b/tests/errmsgs/t19224.nim
new file mode 100644
index 000000000..7a9ecb2e7
--- /dev/null
+++ b/tests/errmsgs/t19224.nim
@@ -0,0 +1,12 @@
+discard """
+cmd: "nim check --hints:off $file"
+errormsg: ""
+nimout: '''
+t19224.nim(10, 10) Error: cannot infer element type of items([])
+t19224.nim(12, 10) Error: cannot infer element type of items(@[])
+'''
+"""
+
+for _ in []: discard
+
+for _ in @[]: discard
diff --git a/tests/errmsgs/t19882.nim b/tests/errmsgs/t19882.nim
new file mode 100644
index 000000000..1f2f95ab7
--- /dev/null
+++ b/tests/errmsgs/t19882.nim
@@ -0,0 +1,10 @@
+
+discard """
+  errormsg: "cannot instantiate 'A[T, P]' inside of type definition: 'init'; Maybe generic arguments are missing?"
+"""
+type A[T,P] = object
+  b:T
+  c:P
+proc init(): ref A =      
+  new(result)
+var a = init()
diff --git a/tests/errmsgs/t19882_2.nim b/tests/errmsgs/t19882_2.nim
new file mode 100644
index 000000000..7f3055a5d
--- /dev/null
+++ b/tests/errmsgs/t19882_2.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "cannot instantiate: 'A[T]'; the object's generic parameters cannot be inferred and must be explicitly given"
+"""
+type A[T] = object
+var a = A()
\ No newline at end of file
diff --git a/tests/errmsgs/t21257.nim b/tests/errmsgs/t21257.nim
new file mode 100644
index 000000000..eecdb1dfe
--- /dev/null
+++ b/tests/errmsgs/t21257.nim
@@ -0,0 +1,20 @@
+discard """
+  action: compile
+  cmd: "nim check $file" 
+"""
+
+type AC_WINCTRL_Fields* = distinct uint8
+
+type AC_STATUSA_WSTATE0* {.pure.} = enum
+  ABOVE = 0x0,
+  INSIDE = 0x1,
+  BELOW = 0x2,
+
+type AC_WINCTRL_WINTSEL0* {.pure.} = enum
+  ABOVE = 0x0,
+  INSIDE = 0x1,
+  BELOW = 0x2,
+  OUTSIDE = 0x3,
+
+proc write*(WINTSEL0: AC_WINCTRL_WINTSEL0 = ABOVE) =
+  discard
diff --git a/tests/errmsgs/t22097.nim b/tests/errmsgs/t22097.nim
new file mode 100644
index 000000000..bb24ee8d3
--- /dev/null
+++ b/tests/errmsgs/t22097.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "type mismatch: got <uint8>"
+"""
+
+proc toUInt16(x: var uint16) =
+  discard
+
+var x = uint8(1)
+toUInt16 x
diff --git a/tests/errmsgs/t22284.nim b/tests/errmsgs/t22284.nim
new file mode 100644
index 000000000..827155e6b
--- /dev/null
+++ b/tests/errmsgs/t22284.nim
@@ -0,0 +1,25 @@
+discard """
+  errormsg: "j(uRef, proc (config: F; sources: auto) {.raises: [].} = discard ) can raise an unlisted exception: Exception"
+"""
+
+import std/macros
+
+macro h(): untyped =
+  result = newTree(nnkStmtList)
+  result.add quote do:
+    new int
+
+type F = object
+
+proc j[SecondarySources](
+    uRef: ref SecondarySources,
+    u: proc (config: F, sources: ref SecondarySources)): F =
+  u(result, uRef)
+
+template programMain(body: untyped) =
+  proc main {.raises: [].} = body  # doesn't SIGSEGV without this {.raises: [].}
+  main()
+
+programMain:
+  var uRef = h()
+  discard j(uRef, u = proc(config: F, sources: auto) {.raises: [].} = discard)
\ No newline at end of file
diff --git a/tests/errmsgs/t22753.nim b/tests/errmsgs/t22753.nim
new file mode 100644
index 000000000..8a504109a
--- /dev/null
+++ b/tests/errmsgs/t22753.nim
@@ -0,0 +1,52 @@
+discard """
+cmd: "nim check --hints:off $file"
+errormsg: "type mismatch"
+nimoutFull: true
+nimout: '''
+t22753.nim(51, 13) Error: array expects two type parameters
+t22753.nim(52, 1) Error: expression 'x' has no type (or is ambiguous)
+t22753.nim(52, 1) Error: expression 'x' has no type (or is ambiguous)
+t22753.nim(52, 2) Error: type mismatch: got <>
+but expected one of:
+proc `[]=`(s: var string; i: BackwardsIndex; x: char)
+  first type mismatch at position: 2
+  required type for i: BackwardsIndex
+  but expression '0' is of type: int literal(0)
+proc `[]=`[I: Ordinal; T, S](a: T; i: I; x: sink S)
+  first type mismatch at position: 0
+proc `[]=`[Idx, T; U, V: Ordinal](a: var array[Idx, T]; x: HSlice[U, V];
+                                  b: openArray[T])
+  first type mismatch at position: 2
+  required type for x: HSlice[[]=.U, []=.V]
+  but expression '0' is of type: int literal(0)
+proc `[]=`[Idx, T](a: var array[Idx, T]; i: BackwardsIndex; x: T)
+  first type mismatch at position: 2
+  required type for i: BackwardsIndex
+  but expression '0' is of type: int literal(0)
+proc `[]=`[T, U: Ordinal](s: var string; x: HSlice[T, U]; b: string)
+  first type mismatch at position: 2
+  required type for x: HSlice[[]=.T, []=.U]
+  but expression '0' is of type: int literal(0)
+proc `[]=`[T; U, V: Ordinal](s: var seq[T]; x: HSlice[U, V]; b: openArray[T])
+  first type mismatch at position: 2
+  required type for x: HSlice[[]=.U, []=.V]
+  but expression '0' is of type: int literal(0)
+proc `[]=`[T](s: var openArray[T]; i: BackwardsIndex; x: T)
+  first type mismatch at position: 2
+  required type for i: BackwardsIndex
+  but expression '0' is of type: int literal(0)
+template `[]=`(a: WideCStringObj; idx: int; val: Utf16Char)
+  first type mismatch at position: 3
+  required type for val: Utf16Char
+  but expression '9' is of type: int literal(9)
+template `[]=`(s: string; i: int; val: char)
+  first type mismatch at position: 3
+  required type for val: char
+  but expression '9' is of type: int literal(9)
+
+expression: x[0] = 9
+'''
+"""
+
+var x: array[3] # bug #22753
+x[0] = 9
diff --git a/tests/errmsgs/t22852.nim b/tests/errmsgs/t22852.nim
new file mode 100644
index 000000000..7c352a49c
--- /dev/null
+++ b/tests/errmsgs/t22852.nim
@@ -0,0 +1,9 @@
+discard """
+  exitcode: 1
+  outputsub: '''
+Error: unhandled exception: value out of range: -2 notin 0 .. 9223372036854775807 [RangeDefect]
+'''
+"""
+
+# bug #22852
+echo [0][2..^2]
diff --git a/tests/errmsgs/t22996.nim b/tests/errmsgs/t22996.nim
new file mode 100644
index 000000000..3a51fd8b0
--- /dev/null
+++ b/tests/errmsgs/t22996.nim
@@ -0,0 +1,7 @@
+discard """
+  errormsg: "invalid type: 'typedesc[string]' for const"
+"""
+
+# bug #22996
+type MyObject = ref object
+  _ = string
diff --git a/tests/errmsgs/t23060.nim b/tests/errmsgs/t23060.nim
new file mode 100644
index 000000000..abb79bcc3
--- /dev/null
+++ b/tests/errmsgs/t23060.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "undeclared identifier: '♔♕♖♗♘♙'"
+"""
+
+♔♕♖♗♘♙ = 1
\ No newline at end of file
diff --git a/tests/errmsgs/t23419.nim b/tests/errmsgs/t23419.nim
new file mode 100644
index 000000000..59a72f081
--- /dev/null
+++ b/tests/errmsgs/t23419.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "invalid type: 'void' in this context: '(array[0..-1, void],)' for var"
+"""
+
+var a: (array[0, void], )
diff --git a/tests/errmsgs/t23435.nim b/tests/errmsgs/t23435.nim
new file mode 100644
index 000000000..5e2e4c82a
--- /dev/null
+++ b/tests/errmsgs/t23435.nim
@@ -0,0 +1,12 @@
+discard """
+  outputsub: "Error: unhandled exception: value out of range: -15 notin 0 .. 9223372036854775807 [RangeDefect]"
+  exitcode: "1"
+"""
+
+# bug #23435
+proc foo() =
+  for _ in @[1, 3, 5]:
+    discard "abcde"[25..<10]
+    break
+
+foo()
diff --git a/tests/errmsgs/t23536.nim b/tests/errmsgs/t23536.nim
new file mode 100644
index 000000000..610a85bab
--- /dev/null
+++ b/tests/errmsgs/t23536.nim
@@ -0,0 +1,26 @@
+discard """
+  matrix: "--stackTrace:on --excessiveStackTrace:off"
+"""
+
+const expected = """
+wrong trace:
+t23536.nim(22)           t23536
+t23536.nim(17)           foo
+assertions.nim(41)       failedAssertImpl
+assertions.nim(36)       raiseAssert
+fatal.nim(53)            sysFatal
+"""
+
+
+try:
+  proc foo = # bug #23536
+    doAssert false
+
+  for i in 0 .. 1:
+
+
+    foo()
+except AssertionDefect:
+  let e = getCurrentException()
+  let trace = e.getStackTrace
+  doAssert "wrong trace:\n" & trace == expected
diff --git a/tests/errmsgs/t2614.nim b/tests/errmsgs/t2614.nim
new file mode 100644
index 000000000..031ecb9d1
--- /dev/null
+++ b/tests/errmsgs/t2614.nim
@@ -0,0 +1,21 @@
+discard """
+  cmd: "nim check $options --hints:off $file"
+  errormsg: ""
+  nimout: '''
+t2614.nim(19, 27) Error: type mismatch: got <array[0..1, proc ()]> but expected 'array[0..1, proc (){.closure.}]'
+  Calling convention mismatch: got '{.nimcall.}', but expected '{.closure.}'.
+t2614.nim(21, 22) Error: type mismatch: got <seq[proc ()]> but expected 'seq[proc (){.closure.}]'
+  Calling convention mismatch: got '{.nimcall.}', but expected '{.closure.}'.
+'''
+"""
+
+proc g
+proc f =
+  if false: g()
+proc g =
+  if false: f()
+
+var a = [f, g] # This works
+var b: array[2, proc()] = [f, g] # Error
+
+var c: seq[proc()] = @[f, g] 
\ No newline at end of file
diff --git a/tests/errmsgs/t5167_4.nim b/tests/errmsgs/t5167_4.nim
index 7a263622b..dafd7754d 100644
--- a/tests/errmsgs/t5167_4.nim
+++ b/tests/errmsgs/t5167_4.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "type mismatch: got <proc [*missing parameters*](x: int) | proc (x: string){.gcsafe, locks: 0.}>"
+errormsg: "type mismatch: got <proc [*missing parameters*](x: int) | proc (x: string){.gcsafe.}>"
 line: 19
 """
 
diff --git a/tests/errmsgs/t5167_5.nim b/tests/errmsgs/t5167_5.nim
index a9e260845..dea7e40b3 100644
--- a/tests/errmsgs/t5167_5.nim
+++ b/tests/errmsgs/t5167_5.nim
@@ -1,13 +1,9 @@
 discard """
-cmd: "nim check $file"
-errormsg: "'t' has unspecified generic parameters"
-nimout: '''
-t5167_5.nim(10, 16) Error: expression 'system' has no type (or is ambiguous)
-t5167_5.nim(21, 9) Error: 't' has unspecified generic parameters
-'''
+cmd: "nim check --mm:refc $file"
 """
 # issue #11942
-discard newSeq[system]()
+discard newSeq[system]() #[tt.Error
+               ^ expression 'system' has no type (or is ambiguous)]#
 
 # issue #5167
 template t[B]() =
@@ -18,8 +14,12 @@ macro m[T]: untyped = nil
 proc bar(x: proc (x: int)) =
   echo "bar"
 
-let x = t
-bar t
+let x = t #[tt.Error
+        ^ 't' has unspecified generic parameters]#
+bar t #[tt.Error
+^ type mismatch: got <template [*missing parameters*]()>]#
 
-let y = m
-bar m
+let y = m #[tt.Error
+        ^ 'm' has unspecified generic parameters]#
+bar m #[tt.Error
+^ type mismatch: got <macro [*missing parameters*](): untyped{.noSideEffect, gcsafe.}>]#
diff --git a/tests/errmsgs/t5282.nim b/tests/errmsgs/t5282.nim
new file mode 100644
index 000000000..4da49d155
--- /dev/null
+++ b/tests/errmsgs/t5282.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "illegal recursion in type 'x'"
+"""
+
+type x = distinct x
diff --git a/tests/errmsgs/t5870.nim b/tests/errmsgs/t5870.nim
index bcbc9cca9..96966bcd7 100644
--- a/tests/errmsgs/t5870.nim
+++ b/tests/errmsgs/t5870.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "invalid type for const: seq[SomeRefObj]"
+errormsg: "invalid type: 'SomeRefObj' in this context: 'seq[SomeRefObj]' for const"
 line: 14
 """
 
diff --git a/tests/errmsgs/t6499.nim b/tests/errmsgs/t6499.nim
new file mode 100644
index 000000000..25e78fdbb
--- /dev/null
+++ b/tests/errmsgs/t6499.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "'chr' is a built-in and cannot be used as a first-class procedure"
+"""
+
+# bug #6499
+let x = (chr, 0)
diff --git a/tests/errmsgs/t6608.nim b/tests/errmsgs/t6608.nim
new file mode 100644
index 000000000..88cbf42fd
--- /dev/null
+++ b/tests/errmsgs/t6608.nim
@@ -0,0 +1,15 @@
+discard """
+  cmd: "nim c --hints:off $file"
+  errormsg: "type mismatch: got <>"
+  nimout: '''t6608.nim(13, 4) Error: type mismatch: got <>
+but expected one of:
+AcceptCB = proc (s: string){.closure.}'''
+"""
+
+type
+  AcceptCB = proc (s: string)
+
+proc x(x: AcceptCB) =
+  x()
+
+x()
diff --git a/tests/errmsgs/t8064.nim b/tests/errmsgs/t8064.nim
new file mode 100644
index 000000000..c35a3abcc
--- /dev/null
+++ b/tests/errmsgs/t8064.nim
@@ -0,0 +1,9 @@
+import tables
+
+values
+
+
+discard """
+  # either this or "expression has no type":
+  errormsg: "ambiguous identifier: 'values' -- use one of the following:"
+"""
diff --git a/tests/errmsgs/t8434.nim b/tests/errmsgs/t8434.nim
index ada38e9c0..5d962ee5c 100644
--- a/tests/errmsgs/t8434.nim
+++ b/tests/errmsgs/t8434.nim
@@ -1,10 +1,9 @@
 discard """
   errormsg: "type mismatch: got <byte, int literal(0)>"
   nimout: '''but expected one of:
-proc fun0[T1: int | float |
-    object | array | seq](a1: T1; a2: int)
+proc fun0[T1: int | float | object | array | seq](a1: T1; a2: int)
   first type mismatch at position: 1
-  required type for a1: T1: int or float or object or array or seq[T]
+  required type for a1: T1: int or float or object or array or seq
   but expression 'byte(1)' is of type: byte
 
 expression: fun0(byte(1), 0)
diff --git a/tests/errmsgs/t8610.nim b/tests/errmsgs/t8610.nim
index dd1a3ed29..ec99beae5 100644
--- a/tests/errmsgs/t8610.nim
+++ b/tests/errmsgs/t8610.nim
@@ -1,5 +1,5 @@
 discard """
-  errmsg: "'typedesc' metatype is not valid here; typed '=' instead of ':'?"
+  errormsg: "invalid type: 'typedesc[int]' for const"
 """
-## issue #8610
+## bug #8610
 const Foo = int
diff --git a/tests/errmsgs/t8794.nim b/tests/errmsgs/t8794.nim
index 22e4014f1..36f05dbad 100644
--- a/tests/errmsgs/t8794.nim
+++ b/tests/errmsgs/t8794.nim
@@ -1,33 +1,16 @@
 discard """
   cmd: "nim check $options $file"
-  errormsg: ""
-  nimout: '''
-t8794.nim(39, 27) Error: undeclared field: 'a3' for type m8794.Foo3 [declared in m8794.nim(1, 6)]
-'''
 """
 
-
-
-
-
-
-
-
-
-
-
-
-## line 20
-
 ## issue #8794
 
 import m8794
 
-when false: # pending https://github.com/nim-lang/Nim/pull/10091 add this
-  type Foo = object
-    a1: int
+type Foo = object
+  a1: int
 
-  discard Foo().a2
+discard Foo().a2 #[tt.Error
+             ^ undeclared field: 'a2' for type t8794.Foo [type declared in t8794.nim(9, 6)]]#
 
 type Foo3b = Foo3
 var x2: Foo3b
@@ -36,4 +19,5 @@ proc getFun[T](): T =
   var a: T
   a
 
-discard getFun[type(x2)]().a3
+discard getFun[type(x2)]().a3 #[tt.Error
+                          ^ undeclared field: 'a3' for type m8794.Foo3 [type declared in m8794.nim(1, 6)]]#
diff --git a/tests/errmsgs/t9768.nim b/tests/errmsgs/t9768.nim
index d369150a5..b5ff58367 100644
--- a/tests/errmsgs/t9768.nim
+++ b/tests/errmsgs/t9768.nim
@@ -1,13 +1,14 @@
 discard """
-  errmsg: "unhandled exception:"
-  file: "system/fatal.nim"
+  errormsg: "unhandled exception: t9768.nim(24, 3) `a < 4`  [AssertionDefect]"
+  file: "std/assertions.nim"
+  matrix: "-d:nimPreviewSlimSystem"
   nimout: '''
 stack trace: (most recent call last)
-t9768.nim(28, 33)        main
-t9768.nim(23, 11)        foo1
+t9768.nim(29, 33)        main
+t9768.nim(24, 11)        foo1
 '''
 """
-
+import std/assertions
 
 
 
diff --git a/tests/errmsgs/t9908_01.nim b/tests/errmsgs/t9908_01.nim
index b9d37b67b..99bc8237d 100644
--- a/tests/errmsgs/t9908_01.nim
+++ b/tests/errmsgs/t9908_01.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "ordinal type expected"
+errormsg: "ordinal type expected; given: string"
 line: 10
 """
 
diff --git a/tests/errmsgs/t9908_02.nim b/tests/errmsgs/t9908_02.nim
index 7ff3d1ff7..4fc60b3df 100644
--- a/tests/errmsgs/t9908_02.nim
+++ b/tests/errmsgs/t9908_02.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "ordinal type expected"
+errormsg: "ordinal type expected; given: float"
 line: 10
 """
 
diff --git a/tests/clearmsg/ta.nim b/tests/errmsgs/ta.nim
index 31baae773..31baae773 100644
--- a/tests/clearmsg/ta.nim
+++ b/tests/errmsgs/ta.nim
diff --git a/tests/errmsgs/tambparam.nim b/tests/errmsgs/tambparam.nim
new file mode 100644
index 000000000..5b56a3fce
--- /dev/null
+++ b/tests/errmsgs/tambparam.nim
@@ -0,0 +1,16 @@
+discard """
+  matrix: "-d:testsConciseTypeMismatch"
+"""
+
+import mambparam2, mambparam3
+
+echo test #[tt.Error
+^ type mismatch
+Expression: echo test
+  [1] test: string | string
+
+Expected one of (first mismatch at [position]):
+[1] proc echo(x: varargs[typed, `$$`])
+  ambiguous identifier: 'test' -- use one of the following:
+    mambparam1.test: string
+    mambparam3.test: string]#
diff --git a/tests/errmsgs/tambparam_legacy.nim b/tests/errmsgs/tambparam_legacy.nim
new file mode 100644
index 000000000..bd99a3aac
--- /dev/null
+++ b/tests/errmsgs/tambparam_legacy.nim
@@ -0,0 +1,14 @@
+import mambparam2, mambparam3
+
+echo test #[tt.Error
+^ type mismatch: got <string | string>
+but expected one of:
+proc echo(x: varargs[typed, `$$`])
+  first type mismatch at position: 1
+  required type for x: varargs[typed]
+  but expression 'test' is of type: None
+  ambiguous identifier: 'test' -- use one of the following:
+    mambparam1.test: string
+    mambparam3.test: string
+
+expression: echo test]#
diff --git a/tests/errmsgs/tassignunpack.nim b/tests/errmsgs/tassignunpack.nim
new file mode 100644
index 000000000..09d928a54
--- /dev/null
+++ b/tests/errmsgs/tassignunpack.nim
@@ -0,0 +1,3 @@
+var a, b = 0
+(a, b) = 1 #[tt.Error
+         ^ tuple expected for tuple unpacking, but got 'int literal(1)']#
diff --git a/tests/errmsgs/tcall_with_default_arg.nim b/tests/errmsgs/tcall_with_default_arg.nim
index 1cc86638f..44752f1ee 100644
--- a/tests/errmsgs/tcall_with_default_arg.nim
+++ b/tests/errmsgs/tcall_with_default_arg.nim
@@ -1,5 +1,5 @@
 discard """
-outputsub: '''tcall_with_default_arg.nim(16) anotherFoo'''
+outputsub: '''tcall_with_default_arg.nim(8) fail'''
 exitcode: 1
 """
 # issue: #5604
diff --git a/tests/errmsgs/tcannot_capture_builtin.nim b/tests/errmsgs/tcannot_capture_builtin.nim
index 3b8aae241..65afa627e 100644
--- a/tests/errmsgs/tcannot_capture_builtin.nim
+++ b/tests/errmsgs/tcannot_capture_builtin.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "'+' cannot be passed to a procvar"
+errormsg: "'+' is a built-in and cannot be used as a first-class procedure"
 line: 8
 """
 
diff --git a/tests/errmsgs/tcase_stmt.nim b/tests/errmsgs/tcase_stmt.nim
new file mode 100644
index 000000000..cf63b9c17
--- /dev/null
+++ b/tests/errmsgs/tcase_stmt.nim
@@ -0,0 +1,29 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  errormsg: ""
+  nimout: '''
+tcase_stmt.nim(22, 7) Error: selector must be of an ordinal type, float or string
+tcase_stmt.nim(28, 6) Error: selector must be of an ordinal type, float or string
+
+
+
+
+
+
+
+'''
+"""
+
+
+
+# bug #19682
+type A = object
+
+case A()
+else:
+  discard
+
+# bug #20283
+
+case @[]
+else: discard
diff --git a/tests/errmsgs/tconceptconstraint.nim b/tests/errmsgs/tconceptconstraint.nim
index 9ab1708c7..066ec5bdb 100644
--- a/tests/errmsgs/tconceptconstraint.nim
+++ b/tests/errmsgs/tconceptconstraint.nim
@@ -1,8 +1,7 @@
 discard """
   errormsg: "cannot instantiate B"
-  line: 20
   nimout: '''
-got: <type string>
+got: <typedesc[string]>
 but expected: <T: A>
 '''
 """
diff --git a/tests/errmsgs/tconcisetypemismatch.nim b/tests/errmsgs/tconcisetypemismatch.nim
new file mode 100644
index 000000000..3093cc24e
--- /dev/null
+++ b/tests/errmsgs/tconcisetypemismatch.nim
@@ -0,0 +1,23 @@
+discard """
+  cmd: "nim c --hints:off -d:testsConciseTypeMismatch $file"
+  errormsg: "type mismatch"
+  nimout: '''
+tconcisetypemismatch.nim(23, 47) Error: type mismatch
+Expression: int(inNanoseconds(t2 - t1)) / 100.5
+  [1] int(inNanoseconds(t2 - t1)): int
+  [2] 100.5: float64
+
+Expected one of (first mismatch at [position]):
+[1] proc `/`(x, y: float): float
+[1] proc `/`(x, y: float32): float32
+[2] proc `/`(x, y: int): float
+'''
+"""
+
+import std/monotimes
+from times import inNanoseconds
+
+let t1 = getMonotime()
+let result = 1 + 2
+let t2 = getMonotime()
+echo "Elapsed: ", (t2 - t1).inNanoseconds.int / 100.5
diff --git a/tests/errmsgs/tconstinfo.nim b/tests/errmsgs/tconstinfo.nim
new file mode 100644
index 000000000..170972b9f
--- /dev/null
+++ b/tests/errmsgs/tconstinfo.nim
@@ -0,0 +1,7 @@
+# https://forum.nim-lang.org/t/9762
+
+const foo = "abc"
+case 'a'
+of foo: echo "should error" #[tt.Error
+   ^ type mismatch: got <string> but expected 'char']#
+else: discard
diff --git a/tests/clearmsg/tconsttypemismatch.nim b/tests/errmsgs/tconsttypemismatch.nim
index 727bfbffb..727bfbffb 100644
--- a/tests/clearmsg/tconsttypemismatch.nim
+++ b/tests/errmsgs/tconsttypemismatch.nim
diff --git a/tests/errmsgs/tdeclaredlocs.nim b/tests/errmsgs/tdeclaredlocs.nim
new file mode 100644
index 000000000..926ebf217
--- /dev/null
+++ b/tests/errmsgs/tdeclaredlocs.nim
@@ -0,0 +1,92 @@
+discard """
+  action: reject
+  matrix: "--declaredLocs --hints:off"
+  nimoutFull: true
+  nimout: '''
+tdeclaredlocs.nim(92, 3) Error: type mismatch: got <seq[MyInt2]>
+but expected one of:
+proc fn(a: Bam) [proc declared in tdeclaredlocs.nim(86, 6)]
+  first type mismatch at position: 1
+  required type for a: Bam [object declared in tdeclaredlocs.nim(78, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: Goo[MyInt2]) [proc declared in tdeclaredlocs.nim(89, 6)]
+  first type mismatch at position: 1
+  required type for a: Goo[MyInt2{char}] [object declared in tdeclaredlocs.nim(79, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: Goo[cint]) [proc declared in tdeclaredlocs.nim(88, 6)]
+  first type mismatch at position: 1
+  required type for a: Goo[cint{int32}] [object declared in tdeclaredlocs.nim(79, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: array[3, Bar]) [proc declared in tdeclaredlocs.nim(82, 6)]
+  first type mismatch at position: 1
+  required type for a: array[0..2, Bar] [object declared in tdeclaredlocs.nim(74, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: seq[Bar]) [proc declared in tdeclaredlocs.nim(81, 6)]
+  first type mismatch at position: 1
+  required type for a: seq[Bar] [object declared in tdeclaredlocs.nim(74, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: seq[MyInt1]) [proc declared in tdeclaredlocs.nim(80, 6)]
+  first type mismatch at position: 1
+  required type for a: seq[MyInt1{int}] [int declared in tdeclaredlocs.nim(72, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: set[Baz]) [proc declared in tdeclaredlocs.nim(84, 6)]
+  first type mismatch at position: 1
+  required type for a: set[Baz{enum}] [enum declared in tdeclaredlocs.nim(75, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: set[MyInt2]) [proc declared in tdeclaredlocs.nim(83, 6)]
+  first type mismatch at position: 1
+  required type for a: set[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: var SetBaz) [proc declared in tdeclaredlocs.nim(85, 6)]
+  first type mismatch at position: 1
+  required type for a: var SetBaz [enum declared in tdeclaredlocs.nim(75, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+proc fn(a: var ref ptr Bam) [proc declared in tdeclaredlocs.nim(87, 6)]
+  first type mismatch at position: 1
+  required type for a: var ref ptr Bam [object declared in tdeclaredlocs.nim(78, 3)]
+  but expression 'a' is of type: seq[MyInt2{char}] [char declared in tdeclaredlocs.nim(73, 3)]
+
+expression: fn(a)
+'''
+"""
+
+#[
+see also: tests/errmsgs/tsigmatch.nim
+]#
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# line 70
+type
+  MyInt1 = int
+  MyInt2 = char
+  Bar = object
+  Baz = enum k0, k1
+  Baz2 = Baz
+  SetBaz = set[Baz2]
+  Bam = ref object
+  Goo[T] = object
+proc fn(a: seq[MyInt1]) = discard
+proc fn(a: seq[Bar]) = discard
+proc fn(a: array[3, Bar]) = discard
+proc fn(a: set[MyInt2]) = discard
+proc fn(a: set[Baz]) = discard
+proc fn(a: var SetBaz) = discard
+proc fn(a: Bam) = discard
+proc fn(a: var ref ptr Bam) = discard
+proc fn(a: Goo[cint]) = discard
+proc fn(a: Goo[MyInt2]) = discard
+
+var a: seq[MyInt2]
+fn(a)
diff --git a/tests/errmsgs/tdistinct_nil.nim b/tests/errmsgs/tdistinct_nil.nim
new file mode 100644
index 000000000..a2b403293
--- /dev/null
+++ b/tests/errmsgs/tdistinct_nil.nim
@@ -0,0 +1,23 @@
+discard """
+  cmd: "nim check $file"
+  action: reject
+  nimout: '''
+tdistinct_nil.nim(23, 4) Error: type mismatch: got <typeof(nil)>
+but expected one of:
+proc foo(x: DistinctPointer)
+  first type mismatch at position: 1
+  required type for x: DistinctPointer
+  but expression 'nil' is of type: typeof(nil)
+
+expression: foo(nil)
+'''
+"""
+
+type
+  DistinctPointer = distinct pointer
+
+proc foo(x: DistinctPointer) =
+  discard
+
+foo(DistinctPointer(nil))
+foo(nil)
diff --git a/tests/errmsgs/tdont_show_system.nim b/tests/errmsgs/tdont_show_system.nim
index 830113218..164fdd801 100644
--- a/tests/errmsgs/tdont_show_system.nim
+++ b/tests/errmsgs/tdont_show_system.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "expression 'true' is of type 'bool' and has to be discarded"
+  errormsg: "expression 'true' is of type 'bool' and has to be used (or discarded)"
   line: 13
   file: "tdont_show_system.nim"
 """
diff --git a/tests/errmsgs/tgcsafety.nim b/tests/errmsgs/tgcsafety.nim
index e6a62204e..66496d364 100644
--- a/tests/errmsgs/tgcsafety.nim
+++ b/tests/errmsgs/tgcsafety.nim
@@ -1,15 +1,16 @@
 discard """
 cmd: "nim check $file"
-errormsg: "type mismatch: got <AsyncHttpServer, Port, proc (req: Request): Future[system.void]{.locks: <unknown>.}>"
+errormsg: "type mismatch: got <AsyncHttpServer, Port, proc (req: Request): Future[system.void]>"
 nimout: '''
-type mismatch: got <AsyncHttpServer, Port, proc (req: Request): Future[system.void]{.locks: <unknown>.}>
+tgcsafety.nim(31, 18) Error: type mismatch: got <AsyncHttpServer, Port, proc (req: Request): Future[system.void]>
 but expected one of:
 proc serve(server: AsyncHttpServer; port: Port;
-          callback: proc (request: Request): Future[void] {.closure, gcsafe.};
-          address = ""): owned(Future[void])
+           callback: proc (request: Request): Future[void] {.closure, gcsafe.};
+           address = ""; assumedDescriptorsPerRequest = -1; domain = AF_INET): owned(
+    Future[void])
   first type mismatch at position: 3
   required type for callback: proc (request: Request): Future[system.void]{.closure, gcsafe.}
-  but expression 'cb' is of type: proc (req: Request): Future[system.void]{.locks: <unknown>.}
+  but expression 'cb' is of type: proc (req: Request): Future[system.void]
   This expression is not GC-safe. Annotate the proc with {.gcsafe.} to get extended error information.
 
 expression: serve(server, Port(7898), cb)
diff --git a/tests/errmsgs/tgenericconstraint.nim b/tests/errmsgs/tgenericconstraint.nim
index e3093fead..b51fb3488 100644
--- a/tests/errmsgs/tgenericconstraint.nim
+++ b/tests/errmsgs/tgenericconstraint.nim
@@ -1,8 +1,7 @@
 discard """
   errormsg: "cannot instantiate B"
-  line: 14
   nimout: '''
-got: <type int>
+got: <typedesc[int]>
 but expected: <T: string or float>
 '''
 """
diff --git a/tests/errmsgs/tgenericmismatchsegfault.nim b/tests/errmsgs/tgenericmismatchsegfault.nim
new file mode 100644
index 000000000..dbb783cb3
--- /dev/null
+++ b/tests/errmsgs/tgenericmismatchsegfault.nim
@@ -0,0 +1,13 @@
+discard """
+  matrix: "-d:testsConciseTypeMismatch"
+"""
+
+template v[T](c: SomeOrdinal): T = T(c)
+discard v[int, char]('A') #[tt.Error
+                    ^ type mismatch
+Expression: v[int, char]('A')
+  [1] 'A': char
+
+Expected one of (first mismatch at [position]):
+[2] template v[T](c: SomeOrdinal): T
+  generic parameter mismatch, expected SomeOrdinal but got 'char' of type: char]#
diff --git a/tests/errmsgs/tgenericmismatchsegfault_legacy.nim b/tests/errmsgs/tgenericmismatchsegfault_legacy.nim
new file mode 100644
index 000000000..1532611b9
--- /dev/null
+++ b/tests/errmsgs/tgenericmismatchsegfault_legacy.nim
@@ -0,0 +1,10 @@
+template v[T](c: SomeOrdinal): T = T(c)
+discard v[int, char]('A') #[tt.Error
+                    ^ type mismatch: got <char>
+but expected one of:
+template v[T](c: SomeOrdinal): T
+  first type mismatch at position: 2 in generic parameters
+  required type for SomeOrdinal: SomeOrdinal
+  but expression 'char' is of type: char
+
+expression: v[int, char]('A')]#
diff --git a/tests/errmsgs/tinconsistentgensym.nim b/tests/errmsgs/tinconsistentgensym.nim
new file mode 100644
index 000000000..8e4c85106
--- /dev/null
+++ b/tests/errmsgs/tinconsistentgensym.nim
@@ -0,0 +1,25 @@
+discard """
+  cmd: "nim check --hints:off $file"
+"""
+
+block:
+  template foo =
+    when false:
+      let x = 123
+    else:
+      template x: untyped {.inject.} = 456
+    echo x #[tt.Error
+         ^ undeclared identifier: 'x`gensym0'; if declared in a template, this identifier may be inconsistently marked inject or gensym]#
+  foo()
+
+block:
+  template foo(y: static bool) =
+    block:
+      when y:
+        let x {.gensym.} = 123
+      else:
+        let x {.inject.} = 456
+      echo x #[tt.Error
+           ^ undeclared identifier: 'x']#
+  foo(false)
+  foo(true)
diff --git a/tests/errmsgs/tinteger_literals.nim b/tests/errmsgs/tinteger_literals.nim
index 98c92a227..f90ab14a1 100644
--- a/tests/errmsgs/tinteger_literals.nim
+++ b/tests/errmsgs/tinteger_literals.nim
@@ -1,15 +1,14 @@
 discard """
-cmd: "nim check $file"
-errormsg: "number out of range: '300'u8'"
-nimout: '''
-tinteger_literals.nim(12, 9) Error: number out of range: '18446744073709551616'u64'
-tinteger_literals.nim(13, 9) Error: number out of range: '9223372036854775808'i64'
-tinteger_literals.nim(14, 9) Error: number out of range: '9223372036854775808'
-tinteger_literals.nim(15, 9) Error: number out of range: '300'u8'
-'''
+  cmd: "nim check $file"
 """
-
-discard 18446744073709551616'u64 # high(uint64) + 1
-discard 9223372036854775808'i64  # high(int64) + 1
-discard 9223372036854775808      # high(int64) + 1
-discard 300'u8
\ No newline at end of file
+# high(uint64) + 1
+discard 18446744073709551616'u64 #[tt.Error
+        ^ number out of range: '18446744073709551616'u64' ]#
+# high(int64) + 1
+discard 9223372036854775808'i64 #[tt.Error
+        ^ number out of range: '9223372036854775808'i64' ]#
+# high(int64) + 1
+discard 9223372036854775808 #[tt.Error
+        ^ number out of range: '9223372036854775808' ]#
+discard 300'u8 #[tt.Error
+        ^ number out of range: '300'u8' ]#
diff --git a/tests/errmsgs/tinvalidinout.nim b/tests/errmsgs/tinvalidinout.nim
index 1fa3805ee..268bcf4d5 100644
--- a/tests/errmsgs/tinvalidinout.nim
+++ b/tests/errmsgs/tinvalidinout.nim
@@ -9,7 +9,7 @@ tinvalidinout.nim(18, 9) Error: the 'in' modifier can be used only with imported
 """
 
 type
-  Foo {.header: "foo.h", importcpp.} [in T] = object
+  Foo[in T] {.header: "foo.h", importcpp.} = object
 
   Bar[out X] = object
     x: int
diff --git a/tests/clearmsg/tmacroerrorproc.nim b/tests/errmsgs/tmacroerrorproc.nim
index 86726af72..86726af72 100644
--- a/tests/clearmsg/tmacroerrorproc.nim
+++ b/tests/errmsgs/tmacroerrorproc.nim
diff --git a/tests/errmsgs/tmetaobjectfields.nim b/tests/errmsgs/tmetaobjectfields.nim
new file mode 100644
index 000000000..47d3acf18
--- /dev/null
+++ b/tests/errmsgs/tmetaobjectfields.nim
@@ -0,0 +1,75 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  action: "reject"
+  nimout: '''
+tmetaobjectfields.nim(26, 5) Error: 'array' is not a concrete type
+tmetaobjectfields.nim(30, 5) Error: 'seq' is not a concrete type
+tmetaobjectfields.nim(34, 5) Error: 'set' is not a concrete type
+tmetaobjectfields.nim(37, 3) Error: 'sink' is not a concrete type
+tmetaobjectfields.nim(39, 3) Error: 'lent' is not a concrete type
+tmetaobjectfields.nim(56, 16) Error: 'seq' is not a concrete type
+tmetaobjectfields.nim(60, 5) Error: 'ptr' is not a concrete type
+tmetaobjectfields.nim(61, 5) Error: 'ref' is not a concrete type
+tmetaobjectfields.nim(62, 5) Error: 'auto' is not a concrete type
+tmetaobjectfields.nim(63, 5) Error: 'UncheckedArray' is not a concrete type
+tmetaobjectfields.nim(68, 5) Error: 'object' is not a concrete type
+tmetaobjectfields.nim(72, 5) Error: 'Type3011:ObjectType' is not a concrete type
+'''
+"""
+
+
+# bug #6982
+# bug #19546
+# bug #23531
+type
+  ExampleObj1 = object
+    arr: array
+
+type
+  ExampleObj2 = object
+    arr: seq
+
+type
+  ExampleObj3 = object
+    arr: set
+
+type A = object
+  b: sink
+  # a: openarray
+  c: lent
+
+type PropertyKind = enum
+  tInt,
+  tFloat,
+  tBool,
+  tString,
+  tArray
+
+type
+  Property = ref PropertyObj
+  PropertyObj = object
+    case kind: PropertyKind
+    of tInt: intValue: int
+    of tFloat: floatValue: float
+    of tBool: boolValue: bool
+    of tString: stringValue: string
+    of tArray: arrayValue: seq
+
+type
+  RegressionTest = object
+    a: ptr
+    b: ref
+    c: auto
+    d: UncheckedArray
+
+# bug #3011
+type
+  Type3011 = ref object 
+    context: ref object
+
+type
+  Value3011 = ref object
+    typ: Type3011
+
+proc x3011(): Value3011 =
+  nil
diff --git a/tests/errmsgs/tnested_empty_seq.nim b/tests/errmsgs/tnested_empty_seq.nim
index ffe8bc3ee..871b0ee85 100644
--- a/tests/errmsgs/tnested_empty_seq.nim
+++ b/tests/errmsgs/tnested_empty_seq.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "invalid type: 'empty' in this context: 'array[0..0, tuple of (string, seq[empty])]' for var"
+  errormsg: "invalid type: 'empty' in this context: 'array[0..0, (string, seq[empty])]' for var"
   line: 8
 """
 
diff --git a/tests/errmsgs/tnon_concrete_cast.nim b/tests/errmsgs/tnon_concrete_cast.nim
index e4ae890ce..9e05c736c 100644
--- a/tests/errmsgs/tnon_concrete_cast.nim
+++ b/tests/errmsgs/tnon_concrete_cast.nim
@@ -34,7 +34,7 @@ proc write(rw: var MyReadWrite; value: SomeNumber): void =
 proc write[T](rw: var MyReadWrite; value: seq[T]): void =
   rw.write value.len
   let dst  = cast[ptr SomeNumber](cast[uint](rw.memfile.mem) + uint(rw.offset))
-  let src  = cast[pointer](value[0].unsafeAddr)
+  let src  = cast[pointer](value[0].addr)
   let size = sizeof(T) * value.len
   copyMem(dst, src, size)
   rw.offset += size
diff --git a/tests/misc/tnoop.nim b/tests/errmsgs/tnoop.nim
index a1365cfbe..f55f2441a 100644
--- a/tests/misc/tnoop.nim
+++ b/tests/errmsgs/tnoop.nim
@@ -1,9 +1,8 @@
 discard """
   nimout: '''
-  found 'a' of kind 'var'
+  found 'a' [var declared in tnoop.nim(10, 3)]
   '''
   file: "tnoop.nim"
-  line: 13
   errormsg: "attempting to call routine: 'a'"
 """
 
diff --git a/tests/errmsgs/tproc_mismatch.nim b/tests/errmsgs/tproc_mismatch.nim
new file mode 100644
index 000000000..16f319f3b
--- /dev/null
+++ b/tests/errmsgs/tproc_mismatch.nim
@@ -0,0 +1,74 @@
+discard """
+  action: reject
+  cmd: '''nim check --hints:off $options $file'''
+  nimoutFull: true
+  nimout: '''
+tproc_mismatch.nim(38, 52) Error: type mismatch: got <proc (a: int, c: float){.cdecl, noSideEffect, gcsafe.}> but expected 'proc (a: int, c: float){.closure, noSideEffect.}'
+  Calling convention mismatch: got '{.cdecl.}', but expected '{.closure.}'.
+tproc_mismatch.nim(42, 6) Error: type mismatch: got <proc (){.inline, noSideEffect, gcsafe.}>
+but expected one of:
+proc bar(a: proc ())
+  first type mismatch at position: 1
+  required type for a: proc (){.closure.}
+  but expression 'fn1' is of type: proc (){.inline, noSideEffect, gcsafe.}
+  Calling convention mismatch: got '{.inline.}', but expected '{.closure.}'.
+
+expression: bar(fn1)
+tproc_mismatch.nim(46, 8) Error: type mismatch: got <proc (){.inline, noSideEffect, gcsafe.}> but expected 'proc (){.closure.}'
+  Calling convention mismatch: got '{.inline.}', but expected '{.closure.}'.
+tproc_mismatch.nim(51, 8) Error: type mismatch: got <proc ()> but expected 'proc (){.closure, noSideEffect.}'
+  Calling convention mismatch: got '{.nimcall.}', but expected '{.closure.}'.
+  Pragma mismatch: got '{..}', but expected '{.noSideEffect.}'.
+tproc_mismatch.nim(55, 8) Error: type mismatch: got <proc (a: int){.noSideEffect, gcsafe.}> but expected 'proc (a: float){.closure.}'
+  Calling convention mismatch: got '{.nimcall.}', but expected '{.closure.}'.
+tproc_mismatch.nim(64, 9) Error: type mismatch: got <proc (a: int)> but expected 'proc (a: int){.closure, gcsafe.}'
+  Calling convention mismatch: got '{.nimcall.}', but expected '{.closure.}'.
+  Pragma mismatch: got '{..}', but expected '{.gcsafe.}'.
+tproc_mismatch.nim(72, 9) Error: type mismatch: got <proc (a: int): int{.nimcall.}> but expected 'proc (a: int): int{.cdecl.}'
+  Calling convention mismatch: got '{.nimcall.}', but expected '{.cdecl.}'.
+tproc_mismatch.nim(73, 9) Error: type mismatch: got <proc (a: int): int{.cdecl.}> but expected 'proc (a: int): int{.nimcall.}'
+  Calling convention mismatch: got '{.cdecl.}', but expected '{.nimcall.}'.
+'''
+"""
+
+
+
+block: # CallConv mismatch
+  func a(a: int, c: float) {.cdecl.} = discard
+  var b: proc(a: int, c: float) {.noSideEffect.} = a
+block: # Parameter CallConv mismatch
+  proc fn1() {.inline.} = discard
+  proc bar(a: proc()) = discard
+  bar(fn1)
+block: # CallConv mismatch
+  proc fn1() {.inline.} = discard
+  var fn: proc()
+  fn = fn1
+block: # Pragma mismatch
+  var a = ""
+  proc fn1() = a.add "b"
+  var fn: proc() {.noSideEffect.}
+  fn = fn1
+block: # Fail match not do to Pragma or CallConv
+  proc fn1(a: int) = discard
+  var fn: proc(a: float)
+  fn = fn1
+block: # Infered noSideEffect assign
+  type Foo = ref object
+    x0: int
+  var g0 = Foo(x0: 1)
+  proc fn1(a: int) = g0.x0 = a
+  var fn2: proc(a: int)
+  var fn3: proc(a: int) {.gcsafe.}
+  fn2 = fn1
+  fn3 = fn1
+block: # Indrection through pragmas
+  {.pragma: inl1, inline.}
+  {.pragma: inl2, inline.}
+  {.pragma: p1, nimcall.}
+  {.pragma: p2, cdecl.}
+  var fn1: proc(a: int): int {.inl1, p1.}
+  var fn2: proc(a: int): int {.inl2, p2.}
+  fn2 = fn1
+  fn1 = fn2
+
diff --git a/tests/errmsgs/tproper_stacktrace.nim b/tests/errmsgs/tproper_stacktrace.nim
index c7dfbaf2a..b0a008840 100644
--- a/tests/errmsgs/tproper_stacktrace.nim
+++ b/tests/errmsgs/tproper_stacktrace.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--stackTrace:on --hint:all:off --warnings:off"
   output: '''ok'''
 """
 import strscans, strutils
@@ -6,7 +7,7 @@ import strscans, strutils
 proc raiseTestException*() =
   raise newException(Exception, "test")
 
-proc matchStackTrace(actualEntries: openarray[StackTraceEntry], expected: string) =
+proc matchStackTrace(actualEntries: openArray[StackTraceEntry], expected: string) =
   var expectedEntries = newSeq[StackTraceEntry]()
   var i = 0
 
@@ -76,10 +77,10 @@ when true:
       bar()
 
     const expectedStackTrace = """
-      tproper_stacktrace.nim(86) tproper_stacktrace
-      tproper_stacktrace.nim(76) foo
-      tproper_stacktrace.nim(73) bar
-      tproper_stacktrace.nim(7) raiseTestException
+      tproper_stacktrace.nim(87) tproper_stacktrace
+      tproper_stacktrace.nim(77) foo
+      tproper_stacktrace.nim(74) bar
+      tproper_stacktrace.nim(8) raiseTestException
     """
 
     verifyStackTrace expectedStackTrace:
@@ -93,9 +94,9 @@ when true:
       bar(x)
 
     const expectedStackTrace = """
-      tproper_stacktrace.nim(103) tproper_stacktrace
-      tproper_stacktrace.nim(90) bar
-      tproper_stacktrace.nim(7) raiseTestException
+      tproper_stacktrace.nim(104) tproper_stacktrace
+      tproper_stacktrace.nim(91) bar
+      tproper_stacktrace.nim(8) raiseTestException
     """
 
     verifyStackTrace expectedStackTrace:
@@ -110,10 +111,10 @@ when true:
       bar()
 
     const expectedStackTrace = """
-      tproper_stacktrace.nim(120) tproper_stacktrace
-      tproper_stacktrace.nim(110) foo
-      tproper_stacktrace.nim(107) bar
-      tproper_stacktrace.nim(7) raiseTestException
+      tproper_stacktrace.nim(121) tproper_stacktrace
+      tproper_stacktrace.nim(111) foo
+      tproper_stacktrace.nim(108) bar
+      tproper_stacktrace.nim(8) raiseTestException
     """
 
     verifyStackTrace expectedStackTrace:
@@ -129,10 +130,10 @@ when true:
       bar()
 
     const expectedStackTrace = """
-      tproper_stacktrace.nim(139) tproper_stacktrace
-      tproper_stacktrace.nim(129) foo
-      tproper_stacktrace.nim(125) baz
-      tproper_stacktrace.nim(7) raiseTestException
+      tproper_stacktrace.nim(140) tproper_stacktrace
+      tproper_stacktrace.nim(130) foo
+      tproper_stacktrace.nim(126) baz
+      tproper_stacktrace.nim(8) raiseTestException
     """
 
     verifyStackTrace expectedStackTrace:
diff --git a/tests/errmsgs/tproper_stacktrace2.nim b/tests/errmsgs/tproper_stacktrace2.nim
index 44b208c87..5a6ca3fcb 100644
--- a/tests/errmsgs/tproper_stacktrace2.nim
+++ b/tests/errmsgs/tproper_stacktrace2.nim
@@ -1,5 +1,6 @@
 discard """
-  outputsub: '''tproper_stacktrace2.nim(20) main'''
+  matrix: "--stackTrace:on"
+  outputsub: '''tproper_stacktrace2.nim(21) main'''
   exitcode: 1
 """
 
diff --git a/tests/errmsgs/tproper_stacktrace3.nim b/tests/errmsgs/tproper_stacktrace3.nim
index c292fa092..97d63e6ec 100644
--- a/tests/errmsgs/tproper_stacktrace3.nim
+++ b/tests/errmsgs/tproper_stacktrace3.nim
@@ -1,5 +1,6 @@
 discard """
-  outputsub: '''tproper_stacktrace3.nim(21) main'''
+  matrix: "--stackTrace:on"
+  outputsub: '''tproper_stacktrace3.nim(22) main'''
   exitcode: 1
 """
 
diff --git a/tests/errmsgs/treportunused.nim b/tests/errmsgs/treportunused.nim
index b339e06bf..46afe163d 100644
--- a/tests/errmsgs/treportunused.nim
+++ b/tests/errmsgs/treportunused.nim
@@ -1,16 +1,28 @@
 discard """
+  matrix: "--hint:all:off --hint:XDeclaredButNotUsed"
+  nimoutFull: true
   nimout: '''
-treportunused.nim(19, 10) Hint: 's1' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(26, 5) Hint: 's8' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(22, 6) Hint: 's4' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(25, 7) Hint: 's7' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(24, 7) Hint: 's6' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(23, 6) Hint: 's5' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(20, 10) Hint: 's2' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(29, 6) Hint: 's11' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(27, 5) Hint: 's9' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(21, 10) Hint: 's3' is declared but not used [XDeclaredButNotUsed]
-treportunused.nim(28, 6) Hint: 's10' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(51, 5) Hint: 'A' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(52, 5) Hint: 'B' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(55, 5) Hint: 'D' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(56, 5) Hint: 'E' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(59, 5) Hint: 'G' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(60, 5) Hint: 'H' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(64, 5) Hint: 'K' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(65, 5) Hint: 'L' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(31, 10) Hint: 's1' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(32, 10) Hint: 's2' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(33, 10) Hint: 's3' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(34, 6) Hint: 's4' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(35, 6) Hint: 's5' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(36, 7) Hint: 's6' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(37, 7) Hint: 's7' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(38, 5) Hint: 's8' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(39, 5) Hint: 's9' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(40, 6) Hint: 's10' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(41, 6) Hint: 's11' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(45, 3) Hint: 'v0.99' is declared but not used [XDeclaredButNotUsed]
+treportunused.nim(46, 3) Hint: 'v0.99.99' is declared but not used [XDeclaredButNotUsed]
 '''
 action: compile
 """
@@ -27,3 +39,27 @@ let s8 = 0
 var s9: int
 type s10 = object
 type s11 = type(1.2)
+
+# bug #14407 (requires `compiler/nim.cfg` containing define:nimPreviewFloatRoundtrip)
+let
+  `v0.99` = "0.99"
+  `v0.99.99` = "0.99.99"
+
+block: # bug #18201
+  # Test that unused type aliases raise hint XDeclaredButNotUsed.
+  type
+    A = int
+    B = distinct int
+
+    C = object
+    D = C
+    E = distinct C
+
+    F = string
+    G = F
+    H = distinct F
+
+    J = enum
+      Foo
+    K = J
+    L = distinct J
diff --git a/tests/errmsgs/tsigmatch.nim b/tests/errmsgs/tsigmatch.nim
index 21e2c217d..85ed34169 100644
--- a/tests/errmsgs/tsigmatch.nim
+++ b/tests/errmsgs/tsigmatch.nim
@@ -1,45 +1,45 @@
 discard """
-  cmd: "nim check --showAllMismatches:on --hints:off $file"
+  cmd: "nim check --mm:refc --showAllMismatches:on --hints:off $file"
   nimout: '''
 tsigmatch.nim(111, 4) Error: type mismatch: got <A, string>
 but expected one of:
+proc f(a: A)
+  first type mismatch at position: 2
+  extra argument given
 proc f(b: B)
   first type mismatch at position: 1
   required type for b: B
   but expression 'A()' is of type: A
-proc f(a: A)
-  first type mismatch at position: 2
-  extra argument given
 
 expression: f(A(), "extra")
-tsigmatch.nim(125, 6) Error: type mismatch: got <tuple of (string, proc (){.gcsafe, locks: 0.})>
+tsigmatch.nim(125, 6) Error: type mismatch: got <(string, proc (){.gcsafe.})>
 but expected one of:
 proc foo(x: (string, proc ()))
   first type mismatch at position: 1
-  required type for x: tuple of (string, proc (){.closure.})
-  but expression '("foobar", proc () = echo(["Hello!"]))' is of type: tuple of (string, proc (){.gcsafe, locks: 0.})
+  required type for x: (string, proc (){.closure.})
+  but expression '("foobar", proc () = echo(["Hello!"]))' is of type: (string, proc (){.gcsafe.})
 
 expression: foo(("foobar", proc () = echo(["Hello!"])))
-tsigmatch.nim(132, 11) Error: type mismatch: got <proc (s: string): string{.noSideEffect, gcsafe, locks: 0.}>
+tsigmatch.nim(132, 11) Error: type mismatch: got <proc (s: string): string{.noSideEffect, gcsafe.}>
 but expected one of:
 proc foo[T, S](op: proc (x: T): S {.cdecl.}): auto
   first type mismatch at position: 1
   required type for op: proc (x: T): S{.cdecl.}
-  but expression 'fun' is of type: proc (s: string): string{.noSideEffect, gcsafe, locks: 0.}
+  but expression 'fun' is of type: proc (s: string): string{.noSideEffect, gcsafe.}
 proc foo[T, S](op: proc (x: T): S {.safecall.}): auto
   first type mismatch at position: 1
   required type for op: proc (x: T): S{.safecall.}
-  but expression 'fun' is of type: proc (s: string): string{.noSideEffect, gcsafe, locks: 0.}
+  but expression 'fun' is of type: proc (s: string): string{.noSideEffect, gcsafe.}
 
 expression: foo(fun)
-tsigmatch.nim(143, 13) Error: type mismatch: got <array[0..0, proc (x: int){.gcsafe, locks: 0.}]>
+tsigmatch.nim(143, 13) Error: type mismatch: got <array[0..0, proc (x: int){.gcsafe.}]>
 but expected one of:
-proc takesFuncs(fs: openArray[proc (x: int) {.gcsafe, locks: 0.}])
+proc takesFuncs(fs: openArray[proc (x: int) {.gcsafe.}])
   first type mismatch at position: 1
-  required type for fs: openArray[proc (x: int){.closure, gcsafe, locks: 0.}]
-  but expression '[proc (x: int) {.gcsafe, locks: 0.} = echo [x]]' is of type: array[0..0, proc (x: int){.gcsafe, locks: 0.}]
+  required type for fs: openArray[proc (x: int){.closure, gcsafe.}]
+  but expression '[proc (x: int) {.gcsafe.} = echo [x]]' is of type: array[0..0, proc (x: int){.gcsafe.}]
 
-expression: takesFuncs([proc (x: int) {.gcsafe, locks: 0.} = echo [x]])
+expression: takesFuncs([proc (x: int) {.gcsafe.} = echo [x]])
 tsigmatch.nim(149, 4) Error: type mismatch: got <int literal(10), a0: int literal(5), string>
 but expected one of:
 proc f(a0: uint8; b: string)
@@ -61,14 +61,14 @@ proc f(a1: string; a2: varargs[string]; a3: float; a4: var string)
 expression: f("asdf", "1", "2", "3", "4", 2.3, "bad")
 tsigmatch.nim(164, 4) Error: type mismatch: got <string, a0: int literal(12)>
 but expected one of:
-proc f(x: string; a0: var int)
-  first type mismatch at position: 2
-  required type for a0: var int
-  but expression 'a0 = 12' is immutable, not 'var'
 proc f(x: string; a0: string)
   first type mismatch at position: 2
   required type for a0: string
   but expression 'a0 = 12' is of type: int literal(12)
+proc f(x: string; a0: var int)
+  first type mismatch at position: 2
+  required type for a0: var int
+  but expression 'a0 = 12' is immutable, not 'var'
 
 expression: f(foo, a0 = 12)
 tsigmatch.nim(171, 7) Error: type mismatch: got <Mystring, string>
@@ -89,22 +89,22 @@ expression: fun1(default(Mystring), "asdf")
 
 
 
-
-
-
+#[
+see also: tests/errmsgs/tdeclaredlocs.nim
+]#
 
 
 
 
 
 ## line 100
-block:
+when true:
   # bug #11061 Type mismatch error "first type mismatch at" points to wrong argument/position
   # Note: the error msg now gives correct position for mismatched argument
   type
     A = object of RootObj
     B = object of A
-
+block:
   proc f(b: B) = discard
   proc f(a: A) = discard
 
@@ -132,15 +132,15 @@ block:
   echo foo(fun)
 
 block:
-  # bug #10285 Function signature don't match when inside seq/array/openarray
+  # bug #10285 Function signature don't match when inside seq/array/openArray
   # Note: the error message now shows `closure` which helps debugging the issue
   # out why it doesn't match
-  proc takesFunc(f: proc (x: int) {.gcsafe, locks: 0.}) =
+  proc takesFunc(f: proc (x: int) {.gcsafe.}) =
     echo "takes single Func"
-  proc takesFuncs(fs: openarray[proc (x: int) {.gcsafe, locks: 0.}]) =
+  proc takesFuncs(fs: openArray[proc (x: int) {.gcsafe.}]) =
     echo "takes multiple Func"
-  takesFunc(proc (x: int) {.gcsafe, locks: 0.} = echo x)         # works
-  takesFuncs([proc (x: int) {.gcsafe, locks: 0.} = echo x])      # fails
+  takesFunc(proc (x: int) {.gcsafe.} = echo x)         # works
+  takesFuncs([proc (x: int) {.gcsafe.} = echo x])      # fails
 
 block:
   # bug https://github.com/nim-lang/Nim/issues/11061#issuecomment-508970465
@@ -163,7 +163,7 @@ block:
   var foo = ""
   f(foo, a0 = 12)
 
-block:
+when true:
   type Mystring = string
   type MyInt = int
   proc fun1(a1: MyInt, a2: Mystring) = discard
diff --git a/tests/errmsgs/tsigmatch2.nim b/tests/errmsgs/tsigmatch2.nim
new file mode 100644
index 000000000..31c966337
--- /dev/null
+++ b/tests/errmsgs/tsigmatch2.nim
@@ -0,0 +1,47 @@
+discard """
+  cmd: "nim check --showAllMismatches:on --hints:off $file"
+  nimout: '''
+tsigmatch2.nim(40, 14) Error: type mismatch: got <float64>
+but expected one of:
+proc foo(args: varargs[string, myproc]): string
+  first type mismatch at position: 1
+  required type for args: varargs[string]
+  but expression '1.2' is of type: float64
+proc foo(i: Foo): string
+  first type mismatch at position: 1
+  required type for i: Foo
+  but expression '1.2' is of type: float64
+
+expression: foo(1.2)
+tsigmatch2.nim(40, 14) Error: expression '' has no type (or is ambiguous)
+tsigmatch2.nim(46, 3) Error: type mismatch: got <int literal(1)>
+but expected one of:
+proc foo(args: varargs[string, myproc])
+  first type mismatch at position: 1
+  required type for args: varargs[string]
+  but expression '1' is of type: int literal(1)
+
+expression: foo 1
+'''
+  errormsg: "type mismatch"
+"""
+
+
+# line 30
+type Foo = object
+block: # issue #13182
+  proc myproc(a: int): string = $("myproc", a)
+  proc foo(args: varargs[string, myproc]): string = $args
+
+  proc foo(i: Foo): string = "in foo(i)"
+  static: doAssert foo(Foo()) == "in foo(i)"
+  static: doAssert foo(1) == """["(\"myproc\", 1)"]"""
+  doAssert not compiles(foo(1.2))
+  discard foo(1.2)
+
+block:
+  proc myproc[T](x: T): string =
+    let temp = 12.isNil
+  proc foo(args: varargs[string, myproc]) = discard
+  foo 1
+static: echo "done"
diff --git a/tests/misc/tsimtych.nim b/tests/errmsgs/tsimpletypecheck.nim
index 74a6ad4c0..422437d3a 100644
--- a/tests/misc/tsimtych.nim
+++ b/tests/errmsgs/tsimpletypecheck.nim
@@ -1,6 +1,6 @@
 discard """
   errormsg: "type mismatch: got <bool> but expected \'string\'"
-  file: "tsimtych.nim"
+  file: "tsimpletypecheck.nim"
   line: 10
 """
 # Test 2
diff --git a/tests/errmsgs/tstaticexprscope.nim b/tests/errmsgs/tstaticexprscope.nim
index 7af5bf9b3..6969e389e 100644
--- a/tests/errmsgs/tstaticexprscope.nim
+++ b/tests/errmsgs/tstaticexprscope.nim
@@ -1,5 +1,5 @@
 discard """
-  errmsg: "undeclared identifier: 'z'"
+  errormsg: "undeclared identifier: 'z'"
   line: 11
 """
 
diff --git a/tests/errmsgs/tsubscriptmismatch.nim b/tests/errmsgs/tsubscriptmismatch.nim
new file mode 100644
index 000000000..a2b297b68
--- /dev/null
+++ b/tests/errmsgs/tsubscriptmismatch.nim
@@ -0,0 +1,11 @@
+discard """
+  matrix: "-d:testsConciseTypeMismatch"
+  nimout: '''
+[1] proc `[]`[T; U, V: Ordinal](s: openArray[T]; x: HSlice[U, V]): seq[T]
+'''
+"""
+
+type Foo = object
+let x = Foo()
+discard x[1] #[tt.Error
+         ^ type mismatch]#
diff --git a/tests/errmsgs/tsubscriptmismatch_legacy.nim b/tests/errmsgs/tsubscriptmismatch_legacy.nim
new file mode 100644
index 000000000..3e1f1eb71
--- /dev/null
+++ b/tests/errmsgs/tsubscriptmismatch_legacy.nim
@@ -0,0 +1,10 @@
+discard """
+  nimout: '''
+  but expression 'x' is of type: Foo
+'''
+"""
+
+type Foo = object
+let x = Foo()
+discard x[1] #[tt.Error
+         ^ type mismatch: got <Foo, int literal(1)>]#
diff --git a/tests/errmsgs/ttupleindexoutofbounds.nim b/tests/errmsgs/ttupleindexoutofbounds.nim
new file mode 100644
index 000000000..ae634dddb
--- /dev/null
+++ b/tests/errmsgs/ttupleindexoutofbounds.nim
@@ -0,0 +1,2 @@
+let a = (1, 2)[4] #[tt.Error
+              ^ invalid index 4 in subscript for tuple of length 2]#
diff --git a/tests/errmsgs/ttypeAllowed.nim b/tests/errmsgs/ttypeAllowed.nim
index a5b335faa..fdb4c70b8 100644
--- a/tests/errmsgs/ttypeAllowed.nim
+++ b/tests/errmsgs/ttypeAllowed.nim
@@ -1,11 +1,11 @@
 discard """
 cmd: "nim check $file"
-errmsg: ""
+errormsg: ""
 nimout: '''
-ttypeAllowed.nim(13, 5) Error: invalid type: 'iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe, locks: 0.}' for let
-ttypeAllowed.nim(17, 7) Error: invalid type for const: iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe, locks: 0.}
-ttypeAllowed.nim(21, 5) Error: invalid type: 'iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe, locks: 0.}' for var
-ttypeAllowed.nim(26, 10) Error: invalid type: 'iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe, locks: 0.}' for result
+ttypeAllowed.nim(13, 5) Error: invalid type: 'iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe.}' for let
+ttypeAllowed.nim(17, 7) Error: invalid type: 'iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe.}' for const
+ttypeAllowed.nim(21, 5) Error: invalid type: 'iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe.}' for var
+ttypeAllowed.nim(26, 10) Error: invalid type: 'iterator (a: int, b: int, step: Positive): int{.inline, noSideEffect, gcsafe.}' for result
 '''
 """
 
diff --git a/tests/errmsgs/tundeclared_field.nim b/tests/errmsgs/tundeclared_field.nim
new file mode 100644
index 000000000..5668050e0
--- /dev/null
+++ b/tests/errmsgs/tundeclared_field.nim
@@ -0,0 +1,50 @@
+discard """
+cmd: '''nim check --hints:off $file'''
+action: reject
+nimout: '''
+tundeclared_field.nim(25, 12) Error: undeclared field: 'bad1' for type tundeclared_field.A [type declared in tundeclared_field.nim(22, 8)]
+tundeclared_field.nim(30, 17) Error: undeclared field: 'bad2' for type tundeclared_field.A [type declared in tundeclared_field.nim(28, 8)]
+tundeclared_field.nim(36, 4) Error: undeclared field: 'bad3' for type tundeclared_field.A [type declared in tundeclared_field.nim(33, 8)]
+tundeclared_field.nim(42, 12) Error: undeclared field: 'bad4' for type tundeclared_field.B [type declared in tundeclared_field.nim(39, 8)]
+tundeclared_field.nim(43, 4) Error: undeclared field: 'bad5' for type tundeclared_field.B [type declared in tundeclared_field.nim(39, 8)]
+tundeclared_field.nim(44, 23) Error: undeclared field: 'bad6' for type tundeclared_field.B [type declared in tundeclared_field.nim(39, 8)]
+tundeclared_field.nim(46, 19) Error: undeclared field: 'bad7' for type tundeclared_field.B [type declared in tundeclared_field.nim(39, 8)]
+tundeclared_field.nim(50, 13) Error: cannot instantiate Foo [type declared in tundeclared_field.nim(49, 8)]
+'''
+"""
+
+#[
+xxx in future work, generic instantiations (e.g. `B[int]`) should be shown with their instantiation instead of `tundeclared_field.B`,
+maybe using TPreferedDesc.preferResolved or preferMixed
+]#
+# line 20
+block:
+  type A = object
+    a0: int
+  var a: A
+  discard a.bad1
+
+block:
+  type A = object
+    a0: int
+  var a = A(bad2: 0)
+
+block:
+  type A = object
+    a0: int
+  var a: A
+  a.bad3 = 0
+
+block:
+  type B[T] = object
+    b0: int
+  var b: B[int]
+  discard b.bad4
+  b.bad5 = 0
+  var b2 = B[int](bad6: 0)
+  type Bi = B[int]
+  var b3 = Bi(bad7: 0)
+
+block:
+  type Foo[T: SomeInteger] = object
+  var a: Foo[float]
diff --git a/tests/errmsgs/tundeclared_routine.nim b/tests/errmsgs/tundeclared_routine.nim
new file mode 100644
index 000000000..41b1d35f4
--- /dev/null
+++ b/tests/errmsgs/tundeclared_routine.nim
@@ -0,0 +1,44 @@
+discard """
+cmd: '''nim check --hints:off $file'''
+action: reject
+nimout: '''
+tundeclared_routine.nim(24, 17) Error: attempting to call routine: 'myiter'
+  found tundeclared_routine.myiter(a: string) [iterator declared in tundeclared_routine.nim(22, 12)]
+  found tundeclared_routine.myiter() [iterator declared in tundeclared_routine.nim(23, 12)]
+tundeclared_routine.nim(29, 28) Error: invalid pragma: myPragma
+tundeclared_routine.nim(36, 13) Error: undeclared field: 'bar3' for type tundeclared_routine.Foo [type declared in tundeclared_routine.nim(33, 8)]
+  found tundeclared_routine.bar3() [iterator declared in tundeclared_routine.nim(35, 12)]
+tundeclared_routine.nim(41, 13) Error: undeclared field: 'bar4' for type tundeclared_routine.Foo [type declared in tundeclared_routine.nim(39, 8)]
+tundeclared_routine.nim(44, 11) Error: undeclared identifier: 'bad5'
+'''
+"""
+
+
+
+
+
+# line 20
+block:
+  iterator myiter(a:string): int = discard
+  iterator myiter(): int = discard
+  let a = myiter(1)
+
+block:
+  proc myPragma():int=discard
+  iterator myPragma():int=discard
+  proc myfun(a:int): int {.myPragma.} = 1
+  let a = myfun(1)
+
+block:
+  type Foo = object
+  var a = Foo()
+  iterator bar3():int=discard
+  let a2 = a.bar3
+
+block:
+  type Foo = object
+  var a = Foo()
+  let a2 = a.bar4
+
+block:
+  let a = bad5(1)
diff --git a/tests/errmsgs/undeclared_routime_compiles.nim b/tests/errmsgs/tundeclared_routine_compiles.nim
index 21daf82bf..21daf82bf 100644
--- a/tests/errmsgs/undeclared_routime_compiles.nim
+++ b/tests/errmsgs/tundeclared_routine_compiles.nim
diff --git a/tests/errmsgs/tunknown_named_parameter.nim b/tests/errmsgs/tunknown_named_parameter.nim
index e9be23068..d3dd6cd2d 100644
--- a/tests/errmsgs/tunknown_named_parameter.nim
+++ b/tests/errmsgs/tunknown_named_parameter.nim
@@ -2,26 +2,26 @@ discard """
 cmd: "nim check $file"
 errormsg: "type mismatch: got <string, set[char], maxsplits: int literal(1)>"
 nimout: '''
-proc rsplit(s: string; sep: char; maxsplit: int = -1): seq[string]
+func rsplit(s: string; sep: char; maxsplit: int = -1): seq[string]
   first type mismatch at position: 2
   required type for sep: char
   but expression '{':'}' is of type: set[char]
-proc rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[string]
-  first type mismatch at position: 3
-  unknown named parameter: maxsplits
-proc rsplit(s: string; sep: string; maxsplit: int = -1): seq[string]
+func rsplit(s: string; sep: string; maxsplit: int = -1): seq[string]
   first type mismatch at position: 2
   required type for sep: string
   but expression '{':'}' is of type: set[char]
+func rsplit(s: string; seps: set[char] = Whitespace; maxsplit: int = -1): seq[
+    string]
+  first type mismatch at position: 3
+  unknown named parameter: maxsplits
 
 expression: rsplit("abc:def", {':'}, maxsplits = 1)
 '''
-disabled: 32bit
 """
 
+
 # bug #8043
 
-# disabled on 32 bit systems because the order of suggested proc alternatives is different.
 
 import strutils
 "abc:def".rsplit({':'}, maxsplits = 1)
diff --git a/tests/misc/tnoinst.nim b/tests/errmsgs/tunresolvedinnerproc.nim
index 85db1e8e7..7655a5a41 100644
--- a/tests/misc/tnoinst.nim
+++ b/tests/errmsgs/tunresolvedinnerproc.nim
@@ -1,16 +1,10 @@
-discard """
-  errormsg: "instantiate 'notConcrete' explicitly"
-  line: 12
-  disabled: "true"
-"""
-
 proc wrap[T]() =
   proc notConcrete[T](x, y: int): int =
     var dummy: T
     result = x - y
 
   var x: proc (x, y: T): int
-  x = notConcrete
-
+  x = notConcrete #[tt.Error
+      ^ 'notConcrete' doesn't have a concrete type, due to unspecified generic parameters.]#
 
 wrap[int]()
diff --git a/tests/errmsgs/tuntypedoverload.nim b/tests/errmsgs/tuntypedoverload.nim
new file mode 100644
index 000000000..1b1c2809c
--- /dev/null
+++ b/tests/errmsgs/tuntypedoverload.nim
@@ -0,0 +1,37 @@
+discard """
+  cmd: "nim check $file"
+"""
+
+block:
+  template foo(x: var int, y: untyped) = discard
+  var a: float
+  foo(a, undeclared) #[tt.Error
+     ^ type mismatch: got <float, untyped>]# # `untyped` is arbitary
+  # previous error: undeclared identifier: 'undeclared'
+
+block: # issue #8697
+  type
+    Fruit = enum
+      apple
+      banana
+      orange
+  macro hello(x, y: untyped) = discard
+  hello(apple, banana, orange) #[tt.Error
+       ^ type mismatch: got <Fruit, Fruit, Fruit>]#
+
+block: # issue #23265
+  template declareFoo(fooName: untyped, value: uint16) =
+    const `fooName Value` {.inject.} = value
+
+  declareFoo(FOO, 0xFFFF)
+  declareFoo(BAR, 0xFFFFF) #[tt.Error
+            ^ type mismatch: got <untyped, int literal(1048575)>]#
+
+block: # issue #9620
+  template forLoop(index: untyped, length: int{lvalue}, body: untyped) =
+    for `index`{.inject.} in 0 ..< length:
+      body
+  var x = newSeq[int](10)
+  forLoop(i, x.len): #[tt.Error
+         ^ type mismatch: got <untyped, int, void>]#
+    x[i] = i
diff --git a/tests/errmsgs/twrong_at_operator.nim b/tests/errmsgs/twrong_at_operator.nim
index ebf6d966b..438186f01 100644
--- a/tests/errmsgs/twrong_at_operator.nim
+++ b/tests/errmsgs/twrong_at_operator.nim
@@ -1,17 +1,16 @@
 discard """
-errormsg: "type mismatch: got <array[0..0, type int]>"
-line: 22
+errormsg: "type mismatch: got <array[0..0, typedesc[int]]>"
 nimout: '''
-twrong_at_operator.nim(22, 30) Error: type mismatch: got <array[0..0, type int]>
+twrong_at_operator.nim(21, 30) Error: type mismatch: got <array[0..0, typedesc[int]]>
 but expected one of:
 proc `@`[IDX, T](a: sink array[IDX, T]): seq[T]
   first type mismatch at position: 1
   required type for a: sink array[IDX, T]
-  but expression '[int]' is of type: array[0..0, type int]
+  but expression '[int]' is of type: array[0..0, typedesc[int]]
 proc `@`[T](a: openArray[T]): seq[T]
   first type mismatch at position: 1
   required type for a: openArray[T]
-  but expression '[int]' is of type: array[0..0, type int]
+  but expression '[int]' is of type: array[0..0, typedesc[int]]
 
 expression: @[int]
 '''
diff --git a/tests/errmsgs/twrong_explicit_typeargs.nim b/tests/errmsgs/twrong_explicit_typeargs.nim
new file mode 100644
index 000000000..5236e5f4f
--- /dev/null
+++ b/tests/errmsgs/twrong_explicit_typeargs.nim
@@ -0,0 +1,26 @@
+discard """
+  cmd: "nim c --hints:off -d:testsConciseTypeMismatch $file"
+  action: reject
+  nimout: '''
+twrong_explicit_typeargs.nim(26, 29) Error: type mismatch
+Expression: newImage[string](320, 200)
+  [1] 320: int literal(320)
+  [2] 200: int literal(200)
+
+Expected one of (first mismatch at [position]):
+[1] proc newImage[T: int32 | int64](w, h: int): ref Image[T]
+  generic parameter mismatch, expected int32 or int64 but got 'string' of type: string
+'''
+"""
+
+# bug #4084
+type
+  Image[T] = object
+    data: seq[T]
+
+proc newImage[T: int32|int64](w, h: int): ref Image[T] =
+  new(result)
+  result.data = newSeq[T](w * h)
+
+var correct = newImage[int32](320, 200)
+var wrong = newImage[string](320, 200)
diff --git a/tests/errmsgs/twrong_explicit_typeargs_legacy.nim b/tests/errmsgs/twrong_explicit_typeargs_legacy.nim
new file mode 100644
index 000000000..cfa528c54
--- /dev/null
+++ b/tests/errmsgs/twrong_explicit_typeargs_legacy.nim
@@ -0,0 +1,25 @@
+discard """
+  action: reject
+  nimout: '''
+twrong_explicit_typeargs_legacy.nim(25, 29) Error: type mismatch: got <int literal(320), int literal(200)>
+but expected one of:
+proc newImage[T: int32 | int64](w, h: int): ref Image[T]
+  first type mismatch at position: 1 in generic parameters
+  required type for T: int32 or int64
+  but expression 'string' is of type: string
+
+expression: newImage[string](320, 200)
+'''
+"""
+
+# bug #4084
+type
+  Image[T] = object
+    data: seq[T]
+
+proc newImage[T: int32|int64](w, h: int): ref Image[T] =
+  new(result)
+  result.data = newSeq[T](w * h)
+
+var correct = newImage[int32](320, 200)
+var wrong = newImage[string](320, 200)
diff --git a/tests/errmsgs/twrongcolon.nim b/tests/errmsgs/twrongcolon.nim
index 6f5cc3e5d..06e802eb7 100644
--- a/tests/errmsgs/twrongcolon.nim
+++ b/tests/errmsgs/twrongcolon.nim
@@ -1,11 +1,10 @@
 discard """
-errormsg: "in expression '("
+errormsg: "in expression ' do:"
 nimout: '''
-Error: in expression '(
-  890)': identifier expected, but found ''
+twrongcolon.nim(10, 12) Error: in expression ' do:
+  890': identifier expected, but found ''
 '''
 
-line: 11
 """
 
 var n: int : 890
diff --git a/tests/errmsgs/undeclared_routime.nim b/tests/errmsgs/undeclared_routime.nim
deleted file mode 100644
index 426507652..000000000
--- a/tests/errmsgs/undeclared_routime.nim
+++ /dev/null
@@ -1,13 +0,0 @@
-discard """
-cmd: '''nim c --hints:off $file'''
-errormsg: "attempting to call routine: 'myiter'"
-nimout: '''undeclared_routime.nim(13, 15) Error: attempting to call routine: 'myiter'
-  found 'undeclared_routime.myiter(a: string)[declared in undeclared_routime.nim(10, 9)]' of kind 'iterator'
-  found 'undeclared_routime.myiter()[declared in undeclared_routime.nim(11, 9)]' of kind 'iterator'
-'''
-"""
-
-iterator myiter(a:string): int = discard
-iterator myiter(): int = discard
-
-let a = myiter(1)
diff --git a/tests/errmsgs/undeclared_routime2.nim b/tests/errmsgs/undeclared_routime2.nim
deleted file mode 100644
index 3e48b48f4..000000000
--- a/tests/errmsgs/undeclared_routime2.nim
+++ /dev/null
@@ -1,9 +0,0 @@
-discard """
-cmd: '''nim c --hints:off $file'''
-errormsg: "invalid pragma: myPragma"
-"""
-
-proc myPragma():int=discard
-iterator myPragma():int=discard
-proc myfun(a:int): int {.myPragma.} = 1
-let a = myfun(1)
diff --git a/tests/errmsgs/undeclared_routime3.nim b/tests/errmsgs/undeclared_routime3.nim
deleted file mode 100644
index 052adfc08..000000000
--- a/tests/errmsgs/undeclared_routime3.nim
+++ /dev/null
@@ -1,13 +0,0 @@
-discard """
-cmd: '''nim c --hints:off $file'''
-errormsg: "undeclared field: 'bar'"
-nimout: '''undeclared_routime3.nim(13, 10) Error: undeclared field: 'bar'
-  found 'undeclared_routime3.bar()[declared in undeclared_routime3.nim(12, 9)]' of kind 'iterator'
-'''
-"""
-
-
-type Foo = object
-var a = Foo()
-iterator bar():int=discard
-let a = a.bar
diff --git a/tests/errmsgs/undeclared_routime4.nim b/tests/errmsgs/undeclared_routime4.nim
deleted file mode 100644
index 674caa421..000000000
--- a/tests/errmsgs/undeclared_routime4.nim
+++ /dev/null
@@ -1,10 +0,0 @@
-discard """
-cmd: '''nim c --hints:off $file'''
-errormsg: "undeclared field: 'bar'"
-nimout: '''undeclared_routime4.nim(10, 10) Error: undeclared field: 'bar'
-'''
-"""
-
-type Foo = object
-var a = Foo()
-let a = a.bar
diff --git a/tests/errmsgs/undeclared_routime5.nim b/tests/errmsgs/undeclared_routime5.nim
deleted file mode 100644
index 4394134ab..000000000
--- a/tests/errmsgs/undeclared_routime5.nim
+++ /dev/null
@@ -1,9 +0,0 @@
-discard """
-cmd: '''nim c --hints:off $file'''
-errormsg: "undeclared identifier: 'myfun'"
-nimout: '''undeclared_routime5.nim(9, 9) Error: undeclared identifier: 'myfun'
-'''
-"""
-
-
-let a = myfun(1)
diff --git a/tests/exception/m21261.nim b/tests/exception/m21261.nim
new file mode 100644
index 000000000..11b12fb5b
--- /dev/null
+++ b/tests/exception/m21261.nim
@@ -0,0 +1 @@
+raise (ref Exception)(msg: "something")
\ No newline at end of file
diff --git a/tests/exception/m22469.nim b/tests/exception/m22469.nim
new file mode 100644
index 000000000..201698701
--- /dev/null
+++ b/tests/exception/m22469.nim
@@ -0,0 +1,4 @@
+# ModuleB
+echo "First top-level statement of ModuleB"
+echo high(int) + 1
+echo "ModuleB last statement"
\ No newline at end of file
diff --git a/tests/exception/t13115.nim b/tests/exception/t13115.nim
new file mode 100644
index 000000000..5db8f9107
--- /dev/null
+++ b/tests/exception/t13115.nim
@@ -0,0 +1,31 @@
+const msg = "This char is `" & '\0' & "` and works fine!"
+
+when defined nim_t13115:
+  # bug #13115
+  template fn =
+    raise newException(Exception, msg)
+  when defined nim_t13115_static:
+    static: fn()
+  fn()
+else:
+  import std/[osproc,strformat,os,strutils]
+  proc main =
+    const nim = getCurrentCompilerExe()
+    const file = currentSourcePath
+    for b in "c js cpp".split:
+      # save CI time by avoiding mostly redundant combinations as far as this bug is concerned
+      var opts = case b
+        of "c": @["", "-d:nim_t13115_static", "-d:danger", "-d:debug"]
+        of "js": @["", "-d:nim_t13115_static"]
+        else: @[""]
+
+      for opt in opts:
+        let cmd = fmt"{nim} r -b:{b} -d:nim_t13115 {opt} --hints:off {file}"
+        let (outp, exitCode) = execCmdEx(cmd)
+        when defined windows:
+          # `\0` not preserved on windows
+          doAssert "` and works fine!" in outp, cmd & "\n" & msg
+        else:
+          doAssert msg in outp, cmd & "\n" & msg
+        doAssert exitCode == 1
+  main()
diff --git a/tests/exception/t18620.nim b/tests/exception/t18620.nim
new file mode 100644
index 000000000..ee23f8bac
--- /dev/null
+++ b/tests/exception/t18620.nim
@@ -0,0 +1,17 @@
+discard """
+  matrix: "--gc:arc; --gc:refc"
+"""
+
+proc hello() =
+  raise newException(ValueError, "You are wrong")
+
+var flag = false
+
+try:
+  hello()
+except ValueError as e:
+  flag = true
+  doAssert len(getStackTraceEntries(e)) > 0
+  doAssert len(getStackTraceEntries(e)) > 0
+
+doAssert flag
diff --git a/tests/exception/t20613.nim b/tests/exception/t20613.nim
new file mode 100644
index 000000000..6edb69415
--- /dev/null
+++ b/tests/exception/t20613.nim
@@ -0,0 +1,8 @@
+discard """
+  matrix: "; --panics:on"
+"""
+
+func test =
+  if 0 > 10:
+    raiseAssert "hey"
+test()
diff --git a/tests/exception/t21261.nim b/tests/exception/t21261.nim
new file mode 100644
index 000000000..84817d854
--- /dev/null
+++ b/tests/exception/t21261.nim
@@ -0,0 +1,9 @@
+discard """
+  exitcode: 1
+  outputsub: '''
+m21261.nim(1)            m21261
+Error: unhandled exception: something [Exception]
+'''
+"""
+
+import m21261
\ No newline at end of file
diff --git a/tests/exception/t22008.nim b/tests/exception/t22008.nim
new file mode 100644
index 000000000..c0758e7b4
--- /dev/null
+++ b/tests/exception/t22008.nim
@@ -0,0 +1,8 @@
+template detect(v: untyped) =
+  doAssert typeof(v) is int
+
+detect:
+  try:
+    raise (ref ValueError)()
+  except ValueError:
+    42
\ No newline at end of file
diff --git a/tests/exception/t22469.nim b/tests/exception/t22469.nim
new file mode 100644
index 000000000..a76c74967
--- /dev/null
+++ b/tests/exception/t22469.nim
@@ -0,0 +1,16 @@
+discard """
+  exitcode: 1
+  output: '''
+First top-level statement of ModuleB
+m22469.nim(3)            m22469
+fatal.nim(53)            sysFatal
+Error: unhandled exception: over- or underflow [OverflowDefect]
+'''
+"""
+
+# bug #22469
+
+# ModuleA
+import m22469
+echo "ModuleA about to have exception"
+echo high(int) + 1
diff --git a/tests/exception/t9657.nim b/tests/exception/t9657.nim
index 0b6e128e0..6ac525a70 100644
--- a/tests/exception/t9657.nim
+++ b/tests/exception/t9657.nim
@@ -1,9 +1,12 @@
 discard """
   action: run
   exitcode: 1
-  target: "c"
+  targets: "c cpp"
+  disabled: "openbsd"
+  disabled: "netbsd"
 """
-# todo: remove `target: "c"` workaround once #10343 is properly fixed
+
 close stdmsg
 const m = "exception!"
+# see #10343 for details on this test
 discard writeBuffer(stdmsg, cstring(m), m.len)
diff --git a/tests/exception/tcpp_imported_exc.nim b/tests/exception/tcpp_imported_exc.nim
index c8349f7d5..55a58440f 100644
--- a/tests/exception/tcpp_imported_exc.nim
+++ b/tests/exception/tcpp_imported_exc.nim
@@ -1,6 +1,8 @@
 discard """
+matrix: "--mm:refc"
 targets: "cpp"
-output: '''caught as std::exception
+output: '''
+caught as std::exception
 expected
 finally1
 finally2
@@ -12,9 +14,10 @@ finally 2
 expected
 cpp exception caught
 '''
+disabled: "windows" # pending bug #18011
 """
 
-type 
+type
   std_exception* {.importcpp: "std::exception", header: "<exception>".} = object
   std_runtime_error* {.importcpp: "std::runtime_error", header: "<stdexcept>".} = object
   std_string* {.importcpp: "std::string", header: "<string>".} = object
@@ -25,7 +28,7 @@ proc constructRuntimeError(s: stdstring): std_runtime_error {.importcpp: "std::r
 
 proc what(ex: std_runtime_error): cstring {.importcpp: "((char *)#.what())".}
 
-proc myexception = 
+proc myexception =
   raise constructRuntimeError(constructStdString("cpp_exception"))
 
 try:
@@ -41,17 +44,17 @@ except std_exception:
 
 doAssert(getCurrentException() == nil)
 
-proc earlyReturn = 
+proc earlyReturn =
   try:
     try:
-        myexception()
+      myexception()
     finally:
       echo "finally1"
   except:
     return
   finally:
     echo "finally2"
-  
+
 earlyReturn()
 doAssert(getCurrentException() == nil)
 
@@ -74,7 +77,7 @@ doAssert(getCurrentException() == nil)
 # raise by pointer and also generic type
 
 type
-  std_vector {.importcpp"std::vector", header"<vector>".} [T] = object
+  std_vector[T] {.importcpp"std::vector", header"<vector>".} = object
 
 proc newVector[T](len: int): ptr std_vector[T] {.importcpp: "new std::vector<'1>(@)".}
 proc deleteVector[T](v: ptr std_vector[T]) {.importcpp: "delete @; @ = NIM_NIL;".}
@@ -118,16 +121,15 @@ try:
     echo "finally 2"
 except:
   echo "expected"
-  
-  
+
 doAssert(getCurrentException() == nil)
 
 try:
-    try:
-      myexception()
-    except std_runtime_error as ex:
-      echo "cpp exception caught"
-      raise newException(ValueError, "rewritten " & $ex.what())
+  try:
+    myexception()
+  except std_runtime_error as ex:
+    echo "cpp exception caught"
+    raise newException(ValueError, "rewritten " & $ex.what())
 except:
   doAssert(getCurrentExceptionMsg() == "rewritten cpp_exception")
 
diff --git a/tests/exception/tcpp_imported_exc2.nim b/tests/exception/tcpp_imported_exc2.nim
new file mode 100644
index 000000000..ff299ea3d
--- /dev/null
+++ b/tests/exception/tcpp_imported_exc2.nim
@@ -0,0 +1,10 @@
+discard """
+targets: "cpp"
+output: ""
+"""
+#issue #14369 case 2
+type RuntimeError {.requiresInit, importcpp: "std::runtime_error", header: "<stdexcept>".} = object
+
+proc initRuntimeError(a: cstring): RuntimeError {.importcpp: "std::runtime_error(@)", constructor.}
+try: raise initRuntimeError("foo2")
+except: discard
diff --git a/tests/exception/texcas.nim b/tests/exception/texcas.nim
index 7108e334c..ad6819f11 100644
--- a/tests/exception/texcas.nim
+++ b/tests/exception/texcas.nim
@@ -1,8 +1,9 @@
 discard """
   targets: "c cpp"
-  output: '''Hello
+  output: '''
 Hello
-  '''
+Hello
+'''
 """
 proc test[T]() =
   try:
diff --git a/tests/exception/texception_inference.nim b/tests/exception/texception_inference.nim
new file mode 100644
index 000000000..7dd01cca1
--- /dev/null
+++ b/tests/exception/texception_inference.nim
@@ -0,0 +1,32 @@
+discard """

+  output: '''good'''

+  cmd: "nim c --gc:orc -d:release $file"

+"""

+

+type

+  Raising[T, E] = object

+

+proc foo[T, Errors](x: proc (x: Raising[T, Errors])) {.raises: Errors.} =

+  discard

+

+proc callback(x: Raising[int, ValueError]) =

+  echo "callback"

+

+proc xy() {.raises: [ValueError].} =

+  foo callback

+

+proc x[E]() {.raises: [E, IOError].} =

+  raise newException(E, "text here")

+

+try:

+  x[ValueError]()

+except ValueError:

+  echo "good"

+

+proc callback2(x: Raising[int, IOError]) =

+  discard

+

+proc foo2[T, OtherErrors](x: proc(x: Raising[T, OtherErrors])) {.raises: [ValueError, OtherErrors].} =

+  discard

+

+foo2 callback2

diff --git a/tests/exception/texceptionbreak.nim b/tests/exception/texceptionbreak.nim
index 6548192c6..b8ce7eead 100644
--- a/tests/exception/texceptionbreak.nim
+++ b/tests/exception/texceptionbreak.nim
@@ -29,16 +29,16 @@ echo "2"
 try:
   raise newException(OSError, "Problem")
 except OSError:
-  block:
-    break
+  block label:
+    break label
 
 echo "3"
 
 # Fourth Variety
-block:
+block label:
   try:
     raise newException(OSError, "Problem")
   except OSError:
-    break
+    break label
 
 echo "4"
diff --git a/tests/exception/texceptions.nim b/tests/exception/texceptions.nim
index 7bce32837..62d24c934 100644
--- a/tests/exception/texceptions.nim
+++ b/tests/exception/texceptions.nim
@@ -1,5 +1,8 @@
 discard """
+  disabled: "windows" # no sigsetjmp() there
+  matrix: "-d:nimStdSetjmp; -d:nimSigSetjmp; -d:nimRawSetjmp; -d:nimBuiltinSetjmp"
   output: '''
+
 BEFORE
 FINALLY
 
@@ -16,7 +19,7 @@ FINALLY
 
 echo ""
 
-proc no_expcetion =
+proc no_exception =
   try:
     echo "BEFORE"
 
@@ -27,7 +30,7 @@ proc no_expcetion =
   finally:
     echo "FINALLY"
 
-try: no_expcetion()
+try: no_exception()
 except: echo "RECOVER"
 
 echo ""
@@ -89,10 +92,10 @@ block:
       result.add(1212)
     try:
       try:
-        raise newException(AssertionError, "a")
+        raise newException(AssertionDefect, "a")
       finally:
         result.add(42)
-    except AssertionError:
+    except AssertionDefect:
       result.add(99)
     finally:
       result.add(10)
@@ -104,7 +107,7 @@ block:
       result.add(-1)
     except ValueError:
       result.add(-1)
-    except IndexError:
+    except IndexDefect:
       result.add(2)
     except:
       result.add(3)
diff --git a/tests/exception/texceptions2.nim b/tests/exception/texceptions2.nim
new file mode 100644
index 000000000..97fd856a0
--- /dev/null
+++ b/tests/exception/texceptions2.nim
@@ -0,0 +1,130 @@
+discard """
+  disabled: "posix" # already covered by texceptions.nim
+  matrix: "-d:nimStdSetjmp; -d:nimRawSetjmp; -d:nimBuiltinSetjmp"
+  output: '''
+
+BEFORE
+FINALLY
+
+BEFORE
+EXCEPT
+FINALLY
+RECOVER
+
+BEFORE
+EXCEPT: IOError: hi
+FINALLY
+'''
+"""
+
+echo ""
+
+proc no_exception =
+  try:
+    echo "BEFORE"
+
+  except:
+    echo "EXCEPT"
+    raise
+
+  finally:
+    echo "FINALLY"
+
+try: no_exception()
+except: echo "RECOVER"
+
+echo ""
+
+proc reraise_in_except =
+  try:
+    echo "BEFORE"
+    raise newException(IOError, "")
+
+  except IOError:
+    echo "EXCEPT"
+    raise
+
+  finally:
+    echo "FINALLY"
+
+try: reraise_in_except()
+except: echo "RECOVER"
+
+echo ""
+
+proc return_in_except =
+  try:
+    echo "BEFORE"
+    raise newException(IOError, "hi")
+
+  except:
+    echo "EXCEPT: ", getCurrentException().name, ": ", getCurrentExceptionMsg()
+    return
+
+  finally:
+    echo "FINALLY"
+
+try: return_in_except()
+except: echo "RECOVER"
+
+block: #10417
+  proc moo() {.noreturn.} = discard
+
+  let bar =
+    try:
+      1
+    except:
+      moo()
+
+  doAssert(bar == 1)
+
+# Make sure the VM handles the exceptions correctly
+block:
+  proc fun1(): seq[int] =
+    try:
+      try:
+        raise newException(ValueError, "xx")
+      except:
+        doAssert("xx" == getCurrentExceptionMsg())
+        raise newException(KeyError, "yy")
+    except:
+      doAssert("yy" == getCurrentExceptionMsg())
+      result.add(1212)
+    try:
+      try:
+        raise newException(AssertionDefect, "a")
+      finally:
+        result.add(42)
+    except AssertionDefect:
+      result.add(99)
+    finally:
+      result.add(10)
+    result.add(4)
+    result.add(0)
+    try:
+      result.add(1)
+    except KeyError:
+      result.add(-1)
+    except ValueError:
+      result.add(-1)
+    except IndexDefect:
+      result.add(2)
+    except:
+      result.add(3)
+
+    try:
+      try:
+        result.add(1)
+        return
+      except:
+        result.add(-1)
+      finally:
+        result.add(2)
+    except KeyError:
+      doAssert(false)
+    finally:
+      result.add(3)
+
+  let x1 = fun1()
+  const x2 = fun1()
+  doAssert(x1 == x2)
diff --git a/tests/exception/tindexerrorformatbounds.nim b/tests/exception/tindexerrorformatbounds.nim
deleted file mode 100644
index 7563c5ffa..000000000
--- a/tests/exception/tindexerrorformatbounds.nim
+++ /dev/null
@@ -1,31 +0,0 @@
-import os, osproc, strutils
-
-const characters = "abcdefghijklmnopqrstuvwxyz"
-var s: string
-
-# # chcks.nim:23
-# # test formatErrorIndexBound returns correct bounds
-block:
-  s = characters
-  try:
-    discard s[0..999]
-  except IndexError:
-    let msg = getCurrentExceptionMsg()
-    let expected = "index $# not in 0 .. $#" % [$len(s), $(len(s)-1)]
-    doAssert msg.contains expected, $(msg, expected)
-
-block:
-  try:
-    discard paramStr(999)
-  except IndexError:
-    let msg = getCurrentExceptionMsg()
-    let expected = "index 999 not in 0 .. 0"
-    doAssert msg.contains expected, $(msg, expected)
-
-block:
-  const nim = getCurrentCompilerExe()
-  for i in 1..4:
-    let (outp, errC) = execCmdEx("$# e tests/exception/testindexerroroutput.nims test$#" % [nim, $i])
-    let expected = "index 3 not in 0 .. 2"
-    doAssert errC != 0
-    doAssert outp.contains expected, $(outp, errC, expected, i)
diff --git a/tests/exception/tsetexceptions.nim b/tests/exception/tsetexceptions.nim
new file mode 100644
index 000000000..0e353f43e
--- /dev/null
+++ b/tests/exception/tsetexceptions.nim
@@ -0,0 +1,11 @@
+discard """
+  targets: "c cpp js"
+  joinable: false
+"""
+
+# refs https://github.com/nim-lang/Nim/pull/18247#issuecomment-860877161
+
+let ex = newException(CatchableError, "test")
+setCurrentException(ex)
+doAssert getCurrentException().msg == ex.msg
+doAssert getCurrentExceptionMsg() == ex.msg
diff --git a/tests/exception/twrongexc.nim b/tests/exception/twrongexc.nim
index 9c656f3d9..d229c5749 100644
--- a/tests/exception/twrongexc.nim
+++ b/tests/exception/twrongexc.nim
@@ -4,5 +4,5 @@ discard """
 """
 try:
   raise newException(ValueError, "")
-except OverflowError:
+except OverflowDefect:
   echo("Error caught")
diff --git a/tests/exprs/t22604.nim b/tests/exprs/t22604.nim
new file mode 100644
index 000000000..c41cd3dfa
--- /dev/null
+++ b/tests/exprs/t22604.nim
@@ -0,0 +1,36 @@
+# if
+for i in 0..<1:
+  let x =
+    case false
+    of true:
+      42
+    of false:
+      if true:
+        continue
+      else:
+        raiseAssert "Won't get here"
+
+# nested case
+for i in 0..<1:
+  let x =
+    case false
+    of true:
+      42
+    of false:
+      case true
+      of true:
+        continue
+      of false:
+        raiseAssert "Won't get here"
+
+# try except
+for i in 0..<1:
+  let x =
+    case false
+    of true:
+      42
+    of false:
+      try:
+        continue
+      except:
+        raiseAssert "Won't get here"
\ No newline at end of file
diff --git a/tests/exprs/texprstmt.nim b/tests/exprs/texprstmt.nim
index 742670cc1..3c9704650 100644
--- a/tests/exprs/texprstmt.nim
+++ b/tests/exprs/texprstmt.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "expression 'result[1 .. BackwardsIndex(1)]' is of type 'string' and has to be discarded"
+  errormsg: "expression 'result[1 .. BackwardsIndex(1)]' is of type 'string' and has to be used (or discarded)"
   line: 10
 """
 
diff --git a/tests/exprs/tresultwarning.nim b/tests/exprs/tresultwarning.nim
index 32934408e..28dabfdb1 100644
--- a/tests/exprs/tresultwarning.nim
+++ b/tests/exprs/tresultwarning.nim
@@ -1,5 +1,5 @@
 discard """
-  nimout: "Special variable 'result' is shadowed. [ResultShadowed]"
+  nimout: "tresultwarning.nim(6, 7) Warning: Special variable 'result' is shadowed. [ResultShadowed]"
 """
 
 proc test(): string =
diff --git a/tests/exprs/tstmtexp.nim b/tests/exprs/tstmtexp.nim
index 75d8dd081..0ae866497 100644
--- a/tests/exprs/tstmtexp.nim
+++ b/tests/exprs/tstmtexp.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "expression '5' is of type 'int literal(5)' and has to be discarded"
+  errormsg: "expression '5' is of type 'int literal(5)' and has to be used (or discarded)"
   file: "tstmtexp.nim"
   line: 8
 """
diff --git a/tests/float/tfloat1.nim b/tests/float/tfloat1.nim
index 54d49a7c1..d3497f24c 100644
--- a/tests/float/tfloat1.nim
+++ b/tests/float/tfloat1.nim
@@ -1,5 +1,5 @@
 discard """
-  outputsub: "Error: unhandled exception: FPU operation caused an overflow [FloatOverflowError]"
+  outputsub: "Error: unhandled exception: FPU operation caused an overflow [FloatOverflowDefect]"
   exitcode: "1"
 """
 # Test new floating point exceptions
diff --git a/tests/float/tfloat2.nim b/tests/float/tfloat2.nim
index 130c71087..1de63dde3 100644
--- a/tests/float/tfloat2.nim
+++ b/tests/float/tfloat2.nim
@@ -1,5 +1,5 @@
 discard """
-  outputsub: "Error: unhandled exception: FPU operation caused a NaN result [FloatInvalidOpError]"
+  outputsub: "Error: unhandled exception: FPU operation caused a NaN result [FloatInvalidOpDefect]"
   exitcode: "1"
 """
 # Test new floating point exceptions
diff --git a/tests/float/tfloat4.nim b/tests/float/tfloat4.nim
index 6a87cbe66..2bb61eb58 100644
--- a/tests/float/tfloat4.nim
+++ b/tests/float/tfloat4.nim
@@ -8,7 +8,7 @@ proc c_sprintf(buf, fmt: cstring) {.importc:"sprintf", header: "<stdio.h>", vara
 
 proc floatToStr(f: float64): string =
   var buffer: array[128, char]
-  c_sprintf(addr buffer, "%.16e", f)
+  c_sprintf(cast[cstring](addr buffer), "%.16e", f)
   result = ""
   for ch in buffer:
     if ch == '\0':
@@ -54,4 +54,16 @@ doAssert 9999999999999999.0 == "9999999999999999.0".parseFloat
 doAssert 0.999999999999999 == ".999999999999999".parseFloat
 doAssert 0.9999999999999999 == ".9999999999999999".parseFloat
 
+# bug #18400
+var s = [-13.888888'f32]
+doAssert $s[0] == "-13.888888"
+var x = 1.23456789012345'f32
+doAssert $x == "1.2345679"
+
+# bug #21847
+doAssert parseFloat"0e+42" == 0.0
+doAssert parseFloat"0e+42949672969" == 0.0
+doAssert parseFloat"0e+42949672970" == 0.0
+doAssert parseFloat"0e+42949623223346323563272970" == 0.0
+
 echo("passed all tests.")
diff --git a/tests/float/tfloat6.nim b/tests/float/tfloat6.nim
deleted file mode 100644
index c4cd6e932..000000000
--- a/tests/float/tfloat6.nim
+++ /dev/null
@@ -1,23 +0,0 @@
-discard """
-  output: '''
-1e-06 : 1e-06
-1e-06 : 1e-06
-0.001 : 0.001
-1e-06 : 1e-06
-1e-06 : 1e-06
-10.000001 : 10.000001
-100.000001 : 100.000001
-'''
-  disabled: "windows"
-"""
-
-import strutils
-
-echo "0.00_0001".parseFloat(), " : ", 1E-6
-echo "0.00__00_01".parseFloat(), " : ", 1E-6
-echo "0.0_01".parseFloat(), " : ", 0.001
-echo "0.00_000_1".parseFloat(), " : ", 1E-6
-echo "0.00000_1".parseFloat(), " : ", 1E-6
-
-echo "1_0.00_0001".parseFloat(), " : ", 10.000001
-echo "1__00.00_0001".parseFloat(), " : ", 1_00.000001
diff --git a/tests/float/tfloatmod.nim b/tests/float/tfloatmod.nim
index 0b84ec7e0..37546a64c 100644
--- a/tests/float/tfloatmod.nim
+++ b/tests/float/tfloatmod.nim
@@ -1,5 +1,5 @@
 discard """
-  targets: "c c++ js"
+  targets: "c cpp js"
   output: "ok"
   exitcode: "0"
 """
diff --git a/tests/float/tfloatnan.nim b/tests/float/tfloatnan.nim
index 8f384c3d9..9e3dd94f6 100644
--- a/tests/float/tfloatnan.nim
+++ b/tests/float/tfloatnan.nim
@@ -15,7 +15,7 @@ echo "Nim: ", f32, " (float)"
 let f64: float64 = NaN
 echo "Nim: ", f64, " (double)"
 
-block: # issue #10305
+block: # bug #10305
   # with `-O3 -ffast-math`, generated C/C++ code is not nan compliant
   # user can pass `--passC:-ffast-math` if he doesn't care.
   proc fun() =
@@ -42,3 +42,16 @@ block: # issue #10305
   fun()
   fun2(0)
 
+template main() =
+  # xxx move all tests under here
+  block: # bug #16469
+    let a1 = 0.0
+    let a2 = -0.0
+    let a3 = 1.0 / a1
+    let a4 = 1.0 / a2
+    doAssert a3 == Inf
+    doAssert a4 == -Inf
+    doAssert $(a1, a2, a3, a4) == "(0.0, -0.0, inf, -inf)"
+
+static: main()
+main()
diff --git a/tests/float/tfloats.nim b/tests/float/tfloats.nim
new file mode 100644
index 000000000..aaed2d615
--- /dev/null
+++ b/tests/float/tfloats.nim
@@ -0,0 +1,163 @@
+discard """
+  matrix: "-d:nimPreviewFloatRoundtrip; -u:nimPreviewFloatRoundtrip"
+  targets: "c cpp js"
+"""
+
+#[
+xxx merge all or most float tests into this file
+]#
+
+import std/[fenv, math, strutils]
+import stdtest/testutils
+
+proc equalsOrNaNs(a, b: float): bool =
+  if isNaN(a): isNaN(b)
+  elif a == 0:
+    b == 0 and signbit(a) == signbit(b)
+  else:
+    a == b
+
+template reject(a) =
+  doAssertRaises(ValueError): discard parseFloat(a)
+
+template main =
+  block:
+    proc test(a: string, b: float) =
+      let a2 = a.parseFloat
+      doAssert equalsOrNaNs(a2, b), $(a, a2, b)
+    test "0.00_0001", 1E-6
+    test "0.00__00_01", 1E-6
+    test "0.0_01", 0.001
+    test "0.00_000_1", 1E-6
+    test "0.00000_1", 1E-6
+    test "1_0.00_0001", 10.000001
+    test "1__00.00_0001", 1_00.000001
+    test "inf", Inf
+    test "-inf", -Inf
+    test "-Inf", -Inf
+    test "-INF", -Inf
+    test "NaN", NaN
+    test "-nan", NaN
+    test ".1", 0.1
+    test "-.1", -0.1
+    test "-0", -0.0
+    test "-0", -0'f # see #18246, -0 won't work
+    test ".1e-1", 0.1e-1
+    test "0_1_2_3.0_1_2_3E+0_1_2", 123.0123e12
+    test "0_1_2.e-0", 12e0
+    test "0_1_2e-0", 12e0
+    test "-0e0", -0.0
+    test "-0e-0", -0.0
+
+  reject "a"
+  reject ""
+  reject "e1"
+  reject "infa"
+  reject "infe1"
+  reject "_"
+  reject "1e"
+
+  when false: # gray area; these numbers should probably be invalid
+    reject "1_"
+    reject "1_.0"
+    reject "1.0_"
+
+  block: # bugs mentioned in https://github.com/nim-lang/Nim/pull/18504#issuecomment-881635317
+    block: # example 1
+      let a = 0.1+0.2
+      doAssert a != 0.3
+      when defined(nimPreviewFloatRoundtrip):
+        doAssert $a == "0.30000000000000004"
+      else:
+        whenRuntimeJs: discard
+        do: doAssert $a == "0.3"
+    block: # example 2
+      const a = 0.1+0.2
+      when defined(nimPreviewFloatRoundtrip):
+        doAssert $($a, a) == """("0.30000000000000004", 0.30000000000000004)"""
+      else:
+        whenRuntimeJs: discard
+        do: doAssert $($a, a) == """("0.3", 0.3)"""
+    block: # example 3
+      const a1 = 0.1+0.2
+      let a2 = a1
+      doAssert a1 != 0.3
+      when defined(nimPreviewFloatRoundtrip):
+        doAssert $[$a1, $a2] == """["0.30000000000000004", "0.30000000000000004"]"""
+      else:
+        whenRuntimeJs: discard
+        do: doAssert $[$a1, $a2] == """["0.3", "0.3"]"""
+
+  when defined(nimPreviewFloatRoundtrip):
+    block: # bug #18148
+      var a = 1.1'f32
+      doAssert $a == "1.1", $a # was failing
+
+    block: # bug #18400
+      block:
+        let a1 = 0.1'f32
+        let a2 = 0.2'f32
+        let a3 = a1 + a2
+        var s = ""
+        s.addFloat(a3)
+        whenVMorJs: discard # xxx refs #12884
+        do:
+          doAssert a3 == 0.3'f32
+          doAssert $a3 == "0.3"
+
+      block:
+        let a1 = 0.1
+        let a2 = 0.2
+        let a3 = a1 + a2
+        var s = ""
+        s.addFloat(a3)
+        doAssert a3 != 0.3
+        doAssert $a3 == "0.30000000000000004"
+
+      block:
+        var s = [-13.888888'f32]
+        whenRuntimeJs: discard
+        do:
+          doAssert $s == "[-13.888888]"
+          doAssert $s[0] == "-13.888888"
+
+    block: # bug #7717
+      proc test(f: float) =
+        let f2 = $f
+        let f3 = parseFloat(f2)
+        doAssert equalsOrNaNs(f, f3), $(f, f2, f3)
+      test 1.0 + epsilon(float64)
+      test 1000000.0000000123
+      test log2(100000.0)
+      test maximumPositiveValue(float32)
+      test maximumPositiveValue(float64)
+      test minimumPositiveValue(float32)
+      test minimumPositiveValue(float64)
+
+    block: # bug #12884
+      block: # example 1
+        const x0: float32 = 1.32
+        let x1 = 1.32
+        let x2 = 1.32'f32
+        var x3: float32 = 1.32
+        doAssert $(x0, x1, x2, x3) == "(1.32, 1.32, 1.32, 1.32)"
+      block: # example https://github.com/nim-lang/Nim/issues/12884#issuecomment-564967962
+        let x = float(1.32'f32)
+        when nimvm: discard # xxx prints 1.3
+        else:
+          when not defined(js):
+            doAssert $x == "1.3200000524520874"
+        doAssert $1.32 == "1.32"
+        doAssert $1.32'f32 == "1.32"
+        let x2 = 1.32'f32
+        doAssert $x2 == "1.32"
+      block:
+        var x = 1.23456789012345'f32
+        when nimvm:
+          discard # xxx, refs #12884
+        else:
+          doAssert x == 1.2345679'f32
+          doAssert $x == "1.2345679"
+
+static: main()
+main()
diff --git a/tests/gc/closureleak.nim b/tests/gc/closureleak.nim
index 0265431d0..e67beb513 100644
--- a/tests/gc/closureleak.nim
+++ b/tests/gc/closureleak.nim
@@ -11,9 +11,19 @@ var foo_counter = 0
 var alive_foos = newseq[int](0)
 
 when defined(gcDestructors):
-  proc `=destroy`(some: var TFoo) =
+  proc `=destroy`(some: TFoo) =
     alive_foos.del alive_foos.find(some.id)
-    `=destroy`(some.fn)
+    # TODO: fixme: investigate why `=destroy` requires `some.fn` to be `gcsafe`
+    # the debugging info below came from `symPrototype` in the liftdestructors
+    # proc (){.closure, gcsafe.}, {tfThread, tfHasAsgn, tfCheckedForDestructor, tfExplicitCallConv}
+    # var proc (){.closure, gcsafe.}, {tfHasGCedMem}
+    # it worked by accident with var T destructors because in the sempass2
+    #
+    # let argtype = skipTypes(a.typ, abstractInst) # !!! it does't skip `tyVar`
+    # if argtype.kind == tyProc and notGcSafe(argtype) and not tracked.inEnforcedGcSafe:
+    #   localError(tracked.config, n.info, $n & " is not GC safe")
+    {.cast(gcsafe).}:
+      `=destroy`(some.fn)
 
 else:
   proc free*(some: ref TFoo) =
diff --git a/tests/gc/cyclecollector.nim b/tests/gc/cyclecollector.nim
index 7b47758f2..2d02a7a3c 100644
--- a/tests/gc/cyclecollector.nim
+++ b/tests/gc/cyclecollector.nim
@@ -9,7 +9,10 @@ type
 proc createCycle(leaf: string): Node =
   new result
   result.a = result
-  shallowCopy result.leaf, leaf
+  when defined(gcArc) or defined(gcOrc):
+    result.leaf = leaf
+  else:
+    shallowCopy result.leaf, leaf
 
 proc main =
   for i in 0 .. 100_000:
diff --git a/tests/gc/gcleak.nim b/tests/gc/gcleak.nim
index 0b2e6e14d..0bf993968 100644
--- a/tests/gc/gcleak.nim
+++ b/tests/gc/gcleak.nim
@@ -12,7 +12,14 @@ type
 proc makeObj(): TTestObj =
   result.x = "Hello"
 
-for i in 1 .. 100_000:
+const numIter =
+  # see tests/gc/gcleak2.nim
+  when defined(boehmgc):
+    1_000
+  elif defined(gcMarkAndSweep): 10_000
+  else: 100_000
+
+for i in 1 .. numIter:
   when defined(gcMarkAndSweep) or defined(boehmgc):
     GC_fullcollect()
   var obj = makeObj()
diff --git a/tests/gc/gcleak2.nim b/tests/gc/gcleak2.nim
index fe1718aef..bc943dbe7 100644
--- a/tests/gc/gcleak2.nim
+++ b/tests/gc/gcleak2.nim
@@ -14,8 +14,20 @@ proc makeObj(): TTestObj =
   result.x = "Hello"
   result.s = @[1,2,3]
 
+const numIter =
+  when defined(boehmgc):
+    # super slow because GC_fullcollect() at each iteration; especially
+    # on OSX 10.15 where it takes ~170s
+    # `getOccupiedMem` should be constant after each iteration for i >= 3
+    1_000
+  elif defined(gcMarkAndSweep):
+    # likewise, somewhat slow, 1_000_000 would run for 8s
+    # and same remark as above
+    100_000
+  else: 1_000_000
+
 proc inProc() =
-  for i in 1 .. 1_000_000:
+  for i in 1 .. numIter:
     when defined(gcMarkAndSweep) or defined(boehmgc):
       GC_fullcollect()
     var obj: TTestObj
diff --git a/tests/gc/gcleak3.nim b/tests/gc/gcleak3.nim
index 588e238e9..5e146d69f 100644
--- a/tests/gc/gcleak3.nim
+++ b/tests/gc/gcleak3.nim
@@ -17,14 +17,10 @@ for i in 0..1024:
   s.add(obj)
 
 proc limit*[t](a: var seq[t]) =
-  var loop = s.len() - 512
-  for i in 0..loop:
-    #echo i
-    #GC_fullCollect()
+  while s.len > 0:
     if getOccupiedMem() > 3000_000: quit("still a leak!")
-    s.delete(i)
+    s.delete(0)
 
 s.limit()
-
 echo "no leak: ", getOccupiedMem()
 
diff --git a/tests/gc/gcleak4.nim b/tests/gc/gcleak4.nim
index fbe18a386..a72db67b7 100644
--- a/tests/gc/gcleak4.nim
+++ b/tests/gc/gcleak4.nim
@@ -35,7 +35,7 @@ proc newPlus(a, b: sink(ref TExpr)): ref TPlusExpr =
 
 const Limit = when compileOption("gc", "markAndSweep") or compileOption("gc", "boehm"): 5*1024*1024 else: 500_000
 
-for i in 0..100_000:
+for i in 0..50_000:
   var s: array[0..11, ref TExpr]
   for j in 0..high(s):
     s[j] = newPlus(newPlus(newLit(j), newLit(2)), newLit(4))
diff --git a/tests/gc/gcleak5.nim b/tests/gc/gcleak5.nim
index 6ab50e19e..f1913831b 100644
--- a/tests/gc/gcleak5.nim
+++ b/tests/gc/gcleak5.nim
@@ -9,7 +9,7 @@ proc main =
   for ii in 0..50_000:
     #while true:
     var t = getTime()
-    var g = t.getGMTime()
+    var g = t.utc()
     #echo isOnStack(addr g)
 
     if i mod 100 == 0:
diff --git a/tests/gc/growobjcrash.nim b/tests/gc/growobjcrash.nim
index 07f92b8f4..ff1aa7e98 100644
--- a/tests/gc/growobjcrash.nim
+++ b/tests/gc/growobjcrash.nim
@@ -1,8 +1,4 @@
-discard """
-  output: "works"
-"""
-
-import cgi, strtabs
+import std/[cgi, strtabs]
 
 proc handleRequest(query: string): StringTableRef =
   iterator foo(): StringTableRef {.closure.} =
@@ -18,7 +14,7 @@ const Limit = 5*1024*1024
 
 proc main =
   var counter = 0
-  for i in 0 .. 100_000:
+  for i in 0 .. 10_000:
     for k, v in handleRequest("nick=Elina2&type=activate"):
       inc counter
       if counter mod 100 == 0:
@@ -26,4 +22,3 @@ proc main =
           quit "but now a leak"
 
 main()
-echo "works"
diff --git a/tests/gc/panicoverride.nim b/tests/gc/panicoverride.nim
new file mode 100644
index 000000000..0f28b0b72
--- /dev/null
+++ b/tests/gc/panicoverride.nim
@@ -0,0 +1,14 @@
+
+proc printf(frmt: cstring) {.varargs, importc, header: "<stdio.h>", cdecl.}
+proc exit(code: int) {.importc, header: "<stdlib.h>", cdecl.}
+
+{.push stack_trace: off, profiler:off.}
+
+proc rawoutput(s: string) =
+  printf("%s\n", s)
+
+proc panic(s: string) {.noreturn.} =
+  rawoutput(s)
+  exit(1)
+
+{.pop.}
\ No newline at end of file
diff --git a/tests/gc/tdisable_orc.nim b/tests/gc/tdisable_orc.nim
new file mode 100644
index 000000000..b5f161c79
--- /dev/null
+++ b/tests/gc/tdisable_orc.nim
@@ -0,0 +1,9 @@
+discard """
+  joinable: false
+"""
+
+import std/asyncdispatch
+
+# bug #22256
+GC_disableMarkAndSweep()
+waitFor sleepAsync(1000)
diff --git a/tests/gc/thavlak.nim b/tests/gc/thavlak.nim
index b4cdacf7c..cfd860e25 100644
--- a/tests/gc/thavlak.nim
+++ b/tests/gc/thavlak.nim
@@ -1,13 +1,13 @@
 discard """
   output: '''Welcome to LoopTesterApp, Nim edition
 Constructing Simple CFG...
-15000 dummy loops
+5000 dummy loops
 Constructing CFG...
 Performing Loop Recognition
 1 Iteration
-Another 5 iterations...
-.....
-Found 1 loops (including artificial root node) (5)'''
+Another 3 iterations...
+...
+Found 1 loops (including artificial root node) (3)'''
 """
 
 # bug #3184
@@ -384,9 +384,9 @@ proc run(self: var LoopTesterApp) =
   discard self.cfg.createNode(1)
   self.buildConnect(0, 2)
 
-  echo "15000 dummy loops"
+  echo "5000 dummy loops"
 
-  for i in 1..15000:
+  for i in 1..5000:
     withScratchRegion:
       var h = newHavlakLoopFinder(self.cfg, newLsg())
       discard h.findLoops
@@ -394,7 +394,7 @@ proc run(self: var LoopTesterApp) =
   echo "Constructing CFG..."
   var n = 2
 
-  when not defined(gcOrc):
+  when true: # not defined(gcOrc):
     # currently cycle detection is so slow that we disable this part
     for parlooptrees in 1..10:
       discard self.cfg.createNode(n + 1)
@@ -414,10 +414,10 @@ proc run(self: var LoopTesterApp) =
   var h = newHavlakLoopFinder(self.cfg, newLsg())
   var loops = h.findLoops
 
-  echo "Another 5 iterations..."
+  echo "Another 3 iterations..."
 
   var sum = 0
-  for i in 1..5:
+  for i in 1..3:
     withScratchRegion:
       write stdout, "."
       flushFile(stdout)
@@ -437,4 +437,5 @@ proc main =
 let mem = getOccupiedMem()
 main()
 when defined(gcOrc):
+  GC_fullCollect()
   doAssert getOccupiedMem() == mem
diff --git a/tests/gc/trace_globals.nim b/tests/gc/trace_globals.nim
new file mode 100644
index 000000000..f62a15692
--- /dev/null
+++ b/tests/gc/trace_globals.nim
@@ -0,0 +1,33 @@
+discard """
+  output: '''
+10000000
+10000000
+10000000'''
+"""
+
+# bug #17085
+
+#[
+refs https://github.com/nim-lang/Nim/issues/17085#issuecomment-786466595
+with --gc:boehm, this warning sometimes gets generated:
+Warning: Repeated allocation of very large block (appr. size 14880768):
+May lead to memory leak and poor performance.
+nim CI now runs this test with `testWithoutBoehm` to avoid running it with --gc:boehm.
+]#
+
+proc init(): string =
+  for a in 0..<10000000:
+    result.add 'c'
+
+proc f() =
+  var a {.global.} = init()
+  var b {.global.} = init()
+  var c {.global.} = init()
+
+  echo a.len
+    # `echo` intentional according to
+    # https://github.com/nim-lang/Nim/pull/17469/files/0c9e94cb6b9ebca9da7cb19a063fba7aa409748e#r600016573
+  echo b.len
+  echo c.len
+
+f()
diff --git a/tests/gc/tregionleak.nim b/tests/gc/tregionleak.nim
new file mode 100644
index 000000000..277cfc987
--- /dev/null
+++ b/tests/gc/tregionleak.nim
@@ -0,0 +1,23 @@
+discard """
+  cmd: '''nim c --gc:regions $file'''
+  output: '''
+finalized
+finalized
+'''
+"""
+
+proc finish(o: RootRef) =
+  echo "finalized"
+
+withScratchRegion:
+  var test: RootRef
+  new(test, finish)
+
+var
+  mr: MemRegion
+  test: RootRef
+
+withRegion(mr):
+  new(test, finish)
+
+deallocAll(mr)
diff --git a/tests/gc/tstandalone.nim b/tests/gc/tstandalone.nim
new file mode 100644
index 000000000..41dad9ba4
--- /dev/null
+++ b/tests/gc/tstandalone.nim
@@ -0,0 +1,14 @@
+discard """
+  matrix: "--os:standalone --gc:none"
+  exitcode: 1
+  output: "value out of range"
+"""
+
+type
+  rangeType = range[0..1]
+
+var
+  r: rangeType = 0
+  i = 2
+
+r = rangeType(i)
diff --git a/tests/generics/m14509.nim b/tests/generics/m14509.nim
new file mode 100644
index 000000000..cabc4f308
--- /dev/null
+++ b/tests/generics/m14509.nim
@@ -0,0 +1,16 @@
+import macros
+
+type float32x4 = array[4, float32]
+type float32x8 = array[8, float32]
+
+{.experimental: "dynamicBindSym".}
+macro dispatch(N: static int, T: type SomeNumber): untyped =
+  let BaseT = getTypeInst(T)[1]
+  result = bindSym($BaseT & "x" & $N)
+
+type
+  VecIntrin*[N: static int, T: SomeNumber] = dispatch(N, T)
+
+func `$`*[N, T](vec: VecIntrin[N, T]): string =
+  ## Display a vector
+  $cast[array[N, T]](vec)
diff --git a/tests/generics/m22373a.nim b/tests/generics/m22373a.nim
new file mode 100644
index 000000000..28e087ca6
--- /dev/null
+++ b/tests/generics/m22373a.nim
@@ -0,0 +1,7 @@
+# module a for t22373
+
+# original:
+type LightClientHeader* = object
+
+# simplified:
+type TypeOrTemplate* = object
diff --git a/tests/generics/m22373b.nim b/tests/generics/m22373b.nim
new file mode 100644
index 000000000..67ee4211b
--- /dev/null
+++ b/tests/generics/m22373b.nim
@@ -0,0 +1,18 @@
+# module b for t22373
+
+import m22373a
+
+# original:
+type
+  LightClientDataFork* {.pure.} = enum
+    None = 0,
+    Altair = 1
+template LightClientHeader*(kind: static LightClientDataFork): auto =
+  when kind == LightClientDataFork.Altair:
+    typedesc[m22373a.LightClientHeader]
+  else:
+    static: raiseAssert "Unreachable"
+
+# simplified:
+template TypeOrTemplate*(num: int): untyped =
+  typedesc[m22373a.TypeOrTemplate]
diff --git a/tests/generics/m3770.nim b/tests/generics/m3770.nim
new file mode 100644
index 000000000..7f5714a2b
--- /dev/null
+++ b/tests/generics/m3770.nim
@@ -0,0 +1,11 @@
+type
+  Noice* = object
+    hidden: int
+
+template jjj*: Noice =
+  Noice(hidden: 15)
+
+type Opt* = object
+  o: int
+
+template none*(O: type Opt): Opt = Opt(o: 0)
diff --git a/tests/generics/mdotlookup.nim b/tests/generics/mdotlookup.nim
index 2984574c2..090b97771 100644
--- a/tests/generics/mdotlookup.nim
+++ b/tests/generics/mdotlookup.nim
@@ -1,16 +1,28 @@
-proc baz(o: any): int = 5 # if bar is exported, it works
+proc baz(o: auto): int = 5 # if bar is exported, it works
 
 type MyObj = object
   x: int
 
-proc foo*(b: any) =
+proc foo*(b: auto) =
   var o: MyObj
   echo b.baz, " ", o.x.baz, " ", b.baz()
 
 import sets
 
-var intset = initSet[int]()
+var intset = initHashSet[int]()
 
 proc fn*[T](a: T) =
   if a in intset: echo("true")
   else: echo("false")
+
+import strutils
+
+proc doStrip*[T](a: T): string =
+  result = ($a).strip()
+
+type Foo = int32
+proc baz2*[T](y: int): auto =
+  result = y.Foo
+
+proc set*(x: var int, a, b: string) =
+  x = a.len + b.len
diff --git a/tests/friends/mfriends.nim b/tests/generics/mfriends.nim
index 19672289e..19672289e 100644
--- a/tests/friends/mfriends.nim
+++ b/tests/generics/mfriends.nim
diff --git a/tests/generics/module_with_generics.nim b/tests/generics/module_with_generics.nim
index e801a4790..960a694d7 100644
--- a/tests/generics/module_with_generics.nim
+++ b/tests/generics/module_with_generics.nim
@@ -1,5 +1,5 @@
 type
-  Base[T] = ref object {.inheritable.}
+  Base[T] {.inheritable.} = ref object
     value*: T
 
   Derived[T] = ref object of Base[T]
diff --git a/tests/generics/mopensymimport1.nim b/tests/generics/mopensymimport1.nim
new file mode 100644
index 000000000..912db1302
--- /dev/null
+++ b/tests/generics/mopensymimport1.nim
@@ -0,0 +1,34 @@
+type
+  Result*[T, E] = object
+    when T is void:
+      when E is void:
+        oResultPrivate*: bool
+      else:
+        case oResultPrivate*: bool
+        of false:
+          eResultPrivate*: E
+        of true:
+          discard
+    else:
+      when E is void:
+        case oResultPrivate*: bool
+        of false:
+          discard
+        of true:
+          vResultPrivate*: T
+      else:
+        case oResultPrivate*: bool
+        of false:
+          eResultPrivate*: E
+        of true:
+          vResultPrivate*: T
+
+template valueOr*[T: not void, E](self: Result[T, E], def: untyped): untyped =
+  let s = (self) # TODO avoid copy
+  case s.oResultPrivate
+  of true:
+    s.vResultPrivate
+  of false:
+    when E isnot void:
+      template error: untyped {.used, inject.} = s.eResultPrivate
+    def
diff --git a/tests/generics/mopensymimport2.nim b/tests/generics/mopensymimport2.nim
new file mode 100644
index 000000000..c17aafd00
--- /dev/null
+++ b/tests/generics/mopensymimport2.nim
@@ -0,0 +1,16 @@
+{.experimental: "openSym".}
+
+import mopensymimport1
+
+type Xxx = enum
+  error
+  value
+
+proc f(): Result[int, cstring] =
+  Result[int, cstring](oResultPrivate: false, eResultPrivate: "f")
+
+proc g*(T: type): string =
+  let x = f().valueOr:
+    return $error
+
+  "ok"
diff --git a/tests/generics/mtypenodes.nim b/tests/generics/mtypenodes.nim
new file mode 100644
index 000000000..e1132241b
--- /dev/null
+++ b/tests/generics/mtypenodes.nim
@@ -0,0 +1,6 @@
+# issue #22699
+
+type Private = distinct int
+
+proc chop*[T](x: int): int =
+  cast[int](cast[tuple[field: Private]](x))
diff --git a/tests/generics/muninstantiatedgenericcalls.nim b/tests/generics/muninstantiatedgenericcalls.nim
new file mode 100644
index 000000000..caed07c98
--- /dev/null
+++ b/tests/generics/muninstantiatedgenericcalls.nim
@@ -0,0 +1,26 @@
+import std/bitops
+
+const
+  lengths = block:
+    var v: array[64, int8]
+    for i in 0..<64:
+      v[i] = int8((i + 7) div 7)
+    v
+
+type
+  Leb128* = object
+
+{.push checks: off.}
+func len(T: type Leb128, x: SomeUnsignedInt): int8 =
+  if x == 0: 1
+  else: lengths[fastLog2(x)]
+{.pop.}
+
+# note private to test scoping issue:
+func maxLen(T: type Leb128, I: type): int8 =
+  Leb128.len(I.high)
+
+type
+  Leb128Buf*[T: SomeUnsignedInt] = object
+    data*: array[maxLen(Leb128, T), byte] 
+    len*: int8
diff --git a/tests/generics/t12938.nim b/tests/generics/t12938.nim
new file mode 100644
index 000000000..e09d65c7a
--- /dev/null
+++ b/tests/generics/t12938.nim
@@ -0,0 +1,9 @@
+type
+  ExampleArray[Size, T] = array[Size, T]
+
+var integerArray: ExampleArray[32, int]  # Compiler crash!
+doAssert integerArray.len == 32
+
+const Size = 2
+var integerArray2: ExampleArray[Size, int]
+doAssert integerArray2.len == 2
diff --git a/tests/generics/t13525.nim b/tests/generics/t13525.nim
new file mode 100644
index 000000000..1fd84852b
--- /dev/null
+++ b/tests/generics/t13525.nim
@@ -0,0 +1,6 @@
+# https://github.com/nim-lang/Nim/issues/13524
+template fun(field): untyped = astToStr(field)
+proc test1(): string = fun(nonexistent1)
+proc test2[T](): string = fun(nonexistent2) # used to cause: Error: undeclared identifier: 'nonexistent2'
+doAssert test1() == "nonexistent1"
+doAssert test2[int]() == "nonexistent2"
diff --git a/tests/generics/t14193.nim b/tests/generics/t14193.nim
new file mode 100644
index 000000000..213b1a8e6
--- /dev/null
+++ b/tests/generics/t14193.nim
@@ -0,0 +1,6 @@
+type
+  Task*[N: int] = object
+    env*: array[N, byte]
+
+var task14193: Task[20]
+doAssert task14193.env.len == 20
diff --git a/tests/generics/t14509.nim b/tests/generics/t14509.nim
new file mode 100644
index 000000000..ef3143ee4
--- /dev/null
+++ b/tests/generics/t14509.nim
@@ -0,0 +1,4 @@
+import m14509
+
+var v: VecIntrin[4, float32]
+doAssert $v == "[0.0, 0.0, 0.0, 0.0]"
diff --git a/tests/generics/t1500.nim b/tests/generics/t1500.nim
new file mode 100644
index 000000000..6dd457d33
--- /dev/null
+++ b/tests/generics/t1500.nim
@@ -0,0 +1,8 @@
+#issue 1500
+
+type
+  TFtpBase*[SockType] = object
+    job: TFTPJob[SockType]
+  PFtpBase*[SockType] = ref TFtpBase[SockType]
+  TFtpClient* = TFtpBase[string]
+  TFTPJob[T] = object
\ No newline at end of file
diff --git a/tests/generics/t17509.nim b/tests/generics/t17509.nim
new file mode 100644
index 000000000..89f507577
--- /dev/null
+++ b/tests/generics/t17509.nim
@@ -0,0 +1,25 @@
+type List[O] = object
+  next: ptr List[O]
+
+proc initList[O](l: ptr List[O]) =
+  l[].next = l
+
+type
+  PolytopeVertex[R] = object
+    list: List[PolytopeVertex[R]]
+
+  PolytopeEdge[R] = object
+    list: List[PolytopeEdge[R]]
+
+  Polytope[R] = object
+    vertices: List[PolytopeVertex[R]]
+    edges: List[PolytopeEdge[R]]
+
+var pt: Polytope[float]
+
+static:
+  doAssert pt.vertices.next is (ptr List[PolytopeVertex[float]])
+  doAssert pt.edges.next is (ptr List[PolytopeEdge[float]])
+
+initList(addr pt.vertices)
+initList(addr pt.edges)
\ No newline at end of file
diff --git a/tests/generics/t18823.nim b/tests/generics/t18823.nim
new file mode 100644
index 000000000..94c79aebe
--- /dev/null
+++ b/tests/generics/t18823.nim
@@ -0,0 +1,6 @@
+type BitsRange[T] = range[0..sizeof(T)*8-1]
+
+proc bar[T](a: T; b: BitsRange[T]) =
+  discard
+
+bar(1, 2.Natural)
diff --git a/tests/generics/t18859.nim b/tests/generics/t18859.nim
new file mode 100644
index 000000000..ca6c3d10b
--- /dev/null
+++ b/tests/generics/t18859.nim
@@ -0,0 +1,17 @@
+import macros
+
+macro symFromDesc(T: typedesc): untyped =
+  let typ = getType(T)
+  typ[1]
+
+template produceType(T: typedesc): untyped =
+  type
+    XT = object
+      x: symFromDesc(T)
+
+  XT
+
+type
+  X[T] = produceType(T)
+
+var x: X[int]
diff --git a/tests/generics/t19848.nim b/tests/generics/t19848.nim
new file mode 100644
index 000000000..f80f0e298
--- /dev/null
+++ b/tests/generics/t19848.nim
@@ -0,0 +1,16 @@
+discard """
+  output: '''
+todo
+'''
+"""
+
+type
+  Maybe[T] = object
+  List[T] = object
+
+proc dump[M: Maybe](a: List[M]) =
+  echo "todo"
+
+var a: List[Maybe[int]]
+  
+dump(a)
diff --git a/tests/generics/t20996.nim b/tests/generics/t20996.nim
new file mode 100644
index 000000000..8aa83c4e2
--- /dev/null
+++ b/tests/generics/t20996.nim
@@ -0,0 +1,15 @@
+discard """
+  action: compile
+"""
+
+import std/macros
+
+macro matchMe(x: typed): untyped =
+  discard x.getTypeImpl
+
+type
+  ElementRT = object
+  Element[Z] = ElementRT # this version is needed, even though we don't use it
+
+let ar = ElementRT()
+matchMe(ar)
diff --git a/tests/generics/t21742.nim b/tests/generics/t21742.nim
new file mode 100644
index 000000000..c49c8ee97
--- /dev/null
+++ b/tests/generics/t21742.nim
@@ -0,0 +1,10 @@
+type
+  Foo[T] = object
+    x:T
+  Bar[T,R] = Foo[T]
+  Baz = Bar[int,float]
+
+proc qux[T,R](x: Bar[T,R]) = discard
+
+var b:Baz
+b.qux()
\ No newline at end of file
diff --git a/tests/generics/t21760.nim b/tests/generics/t21760.nim
new file mode 100644
index 000000000..5343279bb
--- /dev/null
+++ b/tests/generics/t21760.nim
@@ -0,0 +1,8 @@
+import std/tables
+
+type Url = object
+
+proc myInit(_: type[Url], params = default(Table[string, string])): Url =
+  discard
+
+discard myInit(Url)
\ No newline at end of file
diff --git a/tests/generics/t21958.nim b/tests/generics/t21958.nim
new file mode 100644
index 000000000..f566b57cb
--- /dev/null
+++ b/tests/generics/t21958.nim
@@ -0,0 +1,11 @@
+discard """
+  action: compile
+"""
+
+type
+  Ct*[T: SomeUnsignedInt] = distinct T
+
+template `shr`*[T: Ct](x: T, y: SomeInteger): T = T(T.T(x) shr y)
+
+var x: Ct[uint64]
+let y {.used.} = x shr 2
\ No newline at end of file
diff --git a/tests/generics/t22373.nim b/tests/generics/t22373.nim
new file mode 100644
index 000000000..ecfaf0f1b
--- /dev/null
+++ b/tests/generics/t22373.nim
@@ -0,0 +1,16 @@
+# issue #22373
+
+import m22373a
+import m22373b
+
+# original:
+template lazy_header(name: untyped): untyped {.dirty.} =
+  var `name _ ptr`: ptr[data_fork.LightClientHeader]  # this data_fork.Foo part seems required to reproduce
+proc createLightClientUpdates(data_fork: static LightClientDataFork) =
+  lazy_header(attested_header)
+createLightClientUpdates(LightClientDataFork.Altair)
+
+# simplified:
+proc generic[T](abc: T) =
+  var x: abc.TypeOrTemplate
+generic(123)
diff --git a/tests/generics/t22826.nim b/tests/generics/t22826.nim
new file mode 100644
index 000000000..914d4243a
--- /dev/null
+++ b/tests/generics/t22826.nim
@@ -0,0 +1,8 @@
+import std/tables
+
+var a: Table[string, float]
+
+type Value*[T] = object
+  table: Table[string, Value[T]]
+
+discard toTable({"a": Value[float]()})
\ No newline at end of file
diff --git a/tests/generics/t23186.nim b/tests/generics/t23186.nim
new file mode 100644
index 000000000..76f38da6b
--- /dev/null
+++ b/tests/generics/t23186.nim
@@ -0,0 +1,155 @@
+# issue #23186
+
+block: # simplified
+  template typedTempl(x: int, body): untyped =
+    body
+  proc generic1[T]() =
+    discard
+  proc generic2[T]() =
+    typedTempl(1):
+      let x = generic1[T]
+  generic2[int]()
+
+import std/macros
+
+when not compiles(len((1, 2))):
+  import std/typetraits
+
+  func len(x: tuple): int =
+    arity(type(x))
+
+block: # full issue example
+  type FieldDescription = object
+    name: NimNode
+  func isTuple(t: NimNode): bool =
+    t.kind == nnkBracketExpr and t[0].kind == nnkSym and eqIdent(t[0], "tuple")
+  proc collectFieldsFromRecList(result: var seq[FieldDescription],
+                                n: NimNode,
+                                parentCaseField: NimNode = nil,
+                                parentCaseBranch: NimNode = nil,
+                                isDiscriminator = false) =
+    case n.kind
+    of nnkRecList:
+      for entry in n:
+        collectFieldsFromRecList result, entry,
+                                parentCaseField, parentCaseBranch
+    of nnkIdentDefs:
+      for i in 0 ..< n.len - 2:
+        var field: FieldDescription
+        field.name = n[i]
+        if field.name.kind == nnkPragmaExpr:
+          field.name = field.name[0]
+        if field.name.kind == nnkPostfix:
+          field.name = field.name[1]
+        result.add field
+    of nnkNilLit, nnkDiscardStmt, nnkCommentStmt, nnkEmpty:
+      discard
+    else:
+      doAssert false, "Unexpected nodes in recordFields:\n" & n.treeRepr
+  proc collectFieldsInHierarchy(result: var seq[FieldDescription],
+                                objectType: NimNode) =
+    var objectType = objectType
+    if objectType.kind == nnkRefTy:
+      objectType = objectType[0]
+    let recList = objectType[2]
+    collectFieldsFromRecList result, recList
+  proc recordFields(typeImpl: NimNode): seq[FieldDescription] =
+    let objectType = case typeImpl.kind
+      of nnkObjectTy: typeImpl
+      of nnkTypeDef: typeImpl[2]
+      else:
+        macros.error("object type expected", typeImpl)
+        return
+    collectFieldsInHierarchy(result, objectType)
+  proc skipPragma(n: NimNode): NimNode =
+    if n.kind == nnkPragmaExpr: n[0]
+    else: n
+  func declval(T: type): T =
+    doAssert false,
+      "declval should be used only in `typeof` expressions and concepts"
+    default(ptr T)[]
+  macro enumAllSerializedFieldsImpl(T: type, body: untyped): untyped =
+    var typeAst = getType(T)[1]
+    var typeImpl: NimNode
+    let isSymbol = not typeAst.isTuple
+    if not isSymbol:
+      typeImpl = typeAst
+    else:
+      typeImpl = getImpl(typeAst)
+    result = newStmtList()
+    var i = 0
+    for field in recordFields(typeImpl):
+      let
+        fieldIdent = field.name
+        realFieldName = newLit($fieldIdent.skipPragma)
+        fieldName = realFieldName
+        fieldIndex = newLit(i)
+      let fieldNameDefs =
+        if isSymbol:
+          quote:
+            const fieldName {.inject, used.} = `fieldName`
+            const realFieldName {.inject, used.} = `realFieldName`
+        else:
+          quote:
+            const fieldName {.inject, used.} = $`fieldIndex`
+            const realFieldName {.inject, used.} = $`fieldIndex`
+            # we can't access .Fieldn, so our helper knows
+            # to parseInt this
+      let field =
+        if isSymbol:
+          quote do: declval(`T`).`fieldIdent`
+        else:
+          quote do: declval(`T`)[`fieldIndex`]
+      result.add quote do:
+        block:
+          `fieldNameDefs`
+          type FieldType {.inject, used.} = type(`field`)
+          `body`
+      i += 1
+  template enumAllSerializedFields(T: type, body): untyped =
+    when T is ref|ptr:
+      type TT = type(default(T)[])
+      enumAllSerializedFieldsImpl(TT, body)
+    else:
+      enumAllSerializedFieldsImpl(T, body)
+  type
+    MemRange = object
+      startAddr: ptr byte
+      length: int
+    SszNavigator[T] = object
+      m: MemRange
+  func sszMount(data: openArray[byte], T: type): SszNavigator[T] =
+    let startAddr = unsafeAddr data[0]
+    SszNavigator[T](m: MemRange(startAddr: startAddr, length: data.len))
+  func sszMount(data: openArray[char], T: type): SszNavigator[T] =
+    let startAddr = cast[ptr byte](unsafeAddr data[0])
+    SszNavigator[T](m: MemRange(startAddr: startAddr, length: data.len))
+  template sszMount(data: MemRange, T: type): SszNavigator[T] =
+    SszNavigator[T](m: data)
+  func navigateToField[T](
+      n: SszNavigator[T],
+      FieldType: type): SszNavigator[FieldType] =
+    default(SszNavigator[FieldType])
+  type
+    FieldInfo = ref object
+      navigator: proc (m: MemRange): MemRange {.
+        gcsafe, noSideEffect, raises: [IOError] .}
+  func fieldNavigatorImpl[RecordType; FieldType; fieldName: static string](
+      m: MemRange): MemRange =
+    var typedNavigator = sszMount(m, RecordType)
+    discard navigateToField(typedNavigator, FieldType)
+    default(MemRange)
+  func genTypeInfo(T: type) =
+    when T is object:
+      enumAllSerializedFields(T):
+        discard FieldInfo(navigator: fieldNavigatorImpl[T, FieldType, fieldName])
+  type
+    Foo = object
+      bar: Bar
+    BarList = seq[uint64]
+    Bar = object
+      b: BarList
+      baz: Baz
+    Baz = object
+      i: uint64
+  genTypeInfo(Foo)
diff --git a/tests/generics/t23790.nim b/tests/generics/t23790.nim
new file mode 100644
index 000000000..9ac0df6a1
--- /dev/null
+++ b/tests/generics/t23790.nim
@@ -0,0 +1,14 @@
+# bug #23790
+
+discard compiles($default(seq[seq[ref int]]))
+discard compiles($default(seq[seq[ref uint]]))
+discard compiles($default(seq[seq[ref int8]]))
+discard compiles($default(seq[seq[ref uint8]]))
+discard compiles($default(seq[seq[ref int16]]))
+discard compiles($default(seq[seq[ref uint16]]))
+discard compiles($default(seq[seq[ref int32]]))
+discard compiles($default(seq[seq[ref uint32]]))
+discard compiles($default(seq[seq[ref int64]]))
+discard compiles($default(seq[seq[ref uint64]]))
+proc s(_: int | string) = discard
+s(0)
diff --git a/tests/generics/t23853.nim b/tests/generics/t23853.nim
new file mode 100644
index 000000000..bc9514a53
--- /dev/null
+++ b/tests/generics/t23853.nim
@@ -0,0 +1,91 @@
+# issue #23853
+
+block simplified:
+  type QuadraticExt[F] = object
+    coords: array[2, F]
+  template Name(E: type QuadraticExt): int = 123
+  template getBigInt(Name: static int): untyped = int
+  type Foo[GT] = object
+    a: getBigInt(GT.Name)
+  var x: Foo[QuadraticExt[int]]
+  
+import std/macros
+
+type
+  Algebra* = enum
+    BN254_Snarks
+    BLS12_381
+
+  Fp*[Name: static Algebra] = object
+    limbs*: array[4, uint64]
+
+  QuadraticExt*[F] = object
+    ## Quadratic Extension field
+    coords*: array[2, F]
+
+  CubicExt*[F] = object
+    ## Cubic Extension field
+    coords*: array[3, F]
+
+  ExtensionField*[F] = QuadraticExt[F] or CubicExt[F]
+
+  Fp2*[Name: static Algebra] =
+    QuadraticExt[Fp[Name]]
+
+  Fp4*[Name: static Algebra] =
+    QuadraticExt[Fp2[Name]]
+
+  Fp6*[Name: static Algebra] =
+    CubicExt[Fp2[Name]]
+
+  Fp12*[Name: static Algebra] =
+    CubicExt[Fp4[Name]]
+    # QuadraticExt[Fp6[Name]]
+
+template Name*(E: type ExtensionField): Algebra =
+  E.F.Name
+
+const BLS12_381_Order = [uint64 0x1, 0x2, 0x3, 0x4]
+const BLS12_381_Modulus = [uint64 0x5, 0x6, 0x7, 0x8]
+
+
+{.experimental: "dynamicBindSym".}
+
+macro baseFieldModulus*(Name: static Algebra): untyped =
+  result = bindSym($Name & "_Modulus")
+
+macro scalarFieldModulus*(Name: static Algebra): untyped =
+  result = bindSym($Name & "_Order")
+
+type FieldKind* = enum
+  kBaseField
+  kScalarField
+
+template getBigInt*(Name: static Algebra, kind: static FieldKind): untyped =
+  # Workaround:
+  # in `ptr UncheckedArray[BigInt[EC.getScalarField().bits()]]
+  # EC.getScalarField is not accepted by the compiler
+  #
+  # and `ptr UncheckedArray[BigInt[Fr[EC.F.Name].bits]]` gets undeclared field: 'Name'
+  #
+  # but `ptr UncheckedArray[getBigInt(EC.getName(), kScalarField)]` works fine
+  when kind == kBaseField:
+    Name.baseFieldModulus().typeof()
+  else:
+    Name.scalarFieldModulus().typeof()
+
+# ------------------------------------------------------------------------------
+
+type BenchMultiexpContext*[GT] = object
+  elems: seq[GT]
+  exponents: seq[getBigInt(GT.Name, kScalarField)]
+
+proc createBenchMultiExpContext*(GT: typedesc, inputSizes: openArray[int]): BenchMultiexpContext[GT] =
+  discard
+
+# ------------------------------------------------------------------------------
+
+proc main() =
+  let ctx = createBenchMultiExpContext(Fp12[BLS12_381], [2, 4, 8, 16])
+
+main()
diff --git a/tests/generics/t23854.nim b/tests/generics/t23854.nim
new file mode 100644
index 000000000..f1175c8b2
--- /dev/null
+++ b/tests/generics/t23854.nim
@@ -0,0 +1,71 @@
+# issue #23854, not entirely fixed
+
+import std/bitops
+
+const WordBitWidth = sizeof(pointer) * 8
+
+func wordsRequired*(bits: int): int {.inline.} =
+  const divShiftor = fastLog2(uint32(WordBitWidth))
+  result = (bits + WordBitWidth - 1) shr divShiftor
+
+type
+  Algebra* = enum
+    BLS12_381
+
+  BigInt*[bits: static int] = object
+    limbs*: array[wordsRequired(bits), uint]
+
+  Fr*[Name: static Algebra] = object
+    residue_form*: BigInt[255]
+
+  Fp*[Name: static Algebra] = object
+    residue_form*: BigInt[381]
+
+  FF*[Name: static Algebra] = Fp[Name] or Fr[Name]
+
+template getBigInt*[Name: static Algebra](T: type FF[Name]): untyped =
+  ## Get the underlying BigInt type.
+  typeof(default(T).residue_form)
+
+type
+  EC_ShortW_Aff*[F] = object
+    ## Elliptic curve point for a curve in Short Weierstrass form
+    ##   y² = x³ + a x + b
+    ##
+    ## over a field F
+    x*, y*: F
+
+type FieldKind* = enum
+  kBaseField
+  kScalarField
+
+func bits*[Name: static Algebra](T: type FF[Name]): static int =
+  T.getBigInt().bits
+
+template getScalarField*(EC: type EC_ShortW_Aff): untyped =
+  Fr[EC.F.Name]
+
+# ------------------------------------------------------------------------------
+
+type
+  ECFFT_Descriptor*[EC] = object
+    ## Metadata for FFT on Elliptic Curve
+    order*: int
+    rootsOfUnity1*: ptr UncheckedArray[BigInt[EC.getScalarField().bits()]]  # Error: in expression 'EC.getScalarField()': identifier expected, but found 'EC.getScalarField'
+    rootsOfUnity2*: ptr UncheckedArray[BigInt[getScalarField(EC).bits()]] # Compiler SIGSEGV: Illegal Storage Access
+
+func new*(T: type ECFFT_Descriptor): T =
+  discard
+
+# ------------------------------------------------------------------------------
+
+template getBits[bits: static int](x: ptr UncheckedArray[BigInt[bits]]): int = bits
+
+proc main() =
+  let ctx = ECFFT_Descriptor[EC_ShortW_Aff[Fp[BLS12_381]]].new()
+  doAssert getBits(ctx.rootsOfUnity1) == 255
+  doAssert getBits(ctx.rootsOfUnity2) == 255
+  doAssert ctx.rootsOfUnity1[0].limbs.len == wordsRequired(255)
+  doAssert ctx.rootsOfUnity2[0].limbs.len == wordsRequired(255)
+
+main()
diff --git a/tests/generics/t23855.nim b/tests/generics/t23855.nim
new file mode 100644
index 000000000..da8135a98
--- /dev/null
+++ b/tests/generics/t23855.nim
@@ -0,0 +1,61 @@
+# issue #23855, not entirely fixed
+
+import std/bitops
+
+const WordBitWidth = sizeof(pointer) * 8
+
+func wordsRequired*(bits: int): int {.inline.} =
+  const divShiftor = fastLog2(uint32(WordBitWidth))
+  result = (bits + WordBitWidth - 1) shr divShiftor
+
+type
+  Algebra* = enum
+    BLS12_381
+
+  BigInt*[bits: static int] = object
+    limbs*: array[wordsRequired(bits), uint]
+
+  Fr*[Name: static Algebra] = object
+    residue_form*: BigInt[255]
+
+  Fp*[Name: static Algebra] = object
+    residue_form*: BigInt[381]
+
+  FF*[Name: static Algebra] = Fp[Name] or Fr[Name]
+
+template getBigInt*[Name: static Algebra](T: type FF[Name]): untyped =
+  ## Get the underlying BigInt type.
+  typeof(default(T).residue_form)
+
+type
+  EC_ShortW_Aff*[F] = object
+    ## Elliptic curve point for a curve in Short Weierstrass form
+    ##   y² = x³ + a x + b
+    ##
+    ## over a field F
+    x*, y*: F
+
+func bits*[Name: static Algebra](T: type FF[Name]): static int =
+  T.getBigInt().bits
+
+# ------------------------------------------------------------------------------
+
+type
+  ECFFT_Descriptor*[EC] = object
+    ## Metadata for FFT on Elliptic Curve
+    order*: int
+    rootsOfUnity*: ptr UncheckedArray[BigInt[Fr[EC.F.Name].bits()]] # Undeclared identifier `Name`
+
+func new*(T: type ECFFT_Descriptor): T =
+  discard
+
+# ------------------------------------------------------------------------------
+
+template getBits[bits: static int](x: ptr UncheckedArray[BigInt[bits]]): int = bits
+
+proc main() =
+  let ctx = ECFFT_Descriptor[EC_ShortW_Aff[Fp[BLS12_381]]].new()
+  doAssert getBits(ctx.rootsOfUnity) == 255
+  doAssert ctx.rootsOfUnity[0].limbs.len == wordsRequired(255)
+
+main()
diff --git a/tests/generics/t3770.nim b/tests/generics/t3770.nim
new file mode 100644
index 000000000..ffccbeeb5
--- /dev/null
+++ b/tests/generics/t3770.nim
@@ -0,0 +1,13 @@
+# bug #3770
+import m3770
+
+doAssert $jjj() == "(hidden: 15)"  # works
+
+proc someGeneric(_: type) =
+  doAssert $jjj() == "(hidden: 15)" # fails: "Error: the field 'hidden' is not accessible."
+
+someGeneric(int)
+
+# bug #20900
+proc c(y: int | int, w: Opt = Opt.none) = discard
+c(0)
diff --git a/tests/generics/t4668.nim b/tests/generics/t4668.nim
new file mode 100644
index 000000000..bd44cc975
--- /dev/null
+++ b/tests/generics/t4668.nim
@@ -0,0 +1,166 @@
+discard """
+  output: '''
+foo1
+foo2
+'''
+"""
+
+block:
+  type
+    FooObj[T] = object
+      v: T
+    Foo1[T] = FooObj[T]
+    Foo2 = FooObj
+
+  proc foo1(x: Foo1) = echo "foo1"
+  proc foo2(x: Foo2) = echo "foo2"
+
+  var x: FooObj[float]
+  foo1(x)  # works
+  foo2(x)  # works
+
+block:
+  type
+    FooObj[T] = T
+    Foo1[T] = FooObj[T]
+    Foo2 = FooObj
+    Foo3 = Foo1
+    Foo4x = FooObj[SomeInteger]
+    Foo4 = FooObj[SomeFloat]
+    Foo5x = Foo1[SomeInteger]
+    Foo5 = Foo1[SomeFloat]
+
+  proc foo0(x: FooObj): int = 0
+  proc foo1(x: Foo1): int = 1
+  proc foo2(x: Foo2): int = 2
+  proc foo3(x: Foo3): int = 3
+  proc foo4(x: Foo4x): int = 40
+  proc foo4(x: Foo4): int = 4
+  proc foo5(x: Foo5x): int = 50
+  proc foo5(x: Foo5): int = 5
+
+  block:
+    var x: FooObj[float]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+
+  block:
+    var x: Foo1[float]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+
+  block:
+    var x: Foo2[float]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+
+block:
+  type
+    FooObj[T,U] = object
+      x: T
+      y: U
+    Foo1[U,T] = FooObj[T,U]
+    Foo2 = FooObj
+    Foo3 = Foo1
+    Foo4x = FooObj[SomeInteger,SomeInteger]
+    Foo4y = FooObj[SomeInteger,SomeFloat]
+    Foo4z = FooObj[SomeFloat,SomeFloat]
+    Foo4 = FooObj[SomeFloat,SomeInteger]
+    Foo5x = Foo1[SomeInteger,SomeInteger]
+    Foo5y = Foo1[SomeFloat,SomeInteger]
+    Foo5z = Foo1[SomeFloat,SomeFloat]
+    Foo5 = Foo1[SomeInteger,SomeFloat]
+
+  proc foo0(x: FooObj): int = 0
+  proc foo1(x: Foo1): int = 1
+  proc foo2(x: Foo2): int = 2
+  proc foo3(x: Foo3): int = 3
+  proc foo4(x: Foo4x): int = 40
+  proc foo4(x: Foo4y): int = 41
+  proc foo4(x: Foo4z): int = 42
+  proc foo4(x: Foo4): int = 4
+  proc foo5(x: Foo5x): int = 50
+  proc foo5(x: Foo5y): int = 51
+  proc foo5(x: Foo5z): int = 52
+  proc foo5(x: Foo5): int = 5
+
+  block:
+    var x: FooObj[float,int]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+
+  block:
+    var x: Foo1[int,float]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+
+block:
+  type
+    FooObj[T] = object of RootObj
+      v: T
+    FooObj2[T] = object of FooObj[T]
+    Foo1[T] = FooObj[T]
+    Foo2 = FooObj
+    Foo3 = Foo1
+    Foo4x = FooObj[SomeInteger]
+    Foo4 = FooObj[SomeFloat]
+    Foo5x = Foo1[SomeInteger]
+    Foo5 = Foo1[SomeFloat]
+
+  proc foo0(x: FooObj): int = 0
+  proc foo1(x: Foo1): int = 1
+  proc foo2(x: Foo2): int = 2
+  proc foo3(x: Foo3): int = 3
+  proc foo4(x: Foo4x): int = 40
+  proc foo4(x: Foo4): int = 4
+  proc foo5(x: Foo5x): int = 50
+  proc foo5(x: Foo5): int = 5
+
+  block:
+    var x: FooObj[float]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+
+  block:
+    var x: Foo1[float]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+
+  #[ XXX These still fail
+  block:
+    var x: FooObj2[float]
+    doAssert(foo0(x) == 0)
+    doAssert(foo1(x) == 1)
+    doAssert(foo2(x) == 2)
+    doAssert(foo3(x) == 3)
+    doAssert(foo4(x) == 4)
+    doAssert(foo5(x) == 5)
+  ]#
diff --git a/tests/generics/t500.nim b/tests/generics/t500.nim
new file mode 100644
index 000000000..2486359aa
--- /dev/null
+++ b/tests/generics/t500.nim
@@ -0,0 +1,8 @@
+discard """
+action: compile
+"""
+
+type
+  TTest = tuple[x: range[0..80], y: range[0..25]]
+
+let x: TTest = (2, 23)
diff --git a/tests/generics/t5926.nim b/tests/generics/t5926.nim
new file mode 100644
index 000000000..bb14c3af5
--- /dev/null
+++ b/tests/generics/t5926.nim
@@ -0,0 +1,22 @@
+discard """
+action: compile
+"""
+
+type
+  SomeObj[T] = object
+
+template useSomeObj[T]() =
+  var retObj: SomeObj[T]
+
+useSomeObj[void]()
+useSomeObj[int]()
+
+
+type
+  Data*[T] = object
+    x: T
+
+template test*[T](xxx: T) =
+  let data = Data[T](x: xxx)
+
+test(1)
diff --git a/tests/generics/t6060.nim b/tests/generics/t6060.nim
new file mode 100644
index 000000000..6b1856f1c
--- /dev/null
+++ b/tests/generics/t6060.nim
@@ -0,0 +1,11 @@
+import tables
+
+type MyTab[A,B] = distinct TableRef[A,B]
+
+proc `$`[A,B](t: MyTab[A,B]): string =
+  "My special table " & $TableRef[A,B](t)
+
+proc create[A,B](): MyTab[A,B] = MyTab(newTable[A,B]())
+
+var a = create[int,int]()
+doAssert $a == "My special table {:}"
diff --git a/tests/generics/t6137.nim b/tests/generics/t6137.nim
index abf02a756..fb7db22f8 100644
--- a/tests/generics/t6137.nim
+++ b/tests/generics/t6137.nim
@@ -1,6 +1,6 @@
 discard """
-  errormsg: "\'vectFunc\' doesn't have a concrete type, due to unspecified generic parameters."
-  line: 28
+  errormsg: "cannot instantiate: 'T'"
+  line: 19
 """
 
 type
@@ -16,7 +16,7 @@ let
   # define a vector of length 3
   x: vector[3] = [1.0, 3.0, 5.0]
 
-proc vectFunc[T](x: vector[T]): vector[T] {.procvar.} =
+proc vectFunc[T](x: vector[T]): vector[T] =
   # Define a vector function
   result = 2.0*x
 
diff --git a/tests/generics/t6637.nim b/tests/generics/t6637.nim
new file mode 100644
index 000000000..dd4f339a2
--- /dev/null
+++ b/tests/generics/t6637.nim
@@ -0,0 +1,9 @@
+
+type
+  Grid2D*[I: SomeInteger, w, h: static[I], T] = object
+    grid: array[w, array[h, T]]
+  Grid2DIns = Grid2D[int, 2, 3, uint8]
+
+let a = Grid2DIns()
+doAssert a.grid.len == 2
+doAssert a.grid[0].len == 3
diff --git a/tests/generics/t7446.nim b/tests/generics/t7446.nim
new file mode 100644
index 000000000..71aa8f0e8
--- /dev/null
+++ b/tests/generics/t7446.nim
@@ -0,0 +1,10 @@
+proc foo(x: Natural or SomeUnsignedInt):int = 
+  when x is int:
+    result = 1
+  else:
+    result = 2
+let a = 10
+doAssert foo(a) == 1
+
+let b = 10'u8
+doAssert foo(b) == 2
\ No newline at end of file
diff --git a/tests/generics/t7839.nim b/tests/generics/t7839.nim
new file mode 100644
index 000000000..4d17b438b
--- /dev/null
+++ b/tests/generics/t7839.nim
@@ -0,0 +1,9 @@
+type A[I: SomeOrdinal, E] = tuple # same for object
+  length: int
+
+doAssert A.sizeof == sizeof(int) # works without the following proc
+
+proc newA*[I: SomeOrdinal, E](): A[I, E] = # works without `SomeOrdinal`
+  discard
+
+discard newA[uint8, int]()
diff --git a/tests/generics/taliashijack.nim b/tests/generics/taliashijack.nim
new file mode 100644
index 000000000..fdebadded
--- /dev/null
+++ b/tests/generics/taliashijack.nim
@@ -0,0 +1,8 @@
+# issue #23977
+
+type Foo[T] = int
+
+proc foo(T: typedesc) =
+  var a: T
+
+foo(int)
diff --git a/tests/generics/tarc_misc.nim b/tests/generics/tarc_misc.nim
new file mode 100644
index 000000000..3e7762556
--- /dev/null
+++ b/tests/generics/tarc_misc.nim
@@ -0,0 +1,21 @@
+discard """
+  output: ''''''
+  cmd: "nim c --gc:arc $file"
+"""
+
+# bug #13519
+
+var unrelated: seq[proc() {.closure, gcsafe.}]
+
+unrelated.add proc () =
+  echo "gcsafe"
+
+import tables, sequtils
+let t = newTable[int, proc()]()
+
+type
+  MyProc = proc() {.closure.}
+
+var result: seq[MyProc] = @[]
+for x in t.values:
+  result.add(x)
diff --git a/tests/generics/tbadcache.nim b/tests/generics/tbadcache.nim
new file mode 100644
index 000000000..33e65be3a
--- /dev/null
+++ b/tests/generics/tbadcache.nim
@@ -0,0 +1,26 @@
+# issue #16128
+
+import std/[tables, hashes]
+
+type
+  NodeId*[L] = object
+    isSource: bool
+    index: Table[NodeId[L], seq[NodeId[L]]]
+
+func hash*[L](id: NodeId[L]): Hash = discard
+func `==`[L](a, b: NodeId[L]): bool = discard
+
+proc makeIndex*[T, L](tree: T) =
+  var parent = NodeId[L]()
+  var tmp: Table[NodeId[L], seq[NodeId[L]]]
+  tmp[parent] = @[parent]
+
+proc simpleTreeDiff*[T, L](source, target: T) =
+  # Swapping these two lines makes error disappear
+  var m: Table[NodeId[L], NodeId[L]]
+  makeIndex[T, L](target)
+
+var tmp: Table[string, seq[string]] # removing this forward declaration also removes error
+
+proc diff(x1, x2: string): auto =
+  simpleTreeDiff[int, string](12, 12)
diff --git a/tests/generics/tbaddeprecated.nim b/tests/generics/tbaddeprecated.nim
new file mode 100644
index 000000000..335234a25
--- /dev/null
+++ b/tests/generics/tbaddeprecated.nim
@@ -0,0 +1,55 @@
+discard """
+  output: '''
+not deprecated
+not deprecated
+not error
+not error
+'''
+"""
+
+# issue #21724
+
+block: # deprecated
+  {.push warningAsError[Deprecated]: on.}
+  type
+    SomeObj = object
+      hey: bool
+  proc hey() {.deprecated: "Shouldn't use this".} = echo "hey"
+  proc gen(o: auto) =
+    doAssert not compiles(o.hey())
+    if o.hey:
+      echo "not deprecated"
+  gen(SomeObj(hey: true))
+  doAssert not (compiles do:
+    proc hey(o: SomeObj) {.deprecated: "Shouldn't use this".} = echo "hey"
+    proc gen2(o: auto) =
+      if o.hey():
+        echo "not deprecated"
+    gen2(SomeObj(hey: true)))
+  proc hey(o: SomeObj) {.deprecated: "Shouldn't use this".} = echo "hey"
+  proc gen3(o: auto) =
+    if o.hey:
+      echo "not deprecated"
+  gen3(SomeObj(hey: true))
+  {.pop.}
+block: # error
+  type
+    SomeObj = object
+      hey: bool
+  proc hey() {.error: "Shouldn't use this".} = echo "hey"
+  proc gen(o: auto) =
+    doAssert not compiles(o.hey())
+    if o.hey:
+      echo "not error"
+  gen(SomeObj(hey: true))
+  doAssert not (compiles do:
+    proc hey(o: SomeObj) {.error: "Shouldn't use this".} = echo "hey"
+    proc gen2(o: auto) =
+      if o.hey():
+        echo "not error"
+    gen2(SomeObj(hey: true)))
+  proc hey(o: SomeObj) {.error: "Shouldn't use this".} = echo "hey"
+  proc gen3(o: auto) =
+    if o.hey:
+      echo "not error"
+  gen3(SomeObj(hey: true))
diff --git a/tests/generics/tbintree.nim b/tests/generics/tbintree.nim
index a1a13c7b5..83f14406b 100644
--- a/tests/generics/tbintree.nim
+++ b/tests/generics/tbintree.nim
@@ -55,8 +55,8 @@ proc find*[Ty2](b: PBinaryTree[Ty2], data: Ty2): bool =
 
 iterator preorder*[T](root: PBinaryTree[T]): T =
   # Preorder traversal of a binary tree.
-  # Since recursive iterators are not yet implemented,
-  # this uses an explicit stack:
+  # This uses an explicit stack (which is more efficient than
+  # a recursive iterator factory).
   var stack: seq[PBinaryTree[T]] = @[root]
   while stack.len > 0:
     var n = stack.pop()
diff --git a/tests/generics/tbracketinstantiation.nim b/tests/generics/tbracketinstantiation.nim
new file mode 100644
index 000000000..22a86af4c
--- /dev/null
+++ b/tests/generics/tbracketinstantiation.nim
@@ -0,0 +1,86 @@
+discard """
+  nimout: '''
+type
+  Bob = object
+type
+  Another = object
+'''
+"""
+
+block: # issue #22645
+  type
+    Opt[T] = object
+    FutureBase = ref object of RootObj
+    Future[T] = ref object of FutureBase ## Typed future.
+      internalValue: T ## Stored value
+  template err[T](E: type Opt[T]): E = E()
+  proc works(): Future[Opt[int]] {.stackTrace: off, gcsafe, raises: [].} =
+    var chronosInternalRetFuture: FutureBase
+    template result(): untyped {.used.} =
+      Future[Opt[int]](chronosInternalRetFuture).internalValue
+    result = err(type(result))
+  proc breaks(): Future[Opt[int]] {.stackTrace: off, gcsafe, raises: [].} =
+    var chronosInternalRetFuture: FutureBase
+    template result(): untyped {.used.} =
+      cast[Future[Opt[int]]](chronosInternalRetFuture).internalValue
+    result = err(type(result))
+
+import macros
+
+block: # issue #16118
+  macro thing(name: static[string]) =
+    result = newStmtList(
+      nnkTypeSection.newTree(
+        nnkTypeDef.newTree(
+          ident(name),
+          newEmptyNode(),
+          nnkObjectTy.newTree(
+            newEmptyNode(),
+            newEmptyNode(),
+            nnkRecList.newTree()))))
+  template foo(name: string): untyped =
+    thing(name)
+  expandMacros:
+    foo("Bob")
+  block:
+    expandMacros:
+      foo("Another")
+
+block: # issue #19670
+  type
+    Past[Z] = object
+    OpenObject = object
+
+  macro rewriter(prc: untyped): untyped =
+    prc.body.add(nnkCall.newTree(
+      prc.params[0]
+    ))
+    prc
+    
+  macro macroAsync(name, restype: untyped): untyped =
+    quote do:
+      proc `name`(): Past[seq[`restype`]] {.rewriter.} = discard
+      
+  macroAsync(testMacro, OpenObject)
+
+import asyncdispatch
+
+block: # issue #11838 long
+  type
+    R[P] = object
+      updates: seq[P]
+    D[T, P] = ref object
+      ps: seq[P]
+      t: T
+  proc newD[T, P](ps: seq[P], t: T): D[T, P] =
+    D[T, P](ps: ps, t: t)
+  proc loop[T, P](d: D[T, P]) =
+    var results = newSeq[Future[R[P]]](10)
+  let d = newD[string, int](@[1], "")
+  d.loop()
+
+block: # issue #11838 minimal
+  type R[T] = object
+  proc loop[T]() =
+    discard newSeq[R[R[T]]]()
+  loop[int]()
diff --git a/tests/generics/tcalltype.nim b/tests/generics/tcalltype.nim
new file mode 100644
index 000000000..cba691f77
--- /dev/null
+++ b/tests/generics/tcalltype.nim
@@ -0,0 +1,26 @@
+discard """
+  joinable: false # breaks everything because of #23977
+"""
+
+# issue #23406
+
+template helper(_: untyped): untyped =
+  int
+
+type # Each of them should always be `int`.
+  GenA[T] = helper int
+  GenB[T] = helper(int)
+  GenC[T] = helper helper(int)
+
+block:
+  template helper(_: untyped): untyped =
+    float
+
+  type
+    A = GenA[int]
+    B = GenB[int]
+    C = GenC[int]
+
+  assert A is int # OK.
+  assert B is int # Fails; it is `float`!
+  assert C is int # OK.
diff --git a/tests/generics/tcan.nim b/tests/generics/tcan.nim
index eea69cdb7..bbefa7233 100644
--- a/tests/generics/tcan.nim
+++ b/tests/generics/tcan.nim
@@ -31,7 +31,7 @@ block tinherit:
 
 block tspecialise:
   type
-    TGen[T] = object {.inheritable.}
+    TGen[T] {.inheritable.} = object
     TSpef = object of TGen[string]
 
 
diff --git a/tests/constraints/tconstraints.nim b/tests/generics/tconstraints.nim
index 3ca01cfd5..3ca01cfd5 100644
--- a/tests/constraints/tconstraints.nim
+++ b/tests/generics/tconstraints.nim
diff --git a/tests/generics/texplicitgeneric2.nim b/tests/generics/texplicitgeneric2.nim
index 573b10ae8..37b133130 100644
--- a/tests/generics/texplicitgeneric2.nim
+++ b/tests/generics/texplicitgeneric2.nim
@@ -1,6 +1,5 @@
 discard """
   output: "Key: 12 value: 12Key: 13 value: 13 Key: A value: 12 Key: B value: 13"
-  disabled: true
 """
 
 # test explicit type instantiation
@@ -14,12 +13,12 @@ proc newDict*[TKey, TValue](): PDict[TKey, TValue] =
   new(result)
   result.data = @[]
 
-proc add*(d: PDict, k: TKey, v: TValue) =
+proc add*(d: PDict, k: d.TKey, v: d.TValue) =
   d.data.add((k, v))
 
 
-#iterator items*(d: PDict): tuple[k: TKey, v: TValue] =
-#  for k, v in items(d.data): yield (k, v)
+iterator items*(d: PDict): tuple[k: d.TKey, v: d.TValue] =
+  for k, v in items(d.data): yield (k, v)
 
 var d = newDict[int, string]()
 d.add(12, "12")
diff --git a/tests/friends/tfriends.nim b/tests/generics/tfriends.nim
index 1e70d50a5..1e70d50a5 100644
--- a/tests/friends/tfriends.nim
+++ b/tests/generics/tfriends.nim
diff --git a/tests/generics/tgeneric0.nim b/tests/generics/tgeneric0.nim
index ca012734b..16a148f7b 100644
--- a/tests/generics/tgeneric0.nim
+++ b/tests/generics/tgeneric0.nim
@@ -4,11 +4,12 @@ discard """
 0
 float32
 float32
+(name: "Resource 1", readers: ..., writers: ...)
 '''
 """
 
 
-import tables
+import std/tables
 
 
 block tgeneric0:
@@ -124,3 +125,72 @@ block tgeneric5:
     echo T
 
   bar(0.0'f32)
+
+# bug #13378
+
+type
+  Resource = ref object of RootObj
+    name: string
+    readers, writers: seq[RenderTask]
+
+  RenderTask = ref object
+    name: string
+
+var res = Resource(name: "Resource 1")
+
+(proc (r: typeof(res)) =
+   echo r[])(res)
+
+# bug #4061
+
+type List[T] = object
+  e: T
+  n: ptr List[T]
+
+proc zip*[T,U](xs: List[T], ys: List[U]): List[(T,U)] = discard
+
+proc unzip*[T,U](xs: List[tuple[t: T, u: U]]): (List[T], List[U]) = discard
+
+proc unzip2*[T,U](xs: List[(T,U)]): (List[T], List[U]) = discard
+
+type
+  AtomicType = pointer|ptr|int
+
+  Atomic[T: AtomicType] = distinct T
+
+  Block[T: AtomicType] = object
+
+  AtomicContainer[T: AtomicType] = object
+    b: Atomic[ptr Block[T]]
+
+# bug #8295
+var x = AtomicContainer[int]()
+doAssert (ptr Block[int])(x.b) == nil
+
+
+# bug #23233
+type
+  JsonObjectType*[T: string or uint64] = Table[string, JsonValueRef[T]]
+
+  JsonValueRef*[T: string or uint64] = object
+    objVal*: JsonObjectType[T]
+
+proc scanValue[K](val: var K) =
+  var map: JsonObjectType[K.T]
+  var newVal: K
+  map["one"] = newVal
+
+block:
+  var a: JsonValueRef[uint64]
+  scanValue(a)
+
+  var b: JsonValueRef[string]
+  scanValue(b)
+
+block: # bug #21347
+  type K[T] = object
+  template s[T]() = discard
+  proc b1(n: bool | bool) = s[K[K[int]]]()
+  proc b2(n: bool) =        s[K[K[int]]]()
+  b1(false)   # Error: 's' has unspecified generic parameters
+  b2(false)   # Builds, on its own
diff --git a/tests/generics/tgeneric3.nim b/tests/generics/tgeneric3.nim
index 4cb12f91b..29a73afc6 100644
--- a/tests/generics/tgeneric3.nim
+++ b/tests/generics/tgeneric3.nim
@@ -1,9 +1,9 @@
 discard """
 output: '''
 312
-1000000
-1000000
-500000
+1000
+1000
+500
 0
 '''
 """
@@ -12,7 +12,7 @@ import strutils
 
 type
   PNode[T,D] = ref TNode[T,D]
-  TItem {.acyclic, pure, final, shallow.} [T,D] = object
+  TItem[T,D] {.acyclic, pure, final, shallow.} = object
         key: T
         value: D
         node: PNode[T,D]
@@ -20,7 +20,7 @@ type
           val_set: bool
 
   TItems[T,D] = seq[ref TItem[T,D]]
-  TNode {.acyclic, pure, final, shallow.} [T,D] = object
+  TNode[T,D] {.acyclic, pure, final, shallow.} = object
         slots: TItems[T,D]
         left: PNode[T,D]
         count: int32
@@ -243,7 +243,7 @@ proc InsertItem[T,D](APath: RPath[T,D], ANode:PNode[T,D], Akey: T, Avalue: D) =
   of cLenCenter: setLen(APath.Nd.slots, cLen4)
   of cLen4: setLen(APath.Nd.slots, cLenMax)
   else: discard
-  for i in countdown(APath.Nd.count.int - 1, x + 1): shallowCopy(APath.Nd.slots[i], APath.Nd.slots[i - 1])
+  for i in countdown(APath.Nd.count.int - 1, x + 1): APath.Nd.slots[i] = move APath.Nd.slots[i - 1]
   APath.Nd.slots[x] = setItem(Akey, Avalue, ANode)
 
 
@@ -255,31 +255,39 @@ proc SplitPage[T,D](n, left: PNode[T,D], xi: int, Akey:var T, Avalue:var D): PNo
   result.slots.newSeq(cLenCenter)
   result.count = cCenter
   if x == cCenter:
-    for i in 0..cCenter-1: shallowCopy(it1[i], left.slots[i])
-    for i in 0..cCenter-1: shallowCopy(result.slots[i], left.slots[cCenter + i])
+    for i in 0..cCenter-1: 
+      it1[i] = move left.slots[i]
+    for i in 0..cCenter-1:
+      result.slots[i] = move left.slots[cCenter + i]
     result.left = n
   else :
     if x < cCenter :
-      for i in 0..x-1: shallowCopy(it1[i], left.slots[i])
+      for i in 0..x-1:
+        it1[i] = move left.slots[i]
       it1[x] = setItem(Akey, Avalue, n)
-      for i in x+1 .. cCenter-1: shallowCopy(it1[i], left.slots[i-1])
+      for i in x+1 .. cCenter-1:
+        it1[i] = move left.slots[i-1]
       var w = left.slots[cCenter-1]
       Akey = w.key
       Avalue = w.value
       result.left = w.node
-      for i in 0..cCenter-1: shallowCopy(result.slots[i], left.slots[cCenter + i])
+      for i in 0..cCenter-1:
+        result.slots[i] = move left.slots[cCenter + i]
     else :
-      for i in 0..cCenter-1: shallowCopy(it1[i], left.slots[i])
+      for i in 0..cCenter-1:
+        it1[i] = move left.slots[i]
       x = x - (cCenter + 1)
-      for i in 0..x-1: shallowCopy(result.slots[i], left.slots[cCenter + i + 1])
+      for i in 0..x-1:
+        result.slots[i] = move left.slots[cCenter + i + 1]
       result.slots[x] = setItem(Akey, Avalue, n)
-      for i in x+1 .. cCenter-1: shallowCopy(result.slots[i], left.slots[cCenter + i])
+      for i in x+1 .. cCenter-1:
+        result.slots[i] = move left.slots[cCenter + i]
       var w = left.slots[cCenter]
       Akey = w.key
       Avalue = w.value
       result.left = w.node
   left.count = cCenter
-  shallowCopy(left.slots, it1)
+  left.slots = move it1
 
 
 proc internalPut[T,D](ANode: ref TNode[T,D], Akey: T, Avalue: D, Oldvalue: var D): ref TNode[T,D] =
@@ -437,7 +445,7 @@ proc test() =
   var it1 = internalFind(root, 312)
   echo it1.value
 
-  for i in 1..1_000_000:
+  for i in 1..1_000:
     root = internalPut(root, i, i, oldvalue)
 
   var cnt = 0
diff --git a/tests/generics/tgeneric_recursionlimit.nim b/tests/generics/tgeneric_recursionlimit.nim
new file mode 100644
index 000000000..5fe9b43c6
--- /dev/null
+++ b/tests/generics/tgeneric_recursionlimit.nim
@@ -0,0 +1,123 @@
+discard """
+  action: "compile"
+"""
+
+# https://github.com/nim-lang/Nim/issues/20348
+
+type
+  Payload[T] = object
+    payload: T
+  Carrier[T] = object
+    val: T
+
+type
+  Payload0*[T] = object
+    payload: Payload[T]
+  Payload1*[T] = object
+    payload: Payload[T]
+  Payload2*[T] = object
+    payload: Payload[T]
+  Payload3*[T] = object
+    payload: Payload[T]
+  Payload4*[T] = object
+    payload: Payload[T]
+  Payload5*[T] = object
+    payload: Payload[T]
+  Payload6*[T] = object
+    payload: Payload[T]
+  Payload7*[T] = object
+    payload: Payload[T]
+  Payload8*[T] = object
+    payload: Payload[T]
+  Payload9*[T] = object
+    payload: Payload[T]
+  Payload10*[T] = object
+    payload: Payload[T]
+  Payload11*[T] = object
+    payload: Payload[T]
+  Payload12*[T] = object
+    payload: Payload[T]
+  Payload13*[T] = object
+    payload: Payload[T]
+  Payload14*[T] = object
+    payload: Payload[T]
+  Payload15*[T] = object
+    payload: Payload[T]
+  Payload16*[T] = object
+    payload: Payload[T]
+  Payload17*[T] = object
+    payload: Payload[T]
+  Payload18*[T] = object
+    payload: Payload[T]
+  Payload19*[T] = object
+    payload: Payload[T]
+  Payload20*[T] = object
+    payload: Payload[T]
+  Payload21*[T] = object
+    payload: Payload[T]
+  Payload22*[T] = object
+    payload: Payload[T]
+  Payload23*[T] = object
+    payload: Payload[T]
+  Payload24*[T] = object
+    payload: Payload[T]
+  Payload25*[T] = object
+    payload: Payload[T]
+  Payload26*[T] = object
+    payload: Payload[T]
+  Payload27*[T] = object
+    payload: Payload[T]
+  Payload28*[T] = object
+    payload: Payload[T]
+  Payload29*[T] = object
+    payload: Payload[T]
+  Payload30*[T] = object
+    payload: Payload[T]
+  Payload31*[T] = object
+    payload: Payload[T]
+  Payload32*[T] = object
+    payload: Payload[T]
+  Payload33*[T] = object
+    payload: Payload[T]
+
+type
+  Carriers*[T] = object
+    c0*: Carrier[Payload0[T]]
+    c1*: Carrier[Payload1[T]]
+    c2*: Carrier[Payload2[T]]
+    c3*: Carrier[Payload3[T]]
+    c4*: Carrier[Payload4[T]]
+    c5*: Carrier[Payload5[T]]
+    c6*: Carrier[Payload6[T]]
+    c7*: Carrier[Payload7[T]]
+    c8*: Carrier[Payload8[T]]
+    c9*: Carrier[Payload9[T]]
+    c10*: Carrier[Payload10[T]]
+    c11*: Carrier[Payload11[T]]
+    c12*: Carrier[Payload12[T]]
+    c13*: Carrier[Payload13[T]]
+    c14*: Carrier[Payload14[T]]
+    c15*: Carrier[Payload15[T]]
+    c16*: Carrier[Payload16[T]]
+    c17*: Carrier[Payload17[T]]
+    c18*: Carrier[Payload18[T]]
+    c19*: Carrier[Payload19[T]]
+    c20*: Carrier[Payload20[T]]
+    c21*: Carrier[Payload21[T]]
+    c22*: Carrier[Payload22[T]]
+    c23*: Carrier[Payload23[T]]
+    c24*: Carrier[Payload24[T]]
+    c25*: Carrier[Payload25[T]]
+    c26*: Carrier[Payload26[T]]
+    c27*: Carrier[Payload27[T]]
+    c28*: Carrier[Payload28[T]]
+    c29*: Carrier[Payload29[T]]
+    c30*: Carrier[Payload30[T]]
+    c31*: Carrier[Payload31[T]]
+    c32*: Carrier[Payload32[T]]
+    c33*: Carrier[Payload33[T]]
+
+var carriers : Carriers[int]
+
+static:
+  assert $(typeof(carriers.c33.val)) == "Payload33[system.int]"
diff --git a/tests/generics/tgenerics_issues.nim b/tests/generics/tgenerics_issues.nim
index af71a8938..3068a22f2 100644
--- a/tests/generics/tgenerics_issues.nim
+++ b/tests/generics/tgenerics_issues.nim
@@ -23,6 +23,10 @@ concrete 88
 G:0,1:0.1
 G:0,1:0.1
 H:1:0.1
+0
+(foo: none(seq[Foo]), s: "")
+(foo: some(@[(a: "world", bar: none(Bar))]), s: "hello,")
+@[(a: "hey", bar: none(Bar))]
 '''
 joinable: false
 """
@@ -51,8 +55,8 @@ block t88:
 
   let c = ChildClass[string].new("Base", "Child")
 
-  assert c.baseMethod == "Base"
-  assert c.overriddenMethod == "Child"
+  doAssert c.baseMethod == "Base"
+  doAssert c.overriddenMethod == "Child"
 
 
 
@@ -124,7 +128,7 @@ block t1789:
       bar: array[N, T]
 
   proc `[]`[N, T](f: Bar[N, T], n: range[0..(N - 1)]): T =
-    assert high(n) == N-1
+    doAssert high(n) == N-1
     result = f.bar[n]
 
   var b: Bar[3, int]
@@ -599,7 +603,7 @@ block t7854:
 
 
 block t5864:
-  proc defaultStatic(s: openarray, N: static[int] = 1): int = N
+  proc defaultStatic(s: openArray, N: static[int] = 1): int = N
   proc defaultGeneric[T](a: T = 2): int = a
 
   let a = [1, 2, 3, 4].defaultStatic()
@@ -730,7 +734,7 @@ block t1684:
   proc newDerived(idx: int): DerivedType {.inline.} = DerivedType(idx: idx)
 
   let d = newDerived(2)
-  assert(d.index == 2)
+  doAssert(d.index == 2)
 
 
 
@@ -762,3 +766,129 @@ block t3717:
 
   var f: Foo[Foo[int]]
   discard foo(f)
+
+
+
+block: # issue #9458
+  type
+    Option[T] = object
+      val: T
+      has: bool
+
+    Bar = object
+
+  proc none(T: typedesc): Option[T] =
+    discard
+
+  proc foo[T](self: T; x: Option[Bar] = Bar.none) =
+    discard
+
+  foo(1)
+
+
+# bug #8426
+type
+  MyBool[T: uint] = range[T(0)..T(1)] # Works
+
+var x: MyBool[uint]
+echo x
+
+# x = 2 # correctly prevented
+
+type
+  MyBool2 = range[uint(0)..uint(1)] # Error ordinal or float type expected
+
+
+# bug #10396
+import options, strutils
+
+type
+  Foo {.acyclic.} = object
+    a: string
+    bar: Option[Bar]
+
+  Bar {.acyclic.} = object
+    foo: Option[seq[Foo]]   # if this was just Option[Foo], everything works fine
+    s: string
+
+proc getBar(x: string): Bar
+
+proc intoFoos(ss: seq[string]): seq[Foo] =
+  result = @[]
+  for s in ss:
+    let spl = s.split(',')
+    if spl.len > 1:
+      result.add Foo(a: spl[0],
+                     bar: some(getBar(spl[1])))
+    else:
+      result.add Foo(a: s,
+                     bar: none[Bar]())
+
+proc getBar(x: string): Bar =
+  let spl = x.split(' ')
+  result =
+    if spl.len > 1:
+      Bar(foo: some(spl[1..high(spl)].intoFoos),
+          s: spl[0])
+    else:
+      Bar(foo: none[seq[Foo]](),
+          s: "")
+
+proc fakeReadLine(): string = "hey"
+
+echo getBar(fakeReadLine()) # causes error
+
+echo getBar("hello, world") # causes error
+
+discard $getBar(fakeReadLine()) # causes error
+
+discard $getBar("hello, world") # causes error
+
+discard getBar(fakeReadLine()) # no error
+
+discard getBar("hello, world") # no error
+
+echo intoFoos(fakeReadLine().split(' ')) # no error, works as expected
+
+
+# bug #14990
+type
+  Tile3 = Tile2
+  Tile2 = Tile
+  Tile[n] = object
+    a: n
+
+var a: Tile3[int]
+
+block: # Ensure no segfault from constraint
+  type
+    Regex[A: SomeOrdinal] = ref object
+      val: Regex[A]
+    MyConstraint = (seq or enum or set)
+    MyOtherType[A: MyConstraint] = ref object
+      val: MyOtherType[A]
+
+  var
+    a = Regex[int]()
+    b = Regex[bool]()
+    c = MyOtherType[seq[int]]()
+
+block: # https://github.com/nim-lang/Nim/issues/20416
+  type
+    Item[T] = object
+      link:ptr Item[T]
+      data:T
+
+    KVSeq[A,B] = seq[(A,B)]
+
+    MyTable[A,B] = object
+      data: KVSeq[A,B]
+
+    Container[T] = object
+      a: MyTable[int,ref Item[T]]
+
+  proc p1(sg:Container) = discard # Make sure that a non parameterized 'Container' argument still compiles
+
+  proc p2[T](sg:Container[T]) = discard
+  var v : Container[int]
+  p2(v)
diff --git a/tests/generics/tgenerics_various.nim b/tests/generics/tgenerics_various.nim
index 22d3cff7a..53661236e 100644
--- a/tests/generics/tgenerics_various.nim
+++ b/tests/generics/tgenerics_various.nim
@@ -58,23 +58,23 @@ block tgenericdefaults:
   var x1: TFoo[int, float]
 
   static:
-    assert type(x1.x) is int
-    assert type(x1.y) is float
-    assert type(x1.z) is int
+    doAssert type(x1.x) is int
+    doAssert type(x1.y) is float
+    doAssert type(x1.z) is int
 
   var x2: TFoo[string, R = float, U = seq[int]]
 
   static:
-    assert type(x2.x) is string
-    assert type(x2.y) is seq[int]
-    assert type(x2.z) is float
+    doAssert type(x2.x) is string
+    doAssert type(x2.y) is seq[int]
+    doAssert type(x2.z) is float
 
   var x3: TBar[float]
 
   static:
-    assert type(x3.x) is float
-    assert type(x3.y) is array[4, float]
-    assert type(x3.z) is float
+    doAssert type(x3.x) is float
+    doAssert type(x3.y) is array[4, float]
+    doAssert type(x3.z) is float
 
 
 
@@ -127,54 +127,18 @@ block trefs:
 
 
 
-block tsharedcases:
-  proc typeNameLen(x: typedesc): int {.compileTime.} =
-    result = x.name.len
-  macro selectType(a, b: typedesc): typedesc =
-    result = a
-
-  type
-    Foo[T] = object
-      data1: array[T.high, int]
-      data2: array[typeNameLen(T), float]
-      data3: array[0..T.typeNameLen, selectType(float, int)]
-    MyEnum = enum A, B, C, D
-
-  var f1: Foo[MyEnum]
-  var f2: Foo[int8]
-
-  doAssert high(f1.data1) == 2 # (D = 3) - 1 == 2
-  doAssert high(f1.data2) == 5 # (MyEnum.len = 6) - 1 == 5
-
-  doAssert high(f2.data1) == 126 # 127 - 1 == 126
-  doAssert high(f2.data2) == 3 # int8.len - 1 == 3
-
-  static:
-    assert high(f1.data1) == ord(C)
-    assert high(f1.data2) == 5 # length of MyEnum minus one, because we used T.high
-
-    assert high(f2.data1) == 126
-    assert high(f2.data2) == 3
-
-    assert high(f1.data3) == 6 # length of MyEnum
-    assert high(f2.data3) == 4 # length of int8
-
-    assert f2.data3[0] is float
-
-
-
 block tmap_auto:
   let x = map(@[1, 2, 3], x => x+10)
-  assert x == @[11, 12, 13]
+  doAssert x == @[11, 12, 13]
 
   let y = map(@[(1,"a"), (2,"b"), (3,"c")], x => $x[0] & x[1])
-  assert y == @["1a", "2b", "3c"]
+  doAssert y == @["1a", "2b", "3c"]
 
   proc eatsTwoArgProc[T,S,U](a: T, b: S, f: proc(t: T, s: S): U): U =
     f(a,b)
 
   let z = eatsTwoArgProc(1, "a", (t,s) => $t & s)
-  assert z == "1a"
+  doAssert z == "1a"
 
 
 
@@ -230,8 +194,8 @@ block tvarargs_vs_generics:
     echo "direct"
   proc withDirectType[T](arg: T) =
     echo "generic"
-  proc withOpenArray(args: openarray[string]) =
-    echo "openarray"
+  proc withOpenArray(args: openArray[string]) =
+    echo "openArray"
   proc withOpenArray[T](arg: T) =
     echo "generic"
   proc withVarargs(args: varargs[string]) =
@@ -253,3 +217,38 @@ block:
 
   var x: Que[int]
   doAssert(x.x == 0)
+
+
+# bug #4466
+proc identity[T](t: T): T = t
+
+proc doSomething[A, B](t: tuple[a: A, b: B]) = discard
+
+discard identity((c: 1, d: 2))
+doSomething(identity((1, 2)))
+
+# bug #6231
+proc myProc[T, U](x: T or U) = discard
+
+myProc[int, string](x = 2)
+
+block: # issue #8390
+  proc x[T:SomeFloat](q: openarray[T], y: T = 1): string =
+    doAssert $q.type == $openarray[y.type]
+    $y.type
+
+  doAssert x(@[1.0]) == $1.0.type
+
+
+block: # issue #9381
+  var evalCount {.compileTime.} = 0
+
+  macro test(t: typed): untyped =
+    inc evalCount
+    t
+
+  type GenericObj[T] = object
+    f: test(T)
+
+  var x: GenericObj[int]
+  static: doAssert evalCount == 1
diff --git a/tests/generics/tgenericwhen.nim b/tests/generics/tgenericwhen.nim
new file mode 100644
index 000000000..87672a699
--- /dev/null
+++ b/tests/generics/tgenericwhen.nim
@@ -0,0 +1,58 @@
+discard """
+  targets: "c js"
+"""
+
+block: # issue #24041
+  type ArrayBuf[N: static int, T = byte] = object
+    when sizeof(int) > sizeof(uint8):
+      when N <= int(uint8.high):
+        n: uint8
+      else:
+        when sizeof(int) > sizeof(uint16):
+          when N <= int(uint16.high):
+            n: uint16
+          else:
+            when sizeof(int) > sizeof(uint32):
+              when N <= int(uint32.high):
+                n: uint32
+              else:
+                n: int
+            else:
+              n: int
+        else:
+          n: int
+    else:
+      n: int
+
+  var x: ArrayBuf[8]
+  doAssert x.n is uint8
+  when sizeof(int) > sizeof(uint32):
+    var y: ArrayBuf[int(uint32.high) * 8]
+    doAssert y.n is int
+
+block: # constant condition after dynamic one
+  type Foo[T] = object
+    when T is int:
+      a: int
+    elif true:
+      a: string
+    else:
+      a: bool
+  var x: Foo[string]
+  doAssert x.a is string
+  var y: Foo[int]
+  doAssert y.a is int
+  var z: Foo[float]
+  doAssert z.a is string
+
+block: # issue #4774, but not with threads
+  const hasThreadSupport = not defined(js)
+  when hasThreadSupport:
+    type Channel[T] = object
+      value: T
+  type
+    SomeObj[T] = object
+      when hasThreadSupport:
+        channel: ptr Channel[T]
+  var x: SomeObj[int]
+  doAssert compiles(x.channel) == hasThreadSupport
diff --git a/tests/generics/tgensyminst.nim b/tests/generics/tgensyminst.nim
new file mode 100644
index 000000000..3f30188d8
--- /dev/null
+++ b/tests/generics/tgensyminst.nim
@@ -0,0 +1,29 @@
+# issue #24048
+
+import macros
+
+proc map(fn: proc(val: int): void) = fn(1)
+
+# This works fine, and is the exact same function call as what's
+# generated by the macro `aBug`.
+map proc(val: auto): void =
+  let variable = 123
+
+macro aBug() =
+  # 1. let sym = ident("variable")
+  let sym = genSym(nskLet, "variable")
+  let letStmt = newLetStmt(sym, newLit(123))
+
+  let lambda = newProc(
+    params = @[
+      ident("void"),
+      newIdentDefs(ident("val"), ident("auto")),
+      # 2. newIdentDefs(ident("val"), ident("int")),
+    ],
+    body = newStmtList(letStmt),
+    procType = nnkLambda
+  )
+
+  result = newCall(bindSym("map"), lambda)
+
+aBug()
diff --git a/tests/generics/timpl_ast.nim b/tests/generics/timpl_ast.nim
new file mode 100644
index 000000000..97fe128cd
--- /dev/null
+++ b/tests/generics/timpl_ast.nim
@@ -0,0 +1,80 @@
+import std/macros
+import std/assertions
+
+block: # issue #16639
+  type Foo[T] = object
+    when true:
+      x: float
+
+  type Bar = object
+    when true:
+      x: float
+
+  macro test() =
+    let a = getImpl(bindSym"Foo")[^1]
+    let b = getImpl(bindSym"Bar")[^1]
+    doAssert treeRepr(a) == treeRepr(b)
+
+  test()
+
+import strutils
+
+block: # issues #9899, ##14708
+  macro implRepr(a: typed): string =
+    result = newLit(repr(a.getImpl))
+
+  type
+    Option[T] = object
+      when false: discard # issue #14708
+      when false: x: int
+      when T is (ref | ptr):
+        val: T
+      else:
+        val: T
+        has: bool
+
+  static: # check information is retained
+    let r = implRepr(Option)
+    doAssert "when T is" in r
+    doAssert r.count("val: T") == 2
+    doAssert "has: bool" in r
+
+  block: # try to compile the output
+    macro parse(s: static string) =
+      result = parseStmt(s)
+    parse("type " & implRepr(Option))
+
+block: # issue #22639
+  type
+    Spectrum[N: static int] = object
+      data: array[N, float]
+    AngleInterpolator = object
+      data: seq[Spectrum[60]]
+  proc initInterpolator(num: int): AngleInterpolator =
+    result = AngleInterpolator()
+    for i in 0 ..< num:
+      result.data.add Spectrum[60]()
+  macro genCompatibleTuple(t: typed): untyped =
+    let typ = t.getType[1].getTypeImpl[2]
+    result = nnkTupleTy.newTree()
+    for i, ch in typ: # is `nnkObjectTy`
+      result.add nnkIdentDefs.newTree(ident(ch[0].strVal), # ch is `nnkIdentDefs`
+                                      ch[1],
+                                      newEmptyNode())
+  proc fullSize[T: object | tuple](x: T): int =
+    var tmp: genCompatibleTuple(T)
+    result = 0
+    for field, val in fieldPairs(x):
+      result += sizeof(val)
+    doAssert result == sizeof(tmp)
+
+  let reflectivity = initInterpolator(1)
+  for el in reflectivity.data:
+    doAssert fullSize(el) == sizeof(el)
+  doAssert fullSize(reflectivity.data[0]) == sizeof(reflectivity.data[0])
+  doAssert genCompatibleTuple(Spectrum[60]) is tuple[data: array[60, float]]
+  doAssert genCompatibleTuple(Spectrum[120]) is tuple[data: array[120, float]]
+  type Foo[T] = object
+    data: T
+  doAssert genCompatibleTuple(Foo[int]) is tuple[data: int]
+  doAssert genCompatibleTuple(Foo[float]) is tuple[data: float]
diff --git a/tests/generics/timplicit_and_explicit.nim b/tests/generics/timplicit_and_explicit.nim
new file mode 100644
index 000000000..7220b7429
--- /dev/null
+++ b/tests/generics/timplicit_and_explicit.nim
@@ -0,0 +1,65 @@
+
+block: # basic test
+  proc doStuff[T](a: SomeInteger): T = discard
+  proc doStuff[T;Y](a: SomeInteger, b: Y): Y = discard
+  assert typeof(doStuff[int](100)) is int
+  assert typeof(doStuff[int, float](100, 1.0)) is float
+  assert typeof(doStuff[int, string](100, "Hello")) is string
+
+  proc t[T](x: T; z: int | float): seq[T] = result.add(x & $z)
+
+  assert t[string]("Hallo", 2.0) == @["Hallo" & $2.0]
+
+  proc t2[T](z: int | float): seq[T] = result.add($z)
+
+  assert t2[string](2.0) == @[$2.0]
+
+block: # template test
+  template someThing[T;Y](a: SomeFloat, b: SomeOrdinal): (T, Y) = (a, b)
+  assert typeof(someThing[float64, int](1.0, 100)) is (float64, int)
+
+block: # static test
+  proc t[T](s: static bool) = discard
+  proc t2[T](s: static string) = discard
+  t[string](true)
+  t2[int]("hello")
+  t2[string]("world")
+  t2[float]("test222222")
+
+block: #11152
+  proc f[T](X: typedesc) = discard
+  f[int](string)
+
+block: #15622
+  proc test1[T](a: T, b: static[string] = "") = discard
+  test1[int64](123)
+  proc test2[T](a: T, b: static[string] = "") = discard
+  doAssert not (compiles do:
+    test2[int64, static[string]](123))
+
+block: #4688
+  proc convertTo[T](v: int or float): T = (T)(v)
+  discard convertTo[float](1)
+
+block: #4164
+  proc printStr[T](s: static[string]): T = discard
+  discard printStr[int]("hello static")
+
+import macros
+
+block: # issue #9040, statics with template, macro, symchoice explicit generics
+  block: # macro
+    macro fun[N: static int](): untyped =
+      newLit 1
+    const a = fun[2]()
+    doAssert a == 1
+  block: # template
+    template fun[N: static int](): untyped =
+      1
+    const a = fun[2]()
+    doAssert a == 1
+  block: # symchoice
+    proc newSeq[x: static int](): int = 1
+    template foo: int =
+      newSeq[2]()
+    doAssert foo() == 1
diff --git a/tests/generics/timports.nim b/tests/generics/timports.nim
index 800ae7f88..e252ad194 100644
--- a/tests/generics/timports.nim
+++ b/tests/generics/timports.nim
@@ -7,7 +7,7 @@ false
 '''
 """
 
-import mbind_bracket, mclosed_sym, mdotlookup, mmodule_same_as_proc
+import mbind_bracket, mclosed_sym, mdotlookup, mmodule_same_as_proc, mtypenodes
 
 
 block tbind_bracket:
@@ -31,15 +31,33 @@ block tclosed_sym:
   proc same(r:R, d:int) = echo "TEST1"
   doIt(Data[int](d:123), R())
 
+import strutils, unicode # ambiguous `strip`
 
 block tdotlookup:
   foo(7)
   # bug #1444
   fn(4)
-
+  doAssert doStrip(123) == "123"
+  # bug #14254
+  doAssert baz2[float](1'i8) == 1
+  # bug #21883
+  proc abc[T: not not int](x: T): T =
+    var x = x
+    x.set("hello", "world")
+    result = x
+  doAssert abc(5) == 10
+  block: # ensure normal call is consistent with dot call 
+    proc T(x: int): float = x.float
+    proc foo[T](x: int) =
+      doAssert typeof(T(x)) is typeof(x.T)
+    foo[uint](123)
 
 block tmodule_same_as_proc:
   # bug #1965
   proc test[T](t: T) =
     mmodule_same_as_proc"a"
   test(0)
+
+block ttypenodes:
+  # issue #22699
+  doAssert chop[bool](42) == 42
diff --git a/tests/generics/tinheritable_importcpp.nim b/tests/generics/tinheritable_importcpp.nim
new file mode 100644
index 000000000..8ee18b70b
--- /dev/null
+++ b/tests/generics/tinheritable_importcpp.nim
@@ -0,0 +1,10 @@
+discard """
+  targets: "cpp"
+  action: compile
+"""
+
+# #4651
+type
+  Vector[T] {.importcpp: "std::vector<'0 >", header: "vector", inheritable.} = object
+  VectorDerived {.importcpp: "SomeVectorDerived", nodecl.} = object of Vector[int]
+  # Error: inheritance only works with non-final objects
diff --git a/tests/generics/tmacroinjectedsym.nim b/tests/generics/tmacroinjectedsym.nim
new file mode 100644
index 000000000..985e415f2
--- /dev/null
+++ b/tests/generics/tmacroinjectedsym.nim
@@ -0,0 +1,186 @@
+{.experimental: "openSym".}
+
+block: # issue #22605, normal call syntax
+  const error = "bad"
+
+  template valueOr(self: int, def: untyped): untyped =
+    case false
+    of true: ""
+    of false:
+      template error: untyped {.used, inject.} = "good"
+      def
+
+  proc g(T: type): string =
+    let x = valueOr 123:
+      return $error
+
+    "ok"
+
+  doAssert g(int) == "good"
+
+  proc g2(T: type): string =
+    bind error # use the bad version on purpose
+    let x = valueOr 123:
+      return $error
+
+    "ok"
+
+  doAssert g2(int) == "bad"
+
+block: # issue #22605, method call syntax
+  const error = "bad"
+
+  template valueOr(self: int, def: untyped): untyped =
+    case false
+    of true: ""
+    of false:
+      template error: untyped {.used, inject.} = "good"
+      def
+
+  proc g(T: type): string =
+    let x = 123.valueOr:
+      return $error
+
+    "ok"
+
+  doAssert g(int) == "good"
+
+  proc g2(T: type): string =
+    bind error # use the bad version on purpose
+    let x = 123.valueOr:
+      return $error
+
+    "ok"
+
+  doAssert g2(int) == "bad"
+
+block: # issue #22605, original complex example
+  type Xxx = enum
+    error
+    value
+
+  type
+    Result[T, E] = object
+      when T is void:
+        when E is void:
+          oResultPrivate*: bool
+        else:
+          case oResultPrivate*: bool
+          of false:
+            eResultPrivate*: E
+          of true:
+            discard
+      else:
+        when E is void:
+          case oResultPrivate*: bool
+          of false:
+            discard
+          of true:
+            vResultPrivate*: T
+        else:
+          case oResultPrivate*: bool
+          of false:
+            eResultPrivate*: E
+          of true:
+            vResultPrivate*: T
+
+  template valueOr[T: not void, E](self: Result[T, E], def: untyped): untyped =
+    let s = (self) # TODO avoid copy
+    case s.oResultPrivate
+    of true:
+      s.vResultPrivate
+    of false:
+      when E isnot void:
+        template error: untyped {.used, inject.} = s.eResultPrivate
+      def
+
+  proc f(): Result[int, cstring] =
+    Result[int, cstring](oResultPrivate: false, eResultPrivate: "f")
+
+  proc g(T: type): string =
+    let x = f().valueOr:
+      return $error
+
+    "ok"
+
+  doAssert g(int) == "f"
+
+  proc g2(T: type): string =
+    bind error # use the bad version on purpose
+    let x = f().valueOr:
+      return $error
+
+    "ok"
+
+  doAssert g2(int) == "error"
+
+block: # issue #23865
+  type Xxx = enum
+    error
+    value
+
+  type
+    Result[T, E] = object
+      when T is void:
+        when E is void:
+          oResultPrivate: bool
+        else:
+          case oResultPrivate: bool
+          of false:
+            eResultPrivate: E
+          of true:
+            discard
+      else:
+        when E is void:
+          case oResultPrivate: bool
+          of false:
+            discard
+          of true:
+            vResultPrivate: T
+        else:
+          case oResultPrivate: bool
+          of false:
+            eResultPrivate: E
+          of true:
+            vResultPrivate: T
+
+  func error[T, E](self: Result[T, E]): E =
+    ## Fetch error of result if set, or raise Defect
+    case self.oResultPrivate
+    of true:
+      when T isnot void:
+        raiseResultDefect("Trying to access error when value is set", self.vResultPrivate)
+      else:
+        raiseResultDefect("Trying to access error when value is set")
+    of false:
+      when E isnot void:
+        self.eResultPrivate
+
+  template valueOr[T: not void, E](self: Result[T, E], def: untyped): untyped =
+    let s = (self) # TODO avoid copy
+    case s.oResultPrivate
+    of true:
+      s.vResultPrivate
+    of false:
+      when E isnot void:
+        template error: untyped {.used, inject.} = s.eResultPrivate
+      def
+  proc f(): Result[int, cstring] =
+    Result[int, cstring](oResultPrivate: false, eResultPrivate: "f")
+  proc g(T: type): string =
+    let x = f().valueOr:
+      return $error
+    "ok"
+  doAssert g(int) == "f"
+
+import sequtils
+
+block: # issue #12283
+  var b = 5
+  type Foo[T] = object
+    h, w: int
+  proc bar[T](foos: seq[Foo[T]]): T =
+    let w = foldl(foos, a + b.w, 0)
+    w
+  let foos = @[Foo[int](h: 3, w: 5), Foo[int](h: 4, w: 6)]
+  doAssert bar(foos) == 11
diff --git a/tests/generics/tmacroinjectedsymwarning.nim b/tests/generics/tmacroinjectedsymwarning.nim
new file mode 100644
index 000000000..77119004b
--- /dev/null
+++ b/tests/generics/tmacroinjectedsymwarning.nim
@@ -0,0 +1,59 @@
+discard """
+  matrix: "--skipParentCfg --filenames:legacyRelProj"
+"""
+
+type Xxx = enum
+  error
+  value
+
+type
+  Result[T, E] = object
+    when T is void:
+      when E is void:
+        oResultPrivate*: bool
+      else:
+        case oResultPrivate*: bool
+        of false:
+          eResultPrivate*: E
+        of true:
+          discard
+    else:
+      when E is void:
+        case oResultPrivate*: bool
+        of false:
+          discard
+        of true:
+          vResultPrivate*: T
+      else:
+        case oResultPrivate*: bool
+        of false:
+          eResultPrivate*: E
+        of true:
+          vResultPrivate*: T
+
+template valueOr[T: not void, E](self: Result[T, E], def: untyped): untyped =
+  let s = (self) # TODO avoid copy
+  case s.oResultPrivate
+  of true:
+    s.vResultPrivate
+  of false:
+    when E isnot void:
+      template error: untyped {.used, inject.} = s.eResultPrivate
+    def
+
+proc f(): Result[int, cstring] =
+  Result[int, cstring](oResultPrivate: false, eResultPrivate: "f")
+
+proc g(T: type): string =
+  let x = f().valueOr:
+    {.push warningAsError[IgnoredSymbolInjection]: on.}
+    # test spurious error
+    discard true
+    let _ = f
+    {.pop.}
+    return $error #[tt.Warning
+            ^ a new symbol 'error' has been injected during template or generic instantiation, however 'error' [enumField declared in tmacroinjectedsymwarning.nim(6, 3)] captured at the proc declaration will be used instead; either enable --experimental:openSym to use the injected symbol, or `bind` this captured symbol explicitly [IgnoredSymbolInjection]]#
+
+  "ok"
+
+discard g(int)
diff --git a/tests/generics/tmetafield.nim b/tests/generics/tmetafield.nim
index 7a2375abe..cf30a936d 100644
--- a/tests/generics/tmetafield.nim
+++ b/tests/generics/tmetafield.nim
@@ -1,10 +1,23 @@
 discard """
   cmd: "nim check $options $file"
-  errormsg: "'proc' is not a concrete type"
-  errormsg: "'Foo' is not a concrete type."
-  errormsg: "invalid type: 'proc' in this context: 'TBaseMed'"
+  action: "reject"
+  nimout: '''
+tmetafield.nim(26, 5) Error: 'proc' is not a concrete type; for a callback without parameters use 'proc()'
+tmetafield.nim(27, 5) Error: 'Foo' is not a concrete type
+tmetafield.nim(29, 5) Error: invalid type: 'proc' in this context: 'TBaseMed' for var
+'''
 """
 
+# bug #188
+
+
+
+
+
+
+
+
+# line 20
 type
   Foo[T] = object
     x: T
@@ -15,4 +28,3 @@ type
 
 var a: TBaseMed
 
-# issue 188
diff --git a/tests/generics/tnestedissues.nim b/tests/generics/tnestedissues.nim
new file mode 100644
index 000000000..e96a1927e
--- /dev/null
+++ b/tests/generics/tnestedissues.nim
@@ -0,0 +1,24 @@
+block: # issue #23568
+  type G[T] = object
+    j: T
+  proc s[T](u: int) = discard
+  proc s[T]() = discard
+  proc c(e: int | int): G[G[G[int]]] = s[G[G[int]]]()
+  discard c(0)
+
+import std/options
+
+block: # issue #23310
+  type
+    BID = string or uint64
+    Future[T] = ref object of RootObj
+      internalValue: T
+    InternalRaisesFuture[T] = ref object of Future[T]
+  proc newInternalRaisesFutureImpl[T](): InternalRaisesFuture[T] =
+    let fut = InternalRaisesFuture[T]()
+  template newFuture[T](): auto =
+    newInternalRaisesFutureImpl[T]()
+  proc problematic(blockId: BID): Future[Option[seq[int]]] =
+    let resultFuture = newFuture[Option[seq[int]]]()
+    return resultFuture
+  let x = problematic("latest")
diff --git a/tests/generics/tnestedtemplate.nim b/tests/generics/tnestedtemplate.nim
new file mode 100644
index 000000000..22d0a2d3c
--- /dev/null
+++ b/tests/generics/tnestedtemplate.nim
@@ -0,0 +1,9 @@
+block: # issue #13979
+  var s: seq[int]
+  proc filterScanline[T](input: openArray[T]) =
+    template currPix: untyped = input[i]
+    for i in 0..<input.len:
+      s.add currPix
+  let pix = [1, 2, 3]
+  filterScanline(pix)
+  doAssert s == @[1, 2, 3]
diff --git a/tests/generics/tnullary_generics.nim b/tests/generics/tnullary_generics.nim
new file mode 100644
index 000000000..c79558ee3
--- /dev/null
+++ b/tests/generics/tnullary_generics.nim
@@ -0,0 +1,26 @@
+discard """
+  nimout: '''
+hah
+hey
+hey
+hah
+'''
+"""
+
+# non-generic
+proc foo(s: string) =
+  static: echo "hah"
+  echo s
+
+static: echo "hey"
+
+foo("hoo")
+
+# nullary generic
+proc bar[](s: string) =
+  static: echo "hah"
+  echo s
+
+static: echo "hey"
+
+bar("hoo")
diff --git a/tests/generics/tobjecttyperel.nim b/tests/generics/tobjecttyperel.nim
index 80fe23459..6f223c154 100644
--- a/tests/generics/tobjecttyperel.nim
+++ b/tests/generics/tobjecttyperel.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "-d:nimInternalNonVtablesTesting"
   output: '''(peel: 0, color: 15)
 (color: 15)
 17
diff --git a/tests/generics/topensymimport.nim b/tests/generics/topensymimport.nim
new file mode 100644
index 000000000..a47496827
--- /dev/null
+++ b/tests/generics/topensymimport.nim
@@ -0,0 +1,5 @@
+# issue #23386
+
+import mopensymimport2
+
+doAssert g(int) == "f"
diff --git a/tests/generics/toverloading_typedesc.nim b/tests/generics/toverloading_typedesc.nim
index 5ab700828..4d748bfee 100644
--- a/tests/generics/toverloading_typedesc.nim
+++ b/tests/generics/toverloading_typedesc.nim
@@ -1,7 +1,3 @@
-discard """
-  exitcode: 0
-  disabled: '''true'''
-"""
 import moverloading_typedesc
 import tables
 
@@ -9,7 +5,6 @@ type
   LFoo = object
   LBar = object
 
-
 when true:
   doAssert FBar.new() == 3
 
diff --git a/tests/generics/tparam_binding.nim b/tests/generics/tparam_binding.nim
index cd0d58e02..fa7558613 100644
--- a/tests/generics/tparam_binding.nim
+++ b/tests/generics/tparam_binding.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:arc; --mm:refc"
   errormsg: "got <ref Matrix[2, 2, system.float], ref Matrix[2, 1, system.float]>"
-  line: 27
+  line: 28
 """
 
 type
diff --git a/tests/generics/tparser_generator.nim b/tests/generics/tparser_generator.nim
index 8f8fea382..ac921c0e5 100644
--- a/tests/generics/tparser_generator.nim
+++ b/tests/generics/tparser_generator.nim
@@ -147,7 +147,7 @@ proc literal*[N, T, P](pattern: P, kind: N): Rule[N, T] =
   let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
     if start == len(text):
       return -1
-    assert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
+    doAssert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
     when P is string or P is seq[N]:
       debug(debugLex, "Literal[" & $kind & "]: testing " & $pattern & " at " & $start & ": " & $text[start..start+len(pattern)-1])
       if text.continuesWith(pattern, start):
@@ -177,7 +177,7 @@ proc token[N, T](pattern: T, kind: N): Rule[N, T] =
     debug(debugLex, "Token[" & $kind & "]: testing " & pattern & " at " & $start)
     if start == len(text):
       return -1
-    assert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
+    doAssert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
     let m = text.match(re(pattern), start)
     if m.isSome:
       let node = initNode(start, len(m.get.match), kind)
@@ -192,7 +192,7 @@ proc chartest[N, T, S](testfunc: proc(s: S): bool, kind: N): Rule[N, T] =
   let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
     if start == len(text):
       return -1
-    assert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
+    doAssert(len(text)>start, "Attempting to match at $#, string length is $# " % [$start, $len(text)])
     if testfunc(text[start]):
       nodes.add(initNode(start, 1, kind))
       result = 1
@@ -252,11 +252,11 @@ proc fail*[N, T](message: string, kind: N): Rule[N, T] =
 proc `+`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] =
   let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
     var mynodes = newSeq[Node[N]]()
-    assert(not isNil(left.parser), "Left hand side parser is nil")
+    doAssert(not isNil(left.parser), "Left hand side parser is nil")
     let leftlength = left.parser(text, start, mynodes)
     if leftlength == -1:
       return leftlength
-    assert(not isNil(right.parser), "Right hand side parser is nil")
+    doAssert(not isNil(right.parser), "Right hand side parser is nil")
     let rightlength = right.parser(text, start+leftlength, mynodes)
     if rightlength == -1:
       return rightlength
@@ -267,13 +267,13 @@ proc `+`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] =
 proc `/`*[N, T](left: Rule[N, T], right: Rule[N, T]): Rule[N, T] =
   let parser = proc (text: T, start: int, nodes: var seq[Node[N]]): int =
     var mynodes = newSeq[Node[N]]()
-    assert(not isNil(left.parser), "Left hand side of / is not fully defined")
+    doAssert(not isNil(left.parser), "Left hand side of / is not fully defined")
     let leftlength = left.parser(text, start, mynodes)
     if leftlength != -1:
       nodes.add(mynodes)
       return leftlength
     mynodes = newSeq[Node[N]]()
-    assert(not isNil(right.parser), "Right hand side of / is not fully defined")
+    doAssert(not isNil(right.parser), "Right hand side of / is not fully defined")
     let rightlength = right.parser(text, start, mynodes)
     if rightlength == -1:
       return rightlength
@@ -360,7 +360,7 @@ proc `/`*[N, T](rule: Rule[N, T]): Rule[N, T] =
   result = newRule[N, T](parser, rule.kind)
 
 proc `->`*(rule: Rule, production: Rule) =
-  assert(not isnil(production.parser), "Right hand side of -> is nil - has the rule been defined yet?")
+  doAssert(not isnil(production.parser), "Right hand side of -> is nil - has the rule been defined yet?")
   rule.parser = production.parser
 
 template grammar*[K](Kind, Text, Symbol: typedesc; default: K, code: untyped): typed {.hint[XDeclaredButNotUsed]: off.} =
diff --git a/tests/generics/tpointerprocs.nim b/tests/generics/tpointerprocs.nim
new file mode 100644
index 000000000..2bcaf15b3
--- /dev/null
+++ b/tests/generics/tpointerprocs.nim
@@ -0,0 +1,28 @@
+discard """
+cmd: "nim check $options --hints:off $file"
+action: "reject"
+nimout:'''
+tpointerprocs.nim(15, 11) Error: 'foo' doesn't have a concrete type, due to unspecified generic parameters.
+tpointerprocs.nim(27, 11) Error: cannot instantiate: 'foo[int]'; got 1 typeof(s) but expected 2
+tpointerprocs.nim(27, 14) Error: expression 'foo[int]' has no type (or is ambiguous)
+tpointerprocs.nim(28, 11) Error: expression 'bar' has no type (or is ambiguous)
+'''
+"""
+
+block:
+  proc foo(x: int | float): float = result = 1.0
+  let
+    bar = foo
+    baz = bar
+
+block:
+  proc foo(x: int | float): float = result = 1.0
+  let
+    bar = foo[int]
+    baz = bar
+
+block:
+  proc foo(x: int | float, y: int or string): float = result = 1.0
+  let
+    bar = foo[int]
+    baz = bar
\ No newline at end of file
diff --git a/tests/generics/tprevent_double_bind.nim b/tests/generics/tprevent_double_bind.nim
index 86e080ab6..d8fc6e5d3 100644
--- a/tests/generics/tprevent_double_bind.nim
+++ b/tests/generics/tprevent_double_bind.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "type mismatch: got <TT[seq[string]], proc (v: int){.gcsafe, locks: 0.}>"
+  errormsg: "type mismatch: got <TT[seq[string]], proc (v: int){.gcsafe.}>"
   line: 20
 """
 
diff --git a/tests/generics/trecursivegenerics.nim b/tests/generics/trecursivegenerics.nim
new file mode 100644
index 000000000..1b152b063
--- /dev/null
+++ b/tests/generics/trecursivegenerics.nim
@@ -0,0 +1,96 @@
+block: # Replicates #18728
+  type
+    FlipFlop[A, B] = ref object
+      val: A
+      next: FlipFlop[B, A]
+  
+    Trinary[A, B, C] = ref object
+      next: Trinary[B, C, A]
+  
+  assert typeof(FlipFlop[int, string]().next) is FlipFlop[string, int]
+  assert typeof(FlipFlop[string, int]().next) is FlipFlop[int, string]
+  assert typeof(Trinary[int, float, string]().next) is Trinary[float, string, int]
+  assert typeof(Trinary[int, float, string]().next.next) is Trinary[string, int, float]
+  var a = FlipFlop[int, string](val: 100, next: FlipFlop[string, int](val: "Hello"))
+  assert a.val == 100
+  assert a.next.val == "Hello"
+
+block: # 18838
+  type
+    DoublyLinkedNodeObj[T] = object
+      value: T
+
+    DoublyLinkedNode[T] = ref DoublyLinkedNodeObj[T]
+
+    Item[T] = ref object
+      link: DoublyLinkedNode[Item[T]]
+
+    Box = object
+
+  proc newDoublyLinkedNode[T](value: T): DoublyLinkedNode[T] =
+    new(result)
+    result.value = value 
+
+  let link = newDoublyLinkedNode(Item[Box]())
+
+import lists
+block:
+  type
+    Box = object
+    Item[T] = ref object
+      link:DoublyLinkedNode[ Item[T] ]
+
+    ItemSimple = ref object
+      link:DoublyLinkedNode[ ItemSimple ]
+
+  let link = newDoublyLinkedNode( Item[Box]() )
+
+block: #18897
+  type
+    SkipListObj[T] = object
+      over: SkipList[T]
+      down: SkipList[T]
+      value: T
+
+    SkipList[T] = ref SkipListObj[T]
+
+    GraphObj[N, E; F: static[int]] = object
+      nodes: SkipList[Node[N, E]]
+
+    Graph[N, E; F: static[int]] = ref GraphObj[N, E, F]
+
+    Node[N, E] = ref NodeObj[N, E]
+
+    NodeObj[N, E] = object
+      value: N
+      incoming: SkipList[Edge[N, E]]
+      outgoing: SkipList[Edge[N, E]]
+
+    Edge[N, E] = ref EdgeObj[N, E]
+
+    EdgeObj[N, E] = object
+      value: E
+      id: int
+      source: Node[N, E]
+      target: Node[N, E]
+
+    EdgeResult[N, E] = tuple
+      source: Node[N, E]
+      edge: Edge[N, E]
+      target: Node[N, E]
+
+  proc newSkipList[T](value: T): SkipList[T] =
+    static: echo T, " ", typeof(result.value)
+    result = SkipList[T](value: value)
+
+  proc toSkipList[T](values: openArray[T] = @[]): SkipList[T] =
+    for item in items(values):
+      if result.isNil:
+        result = newSkipList(item)
+
+  proc newContainer[N, E, F](graph: Graph[N, E, F]; form: typedesc): auto =
+    result = toSkipList[form]([])
+
+  var
+    result = Graph[int, string, 0]()
+  result.nodes = result.newContainer(Node[int, string])
\ No newline at end of file
diff --git a/tests/generics/treentranttypes.nim b/tests/generics/treentranttypes.nim
index 31fa25293..801f0e444 100644
--- a/tests/generics/treentranttypes.nim
+++ b/tests/generics/treentranttypes.nim
@@ -2,21 +2,13 @@ discard """
 output: '''
 (10, ("test", 1.2))
 3x3 Matrix [[0.0, 2.0, 3.0], [2.0, 0.0, 5.0], [2.0, 0.0, 5.0]]
-
 2x3 Matrix [[0.0, 2.0, 3.0], [2.0, 0.0, 5.0]]
-
 2x3 Literal [[0.0, 2.0, 3.0], [2.0, 0.0, 5.0]]
-
 2x3 Matrix [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
-
 2x2 ArrayArray[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
-
 2x3 ArrayVector[[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
-
 2x3 VectorVector [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
-
 2x3 VectorArray [[0.0, 0.0, 0.0], [0.0, 0.0, 0.0]]
-
 @[1, 2]
 @[1, 2]
 @[1, 2]@[3, 4]
@@ -109,3 +101,14 @@ echo @(b.arr[0].arr), @(b.arr[1].arr)
 let y = b
 echo @(y.arr[0].arr), @(y.arr[1].arr)
 
+import macros
+
+block: # issue #5121
+  type
+    A = object
+    AConst[X] = A
+
+  macro dumpType(t: typedesc): untyped =
+    result = newTree(nnkTupleConstr, newLit $t.getType[1].typeKind, newLit t.getType[1].treeRepr)
+
+  doAssert dumpType(A) == ("ntyObject", "Sym \"A\"")
diff --git a/tests/generics/treturn_inference.nim b/tests/generics/treturn_inference.nim
new file mode 100644
index 000000000..331a9d4db
--- /dev/null
+++ b/tests/generics/treturn_inference.nim
@@ -0,0 +1,184 @@
+
+{.experimental: "inferGenericTypes".}
+
+import std/tables
+
+block:
+  type
+    MyOption[T, Z] = object
+      x: T
+      y: Z
+
+  proc none[T, Z](): MyOption[T, Z] =
+    when T is int:
+      result.x = 22
+    when Z is float:
+      result.y = 12.0
+
+  proc myGenericProc[T, Z](): MyOption[T, Z] =
+    none() # implied by return type
+
+  let a = myGenericProc[int, float]()
+  doAssert a.x == 22
+  doAssert a.y == 12.0
+
+  let b: MyOption[int, float] = none() # implied by type of b
+  doAssert b.x == 22
+  doAssert b.y == 12.0
+
+# Simple template based result with inferred type for errors
+block:
+  type
+    ResultKind {.pure.} = enum
+      Ok
+      Err
+
+    Result[T] = object
+      case kind: ResultKind
+      of Ok:
+        data: T
+      of Err:
+        errmsg: cstring
+
+  template err[T](msg: static cstring): Result[T] =
+    Result[T](kind : ResultKind.Err, errmsg : msg)
+
+  proc testproc(): Result[int] =
+    err("Inferred error!") # implied by proc return
+  let r = testproc()
+  doAssert r.kind == ResultKind.Err
+  doAssert r.errmsg == "Inferred error!"
+
+# Builtin seq
+block:
+  let x: seq[int] = newSeq(1)
+  doAssert x is seq[int]
+  doAssert x.len() == 1
+
+  type
+    MyType[T, Z] = object
+      x: T
+      y: Z
+
+  let y: seq[MyType[int, float]] = newSeq(2)
+  doAssert y is seq[MyType[int, float]]
+  doAssert y.len() == 2
+
+  let z = MyType[seq[float], string](
+    x : newSeq(3),
+    y : "test"
+  )
+  doAssert z.x is seq[float]
+  doAssert z.x.len() == 3
+  doAssert z.y is string
+  doAssert z.y == "test"
+
+# array
+block:
+  proc giveArray[N, T](): array[N, T] =
+    for i in 0 .. N.high:
+      result[i] = i
+  var x: array[2, int] = giveArray()
+  doAssert x == [0, 1]
+
+# tuples
+block:
+  proc giveTuple[T, Z]: (T, Z, T) = discard
+  let x: (int, float, int) = giveTuple()
+  doAssert x is (int, float, int)
+  doAssert x == (0, 0.0, 0)
+
+  proc giveNamedTuple[T, Z]: tuple[a: T, b: Z] = discard
+  let y: tuple[a: int, b: float] = giveNamedTuple()
+  doAssert y is (int, float)
+  doAssert y is tuple[a: int, b: float]
+  doAssert y == (0, 0.0)
+
+  proc giveNestedTuple[T, Z]: ((T, Z), Z) = discard
+  let z: ((int, float), float) = giveNestedTuple()
+  doAssert z is ((int, float), float)
+  doAssert z == ((0, 0.0), 0.0)
+
+  # nesting inside a generic type
+  type MyType[T] = object
+    x: T
+  let a = MyType[(int, MyType[float])](x : giveNamedTuple())
+  doAssert a.x is (int, MyType[float])
+
+
+# basic constructors
+block:
+  type MyType[T] = object
+    x: T
+
+  proc giveValue[T](): T =
+    when T is int:
+      12
+    else:
+      default(T)
+
+  let x = MyType[int](x : giveValue())
+  doAssert x.x is int
+  doAssert x.x == 12
+
+  let y = MyType[MyType[float]](x : MyType[float](x : giveValue()))
+  doAssert y.x is MyType[float]
+  doAssert y.x.x is float
+  doAssert y.x.x == 0.0
+
+  # 'MyType[float]' is bound to 'T' directly
+  #  instead of mapping 'T' to 'float'
+  let z = MyType[MyType[float]](x : giveValue())
+  doAssert z.x is MyType[float]
+  doAssert z.x.x == 0.0
+
+  type Foo = object
+    x: Table[int, float]
+
+  let a = Foo(x: initTable())
+  doAssert a.x is Table[int, float]
+
+# partial binding
+block:
+  type
+    ResultKind = enum
+      Ok, Error
+
+    Result[T, E] = object
+      case kind: ResultKind
+      of Ok:
+        okVal: T
+      of Error:
+        errVal: E
+
+  proc err[T, E](myParam: E): Result[T, E] =
+    Result[T, E](kind : Error, errVal : myParam)
+
+  proc doStuff(): Result[int, string] = 
+    err("Error")
+
+  let res = doStuff()
+  doAssert res.kind == Error
+  doAssert res.errVal == "Error"
+
+# ufcs
+block:
+  proc getValue[T](_: string): T =
+    doAssert T is int
+    44
+  
+  proc `'test`[T](_: string): T =
+    55
+
+  let a: int = getValue("")
+  let b: int = "".getValue()
+  let c: int = "".getValue
+  let d: int = getValue ""
+  let e: int = getValue""
+  let f: int = 12345'test
+  doAssert a == 44
+  doAssert b == 44
+  doAssert c == 44
+  doAssert d == 44
+  doAssert e == 44
+  doAssert f == 55
diff --git a/tests/generics/tstatic_constrained.nim b/tests/generics/tstatic_constrained.nim
new file mode 100644
index 000000000..d356b9d1c
--- /dev/null
+++ b/tests/generics/tstatic_constrained.nim
@@ -0,0 +1,79 @@
+discard """
+  cmd: "nim check --hints:off --warnings:off $file"
+  action: "reject"
+  nimout:'''
+tstatic_constrained.nim(44, 22) Error: cannot instantiate MyOtherType [type declared in tstatic_constrained.nim(30, 5)]
+got: <typedesc[int], int literal(10)>
+but expected: <T: float or string, Y>
+tstatic_constrained.nim(44, 22) Error: cannot instantiate MyOtherType [type declared in tstatic_constrained.nim(30, 5)]
+got: <typedesc[int], int literal(10)>
+but expected: <T: float or string, Y>
+tstatic_constrained.nim(44, 31) Error: object constructor needs an object type [error]
+tstatic_constrained.nim(44, 31) Error: expression '' has no type (or is ambiguous)
+tstatic_constrained.nim(45, 22) Error: cannot instantiate MyOtherType [type declared in tstatic_constrained.nim(30, 5)]
+got: <typedesc[byte], uint8>
+but expected: <T: float or string, Y>
+tstatic_constrained.nim(45, 22) Error: cannot instantiate MyOtherType [type declared in tstatic_constrained.nim(30, 5)]
+got: <typedesc[byte], uint8>
+but expected: <T: float or string, Y>
+tstatic_constrained.nim(45, 34) Error: object constructor needs an object type [error]
+tstatic_constrained.nim(45, 34) Error: expression '' has no type (or is ambiguous)
+tstatic_constrained.nim(77, 14) Error: cannot instantiate MyType [type declared in tstatic_constrained.nim(71, 5)]
+got: <typedesc[float], float64>
+but expected: <T: MyConstraint, Y>
+'''
+"""
+block:
+  type 
+    MyType[T; X: static T] = object
+      data: T
+    MyOtherType[T: float or string, Y: static T] = object
+
+  func f[T,X](a: MyType[T,X]): MyType[T,X] =
+    when T is string:
+      MyType[T,X](data: a.data & X)
+    else:
+      MyType[T,X](data: a.data + X)
+
+  discard MyType[int, 2](data: 1)
+  discard MyType[string, "Helelello"](data: "Hmmm")
+  discard MyType[int, 2](data: 1).f()
+  discard MyType[string, "Helelello"](data: "Hmmm").f()
+  discard MyOtherType[float, 1.3]()
+  discard MyOtherType[string, "Hello"]()
+  discard MyOtherType[int, 10]()
+  discard MyOtherType[byte, 10u8]()
+
+block:
+  type
+    Moduloable = concept m, type M
+      m mod m is M
+    Addable = concept a, type A
+      a + a is A
+    Modulo[T: Moduloable; Mod: static T] = distinct T
+    ModuloAdd[T: Moduloable or Addable; Mod: static T] = distinct T
+    ModuAddable = Addable or Moduloable
+    ModdAddClass[T: ModuAddable; Mod: static T] = distinct T
+
+  proc toMod[T](val: T, modVal: static T): Modulo[T, modVal] =
+    mixin `mod`
+    Modulo[T, modVal](val mod modVal)
+  var
+    a = 3231.toMod(10)
+    b = 5483.toMod(10)
+  discard ModuloAdd[int, 3](0)
+  discard ModdAddClass[int, 3](0)
+
+block:
+  type
+    MyConstraint = int or string
+    MyOtherConstraint[T] = object
+    MyType[T: MyConstraint; Y: static T] = object
+    MyOtherType[T: MyOtherConstraint; Y: static T] = object
+
+  var 
+    a: MyType[int, 10]
+    b: MyType[string, "hello"]
+    c: MyType[float, 10d]
+    d: MyOtherType[MyOtherConstraint[float],MyOtherConstraint[float]()]
+    e: MyOtherType[MyOtherConstraint[int], MyOtherConstraint[int]()]
diff --git a/tests/generics/tthread_generic.nim b/tests/generics/tthread_generic.nim
index 2af5a7615..300da56a6 100644
--- a/tests/generics/tthread_generic.nim
+++ b/tests/generics/tthread_generic.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: "nim $target --hints:on --threads:on $options $file"
+  matrix: "--mm:refc; --mm:orc"
   action: compile
 """
 
diff --git a/tests/generics/tuninstantiated_failure.nim b/tests/generics/tuninstantiated_failure.nim
new file mode 100644
index 000000000..f3d5b34b8
--- /dev/null
+++ b/tests/generics/tuninstantiated_failure.nim
@@ -0,0 +1,16 @@
+discard """
+cmd: "nim check $file"
+"""
+
+type
+  Test[T, K] = object
+    name: string
+  Something = Test[int]
+
+func `[]`[T, K](x: var Test[T, K], idx: int): var Test[T, K] =
+  x
+
+var b: Something
+# Should give an error since Something isn't a valid Test
+b[0].name = "Test" #[tt.Error
+ ^  expression '' has no type (or is ambiguous)]#
diff --git a/tests/generics/tuninstantiatedgenericcalls.nim b/tests/generics/tuninstantiatedgenericcalls.nim
new file mode 100644
index 000000000..f33fc8967
--- /dev/null
+++ b/tests/generics/tuninstantiatedgenericcalls.nim
@@ -0,0 +1,517 @@
+# Cases that used to only work due to weird workarounds in the compiler
+# involving not instantiating calls in generic bodies which are removed
+# due to breaking statics.
+# The issue was that these calls are compiled as regular expressions at
+# the generic declaration with unresolved generic parameter types,
+# which are special cased in some places in the compiler, but sometimes
+# treated like real types.
+
+block:
+  type Base10 = object
+
+  func maxLen(T: typedesc[Base10], I: type): int8 =
+    when I is uint8:
+      3
+    elif I is uint16:
+      5
+    elif I is uint32:
+      10
+    elif I is uint64:
+      20
+    else:
+      when sizeof(uint) == 4:
+        10
+      else:
+        20
+  
+  type
+    Base10Buf[T: SomeUnsignedInt] = object
+      data: array[maxLen(Base10, T), byte]
+      len: int8
+
+  var x: Base10Buf[uint32]
+  doAssert x.data.len == 10
+  var y: Base10Buf[uint16]
+  doAssert y.data.len == 5
+
+import typetraits
+
+block thardcases:
+  proc typeNameLen(x: typedesc): int {.compileTime.} =
+    result = x.name.len
+  macro selectType(a, b: typedesc): typedesc =
+    result = a
+
+  type
+    Foo[T] = object
+      data1: array[T.high, int]
+      data2: array[typeNameLen(T), float]
+      data3: array[0..T.typeNameLen, selectType(float, int)]
+  
+  type MyEnum = enum A, B, C, D
+
+  var f1: Foo[MyEnum]
+  var f2: Foo[int8]
+
+  doAssert high(f1.data1) == 2 # (D = 3) - 1 == 2
+  doAssert high(f1.data2) == 5 # (MyEnum.len = 6) - 1 == 5
+
+  doAssert high(f2.data1) == 126 # 127 - 1 == 126
+  doAssert high(f2.data2) == 3 # int8.len - 1 == 3
+
+  static:
+    doAssert high(f1.data1) == ord(C)
+    doAssert high(f1.data2) == 5 # length of MyEnum minus one, because we used T.high
+
+    doAssert high(f2.data1) == 126
+    doAssert high(f2.data2) == 3
+
+    doAssert high(f1.data3) == 6 # length of MyEnum
+    doAssert high(f2.data3) == 4 # length of int8
+
+    doAssert f2.data3[0] is float
+
+import muninstantiatedgenericcalls
+
+block:
+  var x: Leb128Buf[uint32]
+  doAssert x.data.len == 5
+  var y: Leb128Buf[uint16]
+  doAssert y.data.len == 3
+
+import macros
+
+block: # issue #12415
+  macro isSomePointerImpl(t: typedesc): bool =
+    var impl = t.getTypeInst[1].getTypeImpl
+    if impl.kind == nnkDistinctTy:
+      impl = impl[0].getTypeImpl
+    if impl.kind in {nnkPtrTy,nnkRefTy}:
+      result = newLit(true)
+    elif impl.kind == nnkSym and impl.eqIdent("pointer"):
+      result = newLit(true)
+    else:
+      result = newLit(false)
+
+  proc isSomePointer[T](t: typedesc[T]): bool {.compileTime.} =
+    isSomePointerImpl(t)
+
+  type
+    Option[T] = object
+      ## An optional type that stores its value and state separately in a boolean.
+      when isSomePointer(typedesc(T)):
+        val: T
+      else:
+        val: T
+        has: bool
+  var x: Option[ref int]
+  doAssert not compiles(x.has)
+  var y: Option[int]
+  doAssert compiles(y.has)
+
+block: # issue #2002
+  proc isNillable(T: typedesc): bool =
+    when compiles((let v: T = nil)):
+      return true
+    else:
+      return false
+
+  type
+    Foo[T] = object
+      when isNillable(T):
+        nillable: float
+      else:
+        notnillable: int
+
+  var val1: Foo[ref int]
+  doAssert compiles(val1.nillable)
+  doAssert not compiles(val1.notnillable)
+  var val2: Foo[int]
+  doAssert not compiles(val2.nillable)
+  doAssert compiles(val2.notnillable)
+
+block: # issue #1771
+  type
+    Foo[X, T] = object
+      bar: array[X.low..X.high, T]
+
+  proc test[X, T](f: Foo[X, T]): T =
+    f.bar[X.low]
+
+  var a: Foo[range[0..2], float]
+  doAssert test(a) == 0.0
+
+block: # issue #23730
+  proc test(M: static[int]): array[1 shl M, int] = discard
+  doAssert len(test(3)) == 8
+  doAssert len(test(5)) == 32
+
+block: # issue #19819
+  type
+    Example[N: static int] = distinct int
+    What[E: Example] = Example[E.N + E.N]
+
+block: # issue #23339
+  type
+    A = object
+    B = object
+  template aToB(t: typedesc[A]): typedesc = B
+  type
+    Inner[I] = object
+      innerField: I
+    Outer[O] = object
+      outerField: Inner[O.aToB]
+  var x: Outer[A]
+  doAssert typeof(x.outerField.innerField) is B
+
+block: # deref syntax
+  type
+    Enqueueable = concept x
+      x is ptr
+    Foo[T: Enqueueable] = object
+      x: typeof(default(T)[])
+
+  proc p[T](f: Foo[T]) =
+    var bar: Foo[T]
+    discard
+  var foo: Foo[ptr int]
+  p(foo)
+  doAssert foo.x is int
+  foo.x = 123
+  doAssert foo.x == 123
+  inc foo.x
+  doAssert foo.x == 124
+
+block:
+  type Generic[T] = object
+    field: T
+  macro foo(x: typed): untyped = x
+  macro bar[T](x: typedesc[Generic[T]]): untyped = x
+  type
+    Foo[T] = object
+      field: Generic[int].foo()
+    Foo2[T] = object
+      field: Generic[T].foo()
+    Bar[T] = object
+      field: Generic[int].bar()
+    Bar2[T] = object
+      field: Generic[T].bar()
+  var x: Foo[int]
+  var x2: Foo2[int]
+  var y: Bar[int]
+  var y2: Bar2[int]
+
+block:
+  macro pick(x: static int): untyped =
+    if x < 100:
+      result = bindSym"int"
+    else:
+      result = bindSym"float"
+  
+  type Foo[T: static int] = object
+    fixed1: pick(25)
+    fixed2: pick(125)
+    unknown: pick(T)
+  
+  var a: Foo[123]
+  doAssert a.fixed1 is int
+  doAssert a.fixed2 is float
+  doAssert a.unknown is float
+  var b: Foo[23]
+  doAssert b.fixed1 is int
+  doAssert b.fixed2 is float
+  doAssert b.unknown is int
+
+import std/sequtils
+
+block: # version of #23432 with `typed`, don't delay instantiation
+  type
+    Future[T] = object
+    InternalRaisesFuture[T, E] = object
+  macro Raising[T](F: typedesc[Future[T]], E: varargs[typed]): untyped =
+    let raises = nnkTupleConstr.newTree(E.mapIt(it))
+    nnkBracketExpr.newTree(
+      ident "InternalRaisesFuture",
+      nnkDotExpr.newTree(F, ident"T"),
+      raises
+    )
+  type X[E] = Future[void].Raising(E)
+  proc f(x: X) = discard
+  var v: Future[void].Raising([ValueError])
+  f(v)
+
+block: # issue #22647
+  proc c0(n: static int): int = 8
+  proc c1(n: static int): int = n div 2
+  proc c2(n: static int): int = n * 2
+  proc c3(n: static int, n2: int): int = n * n2
+  proc `**`(n: static int, n2: int): int = n * n2
+  proc c4(n: int, n2: int): int = n * n2
+
+  type
+    a[N: static int] = object
+      f0 : array[N, int]
+
+    b[N: static int] = object
+      f0 : a[c0(N)]  # does not work
+      f1 : a[c1(N)]  # does not work
+      f2 : a[c2(N)]  # does not work
+      f3 : a[N * 2]  # does not work
+      f4 : a[N]      # works
+      f5: a[c3(N, 2)]
+      f6: a[N ** 2]
+      f7: a[2 * N]
+      f8: a[c4(N, 2)]
+
+  proc p[N: static int](x : a[N]) = discard x.f0[0]
+  template check(x, s: untyped) =
+    p(x)
+    doAssert x is a[s]
+    doAssert x.N == s
+    doAssert typeof(x).N == s
+    doAssert x.f0 == default(array[s, int])
+    doAssert x.f0.len == s
+    proc p2[N: static int](y : a[N]) {.gensym.} =
+      doAssert y is a[s]
+      doAssert y.N == s
+      doAssert typeof(y).N == s
+      doAssert y.f0 == default(array[s, int])
+      doAssert y.f0.len == s
+    p2(x)
+    proc p3(z: typeof(x)) {.gensym.} = discard
+    p3(default(a[s]))
+  proc p[N: static int](x : b[N]) =
+    x.f0.check(8)
+    x.f1.check(2)
+    x.f2.check(8)
+    x.f3.check(8)
+    x.f4.check(4)
+    x.f5.check(8)
+    x.f6.check(8)
+    x.f7.check(8)
+    x.f8.check(8)
+
+  var x: b[4]
+  x.p()
+
+block: # issue #1969
+  type ZeroGenerator = object
+  proc next(g: ZeroGenerator): int = 0
+  # This compiles.
+  type TripleOfInts = tuple
+    a, b, c: typeof(new(ZeroGenerator)[].next)
+  # This raises a compiler error before it's even instantiated.
+  # The `new` proc can't be resolved because `Generator` is not defined.
+  type TripleLike[Generator] = tuple
+    a, b, c: typeof(new(Generator)[].next)
+
+import std/atomics
+
+block: # issue #12720
+  const CacheLineSize = 128
+  type
+    Enqueueable = concept x, type T
+      x is ptr
+      x.next is Atomic[pointer]
+    MyChannel[T: Enqueueable] = object
+      pad: array[CacheLineSize - sizeof(default(T)[]), byte]
+      dummy: typeof(default(T)[])
+
+block: # issue #12714
+  type
+    Enqueueable = concept x, type T
+      x is ptr
+      x.next is Atomic[pointer]
+    MyChannel[T: Enqueueable] = object
+      dummy: type(default(T)[])
+
+block: # issue #24044
+  type ArrayBuf[N: static int, T = byte] = object
+    buf: array[N, T]
+  template maxLen(T: type): int =
+    sizeof(T) * 2
+  type MyBuf[I] = ArrayBuf[maxLen(I)]
+  var v: MyBuf[int]
+
+block: # issue #15959
+  proc my[T](a: T): typeof(a[0]) = discard
+  proc my2[T](a: T): array[sizeof(a[0]), T] = discard
+  proc byLent2[T](a: T): lent type(a[0]) = a[0] # Error: type mismatch: got <T, int literal(0)>
+  proc byLent3[T](a: T): lent typeof(a[0]) = a[0] # ditto
+  proc byLent4[T](a: T): lent[type(a[0])] = a[0] # Error: no generic parameters allowed for lent
+  var x = @[1, 2, 3]
+  doAssert my(x) is int
+  doAssert my2(x) is array[sizeof(int), seq[int]]
+  doAssert byLent2(x) == 1
+  doAssert byLent2(x) is lent int
+  doAssert byLent3(x) == 1
+  doAssert byLent3(x) is lent int
+  doAssert byLent4(x) == 1
+  doAssert byLent4(x) is lent int
+  proc fn[U](a: U): auto = a
+  proc my3[T](a: T, b: typeof(fn(a))) = discard
+  my3(x, x)
+  doAssert not compiles(my3(x, x[0]))
+
+block: # issue #22342, type section version of #22607
+  type GenAlias[isInt: static bool] = (
+    when isInt:
+      int
+    else:
+      float
+  )
+  doAssert GenAlias[true] is int
+  doAssert GenAlias[false] is float
+  proc foo(T: static bool): GenAlias[T] = discard
+  doAssert foo(true) is int
+  doAssert foo(false) is float
+  proc foo[T: static bool](v: var GenAlias[T]) =
+    v += 1
+  var x: int
+  foo[true](x)
+  doAssert not compiles(foo[false](x))
+  foo[true](x)
+  doAssert x == 2
+  var y: float
+  foo[false](y)
+  doAssert not compiles(foo[true](y))
+  foo[false](y)
+  doAssert y == 2
+
+block: # `when`, test no constant semchecks
+  type Foo[T] = (
+    when false:
+      {.error: "bad".}
+    elif defined(neverDefined):
+      {.error: "bad 2".}
+    else:
+      T
+  )
+  var x: Foo[int]
+  type Bar[T] = (
+    when true:
+      T
+    elif defined(js):
+      {.error: "bad".}
+    else:
+      {.error: "bad 2".}
+  )
+  var y: Bar[int]
+
+block: # weird regression
+  type
+    Foo[T] = distinct int
+    Bar[T, U] = distinct int
+  proc foo[T, U](x: static Foo[T], y: static Bar[T, U]): Foo[T] =
+    # signature gives:
+    # Error: cannot instantiate Bar
+    # got: <typedesc[T], U>
+    # but expected: <T, U>
+    x
+  doAssert foo(Foo[int](1), Bar[int, int](2)).int == 1
+
+block: # issue #24090
+  type M[V] = object
+  template y[V](N: type M, v: V): M[V] = default(M[V])
+  proc d(x: int | int, f: M[int] = M.y(0)) = discard
+  d(0, M.y(0))
+  type Foo[T] = object
+    x: typeof(M.y(default(T)))
+  var a: Foo[int]
+  doAssert a.x is M[int]
+  var b: Foo[float]
+  doAssert b.x is M[float]
+  doAssert not (compiles do:
+    type Bar[T] = object
+      x: typeof(M()) # actually fails here immediately
+    var bar: Bar[int])
+  doAssert not (compiles do:
+    type Bar[T] = object
+      x: typeof(default(M))
+    var bar: Bar[int]
+    # gives "undeclared identifier x" because of #24091,
+    # normally it should fail in the line above
+    echo bar.x)
+  proc foo[T: M](x: T = default(T)) = discard x
+  foo[M[int]]()
+  doAssert not compiles(foo())
+
+block: # above but encountered by sigmatch using replaceTypeVarsN
+  type Opt[T] = object
+    x: T
+  proc none[T](x: type Opt, y: typedesc[T]): Opt[T] = discard
+  proc foo[T](x: T, a = Opt.none(int)) = discard
+  foo(1, a = Opt.none(int))
+  foo(1)
+
+block: # real version of above
+  type Opt[T] = object
+    x: T
+  template none(x: type Opt, T: type): Opt[T] = Opt[T]()
+  proc foo[T](x: T, a = Opt.none(int)) = discard
+  foo(1, a = Opt.none(int))
+  foo(1)
+
+block: # issue #20880
+  type
+    Child[n: static int] = object
+      data: array[n, int]
+    Parent[n: static int] = object
+      child: Child[3*n]
+  const n = 3
+  doAssert $(typeof Parent[n*3]()) == "Parent[9]"
+  doAssert $(typeof Parent[1]().child) == "Child[3]"
+  doAssert Parent[1]().child.data.len == 3
+
+{.experimental: "dynamicBindSym".}
+block: # issue #16774
+  type SecretWord = distinct uint64
+  const WordBitWidth = 8 * sizeof(uint64)
+  func wordsRequired(bits: int): int {.compileTime.} =
+    ## Compute the number of limbs required
+    # from the **announced** bit length
+    (bits + WordBitWidth - 1) div WordBitWidth
+  type
+    Curve = enum BLS12_381
+    BigInt[bits: static int] = object
+      limbs: array[bits.wordsRequired, SecretWord]
+  const BLS12_381_Modulus = default(BigInt[381])
+  macro Mod(C: static Curve): untyped =
+    ## Get the Modulus associated to a curve
+    result = bindSym($C & "_Modulus")
+  macro getCurveBitwidth(C: static Curve): untyped =
+    result = nnkDotExpr.newTree(
+      getAST(Mod(C)),
+      ident"bits"
+    )
+  type Fp[C: static Curve] = object
+    ## Finite Fields / Modular arithmetic
+    ## modulo the curve modulus
+    mres: BigInt[getCurveBitwidth(C)]
+  var x: Fp[BLS12_381]
+  doAssert x.mres.limbs.len == wordsRequired(getCurveBitWidth(BLS12_381))
+  # minimized, as if we haven't tested it already:
+  macro makeIntLit(c: static int): untyped =
+    result = newLit(c)
+  type Test[T: static int] = object
+    myArray: array[makeIntLit(T), int]
+  var y: Test[2]
+  doAssert y.myArray.len == 2
+  var z: Test[4]
+  doAssert z.myArray.len == 4
+
+block: # issue #16175
+  type
+    Thing[D: static uint] = object
+      when D == 0:
+        kid: char
+      else:
+        kid: Thing[D-1]
+  var t2 = Thing[3]()
+  doAssert t2.kid is Thing[2.uint]
+  doAssert t2.kid.kid is Thing[1.uint]
+  doAssert t2.kid.kid.kid is Thing[0.uint]
+  doAssert t2.kid.kid.kid.kid is char
+  var s = Thing[1]()
+  doAssert s.kid is Thing[0.uint]
+  doAssert s.kid.kid is char
diff --git a/tests/generics/twrong_explicit_typeargs.nim b/tests/generics/twrong_explicit_typeargs.nim
deleted file mode 100644
index e47b38e99..000000000
--- a/tests/generics/twrong_explicit_typeargs.nim
+++ /dev/null
@@ -1,16 +0,0 @@
-discard """
-  errormsg: "cannot instantiate: 'newImage[string]'"
-  line: 16
-"""
-
-# bug #4084
-type
-  Image[T] = object
-    data: seq[T]
-
-proc newImage[T: int32|int64](w, h: int): ref Image[T] =
-  new(result)
-  result.data = newSeq[T](w * h)
-
-var correct = newImage[int32](320, 200)
-var wrong = newImage[string](320, 200)
diff --git a/tests/generics/twrong_generic_object.nim b/tests/generics/twrong_generic_object.nim
index 442b89ea1..4951f735f 100644
--- a/tests/generics/twrong_generic_object.nim
+++ b/tests/generics/twrong_generic_object.nim
@@ -1,6 +1,6 @@
 discard """
-  errormsg: "cannot instantiate: 'GenericNodeObj[T]'; Maybe generic arguments are missing?"
-  line: 21
+  errormsg: "'Node' is not a concrete type"
+  line: 11
 """
 # bug #2509
 type
diff --git a/tests/constr/a_module.nim b/tests/global/a_module.nim
index 1d3f4848c..1d3f4848c 100644
--- a/tests/constr/a_module.nim
+++ b/tests/global/a_module.nim
diff --git a/tests/global/t15005.nim b/tests/global/t15005.nim
new file mode 100644
index 000000000..6395b1dde
--- /dev/null
+++ b/tests/global/t15005.nim
@@ -0,0 +1,18 @@
+type
+  T = ref object
+    data: string
+
+template foo(): T =
+  var a15005 {.global.}: T
+  once:
+    a15005 = T(data: "hi")
+
+  a15005
+
+proc test() =
+  var b15005 = foo()
+
+  doAssert b15005.data == "hi"
+
+test()
+test()
diff --git a/tests/global/t21896.nim b/tests/global/t21896.nim
new file mode 100644
index 000000000..c7765c4dd
--- /dev/null
+++ b/tests/global/t21896.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "cannot assign local to global variable"
+  line: 7
+"""
+
+proc example(a:int) =
+  let b {.global.} = a
+
+example(1)
diff --git a/tests/global/t3505.nim b/tests/global/t3505.nim
new file mode 100644
index 000000000..437a02ae6
--- /dev/null
+++ b/tests/global/t3505.nim
@@ -0,0 +1,41 @@
+discard """
+cmd: "nim check $options --hints:off $file"
+action: "reject"
+nimout: '''
+t3505.nim(22, 22) Error: cannot assign local to global variable
+t3505.nim(31, 28) Error: cannot assign local to global variable
+t3505.nim(39, 29) Error: cannot assign local to global variable
+
+
+
+
+'''
+"""
+
+
+
+
+
+
+proc foo =
+  let a = 0
+  var b {.global.} = a
+foo()
+
+# issue #5132
+proc initX(it: float): int = 8
+proc initX2(it: int): int = it
+
+proc main() =
+  var f: float
+  var x {.global.} = initX2(initX(f))
+  
+main()
+
+# issue #20866
+proc foo2() =
+  iterator bar() {.closure.} =
+    discard
+  var g {.global.} = rawProc(bar)
+
+foo2()
\ No newline at end of file
diff --git a/tests/global/tglobal2.nim b/tests/global/tglobal2.nim
new file mode 100644
index 000000000..73a575bbd
--- /dev/null
+++ b/tests/global/tglobal2.nim
@@ -0,0 +1,9 @@
+# b.nim
+import a_module
+doAssert foo() == 0
+
+proc hello(x: type) =
+  var s {.global.} = default(x)
+  doAssert s == 0
+
+hello(int)
diff --git a/tests/ic/config.nims b/tests/ic/config.nims
new file mode 100644
index 000000000..a622ec309
--- /dev/null
+++ b/tests/ic/config.nims
@@ -0,0 +1 @@
+--mm:refc

diff --git a/tests/ic/mbaseobj.nim b/tests/ic/mbaseobj.nim
new file mode 100644
index 000000000..0f4e4a90d
--- /dev/null
+++ b/tests/ic/mbaseobj.nim
@@ -0,0 +1,7 @@
+
+type
+  Base* = ref object of RootObj
+    s*: string
+
+method m*(b: Base) {.base.} =
+  echo "Base ", b.s
diff --git a/tests/ic/mcompiletime_counter.nim b/tests/ic/mcompiletime_counter.nim
new file mode 100644
index 000000000..6fc7b3f2a
--- /dev/null
+++ b/tests/ic/mcompiletime_counter.nim
@@ -0,0 +1,15 @@
+
+import std/macros
+import std/macrocache
+
+const myCounter = CacheCounter"myCounter"
+
+proc getUniqueId*(): int {.compileTime.} =
+  inc myCounter
+  result = myCounter.value
+
+static:
+  myCounter.inc(3)
+  assert myCounter.value == 3
+
+
diff --git a/tests/ic/mdefconverter.nim b/tests/ic/mdefconverter.nim
new file mode 100644
index 000000000..d0a23f801
--- /dev/null
+++ b/tests/ic/mdefconverter.nim
@@ -0,0 +1,2 @@
+
+converter toBool*(x: int): bool = x != 0
diff --git a/tests/ic/mimports.nim b/tests/ic/mimports.nim
new file mode 100644
index 000000000..50773e001
--- /dev/null
+++ b/tests/ic/mimports.nim
@@ -0,0 +1,9 @@
+from mimportsb {.all.} import fnb1, hfnb3
+
+proc fn1*(): int = 1
+proc fn2*(): int = 2
+proc hfn3(): int = 3
+proc hfn4(): int = 4
+proc hfn5(): int = 5
+
+export mimportsb.fnb2, hfnb3
diff --git a/tests/ic/mimportsb.nim b/tests/ic/mimportsb.nim
new file mode 100644
index 000000000..3cae925c5
--- /dev/null
+++ b/tests/ic/mimportsb.nim
@@ -0,0 +1,4 @@
+proc fnb1*(): int = 1
+proc fnb2*(): int = 2
+proc hfnb3(): int = 3
+proc hfnb4(): int = 4
diff --git a/tests/ic/tcompiletime_counter.nim b/tests/ic/tcompiletime_counter.nim
new file mode 100644
index 000000000..695a6ec27
--- /dev/null
+++ b/tests/ic/tcompiletime_counter.nim
@@ -0,0 +1,24 @@
+discard """
+  output: '''id 4'''
+"""
+
+import mcompiletime_counter
+
+const intId = getUniqueId()
+
+echo "id ", intId
+
+#!EDIT!#
+
+discard """
+  output: '''id 4 5'''
+"""
+
+import mcompiletime_counter
+
+const
+  intId = getUniqueId()
+  floatId = getUniqueId()
+
+echo "id ", intId, " ", floatId
+
diff --git a/tests/ic/tconverter.nim b/tests/ic/tconverter.nim
new file mode 100644
index 000000000..aecdf4b48
--- /dev/null
+++ b/tests/ic/tconverter.nim
@@ -0,0 +1,18 @@
+discard """
+  output: "yes"
+"""
+
+import mdefconverter
+
+echo "yes"
+
+#!EDIT!#
+
+discard """
+  output: "converted int to bool"
+"""
+
+import mdefconverter
+
+if 4:
+  echo "converted int to bool"
diff --git a/tests/ic/tgenericinst.nim b/tests/ic/tgenericinst.nim
new file mode 100644
index 000000000..3346764f5
--- /dev/null
+++ b/tests/ic/tgenericinst.nim
@@ -0,0 +1,11 @@
+discard """
+  cmd: "nim cpp --incremental:on $file"
+"""
+
+{.emit:"""/*TYPESECTION*/
+#include <iostream>
+  struct Foo { };
+""".}
+
+type Foo {.importcpp.} = object
+echo $Foo() #Notice the generic is instantiate in the this module if not, it wouldnt find Foo
\ No newline at end of file
diff --git a/tests/ic/tgenerics.nim b/tests/ic/tgenerics.nim
index bc5c05f4f..138799e85 100644
--- a/tests/ic/tgenerics.nim
+++ b/tests/ic/tgenerics.nim
@@ -1,6 +1,5 @@
 discard """
   output: "bar"
-  disabled: "true"
 """
 
 import tables
diff --git a/tests/ic/timports.nim b/tests/ic/timports.nim
new file mode 100644
index 000000000..518a689f5
--- /dev/null
+++ b/tests/ic/timports.nim
@@ -0,0 +1,29 @@
+import mimports
+doAssert fn1() == 1
+doAssert not declared(hfn3)
+
+#!EDIT!#
+
+import mimports {.all.}
+doAssert fn1() == 1
+doAssert declared(hfn3)
+doAssert hfn3() == 3
+doAssert mimports.hfn4() == 4
+
+# reexports
+doAssert not declared(fnb1)
+doAssert not declared(hfnb4)
+doAssert fnb2() == 2
+doAssert hfnb3() == 3
+
+#!EDIT!#
+
+from mimports {.all.} import hfn3
+doAssert not declared(fn1)
+from mimports {.all.} as bar import fn1
+doAssert fn1() == 1
+doAssert hfn3() == 3
+doAssert not declared(hfn4)
+doAssert declared(mimports.hfn4)
+doAssert mimports.hfn4() == 4
+doAssert bar.hfn4() == 4
diff --git a/tests/ic/tmethods.nim b/tests/ic/tmethods.nim
new file mode 100644
index 000000000..251f26889
--- /dev/null
+++ b/tests/ic/tmethods.nim
@@ -0,0 +1,28 @@
+discard """
+  output: '''Base abc'''
+"""
+
+import mbaseobj
+
+var c = Base(s: "abc")
+m c
+
+#!EDIT!#
+
+discard """
+  output: '''Base abc
+Inherited abc'''
+"""
+
+import mbaseobj
+
+type
+  Inherited = ref object of Base
+
+method m(i: Inherited) =
+  procCall m(Base i)
+  echo "Inherited ", i.s
+
+var c = Inherited(s: "abc")
+m c
+
diff --git a/tests/ic/tstdlib_import_changed.nim b/tests/ic/tstdlib_import_changed.nim
new file mode 100644
index 000000000..da69a53b5
--- /dev/null
+++ b/tests/ic/tstdlib_import_changed.nim
@@ -0,0 +1,15 @@
+discard """
+  output: '''yes'''
+"""
+
+echo "yes"
+
+#!EDIT!#
+
+discard """
+  output: '''yes2'''
+"""
+
+import std / [monotimes]
+#discard getMonoTime()
+echo "yes2"
diff --git a/tests/implicit/timplicit.nim b/tests/implicit/timplicit.nim
deleted file mode 100644
index bb701249c..000000000
--- a/tests/implicit/timplicit.nim
+++ /dev/null
@@ -1,49 +0,0 @@
-discard """
-  output: '''
-1
-2
-3
-4
-2
-88
-timplicit done
-'''
-"""
-
-
-for x in [1, 2, 3, 4]:
-  echo x
-
-
-type
-  TValue* {.pure, final.} = object of RootObj
-    a: int
-  PValue = ref TValue
-  PPValue = ptr PValue
-
-
-var x: PValue
-new x
-var sp: PPValue = addr x
-
-sp.a = 2
-if sp.a == 2: echo 2  # with sp[].a the error is gone
-
-# Test the new auto-deref a little
-
-{.experimental.}
-
-proc p(x: var int; y: int) = x += y
-
-block:
-  var x: ref int
-  new(x)
-
-  x.p(44)
-
-  var indirect = p
-  x.indirect(44)
-
-  echo x[]
-
-  echo "timplicit done"
diff --git a/tests/import/buzz/m21496.nim b/tests/import/buzz/m21496.nim
new file mode 100644
index 000000000..677324000
--- /dev/null
+++ b/tests/import/buzz/m21496.nim
@@ -0,0 +1 @@
+proc fb*: string = "buzz!"
\ No newline at end of file
diff --git a/tests/import/fizz/m21496.nim b/tests/import/fizz/m21496.nim
new file mode 100644
index 000000000..525b653d6
--- /dev/null
+++ b/tests/import/fizz/m21496.nim
@@ -0,0 +1 @@
+proc fb*: string = "fizz!"
\ No newline at end of file
diff --git a/tests/import/t21496.nim b/tests/import/t21496.nim
new file mode 100644
index 000000000..1a4907b12
--- /dev/null
+++ b/tests/import/t21496.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "ambiguous identifier: 'm21496'"
+"""
+
+import fizz/m21496, buzz/m21496
+
+# bug #21496
+
+discard m21496.fb()
diff --git a/tests/import/t22065.nim b/tests/import/t22065.nim
new file mode 100644
index 000000000..dfd87a107
--- /dev/null
+++ b/tests/import/t22065.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "cannot open file: ./sugar"
+"""
+
+import ./sugar
\ No newline at end of file
diff --git a/tests/import/t22208.nim b/tests/import/t22208.nim
new file mode 100644
index 000000000..b935d751c
--- /dev/null
+++ b/tests/import/t22208.nim
@@ -0,0 +1,6 @@
+import fizz/m21496 as alas
+import buzz/m21496
+
+# bug #21496
+
+doAssert m21496.fb() == "buzz!"
diff --git a/tests/import/t23167.nim b/tests/import/t23167.nim
new file mode 100644
index 000000000..0891ee2af
--- /dev/null
+++ b/tests/import/t23167.nim
@@ -0,0 +1,5 @@
+# bug #23167
+template sharedImport() =
+  import std / os
+
+sharedImport()
diff --git a/tests/importalls/m1.nim b/tests/importalls/m1.nim
new file mode 100644
index 000000000..b6ccbf5da
--- /dev/null
+++ b/tests/importalls/m1.nim
@@ -0,0 +1,70 @@
+import ./m2
+import ./m3 {.all.} as m3
+from ./m3 as m3Bis import nil
+
+doAssert m3h2 == 2
+export m3h2
+
+export m3Bis.m3p1
+
+const foo0* = 2
+const foo1 = bar1
+
+const foo1Aux = 2
+export foo1Aux
+
+doAssert not declared(bar2)
+doAssert not compiles(bar2)
+
+var foo2 = 2
+let foo3 = 2
+
+type Foo4 = enum
+  kg1, kg2
+
+type Foo4b {.pure.} = enum
+  foo4b1, foo4b2
+
+type Foo5 = object
+  z1: string
+  z2: Foo4
+  z3: int
+  z4*: int
+
+proc `z3`*(a: Foo5): auto =
+  a.z3 * 10
+
+proc foo6(): auto = 2
+proc foo6b*(): auto = 2
+template foo7: untyped = 2
+macro foo8(): untyped = discard
+template foo9(a: int) = discard
+
+block:
+  template foo10: untyped = 2
+  type Foo11 = enum
+    kg1b, kg2b
+  proc foo12(): auto = 2
+
+proc initFoo5*(z3: int): Foo5 = Foo5(z3: z3)
+
+func foo13(): auto = 2
+iterator foo14a(): int = discard
+iterator foo14b*(): int = discard
+iterator foo14c(): int {.closure.} = discard
+iterator foo14d(): int {.inline.} = discard
+
+# fwd declare
+proc foo15(): int
+proc foo15(): int = 2
+
+proc foo16*(): int
+proc foo16(): int = 2
+
+proc foo17*(): int
+proc foo17*(): int = 2
+
+# other
+type A1 = distinct int
+type A2 = distinct int
+converter foo18(x: A1): A2 = discard
diff --git a/tests/importalls/m2.nim b/tests/importalls/m2.nim
new file mode 100644
index 000000000..186650f68
--- /dev/null
+++ b/tests/importalls/m2.nim
@@ -0,0 +1,3 @@
+const bar1* = 2
+const bar2 = 2
+const bar3 = 3
diff --git a/tests/importalls/m3.nim b/tests/importalls/m3.nim
new file mode 100644
index 000000000..caeae2a01
--- /dev/null
+++ b/tests/importalls/m3.nim
@@ -0,0 +1,5 @@
+# xxx use below naming convention in other test files: p: public, h: hidden
+const m3p1* = 2
+const m3h2 = 2
+const m3h3 = 3
+const m3h4 = 4
diff --git a/tests/importalls/m4.nim b/tests/importalls/m4.nim
new file mode 100644
index 000000000..77ec65c61
--- /dev/null
+++ b/tests/importalls/m4.nim
@@ -0,0 +1,9 @@
+import ./m3 {.all.}
+import ./m3 as m3b
+export m3b
+export m3h3
+export m3.m3h4
+
+import ./m2 {.all.} as m2b
+export m2b except bar3
+
diff --git a/tests/importalls/mt0.nim b/tests/importalls/mt0.nim
new file mode 100644
index 000000000..154d30ef9
--- /dev/null
+++ b/tests/importalls/mt0.nim
@@ -0,0 +1,9 @@
+import ./m1 as m
+doAssert compiles(foo0)
+doAssert not compiles(foo1)
+doAssert foo6b() == 2
+doAssert m3h2 == 2
+
+var f = initFoo5(z3=3)
+doAssert f.z3 == 30
+doAssert z3(f) == 30
diff --git a/tests/importalls/mt1.nim b/tests/importalls/mt1.nim
new file mode 100644
index 000000000..b7983945c
--- /dev/null
+++ b/tests/importalls/mt1.nim
@@ -0,0 +1,23 @@
+import ./m1 {.all.} as m
+doAssert foo1 == 2
+doAssert m.foo1 == 2
+
+doAssert m.m3h2 == 2
+doAssert m3h2 == 2
+doAssert m.foo1Aux == 2
+doAssert m.m3p1 == 2
+
+## field access
+import std/importutils
+privateAccess(Foo5)
+var x = Foo5(z1: "foo", z2: m.kg1)
+doAssert x.z1 == "foo"
+
+var f0: Foo5
+f0.z3 = 3
+doAssert f0.z3 == 3
+var f = initFoo5(z3=3)
+doAssert f.z3 == 3
+doAssert z3(f) == 30
+doAssert m.z3(f) == 30
+doAssert not compiles(mt1.`z3`(f)) # z3 is an imported symbol
diff --git a/tests/importalls/mt2.nim b/tests/importalls/mt2.nim
new file mode 100644
index 000000000..52edbb69e
--- /dev/null
+++ b/tests/importalls/mt2.nim
@@ -0,0 +1,104 @@
+from ./m1 {.all.} as r1 import foo1
+from ./m1 {.all.} as r2 import foo7
+
+block: # different symbol kinds
+  doAssert foo1 == 2
+  doAssert r1.foo1 == 2
+  doAssert r1.foo2 == 2
+  doAssert compiles(foo1)
+  doAssert compiles(r1.foo2)
+  doAssert not compiles(foo2)
+  doAssert not compiles(m3h2)
+  doAssert r1.foo3 == 2
+
+  block: # enum
+    var a: r1.Foo4
+    let a1 = r1.kg1
+    doAssert a1 == r1.Foo4.kg1
+    type A = r1.Foo4
+    doAssert a1 == A.kg1
+    doAssert not compiles(kg1)
+    doAssert compiles(A.kg1)
+    var witness = false
+    for ai in r1.Foo4:
+      doAssert ai == a
+      doAssert ai == a1
+      witness = true
+      break
+    doAssert witness
+
+  block: # {.pure.} enum
+    var a: r1.Foo4b
+    doAssert not compiles(r1.foo4b1) # because pure
+    doAssert not compiles(foo4b1)
+    let a1 = r1.Foo4b.foo4b1
+    doAssert a1 == a
+    type A = r1.Foo4b
+    doAssert a1 == A.foo4b1
+    var witness = false
+    for ai in A:
+      doAssert ai == a
+      doAssert ai == a1
+      witness = true
+      break
+    doAssert witness
+
+  block: # object
+    doAssert compiles(r1.Foo5)
+    var a: r1.Foo5
+    doAssert compiles(a.z4)
+    doAssert not compiles(a.z3)
+
+  block: # remaining symbol kinds
+    doAssert r1.foo6() == 2
+    doAssert r1.foo6b() == 2
+    doAssert foo7() == 2
+    doAssert r2.foo6b() == 2
+
+    r1.foo8()
+    r1.foo9(1)
+    doAssert r1.foo13() == 2
+    for a in r1.foo14a(): discard
+    for a in r1.foo14b(): discard
+    for a in r1.foo14c(): discard
+    for a in r1.foo14d(): discard
+    doAssert r1.foo15() == 2
+    doAssert r1.foo16() == 2
+    doAssert r1.foo17() == 2
+    doAssert compiles(r1.foo18)
+    doAssert declared(r1.foo18)
+
+  block: # declarations at block scope should not be visible
+    doAssert declared(foo7)
+    doAssert declared(r1.foo6)
+    doAssert not declared(foo10)
+    doAssert not declared(foo6)
+    doAssert not declared(r1.Foo11)
+    doAssert not declared(r1.kg1b)
+    doAssert not declared(r1.foo12)
+    doAssert not compiles(r1.foo12())
+
+## field access
+import std/importutils
+privateAccess(r1.Foo5)
+var x = r1.Foo5(z1: "foo", z2: r1.kg1)
+doAssert x.z1 == "foo"
+
+var f0: r1.Foo5
+f0.z3 = 3
+doAssert f0.z3 == 3
+var f = r1.initFoo5(z3=3)
+doAssert f.z3 == 3
+doAssert r1.z3(f) == 30
+
+import ./m1 as r3
+doAssert not declared(foo2)
+doAssert not declared(r3.foo2)
+
+from ./m1 {.all.} as r4 import nil
+doAssert not declared(foo2)
+doAssert declared(r4.foo2)
+
+from ./m1 {.all.} import nil
+doAssert not declared(foo2)
+doAssert declared(m1.foo2)
diff --git a/tests/importalls/mt3.nim b/tests/importalls/mt3.nim
new file mode 100644
index 000000000..2bd7fd79d
--- /dev/null
+++ b/tests/importalls/mt3.nim
@@ -0,0 +1,12 @@
+import ./m1 {.all.}
+  # D20201209T194412:here keep this as is, without `as`, so that mt8.nim test keeps
+  # checking that the original module symbol for `m1` isn't modified and that
+  # only the alias in `createModuleAlias` is affected.
+doAssert declared(m1.foo1)
+doAssert foo1 == 2
+
+
+doAssert m1.foo1 == 2
+
+doAssert not compiles(mt3.foo0) # foo0 is an imported symbol
+doAssert not compiles(mt3.foo1) # ditto
diff --git a/tests/importalls/mt4.nim b/tests/importalls/mt4.nim
new file mode 100644
index 000000000..cd7d32aad
--- /dev/null
+++ b/tests/importalls/mt4.nim
@@ -0,0 +1,4 @@
+import ./m1 {.all.} except foo1
+doAssert foo2 == 2
+doAssert declared(foo2)
+doAssert not compiles(foo1)
diff --git a/tests/importalls/mt4b.nim b/tests/importalls/mt4b.nim
new file mode 100644
index 000000000..4578bc54c
--- /dev/null
+++ b/tests/importalls/mt4b.nim
@@ -0,0 +1,3 @@
+from ./m1 {.all.} as m2 import nil
+doAssert not compiles(foo1)
+doAssert m2.foo1 == 2
diff --git a/tests/importalls/mt5.nim b/tests/importalls/mt5.nim
new file mode 100644
index 000000000..5c5785af6
--- /dev/null
+++ b/tests/importalls/mt5.nim
@@ -0,0 +1,9 @@
+import ./m1 {.all.} as m2 except foo1
+doAssert foo2 == 2
+doAssert not compiles(foo1)
+doAssert m2.foo1 == 2
+doAssert compiles(m2.foo1)
+
+from system {.all.} as s import ThisIsSystem
+doAssert ThisIsSystem
+doAssert s.ThisIsSystem
diff --git a/tests/importalls/mt6.nim b/tests/importalls/mt6.nim
new file mode 100644
index 000000000..ac6f542b6
--- /dev/null
+++ b/tests/importalls/mt6.nim
@@ -0,0 +1,13 @@
+import ./m1 {.all.} as m2
+doAssert compiles(foo1)
+doAssert compiles(m2.foo1)
+doAssert declared(foo1)
+doAssert declared(m2.foo0) # public: works fine
+
+doAssert m2.foo1 == 2
+doAssert declared(m2.foo1)
+doAssert not declared(m2.nonexistent)
+
+# also tests the quoted `""` import
+import "."/"m1" {.all.} as m1b
+doAssert compiles(m1b.foo1)
diff --git a/tests/importalls/mt7.nim b/tests/importalls/mt7.nim
new file mode 100644
index 000000000..45a664610
--- /dev/null
+++ b/tests/importalls/mt7.nim
@@ -0,0 +1,14 @@
+include ./m1
+doAssert compiles(foo1)
+doAssert compiles(mt7.foo1)
+doAssert declared(foo1)
+doAssert declared(mt7.foo1)
+doAssert declared(mt7.foo0)
+
+var f0: Foo5
+f0.z3 = 3
+doAssert f0.z3 == 3
+var f = initFoo5(z3=3)
+doAssert f.z3 == 3
+doAssert mt7.z3(f) == 30
+doAssert z3(f) == 30
diff --git a/tests/importalls/mt8.nim b/tests/importalls/mt8.nim
new file mode 100644
index 000000000..f484e7b01
--- /dev/null
+++ b/tests/importalls/mt8.nim
@@ -0,0 +1,23 @@
+#[
+test multiple imports
+]#
+
+{.warning[UnusedImport]: off.}
+import ./m1, m2 {.all.}, ./m3 {.all.}
+  # make sure this keeps using `import ./m1` without as.
+
+# m1 is regularly imported
+doAssert declared(m1.foo0)
+doAssert declared(foo0)
+
+doAssert not declared(m1.foo1)
+  # if we didn't call `createModuleAlias` even for `import f1 {.all.}`,
+  # this would fail, see D20201209T194412.
+
+# m2
+doAssert declared(m2.bar2)
+doAssert declared(bar2)
+
+# m3
+doAssert declared(m3.m3h2)
+doAssert declared(m3h2)
diff --git a/tests/importalls/mt9.nim b/tests/importalls/mt9.nim
new file mode 100644
index 000000000..42d48ecbd
--- /dev/null
+++ b/tests/importalls/mt9.nim
@@ -0,0 +1,12 @@
+# tests re-export of a module with import {.all.}
+
+import ./m4
+
+doAssert m3p1 == 2
+doAssert not declared(m3h2)
+doAssert m3h3 == 3
+doAssert m3h4 == 4
+
+doAssert bar1 == 2
+doAssert bar2 == 2
+doAssert not declared(bar3)
diff --git a/tests/importalls/tmain2.nim b/tests/importalls/tmain2.nim
new file mode 100644
index 000000000..596f0f135
--- /dev/null
+++ b/tests/importalls/tmain2.nim
@@ -0,0 +1,7 @@
+discard """
+joinable: false # for clarity, but not necessary
+"""
+
+{.warning[UnusedImport]: off.}
+# only import `mt*.nim` here; these depend on `m*.nim`
+import "."/[mt0,mt1,mt2,mt3,mt4,mt4b,mt5,mt6,mt7,mt8,mt9]
diff --git a/tests/init/tcompiles.nim b/tests/init/tcompiles.nim
new file mode 100644
index 000000000..67e17b241
--- /dev/null
+++ b/tests/init/tcompiles.nim
@@ -0,0 +1,101 @@
+discard """
+  matrix: "--warningAsError:ProveInit --warningAsError:Uninit"
+"""
+
+{.experimental: "strictdefs".}
+
+type Test = object
+  id: int
+
+proc foo {.noreturn.} = discard
+
+block:
+  proc test(x: bool): Test =
+    if x:
+      foo()
+    else:
+      foo()
+
+block:
+  proc test(x: bool): Test =
+    if x:
+      result = Test()
+    else:
+      foo()
+
+  discard test(true)
+
+block:
+  proc test(x: bool): Test =
+    if x:
+      result = Test()
+    else:
+      return Test()
+
+  discard test(true)
+
+block:
+  proc test(x: bool): Test =
+    if x:
+      return Test()
+    else:
+      return Test()
+
+  discard test(true)
+
+block:
+  proc test(x: bool): Test =
+    if x:
+      result = Test()
+    else:
+      result = Test()
+      return
+
+  discard test(true)
+
+block:
+  proc test(x: bool): Test =
+    if x:
+      result = Test()
+      return
+    else:
+      raise newException(ValueError, "unreachable")
+
+  discard test(true)
+
+# bug #21615
+# bug #16735
+
+block:
+  type Test {.requiresInit.} = object
+    id: int
+
+  proc bar(): int =
+    raise newException(CatchableError, "error")
+
+  proc test(): Test =
+    raise newException(CatchableError, "")
+
+  template catchError(body) =
+    var done = false
+    try:
+      body
+    except CatchableError:
+      done = true
+    doAssert done
+
+  catchError:
+    echo test()
+
+  catchError:
+    echo bar()
+
+block:
+  proc foo(x: ptr int) =
+    discard
+
+  proc main =
+    var s: int
+    foo(addr s)
+
+  main()
diff --git a/tests/init/tinitchecks_v2.nim b/tests/init/tinitchecks_v2.nim
new file mode 100644
index 000000000..f7716bcca
--- /dev/null
+++ b/tests/init/tinitchecks_v2.nim
@@ -0,0 +1,83 @@
+discard """
+cmd: "nim check $file"
+action: "compile"
+"""
+
+{.experimental: "strictDefs".}
+
+proc myopen(f: out File; s: string): bool =
+  f = default(File)
+  result = false
+
+proc main =
+  var f: File
+  if myopen(f, "aarg"):
+    f.close
+
+proc invalid =
+  var s: seq[string]
+  s.add "abc" #[tt.Warning
+  ^ use explicit initialization of 's' for clarity [Uninit] ]#
+
+proc valid =
+  var s: seq[string] = @[]
+  s.add "abc" # valid!
+
+main()
+invalid()
+valid()
+
+proc branchy(cond: bool) =
+  var s: seq[string]
+  if cond:
+    s = @["y"]
+  else:
+    s = @[]
+  s.add "abc" # valid!
+
+branchy true
+
+proc p(x: out int; y: out string; cond: bool) = #[tt.Warning
+                   ^ Cannot prove that 'y' is initialized. This will become a compile time error in the future. [ProveInit] ]#
+  x = 4
+  if cond:
+    y = "abc"
+  # error: not every path initializes 'y'
+
+var gl: int
+var gs: string
+p gl, gs, false
+
+proc canRaise(x: int): int =
+  result = x
+  raise newException(ValueError, "wrong")
+
+proc currentlyValid(x: out int; y: out string; cond: bool) =
+  x = canRaise(45)
+  y = "abc" # <-- error: not every path initializes 'y'
+
+currentlyValid gl, gs, false
+
+block: # previously effects/toutparam
+  proc gah[T](x: out T) =
+    x = 3
+
+  proc arr1 =
+    var a: array[2, int]
+    var x: int
+    gah(x)
+    a[0] = 3
+    a[x] = 3
+    echo x
+
+  arr1()
+
+  proc arr2 =
+    var a: array[2, int]
+    var x: int
+    a[0] = 3
+    a[x] = 3 #[tt.Warning
+      ^ use explicit initialization of 'x' for clarity [Uninit] ]#
+    echo x
+
+  arr2()
diff --git a/tests/init/tlet.nim b/tests/init/tlet.nim
new file mode 100644
index 000000000..e32bedb18
--- /dev/null
+++ b/tests/init/tlet.nim
@@ -0,0 +1,55 @@
+{.experimental: "strictDefs".}
+
+proc bar(x: out string) =
+  x = "abc"
+
+template moe = # bug #21043
+  try:
+    discard
+  except ValueError as e:
+    echo(e.msg)
+
+template moe0 {.dirty.} = # bug #21043
+  try:
+    discard
+  except ValueError as e:
+    echo(e.msg)
+
+proc foo() =
+  block:
+    let x: string
+    if true:
+      x = "abc"
+    else:
+      x = "def"
+    doAssert x == "abc"
+  block:
+    let y: string
+    bar(y)
+    doAssert y == "abc"
+  block:
+    let x: string
+    if true:
+      x = "abc"
+      discard "abc"
+    else:
+      x = "def"
+      discard "def"
+    doAssert x == "abc"
+  block: #
+    let x {.used.} : int
+  block: #
+    let x: float
+    x = 1.234
+    doAssert x == 1.234
+
+  block:
+    try:
+      discard
+    except ValueError as e:
+      echo(e.msg)
+  moe()
+  moe0()
+
+static: foo()
+foo()
diff --git a/tests/init/tlet_uninit2.nim b/tests/init/tlet_uninit2.nim
new file mode 100644
index 000000000..174aa28f7
--- /dev/null
+++ b/tests/init/tlet_uninit2.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "'let' symbol requires an initialization"
+"""
+
+let x: int
\ No newline at end of file
diff --git a/tests/init/tlet_uninit3.nim b/tests/init/tlet_uninit3.nim
new file mode 100644
index 000000000..cb786f8c8
--- /dev/null
+++ b/tests/init/tlet_uninit3.nim
@@ -0,0 +1,24 @@
+discard """
+  cmd: "nim check $file"
+  action: "reject"
+  nimout: '''
+tlet_uninit3.nim(13, 5) Error: 'let' symbol requires an initialization
+tlet_uninit3.nim(19, 5) Error: 'x' cannot be assigned to
+tlet_uninit3.nim(23, 11) Error: 'let' symbol requires an initialization
+'''
+"""
+
+{.experimental: "strictDefs".}
+
+let global {.used.}: int
+
+proc foo() =
+  block:
+    let x: int
+    x = 13
+    x = 14
+
+  block:
+    let x: int
+    doAssert x == 0
+foo()
diff --git a/tests/init/tlet_uninit4.nim b/tests/init/tlet_uninit4.nim
new file mode 100644
index 000000000..c57d15ff8
--- /dev/null
+++ b/tests/init/tlet_uninit4.nim
@@ -0,0 +1,12 @@
+discard """
+  errormsg: "type mismatch: got <string>"
+"""
+
+{.experimental: "strictDefs".}
+
+proc foo(x: var string) =
+  echo x
+
+proc bar() =
+  let x: string
+  foo(x)
diff --git a/tests/init/toutparam_subtype.nim b/tests/init/toutparam_subtype.nim
new file mode 100644
index 000000000..3597f1459
--- /dev/null
+++ b/tests/init/toutparam_subtype.nim
@@ -0,0 +1,24 @@
+discard """
+cmd: "nim check $file"
+action: "compile"
+errormsg: "type mismatch: got <Subclass[system.int]>"
+line: 21
+"""
+
+{.experimental: "strictDefs".}
+
+type
+  Superclass[T] = object of RootObj
+    a: T
+  Subclass[T] = object of Superclass[T]
+    s: string
+
+proc init[T](x: out Superclass[T]) =
+  x = Superclass(a: 8)
+
+proc subtypeCheck =
+  var v: Subclass[int]
+  init(v)
+  echo v.s # the 's' field was never initialized!
+
+subtypeCheck()
diff --git a/tests/init/toutparams.nim b/tests/init/toutparams.nim
new file mode 100644
index 000000000..590768599
--- /dev/null
+++ b/tests/init/toutparams.nim
@@ -0,0 +1,14 @@
+discard """
+  matrix: "--warningAsError:ProveInit"
+"""
+
+{.experimental: "strictdefs".}
+
+proc foo(x: out int) =
+  x = 1
+
+proc bar(x: out int) =
+  foo(x)
+
+var s: int
+bar(s)
diff --git a/tests/init/tproveinit.nim b/tests/init/tproveinit.nim
new file mode 100644
index 000000000..c9f688309
--- /dev/null
+++ b/tests/init/tproveinit.nim
@@ -0,0 +1,18 @@
+discard """
+  joinable: false
+"""
+
+{.warningAsError[ProveInit]:on.}
+template main() =
+  proc fn(): var int =
+    discard
+  discard fn()
+doAssert not compiles(main())
+
+# bug #9901
+import std/[sequtils, times]
+proc parseMyDates(line: string): DateTime =
+  result = parse(line, "yyyy-MM-dd")
+var dateStrings = @["2018-12-01", "2018-12-02", "2018-12-03"]
+var parsed = dateStrings.map(parseMyDates)
+discard parsed
diff --git a/tests/init/treturns.nim b/tests/init/treturns.nim
new file mode 100644
index 000000000..18cebe0b1
--- /dev/null
+++ b/tests/init/treturns.nim
@@ -0,0 +1,106 @@
+{.experimental: "strictdefs".}
+
+type Test = object
+  id: int
+
+proc foo {.noreturn.} = discard
+
+proc test1(): Test =
+  if true: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+    return Test()
+  else:
+    return
+
+proc test0(): Test =
+  if true: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+    return
+  else:
+    foo()
+
+proc test2(): Test =
+  if true: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+    return
+  else:
+    return
+
+proc test3(): Test =
+  if true: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+    return
+  else:
+    return Test()
+
+proc test4(): Test =
+  if true: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+    return
+  else:
+    result = Test()
+    return
+
+proc test5(x: bool): Test =
+  case x: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+  of true:
+    return
+  else:
+    return Test()
+
+proc test6(x: bool): Test =
+  case x: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+  of true:
+    return
+  else:
+    return
+
+proc test7(x: bool): Test =
+  case x: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+  of true:
+    return
+  else:
+    discard
+
+proc test8(x: bool): Test =
+  case x: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+  of true:
+    discard
+  else:
+    raise
+
+proc hasImportStmt(): bool =
+  if false: #[tt.Warning
+  ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+    return true
+  else:
+    discard
+
+discard hasImportStmt()
+
+block:
+  proc hasImportStmt(): bool =
+    if false: #[tt.Warning
+    ^ Cannot prove that 'result' is initialized. This will become a compile time error in the future. [ProveInit]]#
+      return true
+    else:
+      return
+
+  discard hasImportStmt()
+
+block:
+  block:
+    proc foo(x: var int) =
+      discard
+
+    proc main =
+      var s: int
+      foo(s)#[tt.Warning
+          ^ use explicit initialization of 's' for clarity [Uninit]]#
+
+    main()
+
diff --git a/tests/init/tuninit1.nim b/tests/init/tuninit1.nim
index 67c0c4d8b..ac3007e8d 100644
--- a/tests/init/tuninit1.nim
+++ b/tests/init/tuninit1.nim
@@ -1,11 +1,10 @@
 discard """
-  nimout: "Warning: 'y' might not have been initialized [Uninit]"
-  line:34
+  nimout: "tuninit1.nim(34, 11) Warning: use explicit initialization of 'y' for clarity [Uninit]"
   action: compile
 """
 
 import strutils
-
+{.experimental: "strictDefs".}
 {.warning[Uninit]:on.}
 
 proc p =
diff --git a/tests/int/t1.nim b/tests/int/t1.nim
new file mode 100644
index 000000000..6e5cdc8d4
--- /dev/null
+++ b/tests/int/t1.nim
@@ -0,0 +1,61 @@
+discard """
+  targets: "c cpp"
+"""
+
+doAssert typeOf(1.int64 + 1.int) is int64
+doAssert typeOf(1.uint64 + 1.uint) is uint64
+doAssert int64 is SomeNumber
+doAssert int64 is (SomeNumber and not(uint32|uint64|uint|int))
+doAssert int64 is (not(uint32|uint64|uint|int))
+doAssert int isnot int64
+doAssert int64 isnot int
+var myInt16 = 5i16
+var myInt: int
+doAssert typeOf(myInt16 + 34) is int16    # of type `int16`
+doAssert typeOf(myInt16 + myInt) is int   # of type `int`
+doAssert typeOf(myInt16 + 2i32) is int32  # of type `int32`
+doAssert int32 isnot int64
+doAssert int32 isnot int
+
+block: # bug #23947
+  template foo =
+    let test_u64 : uint64 =   0xFF07.uint64
+    let test_u8  : uint8  = test_u64.uint8
+        # Error: illegal conversion from '65287' to '[0..255]'
+    doAssert test_u8 == 7
+
+  static: foo()
+  foo()
+
+block:
+  # bug #22085
+  const
+    x = uint32(uint64.high) # vm error
+    u = uint64.high
+    v = uint32(u) # vm error
+
+  let
+    z = uint64.high
+    y = uint32(z)  # runtime ok
+
+  let
+    w = uint32(uint64.high)  # semfold error
+
+  doAssert x == w
+  doAssert v == y
+
+  # bug #14522
+  doAssert 0xFF000000_00000000.uint64 == 18374686479671623680'u64
+
+block: # bug #23954
+  let testRT_u8 : uint8 = 0x107.uint8
+  doAssert testRT_u8 == 7
+  const testCT_u8 : uint8 = 0x107.uint8
+  doAssert testCT_u8 == 7
+
+block: # issue #24104
+  type P = distinct uint  # uint, uint8, uint16, uint32, uint64 
+  let v = 0.P
+  case v
+  of 0.P: discard
+  else:   discard
diff --git a/tests/arithm/tarithm.nim b/tests/int/tarithm.nim
index fcb78bd7a..d0943d225 100644
--- a/tests/arithm/tarithm.nim
+++ b/tests/int/tarithm.nim
@@ -12,7 +12,9 @@ int32
 4294967295
 2
 0
+tUnsignedOps OK
 '''
+nimout: "tUnsignedOps OK"
 """
 
 import typetraits
@@ -20,10 +22,10 @@ import typetraits
 
 block tand:
   # bug #5216
-  echo(name type((0x0A'i8 and 0x7F'i32) shl 7'i32))
+  echo(name typeof((0x0A'i8 and 0x7F'i32) shl 7'i32))
 
   let i8 = 0x0A'i8
-  echo(name type((i8 and 0x7F'i32) shl 7'i32))
+  echo(name typeof((i8 and 0x7F'i32) shl 7'i32))
 
   echo((0x0A'i8 and 0x7F'i32) shl 7'i32)
 
@@ -167,3 +169,19 @@ block tissue12177:
   echo(a - b)
   echo(a * b)
   echo(a div b)
+
+block tUnsignedOps:
+  proc testUnsignedOps() =
+    let a: int8 = -128
+    let b: int8 = 127
+
+    doAssert b +% 1 == -128
+    doAssert b -% -1 == -128
+    doAssert b *% 2 == -2
+    doAssert a /% 4 == 32
+    doAssert a %% 7 == 2
+    echo "tUnsignedOps OK"
+
+  testUnsignedOps()
+  static:
+    testUnsignedOps()
diff --git a/tests/arithm/tashr.nim b/tests/int/tashr.nim
index aeb3b6843..aeb3b6843 100644
--- a/tests/arithm/tashr.nim
+++ b/tests/int/tashr.nim
diff --git a/tests/int/tdiv.nim b/tests/int/tdiv.nim
new file mode 100644
index 000000000..5d8eed84d
--- /dev/null
+++ b/tests/int/tdiv.nim
@@ -0,0 +1,19 @@
+discard """
+  targets: "c js"
+"""
+
+
+block divUint64:
+  proc divTest() =
+    let x1 = 12'u16
+    let y = x1 div 5'u16
+    let x2 = 1345567'u32
+    let z = x2 div 5'u32
+    let a = 1345567'u64 div uint64(x1)
+    doAssert y == 2
+    doAssert z == 269113
+    doAssert a == 112130
+
+  static: divTest()
+  divTest()
+
diff --git a/tests/misc/tints.nim b/tests/int/tints.nim
index fa3eb42cb..773e8ccad 100644
--- a/tests/misc/tints.nim
+++ b/tests/int/tints.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "; --backend:js --jsbigint64:off -d:nimStringHash2; --backend:js --jsbigint64:on"
   output: '''
 0 0
 0 0
@@ -6,6 +7,9 @@ Success'''
 """
 # Test the different integer operations
 
+
+import std/private/jsutils
+
 var testNumber = 0
 
 template test(opr, a, b, c: untyped): untyped =
@@ -23,28 +27,37 @@ template test(opr, a, b, c: untyped): untyped =
 
 test(`+`, 12'i8, -13'i16, -1'i16)
 test(`shl`, 0b11, 0b100, 0b110000)
+whenJsNoBigInt64: discard
+do:
+  test(`shl`, 0b11'i64, 0b100'i64, 0b110000'i64)
 when not defined(js):
+  # mixed type shr needlessly complicates codegen with bigint
+  # and thus is not yet supported in JS for 64 bit ints
   test(`shl`, 0b11'i32, 0b100'i64, 0b110000'i64)
 test(`shl`, 0b11'i32, 0b100'i32, 0b110000'i32)
 
 test(`or`, 0xf0f0'i16, 0x0d0d'i16, 0xfdfd'i16)
 test(`and`, 0xf0f0'i16, 0xfdfd'i16, 0xf0f0'i16)
 
-when not defined(js):
+whenJsNoBigInt64: discard
+do:
   test(`shr`, 0xffffffffffffffff'i64, 0x4'i64, 0xffffffffffffffff'i64)
 test(`shr`, 0xffff'i16, 0x4'i16, 0xffff'i16)
 test(`shr`, 0xff'i8, 0x4'i8, 0xff'i8)
 
-when not defined(js):
+whenJsNoBigInt64: discard
+do:
   test(`shr`, 0xffffffff'i64, 0x4'i64, 0x0fffffff'i64)
 test(`shr`, 0xffffffff'i32, 0x4'i32, 0xffffffff'i32)
 
-when not defined(js):
+whenJsNoBigInt64: discard
+do:
   test(`shl`, 0xffffffffffffffff'i64, 0x4'i64, 0xfffffffffffffff0'i64)
 test(`shl`, 0xffff'i16, 0x4'i16, 0xfff0'i16)
 test(`shl`, 0xff'i8, 0x4'i8, 0xf0'i8)
 
-when not defined(js):
+whenJsNoBigInt64: discard
+do:
   test(`shl`, 0xffffffff'i64, 0x4'i64, 0xffffffff0'i64)
 test(`shl`, 0xffffffff'i32, 0x4'i32, 0xfffffff0'i32)
 
@@ -77,5 +90,61 @@ block: # Casts to uint
 
   testCast(-5'i32, uint8, 251'u8)
 
+# issue #7174
+let c = 1'u
+let val = c > 0
+doAssert val
+
+block: # bug #6752
+  when not defined(js) or (defined(js) and compileOption("jsbigint64")):
+    let x = 711127'i64
+    doAssert x * 86400'i64 == 61441372800'i64
+
+block: # bug #17604
+  let a = 2147483648'u
+  doAssert (a and a) == a
+  doAssert (a or 0) == a
+
+block: # bitwise not
+  let
+    z8 = 0'u8
+    z16 = 0'u16
+    z32 = 0'u32
+    z64 = 0'u64
+  doAssert (not z8) == uint8.high
+  doAssert (not z16) == uint16.high
+  doAssert (not z32) == uint32.high
+  when not defined(js) or (defined(js) and compileOption("jsbigint64")):
+    doAssert (not z64) == uint64.high
+
+block: # shl
+  let i8 = int8.high
+  let i16 = int16.high
+  let i32 = int32.high
+  let i64 = int64.high
+  doAssert i8 shl 1 == -2
+  doAssert i8 shl 2 == -4
+  doAssert i16 shl 1 == -2
+  doAssert i16 shl 2 == -4
+  doAssert i32 shl 1 == -2
+  doAssert i32 shl 2 == -4
+  when not defined(js) or (defined(js) and compileOption("jsbigint64")):
+    doAssert i64 shl 1 == -2
+    doAssert i64 shl 2 == -4
+
+  let u8 = uint8.high
+  let u16 = uint16.high
+  let u32 = uint32.high
+  let u64 = uint64.high
+  doAssert u8 shl 1 == u8 - 1
+  doAssert u16 shl 1 == u16 - 1
+  doAssert u32 shl 1 == u32 - 1
+  when not defined(js) or (defined(js) and compileOption("jsbigint64")):
+    doAssert u64 shl 1 == u64 - 1
+
+block: # bug #23378
+  var neg = -1  # prevent compile-time evaluation
+  let n = abs BiggestInt neg
+  doAssert n == 1
 
 echo("Success") #OUT Success
diff --git a/tests/misc/tunsigned64mod.nim b/tests/int/tunsigned64mod.nim
index ca3286df3..ca3286df3 100644
--- a/tests/misc/tunsigned64mod.nim
+++ b/tests/int/tunsigned64mod.nim
diff --git a/tests/misc/tunsignedcmp.nim b/tests/int/tunsignedcmp.nim
index 11b67ac5f..11b67ac5f 100644
--- a/tests/misc/tunsignedcmp.nim
+++ b/tests/int/tunsignedcmp.nim
diff --git a/tests/int/tunsignedcomp.nim b/tests/int/tunsignedcomp.nim
new file mode 100644
index 000000000..970c4ae9d
--- /dev/null
+++ b/tests/int/tunsignedcomp.nim
@@ -0,0 +1,136 @@
+discard """
+  output: ''''''
+  disabled: "true"
+"""
+
+# All operations involving uint64 are commented out
+# as they're not yet supported.
+# All other operations are handled by implicit conversions from uints to ints
+# uint64 could be supported but would need special implementation of the operators
+
+# unsigned < signed
+
+doAssert 10'u8 < 20'i8
+doAssert 10'u8 < 20'i16
+doAssert 10'u8 < 20'i32
+doAssert 10'u8 < 20'i64
+
+doAssert 10'u16 < 20'i8
+doAssert 10'u16 < 20'i16
+doAssert 10'u16 < 20'i32
+doAssert 10'u16 < 20'i64
+
+doAssert 10'u32 < 20'i8
+doAssert 10'u32 < 20'i16
+doAssert 10'u32 < 20'i32
+doAssert 10'u32 < 20'i64
+
+# doAssert 10'u64 < 20'i8
+# doAssert 10'u64 < 20'i16
+# doAssert 10'u64 < 20'i32
+# doAssert 10'u64 < 20'i64
+
+# signed < unsigned
+doAssert 10'i8 < 20'u8
+doAssert 10'i8 < 20'u16
+doAssert 10'i8 < 20'u32
+# doAssert 10'i8 < 20'u64
+
+doAssert 10'i16 < 20'u8
+doAssert 10'i16 < 20'u16
+doAssert 10'i16 < 20'u32
+# doAssert 10'i16 < 20'u64
+
+doAssert 10'i32 < 20'u8
+doAssert 10'i32 < 20'u16
+doAssert 10'i32 < 20'u32
+# doAssert 10'i32 < 20'u64
+
+doAssert 10'i64 < 20'u8
+doAssert 10'i64 < 20'u16
+doAssert 10'i64 < 20'u32
+# doAssert 10'i64 < 20'u64
+
+# unsigned <= signed
+doAssert 10'u8 <= 20'i8
+doAssert 10'u8 <= 20'i16
+doAssert 10'u8 <= 20'i32
+doAssert 10'u8 <= 20'i64
+
+doAssert 10'u16 <= 20'i8
+doAssert 10'u16 <= 20'i16
+doAssert 10'u16 <= 20'i32
+doAssert 10'u16 <= 20'i64
+
+doAssert 10'u32 <= 20'i8
+doAssert 10'u32 <= 20'i16
+doAssert 10'u32 <= 20'i32
+doAssert 10'u32 <= 20'i64
+
+# doAssert 10'u64 <= 20'i8
+# doAssert 10'u64 <= 20'i16
+# doAssert 10'u64 <= 20'i32
+# doAssert 10'u64 <= 20'i64
+
+# signed <= unsigned
+doAssert 10'i8 <= 20'u8
+doAssert 10'i8 <= 20'u16
+doAssert 10'i8 <= 20'u32
+# doAssert 10'i8 <= 20'u64
+
+doAssert 10'i16 <= 20'u8
+doAssert 10'i16 <= 20'u16
+doAssert 10'i16 <= 20'u32
+# doAssert 10'i16 <= 20'u64
+
+doAssert 10'i32 <= 20'u8
+doAssert 10'i32 <= 20'u16
+doAssert 10'i32 <= 20'u32
+# doAssert 10'i32 <= 20'u64
+
+doAssert 10'i64 <= 20'u8
+doAssert 10'i64 <= 20'u16
+doAssert 10'i64 <= 20'u32
+# doAssert 10'i64 <= 20'u64
+
+# signed == unsigned
+doAssert 10'i8 == 10'u8
+doAssert 10'i8 == 10'u16
+doAssert 10'i8 == 10'u32
+# doAssert 10'i8 == 10'u64
+
+doAssert 10'i16 == 10'u8
+doAssert 10'i16 == 10'u16
+doAssert 10'i16 == 10'u32
+# doAssert 10'i16 == 10'u64
+
+doAssert 10'i32 == 10'u8
+doAssert 10'i32 == 10'u16
+doAssert 10'i32 == 10'u32
+# doAssert 10'i32 == 10'u64
+
+doAssert 10'i64 == 10'u8
+doAssert 10'i64 == 10'u16
+doAssert 10'i64 == 10'u32
+# doAssert 10'i64 == 10'u64
+
+# unsigned == signed
+doAssert 10'u8 == 10'i8
+doAssert 10'u8 == 10'i16
+doAssert 10'u8 == 10'i32
+# doAssert 10'u8 == 10'i64
+
+doAssert 10'u16 == 10'i8
+doAssert 10'u16 == 10'i16
+doAssert 10'u16 == 10'i32
+# doAssert 10'u16 == 10'i64
+
+doAssert 10'u32 == 10'i8
+doAssert 10'u32 == 10'i16
+doAssert 10'u32 == 10'i32
+# doAssert 10'u32 == 10'i64
+
+# doAssert 10'u64 == 10'i8
+# doAssert 10'u64 == 10'i16
+# doAssert 10'u64 == 10'i32
+# doAssert 10'u64 == 10'i64
diff --git a/tests/int/tunsignedconv.nim b/tests/int/tunsignedconv.nim
new file mode 100644
index 000000000..6c73521d3
--- /dev/null
+++ b/tests/int/tunsignedconv.nim
@@ -0,0 +1,115 @@
+discard """
+  targets: "c cpp js"
+"""
+
+# Tests unsigned literals and implicit conversion between uints and ints
+
+var h8: uint8 = 128
+var h16: uint16 = 32768
+var h32: uint32 = 2147483648'u32
+var h64: uint64 = 9223372036854775808'u64
+var foobar: uint64 = 9223372036854775813'u64 # Issue 728
+
+var v8: uint8 = 10
+var v16: uint16 = 10
+var v32: uint32 = 10
+var v64: uint64 = 10
+
+# u8 + literal produces u8:
+var a8: uint8 = v8 + 10
+var a16: uint16 = v16 + 10
+
+when false:
+  var d8  = v8 + 10'i8
+  var d16 = v8 + 10'i16
+  var d32 = v8 + 10'i32
+
+when false:
+  # these don't work yet because unsigned.nim is stupid. XXX We need to fix this.
+  var f8  = v16 + 10'u8
+  var f16 = v16 + 10'u16
+  var f32 = v16 + 10'u32
+
+  var g8  = v32 + 10'u8
+  var g16 = v32 + 10'u16
+  var g32 = v32 + 10'u32
+
+var ar: array[0..20, int]
+var n8 = ar[v8]
+var n16 = ar[v16]
+var n32 = ar[v32]
+var n64 = ar[v64]
+
+
+block t4176:
+  var yyy: uint8 = 0
+  yyy = yyy - 127
+  doAssert type(yyy) is uint8
+
+# bug #13661
+
+proc fun(): uint = cast[uint](-1)
+const x0 = fun()
+
+doAssert typeof(x0) is uint
+
+discard $x0
+
+# bug #13671
+
+const x1 = cast[uint](-1)
+discard $(x1,)
+
+# bug #13698
+let n2: csize_t = 1
+doAssert $n2.int32 == "1"
+
+# bug #14616
+
+let limit = 1'u64
+
+let rangeVar = 0'u64 ..< limit
+
+when not defined(gcRefc):
+  doAssert repr(rangeVar) == """0 .. 0""", repr(rangeVar)
+
+# bug #15210
+
+let a3 = not 0'u64
+var success = false
+try:
+  discard a3.int64
+except RangeDefect:
+  success = true
+
+doAssert success, "conversion should fail at runtime"
+
+template main() =
+  # xxx move all tests under here so it gets tested in CT and RT
+  block: # bug #17572
+    type T = distinct uint64
+    func f(x: uint64): auto =
+      let a = T(x)
+      (x, a.uint64)
+    const x = 1'u64 shl 63 or 7
+    const b = T(x)
+    doAssert b.uint64 == 9223372036854775815'u64
+    doAssert $b.uint64 == "9223372036854775815"
+    doAssert f(x) == (9223372036854775815'u64, 9223372036854775815'u64)
+
+static: main()
+main()
+
+block:
+  let a = uint64.high
+  let b = uint32.high
+
+  doAssert a.uint64 == a
+  doAssert a.uint32 == uint32.high
+  doAssert a.uint16 == uint16.high
+  doAssert a.uint8 == uint8.high
+
+  doAssert b.uint64 == b
+  doAssert b.uint32 == b
+  doAssert b.uint16 == uint16.high
+  doAssert b.uint8 == uint8.high
diff --git a/tests/misc/tunsignedinc.nim b/tests/int/tunsignedinc.nim
index 6d1b627d6..9392f1b74 100644
--- a/tests/misc/tunsignedinc.nim
+++ b/tests/int/tunsignedinc.nim
@@ -1,8 +1,8 @@
 
 block: # bug #2427
   var x = 0'u8
-  dec x # OverflowError
-  x -= 1 # OverflowError
+  dec x # OverflowDefect
+  x -= 1 # OverflowDefect
   x = x - 1 # No error
 
   doAssert(x == 253'u8)
@@ -32,3 +32,9 @@ block t4175:
   const j = 0u - 1u
   doAssert i == j
   doAssert j + 1u == 0u
+
+block: # https://forum.nim-lang.org/t/12465#76998
+  var a: int = 1
+  var x: uint8 = 1
+  a.inc(x)   # Error: type mismatch
+  doAssert a == 2
diff --git a/tests/misc/tunsignedmisc.nim b/tests/int/tunsignedmisc.nim
index b2a3849cf..b2a3849cf 100644
--- a/tests/misc/tunsignedmisc.nim
+++ b/tests/int/tunsignedmisc.nim
diff --git a/tests/int/twrongexplicitvarconv.nim b/tests/int/twrongexplicitvarconv.nim
new file mode 100644
index 000000000..79f770e8e
--- /dev/null
+++ b/tests/int/twrongexplicitvarconv.nim
@@ -0,0 +1,16 @@
+discard """
+  action: reject
+  nimout: '''
+  but expression 'int(a)' is immutable, not 'var'
+'''
+"""
+
+proc `++`(n: var int) =
+  n += 1
+
+var a: int32 = 15
+
+++int(a) #[tt.Error
+^ type mismatch: got <int>]#
+
+echo a
diff --git a/tests/int/twrongvarconv.nim b/tests/int/twrongvarconv.nim
new file mode 100644
index 000000000..db6ac2c53
--- /dev/null
+++ b/tests/int/twrongvarconv.nim
@@ -0,0 +1,9 @@
+proc `++`(n: var int) =
+  n += 1
+
+var a: int32 = 15
+
+++a #[tt.Error
+^ type mismatch: got <int32>]#
+
+echo a
diff --git a/tests/isolate/tisolate.nim b/tests/isolate/tisolate.nim
new file mode 100644
index 000000000..a0e71e321
--- /dev/null
+++ b/tests/isolate/tisolate.nim
@@ -0,0 +1,41 @@
+discard """
+  errormsg: "expression cannot be isolated: select(a, b)"
+  line: 39
+"""
+
+import std / isolation
+
+import json, streams
+
+proc myParseJson(s: Stream; filename: string): JsonNode =
+  {.cast(noSideEffect).}:
+    result = parseJson(s, filename)
+
+
+proc f(): seq[int] =
+  @[1, 2, 3]
+
+type
+  Node = ref object
+    x: string
+
+proc g(): Node = nil
+
+proc select(a, b: Node): Node =
+  a
+
+proc main =
+  discard isolate f()
+
+
+  discard isolate g()
+
+  discard isolate select(Node(x: "a"), nil)
+  discard isolate select(Node(x: "a"), Node(x: "b"))
+
+  discard isolate myParseJson(newFileStream("my.json"), "my.json")
+
+  var a, b: Node
+  discard isolate select(a, b)
+
+main()
diff --git a/tests/isolate/tisolate2.nim b/tests/isolate/tisolate2.nim
new file mode 100644
index 000000000..9bf92d82e
--- /dev/null
+++ b/tests/isolate/tisolate2.nim
@@ -0,0 +1,22 @@
+discard """
+  errormsg: "expression cannot be isolated: a_to_b(a)"
+  line: 22
+"""
+
+# bug #19013
+import std/isolation
+
+type Z = ref object
+  i: int
+
+type A = object
+  z: Z
+
+type B = object
+  z: Z
+
+func a_to_b(a: A): B =
+  result = B(z: a.z)
+
+let a = A(z: Z(i: 3))
+let b = isolate(a_to_b(a))
diff --git a/tests/isolate/tisolated_lock.nim b/tests/isolate/tisolated_lock.nim
new file mode 100644
index 000000000..312abf0f6
--- /dev/null
+++ b/tests/isolate/tisolated_lock.nim
@@ -0,0 +1,67 @@
+discard """
+  cmd: "nim $target --threads:on $options $file"
+  action: "compile"
+"""
+
+import std / [os, locks, atomics, isolation]
+
+type
+  MyList {.acyclic.} = ref object
+    data: string
+    next: Isolated[MyList]
+
+template withMyLock*(a: Lock, body: untyped) =
+  acquire(a)
+  {.gcsafe.}:
+    try:
+      body
+    finally:
+      release(a)
+
+var head: Isolated[MyList]
+var headL: Lock
+
+var shouldStop: Atomic[bool]
+
+initLock headL
+
+proc send(x: sink string) =
+  withMyLock headL:
+    head = isolate MyList(data: x, next: move head)
+
+proc worker() {.thread.} =
+  var workItem = MyList(nil)
+  var echoed = 0
+  while true:
+    withMyLock headL:
+      var h = extract head
+      if h != nil:
+        workItem = h
+        # workitem is now isolated:
+        head = move h.next
+      else:
+        workItem = nil
+    # workItem is isolated, so we can access it outside
+    # the lock:
+    if workItem.isNil:
+      if shouldStop.load:
+        break
+      else:
+        # give producer time to breath:
+        os.sleep 30
+    else:
+      if echoed < 100:
+        echo workItem.data
+      inc echoed
+
+var thr: Thread[void]
+createThread(thr, worker)
+
+send "abc"
+send "def"
+for i in 0 ..< 10_000:
+  send "xzy"
+  send "zzz"
+shouldStop.store true
+
+joinThread(thr)
diff --git a/tests/iter/t1550.nim b/tests/iter/t1550.nim
new file mode 100644
index 000000000..c971943ee
--- /dev/null
+++ b/tests/iter/t1550.nim
@@ -0,0 +1,24 @@
+discard """
+  targets: "c js"
+"""
+
+type
+  A[T] = iterator(x: T): T {.gcsafe, closure.}
+
+iterator aimp[T](x: T): T {.gcsafe, closure.} =
+  var total = 0
+  while (total < 100):
+    yield total
+    total += x
+
+iterator bimp(y: A[int], z:int): int {.gcsafe, closure.} =
+  for i in y(z):
+    yield i
+
+for x in aimp[int](3):
+  discard x
+
+var y = aimp[int]
+var z = bimp
+for x in z(y, 1):
+  discard x
\ No newline at end of file
diff --git a/tests/iter/t16076.nim b/tests/iter/t16076.nim
new file mode 100644
index 000000000..2eb409068
--- /dev/null
+++ b/tests/iter/t16076.nim
@@ -0,0 +1,45 @@
+discard """
+  targets: "c js"
+"""
+
+proc main() =
+  block: # bug #17485
+    type
+      O = ref object
+        i: int
+
+    iterator t(o: O): int =
+      if o != nil:
+        yield o.i
+      yield 0
+
+    proc m =
+      var data = ""
+      for i in t(nil):
+        data.addInt i
+
+      doAssert data == "0"
+
+    m()
+
+
+  block: # bug #16076
+    type
+      R = ref object
+        z: int
+
+    var data = ""
+
+    iterator foo(x: int; y: R = nil): int {.inline.} =
+      if y == nil:
+        yield x
+      else:
+        yield y.z
+
+    for b in foo(10):
+      data.addInt b
+
+    doAssert data == "10"
+
+static: main()
+main()
diff --git a/tests/iter/t20891.nim b/tests/iter/t20891.nim
new file mode 100644
index 000000000..34deec41b
--- /dev/null
+++ b/tests/iter/t20891.nim
@@ -0,0 +1,28 @@
+import macros, tables
+
+var mapping {.compileTime.}: Table[string, NimNode]
+
+macro register(a: static[string], b: typed): untyped =
+  mapping[a] = b
+
+macro getPtr(a: static[string]): untyped =
+  result = mapping[a]
+
+proc foo() =
+  iterator it() {.closure.} =
+    discard
+  proc getIterPtr(): pointer {.nimcall.} =
+    rawProc(it)
+  register("foo", getIterPtr())
+  discard getIterPtr() # Comment either this to make it work
+foo() # or this
+
+proc bar() =
+  iterator it() {.closure.} =
+    discard getPtr("foo") # Or this
+    discard
+  proc getIterPtr(): pointer {.nimcall.} =
+    rawProc(it)
+  register("bar", getIterPtr())
+  discard getIterPtr()
+bar()
diff --git a/tests/iter/t21306.nim b/tests/iter/t21306.nim
new file mode 100644
index 000000000..4d0396294
--- /dev/null
+++ b/tests/iter/t21306.nim
@@ -0,0 +1,118 @@
+discard """
+  targets: "c js"
+"""
+
+# bug #21306
+type
+  FutureState {.pure.} = enum
+    Pending, Finished, Cancelled, Failed
+
+  FutureBase = ref object of RootObj
+    state: FutureState
+    error: ref CatchableError
+    id: uint
+
+  Future[T] = ref object of FutureBase
+    closure: iterator(f: Future[T]): FutureBase {.raises: [Defect, CatchableError, Exception], gcsafe.}
+    value: T
+
+template setupFutureBase() =
+  new(result)
+  result.state = FutureState.Pending
+
+proc newFutureImpl[T](): Future[T] =
+  setupFutureBase()
+
+template newFuture[T](fromProc: static[string] = ""): Future[T] =
+  newFutureImpl[T]()
+
+proc internalRead[T](fut: Future[T]): T =
+  when T isnot void:
+    return fut.value
+
+template await[T](f: Future[T]): untyped =
+  when declared(chronosInternalRetFuture):
+    when not declaredInScope(chronosInternalTmpFuture):
+      var chronosInternalTmpFuture {.inject.}: FutureBase = f
+    else:
+      chronosInternalTmpFuture = f
+
+    yield chronosInternalTmpFuture
+
+    when T isnot void:
+      cast[type(f)](chronosInternalTmpFuture).internalRead()
+
+type
+  VerifierError {.pure.} = enum
+    Invalid
+    MissingParent
+    UnviableFork
+    Duplicate
+  ProcessingCallback = proc() {.gcsafe, raises: [Defect].}
+  BlockVerifier =
+    proc(signedBlock: int):
+      Future[VerifierError] {.gcsafe, raises: [Defect].}
+
+  SyncQueueKind {.pure.} = enum
+    Forward, Backward
+
+  SyncRequest[T] = object
+    kind: SyncQueueKind
+    index: uint64
+    slot: uint64
+    count: uint64
+    item: T
+
+  SyncResult[T] = object
+    request: SyncRequest[T]
+    data: seq[ref int]
+
+  SyncQueue[T] = ref object
+    kind: SyncQueueKind
+    readyQueue: seq[SyncResult[T]]
+    blockVerifier: BlockVerifier
+
+iterator blocks[T](sq: SyncQueue[T],
+                    sr: SyncResult[T]): ref int =
+  case sq.kind
+  of SyncQueueKind.Forward:
+    for i in countup(0, len(sr.data) - 1):
+      yield sr.data[i]
+  of SyncQueueKind.Backward:
+    for i in countdown(len(sr.data) - 1, 0):
+      yield sr.data[i]
+
+proc push[T](sq: SyncQueue[T]; sr: SyncRequest[T]; data: seq[ref int];
+             processingCb: ProcessingCallback = nil): Future[void] {.
+    stackTrace: off, gcsafe.} =
+  iterator push_436208182(chronosInternalRetFuture: Future[void]): FutureBase {.
+      closure, gcsafe, raises: [Defect, CatchableError, Exception].} =
+    block:
+      template result(): auto {.used.} =
+        {.fatal: "You should not reference the `result` variable inside" &
+            " a void async proc".}
+
+      let item = default(SyncResult[T])
+      for blk in sq.blocks(item):
+        let res = await sq.blockVerifier(blk[])
+
+  var resultFuture = newFuture[void]("push")
+  resultFuture.closure = push_436208182
+  return resultFuture
+
+type
+  SomeTPeer = ref object
+    score: int
+
+proc getSlice(): seq[ref int] =
+  discard
+
+template smokeTest(kkind: SyncQueueKind, start, finish: uint64,
+                   chunkSize: uint64) =
+  var queue: SyncQueue[SomeTPeer]
+  var request: SyncRequest[SomeTPeer]
+  discard queue.push(request, getSlice())
+
+for k in {SyncQueueKind.Forward}:
+  for item in [(uint64(1181), uint64(1399), 41'u64)]:
+    smokeTest(k, item[0], item[1], item[2])
\ No newline at end of file
diff --git a/tests/iter/t21737.nim b/tests/iter/t21737.nim
new file mode 100644
index 000000000..da06faea7
--- /dev/null
+++ b/tests/iter/t21737.nim
@@ -0,0 +1,22 @@
+discard """
+  action: compile
+"""
+
+template mytoSeq*(iter: untyped): untyped =
+  var result: seq[typeof(iter)]# = @[]
+  for x in iter:
+    result.add(x)
+  result
+
+iterator test(dir:int): int =
+  yield 1234
+
+iterator walkGlobKinds (): int =
+  let dir2 = 123
+  let it = mytoSeq(test(dir2))  
+
+proc main()=
+    let it = iterator(): int=
+      for path in walkGlobKinds():
+          yield path
+main()
diff --git a/tests/iter/t22148.nim b/tests/iter/t22148.nim
new file mode 100644
index 000000000..9954eed87
--- /dev/null
+++ b/tests/iter/t22148.nim
@@ -0,0 +1,15 @@
+discard """

+  action: compile

+"""

+

+import std/memfiles

+

+# bug #22148

+proc make*(input: string) =

+  var inp = memfiles.open(input)

+  for line in memSlices(inp):

+    let lineF = MemFile(mem: line.data, size: line.size)

+    for word in memSlices(lineF, ','):

+      discard

+

+make("") # Must call to trigger

diff --git a/tests/iter/t22548.nim b/tests/iter/t22548.nim
new file mode 100644
index 000000000..b9abb75d0
--- /dev/null
+++ b/tests/iter/t22548.nim
@@ -0,0 +1,21 @@
+discard """
+  action: compile
+"""
+
+type Xxx[T] = object
+
+iterator x(v: string): char =
+  var v2: Xxx[int]
+
+  var y: v2.T
+
+  echo y
+
+proc bbb(vv: string): proc () =
+  proc xxx() =
+    for c in x(vv):
+      echo c
+
+  return xxx
+
+bbb("test")()
diff --git a/tests/iter/t22619.nim b/tests/iter/t22619.nim
new file mode 100644
index 000000000..6a98391f3
--- /dev/null
+++ b/tests/iter/t22619.nim
@@ -0,0 +1,83 @@
+# bug #22619
+
+when false: # todo fixme
+  block:
+    type
+      Resource = object
+        value: int
+  
+      Object = object
+        r {.cursor.}: Resource
+        s {.cursor.}: seq[Resource]
+  
+    var numDestroy = 0
+  
+    proc `=copy`(x: var Resource, y: Resource) {.error.} # disallow full copies
+    proc `=destroy`(x: Resource) =
+      inc numDestroy
+  
+    proc test() =
+      # perform the test in procedure so that globals aren't used (their different
+      # semantics with regards to destruction would interfere)
+      var
+        r = Resource(value: 1) # initialize a resource
+        s = @[Resource(value: 2)]
+  
+      # make sure no copy is required in the initializer expression:
+      var o = Object(r: r, s: s)
+  
+      # copying the object doesn't perform a full copy of the cursor fields:
+      var o2 = o
+      discard addr(o2) # prevent `o2` from being turned into a cursor
+  
+      # check that the fields were shallow-copied:
+      doAssert o2.r.value == 1
+      doAssert o2.s[0].value == 2
+  
+      # make sure no copy is required with normal field assignments:
+      o.r = r
+      o.s = s
+  
+  
+      # when `o` and `o2` are destroyed, their destructor must not be called on
+      # their fields
+  
+    test()
+  
+    # one call for the `r` local and one for the object in `s`
+    doAssert numDestroy == 2
+
+block:
+  type Value = distinct int
+
+  var numDestroy = 0
+
+  when defined(gcRefc):
+    proc `=destroy`(x: var Value) =
+      inc numDestroy
+  else:
+    proc `=destroy`(x: Value) =
+      inc numDestroy
+
+  iterator iter(s: seq[Value]): int {.closure.} =
+    # because it is used across yields, `s2` is lifted into the iterator's
+    # environment. Since non-ref cursors in object didn't have their hooks
+    # disabled inside the environments lifted hooks, this led to double
+    # frees
+    var s2 {.cursor.} = s
+    var i = 0
+    let L = s2.len
+    while i < L:
+      yield s2[i].int
+      inc i
+
+  proc test() =
+    var s = @[Value(1), Value(2)]
+    let cl = iter
+    # make sure resuming the iterator works:
+    doAssert cl(s) == 1
+    doAssert cl(s) == 2
+    doAssert cl(s) == 0
+
+  test()
+  doAssert numDestroy == 2
diff --git a/tests/iter/t2771.nim b/tests/iter/t2771.nim
new file mode 100644
index 000000000..71a8a9dcd
--- /dev/null
+++ b/tests/iter/t2771.nim
@@ -0,0 +1,25 @@
+discard """
+  targets: "c js"
+"""
+
+template t1(i: int): int=
+  i+1
+template t2(i: int): int=
+  i+1
+
+doAssert t1(10).t2() == 12
+
+
+template it1(i: int): iterator(): int =
+  iterator result(): int {.closure, gensym.} =
+    yield i+1
+  result
+
+template it2(iter: iterator(): int): iterator(): int =
+  iterator result(): int {.closure, gensym.} =
+    yield iter()+1
+  result
+
+let x2 = it1(10).it2()
+
+doAssert x2() == 12
diff --git a/tests/iter/tanoniter1.nim b/tests/iter/tanoniter1.nim
index 9f0d0a74b..fee16497f 100644
--- a/tests/iter/tanoniter1.nim
+++ b/tests/iter/tanoniter1.nim
@@ -1,4 +1,5 @@
 discard """
+  targets: "c js"
   output: '''1
 2
 3
diff --git a/tests/iter/tarrayiter.nim b/tests/iter/tarrayiter.nim
new file mode 100644
index 000000000..eb7ba591a
--- /dev/null
+++ b/tests/iter/tarrayiter.nim
@@ -0,0 +1,14 @@
+block:
+  iterator `[]`(a: int, r: int): int = 
+    for q in 0 .. r:
+      yield a
+    
+  for val in 10[2]: discard
+  
+  type Custom = distinct string
+
+  iterator `[]`(a: Custom, r: int): char = 
+    for q in 0 .. r:
+      yield a.string[q]
+      
+  for val in Custom("test")[2]: discard
\ No newline at end of file
diff --git a/tests/iter/tclosureiters.nim b/tests/iter/tclosureiters.nim
index 345a4867a..4a2639852 100644
--- a/tests/iter/tclosureiters.nim
+++ b/tests/iter/tclosureiters.nim
@@ -1,4 +1,5 @@
 discard """
+  targets: "c js"
   output: '''0
 1
 2
@@ -19,7 +20,18 @@ discard """
 0
 1
 2
-70'''
+70
+0
+(1, 1)
+(1, 2)
+(1, 3)
+(2, 1)
+(2, 2)
+(2, 3)
+(3, 1)
+(3, 2)
+(3, 3)
+'''
 """
 
 when true:
@@ -96,7 +108,7 @@ proc unused =
 iterator lineIter2*(filename: string): string {.closure.} =
   var f = open(filename, bufSize=8000)
   defer: close(f)   # <-- commenting defer "solves" the problem
-  var res = TaintedString(newStringOfCap(80))
+  var res = newStringOfCap(80)
   while f.readLine(res): yield res
 
 proc unusedB =
@@ -139,3 +151,26 @@ iterator filesIt(path: string): auto {.closure.} =
     let prefix = path.splitPath[1]
     for f in files:
       yield prefix / f
+
+# bug #13815
+when not defined(js):
+  var love = iterator: int {.closure.} =
+    yield cast[type(
+      block:
+        var a = 0
+        yield a
+        a)](0)
+
+  for i in love():
+    echo i
+else:
+  echo 0
+
+# bug #18474
+iterator pairs(): (int, int) {.closure.} =
+  for i in 1..3:
+    for j in 1..3:
+      yield (i, j)
+
+for pair in pairs():
+  echo pair
diff --git a/tests/iter/tgeniteratorinblock.nim b/tests/iter/tgeniteratorinblock.nim
new file mode 100644
index 000000000..2ab903996
--- /dev/null
+++ b/tests/iter/tgeniteratorinblock.nim
@@ -0,0 +1,54 @@
+discard """
+  output: '''30
+60
+90
+150
+180
+210
+240
+60
+180
+240
+[60, 180, 240]
+[60, 180]'''
+"""
+import std/enumerate
+
+template map[T; Y](i: iterable[T], fn: proc(x: T): Y): untyped =
+  iterator internal(): Y  {.gensym.} =
+    for it in i:
+      yield fn(it)
+  internal()
+
+template filter[T](i: iterable[T], fn: proc(x: T): bool): untyped =
+  iterator internal(): T {.gensym.} =
+    for it in i:
+      if fn(it):
+        yield it
+  internal()
+
+template group[T](i: iterable[T], amount: static int): untyped =
+  iterator internal(): array[amount, T] {.gensym.} =
+    var val: array[amount, T]
+    for ind, it in enumerate i:
+      val[ind mod amount] = it
+      if ind mod amount == amount - 1:
+        yield val
+  internal()
+
+var a = [10, 20, 30, 50, 60, 70, 80]
+
+proc mapFn(x: int): int = x * 3
+proc filterFn(x: int): bool = x mod 20 == 0
+
+for x in a.items.map(mapFn):
+  echo x
+
+for y in a.items.map(mapFn).filter(filterFn):
+  echo y
+
+for y in a.items.map(mapFn).filter(filterFn).group(3):
+  echo y
+
+for y in a.items.map(mapFn).filter(filterFn).group(2):
+  echo y
diff --git a/tests/iter/titer.nim b/tests/iter/titer.nim
index 22be1bad5..b03d43f36 100644
--- a/tests/iter/titer.nim
+++ b/tests/iter/titer.nim
@@ -55,3 +55,93 @@ const
 for i in 0..len(stringArray)-1:
   echo(stringArray[i])
 
+# bug #15360
+
+type Rule[T] = (int, T)
+
+var t: seq[Rule[int]]
+for (c, t) in t:
+  discard
+
+
+
+import std/sugar
+
+# bug #14165
+iterator log_nodups_hamming(): int {.inline.} =
+  let lb3 = 1
+  let lb4 = 123
+  proc mul3(): int = lb3 + lb4
+  yield mul3()
+
+for h in log_nodups_hamming():
+  break
+for h in log_nodups_hamming():
+  break
+for h in log_nodups_hamming():
+  break
+
+# bug #18536
+iterator envPairs*(): int =
+  var foo: seq[int]
+  proc fun() =
+    foo = @[]
+  fun()
+  yield 3
+
+proc main() =
+  for a in envPairs():
+    discard
+  for a in envPairs():
+    discard
+static: main()
+main()
+
+# bug #6269
+iterator makeFn(outer_val: int): proc(a: int): int =
+  for i in 0..1:
+    yield proc(a:int): int =
+      return a + i.int
+
+let v1 = 42
+
+let res = collect:
+  for fn1 in makeFn(v1):
+    let v2 = fn1(v1)
+    for fn2 in makeFn(v2):
+      fn2(v2)
+
+doAssert res == @[42, 43, 43, 44]
+
+block: # bug #21110
+  iterator p(): int =
+    when nimvm:
+      yield 0
+    else:
+      yield 0
+
+  template foo =
+    for k in p():
+      let m = ""
+      proc e() = discard m & ""
+      e()
+  static: foo()
+  foo()
+
+
+# bug #15924
+iterator walk(): (int, int) {.closure.} =
+  yield (10,11)
+
+for (i,j) in walk():
+  doAssert i == 10
+
+proc main123() =
+  let x = false
+  iterator it(): (bool, bool) {.closure.} = # normally {.closure.} here makes #21476 work
+    discard x
+
+  for (_, _) in it():
+    discard
+
+main123()
diff --git a/tests/iter/titer11.nim b/tests/iter/titer11.nim
index c4c7d4a16..153b3c29a 100644
--- a/tests/iter/titer11.nim
+++ b/tests/iter/titer11.nim
@@ -1,4 +1,5 @@
 discard """
+targets: "c js"
 output: '''
 [
 1
@@ -26,3 +27,14 @@ var output = represent(s)
 
 for item in output():
   echo item
+
+
+#------------------------------------------------------------------------------
+# Issue #12747
+
+type
+  ABC = ref object
+      arr: array[0x40000, pointer]
+let a = ABC()
+for a in a.arr:
+    assert a == nil
\ No newline at end of file
diff --git a/tests/iter/titer12.nim b/tests/iter/titer12.nim
index f7fc64da4..f264a0e82 100644
--- a/tests/iter/titer12.nim
+++ b/tests/iter/titer12.nim
@@ -1,4 +1,5 @@
 discard """
+targets: "c js"
 output: '''
 Selecting 2
 1.0
diff --git a/tests/iter/titer13.nim b/tests/iter/titer13.nim
index 0d4a399c5..086c40ca4 100644
--- a/tests/iter/titer13.nim
+++ b/tests/iter/titer13.nim
@@ -72,7 +72,7 @@ block:
     echo a
 
 block t5859:
-  proc flatIterator[T](s: openarray[T]): auto {.noSideEffect.}=
+  proc flatIterator[T](s: openArray[T]): auto {.noSideEffect.}=
     result = iterator(): auto =
       when (T is not seq|array):
         for item in s:
diff --git a/tests/iter/titer2.nim b/tests/iter/titer2.nim
index f60aed73a..975cc786c 100644
--- a/tests/iter/titer2.nim
+++ b/tests/iter/titer2.nim
@@ -17,7 +17,7 @@ type
   TSlotEnum = enum seEmpty, seFilled, seDeleted
   TKeyValuePair[A, B] = tuple[slot: TSlotEnum, key: A, val: B]
   TKeyValuePairSeq[A, B] = seq[TKeyValuePair[A, B]]
-  TTable* {.final.}[A, B] = object
+  TTable*[A, B] {.final.} = object
     data: TKeyValuePairSeq[A, B]
     counter: int
 
diff --git a/tests/iter/titer3.nim b/tests/iter/titer3.nim
index 9dcfd7be5..defd56c98 100644
--- a/tests/iter/titer3.nim
+++ b/tests/iter/titer3.nim
@@ -26,7 +26,7 @@ var x = [[1, 2, 3], [4, 5, 6]]
 for y in iter1(x[0]): write(stdout, $y)
 writeLine(stdout, "")
 
-# ensure closure and inline iterators have the same behaviour wrt
+# ensure closure and inline iterators have the same behaviour regarding
 # parameter passing
 
 iterator clo(a: int): int {.closure.} =
diff --git a/tests/iter/titer_issues.nim b/tests/iter/titer_issues.nim
index a7830dfab..c82b3902d 100644
--- a/tests/iter/titer_issues.nim
+++ b/tests/iter/titer_issues.nim
@@ -1,4 +1,5 @@
 discard """
+  target: "c js"
   output: '''
 0
 1
@@ -18,6 +19,30 @@ end
 1
 2
 7
+9002
+9004
+9006
+9008
+9010
+9012
+9014
+9016
+9018
+@[1, 2]
+@[1, 2, 3]
+1
+nested finally
+outer finally
+nested finally
+outer finally
+nested finally
+outer finally
+nested finally
+outer finally
+In defer
+trying
+exception caught
+finally block
 '''
 """
 
@@ -124,7 +149,7 @@ block t3837_chained:
 
 
 block t3221_complex:
-  iterator permutations[T](ys: openarray[T]): seq[T] =
+  iterator permutations[T](ys: openArray[T]): seq[T] =
     var
       d = 1
       c = newSeq[int](ys.len)
@@ -182,7 +207,7 @@ block t3499_keepstate:
       break
 
   # bug #3499 last snippet fixed
-  # bug 705  last snippet fixed
+  # bug #705  last snippet fixed
 
 
 
@@ -213,3 +238,174 @@ block t2023_objiter:
 
   var o = init()
   echo(o.iter())
+
+
+block:
+  # bug #13739
+  iterator myIter(arg: openArray[int]): int =
+    var tmp = 0
+    let len = arg.len
+    while tmp < len:
+      yield arg[tmp] * 2
+      inc tmp
+
+  proc someProc() =
+    var data = [4501,4502,4503,4504,4505,4506,4507,4508,4509]
+    # StmtListExpr should not get special treatment.
+    for x in myIter((discard;data)):
+      echo x
+
+  someProc()
+
+block:
+  # bug #12576
+  iterator ff(sq: varargs[seq[int]]): int =
+    for x in sq:
+      echo x
+
+  for x in ff(@[1, 2], @[1, 2, 3]):
+    echo x
+
+
+# bug #19575
+
+iterator bb() {.closure.} =
+    while true:
+        try: discard
+        except: break
+        finally: break
+
+var a = bb
+
+iterator cc() {.closure.} =
+    while true:
+        try: discard
+        except:
+          if true:
+            break
+        finally:
+          if true:
+            break
+
+var a2 = cc
+
+# bug #16876
+block:
+  iterator a(num: int): int {.closure.} =
+      if num == 1:
+          yield num
+      else:
+          for i in a(num - 1):
+              yield i
+
+  for i in a(5):
+    echo i
+
+block:
+  # bug #19911 (return in nested try)
+
+  # try yield -> try
+  iterator p1: int {.closure.} =
+    try:
+      yield 0
+      try:
+        return
+      finally:
+        echo "nested finally"
+      echo "shouldn't run"
+    finally:
+      echo "outer finally"
+    echo "shouldn't run"
+
+  for _ in p1():
+    discard
+
+  # try -> try yield
+  iterator p2: int {.closure.} =
+    try:
+      try:
+        yield 0
+        return
+      finally:
+        echo "nested finally"
+      echo "shouldn't run"
+    finally:
+      echo "outer finally"
+    echo "shouldn't run"
+
+  for _ in p2():
+    discard
+
+  # try yield -> try yield
+  iterator p3: int {.closure.} =
+    try:
+      yield 0
+      try:
+        yield 0
+        return
+      finally:
+        echo "nested finally"
+      echo "shouldn't run"
+    finally:
+      echo "outer finally"
+    echo "shouldn't run"
+
+  for _ in p3():
+    discard
+
+  # try -> try
+  iterator p4: int {.closure.} =
+    try:
+      try:
+        return
+      finally:
+        echo "nested finally"
+      echo "shouldn't run"
+    finally:
+      echo "outer finally"
+    echo "shouldn't run"
+
+  for _ in p4():
+    discard
+
+# bug #18824
+iterator poc_iterator: int {.closure.}  =
+  block bug18824:
+    try:
+      break bug18824
+    finally:
+      echo "In defer"
+
+for _ in poc_iterator():
+  discard
+
+# bug #20624
+iterator tryFinally() {.closure.} =
+  block route:
+    try:
+      echo "trying"
+      raise
+    except:
+      echo "exception caught"
+      break route
+    finally:
+      echo "finally block"
+
+var x = tryFinally
+x()
+
+block: # bug #24033
+  type Query = ref object
+
+  iterator pairs(query: Query): (int, (string, float32)) =
+    var output: (int, (string, float32)) = (0, ("foo", 3.14))
+    for id in @[0, 1, 2]:
+      output[0] = id
+      yield output
+
+  var collections: seq[(int, string, string)]
+
+  for id, (str, num) in Query():
+    collections.add (id, str, $num)
+
+  doAssert collections[1] == (1, "foo", "3.14")
diff --git a/tests/iter/titervaropenarray.nim b/tests/iter/titervaropenarray.nim
index 4469fdcf5..b2fe71ceb 100644
--- a/tests/iter/titervaropenarray.nim
+++ b/tests/iter/titervaropenarray.nim
@@ -1,6 +1,6 @@
 discard """
   output: "123"
-  targets: "C"
+  targets: "c cpp"
 """
 # Try to break the transformation pass:
 iterator iterAndZero(a: var openArray[int]): int =
diff --git a/tests/iter/tmoditer.nim b/tests/iter/tmoditer.nim
index b92a416fb..99e5b642d 100644
--- a/tests/iter/tmoditer.nim
+++ b/tests/iter/tmoditer.nim
@@ -43,7 +43,7 @@ proc `=copy`(dst: var NonCopyable, src: NonCopyable) {.error.}
 proc `=sink`(dst: var NonCopyable, src: NonCopyable) =
   dst.x = src.x
 
-iterator lentItems[T](a: openarray[T]): lent T =
+iterator lentItems[T](a: openArray[T]): lent T =
   for i in 0..a.high:
     yield a[i]
 
diff --git a/tests/iter/tpermutations.nim b/tests/iter/tpermutations.nim
index c5067ba31..30a66460f 100644
--- a/tests/iter/tpermutations.nim
+++ b/tests/iter/tpermutations.nim
@@ -12,7 +12,7 @@ perm: 6778800.0 det: 0.0
 
 import sequtils, sugar
 
-iterator permutations*[T](ys: openarray[T]): tuple[perm: seq[T], sign: int] =
+iterator permutations*[T](ys: openArray[T]): tuple[perm: seq[T], sign: int] =
   var
     d = 1
     c = newSeq[int](ys.len)
diff --git a/tests/iter/tshallowcopy_closures.nim b/tests/iter/tshallowcopy_closures.nim
index 279e7d950..06b04a788 100644
--- a/tests/iter/tshallowcopy_closures.nim
+++ b/tests/iter/tshallowcopy_closures.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   ccodecheck: "!@('{' \\s* 'NI HEX3Astate;' \\s* '}')"
   output: '''
 a1 10
diff --git a/tests/iter/tyieldintry.nim b/tests/iter/tyieldintry.nim
index 62c16c741..e51ab7f0d 100644
--- a/tests/iter/tyieldintry.nim
+++ b/tests/iter/tyieldintry.nim
@@ -1,15 +1,16 @@
 discard """
-targets: "c cpp"
-output: "ok"
+  matrix: "; --experimental:strictdefs; -d:nimOptIters"
+  targets: "c cpp"
 """
+
 var closureIterResult = newSeq[int]()
 
 proc checkpoint(arg: int) =
   closureIterResult.add(arg)
 
 type
-  TestException = object of Exception
-  AnotherException = object of Exception
+  TestError = object of CatchableError
+  AnotherError = object of CatchableError
 
 proc testClosureIterAux(it: iterator(): int, exceptionExpected: bool, expectedResults: varargs[int]) =
   closureIterResult.setLen(0)
@@ -19,7 +20,7 @@ proc testClosureIterAux(it: iterator(): int, exceptionExpected: bool, expectedRe
   try:
     for i in it():
       closureIterResult.add(i)
-  except TestException:
+  except TestError:
     exceptionCaught = true
 
   if closureIterResult != @expectedResults or exceptionCaught != exceptionExpected:
@@ -37,8 +38,8 @@ proc test(it: iterator(): int, expectedResults: varargs[int]) =
 proc testExc(it: iterator(): int, expectedResults: varargs[int]) =
   testClosureIterAux(it, true, expectedResults)
 
-proc raiseException() =
-  raise newException(TestException, "Test exception!")
+proc raiseTestError() =
+  raise newException(TestError, "Test exception!")
 
 block:
   iterator it(): int {.closure.} =
@@ -56,8 +57,8 @@ block:
     yield 0
     try:
       checkpoint(1)
-      raiseException()
-    except TestException:
+      raiseTestError()
+    except TestError:
       checkpoint(2)
       yield 3
       checkpoint(4)
@@ -87,7 +88,7 @@ block:
     yield 0
     try:
       yield 1
-      raiseException()
+      raiseTestError()
       yield 2
     finally:
       checkpoint(3)
@@ -101,8 +102,8 @@ block:
   iterator it(): int {.closure.} =
     try:
       try:
-        raiseException()
-      except AnotherException:
+        raiseTestError()
+      except AnotherError:
         yield 123
       finally:
         checkpoint(3)
@@ -115,8 +116,8 @@ block:
   iterator it(): int {.closure.} =
     try:
       yield 1
-      raiseException()
-    except AnotherException:
+      raiseTestError()
+    except AnotherError:
       checkpoint(123)
     finally:
       checkpoint(2)
@@ -132,12 +133,12 @@ block:
         yield 1
         try:
           yield 2
-          raiseException()
-        except AnotherException:
+          raiseTestError()
+        except AnotherError:
           yield 123
         finally:
           yield 3
-      except AnotherException:
+      except AnotherError:
         yield 124
       finally:
         yield 4
@@ -168,10 +169,10 @@ block:
     try:
       try:
         yield 0
-        raiseException()
+        raiseTestError()
       finally:
         checkpoint(1)
-    except TestException:
+    except TestError:
       yield 2
       return
     finally:
@@ -186,10 +187,10 @@ block:
     try:
       try:
         yield 0
-        raiseException()
+        raiseTestError()
       finally:
         return # Return in finally should stop exception propagation
-    except AnotherException:
+    except AnotherError:
       yield 2
       return
     finally:
@@ -226,9 +227,9 @@ block:
     var foo = 123
     let i = try:
         yield 0
-        raiseException()
+        raiseTestError()
         1
-      except TestException as e:
+      except TestError as e:
         assert(e.msg == "Test exception!")
         case foo
         of 1:
@@ -260,9 +261,9 @@ block:
     template tryexcept: int =
       try:
         yield 1
-        raiseException()
+        raiseTestError()
         123
-      except TestException:
+      except TestError:
         yield 2
         checkpoint(3)
         4
@@ -321,11 +322,11 @@ block:
     for i in 0 .. 1:
       try:
         yield 1
-        raiseException()
-      except TestException as e:
+        raiseTestError()
+      except TestError as e:
         doAssert(e.msg == "Test exception!")
         yield 2
-      except AnotherException:
+      except AnotherError:
         yield 123
       except:
         yield 1234
@@ -481,5 +482,48 @@ block: # nnkChckRange
 
   test(it, 1, 2, 3)
 
-echo "ok"
+block: #17849 - yield in case subject
+  template yieldInCase: int =
+    yield 2
+    3
+
+  iterator it(): int {.closure.} =
+    yield 1
+    case yieldInCase()
+    of 1: checkpoint(11)
+    of 3: checkpoint(13)
+    else: checkpoint(14)
+    yield 5
+
+  test(it, 1, 2, 13, 5)
 
+block: # void iterator
+  iterator it() {.closure.} =
+    try:
+      yield
+    except:
+      discard
+  var a = it
+
+if defined(nimOptIters): # Locals present in only 1 state should be on the stack
+  proc checkOnStack(a: pointer, shouldBeOnStack: bool) =
+    # Quick and dirty way to check if a points to stack
+    var dummy = 0
+    let dummyAddr = addr dummy
+    let distance = abs(cast[int](dummyAddr) - cast[int](a))
+    const requiredDistance = 300
+    if shouldBeOnStack:
+      doAssert(distance <= requiredDistance, "a is not on stack, but should")
+    else:
+      doAssert(distance > requiredDistance, "a is on stack, but should not")
+
+  iterator it(): int {.closure.} =
+    var a = 1
+    var b = 2
+    var c {.liftLocals.} = 3
+    checkOnStack(addr a, true)
+    checkOnStack(addr b, false)
+    checkOnStack(addr c, false)
+    yield a
+    yield b
+  test(it, 1, 2)
diff --git a/tests/js/readme.md b/tests/js/readme.md
new file mode 100644
index 000000000..7fcc722fa
--- /dev/null
+++ b/tests/js/readme.md
@@ -0,0 +1,5 @@
+## notes
+Prefer moving tests to a non-js directory so that they get tested across all backends automatically.
+Ideally, tests/js should be reserved to code that only makes sense in js.
+
+Note also that tests for a js specific module (e.g.: `std/jsbigints`) belong to `tests/stdlib`, (e.g.: `tests/stdlib/tjsbigints.nim`)
diff --git a/tests/js/t11166.nim b/tests/js/t11166.nim
index 8dd77925c..e98ccda10 100644
--- a/tests/js/t11166.nim
+++ b/tests/js/t11166.nim
@@ -1,4 +1,20 @@
+discard """
+  output: '''
+test1
+test2
+'''
+"""
+
 import jsffi
 
+type
+  C = object
+    props: int
+
+var c: C
+
 when compiles(c.props):
-  echo "test"
+  echo "test1"
+
+when not compiles(d.props):
+  echo "test2"
diff --git a/tests/js/t11354.nim b/tests/js/t11354.nim
new file mode 100644
index 000000000..8dee90de0
--- /dev/null
+++ b/tests/js/t11354.nim
@@ -0,0 +1,20 @@
+discard """
+  output: '''
+0
+@[@[0, 1]]
+'''
+"""
+
+type
+  TrackySeq[T] = object
+    s: seq[T]
+    pos: int
+
+proc foobar(ls: var TrackySeq[seq[int]], i: int): var seq[int] =
+  echo ls.pos  # removing this, or making the return explicit works
+  ls.s[i]
+
+var foo: TrackySeq[seq[int]]
+foo.s.add(@[0])
+foo.foobar(0).add(1)
+echo foo.s
\ No newline at end of file
diff --git a/tests/js/t11697.nim b/tests/js/t11697.nim
new file mode 100644
index 000000000..967752586
--- /dev/null
+++ b/tests/js/t11697.nim
@@ -0,0 +1,5 @@
+import tables
+
+var xs: Table[int, Table[int, int]]
+
+doAssertRaises(KeyError): reset xs[0]
diff --git a/tests/js/t12303.nim b/tests/js/t12303.nim
new file mode 100644
index 000000000..270d82ced
--- /dev/null
+++ b/tests/js/t12303.nim
@@ -0,0 +1,16 @@
+discard """
+  output: "{ b: 2 }"
+"""
+
+import jsconsole, jsffi
+
+type
+  A = ref object
+   b: B
+
+  B = object
+    b: int
+
+var a = cast[A](js{})
+a.b = B(b: 2)
+console.log a.b
diff --git a/tests/js/t12672.nim b/tests/js/t12672.nim
new file mode 100644
index 000000000..a658fbcbe
--- /dev/null
+++ b/tests/js/t12672.nim
@@ -0,0 +1,12 @@
+discard """
+  output: ""
+"""
+
+proc foo =
+  var x: seq[seq[int]]
+  for row in x.mitems:
+    let i = 1
+    echo row
+    inc row[i-1]
+
+foo()
diff --git a/tests/js/t14153.nim b/tests/js/t14153.nim
new file mode 100644
index 000000000..350bbd83b
--- /dev/null
+++ b/tests/js/t14153.nim
@@ -0,0 +1,22 @@
+discard """
+  output: '''
+index 5 not in 0 .. 2
+index 5 not in 0 .. 2
+'''
+"""
+
+var x = @[1, 2, 3]
+
+try:
+  echo x[5]
+except IndexError:
+  echo getCurrentExceptionMsg()
+except:
+  doAssert false
+
+try:
+  x[5] = 8
+except IndexError:
+  echo getCurrentExceptionMsg()
+except:
+  doAssert false
diff --git a/tests/js/t14570.nim b/tests/js/t14570.nim
new file mode 100644
index 000000000..100c2651d
--- /dev/null
+++ b/tests/js/t14570.nim
@@ -0,0 +1,11 @@
+discard """
+  output: '''
+18
+'''
+"""
+
+type A = range[15 .. 30]
+
+let a: A = 18
+
+echo ord(a)
diff --git a/tests/js/t17177.nim b/tests/js/t17177.nim
new file mode 100644
index 000000000..fc362cec1
--- /dev/null
+++ b/tests/js/t17177.nim
@@ -0,0 +1,10 @@
+import std/asyncjs
+
+proc fn1(n: int): Future[int] {.async.} = return n
+proc main2() =
+  proc fn2(n: int): Future[int] {.async.} = return n
+proc main3(a: auto) =
+  proc fn3(n: int): Future[int] {.async.} = return n
+proc main4() {.async.} =
+  proc fn4(n: int): Future[int] {.async.} = return n
+  discard
diff --git a/tests/js/t20233.nim b/tests/js/t20233.nim
new file mode 100644
index 000000000..401d14122
--- /dev/null
+++ b/tests/js/t20233.nim
@@ -0,0 +1,7 @@
+discard """
+  output: "yes"
+"""
+case 1.0
+of 1.0..2.0, 4.0: echo "yes"
+of 3.0: discard
+else: echo "no"
\ No newline at end of file
diff --git a/tests/js/t20235.nim b/tests/js/t20235.nim
new file mode 100644
index 000000000..3a69c2bd6
--- /dev/null
+++ b/tests/js/t20235.nim
@@ -0,0 +1,11 @@
+discard """
+  action: "run"
+  output: "0 4"
+"""
+
+proc main =
+  var s = ""
+  s.setLen(4)
+  echo s[0].ord, " ", s.len
+
+main()
diff --git a/tests/js/t21209.nim b/tests/js/t21209.nim
new file mode 100644
index 000000000..4de34f035
--- /dev/null
+++ b/tests/js/t21209.nim
@@ -0,0 +1,6 @@
+discard """
+  action: "compile"
+  cmd: "nim check --warning[UnusedImport]:off $file"
+"""
+
+import std/times
diff --git a/tests/js/t21209.nims b/tests/js/t21209.nims
new file mode 100644
index 000000000..318e28f97
--- /dev/null
+++ b/tests/js/t21209.nims
@@ -0,0 +1 @@
+--b:js
\ No newline at end of file
diff --git a/tests/js/t21247.nim b/tests/js/t21247.nim
new file mode 100644
index 000000000..5b38787b3
--- /dev/null
+++ b/tests/js/t21247.nim
@@ -0,0 +1,15 @@
+import std/typetraits
+
+type
+  QueryParams* = distinct seq[(string, string)]
+
+converter toBase*(params: var QueryParams): var seq[(string, string)] =
+  params.distinctBase
+
+proc foo(): QueryParams =
+  # Issue was that the implicit converter call didn't say that it took the
+  # address of the parameter it was converting. This led to the parameter not being
+  # passed as a fat pointer which toBase expected
+  result.add(("hello", "world"))
+
+assert foo().distinctBase() == @[("hello", "world")]
diff --git a/tests/js/t21439.nim b/tests/js/t21439.nim
new file mode 100644
index 000000000..3caeb090a
--- /dev/null
+++ b/tests/js/t21439.nim
@@ -0,0 +1,11 @@
+proc test(a: openArray[string]): proc =
+  let a = @a
+  result = proc =
+    for i in a:
+      discard i
+
+
+const a = ["t1", "t2"]
+
+discard test(a)
+
diff --git a/tests/js/t7109.nim b/tests/js/t7109.nim
new file mode 100644
index 000000000..a1a3b718e
--- /dev/null
+++ b/tests/js/t7109.nim
@@ -0,0 +1,8 @@
+iterator iter*(): int {.closure.} =
+  yield 3
+
+var x = iter
+doAssert x() == 3
+
+let fIt = iterator(): int = yield 70
+doAssert fIt() == 70
diff --git a/tests/js/t7127.nim b/tests/js/t7127.nim
new file mode 100644
index 000000000..364aedd4a
--- /dev/null
+++ b/tests/js/t7127.nim
@@ -0,0 +1,2 @@
+doAssertRaises(DivByZeroDefect): discard 1 mod 0
+doAssertRaises(DivByZeroDefect): discard 1 div 0
\ No newline at end of file
diff --git a/tests/js/t7224.nim b/tests/js/t7224.nim
index be9d0ae9c..77fef10a7 100644
--- a/tests/js/t7224.nim
+++ b/tests/js/t7224.nim
@@ -1,10 +1,11 @@
 discard """
   cmd: "nim $target $options --stackTrace:on --lineTrace:on $file"
   outputsub: '''
-t7224.aaa, line: 21
-t7224.bbb, line: 18
-t7224.ccc, line: 15
-t7224.ddd, line: 12
+t7224.nim(25) at module t7224
+t7224.nim(22) at t7224.aaa
+t7224.nim(19) at t7224.bbb
+t7224.nim(16) at t7224.ccc
+t7224.nim(13) at t7224.ddd
 '''
 """
 
diff --git a/tests/js/t8231.nim b/tests/js/t8231.nim
new file mode 100644
index 000000000..b0625a621
--- /dev/null
+++ b/tests/js/t8231.nim
@@ -0,0 +1,3 @@
+import strutils
+
+doAssert formatSize(2462056448, '.', bpIEC, false) == "2.293GiB"
\ No newline at end of file
diff --git a/tests/js/t8821.nim b/tests/js/t8821.nim
new file mode 100644
index 000000000..38c88efa8
--- /dev/null
+++ b/tests/js/t8821.nim
@@ -0,0 +1,9 @@
+
+proc isInt32(i: int): bool =
+  case i 
+  of 1 .. 70000:
+    return true
+  else:
+    return false
+
+doAssert isInt32(1) == true
\ No newline at end of file
diff --git a/tests/js/t9410.nim b/tests/js/t9410.nim
index 78c329a24..042520dc5 100644
--- a/tests/js/t9410.nim
+++ b/tests/js/t9410.nim
@@ -447,10 +447,10 @@ template tests =
       doAssert seqOfSeqs == @[@[10, 2], @[30, 4]]
 
   when false:
-    block: # openarray
+    block: # openArray
           # Error: internal error: genAddr: nkStmtListExpr
       var calls = 0
-      proc getvarint(x: var openarray[int]): var int =
+      proc getvarint(x: var openArray[int]): var int =
         calls += 1
         if true:
           x[1]
diff --git a/tests/js/taddr.nim b/tests/js/taddr.nim
deleted file mode 100644
index d8ff4c11b..000000000
--- a/tests/js/taddr.nim
+++ /dev/null
@@ -1,79 +0,0 @@
-discard """
-  action: run
-"""
-
-type T = object
-  x: int
-  s: string
-
-var obj: T
-var fieldAddr = addr(obj.x)
-var objAddr = addr(obj)
-
-# Integer tests
-var field = fieldAddr[]
-doAssert field == 0
-
-var objDeref = objAddr[]
-doAssert objDeref.x == 0
-
-# Change value
-obj.x = 42
-
-doAssert field == 0
-doAssert objDeref.x == 0
-
-field = fieldAddr[]
-objDeref = objAddr[]
-
-doAssert field == 42
-doAssert objDeref.x == 42
-
-# String tests
-obj.s = "lorem ipsum dolor sit amet"
-var indexAddr = addr(obj.s[2])
-
-doAssert indexAddr[] == 'r'
-
-indexAddr[] = 'd'
-
-doAssert indexAddr[] == 'd'
-
-doAssert obj.s == "lodem ipsum dolor sit amet"
-
-# Bug #2148
-var x: array[2, int]
-var y = addr x[1]
-
-y[] = 12
-doAssert(x[1] == 12)
-
-type
-  Foo = object
-    bar: int
-
-var foo: array[2, Foo]
-var z = addr foo[1]
-
-z[].bar = 12345
-doAssert(foo[1].bar == 12345)
-
-var t : tuple[a, b: int]
-var pt = addr t[1]
-pt[] = 123
-doAssert(t.b == 123)
-
-#block: # Test "untyped" pointer.
-proc testPtr(p: pointer, a: int) =
-  doAssert(a == 5)
-  (cast[ptr int](p))[] = 124
-var i = 123
-testPtr(addr i, 5)
-doAssert(i == 124)
-
-var someGlobal = 5
-proc getSomeGlobalPtr(): ptr int = addr someGlobal
-let someGlobalPtr = getSomeGlobalPtr()
-doAssert(someGlobalPtr[] == 5)
-someGlobalPtr[] = 10
-doAssert(someGlobal == 10)
diff --git a/tests/js/tarrayboundscheck.nim b/tests/js/tarrayboundscheck.nim
index f0eaeb89d..d8bf8de97 100644
--- a/tests/js/tarrayboundscheck.nim
+++ b/tests/js/tarrayboundscheck.nim
@@ -39,6 +39,12 @@ proc test_arrayboundscheck() =
         echo "month out of bounds: ", idx
     except:
       echo "idx out of bounds: ", i
+  
+  # #13966
+  var negativeIndexed: array[-2..2, int] = [0, 1, 2, 3, 4]
+  negativeIndexed[-1] = 2
+  negativeIndexed[1] = 2
+  doAssert negativeIndexed == [0, 2, 2, 2, 4]
 
 test_arrayboundscheck()
 {.pop.}
\ No newline at end of file
diff --git a/tests/js/tasync.nim b/tests/js/tasync.nim
deleted file mode 100644
index 318237651..000000000
--- a/tests/js/tasync.nim
+++ /dev/null
@@ -1,33 +0,0 @@
-discard """
-  output: '''
-x
-e
-'''
-"""
-
-import asyncjs
-
-# demonstrate forward definition
-# for js
-proc y(e: int): Future[string] {.async.}
-
-proc e: int {.discardable.} =
-  echo "e"
-  return 2
-
-proc x(e: int): Future[void] {.async.} =
-  var s = await y(e)
-  if e > 2:
-    return
-  echo s
-  e()
-
-proc y(e: int): Future[string] {.async.} =
-  if e > 0:
-    return await y(0)
-  else:
-    return "x"
-
-
-discard x(2)
-
diff --git a/tests/js/tasyncjs.nim b/tests/js/tasyncjs.nim
new file mode 100644
index 000000000..f3b273c44
--- /dev/null
+++ b/tests/js/tasyncjs.nim
@@ -0,0 +1,107 @@
+discard """
+  output: '''
+x
+e
+done
+'''
+"""
+
+#[
+xxx move this to tests/stdlib/tasyncjs.nim
+]#
+
+import std/asyncjs
+
+block:
+  # demonstrate forward definition for js
+  proc y(e: int): Future[string] {.async.}
+
+  proc e: int {.discardable.} =
+    echo "e"
+    return 2
+
+  proc x(e: int): Future[void] {.async.} =
+    var s = await y(e)
+    if e > 2:
+      return
+    echo s
+    e()
+
+  proc y(e: int): Future[string] {.async.} =
+    if e > 0:
+      return await y(0)
+    else:
+      return "x"
+
+  discard x(2)
+
+import std/sugar
+from std/strutils import contains
+
+var witness: seq[string]
+
+proc fn(n: int): Future[int] {.async.} =
+  if n >= 7:
+    raise newException(ValueError, "foobar: " & $n)
+  if n > 0:
+    var ret = 1 + await fn(n-1)
+    witness.add $(n, ret)
+    return ret
+  else:
+    return 10
+
+proc asyncFact(n: int): Future[int] {.async.} =
+  if n > 0: result = n * await asyncFact(n-1)
+  else: result = 1
+
+proc asyncIdentity(n: int): Future[int] {.async.} =
+  if n > 0: result = 1 + await asyncIdentity(n-1)
+  else: result = 0
+
+proc main() {.async.} =
+  block: # then
+    let x = await fn(4)
+      .then((a: int) => a.float)
+      .then((a: float) => $a)
+    doAssert x == "14.0"
+    doAssert witness == @["(1, 11)", "(2, 12)", "(3, 13)", "(4, 14)"]
+
+    doAssert (await fn(2)) == 12
+
+    let x2 = await fn(4).then((a: int) => (discard)).then(() => 13)
+    doAssert x2 == 13
+
+    let x4 = await asyncFact(3).then(asyncIdentity).then(asyncIdentity).then((a:int) => a * 7).then(asyncIdentity)
+    doAssert x4 == 3 * 2 * 7
+
+    block: # bug #17177
+      proc asyncIdentityNested(n: int): Future[int] {.async.} = return n
+      let x5 = await asyncFact(3).then(asyncIdentityNested)
+      doAssert x5 == 3 * 2
+
+    when false: # xxx pending bug #17254
+      let x6 = await asyncFact(3).then((a:int) {.async.} => a * 11)
+      doAssert x6 == 3 * 2 * 11
+
+  block: # catch
+    var reason: Error
+    await fn(6).then((a: int) => (witness.add $a)).catch((r: Error) => (reason = r))
+    doAssert reason == nil
+
+    await fn(7).then((a: int) => (discard)).catch((r: Error) => (reason = r))
+    doAssert reason != nil
+    doAssert reason.name == "Error"
+    doAssert "foobar: 7" in $reason.message
+  echo "done" # justified here to make sure we're running this, since it's inside `async`
+
+block asyncPragmaInType:
+  type Handler = proc () {.async.}
+  proc foo() {.async.} = discard
+  var x: Handler = foo
+
+block: # 13341
+  proc f {.async.} =
+    proc g: int =
+      result = 123
+
+discard main()
diff --git a/tests/js/tasyncjs_bad.nim b/tests/js/tasyncjs_bad.nim
new file mode 100644
index 000000000..b1e5a7bc3
--- /dev/null
+++ b/tests/js/tasyncjs_bad.nim
@@ -0,0 +1,22 @@
+discard """
+  exitCode: 1
+ outputsub: "Error: unhandled exception: foobar: 13"
+"""
+
+# note: this needs `--unhandled-rejections=strict`, see D20210217T215950
+
+import std/asyncjs
+from std/sugar import `=>`
+
+proc fn(n: int): Future[int] {.async.} =
+  if n >= 7: raise newException(ValueError, "foobar: " & $n)
+  else: result = n
+
+proc main() {.async.} =
+  let x1 = await fn(6)
+  doAssert x1 == 6
+  await fn(7).catch((a: Error) => (discard))
+  let x3 = await fn(13)
+  doAssert false # shouldn't go here, should fail before
+
+discard main()
diff --git a/tests/js/tasync_pragma.nim b/tests/js/tasyncjs_pragma.nim
index 916769fad..2b6f32e92 100644
--- a/tests/js/tasync_pragma.nim
+++ b/tests/js/tasyncjs_pragma.nim
@@ -5,6 +5,8 @@ t
 '''
 """
 
+# xxx merge into tasyncjs.nim
+
 import asyncjs, macros
 
 macro f*(a: untyped): untyped =
diff --git a/tests/js/tbasics.nim b/tests/js/tbasics.nim
index b297bb037..ef84f8bb5 100644
--- a/tests/js/tbasics.nim
+++ b/tests/js/tbasics.nim
@@ -54,7 +54,7 @@ for x in someGlobal: doAssert(x == 0)
 proc tdefault =
   var x = default(int)
   doAssert(x == 0)
-  proc inner(v: openarray[string]) =
+  proc inner(v: openArray[string]) =
     doAssert(v.len == 0)
 
   inner(default(seq[string]))
diff --git a/tests/js/tbigint_backend.nim b/tests/js/tbigint_backend.nim
new file mode 100644
index 000000000..8f2f6c4f4
--- /dev/null
+++ b/tests/js/tbigint_backend.nim
@@ -0,0 +1,57 @@
+import std/private/jsutils
+
+
+type JsBigIntImpl {.importc: "bigint".} = int
+type JsBigInt = distinct JsBigIntImpl
+
+doAssert JsBigInt isnot int
+func big*(integer: SomeInteger): JsBigInt {.importjs: "BigInt(#)".}
+func big*(integer: cstring): JsBigInt {.importjs: "BigInt(#)".}
+func `<=`*(x, y: JsBigInt): bool {.importjs: "(# $1 #)".}
+func `==`*(x, y: JsBigInt): bool {.importjs: "(# === #)".}
+func inc*(x: var JsBigInt) {.importjs: "[#][0][0]++".}
+func inc2*(x: var JsBigInt) {.importjs: "#++".}
+func toCstring*(this: JsBigInt): cstring {.importjs: "#.toString()".}
+func `$`*(this: JsBigInt): string =
+  $toCstring(this)
+
+block:
+  doAssert defined(nimHasJsBigIntBackend)
+  let z1 = big"10"
+  let z2 = big"15"
+  doAssert z1 == big"10"
+  doAssert z1 == z1
+  doAssert z1 != z2
+  var s: seq[cstring]
+  for i in z1 .. z2:
+    s.add $i
+  doAssert s == @["10".cstring, "11", "12", "13", "14", "15"]
+  block:
+    var a=big"3"
+    a.inc
+    doAssert a == big"4"
+  block:
+    var z: JsBigInt
+    doAssert $z == "0"
+    doAssert z.jsTypeOf == "bigint" # would fail without codegen change
+    doAssert z != big(1)
+    doAssert z == big"0" # ditto
+
+  # ditto below
+  block:
+    let z: JsBigInt = big"1"
+    doAssert $z == "1"
+    doAssert z.jsTypeOf == "bigint"
+    doAssert z == big"1"
+
+  block:
+    let z = JsBigInt.default
+    doAssert $z == "0"
+    doAssert z.jsTypeOf == "bigint"
+    doAssert z == big"0"
+
+  block:
+    var a: seq[JsBigInt]
+    a.setLen 3
+    doAssert a[^1].jsTypeOf == "bigint"
+    doAssert a[^1] == big"0"
diff --git a/tests/js/tbyvar.nim b/tests/js/tbyvar.nim
index 705d62574..93724a2f1 100644
--- a/tests/js/tbyvar.nim
+++ b/tests/js/tbyvar.nim
@@ -1,15 +1,16 @@
 discard """
-  output: '''foo 12
+  output: '''
+foo 12
 bar 12
 2
 foo 12
 bar 12
 2
 12.5
-(nums: @[5, 5, 10, 5, 5, 5, 5, 5, 5, 5])
-(nums: @[5, 5, 50, 5, 5, 5, 5, 5, 5, 5])
-(nums: @[5, 5, 45, 5, 5, 5, 5, 5, 5, 5])
-(nums: @[5, 5, 9, 5, 5, 5, 5, 5, 5, 5])
+(nums: @[5.0, 5.0, 10.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0])
+(nums: @[5.0, 5.0, 50.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0])
+(nums: @[5.0, 5.0, 45.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0])
+(nums: @[5.0, 5.0, 9.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0, 5.0])
 asd
 '''
 """
@@ -38,9 +39,9 @@ proc main =
 
 main()
 
-# Test: pass var seq to var openarray
+# Test: pass var seq to var openArray
 var s = @[2, 1]
-proc foo(a: var openarray[int]) = a[0] = 123
+proc foo(a: var openArray[int]) = a[0] = 123
 
 proc bar(s: var seq[int], a: int) =
   doAssert(a == 5)
diff --git a/tests/js/tclosures.nim b/tests/js/tclosures.nim
index 3137123bf..4f1c28de3 100644
--- a/tests/js/tclosures.nim
+++ b/tests/js/tclosures.nim
@@ -22,7 +22,7 @@ asm """
     function print (text) { console.log (text); }
 """
 
-proc consoleprint (str:cstring): void {.importc: "print", noDecl.}
+proc consoleprint (str:cstring): void {.importc: "print", nodecl.}
 proc print* (a: varargs[string, `$`]) = consoleprint "$1: $2" % [consolePrefix, join(a, " ")]
 
 type CallbackProc {.importc.} = proc () : cstring
diff --git a/tests/js/tcodegendeclproc.nim b/tests/js/tcodegendeclproc.nim
index 3acf0bc13..33064bdf1 100644
--- a/tests/js/tcodegendeclproc.nim
+++ b/tests/js/tcodegendeclproc.nim
@@ -3,7 +3,7 @@ discard """
 -1
 8
 '''
-  ccodecheck: "'console.log(-1); function fac_' \\d+ '(n_' \\d+ ')'"
+  ccodecheck: "'console.log(-1); function fac__tcodegendeclproc_u1(n_p0)'"
 """
 proc fac(n: int): int {.codegenDecl: "console.log(-1); function $2($3)".} =
   return n
diff --git a/tests/js/tconsole.nim b/tests/js/tconsole.nim
index b2eecc656..88c71ea18 100644
--- a/tests/js/tconsole.nim
+++ b/tests/js/tconsole.nim
@@ -3,7 +3,6 @@ discard """
 Hello, console
 1 2 3
 '''
-  disabled: "freebsd"
 """
 
 # This file tests the JavaScript console
diff --git a/tests/js/tcsymbol.nim b/tests/js/tcsymbol.nim
new file mode 100644
index 000000000..07e52b9b6
--- /dev/null
+++ b/tests/js/tcsymbol.nim
@@ -0,0 +1,6 @@
+discard """
+  matrix: "--cc:gcc; --cc:tcc"
+"""
+
+doAssert not defined(gcc)
+doAssert not defined(tcc)
\ No newline at end of file
diff --git a/tests/js/tdanger.nim b/tests/js/tdanger.nim
new file mode 100644
index 000000000..9088859a8
--- /dev/null
+++ b/tests/js/tdanger.nim
@@ -0,0 +1,17 @@
+discard """
+  matrix: ";--d:danger"
+"""
+
+block:
+  proc foo() =
+    var name = int64(12)
+    var x = uint32(name)
+    var m = x + 12
+
+    var y = int32(name)
+    var n = y + 1
+
+    doAssert m == uint32(n + 11)
+
+
+  foo()
diff --git a/tests/js/tdiscard.nim b/tests/js/tdiscard.nim
new file mode 100644
index 000000000..9aa6ea1b1
--- /dev/null
+++ b/tests/js/tdiscard.nim
@@ -0,0 +1,3 @@
+import dom
+
+discard Node()
\ No newline at end of file
diff --git a/tests/js/tdollar_float.nim b/tests/js/tdollar_float.nim
new file mode 100644
index 000000000..4fd8e3cba
--- /dev/null
+++ b/tests/js/tdollar_float.nim
@@ -0,0 +1,62 @@
+#[
+merge into tests/system/tdollars.nim once https://github.com/nim-lang/Nim/pull/14122
+is merged
+]#
+
+import unittest
+
+block: # https://github.com/timotheecour/Nim/issues/133
+  # simple test
+  var a: float = 2
+  check $a == "2.0"
+
+  # systematic tests
+  template fun(a2: static float) =
+    const a: float = a2 # needed pending https://github.com/timotheecour/Nim/issues/132
+    var b = a
+    check $b == $a
+
+  fun 2
+  fun 2.0
+  fun 2.1
+  fun 1_000
+  fun 1_000.1
+  fun 1_000_000_000.1
+  fun 1_000_000_000_000.1
+
+  # negatives
+  fun -2.0
+  fun -2.1
+
+  # 0
+  fun 0
+  fun -0
+  fun 0.0
+
+  block:
+    var a = -0.0
+    check $a in ["-0.0", "0.0"]
+
+  # exponents
+  block:
+    var a = 5e20
+    check $a in ["5e20", "500000000000000000000.0"]
+
+  fun 3.4e1'f32
+  fun 3.4e-1'f32
+  fun -3.4e-1'f32
+  fun 3.4e-1'f32
+  fun 3e-1'f32
+
+  block:
+    var a = 3.4e38'f32
+    check $a in ["3.4e+38", "3.4e+038"]
+      # on windows, printf (used in VM) prints as 3.4e+038
+      # but js prints as 3.4e+38
+      # on osx, both print as 3.4e+38
+      # see https://github.com/timotheecour/Nim/issues/138
+
+  when false: # edge cases
+    fun -0.0 # see https://github.com/timotheecour/Nim/issues/136
+    fun 5e20
+    fun 3.4e38'f32
diff --git a/tests/js/temptyseq.nim b/tests/js/temptyseq.nim
new file mode 100644
index 000000000..6489cf817
--- /dev/null
+++ b/tests/js/temptyseq.nim
@@ -0,0 +1,8 @@
+# #12671
+
+proc foo =
+  var x: seq[int]
+  doAssertRaises(IndexDefect):
+    inc x[0]
+
+foo()
diff --git a/tests/js/tfieldchecks.nim b/tests/js/tfieldchecks.nim
index 77759a75a..a0679a349 100644
--- a/tests/js/tfieldchecks.nim
+++ b/tests/js/tfieldchecks.nim
@@ -24,15 +24,15 @@ var obj = X(f0: "foo", f1: C, f3: 3.14)
 block:
   echo obj.f0
   echo obj.f1
-  doAssertRaises(FieldError): echo obj.f2
+  doAssertRaises(FieldDefect): echo obj.f2
   echo obj.f3
 
 block:
   let a0 = addr(obj.f0)
   echo a0[]
-  # let a1 = unsafeAddr(obj.f1)
+  # let a1 = addr(obj.f1)
   # echo a1[]
-  doAssertRaises(FieldError):
+  doAssertRaises(FieldDefect):
     let a2 = addr(obj.f2)
     echo a2[]
   let a3 = addr(obj.f3)
diff --git a/tests/js/tglobal.nim b/tests/js/tglobal.nim
new file mode 100644
index 000000000..38f5eec34
--- /dev/null
+++ b/tests/js/tglobal.nim
@@ -0,0 +1,30 @@
+block global:
+  proc getState(): int =
+    var state0 {.global.}: int
+    inc state0
+    result = state0
+
+  for i in 0 ..< 3:
+    doAssert getState() == i + 1
+
+  for i in 0 ..< 3:
+    once:
+      doAssert i == 0
+
+
+block threadvar:
+  proc getThreadState0(): int =
+    var state0 {.threadvar.}: int
+    inc state0
+    result = state0
+
+  for i in 0 ..< 3:
+    doAssert getThreadState0() == i + 1
+
+  proc getThreadState1(): int =
+    var state1 {.threadvar.}: int
+    inc state1
+    result = state1
+
+  for i in 0 ..< 3:
+    doAssert getThreadState1() == i + 1
diff --git a/tests/js/tindexdefect.nim b/tests/js/tindexdefect.nim
new file mode 100644
index 000000000..37994ec2e
--- /dev/null
+++ b/tests/js/tindexdefect.nim
@@ -0,0 +1,9 @@
+discard """
+  outputsub: "unhandled exception: index 10000 not in 0 .. 0 [IndexDefect]"
+  exitcode: 1
+  joinable: false
+"""
+
+var s = ['a']
+let z = s[10000] == 'a'
+echo z
\ No newline at end of file
diff --git a/tests/js/tjsffi.nim b/tests/js/tjsffi.nim
index af33cee8a..f27ea5546 100644
--- a/tests/js/tjsffi.nim
+++ b/tests/js/tjsffi.nim
@@ -1,291 +1,197 @@
 discard """
+matrix: "--legacy:jsnolambdalifting;"
 output: '''
-true
-true
-true
-true
-true
-true
-true
-true
-true
-true
-true
-true
-true
-true
-true
-true
 3
 2
 12
 Event { name: 'click: test' }
 Event { name: 'reloaded: test' }
 Event { name: 'updates: test' }
-true
-true
-true
-true
-true
-true
-true
 '''
 """
 
 import jsffi, jsconsole
 
 # Tests for JsObject
-# Test JsObject []= and []
-block:
-  proc test(): bool =
-    let obj = newJsObject()
-    var working = true
-    obj["a"] = 11
-    obj["b"] = "test"
-    obj["c"] = "test".cstring
-    working = working and obj["a"].to(int) == 11
-    working = working and obj["c"].to(cstring) == "test".cstring
-    working
-  echo test()
+block: # Test JsObject []= and []
+  let obj = newJsObject()
+  obj["a"] = 11
+  obj["b"] = "test"
+  obj["c"] = "test".cstring
+  doAssert obj["a"].to(int) == 11
+  doAssert obj["c"].to(cstring) == "test".cstring
 
-# Test JsObject .= and .
-block:
-  proc test(): bool =
-    let obj = newJsObject()
-    var working = true
-    obj.a = 11
-    obj.b = "test"
-    obj.c = "test".cstring
-    obj.`$!&` = 42
-    obj.`while` = 99
-    working = working and obj.a.to(int) == 11
-    working = working and obj.b.to(string) == "test"
-    working = working and obj.c.to(cstring) == "test".cstring
-    working = working and obj.`$!&`.to(int) == 42
-    working = working and obj.`while`.to(int) == 99
-    working
-  echo test()
+block: # Test JsObject .= and .
+  let obj = newJsObject()
+  obj.a = 11
+  obj.b = "test"
+  obj.c = "test".cstring
+  obj.`$!&` = 42
+  obj.`while` = 99
+  doAssert obj.a.to(int) == 11
+  doAssert obj.b.to(string) == "test"
+  doAssert obj.c.to(cstring) == "test".cstring
+  doAssert obj.`$!&`.to(int) == 42
+  doAssert obj.`while`.to(int) == 99
 
-# Test JsObject .()
-block:
-  proc test(): bool =
-    let obj = newJsObject()
-    obj.`?!$` = proc(x, y, z: int, t: cstring): cstring = t & $(x + y + z)
-    obj.`?!$`(1, 2, 3, "Result is: ").to(cstring) == cstring"Result is: 6"
-  echo test()
+block: # Test JsObject .()
+  let obj = newJsObject()
+  obj.`?!$` = proc(x, y, z: int, t: cstring): cstring = t & $(x + y + z)
+  doAssert obj.`?!$`(1, 2, 3, "Result is: ").to(cstring) == cstring"Result is: 6"
 
-# Test JsObject []()
-block:
-  proc test(): bool =
-    let obj = newJsObject()
-    obj.a = proc(x, y, z: int, t: string): string = t & $(x + y + z)
-    let call = obj["a"].to(proc(x, y, z: int, t: string): string)
-    call(1, 2, 3, "Result is: ") == "Result is: 6"
-  echo test()
+block: # Test JsObject []()
+  let obj = newJsObject()
+  obj.a = proc(x, y, z: int, t: string): string = t & $(x + y + z)
+  let call = obj["a"].to(proc(x, y, z: int, t: string): string)
+  doAssert call(1, 2, 3, "Result is: ") == "Result is: 6"
 
 # Test JsObject Iterators
-block:
-  proc testPairs(): bool =
-    let obj = newJsObject()
-    var working = true
-    obj.a = 10
-    obj.b = 20
-    obj.c = 30
-    for k, v in obj.pairs:
-      case $k
-      of "a":
-        working = working and v.to(int) == 10
-      of "b":
-        working = working and v.to(int) == 20
-      of "c":
-        working = working and v.to(int) == 30
-      else:
-        return false
-    working
-  proc testItems(): bool =
-    let obj = newJsObject()
-    var working = true
-    obj.a = 10
-    obj.b = 20
-    obj.c = 30
-    for v in obj.items:
-      working = working and v.to(int) in [10, 20, 30]
-    working
-  proc testKeys(): bool =
-    let obj = newJsObject()
-    var working = true
-    obj.a = 10
-    obj.b = 20
-    obj.c = 30
-    for v in obj.keys:
-      working = working and $v in ["a", "b", "c"]
-    working
-  proc test(): bool = testPairs() and testItems() and testKeys()
-  echo test()
+block: # testPairs
+  let obj = newJsObject()
+  obj.a = 10
+  obj.b = 20
+  obj.c = 30
+  for k, v in obj.pairs:
+    case $k
+    of "a":
+      doAssert v.to(int) == 10
+    of "b":
+      doAssert v.to(int) == 20
+    of "c":
+      doAssert v.to(int) == 30
+    else:
+      doAssert false
+block: # testItems
+  let obj = newJsObject()
+  obj.a = 10
+  obj.b = 20
+  obj.c = 30
+  for v in obj.items:
+    doAssert v.to(int) in [10, 20, 30]
+block: # testKeys
+  let obj = newJsObject()
+  obj.a = 10
+  obj.b = 20
+  obj.c = 30
+  for v in obj.keys:
+    doAssert $v in ["a", "b", "c"]
 
-# Test JsObject equality
-block:
-  proc test(): bool =
-    {. emit: "var comparison = {a: 22, b: 'test'};" .}
-    var comparison {. importjs, nodecl .}: JsObject
-    let obj = newJsObject()
-    obj.a = 22
-    obj.b = "test".cstring
-    obj.a == comparison.a and obj.b == comparison.b
-  echo test()
+block: # Test JsObject equality
+  {. emit: "var comparison = {a: 22, b: 'test'};" .}
+  var comparison {. importjs, nodecl .}: JsObject
+  let obj = newJsObject()
+  obj.a = 22
+  obj.b = "test".cstring
+  doAssert obj.a == comparison.a and obj.b == comparison.b
 
-# Test JsObject literal
-block:
-  proc test(): bool =
-    {. emit: "var comparison = {a: 22, b: 'test'};" .}
-    var comparison {. importjs, nodecl .}: JsObject
-    let obj = JsObject{ a: 22, b: "test".cstring }
-    obj.a == comparison.a and obj.b == comparison.b
-  echo test()
+block: # Test JsObject literal
+  {. emit: "var comparison = {a: 22, b: 'test'};" .}
+  var comparison {. importjs, nodecl .}: JsObject
+  let obj = JsObject{ a: 22, b: "test".cstring }
+  doAssert obj.a == comparison.a and obj.b == comparison.b
 
 # Tests for JsAssoc
-# Test JsAssoc []= and []
-block:
-  proc test(): bool =
-    let obj = newJsAssoc[int, int]()
-    var working = true
-    obj[1] = 11
-    working = working and not compiles(obj["a"] = 11)
-    working = working and not compiles(obj["a"])
-    working = working and not compiles(obj[2] = "test")
-    working = working and not compiles(obj[3] = "test".cstring)
-    working = working and obj[1] == 11
-    working
-  echo test()
+block: # Test JsAssoc []= and []
+  let obj = newJsAssoc[int, int]()
+  obj[1] = 11
+  doAssert not compiles(obj["a"] = 11)
+  doAssert not compiles(obj["a"])
+  doAssert not compiles(obj[2] = "test")
+  doAssert not compiles(obj[3] = "test".cstring)
+  doAssert obj[1] == 11
 
-# Test JsAssoc .= and .
-block:
-  proc test(): bool =
-    let obj = newJsAssoc[cstring, int]()
-    var working = true
-    obj.a = 11
-    obj.`$!&` = 42
-    working = working and not compiles(obj.b = "test")
-    working = working and not compiles(obj.c = "test".cstring)
-    working = working and obj.a == 11
-    working = working and obj.`$!&` == 42
-    working
-  echo test()
+block: # Test JsAssoc .= and .
+  let obj = newJsAssoc[cstring, int]()
+  var working = true
+  obj.a = 11
+  obj.`$!&` = 42
+  doAssert not compiles(obj.b = "test")
+  doAssert not compiles(obj.c = "test".cstring)
+  doAssert obj.a == 11
+  doAssert obj.`$!&` == 42
 
-# Test JsAssoc .()
-block:
-  proc test(): bool =
-    let obj = newJsAssoc[cstring, proc(e: int): int]()
-    obj.a = proc(e: int): int = e * e
-    obj.a(10) == 100
-  echo test()
+block: # Test JsAssoc .()
+  let obj = newJsAssoc[cstring, proc(e: int): int]()
+  obj.a = proc(e: int): int = e * e
+  doAssert obj.a(10) == 100
 
-# Test JsAssoc []()
-block:
-  proc test(): bool =
-    let obj = newJsAssoc[cstring, proc(e: int): int]()
-    obj.a = proc(e: int): int = e * e
-    let call = obj["a"]
-    call(10) == 100
-  echo test()
+block: # Test JsAssoc []()
+  let obj = newJsAssoc[cstring, proc(e: int): int]()
+  obj.a = proc(e: int): int = e * e
+  let call = obj["a"]
+  doAssert call(10) == 100
 
 # Test JsAssoc Iterators
-block:
-  proc testPairs(): bool =
-    let obj = newJsAssoc[cstring, int]()
-    var working = true
-    obj.a = 10
-    obj.b = 20
-    obj.c = 30
-    for k, v in obj.pairs:
-      case $k
-      of "a":
-        working = working and v == 10
-      of "b":
-        working = working and v == 20
-      of "c":
-        working = working and v == 30
-      else:
-        return false
-    working
-  proc testItems(): bool =
-    let obj = newJsAssoc[cstring, int]()
-    var working = true
-    obj.a = 10
-    obj.b = 20
-    obj.c = 30
-    for v in obj.items:
-      working = working and v in [10, 20, 30]
-    working
-  proc testKeys(): bool =
-    let obj = newJsAssoc[cstring, int]()
-    var working = true
-    obj.a = 10
-    obj.b = 20
-    obj.c = 30
-    for v in obj.keys:
-      working = working and v in [cstring"a", cstring"b", cstring"c"]
-    working
-  proc test(): bool = testPairs() and testItems() and testKeys()
-  echo test()
+block: # testPairs
+  let obj = newJsAssoc[cstring, int]()
+  obj.a = 10
+  obj.b = 20
+  obj.c = 30
+  for k, v in obj.pairs:
+    case $k
+    of "a":
+      doAssert v == 10
+    of "b":
+      doAssert v == 20
+    of "c":
+      doAssert v == 30
+    else:
+      doAssert false
+block: # testItems
+  let obj = newJsAssoc[cstring, int]()
+  obj.a = 10
+  obj.b = 20
+  obj.c = 30
+  for v in obj.items:
+    doAssert v in [10, 20, 30]
+block: # testKeys
+  let obj = newJsAssoc[cstring, int]()
+  obj.a = 10
+  obj.b = 20
+  obj.c = 30
+  for v in obj.keys:
+    doAssert v in [cstring"a", cstring"b", cstring"c"]
 
-# Test JsAssoc equality
-block:
-  proc test(): bool =
-    {. emit: "var comparison = {a: 22, b: 55};" .}
-    var comparison {. importjs, nodecl .}: JsAssoc[cstring, int]
-    let obj = newJsAssoc[cstring, int]()
-    obj.a = 22
-    obj.b = 55
-    obj.a == comparison.a and obj.b == comparison.b
-  echo test()
+block: # Test JsAssoc equality
+  {. emit: "var comparison = {a: 22, b: 55};" .}
+  var comparison {. importjs, nodecl .}: JsAssoc[cstring, int]
+  let obj = newJsAssoc[cstring, int]()
+  obj.a = 22
+  obj.b = 55
+  doAssert obj.a == comparison.a and obj.b == comparison.b
 
-# Test JsAssoc literal
-block:
-  proc test(): bool =
-    {. emit: "var comparison = {a: 22, b: 55};" .}
-    var comparison {. importjs, nodecl .}: JsAssoc[cstring, int]
-    let obj = JsAssoc[cstring, int]{ a: 22, b: 55 }
-    var working = true
-    working = working and
-      compiles(JsAssoc[int, int]{ 1: 22, 2: 55 })
-    working = working and
-      comparison.a == obj.a and comparison.b == obj.b
-    working = working and
-      not compiles(JsAssoc[cstring, int]{ a: "test" })
-    working
-  echo test()
+block: # Test JsAssoc literal
+  {. emit: "var comparison = {a: 22, b: 55};" .}
+  var comparison {. importjs, nodecl .}: JsAssoc[cstring, int]
+  let obj = JsAssoc[cstring, int]{ a: 22, b: 55 }
+  doAssert compiles(JsAssoc[int, int]{ 1: 22, 2: 55 })
+  doAssert comparison.a == obj.a and comparison.b == obj.b
+  doAssert not compiles(JsAssoc[cstring, int]{ a: "test" })
 
 # Tests for macros on non-JsRoot objects
-# Test lit
-block:
+block: # Test lit
   type TestObject = object
     a: int
     b: cstring
-  proc test(): bool =
-    {. emit: "var comparison = {a: 1};" .}
-    var comparison {. importjs, nodecl .}: TestObject
-    let obj = TestObject{ a: 1 }
-    obj == comparison
-  echo test()
+  {. emit: "var comparison = {a: 1};" .}
+  var comparison {. importjs, nodecl .}: TestObject
+  let obj = TestObject{ a: 1 }
+  doAssert obj == comparison
 
-# Test bindMethod
-block:
+block: # Test bindMethod
   type TestObject = object
     a: int
-    onWhatever: proc(e: int): int
+    onWhatever: proc(e: int): int {.nimcall.}
   proc handleWhatever(this: TestObject, e: int): int =
     e + this.a
-  proc test(): bool =
+  block:
     let obj = TestObject(a: 9, onWhatever: bindMethod(handleWhatever))
-    obj.onWhatever(1) == 10
-  echo test()
+    doAssert obj.onWhatever(1) == 10
 
 block:
   {.emit: "function jsProc(n) { return n; }" .}
   proc jsProc(x: int32): JsObject {.importjs: "jsProc(#)".}
-
-  proc test() =
+  block:
     var x = jsProc(1)
     var y = jsProc(2)
     console.log x + y
@@ -294,8 +200,6 @@ block:
     x += jsProc(10)
     console.log x
 
-  test()
-
 block:
   {.emit:
   """
@@ -314,7 +218,7 @@ block:
   on("click") do (e: Event):
     console.log e
 
-  jslib.on("reloaded") do:
+  jslib.on("reloaded") do ():
     console.log jsarguments[0]
 
   # this test case is different from the above, because
@@ -323,11 +227,48 @@ block:
     console.log jsarguments[0]
 
 block:
+  doAssert jsUndefined == jsNull
+  doAssert jsUndefined == nil
+  doAssert jsNull == nil
+  doAssert jsUndefined.isNil
+  doAssert jsNull.isNil
+  doAssert jsNull.isNull
+  doAssert jsUndefined.isUndefined
+
+block: # test **
+  var a = toJs(0)
+  var b = toJs(0)
+  doAssert to(a ** b, int) == 1
+  a = toJs(1)
+  b = toJs(1)
+  doAssert to(a ** b, int) == 1
+  a = toJs(-1)
+  b = toJs(-1)
+  doAssert to(a ** b, int) == -1
+  a = toJs(6)
+  b = toJs(6)
+  doAssert to(a ** b, int) == 46656
+  a = toJs(5.5)
+  b = toJs(3)
+  doAssert to(a ** b, float) == 166.375
+  a = toJs(5)
+  b = toJs(3.0)
+  doAssert to(a ** b, float) == 125.0
+  a = toJs(7.0)
+  b = toJS(6.0)
+  doAssert to(a ** b, float) == 117649.0
+  a = toJs(8)
+  b = toJS(-2)
+  doAssert to(a ** b, float) == 0.015625
+
+  a = toJs(1)
+  b = toJs(1)
+  doAssert to(`**`(a + a, b), int) == 2
+
+  doAssert to(`**`(toJs(1) + toJs(1), toJs(2)), int) == 4
 
-  echo jsUndefined == jsNull
-  echo jsUndefined == nil
-  echo jsNull == nil
-  echo jsUndefined.isNil
-  echo jsNull.isNil
-  echo jsNull.isNull
-  echo jsUndefined.isUndefined
+block: # issue #21208
+  type MyEnum = enum baz
+  var obj: JsObject
+  {.emit: "`obj` = {bar: {baz: 123}};".}
+  discard obj.bar.baz
diff --git a/tests/js/tjsffi_old.nim b/tests/js/tjsffi_old.nim
index 1f149694b..378003f4e 100644
--- a/tests/js/tjsffi_old.nim
+++ b/tests/js/tjsffi_old.nim
@@ -35,6 +35,9 @@ true
 ## same as tjsffi, but this test uses the old names: importc and
 ## importcpp. This test is for backwards compatibility.
 
+# xxx instead of maintaining this near-duplicate test file, just have tests
+# that check that importc, importcpp, importjs work and remove this file.
+
 import jsffi, jsconsole
 
 # Tests for JsObject
@@ -276,8 +279,8 @@ block:
 block:
   type TestObject = object
     a: int
-    onWhatever: proc(e: int): int
-  proc handleWhatever(this: TestObject, e: int): int =
+    onWhatever: proc(e: int): int {.nimcall.}
+  proc handleWhatever(this: TestObject, e: int): int {.nimcall.} =
     e + this.a
   proc test(): bool =
     let obj = TestObject(a: 9, onWhatever: bindMethod(handleWhatever))
@@ -318,7 +321,7 @@ block:
   on("click") do (e: Event):
     console.log e
 
-  jslib.on("reloaded") do:
+  jslib.on("reloaded") do ():
     console.log jsarguments[0]
 
   # this test case is different from the above, because
diff --git a/tests/js/tjshello.nim b/tests/js/tjshello.nim
index 19e0b90ae..8e090b3d2 100644
--- a/tests/js/tjshello.nim
+++ b/tests/js/tjshello.nim
@@ -1,4 +1,5 @@
 discard """
+  cmd: "nim $target $options --stackTrace:off --lineTrace:off $file"
   output: "Hello World"
   maxcodesize: 1000
   ccodecheck: "!@'function'"
@@ -7,4 +8,3 @@ discard """
 import jsconsole
 
 console.log "Hello World"
-
diff --git a/tests/js/tjshello_stacktrace.nim b/tests/js/tjshello_stacktrace.nim
new file mode 100644
index 000000000..d5e1c36eb
--- /dev/null
+++ b/tests/js/tjshello_stacktrace.nim
@@ -0,0 +1,9 @@
+discard """
+  output: "Hello World"
+  maxcodesize: 4500
+  ccodecheck: "!@'function'"
+"""
+
+import jsconsole
+
+console.log "Hello World"
diff --git a/tests/js/tjsnimscombined.nim b/tests/js/tjsnimscombined.nim
new file mode 100644
index 000000000..4d3e6c453
--- /dev/null
+++ b/tests/js/tjsnimscombined.nim
@@ -0,0 +1 @@
+import std/jsffi
diff --git a/tests/js/tjsnimscombined.nims b/tests/js/tjsnimscombined.nims
new file mode 100644
index 000000000..01b93d3fa
--- /dev/null
+++ b/tests/js/tjsnimscombined.nims
@@ -0,0 +1 @@
+# test the condition where both `js` and `nimscript` are defined (nimscript receives priority)
diff --git a/tests/js/tlent.nim b/tests/js/tlent.nim
new file mode 100644
index 000000000..2546e5b1d
--- /dev/null
+++ b/tests/js/tlent.nim
@@ -0,0 +1,33 @@
+discard """
+  output: '''
+hmm
+100
+hmm
+100
+'''
+"""
+
+# #16800
+
+type A = object
+  b: int
+var t = A(b: 100)
+block:
+  proc getValues: lent int =
+    echo "hmm"
+    result = t.b
+  echo getValues()
+block:
+  proc getValues: lent int =
+    echo "hmm"
+    t.b
+  echo getValues()
+
+when false: # still an issue, #16908
+  template main =
+    iterator fn[T](a:T): lent T = yield a
+    let a = @[10]
+    for b in fn(a): echo b
+
+  static: main()
+  main()
diff --git a/tests/js/tmangle.nim b/tests/js/tmangle.nim
index c97bf7029..caaa15fa1 100644
--- a/tests/js/tmangle.nim
+++ b/tests/js/tmangle.nim
@@ -62,8 +62,8 @@ block:
     result = result and obj1.`&&`.addr[] == "bar".cstring
     result = result and obj2.`if` == 0
     result = result and obj2.`for` == 0
-    result = result and obj2.`==`.isNil()
-    result = result and obj2.`&&`.isNil()
+    result = result and obj2.`==`.isNil
+    result = result and obj2.`&&`.isNil
   echo test()
 
 # Test codegen for fields with uppercase letters:
diff --git a/tests/js/tmodify_cstring.nim b/tests/js/tmodify_cstring.nim
new file mode 100644
index 000000000..82f8ccb23
--- /dev/null
+++ b/tests/js/tmodify_cstring.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "cstring doesn't support `[]=` operator"
+"""
+
+var x = cstring"abcd"
+x[0] = 'x'
diff --git a/tests/js/tnativeexc.nim b/tests/js/tnativeexc.nim
index ea371c1cd..8b2b43e8f 100644
--- a/tests/js/tnativeexc.nim
+++ b/tests/js/tnativeexc.nim
@@ -18,7 +18,7 @@ try:
 except JsEvalError:
   doAssert false
 except JsSyntaxError as se:
-  doAssert se.message == "Unexpected token ; in JSON at position 0"
+  doAssert se.message == "Unexpected token ';', \";;\" is not valid JSON"
 except JsError as e:
   doAssert false
 
diff --git a/tests/js/tneginthash.nim b/tests/js/tneginthash.nim
new file mode 100644
index 000000000..c082405c9
--- /dev/null
+++ b/tests/js/tneginthash.nim
@@ -0,0 +1,21 @@
+# issue #19929
+
+import std/[tables, hashes]
+
+type Foo = object
+  a: int
+
+proc hash(f: Foo): Hash =
+  var h: Hash = 0
+  h = h !& hash(f.a)
+  result = !$h
+
+proc transpose[T, S](data: array[T, S]): Table[S, T] =
+  for i, x in data:
+    result[x] = i
+
+const xs = [Foo(a: 5), Foo(a: -5)]
+const x = transpose(xs)
+
+doAssert x[Foo(a: -5)] == 1
+doAssert x[Foo(a: 5)] == 0
diff --git a/tests/js/tnilstrs.nim b/tests/js/tnilstrs.nim
index c0048cb24..6c1e4e401 100644
--- a/tests/js/tnilstrs.nim
+++ b/tests/js/tnilstrs.nim
@@ -14,4 +14,12 @@ block:
   var x = "foo".cstring
   var y: string
   add(y, x)
-  doAssert y == "foo"
\ No newline at end of file
+  doAssert y == "foo"
+
+block:
+  type Foo = object
+    a: string
+  var foo = Foo(a: "foo")
+  var y = move foo.a
+  doAssert foo.a.len == 0
+  doAssert y == "foo"
diff --git a/tests/js/tos.nim b/tests/js/tos.nim
new file mode 100644
index 000000000..40fb52bcf
--- /dev/null
+++ b/tests/js/tos.nim
@@ -0,0 +1,21 @@
+# xxx consider merging this in tests/stdlib/tos.nim for increased coverage (with selecting disabling)
+
+static: doAssert defined(nodejs)
+
+import os
+
+block:
+  doAssert "./foo//./bar/".normalizedPath == "foo/bar"
+  doAssert relativePath(".//foo/bar", "foo") == "bar"
+  doAssert "/".isAbsolute
+  doAssert not "".isAbsolute
+  doAssert not ".".isAbsolute
+  doAssert not "foo".isAbsolute
+  doAssert relativePath("", "bar") == ""
+  doAssert normalizedPath(".///foo//./") == "foo"
+
+  when nimvm: discard
+  else:
+    let cwd = getCurrentDir()
+    doAssert cwd.isAbsolute
+    doAssert relativePath(getCurrentDir() / "foo", "bar") == ".." / "foo"
diff --git a/tests/js/trepr.nim b/tests/js/trepr.nim
index 366d247c5..a562ad63b 100644
--- a/tests/js/trepr.nim
+++ b/tests/js/trepr.nim
@@ -1,6 +1,4 @@
-discard """
-  action: run
-"""
+# xxx consider merging with `tests/stdlib/trepr.nim` to increase overall test coverage
 
 block ints:
   let
@@ -137,15 +135,13 @@ block tuples:
   when defined js:
     doAssert(repr(ot) == """
 [Field0 = true,
-Field1 = 120]
-""")
+Field1 = 120]""")
     doAssert(repr(t) == """
 [Field0 = 42,
 Field1 = 12.34,
 Field2 = "tuple",
 Field3 = [Field0 = true,
-Field1 = 120]]
-""")
+Field1 = 120]]""")
 
 block objects:
   type
@@ -162,14 +158,12 @@ block objects:
 
   doAssert(repr(oo) == """
 [a = true,
-b = 120]
-""")
+b = 120]""")
   doAssert(repr(o) == """
 [a = 42,
 b = 12.34,
 c = [a = true,
-b = 120]]
-""")
+b = 120]]""")
 
 block arrays:
   type
@@ -183,15 +177,14 @@ block arrays:
     c = [o, o, o]
     d = ["hi", "array", "!"]
 
-  doAssert(repr(a) == "[0.0, 1.0, 2.0]\n")
-  doAssert(repr(b) == "[[0.0, 1.0, 2.0], [0.0, 1.0, 2.0], [0.0, 1.0, 2.0]]\n")
+  doAssert(repr(a) == "[0.0, 1.0, 2.0]")
+  doAssert(repr(b) == "[[0.0, 1.0, 2.0], [0.0, 1.0, 2.0], [0.0, 1.0, 2.0]]")
   doAssert(repr(c) == """
 [[x = 42,
 y = [0.0, 1.0, 2.0]], [x = 42,
 y = [0.0, 1.0, 2.0]], [x = 42,
-y = [0.0, 1.0, 2.0]]]
-""")
-  doAssert(repr(d) == "[\"hi\", \"array\", \"!\"]\n")
+y = [0.0, 1.0, 2.0]]]""")
+  doAssert(repr(d) == "[\"hi\", \"array\", \"!\"]")
 
 block seqs:
   type
@@ -205,15 +198,14 @@ block seqs:
     c = @[o, o, o]
     d = @["hi", "array", "!"]
 
-  doAssert(repr(a) == "@[0.0, 1.0, 2.0]\n")
-  doAssert(repr(b) == "@[@[0.0, 1.0, 2.0], @[0.0, 1.0, 2.0], @[0.0, 1.0, 2.0]]\n")
+  doAssert(repr(a) == "@[0.0, 1.0, 2.0]")
+  doAssert(repr(b) == "@[@[0.0, 1.0, 2.0], @[0.0, 1.0, 2.0], @[0.0, 1.0, 2.0]]")
   doAssert(repr(c) == """
 @[[x = 42,
 y = @[0.0, 1.0, 2.0]], [x = 42,
 y = @[0.0, 1.0, 2.0]], [x = 42,
-y = @[0.0, 1.0, 2.0]]]
-""")
-  doAssert(repr(d) == "@[\"hi\", \"array\", \"!\"]\n")
+y = @[0.0, 1.0, 2.0]]]""")
+  doAssert(repr(d) == "@[\"hi\", \"array\", \"!\"]")
 
 block ptrs:
   type
@@ -226,13 +218,12 @@ block ptrs:
     c = addr a[2]
     d = AObj()
 
-  doAssert(repr(a) == "[12.0, 13.0, 14.0]\n")
-  doAssert(repr(b) == "ref 0 --> 12.0\n")
-  doAssert(repr(c) == "ref 2 --> 14.0\n")
+  doAssert(repr(a) == "[12.0, 13.0, 14.0]")
+  doAssert(repr(b) == "ref 0 --> 12.0")
+  doAssert(repr(c) == "ref 2 --> 14.0")
   doAssert(repr(d) == """
 [x = nil,
-y = 0]
-""")
+y = 0]""")
 
 block ptrs:
   type
@@ -248,8 +239,7 @@ block ptrs:
 [x = ref 0 --> [[x = nil,
 y = 0], [x = nil,
 y = 0]],
-y = 0]
-""")
+y = 0]""")
 
 block procs:
   proc test(): int =
@@ -258,9 +248,9 @@ block procs:
     ptest = test
     nilproc: proc(): int
 
-  doAssert(repr(test) == "0\n")
-  doAssert(repr(ptest) == "0\n")
-  doAssert(repr(nilproc) == "nil\n")
+  doAssert(repr(test) == "0")
+  doAssert(repr(ptest) == "0")
+  doAssert(repr(nilproc) == "nil")
 
 block bunch:
   type
@@ -293,7 +283,7 @@ block bunch:
     result[] = b
 
   var
-    aa: A
+    aa = default(A)
     bb: B = B(a: "inner", b: @['o', 'b', 'j'])
     cc: A = A(a: 12, b: 1, c: 1.2, d: '\0', e: eC,
                 f: "hello", g: {'A'}, h: {2'i16},
@@ -308,22 +298,21 @@ b = 0,
 c = 0.0,
 d = '\0',
 e = eA,
-f = nil,
+f = "",
 g = {},
 h = {},
-i = [nil, nil, nil],
-j = nil,
-k = 0,
-l = [a = nil,
-b = nil],
+i = ["", "", ""],
+j = @[],
+k = -12,
+l = [a = "",
+b = @[]],
 m = nil,
 n = nil,
-o = [Field0 = [a = nil,
-b = nil],
-Field1 = nil],
+o = [Field0 = [a = "",
+b = @[]],
+Field1 = ""],
 p = nil,
-q = nil]
-""")
+q = nil]""")
   doAssert(repr(cc) == """
 [a = 12,
 b = 1,
@@ -346,8 +335,7 @@ o = [Field0 = [a = "inner",
 b = @['o', 'b', 'j']],
 Field1 = "tuple!"],
 p = 0,
-q = "cstringtest"]
-""")
+q = "cstringtest"]""")
 
 block another:
   type
@@ -358,9 +346,9 @@ block another:
     Size3 = enum
       s3e=0, s3f=2000000000
 
-  doAssert(repr([s1a, s1b]) == "[s1a, s1b]\n")
-  doAssert(repr([s2c, s2d]) == "[s2c, s2d]\n")
-  doAssert(repr([s3e, s3f]) == "[s3e, s3f]\n")
+  doAssert(repr([s1a, s1b]) == "[s1a, s1b]")
+  doAssert(repr([s2c, s2d]) == "[s2c, s2d]")
+  doAssert(repr([s3e, s3f]) == "[s3e, s3f]")
 
 block another2:
 
@@ -395,15 +383,13 @@ block another2:
 y = 13,
 z = 45,
 s = ["abc", "xyz"],
-e = en6]
-""")
+e = en6]""")
   doAssert(repr(q) == """
 ref 0 --> [x = 0,
 y = 13,
 z = 45,
 s = ["abc", "xyz"],
-e = en6]
-""")
+e = en6]""")
   doAssert(repr(s) == """
 @[ref 0 --> [x = 0,
 y = 13,
@@ -421,8 +407,7 @@ e = en6], ref 3 --> [x = 0,
 y = 13,
 z = 45,
 s = ["abc", "xyz"],
-e = en6]]
-""")
+e = en6]]""")
   doAssert(repr(en4) == "en4")
 
   doAssert(repr({'a'..'p'}) == "{'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'}")
diff --git a/tests/js/treprinifexpr.nim b/tests/js/treprinifexpr.nim
new file mode 100644
index 000000000..09ded18b9
--- /dev/null
+++ b/tests/js/treprinifexpr.nim
@@ -0,0 +1,18 @@
+type
+  Enum = enum A
+
+let
+  enumVal = A
+  tmp = if true: $enumVal else: $enumVal
+
+let
+  intVal = 12
+  tmp2 = if true: repr(intVal) else: $enumVal
+
+let
+  strVal = "123"
+  tmp3 = if true: repr(strVal) else: $strVal
+
+let
+  floatVal = 12.4
+  tmp4 = if true: repr(floatVal) else: $floatVal
\ No newline at end of file
diff --git a/tests/js/tseqops.nim b/tests/js/tseqops.nim
index af664222c..8cfb50886 100644
--- a/tests/js/tseqops.nim
+++ b/tests/js/tseqops.nim
@@ -1,11 +1,3 @@
-discard """
-  output: '''(x: 0, y: 0)
-(x: 5, y: 0)
-@[(x: "2", y: 4), (x: "4", y: 5), (x: "4", y: 5)]
-@[(a: "3", b: 3), (a: "1", b: 1), (a: "2", b: 2)]
-'''
-"""
-
 # bug #4139
 
 type
@@ -17,8 +9,8 @@ proc onLoad() =
   var foo = TestO(x: 0, y: 0)
   test.add(foo)
   foo.x = 5
-  echo(test[0])
-  echo foo
+  doAssert $test[0] == "(x: 0, y: 0)"
+  doAssert $foo == "(x: 5, y: 0)"
 
 onLoad()
 
@@ -34,7 +26,7 @@ proc foo(x: var seq[MyObj]) =
 
 var s = @[MyObj(x: "2", y: 4), MyObj(x: "4", y: 5)]
 foo(s)
-echo s
+doAssert $s == """@[(x: "2", y: 4), (x: "4", y: 5), (x: "4", y: 5)]"""
 
 # bug  #5933
 import sequtils
@@ -48,4 +40,9 @@ var test = @[Test(a: "1", b: 1), Test(a: "2", b: 2)]
 
 test.insert(@[Test(a: "3", b: 3)], 0)
 
-echo test
+doAssert $test == """@[(a: "3", b: 3), (a: "1", b: 1), (a: "2", b: 2)]"""
+
+proc hello(): array[5, int] = discard
+var x = @(hello())
+x.add(2)
+doAssert x == @[0, 0, 0, 0, 0, 2]
diff --git a/tests/js/tsourcemap.nim b/tests/js/tsourcemap.nim
new file mode 100644
index 000000000..d358e4a57
--- /dev/null
+++ b/tests/js/tsourcemap.nim
@@ -0,0 +1,96 @@
+discard """
+  action: "run"
+  targets: "js"
+  cmd: "nim js -r -d:nodejs $options --sourceMap:on $file"
+"""
+import std/[os, json, strutils, sequtils, algorithm, assertions, paths, compilesettings]
+
+# Implements a very basic sourcemap parser and then runs it on itself.
+# Allows to check for basic problems such as bad counts and lines missing (e.g. issue #21052)
+
+type
+  SourceMap = object
+    version:   int
+    sources:   seq[string]
+    names:     seq[string]
+    mappings:  string
+    file:      string
+
+  Line = object
+    line, column: int
+    file: string
+
+const
+  flag = 1 shl 5
+  signBit = 0b1
+  fourBits = 0b1111
+  fiveBits = 0b11111
+  mask = (1 shl 5) - 1
+  alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
+
+var b64Table: seq[int] = 0.repeat(max(alphabet.mapIt(it.ord)) + 1)
+for i, b in alphabet.pairs:
+  b64Table[b.ord] = i
+
+# From https://github.com/juancarlospaco/nodejs/blob/main/src/nodejs/jsfs.nim
+proc importFs*() {.importjs: "var fs = require(\"fs\");".}
+proc readFileSync*(path: cstring): cstring {.importjs: "(fs.$1(#).toString())".}
+importFS()
+# Read in needed files
+let
+  jsFileName = string(querySetting(outDir).Path / "tsourcemap.js".Path)
+  mapFileName = jsFileName & ".map"
+
+  data = parseJson($mapFileName.cstring.readFileSync()).to(SourceMap)
+  jsFile = $readFileSync(jsFileName.cstring)
+
+proc decodeVLQ(inp: string): seq[int] =
+  var
+    shift, value: int
+  for v in inp.mapIt(b64Table[it.ord]):
+    value += (v and mask) shl shift
+    if (v and flag) > 0:
+      shift += 5
+      continue
+    result &= (value shr 1) * (if (value and 1) > 0: -1 else: 1)
+    shift = 0
+    value = 0
+
+
+# Keep track of state
+var
+  line = 0
+  source = 0
+  name = 0
+  column = 0
+  jsLine = 1
+  lines: seq[Line]
+
+for gline in data.mappings.split(';'):
+  jsLine += 1
+  var jsColumn = 0
+  for item in gline.strip().split(','):
+    let value = item.decodeVLQ()
+    doAssert value.len in [0, 1, 4, 5]
+    if value.len == 0:
+      continue
+    jsColumn += value[0]
+    if value.len >= 4:
+      source += value[1]
+      line += value[2]
+      column += value[3]
+      lines &= Line(line: line, column: column, file: data.sources[source])
+
+let jsLines = jsFile.splitLines().len
+# There needs to be a mapping for every line in the JS
+# If there isn't then the JS lines wont match up with Nim lines.
+# Except we don't care about the final line since that doesn't need to line up
+doAssert data.mappings.count(';') == jsLines - 1
+
+# Check we can find this file somewhere in the source map
+var foundSelf = false
+for line in lines:
+  if "tsourcemap.nim" in line.file:
+    foundSelf = true
+    doAssert line.line in 0..<jsLines, "Lines is out of bounds for file"
+doAssert foundSelf, "Couldn't find tsourcemap.nim in source map"
diff --git a/tests/js/tstdlib_imports.nim b/tests/js/tstdlib_imports.nim
new file mode 100644
index 000000000..db851ba28
--- /dev/null
+++ b/tests/js/tstdlib_imports.nim
@@ -0,0 +1,80 @@
+discard """
+  action: compile
+"""
+
+{.warning[UnusedImport]: off.}
+
+when defined(nimPreviewSlimSystem):
+  import std/[
+    syncio, assertions, formatfloat, objectdollar, widestrs
+  ]
+
+import std/[
+  # Core:
+  bitops, typetraits, lenientops, macros, volatile, typeinfo,
+  # fails due to FFI: rlocks
+  # fails due to cstring cast/copyMem: endians
+  # works but uses FFI: cpuinfo, locks
+
+  # Algorithms:
+  algorithm, enumutils, sequtils, setutils,
+  
+  # Collections:
+  critbits, deques, heapqueue, intsets, lists, options, sets,
+  tables, packedsets,
+
+  # Strings:
+  cstrutils, editdistance, wordwrap, parseutils, ropes,
+  pegs, strformat, strmisc, strscans, strtabs,
+  strutils, unicode, unidecode,
+  # fails due to FFI: encodings
+
+  # Time handling:
+  monotimes, times,
+
+  # Generic operator system services:
+  os, streams,
+  # fails intentionally: dynlib, marshal, memfiles
+  # fails due to FFI: osproc, terminal
+  # fails due to osproc import: distros
+
+  # Math libraries:
+  complex, math, random, rationals, stats, sums, sysrand,
+  # works but uses FFI: fenv
+
+  # Internet protocols:
+  cookies, httpcore, mimetypes, uri,
+  # fails due to FFI: asyncdispatch, asyncfile, asyncftpclient, asynchttpserver,
+  # asyncnet, cgi, httpclient, nativesockets, net, selectors
+  # works but no need to test: asyncstreams, asyncfutures
+  
+  # Threading:
+  # fails due to FFI: threadpool
+
+  # Parsers:
+  htmlparser, json, lexbase, parsecfg, parsecsv, parsesql, parsexml,
+  parseopt, jsonutils,
+
+  # XML processing:
+  xmltree, xmlparser,
+
+  # Generators:
+  htmlgen,
+
+  # Hashing:
+  base64, hashes,
+  # fails due to cstring cast/endians import: oids
+  # fails due to copyMem/endians import: sha1
+
+  # Miscellaneous:
+  colors, logging, sugar, unittest, varints, enumerate, with,
+  # fails due to FFI: browsers, coro
+  # works but uses FFI: segfaults
+
+  # Modules for JS backend:
+  asyncjs, dom, jsconsole, jscore, jsffi, jsbigints,
+
+  # Unlisted in lib.html:
+  decls, compilesettings, wrapnils, exitprocs, effecttraits,
+  genasts, importutils, isolation, jsfetch, jsformdata, jsheaders
+]
diff --git a/tests/js/tstdlib_various.nim b/tests/js/tstdlib_various.nim
new file mode 100644
index 000000000..1e584f735
--- /dev/null
+++ b/tests/js/tstdlib_various.nim
@@ -0,0 +1,174 @@
+discard """
+output: '''
+abc
+def
+definition
+prefix
+xyz
+def
+definition
+Hi Andreas! How do you feel, Rumpf?
+
+@[0, 2, 1]
+@[1, 0, 2]
+@[1, 2, 0]
+@[2, 0, 1]
+@[2, 1, 0]
+@[2, 0, 1]
+@[1, 2, 0]
+@[1, 0, 2]
+@[0, 2, 1]
+@[0, 1, 2]
+[5]
+[4, 5]
+[3, 4, 5]
+[2, 3, 4, 5]
+[2, 3, 4, 5, 6]
+[1, 2, 3, 4, 5, 6]
+'''
+"""
+
+import
+  critbits, sets, strutils, tables, random, algorithm, ropes,
+  lists, htmlgen, xmltree, strtabs
+
+
+block tcritbits:
+  var r: CritBitTree[void]
+  r.incl "abc"
+  r.incl "xyz"
+  r.incl "def"
+  r.incl "definition"
+  r.incl "prefix"
+  doAssert r.contains"def"
+  #r.del "def"
+
+  for w in r.items:
+    echo w
+  for w in r.itemsWithPrefix("de"):
+    echo w
+
+
+
+block testequivalence:
+  doAssert(toHashSet(@[1,2,3]) <= toHashSet(@[1,2,3,4]), "equivalent or subset")
+  doAssert(toHashSet(@[1,2,3]) <= toHashSet(@[1,2,3]), "equivalent or subset")
+  doAssert((not(toHashSet(@[1,2,3]) <= toHashSet(@[1,2]))), "equivalent or subset")
+  doAssert(toHashSet(@[1,2,3]) <= toHashSet(@[1,2,3,4]), "strict subset")
+  doAssert((not(toHashSet(@[1,2,3]) < toHashSet(@[1,2,3]))), "strict subset")
+  doAssert((not(toHashSet(@[1,2,3]) < toHashSet(@[1,2]))), "strict subset")
+  doAssert((not(toHashSet(@[1,2,3]) == toHashSet(@[1,2,3,4]))), "==")
+  doAssert(toHashSet(@[1,2,3]) == toHashSet(@[1,2,3]), "==")
+  doAssert((not(toHashSet(@[1,2,3]) == toHashSet(@[1,2]))), "==")
+
+
+
+block tformat:
+  echo("Hi $1! How do you feel, $2?\n" % ["Andreas", "Rumpf"])
+
+
+
+block tnilecho:
+  var x = @["1", "", "3"]
+  doAssert $x == """@["1", "", "3"]"""
+
+
+
+block torderedtable:
+  var t = initOrderedTable[int,string]()
+
+  # this tests issue #5917
+  var data = newSeq[int]()
+  for i in 0..<1000:
+    var x = rand(1000)
+    if x notin t: data.add(x)
+    t[x] = "meh"
+
+  # this checks that keys are re-inserted
+  # in order when table is enlarged.
+  var i = 0
+  for k, v in t:
+    doAssert(k == data[i])
+    doAssert(v == "meh")
+    inc(i)
+
+
+
+block tpermutations:
+  var v = @[0, 1, 2]
+  while v.nextPermutation():
+    echo v
+  while v.prevPermutation():
+    echo v
+
+
+block tropes:
+  var
+    r1 = rope("")
+    r2 = rope("123")
+  doAssert r1.len == 0
+  doAssert r2.len == 3
+  doAssert $r1 == ""
+  doAssert $r2 == "123"
+
+  r1.add("123")
+  r2.add("456")
+  doAssert r1.len == 3
+  doAssert r2.len == 6
+  doAssert $r1 == "123"
+  doAssert $r2 == "123456"
+  doAssert $r1[1] == "2"
+  doAssert $r2[2] == "3"
+
+
+block tsinglylinkedring:
+  var r = initSinglyLinkedRing[int]()
+  r.prepend(5)
+  echo r
+  r.prepend(4)
+  echo r
+  r.prepend(3)
+  echo r
+  r.prepend(2)
+  echo r
+  r.append(6)
+  echo r
+  r.prepend(1)
+  echo r
+
+block tsplit:
+  var s = ""
+  for w in split("|abc|xy|z", {'|'}):
+    s.add("#")
+    s.add(w)
+
+  doAssert s == "##abc#xy#z"
+
+block tsplit2:
+  var s = ""
+  for w in split("|abc|xy|z", {'|'}):
+    s.add("#")
+    s.add(w)
+
+  doAssert "true".split("") == @["true"]
+
+block txmlgen:
+  var nim = "Nim"
+  doAssert h1(a(href="http://force7.de/nim", nim)) ==
+    "<h1><a href=\"http://force7.de/nim\">Nim</a></h1>"
+
+block txmltree:
+  var x = <>a(href="nim.de", newText("www.nim-test.de"))
+
+  doAssert($x == "<a href=\"nim.de\">www.nim-test.de</a>")
+  doAssert(newText("foo").innerText == "foo")
+  doAssert(newEntity("bar").innerText == "bar")
+  doAssert(newComment("baz").innerText == "")
+
+  let y = newXmlTree("x", [
+    newText("foo"),
+    newXmlTree("y", [
+      newText("bar")
+    ])
+  ])
+  doAssert(y.innerText == "foobar")
diff --git a/tests/js/tstreams.nim b/tests/js/tstreams.nim
new file mode 100644
index 000000000..43c26e01a
--- /dev/null
+++ b/tests/js/tstreams.nim
@@ -0,0 +1,22 @@
+discard """
+  output: '''
+I
+AM
+GROOT
+'''
+"""
+
+import streams
+
+var s = newStringStream("I\nAM\nGROOT")
+doAssert s.peekStr(1) == "I"
+doAssert s.peekChar() == 'I'
+for line in s.lines:
+  echo line
+s.close
+
+var s2 = newStringStream("abc")
+doAssert s2.readAll == "abc"
+s2.write("def")
+doAssert s2.data == "abcdef"
+s2.close
diff --git a/tests/js/ttempgen.nim b/tests/js/ttempgen.nim
new file mode 100644
index 000000000..badc66c1b
--- /dev/null
+++ b/tests/js/ttempgen.nim
@@ -0,0 +1,79 @@
+discard """
+  output: '''
+foo
+'''
+"""
+
+block: # #12672
+  var a = @[1]
+  let i = 1
+  inc a[i-1]
+
+  var b: seq[int]
+  doAssertRaises(IndexDefect): inc b[0]
+  doAssertRaises(IndexDefect): inc b[i-1]
+
+  var x: seq[seq[int]]
+  doAssertRaises(IndexDefect): # not TypeError
+    inc x[0][i-1]
+
+block: # #14087
+  type Obj = object
+    str: string
+
+  var s = @[Obj(str: "abc"), Obj(str: "def")]
+  s[1].str.add("ghi")
+  s[s.len - 1].str.add("jkl")
+  s[^1].str.add("mno")
+  s[s.high].str.add("pqr")
+
+  let slen = s.len
+  s[slen - 1].str.add("stu")
+
+  let shigh = s.high
+  s[shigh].str.add("vwx")
+
+  proc foo(): int =
+    echo "foo"
+    shigh
+  s[foo()].str.add("yz")
+  doAssert s[1].str == "defghijklmnopqrstuvwxyz"
+
+block: # #14117
+  type
+    A = object
+      case kind: bool
+      of true:
+        sons: seq[int]
+      else: discard
+
+  var a = A(kind: true)
+  doAssert a.sons.len == 0
+  a.sons.add(1)
+  doAssert a.sons.len == 1
+
+import tables
+
+block: # #13966
+  var t: Table[int8, array[int8, seq[tuple[]]]]
+
+  t[0] = default(array[int8, seq[tuple[]]])
+  t[0][0].add ()
+
+block: # #11783
+  proc fun(): string =
+    discard
+
+  var ret: string
+  ret.add fun()
+  doAssert ret == ""
+
+block: # #12256
+  var x: bool
+
+  doAssert x == false
+
+  reset x
+
+  doAssert x == false
+  doAssert x != true
diff --git a/tests/js/ttypedarray.nim b/tests/js/ttypedarray.nim
new file mode 100644
index 000000000..4807cb103
--- /dev/null
+++ b/tests/js/ttypedarray.nim
@@ -0,0 +1,26 @@
+discard """
+  matrix: "--jsbigint64:off -d:nimStringHash2; --jsbigint64:on"
+"""
+
+import std/private/jsutils
+
+proc main()=
+  template fn(a): untyped = jsConstructorName(a)
+  doAssert fn(array[2, int8].default) == "Int8Array"
+  doAssert fn(array[2, uint8].default) == "Uint8Array"
+  doAssert fn(array[2, byte].default) == "Uint8Array"
+  doAssert fn(array[2, char].default) == "Uint8Array"
+  whenJsNoBigInt64: discard
+  do:
+    doAssert fn(array[2, uint64].default) == "BigUint64Array"
+  doAssert fn([1'u8]) == "Uint8Array"
+  doAssert fn([1'u16]) == "Uint16Array"
+  doAssert fn([byte(1)]) == "Uint8Array"
+  doAssert fn([1.0'f32]) == "Float32Array"
+  doAssert fn(array[2, float32].default) == "Float32Array"
+  doAssert fn(array[2, float].default) == "Float64Array"
+  doAssert fn(array[2, float64].default) == "Float64Array"
+  doAssert fn([1.0]) == "Float64Array"
+  doAssert fn([1.0'f64]) == "Float64Array"
+
+main()
diff --git a/tests/js/tunion.nim b/tests/js/tunion.nim
new file mode 100644
index 000000000..e185495ad
--- /dev/null
+++ b/tests/js/tunion.nim
@@ -0,0 +1,7 @@
+discard """
+  errormsg: "`{.union.}` is not implemented for js backend."
+"""
+
+type Foo {.union.} = object
+  as_bytes: array[8, int8]
+  data: int64
diff --git a/tests/js/tunittest_error.nim b/tests/js/tunittest_error.nim
new file mode 100644
index 000000000..781e34338
--- /dev/null
+++ b/tests/js/tunittest_error.nim
@@ -0,0 +1,24 @@
+discard """
+  exitcode: 1
+  outputsub: "[FAILED] with exception"
+"""
+
+# see also: `tests/stdlib/tunittest_error.nim`
+
+import unittest
+
+proc ddd() =
+  raise newException(IOError, "didn't do stuff")
+
+proc ccc() =
+  ddd()
+
+proc bbb() =
+  ccc()
+
+proc aaa() =
+  bbb()
+
+test "with exception":
+  check 3 == 3
+  aaa()
diff --git a/tests/js/tunittest_error2.nim b/tests/js/tunittest_error2.nim
new file mode 100644
index 000000000..9c5af7529
--- /dev/null
+++ b/tests/js/tunittest_error2.nim
@@ -0,0 +1,16 @@
+discard """
+  exitcode: 1
+  outputsub: '''
+[<foreign exception>]
+[FAILED] Bad test
+  '''
+  matrix: "-d:nodejs"
+  targets: "js"
+  joinable: false
+"""
+
+# bug #16978
+import unittest
+test "Bad test":
+  var x: cstring = nil
+  let y = x[0]
diff --git a/tests/js/tunittests.nim b/tests/js/tunittests.nim
deleted file mode 100644
index 7c2e70563..000000000
--- a/tests/js/tunittests.nim
+++ /dev/null
@@ -1,11 +0,0 @@
-discard """
-  output: '''
-[Suite] Bacon
-  [OK] >:)'''
-"""
-
-import unittest
-
-suite "Bacon":
-  test ">:)":
-    check(true == true)
diff --git a/tests/js/twritestacktrace.nim b/tests/js/twritestacktrace.nim
new file mode 100644
index 000000000..2fe2b1987
--- /dev/null
+++ b/tests/js/twritestacktrace.nim
@@ -0,0 +1,12 @@
+discard """
+  cmd: "nim js --panics:on $file"
+  output: '''Traceback (most recent call last)
+twritestacktrace.nim(12) at module twritestacktrace
+twritestacktrace.nim(10) at twritestacktrace.hello
+'''
+"""
+
+proc hello() =
+  writeStackTrace()
+
+hello()
diff --git a/tests/lent/t16898.nim b/tests/lent/t16898.nim
new file mode 100644
index 000000000..a69c6d244
--- /dev/null
+++ b/tests/lent/t16898.nim
@@ -0,0 +1,31 @@
+discard """
+  errormsg: "invalid type: 'lent QuadraticExt' in this context: 'proc (r: var QuadraticExt, a: lent QuadraticExt, b: lent QuadraticExt){.noSideEffect, gcsafe.}' for proc"
+"""
+
+# bug #16898
+type
+  Fp[N: static int, T] = object
+    big: array[N, T]
+
+type
+  QuadraticExt* = concept x
+    ## Quadratic Extension concept (like complex)
+    type BaseField = auto
+    x.c0 is BaseField
+    x.c1 is BaseField
+
+{.experimental:"views".}
+
+func prod(r: var QuadraticExt, a, b: lent QuadraticExt) =
+  discard
+
+type
+  Fp2[N: static int, T] = object
+    c0, c1: Fp[N, T]
+
+# This should be passed by reference,
+# but concepts do not respect the 24 bytes rule
+# or `byref` pragma.
+var r, a, b: Fp2[6, uint64]
+
+prod(r, a, b)
diff --git a/tests/lent/t17621.nim b/tests/lent/t17621.nim
new file mode 100644
index 000000000..e324a963e
--- /dev/null
+++ b/tests/lent/t17621.nim
@@ -0,0 +1,15 @@
+discard """
+  errormsg: "invalid type: 'lent Test' in this context: 'proc (self: lent Test)' for proc"
+"""
+
+# bug #17621
+{.experimental: "views".}
+
+type Test = ref object
+  foo: int
+
+proc modify(self: lent Test) =
+  self.foo += 1
+
+let test = Test(foo: 12)
+modify(test)
diff --git a/tests/lent/tbasic_lent_check.nim b/tests/lent/tbasic_lent_check.nim
index 4389cbc6e..ce9b89adf 100644
--- a/tests/lent/tbasic_lent_check.nim
+++ b/tests/lent/tbasic_lent_check.nim
@@ -1,4 +1,5 @@
 discard """
+  targets: "c cpp js"
   output: "1"
 """
 
@@ -14,3 +15,48 @@ proc main =
   doAssert(not compiles(passToVar(viewInto(x))))
 
 main()
+
+template main2 = # bug #15958
+  when defined(js):
+    proc sameAddress[T](a, b: T): bool {.importjs: "(# === #)".}
+  else:
+    template sameAddress(a, b): bool = a.unsafeAddr == b.unsafeAddr
+  proc byLent[T](a: T): lent T = a
+  let a = [11,12]
+  let b = @[21,23]
+  let ss = {1, 2, 3, 5}
+  doAssert byLent(a) == [11,12]
+  doAssert sameAddress(byLent(a), a)
+  doAssert byLent(b) == @[21,23]
+  # bug #16073
+  doAssert sameAddress(byLent(b), b)
+  doAssert byLent(ss) == {1, 2, 3, 5}
+  doAssert sameAddress(byLent(ss), ss)
+
+  let r = new(float)
+  r[] = 10.0
+  # bug #16073
+  doAssert byLent(r)[] == 10.0
+
+  when not defined(js): # pending bug https://github.com/timotheecour/Nim/issues/372
+    let p = create(float)
+    p[] = 20.0
+    doAssert byLent(p)[] == 20.0
+
+  proc byLent2[T](a: openArray[T]): lent T = a[0]
+  doAssert byLent2(a) == 11
+  doAssert sameAddress(byLent2(a), a[0])
+  doAssert byLent2(b) == 21
+  doAssert sameAddress(byLent2(b), b[0])
+
+  proc byLent3[T](a: varargs[T]): lent T = a[1]
+  let 
+    x = 10
+    y = 20
+    z = 30
+  doAssert byLent3(x, y, z) == 20
+
+main2()
+when false:
+  # bug: Error: unhandled exception: 'node' is not accessible using discriminant 'kind' of type 'TFullReg' [FieldDefect]
+  static: main2()
diff --git a/tests/lent/tlent_from_var.nim b/tests/lent/tlent_from_var.nim
new file mode 100644
index 000000000..1fb3d0c17
--- /dev/null
+++ b/tests/lent/tlent_from_var.nim
@@ -0,0 +1,107 @@
+discard """
+  output: '''x
+[10, 11, 12, 13]'''
+"""
+
+# bug #14805
+
+type Foo = object
+  a: string
+
+proc bar(f: var Foo): lent string =
+  result = f.a
+
+var foo = Foo(a: "x")
+echo bar(foo)
+
+
+# bug #14878
+
+# proc byLentImpl[T](a: T): lent T = a
+proc byLentVar[T](a: var T): lent T =
+  result = a
+  # result = a.byLentImpl # this doesn't help
+
+var x = 3 # error: cannot take the address of an rvalue of type 'NI *'
+
+var xs = [10,11,12,13] # SIGSEGV
+
+let x2 = x.byLentVar
+
+let xs2 = xs.byLentVar
+echo xs2
+
+# bug #22138
+
+type Xxx = object
+
+type
+  Opt[T] = object
+    case oResultPrivate*: bool
+    of false:
+      discard
+    of true:
+      vResultPrivate*: T
+
+func value*[T: not void](self: Opt[T]): lent T {.inline.} =
+  self.vResultPrivate
+template get*[T: not void](self: Opt[T]): T = self.value()
+
+method connect*(
+  self: Opt[(int, int)]) =
+  discard self.get()[0]
+
+block: # bug #23454
+  type
+    Letter = enum
+      A
+
+    LetterPairs = object
+      values: seq[(Letter, string)]
+
+  iterator items(list: var LetterPairs): lent (Letter, string) =
+    for item in list.values:
+      yield item
+
+  var instance = LetterPairs(values: @[(A, "foo")])
+
+  for (a, _) in instance:
+    case a
+    of A: discard
+
+block: # bug #23454
+  type
+    Letter = enum
+      A
+
+    LetterPairs = object
+      values: seq[(Letter, string)]
+
+  iterator items(list: var LetterPairs): var (Letter, string) =
+    for item in list.values.mItems:
+      yield item
+
+  var instance = LetterPairs(values: @[(A, "foo")])
+
+  for (a, _) in instance:
+    case a
+    of A: discard
+
+block: # bug #24034
+  type T = object
+    v: array[100, byte]
+
+
+  iterator pairs(t: T): (int, lent array[100, byte]) =
+    yield (0, t.v)
+
+
+  block:
+    for a, b in default(T):
+      doAssert a == 0
+      doAssert b.len == 100
+
+  block:
+    for (a, b) in pairs(default(T)):
+      doAssert a == 0
+      doAssert b.len == 100
diff --git a/tests/lent/tnot_allowed_lent.nim b/tests/lent/tnot_allowed_lent.nim
index b144ce36b..a1db6d184 100644
--- a/tests/lent/tnot_allowed_lent.nim
+++ b/tests/lent/tnot_allowed_lent.nim
@@ -1,5 +1,5 @@
 discard """
-  errmsg: "expression has no address"
+  errormsg: "expression has no address"
 """
 type
   MyObject = object
@@ -7,10 +7,10 @@ type
 
 proc mytest1(s: MyObject, i: int): lent string =
   ## works fine
-  if i < s.x.len - 1 and s.x[i] != "": 
+  if i < s.x.len - 1 and s.x[i] != "":
     result = s.x[i]
   else: raise newException(KeyError, "err1")
-  
+
 proc mytest2(s: MyObject, i: int): lent string =
   ## reject due to if expr
   if i < s.x.len - 1 and s.x[i] != "": s.x[i]
diff --git a/tests/lent/tnot_allowed_lent2.nim b/tests/lent/tnot_allowed_lent2.nim
new file mode 100644
index 000000000..d0c958df3
--- /dev/null
+++ b/tests/lent/tnot_allowed_lent2.nim
@@ -0,0 +1,14 @@
+discard """
+  errormsg: "'x' cannot be assigned to"
+  line: 10
+"""
+
+proc bug14498 =
+  var a = @['a', 'b', 'c', 'd', 'e', 'f']
+
+  for x in a:
+    x = 'c'
+
+  echo a
+
+bug14498()
diff --git a/tests/lent/tvm.nim b/tests/lent/tvm.nim
new file mode 100644
index 000000000..5df1d1270
--- /dev/null
+++ b/tests/lent/tvm.nim
@@ -0,0 +1,21 @@
+block: # issue #17527
+  iterator items2[IX, T](a: array[IX, T]): lent T {.inline.} =
+    var i = low(IX)
+    if i <= high(IX):
+      while true:
+        yield a[i]
+        if i >= high(IX): break
+        inc(i)
+
+  proc main() =
+    var s: seq[string] = @[]
+    for i in 0..<3:
+      for (key, val) in items2([("any", "bar")]):
+        s.add $(i, key, val)
+    doAssert s == @[
+      "(0, \"any\", \"bar\")",
+      "(1, \"any\", \"bar\")",
+      "(2, \"any\", \"bar\")"
+    ]
+
+  static: main()
diff --git a/tests/let/timportc.nim b/tests/let/timportc.nim
new file mode 100644
index 000000000..85244da9f
--- /dev/null
+++ b/tests/let/timportc.nim
@@ -0,0 +1,24 @@
+discard """
+targets: "c cpp js"
+"""
+
+when defined(c) or defined(cpp):
+  {.emit:"""
+  const int TEST1 = 123;
+  #define TEST2 321
+  """.}
+
+when defined(js):
+  {.emit:"""
+  const TEST1 = 123;
+  const TEST2 = 321; // JS doesn't have macros, so we just duplicate
+  """.}
+
+let
+  TEST0 = 1
+  TEST1 {.importc, nodecl.}: cint
+  TEST2 {.importc, nodecl.}: cint
+
+doAssert TEST0 == 1
+doAssert TEST1 == 123
+doAssert TEST2 == 321
diff --git a/tests/let/timportc2.nim b/tests/let/timportc2.nim
new file mode 100644
index 000000000..964305923
--- /dev/null
+++ b/tests/let/timportc2.nim
@@ -0,0 +1,8 @@
+discard """
+  errormsg: "'let' symbol requires an initialization"
+  line: "7"
+"""
+
+# Test that this still works when not annotated with importc
+let test: cint
+echo test
diff --git a/tests/lexer/mlexerutils.nim b/tests/lexer/mlexerutils.nim
new file mode 100644
index 000000000..eae7a0006
--- /dev/null
+++ b/tests/lexer/mlexerutils.nim
@@ -0,0 +1,9 @@
+import macros
+
+macro lispReprStr*(a: untyped): untyped = newLit(a.lispRepr)
+
+macro assertAST*(expected: string, struct: untyped): untyped =
+  var ast = newLit(struct.treeRepr)
+  result = quote do:
+    if `ast` != `expected`:
+      doAssert false, "\nGot:\n" & `ast`.indent(2) & "\nExpected:\n" & `expected`.indent(2)
\ No newline at end of file
diff --git a/tests/lexer/tcustom_numeric_literals.nim b/tests/lexer/tcustom_numeric_literals.nim
new file mode 100644
index 000000000..35b4803d3
--- /dev/null
+++ b/tests/lexer/tcustom_numeric_literals.nim
@@ -0,0 +1,177 @@
+discard """
+  targets: "c cpp js"
+"""
+
+# Test tkStrNumLit
+
+import std/[macros, strutils]
+import mlexerutils
+
+# AST checks
+
+assertAST dedent """
+  StmtList
+    ProcDef
+      AccQuoted
+        Ident "\'"
+        Ident "wrap"
+      Empty
+      Empty
+      FormalParams
+        Ident "string"
+        IdentDefs
+          Ident "number"
+          Ident "string"
+          Empty
+      Empty
+      Empty
+      StmtList
+        Asgn
+          Ident "result"
+          Infix
+            Ident "&"
+            Infix
+              Ident "&"
+              StrLit "[["
+              Ident "number"
+            StrLit "]]"""":
+  proc `'wrap`(number: string): string =
+    result = "[[" & number & "]]"
+
+assertAST dedent """
+  StmtList
+    DotExpr
+      RStrLit "-38383839292839283928392839283928392839283.928493849385935898243e-50000"
+      Ident "\'wrap"""":
+  -38383839292839283928392839283928392839283.928493849385935898243e-50000'wrap
+
+proc `'wrap`(number: string): string = "[[" & number & "]]"
+proc wrap2(number: string): string = "[[" & number & "]]"
+doAssert lispReprStr(-1'wrap) == """(DotExpr (RStrLit "-1") (Ident "\'wrap"))"""
+
+template main =
+  block: # basic suffix usage
+    template `'twrap`(number: string): untyped =
+      number.`'wrap`
+    proc extraContext(): string =
+      22.40'wrap
+    proc `*`(left, right: string): string =
+      result = left & "times" & right
+    proc `+`(left, right: string): string =
+      result = left & "plus" & right
+
+    doAssert 1'wrap == "[[1]]"
+    doAssert -1'wrap == "[[-1]]":
+      "unable to resolve a negative integer-suffix pattern"
+    doAssert 12345.67890'wrap == "[[12345.67890]]"
+    doAssert 1'wrap*1'wrap == "[[1]]times[[1]]":
+      "unable to resolve an operator between two suffixed numeric literals"
+    doAssert 1'wrap+ -1'wrap == "[[1]]plus[[-1]]":  # will generate a compiler warning about inconsistent spacing
+      "unable to resolve a negative suffixed numeric literal following an operator"
+    doAssert 1'wrap + -1'wrap == "[[1]]plus[[-1]]"
+    doAssert 1'twrap == "[[1]]"
+    doAssert extraContext() == "[[22.40]]":
+      "unable to return a suffixed numeric literal by an implicit return"
+    doAssert 0x5a3a'wrap == "[[0x5a3a]]"
+    doAssert 0o5732'wrap == "[[0o5732]]"
+    doAssert 0b0101111010101'wrap == "[[0b0101111010101]]"
+    doAssert -38383839292839283928392839283928392839283.928493849385935898243e-50000'wrap == "[[-38383839292839283928392839283928392839283.928493849385935898243e-50000]]"
+    doAssert 1234.56'wrap == "[[1234.56]]":
+      "unable to properly account for context with suffixed numeric literals"
+
+  block: # verify that the i64, f32, etc builtin suffixes still parse correctly
+    const expectedF32: float32 = 123.125
+    proc `'f9`(number: string): string =   # proc starts with 'f' just like 'f32'
+      "[[" & number & "]]"
+    proc `'f32a`(number: string): string =   # looks even more like 'f32'
+      "[[" & number & "]]"
+    proc `'d9`(number: string): string =   # proc starts with 'd' just like the d suffix
+      "[[" & number & "]]"
+    proc `'i9`(number: string): string =   # proc starts with 'i' just like 'i64'
+      "[[" & number & "]]"
+    proc `'u9`(number: string): string =   # proc starts with 'u' just like 'u8'
+      "[[" & number & "]]"
+
+    doAssert 123.125f32 == expectedF32:
+      "failing to support non-quoted legacy f32 floating point suffix"
+    doAssert 123.125'f32 == expectedF32
+    doAssert 123.125e0'f32 == expectedF32
+    doAssert 1234.56'wrap == 1234.56'f9
+    doAssert 1234.56'wrap == 1234.56'f32a
+    doAssert 1234.56'wrap == 1234.56'd9
+    doAssert 1234.56'wrap == 1234.56'i9
+    doAssert 1234.56'wrap == 1234.56'u9
+    doAssert lispReprStr(1234.56'u9) == """(DotExpr (RStrLit "1234.56") (Ident "\'u9"))""":
+      "failed to properly build AST for suffix that starts with u"
+    doAssert -128'i8 == (-128).int8
+
+  block: # case checks
+    doAssert 1E2 == 100:
+      "lexer not handling upper-case exponent"
+    doAssert 1.0E2 == 100.0
+    doAssert 1e2 == 100
+    doAssert 0xdeadBEEF'wrap == "[[0xdeadBEEF]]":
+      "lexer not maintaining original case"
+    doAssert 0.1E12'wrap == "[[0.1E12]]"
+    doAssert 0.0e12'wrap == "[[0.0e12]]"
+    doAssert 0.0e+12'wrap == "[[0.0e+12]]"
+    doAssert 0.0e-12'wrap == "[[0.0e-12]]"
+    doAssert 0e-12'wrap == "[[0e-12]]"
+
+  block: # macro and template usage
+    template `'foo`(a: string): untyped = (a, 2)
+    doAssert -12'foo == ("-12", 2)
+    template `'fooplus`(a: string, b: int): untyped = (a, b)
+    doAssert -12'fooplus(2) == ("-12", 2)
+    template `'fooplusopt`(a: string, b: int = 99): untyped = (a, b)
+    doAssert -12'fooplusopt(2) == ("-12", 2)
+    doAssert -12'fooplusopt() == ("-12", 99)
+    doAssert -12'fooplusopt == ("-12", 99)
+    macro `'bar`(a: static string): untyped = newLit(a.repr)
+    doAssert -12'bar == "\"-12\""
+    macro deb(a): untyped = newLit(a.repr)
+    doAssert deb(-12'bar) == "-12'bar"
+
+  block: # bug 1 from https://github.com/nim-lang/Nim/pull/17020#issuecomment-803193947
+    macro deb1(a): untyped = newLit a.repr
+    macro deb2(a): untyped =
+      a[1] = ident($a[1])
+      newLit a.lispRepr
+    doAssert deb1(-12'wrap) == "-12'wrap"
+    doAssert deb1(-12'nonexistent) == "-12'nonexistent"
+    doAssert deb2(-12'nonexistent) == """(DotExpr (RStrLit "-12") (Ident "\'nonexistent"))"""
+    doAssert deb2(-12.wrap2) == """(DotExpr (IntLit -12) (Ident "wrap2"))"""
+    doAssert deb2(-12'wrap) == """(DotExpr (RStrLit "-12") (Ident "\'wrap"))"""
+
+  block: # bug 2 from https://github.com/nim-lang/Nim/pull/17020#issuecomment-803193947
+    template toSuf(`'suf`): untyped =
+      let x = -12'suf
+      x
+    doAssert toSuf(`'wrap`) == "[[-12]]"
+
+  block: # bug 10 from https://github.com/nim-lang/Nim/pull/17020#issuecomment-803193947
+    proc `myecho`(a: auto): auto = a
+    template fn1(): untyped =
+      let a = "abc"
+      -12'wrap
+    template fn2(): untyped =
+      `myecho` -12'wrap
+    template fn3(): untyped =
+      -12'wrap
+    doAssert fn1() == "[[-12]]"
+    doAssert fn2() == "[[-12]]"
+    doAssert fn3() == "[[-12]]"
+
+    block: # bug 9 from https://github.com/nim-lang/Nim/pull/17020#issuecomment-803193947
+      macro metawrap(): untyped =
+        func wrap1(a: string): string = "{" & a & "}"
+        func `'wrap3`(a: string): string = "{" & a & "}"
+        result = quote do:
+          let a1 {.inject.} = wrap1"-128"
+          let a2 {.inject.} = -128'wrap3
+      metawrap()
+      doAssert a1 == "{-128}"
+      doAssert a2 == "{-128}"
+
+static: main()
+main()
diff --git a/tests/lexer/tintegerliterals.nim b/tests/lexer/tintegerliterals.nim
index 7420db144..fd401b71b 100644
--- a/tests/lexer/tintegerliterals.nim
+++ b/tests/lexer/tintegerliterals.nim
@@ -1,9 +1,9 @@
 # test the valid literals
-assert 0b10 == 2
-assert 0B10 == 2
-assert 0x10 == 16
-assert 0X10 == 16
-assert 0o10 == 8
+doAssert 0b10 == 2
+doAssert 0B10 == 2
+doAssert 0x10 == 16
+doAssert 0X10 == 16
+doAssert 0o10 == 8
 # the following is deprecated:
-assert 0c10 == 8
-assert 0C10 == 8
+doAssert 0c10 == 8
+doAssert 0C10 == 8
diff --git a/tests/lexer/tlexerspaces.nim b/tests/lexer/tlexerspaces.nim
new file mode 100644
index 000000000..14b16111d
--- /dev/null
+++ b/tests/lexer/tlexerspaces.nim
@@ -0,0 +1,2 @@
+discard 12 +                                                                                                                                                                                                                                                                           5
+discard 12 + 5                                                                                                                        
diff --git a/tests/misc/trawstr.nim b/tests/lexer/trawstr.nim
index aa41071d5..aa41071d5 100644
--- a/tests/misc/trawstr.nim
+++ b/tests/lexer/trawstr.nim
diff --git a/tests/lexer/tunary_minus.nim b/tests/lexer/tunary_minus.nim
new file mode 100644
index 000000000..5ec2b5c70
--- /dev/null
+++ b/tests/lexer/tunary_minus.nim
@@ -0,0 +1,83 @@
+discard """
+  targets: "c cpp js"
+"""
+
+# Test numeric literals and handling of minus symbol
+
+import std/[macros, strutils]
+import std/private/jsutils
+
+import mlexerutils
+
+const one = 1
+const minusOne = `-`(one)
+
+# border cases that *should* generate compiler errors:
+assertAST dedent """
+  StmtList
+    Asgn
+      Ident "x"
+      Command
+        IntLit 4
+        IntLit -1""":
+  x = 4 -1
+assertAST dedent """
+  StmtList
+    VarSection
+      IdentDefs
+        Ident "x"
+        Ident "uint"
+        IntLit -1""":
+  var x: uint = -1
+template bad() =
+  x = 4 -1
+doAssert not compiles(bad())
+
+template main =
+  block: # check when a minus (-) is a negative sign for a literal
+    doAssert -1 == minusOne:
+      "unable to parse a spaced-prefixed negative int"
+    doAssert lispReprStr(-1) == """(IntLit -1)"""
+    doAssert -1.0'f64 == minusOne.float64
+    doAssert lispReprStr(-1.000'f64) == """(Float64Lit -1.0)"""
+    doAssert lispReprStr( -1.000'f64) == """(Float64Lit -1.0)"""
+    doAssert [-1].contains(minusOne):
+      "unable to handle negatives after square bracket"
+    doAssert lispReprStr([-1]) == """(Bracket (IntLit -1))"""
+    doAssert (-1, 2)[0] == minusOne:
+      "unable to handle negatives after parenthesis"
+    doAssert lispReprStr((-1, 2)) == """(TupleConstr (IntLit -1) (IntLit 2))"""
+    proc x(): int =
+      var a = 1;-1  # the -1 should act as the return value
+    doAssert x() == minusOne:
+      "unable to handle negatives after semi-colon"
+
+  block:
+    doAssert -0b111 == -7
+    doAssert -0xff == -255
+    doAssert -128'i8 == (-128).int8
+    doAssert $(-128'i8) == "-128"
+    doAssert -32768'i16 == int16.low
+    doAssert -2147483648'i32 == int32.low
+    when int.sizeof > 4:
+      doAssert -9223372036854775808 == int.low
+    whenJsNoBigInt64: discard
+    do:
+      doAssert -9223372036854775808 == int64.low
+
+  block: # check when a minus (-) is an unary op
+    doAssert -one == minusOne:
+      "unable to a negative prior to identifier"
+
+  block: # check when a minus (-) is a a subtraction op
+    doAssert 4-1 == 3:
+      "unable to handle subtraction sans surrounding spaces with a numeric literal"
+    doAssert 4-one == 3:
+      "unable to handle subtraction sans surrounding spaces with an identifier"
+    doAssert 4 - 1 == 3:
+      "unable to handle subtraction with surrounding spaces with a numeric literal"
+    doAssert 4 - one == 3:
+      "unable to handle subtraction with surrounding spaces with an identifier"
+
+static: main()
+main()
diff --git a/tests/lexer/tunicode_operators.nim b/tests/lexer/tunicode_operators.nim
new file mode 100644
index 000000000..6ad40beab
--- /dev/null
+++ b/tests/lexer/tunicode_operators.nim
@@ -0,0 +1,16 @@
+#{.experimental: "unicodeOperators".}
+
+proc `⊙`(x, y: int): int = x * y
+proc `⊙=`(x: var int, y: int) = x *= y
+
+proc `⊞++`(x, y: int): int = x + y
+
+const a = 9
+
+var x = 45
+x ⊙= a⊞++4⊙3
+
+var y = 45
+y *= 9 + 4 * 3
+
+assert x == y
diff --git a/tests/lookups/issue_23032/deep_scope.nim b/tests/lookups/issue_23032/deep_scope.nim
new file mode 100644
index 000000000..3e25809a7
--- /dev/null
+++ b/tests/lookups/issue_23032/deep_scope.nim
@@ -0,0 +1,2 @@
+type A*[T] = object
+proc foo*(a: A[int]): bool = false
diff --git a/tests/lookups/issue_23172/m23172.nim b/tests/lookups/issue_23172/m23172.nim
new file mode 100644
index 000000000..36af48761
--- /dev/null
+++ b/tests/lookups/issue_23172/m23172.nim
@@ -0,0 +1,6 @@
+type
+  Foo* = object
+  Bar* = object
+
+func `$`*(x: Foo | Bar): string =
+  "X"
diff --git a/tests/ambsym/mambsym1.nim b/tests/lookups/mambsym1.nim
index c4902b1b4..c4902b1b4 100644
--- a/tests/ambsym/mambsym1.nim
+++ b/tests/lookups/mambsym1.nim
diff --git a/tests/ambsym/mambsym2.nim b/tests/lookups/mambsym2.nim
index 21d980073..21d980073 100644
--- a/tests/ambsym/mambsym2.nim
+++ b/tests/lookups/mambsym2.nim
diff --git a/tests/lookups/mambsym3.nim b/tests/lookups/mambsym3.nim
new file mode 100644
index 000000000..946a5ff29
--- /dev/null
+++ b/tests/lookups/mambsym3.nim
@@ -0,0 +1,4 @@
+# Module A
+var x*: string
+proc foo*(a: string) =
+  echo "A: ", a
diff --git a/tests/lookups/mambsym4.nim b/tests/lookups/mambsym4.nim
new file mode 100644
index 000000000..ed66cc16d
--- /dev/null
+++ b/tests/lookups/mambsym4.nim
@@ -0,0 +1,4 @@
+# Module B
+var x*: int
+proc foo*(b: int) =
+  echo "B: ", b
diff --git a/tests/ambsym/mambsys1.nim b/tests/lookups/mambsys1.nim
index 22e54cb94..22e54cb94 100644
--- a/tests/ambsym/mambsys1.nim
+++ b/tests/lookups/mambsys1.nim
diff --git a/tests/ambsym/mambsys2.nim b/tests/lookups/mambsys2.nim
index ef63e4f7e..ef63e4f7e 100644
--- a/tests/ambsym/mambsys2.nim
+++ b/tests/lookups/mambsys2.nim
diff --git a/tests/lookups/mambtype1.nim b/tests/lookups/mambtype1.nim
new file mode 100644
index 000000000..47046142e
--- /dev/null
+++ b/tests/lookups/mambtype1.nim
@@ -0,0 +1 @@
+type K* = object
diff --git a/tests/lookups/mambtype2.nim b/tests/lookups/mambtype2.nim
new file mode 100644
index 000000000..cf622466b
--- /dev/null
+++ b/tests/lookups/mambtype2.nim
@@ -0,0 +1,4 @@
+import ./mambtype1
+export mambtype1
+template K*(kind: static int): auto = typedesc[mambtype1.K]
+template B*(kind: static int): auto = typedesc[mambtype1.K]
diff --git a/tests/bind/mbind3.nim b/tests/lookups/mbind3.nim
index 1a7d3b63b..1a7d3b63b 100644
--- a/tests/bind/mbind3.nim
+++ b/tests/lookups/mbind3.nim
diff --git a/tests/lookups/mdisambsym1.nim b/tests/lookups/mdisambsym1.nim
new file mode 100644
index 000000000..b8beca035
--- /dev/null
+++ b/tests/lookups/mdisambsym1.nim
@@ -0,0 +1,2 @@
+proc count*(s: string): int = 
+  s.len
diff --git a/tests/lookups/mdisambsym2.nim b/tests/lookups/mdisambsym2.nim
new file mode 100644
index 000000000..1e056311d
--- /dev/null
+++ b/tests/lookups/mdisambsym2.nim
@@ -0,0 +1 @@
+var count*: int = 10
diff --git a/tests/lookups/mdisambsym3.nim b/tests/lookups/mdisambsym3.nim
new file mode 100644
index 000000000..95bd19702
--- /dev/null
+++ b/tests/lookups/mdisambsym3.nim
@@ -0,0 +1 @@
+const count* = 3.142
diff --git a/tests/lookups/mmacroamb.nim b/tests/lookups/mmacroamb.nim
new file mode 100644
index 000000000..107e51055
--- /dev/null
+++ b/tests/lookups/mmacroamb.nim
@@ -0,0 +1,10 @@
+# issue #12732
+
+import std/macros
+const getPrivate3_tmp* = 0
+const foobar1* = 0 # comment this or make private and it'll compile fine
+macro foobar4*(): untyped =
+  newLit "abc"
+template currentPkgDir2*: string = foobar4()
+macro currentPkgDir2*(dir: string): untyped =
+  newLit "abc2"
diff --git a/tests/lookups/t23032.nim b/tests/lookups/t23032.nim
new file mode 100644
index 000000000..144abcb05
--- /dev/null
+++ b/tests/lookups/t23032.nim
@@ -0,0 +1,13 @@
+discard """
+action: "run"
+outputsub: "proc (a: A[system.float]): bool{.noSideEffect, gcsafe.}"
+"""
+
+import issue_23032/deep_scope
+
+proc foo(a: A[float]):bool = true
+
+let p: proc = foo
+echo p.typeof
+doAssert p(A[float]()) == true
+doAssert compiles(doAssert p(A[int]()) == true) == false
diff --git a/tests/lookups/t23172.nim b/tests/lookups/t23172.nim
new file mode 100644
index 000000000..9edf9905a
--- /dev/null
+++ b/tests/lookups/t23172.nim
@@ -0,0 +1,9 @@
+import issue_23172/m23172
+
+type FooX = distinct Foo
+
+func `$`*(x: FooX): string =
+  $m23172.Foo(x)
+
+var a: FooX
+doAssert $a == "X"
diff --git a/tests/lookups/t23749.nim b/tests/lookups/t23749.nim
new file mode 100644
index 000000000..650f04ea4
--- /dev/null
+++ b/tests/lookups/t23749.nim
@@ -0,0 +1,37 @@
+discard """
+  action: compile
+"""
+
+{.pragma: callback, gcsafe, raises: [].}
+
+type
+  DataProc* = proc(val: openArray[byte]) {.callback.}
+  GetProc = proc (db: RootRef, key: openArray[byte], onData: DataProc): bool {.nimcall, callback.}
+  KvStoreRef* = ref object
+    obj: RootRef
+    getProc: GetProc
+
+template get(dbParam: KvStoreRef, key: openArray[byte], onData: untyped): bool =
+  let db = dbParam
+  db.getProc(db.obj, key, onData)
+
+func decode(input: openArray[byte], maxSize = 128): seq[byte] =
+  @[]
+
+proc getSnappySSZ(db: KvStoreRef, key: openArray[byte]): string =
+  var status = "not found"
+  proc decode(data: openArray[byte]) =
+    status =
+      if true: "found"
+      else: "corrupted"
+  discard db.get(key, decode)
+  status
+
+
+var ksr: KvStoreRef
+var k = [byte(1), 2, 3, 4, 5]
+
+proc foo(): string =
+  getSnappySSZ(ksr, toOpenArray(k, 1, 3))
+
+echo foo()
diff --git a/tests/lookups/tambiguousemit.nim b/tests/lookups/tambiguousemit.nim
new file mode 100644
index 000000000..4f4bacce4
--- /dev/null
+++ b/tests/lookups/tambiguousemit.nim
@@ -0,0 +1,12 @@
+discard """
+  cmd: "nim check $options $file" # use check to assure error is pre-codegen
+  matrix: "; --backend:js" # backend shouldn't matter but at least check js
+"""
+
+proc foo(x: int) = discard
+proc foo(x: float) = discard
+
+{.emit: ["// ", foo].} #[tt.Error
+                ^ ambiguous identifier: 'foo' -- use one of the following:
+  tambiguousemit.foo: proc (x: int){.noSideEffect, gcsafe.}
+  tambiguousemit.foo: proc (x: float){.noSideEffect, gcsafe.}]#
diff --git a/tests/lookups/tambprocvar.nim b/tests/lookups/tambprocvar.nim
new file mode 100644
index 000000000..f5c3fde4f
--- /dev/null
+++ b/tests/lookups/tambprocvar.nim
@@ -0,0 +1,19 @@
+discard """
+  action: reject
+  cmd: "nim check $file"
+  nimout: '''
+tambprocvar.nim(15, 11) Error: ambiguous identifier: 'foo' -- use one of the following:
+  tambprocvar.foo: proc (x: int){.noSideEffect, gcsafe.}
+  tambprocvar.foo: proc (x: float){.noSideEffect, gcsafe.}
+'''
+"""
+
+block:
+  proc foo(x: int) = discard
+  proc foo(x: float) = discard
+
+  let x = foo
+
+block:
+  let x = `+` #[tt.Error
+          ^ ambiguous identifier: '+' -- use one of the following:]#
diff --git a/tests/ambsym/tambsym.nim b/tests/lookups/tambsym.nim
index bd0f41717..bd0f41717 100644
--- a/tests/ambsym/tambsym.nim
+++ b/tests/lookups/tambsym.nim
diff --git a/tests/ambsym/tambsym2.nim b/tests/lookups/tambsym2.nim
index 747f1a086..747f1a086 100644
--- a/tests/ambsym/tambsym2.nim
+++ b/tests/lookups/tambsym2.nim
diff --git a/tests/ambsym/tambsym3.nim b/tests/lookups/tambsym3.nim
index 0558517bd..6bbebca10 100644
--- a/tests/ambsym/tambsym3.nim
+++ b/tests/lookups/tambsym3.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "ambiguous identifier"
+  errormsg: "ambiguous identifier: 'mDec' -- use one of the following:"
   file: "tambsym3.nim"
   line: 11
 """
diff --git a/tests/lookups/tambsymmanual.nim b/tests/lookups/tambsymmanual.nim
new file mode 100644
index 000000000..3ad91b8cc
--- /dev/null
+++ b/tests/lookups/tambsymmanual.nim
@@ -0,0 +1,25 @@
+discard """
+  output: '''
+A: abc
+B: 123
+A: def
+4
+'''
+"""
+# Module C
+import mambsym3, mambsym4
+
+foo("abc") # A: abc
+foo(123) # B: 123
+let inferred: proc (x: string) = foo
+foo("def") # A: def
+
+doAssert not compiles(write(stdout, x)) # error: x is ambiguous
+write(stdout, mambsym3.x) # no error: qualifier used
+
+proc bar(a: int): int = a + 1
+doAssert bar(x) == x + 1 # no error: only A.x of type int matches
+
+var x = 4
+write(stdout, x) # not ambiguous: uses the module C's x
+echo() # for test output
diff --git a/tests/ambsym/tambsys.nim b/tests/lookups/tambsys.nim
index aa740c38f..aa740c38f 100644
--- a/tests/ambsym/tambsys.nim
+++ b/tests/lookups/tambsys.nim
diff --git a/tests/lookups/tambtype.nim b/tests/lookups/tambtype.nim
new file mode 100644
index 000000000..a292db83a
--- /dev/null
+++ b/tests/lookups/tambtype.nim
@@ -0,0 +1,20 @@
+import ./mambtype2
+
+block: # issue #23893
+  discard default(K(0))       # works
+  discard default(mambtype2.B(0))     # works
+  discard default(mambtype2.K(0))     # doesn't work
+
+block: # issue #23898, in template
+  template r() =
+    discard default(B(0))     # compiles
+    discard default(mambtype2.B(0))   # compiles
+    discard default(K(0))     # does not compile
+  r()
+
+block: # in generics
+  proc foo[T]() =
+    discard default(B(0))     # compiles
+    discard default(mambtype2.B(0))   # compiles
+    discard default(K(0))     # does not compile
+  foo[int]()
diff --git a/tests/bind/tbind.nim b/tests/lookups/tbind.nim
index 49c37ae2e..f3fb952e3 100644
--- a/tests/bind/tbind.nim
+++ b/tests/lookups/tbind.nim
@@ -4,6 +4,7 @@ output: '''
 1
 1
 1
+5
 '''
 """
 
@@ -65,3 +66,13 @@ block tmixin:
 
   Foo(a)
   Foo(b)
+
+# issue #11811
+proc p(a : int) =
+  echo a
+
+proc printVar*[T:int|float|string](a : T) =
+  bind p
+  p(a)
+
+printVar(5)
diff --git a/tests/lookups/tbind_for_generics.nim b/tests/lookups/tbind_for_generics.nim
new file mode 100644
index 000000000..db5fbebbc
--- /dev/null
+++ b/tests/lookups/tbind_for_generics.nim
@@ -0,0 +1,17 @@
+discard """
+  errormsg: "type mismatch: got <Foo, Foo>"
+  line: 8
+"""
+proc g[T](x: T) =
+  bind `+`
+  # because we bind `+` here, we must not find the `+` for 'Foo' below:
+  echo x + x
+
+type
+  Foo = object
+    a: int
+
+proc `+`(a, b: Foo): Foo = Foo(a: a.a+b.a)
+
+g(3)
+g(Foo(a: 8))
diff --git a/tests/lookups/tdisambsym.nim b/tests/lookups/tdisambsym.nim
new file mode 100644
index 000000000..678528ad6
--- /dev/null
+++ b/tests/lookups/tdisambsym.nim
@@ -0,0 +1,8 @@
+# issue #15247
+
+import mdisambsym1, mdisambsym2, mdisambsym3
+
+proc twice(n: int): int =
+  n*2
+
+doAssert twice(count) == 20
diff --git a/tests/lookups/tenumlocalsym.nim b/tests/lookups/tenumlocalsym.nim
new file mode 100644
index 000000000..575227c07
--- /dev/null
+++ b/tests/lookups/tenumlocalsym.nim
@@ -0,0 +1,22 @@
+block:
+  type Enum = enum a, b
+
+  block:
+    let a = b
+    let x: Enum = a
+    doAssert x == b
+  
+block:
+  type
+    Enum = enum
+      a = 2
+      b = 10
+
+  iterator items2(): Enum =
+    for a in [a, b]:
+      yield a
+
+  var s = newSeq[Enum]()
+  for i in items2():
+    s.add i
+  doAssert s == @[a, b]
diff --git a/tests/lookups/test.nim b/tests/lookups/test.nim
index 97dfa131a..dfacaf5b5 100644
--- a/tests/lookups/test.nim
+++ b/tests/lookups/test.nim
@@ -1,7 +1,7 @@
 discard """
 output: '''
-[Suite] memoization
 
+[Suite] memoization
 '''
 """
 
diff --git a/tests/gensym/tgensym.nim b/tests/lookups/tgensym.nim
index e33a2783f..e33a2783f 100644
--- a/tests/gensym/tgensym.nim
+++ b/tests/lookups/tgensym.nim
diff --git a/tests/gensym/tgensymgeneric.nim b/tests/lookups/tgensymgeneric.nim
index c17a0715f..6e1df4842 100644
--- a/tests/gensym/tgensymgeneric.nim
+++ b/tests/lookups/tgensymgeneric.nim
@@ -21,7 +21,7 @@ template genImpl() =
     gensymed.x = "abc"
   else:
     gensymed.x = 123
-  shallowCopy(result, gensymed)
+  result = move gensymed
 
 proc gen[T](x: T): T =
   genImpl()
diff --git a/tests/bind/tinvalidbindtypedesc.nim b/tests/lookups/tinvalidbindtypedesc.nim
index 4bcd4e39d..1c71c8daf 100644
--- a/tests/bind/tinvalidbindtypedesc.nim
+++ b/tests/lookups/tinvalidbindtypedesc.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "type mismatch: got <type float, string>"
+  errormsg: "type mismatch: got <typedesc[float], string>"
   line: 10
 """
 
diff --git a/tests/lookups/tmacroamb.nim b/tests/lookups/tmacroamb.nim
new file mode 100644
index 000000000..854017e72
--- /dev/null
+++ b/tests/lookups/tmacroamb.nim
@@ -0,0 +1,5 @@
+# issue #12732
+
+import mmacroamb
+const s0 = currentPkgDir2 #[tt.Error
+           ^ ambiguous identifier: 'currentPkgDir2' -- use one of the following:]#
diff --git a/tests/lookups/tmoduleclash1.nim b/tests/lookups/tmoduleclash1.nim
new file mode 100644
index 000000000..7058f691e
--- /dev/null
+++ b/tests/lookups/tmoduleclash1.nim
@@ -0,0 +1,13 @@
+# issue #23596
+
+import std/heapqueue
+type Algo = enum heapqueue, quick
+when false:
+  let x = heapqueue
+let y: Algo = heapqueue
+proc bar*(algo=quick) =
+  var x: HeapQueue[int]
+  case algo
+  of heapqueue: echo 1 # `Algo.heapqueue` works on devel
+  of quick: echo 2
+  echo x.len
diff --git a/tests/lookups/tmoduleclash2.nim b/tests/lookups/tmoduleclash2.nim
new file mode 100644
index 000000000..958da2299
--- /dev/null
+++ b/tests/lookups/tmoduleclash2.nim
@@ -0,0 +1,6 @@
+import std/heapqueue
+proc heapqueue(x: int) = discard
+let x: proc (x: int) = heapqueue
+let y: proc = heapqueue
+when false:
+  let z = heapqueue
diff --git a/tests/bind/tnicerrorforsymchoice.nim b/tests/lookups/tnicerrorforsymchoice.nim
index 684b83239..6001b6b09 100644
--- a/tests/bind/tnicerrorforsymchoice.nim
+++ b/tests/lookups/tnicerrorforsymchoice.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "type mismatch: got <proc (s: TScgi: ScgiState or AsyncScgiState) | proc (client: AsyncSocket, headers: StringTableRef, input: string){.noSideEffect, gcsafe, locks: 0.}>"
+  errormsg: "type mismatch: got <proc (s: TScgi: ScgiState or AsyncScgiState) | proc (client: AsyncSocket, headers: StringTableRef, input: string){.noSideEffect, gcsafe.}>"
   line: 23
 """
 
diff --git a/tests/bind/tbind2.nim b/tests/lookups/told_bind_expr.nim
index fc2eeda1a..56389eaf6 100644
--- a/tests/bind/tbind2.nim
+++ b/tests/lookups/told_bind_expr.nim
@@ -1,9 +1,10 @@
 discard """
   errormsg: "ambiguous call"
-  file: "tbind2.nim"
-  line: 12
+  file: "told_bind_expr.nim"
+  line: 13
 """
-# Test the new ``bind`` keyword for templates
+
+# Pre-0.9 deprecated bind expression syntax
 
 proc p1(x: int8, y: int): int = return x + y
 proc p1(x: int, y: int8): int = return x - y
diff --git a/tests/lookups/tredef.nim b/tests/lookups/tredef.nim
index 8f1b38bd1..7c1df238e 100644
--- a/tests/lookups/tredef.nim
+++ b/tests/lookups/tredef.nim
@@ -4,7 +4,7 @@ foo(1, "test")
 proc bar(a: int, b: string) = discard
 bar(1, "test")
 
-template foo(a: int, b: string) = bar(a, b)
+template foo(a: int, b: string) {.redefine.} = bar(a, b)
 foo(1, "test")
 
 block:
diff --git a/tests/lookups/tundeclaredmixin.nim b/tests/lookups/tundeclaredmixin.nim
new file mode 100644
index 000000000..74d16cdde
--- /dev/null
+++ b/tests/lookups/tundeclaredmixin.nim
@@ -0,0 +1,17 @@
+discard """
+  nimout: '''
+  mixin nothing, add
+'''
+"""
+
+# issue #22012
+
+import macros
+
+expandMacros:
+  proc foo[T](): int =
+    # `nothing` is undeclared, `add` is declared
+    mixin nothing, add
+    123
+
+  doAssert foo[int]() == 123
diff --git a/tests/m14634.nim b/tests/m14634.nim
new file mode 100644
index 000000000..f19f02f0c
--- /dev/null
+++ b/tests/m14634.nim
@@ -0,0 +1,48 @@
+#[
+Tool to investigate underlying reasons for https://github.com/nim-lang/Nim/pull/14634
+nim r --threads:on -d:threadsafe tests/m14634.nim
+]#
+
+when not defined(windows):
+  import std/selectors
+
+  type TestData = object
+    s1, s2, s3: int
+
+  proc timerNotificationTestImpl(data: var TestData) =
+    var selector = newSelector[int]()
+    let t0 = 5
+    var timer = selector.registerTimer(t0, false, 0)
+    let t = 2000
+      # values too close to `t0` cause the test to be flaky in CI on OSX+freebsd
+      # When running locally, t0=100, t=98 will succeed some of the time which indicates
+      # there is some lag involved. Note that the higher `t-t0` is, the less times
+      # the test fails.
+    var rc1 = selector.select(t)
+    var rc2 = selector.select(t)
+    doAssert len(rc1) <= 1 and len(rc2) <= 1
+    data.s1 += ord(len(rc1) == 1)
+    data.s2 += ord(len(rc2) == 1)
+    selector.unregister(timer)
+    discard selector.select(0)
+    selector.registerTimer(t0, true, 0)
+      # same comment as above
+    var rc4 = selector.select(t)
+    let t2 = 100
+      # this can't be too large as it'll actually wait that long:
+      # timer_notification_test.n * t2
+    var rc5 = selector.select(t2)
+    doAssert len(rc4) + len(rc5) <= 1
+    data.s3 += ord(len(rc4) + len(rc5) == 1)
+    doAssert(selector.isEmpty())
+    selector.close()
+
+  proc timerNotificationTest() =
+    var data: TestData
+    let n = 10
+    for i in 0..<n:
+      timerNotificationTestImpl(data)
+    doAssert data.s1 == n and data.s2 == n and data.s3 == n, $data
+
+  when isMainModule:
+    timerNotificationTest()
diff --git a/tests/macros/m18235.nim b/tests/macros/m18235.nim
new file mode 100644
index 000000000..6bb4547e0
--- /dev/null
+++ b/tests/macros/m18235.nim
@@ -0,0 +1,42 @@
+import macros
+
+# Necessary code to update the AST on a symbol across module boundaries when
+# processed by a type macro. Used by a test of a corresponding name of this
+# file.
+
+macro eexport(n: typed): untyped =
+  result = copyNimTree(n)
+  # turn exported nnkSym -> nnkPostfix(*, nnkIdent), forcing re-sem
+  result[0] = nnkPostfix.newTree(ident"*").add:
+    n.name.strVal.ident
+
+macro unexport(n: typed): untyped =
+  result = copyNimTree(n)
+  # turn nnkSym -> nnkIdent, forcing re-sem and dropping any exported-ness
+  # that might be present
+  result[0] = n.name.strVal.ident
+
+proc foo*() {.unexport.} = discard
+proc bar() {.eexport.} = discard
+
+proc foooof*() {.unexport, eexport, unexport.} = discard
+proc barrab() {.eexport, unexport, eexport.} = discard
+
+macro eexportMulti(n: typed): untyped =
+  # use the call version of `eexport` macro for one or more decls
+  result = copyNimTree(n)
+  for i in 0..<result.len:
+    result[i] = newCall(ident"eexport", result[i])
+
+macro unexportMulti(n: typed): untyped =
+  # use the call version of `unexport` macro for one or more decls
+  result = copyNimTree(n)
+  for i in 0..<result.len:
+    result[i] = newCall(ident"unexport", result[i])
+
+unexportMulti:
+  proc oof*() = discard
+
+eexportMulti:
+  proc rab() = discard
+  proc baz*() = discard
\ No newline at end of file
diff --git a/tests/macros/mparsefile.nim b/tests/macros/mparsefile.nim
new file mode 100644
index 000000000..8ac99d568
--- /dev/null
+++ b/tests/macros/mparsefile.nim
@@ -0,0 +1,4 @@
+let a = 1
+let b = 2
+let c =
+let d = 4
diff --git a/tests/macros/t14227.nim b/tests/macros/t14227.nim
new file mode 100644
index 000000000..4206e2c06
--- /dev/null
+++ b/tests/macros/t14227.nim
@@ -0,0 +1,23 @@
+discard """
+  action: "compile"
+"""
+import sugar
+
+
+block:
+  let y = @[@[1, 2], @[2, 4, 6]]
+  let x = collect(newSeq):
+    for i in y:
+      if i.len > 2:
+        for j in i:
+          j
+  echo(x)
+
+block:
+  let y = @[@[1, 2], @[2, 4, 6]]
+  let x = collect(newSeq):
+    for i in y:
+      for j in i:
+        if i.len > 2:
+          j
+  echo(x)
diff --git a/tests/macros/t14329.nim b/tests/macros/t14329.nim
new file mode 100644
index 000000000..b5606424a
--- /dev/null
+++ b/tests/macros/t14329.nim
@@ -0,0 +1,4 @@
+import macros
+
+macro myMacro(n) =
+  let x = if true: newLit"test" else: error "error", n
diff --git a/tests/macros/t14511.nim b/tests/macros/t14511.nim
new file mode 100644
index 000000000..f3b1e2894
--- /dev/null
+++ b/tests/macros/t14511.nim
@@ -0,0 +1,54 @@
+discard """
+  output: "true\n(y: XInt, a: 5)\n(y: XString, b: \"abc\")"
+"""
+
+import macros
+
+block TEST_1:
+  # https://github.com/nim-lang/Nim/issues/14511
+
+  template myPragma() {.pragma.}
+
+  type
+    XType = enum
+      XInt,
+      XString,
+      XUnused
+    X = object
+      case y {.myPragma.}: XType
+        of XInt, XUnused:
+          a: int
+        else: # <-- Else case caused the "Error: index 1 not in 0 .. 0" error
+          b: string
+
+  var x: X = X(y: XInt, a: 5)
+  echo x.y.hasCustomPragma(myPragma)
+  echo x
+  echo X(y: XString, b: "abc")
+
+
+block TEST_2:
+  template myDevice(val: string) {.pragma.}
+  template myKey(val: string) {.pragma.}
+  template myMouse(val: string) {.pragma.}
+
+  type
+    Device {.pure.} = enum Keyboard, Mouse
+    Key = enum Key1, Key2
+    Mouse = enum Mouse1, Mouse2
+
+  type
+    Obj = object of RootObj
+      case device {.myDevice: "MyDevicePragmaStr".}: Device
+      of Device.Keyboard:
+        key {.myKey: "MyKeyPragmaStr".}: Key
+      else: # <-- Else case caused the "Error: index 1 not in 0 .. 0" error
+        mouse {.myMouse: "MyMousePragmaStr".}: Mouse
+
+  var obj: Obj
+  assert obj.device.hasCustomPragma(myDevice) == true
+  assert obj.key.hasCustomPragma(myKey) == true
+  assert obj.mouse.hasCustomPragma(myMouse) == true
+  assert obj.device.getCustomPragmaVal(myDevice) == "MyDevicePragmaStr"
+  assert obj.key.getCustomPragmaVal(myKey) == "MyKeyPragmaStr"
+  assert obj.mouse.getCustomPragmaVal(myMouse) == "MyMousePragmaStr"
\ No newline at end of file
diff --git a/tests/macros/t14847.nim b/tests/macros/t14847.nim
new file mode 100644
index 000000000..0e6d0dd2d
--- /dev/null
+++ b/tests/macros/t14847.nim
@@ -0,0 +1,20 @@
+discard """
+  output: "98"
+"""
+import macros
+
+#bug #14847
+proc hello*(b: string) =
+  echo b
+
+macro dispatch(pro: typed, params: untyped): untyped =
+  var impl = pro.getImpl
+  let id = ident(pro.strVal & "_coverage")
+  impl[0] = id
+  let call = newCall(id, params)
+
+  result = newStmtList()
+  result.add(impl)
+  result.add(call)
+
+dispatch(hello, "98")
diff --git a/tests/macros/t15691.nim b/tests/macros/t15691.nim
new file mode 100644
index 000000000..c1e8a8648
--- /dev/null
+++ b/tests/macros/t15691.nim
@@ -0,0 +1,22 @@
+discard """
+  action: compile
+"""
+
+import std/macros
+
+macro simplifiedExpandMacros(body: typed): untyped =
+  result = body
+
+simplifiedExpandMacros:
+  proc testProc() = discard
+
+simplifiedExpandMacros:
+  template testTemplate(): untyped = discard
+
+# Error: illformed AST: macro testMacro(): untyped =
+simplifiedExpandMacros:
+  macro testMacro(): untyped = discard
+
+# Error: illformed AST: converter testConverter(x: int): float =
+simplifiedExpandMacros:
+  converter testConverter(x: int): float = discard
diff --git a/tests/macros/t15751.nim b/tests/macros/t15751.nim
new file mode 100644
index 000000000..fcabb2f9e
--- /dev/null
+++ b/tests/macros/t15751.nim
@@ -0,0 +1,11 @@
+discard """
+  cmd: "nim c --hints:off $file"
+  nimout: "out"
+"""
+
+# bug #15751
+macro print(n: untyped): untyped =
+  echo n.repr
+
+print:
+  out
diff --git a/tests/macros/t16758.nim b/tests/macros/t16758.nim
new file mode 100644
index 000000000..66b6d42c5
--- /dev/null
+++ b/tests/macros/t16758.nim
@@ -0,0 +1,38 @@
+discard """

+errormsg: "'blk.p(a)' has nil child at index 1"

+action: reject

+"""

+import macros

+

+type BlockLiteral[T] = object

+  p: T

+

+proc p[T](a:int) = echo 1

+proc p[T](a:string) = echo "a"

+

+iterator arguments(formalParams: NimNode): NimNode =

+  var iParam = 0

+  for i in 1 ..< formalParams.len:

+    let pp = formalParams[i]

+    for j in 0 .. pp.len - 3:

+      yield pp[j]

+      inc iParam

+

+macro implementInvoke(T: typedesc): untyped =

+  let t = getTypeImpl(T)[1]

+

+  let call = newCall(newDotExpr(ident"blk", ident"p"))

+  let params = copyNimTree(t[0])

+  result = newProc(ident"invoke", body = call)

+  # result[2] = newTree(nnkGenericParams,T)

+  for n in arguments(params):

+    call.add(n)

+  

+  params.insert(1, newIdentDefs(ident"blk", newTree(nnkBracketExpr, bindSym"BlockLiteral", T)))

+  result.params = params

+

+proc getInvoke(T: typedesc) =

+  implementInvoke(T)

+

+

+getInvoke(proc(a: int))

diff --git a/tests/macros/t17836.nim b/tests/macros/t17836.nim
new file mode 100644
index 000000000..2453637f5
--- /dev/null
+++ b/tests/macros/t17836.nim
@@ -0,0 +1,15 @@
+import macros
+
+# Ensure that `isNil` works in the typed macro context when pass procs.
+
+type
+  O = object
+    fn: proc(i: int): int
+
+var o: O
+
+macro typedBug(expr: typed) =
+  doAssert expr[1] != nil
+  doAssert not expr[1].isNil
+
+typedBug(o.fn)
\ No newline at end of file
diff --git a/tests/macros/t18203.nim b/tests/macros/t18203.nim
new file mode 100644
index 000000000..aae0a2690
--- /dev/null
+++ b/tests/macros/t18203.nim
@@ -0,0 +1,15 @@
+discard """
+  matrix: "--hint:SuccessX:off --hint:Link:off --hint:Conf:off --hint:CC:off --hint:XDeclaredButNotUsed:on"
+  nimout: '''
+'''
+nimoutFull: true
+action: compile
+"""
+
+# bug #18203
+import std/macros
+
+macro foo(x: typed) = newProc ident"bar"
+proc bar() {.foo.} = raise
+bar()
+
diff --git a/tests/macros/t18235.nim b/tests/macros/t18235.nim
new file mode 100644
index 000000000..ba5c48a24
--- /dev/null
+++ b/tests/macros/t18235.nim
@@ -0,0 +1,18 @@
+import m18235
+
+# this must error out because it was never actually exported
+doAssert(not declared(foo))
+doAssert not compiles(foo())
+
+doAssert(not declared(foooof))
+doAssert not compiles(foooof())
+
+doAssert(not declared(oof))
+doAssert not compiles(oof())
+
+# this should have been exported just fine
+
+bar()
+barrab()
+rab()
+baz()
\ No newline at end of file
diff --git a/tests/macros/t19766_20114.nim b/tests/macros/t19766_20114.nim
new file mode 100644
index 000000000..ac336f150
--- /dev/null
+++ b/tests/macros/t19766_20114.nim
@@ -0,0 +1,16 @@
+discard """
+  action: compile
+  nimout: '''
+const
+  foo {.strdefine.} = "abc"
+let hey {.tddd.} = 5
+'''
+"""
+
+import macros
+
+template tddd {.pragma.}
+
+expandMacros:
+  const foo {.strdefine.} = "abc"
+  let hey {.tddd.} = 5
diff --git a/tests/macros/t20067.nim b/tests/macros/t20067.nim
new file mode 100644
index 000000000..0ee3a4712
--- /dev/null
+++ b/tests/macros/t20067.nim
@@ -0,0 +1,28 @@
+discard """
+  output: '''
+b.defaultVal = foo
+$c.defaultVal = bar
+'''
+"""
+
+import macros
+
+# #18976
+
+macro getString(identifier): string =
+  result = newLit($identifier)
+doAssert getString(abc) == "abc"
+doAssert getString(`a b c`) == "abc"
+
+# #20067
+
+template defaultVal*(value : typed) {.pragma.}
+
+type A = ref object
+  b {.defaultVal: "foo".}: string
+  `$c` {.defaultVal: "bar".}: string
+
+let a = A(b: "a", `$c`: "b")
+
+echo "b.defaultVal = " & a.b.getCustomPragmaVal(defaultVal)
+echo "$c.defaultVal = " & a.`$c`.getCustomPragmaVal(defaultVal)
diff --git a/tests/macros/t20435.nim b/tests/macros/t20435.nim
new file mode 100644
index 000000000..824282198
--- /dev/null
+++ b/tests/macros/t20435.nim
@@ -0,0 +1,30 @@
+
+#[
+  A better test requires matching, so the use of @ working can be showcased
+  For example:
+
+  proc regularCase[T]() = 
+    case [(1, 3), (3, 4)]:
+    of [(1, @a), (_, @b)]:
+      echo a, b
+    else: discard
+]#
+
+{.experimental: "caseStmtMacros".}
+
+import macros
+
+type Foo = object
+
+macro `case`(obj: Foo) = quote do: discard
+
+proc notGeneric() =
+  case Foo()
+  of a b c d: discard
+
+proc generic[T]() =
+  case Foo()
+  of a b c d: discard
+
+notGeneric()
+generic[int]()
diff --git a/tests/macros/t21593.nim b/tests/macros/t21593.nim
new file mode 100644
index 000000000..b0b7ebe75
--- /dev/null
+++ b/tests/macros/t21593.nim
@@ -0,0 +1,13 @@
+discard """
+nimout: '''
+StmtList
+  UIntLit 18446744073709551615
+  IntLit -1'''
+"""
+
+import macros
+
+dumpTree:
+  0xFFFFFFFF_FFFFFFFF'u
+  0xFFFFFFFF_FFFFFFFF
+
diff --git a/tests/macros/t23032_1.nim b/tests/macros/t23032_1.nim
new file mode 100644
index 000000000..4e1707414
--- /dev/null
+++ b/tests/macros/t23032_1.nim
@@ -0,0 +1,19 @@
+import std/macros
+
+type A[T, H] = object
+
+proc `%*`(a: A): bool = true
+proc `%*`[T](a: A[int, T]): bool = false
+
+macro collapse(s: untyped) =
+  result = newStmtList()
+  result.add quote do:
+    doAssert(`s`(A[float, int]()) == true)
+
+macro startHere(n: untyped): untyped =
+  result = newStmtList()
+  let s = n[0]
+  result.add quote do:
+    `s`.collapse()
+
+startHere(`a` %* `b`)
diff --git a/tests/macros/t23032_2.nim b/tests/macros/t23032_2.nim
new file mode 100644
index 000000000..8dde29e10
--- /dev/null
+++ b/tests/macros/t23032_2.nim
@@ -0,0 +1,20 @@
+discard """
+  action: "reject"
+  errormsg: "ambiguous identifier: '%*'"
+"""
+import std/macros
+
+type A[T, H] = object
+
+proc `%*`[T](a: A) = discard
+proc `%*`[T](a: A[int, T]) = discard
+
+macro collapse(s: typed) = discard
+
+macro startHere(n: untyped): untyped =
+  result = newStmtList()
+  let s = n[0]
+  result.add quote do:
+    collapse(`s`.typeof())
+
+startHere(`a` %* `b`)
diff --git a/tests/macros/t23547.nim b/tests/macros/t23547.nim
new file mode 100644
index 000000000..9a2bff9ff
--- /dev/null
+++ b/tests/macros/t23547.nim
@@ -0,0 +1,23 @@
+# https://github.com/nim-lang/Nim/issues/23547
+
+type
+  A[T] = object
+    x: T
+
+proc mulCheckSparse[F](dummy: var A[F], xmulchecksparse: static A[F]) =
+  static:
+    echo "mulCheckSparse: ", typeof(dummy), ", ", typeof(xmulchecksparse) # when generic params not specified: A[system.int], A
+
+template sumImpl(xsumimpl: typed) =
+  static:
+    echo "sumImpl: ", typeof(xsumimpl) # A
+  var a = A[int](x: 55)
+  mulCheckSparse(a, xsumimpl) # fails here
+
+proc sum[T](xsum: static T) =
+  static:
+    echo "sum: ", typeof(xsum) # A[system.int]
+  sumImpl(xsum)
+
+const constA = A[int](x : 100)
+sum[A[int]](constA)
diff --git a/tests/macros/t23784.nim b/tests/macros/t23784.nim
new file mode 100644
index 000000000..31b4544c6
--- /dev/null
+++ b/tests/macros/t23784.nim
@@ -0,0 +1,157 @@
+discard """
+  joinable: false
+"""
+
+
+# debug ICE: genCheckedRecordField
+# apparently after https://github.com/nim-lang/Nim/pull/23477
+
+# bug #23784
+
+import std/bitops, std/macros
+
+# --------------------------------------------------------------
+
+type Algebra = enum
+  BN254_Snarks
+
+type SecretWord* = distinct uint64
+const WordBitWidth* = sizeof(SecretWord) * 8
+
+func wordsRequired*(bits: int): int {.inline.} =
+  const divShiftor = fastLog2(WordBitWidth)
+  result = (bits + WordBitWidth - 1) shr divShiftor
+
+type
+  BigInt*[bits: static int] = object
+    limbs*: array[bits.wordsRequired, SecretWord]  # <--- crash points to here
+
+# --------------------------------------------------------------
+
+const CurveBitWidth = [
+  BN254_Snarks: 254
+]
+
+const BN254_Snarks_Modulus = BigInt[254](limbs: [SecretWord 0x1, SecretWord 0x2, SecretWord 0x3, SecretWord 0x4])
+const BN254_Snarks_Order = BigInt[254](limbs: [SecretWord 0x1, SecretWord 0x1, SecretWord 0x2, SecretWord 0x2])
+
+func montyOne*(M: BigInt[254]): BigInt[254] =
+  ## Returns "1 (mod M)" in the Montgomery domain.
+  ## This is equivalent to R (mod M) in the natural domain
+  BigInt[254](limbs: [SecretWord 0x1, SecretWord 0x1, SecretWord 0x1, SecretWord 0x1])
+
+
+{.experimental: "dynamicBindSym".}
+
+type
+  DerivedConstantMode* = enum
+    kModulus
+    kOrder
+
+macro genDerivedConstants*(mode: static DerivedConstantMode): untyped =
+  ## Generate constants derived from the main constants
+  ##
+  ## For example
+  ## - the Montgomery magic constant "R^2 mod N" in ROM
+  ##   For each curve under the private symbol "MyCurve_R2modP"
+  ## - the Montgomery magic constant -1/P mod 2^Wordbitwidth
+  ##   For each curve under the private symbol "MyCurve_NegInvModWord
+  ## - ...
+
+  # Now typedesc are NimNode and there is no way to translate
+  # NimNode -> typedesc easily so we can't
+  # "for curve in low(Curve) .. high(Curve):"
+  # As an ugly workaround, we count
+  # The item at position 0 is a pragma
+  result = newStmtList()
+
+  template used(name: string): NimNode =
+    nnkPragmaExpr.newTree(
+      ident(name),
+      nnkPragma.newTree(ident"used")
+    )
+
+  let ff = if mode == kModulus: "_Fp" else: "_Fr"
+
+  for curveSym in low(Algebra) .. high(Algebra):
+    let curve = $curveSym
+    let M = if mode == kModulus: bindSym(curve & "_Modulus")
+            else: bindSym(curve & "_Order")
+
+    # const MyCurve_montyOne = montyOne(MyCurve_Modulus)
+    result.add newConstStmt(
+      used(curve & ff & "_MontyOne"), newCall(
+        bindSym"montyOne",
+        M
+      )
+    )
+
+# --------------------------------------------------------------
+
+{.experimental: "dynamicBindSym".}
+
+genDerivedConstants(kModulus)
+genDerivedConstants(kOrder)
+
+proc bindConstant(ff: NimNode, property: string): NimNode =
+  # Need to workaround https://github.com/nim-lang/Nim/issues/14021
+  # which prevents checking if a type FF[Name] = Fp[Name] or Fr[Name]
+  # was instantiated with Fp or Fr.
+  # getTypeInst only returns FF and sameType doesn't work.
+  # so quote do + when checks.
+  let T = getTypeInst(ff)
+  T.expectKind(nnkBracketExpr)
+  doAssert T[0].eqIdent("typedesc")
+
+  let curve =
+    if T[1].kind == nnkBracketExpr: # typedesc[Fp[BLS12_381]] as used internally
+      # doAssert T[1][0].eqIdent"Fp" or T[1][0].eqIdent"Fr", "Found ident: '" & $T[1][0] & "' instead of 'Fp' or 'Fr'"
+      T[1][1].expectKind(nnkIntLit) # static enum are ints in the VM
+      $Algebra(T[1][1].intVal)
+    else: # typedesc[bls12381_fp] alias as used for C exports
+      let T1 = getTypeInst(T[1].getImpl()[2])
+      if T1.kind != nnkBracketExpr or
+         T1[1].kind != nnkIntLit:
+        echo T.repr()
+        echo T1.repr()
+        echo getTypeInst(T1).treerepr()
+        error "getTypeInst didn't return the full instantiation." &
+          " Dealing with types in macros is hard, complain at https://github.com/nim-lang/RFCs/issues/44"
+      $Algebra(T1[1].intVal)
+
+  let curve_fp = bindSym(curve & "_Fp_" & property)
+  let curve_fr = bindSym(curve & "_Fr_" & property)
+  result = quote do:
+    when `ff` is Fp:
+      `curve_fp`
+    elif `ff` is Fr:
+      `curve_fr`
+    else:
+      {.error: "Unreachable, received type: " & $`ff`.}
+
+# --------------------------------------------------------------
+
+template matchingBigInt*(Name: static Algebra): untyped =
+  ## BigInt type necessary to store the prime field Fp
+  # Workaround: https://github.com/nim-lang/Nim/issues/16774
+  # as we cannot do array accesses in type section.
+  # Due to generic sandwiches, it must be exported.
+  BigInt[CurveBitWidth[Name]]
+
+type
+  Fp*[Name: static Algebra] = object
+    mres*: matchingBigInt(Name)
+
+macro getMontyOne*(ff: type Fp): untyped =
+  ## Get one in Montgomery representation (i.e. R mod P)
+  result = bindConstant(ff, "MontyOne")
+
+func getOne*(T: type Fp): T {.noInit, inline.} =
+  result = cast[ptr T](unsafeAddr getMontyOne(T))[]
+
+# --------------------------------------------------------------
+proc foo(T: Fp) =
+  discard T
+
+let a = Fp[BN254_Snarks].getOne()
+foo(a) # oops this was a leftover that broke the bisect.
diff --git a/tests/macros/t7875.nim b/tests/macros/t7875.nim
new file mode 100644
index 000000000..7b6e47b86
--- /dev/null
+++ b/tests/macros/t7875.nim
@@ -0,0 +1,22 @@
+discard """
+  nimout: "var mysym`gensym0: MyType[float32]"
+  joinable: false
+"""
+
+import macros
+
+type
+  MyType[T] = object
+
+# this is totally fine
+var mysym: MyType[float32]
+
+macro foobar(): untyped =
+  let floatSym = bindSym"float32"
+
+  result = quote do:
+    var mysym: MyType[`floatSym`]
+
+  echo result.repr
+
+foobar()
diff --git a/tests/macros/tastrepr.nim b/tests/macros/tastrepr.nim
index e4271f019..96a37c7a2 100644
--- a/tests/macros/tastrepr.nim
+++ b/tests/macros/tastrepr.nim
@@ -1,5 +1,6 @@
 discard """
 output: '''
+
 var data = @[(1, "one"), (2, "two")]
 for (i, d) in pairs(data):
   discard
@@ -7,7 +8,11 @@ for i, d in pairs(data):
   discard
 for i, (x, y) in pairs(data):
   discard
-var (a, b) = (1, 2)
+var
+  a = 1
+  b = 2
+type
+  A* = object
 
 var data = @[(1, "one"), (2, "two")]
 for (i, d) in pairs(data):
@@ -17,6 +22,11 @@ for i, d in pairs(data):
 for i, (x, y) in pairs(data):
   discard
 var (a, b) = (1, 2)
+type
+  A* = object
+
+var t04 = 1.0'f128
+t04 = 2.0'f128
 '''
 """
 
@@ -41,3 +51,8 @@ echoTypedAndUntypedRepr:
   for i, (x,y) in pairs(data):
     discard
   var (a,b) = (1,2)
+  type A* = object # issue #22933
+
+echoUntypedRepr:
+  var t04 = 1'f128
+  t04 = 2'f128
diff --git a/tests/macros/tcasestmtmacro.nim b/tests/macros/tcasestmtmacro.nim
new file mode 100644
index 000000000..32019a92a
--- /dev/null
+++ b/tests/macros/tcasestmtmacro.nim
@@ -0,0 +1,33 @@
+discard """
+  output: '''
+yes
+'''
+"""
+
+import macros
+
+macro `case`(n: tuple): untyped =
+  result = newTree(nnkIfStmt)
+  let selector = n[0]
+  for i in 1 ..< n.len:
+    let it = n[i]
+    case it.kind
+    of nnkElse, nnkElifBranch, nnkElifExpr, nnkElseExpr:
+      result.add it
+    of nnkOfBranch:
+      for j in 0..it.len-2:
+        let cond = newCall("==", selector, it[j])
+        result.add newTree(nnkElifBranch, cond, it[^1])
+    else:
+      error "custom 'case' for tuple cannot handle this node", it
+
+var correct = false
+
+case ("foo", 78)
+of ("foo", 78):
+  correct = true
+  echo "yes"
+of ("bar", 88): echo "no"
+else: discard
+
+doAssert correct
diff --git a/tests/macros/tclosuremacro.nim b/tests/macros/tclosuremacro.nim
index 9f2137dec..44c2411a5 100644
--- a/tests/macros/tclosuremacro.nim
+++ b/tests/macros/tclosuremacro.nim
@@ -1,11 +1,6 @@
 discard """
-  output: '''10
-10
-10
-3
-3
+  output: '''
 noReturn
-6
 calling mystuff
 yes
 calling mystuff
@@ -13,7 +8,7 @@ yes
 '''
 """
 
-import future, macros
+import sugar, macros
 
 proc twoParams(x: (int, int) -> int): int =
   result = x(5, 5)
@@ -30,23 +25,23 @@ proc noReturn(x: () -> void) =
 proc doWithOneAndTwo(f: (int, int) -> int): int =
   f(1,2)
 
-echo twoParams(proc (a, b: auto): auto = a + b)
-echo twoParams((x, y) => x + y)
-
-echo oneParam(x => x+5)
-
-echo noParams(() => 3)
-
-echo doWithOneAndTwo((x, y) => x + y)
+doAssert twoParams(proc (a, b: auto): auto = a + b) == 10
+doAssert twoParams((x, y) => x + y) == 10
+doAssert oneParam(x => x+5) == 10
+doAssert noParams(() => 3) == 3
+doAssert doWithOneAndTwo((x, y) => x + y) == 3
 
 noReturn((() -> void) => echo("noReturn"))
 
 proc pass2(f: (int, int) -> int): (int) -> int =
   ((x: int) -> int) => f(2, x)
 
-echo pass2((x, y) => x + y)(4)
+doAssert pass2((x, y) => x + y)(4) == 6
 
+const fun = (x, y: int) {.noSideEffect.} => x + y
 
+doAssert typeof(fun) is (proc (x, y: int): int {.nimcall.})
+doAssert fun(3, 4) == 7
 
 proc register(name: string; x: proc()) =
   echo "calling ", name
@@ -72,3 +67,14 @@ macro m(x: untyped): untyped =
 m:
   proc mystuff() =
     echo "yes"
+
+const typedParamAndPragma = (x, y: int) -> int => x + y
+doAssert typedParamAndPragma(1, 2) == 3
+
+type
+  Bot = object
+    call: proc (): string {.noSideEffect.}
+
+var myBot = Bot()
+myBot.call = () {.noSideEffect.} => "I'm a bot."
+doAssert myBot.call() == "I'm a bot."
diff --git a/tests/macros/tdumpast.nim b/tests/macros/tdumpast.nim
index 3a26ffd2f..484b3c2f3 100644
--- a/tests/macros/tdumpast.nim
+++ b/tests/macros/tdumpast.nim
@@ -2,32 +2,160 @@
 
 import macros
 
-template plus(a, b: untyped): untyped {.dirty} =
-  a + b
+block:
+  template plus(a, b: untyped): untyped {.dirty} =
+    a + b
 
-macro call(e: untyped): untyped =
-  result = newCall("foo", newStrLitNode("bar"))
+  macro call(e: untyped): untyped =
+    result = newCall("foo", newStrLitNode("bar"))
 
-macro dumpAST(n: untyped): untyped =
-  # dump AST as a side-effect and return the inner node
-  let n = callsite()
-  echo n.lispRepr
-  echo n.treeRepr
+  macro dumpAST(n: untyped): string =
+    var msg = ""
+    msg.add "lispRepr:\n" & n.lispRepr & "\n"
+    msg.add "treeRepr:\n" & n.treeRepr & "\n"
 
-  var plusAst = getAst(plus(1, 2))
-  echo plusAst.lispRepr
+    var plusAst = getAst(plus(1, 2))
+    msg.add "lispRepr:\n" & n.lispRepr & "\n"
 
-  var callAst = getAst(call(4))
-  echo callAst.lispRepr
+    var callAst = getAst(call(4))
+    msg.add "callAst.lispRepr:\n" & callAst.lispRepr & "\n"
 
-  var e = parseExpr("foo(bar + baz)")
-  echo e.lispRepr
+    var e = parseExpr("foo(bar + baz)")
+    msg.add "e.lispRepr:\n" & e.lispRepr & "\n"
+    result = msg.newLit
 
-  result = n[1]
+  let a = dumpAST:
+    proc add(x, y: int): int =
+      return x + y
+    const foo = 3
 
-dumpAST:
-  proc add(x, y: int): int =
-    return x + y
+  doAssert a == """
+lispRepr:
+(StmtList (ProcDef (Ident "add") (Empty) (Empty) (FormalParams (Ident "int") (IdentDefs (Ident "x") (Ident "y") (Ident "int") (Empty))) (Empty) (Empty) (StmtList (ReturnStmt (Infix (Ident "+") (Ident "x") (Ident "y"))))) (ConstSection (ConstDef (Ident "foo") (Empty) (IntLit 3))))
+treeRepr:
+StmtList
+  ProcDef
+    Ident "add"
+    Empty
+    Empty
+    FormalParams
+      Ident "int"
+      IdentDefs
+        Ident "x"
+        Ident "y"
+        Ident "int"
+        Empty
+    Empty
+    Empty
+    StmtList
+      ReturnStmt
+        Infix
+          Ident "+"
+          Ident "x"
+          Ident "y"
+  ConstSection
+    ConstDef
+      Ident "foo"
+      Empty
+      IntLit 3
+lispRepr:
+(StmtList (ProcDef (Ident "add") (Empty) (Empty) (FormalParams (Ident "int") (IdentDefs (Ident "x") (Ident "y") (Ident "int") (Empty))) (Empty) (Empty) (StmtList (ReturnStmt (Infix (Ident "+") (Ident "x") (Ident "y"))))) (ConstSection (ConstDef (Ident "foo") (Empty) (IntLit 3))))
+callAst.lispRepr:
+(Call (Ident "foo") (StrLit "bar"))
+e.lispRepr:
+(Call (Ident "foo") (Infix (Ident "+") (Ident "bar") (Ident "baz")))
+"""
 
-  proc sub(x, y: int): int = return x - y
+macro fun() =
+  let n = quote do:
+    1+1 == 2
+  doAssert n.repr == "1 + 1 == 2", n.repr
+fun()
 
+macro fun2(): untyped =
+  let n = quote do:
+    1 + 2 * 3 == 1 + 6
+  doAssert n.repr == "1 + 2 * 3 == 1 + 6", n.repr
+fun2()
+
+macro fun3(): untyped =
+  let n = quote do:
+    int | float | array | seq | object | ptr | pointer | float32
+  doAssert n.repr == "int | float | array | seq | object | ptr | pointer | float32", n.repr
+fun3()
+
+macro fun4() =
+  let n = quote do:
+    (a: 1)
+  doAssert n.repr == "(a: 1)", n.repr
+fun4()
+
+# nkTupleConstr vs nkPar tests:
+block: # lispRepr
+  macro lispRepr2(a: untyped): string = newLit a.lispRepr
+
+  doAssert lispRepr2(()) == """(TupleConstr)"""
+  doAssert lispRepr2((a: 1)) == """(TupleConstr (ExprColonExpr (Ident "a") (IntLit 1)))"""
+  doAssert lispRepr2((a: 1, b: 2)) == """(TupleConstr (ExprColonExpr (Ident "a") (IntLit 1)) (ExprColonExpr (Ident "b") (IntLit 2)))"""
+  doAssert lispRepr2((1,)) == """(TupleConstr (IntLit 1))"""
+  doAssert lispRepr2((1, 2)) == """(TupleConstr (IntLit 1) (IntLit 2))"""
+  doAssert lispRepr2((1, 2, 3.0)) == """(TupleConstr (IntLit 1) (IntLit 2) (FloatLit 3.0))"""
+  doAssert lispRepr2((1)) == """(Par (IntLit 1))"""
+  doAssert lispRepr2((1+2)) == """(Par (Infix (Ident "+") (IntLit 1) (IntLit 2)))"""
+
+block: # repr
+  macro repr2(a: untyped): string = newLit a.repr
+
+  doAssert repr2(()) == "()"
+  doAssert repr2((a: 1)) == "(a: 1)"
+  doAssert repr2((a: 1, b: 2)) == "(a: 1, b: 2)"
+  doAssert repr2((1,)) == "(1,)"
+  doAssert repr2((1, 2)) == "(1, 2)"
+  doAssert repr2((1, 2, 3.0)) == "(1, 2, 3.0)"
+  doAssert repr2((1)) == "(1)"
+  doAssert repr2((1+2)) == "(1 + 2)"
+
+block: # treeRepr
+  macro treeRepr2(a: untyped): string = newLit a.treeRepr
+  macro treeRepr3(a: typed): string = newLit a.treeRepr
+
+  doAssert treeRepr2(1+1 == 2) == """
+Infix
+  Ident "=="
+  Infix
+    Ident "+"
+    IntLit 1
+    IntLit 1
+  IntLit 2"""
+
+  proc baz() = discard
+  proc baz(a: int) = discard
+  proc baz(a: float) = discard
+
+  doAssert treeRepr3(baz()) == """
+Call
+  Sym "baz""""
+
+  let a = treeRepr3(block:
+    proc bar(a: auto) = baz())
+  doAssert a == """
+BlockStmt
+  Empty
+  ProcDef
+    Sym "bar"
+    Empty
+    GenericParams
+      Sym "a:type"
+    FormalParams
+      Empty
+      IdentDefs
+        Sym "a"
+        Sym "auto"
+        Empty
+    Empty
+    Bracket
+      Empty
+      Empty
+    StmtList
+      Call
+        OpenSymChoice 3 "baz""""
diff --git a/tests/macros/texpectIdent1.nim b/tests/macros/texpectIdent1.nim
new file mode 100644
index 000000000..26e52afb5
--- /dev/null
+++ b/tests/macros/texpectIdent1.nim
@@ -0,0 +1,18 @@
+discard """
+errormsg: "Expected identifier to be `foo` here"
+line: 18
+"""
+
+import macros
+
+macro testUntyped(arg: untyped): void =
+  arg.expectKind nnkStmtList
+  arg.expectLen 2
+  arg[0].expectKind nnkCall
+  arg[0][0].expectIdent "foo"  # must pass
+  arg[1].expectKind nnkCall
+  arg[1][0].expectIdent "foo"  # must fail
+
+testUntyped:
+  foo(123)
+  bar(321)
diff --git a/tests/macros/texpectIdent2.nim b/tests/macros/texpectIdent2.nim
new file mode 100644
index 000000000..887a6ddc3
--- /dev/null
+++ b/tests/macros/texpectIdent2.nim
@@ -0,0 +1,24 @@
+discard """
+errormsg: "Expected identifier to be `foo` here"
+line: 24
+"""
+
+import macros
+
+macro testTyped(arg: typed): void =
+  arg.expectKind nnkStmtList
+  arg.expectLen 2
+  arg[0].expectKind nnkCall
+  arg[0][0].expectIdent "foo"  # must pass
+  arg[1].expectKind nnkCall
+  arg[1][0].expectIdent "foo"  # must fail
+
+proc foo(arg: int) =
+  discard
+
+proc bar(arg: int) =
+  discard
+
+testTyped:
+  foo(123)
+  bar(321)
diff --git a/tests/macros/tfail_parse.nim b/tests/macros/tfail_parse.nim
new file mode 100644
index 000000000..1925f2b69
--- /dev/null
+++ b/tests/macros/tfail_parse.nim
@@ -0,0 +1,15 @@
+discard """
+action: "reject"
+cmd: "nim check $file"
+errormsg: "expected expression, but got multiple statements [ValueError]"
+file: "macros.nim"
+"""
+
+import macros
+static:
+  discard parseStmt("'")
+  discard parseExpr("'")
+  discard parseExpr("""
+proc foo()
+proc foo() = discard
+""")
diff --git a/tests/macros/tforloop_macro1.nim b/tests/macros/tforloop_macro1.nim
index 49918563d..a8f45c7ac 100644
--- a/tests/macros/tforloop_macro1.nim
+++ b/tests/macros/tforloop_macro1.nim
@@ -12,7 +12,7 @@ discard """
 """
 
 import macros
-{.experimental: "forLoopMacros".}
+
 macro mymacro(): untyped =
   result = newLit([1, 2, 3])
 
diff --git a/tests/macros/tgetimpl.nim b/tests/macros/tgetimpl.nim
index d231a4336..ab33131b0 100644
--- a/tests/macros/tgetimpl.nim
+++ b/tests/macros/tgetimpl.nim
@@ -1,5 +1,5 @@
 discard """
-  nimout: '''"muhaha"
+  nimout: '''foo = "muhaha"
 proc poo(x, y: int) =
   let y = x
   echo ["poo"]'''
@@ -44,10 +44,11 @@ static:
   doAssert checkOwner(poo, 2) == "nskProc"
   doAssert checkOwner(poo, 3) == "nskModule"
   doAssert isSameOwner(foo, poo)
-  doAssert isSameOwner(foo, echo) == false
-  doAssert isSameOwner(poo, len) == false
-
-#---------------------------------------------------------------
+  proc wrappedScope() =
+    proc dummyproc() = discard
+    doAssert isSameOwner(foo, dummyproc) == false
+    doAssert isSameOwner(poo, dummyproc) == false
+  wrappedScope()
 
 macro check_gen_proc(ex: typed): (bool, bool) =
   let lenChoice = bindsym"len"
@@ -65,3 +66,38 @@ macro check_gen_proc(ex: typed): (bool, bool) =
 let a = @[1,2,3]
 assert: check_gen_proc(len(a)) == (false, true)
 
+
+#---------------------------------------------------------------
+# issue #16110
+
+macro check(x: type): untyped =
+  let z = getType(x)
+  let y = getImpl(z[1])  
+  var sym = y[0]
+  if sym.kind == nnkPragmaExpr: sym = sym[0]
+  if sym.kind == nnkPostfix: sym = sym[1]
+  expectKind(z[1], nnkSym)
+  expectKind(sym, nnkSym)
+  expectKind(y[2], nnkObjectTy)
+  doAssert(sym == z[1])
+
+type
+  TirePtr = ptr object
+    code: int
+
+  TireRef* = ref object
+    code: int
+
+  TireRef2* {.inheritable.} = ref object
+    code: int
+
+  TireRef3* {.inheritable.} = object
+    code: int
+
+var z1: TirePtr
+check(typeof(z1[]))
+var z2: TireRef
+check(typeof(z2[]))
+var z3: TireRef2
+check(typeof(z3[]))
+check(TireRef3)
diff --git a/tests/macros/tgetraiseslist.nim b/tests/macros/tgetraiseslist.nim
new file mode 100644
index 000000000..79694a66f
--- /dev/null
+++ b/tests/macros/tgetraiseslist.nim
@@ -0,0 +1,29 @@
+discard """
+  nimout: '''##[ValueError, Gen[string]]##
+%%[RootEffect]%%
+true true'''
+"""
+
+import macros
+import std / effecttraits
+
+type
+  Gen[T] = object of CatchableError
+    x: T
+
+macro m(call: typed): untyped =
+  echo "##", repr getRaisesList(call[0]), "##"
+  echo "%%", repr getTagsList(call[0]), "%%"
+  echo isGcSafe(call[0]), " ", hasNoSideEffects(call[0])
+  result = call
+
+proc gutenTag() {.tags: RootEffect.} = discard
+
+proc r(inp: int) =
+  if inp == 0:
+    raise newException(ValueError, "bah")
+  elif inp == 1:
+    raise newException(Gen[string], "bahB")
+  gutenTag()
+
+m r(2)
diff --git a/tests/macros/tgettype.nim b/tests/macros/tgettype.nim
index bd70a1c30..d91efe1fe 100644
--- a/tests/macros/tgettype.nim
+++ b/tests/macros/tgettype.nim
@@ -1,29 +1,85 @@
-discard """
-output: '''
-(ObjectTy (Empty) (Sym "Model") (RecList (Sym "name") (Sym "password")))
-(BracketExpr (Sym "typeDesc") (Sym "User"))
-'''
-"""
-import macros
+import std/macros
+import stdtest/testutils
 
-type
-  Model = object of RootObj
-  User = object of Model
-    name : string
-    password : string
+# getType
 
-macro testUser: string =
-  result = newLit(User.getType.lispRepr)
+block:
+  type
+    Model = object of RootObj
+    User = object of Model
+      name : string
+      password : string
 
-macro testGeneric(T: typedesc[Model]): string=
-  result = newLit(T.getType.lispRepr)
+  macro testUser: string =
+    result = newLit(User.getType.lispRepr)
 
-echo testUser
-echo User.testGeneric
+  macro testGeneric(T: typedesc[Model]): string=
+    result = newLit(T.getType.lispRepr)
 
-macro assertVoid(e: typed): untyped =
-  assert(getTypeInst(e).typeKind == ntyVoid)
+  doAssert testUser == """(ObjectTy (Empty) (Sym "Model") (RecList (Sym "name") (Sym "password")))"""
+  doAssert User.testGeneric == """(BracketExpr (Sym "typeDesc") (Sym "User"))"""
 
-proc voidProc() = discard
+  macro assertVoid(e: typed): untyped =
+    assert(getTypeInst(e).typeKind == ntyVoid)
 
-assertVoid voidProc()
+  proc voidProc() = discard
+
+  assertVoid voidProc()
+
+block:
+  # refs #18220; not an actual solution (yet) but at least shows what's currently
+  # possible
+
+  type Callable1[R, T, U] = concept fn
+    fn(default(T)) is R
+    fn is U
+
+  # note that typetraits.arity doesn't work
+  macro arity(a: typed): int =
+    # number of params
+    # this is not production code!
+    let a2 = a.getType[1] # this used to crash nim, with: `vmdeps.nim(292, 25) `false``
+    newLit a2.len - 1
+
+  type Callable2[R, T, U] = concept fn
+    fn(default(T)) is R
+    fn is U
+    arity(U) == 2
+
+  proc map1[T, R, U](a: T, fn: Callable1[R, T, U]): R =
+    let fn = U(fn)
+      # `cast[U](fn)` would also work;
+      # this is currently needed otherwise, sigmatch errors with:
+      # Error: attempting to call routine: 'fn'
+      #  found 'fn' [param declared in tgettype.nim(53, 28)]
+      # this can be fixed in future work
+    fn(a)
+
+  proc map2[T, R, U](a: T, fn: Callable2[R, T, U]): R =
+    let fn = U(fn)
+    fn(a)
+
+  proc fn1(a: int, a2 = 'x'): string = $(a, a2, "fn1")
+  proc fn2(a: int, a2 = "zoo"): string = $(a, a2, "fn2")
+  proc fn3(a: int, a2 = "zoo2"): string = $(a, a2, "fn3")
+  proc fn4(a: int): string {.inline.} = $(a, "fn4")
+  proc fn5(a: int): string = $(a, "fn5")
+
+  assertAll:
+    # Callable1
+    1.map1(fn1) == """(1, 'x', "fn1")"""
+    1.map1(fn2) == """(1, "zoo", "fn2")"""
+    1.map1(fn3) == """(1, "zoo", "fn3")"""
+      # fn3's optional param is not honored, because fn3 and fn2 yield same
+      # generic instantiation; this is a caveat with this approach
+      # There are several possible ways to improve things in future work.
+    1.map1(fn4) == """(1, "fn4")"""
+    1.map1(fn5) == """(1, "fn5")"""
+
+    # Callable2; prevents passing procs with optional params to avoid above
+    # mentioned caveat, but more restrictive
+    not compiles(1.map2(fn1))
+    not compiles(1.map2(fn2))
+    not compiles(1.map2(fn3))
+    1.map2(fn4) == """(1, "fn4")"""
+    1.map2(fn5) == """(1, "fn5")"""
diff --git a/tests/macros/tgettypeinst.nim b/tests/macros/tgettypeinst.nim
index 2f9557160..e722f14aa 100644
--- a/tests/macros/tgettypeinst.nim
+++ b/tests/macros/tgettypeinst.nim
@@ -191,14 +191,14 @@ template myAttr3() {.pragma.}
 template serializationKey(key: string) {.pragma.}
 
 type
-  MyObj = object {.packed,myAttr,serializationKey: "one".}
+  MyObj {.packed,myAttr,serializationKey: "one".} = object
     myField {.myAttr2,serializationKey: "two".}: int
     myField2 {.myAttr3,serializationKey: "three".}: float
 
 # field pragmas not currently supported
 test(MyObj):
   type
-    _ = object {.packed,myAttr,serializationKey: "one".}
+    _ {.packed,myAttr,serializationKey: "one".} = object
       myField: int
       myField2: float
 
diff --git a/tests/macros/tgettypeinst7737.nim b/tests/macros/tgettypeinst7737.nim
new file mode 100644
index 000000000..e49f82562
--- /dev/null
+++ b/tests/macros/tgettypeinst7737.nim
@@ -0,0 +1,61 @@
+discard """
+  nimout: '''
+seq[int]
+CustomSeq[int]
+'''
+"""
+
+import macros, typetraits, sequtils
+
+block: # issue #7737 original
+  type
+    CustomSeq[T] = object
+      data: seq[T]
+
+  proc getSubType(T: NimNode): NimNode =
+    echo getTypeInst(T).repr
+    result = getTypeInst(T)[1]
+
+  macro typed_helper(x: varargs[typed]): untyped =
+    let foo = getSubType(x[0])
+    result = quote do: discard
+
+  macro untyped_heavylifting(x: varargs[untyped]): untyped =
+    var containers = nnkArgList.newTree()
+    for arg in x:
+      case arg.kind:
+      of nnkInfix:
+        if eqIdent(arg[0], "in"):
+          containers.add arg[2]
+      else:
+        discard
+    result = quote do:
+      typed_helper(`containers`)
+  var a, b, c: seq[int]
+  untyped_heavylifting z in c, x in a, y in b:
+    discard
+  ## The following gives me CustomSeq instead
+  ## of CustomSeq[int] in getTypeInst
+  var u, v, w: CustomSeq[int]
+  untyped_heavylifting z in u, x in v, y in w:
+    discard
+
+block: # issue #7737 comment
+  type
+    CustomSeq[T] = object
+      data: seq[T]
+  # when using just one argument, `foo` and `bar` should be exactly
+  # identical.
+  macro foo(arg: typed): string =
+    result = newLit(arg.getTypeInst.repr)
+  macro bar(args: varargs[typed]): untyped =
+    result = newTree(nnkBracket)
+    for arg in args:
+      result.add newLit(arg.getTypeInst.repr)
+  var
+    a: seq[int]
+    b: CustomSeq[int]
+  doAssert foo(a) == "seq[int]"
+  doAssert bar(a) == ["seq[int]"]
+  doAssert foo(b) == "CustomSeq[int]"
+  doAssert bar(b) == ["CustomSeq[int]"]
diff --git a/tests/macros/tmacro2.nim b/tests/macros/tmacro2.nim
index 72972c0c1..1ad63ec8c 100644
--- a/tests/macros/tmacro2.nim
+++ b/tests/macros/tmacro2.nim
@@ -26,3 +26,11 @@ const t = mac("HEllo World")
 echo s, " ", t
 
 
+#-----------------------------------------------------------------------------
+# issue #15326
+macro m(n:typed):auto =
+  result = n
+
+proc f[T](x:T): T {.m.} = x
+
+discard f(3)
\ No newline at end of file
diff --git a/tests/macros/tmacro6.nim b/tests/macros/tmacro6.nim
index 0b6423100..c65d34b6d 100644
--- a/tests/macros/tmacro6.nim
+++ b/tests/macros/tmacro6.nim
@@ -1,22 +1,22 @@
 discard """
-errormsg: "expression '123' is of type 'int literal(123)' and has to be discarded"
+errormsg: "expression '123' is of type 'int literal(123)' and has to be used (or discarded)"
 line: 71
 """
 
 import macros
 
-proc foo(a,b,c: int): int =
+proc foo(a, b, c: int): int =
   result += a
   result += b
   result += c
 
-macro bar(a,b,c: int): int =
+macro bar(a, b, c: int): int =
   result = newCall(ident"echo")
   result.add a
   result.add b
   result.add c
 
-macro baz(a,b,c: int): int =
+macro baz(a, b, c: int): int =
   let stmt = nnkStmtListExpr.newTree()
   stmt.add newCall(ident"echo", a)
   stmt.add newCall(ident"echo", b)
@@ -26,7 +26,7 @@ macro baz(a,b,c: int): int =
 
 # test no result type with explicit return
 
-macro baz2(a,b,c: int) =
+macro baz2(a, b, c: int) =
   let stmt = nnkStmtListExpr.newTree()
   stmt.add newCall(ident"echo", a)
   stmt.add newCall(ident"echo", b)
@@ -35,7 +35,7 @@ macro baz2(a,b,c: int) =
 
 # test explicit void type with explicit return
 
-macro baz3(a,b,c: int): void =
+macro baz3(a, b, c: int): void =
   let stmt = nnkStmtListExpr.newTree()
   stmt.add newCall(ident"echo", a)
   stmt.add newCall(ident"echo", b)
@@ -44,7 +44,7 @@ macro baz3(a,b,c: int): void =
 
 # test no result type with result variable
 
-macro baz4(a,b,c: int) =
+macro baz4(a, b, c: int) =
   result = nnkStmtListExpr.newTree()
   result.add newCall(ident"echo", a)
   result.add newCall(ident"echo", b)
@@ -52,7 +52,7 @@ macro baz4(a,b,c: int) =
 
 # test explicit void type with result variable
 
-macro baz5(a,b,c: int): void =
+macro baz5(a, b, c: int): void =
   let result = nnkStmtListExpr.newTree()
   result.add newCall(ident"echo", a)
   result.add newCall(ident"echo", b)
diff --git a/tests/macros/tmacrogensym.nim b/tests/macros/tmacrogensym.nim
index 15a08c574..7c0d75f82 100644
--- a/tests/macros/tmacrogensym.nim
+++ b/tests/macros/tmacrogensym.nim
@@ -1,6 +1,6 @@
 import nativesockets, asyncdispatch, macros
 var p = newDispatcher()
-var sock = newAsyncNativeSocket()
+var sock = createAsyncNativeSocket()
 
 proc convertReturns(node, retFutureSym: NimNode): NimNode {.compileTime.} =
   case node.kind
@@ -27,7 +27,7 @@ macro async2(prc: untyped): untyped =
 
   # -> iterator nameIter(): FutureBase {.closure.} = <proc_body>
   # Changing this line to: newIdentNode($prc[0].ident & "Iter") # will make it work.
-  var iteratorNameSym = genSym(nskIterator, $prc[0].ident & "Iter")
+  var iteratorNameSym = genSym(nskIterator, $prc[0] & "Iter")
   assert iteratorNameSym.symKind == nskIterator
   #var iteratorNameSym = newIdentNode($prc[0].ident & "Iter")
   var procBody = prc[6].convertReturns(retFutureSym)
@@ -39,7 +39,7 @@ macro async2(prc: untyped): untyped =
 
   # -> var nameIterVar = nameIter
   # -> var first = nameIterVar()
-  var varNameIterSym = newIdentNode($prc[0].ident & "IterVar") #genSym(nskVar, $prc[0].ident & "IterVar")
+  var varNameIterSym = newIdentNode($prc[0] & "IterVar") #genSym(nskVar, $prc[0].ident & "IterVar")
   var varNameIter = newVarStmt(varNameIterSym, iteratorNameSym)
   outerProcBody.add varNameIter
   var varFirstSym = genSym(nskVar, "first")
@@ -52,7 +52,7 @@ macro async2(prc: untyped): untyped =
 
   # Remove the 'closure' pragma.
   for i in 0 ..< result[4].len:
-    if result[4][i].ident == !"async":
+    if result[4][i] == newIdentNode("async"):
       result[4].del(i)
 
   result[6] = outerProcBody
diff --git a/tests/macros/tmacrogetimpl.nim b/tests/macros/tmacrogetimpl.nim
new file mode 100644
index 000000000..1d996ff29
--- /dev/null
+++ b/tests/macros/tmacrogetimpl.nim
@@ -0,0 +1,31 @@
+import macros
+
+# bug #5034
+
+macro copyImpl(srsProc: typed, toSym: untyped) =
+  result = copyNimTree(getImplTransformed(srsProc))
+  result[0] = ident $toSym.toStrLit()
+
+proc foo1(x: float, one: bool = true): float =
+  if one:
+    return 1'f
+  result = x
+
+proc bar1(what: string): string =
+  ## be a little more adversarial with `skResult`
+  proc buzz: string =
+    result = "lightyear"
+  if what == "buzz":
+    result = "buzz " & buzz()
+  else:
+    result = what
+  return result
+
+copyImpl(foo1, foo2)
+doAssert foo1(1'f) == 1.0
+doAssert foo2(10.0, false) == 10.0
+doAssert foo2(10.0) == 1.0
+
+copyImpl(bar1, bar2)
+doAssert bar1("buzz") == "buzz lightyear"
+doAssert bar1("macros") == "macros"
diff --git a/tests/macros/tmacros1.nim b/tests/macros/tmacros1.nim
index 53af4287c..c588ff7e6 100644
--- a/tests/macros/tmacros1.nim
+++ b/tests/macros/tmacros1.nim
@@ -60,3 +60,22 @@ macro foo(t: static Tuple): untyped =
   doAssert t.b == 12345
 
 foo((a: "foo", b: 12345))
+
+
+# bug #16307
+
+macro bug(x: untyped): string =
+  newLit repr(x)
+
+let res = bug:
+  block:
+    ## one
+    ## two
+    ## three
+
+doAssert res == """
+
+block:
+  ## one
+  ## two
+  ## three"""
diff --git a/tests/macros/tmacros_issues.nim b/tests/macros/tmacros_issues.nim
index df385c445..a81c51658 100644
--- a/tests/macros/tmacros_issues.nim
+++ b/tests/macros/tmacros_issues.nim
@@ -19,6 +19,8 @@ nil
 42
 false
 true
+@[i0, i1, i2, i3, i4]
+@[tmp, tmp, tmp, tmp, tmp]
 '''
 
   output: '''
@@ -27,6 +29,18 @@ array[0 .. 100, int]
 10
 test
 0o377'i8
+0o000000000755'i32
+1
+2
+3
+foo1
+foo2
+foo3
+true
+false
+true
+false
+1.0
 '''
 """
 
@@ -50,7 +64,7 @@ block t7723:
 
 block t8706:
   macro varargsLen(args:varargs[untyped]): untyped =
-    doAssert args.kind == nnkArglist
+    doAssert args.kind == nnkArgList
     doAssert args.len == 0
     result = newLit(args.len)
 
@@ -244,3 +258,264 @@ macro toRendererBug(n): untyped =
   result = newLit repr(n)
 
 echo toRendererBug(0o377'i8)
+echo toRendererBug(0o755'i32)
+
+# bug #12129
+macro foobar() =
+  var loopVars = newSeq[NimNode](5)
+  for i, sym in loopVars.mpairs():
+    sym = ident("i" & $i)
+  echo loopVars
+  for sym in loopVars.mitems():
+    sym = ident("tmp")
+  echo loopVars
+
+foobar()
+
+
+# bug #13253
+import macros
+
+type
+  FooBar = object
+    a: seq[int]
+
+macro genFoobar(a: static FooBar): untyped =
+  result = newStmtList()
+  for b in a.a:
+    result.add(newCall(bindSym"echo", newLit b))
+
+proc foobar(a: static FooBar) =
+  genFoobar(a)  # removing this make it work
+  for b in a.a:
+    echo "foo" & $b
+
+proc main() =
+  const a: seq[int] = @[1, 2,3]
+  # Error: type mismatch: got <array[0..2, int]> but expected 'seq[int]'
+  const fb = Foobar(a: a)
+  foobar(fb)
+main()
+
+# bug #13484
+
+proc defForward(id, nid: NimNode): NimNode =
+  result = newProc(id, @[newIdentNode("bool"), newIdentDefs(nid, newIdentNode("int"))], body=newEmptyNode())
+
+proc defEven(evenid, oddid, nid: NimNode): NimNode =
+  result = quote do:
+    proc `evenid`(`nid`: int): bool =
+      if `nid` == 0:
+        return true
+      else:
+        return `oddid`(`nid` - 1)
+
+proc defOdd(evenid, oddid, nid: NimNode): NimNode =
+  result = quote do:
+    proc `oddid`(`nid`: int): bool =
+      if `nid` == 0:
+        return false
+      else:
+        return `evenid`(`nid` - 1)
+
+proc callNode(funid, param: NimNode): NimNode =
+  result = quote do:
+    `funid`(`param`)
+
+macro testEvenOdd3(): untyped =
+  let
+    evenid = newIdentNode("even3")
+    oddid = newIdentNode("odd3")
+    nid = newIdentNode("n")
+    oddForward = defForward(oddid, nid)
+    even = defEven(evenid, oddid, nid)
+    odd = defOdd(evenid, oddid, nid)
+    callEven = callNode(evenid, newLit(42))
+    callOdd = callNode(oddid, newLit(42))
+  result = quote do:
+    `oddForward`
+    `even`
+    `odd`
+    echo `callEven`
+    echo `callOdd`
+
+macro testEvenOdd4(): untyped =
+  let
+    evenid = newIdentNode("even4")
+    oddid = newIdentNode("odd4")
+    nid = newIdentNode("n")
+    oddForward = defForward(oddid, nid)
+    even = defEven(evenid, oddid, nid)
+    odd = defOdd(evenid, oddid, nid)
+    callEven = callNode(evenid, newLit(42))
+    callOdd = callNode(oddid, newLit(42))
+  # rewrite the body of proc node.
+  oddForward[6] = newStmtList()
+  result = quote do:
+    `oddForward`
+    `even`
+    `odd`
+    echo `callEven`
+    echo `callOdd`
+
+macro testEvenOdd5(): untyped =
+  let
+    evenid = genSym(nskProc, "even5")
+    oddid = genSym(nskProc, "odd5")
+    nid = newIdentNode("n")
+    oddForward = defForward(oddid, nid)
+    even = defEven(evenid, oddid, nid)
+    odd = defOdd(evenid, oddid, nid)
+    callEven = callNode(evenid, newLit(42))
+    callOdd = callNode(oddid, newLit(42))
+  result = quote do:
+    `oddForward`
+    `even`
+    `odd`
+    echo `callEven`
+    echo `callOdd`
+
+macro testEvenOdd6(): untyped =
+  let
+    evenid = genSym(nskProc, "even6")
+    oddid = genSym(nskProc, "odd6")
+    nid = newIdentNode("n")
+    oddForward = defForward(oddid, nid)
+    even = defEven(evenid, oddid, nid)
+    odd = defOdd(evenid, oddid, nid)
+    callEven = callNode(evenid, newLit(42))
+    callOdd = callNode(oddid, newLit(42))
+  # rewrite the body of proc node.
+  oddForward[6] = newStmtList()
+  result = quote do:
+    `oddForward`
+    `even`
+    `odd`
+    echo `callEven`
+    echo `callOdd`
+
+# it works
+testEvenOdd3()
+
+# it causes an error (redefinition of odd4), which is correct
+assert not compiles testEvenOdd4()
+
+# it caused an error (still forwarded: odd5)
+testEvenOdd5()
+
+# it works, because the forward decl and definition share the symbol and the compiler is forgiving here
+#testEvenOdd6() #Don't test it though, the compiler may become more strict in the future
+
+# bug #15385
+var captured_funcs {.compileTime.}: seq[NimNode] = @[]
+
+macro aad*(fns: varargs[typed]): typed =
+  result = newStmtList()
+  for fn in fns:
+    captured_funcs.add fn[0]
+    result.add fn
+
+func exp*(x: float): float ## get different error if you remove forward declaration
+
+func exp*(x: float): float {.aad.} =
+  var x1 = min(max(x, -708.4), 709.8)
+  var result: float   ## looks weird because it is taken from template expansion
+  result = x1 + 1.0
+  result
+
+template check_accuracy(f: untyped, rng: Slice[float], n: int, verbose = false): auto =
+
+  proc check_accuracy: tuple[avg_ulp: float, max_ulp: int] {.gensym.} =
+    let k = (rng.b - rng.a) / (float) n
+    var
+      res, x: float
+      i, max_ulp = 0
+      avg_ulp = 0.0
+
+    x = rng.a
+    while (i < n):
+      res = f(x)
+      i.inc
+      x = x + 0.001
+    (avg_ulp, max_ulp)
+  check_accuracy()
+
+discard check_accuracy(exp, -730.0..709.4, 4)
+
+# And without forward decl
+macro aad2*(fns: varargs[typed]): typed =
+  result = newStmtList()
+  for fn in fns:
+    captured_funcs.add fn[0]
+    result.add fn
+
+func exp2*(x: float): float {.aad2.} =
+  var x1 = min(max(x, -708.4), 709.8)
+  var result: float   ## looks weird because it is taken from template expansion
+  result = x1 + 1.0
+  result
+
+template check_accuracy2(f: untyped, rng: Slice[float], n: int, verbose = false): auto =
+
+  proc check_accuracy2: tuple[avg_ulp: float, max_ulp: int] {.gensym.} =
+    let k = (rng.b - rng.a) / (float) n
+    var
+      res, x: float
+      i, max_ulp = 0
+      avg_ulp = 0.0
+
+    x = rng.a
+    while (i < n):
+      res = f(x)
+      i.inc
+      x = x + 0.001
+    (avg_ulp, max_ulp)
+  check_accuracy2()
+
+discard check_accuracy2(exp2, -730.0..709.4, 4)
+
+# And minimized:
+macro aadMin(fn: typed): typed = fn
+
+func expMin: float
+
+func expMin: float {.aadMin.} = 1
+
+echo expMin()
+
+
+# doubly-typed forward decls
+macro noop(x: typed) = x
+noop:
+  proc cally() = discard
+
+cally()
+
+noop:
+  proc barry()
+
+proc barry() = discard
+
+# some more:
+proc barry2() {.noop.}
+proc barry2() = discard
+
+proc barry3() {.noop.}
+proc barry3() {.noop.} = discard
+
+
+# issue #15389
+block double_sem_for_procs:
+
+  macro aad(fns: varargs[typed]): typed =
+    result = newStmtList()
+    for fn in fns:
+      result.add fn
+
+  func exp(x: float): float {.aad.} =
+    var x1 = min(max(x, -708.4), 709.8)
+    if x1 > 0.0:
+      return x1 + 1.0
+    result = 10.0
+
+  discard exp(5.0)
diff --git a/tests/macros/tmacros_various.nim b/tests/macros/tmacros_various.nim
index 3991a5e30..e351b4527 100644
--- a/tests/macros/tmacros_various.nim
+++ b/tests/macros/tmacros_various.nim
@@ -22,6 +22,9 @@ a[1]: 45
 x: some string
 ([("key", "val"), ("keyB", "2")], [("val", "key"), ("2", "keyB")])
 ([("key", "val"), ("keyB", "2")], [("val", "key"), ("2", "keyB")])
+0
+0
+0
 '''
 """
 
@@ -88,7 +91,7 @@ block tlexerex:
 
 
 
-block tlineinfo:
+block tcopylineinfo:
   # issue #5617, feature request
   type Test = object
 
@@ -100,6 +103,27 @@ block tlineinfo:
   var z = mixer(Test)
   doAssert z
 
+block tsetgetlineinfo:
+  # issue #21098, feature request
+  type Test = object
+
+  macro mixer1(n: typed): untyped =
+    let x = newIdentNode("echo")
+    var lineInfo = n.lineInfoObj
+    x.setLineInfo lineInfo
+    result = newLit(x.lineInfo == n.lineInfo)
+
+  macro mixer2(n: typed): untyped =
+    let x = newIdentNode("echo")
+    var lineInfo = n.lineInfoObj
+    lineInfo.line += 1
+    x.setLineInfo lineInfo
+    result = newLit(x.lineInfo != n.lineInfo)
+
+  doAssert mixer1(Test)
+
+  doAssert mixer2(Test)
+
 
 
 block tdebugstmt:
@@ -194,3 +218,174 @@ static:
     doAssert(v == a)
 
   echo "macrocache ok"
+
+block tupleNewLitTests:
+  macro t(): untyped =
+    result = newLit (1, "foo", (), (1,), (a1: 'x', a2: @["ba"]))
+  doAssert $t() == """(1, "foo", (), (1,), (a1: 'x', a2: @["ba"]))"""
+    # this `$` test is needed because tuple equality doesn't distinguish
+    # between named vs unnamed tuples
+  doAssert t() == (1, "foo", (), (1, ), (a1: 'x', a2: @["ba"]))
+
+from strutils import contains
+block getImplTransformed:
+  macro bar(a: typed): string =
+    # newLit a.getImpl.repr # this would be before code transformation
+    let b = a.getImplTransformed
+    newLit b.repr
+  template toExpand() =
+    for ai in 0..2: echo ai
+  proc baz(a=1): int =
+    defer: discard
+    toExpand()
+    12
+  const code = bar(baz)
+  # sanity check:
+  doAssert "finally" in code # `defer` is lowered to try/finally
+  doAssert "while" in code # `for` is lowered to `while`
+  doAssert "toExpand" notin code
+    # template is expanded (but that would already be the case with
+    # `a.getImpl.repr`, unlike the other transformations mentioned above
+
+
+# test macro resemming
+macro makeVar(): untyped =
+  quote:
+    var tensorY {.inject.}: int
+
+macro noop(a: typed): untyped =
+  a
+
+noop:
+  makeVar
+echo tensorY
+
+macro xbenchmark(body: typed): untyped =
+  result = body
+
+xbenchmark:
+  proc fastSHA(inputtest: string) =
+    discard inputtest
+  fastSHA("hey")
+
+block: # issue #4547
+  macro lazy(stmtList : typed) : untyped =
+    let decl = stmtList[0]
+    decl.expectKind nnkLetSection
+    let name = decl[0][0].strVal
+    let call = decl[0][2].copy
+    call.expectKind nnkCall
+    let ident = newIdentNode("get" & name)
+    result = quote do:
+      var value : type(`call`)
+      proc `ident`() : type(`call`) =
+        if value.isNil:
+          value = `call`
+        value
+  type MyObject = object
+    a,b: int    
+  # this part, the macro call and it's result (written in the comment below) is important
+  lazy:
+    let y = new(MyObject)
+  #[
+    var value: type(new(MyObject))
+    proc gety(): type(new(MyObject)) =
+      if value.isNil:
+        value = new(MyObject)
+      value    
+  ]#
+  doAssert gety().a == 0  # works and should work
+  doAssert gety().b == 0  # works and should work
+  doAssert not declared(y)
+  doAssert not compiles(y.a)       # identifier y should not exist anymore
+  doAssert not compiles(y.b)       # identifier y should not exist anymore
+
+block: # bug #13511
+  type
+    Builder = ref object
+      components: seq[Component]
+    Component = object
+
+  proc add(builder: var Builder, component: Component) {.compileTime.} =
+    builder.components.add(component)
+
+  macro debugAst(arg: typed): untyped =
+    ## just for debugging purpose.
+    discard arg.treeRepr
+    return arg
+
+  static:
+    var component = Component()
+    var builder = Builder()
+
+    template foo(): untyped =
+      ## WAS: this doc comment causes compilation failure.
+      builder
+
+    debugAst:
+      add(foo(), component)
+
+block: # bug #15118
+  macro flop(name: static string) =
+    let id = genSym(nskType, "env")
+    let r =
+      nnkStmtList.newTree(
+        nnkTypeSection.newTree(
+          nnkTypeDef.newTree(
+            id,
+            newEmptyNode(),
+            nnkRefTy.newTree(
+              nnkObjectTy.newTree(
+                newEmptyNode(),
+                newEmptyNode(),
+                nnkRecList.newTree(
+                  nnkIdentDefs.newTree(
+                    newIdentNode(name),
+                    newIdentNode("int"),
+                    newEmptyNode()
+                  )
+                )
+              ) 
+            )
+          )
+        ),
+
+        # var f: T
+  
+        nnkVarSection.newTree(
+          nnkIdentDefs.newTree(
+            newIdentNode("f"),
+            id,
+            newEmptyNode()
+          )
+        ),
+
+        # echo f.a
+        nnkCommand.newTree(
+          newIdentNode("new"),
+          newIdentNode("f")
+        ),
+
+        nnkCommand.newTree(
+          newIdentNode("echo"),
+          nnkDotExpr.newTree(
+            newIdentNode("f"),
+            newIdentNode(name)
+          )
+        )
+      )
+    r
+
+
+  block:
+    flop("a")
+
+  block:
+    flop("b")
+
+static:
+  block:
+    const containsTable = CacheTable"containsTable"
+    doAssert "foo" notin containsTable
+    containsTable["foo"] = newLit 42
+    doAssert "foo" in containsTable
diff --git a/tests/macros/tmacrostmt.nim b/tests/macros/tmacrostmt.nim
index 56a0bf840..817bc8352 100644
--- a/tests/macros/tmacrostmt.nim
+++ b/tests/macros/tmacrostmt.nim
@@ -100,25 +100,38 @@ proc fn4(x: int): int =
 proc fn5(a, b: float): float =
   result = - a * a / (b * b)
 
+proc `{}`(x: seq[float], i: int, j: int): float = 
+  x[i + 0 * j]
+
+proc `{}=`(x: var seq[float], i: int, val: float) = 
+  x[i] = val
+
+proc fn6() =
+  var a = @[1.0, 2.0]
+  let z = a{0, 1} 
+  a{2} = 5.0
+
+
 #------------------------------------
 # bug #10807
 proc fn_unsafeaddr(x: int): int =
   cast[int](unsafeAddr(x))
 
 static:
-  echo fn_unsafeaddr.repr_to_string
   let fn1s = "proc fn1(x, y: int): int =\n  result = 2 * (x + y)\n"
   let fn2s = "proc fn2(x, y: float): float =\n  result = (y + 2 * x) / (x - y)\n"
   let fn3s = "proc fn3(x, y: int): bool =\n  result = ((x and 3) div 4 or x mod (y xor -1)) == 0 or not contains([1, 2], y)\n"
   let fn4s = "proc fn4(x: int): int =\n  if x mod 2 == 0:\n    return x + 2\n  else:\n    return 0\n"
   let fn5s = "proc fn5(a, b: float): float =\n  result = -a * a / (b * b)\n"
-  let fnAddr = "proc fn_unsafeaddr(x: int): int =\n  result = cast[int](unsafeAddr(x))\n"
+  let fn6s = "proc fn6() =\n  var a = @[1.0, 2.0]\n  let z = a{0, 1}\n  a{2} = 5.0\n"
+  let fnAddr = "proc fn_unsafeaddr(x: int): int =\n  result = cast[int](addr(x))\n"
 
   doAssert fn1.repr_to_string == fn1s
   doAssert fn2.repr_to_string == fn2s
   doAssert fn3.repr_to_string == fn3s
   doAssert fn4.repr_to_string == fn4s
   doAssert fn5.repr_to_string == fn5s
+  doAssert fn6.repr_to_string == fn6s
   doAssert fn_unsafeaddr.repr_to_string == fnAddr
 
 #------------------------------------
diff --git a/tests/macros/tmacrotypes.nim b/tests/macros/tmacrotypes.nim
index 8cf93a593..13b421303 100644
--- a/tests/macros/tmacrotypes.nim
+++ b/tests/macros/tmacrotypes.nim
@@ -1,23 +1,53 @@
 discard """
-  nimout: '''intProc; ntyProc; proc[int, int, float]; proc (a: int; b: float): int
+  nimout: '''intProc; ntyProc; proc[int, int, float]; proc (a: int; b: float): int {.nimcall.}
 void; ntyVoid; void; void
 int; ntyInt; int; int
-proc (); ntyProc; proc[void]; proc ()
-voidProc; ntyProc; proc[void]; proc ()
+proc () {.nimcall.}; ntyProc; proc[void]; proc () {.nimcall.}
+voidProc; ntyProc; proc[void]; proc () {.nimcall.}
+listing fields for ObjType
+a: string
+b: int
+listing fields for ObjRef
+skipping ref type
+a: string
+b: int
+listing fields for RefType
+skipping ref type
+a: int
+b: float
+listing fields for typeof(a)
+skipping ref type
+a: string
+b: int
+listing fields for typeof(b)
+skipping ref type
+a: string
+b: int
+listing fields for typeof(c)
+skipping ref type
+a: int
+b: float
+listing fields for typeof(x)
+a: string
+b: int
+listing fields for typeof(x)
+a: int
+b: float
 typeDesc[range[1 .. 5]]; ntyTypeDesc; typeDesc[range[1, 5]]; typeDesc[range[1 .. 5]]
 typeDesc[range]; ntyTypeDesc; typeDesc[range[T]]; typeDesc[range]'''
 """
 
-import macros
+import macros, typetraits
 
 macro checkType(ex: typed): untyped =
   echo ex.getTypeInst.repr, "; ", ex.typeKind, "; ", ex.getType.repr, "; ", ex.getTypeImpl.repr
 
 macro checkProcType(fn: typed): untyped =
+  if fn.kind == nnkProcDef:
+    result = fn
   let fn_sym = if fn.kind == nnkProcDef: fn[0] else: fn
   echo fn_sym, "; ", fn_sym.typeKind, "; ", fn_sym.getType.repr, "; ", fn_sym.getTypeImpl.repr
 
-
 proc voidProc = echo "hello"
 proc intProc(a: int, b: float): int {.checkProcType.} = 10
 
@@ -26,6 +56,58 @@ checkType(intProc(10, 20.0))
 checkType(voidProc)
 checkProcType(voidProc)
 
+macro listFields(T: typed) =
+  echo "listing fields for ", repr(T)
+  let inputExprType = getType(T)
+
+  var objType = inputExprType[1]
+  if objType.kind == nnkBracketExpr and objType.len > 1:
+    if ((objType[0].kind == nnkRefTy) or
+        (objType[0].kind == nnkSym and eqIdent(objType[0], "ref"))):
+      echo "skipping ref type"
+      objType = objType[1]
+
+  let typeAst = objType.getImpl
+
+  var objectDef = typeAst[2]
+  if objectDef.kind == nnkRefTy:
+    objectDef = objectDef[0]
+
+  let recList = objectDef[2]
+  for rec in recList:
+    echo $rec[0], ": ", $rec[1]
+
+type
+  ObjType* = object of RootObj
+    a: string
+    b: int
+
+  ObjRef = ref ObjType
+
+  RefType* = ref object of RootObj
+    a: int
+    b: float
+
+listFields ObjType
+listFields ObjRef
+listFields RefType
+
+let
+  a = new ObjType
+  b = new ObjRef
+  c = new RefType
+
+listFields typeOf(a)
+listFields typeOf(b)
+listFields typeOf(c)
+
+proc genericProc(x: object) =
+  listFields typeOf(x)
+
+genericProc a[]
+genericProc b[]
+genericProc c[]
+
 # bug #10548
 block:
   var c {.compileTime.} = 0
diff --git a/tests/macros/tmemit.nim b/tests/macros/tmemit.nim
index 06ab8a1e2..6c9f9f935 100644
--- a/tests/macros/tmemit.nim
+++ b/tests/macros/tmemit.nim
@@ -1,6 +1,5 @@
 discard """
   output: '''
-HELLO WORLD
 c_func
 12
 '''
@@ -8,8 +7,6 @@ c_func
 
 import macros, strutils
 
-emit("echo " & '"' & "hello world".toUpperAscii & '"')
-
 # bug #1025
 
 macro foo(icname): untyped =
diff --git a/tests/macros/tparsefile.nim b/tests/macros/tparsefile.nim
new file mode 100644
index 000000000..a41223f80
--- /dev/null
+++ b/tests/macros/tparsefile.nim
@@ -0,0 +1,11 @@
+import macros
+
+static:
+  let fn = "mparsefile.nim"
+  var raised = false
+  try:
+    discard parseStmt(staticRead(fn), filename = fn)
+  except ValueError as e:
+    raised = true
+    doAssert e.msg == "mparsefile.nim(4, 1) Error: invalid indentation"
+  doAssert raised
diff --git a/tests/macros/tprocgettype.nim b/tests/macros/tprocgettype.nim
new file mode 100644
index 000000000..0c1cc4270
--- /dev/null
+++ b/tests/macros/tprocgettype.nim
@@ -0,0 +1,28 @@
+discard """
+  nimout: '''
+var x: proc () {.cdecl.} = foo
+var x: iterator (): int {.closure.} = bar
+'''
+"""
+
+# issue #19010
+
+import macros
+
+macro createVar(x: typed): untyped =
+  result = nnkVarSection.newTree:
+    newIdentDefs(ident"x", getTypeInst(x), copy(x))
+  
+  echo repr result
+
+block:
+  proc foo() {.cdecl.} = discard
+
+  createVar(foo)
+  x()
+
+block:
+  iterator bar(): int {.closure.} = discard
+
+  createVar(bar)
+  for a in x(): discard
diff --git a/tests/macros/tprochelpers.nim b/tests/macros/tprochelpers.nim
new file mode 100644
index 000000000..d95a2ced8
--- /dev/null
+++ b/tests/macros/tprochelpers.nim
@@ -0,0 +1,22 @@
+import std/macros
+import stdtest/testutils
+
+macro test1(prc: untyped): untyped =
+  assertAll:
+    prc.params.len == 2
+    prc.params[1].len == 4
+    prc.pragma.len == 2
+
+  prc.params = nnkFormalParams.newTree(
+    ident("int")
+  )
+  prc.pragma = newEmptyNode()
+
+  assertAll:
+    prc.params.len == 1
+    prc.pragma.len == 0
+  prc
+
+proc test(a, b: int): int {.gcsafe, raises: [], test1.} = 5
+
+type hello = proc(a, b: int): int {.gcsafe, raises: [], test1.}
diff --git a/tests/macros/tstaticparamsmacro.nim b/tests/macros/tstaticparamsmacro.nim
index 8bd653920..2632ca730 100644
--- a/tests/macros/tstaticparamsmacro.nim
+++ b/tests/macros/tstaticparamsmacro.nim
@@ -7,9 +7,9 @@ numbers
 11
 22
 AST a
-[(11, 22), (33, 44)]
+@[(c: 11, d: 22), (c: 33, d: 44)]
 AST b
-([55, 66], [77, 88])
+(e: @[55, 66], f: @[77, 88])
 55
 10
 20Test
diff --git a/tests/macros/tstructuredlogging.nim b/tests/macros/tstructuredlogging.nim
index 05bb52a40..649c6c0bd 100644
--- a/tests/macros/tstructuredlogging.nim
+++ b/tests/macros/tstructuredlogging.nim
@@ -1,7 +1,7 @@
 discard """
 output: '''
 main started: a=10, b=inner-b, c=10, d=some-d, x=16, z=20
-exiting: a=12, b=overriden-b, c=100, msg=bye bye, x=16
+exiting: a=12, b=overridden-b, c=100, msg=bye bye, x=16
 '''
 """
 
@@ -66,7 +66,7 @@ macro mergeScopes(scopeHolders: typed, newBindings: untyped): untyped =
     newScopeDefinition.add newAssignment(newIdentNode(k), v)
 
   result = quote:
-    template scopeHolder = `newScopeDefinition`
+    template scopeHolder {.redefine.} = `newScopeDefinition`
 
 template scope(newBindings: untyped) {.dirty.} =
   mergeScopes(bindSym"scopeHolder", newBindings)
@@ -134,7 +134,7 @@ scope:
 
 scope:
   x = 16
-  b = "overriden-b"
+  b = "overridden-b"
 
 scope:
   c = 100
diff --git a/tests/macros/ttemplatesymbols.nim b/tests/macros/ttemplatesymbols.nim
index 280b34ff1..3182de79d 100644
--- a/tests/macros/ttemplatesymbols.nim
+++ b/tests/macros/ttemplatesymbols.nim
@@ -148,8 +148,6 @@ proc overloadedProc[T](x: T) =
   echo x
 
 """
-  # XXX: There seems to be a repr rendering problem above.
-  # Notice that `echo [x]`
 
 inspectSymbol overloadedProc[float], """
 proc overloadedProc(x: T) =
diff --git a/tests/macros/ttryparseexpr.nim b/tests/macros/ttryparseexpr.nim
index fc0ee61d0..e6e9e9880 100644
--- a/tests/macros/ttryparseexpr.nim
+++ b/tests/macros/ttryparseexpr.nim
@@ -18,3 +18,7 @@ const
   c = test("\"") # bug #2504
 
 echo a, " ", b
+
+static:
+  # Issue #9918
+  discard parseStmt("echo(1+1);")
diff --git a/tests/macros/ttypenodes.nim b/tests/macros/ttypenodes.nim
new file mode 100644
index 000000000..233ea9780
--- /dev/null
+++ b/tests/macros/ttypenodes.nim
@@ -0,0 +1,16 @@
+import macros
+
+macro makeEnum(): untyped =
+  newTree(nnkEnumTy, newEmptyNode(), ident"a", ident"b", ident"c")
+
+macro makeObject(): untyped =
+  newTree(nnkObjectTy, newEmptyNode(), newEmptyNode(), newTree(nnkRecList,
+    newTree(nnkIdentDefs, ident"x", ident"y", ident"int", newEmptyNode())))
+
+type
+  Foo = makeEnum()
+  Bar = makeObject()
+
+doAssert {a, b, c} is set[Foo]
+let bar = Bar(x: 3, y: 4)
+doAssert (bar.x, bar.y) == (3, 4)
diff --git a/tests/macros/tvtable.nim b/tests/macros/tvtable.nim
index dc07a726b..0f322b7d5 100644
--- a/tests/macros/tvtable.nim
+++ b/tests/macros/tvtable.nim
@@ -18,7 +18,7 @@ type
   # it's also possible to use a strongly typed tuple here
   VTable = array[0..1, pointer]
 
-  TBase = object {.inheritable.}
+  TBase {.inheritable.} = object
     vtbl: ptr VTable
 
   TUserObject1 = object of TBase
diff --git a/tests/magics/trunnableexamples.nim b/tests/magics/trunnableexamples.nim
deleted file mode 100644
index e6b2b70f8..000000000
--- a/tests/magics/trunnableexamples.nim
+++ /dev/null
@@ -1,60 +0,0 @@
-discard """
-cmd: "nim doc $file"
-action: "compile"
-nimout: '''
-foo1
-foo2
-foo3
-foo5
-foo6
-foo7
-foo8
-foo9
-'''
-joinable: false
-"""
-
-proc fun*() =
-  runnableExamples:
-    block: # `defer` only allowed inside a block
-      defer: echo "foo1"
-
-  runnableExamples:
-    # `fun*` only allowed at top level
-    proc fun*()=echo "foo2"
-    fun()
-    block:
-      defer: echo "foo3"
-
-  runnableExamples:
-    # ditto
-    proc fun*()=echo "foo5"
-    fun()
-
-  runnableExamples:
-    # `codeReordering` only allowed at top level
-    {.experimental: "codeReordering".}
-    proc fun1() = fun2()
-    proc fun2() = echo "foo6"
-    fun1()
-
-  runnableExamples:
-    # only works at top level
-    import std/macros
-    macro myImport(a: static string): untyped =
-      newTree(nnkImportStmt, [newLit a])
-    myImport "str" & "utils"
-    doAssert declared(isAlphaAscii)
-    echo "foo7"
-
-# also check for runnableExamples at module scope
-runnableExamples:
-  block:
-    defer: echo "foo8"
-
-runnableExamples:
-  proc fun*()=echo "foo9"
-  fun()
-
-# note: there are yet other examples where putting runnableExamples at module
-# scope is needed, for example when using an `include` before an `import`, etc.
diff --git a/tests/manyloc/argument_parser/argument_parser.nim b/tests/manyloc/argument_parser/argument_parser.nim
index 9cea59477..0ad57167b 100644
--- a/tests/manyloc/argument_parser/argument_parser.nim
+++ b/tests/manyloc/argument_parser/argument_parser.nim
@@ -102,7 +102,7 @@ type
 
 # - Tparam_kind procs
 
-proc `$`*(value: Tparam_kind): string {.procvar.} =
+proc `$`*(value: Tparam_kind): string =
   ## Stringifies the type, used to generate help texts.
   case value:
   of PK_EMPTY: result = ""
@@ -137,7 +137,7 @@ proc new_parameter_specification*(consumes = PK_EMPTY,
 
 # - Tparsed_parameter procs
 
-proc `$`*(data: Tparsed_parameter): string {.procvar.} =
+proc `$`*(data: Tparsed_parameter): string =
   ## Stringifies the value, mostly for debug purposes.
   ##
   ## The proc will display the value followed by non string type in brackets.
@@ -168,14 +168,14 @@ template new_parsed_parameter*(tkind: Tparam_kind, expr): Tparsed_parameter =
   ## initialised with. The template figures out at compile time what field to
   ## assign the variable to, and thus you reduce code clutter and may use this
   ## to initialise single assignments variables in `let` blocks. Example:
-  ##
-  ## .. code-block:: nim
+  ##   ```nim
   ##   let
   ##     parsed_param1 = new_parsed_parameter(PK_FLOAT, 3.41)
   ##     parsed_param2 = new_parsed_parameter(PK_BIGGEST_INT, 2358123 * 23123)
   ##     # The following line doesn't compile due to
   ##     # type mismatch: got <string> but expected 'int'
   ##     #parsed_param3 = new_parsed_parameter(PK_INT, "231")
+  ##   ```
   var result {.gensym.}: Tparsed_parameter
   result.kind = tkind
   when tkind == PK_EMPTY: discard
@@ -225,7 +225,7 @@ template raise_or_quit(exception, message: untyped) =
 
 template run_custom_proc(parsed_parameter: Tparsed_parameter,
     custom_validator: Tparameter_callback,
-    parameter: TaintedString) =
+    parameter: string) =
   ## Runs the custom validator if it is not nil.
   ##
   ## Pass in the string of the parameter triggering the call. If the
@@ -251,8 +251,8 @@ proc parse_parameter(quit_on_failure: bool, param, value: string,
   case param_kind:
   of PK_INT:
     try: result.int_val = value.parseInt
-    except OverflowError:
-      raise_or_quit(OverflowError, ("parameter $1 requires an " &
+    except OverflowDefect:
+      raise_or_quit(OverflowDefect, ("parameter $1 requires an " &
         "integer, but $2 is too large to fit into one") % [param,
         escape(value)])
     except ValueError:
@@ -301,8 +301,7 @@ template build_specification_lookup():
     OrderedTable[string, ptr Tparameter_specification] =
   ## Returns the table used to keep pointers to all of the specifications.
   var result {.gensym.}: OrderedTable[string, ptr Tparameter_specification]
-  result = initOrderedTable[string, ptr Tparameter_specification](
-    tables.rightSize(expected.len))
+  result = initOrderedTable[string, ptr Tparameter_specification](expected.len)
   for i in 0..expected.len-1:
     for param_to_detect in expected[i].names:
       if result.hasKey(param_to_detect):
@@ -319,7 +318,7 @@ proc echo_help*(expected: seq[Tparameter_specification] = @[],
 
 
 proc parse*(expected: seq[Tparameter_specification] = @[],
-    type_of_positional_parameters = PK_STRING, args: seq[TaintedString] = @[],
+    type_of_positional_parameters = PK_STRING, args: seq[string] = @[],
     bad_prefixes = @["-", "--"], end_of_options = "--",
     quit_on_failure = true): Tcommandline_results =
   ## Parses parameters and returns results.
@@ -447,7 +446,7 @@ proc build_help*(expected: seq[Tparameter_specification] = @[],
 
   # First generate the joined version of input parameters in a list.
   var
-    seen = initSet[string]()
+    seen = initHashSet[string]()
     prefixes: seq[string] = @[]
     helps: seq[string] = @[]
   for key in keys:
diff --git a/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim b/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim
index 552b3e756..6eb1b3844 100644
--- a/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim
+++ b/tests/manyloc/keineschweine/dependencies/chipmunk/chipmunk.nim
@@ -106,7 +106,7 @@ type
 
   #/ Collision begin event function callback type.
   #/ Returning false from a begin callback causes the collision to be ignored until
-  #/ the the separate callback is called when the objects stop colliding.
+  #/ the separate callback is called when the objects stop colliding.
   TCollisionBeginFunc* = proc (arb: PArbiter; space: PSpace; data: pointer): bool{.
       cdecl.}
   #/ Collision pre-solve event function callback type.
diff --git a/tests/manyloc/keineschweine/dependencies/enet/enet.nim b/tests/manyloc/keineschweine/dependencies/enet/enet.nim
index 02ebef595..5dee6ae9c 100644
--- a/tests/manyloc/keineschweine/dependencies/enet/enet.nim
+++ b/tests/manyloc/keineschweine/dependencies/enet/enet.nim
@@ -265,7 +265,7 @@ const
   ENET_PEER_RELIABLE_WINDOW_SIZE         = 0x1000
   ENET_PEER_FREE_RELIABLE_WINDOWS        = 8
 
-when defined(Linux) or true:
+when defined(linux) or true:
   import posix
   const
     ENET_SOCKET_NULL*: cint = -1
@@ -295,7 +295,7 @@ when defined(Linux) or true:
   template ENET_SOCKETSET_CHECK*(sockset, socket: untyped): untyped =
     FD_ISSET(socket, addr((sockset)))
 
-when defined(Windows):
+when defined(windows):
   ## put the content of win32.h in here
 
 
diff --git a/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim b/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim
index ad0d20f1c..a0c8a7a3c 100644
--- a/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim
+++ b/tests/manyloc/keineschweine/dependencies/genpacket/streams_enh.nim
@@ -1,7 +1,7 @@
 import streams
 from strutils import repeat
 
-proc readPaddedStr*(s: PStream, length: int, padChar = '\0'): TaintedString =
+proc readPaddedStr*(s: PStream, length: int, padChar = '\0'): string =
   var lastChr = length
   result = s.readStr(length)
   while lastChr >= 0 and result[lastChr - 1] == padChar: dec(lastChr)
@@ -16,7 +16,7 @@ proc writePaddedStr*(s: PStream, str: string, length: int, padChar = '\0') =
   else:
     s.write(str)
 
-proc readLEStr*(s: PStream): TaintedString =
+proc readLEStr*(s: PStream): string =
   var len = s.readInt16()
   result = s.readStr(len)
 
diff --git a/tests/manyloc/keineschweine/dependencies/nake/nake.nim b/tests/manyloc/keineschweine/dependencies/nake/nake.nim
index 83569e30e..36538097e 100644
--- a/tests/manyloc/keineschweine/dependencies/nake/nake.nim
+++ b/tests/manyloc/keineschweine/dependencies/nake/nake.nim
@@ -7,6 +7,10 @@ contents thereof.
 
 As said in the Olde Country, `Keepe it Gangster'."""
 
+#[
+xxx remove this? seems mostly duplicate of: tests/manyloc/nake/nake.nim
+]#
+
 import strutils, parseopt, tables, os
 
 type
@@ -51,7 +55,7 @@ template withDir*(dir: string; body: stmt): stmt =
   cd(curDir)
 
 when true:
-  if not existsFile("nakefile.nim"):
+  if not fileExists("nakefile.nim"):
     echo "No nakefile.nim found. Current working dir is ", getCurrentDir()
     quit 1
   var args = ""
@@ -60,11 +64,12 @@ when true:
     args.add " "
   quit(shell("nim", "c", "-r", "nakefile.nim", args))
 else:
-  addQuitProc(proc() {.noconv.} =
+  import std/exitprocs
+  addExitProc(proc() {.noconv.} =
     var
       task: string
       printTaskList: bool
-    for kind, key, val in getOpt():
+    for kind, key, val in getopt():
       case kind
       of cmdLongOption, cmdShortOption:
         case key.tolower
diff --git a/tests/manyloc/keineschweine/enet_server/enet_server.nim b/tests/manyloc/keineschweine/enet_server/enet_server.nim
index 336e57755..86d0ab360 100644
--- a/tests/manyloc/keineschweine/enet_server/enet_server.nim
+++ b/tests/manyloc/keineschweine/enet_server/enet_server.nim
@@ -113,12 +113,12 @@ when true:
 
   block:
     var zoneCfgFile = "./server_settings.json"
-    for kind, key, val in getOpt():
+    for kind, key, val in getopt():
       case kind
       of cmdShortOption, cmdLongOption:
         case key
         of "f", "file":
-          if existsFile(val):
+          if fileExists(val):
             zoneCfgFile = val
           else:
             echo("File does not exist: ", val)
@@ -136,7 +136,7 @@ when true:
     address.port = port
 
     var path = getAppDir()/../"data"/zoneFile
-    if not existsFile(path):
+    if not fileExists(path):
       echo("Zone settings file does not exist: ../data/", zoneFile)
       echo(path)
       quit(1)
diff --git a/tests/manyloc/keineschweine/enet_server/server_utils.nim b/tests/manyloc/keineschweine/enet_server/server_utils.nim
index 1fb8326ed..3940dcf01 100644
--- a/tests/manyloc/keineschweine/enet_server/server_utils.nim
+++ b/tests/manyloc/keineschweine/enet_server/server_utils.nim
@@ -1,4 +1,6 @@
-import enet, sg_packets, estreams, md5, zlib_helpers, client_helpers, strutils,
+import ../../../../dist/checksums/src/checksums/md5
+
+import enet, sg_packets, estreams, zlib_helpers, client_helpers, strutils,
   idgen, sg_assets, tables, os
 type
   PClient* = ref object
diff --git a/tests/manyloc/keineschweine/keineschweine.nim b/tests/manyloc/keineschweine/keineschweine.nim
index b6fd3cc19..123a4aebb 100644
--- a/tests/manyloc/keineschweine/keineschweine.nim
+++ b/tests/manyloc/keineschweine/keineschweine.nim
@@ -446,7 +446,7 @@ ingameClient.registerHandler(KeyF12, down, proc() = toggleSpec())
 ingameClient.registerHandler(KeyF11, down, toggleShipSelect)
 ingameClient.registerHandler(MouseLeft, down, handleLClick)
 when defined(recordMode):
-  if not existsDir("data/snapshots"):
+  if not dirExists("data/snapshots"):
     createDir("data/snapshots")
   ingameClient.registerHandler(keynum9, down, proc() =
     if not isRecording: startRecording()
@@ -486,7 +486,7 @@ when defined(DebugKeys):
       activeVehicle.body.setPos mouseToSpace())
   ingameClient.registerHandler(KeyY, down, proc() =
     const looloo = ["Asteroid1", "Asteroid2"]
-    addObject(looloo[random(looloo.len)]))
+    addObject(looloo[rand(looloo.len)]))
   ingameClient.registerHandler(KeyO, down, proc() =
     if objects.len == 0:
       echo "Objects is empty"
@@ -691,7 +691,7 @@ when true:
 
   block:
     var bPlayOffline = false
-    for kind, key, val in getOpt():
+    for kind, key, val in getopt():
       case kind
       of cmdArgument:
         if key == "offline": bPlayOffline = true
diff --git a/tests/manyloc/keineschweine/keineschweine.nim.cfg b/tests/manyloc/keineschweine/keineschweine.nim.cfg
index f335a0e0e..a670e2b77 100644
--- a/tests/manyloc/keineschweine/keineschweine.nim.cfg
+++ b/tests/manyloc/keineschweine/keineschweine.nim.cfg
@@ -7,4 +7,4 @@ path = "dependencies/genpacket"
 path = "enet_server"
 debugger = off
 warning[SmallLshouldNotBeUsed] = off
-nilseqs = on
+mm = refc
diff --git a/tests/manyloc/keineschweine/lib/client_helpers.nim b/tests/manyloc/keineschweine/lib/client_helpers.nim
index 0ebb4ade1..b21e67cf7 100644
--- a/tests/manyloc/keineschweine/lib/client_helpers.nim
+++ b/tests/manyloc/keineschweine/lib/client_helpers.nim
@@ -1,6 +1,8 @@
+import ../../../../dist/checksums/src/checksums/md5
+
 import
   tables, sg_packets, enet, estreams, sg_gui, sfml,
-  zlib_helpers, md5, sg_assets, os
+  zlib_helpers, sg_assets, os
 type
   PServer* = ptr TServer
   TServer* = object
@@ -69,7 +71,7 @@ proc updateFileProgress*() =
   downloadProgress.setString($currentFileTransfer.pos & '/' & $currentFileTransfer.fullLen)
 
 ## HFileTransfer
-proc handleFilePartRecv*(serv: PServer; buffer: PBuffer) {.procvar.} =
+proc handleFilePartRecv*(serv: PServer; buffer: PBuffer) =
   var
     f = readScFileTransfer(buffer)
   updateFileProgress()
@@ -103,14 +105,14 @@ proc saveCurrentFile() =
   let
     path = expandPath(currentFileTransfer.assetType, currentFileTransfer.fileName)
     parent = parentDir(path)
-  if not existsDir(parent):
+  if not dirExists(parent):
     createDir(parent)
     echo("Created dir")
   writeFile path, currentFIleTransfer.data
   echo "Write file"
 
 ## HChallengeResult
-proc handleFileChallengeResult*(serv: PServer; buffer: PBuffer) {.procvar.} =
+proc handleFileChallengeResult*(serv: PServer; buffer: PBuffer) =
   var res = readScChallengeResult(buffer).status
   echo "got challnege result: ", res
   if res and currentFileTransfer.readyToSave:
@@ -122,12 +124,12 @@ proc handleFileChallengeResult*(serv: PServer; buffer: PBuffer) {.procvar.} =
     echo "REsetting current file"
 
 ## HFileCHallenge
-proc handleFileChallenge*(serv: PServer; buffer: PBuffer) {.procvar.} =
+proc handleFileChallenge*(serv: PServer; buffer: PBuffer) =
   var
     challenge = readScFileChallenge(buffer)
     path = expandPath(challenge)
     resp: CsFileChallenge
-  if not existsFile(path):
+  if not fileExists(path):
     resp.needFile = true
     echo "Got file challenge, need file."
   else:
diff --git a/tests/manyloc/keineschweine/lib/estreams.nim b/tests/manyloc/keineschweine/lib/estreams.nim
index 5ab029b52..c5e45e0e7 100644
--- a/tests/manyloc/keineschweine/lib/estreams.nim
+++ b/tests/manyloc/keineschweine/lib/estreams.nim
@@ -78,9 +78,9 @@ proc write*(buffer: PBuffer; val: var string) =
   setLen buffer.data, buffer.pos + length.int
   copyMem(addr buffer.data[buffer.pos], addr val[0], length.int)
   inc buffer.pos, length.int
-proc write*[T: SomeNumber|bool|char|byte](buffer: PBuffer; val: T) =
+proc write*[T: SomeNumber|bool|char|byte](buffer: PBuffer; val: sink T) =
   var v: T
-  shallowCopy v, val
+  v = val
   writeBE buffer, v
 
 proc readInt8*(buffer: PBuffer): int8 =
diff --git a/tests/manyloc/keineschweine/lib/glut.nim b/tests/manyloc/keineschweine/lib/glut.nim
index 44a290728..de9a97456 100644
--- a/tests/manyloc/keineschweine/lib/glut.nim
+++ b/tests/manyloc/keineschweine/lib/glut.nim
@@ -93,7 +93,7 @@ const
   GLUT_NORMAL* = 0
   GLUT_OVERLAY* = 1
 
-when defined(Windows):
+when defined(windows):
   const                       # Stroke font constants (use these in GLUT program).
     GLUT_STROKE_ROMAN* = cast[Pointer](0)
     GLUT_STROKE_MONO_ROMAN* = cast[Pointer](1) # Bitmap font constants (use these in GLUT program).
diff --git a/tests/manyloc/keineschweine/lib/sg_assets.nim b/tests/manyloc/keineschweine/lib/sg_assets.nim
index 7caa9c3fb..96c962dc3 100644
--- a/tests/manyloc/keineschweine/lib/sg_assets.nim
+++ b/tests/manyloc/keineschweine/lib/sg_assets.nim
@@ -1,6 +1,8 @@
+import ../../../../dist/checksums/src/checksums/md5
+
 import
   re, json, strutils, tables, math, os, math_helpers,
-  sg_packets, md5, zlib_helpers
+  sg_packets, zlib_helpers
 
 when defined(NoSFML):
   import server_utils
@@ -221,7 +223,7 @@ template cacheImpl(procName, cacheName, resultType, body: untyped) {.dirty.} =
     cacheName[filename] = result
 
 template checkFile(path: untyped) {.dirty.} =
-  if not existsFile(path):
+  if not fileExists(path):
     errors.add("File missing: " & path)
 
 cacheImpl newSprite, SpriteSheets, PSpriteSheet:
@@ -322,7 +324,7 @@ proc validateSettings*(settings: JsonNode, errors: var seq[string]): bool =
         inc id
 
 proc loadSettingsFromFile*(filename: string, errors: var seq[string]): bool =
-  if not existsFile(filename):
+  if not fileExists(filename):
     errors.add("File does not exist: "&filename)
   else:
     result = loadSettings(readFile(filename), errors)
diff --git a/tests/manyloc/keineschweine/lib/sg_gui.nim b/tests/manyloc/keineschweine/lib/sg_gui.nim
index 83ad0d1bf..bcf415556 100644
--- a/tests/manyloc/keineschweine/lib/sg_gui.nim
+++ b/tests/manyloc/keineschweine/lib/sg_gui.nim
@@ -193,28 +193,28 @@ proc setActive*(t: PTextEntry) =
   if not t.isNil and not t.inputClient.isNil:
     input_helpers.setActive(t.inputClient)
 
+when false:
+  proc newMessageArea*(container: PGuiContainer; position: TVector2f): PMessageArea =
+    new(result)
+    result.messages = @[]
+    result.pos = position
+    container.add(result)
+  proc add*(m: PMessageArea, text: string): PText =
+    result = messageProto.copy()
+    result.setString(text)
+    m.messages.add(result)
+    let nmsgs = len(m.messages)
+    var pos   = vec2f(m.pos.x, m.pos.y)
+    for i in countdown(nmsgs - 1, max(nmsgs - 30, 0)):
+      setPosition(m.messages[i], pos)
+      pos.y -= 16.0
 
-discard """proc newMessageArea*(container: PGuiContainer; position: TVector2f): PMessageArea =
-  new(result)
-  result.messages = @[]
-  result.pos = position
-  container.add(result)
-proc add*(m: PMessageArea, text: string): PText =
-  result = messageProto.copy()
-  result.setString(text)
-  m.messages.add(result)
-  let nmsgs = len(m.messages)
-  var pos   = vec2f(m.pos.x, m.pos.y)
-  for i in countdown(nmsgs - 1, max(nmsgs - 30, 0)):
-    setPosition(m.messages[i], pos)
-    pos.y -= 16.0
+  proc draw*(window: PRenderWindow; m: PMessageArea) =
+    let nmsgs = len(m.messages)
+    if nmsgs == 0: return
+    for i in countdown(nmsgs - 1, max(nmsgs - 30, 0)):
+      window.draw(m.messages[i])
 
-proc draw*(window: PRenderWindow; m: PMessageArea) =
-  let nmsgs = len(m.messages)
-  if nmsgs == 0: return
-  for i in countdown(nmsgs - 1, max(nmsgs - 30, 0)):
-    window.draw(m.messages[i])
-"""
 proc newMessageArea*(container: PGuiContainer; position: TVector2f): PMessageArea =
   new(result)
   result.messages = @[]
diff --git a/tests/manyloc/keineschweine/lib/sg_packets.nim b/tests/manyloc/keineschweine/lib/sg_packets.nim
index 0727c699a..797a60706 100644
--- a/tests/manyloc/keineschweine/lib/sg_packets.nim
+++ b/tests/manyloc/keineschweine/lib/sg_packets.nim
@@ -1,4 +1,6 @@
-import genpacket_enet, nativesockets, net, md5, enet
+import ../../../../dist/checksums/src/checksums/md5
+
+import genpacket_enet, nativesockets, net, enet
 defPacketImports()
 
 type
diff --git a/tests/manyloc/keineschweine/lib/zlib_helpers.nim b/tests/manyloc/keineschweine/lib/zlib_helpers.nim
index 895f41759..e51c000c8 100644
--- a/tests/manyloc/keineschweine/lib/zlib_helpers.nim
+++ b/tests/manyloc/keineschweine/lib/zlib_helpers.nim
@@ -1,21 +1,26 @@
+# xxx this test is bad (echo instead of error, etc)
+
 import zip/zlib
 
 proc compress*(source: string): string =
   var
     sourcelen = source.len
-    destlen = sourcelen + (sourcelen.float * 0.1).int + 16
+    destLen = sourcelen + (sourcelen.float * 0.1).int + 16
   result = ""
   result.setLen destLen
-  var res = zlib.compress(cstring(result), addr destLen, cstring(source), sourceLen)
+  # see http://www.zlib.net/zlib-1.2.11.tar.gz for correct definitions
+  var destLen2 = destLen.Ulongf
+  var res = zlib.compress(cstring(result), addr destLen2, cstring(source), sourceLen.Ulong)
   if res != Z_OK:
     echo "Error occurred: ", res
-  elif destLen < result.len:
-    result.setLen(destLen)
+  elif destLen2.int < result.len:
+    result.setLen(destLen2.int)
 
 proc uncompress*(source: string, destLen: var int): string =
   result = ""
   result.setLen destLen
-  var res = zlib.uncompress(cstring(result), addr destLen, cstring(source), source.len)
+  var destLen2 = destLen.Ulongf
+  var res = zlib.uncompress(cstring(result), addr destLen2, cstring(source), source.len.Ulong)
   if res != Z_OK:
     echo "Error occurred: ", res
 
diff --git a/tests/manyloc/keineschweine/server/old_dirserver.nim b/tests/manyloc/keineschweine/server/old_dirserver.nim
index 390b738aa..a63829691 100644
--- a/tests/manyloc/keineschweine/server/old_dirserver.nim
+++ b/tests/manyloc/keineschweine/server/old_dirserver.nim
@@ -1,9 +1,9 @@
 ## directory server
 ## handles client authorization and assets
-
+import ../../../dist/checksums/src/checksums/md5
 import
   sockets, times, streams, streams_enh, tables, json, os,
-  sg_packets, sg_assets, md5, server_utils, map_filter
+  sg_packets, sg_assets, server_utils, map_filter
 type
   THandler = proc(client: PCLient; stream: PStream)
 var
@@ -159,12 +159,12 @@ proc poll*(timeout: int = 250) =
 when true:
   import parseopt, strutils
   var cfgFile = "dirserver_settings.json"
-  for kind, key, val in getOpt():
+  for kind, key, val in getopt():
     case kind
     of cmdShortOption, cmdLongOption:
       case key
       of "f", "file":
-        if existsFile(val):
+        if fileExists(val):
           cfgFile = val
         else:
           echo("File does not exist: ", val)
diff --git a/tests/manyloc/keineschweine/server/old_server_utils.nim b/tests/manyloc/keineschweine/server/old_server_utils.nim
index 3da6e078c..f389c0836 100644
--- a/tests/manyloc/keineschweine/server/old_server_utils.nim
+++ b/tests/manyloc/keineschweine/server/old_server_utils.nim
@@ -1,5 +1,7 @@
+import ../../../dist/checksums/src/checksums/md5
+
 import
-  streams, md5, sockets,
+  streams, sockets,
   sg_packets, zlib_helpers, idgen
 type
   TClientType* = enum
diff --git a/tests/manyloc/keineschweine/server/old_sg_server.nim b/tests/manyloc/keineschweine/server/old_sg_server.nim
index 473880e2b..d6fbbe99e 100644
--- a/tests/manyloc/keineschweine/server/old_sg_server.nim
+++ b/tests/manyloc/keineschweine/server/old_sg_server.nim
@@ -144,12 +144,12 @@ proc poll*(timeout: int = 250) =
 when true:
   import parseopt, strutils
   var zoneCfgFile = "./server_settings.json"
-  for kind, key, val in getOpt():
+  for kind, key, val in getopt():
     case kind
     of cmdShortOption, cmdLongOption:
       case key
       of "f", "file":
-        if existsFile(val):
+        if fileExists(val):
           zoneCfgFile = val
         else:
           echo("File does not exist: ", val)
@@ -165,7 +165,7 @@ when true:
     dirServerInfo = jsonSettings["dirserver"]
 
   var path = getAppDir()/../"data"/zoneFile
-  if not existsFile(path):
+  if not fileExists(path):
     echo("Zone settings file does not exist: ../data/", zoneFile)
     echo(path)
     quit(1)
diff --git a/tests/manyloc/keineschweine/server/sg_lobby.nim b/tests/manyloc/keineschweine/server/sg_lobby.nim
index d7e01e6e6..04ce10f08 100644
--- a/tests/manyloc/keineschweine/server/sg_lobby.nim
+++ b/tests/manyloc/keineschweine/server/sg_lobby.nim
@@ -1,6 +1,7 @@
+import ../../../dist/checksums/src/checksums/md5
 
 import
-  sockets, streams, tables, times, math, strutils, json, os, md5,
+  sockets, streams, tables, times, math, strutils, json, os,
   sfml, sfml_vector, sfml_colors,
   streams_enh, input_helpers, zlib_helpers, client_helpers, sg_packets, sg_assets, sg_gui
 type
diff --git a/tests/manyloc/nake/nake.nim b/tests/manyloc/nake/nake.nim
index ebcf21d19..5d3173a20 100644
--- a/tests/manyloc/nake/nake.nim
+++ b/tests/manyloc/nake/nake.nim
@@ -51,7 +51,7 @@ template withDir*(dir: string; body: untyped) =
   cd(curDir)
 
 when true:
-  if not existsFile("nakefile.nim"):
+  if not fileExists("nakefile.nim"):
     echo "No nakefile.nim found. Current working dir is ", getCurrentDir()
     quit 1
   var args = ""
@@ -60,11 +60,12 @@ when true:
     args.add " "
   quit(shell("nim", "c", "-r", "nakefile.nim", args))
 else:
-  addQuitProc(proc() {.noconv.} =
+  import std/exitprocs
+  addExitProc(proc() {.noconv.} =
     var
       task: string
       printTaskList: bool
-    for kind, key, val in getOpt():
+    for kind, key, val in getopt():
       case kind
       of cmdLongOption, cmdShortOption:
         case key.tolowerAscii
diff --git a/tests/manyloc/nake/nakefile.nim b/tests/manyloc/nake/nakefile.nim
index 35ed3cbb0..fc479a5c2 100644
--- a/tests/manyloc/nake/nakefile.nim
+++ b/tests/manyloc/nake/nakefile.nim
@@ -29,11 +29,12 @@ task "test2", "Build release test build test release build":
   if shell("nim", ReleaseDefines, ReleaseTestDefines, "compile", ExeName) == 0:
     shell "."/ExeName
 
-discard """task "dirserver", "build the directory server":
-  withDir "server":
-    if shell("nim", ServerDefines, "compile", "dirserver") != 0:
-      echo "Failed to build the dirserver"
-      quit 1"""
+when false:
+  task "dirserver", "build the directory server":
+    withDir "server":
+      if shell("nim", ServerDefines, "compile", "dirserver") != 0:
+        echo "Failed to build the dirserver"
+        quit 1
 
 task "zoneserver", "build the zone server":
   withDir "enet_server":
@@ -63,7 +64,7 @@ task "release", "release build":
     ## zip up all the files and such or something useful here
 
 task "testskel", "create skeleton test dir for testing":
-  let dirname = "test-"& $random(5000)
+  let dirname = "test-" & $rand(5000)
   removeDir dirName
   createDir dirName/"data/fnt"
   copyFile "data/fnt/LiberationMono-Regular", dirName/"data/fnt/LiberationMono-Regular.ttf"
@@ -77,7 +78,7 @@ task "testskel", "create skeleton test dir for testing":
 task "clean", "cleanup generated files":
   var dirs = @["nimcache", "server"/"nimcache"]
   dirs.apply(proc(x: var string) =
-    if existsDir(x): removeDir(x))
+    if dirExists(x): removeDir(x))
 
 task "download", "download game assets":
   var
@@ -86,7 +87,7 @@ task "download", "download game assets":
     client = newHttpClient()
   path.add DirSep
   path.add(extractFilename(GameAssets))
-  if existsFile(path):
+  if fileExists(path):
     echo "The file already exists\n",
       "[R]emove  [M]ove  [Q]uit  [S]kip    Source: ", GameAssets
     case stdin.readLine.toLowerAscii
@@ -133,7 +134,7 @@ task "download", "download game assets":
   else:  ## this crashes, dunno why
     var
       z: TZipArchive
-      destDir = getCurrentDir()/("unzip"& $random(5000))
+      destDir = getCurrentDir()/("unzip" & $rand(5000))
     if not z.open(path, fmRead):
       echo "Could not open zip, bad download?"
       return
diff --git a/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/gl.nim b/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/gl.nim
index 7d787c07b..29e23f9d0 100644
--- a/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/gl.nim
+++ b/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/gl.nim
@@ -53,7 +53,7 @@ else:
   const
     glRealType* = cGLfloat
 
-proc setUniformV4*[T](loc: GLint, vecs: var openarray[TV4[T]]) =
+proc setUniformV4*[T](loc: GLint, vecs: var openArray[TV4[T]]) =
   glUniform4fv(loc, vecs.len.GLsizei, cast[ptr GLfloat](vecs[0].addr))
 
 proc setUniformV4*[T](loc: GLint, vec: TV4[T]) =
diff --git a/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/primitive.nim b/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/primitive.nim
index 3bfaf1cbc..accc2d96b 100644
--- a/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/primitive.nim
+++ b/tests/manyloc/named_argument_bug/tri_engine/gfx/gl/primitive.nim
@@ -47,7 +47,7 @@ proc newVert*(rect: rect.TRect): seq[TVert] =
 proc newVertAttrib(i: GLuint, size: GLint, stride: GLsizei, offset: GLvoid): TVertAttrib =
   TVertAttrib(i: i, size: size, stride: stride, offset: offset)
 
-proc genBuf*[T](vboTarget, objUsage: GLenum, data: var openarray[T]): GLuint =
+proc genBuf*[T](vboTarget, objUsage: GLenum, data: var openArray[T]): GLuint =
   result = 0.GLuint
   ?glGenBuffers(1, result.addr)
   ?glBindBuffer(vboTarget, result)
diff --git a/tests/manyloc/standalone/panicoverride.nim b/tests/manyloc/standalone/panicoverride.nim
index d9b3f4388..c0b8bb030 100644
--- a/tests/manyloc/standalone/panicoverride.nim
+++ b/tests/manyloc/standalone/panicoverride.nim
@@ -11,9 +11,4 @@ proc panic(s: string) {.noreturn.} =
   rawoutput(s)
   exit(1)
 
-# Alternatively we also could implement these 2 here:
-#
-# proc sysFatal(exceptn: typeDesc, message: string) {.noReturn.}
-# proc sysFatal(exceptn: typeDesc, message, arg: string) {.noReturn.}
-
 {.pop.}
diff --git a/tests/manyloc/standalone2/panicoverride.nim b/tests/manyloc/standalone2/panicoverride.nim
new file mode 100644
index 000000000..c0b8bb030
--- /dev/null
+++ b/tests/manyloc/standalone2/panicoverride.nim
@@ -0,0 +1,14 @@
+
+proc printf(frmt: cstring) {.varargs, importc, header: "<stdio.h>", cdecl.}
+proc exit(code: int) {.importc, header: "<stdlib.h>", cdecl.}
+
+{.push stack_trace: off, profiler:off.}
+
+proc rawoutput(s: string) =
+  printf("%s\n", s)
+
+proc panic(s: string) {.noreturn.} =
+  rawoutput(s)
+  exit(1)
+
+{.pop.}
diff --git a/tests/manyloc/standalone2/tavr.nim b/tests/manyloc/standalone2/tavr.nim
new file mode 100644
index 000000000..6cbc5c699
--- /dev/null
+++ b/tests/manyloc/standalone2/tavr.nim
@@ -0,0 +1,7 @@
+# bug #16404
+
+proc printf(frmt: cstring) {.varargs, header: "<stdio.h>", cdecl.}
+
+var x = 0
+inc x
+printf("hi %ld\n", x+4777)
diff --git a/tests/manyloc/standalone2/tavr.nim.cfg b/tests/manyloc/standalone2/tavr.nim.cfg
new file mode 100644
index 000000000..2a31618d0
--- /dev/null
+++ b/tests/manyloc/standalone2/tavr.nim.cfg
@@ -0,0 +1,5 @@
+--gc:arc
+--cpu:avr
+--os:standalone
+--compileOnly
+--threads:off
diff --git a/tests/metatype/tcompositetypeclasses.nim b/tests/metatype/tcompositetypeclasses.nim
index d125b119b..43b6a57e4 100644
--- a/tests/metatype/tcompositetypeclasses.nim
+++ b/tests/metatype/tcompositetypeclasses.nim
@@ -30,7 +30,7 @@ accept bar(vbar)
 accept baz(vbar)
 accept baz(vbaz)
 
-#reject baz(vnotbaz) # XXX this really shouldn't compile
+reject baz(vnotbaz)
 reject bar(vfoo)
 
 # https://github.com/Araq/Nim/issues/517
diff --git a/tests/metatype/tcps.nim b/tests/metatype/tcps.nim
new file mode 100644
index 000000000..042e32bd6
--- /dev/null
+++ b/tests/metatype/tcps.nim
@@ -0,0 +1,35 @@
+discard """
+  output: '''10
+string'''
+"""
+
+# bug #18059
+type
+  C = ref object of RootObj
+    fn: ContProc
+    ex: ref Exception
+
+  ContProc = proc (c: C): C {.nimcall.}
+
+proc noop(c: C): C = c
+
+type
+  Env[T] = ref object of C
+    x: T
+
+proc foo_cont[U](c: C): C =
+  proc afterCall[V](c: C): C =
+    echo Env[V](c).x
+
+  c.fn = afterCall[U]
+  return noop(c)
+
+proc foo[T](x: T): C =
+  return Env[T](fn: foo_cont[T], x: x)
+
+proc tramp(c: sink C) =
+  while c != nil and c.fn != nil:
+    c = c.fn(c)
+
+tramp foo(10)
+tramp foo("string")
diff --git a/tests/metatype/tmatrix3.nim b/tests/metatype/tmatrix3.nim
index a143e2bc9..28e85fcee 100644
--- a/tests/metatype/tmatrix3.nim
+++ b/tests/metatype/tmatrix3.nim
@@ -1,5 +1,5 @@
 discard """
-  output: ""
+  output: "\n"
 """
 
 type Matrix[M,N: static[int]] = array[M, array[N, float]]
diff --git a/tests/metatype/tmetatype_issues.nim b/tests/metatype/tmetatype_issues.nim
index 21c5c02f1..d33d8dd31 100644
--- a/tests/metatype/tmetatype_issues.nim
+++ b/tests/metatype/tmetatype_issues.nim
@@ -157,3 +157,12 @@ block t3338:
   var t2 = Bar[int32]()
   t2.add()
   doAssert t2.x == 5
+
+block: # issue #24203
+  proc b(G: typedesc) =
+    type U = G
+  template s(h: untyped) = h
+  s(b(typeof (0, 0)))
+  b(seq[int])
+  b((int, int))
+  b(typeof (0, 0))
diff --git a/tests/metatype/tmetatype_various.nim b/tests/metatype/tmetatype_various.nim
index a56eca018..45c74432d 100644
--- a/tests/metatype/tmetatype_various.nim
+++ b/tests/metatype/tmetatype_various.nim
@@ -1,4 +1,7 @@
-
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  output: '''[1, 0, 0, 0, 0, 0, 0, 0] CTBool[Ct[system.uint32]]'''
+"""
 
 block tconstraints:
   proc myGenericProc[T: object|tuple|int|ptr|ref|distinct](x: T): string =
@@ -37,13 +40,34 @@ block tfieldaccessor:
 block tprocbothmeta:
   proc myFun[A](x: A): auto =
     result = float(x+10)
-  
+
   proc myMap[T,S](sIn: seq[T], f: proc (q: T): S): seq[S] =
     result = newSeq[S](sIn.len)
     for i in 0..<sIn.len:
       result[i] = f(sIn[i])
-  
+
   assert myMap(@[1,2,3], myFun) == @[11.0, 12.0, 13.0]
 
 
+# https://github.com/nim-lang/Nim/issues/13646
+
+type
+  BaseUint* = SomeUnsignedInt or byte
+  Ct*[T] = distinct T
+    ## Constant-Time wrapper
+    ## Only constant-time operations in particular the ternary operator equivalent
+    ##   condition: if true: a else: b
+    ## are allowed
+
+  CTBool*[T] = distinct range[T(0)..T(1)]
+    ## Constant-Time boolean wrapper
+
+var x: array[8, CTBool[Ct[uint32]]]
+x[0] = (CTBool[Ct[uint32]])(1)
+echo x.repr, " ", typeof(x[0])
+
+block: # bug #23139
+  type Foo = enum a, b
 
+  var x: range[a..b]
+  doAssert (repr x) == "a"
diff --git a/tests/metatype/tshacontext.nim b/tests/metatype/tshacontext.nim
new file mode 100644
index 000000000..7f649d202
--- /dev/null
+++ b/tests/metatype/tshacontext.nim
@@ -0,0 +1,44 @@
+
+# bug #14136
+
+type
+  MDigest*[bits: static[int]] = object
+    ## Message digest type
+    data*: array[bits div 8, byte]
+
+  Sha2Context*[bits: static[int],
+               bsize: static[int],
+               T: uint32|uint64] = object
+    count: array[2, T]
+    state: array[8, T]
+    buffer: array[bsize, byte]
+
+  sha256* = Sha2Context[256, 64, uint32]
+
+template hmacSizeBlock*(h: typedesc): int =
+  when (h is Sha2Context):
+    int(h.bsize)
+  else:
+    {.fatal: "Choosen hash primitive is not yet supported!".}
+
+type
+  HMAC*[HashType] = object
+    ## HMAC context object.
+    mdctx: HashType
+    opadctx: HashType
+    ipad: array[HashType.hmacSizeBlock, byte]
+    opad: array[HashType.hmacSizeBlock, byte]
+
+func hkdfExtract*[T;S,I: char|byte](ctx: var HMAC[T],
+                     prk: var MDigest[T.bits], # <------- error here "Error: type expected"
+                     salt: openArray[S],
+                     ikm: openArray[I]
+                    ) =
+  discard
+
+var ctx: HMAC[sha256]
+var prk: MDigest[sha256.bits]
+let salt = [byte 0x00, 0x01, 0x02]
+let ikm = "CompletelyRandomInput"
+
+ctx.hkdfExtract(prk, salt, ikm)
diff --git a/tests/metatype/tstatic_generic_typeclass.nim b/tests/metatype/tstatic_generic_typeclass.nim
new file mode 100644
index 000000000..0e9256a62
--- /dev/null
+++ b/tests/metatype/tstatic_generic_typeclass.nim
@@ -0,0 +1,30 @@
+type MyThing[T: static int] = object
+  when T == 300:
+    a: int
+
+var a = MyThing[300]()
+proc doThing(myThing: MyThing): string = $myThing
+proc doOtherThing[T](myThing: MyThing[T]): string = $myThing
+assert doThing(a) == $a
+assert doThing(MyThing[0]()) == $MyThing[0]()
+assert doOtherThing(a) == "(a: 0)"
+
+type
+  Backend* = enum
+    Cpu,
+    Cuda
+
+  Tensor*[B: static[Backend]; T] = object
+    shape: seq[int]
+    strides: seq[int]
+    offset: int
+    when B == Backend.Cpu:
+      data: seq[T]
+    else:
+      data_ptr: ptr T
+
+template shape*(t: Tensor): seq[int] =
+  t.shape
+
+
+assert Tensor[Cpu, int]().shape == @[]
diff --git a/tests/metatype/tstaticparammacro.nim b/tests/metatype/tstaticparammacro.nim
index 16a6e56b8..bcf28d331 100644
--- a/tests/metatype/tstaticparammacro.nim
+++ b/tests/metatype/tstaticparammacro.nim
@@ -6,9 +6,9 @@ numbers
 11
 22
 AST a
-[(11, 22), (33, 44)]
+@[(c: 11, d: 22), (c: 33, d: 44)]
 AST b
-([55, 66], [77, 88])
+(e: @[55, 66], f: @[77, 88])
 55
 10
 20Test
diff --git a/tests/metatype/tstaticparams.nim b/tests/metatype/tstaticparams.nim
index 09d505f94..de80d46ae 100644
--- a/tests/metatype/tstaticparams.nim
+++ b/tests/metatype/tstaticparams.nim
@@ -171,3 +171,27 @@ echo inSize([
   [1, 2, 3],
   [4, 5, 6]
 ])
+
+block: # #12864
+  template fun() =
+    type Object = object
+    proc fun(f: Object): int = 1
+    proc fun(f: static[int]): int = 2
+    doAssert fun(Object()) == 1
+
+    var a: Object
+    doAssert fun(a) == 1
+
+    proc fun2(f: Object): int = 1
+    proc fun2(f: static[Object]): int = 2
+    doAssert fun2(Object()) == 2
+    doAssert fun2(a) == 1
+    const a2 = Object()
+    doAssert fun2(a2) == 2
+
+  fun()
+  static: fun()
+
+when true: #12864 original snippet
+  import times
+  discard times.format(initDateTime(30, mMar, 2017, 0, 0, 0, 0, utc()), TimeFormat())
diff --git a/tests/metatype/tstaticvector.nim b/tests/metatype/tstaticvector.nim
index ca16518fe..85a66974b 100644
--- a/tests/metatype/tstaticvector.nim
+++ b/tests/metatype/tstaticvector.nim
@@ -1,9 +1,10 @@
 discard """
+  matrix: "--mm:orc"
   output: '''0
 0
 2
 100
-30.0 [data = [2.0]]
+30.0 TVec[1, system.float32](data: [2.0])
 '''
 """
 
diff --git a/tests/metatype/ttensor.nim b/tests/metatype/ttensor.nim
index f2f24ba8c..89a0bf007 100644
--- a/tests/metatype/ttensor.nim
+++ b/tests/metatype/ttensor.nim
@@ -1,13 +1,11 @@
 discard """
-  output: '''before tensor2:
+  output: '''
+before tensor2:
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0]
-
 before tensor3:
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0]
-
 after tensor3:
 [0.0, 1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 14.0, 15.0, 16.0, 17.0, 18.0, 19.0, 20.0, 21.0, 22.0, 23.0, 24.0, 25.0, 26.0]
-
 a3:
 [1000.0, 1001.0, 1002.0, 1003.0, 1004.0, 1005.0, 1006.0, 1007.0, 1008.0, 1009.0, 1010.0, 1011.0, 1012.0, 1013.0, 1014.0, 1015.0, 1016.0, 1017.0, 1018.0, 1019.0, 1020.0, 1021.0, 1022.0, 1023.0, 1024.0, 1025.0, 1026.0]'''
 """
diff --git a/tests/metatype/ttypedesc1.nim b/tests/metatype/ttypedesc1.nim
index 837c8eccc..549dbc62a 100644
--- a/tests/metatype/ttypedesc1.nim
+++ b/tests/metatype/ttypedesc1.nim
@@ -60,3 +60,9 @@ reject:
 reject:
   foo seq[int], ss
 
+# issue #12398
+reject:
+  let xs = [int, float, string]
+
+reject:
+  let data = @[int, typedesc]
diff --git a/tests/metatype/ttypedesc2.nim b/tests/metatype/ttypedesc2.nim
index 89c38f367..96dab9052 100644
--- a/tests/metatype/ttypedesc2.nim
+++ b/tests/metatype/ttypedesc2.nim
@@ -35,9 +35,23 @@ type Point[T] = tuple[x, y: T]
 proc origin(T: typedesc): Point[T] = discard
 discard origin(int)
 
+block: # issue #12704
+  const a = $("a", "b")
+  proc fun() =
+    const str = $int
+    let b = $(str, "asdf")
+  fun()
+
 # https://github.com/nim-lang/Nim/issues/7516
 import typetraits
 
+block: #issue #12704
+  const a = $("a", "b")
+  proc fun() =
+    const str = name(int)
+    let b = $(str, "asdf")
+  fun()
+
 proc hasDefault1(T: type = int): auto = return T.name
 doAssert hasDefault1(int) == "int"
 doAssert hasDefault1(string) == "string"
diff --git a/tests/metatype/ttypedesc3.nim b/tests/metatype/ttypedesc3.nim
index ff6e22718..d3a58853d 100644
--- a/tests/metatype/ttypedesc3.nim
+++ b/tests/metatype/ttypedesc3.nim
@@ -1,11 +1,14 @@
 discard """
-output: '''
+  matrix: "--mm:arc; --mm:refc"
+  output: '''
 proc Base
 proc Child
 method Base
+method Child
 yield Base
 yield Child
 12
+1
 '''
 """
 
@@ -23,8 +26,7 @@ Base.pr
 Child.pr
 
 Base.me
-when false:
-  Child.me #<- bug #2710
+Child.me #<- bug #2710
 
 for s in Base.it: echo s
 for s in Child.it: echo s #<- bug #2662
@@ -41,3 +43,11 @@ type
   MyRefType = ref MyType
 
 echo sizeof(default(MyRefType)[])
+
+type
+  Foo[T] = object
+    val: T
+
+var x: Foo[int].val
+inc(x)
+echo x
diff --git a/tests/metatype/ttypedescnotnimnode.nim b/tests/metatype/ttypedescnotnimnode.nim
new file mode 100644
index 000000000..52a04815b
--- /dev/null
+++ b/tests/metatype/ttypedescnotnimnode.nim
@@ -0,0 +1,21 @@
+discard """
+  errormsg: "type mismatch: got <NimNode> but expected 'typedesc'"
+  line: 14
+"""
+
+import macros
+
+# This is the same example as ttypeselectors but using a proc instead of a macro
+# Instead of type mismatch for macro, proc just failed with internal error: getTypeDescAux(tyNone)
+# https://github.com/nim-lang/Nim/issues/7231
+
+proc getBase2*(bits: static[int]): typedesc =
+  if bits == 128:
+    result = newTree(nnkBracketExpr, ident("MpUintBase"), ident("uint64"))
+  else:
+    result = newTree(nnkBracketExpr, ident("MpUintBase"), ident("uint32"))
+
+type
+  MpUint2*[bits: static[int]] = getbase2(bits)
+# technically shouldn't error until instantiation, so instantiate it
+var x: MpUint2[123]
diff --git a/tests/metatype/ttypeselectors.nim b/tests/metatype/ttypeselectors.nim
index 5385a1be9..d0843511d 100644
--- a/tests/metatype/ttypeselectors.nim
+++ b/tests/metatype/ttypeselectors.nim
@@ -98,16 +98,3 @@ var c: Bar[32]
 echo sizeof(a)
 echo sizeof(b)
 echo sizeof(c)
-
-# This is the same example but using a proc instead of a macro
-# Instead of type mismatch for macro, proc just failed with internal error: getTypeDescAux(tyNone)
-# https://github.com/nim-lang/Nim/issues/7231
-
-proc getBase2*(bits: static[int]): typedesc =
-  if bits == 128:
-    result = newTree(nnkBracketExpr, ident("MpUintBase"), ident("uint64"))
-  else:
-    result = newTree(nnkBracketExpr, ident("MpUintBase"), ident("uint32"))
-
-type
-  MpUint2*[bits: static[int]] = getbase2(bits)
diff --git a/tests/metatype/ttypetraits.nim b/tests/metatype/ttypetraits.nim
index dfd22b418..0523390a7 100644
--- a/tests/metatype/ttypetraits.nim
+++ b/tests/metatype/ttypetraits.nim
@@ -1,11 +1,28 @@
 import typetraits
 import macros
 
+block: # toUnsigned, toSigned
+  var a1: toSigned(int16)
+  doAssert a1 is int16
+  var a2: toSigned(uint16)
+  doAssert $a2.typeof == "int16"
+  doAssert toSigned(uint32) is int32
+  doAssert uint64.toSigned is int64
+  doAssert int64.toSigned is int64
+  doAssert int64.toUnsigned is uint64
+  doAssert int.toUnsigned is uint
+  doAssert $uint.toUnsigned == "uint"
+  # disallowed for now
+  doAssert not compiles(toUnsigned(range[0..7]))
+  doAssert not compiles(toSigned(range[0..7]))
+
 block: # isNamedTuple
   type Foo1 = (a:1,).type
   type Foo2 = (Field0:1,).type
   type Foo3 = ().type
   type Foo4 = object
+  type Foo5[T] = tuple[x:int, y: T]
+  type Foo6[T] = (T,)
 
   doAssert (a:1,).type.isNamedTuple
   doAssert Foo1.isNamedTuple
@@ -14,6 +31,9 @@ block: # isNamedTuple
   doAssert not Foo3.isNamedTuple
   doAssert not Foo4.isNamedTuple
   doAssert not (1,).type.isNamedTuple
+  doAssert isNamedTuple(Foo5[int8])
+  doAssert not isNamedTuple(Foo5)
+  doAssert not isNamedTuple(Foo6[int8])
 
 proc typeToString*(t: typedesc, prefer = "preferTypeName"): string {.magic: "TypeTrait".}
   ## Returns the name of the given type, with more flexibility than `name`,
@@ -21,6 +41,35 @@ proc typeToString*(t: typedesc, prefer = "preferTypeName"): string {.magic: "Typ
   ## prefer = "preferResolved" will resolve type aliases recursively.
   # Move to typetraits.nim once api stabilized.
 
+block: # name, `$`
+  static:
+    doAssert $type(42) == "int"
+    doAssert int.name == "int"
+
+  const a1 = name(int)
+  const a2 = $(int)
+  const a3 = $int
+  doAssert a1 == "int"
+  doAssert a2 == "int"
+  doAssert a3 == "int"
+
+  proc fun[T: typedesc](t: T) =
+    const a1 = name(t)
+    const a2 = $(t)
+    const a3 = $t
+    doAssert a1 == "int"
+    doAssert a2 == "int"
+    doAssert a3 == "int"
+  fun(int)
+
+  doAssert $(int,) == "(int,)"
+  doAssert $(1,) == "(1,)" # just for comparison to make sure it has same structure
+  doAssert $tuple[] == "tuple[]"
+  doAssert $(int,) == "(int,)"
+  doAssert $(int, float) == "(int, float)"
+  doAssert $((int), tuple[], tuple[a: uint], tuple[a: uint, b: float], (int,), (int, float)) ==
+    "(int, tuple[], tuple[a: uint], tuple[a: uint, b: float], (int,), (int, float))"
+
 block: # typeToString
   type MyInt = int
   type
@@ -42,7 +91,13 @@ block: # typeToString
   doAssert MyInt.name3 == "MyInt{int}"
   doAssert (tuple[a: MyInt, b: float]).name3 == "tuple[a: MyInt{int}, b: float]"
   doAssert (tuple[a: C2b[MyInt, C4[cstring]], b: cint, c: float]).name3 ==
-    "tuple[a: C2b{C}[MyInt{int}, C4[cstring]], b: cint{int32}, c: float]"
+    "tuple[a: C[MyInt{int}, C4[cstring]], b: cint{int32}, c: float]"
+
+  macro fn(): string =
+    # not 100% sure whether this should even compile; if some PR breaks this test,
+    # this could be revisited, maybe.
+    newLit $($getType(untyped), $getType(typed))
+  doAssert fn() == """("untyped", "typed")"""
 
 block distinctBase:
   block:
@@ -50,6 +105,8 @@ block distinctBase:
       Foo[T] = distinct seq[T]
     var a: Foo[int]
     doAssert a.type.distinctBase is seq[int]
+    doAssert seq[int].distinctBase is seq[int]
+    doAssert "abc".distinctBase == "abc"
 
   block:
     # simplified from https://github.com/nim-lang/Nim/pull/8531#issuecomment-410436458
@@ -87,6 +144,67 @@ block distinctBase:
         doAssert($distinctBase(typeof(b2)) == "string")
         doAssert($distinctBase(typeof(c2)) == "int")
 
+block: # rangeBase
+  {.push warningAsError[EnumConv]: on.}
+  proc foo[T: not range](x: T): string =
+    $T & "(" & $x & ")"
+  proc foo[T: range](x: T): string =
+    "ranged(" & $low(T) & ".." & $high(T) & " of " & $rangeBase(T) & ") " & foo(rangeBase(x))
+  doAssert foo(123) == "int(123)"
+  type IntRange = range[0..3]
+  let x: IntRange = 2
+  doAssert foo(x) == "ranged(0..3 of int) int(2)"
+  type E = enum a, b, c, d, e, f
+  type EnumRange = range[c..e]
+  let y: EnumRange = d
+  doAssert foo(y) == "ranged(c..e of E) E(d)"
+  let z: range['a'..'z'] = 'g'
+  doAssert foo(z) == "ranged(a..z of char) char(g)"
+  {.pop.}
+
+  # works only with #24037:
+  var toChange: range[0..3] = 1
+  proc bar[T: int and not range](y: var T) =
+    inc y
+  doAssert not compiles(bar(toChange))
+  bar(rangeBase(toChange))
+  doAssert toChange == 2
+
+block: # tupleLen
+  doAssert not compiles(tupleLen(int))
+
+  type
+    MyTupleType = (int,float,string)
+
+  static: doAssert MyTupleType.tupleLen == 3
+
+  type
+    MyGenericTuple[T] = (T,int,float)
+    MyGenericAlias = MyGenericTuple[string]
+  static: doAssert MyGenericAlias.tupleLen == 3
+
+  type
+    MyGenericTuple2[T,U] = (T,U,string)
+    MyGenericTuple2Alias[T] =  MyGenericTuple2[T,int]
+
+    MyGenericTuple2Alias2 =   MyGenericTuple2Alias[float]
+  static: doAssert MyGenericTuple2Alias2.tupleLen == 3
+
+  static: doAssert (int, float).tupleLen == 2
+  static: doAssert (1, ).tupleLen == 1
+  static: doAssert ().tupleLen == 0
+
+  let x = (1,2,)
+  doAssert x.tupleLen == 2
+  doAssert ().tupleLen == 0
+  doAssert (1,).tupleLen == 1
+  doAssert (int,).tupleLen == 1
+  doAssert type(x).tupleLen == 2
+  doAssert type(x).default.tupleLen == 2
+  type T1 = (int,float)
+  type T2 = T1
+  doAssert T2.tupleLen == 2
+
 block genericParams:
   type Foo[T1, T2]=object
   doAssert genericParams(Foo[float, string]) is (float, string)
@@ -98,16 +216,74 @@ block genericParams:
   doAssert genericParams(Foo2).get(1) is Foo1
   doAssert (int,).get(0) is int
   doAssert (int, float).get(1) is float
-  static: doAssert (int, float).lenTuple == 2
-  static: doAssert (1, ).lenTuple == 1
-  static: doAssert ().lenTuple == 0
 
+  type Bar[N: static int, T] = object
+  type Bar3 = Bar[3, float]
+  doAssert genericParams(Bar3) is (StaticParam[3], float)
+  doAssert genericParams(Bar3).get(0) is StaticParam
+  doAssert genericParams(Bar3).get(0).value == 3
+  doAssert genericParams(Bar[3, float]).get(0).value == 3
+  static: doAssert genericParams(Bar[3, float]).get(0).value == 3
+
+  type
+    VectorElementType = SomeNumber | bool
+    Vec[N: static[int], T: VectorElementType] = object
+      arr: array[N, T]
+    Vec4[T: VectorElementType] = Vec[4,T]
+    Vec4f = Vec4[float32]
+
+    MyTupleType = (int,float,string)
+    MyGenericTuple[T] = (T,int,float)
+    MyGenericAlias = MyGenericTuple[string]
+    MyGenericTuple2[T,U] = (T,U,string)
+    MyGenericTuple2Alias[T] =  MyGenericTuple2[T,int]
+    MyGenericTuple2Alias2 =   MyGenericTuple2Alias[float]
+
+  doAssert genericParams(MyGenericAlias) is (string,)
+  doAssert genericHead(MyGenericAlias) is MyGenericTuple
+  doAssert genericParams(MyGenericTuple2Alias2) is (float,)
+  doAssert genericParams(MyGenericTuple2[float, int]) is (float, int)
+  doAssert genericParams(MyGenericAlias) is (string,)
+  doAssert genericParams(Vec4f) is (float32,)
+  doAssert genericParams(Vec[4, bool]) is (StaticParam[4], bool)
+
+  block:
+    type Foo[T1, T2]=object
+    doAssert genericParams(Foo[float, string]) is (float, string)
+    type Bar[N: static float, T] = object
+    doAssert genericParams(Bar[1.0, string]) is (StaticParam[1.0], string)
+    type Bar2 = Bar[2.0, string]
+    doAssert genericParams(Bar2) is (StaticParam[2.0], string)
+    type Bar3 = Bar[1.0 + 2.0, string]
+    doAssert genericParams(Bar3) is (StaticParam[3.0], string)
+
+    const F = 5.0
+    type Bar4 = Bar[F, string]
+    doAssert genericParams(Bar4) is (StaticParam[5.0], string)
+    doAssert genericParams(Bar[F, string]) is (StaticParam[5.0], string)
+
+  block typeof:
+    var
+      a: seq[int]
+      b: array[42, float]
+      c: array[char, int]
+      d: array[1..2, char]
+
+    doAssert genericParams(typeof(a)).get(0) is int
+    doAssert genericParams(typeof(b)) is (range[0..41], float)
+    doAssert genericParams(typeof(c)) is (char, int)
+    doAssert genericParams(typeof(d)) is (range[1..2], char)
+
+  block nestedContainers:
+    doAssert genericParams(seq[Foo[string, float]]).get(0) is Foo[string, float]
+    doAssert genericParams(array[10, Foo[Bar[1, int], Bar[2, float]]]) is (StaticParam[10], Foo[Bar[1, int], Bar[2, float]])
+    doAssert genericParams(array[1..9, int]) is (range[1..9], int)
 
 ##############################################
 # bug 13095
 
 type
-  CpuStorage{.shallow.}[T] = ref object
+  CpuStorage[T] {.shallow.} = ref object
     when supportsCopyMem(T):
       raw_buffer*: ptr UncheckedArray[T] # 8 bytes
       memalloc*: pointer                 # 8 bytes
@@ -120,4 +296,109 @@ var x = CpuStorage[string]()
 static:
   doAssert(not string.supportsCopyMem)
   doAssert x.T is string          # true
-  doAssert x.raw_buffer is seq
\ No newline at end of file
+  doAssert x.raw_buffer is seq
+
+block genericHead:
+  type Foo[T1,T2] = object
+    x1: T1
+    x2: T2
+  type FooInst = Foo[int, float]
+  type Foo2 = genericHead(FooInst)
+  doAssert Foo2 is Foo # issue #13066
+
+  block:
+    type Goo[T] = object
+    type Moo[U] = object
+    type Hoo = Goo[Moo[float]]
+    type Koo = genericHead(Hoo)
+    doAssert Koo is Goo
+    doAssert genericParams(Hoo) is (Moo[float],)
+    doAssert genericParams(Hoo).get(0) is Moo[float]
+    doAssert genericHead(genericParams(Hoo).get(0)) is Moo
+
+  type Foo2Inst = Foo2[int, float]
+  doAssert FooInst.default == Foo2Inst.default
+  doAssert FooInst.default.x2 == 0.0
+  doAssert Foo2Inst is FooInst
+  doAssert FooInst is Foo2Inst
+  doAssert compiles(genericHead(FooInst))
+  doAssert not compiles(genericHead(Foo))
+  type Bar = object
+  doAssert not compiles(genericHead(Bar))
+
+  when false: # xxx not supported yet
+    doAssert seq[int].genericHead is seq
+  when false: # xxx not supported yet, gives: Error: identifier expected
+    type Hoo[T] = object
+    doAssert genericHead(Hoo[int])[float] is Hoo[float]
+
+block: # elementType
+  iterator myiter(n: int): auto =
+    for i in 0..<n: yield i
+  iterator myiter3(): int = yield 10
+  iterator myiter2(n: int): auto {.closure.} =
+    for i in 0..<n: yield i
+  doAssert elementType(@[1,2]) is int
+  doAssert elementType("asdf") is char
+  doAssert elementType(myiter(3)) is int
+  doAssert elementType(myiter2(3)) is int
+  doAssert elementType([1.1]) is float
+  doAssert compiles elementType([1])
+  doAssert not compiles elementType(1)
+  doAssert compiles elementType(myiter3())
+  doAssert not compiles elementType(myiter3)
+  # check that it also works for 0-sized seq:
+  var a: seq[int]
+  doAssert elementType(a) is int
+  doAssert elementType(seq[char].default) is char
+
+block: # enum.len
+  type
+    Direction = enum
+      north, east, south, west
+    
+    Direction2 = Direction
+    Direction3 = Direction2
+
+    TokenType = enum
+      a = 2, b = 4, c = 89
+    
+    MyEnum = enum
+      ##[This is test of enum with a doc comment.
+
+         Which is also a multi line one.]##
+      valueA = (0, "my value A"),
+        ## The items are also commented. This has both integer and string
+        ## values.
+      valueB = "value B",
+        ## This item has only a string value,
+      valueC = 2,
+        ## and this one only an integer.
+      valueD = (3, "abc")
+        ## Both, integer and string values again.
+
+    OtherEnum {.pure.} = enum
+      valueX, valueY, valueZ
+
+    MyFlag {.size: sizeof(cint).} = enum
+      A, B, C, D
+
+  static:
+    doAssert Direction.enumLen == 4
+    doAssert Direction2.enumLen == 4
+    doAssert Direction3.enumLen == 4
+    doAssert TokenType.enumLen == 3
+    doAssert MyEnum.enumLen == 4
+    doAssert OtherEnum.enumLen == 3
+    doAssert MyFlag.enumLen == 4
+
+when true: # Odd bug where alias can seep inside of `distinctBase`
+  import std/unittest
+
+  type
+    AdtChild* = concept t
+      distinctBase(t)
+
+  proc `$`*[T: AdtChild](adtChild: T): string = ""
+
+  check 10 is int
diff --git a/tests/metatype/tunresolved_return_type.nim b/tests/metatype/tunresolved_return_type.nim
index f67e065ea..637a9b733 100644
--- a/tests/metatype/tunresolved_return_type.nim
+++ b/tests/metatype/tunresolved_return_type.nim
@@ -11,7 +11,7 @@ type
 
 proc toNumber[T: int|uint|int64|uint64](v: ResultValue): T =
   if v < low(T) or v > high(T):
-    raise newException(RangeError, "protocol error")
+    raise newException(RangeDefect, "protocol error")
   return T(v)
 
 #proc toNumber[T](v: int32): T =
diff --git a/tests/metatype/twildtypedesc.nim b/tests/metatype/twildtypedesc.nim
index 268bff0d8..d1c5ffba5 100644
--- a/tests/metatype/twildtypedesc.nim
+++ b/tests/metatype/twildtypedesc.nim
@@ -17,8 +17,8 @@ proc unpack[T](v: string): T =
 
 var s = "123"
 
-assert(unpack[string](s) is string)
-assert(unpack[int](s) is int)
+doAssert(unpack[string](s) is string)
+doAssert(unpack[int](s) is int)
 
 echo unpack[int](s)
 echo unpack[string](s)
@@ -37,7 +37,7 @@ proc unit(t: typedesc[int]): t = 0
 proc unit(t: typedesc[string]): t = ""
 proc unit(t: typedesc[float]): t = 0.0
 
-assert unit(int) == 0
-assert unit(string) == ""
-assert unit(float) == 0.0
+doAssert unit(int) == 0
+doAssert unit(string) == ""
+doAssert unit(float) == 0.0
 
diff --git a/tests/metatype/twrong_same_type.nim b/tests/metatype/twrong_same_type.nim
new file mode 100644
index 000000000..ea903b7a3
--- /dev/null
+++ b/tests/metatype/twrong_same_type.nim
@@ -0,0 +1,28 @@
+# bug #23418
+
+template mapIt*(x: untyped): untyped =
+  type OutType {.gensym.} = typeof(x) #typeof(x, typeOfProc)
+  newSeq[OutType](5)
+
+type F[E] = object
+
+proc start(v: int): F[(ValueError,)] = discard
+proc stop(v: int): F[tuple[]] = discard
+
+assert $typeof(mapIt(start(9))) == "seq[F[(ValueError,)]]"
+assert $typeof(mapIt(stop(9))) == "seq[F[tuple[]]]"
+
+# bug #23445
+
+type F2[T; I: static int] = distinct int
+
+proc start2(v: int): F2[void, 22] = discard
+proc stop2(v: int): F2[void, 33] = discard
+
+var a = mapIt(start2(5))
+
+assert $type(a) == "seq[F2[system.void, 22]]", $type(a)
+
+var b = mapIt(stop2(5))
+
+assert $type(b) == "seq[F2[system.void, 33]]", $type(b)
diff --git a/tests/metatype/typeclassinference.nim b/tests/metatype/typeclassinference.nim
index c845e04f7..b3f197718 100644
--- a/tests/metatype/typeclassinference.nim
+++ b/tests/metatype/typeclassinference.nim
@@ -19,3 +19,25 @@ var ptr1: ptr = addr(str1)
 var str2: string = "hello, world!"
 var ptr2: ptr = str2
 
+block: # built in typeclass inference
+  proc tupleA(): tuple = return (1, 2)
+  proc tupleB(): tuple = (1f, 2f)
+  assert typeof(tupleA()) is (int, int)
+  assert typeof(tupleB()) is (float32, float32)
+
+  proc a(val: int or float): tuple = 
+    when typeof(val) is int:
+      (10, 10)
+    else:
+      (30f, 30f)
+
+  assert typeof(a(10)) is (int, int)
+  assert typeof(a(10.0)) is (float32, float32)
+
+  proc b(val: int or float): set = 
+    when typeof(val) is int:
+      {10u8, 3}
+    else:
+      {'a', 'b'}
+  assert typeof(b(10)) is set[uint8]
+  assert typeof(b(10.0)) is set[char]
\ No newline at end of file
diff --git a/tests/metatype/typedesc_as_value.nim b/tests/metatype/typedesc_as_value.nim
index f6e526987..463d23724 100644
--- a/tests/metatype/typedesc_as_value.nim
+++ b/tests/metatype/typedesc_as_value.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "'typedesc' metatype is not valid here; typed '=' instead of ':'?"
+  errormsg: "invalid type: 'typedesc[int]' for var"
 """
 
 
diff --git a/tests/metatype/utypeclasses.nim b/tests/metatype/utypeclasses.nim
index 06bab375e..f94b39742 100644
--- a/tests/metatype/utypeclasses.nim
+++ b/tests/metatype/utypeclasses.nim
@@ -3,11 +3,11 @@ import unittest
 proc concat(a, b): string =
   result = $a & $b
 
-test "if proc param types are not supplied, the params are assumed to be generic":
+block: # if proc param types are not supplied, the params are assumed to be generic
   check concat(1, "test") == "1test"
   check concat(1, 20) == "120"
   check concat("foo", "bar") == "foobar"
 
-test "explicit param types can still be specified":
+block: # explicit param types can still be specified
   check concat[cstring, cstring]("x", "y") == "xy"
 
diff --git a/tests/method/nim.cfg b/tests/method/nim.cfg
deleted file mode 100644
index 57698b028..000000000
--- a/tests/method/nim.cfg
+++ /dev/null
@@ -1 +0,0 @@
-multimethods:on
diff --git a/tests/method/t20515.nim b/tests/method/t20515.nim
new file mode 100644
index 000000000..1921f2e46
--- /dev/null
+++ b/tests/method/t20515.nim
@@ -0,0 +1,20 @@
+discard """
+  errormsg: "Base method 'zzz' requires explicit '{.gcsafe.}' to be GC-safe"
+  line: 10
+"""
+
+type
+  A = ref object of RootObj
+  B = ref object of A
+
+method zzz(a: A) {.base.} =
+  discard
+
+var s: seq[int]
+method zzz(a: B) =
+  echo s
+
+proc xxx(someObj: A) {.gcsafe.} =
+  someObj.zzz()
+
+xxx(B())
diff --git a/tests/method/t22673.nim b/tests/method/t22673.nim
new file mode 100644
index 000000000..1689e9d42
--- /dev/null
+++ b/tests/method/t22673.nim
@@ -0,0 +1,21 @@
+discard """
+  matrix: "--warningAsError:UseBase"
+"""
+
+# bug #22673
+type RefEntry = ref object of RootObj
+
+type RefFile = ref object of RefEntry
+    filename*: string
+    data*: string
+
+type RefDir = ref object of RefEntry
+    dirname*: string
+    files*: seq[RefFile]
+
+method name*(e: RefEntry): lent string {.base.} =
+  raiseAssert "Don't call the base method"
+
+method name*(e: RefFile): lent string = e.filename
+
+method name*(e: RefDir): lent string = e.dirname
\ No newline at end of file
diff --git a/tests/method/tcompilegenerics.nim b/tests/method/tcompilegenerics.nim
new file mode 100644
index 000000000..d0732895b
--- /dev/null
+++ b/tests/method/tcompilegenerics.nim
@@ -0,0 +1,24 @@
+discard """
+  matrix: "--mm:arc; --mm:refc"
+  output: '''
+newDNode base
+'''
+"""
+
+type
+  SNodeAny = ref object of RootObj
+  SNode[T] = ref object of SNodeAny
+    m: T
+  DNode[T] = ref object
+
+method getStr(s: SNode[float]): string {.base.} = "blahblah"
+
+method newDNode(s: SNodeAny) {.base.} =
+  echo "newDNode base"
+
+method newDNode[T](s: SNode[T]) =
+  echo "newDNode generic"
+
+let m = SNode[float]()
+let s = SNodeAny(m)
+newDnode(s)
\ No newline at end of file
diff --git a/tests/method/tgeneric_methods.nim b/tests/method/tgeneric_methods.nim
index 0e2aeeede..f8d068cc5 100644
--- a/tests/method/tgeneric_methods.nim
+++ b/tests/method/tgeneric_methods.nim
@@ -1,41 +1,42 @@
-discard """
-  output: '''wow2
-X 1
-X 3'''
-"""
-type
-  First[T] = ref object of RootObj
-    value: T
-
-  Second[T] = ref object of First[T]
-    value2: T
-
-method wow[T](y: int; x: First[T]) {.base.} =
-  echo "wow1"
-
-method wow[T](y: int; x: Second[T]) =
-  echo "wow2"
-
-var
-  x: Second[int]
-new(x)
-
-proc takeFirst(x: First[int]) =
-  wow(2, x)
-
-takeFirst(x)
-
-
-# bug #5479
-type
-  Base[T: static[int]] = ref object of RootObj
-
-method test[T](t: Base[T]) {.base.} =
-  echo "X ", t.T
-
-let ab = Base[1]()
-
-ab.test()
-
-let ac = Base[3]()
-ac.test()
+discard """

+  matrix: "--mm:arc --multimethods:on -d:nimInternalNonVtablesTesting; --mm:refc --multimethods:on -d:nimInternalNonVtablesTesting"

+  output: '''wow2

+X 1

+X 3'''

+"""

+type

+  First[T] = ref object of RootObj

+    value: T

+

+  Second[T] = ref object of First[T]

+    value2: T

+

+method wow[T](y: int; x: First[T]) {.base.} =

+  echo "wow1"

+

+method wow[T](y: int; x: Second[T]) =

+  echo "wow2"

+

+var

+  x: Second[int]

+new(x)

+

+proc takeFirst(x: First[int]) =

+  wow(2, x)

+

+takeFirst(x)

+

+

+# bug #5479

+type

+  Base[T: static[int]] = ref object of RootObj

+

+method test[T](t: Base[T]) {.base.} =

+  echo "X ", t.T

+

+let ab = Base[1]()

+

+ab.test()

+

+let ac = Base[3]()

+ac.test()

diff --git a/tests/method/tmethod_issues.nim b/tests/method/tmethod_issues.nim
index 80f54caee..daaa46522 100644
--- a/tests/method/tmethod_issues.nim
+++ b/tests/method/tmethod_issues.nim
@@ -1,13 +1,16 @@
 discard """
+  matrix: "--mm:arc; --mm:refc"
   output: '''
 wof!
 wof!
+type A
+type B
 '''
 """
 
 
 # bug #1659
-type Animal = ref object {.inheritable.}
+type Animal {.inheritable.} = ref object
 type Dog = ref object of Animal
 
 method say(a: Animal): auto {.base.} = "wat!"
@@ -126,3 +129,42 @@ var obj2 = Class2()
 
 obj1.test(obj2) 
 obj2.test(obj1)
+
+
+# -------------------------------------------------------
+# issue #16516
+
+type
+  A = ref object of RootObj
+    x: int
+
+  B = ref object of A
+
+method foo(v: sink A, lst: var seq[A]) {.base,locks:0.} =
+  echo "type A"
+  lst.add v
+
+method foo(v: sink B, lst: var seq[A]) =
+  echo "type B"
+  lst.add v
+
+proc main() =
+  let
+    a = A(x: 5)
+    b: A = B(x: 5)
+
+  var lst: seq[A]
+
+  foo(a, lst)
+  foo(b, lst)
+
+main()
+
+block: # bug #20391
+  type Container[T] = ref object of RootRef
+    item: T
+
+  let a = Container[int]()
+
+  doAssert a of Container[int]
+  doAssert not (a of Container[string])
diff --git a/tests/method/tmethod_various.nim b/tests/method/tmethod_various.nim
index fd022717b..3b64aea8d 100644
--- a/tests/method/tmethod_various.nim
+++ b/tests/method/tmethod_various.nim
@@ -1,17 +1,15 @@
 discard """
+  matrix: "--mm:arc; --mm:refc"
   output: '''
-do nothing
 HELLO WORLD!
 '''
 """
 
 
-# tmethods1
-method somethin(obj: RootObj) {.base.} =
-  echo "do nothing"
+
 
 type
-  TNode* = object {.inheritable.}
+  TNode* {.inheritable.} = object
   PNode* = ref TNode
 
   PNodeFoo* = ref object of TNode
@@ -22,14 +20,12 @@ type
 method foo(a: PNode, b: PSomethingElse) {.base.} = discard
 method foo(a: PNodeFoo, b: PSomethingElse) = discard
 
-var o: RootObj
-o.somethin()
 
 
 
 # tmproto
 type
-  Obj1 = ref object {.inheritable.}
+  Obj1 {.inheritable.} = ref object
   Obj2 = ref object of Obj1
 
 method beta(x: Obj1): int {.base.}
diff --git a/tests/method/tmethods_old.nim b/tests/method/tmethods_old.nim
new file mode 100644
index 000000000..d24eb0cc7
--- /dev/null
+++ b/tests/method/tmethods_old.nim
@@ -0,0 +1,12 @@
+discard """
+  matrix: "--mm:arc -d:nimInternalNonVtablesTesting"
+  output: '''
+do nothing
+'''
+"""
+
+# tmethods1
+method somethin(obj: RootObj) {.base.} =
+  echo "do nothing"
+var o: RootObj
+o.somethin()
diff --git a/tests/method/tmultim.nim b/tests/method/tmultim.nim
index 7023e18bf..bba4d8c5c 100644
--- a/tests/method/tmultim.nim
+++ b/tests/method/tmultim.nim
@@ -1,95 +1,97 @@
-discard """
-  output: '''
-collide: unit, thing
-collide: unit, thing
-collide: thing, unit
-collide: thing, thing
-collide: unit, thing |
-collide: unit, thing |
-collide: thing, unit |
-do nothing
-'''
-  joinable: false
-"""
-
-
-# tmultim2
-type
-  TThing = object {.inheritable.}
-  TUnit = object of TThing
-    x: int
-  TParticle = object of TThing
-    a, b: int
-
-method collide(a, b: TThing) {.base, inline.} =
-  echo "collide: thing, thing"
-
-method collide(a: TThing, b: TUnit) {.inline.} =
-  echo "collide: thing, unit"
-
-method collide(a: TUnit, b: TThing) {.inline.} =
-  echo "collide: unit, thing"
-
-proc test(a, b: TThing) {.inline.} =
-  collide(a, b)
-
-proc staticCollide(a, b: TThing) {.inline.} =
-  procCall collide(a, b)
-
-var
-  a: TThing
-  b, c: TUnit
-collide(b, c) # ambiguous (unit, thing) or (thing, unit)? -> prefer unit, thing!
-test(b, c)
-collide(a, b)
-staticCollide(a, b)
-
-
-
-# tmultim6
-type
-  Thing = object {.inheritable.}
-  Unit[T] = object of Thing
-    x: T
-  Particle = object of Thing
-    a, b: int
-
-method collide(a, b: Thing) {.base, inline.} =
-  quit "to override!"
-
-method collide[T](a: Thing, b: Unit[T]) {.inline.} =
-  echo "collide: thing, unit |"
-
-method collide[T](a: Unit[T], b: Thing) {.inline.} =
-  echo "collide: unit, thing |"
-
-proc test(a, b: Thing) {.inline.} =
-  collide(a, b)
-
-var
-  aaa: Thing
-  bbb, ccc: Unit[string]
-collide(bbb, Thing(ccc))
-test(bbb, ccc)
-collide(aaa, bbb)
-
-
-
-# tmethods1
-method somethin(obj: RootObj) {.base.} =
-  echo "do nothing"
-
-type
-  TNode* = object {.inheritable.}
-  PNode* = ref TNode
-
-  PNodeFoo* = ref object of TNode
-
-  TSomethingElse = object
-  PSomethingElse = ref TSomethingElse
-
-method foo(a: PNode, b: PSomethingElse) {.base.} = discard
-method foo(a: PNodeFoo, b: PSomethingElse) = discard
-
-var o: RootObj
-o.somethin()
+discard """

+  matrix: "--multimethods:on"

+  output: '''

+collide: unit, thing

+collide: unit, thing

+collide: thing, unit

+collide: thing, thing

+collide: unit, thing |

+collide: unit, thing |

+collide: thing, unit |

+do nothing

+'''

+  joinable: false

+  disabled: true

+"""

+

+

+# tmultim2

+type

+  TThing {.inheritable.} = object

+  TUnit = object of TThing

+    x: int

+  TParticle = object of TThing

+    a, b: int

+

+method collide(a, b: TThing) {.base, inline.} =

+  echo "collide: thing, thing"

+

+method collide(a: TThing, b: TUnit) {.inline.} =

+  echo "collide: thing, unit"

+

+method collide(a: TUnit, b: TThing) {.inline.} =

+  echo "collide: unit, thing"

+

+proc test(a, b: TThing) {.inline.} =

+  collide(a, b)

+

+proc staticCollide(a, b: TThing) {.inline.} =

+  procCall collide(a, b)

+

+var

+  a: TThing

+  b, c: TUnit

+collide(b, c) # ambiguous (unit, thing) or (thing, unit)? -> prefer unit, thing!

+test(b, c)

+collide(a, b)

+staticCollide(a, b)

+

+

+

+# tmultim6

+type

+  Thing {.inheritable.} = object

+  Unit[T] = object of Thing

+    x: T

+  Particle = object of Thing

+    a, b: int

+

+method collide(a, b: Thing) {.base, inline.} =

+  quit "to override!"

+

+method collide[T](a: Thing, b: Unit[T]) {.inline.} =

+  echo "collide: thing, unit |"

+

+method collide[T](a: Unit[T], b: Thing) {.inline.} =

+  echo "collide: unit, thing |"

+

+proc test(a, b: Thing) {.inline.} =

+  collide(a, b)

+

+var

+  aaa: Thing

+  bbb, ccc: Unit[string]

+collide(bbb, Thing(ccc))

+test(bbb, ccc)

+collide(aaa, bbb)

+

+

+

+# tmethods1

+method somethin(obj: RootObj) {.base.} =

+  echo "do nothing"

+

+type

+  TNode* {.inheritable.} = object

+  PNode* = ref TNode

+

+  PNodeFoo* = ref object of TNode

+

+  TSomethingElse = object

+  PSomethingElse = ref TSomethingElse

+

+method foo(a: PNode, b: PSomethingElse) {.base.} = discard

+method foo(a: PNodeFoo, b: PSomethingElse) = discard

+

+var o: RootObj

+o.somethin()

diff --git a/tests/method/tmultimjs.nim b/tests/method/tmultimjs.nim
index ce62a2c23..36960f2e1 100644
--- a/tests/method/tmultimjs.nim
+++ b/tests/method/tmultimjs.nim
@@ -4,6 +4,7 @@ discard """
 Hi derived!
 hello
 '''
+  disabled: true
 """
 
 
diff --git a/tests/method/tnildispatcher.nim b/tests/method/tnildispatcher.nim
index 017e8155f..219d2b29f 100644
--- a/tests/method/tnildispatcher.nim
+++ b/tests/method/tnildispatcher.nim
@@ -1,5 +1,5 @@
 discard """
-  outputsub: '''Error: unhandled exception: cannot dispatch; dispatcher is nil [NilAccessError]'''
+  outputsub: '''Error: unhandled exception: cannot dispatch; dispatcher is nil [NilAccessDefect]'''
   exitcode: 1
 """
 # bug #5599
diff --git a/tests/method/tsingle_methods.nim b/tests/method/tsingle_methods.nim
index 40269559a..b564e7d87 100644
--- a/tests/method/tsingle_methods.nim
+++ b/tests/method/tsingle_methods.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: "nim c --multimethods:off $file"
+  matrix: "--mm:arc --multimethods:off; --mm:refc --multimethods:off"
   output: '''base
 base
 base
diff --git a/tests/method/tvtable.nim b/tests/method/tvtable.nim
new file mode 100644
index 000000000..a1b33d6b7
--- /dev/null
+++ b/tests/method/tvtable.nim
@@ -0,0 +1,24 @@
+discard """

+  targets: "c cpp"

+"""

+

+type FooBase = ref object of RootObj

+  dummy: int

+type Foo = ref object of FooBase

+  value : float32

+type Foo2 = ref object of Foo

+  change : float32

+method bar(x: FooBase, a: float32) {.base.} =

+  discard

+method bar(x: Foo, a: float32)  =

+  x.value += a

+method bar(x: Foo2, a: float32)  =

+  x.value += a

+

+

+proc test() =

+  var x = new Foo2

+  x.bar(2.3)

+  doAssert x.value <= 2.3

+

+test()
\ No newline at end of file
diff --git a/tests/misc/m15316.nim b/tests/misc/m15316.nim
new file mode 100644
index 000000000..188d06946
--- /dev/null
+++ b/tests/misc/m15316.nim
@@ -0,0 +1 @@
+proc foo = (if)
diff --git a/tests/misc/m15955.nim b/tests/misc/m15955.nim
new file mode 100644
index 000000000..22da345db
--- /dev/null
+++ b/tests/misc/m15955.nim
@@ -0,0 +1,4 @@
+proc add*(a, b: int): int {.cdecl, exportc.} =
+    a + b
+proc sub*(a, b: int): int {.cdecl, exportc.} =
+    a - b
\ No newline at end of file
diff --git a/tests/misc/m15955_main.nim b/tests/misc/m15955_main.nim
new file mode 100644
index 000000000..a71af8121
--- /dev/null
+++ b/tests/misc/m15955_main.nim
@@ -0,0 +1,11 @@
+import stdtest/specialpaths
+import std/os
+
+const buildLib = buildDir / "libD20220923T19380"
+
+{.passL: buildLib.}
+proc add*(a, b: int):int {.cdecl, importc.}
+proc sub*(a, b: int):int {.cdecl, importc.}
+
+echo add(10, 5)
+echo sub(10, 5)
diff --git a/tests/misc/m20149.nim b/tests/misc/m20149.nim
new file mode 100644
index 000000000..942262a6e
--- /dev/null
+++ b/tests/misc/m20149.nim
@@ -0,0 +1,2 @@
+let x = 12
+echo x
diff --git a/tests/misc/m20456.nims b/tests/misc/m20456.nims
new file mode 100644
index 000000000..8a9313129
--- /dev/null
+++ b/tests/misc/m20456.nims
@@ -0,0 +1 @@
+echo 123
\ No newline at end of file
diff --git a/tests/misc/mbackend.nim b/tests/misc/mbackend.nim
new file mode 100644
index 000000000..b6578a212
--- /dev/null
+++ b/tests/misc/mbackend.nim
@@ -0,0 +1,30 @@
+#[
+We can't merge this test inside a `when defined(cpp)` because some bug that was
+fixed would not trigger in that case.
+]#
+
+import std/compilesettings
+
+static:
+  ## bugfix 1: this used to CT error with: Error: unhandled exception: mimportcpp.nim(6, 18) `defined(cpp)`
+  doAssert defined(cpp)
+  doAssert querySetting(backend) == "cpp"
+
+  ## checks that `--backend:c` has no side effect (ie, can be overridden by subsequent commands)
+  doAssert not defined(c)
+  doAssert not defined(js)
+  doAssert not defined(js)
+
+type
+  std_exception {.importcpp: "std::exception", header: "<exception>".} = object
+proc what(s: std_exception): cstring {.importcpp: "((char *)#.what())".}
+
+var isThrown = false
+try:
+  ## bugfix 2: this used to CT error with: Error: only a 'ref object' can be raised
+  raise std_exception()
+except std_exception as ex:
+  doAssert ex.what().len > 0
+  isThrown = true
+
+doAssert isThrown
diff --git a/tests/misc/mbetterrun.nim b/tests/misc/mbetterrun.nim
new file mode 100644
index 000000000..d4f427af0
--- /dev/null
+++ b/tests/misc/mbetterrun.nim
@@ -0,0 +1,3 @@
+const mbetterrunVal {.strdefine.} = ""
+static: echo "compiling: " & mbetterrunVal
+echo "running: " & mbetterrunVal
diff --git a/tests/misc/mfield_defect.nim b/tests/misc/mfield_defect.nim
new file mode 100644
index 000000000..53bfba40e
--- /dev/null
+++ b/tests/misc/mfield_defect.nim
@@ -0,0 +1,30 @@
+#[
+ran from trunner
+]#
+
+
+
+
+
+
+# line 10
+type Kind = enum k0, k1, k2, k3, k4
+
+type Foo = object
+  case kind: Kind
+  of k0: f0: int
+  of k1: f1: int
+  of k2: f2: int
+  of k3: f3: int
+  of k4: f4: int
+
+proc main()=
+  var foo = Foo(kind: k3, f3: 3)
+  let s1 = foo.f3
+  doAssert s1 == 3
+  let s2 = foo.f2
+
+when defined case1:
+  static: main()
+when defined case2:
+  main()
diff --git a/tests/misc/mimportc.nim b/tests/misc/mimportc.nim
new file mode 100644
index 000000000..602c6372d
--- /dev/null
+++ b/tests/misc/mimportc.nim
@@ -0,0 +1,26 @@
+#[
+this test will grow with more importc+importcpp tests; see driver in trunner.nim
+]#
+
+{.emit:"""
+struct A {
+  static int fun0(int a){
+    return a;
+  }
+  static int& fun1(int& a){
+    return a;
+  }
+};
+""".}
+
+proc fun0*(a: cint): int {.importcpp:"A::$1(@)".}
+proc fun1*(a: var cint): var int {.importcpp:"A::$1(@)".} =
+  ## some comment; this test is for #14314
+  runnableExamples: discard
+
+proc main()=
+  var a = 10.cint
+  doAssert fun0(a) == a
+  doAssert fun1(a).addr == a.addr
+  echo "witness"
+main()
diff --git a/tests/misc/mjsondoc.nim b/tests/misc/mjsondoc.nim
new file mode 100644
index 000000000..016c8522d
--- /dev/null
+++ b/tests/misc/mjsondoc.nim
@@ -0,0 +1,14 @@
+proc doSomething*(x, y: int): int =
+  ## do something
+  x + y
+
+const
+  a* = 1 ## echo 1234
+  b* = "test"
+
+type
+  MyEnum* = enum
+    foo, bar
+
+proc foo2*[T: int, M: string, U](x: T, y: U, z: M) =
+  echo 1
diff --git a/tests/misc/msizeof5.nim b/tests/misc/msizeof5.nim
new file mode 100644
index 000000000..63573a705
--- /dev/null
+++ b/tests/misc/msizeof5.nim
@@ -0,0 +1,131 @@
+## tests for -d:checkAbi used by addAbiCheck via NIM_STATIC_ASSERT
+
+{.emit:"""/*TYPESECTION*/
+struct Foo1{
+  int a;
+};
+struct Foo2{
+  int a;
+};
+enum Foo3{k1, k2};
+typedef enum Foo3 Foo3b;
+typedef enum Foo4{k3, k4} Foo4;
+
+typedef int Foo5[3];
+
+typedef struct Foo6{
+  int a1;
+  bool a2;
+  double a3;
+  struct Foo6* a4;
+} Foo6;
+""".}
+
+template ensureCgen(T: typedesc) =
+  ## ensures cgen
+  var a {.volatile.}: T
+
+block:
+  type Foo1Alias{.importc: "struct Foo1", size: sizeof(cint).} = object
+    a: cint
+  ensureCgen Foo1Alias
+
+block:
+  type Foo3Alias{.importc: "enum Foo3", size: sizeof(cint).} = enum
+    k1, k2
+  ensureCgen Foo3Alias
+
+block:
+  type Foo3bAlias{.importc: "Foo3b", size: sizeof(cint).} = enum
+    k1, k2
+  ensureCgen Foo3bAlias
+
+block:
+  type Foo3b{.importc, size: sizeof(cint).} = enum
+    k1, k2
+  ensureCgen Foo3b
+  static:
+    doAssert Foo3b.sizeof == cint.sizeof
+
+block:
+  type Foo4{.importc, size: sizeof(cint).} = enum
+    k3, k4
+  # adding entries should not yield duplicate ABI checks, as enforced by
+  # `typeABICache`.
+  # Currently the test doesn't check for this but you can inspect the cgen'd file
+  ensureCgen Foo4
+  ensureCgen Foo4
+  ensureCgen Foo4
+
+block:
+  type Foo5{.importc.} = array[3, cint]
+  ensureCgen Foo5
+
+block:
+  type Foo5{.importc.} = array[3, cint]
+  ensureCgen Foo5
+
+block: # CT sizeof
+  type Foo6GT = object # grountruth
+    a1: cint
+    a2: bool
+    a3: cfloat
+    a4: ptr Foo6GT
+
+  type Foo6{.importc, completeStruct.} = object
+    a1: cint
+    a2: bool
+    a3: cfloat
+    a4: ptr Foo6
+
+  static: doAssert compiles(static(Foo6.sizeof))
+  static: doAssert Foo6.sizeof == Foo6GT.sizeof
+  static: doAssert (Foo6, int, array[2, Foo6]).sizeof ==
+    (Foo6GT, int, array[2, Foo6GT]).sizeof
+
+block:
+  type GoodImportcType {.importc: "signed char", nodecl.} = char
+    # "good" in sense the sizeof will match
+  ensureCgen GoodImportcType
+
+block:
+  type Foo6{.importc.} = object
+    a1: cint
+  doAssert compiles(Foo6.sizeof)
+  static: doAssert not compiles(static(Foo6.sizeof))
+
+when defined caseBad:
+  # Each case below should give a static cgen assert fail message
+
+  block:
+    type BadImportcType {.importc: "unsigned char", nodecl.} = uint64
+      # "sizeof" check will fail
+    ensureCgen BadImportcType
+
+  block:
+    type Foo2AliasBad{.importc: "struct Foo2", size: 1.} = object
+      a: cint
+    ensureCgen Foo2AliasBad
+
+  block:
+    type Foo5{.importc.} = array[4, cint]
+    ensureCgen Foo5
+
+  block:
+    type Foo5{.importc.} = array[3, bool]
+    ensureCgen Foo5
+
+  block:
+    type Foo6{.importc:"struct Foo6", completeStruct.} = object
+      a1: cint
+      # a2: bool # missing this should trigger assert fail
+      a3: cfloat
+      a4: ptr Foo6
+    ensureCgen Foo6
+
+  when false:
+    block:
+      # pre-existing BUG: this should give a CT error in semcheck because `size`
+      # disagrees with `array[3, cint]`
+      type Foo5{.importc, size: 1.} = array[3, cint]
+      ensureCgen Foo5
diff --git a/tests/misc/msizeof5.nim.cfg b/tests/misc/msizeof5.nim.cfg
new file mode 100644
index 000000000..dc0712a8c
--- /dev/null
+++ b/tests/misc/msizeof5.nim.cfg
@@ -0,0 +1,5 @@
+# Do not limit number of error messages from backend compiler.
+gcc.options.always %= "${gcc.options.always} -fmax-errors=100"
+clang.options.always %= "${clang.options.always} -ferror-limit=100"
+gcc.cpp.options.always %= "${gcc.cpp.options.always} -fmax-errors=100"
+clang.cpp.options.always %= "${clang.cpp.options.always} -ferror-limit=100"
diff --git a/tests/misc/mtlsemulation.h b/tests/misc/mtlsemulation.h
new file mode 100644
index 000000000..992977acd
--- /dev/null
+++ b/tests/misc/mtlsemulation.h
@@ -0,0 +1,37 @@
+#include <stdio.h>
+
+struct Foo1 {
+  /*
+  uncommenting would give:
+  error: initializer for thread-local variable must be a constant expression
+  N_LIB_PRIVATE NIM_THREADVAR Foo1 g1__9brEZhPEldbVrNpdRGmWESA;
+  */
+  // Foo1() noexcept { }
+
+  /*
+  uncommenting would give:
+  error: type of thread-local variable has non-trivial destruction
+  */
+  // ~Foo1() { }
+  int x;
+};
+
+struct Foo2 {
+  Foo2() noexcept { }
+  ~Foo2() { }
+  int x;
+};
+
+static int ctorCalls = 0;
+static int dtorCalls = 0;
+
+struct Foo3 {
+  Foo3() noexcept {
+    ctorCalls = ctorCalls + 1;
+    x = 10;
+  }
+  ~Foo3() {
+    dtorCalls = dtorCalls + 1;
+  }
+  int x;
+};
diff --git a/tests/misc/parsecomb.nim b/tests/misc/parsecomb.nim
index 4ff2f65d2..4f149cbf6 100644
--- a/tests/misc/parsecomb.nim
+++ b/tests/misc/parsecomb.nim
@@ -1,3 +1,7 @@
+discard """
+  matrix: "--mm:arc; --mm:refc"
+"""
+
 type Input[T] = object
   toks: seq[T]
   index: int
diff --git a/tests/misc/t11634.nim b/tests/misc/t11634.nim
new file mode 100644
index 000000000..390af40f4
--- /dev/null
+++ b/tests/misc/t11634.nim
@@ -0,0 +1,17 @@
+discard """
+  action: reject
+"""
+
+type Foo = ref object
+  val: int
+
+proc divmod(a, b: Foo): (Foo, Foo) =
+  (
+    Foo(val: a.val div b.val),
+    Foo(val: a.val mod b.val)
+  )
+
+block:
+  let a {.compileTime.} = Foo(val: 2)
+  let b {.compileTime.} = Foo(val: 3)
+  let (c11634 {.compileTime.}, d11634 {.compileTime.}) = divmod(a, b)
diff --git a/tests/misc/t12869.nim b/tests/misc/t12869.nim
new file mode 100644
index 000000000..054e28a03
--- /dev/null
+++ b/tests/misc/t12869.nim
@@ -0,0 +1,14 @@
+discard """
+  errormsg: "type mismatch: got <openArray[int], proc (x: GenericParam, y: GenericParam): auto, SortOrder>"
+  line: 12
+"""
+
+import sugar
+from algorithm import sorted, SortOrder
+
+let a = 5
+
+proc sorted*[T](a: openArray[T], key: proc(v: T): int, order = SortOrder.Ascending): seq[T] =
+  sorted(a, (x, y) => key(x) < key(y), order)
+
+echo sorted(@[9, 1, 8, 2, 6, 4, 5, 0], (x) => (a - x).abs)
diff --git a/tests/misc/t14667.nim b/tests/misc/t14667.nim
new file mode 100644
index 000000000..3034e2841
--- /dev/null
+++ b/tests/misc/t14667.nim
@@ -0,0 +1,12 @@
+discard """
+  matrix: "--cc:vcc"
+  disabled: "linux"
+  disabled: "bsd"
+  disabled: "osx"
+  disabled: "unix"
+  disabled: "posix"
+"""
+
+type A = tuple
+discard ()
+discard default(A)
diff --git a/tests/misc/t15351.nim b/tests/misc/t15351.nim
new file mode 100644
index 000000000..c31e604a2
--- /dev/null
+++ b/tests/misc/t15351.nim
@@ -0,0 +1,5 @@
+discard """
+  action: "compile"
+"""
+var
+  ## TODO: broken
diff --git a/tests/misc/t15955.nim b/tests/misc/t15955.nim
new file mode 100644
index 000000000..7441e5398
--- /dev/null
+++ b/tests/misc/t15955.nim
@@ -0,0 +1,22 @@
+discard """
+joinable: false
+"""
+
+import stdtest/specialpaths
+import std/[osproc, strformat, os]
+
+const
+  nim = getCurrentCompilerExe()
+  buildLib = buildDir / "libD20220923T19380"
+  currentDir = splitFile(currentSourcePath).dir
+  file = currentDir / "m15955.nim"
+  main = currentDir / "m15955_main.nim"
+
+
+proc runCmd(cmd: string) =
+  let (msg, code) = execCmdEx(cmd)
+  doAssert code == 0, msg
+
+
+runCmd fmt"{nim} c -o:{buildLib} --nomain --nimMainPrefix:libA -f --app:staticlib {file}"
+runCmd fmt"{nim} c -r {main}"
diff --git a/tests/misc/t16244.nim b/tests/misc/t16244.nim
new file mode 100644
index 000000000..5e8128736
--- /dev/null
+++ b/tests/misc/t16244.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "type mismatch: got <int, float64>"
+  line: 9
+"""
+
+proc g(): auto = 1
+proc h(): auto = 1.0
+
+var a = g() + h()
diff --git a/tests/misc/t16264.nim b/tests/misc/t16264.nim
new file mode 100644
index 000000000..afe319e6c
--- /dev/null
+++ b/tests/misc/t16264.nim
@@ -0,0 +1,2 @@
+import times
+doAssert low(Time) == fromUnix(0)
\ No newline at end of file
diff --git a/tests/misc/t16541.nim b/tests/misc/t16541.nim
new file mode 100644
index 000000000..452327e8f
--- /dev/null
+++ b/tests/misc/t16541.nim
@@ -0,0 +1,12 @@
+discard """
+  action: "reject"
+
+"""
+
+import strutils, sugar, nre
+
+proc my_replace*(s: string, r: Regex, by: string | (proc (match: string): string)): string =
+  nre.replace(s, r, by)
+
+discard my_replace("abcde", re"[bcd]", match => match.to_upper) == "aBCDe"
+discard my_replace("abcde", re"[bcd]", (match: string) => match.to_upper) == "aBCDe"
diff --git a/tests/misc/t17286.nim b/tests/misc/t17286.nim
new file mode 100644
index 000000000..3a54e624e
--- /dev/null
+++ b/tests/misc/t17286.nim
@@ -0,0 +1,16 @@
+discard """
+  cmd: "nim check -b:js $file"
+  action: "compile"
+"""
+
+# bug #17286
+
+import std/compilesettings
+
+static:
+  doAssert querySetting(backend) == "js"
+  doAssert defined(js)
+  doAssert not defined(c)
+
+import random
+randomize()
\ No newline at end of file
diff --git a/tests/misc/t18077.nim b/tests/misc/t18077.nim
new file mode 100644
index 000000000..6cd05d575
--- /dev/null
+++ b/tests/misc/t18077.nim
@@ -0,0 +1,21 @@
+discard """
+  cmd: '''nim doc -d:nimTestsT18077b:4 --doccmd:"-d:nimTestsT18077 -d:nimTestsT18077b:3 --hints:off" $file'''
+  action: compile
+"""
+
+# bug #18077
+
+const nimTestsT18077b {.intdefine.} = 1
+
+static:
+  when defined(nimdoc):
+    doAssert nimTestsT18077b == 4
+    doAssert not defined(nimTestsT18077)
+  else:
+    doAssert defined(nimTestsT18077)
+    doAssert nimTestsT18077b == 3
+
+runnableExamples:
+  const nimTestsT18077b {.intdefine.} = 2
+  doAssert nimTestsT18077b == 3
+  doAssert defined(nimTestsT18077)
diff --git a/tests/misc/t18079.nim b/tests/misc/t18079.nim
new file mode 100644
index 000000000..ae64bbff9
--- /dev/null
+++ b/tests/misc/t18079.nim
@@ -0,0 +1,15 @@
+discard """
+  matrix: "--mm:orc"
+"""
+
+type
+  Foo = object
+    y: int
+
+  Bar = object
+    x: Foo
+
+proc baz(state: var Bar):int = 
+  state.x.y = 2
+  state.x.y
+doAssert baz((ref Bar)(x: (new Foo)[])[]) == 2
diff --git a/tests/misc/t19046.nim b/tests/misc/t19046.nim
new file mode 100644
index 000000000..b3bfec7ae
--- /dev/null
+++ b/tests/misc/t19046.nim
@@ -0,0 +1,19 @@
+discard """
+  targets: "c cpp"
+  matrix: "--threads:on"
+  disabled: "win"
+  disabled: "osx"
+  action: compile
+"""
+
+# bug #19046
+
+import std/os
+
+var t: Thread[void]
+
+proc test = discard
+proc main = 
+  createThread(t, test)
+  pinToCpu(t, 1)
+main()
\ No newline at end of file
diff --git a/tests/misc/t20253.nim b/tests/misc/t20253.nim
new file mode 100644
index 000000000..d47c36c55
--- /dev/null
+++ b/tests/misc/t20253.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "'result' requires explicit initialization"
+  line: 10
+"""
+
+type Meow {.requiresInit.} = object 
+  init: bool
+
+proc initMeow(): Meow =
+  discard
diff --git a/tests/misc/t20289.nim b/tests/misc/t20289.nim
new file mode 100644
index 000000000..5a0a269f0
--- /dev/null
+++ b/tests/misc/t20289.nim
@@ -0,0 +1,15 @@
+discard """
+  action: reject
+"""
+
+type E[T] = object
+  v: T
+
+template j[T](R: type E[T], x: untyped): R = R(v: x)
+template d[T](O: type E, v: T): E[T] = E[T].j(v)
+
+proc w[T](): E[T] =
+  template r(k: int): auto = default(T)
+  E.d r
+
+discard w[int]()
diff --git a/tests/misc/t20456_2.nim b/tests/misc/t20456_2.nim
new file mode 100644
index 000000000..37e52c452
--- /dev/null
+++ b/tests/misc/t20456_2.nim
@@ -0,0 +1,14 @@
+discard """
+  joinable: false
+"""
+
+import std/[osproc, os, strformat]
+from stdtest/specialpaths import testsDir
+
+when defined(nimPreviewSlimSystem):
+  import std/assertions
+
+const
+  nim = getCurrentCompilerExe()
+  file = testsDir / "misc" / "m20456.nims"
+doAssert execCmd(fmt"{nim} check {file}") == 0
diff --git a/tests/misc/t20883.nim b/tests/misc/t20883.nim
new file mode 100644
index 000000000..92e7929f4
--- /dev/null
+++ b/tests/misc/t20883.nim
@@ -0,0 +1,13 @@
+discard """
+  action: reject
+nimout: '''
+t20883.nim(13, 4) template/generic instantiation of `foo` from here
+t20883.nim(9, 11) Error: cannot instantiate: 'U'
+'''
+"""
+
+proc foo*[U](x: U = U(1e-6)) =
+  echo x
+
+foo[float]()
+foo()
diff --git a/tests/misc/t21109.nim b/tests/misc/t21109.nim
new file mode 100644
index 000000000..0f7980896
--- /dev/null
+++ b/tests/misc/t21109.nim
@@ -0,0 +1,13 @@
+discard """
+  action: reject
+  errormsg: "type expected"
+  file: "iterators.nim"
+"""
+
+
+template b(j: untyped) = j
+template m() = discard
+
+b:
+  for t, f in @[]:
+    m()
diff --git a/tests/misc/t21443.nim b/tests/misc/t21443.nim
new file mode 100644
index 000000000..70413c5b3
--- /dev/null
+++ b/tests/misc/t21443.nim
@@ -0,0 +1,6 @@
+import std/envvars
+
+# bug #19292
+putEnv("NimPutEnvTest", "test")
+# bug #21122
+doAssert getEnv("NimPutEnvTest") == "test"
diff --git a/tests/misc/t23240.nim b/tests/misc/t23240.nim
new file mode 100644
index 000000000..d5edcefe8
--- /dev/null
+++ b/tests/misc/t23240.nim
@@ -0,0 +1,6 @@
+discard """
+  cmd: "nim c foo/bar.nim"
+  action: "reject"
+  errormsg: "cannot open 'foo/'"
+  file: ""
+"""
diff --git a/tests/misc/t3482.nim b/tests/misc/t3482.nim
new file mode 100644
index 000000000..33b3b8f40
--- /dev/null
+++ b/tests/misc/t3482.nim
@@ -0,0 +1,15 @@
+discard """
+  action: reject
+  nimout: "t3482.nim(13, 8) Error: undeclared identifier: 'output'"
+"""
+# bug #3482 (correct behavior since 1.4.0, cgen error in 1.2.0)
+template foo*(body: typed) =
+  if true:
+    body
+
+proc test =
+  foo:
+    var output = ""
+  echo output.len
+
+test()
diff --git a/tests/misc/t3907.nim b/tests/misc/t3907.nim
new file mode 100644
index 000000000..45fc75e81
--- /dev/null
+++ b/tests/misc/t3907.nim
@@ -0,0 +1,10 @@
+import std/assertions
+
+let a = 0
+let b = if false: -1 else: a
+doAssert b == 0
+
+let c: range[0..high(int)] = 0
+let d = if false: -1 else: c
+
+doAssert d == 0
diff --git a/tests/misc/t5540.nim b/tests/misc/t5540.nim
new file mode 100644
index 000000000..6a19e70e1
--- /dev/null
+++ b/tests/misc/t5540.nim
@@ -0,0 +1,45 @@
+# bug #5540; works in 1.2.0
+# fails in 1.0 (Error: cannot generate VM code for)
+# fails in 0.18.0 (Error: type mismatch: got <type T>)
+
+block:
+  type
+    Fruit = object
+    Yellow = object
+      a: int
+  template getColor(x: typedesc[Fruit]): typedesc = Yellow
+  type
+    Banana[T] = object
+      b: T
+      a: getColor(Fruit)
+    Apple[T] = object
+      a: T
+      b: getColor(T)
+  block:
+    var x: Banana[int]
+    doAssert x.b == 0
+    doAssert x.a is Yellow
+  block:
+    var x: Apple[Fruit]
+    doAssert x.b is Yellow
+
+block:
+  type
+    Fruit = object
+    Yellow = object
+      a: int
+    
+  template getColor(x: typedesc[Fruit]): typedesc = Yellow
+
+  type
+    Banana[T] = object
+      b: T
+      a: getColor(Fruit)
+
+    Apple[T] = object
+      a: T
+      b: getColor(T)
+      
+  var x: Banana[int]
+  x.b = 13
+  x.a.a = 17
diff --git a/tests/misc/t6549.nim b/tests/misc/t6549.nim
new file mode 100644
index 000000000..1d7393318
--- /dev/null
+++ b/tests/misc/t6549.nim
@@ -0,0 +1,4 @@
+
+const l = $(range[low(uint64) .. high(uint64)])
+const r = "range 0..18446744073709551615(uint64)"
+doAssert l == r
diff --git a/tests/misc/t8404.nim b/tests/misc/t8404.nim
new file mode 100644
index 000000000..87991071c
--- /dev/null
+++ b/tests/misc/t8404.nim
@@ -0,0 +1,33 @@
+discard """
+  targets: "c cpp js"
+"""
+template main() =
+  block: # bug #8404
+    # can conv
+    template float2int(T) =
+      var a = -1.0
+      let b = T(a)
+      doAssert b < 0
+      let c = b + 1
+      doAssert c is T
+      doAssert c == 0
+
+    float2int(int8)
+    float2int(int16)
+    float2int(int32)
+    float2int(int64)
+
+  block:
+    # can handle middle conv
+    # `/` can trigger int to float
+    template float2int(T) =
+      let n = T(1 / 256)
+      doAssert n == 0
+
+    float2int(int8)
+    float2int(int16)
+    float2int(int32)
+    # float2int(int64)
+main()
+static:
+  main()
diff --git a/tests/misc/t8545.nim b/tests/misc/t8545.nim
new file mode 100644
index 000000000..48b886cb8
--- /dev/null
+++ b/tests/misc/t8545.nim
@@ -0,0 +1,24 @@
+discard """
+  # just tests that this doesn't crash the compiler
+  errormsg: "cannot instantiate: 'a:type'"
+"""
+
+# bug #8545
+
+template bar(a: static[bool]): untyped = int
+
+proc main() =
+  proc foo1(a: static[bool]): auto = 1
+  doAssert foo1(true) == 1
+
+  proc foo2(a: static[bool]): bar(a) = 1
+  doAssert foo2(true) == 1
+
+  proc foo3(a: static[bool]): bar(cast[static[bool]](a)) = 1
+  doAssert foo3(true) == 1
+
+  proc foo4(a: static[bool]): bar(static(a)) = 1
+  doAssert foo4(true) == 1
+
+static: main()
+main()
diff --git a/tests/misc/t9039.nim b/tests/misc/t9039.nim
new file mode 100644
index 000000000..3271cd34e
--- /dev/null
+++ b/tests/misc/t9039.nim
@@ -0,0 +1,24 @@
+discard """
+  action: reject
+  nimout: '''
+t9039.nim(22, 22) Error: type mismatch: got <array[0..2, int], int, array[0..1, int]>
+but expression 'nesting + 1' is of type: int
+'''
+"""
+
+# bug #9039; this used to hang in 0.19.0
+
+
+
+
+
+# line 15
+func default(T: typedesc[array]): T = discard
+doAssert default(array[3, int]) == [0, 0, 0]
+func shapeBad*[T: not char](s: openArray[T], rank: static[int], nesting = 0, parent_shape = default(array[rank, int])): array[rank, int] =
+  result = parent_shape
+  result[nesting] = s.len
+  when (T is seq|array):
+    result = shapeBad(s[0], nesting + 1, result)
+let a1 = [1, 2, 3].shapeBad(rank = 1)
+let a2 = [[1, 2, 3], [4, 5, 6]].shapeBad(rank = 2)
diff --git a/tests/misc/t9091.nim b/tests/misc/t9091.nim
new file mode 100644
index 000000000..6e7a98ca5
--- /dev/null
+++ b/tests/misc/t9091.nim
@@ -0,0 +1,33 @@
+# bug #9091
+
+import streams
+
+block:
+  type Mine = ref object
+    a: int
+
+  proc write(io: Stream, t: Mine) =
+    io.write("sure")
+
+  let str = newStringStream()
+  let mi = new Mine
+
+  str.write(mi)
+  str.setPosition 0
+  doAssert str.readAll == "sure"
+
+block:
+  type
+    AObj = object
+      x: int
+
+  proc foo(a: int): string = ""
+
+  proc test(args: varargs[string, foo]) =
+    doAssert false
+
+  proc test(a: AObj) =
+    discard
+
+  let x = AObj()
+  test(x)
diff --git a/tests/misc/t9710.nim b/tests/misc/t9710.nim
new file mode 100644
index 000000000..c65cb7bf4
--- /dev/null
+++ b/tests/misc/t9710.nim
@@ -0,0 +1,6 @@
+discard """
+  matrix: "--debugger:native"
+"""
+# bug #9710
+for i in 1 || 200:
+  discard i
diff --git a/tests/misc/taddr.nim b/tests/misc/taddr.nim
new file mode 100644
index 000000000..64f95c7e3
--- /dev/null
+++ b/tests/misc/taddr.nim
@@ -0,0 +1,295 @@
+discard """
+  targets: "c cpp js"
+  matrix: "; -d:release"
+"""
+
+type T = object
+  x: int
+  s: string
+
+var obj: T
+var fieldAddr = addr(obj.x)
+var objAddr = addr(obj)
+
+# Integer tests
+var field = fieldAddr[]
+doAssert field == 0
+
+var objDeref = objAddr[]
+doAssert objDeref.x == 0
+
+# Change value
+obj.x = 42
+
+doAssert field == 0
+doAssert objDeref.x == 0
+
+field = fieldAddr[]
+objDeref = objAddr[]
+
+doAssert field == 42
+doAssert objDeref.x == 42
+
+# String tests
+obj.s = "lorem ipsum dolor sit amet"
+when defined(gcArc) or defined(gcOrc):
+  prepareMutation(obj.s)
+
+
+var indexAddr = addr(obj.s[2])
+
+doAssert indexAddr[] == 'r'
+
+indexAddr[] = 'd'
+
+doAssert indexAddr[] == 'd'
+
+doAssert obj.s == "lodem ipsum dolor sit amet"
+
+# Bug #2148
+var x: array[2, int]
+var y = addr x[1]
+
+y[] = 12
+doAssert(x[1] == 12)
+
+type
+  Foo = object
+    bar: int
+
+var foo: array[2, Foo]
+var z = addr foo[1]
+
+z[].bar = 12345
+doAssert(foo[1].bar == 12345)
+
+var t : tuple[a, b: int]
+var pt = addr t[1]
+pt[] = 123
+doAssert(t.b == 123)
+
+#block: # Test "untyped" pointer.
+proc testPtr(p: pointer, a: int) =
+  doAssert(a == 5)
+  (cast[ptr int](p))[] = 124
+var i = 123
+testPtr(addr i, 5)
+doAssert(i == 124)
+
+var someGlobal = 5
+proc getSomeGlobalPtr(): ptr int = addr someGlobal
+let someGlobalPtr = getSomeGlobalPtr()
+doAssert(someGlobalPtr[] == 5)
+someGlobalPtr[] = 10
+doAssert(someGlobal == 10)
+
+block:
+  # bug #14576
+  # lots of these used to give: Error: internal error: genAddr: 2
+  proc byLent[T](a: T): lent T = a
+  proc byPtr[T](a: T): ptr T = a.addr
+
+  block:
+    let a = (10,11)
+    let (x,y) = byLent(a)
+    doAssert (x,y) == a
+
+  block: # (with -d:release) bug #14578
+    let a = 10
+    doAssert byLent(a) == 10
+    let a2 = byLent(a)
+    doAssert a2 == 10
+
+  block:
+    let a = [11,12]
+    doAssert byLent(a) == [11,12] # bug #15958
+    let a2 = (11,)
+    doAssert byLent(a2) == (11,)
+
+  block:
+    proc byLent2[T](a: seq[T]): lent T = a[1]
+    var a = @[20,21,22]
+    doAssert byLent2(a) == 21
+
+  block: # sanity checks
+    proc bar[T](a: var T): var T = a
+    var a = (10, 11)
+    let (k,v) = bar(a)
+    doAssert (k, v) == a
+    doAssert k == 10
+    bar(a)[0]+=100
+    doAssert a == (110, 11)
+    var a2 = 12
+    doAssert bar(a2) == a2
+    bar(a2).inc
+    doAssert a2 == 13
+
+  block: # pending bug #15959
+    when false:
+      proc byLent2[T](a: T): lent type(a[0]) = a[0]
+
+proc test14420() = # bug #14420
+  # s/proc/template/ would hit bug #16005
+  block:
+    type Foo = object
+      x: float
+
+    proc fn(a: var Foo): var float =
+      ## WAS: discard <- turn this into a comment (or a `discard`) and error disappears
+      # result = a.x # this works
+      a.x #  WAS: Error: limited VM support for 'addr'
+
+    proc fn2(a: var Foo): var float =
+      result = a.x # this works
+      a.x #  WAS: Error: limited VM support for 'addr'
+
+    var a = Foo()
+    discard fn(a)
+    discard fn2(a)
+
+  block:
+    proc byLent2[T](a: T): lent T =
+      runnableExamples: discard
+      a
+    proc byLent3[T](a: T): lent T =
+      runnableExamples: discard
+      result = a
+    var a = 10
+    let x3 = byLent3(a) # works
+    let x2 = byLent2(a) # WAS: Error: internal error: genAddr: nkStmtListExpr
+
+  block:
+    type MyOption[T] = object
+      case has: bool
+      of true:
+        value: T
+      of false:
+        discard
+    func some[T](val: T): MyOption[T] =
+      result = MyOption[T](has: true, value: val)
+    func get[T](opt: MyOption[T]): lent T =
+      doAssert opt.has
+      # result = opt.value # this was ok
+      opt.value # this had the bug
+    let x = some(10)
+    doAssert x.get() == 10
+
+template test14339() = # bug #14339
+  block:
+    type
+      Node = ref object
+        val: int
+    proc bar(c: Node): var int =
+      var n = c # was: Error: limited VM support for 'addr'
+      c.val
+    var a = Node()
+    discard a.bar()
+  block:
+    type
+      Node = ref object
+        val: int
+    proc bar(c: Node): var int =
+      var n = c
+      doAssert n.val == n[].val
+      n.val
+    var a = Node(val: 3)
+    a.bar() = 5
+    when nimvm:
+      doAssert a.val == 5
+    else:
+      when not defined(js): # pending bug #16003
+        doAssert a.val == 5
+
+template testStatic15464() = # bug #15464
+  proc access(s: var seq[char], i: int): var char = s[i]
+  proc access(s: var string, i: int): var char = s[i]
+  static:
+    var s = @['a', 'b', 'c']
+    access(s, 2) = 'C'
+    doAssert access(s, 2) == 'C'
+  static:
+    var s = "abc"
+    access(s, 2) = 'C'
+    doAssert access(s, 2) == 'C'
+
+proc test15464() = # bug #15464 (v2)
+  proc access(s: var seq[char], i: int): var char = s[i]
+  proc access(s: var string, i: int): var char = s[i]
+  block:
+    var s = @['a', 'b', 'c']
+    access(s, 2) = 'C'
+    doAssert access(s, 2) == 'C'
+  block:
+    var s = "abc"
+    access(s, 2) = 'C'
+    doAssert access(s, 2) == 'C'
+
+block: # bug #15939
+  block:
+    const foo = "foo"
+    proc proc1(s: var string) =
+      if s[^1] notin {'a'..'z'}:
+        s = ""
+    proc proc2(f: string): string =
+      result = f
+      proc1(result)
+    const bar = proc2(foo)
+    doAssert bar == "foo"
+
+template prepareMutationForOrc(x: string) =
+  when defined(gcArc) or defined(gcOrc):
+    when nimvm:
+      discard
+    else:
+      prepareMutation(x)
+
+proc test15939() = # bug #15939 (v2)
+  template fn(a) =
+    when typeof(a) is string:
+      prepareMutationForOrc(a)
+    let pa = a[0].addr
+    doAssert pa != nil
+    doAssert pa[] == 'a'
+    pa[] = 'x'
+    doAssert pa[] == 'x'
+    doAssert a == "xbc"
+    when not defined js: # otherwise overflows
+      let pa2 = cast[ptr char](cast[int](pa) + 1)
+      doAssert pa2[] == 'b'
+      pa2[] = 'B'
+      doAssert a == "xBc"
+
+  # mystring[ind].addr
+  var a = "abc"
+  fn(a)
+
+  # mycstring[ind].addr
+  template cstringTest =
+    var a2 = "abc"
+    prepareMutationForOrc(a2)
+    var b2 = a2.cstring
+    fn(b2)
+  when nimvm: cstringTest()
+  else: # can't take address of cstring element in js
+    when not defined(js): cstringTest()
+
+block: # bug #23499
+  template volatileStore[T](dest: ptr T, val: T) =
+    dest[] = val
+
+  proc foo =
+    var ctr = 0
+    volatileStore(addr ctr, 0)
+
+  foo()
+
+template main =
+  # xxx wrap all other tests here like that so they're also tested in VM
+  test14420()
+  test14339()
+  test15464()
+  test15939()
+
+testStatic15464()
+static: main()
+main()
diff --git a/tests/misc/tapp_lib_staticlib.nim b/tests/misc/tapp_lib_staticlib.nim
new file mode 100644
index 000000000..92c9acbc3
--- /dev/null
+++ b/tests/misc/tapp_lib_staticlib.nim
@@ -0,0 +1,27 @@
+discard """
+joinable: false
+"""
+
+# bug #16949
+
+when defined case1:
+  proc foo(): int {.exportc.} = 10
+elif defined case2:
+  proc foo(): int {.exportc, dynlib.} = 10
+elif defined caseMain:
+  proc foo(): int {.importc.}
+  doAssert foo() == 10
+else:
+  import stdtest/specialpaths
+  import std/[os, strformat, strutils, compilesettings]
+  proc runCmd(cmd: string) =
+    doAssert execShellCmd(cmd) == 0, $cmd
+  const
+    file = currentSourcePath
+    nim = getCurrentCompilerExe()
+    mode = querySetting(backend)
+  proc test(lib, options: string) =
+    runCmd fmt"{nim} {mode} -o:{lib} --nomain {options} -f {file}"
+    # runCmd fmt"{nim} r -b:{mode} --passl:{lib} -d:caseMain -f {file}" # pending https://github.com/nim-lang/Nim/pull/16945
+  test(buildDir / "libD20210205T172314.a", "--app:staticlib -d:nimLinkerWeakSymbols -d:case1")
+  test(buildDir / DynlibFormat % "D20210205T172720", "--app:lib -d:case2")
diff --git a/tests/misc/tcast.nim b/tests/misc/tcast.nim
index a8d1cf306..73196e76c 100644
--- a/tests/misc/tcast.nim
+++ b/tests/misc/tcast.nim
@@ -1,6 +1,7 @@
 discard """
   output: '''
 Hello World
+Hello World
 Hello World'''
   joinable: false
 """
@@ -8,7 +9,9 @@ type MyProc = proc() {.cdecl.}
 type MyProc2 = proc() {.nimcall.}
 type MyProc3 = proc() #{.closure.} is implicit
 
-proc testProc()  = echo "Hello World"
+proc testProc() {.exportc:"foo".} = echo "Hello World"
+
+template reject(x) = doAssert(not compiles(x))
 
 proc callPointer(p: pointer) =
   # can cast to proc(){.cdecl.}
@@ -16,9 +19,90 @@ proc callPointer(p: pointer) =
   # can cast to proc(){.nimcall.}
   let ffunc1 = cast[MyProc2](p)
   # cannot cast to proc(){.closure.}
-  doAssert(not compiles(cast[MyProc3](p)))
+  reject: cast[MyProc3](p)
 
   ffunc0()
   ffunc1()
 
+    # bug #5901
+  proc foo() {.importc.}
+  (cast[proc(a: int) {.cdecl.}](foo))(5)
+
 callPointer(cast[pointer](testProc))
+
+reject: discard cast[enum](0)
+proc a = echo "hi"
+
+reject: discard cast[ptr](a)
+
+# bug #15623
+block:
+  if false:
+    let x = cast[ptr int](nil)
+    echo x[]
+
+block:
+  if false:
+    var x: ref int = nil
+    echo cast[ptr int](x)[]
+
+block:
+  doAssert cast[int](cast[ptr int](nil)) == 0
+
+block:
+  var x: ref int = nil
+  doAssert cast[int](cast[ptr int](x)) == 0
+
+block: # cast of nil
+  block:
+    static:
+      let a = cast[pointer](nil)
+      doAssert a.repr == "nil"
+
+  block:
+    static:
+      doAssert cast[ptr int](nil).repr == "nil"
+
+  block:
+    const str = cast[ptr int](nil)
+    static:
+      doAssert str.repr == "nil"
+
+  block:
+    static:
+      doAssert cast[ptr int](nil).repr == "nil"
+
+  block:
+    static:
+      doAssert cast[RootRef](nil).repr == "nil"
+
+  when false: # xxx bug #15730, not fixed yet
+    block:
+      static:
+        doAssert cast[cstring](nil).repr == "nil"
+
+template main() =
+  # xxx move all under here to get tested in VM
+  block: # cast of enum
+    type Koo = enum k1, k2
+    type Goo = enum g1, g2
+    type Boo = enum b1 = -1, b2, b3, b4
+    type Coo = enum c1 = -1i8, c2, c3, c4
+    when nimvm:
+      # xxx: Error: VM does not support 'cast' from tyEnum to tyEnum
+      discard
+    else:
+      doAssert cast[Koo](k2) == k2
+      doAssert cast[Goo](k2) == g2
+      doAssert cast[Goo](k2.ord) == g2
+
+      doAssert b3.ord == 1
+      doAssert cast[Koo](b3) == k2
+      doAssert cast[Boo](k2) == b3
+
+      doAssert c3.ord == 1
+      doAssert cast[Koo](c3) == k2
+      doAssert cast[Coo](k2) == c3
+
+static: main()
+main()
diff --git a/tests/misc/tconv.nim b/tests/misc/tconv.nim
index f7d15b0b5..90fae868b 100644
--- a/tests/misc/tconv.nim
+++ b/tests/misc/tconv.nim
@@ -1,5 +1,14 @@
+discard """
+  matrix: "--warningAsError:EnumConv --warningAsError:CStringConv"
+"""
+
+from std/enumutils import items  # missing from the example code
+from std/sequtils import toSeq
+
 template reject(x) =
-    static: assert(not compiles(x))
+  static: doAssert(not compiles(x))
+template accept(x) =
+  static: doAssert(compiles(x))
 
 reject:
     const x = int8(300)
@@ -55,3 +64,80 @@ block: # issue 3766
     proc r(x: static[R]) =
       echo x
     r 3.R
+
+
+block: # https://github.com/nim-lang/RFCs/issues/294
+  type Koo = enum k1, k2
+  type Goo = enum g1, g2
+
+  accept: Koo(k2)
+  accept: k2.Koo
+  accept: k2.int.Goo
+
+  reject: Goo(k2)
+  reject: k2.Goo
+  reject: k2.string
+
+  {.push warningAsError[EnumConv]:off.}
+  discard Goo(k2)
+  accept: Goo(k2)
+  accept: k2.Goo
+  reject: k2.string
+  {.pop.}
+
+  reject: Goo(k2)
+  reject: k2.Goo
+
+  type KooRange = range[k2..k2]
+  accept: KooRange(k2)
+  accept: k2.KooRange
+  let k2ranged: KooRange = k2
+  accept: Koo(k2ranged)
+  accept: k2ranged.Koo
+
+reject:
+  # bug #18550
+  proc f(c: char): cstring =
+    var x = newString(109*1024*1024)
+    x[0] = c
+    x
+
+{.push warning[AnyEnumConv]:on, warningAsError[AnyEnumConv]:on.}
+
+reject:
+  type
+    Foo = enum
+      one
+      three
+
+  var va = 2
+  var vb = va.Foo
+
+{.pop.}
+
+{.push warningAsError[HoleEnumConv]:on.}
+
+reject:
+  # bug #12815
+  type
+    Hole = enum
+      one = 1
+      three = 3
+
+  var va = 2
+  var vb = va.Hole
+
+block: # bug #22844
+  type
+    A = enum
+      a0 = 2
+      a1 = 4
+      a2
+    B[T] = enum
+      b0 = 2
+      b1 = 4
+
+  doAssert A.toSeq == [a0, a1, a2]
+  doAssert B[float].toSeq == [B[float].b0, B[float].b1]
+
+{.pop.}
diff --git a/tests/usingstmt/tusingstatement.nim b/tests/misc/tcsharpusingstatement.nim
index 6e4998892..1ce553895 100644
--- a/tests/usingstmt/tusingstatement.nim
+++ b/tests/misc/tcsharpusingstatement.nim
@@ -38,7 +38,7 @@ macro autoClose(args: varargs[untyped]): untyped =
       varAssignment.add(varValue)
       variables.add(varAssignment)
 
-      closingCalls.add(newCall(!"close", varName))
+      closingCalls.add(newCall(newIdentNode("close"), varName))
     else:
       error "Using statement: Unexpected expression. Got " &
         $args[i].kind & " instead of assignment."
@@ -49,25 +49,13 @@ macro autoClose(args: varargs[untyped]): untyped =
   var finallyBlock = newNimNode(nnkStmtList)
   finallyBlock.add(closingCalls)
 
-  # XXX: Use a template here once getAst is working properly
-  var targetAst = parseStmt"""block:
-    var
-      x = foo()
-      y = bar()
-
-    try:
-      body()
-
-    finally:
-      close x
-      close y
-  """
-
-  targetAst[0][1][0] = varSection
-  targetAst[0][1][1][0] = body
-  targetAst[0][1][1][1][0] = finallyBlock
-
-  result = targetAst
+  result = quote do:
+    block:
+      `varSection`
+      try:
+        `body`
+      finally:
+        `finallyBlock`
 
 type
   TResource* = object
diff --git a/tests/misc/tdangerisrelease.nim b/tests/misc/tdangerisrelease.nim
new file mode 100644
index 000000000..e1854dca5
--- /dev/null
+++ b/tests/misc/tdangerisrelease.nim
@@ -0,0 +1,14 @@
+discard """
+  cmd: "nim c $options -r $file"
+  matrix: "-d:danger; -d:release"
+  output: '''
+a
+b
+c
+'''
+"""
+
+echo "a"
+when defined(release):
+  echo "b"
+echo "c"
diff --git a/tests/misc/tdefine.nim b/tests/misc/tdefine.nim
index 1378b8901..f3fa4711f 100644
--- a/tests/misc/tdefine.nim
+++ b/tests/misc/tdefine.nim
@@ -1,12 +1,23 @@
 discard """
 joinable: false
-cmd: "nim c -d:booldef -d:booldef2=false -d:intdef=2 -d:strdef=foobar -r $file"
+cmd: "nim c $options -d:booldef -d:booldef2=false -d:intdef=2 -d:strdef=foobar -d:namespaced.define=false -d:double.namespaced.define -r $file"
+matrix: "; -d:useGenericDefine"
 """
 
-const booldef {.booldefine.} = false
-const booldef2 {.booldefine.} = true
-const intdef {.intdefine.} = 0
-const strdef {.strdefine.} = ""
+when defined(useGenericDefine):
+  {.pragma: booldefine2, define.}
+  {.pragma: intdefine2, define.}
+  {.pragma: strdefine2, define.}
+else:
+  
+  {.pragma: booldefine2, booldefine.}
+  {.pragma: intdefine2, intdefine.}
+  {.pragma: strdefine2, strdefine.}
+
+const booldef {.booldefine2.} = false
+const booldef2 {.booldefine2.} = true
+const intdef {.intdefine2.} = 0
+const strdef {.strdefine2.} = ""
 
 doAssert defined(booldef)
 doAssert defined(booldef2)
@@ -16,3 +27,51 @@ doAssert booldef
 doAssert not booldef2
 doAssert intdef == 2
 doAssert strdef == "foobar"
+
+when defined(useGenericDefine):
+  block:
+    const uintdef {.define: "intdef".}: uint = 17
+    doAssert intdef == int(uintdef)
+    const cstrdef {.define: "strdef".}: cstring = "not strdef"
+    doAssert $cstrdef == strdef
+    type FooBar = enum foo, bar, foobar
+    const enumdef {.define: "strdef".} = foo
+    doAssert $enumdef == strdef
+    doAssert enumdef == foobar
+
+# Intentionally not defined from command line
+const booldef3 {.booldefine2.} = true
+const intdef2 {.intdefine2.} = 1
+const strdef2 {.strdefine2.} = "abc"
+type T = object
+  when booldef3:
+    field1: int
+  when intdef2 == 1:
+    field2: int
+  when strdef2 == "abc":
+    field3: int
+
+doAssert not defined(booldef3)
+doAssert not defined(intdef2)
+doAssert not defined(strdef2)
+discard T(field1: 1, field2: 2, field3: 3)
+
+doAssert defined(namespaced.define)
+const `namespaced.define` {.booldefine2.} = true
+doAssert not `namespaced.define`
+when defined(useGenericDefine):
+  const aliasToNamespacedDefine {.define: "namespaced.define".} = not `namespaced.define`
+else:
+  const aliasToNamespacedDefine {.booldefine: "namespaced.define".} = not `namespaced.define`
+doAssert aliasToNamespacedDefine == `namespaced.define`
+
+doAssert defined(double.namespaced.define)
+const `double.namespaced.define` {.booldefine2.} = false
+doAssert `double.namespaced.define`
+when defined(useGenericDefine):
+  const aliasToDoubleNamespacedDefine {.define: "double.namespaced.define".} = not `double.namespaced.define`
+else:
+  const aliasToDoubleNamespacedDefine {.booldefine: "double.namespaced.define".} = not `double.namespaced.define`
+doAssert aliasToDoubleNamespacedDefine == `double.namespaced.define`
+
+doAssert not defined(namespaced.butnotdefined)
diff --git a/tests/misc/temptyecho.nim b/tests/misc/temptyecho.nim
deleted file mode 100644
index 5f1aa6515..000000000
--- a/tests/misc/temptyecho.nim
+++ /dev/null
@@ -1,2 +0,0 @@
-echo()
-
diff --git a/tests/misc/tevents.nim b/tests/misc/tevents.nim
deleted file mode 100644
index 045c9fc5b..000000000
--- a/tests/misc/tevents.nim
+++ /dev/null
@@ -1,48 +0,0 @@
-discard """
-output: '''
-HandlePrintEvent: Output -> Handled print event
-HandlePrintEvent2: Output -> printing for ME
-HandlePrintEvent2: Output -> printing for ME
-'''
-"""
-
-import events
-
-type
-  PrintEventArgs = object of EventArgs
-    user*: string
-
-proc handleprintevent*(e: EventArgs) =
-    write(stdout, "HandlePrintEvent: Output -> Handled print event\n")
-
-proc handleprintevent2*(e: EventArgs) =
-    var args: PrintEventArgs = PrintEventArgs(e)
-    write(stdout, "HandlePrintEvent2: Output -> printing for " & args.user)
-
-var ee = initEventEmitter()
-
-var eventargs: PrintEventArgs
-eventargs.user = "ME\n"
-
-##method one test
-
-ee.on("print", handleprintevent)
-ee.on("print", handleprintevent2)
-
-ee.emit("print", eventargs)
-
-##method two test
-
-type
-  SomeObject = object of RootObj
-    printEvent: EventHandler
-
-var obj: SomeObject
-obj.printEvent = initEventHandler("print")
-obj.printEvent.addHandler(handleprintevent2)
-
-ee.emit(obj.printEvent, eventargs)
-
-obj.printEvent.removeHandler(handleprintevent2)
-
-ee.emit(obj.printEvent, eventargs)
diff --git a/tests/misc/tgenconstraints.nim b/tests/misc/tgenconstraints.nim
deleted file mode 100644
index 829da5173..000000000
--- a/tests/misc/tgenconstraints.nim
+++ /dev/null
@@ -1,31 +0,0 @@
-discard """
-  errormsg: "cannot instantiate T2"
-  file: "tgenconstraints.nim"
-  line: 25
-  disabled: true
-"""
-
-type
-  T1[T: int|string] = object
-    x: T
-
-  T2[T: Ordinal] = object
-    x: T
-
-var x1: T1[int]
-var x2: T1[string]
-var x3: T2[int]
-
-proc foo[T](x: T): T2[T] {.discardable.} =
-  var o: T1[T]
-
-foo(10)
-
-# XXX: allow type intersections in situation like this
-proc bar(x: int|TNumber): T1[type(x)] {.discardable.} =
-  when type(x) is TNumber:
-    var o: T2[type(x)]
-
-bar "test"
-bar 100
-bar 1.1
diff --git a/tests/misc/theaproots.nim b/tests/misc/theaproots.nim
index 1ea3c86b9..2dd345254 100644
--- a/tests/misc/theaproots.nim
+++ b/tests/misc/theaproots.nim
@@ -28,7 +28,7 @@ proc acc(x: var Foo): var ref Bar =
 
 proc test(maybeFoo: var Foo,
           maybeSeq: var seq[ref Bar],
-          bars: var openarray[ref Bar],
+          bars: var openArray[ref Bar],
           maybeTup: var Tup) =
   var bb: ref Bar
   maybeFoo.rmaybe = bb
diff --git a/tests/misc/tinvalidnewseq.nim b/tests/misc/tinvalidnewseq.nim
index dec00fd4a..7a95db020 100644
--- a/tests/misc/tinvalidnewseq.nim
+++ b/tests/misc/tinvalidnewseq.nim
@@ -13,7 +13,7 @@ proc parseURL(url: string): TURL =
   var pattern: string = r"([a-zA-Z]+://)?(\w+?\.)?(\w+)(\.\w+)(:[0-9]+)?(/.+)?"
   var m: array[0..6, string] #Array with the matches
   newSeq(m, 7) #ERROR
-  discard regexprs.match(url, re(pattern), m)
+  discard re.match(url, re(pattern), m)
 
   result = (protocol: m[1], subdomain: m[2], domain: m[3] & m[4],
             port: m[5], path: m[6].split('/'))
diff --git a/tests/misc/tjoinable.nim b/tests/misc/tjoinable.nim
new file mode 100644
index 000000000..f23fca0d4
--- /dev/null
+++ b/tests/misc/tjoinable.nim
@@ -0,0 +1,3 @@
+# checks that megatest allows duplicate names, see also `tests/testament/tjoinable.nim`
+doAssert defined(testing)
+doAssert defined(nimMegatest)
diff --git a/tests/misc/tnoforward.nim b/tests/misc/tnoforward.nim
index 3e96e3489..b6a71897a 100644
--- a/tests/misc/tnoforward.nim
+++ b/tests/misc/tnoforward.nim
@@ -1,5 +1,5 @@
 discard """
-  disabled: true
+  output: "10"
 """
 
 # {. noforward: on .}
diff --git a/tests/misc/tparseopt.nim b/tests/misc/tparseopt.nim
index 25ce77816..47be05bac 100644
--- a/tests/misc/tparseopt.nim
+++ b/tests/misc/tparseopt.nim
@@ -22,6 +22,15 @@ kind: cmdShortOption	key:val  --  r:0
 kind: cmdShortOption	key:val  --  l:
 kind: cmdShortOption	key:val  --  r:4
 kind: cmdLongOption	key:val  --  debug:
+cmdShortOption key: v value: ''
+cmdArgument key: ABC value: ''
+cmdShortOption key: v value: 'ABC'
+cmdShortOption key: v value: ''
+cmdArgument key: ABC value: ''
+cmdShortOption key: v value: ''
+cmdArgument key: ABC value: ''
+cmdShortOption key: j value: '4'
+cmdArgument key: ok value: ''
 '''
 joinable: false
 """
@@ -71,7 +80,7 @@ else:
 
   import osproc, os, strutils
   from stdtest/specialpaths import buildDir
-  import "../.." / compiler/unittest_light
+  import stdtest/unittest_light
 
   block: # fix #9951
     template runTest(parseoptCustom) =
@@ -121,3 +130,27 @@ arg 3 ai.len:4 :{a4"b}
 arg 4 ai.len:4 :{a5'b}
 arg 5 ai.len:4 :{a6\b}
 arg 6 ai.len:4 :{a7'b}"""
+
+
+
+  block:
+    let args = @["-v", "ABC"]
+    var p = parseopt.initOptParser(args, shortnoVal = {'n'}, longnoVal = @["novalue"])
+    for kind, key, val in parseopt.getopt(p):
+      echo kind," key: ", key, " value: '", val, "'"
+
+    var r = parseopt.initOptParser(@["-v ABC"], shortnoVal = {'n'}, longnoVal = @["novalue"])
+    for kind, key, val in parseopt.getopt(r):
+      echo kind," key: ", key, " value: '", val, "'"
+
+    var s = parseopt.initOptParser("-v ABC", shortnoVal = {'v'}, longnoVal = @["novalue"])
+    for kind, key, val in parseopt.getopt(s):
+      echo kind," key: ", key, " value: '", val, "'"
+
+    var m = parseopt.initOptParser("-v ABC", shortnoVal = {'n'}, longnoVal = @["novalue"])
+    for kind, key, val in parseopt.getopt(m):
+      echo kind," key: ", key, " value: '", val, "'"
+
+    var n = parseopt.initOptParser("-j4 ok", shortnoVal = {'n'}, longnoVal = @["novalue"])
+    for kind, key, val in parseopt.getopt(n):
+      echo kind," key: ", key, " value: '", val, "'"
diff --git a/tests/misc/tradix.nim b/tests/misc/tradix.nim
index 1773a9609..f4fb56849 100644
--- a/tests/misc/tradix.nim
+++ b/tests/misc/tradix.nim
@@ -40,8 +40,8 @@ type
   TRadixNode {.pure, inheritable.} = object
     kind: TRadixNodeKind
   TRadixNodeLinear = object of TRadixNode
-    len: int8
-    keys: array[0..31, int8]
+    len: uint8
+    keys: array[0..31, uint8]
     vals: array[0..31, PRadixNode]
 
   TRadixNodeFull = object of TRadixNode
@@ -49,8 +49,8 @@ type
   TRadixNodeLeafBits = object of TRadixNode
     b: array[0..7, int]
   TRadixNodeLeafLinear = object of TRadixNode
-    len: int8
-    keys: array[0..31, int8]
+    len: uint8
+    keys: array[0..31, uint8]
 
 var
   root: PRadixNode
@@ -59,8 +59,8 @@ proc searchInner(r: PRadixNode, a: int): PRadixNode =
   case r.kind
   of rnLinear:
     var x = cast[ptr TRadixNodeLinear](r)
-    for i in 0..ze(x.len)-1:
-      if ze(x.keys[i]) == a: return x.vals[i]
+    for i in 0..int(x.len)-1:
+      if int(x.keys[i]) == a: return x.vals[i]
   of rnFull:
     var x = cast[ptr TRadixNodeFull](r)
     return x.b[a]
@@ -87,8 +87,8 @@ proc searchLeaf(r: PRadixNode, a: int): bool =
     return testBit(x.b[a /% BitsPerUnit], a)
   of rnLeafLinear:
     var x = cast[ptr TRadixNodeLeafLinear](r)
-    for i in 0..ze(x.len)-1:
-      if ze(x.keys[i]) == a: return true
+    for i in 0..int(x.len)-1:
+      if int(x.keys[i]) == a: return true
   else: assert(false)
 
 proc exclLeaf(r: PRadixNode, a: int) =
@@ -98,9 +98,9 @@ proc exclLeaf(r: PRadixNode, a: int) =
     resetBit(x.b[a /% BitsPerUnit], a)
   of rnLeafLinear:
     var x = cast[ptr TRadixNodeLeafLinear](r)
-    var L = ze(x.len)
+    var L = int(x.len)
     for i in 0..L-1:
-      if ze(x.keys[i]) == a:
+      if int(x.keys[i]) == a:
         x.keys[i] = x.keys[L-1]
         dec(x.len)
         return
@@ -131,8 +131,8 @@ proc addLeaf(r: var PRadixNode, a: int): bool =
     # a linear node:
     var x = cast[ptr TRadixNodeLinear](alloc0(sizeof(TRadixNodeLinear)))
     x.kind = rnLeafLinear
-    x.len = 1'i8
-    x.keys[0] = toU8(a)
+    x.len = 1'u8
+    x.keys[0] = uint8(a)
     r = x
     return false # not already in set
   case r.kind
@@ -141,18 +141,18 @@ proc addLeaf(r: var PRadixNode, a: int): bool =
     return testOrSetBit(x.b[a /% BitsPerUnit], a)
   of rnLeafLinear:
     var x = cast[ptr TRadixNodeLeafLinear](r)
-    var L = ze(x.len)
+    var L = int(x.len)
     for i in 0..L-1:
-      if ze(x.keys[i]) == a: return true
+      if int(x.keys[i]) == a: return true
     if L <= high(x.keys):
-      x.keys[L] = toU8(a)
+      x.keys[L] = uint8(a)
       inc(x.len)
     else:
       # transform into a full node:
       var y = cast[ptr TRadixNodeLeafBits](alloc0(sizeof(TRadixNodeLeafBits)))
       y.kind = rnLeafBits
-      for i in 0..ze(x.len)-1:
-        var u = ze(x.keys[i])
+      for i in 0..int(x.len)-1:
+        var u = int(x.keys[i])
         setBit(y.b[u /% BitsPerUnit], u)
       setBit(y.b[a /% BitsPerUnit], a)
       dealloc(r)
@@ -167,26 +167,26 @@ proc addInner(r: var PRadixNode, a: int, d: int): bool =
     # a linear node:
     var x = cast[ptr TRadixNodeLinear](alloc0(sizeof(TRadixNodeLinear)))
     x.kind = rnLinear
-    x.len = 1'i8
-    x.keys[0] = toU8(k)
+    x.len = 1'u8
+    x.keys[0] = uint8(k)
     r = x
     return addInner(x.vals[0], a, d-8)
   case r.kind
   of rnLinear:
     var x = cast[ptr TRadixNodeLinear](r)
-    var L = ze(x.len)
+    var L = int(x.len)
     for i in 0..L-1:
-      if ze(x.keys[i]) == k: # already exists
+      if int(x.keys[i]) == k: # already exists
         return addInner(x.vals[i], a, d-8)
     if L <= high(x.keys):
-      x.keys[L] = toU8(k)
+      x.keys[L] = uint8(k)
       inc(x.len)
       return addInner(x.vals[L], a, d-8)
     else:
       # transform into a full node:
       var y = cast[ptr TRadixNodeFull](alloc0(sizeof(TRadixNodeFull)))
       y.kind = rnFull
-      for i in 0..L-1: y.b[ze(x.keys[i])] = x.vals[i]
+      for i in 0..L-1: y.b[int(x.keys[i])] = x.vals[i]
       dealloc(r)
       r = y
       return addInner(y.b[k], a, d-8)
@@ -211,8 +211,8 @@ iterator innerElements(r: PRadixNode): tuple[prefix: int, n: PRadixNode] =
           yield (i, r.b[i])
     of rnLinear:
       var r = cast[ptr TRadixNodeLinear](r)
-      for i in 0..ze(r.len)-1:
-        yield (ze(r.keys[i]), r.vals[i])
+      for i in 0..int(r.len)-1:
+        yield (int(r.keys[i]), r.vals[i])
     else: assert(false)
 
 iterator leafElements(r: PRadixNode): int =
@@ -228,8 +228,8 @@ iterator leafElements(r: PRadixNode): int =
               yield i*BitsPerUnit+j
     of rnLeafLinear:
       var r = cast[ptr TRadixNodeLeafLinear](r)
-      for i in 0..ze(r.len)-1:
-        yield ze(r.keys[i])
+      for i in 0..int(r.len)-1:
+        yield int(r.keys[i])
     else: assert(false)
 
 iterator elements*(r: PRadixNode): ByteAddress {.inline.} =
diff --git a/tests/misc/trfc405.nim b/tests/misc/trfc405.nim
new file mode 100644
index 000000000..0828879ee
--- /dev/null
+++ b/tests/misc/trfc405.nim
@@ -0,0 +1,112 @@
+
+{.experimental: "flexibleOptionalParams".}
+
+# https://github.com/nim-lang/RFCs/issues/405
+
+template main =
+  template fn1(a = 1, b = 2, body): auto = (a, b, astToStr(body))
+  let a1 = fn1(10, 20):
+    foo
+  doAssert a1 == (10, 20, "\nfoo")
+
+  template fn2(a = 1, b = 2, body): auto = (a, b, astToStr(body))
+  let a2 = fn2(a = 10): foo
+  doAssert a2 == (10, 2, "\nfoo")
+  let a2b = fn2(b = 20): foo
+  doAssert a2b == (1, 20, "\nfoo")
+
+  template fn3(x: int, a = 1, b = 2, body): auto = (a, b, astToStr(body))
+  let a3 = fn3(3, 10, 20): foo
+  doAssert a3 == (10, 20, "\nfoo")
+  let a3b = fn3(3, a = 10): foo
+  doAssert a3b == (10, 2, "\nfoo")
+
+  template fn4(x: int, y: int, body): auto = (x, y, astToStr(body))
+  let a4 = fn4(1, 2): foo
+  doAssert a4 == (1, 2, "\nfoo")
+
+  template fn5(x = 1, y = 2, body: untyped = 3): auto = (x, y, astToStr(body))
+  doAssert compiles(fn5(1, 2, foo))
+  doAssert not compiles(fn5(1, foo))
+
+  block:
+    # with an overload
+    var witness = 0
+    template fn6() = discard
+    template fn6(procname: string, body: untyped): untyped = witness.inc
+    fn6("abc"): discard
+    assert witness == 1
+
+  block:
+    # with overloads
+    var witness = 0
+    template fn6() = discard
+    template fn6(a: int) = discard
+    template fn6(procname: string, body: untyped): untyped = witness.inc
+    fn6("abc"): discard
+    assert witness == 1
+
+    template fn6(b = 1.5, body: untyped): untyped = witness.inc
+    fn6(1.3): discard
+    assert witness == 2
+
+  block:
+    var witness = 0
+    template fn6(a: int) = discard
+    template fn6(a: string) = discard
+    template fn6(ignore: string, b = 1.5, body: untyped): untyped = witness.inc
+    fn6(""):
+      foobar1
+      foobar2
+    doAssert witness == 1
+    fn6(""): discard
+    doAssert witness == 2
+
+  block: # multi block args
+    template fn8(a = 1, b = 2, body1: untyped, body2: untyped): auto = (a, b, astToStr(body1), astToStr(body2))
+    let a1 = fn8():
+      foobar1
+      foobar2
+    do:
+      foobar3
+      foobar4
+    doAssert a1 == (1, 2, "\nfoobar1\nfoobar2", "\nfoobar3\nfoobar4")
+
+    let a2 = fn8(b = 20):
+      foobar1
+      foobar2
+    do:
+      foobar3
+      foobar4
+    doAssert a2 == (1, 20, "\nfoobar1\nfoobar2", "\nfoobar3\nfoobar4")
+  
+  block: # issue #19015
+    template hi(a: untyped, b: varargs[untyped]): untyped =
+      a
+
+    var worked = false
+    hi:
+      worked = true
+    doAssert worked
+    worked = false
+    hi(doAssert(not worked)):
+      doesntCompile
+    hi(doAssert(not worked), doesntCompile, againDoesntCompile):
+      definitelyDoesntCompile
+
+    template hi2(a: bool, b: untyped, c: varargs[untyped]): untyped =
+      b
+      doAssert a
+
+    hi2 worked:
+      worked = true
+    doAssert worked
+    hi2 worked, doAssert(worked):
+      doesntCompile
+    hi2 worked, doAssert(worked), doesntCompile, againDoesntCompile:
+      definitelyDoesntCompile
+    hi2 worked, doAssert(worked), againDoesntCompile:
+      definitelyDoesntCompile
+
+static: main()
+main()
diff --git a/tests/misc/trunner.nim b/tests/misc/trunner.nim
new file mode 100644
index 000000000..6e5487d1b
--- /dev/null
+++ b/tests/misc/trunner.nim
@@ -0,0 +1,444 @@
+discard """
+  targets: "c cpp"
+  joinable: false
+"""
+
+## tests that don't quite fit the mold and are easier to handle via `execCmdEx`
+## A few others could be added to here to simplify code.
+## Note: this test is a bit slow but tests a lot of things; please don't disable.
+## Note: if needed, we could use `matrix: "-d:case1; -d:case2"` to split this
+## into several independent tests while retaining the common test helpers.
+
+import std/[strformat,os,osproc,unittest,compilesettings]
+from std/sequtils import toSeq,mapIt
+from std/algorithm import sorted
+import stdtest/[specialpaths, unittest_light]
+from std/private/globs import nativeToUnixPath
+from strutils import startsWith, strip, removePrefix
+from std/sugar import dup
+import "$lib/../compiler/nimpaths"
+
+proc isDots(a: string): bool =
+  ## test for `hintProcessing` dots
+  a.startsWith(".") and a.strip(chars = {'.'}) == ""
+
+const
+  nim = getCurrentCompilerExe()
+  mode = querySetting(backend)
+  nimcache = buildDir / "nimcacheTrunner"
+    # instead of `querySetting(nimcacheDir)`, avoids stomping on other parallel tests
+
+proc runNimCmd(file, options = "", rtarg = ""): auto =
+  let fileabs = testsDir / file.unixToNativePath
+  # doAssert fileabs.fileExists, fileabs # disabled because this allows passing `nim r --eval:code fakefile`
+  let cmd = fmt"{nim} {mode} --hint:all:off {options} {fileabs} {rtarg}"
+  result = execCmdEx(cmd)
+  when false: # for debugging
+    echo cmd
+    echo result[0] & "\n" & $result[1]
+
+proc runNimCmdChk(file, options = "", rtarg = "", status = 0): string =
+  let (ret, status2) = runNimCmd(file, options, rtarg = rtarg)
+  doAssert status2 == status, $(file, options, status, status2) & "\n" & ret
+  ret
+
+proc genShellCmd(filename: string): string =
+  let filename = filename.quoteShell
+  when defined(windows): "cmd /c " & filename # or "cmd /c " ?
+  else: "sh " & filename
+
+when defined(nimTrunnerFfi):
+  block: # mevalffi
+    when defined(openbsd):
+      #[
+      openbsd defines `#define stderr (&__sF[2])` which makes it cumbersome
+      for dlopen'ing inside `importcSymbol`. Instead of adding special rules
+      inside `importcSymbol` to handle this, we disable just the part that's
+      not working and will provide a more general, clean fix in future PR.
+      ]#
+      var opt = "-d:nimEvalffiStderrWorkaround"
+      let prefix = ""
+    else:
+      var opt = ""
+      let prefix = """
+hello world stderr
+hi stderr
+"""
+    let output = runNimCmdChk("vm/mevalffi.nim", fmt"{opt} --warnings:off --experimental:compiletimeFFI")
+    doAssert output == fmt"""
+{prefix}foo
+foo:100
+foo:101
+foo:102:103
+foo:102:103:104
+foo:0.03:asdf:103:105
+ret=[s1:foobar s2:foobar age:25 pi:3.14]
+""", output
+
+elif not defined(nimTestsTrunnerDebugging):
+  # don't run twice the same test with `nimTrunnerFfi`
+  # use `-d:nimTestsTrunnerDebugging` for debugging convenience when you want to just run 1 test
+  import std/strutils
+  import std/json
+  template check2(msg) = doAssert msg in output, output
+
+  block: # tests with various options `nim doc --project --index --docroot`
+    # regression tests for issues and PRS: #14376 #13223 #6583 ##13647
+    let file = testsDir / "nimdoc/sub/mmain.nim"
+    let mainFname = "mmain.html"
+    let htmldocsDirCustom = nimcache / "htmldocsCustom"
+    let docroot = testsDir / "nimdoc"
+    let options = [
+      0: "--project",
+      1: "--project --docroot",
+      2: "",
+      3: fmt"--outDir:{htmldocsDirCustom}",
+      4: fmt"--docroot:{docroot}",
+      5: "--project --useNimcache",
+      6: "--index:off",
+    ]
+
+    for i in 0..<options.len:
+      let htmldocsDir = case i
+      of 3: htmldocsDirCustom
+      of 5: nimcache / htmldocsDirname
+      else: file.parentDir / htmldocsDirname
+
+      var cmd = fmt"{nim} doc --index:on --filenames:abs --hint:successX:on --nimcache:{nimcache} {options[i]} {file}"
+      removeDir(htmldocsDir)
+      let (outp, exitCode) = execCmdEx(cmd)
+      check exitCode == 0
+      let ret = toSeq(walkDirRec(htmldocsDir, relative=true)).mapIt(it.nativeToUnixPath).sorted.join("\n")
+      let context = $(i, ret, cmd)
+      case i
+      of 0,5:
+        let htmlFile = htmldocsDir/mainFname
+        check htmlFile in outp # sanity check for `hintSuccessX`
+        assertEquals ret, fmt"""
+{dotdotMangle}/imp.html
+{dotdotMangle}/imp.idx
+{docHackJsFname}
+imp.html
+imp.idx
+imp2.html
+imp2.idx
+{mainFname}
+mmain.idx
+{nimdocOutCss}
+{theindexFname}""", context
+      of 1: assertEquals ret, fmt"""
+{docHackJsFname}
+{nimdocOutCss}
+tests/nimdoc/imp.html
+tests/nimdoc/imp.idx
+tests/nimdoc/sub/imp.html
+tests/nimdoc/sub/imp.idx
+tests/nimdoc/sub/imp2.html
+tests/nimdoc/sub/imp2.idx
+tests/nimdoc/sub/{mainFname}
+tests/nimdoc/sub/mmain.idx
+{theindexFname}"""
+      of 2, 3: assertEquals ret, fmt"""
+{docHackJsFname}
+{mainFname}
+mmain.idx
+{nimdocOutCss}""", context
+      of 4: assertEquals ret, fmt"""
+{docHackJsFname}
+{nimdocOutCss}
+sub/{mainFname}
+sub/mmain.idx""", context
+      of 6: assertEquals ret, fmt"""
+{mainFname}
+{nimdocOutCss}""", context
+      else: doAssert false
+
+  block: # mstatic_assert
+    let (output, exitCode) = runNimCmd("ccgbugs/mstatic_assert.nim", "-d:caseBad")
+    check2 "sizeof(bool) == 2"
+    check exitCode != 0
+
+  block: # ABI checks
+    let file = "misc/msizeof5.nim"
+    block:
+      discard runNimCmdChk(file, "-d:checkAbi")
+    block:
+      let (output, exitCode) = runNimCmd(file, "-d:checkAbi -d:caseBad")
+      # on platforms that support _StaticAssert natively, errors will show full context, e.g.:
+      # error: static_assert failed due to requirement 'sizeof(unsigned char) == 8'
+      # "backend & Nim disagree on size for: BadImportcType{int64} [declared in mabi_check.nim(1, 6)]"
+      check2 "sizeof(unsigned char) == 8"
+      check2 "sizeof(struct Foo2) == 1"
+      check2 "sizeof(Foo5) == 16"
+      check2 "sizeof(Foo5) == 3"
+      check2 "sizeof(struct Foo6) == "
+      check exitCode != 0
+
+  import streams
+  block: # stdin input
+    let nimcmd = fmt"""{nim} r --hints:off - -firstparam "-second param" """
+    let expected = """@["-firstparam", "-second param"]"""
+    block:
+      let p = startProcess(nimcmd, options = {poEvalCommand})
+      p.inputStream.write("import os; echo commandLineParams()")
+      p.inputStream.close
+      var output = p.outputStream.readAll
+      let error = p.errorStream.readAll
+      doAssert p.waitForExit == 0
+      doAssert error.len == 0, $error
+      output.stripLineEnd
+      check output == expected
+      p.errorStream.close
+      p.outputStream.close
+
+    block:
+      when defined posix:
+        # xxx on windows, `poEvalCommand` should imply `/cmd`, (which should
+        # make this work), but currently doesn't
+        let cmd = fmt"""echo "import os; echo commandLineParams()" | {nimcmd}"""
+        var (output, exitCode) = execCmdEx(cmd)
+        output.stripLineEnd
+        check output == expected
+        doAssert exitCode == 0
+
+  block: # nim doc --backend:$backend --doccmd:$cmd
+    # test for https://github.com/nim-lang/Nim/issues/13129
+    # test for https://github.com/nim-lang/Nim/issues/13891
+    let file = testsDir / "nimdoc/m13129.nim"
+    for backend in fmt"{mode} js".split:
+      # pending #14343 this fails on windows: --doccmd:"-d:m13129Foo2 --hints:off"
+      let cmd = fmt"""{nim} doc -b:{backend} --nimcache:{nimcache} -d:m13129Foo1 "--doccmd:-d:m13129Foo2 --hints:off" --usenimcache --hints:off {file}"""
+      check execCmdEx(cmd) == (&"ok1:{backend}\nok2: backend: {backend}\n", 0)
+    # checks that --usenimcache works with `nim doc`
+    check fileExists(nimcache / "htmldocs/m13129.html")
+
+    block: # mak sure --backend works with `nim r`
+      let cmd = fmt"{nim} r --backend:{mode} --hints:off --nimcache:{nimcache} {file}"
+      check execCmdEx(cmd) == ("ok3\n", 0)
+
+  block: # nim jsondoc # bug #20132
+    let file = testsDir / "misc/mjsondoc.nim"
+    let output = "nimcache_tjsondoc.json"
+    defer: removeFile(output)
+    let (msg, exitCode) = execCmdEx(fmt"{nim} jsondoc -o:{output} {file}")
+    doAssert exitCode == 0, msg
+
+    let data = parseJson(readFile(output))["entries"]
+    doAssert data.len == 5
+    let doSomething = data[0]
+    doAssert doSomething["name"].getStr == "doSomething"
+    doAssert doSomething["type"].getStr == "skProc"
+    doAssert doSomething["line"].getInt == 1
+    doAssert doSomething["col"].getInt == 0
+    doAssert doSomething["code"].getStr == "proc doSomething(x, y: int): int {.raises: [], tags: [], forbids: [].}"
+    let foo2 = data[4]
+    doAssert $foo2["signature"] == """{"arguments":[{"name":"x","type":"T"},{"name":"y","type":"U"},{"name":"z","type":"M"}],"genericParams":[{"name":"T","types":"int"},{"name":"M","types":"string"},{"name":"U"}]}"""
+
+  block: # nim jsondoc # bug #11953
+    let file = testsDir / "misc/mjsondoc.nim"
+    let destDir = testsDir / "misc/htmldocs"
+    removeDir(destDir)
+    defer: removeDir(destDir)
+    let (msg, exitCode) = execCmdEx(fmt"{nim} jsondoc {file}")
+    doAssert exitCode == 0, msg
+
+    let data = parseJson(readFile(destDir / "mjsondoc.json"))["entries"]
+    doAssert data.len == 5
+    let doSomething = data[0]
+    doAssert doSomething["name"].getStr == "doSomething"
+    doAssert doSomething["type"].getStr == "skProc"
+    doAssert doSomething["line"].getInt == 1
+    doAssert doSomething["col"].getInt == 0
+    doAssert doSomething["code"].getStr == "proc doSomething(x, y: int): int {.raises: [], tags: [], forbids: [].}"
+
+  block: # further issues with `--backend`
+    let file = testsDir / "misc/mbackend.nim"
+    var cmd = fmt"{nim} doc -b:cpp --hints:off --nimcache:{nimcache} {file}"
+    check execCmdEx(cmd) == ("", 0)
+    cmd = fmt"{nim} check -b:c -b:cpp --hints:off --nimcache:{nimcache} {file}"
+    check execCmdEx(cmd) == ("", 0)
+    # issue https://github.com/timotheecour/Nim/issues/175
+    cmd = fmt"{nim} c -b:js -b:cpp --hints:off --nimcache:{nimcache} {file}"
+    check execCmdEx(cmd) == ("", 0)
+
+  block: # some importc tests
+    # issue #14314
+    let file = testsDir / "misc/mimportc.nim"
+    let cmd = fmt"{nim} r -b:cpp --hints:off --nimcache:{nimcache} --warningAsError:ProveInit {file}"
+    check execCmdEx(cmd) == ("witness\n", 0)
+
+  block: # bug #20149
+    let file = testsDir / "misc/m20149.nim"
+    let cmd = fmt"{nim} r --hints:off --nimcache:{nimcache} --hintAsError:XDeclaredButNotUsed {file}"
+    check execCmdEx(cmd) == ("12\n", 0)
+
+  block: # bug #15316
+    when not defined(windows):
+      # This never worked reliably on Windows. Needs further investigation but it is hard to reproduce.
+      # Looks like a mild stack corruption when bailing out of nested exception handling.
+      let file = testsDir / "misc/m15316.nim"
+      let cmd = fmt"{nim} check --hints:off --nimcache:{nimcache} {file}"
+      check execCmdEx(cmd) == ("m15316.nim(1, 15) Error: expression expected, but found \')\'\nm15316.nim(2, 1) Error: expected: \':\', but got: \'[EOF]\'\nm15316.nim(2, 1) Error: expression expected, but found \'[EOF]\'\nm15316.nim(2, 1) " &
+            "Error: expected: \')\', but got: \'[EOF]\'\nError: illformed AST: \n", 1)
+
+
+  block: # config.nims, nim.cfg, hintConf, bug #16557
+    let cmd = fmt"{nim} r --hint:all:off --hint:conf tests/newconfig/bar/mfoo.nim"
+    let (outp, exitCode) = execCmdEx(cmd, options = {poStdErrToStdOut})
+    doAssert exitCode == 0
+    let dir = getCurrentDir()
+    let files = """
+tests/config.nims
+tests/newconfig/bar/nim.cfg
+tests/newconfig/bar/config.nims
+tests/newconfig/bar/mfoo.nim.cfg
+tests/newconfig/bar/mfoo.nims""".splitLines
+    var expected = ""
+    for a in files:
+      let b = dir / a
+      expected.add &"Hint: used config file '{b}' [Conf]\n"
+    doAssert outp.endsWith expected, outp & "\n" & expected
+
+  block: # bug #8219
+    let file = "tests/newconfig/mconfigcheck.nims"
+    let cmd = fmt"{nim} check --hints:off {file}"
+    check execCmdEx(cmd) == ("", 0)
+
+  block: # mfoo2.customext
+    let filename = testsDir / "newconfig/foo2/mfoo2.customext"
+    let cmd = fmt"{nim} e --hint:conf {filename}"
+    let (outp, exitCode) = execCmdEx(cmd, options = {poStdErrToStdOut})
+    doAssert exitCode == 0
+    var expected = &"Hint: used config file '{filename}' [Conf]\n"
+    doAssert outp.endsWith "123" & "\n" & expected
+
+
+  block: # nim --eval
+    let opt = "--hints:off"
+    check fmt"""{nim} {opt} --eval:"echo defined(nimscript)"""".execCmdEx == ("true\n", 0)
+    check fmt"""{nim} r {opt} --eval:"echo defined(c)"""".execCmdEx == ("true\n", 0)
+    check fmt"""{nim} r -b:js {opt} --eval:"echo defined(js)"""".execCmdEx == ("true\n", 0)
+
+  block: # `hintProcessing` dots should not interfere with `static: echo` + friends
+    let cmd = fmt"""{nim} r --hint:all:off --hint:processing -f --eval:"static: echo 1+1""""
+    let (outp, exitCode) = execCmdEx(cmd, options = {poStdErrToStdOut})
+    template check3(cond) = doAssert cond, $(outp,)
+    doAssert exitCode == 0
+    let lines = outp.splitLines
+    check3 lines.len == 3
+    when not defined(windows): # xxx: on windows, dots not properly handled, gives: `....2\n\n`
+      check3 lines[0].isDots
+      check3 lines[1] == "2"
+      check3 lines[2] == ""
+    else:
+      check3 "2" in outp
+
+  block: # nim secret
+    let opt = "--hint:all:off --hint:processing"
+    template check3(cond) = doAssert cond, $(outp,)
+    for extra in ["", "--stdout"]:
+      let cmd = fmt"""{nim} secret {opt} {extra}"""
+      # xxx minor bug: `nim --hint:QuitCalled:off secret` ignores the hint cmdline flag
+      template run(input2): untyped =
+        execCmdEx(cmd, options = {poStdErrToStdOut}, input = input2)
+      block:
+        let (outp, exitCode) = run """echo 1+2; import strutils; echo strip(" ab "); quit()"""
+        let lines = outp.splitLines
+        when not defined(windows):
+          check3 lines.len == 5
+          check3 lines[0].isDots
+          # check3 lines[1].isDots # todo nim secret might use parsing pipeline
+          check3 lines[2].dup(removePrefix(">>> ")) == "3" # prompt depends on `nimUseLinenoise`
+          check3 lines[3] == "ab"
+          check3 lines[4] == ""
+        else:
+          check3 "3" in outp
+          check3 "ab" in outp
+        doAssert exitCode == 0
+      block:
+        let (outp, exitCode) = run "echo 1+2; quit(2)"
+        check3 "3" in outp
+        doAssert exitCode == 2
+
+  block: # nimBetterRun
+    let file = "misc/mbetterrun.nim"
+    const nimcache2 = buildDir / "D20210423T185116"
+    removeDir nimcache2
+    # related to `-d:nimBetterRun`
+    let opt = fmt"-r --usenimcache --nimcache:{nimcache2}"
+    var ret = ""
+    for a in @["v1", "v2", "v1", "v3"]:
+      ret.add runNimCmdChk(file, fmt"{opt} -d:mbetterrunVal:{a}")
+    ret.add runNimCmdChk(file, fmt"{opt} -d:mbetterrunVal:v2", rtarg = "arg1 arg2")
+      # rt arguments should not cause a recompilation
+    doAssert ret == """
+compiling: v1
+running: v1
+compiling: v2
+running: v2
+running: v1
+compiling: v3
+running: v3
+running: v2
+""", ret
+
+  block: # nim dump
+    let cmd = fmt"{nim} dump --dump.format:json -d:D20210428T161003 --hints:off ."
+    let (ret, status) = execCmdEx(cmd)
+    doAssert status == 0
+    let j = ret.parseJson
+    # sanity checks
+    doAssert "D20210428T161003" in j["defined_symbols"].to(seq[string])
+    doAssert j["version"].to(string) == NimVersion
+    doAssert j["nimExe"].to(string) == getCurrentCompilerExe()
+
+  block: # genscript
+    const nimcache2 = buildDir / "D20210524T212851"
+    removeDir(nimcache2)
+    let input = "tgenscript_fakefile" # no need for a real file, --eval is good enough
+    let output = runNimCmdChk(input, fmt"""--genscript --nimcache:{nimcache2.quoteShell} --eval:"echo(12345)" """)
+    doAssert output.len == 0, output
+    let ext = when defined(windows): ".bat" else: ".sh"
+    let filename = fmt"compile_{input}{ext}" # synchronize with `generateScript`
+    doAssert fileExists(nimcache2/filename), nimcache2/filename
+    let (outp, status) = execCmdEx(genShellCmd(filename), options = {poStdErrToStdOut}, workingDir = nimcache2)
+    doAssert status == 0, outp
+    let (outp2, status2) = execCmdEx(nimcache2 / input, options = {poStdErrToStdOut})
+    doAssert outp2 == "12345\n", outp2
+    doAssert status2 == 0
+
+  block: # UnusedImport
+    proc fn(opt: string, expected: string) =
+      let output = runNimCmdChk("msgs/mused3.nim", fmt"--warning:all:off --warning:UnusedImport --hint:DuplicateModuleImport {opt}")
+      doAssert output == expected, opt & "\noutput:\n" & output & "expected:\n" & expected
+    fn("-d:case1"): """
+mused3.nim(13, 8) Warning: imported and not used: 'mused3b' [UnusedImport]
+"""
+    fn("-d:case2"): ""
+    fn("-d:case3"): ""
+    fn("-d:case4"): ""
+    fn("-d:case5"): ""
+    fn("-d:case6"): ""
+    fn("-d:case7"): ""
+    fn("-d:case8"): ""
+    fn("-d:case9"): ""
+    fn("-d:case10"): ""
+    when false:
+      fn("-d:case11"): """
+  Warning: imported and not used: 'm2' [UnusedImport]
+  """
+    fn("-d:case12"): """
+mused3.nim(75, 10) Hint: duplicate import of 'mused3a'; previous import here: mused3.nim(74, 10) [DuplicateModuleImport]
+"""
+
+  block: # FieldDefect
+    proc fn(opt: string, expected: string) =
+      let output = runNimCmdChk("misc/mfield_defect.nim", fmt"-r --warning:all:off --declaredlocs {opt}", status = 1)
+      doAssert expected in output, opt & "\noutput:\n" & output & "expected:\n" & expected
+    fn("-d:case1"): """mfield_defect.nim(25, 15) Error: field 'f2' is not accessible for type 'Foo' [discriminant declared in mfield_defect.nim(14, 8)] using 'kind = k3'"""
+    fn("-d:case2 --gc:refc"): """mfield_defect.nim(25, 15) field 'f2' is not accessible for type 'Foo' [discriminant declared in mfield_defect.nim(14, 8)] using 'kind = k3'"""
+    fn("-d:case1 -b:js"): """mfield_defect.nim(25, 15) Error: field 'f2' is not accessible for type 'Foo' [discriminant declared in mfield_defect.nim(14, 8)] using 'kind = k3'"""
+    fn("-d:case2 -b:js"): """field 'f2' is not accessible for type 'Foo' [discriminant declared in mfield_defect.nim(14, 8)] using 'kind = k3'"""
+    fn("-d:case2 --gc:arc"): """mfield_defect.nim(25, 15) field 'f2' is not accessible for type 'Foo' [discriminant declared in mfield_defect.nim(14, 8)] using 'kind = k3'"""
+else:
+  discard # only during debugging, tests added here will run with `-d:nimTestsTrunnerDebugging` enabled
diff --git a/tests/misc/trunner_special.nim b/tests/misc/trunner_special.nim
new file mode 100644
index 000000000..e08b419b0
--- /dev/null
+++ b/tests/misc/trunner_special.nim
@@ -0,0 +1,37 @@
+discard """
+  targets: "c cpp"
+  joinable: false
+  disabled: osx
+"""
+
+#[
+Runs tests that require special treatment, e.g. because they rely on 3rd party code
+or require external networking.
+
+xxx test all tests/untestable/* here, possibly with adjustments to make running times reasonable
+]#
+
+import std/[strformat,os,unittest,compilesettings]
+import stdtest/specialpaths
+
+
+from stdtest/testutils import disableSSLTesting
+
+
+const
+  nim = getCurrentCompilerExe()
+  mode = querySetting(backend)
+
+proc runCmd(cmd: string) =
+  let ret = execShellCmd(cmd)
+  check ret == 0 # allows more than 1 failure
+
+proc main =
+  let options = fmt"-b:{mode} --hints:off"
+  block: # SSL nimDisableCertificateValidation integration tests
+    runCmd fmt"{nim} r {options} -d:nimDisableCertificateValidation -d:ssl {testsDir}/untestable/thttpclient_ssl_disabled.nim"
+  block: # SSL certificate check integration tests
+    runCmd fmt"{nim} r {options} -d:ssl --threads:on --mm:refc {testsDir}/untestable/thttpclient_ssl_remotenetwork.nim"
+
+when not disableSSLTesting():
+  main()
diff --git a/tests/misc/tsemfold.nim b/tests/misc/tsemfold.nim
index 486ddc5a6..2ce8d9560 100644
--- a/tests/misc/tsemfold.nim
+++ b/tests/misc/tsemfold.nim
@@ -2,25 +2,25 @@ discard """
   action: run
 """
 
-doAssertRaises(OverflowError): discard low(int8) - 1'i8
-doAssertRaises(OverflowError): discard high(int8) + 1'i8
-doAssertRaises(OverflowError): discard abs(low(int8))
-doAssertRaises(DivByZeroError): discard 1 mod 0
-doAssertRaises(DivByZeroError): discard 1 div 0
-doAssertRaises(OverflowError): discard low(int8) div -1'i8
+doAssertRaises(OverflowDefect): discard low(int8) - 1'i8
+doAssertRaises(OverflowDefect): discard high(int8) + 1'i8
+doAssertRaises(OverflowDefect): discard abs(low(int8))
+doAssertRaises(DivByZeroDefect): discard 1 mod 0
+doAssertRaises(DivByZeroDefect): discard 1 div 0
+doAssertRaises(OverflowDefect): discard low(int8) div -1'i8
 
-doAssertRaises(OverflowError): discard -low(int64)
-doAssertRaises(OverflowError): discard low(int64) - 1'i64
-doAssertRaises(OverflowError): discard high(int64) + 1'i64
+doAssertRaises(OverflowDefect): discard -low(int64)
+doAssertRaises(OverflowDefect): discard low(int64) - 1'i64
+doAssertRaises(OverflowDefect): discard high(int64) + 1'i64
 
 type E = enum eA, eB
-doAssertRaises(OverflowError): discard eA.pred
-doAssertRaises(OverflowError): discard eB.succ
+doAssertRaises(OverflowDefect): discard eA.pred
+doAssertRaises(OverflowDefect): discard eB.succ
 
-doAssertRaises(OverflowError): discard low(int8) * -1
-doAssertRaises(OverflowError): discard low(int64) * -1
-doAssertRaises(OverflowError): discard high(int8) * 2
-doAssertRaises(OverflowError): discard high(int64) * 2
+doAssertRaises(OverflowDefect): discard low(int8) * -1
+doAssertRaises(OverflowDefect): discard low(int64) * -1
+doAssertRaises(OverflowDefect): discard high(int8) * 2
+doAssertRaises(OverflowDefect): discard high(int64) * 2
 
 doAssert abs(-1) == 1
 doAssert 2 div 2 == 1
diff --git a/tests/misc/tsimplesort.nim b/tests/misc/tsimplesort.nim
index e4a8e0b37..395db55e6 100644
--- a/tests/misc/tsimplesort.nim
+++ b/tests/misc/tsimplesort.nim
@@ -10,7 +10,7 @@ type
   TSlotEnum = enum seEmpty, seFilled, seDeleted
   TKeyValuePair[A, B] = tuple[slot: TSlotEnum, key: A, val: B]
   TKeyValuePairSeq[A, B] = seq[TKeyValuePair[A, B]]
-  TTable* {.final, myShallow.}[A, B] = object
+  TTable*[A, B] {.final, myShallow.} = object
     data: TKeyValuePairSeq[A, B]
     counter: int
 
@@ -112,7 +112,7 @@ proc initTable*[A, B](initialSize=64): TTable[A, B] =
   result.counter = 0
   newSeq(result.data, initialSize)
 
-proc toTable*[A, B](pairs: openarray[tuple[key: A,
+proc toTable*[A, B](pairs: openArray[tuple[key: A,
                     val: B]]): TTable[A, B] =
   ## creates a new hash table that contains the given `pairs`.
   result = initTable[A, B](nextPowerOfTwo(pairs.len+10))
@@ -137,8 +137,7 @@ proc `$`*[A, B](t: TTable[A, B]): string =
 # ------------------------------ count tables -------------------------------
 
 type
-  TCountTable* {.final, myShallow.}[
-      A] = object ## table that counts the number of each key
+  TCountTable*[A] {.final, myShallow.} = object ## table that counts the number of each key
     data: seq[tuple[key: A, val: int]]
     counter: int
 
diff --git a/tests/misc/tsizeof.nim b/tests/misc/tsizeof.nim
index 7b92d3639..ce5334664 100644
--- a/tests/misc/tsizeof.nim
+++ b/tests/misc/tsizeof.nim
@@ -78,7 +78,7 @@ macro c_offsetof(fieldAccess: typed): int32 =
   ## Bullet proof implementation that works on actual offsetof operator
   ## in the c backend. Assuming of course this implementation is
   ## correct.
-  let s = if fieldAccess.kind == nnkCheckedFieldExpr: fieldAccess[0] 
+  let s = if fieldAccess.kind == nnkCheckedFieldExpr: fieldAccess[0]
           else: fieldAccess
   let a = s[0].getTypeInst
   let b = s[1]
@@ -346,6 +346,31 @@ testinstance:
       c: char
       d: int32  # unaligned
 
+    Kind = enum
+      K1, K2
+  
+    AnotherEnum = enum
+      X1, X2, X3
+
+    MyObject = object
+      s: string
+      case k: Kind
+      of K1: nil
+      of K2:
+          x: float
+          y: int32
+      z: AnotherEnum
+
+    Stack[N: static int, T: object] = object
+      pad: array[128 - sizeof(array[N, ptr T]) - sizeof(int) - sizeof(pointer), byte]
+      stack: array[N, ptr T]
+      len*: int
+      rawMem: ptr array[N, T]
+
+    Stack2[T: object] = object
+      pad: array[128 - sizeof(array[sizeof(T), ptr T]), byte]
+    
+
   const trivialSize = sizeof(TrivialType) # needs to be able to evaluate at compile time
 
   proc main(): void =
@@ -361,6 +386,9 @@ testinstance:
     var go : GenericObject[int64]
     var po : PaddingOfSetEnum33
     var capo: MyCustomAlignPackedObject
+    var issue15516: MyObject
+    var issue12636_1: Stack[5, MyObject]
+    var issue12636_2: Stack2[MyObject]
 
     var
       e1: Enum1
@@ -379,7 +407,7 @@ testinstance:
     else:
       doAssert sizeof(SimpleAlignment) > 10
 
-    testSizeAlignOf(t,a,b,c,d,e,f,g,ro,go,po, e1, e2, e4, e8, eoa, eob, capo)
+    testSizeAlignOf(t,a,b,c,d,e,f,g,ro,go,po, e1, e2, e4, e8, eoa, eob, capo, issue15516, issue12636_1, issue12636_2)
 
     type
       WithBitsize {.objectconfig.} = object
@@ -686,3 +714,29 @@ reject:
 
 reject:
   const off8 = offsetof(MyPackedCaseObject, val5)
+
+
+type
+  O0 = object
+  T0 = tuple[]
+
+doAssert sizeof(O0) == 1
+doAssert sizeof(T0) == 1
+
+
+type
+  # this thing may not have padding bytes at the end
+  PackedUnion* {.union, packed.} = object
+    a*: array[11, byte]
+    b*: int64
+
+doAssert sizeof(PackedUnion) == 11
+doAssert alignof(PackedUnion) == 1
+
+# bug #22553
+type
+  ChunkObj = object
+    data: UncheckedArray[byte]
+
+doAssert sizeof(ChunkObj) == 1
+doAssert offsetOf(ChunkObj, data) == 1
diff --git a/tests/misc/tsizeof2.nim b/tests/misc/tsizeof2.nim
index a193cf7c3..da28de508 100644
--- a/tests/misc/tsizeof2.nim
+++ b/tests/misc/tsizeof2.nim
@@ -1,5 +1,5 @@
 discard """
-errormsg: "cannot evaluate 'sizeof' because its type is not defined completely"
+errormsg: "'sizeof' requires '.importc' types to be '.completeStruct'"
 line: 9
 """
 
diff --git a/tests/misc/tsizeof3.nim b/tests/misc/tsizeof3.nim
index 1215b4bcd..f0ba8c4d0 100644
--- a/tests/misc/tsizeof3.nim
+++ b/tests/misc/tsizeof3.nim
@@ -27,3 +27,32 @@ type
 
 static:
   doAssert(compiles(offsetOf(Payload, vals)))
+
+
+type
+  GoodboySave* {.bycopy.} = object
+    saveCount: uint8
+    savePoint: uint16
+    shards: uint32
+    friendCount: uint8
+    friendCards: set[0..255]
+    locationsKnown: set[0..127]
+    locationsUnlocked: set[0..127]
+    pickupsObtained: set[0..127]
+    pickupsUsed: set[0..127]
+    pickupCount: uint8
+
+block: # bug #20914
+  block:
+    proc csizeof[T](a: T): int {.importc:"sizeof", nodecl.}
+
+    var s: GoodboySave
+    doAssert sizeof(s) == 108
+    doAssert csizeof(s) == static(sizeof(s))
+
+  block:
+    proc calignof[T](a: T): int {.importc:"alignof", header: "<stdalign.h>".}
+
+    var s: set[0..256]
+    doAssert alignof(s) == 1
+    doAssert calignof(s) == static(alignof(s))
diff --git a/tests/misc/ttlsemulation.nim b/tests/misc/ttlsemulation.nim
new file mode 100644
index 000000000..767a9bd4e
--- /dev/null
+++ b/tests/misc/ttlsemulation.nim
@@ -0,0 +1,76 @@
+discard """
+  disabled: i386
+  matrix: "-d:nimTtlsemulationCase1 --threads --tlsEmulation:on; -d:nimTtlsemulationCase2 --threads --tlsEmulation:off; -d:nimTtlsemulationCase3 --threads"
+  targets: "c cpp"
+"""
+
+#[
+tests for: `.cppNonPod`, `--tlsEmulation`
+]#
+
+import std/sugar
+
+block:
+  # makes sure the logic in config/nim.cfg or testament doesn't interfere with `--tlsEmulation` so we test the right thing.
+  when defined(nimTtlsemulationCase1):
+    doAssert compileOption("tlsEmulation")
+  elif defined(nimTtlsemulationCase2):
+    doAssert not compileOption("tlsEmulation")
+  elif defined(nimTtlsemulationCase3):
+    when defined(osx):
+      doAssert not compileOption("tlsEmulation")
+  else:
+    doAssert false
+
+block:
+  proc main1(): int =
+    var g0 {.threadvar.}: int
+    g0.inc
+    g0
+  let s = collect:
+    for i in 0..<3: main1()
+  doAssert s == @[1,2,3]
+
+when defined(cpp): # bug #16752
+  when defined(windows) and defined(nimTtlsemulationCase2):
+    discard # xxx this failed with exitCode 1
+  else:
+    type Foo1 {.importcpp: "Foo1", header: "mtlsemulation.h".} = object
+      x: cint
+    type Foo2 {.cppNonPod, importcpp: "Foo2", header: "mtlsemulation.h".} = object
+      x: cint
+
+    var ctorCalls {.importcpp.}: cint
+    var dtorCalls {.importcpp.}: cint
+    type Foo3 {.cppNonPod, importcpp: "Foo3", header: "mtlsemulation.h".} = object
+      x: cint
+
+    proc sub(i: int) =
+      var g1 {.threadvar.}: Foo1
+      var g2 {.threadvar.}: Foo2
+      var g3 {.threadvar.}: Foo3
+      discard g1
+      discard g2
+
+      # echo (g3.x, ctorCalls, dtorCalls)
+      when compileOption("tlsEmulation"):
+        # xxx bug
+        discard
+      else:
+        doAssert g3.x.int == 10 + i
+        doAssert ctorCalls == 2
+      doAssert dtorCalls == 1
+      g3.x.inc
+
+    proc main() =
+      doAssert ctorCalls == 0
+      doAssert dtorCalls == 0
+      block:
+        var f3: Foo3
+        doAssert f3.x == 10
+      doAssert ctorCalls == 1
+      doAssert dtorCalls == 1
+
+      for i in 0..<3:
+        sub(i)
+    main()
diff --git a/tests/misc/tunsignedcomp.nim b/tests/misc/tunsignedcomp.nim
deleted file mode 100644
index 19c8876b1..000000000
--- a/tests/misc/tunsignedcomp.nim
+++ /dev/null
@@ -1,136 +0,0 @@
-discard """
-  output: ''''''
-  disabled: "true"
-"""
-
-# All operations involving uint64 are commented out
-# as they're not yet supported.
-# All other operations are handled by implicit conversions from uints to ints
-# uint64 could be supported but would need special implementation of the operators
-
-# unsigned < signed
-
-assert 10'u8 < 20'i8
-assert 10'u8 < 20'i16
-assert 10'u8 < 20'i32
-assert 10'u8 < 20'i64
-
-assert 10'u16 < 20'i8
-assert 10'u16 < 20'i16
-assert 10'u16 < 20'i32
-assert 10'u16 < 20'i64
-
-assert 10'u32 < 20'i8
-assert 10'u32 < 20'i16
-assert 10'u32 < 20'i32
-assert 10'u32 < 20'i64
-
-# assert 10'u64 < 20'i8
-# assert 10'u64 < 20'i16
-# assert 10'u64 < 20'i32
-# assert 10'u64 < 20'i64
-
-# signed < unsigned
-assert 10'i8 < 20'u8
-assert 10'i8 < 20'u16
-assert 10'i8 < 20'u32
-# assert 10'i8 < 20'u64
-
-assert 10'i16 < 20'u8
-assert 10'i16 < 20'u16
-assert 10'i16 < 20'u32
-# assert 10'i16 < 20'u64
-
-assert 10'i32 < 20'u8
-assert 10'i32 < 20'u16
-assert 10'i32 < 20'u32
-# assert 10'i32 < 20'u64
-
-assert 10'i64 < 20'u8
-assert 10'i64 < 20'u16
-assert 10'i64 < 20'u32
-# assert 10'i64 < 20'u64
-
-# unsigned <= signed
-assert 10'u8 <= 20'i8
-assert 10'u8 <= 20'i16
-assert 10'u8 <= 20'i32
-assert 10'u8 <= 20'i64
-
-assert 10'u16 <= 20'i8
-assert 10'u16 <= 20'i16
-assert 10'u16 <= 20'i32
-assert 10'u16 <= 20'i64
-
-assert 10'u32 <= 20'i8
-assert 10'u32 <= 20'i16
-assert 10'u32 <= 20'i32
-assert 10'u32 <= 20'i64
-
-# assert 10'u64 <= 20'i8
-# assert 10'u64 <= 20'i16
-# assert 10'u64 <= 20'i32
-# assert 10'u64 <= 20'i64
-
-# signed <= unsigned
-assert 10'i8 <= 20'u8
-assert 10'i8 <= 20'u16
-assert 10'i8 <= 20'u32
-# assert 10'i8 <= 20'u64
-
-assert 10'i16 <= 20'u8
-assert 10'i16 <= 20'u16
-assert 10'i16 <= 20'u32
-# assert 10'i16 <= 20'u64
-
-assert 10'i32 <= 20'u8
-assert 10'i32 <= 20'u16
-assert 10'i32 <= 20'u32
-# assert 10'i32 <= 20'u64
-
-assert 10'i64 <= 20'u8
-assert 10'i64 <= 20'u16
-assert 10'i64 <= 20'u32
-# assert 10'i64 <= 20'u64
-
-# signed == unsigned
-assert 10'i8 == 10'u8
-assert 10'i8 == 10'u16
-assert 10'i8 == 10'u32
-# assert 10'i8 == 10'u64
-
-assert 10'i16 == 10'u8
-assert 10'i16 == 10'u16
-assert 10'i16 == 10'u32
-# assert 10'i16 == 10'u64
-
-assert 10'i32 == 10'u8
-assert 10'i32 == 10'u16
-assert 10'i32 == 10'u32
-# assert 10'i32 == 10'u64
-
-assert 10'i64 == 10'u8
-assert 10'i64 == 10'u16
-assert 10'i64 == 10'u32
-# assert 10'i64 == 10'u64
-
-# unsigned == signed
-assert 10'u8 == 10'i8
-assert 10'u8 == 10'i16
-assert 10'u8 == 10'i32
-# assert 10'u8 == 10'i64
-
-assert 10'u16 == 10'i8
-assert 10'u16 == 10'i16
-assert 10'u16 == 10'i32
-# assert 10'u16 == 10'i64
-
-assert 10'u32 == 10'i8
-assert 10'u32 == 10'i16
-assert 10'u32 == 10'i32
-# assert 10'u32 == 10'i64
-
-# assert 10'u64 == 10'i8
-# assert 10'u64 == 10'i16
-# assert 10'u64 == 10'i32
-# assert 10'u64 == 10'i64
diff --git a/tests/misc/tunsignedconv.nim b/tests/misc/tunsignedconv.nim
deleted file mode 100644
index 17d137947..000000000
--- a/tests/misc/tunsignedconv.nim
+++ /dev/null
@@ -1,45 +0,0 @@
-
-# Tests unsigned literals and implicit conversion between uints and ints
-# Passes if it compiles
-
-var h8:uint8 = 128
-var h16:uint16 = 32768
-var h32:uint32 = 2147483648'u32
-var h64:uint64 = 9223372036854775808'u64
-var foobar:uint64 = 9223372036854775813'u64 # Issue 728
-
-var v8:uint8 = 10
-var v16:uint16 = 10
-var v32:uint32 = 10
-var v64:uint64 = 10
-
-# u8 + literal produces u8:
-var a8: uint8 = v8 + 10
-var a16: uint16 = v16 + 10
-
-when false:
-  var d8  = v8 + 10'i8
-  var d16 = v8 + 10'i16
-  var d32 = v8 + 10'i32
-
-when false:
-  # these don't work yet because unsigned.nim is stupid. XXX We need to fix this.
-  var f8  = v16 + 10'u8
-  var f16 = v16 + 10'u16
-  var f32 = v16 + 10'u32
-
-  var g8  = v32 + 10'u8
-  var g16 = v32 + 10'u16
-  var g32 = v32 + 10'u32
-
-var ar: array[0..20, int]
-var n8 = ar[v8]
-var n16 = ar[v16]
-var n32 = ar[v32]
-var n64 = ar[v64]
-
-
-block t4176:
-  var yyy: uint8 = 0
-  yyy = yyy - 127
-  doAssert type(yyy) is uint8
diff --git a/tests/misc/tupcomingfeatures.nim b/tests/misc/tupcomingfeatures.nim
deleted file mode 100644
index d37ce85cf..000000000
--- a/tests/misc/tupcomingfeatures.nim
+++ /dev/null
@@ -1,35 +0,0 @@
-discard """
-  output: '''0 -2 0
-0 -2'''
-"""
-
-{.this: self.}
-
-type
-  Foo = object
-    a, b, x: int
-
-proc yay(self: Foo) =
-  echo a, " ", b, " ", x
-
-proc footest[T](self: var Foo, a: T) =
-  b = 1+a
-  yay()
-
-proc nongeneric(self: Foo) =
-  echo a, " ", b
-
-var ff: Foo
-footest(ff, -3)
-ff.nongeneric
-
-{.experimental.}
-using
-  c: Foo
-  x, y: int
-
-proc usesSig(c) =
-  echo "yummy"
-
-proc foobar(c, y) =
-  echo "yay"
diff --git a/tests/misc/tvarious1.nim b/tests/misc/tvarious1.nim
index 9c0b541db..9c912ee8e 100644
--- a/tests/misc/tvarious1.nim
+++ b/tests/misc/tvarious1.nim
@@ -46,3 +46,13 @@ echo value
 var ys = @[4.1, 5.6, 7.2, 1.7, 9.3, 4.4, 3.2]
 #var x = int(ys.high / 2) #echo ys[x] # Works
 echo ys[int(ys.high / 2)] # Doesn't work
+
+
+# bug #19680
+var here = ""
+when stderr is static:
+  doAssert false
+else:
+  here = "works"
+
+doAssert here == "works"
diff --git a/tests/misc/tvarnums.nim b/tests/misc/tvarnums.nim
index 2aef242e1..498099c49 100644
--- a/tests/misc/tvarnums.nim
+++ b/tests/misc/tvarnums.nim
@@ -7,7 +7,7 @@ import
   strutils
 
 type
-  TBuffer = array[0..10, int8]
+  TBuffer = array[0..10, uint8]
 
 proc toVarNum(x: int32, b: var TBuffer) =
   # encoding: first bit indicates end of number (0 if at end)
@@ -21,11 +21,11 @@ proc toVarNum(x: int32, b: var TBuffer) =
     # anyway
     a = abs(x)
   # first 6 bits:
-  b[0] = toU8(ord(a >% 63'i32) shl 7 or (ord(x < 0'i32) shl 6) or (int(a) and 63))
+  b[0] = uint8(ord(a >% 63'i32) shl 7 or (ord(x < 0'i32) shl 6) or (int(a) and 63))
   a = (a shr 6'i32) and 0x03ffffff # skip first 6 bits
   var i = 1
   while a != 0'i32:
-    b[i] = toU8(ord(a >% 127'i32) shl 7 or (int(a) and 127))
+    b[i] = uint8(ord(a >% 127'i32) shl 7 or (int(a) and 127))
     inc(i)
     a = a shr 7'i32
 
@@ -41,40 +41,40 @@ proc toVarNum64(x: int64, b: var TBuffer) =
     # anyway
     a = abs(x)
   # first 6 bits:
-  b[0] = toU8(ord(a >% 63'i64) shl 7 or (ord(x < 0'i64) shl 6) or int(a and 63))
+  b[0] = uint8(ord(a >% 63'i64) shl 7 or (ord(x < 0'i64) shl 6) or int(a and 63))
   a = (a shr 6) and 0x03ffffffffffffff # skip first 6 bits
   var i = 1
   while a != 0'i64:
-    b[i] = toU8(ord(a >% 127'i64) shl 7 or int(a and 127))
+    b[i] = uint8(ord(a >% 127'i64) shl 7 or int(a and 127))
     inc(i)
     a = a shr 7
 
 proc toNum64(b: TBuffer): int64 =
   # treat first byte different:
-  result = ze64(b[0]) and 63
+  result = int64(b[0]) and 63
   var
     i = 0
     Shift = 6'i64
-  while (ze(b[i]) and 128) != 0:
+  while (int(b[i]) and 128) != 0:
     inc(i)
-    result = result or ((ze64(b[i]) and 127) shl Shift)
+    result = result or ((int64(b[i]) and 127) shl Shift)
     inc(Shift, 7)
-  if (ze(b[0]) and 64) != 0: # sign bit set?
+  if (int(b[0]) and 64) != 0: # sign bit set?
     result = not result +% 1
     # this is the same as ``- result``
     # but gives no overflow error for low(int)
 
 proc toNum(b: TBuffer): int32 =
   # treat first byte different:
-  result = int32 ze(b[0]) and 63
+  result = int32(b[0]) and 63
   var
     i = 0
     Shift = 6'i32
-  while (ze(b[i]) and 128) != 0:
+  while (int(b[i]) and 128) != 0:
     inc(i)
-    result = result or ((int32(ze(b[i])) and 127'i32) shl Shift)
+    result = result or ((int32(b[i]) and 127'i32) shl Shift)
     Shift = Shift + 7'i32
-  if (ze(b[0]) and (1 shl 6)) != 0: # sign bit set?
+  if (int(b[0]) and (1 shl 6)) != 0: # sign bit set?
     result = (not result) +% 1'i32
     # this is the same as ``- result``
     # but gives no overflow error for low(int)
diff --git a/tests/misc/tvcc.nim b/tests/misc/tvcc.nim
new file mode 100644
index 000000000..10533729c
--- /dev/null
+++ b/tests/misc/tvcc.nim
@@ -0,0 +1,9 @@
+discard """
+  matrix: "--cc:vcc"
+  disabled: "linux"
+  disabled: "bsd"
+  disabled: "osx"
+  disabled: "unix"
+  disabled: "posix"
+"""
+doAssert true
diff --git a/tests/mmaptest.nim b/tests/mmaptest.nim
index 7a93cdd45..33010606f 100644
--- a/tests/mmaptest.nim
+++ b/tests/mmaptest.nim
@@ -19,8 +19,11 @@ proc `+!!`(p: pointer, size: int): pointer {.inline.} =
   result = cast[pointer](cast[int](p) + size)
 
 const
-  PageShift = when defined(cpu16): 8 else: 12 # \
-    # my tests showed no improvements for using larger page sizes.
+  PageShift = when defined(nimPage256) or defined(cpu16): 8
+              elif defined(nimPage512): 9
+              elif defined(nimPage1k): 10
+              else: 12 # \ # my tests showed no improvements for using larger page sizes.
+
   PageSize = 1 shl PageShift
 
 var p = osAllocPages(3 * PageSize)
diff --git a/tests/modules/a/module_name_clashes.nim b/tests/modules/a/module_name_clashes.nim
new file mode 100644
index 000000000..209526e22
--- /dev/null
+++ b/tests/modules/a/module_name_clashes.nim
@@ -0,0 +1,8 @@
+# See `tmodule_name_clashes`
+
+import ../b/module_name_clashes
+type A* = object
+  b*: B
+
+proc print*(a: A) =
+  echo repr a
diff --git a/tests/modules/b/module_name_clashes.nim b/tests/modules/b/module_name_clashes.nim
new file mode 100644
index 000000000..6a10cac33
--- /dev/null
+++ b/tests/modules/b/module_name_clashes.nim
@@ -0,0 +1,3 @@
+# See `tmodule_name_clashes`
+
+type B* = object
diff --git a/tests/modules/mforwarded_pure_enum.nim b/tests/modules/mforwarded_pure_enum.nim
new file mode 100644
index 000000000..3f03390a5
--- /dev/null
+++ b/tests/modules/mforwarded_pure_enum.nim
@@ -0,0 +1,3 @@
+
+import mforwarded_pure_enum2
+export mforwarded_pure_enum2.PureEnum
diff --git a/tests/modules/mforwarded_pure_enum2.nim b/tests/modules/mforwarded_pure_enum2.nim
new file mode 100644
index 000000000..e5d5d2a71
--- /dev/null
+++ b/tests/modules/mforwarded_pure_enum2.nim
@@ -0,0 +1,4 @@
+
+type
+  PureEnum* {.pure.} = enum
+    x, y, z
diff --git a/tests/modules/mincludeprefix.nim b/tests/modules/mincludeprefix.nim
new file mode 100644
index 000000000..6d557a430
--- /dev/null
+++ b/tests/modules/mincludeprefix.nim
@@ -0,0 +1 @@
+const bar = 456
diff --git a/tests/modules/mincludetemplate.nim b/tests/modules/mincludetemplate.nim
new file mode 100644
index 000000000..febe9bfcf
--- /dev/null
+++ b/tests/modules/mincludetemplate.nim
@@ -0,0 +1 @@
+const foo = 123
diff --git a/tests/modules/seq.nim b/tests/modules/seq.nim
new file mode 100644
index 000000000..176e44025
--- /dev/null
+++ b/tests/modules/seq.nim
@@ -0,0 +1,5 @@
+var seq: seq[int]
+var b: seq[float]
+
+echo seq
+echo b
diff --git a/tests/modules/texplicit_system_import.nim b/tests/modules/texplicit_system_import.nim
index bc4d018bf..0a4cedc71 100644
--- a/tests/modules/texplicit_system_import.nim
+++ b/tests/modules/texplicit_system_import.nim
@@ -1,9 +1,9 @@
-##.
 import system except `+`
+
 discard """
   errormsg: "undeclared identifier: '+'"
   line: 9
 """
-# Testament requires that the initial """ occurs before the 40th byte
-# in the file. No kidding...
+
+
 echo 4+5
diff --git a/tests/modules/tfowarded_pure_enum.nim b/tests/modules/tfowarded_pure_enum.nim
new file mode 100644
index 000000000..1d2c4f342
--- /dev/null
+++ b/tests/modules/tfowarded_pure_enum.nim
@@ -0,0 +1,7 @@
+discard """
+  output: '''z'''
+"""
+
+import mforwarded_pure_enum as t2
+
+echo z
diff --git a/tests/modules/timportas.nim b/tests/modules/timportas.nim
index 2f7bf7f6a..179613c6b 100644
--- a/tests/modules/timportas.nim
+++ b/tests/modules/timportas.nim
@@ -2,15 +2,20 @@ discard """
     action: run
 """
 
-import .. / modules / [definitions as foo]
-import .. / modules / definitions as foo
+import .. / modules / [mexporta as a1, definitions as foo1]
+import .. / modules / definitions as foo2
+import ./[mexporta as a2, definitions as foo3]
 import std / times as bar
 from times as bar2 import nil
 import times as bar3 except convert
 import definitions as baz
 
-discard foo.v
+discard foo1.v
+discard foo2.v
+discard foo3.v
 discard bar.now()
 discard bar2.now()
 discard bar3.now()
 discard baz.v
+discard a1.xyz
+discard a2.xyz
diff --git a/tests/modules/tincludeprefix.nim b/tests/modules/tincludeprefix.nim
new file mode 100644
index 000000000..d45a6eff3
--- /dev/null
+++ b/tests/modules/tincludeprefix.nim
@@ -0,0 +1,3 @@
+include ./[mincludeprefix, mincludetemplate]
+doAssert foo == 123
+doAssert bar == 456
diff --git a/tests/modules/tincludetemplate.nim b/tests/modules/tincludetemplate.nim
new file mode 100644
index 000000000..77e409ee5
--- /dev/null
+++ b/tests/modules/tincludetemplate.nim
@@ -0,0 +1,5 @@
+# issue #12539
+
+template includePath(n: untyped) = include ../modules/n # But `include n` works
+includePath(mincludetemplate)
+doAssert foo == 123
diff --git a/tests/modules/tmodule_name_clashes.nim b/tests/modules/tmodule_name_clashes.nim
new file mode 100644
index 000000000..814d5d152
--- /dev/null
+++ b/tests/modules/tmodule_name_clashes.nim
@@ -0,0 +1,17 @@
+discard """
+matrix: "--mm:refc"
+targets: "c"
+ccodecheck: "\\i @('atmaatsmodule_name_clashesdotnim_DatInit000')"
+ccodecheck: "\\i @('atmbatsmodule_name_clashesdotnim_DatInit000')"
+joinable: false
+"""
+
+# Test module name clashes within same package.
+# This was created to test that module symbol mangling functioned correctly
+# for the C backend when there are one or more modules with the same name in
+# a package, and more than one of them require module initialization procs.
+# I'm not sure of the simplest method to cause the init procs to be generated.
+
+import a/module_name_clashes
+
+print A()
diff --git a/tests/modules/tmodulesymtype.nim b/tests/modules/tmodulesymtype.nim
new file mode 100644
index 000000000..d17c4cca4
--- /dev/null
+++ b/tests/modules/tmodulesymtype.nim
@@ -0,0 +1,22 @@
+discard """
+cmd: "nim check $file"
+"""
+
+# bug #19225
+import std/sequtils
+sequtils #[tt.Error
+^ expression has no type: sequtils]#
+proc foo() =
+  block: #[tt.Error
+  ^ expression has no type: block:
+  sequtils]#
+    sequtils
+
+foo()
+
+# issue #23399
+when isMainModule:
+  sequtils #[tt.Error
+  ^ expression has no type: sequtils]#
+
+discard
diff --git a/tests/modules/treorder.nim b/tests/modules/treorder.nim
index c81715cd8..ff0b2e071 100644
--- a/tests/modules/treorder.nim
+++ b/tests/modules/treorder.nim
@@ -1,5 +1,5 @@
 discard """
-  cmd: "nim -d:testdef $target $file"
+  matrix: "-d:testdef"
   output: '''works 34
 34
 defined
@@ -8,6 +8,8 @@ defined
 
 {.experimental: "codeReordering".}
 
+{.push callconv: stdcall.}
+
 proc bar(x: T)
 
 proc foo() =
@@ -41,3 +43,5 @@ using
   my, omy: int
 
 goo(3, 4)
+
+{.pop.}
diff --git a/tests/modules/tselfimport.nim b/tests/modules/tselfimport.nim
index 7e50bef7c..ba5d9b4cf 100644
--- a/tests/modules/tselfimport.nim
+++ b/tests/modules/tselfimport.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "A module cannot import itself"
+  errormsg: "module 'tselfimport' cannot import itself"
   file: "tselfimport.nim"
   line: 7
 """
diff --git a/tests/modules/tseq.nim b/tests/modules/tseq.nim
new file mode 100644
index 000000000..22ee48f42
--- /dev/null
+++ b/tests/modules/tseq.nim
@@ -0,0 +1,8 @@
+discard """
+  joinable: false
+  output: '''@[]
+@[]
+'''
+"""
+
+import seq
diff --git a/tests/modules/tstrutils_insert_sep.nim b/tests/modules/tstrutils_insert_sep.nim
new file mode 100644
index 000000000..775fe7da1
--- /dev/null
+++ b/tests/modules/tstrutils_insert_sep.nim
@@ -0,0 +1,13 @@
+discard """
+  output: '''
+-100
+-100,000
+100,000
+'''
+"""
+# test https://github.com/nim-lang/Nim/issues/11352
+
+import strutils
+echo insertSep($(-100), ',')
+echo insertSep($(-100_000), ',')
+echo insertSep($(100_000), ',')
\ No newline at end of file
diff --git a/tests/deprecated/importme.nim b/tests/msgs/mdeprecated3.nim
index 0a9c6e37d..0a9c6e37d 100644
--- a/tests/deprecated/importme.nim
+++ b/tests/msgs/mdeprecated3.nim
diff --git a/tests/msgs/mspellsuggest.nim b/tests/msgs/mspellsuggest.nim
new file mode 100644
index 000000000..ad449554f
--- /dev/null
+++ b/tests/msgs/mspellsuggest.nim
@@ -0,0 +1,7 @@
+proc fooBar4*(a: int) = discard
+var fooBar9* = 0
+
+var fooCar* = 0
+type FooBar* = int
+type FooCar* = int
+type GooBa* = int
diff --git a/tests/msgs/mused2a.nim b/tests/msgs/mused2a.nim
new file mode 100644
index 000000000..d9b2bb9bf
--- /dev/null
+++ b/tests/msgs/mused2a.nim
@@ -0,0 +1,23 @@
+import std/strutils
+
+from std/os import fileExists
+
+import std/typetraits as typetraits2
+from std/setutils import complement
+
+
+
+
+
+proc fn1() = discard
+proc fn2*() = discard
+
+
+let fn4 = 0
+let fn5* = 0
+
+
+const fn7 = 0
+const fn8* = 0
+
+type T1 = object
diff --git a/tests/msgs/mused2b.nim b/tests/msgs/mused2b.nim
new file mode 100644
index 000000000..39c92b964
--- /dev/null
+++ b/tests/msgs/mused2b.nim
@@ -0,0 +1,3 @@
+import mused2c
+export mused2c
+
diff --git a/tests/msgs/mused2c.nim b/tests/msgs/mused2c.nim
new file mode 100644
index 000000000..a374e634e
--- /dev/null
+++ b/tests/msgs/mused2c.nim
@@ -0,0 +1 @@
+proc baz*() = discard
\ No newline at end of file
diff --git a/tests/msgs/mused3.nim b/tests/msgs/mused3.nim
new file mode 100644
index 000000000..0beec1d44
--- /dev/null
+++ b/tests/msgs/mused3.nim
@@ -0,0 +1,76 @@
+#[
+ran from trunner
+]#
+
+
+
+
+
+
+# line 10
+when defined case1:
+  from mused3a import nil
+  from mused3b import nil
+  mused3a.fn1()
+
+when defined case2:
+  from mused3a as m1 import nil
+  m1.fn1()
+
+when defined case3:
+  from mused3a import fn1
+  fn1()
+
+when defined case4:
+  from mused3a as m1 import fn1
+  m1.fn1()
+
+when defined case5:
+  import mused3a as m1
+  fn1()
+
+when defined case6:
+  import mused3a except nonexistent
+  fn1()
+
+when defined case7:
+  import mused3a
+  mused3a.fn1()
+
+when defined case8:
+  # re-export test
+  import mused3a except nonexistent
+  gn1()
+
+when defined case9:
+  # re-export test
+  import mused3a
+  gn1()
+
+when defined case10:
+  #[
+  edge case which happens a lot in compiler code:
+  don't report UnusedImport for mused3b here even though it works without `import mused3b`,
+  because `a.b0.f0` is accessible from both mused3a and mused3b (fields are given implicit access)
+  ]#
+  import mused3a
+  import mused3b
+  var a: Bar
+  discard a.b0.f0
+
+when false:
+  when defined case11:
+    #[
+    xxx minor bug: this should give:
+    Warning: imported and not used: 'm2' [UnusedImport]
+    but doesn't, because currently implementation in `markOwnerModuleAsUsed`
+    only looks at `fn1`, not fully qualified call `m1.fn1()
+    ]#
+    from mused3a as m1 import nil
+    from mused3a as m2 import nil
+    m1.fn1()
+
+when defined case12:
+  import mused3a
+  import mused3a
+  fn1()
diff --git a/tests/msgs/mused3a.nim b/tests/msgs/mused3a.nim
new file mode 100644
index 000000000..c33d1ecb3
--- /dev/null
+++ b/tests/msgs/mused3a.nim
@@ -0,0 +1,41 @@
+when defined case1:
+  proc fn1*() = discard
+
+when defined case2:
+  proc fn1*() = discard
+
+when defined case3:
+  proc fn1*() = discard
+  proc fn2*() = discard
+
+when defined case4:
+  proc fn1*() = discard
+  proc fn2*() = discard
+
+when defined case5:
+  proc fn1*() = discard
+
+when defined case6:
+  proc fn1*() = discard
+
+when defined case7:
+  proc fn1*() = discard
+
+when defined case8:
+  import mused3b
+  export mused3b
+
+when defined case9:
+  import mused3b
+  export mused3b
+
+when defined case10:
+  import mused3b
+  type Bar* = object
+    b0*: Foo
+
+when defined case11:
+  proc fn1*() = discard
+
+when defined case12:
+  proc fn1*() = discard
diff --git a/tests/msgs/mused3b.nim b/tests/msgs/mused3b.nim
new file mode 100644
index 000000000..de288bb08
--- /dev/null
+++ b/tests/msgs/mused3b.nim
@@ -0,0 +1,12 @@
+when defined case1:
+  proc gn1*()=discard
+
+when defined case8:
+  proc gn1*()=discard
+
+when defined case9:
+  proc gn1*()=discard
+
+when defined case10:
+  type Foo* = object
+    f0*: int
diff --git a/tests/msgs/tdeprecated1.nim b/tests/msgs/tdeprecated1.nim
new file mode 100644
index 000000000..f4e85da0b
--- /dev/null
+++ b/tests/msgs/tdeprecated1.nim
@@ -0,0 +1,15 @@
+let foo* {.deprecated: "abcd".} = 42
+var foo1* {.deprecated: "efgh".} = 42
+foo1 = foo #[tt.Warning
+^ efgh; foo1 is deprecated [Deprecated]; tt.Warning
+       ^ abcd; foo is deprecated [Deprecated]]#
+
+proc hello[T](a: T) {.deprecated: "Deprecated since v1.2.0, use 'HelloZ'".} =
+  discard
+
+hello[int](12) #[tt.Warning
+^ Deprecated since v1.2.0, use 'HelloZ'; hello is deprecated [Deprecated]]#
+
+const foo2* {.deprecated: "abcd".} = 42
+discard foo2 #[tt.Warning
+        ^ abcd; foo2 is deprecated [Deprecated]]#
diff --git a/tests/deprecated/tdeprecated.nim b/tests/msgs/tdeprecated2.nim
index ba8d579ad..71d20081e 100644
--- a/tests/deprecated/tdeprecated.nim
+++ b/tests/msgs/tdeprecated2.nim
@@ -1,8 +1,8 @@
 discard """
   nimout: '''
-tdeprecated.nim(23, 3) Warning: a is deprecated [Deprecated]
-tdeprecated.nim(30, 11) Warning: asdf; enum 'Foo' which contains field 'a' is deprecated [Deprecated]
-tdeprecated.nim(40, 16) Warning: use fooX instead; fooA is deprecated [Deprecated]
+tdeprecated2.nim(23, 3) Warning: a is deprecated [Deprecated]
+tdeprecated2.nim(30, 11) Warning: asdf; enum 'Foo' which contains field 'a' is deprecated [Deprecated]
+tdeprecated2.nim(40, 16) Warning: use fooX instead; fooA is deprecated [Deprecated]
 end
 '''
 """
@@ -35,7 +35,7 @@ block: # issue #8063
     Foo = enum
       fooX
 
-  {.deprecated: [fooA: fooX].}
+  const fooA {.deprecated: "use fooX instead".} = fooX
   let
     foo: Foo = fooA
   echo foo
diff --git a/tests/msgs/tdeprecated3.nim b/tests/msgs/tdeprecated3.nim
new file mode 100644
index 000000000..0c1b7deff
--- /dev/null
+++ b/tests/msgs/tdeprecated3.nim
@@ -0,0 +1,33 @@
+discard """
+  matrix: "--hint:all:off"
+  nimoutFull: true
+  nimout: '''
+tdeprecated3.nim(21, 8) Warning: goodbye; mdeprecated3 is deprecated [Deprecated]
+tdeprecated3.nim(24, 10) Warning: Ty is deprecated [Deprecated]
+tdeprecated3.nim(27, 10) Warning: hello; Ty1 is deprecated [Deprecated]
+tdeprecated3.nim(30, 8) Warning: aVar is deprecated [Deprecated]
+tdeprecated3.nim(32, 3) Warning: aProc is deprecated [Deprecated]
+tdeprecated3.nim(33, 3) Warning: hello; aProc1 is deprecated [Deprecated]
+'''
+"""
+
+
+
+
+
+
+
+# line 20
+import mdeprecated3
+
+block:
+  var z: Ty
+  z = 0
+block:
+  var z: Ty1
+  z = 0
+block:
+  echo aVar
+block:
+  aProc()
+  aProc1()
diff --git a/tests/msgs/tdeprecatedequalhook.nim b/tests/msgs/tdeprecatedequalhook.nim
new file mode 100644
index 000000000..79ee835f8
--- /dev/null
+++ b/tests/msgs/tdeprecatedequalhook.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "Overriding `=` hook is deprecated; Override `=copy` hook instead"
+  matrix: "--warningAsError[Deprecated]:on"
+"""
+
+type
+  SharedString = object
+    data: string
+
+proc `=`(x: var SharedString, y: SharedString) =
+  discard
\ No newline at end of file
diff --git a/tests/compilerfeatures/texpandmacro.nim b/tests/msgs/texpandmacro.nim
index 76b0263ae..fea8b571f 100644
--- a/tests/compilerfeatures/texpandmacro.nim
+++ b/tests/msgs/texpandmacro.nim
@@ -1,6 +1,6 @@
 discard """
   cmd: "nim c --expandMacro:foo $file"
-  nimout: '''Hint: expanded macro:
+  nimout: '''texpandmacro.nim(17, 1) Hint: expanded macro:
 echo ["injected echo"]
 var x = 4 [ExpandMacro]
 '''
diff --git a/tests/msgs/thints_off.nim b/tests/msgs/thints_off.nim
new file mode 100644
index 000000000..5a4cadad6
--- /dev/null
+++ b/tests/msgs/thints_off.nim
@@ -0,0 +1,4 @@
+discard """
+  matrix: "--hints:off"
+"""
+doAssert true
diff --git a/tests/msgs/tspellsuggest.nim b/tests/msgs/tspellsuggest.nim
new file mode 100644
index 000000000..ea0a98cd3
--- /dev/null
+++ b/tests/msgs/tspellsuggest.nim
@@ -0,0 +1,45 @@
+discard """
+  matrix: "--spellsuggest:15 --hints:off"
+  action: "reject"
+  nimout: '''
+tspellsuggest.nim(45, 13) Error: undeclared identifier: 'fooBar'
+candidates (edit distance, scope distance); see '--spellSuggest':
+ (1, 0): 'fooBar8'
+ (1, 1): 'fooBar7'
+ (1, 3): 'fooBar1'
+ (1, 3): 'fooBar2'
+ (1, 3): 'fooBar3'
+ (1, 3): 'fooBar4'
+ (1, 3): 'fooBar5'
+ (1, 3): 'fooBar6'
+ (1, 5): 'FooBar'
+ (1, 5): 'fooBar4'
+ (1, 5): 'fooBar9'
+ (1, 5): 'fooCar'
+ (2, 5): 'FooCar'
+ (2, 5): 'GooBa'
+ (3, 0): 'fooBarBaz'
+'''
+"""
+
+# tests `--spellsuggest:num`
+
+
+
+
+# line 30
+import ./mspellsuggest
+
+var fooBar1 = 0
+let fooBar2 = 0
+const fooBar3 = 0
+proc fooBar4() = discard
+template fooBar5() = discard
+macro fooBar6() = discard
+
+proc main =
+  var fooBar7 = 0
+  block:
+    var fooBar8 = 0
+    const fooBarBaz = 0
+    let x = fooBar
diff --git a/tests/msgs/tspellsuggest2.nim b/tests/msgs/tspellsuggest2.nim
new file mode 100644
index 000000000..4bf05799e
--- /dev/null
+++ b/tests/msgs/tspellsuggest2.nim
@@ -0,0 +1,45 @@
+discard """
+  matrix: "--spellsuggest:12 --hints:off"
+  action: "reject"
+  nimout: '''
+tspellsuggest2.nim(45, 13) Error: undeclared identifier: 'fooBar'
+candidates (edit distance, scope distance); see '--spellSuggest':
+ (1, 0): 'fooBar8'
+ (1, 1): 'fooBar7'
+ (1, 3): 'fooBar1'
+ (1, 3): 'fooBar2'
+ (1, 3): 'fooBar3'
+ (1, 3): 'fooBar4'
+ (1, 3): 'fooBar5'
+ (1, 3): 'fooBar6'
+ (1, 5): 'FooBar'
+ (1, 5): 'fooBar4'
+ (1, 5): 'fooBar9'
+ (1, 5): 'fooCar'
+'''
+"""
+
+# tests `--spellsuggest`
+
+
+
+
+
+
+
+# line 30
+import ./mspellsuggest
+
+var fooBar1 = 0
+let fooBar2 = 0
+const fooBar3 = 0
+proc fooBar4() = discard
+template fooBar5() = discard
+macro fooBar6() = discard
+
+proc main =
+  var fooBar7 = 0
+  block:
+    var fooBar8 = 0
+    const fooBarBaz = 0
+    let x = fooBar
diff --git a/tests/msgs/tspellsuggest3.nim b/tests/msgs/tspellsuggest3.nim
new file mode 100644
index 000000000..bd4d5256f
--- /dev/null
+++ b/tests/msgs/tspellsuggest3.nim
@@ -0,0 +1,21 @@
+discard """
+  matrix: "--spellsuggest:4 --hints:off"
+  action: "reject"
+  nimout: '''
+tspellsuggest3.nim(21, 1) Error: undeclared identifier: 'fooBar'
+candidates (edit distance, scope distance); see '--spellSuggest':
+ (1, 2): 'FooBar'
+ (1, 2): 'fooBar4'
+ (1, 2): 'fooBar9'
+ (1, 2): 'fooCar'
+'''
+"""
+
+
+import ./mspellsuggest
+import ./mspellsuggest
+import ./mspellsuggest
+import ./mspellsuggest
+
+
+fooBar
diff --git a/tests/msgs/tused2.nim b/tests/msgs/tused2.nim
new file mode 100644
index 000000000..5ccda7737
--- /dev/null
+++ b/tests/msgs/tused2.nim
@@ -0,0 +1,46 @@
+discard """
+  matrix: "--hint:all:off --hint:XDeclaredButNotUsed --path:."
+  joinable: false
+  nimoutFull: true
+  nimout: '''
+mused2a.nim(12, 6) Hint: 'fn1' is declared but not used [XDeclaredButNotUsed]
+mused2a.nim(16, 5) Hint: 'fn4' is declared but not used [XDeclaredButNotUsed]
+mused2a.nim(20, 7) Hint: 'fn7' is declared but not used [XDeclaredButNotUsed]
+mused2a.nim(23, 6) Hint: 'T1' is declared but not used [XDeclaredButNotUsed]
+mused2a.nim(1, 12) Warning: imported and not used: 'strutils' [UnusedImport]
+mused2a.nim(3, 10) Warning: imported and not used: 'os' [UnusedImport]
+mused2a.nim(5, 23) Warning: imported and not used: 'typetraits2' [UnusedImport]
+mused2a.nim(6, 10) Warning: imported and not used: 'setutils' [UnusedImport]
+tused2.nim(42, 8) Warning: imported and not used: 'mused2a' [UnusedImport]
+tused2.nim(45, 12) Warning: imported and not used: 'strutils' [UnusedImport]
+'''
+"""
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+# line 40
+
+import mused2a
+import mused2b
+
+import std/strutils
+baz()
diff --git a/tests/msgs/twarningaserror.nim b/tests/msgs/twarningaserror.nim
new file mode 100644
index 000000000..6f7b76095
--- /dev/null
+++ b/tests/msgs/twarningaserror.nim
@@ -0,0 +1,35 @@
+discard """
+  joinable: false
+"""
+
+#[
+tests: hintAsError, warningAsError
+]#
+
+template fn1 =
+  {.hintAsError[ConvFromXtoItselfNotNeeded]:on.}
+  proc fn(a: string) = discard a.string
+  {.hintAsError[ConvFromXtoItselfNotNeeded]:off.}
+
+template fn2 =
+  {.hintAsError[ConvFromXtoItselfNotNeeded]:on.}
+  proc fn(a: string) = discard a
+  {.hintAsError[ConvFromXtoItselfNotNeeded]:off.}
+
+template gn1 =
+  {.warningAsError[ProveInit]:on.}
+  proc fn(): var int = discard
+  discard fn()
+  {.warningAsError[ProveInit]:off.}
+
+template gn2 =
+  {.warningAsError[ProveInit]:on.}
+  proc fn(): int = discard
+  discard fn()
+  {.warningAsError[ProveInit]:off.}
+
+doAssert not compiles(fn1())
+doAssert compiles(fn2())
+
+doAssert not compiles(gn1())
+doAssert compiles(gn2())
diff --git a/tests/navigator/minclude.nim b/tests/navigator/minclude.nim
new file mode 100644
index 000000000..f65ebfab9
--- /dev/null
+++ b/tests/navigator/minclude.nim
@@ -0,0 +1,2 @@
+# An include file.
+foo(3)
diff --git a/tests/navigator/tincludefile.nim b/tests/navigator/tincludefile.nim
new file mode 100644
index 000000000..a913d0736
--- /dev/null
+++ b/tests/navigator/tincludefile.nim
@@ -0,0 +1,29 @@
+discard """
+  disabled: true
+  cmd: "nim check $options --defusages:$file,12,7 $file"
+  nimout: '''def tincludefile_temp.nim(11, 10)
+usage tincludefile_temp.nim(12, 8)
+  '''
+"""
+
+
+
+proc foo(x: int) =
+  echo x
+
+foo(3)
+echo "yes", 1 != 3
+
+#!EDIT!#
+discard """
+  cmd: "nim check $options --defusages:$file/../minclude.nim,2,2 $file"
+  nimout: '''def tincludefile_temp.nim(10, 6)
+usage minclude.nim(2, 1)
+  '''
+"""
+
+
+proc foo(x: int) =
+  echo x
+
+include minclude
diff --git a/tests/navigator/tnav1.nim b/tests/navigator/tnav1.nim
new file mode 100644
index 000000000..e76c921f3
--- /dev/null
+++ b/tests/navigator/tnav1.nim
@@ -0,0 +1,33 @@
+discard """
+  disabled: true
+  cmd: "nim check $options --defusages:$file,12,7 $file"
+  nimout: '''def tnav1_temp.nim(11, 10)
+usage tnav1_temp.nim(12, 8)
+  '''
+"""
+
+import std / [times]
+
+proc foo(x: int) =
+  echo x
+
+foo(3)
+echo "yes", 1 != 3
+
+#!EDIT!#
+discard """
+  cmd: "nim check $options --defusages:$file,15,2 $file"
+  nimout: '''def tnav1_temp.nim(12, 6)
+usage tnav1_temp.nim(15, 1)
+  '''
+"""
+
+
+import std / [times]
+
+proc foo(x: int) =
+  echo x
+
+foo(3)
+echo "yes", 1 != 3
+
diff --git a/tests/newconfig/bar/config.nims b/tests/newconfig/bar/config.nims
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/newconfig/bar/config.nims
diff --git a/tests/newconfig/bar/mfoo.nim b/tests/newconfig/bar/mfoo.nim
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/newconfig/bar/mfoo.nim
diff --git a/tests/newconfig/bar/mfoo.nim.cfg b/tests/newconfig/bar/mfoo.nim.cfg
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/newconfig/bar/mfoo.nim.cfg
diff --git a/tests/newconfig/bar/mfoo.nims b/tests/newconfig/bar/mfoo.nims
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/newconfig/bar/mfoo.nims
diff --git a/tests/newconfig/bar/nim.cfg b/tests/newconfig/bar/nim.cfg
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/newconfig/bar/nim.cfg
diff --git a/tests/newconfig/foo2/mfoo2.customext b/tests/newconfig/foo2/mfoo2.customext
new file mode 100644
index 000000000..66c8b1d15
--- /dev/null
+++ b/tests/newconfig/foo2/mfoo2.customext
@@ -0,0 +1,2 @@
+doAssert defined(nimscript)
+echo "123"
diff --git a/tests/newconfig/mconfigcheck.nims b/tests/newconfig/mconfigcheck.nims
new file mode 100644
index 000000000..8df6715f6
--- /dev/null
+++ b/tests/newconfig/mconfigcheck.nims
@@ -0,0 +1,9 @@
+mode = ScriptMode.Verbose
+proc build() =
+  echo "building nim... "
+  exec "sleep 10"
+  exec "nonexistant command"
+  echo getCurrentDir()
+
+echo "hello"
+build()
diff --git a/tests/newconfig/tfoo.nim b/tests/newconfig/tfoo.nim
index f332cd6d4..0c6ded470 100644
--- a/tests/newconfig/tfoo.nim
+++ b/tests/newconfig/tfoo.nim
@@ -1,6 +1,6 @@
 discard """
-  cmd: "nim default $file"
-  output: '''hello world! 0.5'''
+  cmd: "nim default --hint:cc:off --hint:cc $file"
+  output: '''hello world! 0.5 true'''
   nimout: '''[NimScript] exec: gcc -v'''
 """
 
@@ -10,4 +10,4 @@ when not defined(definedefine):
 import math, mfriends
 
 discard gen[int]()
-echo "hello world! ", ln 2.0
+echo "hello world! ", ln 2.0, " ", compileOption("opt", "speed")
diff --git a/tests/newconfig/tfoo.nims b/tests/newconfig/tfoo.nims
index 8dcc7d6f1..f22caaacd 100644
--- a/tests/newconfig/tfoo.nims
+++ b/tests/newconfig/tfoo.nims
@@ -3,11 +3,32 @@ mode = ScriptMode.Whatif
 
 exec "gcc -v"
 
+--define:release
+
 --forceBuild
---path: "../friends"
+--path: "../generics"
 
 warning("uninit", off)
-hint("processing", off)
+
+block: # supported syntaxes for hint,warning,switch
+  --hint:processing
+  hint("processing", on)
+  hint("processing", off)
+  switch("hint", "processing")
+  switch("hint", "processing:on")
+  switch("hint", "processing:off")
+  switch("hint", "[processing]")
+  switch("hint", "[processing]:on")
+  switch("hint", "[processing]:off") # leave it off
+
+  --warning:UnusedImport
+  switch("warning", "UnusedImport:off")
+  switch("warning", "UnusedImport:on")
+  switch("warning", "[UnusedImport]:off")
+  switch("warning", "[UnusedImport]:on")
+  switch("warning", "[UnusedImport]")
+  switch("warning", "UnusedImport") # leave it on
+
 #--verbosity:2
 patchFile("stdlib", "math", "mymath")
 
@@ -24,65 +45,64 @@ doAssert(existsEnv("dummy") == false)
 
 # issue #7283
 putEnv("dummy", "myval")
-doAssert(existsEnv("dummy") == true)
+doAssert(existsEnv("dummy"))
 doAssert(getEnv("dummy") == "myval")
+delEnv("dummy")
+doAssert(existsEnv("dummy") == false)
 
 # issue #7393
 let wd = getCurrentDir()
 cd("..")
-assert wd != getCurrentDir()
+doAssert wd != getCurrentDir()
 cd(wd)
-assert wd == getCurrentDir()
+doAssert wd == getCurrentDir()
 
 when false:
   # this doesn't work in a 'koch testintall' environment
-  assert findExe("nim") != ""
+  doAssert findExe("nim") != ""
 
 # general tests
 mode = ScriptMode.Verbose
 
-assert getCommand() == "c"
+doAssert getCommand() == "c"
 setCommand("cpp")
-assert getCommand() == "cpp"
+doAssert getCommand() == "cpp"
 setCommand("c")
 
-assert cmpic("HeLLO", "hello") == 0
+doAssert cmpic("HeLLO", "hello") == 0
 
-assert fileExists("tests/newconfig/tfoo.nims") == true
-assert dirExists("tests") == true
+doAssert fileExists("tests/newconfig/tfoo.nims") == true
+doAssert dirExists("tests") == true
 
-assert existsFile("tests/newconfig/tfoo.nims") == true
-assert existsDir("tests") == true
+doAssert fileExists("tests/newconfig/tfoo.nims") == true
+doAssert dirExists("tests") == true
 
 discard selfExe()
 
 when defined(windows):
-  assert toExe("nim") == "nim.exe"
-  assert toDll("nim") == "nim.dll"
+  doAssert toExe("nim") == "nim.exe"
+  doAssert toDll("nim") == "nim.dll"
 else:
-  assert toExe("nim") == "nim"
-  assert toDll("nim") == "libnim.so"
+  doAssert toExe("nim") == "nim"
+  doAssert toDll("nim") == "libnim.so"
 
 rmDir("tempXYZ")
-assert dirExists("tempXYZ") == false
+doAssertRaises(OSError):
+  rmDir("tempXYZ", checkDir = true)
+doAssert dirExists("tempXYZ") == false
 mkDir("tempXYZ")
-assert dirExists("tempXYZ") == true
-assert fileExists("tempXYZ/koch.nim") == false
+doAssert dirExists("tempXYZ") == true
+doAssert fileExists("tempXYZ/koch.nim") == false
 
 when false:
   # this doesn't work in a 'koch testintall' environment
   cpFile("koch.nim", "tempXYZ/koch.nim")
-  assert fileExists("tempXYZ/koch.nim") == true
+  doAssert fileExists("tempXYZ/koch.nim") == true
   cpDir("nimsuggest", "tempXYZ/.")
-  assert dirExists("tempXYZ/tests") == true
-  assert fileExists("tempXYZ/nimsuggest.nim") == true
+  doAssert dirExists("tempXYZ/tests") == true
+  doAssert fileExists("tempXYZ/nimsuggest.nim") == true
   rmFile("tempXYZ/koch.nim")
-  assert fileExists("tempXYZ/koch.nim") == false
+  doAssert fileExists("tempXYZ/koch.nim") == false
 
 rmDir("tempXYZ")
-assert dirExists("tempXYZ") == false
-
-putEnv("dummy", "myval")
-doAssert(existsEnv("dummy") == true)
-delEnv("dummy")
-doAssert(existsEnv("dummy") == false)
+doAssert dirExists("tempXYZ") == false
diff --git a/tests/nimble/tnimblepathdollarfail.nim b/tests/nimble/tnimblepathdollar_fault.nim
index 0b9b04eb4..3f0270123 100644
--- a/tests/nimble/tnimblepathdollarfail.nim
+++ b/tests/nimble/tnimblepathdollar_fault.nim
@@ -1,6 +1,9 @@
 discard """
-  errmsg: "cannot open file: pkgA/module"
+  errormsg: "cannot open file: pkgA/module"
 """
+
+# see nims file; comment out `switch("noNimblePath")` there and there would be no error
+
 import pkgA/module as A
 import pkgB/module as B
 import pkgC/module as C
diff --git a/tests/nimble/tnimblepathdollarfail.nims b/tests/nimble/tnimblepathdollar_fault.nims
index 7d47da744..7d47da744 100644
--- a/tests/nimble/tnimblepathdollarfail.nims
+++ b/tests/nimble/tnimblepathdollar_fault.nims
diff --git a/tests/nimdoc/imp.nim b/tests/nimdoc/imp.nim
new file mode 100644
index 000000000..ca08dcb35
--- /dev/null
+++ b/tests/nimdoc/imp.nim
@@ -0,0 +1 @@
+proc fn5*() = discard
diff --git a/tests/nimdoc/m13129.nim b/tests/nimdoc/m13129.nim
new file mode 100644
index 000000000..34e118381
--- /dev/null
+++ b/tests/nimdoc/m13129.nim
@@ -0,0 +1,37 @@
+# issue #13129
+
+when defined(cpp):
+  {.push header: "<vector>".}
+  type
+    Vector[T] {.importcpp: "std::vector".} = object
+  {.pop.}
+elif defined(js):
+  proc endsWith*(s, suffix: cstring): bool {.noSideEffect,importjs: "#.endsWith(#)".}
+elif defined(c):
+  proc c_printf*(frmt: cstring): cint {.
+    importc: "printf", header: "<stdio.h>", varargs, discardable.}
+
+proc main*() =
+  runnableExamples:
+    import std/compilesettings
+    doAssert not defined(m13129Foo1)
+    doAssert defined(m13129Foo2)
+    doAssert not defined(nimdoc)
+    echo "ok2: backend: " & querySetting(backend)
+
+import std/compilesettings
+when defined nimdoc:
+  static:
+    doAssert defined(m13129Foo1)
+    doAssert not defined(m13129Foo2)
+    echo "ok1:" & querySetting(backend)
+
+when isMainModule:
+  when not defined(js):
+    import std/os
+    let cache = querySetting(nimcacheDir)
+    doAssert cache.len > 0
+    let app = getAppFilename()
+    doAssert app.isRelativeTo(cache), $(app, cache)
+    doAssert querySetting(projectFull) == currentSourcePath
+    echo "ok3"
diff --git a/tests/nimdoc/readme.md b/tests/nimdoc/readme.md
new file mode 100644
index 000000000..40b5841eb
--- /dev/null
+++ b/tests/nimdoc/readme.md
@@ -0,0 +1,3 @@
+## links
+* $nim/nimdoc/tester.nim: tests html validation
+* $nim/tests/nimdoc/: tests `runnableExamples` + `nim doc` logic
diff --git a/tests/nimdoc/sub/imp.nim b/tests/nimdoc/sub/imp.nim
new file mode 100644
index 000000000..d66542e45
--- /dev/null
+++ b/tests/nimdoc/sub/imp.nim
@@ -0,0 +1 @@
+proc fn4*() = discard
diff --git a/tests/nimdoc/sub/imp2.nim b/tests/nimdoc/sub/imp2.nim
new file mode 100644
index 000000000..60fa1e72d
--- /dev/null
+++ b/tests/nimdoc/sub/imp2.nim
@@ -0,0 +1 @@
+proc fn3*() = discard
diff --git a/tests/nimdoc/sub/mmain.nim b/tests/nimdoc/sub/mmain.nim
new file mode 100644
index 000000000..42547b0b8
--- /dev/null
+++ b/tests/nimdoc/sub/mmain.nim
@@ -0,0 +1,8 @@
+{.warning[UnusedImport]: off.}
+
+import ../imp as impa
+import imp as impb
+import imp2
+
+proc fn1*() = discard
+proc fn2*() = discard
diff --git a/tests/nimdoc/t15916.nim b/tests/nimdoc/t15916.nim
new file mode 100644
index 000000000..c6c09d94b
--- /dev/null
+++ b/tests/nimdoc/t15916.nim
@@ -0,0 +1,16 @@
+discard """
+cmd: "nim doc --hints:off $file"
+action: "compile"
+joinable: false
+"""
+
+type
+  Test* = object
+    id: int
+
+proc initTest*(id: int): Test =
+  result.id = id
+
+proc hello*() =
+  runnableExamples:
+    discard
diff --git a/tests/nimdoc/t17615.nim b/tests/nimdoc/t17615.nim
new file mode 100644
index 000000000..77ae35a15
--- /dev/null
+++ b/tests/nimdoc/t17615.nim
@@ -0,0 +1,11 @@
+discard """
+  cmd: "nim doc -r $file"
+  errormsg: "runnableExamples must appear before the first non-comment statement"
+  line: 10
+"""
+
+func fn*() =
+  ## foo
+  discard
+  runnableExamples:
+    assert true
diff --git a/tests/nimdoc/trunnableexamples.nim b/tests/nimdoc/trunnableexamples.nim
new file mode 100644
index 000000000..57e725b2e
--- /dev/null
+++ b/tests/nimdoc/trunnableexamples.nim
@@ -0,0 +1,213 @@
+discard """
+cmd: '''nim doc --doccmd:"-d:testFooExternal --hints:off" --hints:off $file'''
+action: "compile"
+nimoutFull: true
+nimout: '''
+foo1
+foo2
+foo3
+foo5
+foo7
+in examplesInTemplate1
+doc in outer
+doc in inner1
+doc in inner2
+foo8
+foo9
+foo6
+'''
+joinable: false
+"""
+
+
+proc fun*() =
+  runnableExamples:
+    block: # `defer` only allowed inside a block
+      defer: echo "foo1"
+
+  runnableExamples:
+    # `fun*` only allowed at top level
+    proc fun*()=echo "foo2"
+    fun()
+    block:
+      defer: echo "foo3"
+
+  runnableExamples:
+    # ditto
+    proc fun*()=echo "foo5"
+    fun()
+
+  runnableExamples("--experimental:codeReordering --warnings:off"):
+    # `codeReordering` only allowed at top level
+    {.experimental: "codeReordering".}
+    proc fun1() = fun2()
+    proc fun2() = echo "foo6"
+    fun1()
+
+  runnableExamples:
+    # only works at top level
+    import std/macros
+    macro myImport(a: static string): untyped =
+      newTree(nnkImportStmt, [newLit a])
+    myImport "str" & "utils"
+    doAssert declared(isAlphaAscii)
+    echo "foo7"
+
+when true: # issue #12746
+  # this proc on its own works fine with `nim doc`
+  proc goodProc*() =
+    runnableExamples:
+      try:
+        discard
+      except CatchableError:
+        # just the general except will work
+        discard
+
+  # FIXED: this proc fails with `nim doc`
+  proc badProc*() =
+    runnableExamples:
+      try:
+        discard
+      except IOError:
+        # specifying Error is culprit
+        discard
+
+when true: # runnableExamples with rdoccmd
+  runnableExamples "-d:testFoo -d:testBar":
+    doAssert defined(testFoo) and defined(testBar)
+    doAssert defined(testFooExternal)
+  runnableExamples "-d:testFoo2":
+    doAssert defined(testFoo2)
+    doAssert not defined(testFoo) # doesn't get confused by other examples
+
+  ## all these syntaxes work too
+  runnableExamples("-d:testFoo2"): discard
+  runnableExamples(): discard
+  runnableExamples: discard
+  runnableExamples "-r:off": # issue #10731
+    doAssert false ## we compile only (-r:off), so this won't be run
+  runnableExamples "-b:js":
+    import std/compilesettings
+    proc startsWith*(s, prefix: cstring): bool {.noSideEffect, importjs: "#.startsWith(#)".}
+    doAssert querySetting(backend) == "js"
+  runnableExamples "-b:cpp":
+    static: doAssert defined(cpp)
+    type std_exception {.importcpp: "std::exception", header: "<exception>".} = object
+
+  proc fun2*() =
+    runnableExamples "-d:foo": discard # checks that it also works inside procs
+
+  template fun3Impl(): untyped =
+    runnableExamples(rdoccmd="-d:foo"):
+      nonexistent
+        # bugfix: this shouldn't be semchecked when `runnableExamples`
+        # has more than 1 argument
+    discard
+
+  proc fun3*[T]() =
+    fun3Impl()
+
+  when false: # future work
+    # passing non-string-litterals (for reuse)
+    const a = "-b:cpp"
+    runnableExamples(a): discard
+
+    # passing seq (to run with multiple compilation options)
+    runnableExamples(@["-b:cpp", "-b:js"]): discard
+
+when true: # bug #16993
+  template examplesInTemplate1*(cond: untyped) =
+    ## in examplesInTemplate1
+    runnableExamples:
+      echo "in examplesInTemplate1"
+    discard
+  examplesInTemplate1 true
+  examplesInTemplate1 true
+  examplesInTemplate1 true
+
+when true: # bug #18054
+  template outer*(body: untyped) =
+    ## outer template doc string.
+    runnableExamples:
+      echo "doc in outer"
+    ##
+    template inner1*() =
+      ## inner1 template doc string.
+      runnableExamples:
+        echo "doc in inner1"
+      ##
+
+    template inner2*() =
+      ## inner2 template doc string.
+      runnableExamples:
+        echo "doc in inner2"
+    body
+  outer:
+    inner1()
+    inner2()
+
+when true: # bug #17835
+  template anyItFake*(s, pred: untyped): bool =
+    ## Foo
+    runnableExamples: discard
+    true
+
+  proc anyItFakeMain*(n: seq[int]): bool =
+    result = anyItFake(n, it == 0)
+      # this was giving: Error: runnableExamples must appear before the first non-comment statement
+
+runnableExamples:
+  block: # bug #17279
+    when int.sizeof == 8:
+      let x = 0xffffffffffffffff
+      doAssert x == -1
+
+  # bug #13491
+  block:
+    proc fun(): int = doAssert false
+    doAssertRaises(AssertionDefect, (discard fun()))
+
+  block:
+    template foo(body) = discard
+    foo (discard)
+
+  block:
+    template fn(body: untyped): untyped = true
+    doAssert(fn do: nonexistent)
+  import std/macros
+  macro foo*(x, y) =
+    result = newLetStmt(x[0][0], x[0][1])
+  foo:
+    a = 1
+  do: discard
+
+# also check for runnableExamples at module scope
+runnableExamples:
+  block:
+    defer: echo "foo8"
+
+runnableExamples:
+  proc fun*()=echo "foo9"
+  fun()
+
+# import std/assertions by default
+runnableExamples("-d:nimPreviewSlimSystem"):
+  doAssert true
+
+# note: there are yet other examples where putting runnableExamples at module
+# scope is needed, for example when using an `include` before an `import`, etc.
+
+##[
+snippet:
+
+.. code-block:: Nim
+    :test:
+
+  doAssert defined(testFooExternal)
+
+]##
+
+when true: # runnableExamples with rdoccmd
+  runnableExamples "-d:testFoo -d:testBar":
+    doAssert defined(testFoo) and defined(testBar)
+    doAssert defined(testFooExternal)
diff --git a/tests/niminaction/Chapter1/various1.nim b/tests/niminaction/Chapter1/various1.nim
index 4e2cb463d..21553dc40 100644
--- a/tests/niminaction/Chapter1/various1.nim
+++ b/tests/niminaction/Chapter1/various1.nim
@@ -32,7 +32,7 @@ block: # Block added due to clash.
   let dog = Dog()
   dog.bark() #<2>
 
-import sequtils, future, strutils
+import sequtils, sugar, strutils
 let list = @["Dominik Picheta", "Andreas Rumpf", "Desmond Hume"]
 list.map(
   (x: string) -> (string, string) => (x.split[0], x.split[1])
diff --git a/tests/niminaction/Chapter2/explicit_discard.nim b/tests/niminaction/Chapter2/explicit_discard.nim
index 9a3b4407e..7f3b3395e 100644
--- a/tests/niminaction/Chapter2/explicit_discard.nim
+++ b/tests/niminaction/Chapter2/explicit_discard.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "has to be discarded"
+  errormsg: "has to be used (or discarded)"
   line: 7
 """
 
diff --git a/tests/niminaction/Chapter2/resultaccept.nim b/tests/niminaction/Chapter2/resultaccept.nim
index 7dd976b40..390f7b329 100644
--- a/tests/niminaction/Chapter2/resultaccept.nim
+++ b/tests/niminaction/Chapter2/resultaccept.nim
@@ -22,7 +22,7 @@ proc resultVar2: string =
   result.add("returned")
 
 doAssert implicit() == "I will be returned"
-doAssert discarded() == nil
+doAssert discarded().len == 0
 doAssert explicit() == "I will be returned"
 doAssert resultVar() == "I will be returned"
 doAssert resultVar2() == "I will be returned"
\ No newline at end of file
diff --git a/tests/niminaction/Chapter2/resultreject.nim b/tests/niminaction/Chapter2/resultreject.nim
index 87c84bf0a..145345072 100644
--- a/tests/niminaction/Chapter2/resultreject.nim
+++ b/tests/niminaction/Chapter2/resultreject.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "has to be discarded"
+  errormsg: "has to be used (or discarded)"
   line: 27
 """
 
diff --git a/tests/niminaction/Chapter2/various2.nim b/tests/niminaction/Chapter2/various2.nim
index dddbdb472..921f38c7d 100644
--- a/tests/niminaction/Chapter2/various2.nim
+++ b/tests/niminaction/Chapter2/various2.nim
@@ -140,7 +140,7 @@ let numbers = @[1, 2, 3, 4, 5, 6]
 let odd = filter(numbers, proc (x: int): bool = x mod 2 != 0)
 doAssert odd == @[1, 3, 5]
 
-import sequtils, future
+import sequtils, sugar
 let numbers1 = @[1, 2, 3, 4, 5, 6]
 let odd1 = filter(numbers1, (x: int) -> bool => x mod 2 != 0)
 assert odd1 == @[1, 3, 5]
@@ -149,7 +149,7 @@ proc isValid(x: int, validator: proc (x: int): bool) =
   if validator(x): echo(x, " is valid")
   else: echo(x, " is NOT valid")
 
-import future
+import sugar
 proc isValid2(x: int, validator: (x: int) -> bool) =
   if validator(x): echo(x, " is valid")
   else: echo(x, " is NOT valid")
@@ -179,13 +179,13 @@ for i in list4.low .. list4.high:
   echo(list4[i])
 
 var list5: seq[int] = @[]
-doAssertRaises(IndexError):
+doAssertRaises(IndexDefect):
   list5[0] = 1
 
 list5.add(1)
 
 assert list5[0] == 1
-doAssertRaises(IndexError):
+doAssertRaises(IndexDefect):
   echo list5[42]
 
 # -- Errata: var list: seq[int]; echo(list[0]). This now creates an exception,
@@ -193,7 +193,7 @@ doAssertRaises(IndexError):
 
 block:
   var list = newSeq[string](3)
-  assert list[0] == nil
+  assert list[0].len == 0
   list[0] = "Foo"
   list[1] = "Bar"
   list[2] = "Baz"
diff --git a/tests/niminaction/Chapter3/various3.nim b/tests/niminaction/Chapter3/various3.nim
index 711740da8..c7cdf7db4 100644
--- a/tests/niminaction/Chapter3/various3.nim
+++ b/tests/niminaction/Chapter3/various3.nim
@@ -1,4 +1,5 @@
 discard """
+matrix: "--mm:refc"
 output: '''
 Future is no longer empty, 42
 '''
@@ -7,7 +8,7 @@ Future is no longer empty, 42
 import threadpool
 proc foo: string = "Dog"
 var x: FlowVar[string] = spawn foo()
-assert(^x == "Dog")
+doAssert(^x == "Dog")
 
 block:
   type
@@ -19,20 +20,20 @@ block:
         discard
 
   var obj = Box(empty: false, contents: "Hello")
-  assert obj.contents == "Hello"
+  doAssert obj.contents == "Hello"
 
   var obj2 = Box(empty: true)
-  doAssertRaises(FieldError):
+  doAssertRaises(FieldDefect):
     echo(obj2.contents)
 
 import json
-assert parseJson("null").kind == JNull
-assert parseJson("true").kind == JBool
-assert parseJson("42").kind == JInt
-assert parseJson("3.14").kind == JFloat
-assert parseJson("\"Hi\"").kind == JString
-assert parseJson("""{ "key": "value" }""").kind == JObject
-assert parseJson("[1, 2, 3, 4]").kind == JArray
+doAssert parseJson("null").kind == JNull
+doAssert parseJson("true").kind == JBool
+doAssert parseJson("42").kind == JInt
+doAssert parseJson("3.14").kind == JFloat
+doAssert parseJson("\"Hi\"").kind == JString
+doAssert parseJson("""{ "key": "value" }""").kind == JObject
+doAssert parseJson("[1, 2, 3, 4]").kind == JArray
 
 import json
 let data = """
@@ -40,15 +41,15 @@ let data = """
 """
 
 let obj = parseJson(data)
-assert obj.kind == JObject
-assert obj["username"].kind == JString
-assert obj["username"].str == "Dominik"
+doAssert obj.kind == JObject
+doAssert obj["username"].kind == JString
+doAssert obj["username"].str == "Dominik"
 
 block:
   proc count10(): int =
     for i in 0 ..< 10:
       result.inc
-  assert count10() == 10
+  doAssert count10() == 10
 
 type
   Point = tuple[x, y: int]
diff --git a/tests/niminaction/Chapter7/Tweeter/src/createDatabase.nim b/tests/niminaction/Chapter7/Tweeter/src/createDatabase.nim
index a7d4ebe00..67d9323f2 100644
--- a/tests/niminaction/Chapter7/Tweeter/src/createDatabase.nim
+++ b/tests/niminaction/Chapter7/Tweeter/src/createDatabase.nim
@@ -1,4 +1,5 @@
 discard """
+disabled: true
 output: "Database created successfully!"
 """
 
diff --git a/tests/niminaction/Chapter7/Tweeter/src/database.nim b/tests/niminaction/Chapter7/Tweeter/src/database.nim
index 3785ea307..bd6667f70 100644
--- a/tests/niminaction/Chapter7/Tweeter/src/database.nim
+++ b/tests/niminaction/Chapter7/Tweeter/src/database.nim
@@ -50,7 +50,7 @@ proc post*(database: Database, message: Message) =
     raise newException(ValueError, "Message has to be less than 140 characters.")
 
   database.db.exec(sql"INSERT INTO Message VALUES (?, ?, ?);", #<2>
-    message.username, $message.time.toSeconds().int, message.msg) #<3>
+    message.username, $message.time.toUnix().int, message.msg) #<3>
 
 proc follow*(database: Database, follower: User, user: User) =
   database.db.exec(sql"INSERT INTO Following VALUES (?, ?);",#<2>
@@ -90,4 +90,4 @@ proc findMessages*(database: Database, usernames: seq[string],
           "ORDER BY time DESC LIMIT " & $limit),
       usernames)
   for row in messages:
-    result.add(Message(username: row[0], time: fromSeconds(row[1].parseInt), msg: row[2]))
+    result.add(Message(username: row[0], time: fromUnix(row[1].parseInt), msg: row[2]))
diff --git a/tests/niminaction/Chapter7/Tweeter/src/tweeter.nim b/tests/niminaction/Chapter7/Tweeter/src/tweeter.nim
index 12aaf49b8..1b521521c 100644
--- a/tests/niminaction/Chapter7/Tweeter/src/tweeter.nim
+++ b/tests/niminaction/Chapter7/Tweeter/src/tweeter.nim
@@ -1,5 +1,7 @@
 discard """
+disabled: true
 action: compile
+matrix: "--threads:off"
 """
 
 import asyncdispatch, times
@@ -51,7 +53,7 @@ routes:
     redirect(uri("/" & @"target"))
 
   post "/login":
-    setCookie("username", @"username", getTime().getGMTime() + 2.hours)
+    setCookie("username", @"username", getTime().utc() + 2.hours)
     redirect("/")
 
   post "/createMessage":
diff --git a/tests/niminaction/Chapter7/Tweeter/src/views/user.nim b/tests/niminaction/Chapter7/Tweeter/src/views/user.nim
index 18f3713b3..4abcf440d 100644
--- a/tests/niminaction/Chapter7/Tweeter/src/views/user.nim
+++ b/tests/niminaction/Chapter7/Tweeter/src/views/user.nim
@@ -33,7 +33,7 @@
   #for message in messages:
     <div>
       <a href="/${message.username}">${message.username}</a>
-      <span>${message.time.getGMTime().format("HH:mm MMMM d',' yyyy")}</span>
+      <span>${message.time.utc().format("HH:mm MMMM d',' yyyy")}</span>
       <h3>${message.msg}</h3>
     </div>
   #end for
diff --git a/tests/niminaction/Chapter7/Tweeter/tests/database_test.nim b/tests/niminaction/Chapter7/Tweeter/tests/database_test.nim
index a3cab4cba..c8beb4a30 100644
--- a/tests/niminaction/Chapter7/Tweeter/tests/database_test.nim
+++ b/tests/niminaction/Chapter7/Tweeter/tests/database_test.nim
@@ -1,4 +1,5 @@
 discard """
+disabled: true
 outputsub: "All tests finished successfully!"
 """
 
diff --git a/tests/niminaction/Chapter8/sdl/sdl.nim b/tests/niminaction/Chapter8/sdl/sdl.nim
index 14fa59c85..212f7b022 100644
--- a/tests/niminaction/Chapter8/sdl/sdl.nim
+++ b/tests/niminaction/Chapter8/sdl/sdl.nim
@@ -1,8 +1,8 @@
-when defined(Windows):
+when defined(windows):
   const libName* = "SDL2.dll"
-elif defined(Linux) or defined(freebsd):
+elif defined(linux) or defined(freebsd) or defined(netbsd):
   const libName* = "libSDL2.so"
-elif defined(MacOsX):
+elif defined(macosx):
   const libName* = "libSDL2.dylib"
 elif defined(openbsd):
   const libName* = "libSDL2.so.0.6"
diff --git a/tests/niminaction/Chapter8/sdl/sdl_test.nim b/tests/niminaction/Chapter8/sdl/sdl_test.nim
index 1c4d258fb..db1700e0d 100644
--- a/tests/niminaction/Chapter8/sdl/sdl_test.nim
+++ b/tests/niminaction/Chapter8/sdl/sdl_test.nim
@@ -18,7 +18,7 @@ renderer.setDrawColor 29, 64, 153, 255
 renderer.clear
 renderer.setDrawColor 255, 255, 255, 255
 
-when defined(c):
+when false: # no long work with gcc 14!
   # just to ensure code from NimInAction still works, but
   # the `else` branch would work as well in C mode
   var points = [
diff --git a/tests/niminaction/Chapter8/sfml/sfml_test.nim b/tests/niminaction/Chapter8/sfml/sfml_test.nim
index 3c158d1de..e71060cb4 100644
--- a/tests/niminaction/Chapter8/sfml/sfml_test.nim
+++ b/tests/niminaction/Chapter8/sfml/sfml_test.nim
@@ -1,7 +1,6 @@
 discard """
 action: compile
 disabled: "windows"
-disabled: "freebsd"
 """
 
 import sfml, os
diff --git a/tests/notnil/tmust_compile.nim b/tests/notnil/tmust_compile.nim
index d09dda057..3a013e9ed 100644
--- a/tests/notnil/tmust_compile.nim
+++ b/tests/notnil/tmust_compile.nim
@@ -63,3 +63,13 @@ proc parse(cts: CTS, jn: JsonNode) =
 
 proc p(x: proc(){.closure.} not nil) = discard
 p(proc(){.closure.} = discard)
+
+# bug #6490
+
+proc p2(a: proc()) =
+    if a.isNil:
+        raise newException(ValueError, "a is nil")
+    else:
+        let b: proc() not nil = a
+
+p2(writeStackTrace)
diff --git a/tests/notnil/tnotnil4.nim b/tests/notnil/tnotnil4.nim
index 4fd169827..c5178f71b 100644
--- a/tests/notnil/tnotnil4.nim
+++ b/tests/notnil/tnotnil4.nim
@@ -10,8 +10,9 @@ proc check(a: TObj not nil) =
 proc doit() =
    var x : array[0..1, TObj]
 
-   if x[0] != nil:
-      check(x[0])
+   let y = x[0]
+   if y != nil:
+      check(y)
 
 doit()
 
diff --git a/tests/notnil/tnotnil5.nim b/tests/notnil/tnotnil5.nim
new file mode 100644
index 000000000..2dcb7f7c3
--- /dev/null
+++ b/tests/notnil/tnotnil5.nim
@@ -0,0 +1,28 @@
+discard """
+  matrix: "--threads:on"
+"""
+
+{.experimental: "parallel".}
+{.experimental: "notnil".}
+import threadpool
+
+type
+  AO = object
+    x: int
+
+  A = ref AO not nil
+
+proc process(a: A): A =
+  return A(x: a.x+1)
+
+proc processMany(ayys: openArray[A]): seq[A] =
+  var newAs: seq[FlowVar[A]]
+
+  parallel:
+    for a in ayys:
+      newAs.add(spawn process(a))
+  for newAflow in newAs:
+    let newA = ^newAflow
+    if isNil(newA):
+      return @[]
+    result.add(newA)
diff --git a/tests/notnil/tnotnil_in_objconstr.nim b/tests/notnil/tnotnil_in_objconstr.nim
index fb8ac8d6f..471150f44 100644
--- a/tests/notnil/tnotnil_in_objconstr.nim
+++ b/tests/notnil/tnotnil_in_objconstr.nim
@@ -1,13 +1,17 @@
 discard """
-  errormsg: "fields not initialized: bar"
-  line: "13"
+  errormsg: "The Foo type requires the following fields to be initialized: bar, baz"
+  line: "17"
 """
 {.experimental: "notnil".}
 # bug #2355
 type
-  Foo = object
+  Base = object of RootObj
+    baz: ref int not nil
+
+  Foo = object of Base
     foo: ref int
     bar: ref int not nil
+
 var x: ref int = new(int)
 # Create instance without initializing the `bar` field
 var f = Foo(foo: x)
diff --git a/tests/notnil/tparse.nim b/tests/notnil/tparse.nim
new file mode 100644
index 000000000..5c938ff04
--- /dev/null
+++ b/tests/notnil/tparse.nim
@@ -0,0 +1,18 @@
+# issue #16324
+
+{.push experimental: "notnil".}
+
+block:
+  type Foo = ref object
+    value: int
+    
+  proc newFoo1(): Foo not nil =               # This compiles
+    return Foo(value: 1)
+    
+  proc newFoo2(): Foo not nil {.inline.} =    # This does not
+    return Foo(value: 1)
+
+  doAssert newFoo1().value == 1
+  doAssert newFoo2().value == 1
+
+{.pop.}
diff --git a/tests/objects/m19342.c b/tests/objects/m19342.c
new file mode 100644
index 000000000..113f65309
--- /dev/null
+++ b/tests/objects/m19342.c
@@ -0,0 +1,12 @@
+struct Node
+{
+  int data[25];
+};
+
+
+struct Node hello(int name) {
+  struct Node x = {999, 1, 2, 3, 4, 5, 6, 7, 8, 9,
+            0, 1, 2, 3, 4, 5, 6, 7 ,8, 9,
+            1, 2, 3, 4, 5};
+  return x;
+}
\ No newline at end of file
diff --git a/tests/objects/mobject_default_value.nim b/tests/objects/mobject_default_value.nim
new file mode 100644
index 000000000..224549501
--- /dev/null
+++ b/tests/objects/mobject_default_value.nim
@@ -0,0 +1,15 @@
+type
+  Clean = object
+    mem: int
+  Default* = object
+    poi: int = 12
+    clc: Clean
+    se*: range[0'i32 .. high(int32)]
+
+  NonDefault* = object
+    poi: int
+
+  PrellDeque*[T] = object
+    pendingTasks*: range[0'i32 .. high(int32)]
+    head: T
+    tail: T
diff --git a/tests/objects/t17437.nim b/tests/objects/t17437.nim
new file mode 100644
index 000000000..b5c0e0525
--- /dev/null
+++ b/tests/objects/t17437.nim
@@ -0,0 +1,22 @@
+discard """
+  cmd: "nim check $file"
+  errormsg: ""
+  nimout: '''
+t17437.nim(20, 16) Error: undeclared identifier: 'x'
+t17437.nim(20, 16) Error: expression 'x' has no type (or is ambiguous)
+t17437.nim(20, 19) Error: incorrect object construction syntax
+t17437.nim(20, 19) Error: incorrect object construction syntax
+t17437.nim(20, 12) Error: expression '' has no type (or is ambiguous)
+'''
+"""
+
+# bug #17437 invalid object construction should result in error
+
+type
+  V = ref object
+    x, y: int
+
+proc m =
+  var v = V(x: x, y)
+
+m()
diff --git a/tests/objects/t19342.nim b/tests/objects/t19342.nim
new file mode 100644
index 000000000..d40d15a4b
--- /dev/null
+++ b/tests/objects/t19342.nim
@@ -0,0 +1,18 @@
+discard """
+  targets: "c cpp"
+"""
+
+{.compile: "m19342.c".}
+
+# bug #19342
+type
+  Node* {.bycopy.} = object
+    data: array[25, cint]
+
+proc myproc(name: cint): Node {.importc: "hello", cdecl.}
+
+proc parse =
+  let node = myproc(10)
+  doAssert node.data[0] == 999
+
+parse()
diff --git a/tests/objects/t19342_2.nim b/tests/objects/t19342_2.nim
new file mode 100644
index 000000000..6f6d0f2b3
--- /dev/null
+++ b/tests/objects/t19342_2.nim
@@ -0,0 +1,18 @@
+discard """
+  targets: "c cpp"
+"""
+
+{.compile: "m19342.c".}
+
+# bug #19342
+type
+  Node* {.byRef.} = object
+    data: array[25, cint]
+
+proc myproc(name: cint): Node {.importc: "hello", cdecl.}
+
+proc parse =
+  let node = myproc(10)
+  doAssert node.data[0] == 999
+
+parse()
\ No newline at end of file
diff --git a/tests/objects/t20972.nim b/tests/objects/t20972.nim
new file mode 100644
index 000000000..6383dc9b1
--- /dev/null
+++ b/tests/objects/t20972.nim
@@ -0,0 +1,15 @@
+discard """
+  matrix: "--mm:refc -d:release; --mm:orc -d:release"
+"""
+
+{.passC: "-fsanitize=undefined -fsanitize-undefined-trap-on-error -Wall -Wextra -pedantic -flto".}
+{.passL: "-fsanitize=undefined -fsanitize-undefined-trap-on-error -flto".}
+
+# bug #20972
+type ForkedEpochInfo = object
+  case kind: bool
+  of true, false: discard
+var info = ForkedEpochInfo(kind: true)
+doAssert info.kind
+info.kind = false
+doAssert not info.kind
diff --git a/tests/objects/t22301.nim b/tests/objects/t22301.nim
new file mode 100644
index 000000000..8746bf584
--- /dev/null
+++ b/tests/objects/t22301.nim
@@ -0,0 +1,17 @@
+discard """
+  errormsg: "branch initialization with a runtime discriminator is not supported for a branch whose fields have default values."
+"""
+
+# bug #22301
+type
+  Enum = enum A, B
+  Object = object
+    case a: Enum
+    of A:
+      integer: int = 200
+    of B:
+      time: string
+
+let x = A
+let s = Object(a: x)
+echo s
\ No newline at end of file
diff --git a/tests/objects/t4318.nim b/tests/objects/t4318.nim
new file mode 100644
index 000000000..beadd6909
--- /dev/null
+++ b/tests/objects/t4318.nim
@@ -0,0 +1,17 @@
+discard """
+  matrix: "--mm:refc"
+"""
+
+
+type
+  A = object of RootObj
+  B = object of A
+
+method identify(a:A) {.base.} = echo "A"
+method identify(b:B) = echo "B"
+
+var b: B
+
+doAssertRaises(ObjectAssignmentDefect):
+  var a: A = b
+  discard a
diff --git a/tests/objects/tdefaultfieldscheck.nim b/tests/objects/tdefaultfieldscheck.nim
new file mode 100644
index 000000000..8a05439d9
--- /dev/null
+++ b/tests/objects/tdefaultfieldscheck.nim
@@ -0,0 +1,16 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  errormsg: ""
+  nimout:
+'''
+tdefaultfieldscheck.nim(14, 17) Error: type mismatch: got <string> but expected 'int'
+'''
+"""
+
+
+type
+  Date* = object
+    goal: float = 7
+    name: int = "string"
+
+echo default(Date)
diff --git a/tests/objects/tdefaultrangetypescheck.nim b/tests/objects/tdefaultrangetypescheck.nim
new file mode 100644
index 000000000..71e7ac59b
--- /dev/null
+++ b/tests/objects/tdefaultrangetypescheck.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "cannot convert 0 to range 1..5(int)"
+  line: 9
+"""
+
+type
+  Point = object
+    y: int
+    x: range[1..5] = 0
+
+echo default(Point)
diff --git a/tests/objects/tillegal_recursion.nim b/tests/objects/tillegal_recursion.nim
index 222139101..428c2e445 100644
--- a/tests/objects/tillegal_recursion.nim
+++ b/tests/objects/tillegal_recursion.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "inheritance only works with non-final objects"
+  errormsg: "Cannot inherit from: 'Foo:ObjectType'"
   line: 7
 """
 # bug #1691
diff --git a/tests/objects/tillegal_recursion2.nim b/tests/objects/tillegal_recursion2.nim
new file mode 100644
index 000000000..ce2279f04
--- /dev/null
+++ b/tests/objects/tillegal_recursion2.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "Cannot inherit from: 'Foo'"
+  line: 6
+"""
+type
+  Foo = object of Foo
diff --git a/tests/objects/tillegal_recursion3.nim b/tests/objects/tillegal_recursion3.nim
new file mode 100644
index 000000000..c80f29e28
--- /dev/null
+++ b/tests/objects/tillegal_recursion3.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "Cannot inherit from: 'Foo'"
+  line: 6
+"""
+type
+  Foo = object of ref Foo
diff --git a/tests/objects/tobj_asgn_dont_slice.nim b/tests/objects/tobj_asgn_dont_slice.nim
index 866b5aecc..ce67c4490 100644
--- a/tests/objects/tobj_asgn_dont_slice.nim
+++ b/tests/objects/tobj_asgn_dont_slice.nim
@@ -1,5 +1,6 @@
 discard """
-  outputsub: '''ObjectAssignmentError'''
+  matrix: "--mm:refc"
+  outputsub: '''ObjectAssignmentDefect'''
   exitcode: "1"
 """
 
diff --git a/tests/objects/tobjconstr.nim b/tests/objects/tobjconstr.nim
index 1e4d89d68..ee5a5b221 100644
--- a/tests/objects/tobjconstr.nim
+++ b/tests/objects/tobjconstr.nim
@@ -50,27 +50,30 @@ type
   BS = object of B
   C = object of BS
     z*: int
-# inherited fields are ignored, so no fields are set
-when true:
-  var
-    o: B
-  o = B(x: 123)
-  echo o
-  o = B(y: 678, x: 123)
-  echo o
 
-# inherited fields are ignored
-echo C(x: 128, z: 89)          # (y: 0, x: 0)
-echo B(y: 678, x: 123)  # (y: 678, x: 0)
-echo B(x: 123, y: 678)  # (y: 678, x: 0)
+proc main2 =
+  # inherited fields are ignored, so no fields are set
+  when true:
+    var
+      o: B
+    o = B(x: 123)
+    echo o
+    o = B(y: 678, x: 123)
+    echo o
 
-when true:
-  # correct, both with `var` and `let`;
-  var b=B(x: 123)
-  echo b                  # (y: 0, x: 123)
-  b=B(y: 678, x: 123)
-  echo b                  # (y: 678, x: 123)
-  b=B(y: b.x, x: b.y)
-  echo b                  # (y: 123, x: 678)
+  # inherited fields are ignored
+  echo C(x: 128, z: 89)          # (y: 0, x: 0)
+  echo B(y: 678, x: 123)  # (y: 678, x: 0)
+  echo B(x: 123, y: 678)  # (y: 678, x: 0)
 
+  when true:
+    # correct, both with `var` and `let`;
+    var b=B(x: 123)
+    echo b                  # (y: 0, x: 123)
+    b=B(y: 678, x: 123)
+    echo b                  # (y: 678, x: 123)
+    b=B(y: b.x, x: b.y)
+    echo b                  # (y: 123, x: 678)
+
+main2()
 GC_fullCollect()
diff --git a/tests/objects/tobjconstr2.nim b/tests/objects/tobjconstr2.nim
index 6253edab0..cf4a694b4 100644
--- a/tests/objects/tobjconstr2.nim
+++ b/tests/objects/tobjconstr2.nim
@@ -15,8 +15,8 @@ echo s[0].x
 
 # bug #563
 type
-  Foo =
-    object {.inheritable.}
+  Foo {.inheritable.} =
+    object
       x: int
 
   Bar =
diff --git a/tests/objects/tobjcov.nim b/tests/objects/tobjcov.nim
index 6c587e04d..a12f74702 100644
--- a/tests/objects/tobjcov.nim
+++ b/tests/objects/tobjcov.nim
@@ -1,6 +1,6 @@
 discard """
 action: compile
-target: "c"
+targets: "c"
 """
 
 # Covariance is not type safe:
diff --git a/tests/objects/tobject.nim b/tests/objects/tobject.nim
index 34856eaef..a185bebcb 100644
--- a/tests/objects/tobject.nim
+++ b/tests/objects/tobject.nim
@@ -1,8 +1,3 @@
-discard """
-output: "[Suite] object basic methods"
-"""
-
-import unittest
 
 type Obj = object
   foo: int
@@ -10,13 +5,13 @@ type Obj = object
 proc makeObj(x: int): Obj =
   result.foo = x
 
-suite "object basic methods":
-  test "it should convert an object to a string":
+block: # object basic methods
+  block: # it should convert an object to a string
     var obj = makeObj(1)
     # Should be "obj: (foo: 1)" or similar.
-    check($obj == "(foo: 1)")
-  test "it should test equality based on fields":
-    check(makeObj(1) == makeObj(1))
+    doAssert($obj == "(foo: 1)")
+  block: # it should test equality based on fields
+    doAssert(makeObj(1) == makeObj(1))
 
 # bug #10203
 
@@ -42,3 +37,38 @@ var b: TMyObj = a
 type
   InheritableFoo {.inheritable.} = ref object
   InheritableBar = ref object of InheritableFoo # ERROR.
+
+block: # bug #14698
+  const N = 3
+  type Foo[T] = ref object
+    x1: int
+    when N == 2:
+      x2: float
+    when N == 3:
+      x3: seq[int]
+    else:
+      x4: char
+      x4b: array[9, char]
+
+  let t = Foo[float](x1: 1)
+  doAssert $(t[]) == "(x1: 1, x3: @[])"
+  doAssert t.sizeof == int.sizeof
+  type Foo1 = object
+    x1: int
+    x3: seq[int]
+  doAssert t[].sizeof == Foo1.sizeof
+
+# bug #147
+type
+  TValue* {.pure, final.} = object of RootObj
+    a: int
+  PValue = ref TValue
+  PPValue = ptr PValue
+
+
+var x: PValue
+new x
+var sp: PPValue = addr x
+
+sp.a = 2
+doAssert sp.a == 2
diff --git a/tests/objects/tobject3.nim b/tests/objects/tobject3.nim
index bec2582fe..9ff1743ce 100644
--- a/tests/objects/tobject3.nim
+++ b/tests/objects/tobject3.nim
@@ -82,3 +82,14 @@ proc newArrayAnimationSampler*[T](): ArrayAnimationSampler[T] =
 
 discard newArrayAnimationSampler[Foo6]()
 discard newArrayAnimationSampler[AnotherFoo]()
+
+type
+  DefaultIsNone* = pointer | ptr | ref | proc {.nimcall.} | cstring | cstringArray
+  OptionKind* {.pure.} = enum None, Some
+  OptionA* [T] = object of RootObj
+    when T is DefaultIsNone:
+      value: T
+    else:
+      value: T
+      kind: OptionKind
+  SomeA* [T] = object of OptionA[T]
diff --git a/tests/objects/tobject_default_value.nim b/tests/objects/tobject_default_value.nim
new file mode 100644
index 000000000..0cd05e4f3
--- /dev/null
+++ b/tests/objects/tobject_default_value.nim
@@ -0,0 +1,780 @@
+discard """
+  matrix: "-d:nimPreviewRangeDefault --mm:refc; -d:nimPreviewRangeDefault --warningAsError:ProveInit --mm:orc"
+  targets: "c cpp js"
+"""
+
+import std/[times, macros, tables]
+
+type
+  Guess = object
+    poi: DateTime
+
+  GuessDistinct = distinct Guess
+
+block:
+  var x: Guess
+  discard Guess()
+
+  var y: GuessDistinct
+
+  discard y
+
+  discard GuessDistinct(x)
+
+
+import mobject_default_value
+
+block:
+  let x = Default()
+  doAssert x.se == 0'i32
+
+block:
+  let x = default(Default)
+  doAssert x.se == 0'i32
+# echo Default(poi: 12)
+# echo Default(poi: 17)
+
+# echo NonDefault(poi: 77)
+
+block:
+  var x: Default
+  doAssert x.se == 0'i32
+
+type
+  ObjectBase = object of RootObj
+    value = 12
+
+  ObjectBaseDistinct = distinct ObjectBase
+
+  DinstinctInObject = object
+    data: ObjectBaseDistinct
+
+  Object = object of ObjectBase
+    time: float = 1.2
+    date: int
+    scale: range[1..10]
+
+  Object2 = object
+    name: Object
+
+  Object3 = object
+    obj: Object2
+
+  ObjectTuple = tuple
+    base: ObjectBase
+    typ: int
+    obj: Object
+
+  TupleInObject = object
+    size = 777
+    data: ObjectTuple
+
+  Ref = ref object of ObjectBase
+
+  RefInt = ref object of Ref
+    data = 73
+
+  Ref2 = ref object of ObjectBase
+
+  RefInt2 = ref object of Ref
+    data = 73
+
+var t {.threadvar.}: Default
+# var m1, m2 {.threadvar.}: Default
+
+block:
+  doAssert t.se == 0'i32
+
+block: # ARC/ORC cannot bind destructors twice, so it cannot
+      # be moved into main
+  block:
+    var x: Ref
+    new(x)
+    doAssert x.value == 12, "Ref.value = " & $x.value
+
+    var y: RefInt
+    new(y)
+    doAssert y.value == 12
+    doAssert y.data == 73
+
+  block:
+    var x: Ref2
+    new(x, proc (x: Ref2) {.nimcall.} = discard "call Ref")
+    doAssert x.value == 12, "Ref.value = " & $x.value
+
+    proc call(x: RefInt2) =
+      discard "call RefInt"
+
+    var y: RefInt2
+    new(y, call)
+    doAssert y.value == 12
+    doAssert y.data == 73
+
+template main {.dirty.} =
+  block: # bug #16744
+    type
+      R = range[1..10]
+      Obj = object
+        r: R
+
+    var
+      rVal: R = default(R) # Works fine
+      objVal = default(Obj)
+
+    doAssert rVal == 1
+    doAssert objVal.r == 1
+
+  block: # bug #16744
+    type
+      R = range[1..10]
+      Obj = object
+        r: R
+
+    var
+      rVal: R = default(R) # Works fine
+      objVal = Obj()
+
+    doAssert rVal == 1 # it should be 1
+    doAssert objVal.r == 1
+
+  block: # bug #3608
+    type
+      abc = ref object
+        w: range[2..100]
+
+    proc createABC(): abc =
+      new(result)
+      result.w = 20
+
+    doAssert createABC().w == 20
+
+  block:
+    var x = new ObjectBase
+    doAssert x.value == 12
+
+    proc hello(): ref ObjectBase =
+      new result
+
+    let z = hello()
+    doAssert z.value == 12
+
+  block:
+    var base = ObjectBase()
+    var x: ObjectBaseDistinct = ObjectBaseDistinct(base)
+    doAssert ObjectBase(x).value == 12
+    let y = ObjectBaseDistinct(default(ObjectBase))
+    doAssert ObjectBase(y).value == 12
+
+    let m = ObjectBaseDistinct(ObjectBase())
+    doAssert ObjectBase(m).value == 12
+
+    proc hello(): ObjectBaseDistinct =
+      result = ObjectBaseDistinct(default(ObjectBase))
+
+    let z = hello()
+    doAssert ObjectBase(z).value == 12
+
+  block:
+    var x: DinstinctInObject
+    x.data = ObjectBaseDistinct(default(ObjectBase))
+
+    doAssert ObjectBase(x.data).value == 12
+
+  block:
+    var x = Object()
+    doAssert x.value == 12
+    doAssert x.time == 1.2
+    doAssert x.scale == 1
+
+    let y = default(Object)
+    doAssert y.value == 12
+    doAssert y.time == 1.2
+    doAssert y.scale == 1
+
+    var x1, x2, x3 = default(Object)
+    doAssert x1.value == 12
+    doAssert x1.time == 1.2
+    doAssert x1.scale == 1
+    doAssert x2.value == 12
+    doAssert x2.time == 1.2
+    doAssert x2.scale == 1
+    doAssert x3.value == 12
+    doAssert x3.time == 1.2
+    doAssert x3.scale == 1
+
+  block:
+    var x = new Object
+    doAssert x[] == default(Object)
+
+  block:
+    var x = default(Object2)
+    doAssert x.name.value == 12
+    doAssert x.name.time == 1.2
+    doAssert x.name.scale == 1
+
+  block:
+    let x = Object2()
+    doAssert x.name.value == 12
+    doAssert x.name.time == 1.2
+    doAssert x.name.scale == 1
+
+  block:
+    var x: ref Object2
+    new x
+    doAssert x[] == default(Object2)
+
+  block:
+    var x = default(Object3)
+    doAssert x.obj.name.value == 12
+    doAssert x.obj.name.time == 1.2
+    doAssert x.obj.name.scale == 1
+
+  block:
+    var x = Object3()
+    doAssert x.obj.name.value == 12
+    doAssert x.obj.name.time == 1.2
+    doAssert x.obj.name.scale == 1
+
+  when nimvm:
+    # todo
+    discard "fixme"
+  else:
+    when defined(gcArc) or defined(gcOrc):
+      block: #seq
+        var x = newSeq[Object](10)
+        let y = x[0]
+        doAssert y.value == 12
+        doAssert y.time == 1.2
+        doAssert y.scale == 1
+
+      block:
+        var x: seq[Object]
+        setLen(x, 5)
+        let y = x[^1]
+        doAssert y.value == 12
+        doAssert y.time == 1.2
+        doAssert y.scale == 1
+
+      block:
+        var my = @[1, 2, 3, 4, 5]
+        my.setLen(0)
+        my.setLen(5)
+        doAssert my == @[0, 0, 0, 0, 0]
+
+      block:
+        var my = "hello"
+        my.setLen(0)
+        my.setLen(5)
+        doAssert $(@my) == """@['\x00', '\x00', '\x00', '\x00', '\x00']"""
+
+  block: # array
+    var x: array[10, Object] = default(array[10, Object])
+    let y = x[0]
+    doAssert y.value == 12
+    doAssert y.time == 1.2
+    doAssert y.scale == 1
+
+  block: # array
+    var x {.noinit.}: array[10, Object]
+    discard x
+
+  block: # tuple
+    var x = default(ObjectTuple)
+    doAssert x.base.value == 12
+    doAssert x.typ == 0
+    doAssert x.obj.time == 1.2
+    doAssert x.obj.date == 0
+    doAssert x.obj.scale == 1
+    doAssert x.obj.value == 12
+
+  block: # tuple in object
+    var x = default(TupleInObject)
+    doAssert x.data.base.value == 12
+    doAssert x.data.typ == 0
+    doAssert x.data.obj.time == 1.2
+    doAssert x.data.obj.date == 0
+    doAssert x.data.obj.scale == 1
+    doAssert x.data.obj.value == 12
+    doAssert x.size == 777
+
+  type
+    ObjectArray = object
+      data: array[10, Object]
+
+  block:
+    var x = default(ObjectArray)
+    let y = x.data[0]
+    doAssert y.value == 12
+    doAssert y.time == 1.2
+    doAssert y.scale == 1
+
+  block:
+    var x: PrellDeque[int]
+    doAssert x.pendingTasks == 0
+
+  type
+    Color = enum
+      Red, Blue, Yellow
+
+    ObjectVarint = object
+      case kind: Color
+      of Red:
+        data: int = 10
+      of Blue:
+        fill = "123"
+      of Yellow:
+        time = 1.8'f32
+
+    ObjectVarint1 = object
+      case kind: Color = Blue
+      of Red:
+        data1: int = 10
+      of Blue:
+        fill2 = "123"
+        cry: float
+      of Yellow:
+        time3 = 1.8'f32
+        him: int
+
+  block:
+    var x = ObjectVarint(kind: Red)
+    doAssert x.kind == Red
+    doAssert x.data == 10
+
+  block:
+    var x = ObjectVarint(kind: Blue)
+    doAssert x.kind == Blue
+    doAssert x.fill == "123"
+
+  block:
+    var x = ObjectVarint(kind: Yellow)
+    doAssert x.kind == Yellow
+    doAssert typeof(x.time) is float32
+
+  block:
+    var x = default(ObjectVarint1)
+    doAssert x.kind == Blue
+    doAssert x.fill2 == "123"
+    x.cry = 326
+
+  type
+    ObjectVarint2 = object
+      case kind: Color
+      of Red:
+        data: int = 10
+      of Blue:
+        fill = "123"
+      of Yellow:
+        time = 1.8'f32
+
+  block:
+    var x = ObjectVarint2(kind: Blue)
+    doAssert x.fill == "123"
+
+  block:
+    type
+      Color = enum
+        Red, Blue, Yellow
+  
+    type
+      ObjectVarint3 = object
+        case kind: Color = Blue
+        of Red:
+          data1: int = 10
+        of Blue:
+          case name: Color = Blue
+          of Blue:
+            go = 12
+          else:
+            temp = 66
+          fill2 = "123"
+          cry: float
+        of Yellow:
+          time3 = 1.8'f32
+          him: int
+
+    block:
+      var x = default(ObjectVarint3)
+      doAssert x.kind == Blue
+      doAssert x.name == Blue
+      doAssert x.go == 12
+
+    block:
+      var x = ObjectVarint3(kind: Blue, name: Red, temp: 99)
+      doAssert x.kind == Blue
+      doAssert x.name == Red
+      doAssert x.temp == 99
+
+  block:
+    type
+      Default = tuple
+        id: int = 1
+        obj: ObjectBase
+        name: string
+
+      Class = object
+        def: Default
+
+      Member = object
+        def: Default = (id: 777, obj: ObjectBase(), name: "fine")
+
+    block:
+      var x = default(Default)
+      doAssert x.id == 1
+      doAssert x.obj == default(ObjectBase)
+      doAssert x.name == ""
+
+    block:
+      var x = default(Class)
+      doAssert x.def == default(Default)
+      doAssert x.def.id == 1
+      doAssert x.def.obj == default(ObjectBase)
+      doAssert x.def.name == ""
+
+    block:
+      var x = default(Member)
+      doAssert x.def.id == 777
+      doAssert x.def.obj == default(ObjectBase)
+      doAssert x.def.name == "fine"
+
+  block:
+    var x {.noinit.} = 12
+    doAssert x == 12
+
+    type
+      Pure = object
+        id: int = 12
+
+    var y {.noinit.}: Pure
+    doAssert y.id == 0
+
+    var z {.noinit.}: Pure = Pure(id: 77)
+    doAssert z.id == 77
+
+  block: # bug #20681
+    type A = object
+      d: DateTime = DateTime()
+
+    let x = default(A)
+    doAssert $x == "(d: Uninitialized DateTime)"
+
+  block: # bug #20715
+    block:
+      type
+        Foo = enum
+          A
+          B
+
+        Bar = object
+          case foo: Foo
+          of A:
+            t: range[-1..2]
+          else: discard
+
+      var d = default(Bar)
+      doAssert d.t == -1
+
+    block:
+      type
+        Foo = enum
+          A
+          B
+
+        Bar = object
+          case foo: Foo
+          of A:
+            t: range[0..2]
+          else: discard
+
+      var d = default(Bar)
+      doAssert d.t == 0
+
+    block: # bug #20740
+      block:
+        proc foo(x: static DateTime = Datetime()) =
+          discard
+
+        foo()
+
+      block:
+        macro foo(x: static DateTime) =
+          discard x
+
+        macro foo2: untyped =
+          var x = DateTime()
+
+          result = quote do:
+            foo(`x`)
+
+        foo2()
+
+
+  block: # issue #20699
+    type
+      Either[A,B] = object
+        case kind:bool
+        of false:
+          b: B
+        of true:
+            a: A
+      O = object of RootRef
+
+    proc oToEither(o:O):Either[O,void] =
+      Either[O,void](kind:true,a: o)
+
+    discard oToEither(O())
+
+  block: # bug #20695
+    type
+      Default = object
+        tabs: Table[string, int] = initTable[string, int]()
+
+    let d = default(Default)
+    doAssert d.tabs.len == 0
+
+  block:
+    type
+      Default = object
+        tabs: Table[string, int] = Table[string, int]()
+
+    let d = default(Default)
+    doAssert d.tabs.len == 0
+
+
+  block:
+    type DjangoDateTime = distinct DateTime
+
+    type Default = object
+      data: DjangoDateTime = DjangoDateTime(DateTime())
+
+    let x = default(Default)
+    doAssert x.data is DjangoDateTime
+
+  block:
+    type DjangoDateTime = distinct DateTime
+
+    type Default = object
+      data = DjangoDateTime(DateTime())
+
+    let x = default(Default)
+    doAssert x.data is DjangoDateTime
+
+  block:
+    type
+      Result2 = object
+        case o: bool
+        of false:
+          e: float
+        of true:
+          v {.requiresInit.} : int = 1
+
+    proc startSessionSync(): Result2 =
+      return Result2(o: true)
+
+    proc mainSync =
+      let ff = startSessionSync()
+      doAssert ff.v == 1
+
+    mainSync()
+
+  block:
+    type
+      Result2 = object
+        v {.requiresInit.} : int = 1
+
+    proc startSessionSync(): Result2 =
+      return Result2()
+
+    proc mainSync =
+      let ff = startSessionSync()
+      doAssert ff.v == 1
+
+    mainSync()
+
+  block: # bug #21801
+    func evaluate(i: int): float =
+      0.0
+
+    func evaluate(): float =
+      0.0
+
+    type SearchOptions = object
+        evaluation: proc(): float = evaluate
+
+  block:
+    func evaluate(): float =
+      0.0
+
+    type SearchOptions = object
+        evaluation: proc(): float = evaluate
+
+  block:
+    func evaluate(i: int): float =
+      0.0
+
+    type SearchOptions = object
+        evaluation = evaluate
+  block:
+    type
+      Result[T, E] = object
+        when T is void:
+          when E is void:
+            oResultPrivate: bool
+          else:
+            case oResultPrivate: bool
+            of false:
+              eResultPrivate: E
+            of true:
+              discard
+        else:
+          when E is void:
+            case oResultPrivate: bool
+            of false:
+              discard
+            of true:
+              vResultPrivate: T
+          else:
+            case oResultPrivate: bool
+            of false:
+              eResultPrivate: E
+            of true:
+              vResultPrivate: T
+
+
+    template `?`[T, E](self: Result[T, E]): auto =
+      let v = (self)
+      if not v.oResultPrivate:
+        when compiles(`assignResult?`(default(typeof(result)))):
+          when typeof(result) is typeof(v):
+            `assignResult?`(v)
+          elif E is void:
+            `assignResult?`(err(typeof(result)))
+          else:
+            `assignResult?`(err(typeof(result), v.eResultPrivate))
+          return
+        else:
+          return
+            when typeof(result) is typeof(v):
+              v
+            elif E is void:
+              err(typeof(result))
+            else:
+              err(typeof(result), v.eResultPrivate)
+
+      when not(T is void):
+        v.vResultPrivate
+        
+    type R = Result[int, string]
+
+    proc testAssignResult() =
+      var assigned: bool
+      template `assignResult?`(v: Result) =
+        assigned = true
+        result = v
+
+      proc failed(): Result[int, string] =
+        discard
+
+      proc calling(): Result[int, string] =
+        let _ = ? failed()
+        doAssert false
+
+      let r = calling()
+      doAssert assigned
+
+    when nimvm:
+      when not defined(js):
+        testAssignResult()
+    else:
+      testAssignResult()
+
+  block: # bug #22123
+    type Thing = object
+      x: float32 = 1
+
+    type ThingWithArray = object
+        arr: array[256, float32]
+        n: float32 = 1
+
+    type Container = ref object
+        thing: array[5, Thing]
+        thing_with_array: array[5, ThingWithArray]
+
+    var foo = new Container
+    doAssert int(foo.thing[0].x) == 1
+
+  block: # bug #22613
+    type
+      K = enum
+        A = "a"
+        B = "b"
+      T = object
+        case kind: K = B
+        of A:
+          a: int
+        of B:
+          b: float
+
+    doAssert T().kind == B
+
+  block: # bug #22926
+    type
+      Direction = enum
+        North
+        South
+        East
+        West
+
+      ArrayObj1 = object
+        list: array[Direction, int]
+
+      ArrayObj2 = object
+        list: array[Direction, int] = [1, 2, 3, 4]
+
+    block:
+      var a: ArrayObj1
+      doAssert a.list[West] == 0
+      var b = default ArrayObj1
+      doAssert b.list[North] == 0
+
+
+    block:
+      var a: ArrayObj2
+      doAssert a.list[West] == 0
+      var b = default ArrayObj2
+      doAssert b.list[North] == 1
+
+  block:
+    type limited_float = range[1.2..20.0]
+    doAssert default(limited_float) == 1.2
+
+
+  block:
+    type
+      range1 = range[1..10]
+      range2 = range[-1..10]
+
+    proc foo =
+      doAssert default(range1) == 1
+      doAssert default(range2) == -1
+
+      let s = default(array[5, range1])
+      doAssert s == [range1 1, 1, 1, 1, 1]
+
+    foo()
+
+  block:
+    type
+      Object = object
+        id: range[1.2..29.3]
+
+    var s = default(Object)
+    doAssert s.id == 1.2
+
+  block: # bug #23943
+    type limited_int = range[1..20]
+    var d: limited_int;
+    doAssert d == 1
+
+static: main()
+main()
diff --git a/tests/objects/tobjects_issues.nim b/tests/objects/tobjects_issues.nim
index fddfff7d5..f1a416d04 100644
--- a/tests/objects/tobjects_issues.nim
+++ b/tests/objects/tobjects_issues.nim
@@ -113,5 +113,5 @@ block t3038:
     Type = ref object of RootObj
     SubType[T] = ref object of Type
       data: Data[T]
-    SubSubType = ref object of SubType
+    SubSubType = ref object of SubType[int]
     SubSubSubType = ref object of SubSubType
diff --git a/tests/objects/tobjects_various.nim b/tests/objects/tobjects_various.nim
index 315193de9..55db9312e 100644
--- a/tests/objects/tobjects_various.nim
+++ b/tests/objects/tobjects_various.nim
@@ -31,7 +31,7 @@ block tobject2:
 
 block tofopr:
   type
-    TMyType = object {.inheritable.}
+    TMyType {.inheritable.} = object
       len: int
       data: string
 
@@ -105,3 +105,16 @@ block t7244:
 
   proc test(foo: var Foo) = discard
   proc test(bar: var Bar) = test(Foo(bar))
+
+
+import std/macros
+
+#bug #20856
+macro ensureImplWorksOnConstr(t: typed): untyped =
+  expectKind(t, nnkObjConstr)
+  doAssert t[0].getTypeInst.getImpl.repr == "A = object"
+  doAssert t[0].getImpl.repr == "A = object"
+
+type A = object
+
+ensureImplWorksOnConstr(A())
diff --git a/tests/objects/trequireinit.nim b/tests/objects/trequireinit.nim
new file mode 100644
index 000000000..202667b02
--- /dev/null
+++ b/tests/objects/trequireinit.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "The MPlayerObj type doesn't have a default value. The following fields must be initialized: foo."
+"""
+
+type
+  MPlayerObj* {.requiresInit.} = object
+    foo: range[5..10] = 5
+
+var a: MPlayerObj
+echo a.foo
\ No newline at end of file
diff --git a/tests/objects/tunsafenew.nim b/tests/objects/tunsafenew.nim
new file mode 100644
index 000000000..6c1b33cd9
--- /dev/null
+++ b/tests/objects/tunsafenew.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "conversion from int literal(-1) to Natural is invalid"
+"""
+
+type
+  Obj = object
+    case b: bool
+    else: discard
+var o: ref Obj
+unsafeNew(o, -1)
\ No newline at end of file
diff --git a/tests/objects/tunsafenew2.nim b/tests/objects/tunsafenew2.nim
new file mode 100644
index 000000000..83112bcfc
--- /dev/null
+++ b/tests/objects/tunsafenew2.nim
@@ -0,0 +1,15 @@
+discard """
+valgrind: "leaks"
+matrix: "-d:useMalloc"
+targets: "c cpp"
+"""
+
+type
+  Obj = object
+    case b: bool
+    else: discard
+    a: UncheckedArray[byte]
+
+var o: ref Obj
+unsafeNew(o, sizeof(Obj) + 512)
+zeroMem(addr o.a, 512)
diff --git a/tests/objects/twhen1.nim b/tests/objects/twhen1.nim
index 2301d255a..fe072a46b 100644
--- a/tests/objects/twhen1.nim
+++ b/tests/objects/twhen1.nim
@@ -49,3 +49,41 @@ block:
 
 block:
   var x: Foo4[0]
+
+type
+  MyObject = object
+    x: int
+    when (NimMajor, NimMinor) >= (1, 1):
+      y: int
+discard MyObject(x: 100, y: 200)
+
+block: # Ensure when evaluates properly in objects
+  type X[bits: static int] = object #22474
+    when bits >= 256:
+     data32: byte
+    else:
+     data16: byte
+
+  static:
+    discard X[255]().data16
+    discard X[256]().data32
+
+
+  type ComplexExprObject[S: static string, I: static int, Y: static auto] = object
+    when 'h' in S and I < 10 and Y isnot float:
+      a: int
+    elif I > 30:
+      b: int
+    elif typeof(Y) is float:
+      c: int
+    else:
+      d: int
+
+  static:
+    discard ComplexExprObject["hello", 9, 300i32]().a
+    discard ComplexExprObject["", 40, 30f]().b
+    discard ComplexExprObject["", 20, float 30]().c
+    discard ComplexExprObject["", 20, ""]().d
+
+
+
diff --git a/tests/objvariant/t14581.nim b/tests/objvariant/t14581.nim
new file mode 100644
index 000000000..72ba32f18
--- /dev/null
+++ b/tests/objvariant/t14581.nim
@@ -0,0 +1,25 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+  output: "abc: @[(kind: A, x: 0)]"
+"""
+
+import std/tables
+
+type E = enum
+  A, B
+
+type O = object
+  case kind: E
+  of A:
+    x: int
+  of B:
+    y: int 
+
+proc someTable(): Table[string, seq[O]] =
+  result = initTable[string, seq[O]]()
+  result["abc"] = @[O(kind: A)]
+
+const t = someTable()
+
+for k, v in t:
+  echo k, ": ", v
diff --git a/tests/objvariant/tcheckedfield1.nim b/tests/objvariant/tcheckedfield1.nim
index 69b099f24..4a6c49f66 100644
--- a/tests/objvariant/tcheckedfield1.nim
+++ b/tests/objvariant/tcheckedfield1.nim
@@ -1,6 +1,5 @@
 discard """
-  nimout: "Warning: cannot prove that field 'x.s' is accessible [ProveField]"
-  line:51
+  nimout: "tcheckedfield1.nim(39, 6) Warning: cannot prove that field 'x.s' is accessible [ProveField]"
   action: run
   output: "abc abc"
 """
diff --git a/tests/objvariant/tconstobjvariant.nim b/tests/objvariant/tconstobjvariant.nim
new file mode 100644
index 000000000..45a647707
--- /dev/null
+++ b/tests/objvariant/tconstobjvariant.nim
@@ -0,0 +1,18 @@
+# This is a sample code, the first echo statement prints out the error
+type
+  A = object
+    case w: uint8
+    of 1:
+      n: int
+    else:
+      other: string
+
+const
+  a = A(w: 1, n: 5)
+
+proc foo =
+
+  let c = [a]
+  doAssert c[0].n == 5
+
+foo()
\ No newline at end of file
diff --git a/tests/objvariant/tconstructionorder.nim b/tests/objvariant/tconstructionorder.nim
index 19ddea7a1..5ca484884 100644
--- a/tests/objvariant/tconstructionorder.nim
+++ b/tests/objvariant/tconstructionorder.nim
@@ -23,22 +23,22 @@ type
 # This will test that all the values are what we expect.
 proc assertTree(root: Node) =
   # check root of tree
-  assert root.kind == Operator
-  assert root.operator == '*'
+  doAssert root.kind == Operator
+  doAssert root.operator == '*'
 
   # check left subtree
-  assert root.left.value == 5
-  assert root.left.kind == Literal
+  doAssert root.left.value == 5
+  doAssert root.left.kind == Literal
 
   # check right subtree
-  assert root.right.kind == Operator
-  assert root.right.operator == '+'
+  doAssert root.right.kind == Operator
+  doAssert root.right.operator == '+'
 
-  assert root.right.left.value == 5
-  assert root.right.left.kind == Literal
+  doAssert root.right.left.value == 5
+  doAssert root.right.left.kind == Literal
 
-  assert root.right.right.value == 10
-  assert root.right.right.kind == Literal
+  doAssert root.right.right.value == 10
+  doAssert root.right.right.kind == Literal
 
 proc newLiteralNode(value: int): Node =
   result = Node(
diff --git a/tests/objvariant/treassign.nim b/tests/objvariant/treassign.nim
index 2938b30a3..527204616 100644
--- a/tests/objvariant/treassign.nim
+++ b/tests/objvariant/treassign.nim
@@ -25,3 +25,34 @@ t.curr = TokenObject(kind: Token.bar, bar: BasicNumber(value: 12.34))
 t.curr = TokenObject(kind: Token.foo, foo: "foo")
 
 echo "SUCCESS"
+
+proc passToVar(x: var Token) = discard
+
+{.cast(uncheckedAssign).}:
+  passToVar(t.curr.kind)
+
+  t.curr = TokenObject(kind: t.curr.kind, foo: "abc")
+
+  t.curr.kind = Token.foo
+
+
+block:
+  type
+    TokenKind = enum
+      strLit, intLit
+    Token = object
+      case kind*: TokenKind
+      of strLit:
+        s*: string
+      of intLit:
+        i*: int64
+
+  var t = Token(kind: strLit, s: "abc")
+
+  {.cast(uncheckedAssign).}:
+
+    # inside the 'cast' section it is allowed to assign to the 't.kind' field directly:
+    t.kind = intLit
+
+  {.cast(uncheckedAssign).}:
+    t.kind = strLit
\ No newline at end of file
diff --git a/tests/openarray/topena1.nim b/tests/openarray/topena1.nim
index ed3a0cedb..380c57f2a 100644
--- a/tests/openarray/topena1.nim
+++ b/tests/openarray/topena1.nim
@@ -6,4 +6,4 @@ discard """
 # Tests a special bug
 
 var
-  x: ref openarray[string] #ERROR_MSG invalid type
+  x: ref openArray[string] #ERROR_MSG invalid type
diff --git a/tests/openarray/topenarray.nim b/tests/openarray/topenarray.nim
new file mode 100644
index 000000000..25b983651
--- /dev/null
+++ b/tests/openarray/topenarray.nim
@@ -0,0 +1,88 @@
+discard """
+  targets: "c cpp js"
+"""
+
+proc fn1[T](a: openArray[T]): seq[T] =
+  for ai in a: result.add ai
+
+proc fn2[T](a: var openArray[T]): seq[T] =
+  for ai in a: result.add ai
+
+proc fn3[T](a: var openArray[T]) =
+  for i, ai in mpairs(a): ai = i * 10
+
+proc main =
+  var a = [1,2,3,4,5]
+
+  doAssert fn1(a.toOpenArray(1,3)) == @[2,3,4]
+
+  doAssert fn2(toOpenArray(a, 1, 3)) == @[2,3,4]
+  doAssert fn2(a.toOpenArray(1,3)) == @[2,3,4]
+
+  fn3(a.toOpenArray(1,3))
+  when defined(js): discard # xxx bug #15952: `a` left unchanged
+  else: doAssert a == [1, 0, 10, 20, 5]
+
+  block: # bug #12521
+    block:
+      type slice[T] = openArray[T]
+
+      # Proc using that alias
+      proc testing(sl: slice[int]): seq[int] =
+        for item in sl:
+          result.add item
+
+      let mySeq = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
+      doAssert testing(mySeq) == mySeq
+      doAssert testing(mySeq[2..^2]) == mySeq[2..^2]
+
+    block:
+      type slice = openArray[int]
+
+      # Proc using that alias
+      proc testing(sl: slice): seq[int] =
+        for item in sl:
+          result.add item
+
+      let mySeq = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
+      doAssert testing(mySeq) == mySeq
+      doAssert testing(mySeq[2..^2]) == mySeq[2..^2]
+
+  block: # bug #23321
+    block:
+      proc foo(x: openArray[int]) =
+        doAssert x[0] == 0
+
+      var d = new array[1, int]
+      foo d[].toOpenArray(0, 0)
+
+    block:
+      proc foo(x: openArray[int]) =
+        doAssert x[0] == 0
+
+      proc task(x: var array[1, int]): var array[1, int] =
+        result = x
+      var d: array[1, int]
+      foo task(d).toOpenArray(0, 0)
+
+    block:
+      proc foo(x: openArray[int]) =
+        doAssert x[0] == 0
+
+      proc task(x: var array[1, int]): lent array[1, int] =
+        result = x
+      var d: array[1, int]
+      foo task(d).toOpenArray(0, 0)
+
+    block:
+      proc foo(x: openArray[int]) =
+        doAssert x[0] == 0
+
+      proc task(x: var array[1, int]): ptr array[1, int] =
+        result = addr x
+      var d: array[1, int]
+      foo task(d)[].toOpenArray(0, 0)
+
+
+main()
+static: main()
diff --git a/tests/openarray/topenarrayrepr.nim b/tests/openarray/topenarrayrepr.nim
index 3784d4bbb..fc40d88c3 100644
--- a/tests/openarray/topenarrayrepr.nim
+++ b/tests/openarray/topenarrayrepr.nim
@@ -2,12 +2,12 @@ discard """
   output: "5 - [1]"
 """
 type
-  TProc = proc (n: int, m: openarray[int64]) {.nimcall.}
+  TProc = proc (n: int, m: openArray[int64]) {.nimcall.}
 
 proc Foo(x: int, P: TProc) =
   P(x, [ 1'i64 ])
 
-proc Bar(n: int, m: openarray[int64]) =
+proc Bar(n: int, m: openArray[int64]) =
   echo($n & " - " & repr(m))
 
 Foo(5, Bar) #OUT 5 - [1]
diff --git a/tests/openarray/topenlen.nim b/tests/openarray/topenlen.nim
index 83d58ac5c..164241b85 100644
--- a/tests/openarray/topenlen.nim
+++ b/tests/openarray/topenlen.nim
@@ -5,7 +5,7 @@ discard """
 
 proc choose(b: openArray[string]): string = return b[0]
 
-proc p(a, b: openarray[string]): int =
+proc p(a, b: openArray[string]): int =
   result = a.len + b.len - 1
   for j in 0 .. a.len: inc(result)
   discard choose(a)
diff --git a/tests/openarray/tptrarrayderef.nim b/tests/openarray/tptrarrayderef.nim
index 5e77430d1..1b7ef0df0 100644
--- a/tests/openarray/tptrarrayderef.nim
+++ b/tests/openarray/tptrarrayderef.nim
@@ -15,14 +15,14 @@ var
   raa = [11,12,13]
 
 #bug #3586
-proc mutate[T](arr:openarray[T], brr: openArray[T]) =
+proc mutate[T](arr:openArray[T], brr: openArray[T]) =
   for i in 0..arr.len-1:
     doAssert(arr[i] == brr[i])
 
 mutate(arr, arr)
 
 #bug #2240
-proc f(a: openarray[int], b: openArray[int]) =
+proc f(a: openArray[int], b: openArray[int]) =
   for i in 0..a.len-1:
    doAssert(a[i] == b[i])
 
@@ -37,7 +37,7 @@ ra[2] = 13
 f(ra[], raa)
 
 #bug #2240b
-proc fillBuffer(buf: var openarray[char]) =
+proc fillBuffer(buf: var openArray[char]) =
   for i in 0..buf.len-1:
     buf[i] = chr(i)
 
diff --git a/tests/openarray/tuncheckedarray.nim b/tests/openarray/tuncheckedarray.nim
new file mode 100644
index 000000000..c8ca9d2d4
--- /dev/null
+++ b/tests/openarray/tuncheckedarray.nim
@@ -0,0 +1,19 @@
+discard """
+  exitcode: 0
+  targets: "c cpp"
+"""
+
+proc main =
+  block: # issue 19171
+    var a = ['A']
+    proc mutB(x: var openArray[char]) =
+      x[0] = 'B'
+    mutB(toOpenArray(cast[ptr UncheckedArray[char]](addr a), 0, 0))
+    doAssert a[0] == 'B'
+    proc mutC(x: var openArray[char]; c: char) =
+      x[0] = c
+    let p = cast[ptr UncheckedArray[char]](addr a)
+    mutC(toOpenArray(p, 0, 0), 'C')
+    doAssert p[0] == 'C'
+
+main()
diff --git a/tests/options/tnimbasepattern.nim b/tests/options/tnimbasepattern.nim
new file mode 100644
index 000000000..1237af5c5
--- /dev/null
+++ b/tests/options/tnimbasepattern.nim
@@ -0,0 +1,26 @@
+discard """
+  cmd: "nim cpp --nimbasepattern:test.h --cincludes:./tests/options $file "
+  output:'''
+(a: 1)
+'''
+"""
+const header = """
+#pragma once
+#include "nimbase.h"
+struct Foo {
+  int a;
+};
+"""
+
+import os
+static:
+  const dir = "./tests/options/"
+  createDir(dir)
+  writeFile(dir / "test.h", header)
+
+type 
+  Foo {.importc.} = object
+    a: int32 = 1
+  
+
+echo $Foo()
\ No newline at end of file
diff --git a/tests/osproc/passenv.nim b/tests/osproc/passenv.nim
index 815f7536f..40b1c3f7c 100644
--- a/tests/osproc/passenv.nim
+++ b/tests/osproc/passenv.nim
@@ -1,7 +1,7 @@
 discard """
   file: "passenv.nim"
   output: "123"
-  targets: "c c++ objc"
+  targets: "c cpp objc"
 """
 
 import osproc, os, strtabs
diff --git a/tests/osproc/ta_in.nim b/tests/osproc/ta_in.nim
deleted file mode 100644
index fb294ec14..000000000
--- a/tests/osproc/ta_in.nim
+++ /dev/null
@@ -1,9 +0,0 @@
-discard """
-action: compile
-"""
-
-# This file is prefixed with an "a", because other tests
-# depend on it and it must be compiled first.
-import strutils
-let x = stdin.readLine()
-echo x.parseInt + 5
diff --git a/tests/osproc/ta_out.nim b/tests/osproc/ta_out.nim
deleted file mode 100644
index 01b78eb11..000000000
--- a/tests/osproc/ta_out.nim
+++ /dev/null
@@ -1,33 +0,0 @@
-discard """
-output: '''
-start ta_out
-to stdout
-to stdout
-to stderr
-to stderr
-to stdout
-to stdout
-end ta_out
-'''
-"""
-
-echo "start ta_out"
-
-# This file is prefixed with an "a", because other tests
-# depend on it and it must be compiled first.
-stdout.writeLine("to stdout")
-stdout.flushFile()
-stdout.writeLine("to stdout")
-stdout.flushFile()
-
-stderr.writeLine("to stderr")
-stderr.flushFile()
-stderr.writeLine("to stderr")
-stderr.flushFile()
-
-stdout.writeLine("to stdout")
-stdout.flushFile()
-stdout.writeLine("to stdout")
-stdout.flushFile()
-
-echo "end ta_out"
diff --git a/tests/osproc/tafalse.nim b/tests/osproc/tafalse.nim
deleted file mode 100644
index 05a0bfce9..000000000
--- a/tests/osproc/tafalse.nim
+++ /dev/null
@@ -1,7 +0,0 @@
-discard """
-exitcode: 1
-"""
-
-# 'tafalse.nim' to ensure it is compiled before texitcode.nim
-import system
-quit(QuitFailure)
diff --git a/tests/osproc/tclose.nim b/tests/osproc/tclose.nim
index d466b466a..1c99237c7 100644
--- a/tests/osproc/tclose.nim
+++ b/tests/osproc/tclose.nim
@@ -13,12 +13,12 @@ when defined(linux):
   let initCount = countFds()
 
   let p = osproc.startProcess("echo", options={poUsePath})
-  assert countFds() == initCount + 3
+  doAssert countFds() == initCount + 3
   p.close
-  assert countFds() == initCount
+  doAssert countFds() == initCount
 
   let p1 = osproc.startProcess("echo", options={poUsePath})
   discard p1.inputStream
-  assert countFds() == initCount + 3
+  doAssert countFds() == initCount + 3
   p.close
-  assert countFds() == initCount
+  doAssert countFds() == initCount
diff --git a/tests/osproc/texecps.nim b/tests/osproc/texecps.nim
index 10715fa0f..b818fe8eb 100644
--- a/tests/osproc/texecps.nim
+++ b/tests/osproc/texecps.nim
@@ -1,3 +1,7 @@
+discard """
+joinable: false
+"""
+
 import osproc, streams, strutils, os
 
 const NumberOfProcesses = 13
diff --git a/tests/osproc/texitcode.nim b/tests/osproc/texitcode.nim
deleted file mode 100644
index 558017716..000000000
--- a/tests/osproc/texitcode.nim
+++ /dev/null
@@ -1,23 +0,0 @@
-discard """
-  output: ""
-"""
-
-import osproc, os
-
-const filename = when defined(Windows): "tafalse.exe" else: "tafalse"
-let dir = getCurrentDir() / "tests" / "osproc"
-doAssert fileExists(dir / filename)
-
-var p = startProcess(filename, dir)
-doAssert(waitForExit(p) == QuitFailure)
-
-p = startProcess(filename, dir)
-var running = true
-while running:
-  running = running(p)
-doAssert(waitForExit(p) == QuitFailure)
-
-# make sure that first call to running() after process exit returns false
-p = startProcess(filename, dir)
-os.sleep(500)
-doAssert(not running(p))
diff --git a/tests/osproc/tnoexe.nim b/tests/osproc/tnoexe.nim
new file mode 100644
index 000000000..19a3cca67
--- /dev/null
+++ b/tests/osproc/tnoexe.nim
@@ -0,0 +1,27 @@
+discard """
+  output: '''true
+true'''
+"""
+
+import std/osproc
+
+const command = "lsaaa -lah"
+
+try:
+  let process = startProcess(command, options = {poUsePath})
+  discard process.waitForExit()
+except OSError as e:
+  echo e.errorCode != 0
+
+# `poEvalCommand`, invokes the system shell to run the specified command
+try:
+  let process = startProcess(command, options = {poUsePath, poEvalCommand})
+  # linux
+  let exitCode = process.waitForExit()
+  echo exitCode != 0
+except OSError as e:
+  # Because the implementation of `poEvalCommand` on different platforms is inconsistent, 
+  # Linux will not throw an exception, but Windows will throw an exception
+
+  # windows
+  echo e.errorCode != 0
diff --git a/tests/osproc/treadlines.nim b/tests/osproc/treadlines.nim
new file mode 100644
index 000000000..bb6a7f129
--- /dev/null
+++ b/tests/osproc/treadlines.nim
@@ -0,0 +1,23 @@
+discard """
+  output: '''
+Error: cannot open 'a.nim'
+Error: cannot open 'b.nim'
+'''
+  targets: "c"
+"""
+
+import osproc
+from std/os import getCurrentCompilerExe
+
+var ps: seq[Process] # compile & run 2 progs in parallel
+const nim = getCurrentCompilerExe()
+for prog in ["a", "b"]:
+  ps.add startProcess(nim, "",
+                      ["r", "--hint:Conf:off", "--hint:Processing:off", prog],
+                      options = {poUsePath, poDaemon, poStdErrToStdOut})
+
+for p in ps:
+  let (lines, exCode) = p.readLines
+  if exCode != 0:
+    for line in lines: echo line
+  p.close
diff --git a/tests/osproc/tstderr.nim b/tests/osproc/tstderr.nim
deleted file mode 100644
index 55b11eba5..000000000
--- a/tests/osproc/tstderr.nim
+++ /dev/null
@@ -1,37 +0,0 @@
-discard """
-  output: '''
-start tstderr
---------------------------------------
-to stderr
-to stderr
---------------------------------------
-'''
-"""
-
-echo "start tstderr"
-
-import osproc, os, streams
-
-const filename = "ta_out".addFileExt(ExeExt)
-
-doAssert fileExists(getCurrentDir() / "tests" / "osproc" / filename)
-
-var p = startProcess(filename, getCurrentDir() / "tests" / "osproc",
-                     options={})
-
-try:
-  let stdoutStream = p.outputStream
-  let stderrStream = p.errorStream
-  var x = newStringOfCap(120)
-  var output = ""
-  while stderrStream.readLine(x.TaintedString):
-    output.add(x & "\n")
-
-  echo "--------------------------------------"
-  stdout.flushFile()
-  stderr.write output
-  stderr.flushFile()
-  echo "--------------------------------------"
-  stdout.flushFile()
-finally:
-  p.close()
diff --git a/tests/osproc/tstdin.nim b/tests/osproc/tstdin.nim
deleted file mode 100644
index 8579680ab..000000000
--- a/tests/osproc/tstdin.nim
+++ /dev/null
@@ -1,17 +0,0 @@
-discard """
-  output: "10"
-"""
-import osproc, os, streams
-
-const filename = when defined(Windows): "ta_in.exe" else: "ta_in"
-
-doAssert fileExists(getCurrentDir() / "tests" / "osproc" / filename)
-
-var p = startProcess(filename, getCurrentDir() / "tests" / "osproc")
-p.inputStream.write("5\n")
-p.inputStream.flush()
-
-var line = ""
-
-while p.outputStream.readLine(line.TaintedString):
-  echo line
diff --git a/tests/osproc/tstdout.nim b/tests/osproc/tstdout.nim
deleted file mode 100644
index e3ed3986a..000000000
--- a/tests/osproc/tstdout.nim
+++ /dev/null
@@ -1,31 +0,0 @@
-discard """
-  output: '''--------------------------------------
-start ta_out
-to stdout
-to stdout
-to stderr
-to stderr
-to stdout
-to stdout
-end ta_out
---------------------------------------
-'''
-"""
-import osproc, os, streams
-
-const filename = when defined(Windows): "ta_out.exe" else: "ta_out"
-
-doAssert fileExists(getCurrentDir() / "tests" / "osproc" / filename)
-
-var p = startProcess(filename, getCurrentDir() / "tests" / "osproc",
-                     options={poStdErrToStdOut})
-
-let outputStream = p.outputStream
-var x = newStringOfCap(120)
-var output = ""
-while outputStream.readLine(x.TaintedString):
-  output.add(x & "\n")
-
-echo "--------------------------------------"
-stdout.write output
-echo "--------------------------------------"
diff --git a/tests/osproc/twaitforexit.nim b/tests/osproc/twaitforexit.nim
new file mode 100644
index 000000000..535faca63
--- /dev/null
+++ b/tests/osproc/twaitforexit.nim
@@ -0,0 +1,38 @@
+import std/[osproc, os, times]
+
+block: # bug #5091
+    when defined(linux):
+        const filename = "false"
+        var p = startProcess(filename, options = {poStdErrToStdOut, poUsePath})
+        os.sleep(1000) # make sure process has exited already
+
+        let atStart = getTime()
+        const msWait = 2000
+
+        try:
+            discard waitForExit(p, msWait)
+        except OSError:
+            discard
+
+        # check that we don't have to wait msWait milliseconds
+        doAssert(getTime() <  atStart + milliseconds(msWait))
+
+block: # bug #23825
+
+    # the sleep command might not be available in all Windows installations
+
+    when defined(linux):
+
+        var thr: array[0..99, Thread[int]]
+
+        proc threadFunc(i: int) {.thread.} =
+            let sleepTime = float(i) / float(thr.len + 1)
+            doAssert sleepTime < 1.0
+            let p = startProcess("sleep", workingDir = "", args = @[$sleepTime], options = {poUsePath, poParentStreams})
+            # timeout = 1_000_000 seconds ~= 278 hours ~= 11.5 days
+            doAssert p.waitForExit(timeout=1_000_000_000) == 0
+
+        for i in low(thr)..high(thr):
+            createThread(thr[i], threadFunc, i)
+
+        joinThreads(thr) 
diff --git a/tests/overflow/tdistinct_range.nim b/tests/overflow/tdistinct_range.nim
new file mode 100644
index 000000000..f53515d45
--- /dev/null
+++ b/tests/overflow/tdistinct_range.nim
@@ -0,0 +1,6 @@
+discard """
+  outputsub: "Error: unhandled exception: over- or underflow [OverflowDefect]"
+  exitcode: "1"
+"""
+var x: distinct range[0..5]
+dec(x)
\ No newline at end of file
diff --git a/tests/overflow/toverflow.nim b/tests/overflow/toverflow.nim
new file mode 100644
index 000000000..972f929c6
--- /dev/null
+++ b/tests/overflow/toverflow.nim
@@ -0,0 +1,82 @@
+discard """
+  output: "ok"
+  matrix: "--overflowChecks:off; --overflowChecks:off --b:js"
+"""
+# Tests nim's ability to detect overflows
+
+{.push overflowChecks: on.}
+
+var
+  a = high(int)
+  b = -2
+  overflowDetected = false
+
+try:
+  echo(b - a)
+except OverflowDefect:
+  overflowDetected = true
+
+{.pop.} # overflow check
+
+doAssert(overflowDetected)
+
+block: # Overflow checks in a proc
+  var
+    a = high(int)
+    b = -2
+    overflowDetected = false
+
+  {.push overflowChecks: on.}
+  proc foo() =
+    let c = b - a
+  {.pop.}
+
+  try:
+    foo()
+  except OverflowDefect:
+    overflowDetected = true
+
+  doAssert(overflowDetected)
+
+block: # Overflow checks in a forward declared proc
+  var
+    a = high(int)
+    b = -2
+    overflowDetected = false
+
+  proc foo()
+
+  {.push overflowChecks: on.}
+  proc foo() =
+    let c = b - a
+  {.pop.}
+
+  try:
+    foo()
+  except OverflowDefect:
+    overflowDetected = true
+
+  doAssert(overflowDetected)
+
+block: # Overflow checks doesn't affect fwd declaration
+  var
+    a = high(int)
+    b = -2
+    overflowDetected = false
+
+  {.push overflowChecks: on.}
+  proc foo()
+  {.pop.}
+
+  proc foo() =
+    let c = b - a
+
+  try:
+    foo()
+  except OverflowDefect:
+    overflowDetected = true
+
+  doAssert(not overflowDetected)
+
+
+echo "ok"
diff --git a/tests/overflw/toverflw2.nim b/tests/overflow/toverflow2.nim
index 91b900ca4..c06b35c6d 100644
--- a/tests/overflw/toverflw2.nim
+++ b/tests/overflow/toverflow2.nim
@@ -1,5 +1,5 @@
 discard """
-  outputsub: "Error: unhandled exception: over- or underflow [OverflowError]"
+  outputsub: "Error: unhandled exception: over- or underflow [OverflowDefect]"
   exitcode: "1"
 """
 var a : int32 = 2147483647
diff --git a/tests/overflw/toverflw.nim b/tests/overflow/toverflow_reorder.nim
index d96231900..fcf7b0c82 100644
--- a/tests/overflw/toverflw.nim
+++ b/tests/overflow/toverflow_reorder.nim
@@ -1,3 +1,5 @@
+{.experimental: "codeReordering".}
+
 discard """
   output: "ok"
   cmd: "nim $target --overflowChecks:off $options $file"
@@ -12,8 +14,8 @@ var
   overflowDetected = false
 
 try:
-  writeLine(stdout, b - a)
-except OverflowError:
+  echo b - a
+except OverflowDefect:
   overflowDetected = true
 
 {.pop.} # overflow check
@@ -33,7 +35,7 @@ block: # Overflow checks in a proc
 
   try:
     foo()
-  except OverflowError:
+  except OverflowDefect:
     overflowDetected = true
 
   doAssert(overflowDetected)
@@ -53,7 +55,7 @@ block: # Overflow checks in a forward declared proc
 
   try:
     foo()
-  except OverflowError:
+  except OverflowDefect:
     overflowDetected = true
 
   doAssert(overflowDetected)
@@ -73,7 +75,7 @@ block: # Overflow checks doesn't affect fwd declaration
 
   try:
     foo()
-  except OverflowError:
+  except OverflowDefect:
     overflowDetected = true
 
   doAssert(not overflowDetected)
diff --git a/tests/overflw/tovfint.nim b/tests/overflow/tovfint.nim
index 5c440a540..5c440a540 100644
--- a/tests/overflw/tovfint.nim
+++ b/tests/overflow/tovfint.nim
diff --git a/tests/misc/trangechecks.nim b/tests/overflow/trangechecks.nim
index 2c6f0f66d..e48b1272b 100644
--- a/tests/misc/trangechecks.nim
+++ b/tests/overflow/trangechecks.nim
@@ -14,14 +14,14 @@ var x: range[1..10] = 10
 try:
   x += 1
   echo x
-except OverflowError, RangeError:
+except OverflowDefect, RangeDefect:
   expected += 1
   echo x
 
 try:
   inc x
   echo x
-except OverflowError, RangeError:
+except OverflowDefect, RangeDefect:
   expected += 1
   echo x
 
@@ -29,15 +29,20 @@ x = 1
 try:
   x -= 1
   echo x
-except OverflowError, RangeError:
+except OverflowDefect, RangeDefect:
   expected += 1
   echo x
 
 try:
   dec x
   echo x
-except OverflowError, RangeError:
+except OverflowDefect, RangeDefect:
   expected += 1
   echo x
 
 echo expected == 4
+
+# bug #13698
+var
+  x45 = "hello".cstring
+  p = x45.len.int32
diff --git a/tests/overflow/twronginference.nim b/tests/overflow/twronginference.nim
new file mode 100644
index 000000000..34a982976
--- /dev/null
+++ b/tests/overflow/twronginference.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "cannot convert 256 to int8"
+  line: 9
+"""
+
+# issue #23177
+
+var x: int8
+x = 256
+echo x # 0
diff --git a/tests/overload/issue22142/tfail_implicit_ambiguous.nim b/tests/overload/issue22142/tfail_implicit_ambiguous.nim
new file mode 100644
index 000000000..2586e0877
--- /dev/null
+++ b/tests/overload/issue22142/tfail_implicit_ambiguous.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "ambiguous call"
+"""
+type
+  A[T] = object
+  C = object
+
+proc test[T: A](param: T): bool = false
+proc test(param: A): bool = true
+doAssert test(A[C]()) == true  # previously would pass
diff --git a/tests/overload/issue22142/tfail_nested_pointers.nim b/tests/overload/issue22142/tfail_nested_pointers.nim
new file mode 100644
index 000000000..1603d98cb
--- /dev/null
+++ b/tests/overload/issue22142/tfail_nested_pointers.nim
@@ -0,0 +1,12 @@
+discard """
+  errormsg: "ambiguous call"
+"""
+
+type
+  A[T] = object
+  C = object
+    x:int
+proc p[T: A[ptr]](x:ptr[T]):bool = false
+proc p(x: ptr[A[ptr]]):bool = true
+var a: A[ptr[C]]
+doAssert p(a.addr) == true
diff --git a/tests/overload/issue22142/tfail_object_is_generic.nim b/tests/overload/issue22142/tfail_object_is_generic.nim
new file mode 100644
index 000000000..b46795bd5
--- /dev/null
+++ b/tests/overload/issue22142/tfail_object_is_generic.nim
@@ -0,0 +1,16 @@
+discard """
+  errormsg: "ambiguous call"
+"""
+
+#[
+As of the time of writing `object` needs some special
+treament in order to be considered "generic" in the right
+context when used implicitly
+]#
+
+type
+  C = object
+
+proc test[T: object](param: T): bool = false
+proc test(param: object): bool = true  
+doAssert test(C()) == true  # previously would pass
diff --git a/tests/overload/issue22142/tfail_typeclass_var_invar.nim b/tests/overload/issue22142/tfail_typeclass_var_invar.nim
new file mode 100644
index 000000000..07db65fef
--- /dev/null
+++ b/tests/overload/issue22142/tfail_typeclass_var_invar.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "ambiguous call"
+"""
+
+type C = object
+proc test[T: ptr](param: var T): bool = false
+proc test(param: var ptr): bool = true
+var d: ptr[C]
+doAssert test(d) == true  # previously would pass
diff --git a/tests/overload/issue22142/tissue22142_shouldpass.nim b/tests/overload/issue22142/tissue22142_shouldpass.nim
new file mode 100644
index 000000000..90d4efe51
--- /dev/null
+++ b/tests/overload/issue22142/tissue22142_shouldpass.nim
@@ -0,0 +1,68 @@
+type
+  A[T] = object of RootObj
+  B[T] = object
+  C = object
+    x:int
+
+# change (previously true)
+block:
+  proc test[J;H: A[J];T: B[H]](param: T): bool = false
+  proc test[T](param: B[T]): bool = true
+  doAssert test(B[A[int]]()) == false
+block:  # object is more specific then `T`
+  proc p[H:object;T:ptr[H]](param:T):bool = false
+  proc p[T](param:ptr[T]):bool= true
+  var l: ptr[C]
+  doAssert p(l) == false
+block:
+  proc p[T:A[object]](param:T):bool = false
+  proc p[T](param: A[T]):bool= true
+  doAssert p(A[C]()) == false
+block:
+  proc test[H;T: A[H]](param: T): bool = false
+  proc test(param: A): bool = true
+  doAssert test(A[C]()) == false
+
+# change (previously ambiguous)
+block:
+  proc p[T](a: A[T]): bool = false
+  proc p[T: object](a: T): bool = true
+  doAssert p(A[int]()) == false
+block:  # A is more specific than `object`
+  proc test[T: A](param: T): bool = false
+  proc test[T: object](param: T): bool = true
+  doAssert test(A[int]()) == false
+block:
+  proc test[T: A](param: T): bool = false
+  proc test(param: object): bool = true
+  doAssert test(A[int]()) == false
+block:
+  proc test[H;T: A[H]](param: T): bool = false
+  proc test(param: object): bool = true
+  doAssert test(A[C]()) == false
+block:
+  proc test[H;T: A[B[H]]](param: T): bool = false
+  proc test[T: object](param: T): bool = true
+  doAssert test(A[B[int]]()) == false
+block:
+  #[
+  This was referenced in the nim compiler source (`sumGeneric`) as a case
+  that was supposed to not be ambiguous, yet it was
+  ]#
+  proc test[J;H:A[J]; T: A[H]](param: T): bool = false
+  proc test[H;T: A[H]](param: T): bool = true
+  doAssert test(A[A[C]]()) == false
+block:
+  proc test[J;T:A[J]](param: A[T]): bool = false
+  proc test[T](param: A[T]): bool = true
+  doAssert test(A[A[C]]()) == false
+block:
+  proc test[T](param: A[T]): bool = false
+  proc test[T: object](param: A[T]): bool = true
+  doAssert test(A[C]()) == true
+
+
+block: #anti-regression (object is more specific then `T`)
+  proc test[J;T:A[J]](param: A[T]): bool = false
+  proc test(param: A[A[object]]): bool = true
+  doAssert test(A[A[C]]()) == true
\ No newline at end of file
diff --git a/tests/overload/m19737.nim b/tests/overload/m19737.nim
new file mode 100644
index 000000000..7f7ac98e2
--- /dev/null
+++ b/tests/overload/m19737.nim
@@ -0,0 +1,10 @@
+type
+  UInt128* = object
+    lo, hi: uint64
+
+func `<`*(x, y: UInt128): bool =
+  (x.hi < y.hi) or ((x.hi == y.hi) and (x.lo < y.lo))
+
+when not defined(works):
+  func `>`*(x, y: UInt128): bool =
+    (x.hi > y.hi) or ((x.hi == y.hi) and (x.lo > y.lo))
diff --git a/tests/overload/mvaruintconv.nim b/tests/overload/mvaruintconv.nim
new file mode 100644
index 000000000..b889c90cf
--- /dev/null
+++ b/tests/overload/mvaruintconv.nim
@@ -0,0 +1,145 @@
+import
+  std/[macros, tables, hashes]
+
+export
+  macros
+
+type
+  FieldDescription* = object
+    name*: NimNode
+    isPublic*: bool
+    isDiscriminator*: bool
+    typ*: NimNode
+    pragmas*: NimNode
+    caseField*: NimNode
+    caseBranch*: NimNode
+
+{.push raises: [].}
+
+func isTuple*(t: NimNode): bool =
+  t.kind == nnkBracketExpr and t[0].kind == nnkSym and eqIdent(t[0], "tuple")
+
+macro isTuple*(T: type): untyped =
+  newLit(isTuple(getType(T)[1]))
+
+proc collectFieldsFromRecList(result: var seq[FieldDescription],
+                              n: NimNode,
+                              parentCaseField: NimNode = nil,
+                              parentCaseBranch: NimNode = nil,
+                              isDiscriminator = false) =
+  case n.kind
+  of nnkRecList:
+    for entry in n:
+      collectFieldsFromRecList result, entry,
+                               parentCaseField, parentCaseBranch
+  of nnkRecWhen:
+    for branch in n:
+      case branch.kind:
+      of nnkElifBranch:
+        collectFieldsFromRecList result, branch[1],
+                                 parentCaseField, parentCaseBranch
+      of nnkElse:
+        collectFieldsFromRecList result, branch[0],
+                                 parentCaseField, parentCaseBranch
+      else:
+        doAssert false
+
+  of nnkRecCase:
+    collectFieldsFromRecList result, n[0],
+                             parentCaseField,
+                             parentCaseBranch,
+                             isDiscriminator = true
+
+    for i in 1 ..< n.len:
+      let branch = n[i]
+      case branch.kind
+      of nnkOfBranch:
+        collectFieldsFromRecList result, branch[^1], n[0], branch
+      of nnkElse:
+        collectFieldsFromRecList result, branch[0], n[0], branch
+      else:
+        doAssert false
+
+  of nnkIdentDefs:
+    let fieldType = n[^2]
+    for i in 0 ..< n.len - 2:
+      var field: FieldDescription
+      field.name = n[i]
+      field.typ = fieldType
+      field.caseField = parentCaseField
+      field.caseBranch = parentCaseBranch
+      field.isDiscriminator = isDiscriminator
+
+      if field.name.kind == nnkPragmaExpr:
+        field.pragmas = field.name[1]
+        field.name = field.name[0]
+
+      if field.name.kind == nnkPostfix:
+        field.isPublic = true
+        field.name = field.name[1]
+
+      result.add field
+
+  of nnkSym:
+    result.add FieldDescription(
+      name: n,
+      typ: getType(n),
+      caseField: parentCaseField,
+      caseBranch: parentCaseBranch,
+      isDiscriminator: isDiscriminator)
+
+  of nnkNilLit, nnkDiscardStmt, nnkCommentStmt, nnkEmpty:
+    discard
+
+  else:
+    doAssert false, "Unexpected nodes in recordFields:\n" & n.treeRepr
+
+proc collectFieldsInHierarchy(result: var seq[FieldDescription],
+                              objectType: NimNode) =
+  var objectType = objectType
+
+  objectType.expectKind {nnkObjectTy, nnkRefTy}
+
+  if objectType.kind == nnkRefTy:
+    objectType = objectType[0]
+
+  objectType.expectKind nnkObjectTy
+
+  var baseType = objectType[1]
+  if baseType.kind != nnkEmpty:
+    baseType.expectKind nnkOfInherit
+    baseType = baseType[0]
+    baseType.expectKind nnkSym
+    baseType = getImpl(baseType)
+    baseType.expectKind nnkTypeDef
+    baseType = baseType[2]
+    baseType.expectKind {nnkObjectTy, nnkRefTy}
+    collectFieldsInHierarchy result, baseType
+
+  let recList = objectType[2]
+  collectFieldsFromRecList result, recList
+
+proc recordFields*(typeImpl: NimNode): seq[FieldDescription] =
+  if typeImpl.isTuple:
+    for i in 1 ..< typeImpl.len:
+      result.add FieldDescription(typ: typeImpl[i], name: ident("Field" & $(i - 1)))
+    return
+
+  let objectType = case typeImpl.kind
+    of nnkObjectTy: typeImpl
+    of nnkTypeDef: typeImpl[2]
+    else:
+      macros.error("object type expected", typeImpl)
+      return
+
+  collectFieldsInHierarchy(result, objectType)
+
+macro field*(obj: typed, fieldName: static string): untyped =
+  newDotExpr(obj, ident fieldName)
+
+proc skipPragma*(n: NimNode): NimNode =
+  if n.kind == nnkPragmaExpr: n[0]
+  else: n
+
+
+{.pop.}
diff --git a/tests/overload/t19737.nim b/tests/overload/t19737.nim
new file mode 100644
index 000000000..b33ba9d8b
--- /dev/null
+++ b/tests/overload/t19737.nim
@@ -0,0 +1,15 @@
+# issue #19737
+
+import ./m19737
+
+var m: seq[uint64]
+
+proc foo(x: bool) = discard
+
+proc test[T: uint64|uint32](s: var seq[T]) =
+  var tmp = newSeq[T](1)
+  s = newSeq[T](1)
+
+  foo s[0] > tmp[0]
+
+test(m)
diff --git a/tests/overload/t23249.nim b/tests/overload/t23249.nim
new file mode 100644
index 000000000..f4657833b
--- /dev/null
+++ b/tests/overload/t23249.nim
@@ -0,0 +1,17 @@
+# issue #23249
+
+type Control* = object
+proc onAction*(c: Control, handler: proc(e: int) {.gcsafe.}) = discard
+proc onAction*(c: Control, handler: proc() {.gcsafe.}) = discard
+
+template setControlHandlerBlock(c: Control, p: untyped, a: untyped) =
+    when compiles(c.p(nil)):
+        c.p() do() {.gcsafe.}: a
+    else:
+        c.p = proc() {.gcsafe.} =
+            a
+
+proc mkLayout() =
+  var b: Control
+  setControlHandlerBlock(b, onAction):
+    echo "hi"
diff --git a/tests/overload/t23755.nim b/tests/overload/t23755.nim
new file mode 100644
index 000000000..de338a2ce
--- /dev/null
+++ b/tests/overload/t23755.nim
@@ -0,0 +1,62 @@
+type
+  BigInt[bits: static int] = object
+    limbs: array[8, uint64]
+
+block:
+  proc view[N](a: array[N, uint64]) =
+    discard
+
+  proc view[N](a: var array[N, uint64]) =
+    discard
+
+  var r: BigInt[64]
+  r.limbs.view()
+
+
+type Limbs[N: static int] = array[N, uint64]
+
+block:
+  proc view(a: Limbs) =
+    discard
+
+  proc view(a: var Limbs) =
+    discard
+
+  var r: BigInt[64]
+  r.limbs.view()
+
+
+block:
+  type IntArray[N: static[int]] = array[N, int]
+
+  proc p[T](a: IntArray[T]): bool= true
+  proc p(a: IntArray[5]): bool= false
+
+  var s: IntArray[5]
+  doAssert s.p == false
+
+block:
+  type IntArray[N: static[int]] = array[N, int]
+
+  proc `$`(a: IntArray): string =
+    return "test"
+
+  var s: IntArray[5] = [1,1,1,1,1]
+  doAssert `$`(s) == "test"
+
+block: 
+  proc p[n:static[int]](a: array[n, char]):bool=true
+  proc p[T, IDX](a: array[IDX, T]):bool=false
+
+  var g: array[32, char]
+  doAssert p(g)
+
+block:  # issue #23823
+  func p[N,T](a, b: array[N,T]) =
+    discard
+
+  func p[N: static int; T](x, y: array[N, T]) =
+    discard
+
+  var a: array[5, int]
+  p(a,a)
diff --git a/tests/overload/t7416.nim b/tests/overload/t7416.nim
new file mode 100644
index 000000000..4a9b2e7cb
--- /dev/null
+++ b/tests/overload/t7416.nim
@@ -0,0 +1,9 @@
+type
+  Foo[T] = object
+  IntFoo = Foo[int]
+
+proc bar(b: object|tuple) = discard
+proc bar(b: IntFoo) = discard
+
+var f: IntFoo
+bar(f)
\ No newline at end of file
diff --git a/tests/overload/t8829.nim b/tests/overload/t8829.nim
new file mode 100644
index 000000000..85d87f136
--- /dev/null
+++ b/tests/overload/t8829.nim
@@ -0,0 +1,18 @@
+block:
+  let txt = "Hello World"
+
+  template `[]`[T](p: ptr T, span: Slice[int]): untyped =
+    toOpenArray(cast[ptr UncheckedArray[T]](p), span.a, span.b)
+
+  doAssert $cast[ptr uint8](txt[0].addr)[0 ..< txt.len] == 
+                "[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]"
+
+
+block:
+  let txt = "Hello World"
+
+  template `[]`[T](p: ptr T, span: Slice[int]): untyped =
+    toOpenArray(cast[ptr UncheckedArray[T]](p), span.a, span.b)
+
+  doAssert $cast[ptr uint8](txt[0].addr)[0 ..< txt.len] == 
+                "[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100]"
diff --git a/tests/overload/tgenericalias.nim b/tests/overload/tgenericalias.nim
new file mode 100644
index 000000000..50a44bd32
--- /dev/null
+++ b/tests/overload/tgenericalias.nim
@@ -0,0 +1,13 @@
+block: # issue #13799
+  type
+    X[A, B] = object
+      a: A
+      b: B
+
+    Y[A] = X[A, int]
+  template s(T: type X): X = T()
+  template t[A, B](T: type X[A, B]): X[A, B] = T()
+  proc works1(): Y[int] = s(X[int, int])
+  proc works2(): Y[int] = t(X[int, int])
+  proc works3(): Y[int] = t(Y[int])
+  proc broken(): Y[int] = s(Y[int])
diff --git a/tests/overload/tnamedparamoverloading.nim b/tests/overload/tnamedparamoverloading.nim
new file mode 100644
index 000000000..a7c37ba52
--- /dev/null
+++ b/tests/overload/tnamedparamoverloading.nim
@@ -0,0 +1,14 @@
+discard """
+  output: '''
+Using x: 2
+Using y: 2
+'''
+"""
+
+proc foo(x: int) =
+  echo "Using x: ", x
+proc foo(y: int) =
+  echo "Using y: ", y
+
+foo(x = 2)
+foo(y = 2)
\ No newline at end of file
diff --git a/tests/overload/tor_isnt_better.nim b/tests/overload/tor_isnt_better.nim
index 5ef8bc7c4..bee125386 100644
--- a/tests/overload/tor_isnt_better.nim
+++ b/tests/overload/tor_isnt_better.nim
@@ -1,18 +1,41 @@
-discard """
-  errormsg: "ambiguous call;"
-  line: 16
-"""
-
-# bug #8568
-
 type
   D[T] = object
   E[T] = object
 
-proc g(a: D|E): string = "foo D|E"
-proc g(a: D): string = "foo D"
+block: # PR #22261
+  proc d(x: D):bool= false
+  proc d(x: int | D[SomeInteger]):bool= true
+  doAssert d(D[5]()) == false
 
-proc test() =
-  let x = g D[int]()
+block: # bug #8568
+#[
+  Since PR #22261 and amendment has been made. Since D is a subset of D | E but
+  not the other way around `checkGeneric` should favor proc g(a: D) instead
+  of asserting ambiguity
+]#
+  proc g(a: D|E): string = "foo D|E"
+  proc g(a: D): string = "foo D"
+  doAssert g(D[int]()) == "foo D"
 
-test()
+type Obj1[T] = object
+  v: T
+converter toObj1[T](t: T): Obj1[T] = return Obj1[T](v: t)
+block: # issue #10019
+  proc fun1[T](elements: seq[T]): string = "fun1 seq"
+  proc fun1(o: object|tuple): string = "fun1 object|tuple"
+  proc fun2[T](elements: openArray[T]): string = "fun2 openarray"
+  proc fun2(o: object): string = "fun2 object"
+  proc fun_bug[T](elements: openArray[T]): string = "fun_bug openarray"
+  proc fun_bug(o: object|tuple):string = "fun_bug object|tuple"
+  proc main() =
+    var x = @["hello", "world"]
+    block:
+      # no ambiguity error shown here even though this would compile if we remove either 1st or 2nd overload of fun1
+      doAssert fun1(x) == "fun1 seq"
+    block:
+      # ditto
+      doAssert fun2(x) == "fun2 openarray"
+    block:
+      # Error: ambiguous call; both t0065.fun_bug(elements: openarray[T])[declared in t0065.nim(17, 5)] and t0065.fun_bug(o: object or tuple)[declared in t0065.nim(20, 5)] match for: (array[0..1, string])
+      doAssert fun_bug(x) == "fun_bug openarray"
+  main()
diff --git a/tests/overload/toverl4.nim b/tests/overload/toverl4.nim
index 537925674..21cedaa96 100644
--- a/tests/overload/toverl4.nim
+++ b/tests/overload/toverl4.nim
@@ -1,5 +1,6 @@
 discard """
-  output: '''true'''
+  output: '''true
+5.0'''
 """
 
 #bug #592
@@ -75,3 +76,26 @@ proc add*[TKey, TData](root: var PElement[TKey, TData], key: TKey, data: TData)
 var tree = PElement[int, int](kind: ElementKind.inner, key: 0, left: nil, right: nil)
 let result = add(tree, 1, 1)
 echo(result)
+
+# bug #3748
+type
+  Foo = object
+    bar: int
+
+proc bar(cur: Foo, val: int, s:seq[string]) =
+  discard cur.bar
+
+proc does_fail(): Foo =
+  let a = @["a"]
+  result.bar(5, a)
+
+doAssert does_fail().bar == 0
+
+# bug #20645
+
+type Zzz[Gen] = object
+
+proc testZ(z: Zzz) =
+  echo z.Gen(5)
+
+testZ(Zzz[float]())
diff --git a/tests/overload/toverload_issues.nim b/tests/overload/toverload_issues.nim
index 5db7b54fa..26bf89091 100644
--- a/tests/overload/toverload_issues.nim
+++ b/tests/overload/toverload_issues.nim
@@ -77,27 +77,30 @@ testPred(1)
 
 
 
-# bug #6526
-type
-  BaseObj = ref object of RootObj
-  DerivedObj = ref object of BaseObj
-  OtherDerivate = ref object of BaseObj
-
-proc `==`*[T1, T2: BaseObj](a: T1, b: T2): bool =
-  echo "baseobj =="
-  return true
-
-let a = DerivedObj()
-let b = DerivedObj()
-echo a == b
-
-proc `==`*[T1, T2: OtherDerivate](a: T1, b: T2): bool =
-  echo "even better! =="
-  return true
-
-let a2 = OtherDerivate()
-let b2 = OtherDerivate()
-echo a2 == b2
+block: # bug #6526
+  type
+    BaseObj = ref object of RootObj
+    DerivedObj = ref object of BaseObj
+    OtherDerivate = ref object of BaseObj
+
+  proc p[T](a: T, b: T): bool =
+    assert false
+
+  proc p[T1, T2: BaseObj](a: T1, b: T2): bool =
+    echo "baseobj =="
+    return true
+
+  let a = DerivedObj()
+  let b = DerivedObj()
+  echo p(a,b)
+
+  proc p[T1, T2: OtherDerivate](a: T1, b: T2): bool =
+    echo "even better! =="
+    return true
+
+  let a2 = OtherDerivate()
+  let b2 = OtherDerivate()
+  echo p(a2, b2)
 
 
 
diff --git a/tests/overload/toverload_various.nim b/tests/overload/toverload_various.nim
index 78497e607..d195a069d 100644
--- a/tests/overload/toverload_various.nim
+++ b/tests/overload/toverload_various.nim
@@ -264,9 +264,305 @@ proc init*[T](hmctx: HMAC[T], key: ptr byte, ulen: uint) =
   const sizeBlock = hmctx.sizeBlock
   echo sizeBlock
 
-proc hmac*[A, B](HashType: typedesc, key: openarray[A],
-                 data: openarray[B]) =
+proc hmac*[A, B](HashType: typedesc, key: openArray[A],
+                 data: openArray[B]) =
   var ctx: HMAC[HashType]
   ctx.init(nil, 0)
 
 sha256.hmac("", "")
+
+
+
+# nested generic types
+block:
+  type
+    Foo[T] = object
+      f: T
+    Bar[T] = object
+      b: T
+    Baz[T] = object
+      z: T
+    FooBar[T] = Foo[Bar[T]]
+    FooBarBaz[T] = FooBar[Baz[T]]
+    #Int = int
+    Int = SomeInteger
+    FooBarBazInt = FooBarBaz[Int]
+    FooBarBazX = FooBarBaz[int]
+
+  proc p00(x: Foo): auto = x.f
+  proc p01[T](x: Foo[T]): auto = x.f
+  proc p02[T:Foo](x: T): auto = x.f
+
+  proc p10(x: FooBar): auto = x.f
+  proc p11[T](x: FooBar[T]): auto = x.f
+  proc p12[T:FooBar](x: T): auto = x.f
+  proc p13(x: Foo[Bar]): auto = x.f
+  proc p14[T](x: Foo[Bar[T]]): auto = x.f
+  proc p15[T:Bar](x: Foo[T]): auto = x.f
+  proc p16[T:Foo[Bar]](x: T): auto = x.f
+
+  proc p20(x: FooBarBaz): auto = x.f
+  proc p21[T](x: FooBarBaz[T]): auto = x.f
+  proc p22[T:FooBarBaz](x: T): auto = x.f
+  proc p23(x: FooBar[Baz]): auto = x.f
+  proc p24[T](x: FooBar[Baz[T]]): auto = x.f
+  proc p25[T:Baz](x: FooBar[T]): auto = x.f
+  proc p26[T:FooBar[Baz]](x: T): auto = x.f
+  proc p27(x: Foo[Bar[Baz]]): auto = x.f
+  proc p28[T](x: Foo[Bar[Baz[T]]]): auto = x.f
+  proc p29[T:Baz](x: Foo[Bar[T]]): auto = x.f
+  proc p2A[T:Bar[Baz]](x: Foo[T]): auto = x.f
+  proc p2B[T:Foo[Bar[Baz]]](x: T): auto = x.f
+
+  proc p30(x: FooBarBazInt): auto = x.f
+  proc p31[T:FooBarBazInt](x: T): auto = x.f
+  proc p32(x: FooBarBaz[Int]): auto = x.f
+  proc p33[T:Int](x: FooBarBaz[T]): auto = x.f
+  proc p34[T:FooBarBaz[Int]](x: T): auto = x.f
+  proc p35(x: FooBar[Baz[Int]]): auto = x.f
+  proc p36[T:Int](x: FooBar[Baz[T]]): auto = x.f
+  proc p37[T:Baz[Int]](x: FooBar[T]): auto = x.f
+  proc p38[T:FooBar[Baz[Int]]](x: T): auto = x.f
+  proc p39(x: Foo[Bar[Baz[Int]]]): auto = x.f
+  proc p3A[T:Int](x: Foo[Bar[Baz[T]]]): auto = x.f
+  proc p3B[T:Baz[Int]](x: Foo[Bar[T]]): auto = x.f
+  proc p3C[T:Bar[Baz[Int]]](x: Foo[T]): auto = x.f
+  proc p3D[T:Foo[Bar[Baz[Int]]]](x: T): auto = x.f
+
+  template test(x: typed) =
+    let t00 = p00(x)
+    let t01 = p01(x)
+    let t02 = p02(x)
+    let t10 = p10(x)
+    let t11 = p11(x)
+    let t12 = p12(x)
+    #let t13 = p13(x)
+    let t14 = p14(x)
+    #let t15 = p15(x)
+    #let t16 = p16(x)
+    let t20 = p20(x)
+    let t21 = p21(x)
+    let t22 = p22(x)
+    #let t23 = p23(x)
+    let t24 = p24(x)
+    #let t25 = p25(x)
+    #let t26 = p26(x)
+    #let t27 = p27(x)
+    let t28 = p28(x)
+    #let t29 = p29(x)
+    #let t2A = p2A(x)
+    #let t2B = p2B(x)
+    let t30 = p30(x)
+    let t31 = p31(x)
+    let t32 = p32(x)
+    let t33 = p33(x)
+    let t34 = p34(x)
+    let t35 = p35(x)
+    let t36 = p36(x)
+    let t37 = p37(x)
+    let t38 = p38(x)
+    let t39 = p39(x)
+    let t3A = p3A(x)
+    let t3B = p3B(x)
+    let t3C = p3C(x)
+    let t3D = p3D(x)
+
+  var a: Foo[Bar[Baz[int]]]
+  test(a)
+  var b: FooBar[Baz[int]]
+  test(b)
+  var c: FooBarBaz[int]
+  test(c)
+  var d: FooBarBazX
+  test(d)
+
+
+# overloading on tuples with generic alias
+block:
+  type
+    Foo[F,T] = object
+      exArgs: T
+    FooUn[F,T] = Foo[F,tuple[a:T]]
+    FooBi[F,T1,T2] = Foo[F,tuple[a:T1,b:T2]]
+
+  proc foo1[F,T](x: Foo[F,tuple[a:T]]): int = 1
+  proc foo1[F,T1,T2](x: Foo[F,tuple[a:T1,b:T2]]): int = 2
+  proc foo2[F,T](x: FooUn[F,T]): int = 1
+  proc foo2[F,T1,T2](x: FooBi[F,T1,T2]):int = 2
+
+  template bar1[F,T](x: Foo[F,tuple[a:T]]): int = 1
+  template bar1[F,T1,T2](x: Foo[F,tuple[a:T1,b:T2]]): int = 2
+  template bar2[F,T](x: FooUn[F,T]): int = 1
+  template bar2[F,T1,T2](x: FooBi[F,T1,T2]): int = 2
+
+  proc test(x: auto, n: int) =
+    doAssert(foo1(x) == n)
+    doAssert(foo2(x) == n)
+    doAssert(bar1(x) == n)
+    doAssert(bar2(x) == n)
+
+  var a: Foo[int, tuple[a:int]]
+  test(a, 1)
+  var b: FooUn[int, int]
+  test(b, 1)
+  var c: Foo[int, tuple[a:int,b:int]]
+  test(c, 2)
+  var d: FooBi[int, int, int]
+  test(d, 2)
+
+
+# inheritance and generics
+block:
+  type
+    Foo[T] = object of RootObj
+      x: T
+    Bar[T] = object of Foo[T]
+      y: T
+    Baz[T] = object of Bar[T]
+      z: T
+
+  template t0(x: Foo[int]): int = 0
+  template t0(x: Bar[int]): int = 1
+  template t0(x: Foo[bool or int]): int = 10
+  template t0(x: Bar[bool or int]): int = 11
+  #template t0[T:bool or int](x: Bar[T]): int = 11
+  template t0[T](x: Foo[T]): int = 20
+  template t0[T](x: Bar[T]): int = 21
+  proc p0(x: Foo[int]): int = 0
+  proc p0(x: Bar[int]): int = 1
+  #proc p0(x: Foo[bool or int]): int = 10
+  #proc p0(x: Bar[bool or int]): int = 11
+  proc p0[T](x: Foo[T]): int = 20
+  proc p0[T](x: Bar[T]): int = 21
+
+  var a: Foo[int]
+  var b: Bar[int]
+  var c: Baz[int]
+  var d: Foo[bool]
+  var e: Bar[bool]
+  var f: Baz[bool]
+  var g: Foo[float]
+  var h: Bar[float]
+  var i: Baz[float]
+  doAssert(t0(a) == 0)
+  doAssert(t0(b) == 1)
+  doAssert(t0(c) == 1)
+  doAssert(t0(d) == 10)
+  doAssert(t0(e) == 11)
+  doAssert(t0(f) == 11)
+  doAssert(t0(g) == 20)
+  doAssert(t0(h) == 21)
+  #doAssert(t0(i) == 21)
+  doAssert(p0(a) == 0)
+  doAssert(p0(b) == 1)
+  doAssert(p0(c) == 1)
+  #doAssert(p0(d) == 10)
+  #doAssert(p0(e) == 11)
+  #doAssert(p0(f) == 11)
+  doAssert(p0(g) == 20)
+  doAssert(p0(h) == 21)
+  doAssert(p0(i) == 21)
+
+  #type
+  #  f0 = proc(x:Foo)
+
+
+block:
+  type
+    TilesetCT[n: static[int]] = distinct int
+    TilesetRT = int
+    Tileset = TilesetCT | TilesetRT
+
+  func prepareTileset(tileset: var Tileset) = discard
+
+  func prepareTileset(tileset: Tileset): Tileset =
+    result = tileset
+    result.prepareTileset
+
+  var parsedTileset: TilesetRT
+  prepareTileset(parsedTileset)
+
+
+block:
+  proc p1[T,U: SomeInteger|SomeFloat](x: T, y: U): int|float =
+    when T is SomeInteger and U is SomeInteger:
+      result = int(x) + int(y)
+    else:
+      result = float(x) + float(y)
+  doAssert(p1(1,2) == 3)
+  doAssert(p1(1.0,2) == 3.0)
+  doAssert(p1(1,2.0) == 3.0)
+  doAssert(p1(1.0,2.0) == 3.0)
+
+  type Foo[T,U] = U
+  template F[T,U](t: typedesc[T], x: U): untyped = Foo[T,U](x)
+  proc p2[T; U,V:Foo[T,SomeNumber]](x: U, y: V): T =
+    T(x) + T(y)
+  #proc p2[T; U:Foo[T,SomeNumber], V:Foo[not T,SomeNumber]](x: U, y: V): T =
+  #  T(x) + T(y)
+  doAssert(p2(F(int,1),F(int,2)) == 3)
+  doAssert(p2(F(float,1),F(float,2)) == 3.0)
+  doAssert(p2(F(float,1),F(float,2.0)) == 3.0)
+  doAssert(p2(F(float,1.0),F(float,2)) == 3.0)
+  doAssert(p2(F(float,1.0),F(float,2.0)) == 3.0)
+  #doAssert(p2(F(float,1),F(int,2.0)) == 3.0)
+
+block: # PR #23870
+  type
+    A {.inheritable.} = object
+    B = object of A
+    C = object of B
+
+  proc p[T: A](x: T): int = 0
+  proc p[T: B](x: T): int = 1
+
+  proc d(x: A): int = 0
+  proc d(x: B): int = 1
+  
+  proc g[T:A](x: typedesc[T]): int = 0
+  proc g[T: B](x: typedesc[T]): int = 1
+  
+  proc f[T](x: typedesc[T]): int = 0
+  proc f[T:B](x: typedesc[T]): int = 1
+
+  assert p(C()) == 1
+  assert d(C()) == 1
+  assert g(C) == 1
+  assert f(C) == 1
+
+block: # PR #23870
+  type
+    A = object of RootObj
+    PT = proc(ev: A) {.closure.}
+    sdt = seq[(PT, PT)]
+
+  proc encap() =
+    proc p(a: A) {.closure.} =
+      discard
+
+    var s: sdt
+    s.add (p, nil)
+
+  encap()
+
+block: # PR #23870
+  type
+    A = object of RootObj
+    B = object of A
+    C = object of B
+
+  proc p(a: B | RootObj): int =
+    0
+
+  proc p(a: A | A): int =
+    1
+
+  assert p(C()) == 0
+
+  proc d(a: RootObj | B): int =
+    0
+
+  proc d(a: A | A): int =
+    1
+
+  assert d(C()) == 0
diff --git a/tests/overload/tproc_types_dont_like_subtypes.nim b/tests/overload/tproc_types_dont_like_subtypes.nim
new file mode 100644
index 000000000..6774be156
--- /dev/null
+++ b/tests/overload/tproc_types_dont_like_subtypes.nim
@@ -0,0 +1,20 @@
+discard """
+  errormsg: "got <B, proc (b: B){.closure, gcsafe.}>"
+  line: 20
+"""
+
+type
+  A = ref object of RootObj
+  B = ref object of A
+
+  P = proc (a: A)
+
+# bug #16325
+
+proc doThings(a: A, p: P) =
+  p(a)
+
+var x = proc (b: B) {.closure.} =
+  echo "B"
+
+doThings(B(), x)
diff --git a/tests/overload/tselfderef.nim b/tests/overload/tselfderef.nim
deleted file mode 100644
index 96f1da42a..000000000
--- a/tests/overload/tselfderef.nim
+++ /dev/null
@@ -1,20 +0,0 @@
-discard """
-action: compile
-"""
-
-# bug #4671
-{.experimental.}
-{.this: self.}
-type
-  SomeObj = object
-    f: int
-
-proc f(num: int) =
-  discard
-
-var intptr: ptr int
-intptr.f() # compiles fine
-
-proc doSomething(self: var SomeObj) =
-  var pint: ptr int
-  pint.f() # Error: expression '.(pint, "f")' cannot be called
diff --git a/tests/overload/tstatic_with_converter.nim b/tests/overload/tstatic_with_converter.nim
index 2871744eb..2bc1dfaab 100644
--- a/tests/overload/tstatic_with_converter.nim
+++ b/tests/overload/tstatic_with_converter.nim
@@ -1,6 +1,7 @@
 discard """
 output: '''
-9.0'''
+9.0
+'''
 """
 
 ### bug #6773
@@ -37,11 +38,11 @@ proc `^`(x: vfloat, exp: static[float]): vfloat =
   when exp == 0.5:
     sqrt(x)
   else:
-   pow(x, exp)
+    pow(x, exp)
  
 proc `$`(x: vfloat): string =
-  let y = cast[ptr float](unsafeAddr x)
-  echo y[]
+  let y = cast[ptr float](addr x)
+  result = $y[]
  
 let x = set1(9.0)
 echo x^0.5
diff --git a/tests/overload/tuntypedarg.nim b/tests/overload/tuntypedarg.nim
new file mode 100644
index 000000000..9aa4fad3b
--- /dev/null
+++ b/tests/overload/tuntypedarg.nim
@@ -0,0 +1,19 @@
+import macros
+
+block: # issue #7385
+  type CustomSeq[T] = object
+    data: seq[T]
+  macro `[]`[T](s: CustomSeq[T], args: varargs[untyped]): untyped =
+    ## The end goal is to replace the joker "_" by something else
+    result = newIntLitNode(10)
+  proc foo1(): CustomSeq[int] =
+    result.data.newSeq(10)
+    # works since no overload matches first argument with type `CustomSeq`
+    # except magic `[]`, which always matches without checking arguments
+    doAssert result[_] == 10
+  doAssert foo1() == CustomSeq[int](data: newSeq[int](10))
+  proc foo2[T](): CustomSeq[T] =
+    result.data.newSeq(10)
+    # works fine with generic return type
+    doAssert result[_] == 10
+  doAssert foo2[int]() == CustomSeq[int](data: newSeq[int](10))
diff --git a/tests/overload/tvartypeclass.nim b/tests/overload/tvartypeclass.nim
new file mode 100644
index 000000000..04f3f5a91
--- /dev/null
+++ b/tests/overload/tvartypeclass.nim
@@ -0,0 +1,11 @@
+# issue #13302
+
+proc foo(x: object): int = x.i*2
+proc foo(x: var object) = x.i*=2
+type Foo = object
+  i: int
+let x = Foo(i: 3)
+var y = Foo(i: 4)
+doAssert foo(x) == 6
+foo(y)
+doAssert y.i == 8
diff --git a/tests/overload/tvaruintconv.nim b/tests/overload/tvaruintconv.nim
new file mode 100644
index 000000000..87ebd285d
--- /dev/null
+++ b/tests/overload/tvaruintconv.nim
@@ -0,0 +1,207 @@
+discard """
+  action: compile
+"""
+
+# https://github.com/status-im/nimbus-eth2/pull/6554#issuecomment-2354977102
+# failed with "for a 'var' type a variable needs to be passed; but 'uint64(result)' is immutable"
+
+import
+  std/[typetraits, macros]
+
+type
+  DefaultFlavor = object
+
+template serializationFormatImpl(Name: untyped) {.dirty.} =
+  type Name = object
+
+template serializationFormat(Name: untyped) =
+  serializationFormatImpl(Name)
+
+template setReader(Format, FormatReader: distinct type) =
+  when arity(FormatReader) > 1:
+    template Reader(T: type Format, F: distinct type = DefaultFlavor): type = FormatReader[F]
+  else:
+    template ReaderType(T: type Format): type = FormatReader
+    template Reader(T: type Format): type = FormatReader
+
+template useDefaultReaderIn(T: untyped, Flavor: type) =
+  mixin Reader
+
+  template readValue(r: var Reader(Flavor), value: var T) =
+    mixin readRecordValue
+    readRecordValue(r, value)
+
+import mvaruintconv
+
+type
+  FieldTag[RecordType: object; fieldName: static string] = distinct void
+
+func declval*(T: type): T {.compileTime.} =
+  default(ptr T)[]
+
+macro enumAllSerializedFieldsImpl(T: type, body: untyped): untyped =
+  var typeAst = getType(T)[1]
+  var typeImpl: NimNode
+  let isSymbol = not typeAst.isTuple
+
+  if not isSymbol:
+    typeImpl = typeAst
+  else:
+    typeImpl = getImpl(typeAst)
+  result = newStmtList()
+
+  var i = 0
+  for field in recordFields(typeImpl):
+    let
+      fieldIdent = field.name
+      realFieldName = newLit($fieldIdent.skipPragma)
+      fieldName = realFieldName
+      fieldIndex = newLit(i)
+
+    let fieldNameDefs =
+      if isSymbol:
+        quote:
+          const fieldName {.inject, used.} = `fieldName`
+          const realFieldName {.inject, used.} = `realFieldName`
+      else:
+        quote:
+          const fieldName {.inject, used.} = $`fieldIndex`
+          const realFieldName {.inject, used.} = $`fieldIndex`
+
+    let field =
+      if isSymbol:
+        quote do: declval(`T`).`fieldIdent`
+      else:
+        quote do: declval(`T`)[`fieldIndex`]
+
+    result.add quote do:
+      block:
+        `fieldNameDefs`
+
+        template FieldType: untyped {.inject, used.} = typeof(`field`)
+
+        `body`
+
+  # echo repr(result)
+
+template enumAllSerializedFields(T: type, body): untyped =
+  enumAllSerializedFieldsImpl(T, body)
+
+type
+  FieldReader[RecordType, Reader] = tuple[
+    fieldName: string,
+    reader: proc (rec: var RecordType, reader: var Reader)
+                 {.gcsafe, nimcall.}
+  ]
+
+proc totalSerializedFieldsImpl(T: type): int =
+  mixin enumAllSerializedFields
+  enumAllSerializedFields(T): inc result
+
+template totalSerializedFields(T: type): int =
+  (static(totalSerializedFieldsImpl(T)))
+
+template GetFieldType(FT: type FieldTag): type =
+  typeof field(declval(FT.RecordType), FT.fieldName)
+
+proc makeFieldReadersTable(RecordType, ReaderType: distinct type,
+                           numFields: static[int]):
+                           array[numFields, FieldReader[RecordType, ReaderType]] =
+  mixin enumAllSerializedFields, handleReadException
+  var idx = 0
+
+  enumAllSerializedFields(RecordType):
+    proc readField(obj: var RecordType, reader: var ReaderType)
+                  {.gcsafe, nimcall.} =
+
+      mixin readValue
+
+      type F = FieldTag[RecordType, realFieldName]
+      field(obj, realFieldName) = reader.readValue(GetFieldType(F))
+
+    result[idx] = (fieldName, readField)
+    inc idx
+
+proc fieldReadersTable(RecordType, ReaderType: distinct type): auto =
+  mixin readValue
+  type T = RecordType
+  const numFields = totalSerializedFields(T)
+  var tbl {.threadvar.}: ref array[numFields, FieldReader[RecordType, ReaderType]]
+  if tbl == nil:
+    tbl = new typeof(tbl)
+    tbl[] = makeFieldReadersTable(RecordType, ReaderType, numFields)
+  return addr(tbl[])
+
+proc readValue(reader: var auto, T: type): T =
+  mixin readValue
+  reader.readValue(result)
+
+template decode(Format: distinct type,
+                 input: string,
+                 RecordType: distinct type): auto =
+  mixin Reader
+  block:  # https://github.com/nim-lang/Nim/issues/22874
+    var reader: Reader(Format)
+    reader.readValue(RecordType)
+
+template readValue(Format: type,
+                    ValueType: type): untyped =
+  mixin Reader, init, readValue
+  var reader: Reader(Format)
+  readValue reader, ValueType
+
+template parseArrayImpl(numElem: untyped,
+                        actionValue: untyped) =
+  actionValue
+
+serializationFormat Json
+template createJsonFlavor(FlavorName: untyped,
+                           skipNullFields = false) {.dirty.} =
+  type FlavorName = object
+
+  template Reader(T: type FlavorName): type = Reader(Json, FlavorName)
+type
+  JsonReader[Flavor = DefaultFlavor] = object
+
+Json.setReader JsonReader
+
+template parseArray(r: var JsonReader; body: untyped) =
+  parseArrayImpl(idx): body
+
+template parseArray(r: var JsonReader; idx: untyped; body: untyped) =
+  parseArrayImpl(idx): body
+
+proc readRecordValue[T](r: var JsonReader, value: var T) =
+  type
+    ReaderType {.used.} = type r
+    T = type value
+
+  discard T.fieldReadersTable(ReaderType)
+
+proc readValue[T](r: var JsonReader, value: var T) =
+  mixin readValue
+
+  when value is seq:
+    r.parseArray:
+      readValue(r, value[0])
+
+  elif value is object:
+    readRecordValue(r, value)
+
+type
+  RemoteSignerInfo = object
+    id: uint32
+  RemoteKeystore = object
+
+proc readValue(reader: var JsonReader, value: var RemoteKeystore) =
+  discard reader.readValue(seq[RemoteSignerInfo])
+
+createJsonFlavor RestJson
+useDefaultReaderIn(RemoteSignerInfo, RestJson)
+proc readValue(reader: var JsonReader[RestJson], value: var uint64) =
+  discard reader.readValue(string)
+
+discard Json.decode("", RemoteKeystore)
+block:  # https://github.com/nim-lang/Nim/issues/22874
+  var reader: Reader(RestJson)
+  discard reader.readValue(RemoteSignerInfo)
diff --git a/tests/package/stdlib/stdlib.nimble b/tests/package/stdlib/stdlib.nimble
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/package/stdlib/stdlib.nimble
diff --git a/tests/package/stdlib/system.nim b/tests/package/stdlib/system.nim
new file mode 100644
index 000000000..475f8ec5b
--- /dev/null
+++ b/tests/package/stdlib/system.nim
@@ -0,0 +1,2 @@
+# this module is part of tstdlib_name_not_special
+doAssert true
\ No newline at end of file
diff --git a/tests/package/tstdlib_name_not_special.nim b/tests/package/tstdlib_name_not_special.nim
new file mode 100644
index 000000000..e8226a82d
--- /dev/null
+++ b/tests/package/tstdlib_name_not_special.nim
@@ -0,0 +1,3 @@
+# Test whether a another package named 'stdlib' can be imported and used.
+# This caused a crash in the past.
+import stdlib/system
\ No newline at end of file
diff --git a/tests/parallel/t10913.nim b/tests/parallel/t10913.nim
new file mode 100644
index 000000000..191939100
--- /dev/null
+++ b/tests/parallel/t10913.nim
@@ -0,0 +1,20 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  errormsg: "'spawn'ed function cannot have a 'typed' or 'untyped' parameter"
+"""
+
+# bug #10913
+
+import threadpool
+
+proc useParallel*[T](unused: T) =
+  # use a generic T here to show the problem.
+  {.push experimental: "parallel".}
+  parallel:
+    for i in 0..4:
+      spawn echo "echo in parallel"
+  sync()
+  
+  {.pop.}
+
+useParallel(1)
diff --git a/tests/parallel/t7535.nim b/tests/parallel/t7535.nim
new file mode 100644
index 000000000..7817a1c9e
--- /dev/null
+++ b/tests/parallel/t7535.nim
@@ -0,0 +1,11 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  errormsg: "'spawn' takes a call expression; got: proc (x: uint32) = echo [x]"
+"""
+
+import threadpool
+
+# bug #7535
+proc print_parallel_nok(r: uint32) =
+  for x in 0..r:
+    spawn (proc (x: uint32) = echo x)
diff --git a/tests/parallel/t9691.nim b/tests/parallel/t9691.nim
new file mode 100644
index 000000000..254f03416
--- /dev/null
+++ b/tests/parallel/t9691.nim
@@ -0,0 +1,9 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  errormsg: "'spawn'ed function cannot have a 'typed' or 'untyped' parameter"
+"""
+
+# bug #9691
+
+import threadpool
+spawn echo()
diff --git a/tests/parallel/tarray_of_channels.nim b/tests/parallel/tarray_of_channels.nim
index 5139920ea..9479227aa 100644
--- a/tests/parallel/tarray_of_channels.nim
+++ b/tests/parallel/tarray_of_channels.nim
@@ -8,6 +8,7 @@ test
 test
 test
 '''
+disabled: "openbsd"
 """
 
 # bug #2257
diff --git a/tests/parallel/tblocking_channel.nim b/tests/parallel/tblocking_channel.nim
index 8b8b49454..f3ccd166a 100644
--- a/tests/parallel/tblocking_channel.nim
+++ b/tests/parallel/tblocking_channel.nim
@@ -1,6 +1,8 @@
 discard """
 output: ""
+disabled: "freebsd" # see #15725
 """
+
 import threadpool, os
 
 var chan: Channel[int]
@@ -25,11 +27,11 @@ proc emitter() =
 
 spawn emitter()
 # At this point emitter should be stuck in `send`
-sleep(100) # Sleep a bit to ensure that it is still stuck
+sleep(50) # Sleep a bit to ensure that it is still stuck
 doAssert(not msgSent)
 
 spawn receiver()
-sleep(100) # Sleep a bit to let receicer consume the messages
+sleep(50) # Sleep a bit to let receicer consume the messages
 doAssert(msgSent) # Sender should be unblocked
 
 doAssert(chan.trySend(4))
diff --git a/tests/parallel/tconvexhull.nim b/tests/parallel/tconvexhull.nim
index 184a131a2..a89aa910b 100644
--- a/tests/parallel/tconvexhull.nim
+++ b/tests/parallel/tconvexhull.nim
@@ -1,8 +1,7 @@
 discard """
+  matrix: "--mm:refc"
   output: '''
 '''
-
-ccodeCheck: "\\i ! @'deepCopy(' .*"
 """
 
 # parallel convex hull for Nim bigbreak
@@ -51,12 +50,11 @@ proc convex_hull[T](points: var seq[T], cmp: proc(x, y: T): int {.closure.}) : s
       ul[k] = spawn half[T](points, k == 0)
   result = concat(^ul[0], ^ul[1])
 
-var s = map(toSeq(0..99999), proc(x: int): Point = (float(x div 1000), float(x mod 1000)))
+var s = map(toSeq(0..9999), proc(x: int): Point = (float(x div 100), float(x mod 100)))
 # On some runs, this pool size reduction will set the "shutdown" attribute on the
 # worker thread that executes our spawned task, before we can read the flowvars.
 setMaxPoolSize 2
 
-#echo convex_hull[Point](s, cmpPoint)
-for i in 0..5:
+for i in 0..2:
   doAssert convex_hull[Point](s, cmpPoint) ==
-      @[(0.0, 0.0), (99.0, 0.0), (99.0, 999.0), (0.0, 999.0)]
+      @[(0.0, 0.0), (99.0, 0.0), (99.0, 99.0), (0.0, 99.0)]
diff --git a/tests/parallel/tdeepcopy.nim b/tests/parallel/tdeepcopy.nim
index 84e2edf3f..96ca15ca3 100644
--- a/tests/parallel/tdeepcopy.nim
+++ b/tests/parallel/tdeepcopy.nim
@@ -1,18 +1,55 @@
 discard """
-  output: '''13 abc'''
+  matrix: "--mm:refc"
+  output: '''
+13 abc
+called deepCopy for int
+called deepCopy for int
+done999 999
+'''
 """
 
-type
-  PBinaryTree = ref object
-    le, ri: PBinaryTree
-    value: int
+import threadpool
 
+block one:
+  type
+    PBinaryTree = ref object
+      le, ri: PBinaryTree
+      value: int
 
-proc main =
-  var x: PBinaryTree
-  deepCopy(x, PBinaryTree(ri: PBinaryTree(le: PBinaryTree(value: 13))))
-  var y: string
-  deepCopy y, "abc"
-  echo x.ri.le.value, " ", y
+  proc main =
+    var x: PBinaryTree
+    deepCopy(x, PBinaryTree(ri: PBinaryTree(le: PBinaryTree(value: 13))))
+    var y: string
+    deepCopy y, "abc"
+    echo x.ri.le.value, " ", y
 
-main()
+  main()
+
+
+block two:
+  type
+    Bar[T] = object
+      x: T
+
+  proc `=deepCopy`[T](b: ref Bar[T]): ref Bar[T] =
+    result.new
+    result.x = b.x
+    when T is int:
+      echo "called deepCopy for int"
+    else:
+      echo "called deepCopy for something else"
+
+  proc foo(b: ref Bar[int]): int = 999
+
+# test that the disjoint checker deals with 'a = spawn f(); g = spawn f()':
+
+  proc main =
+    var dummy: ref Bar[int]
+    new(dummy)
+    dummy.x = 44
+    #parallel:
+    let f = spawn foo(dummy)
+    let b = spawn foo(dummy)
+    echo "done", ^f, " ", ^b
+
+  main()
diff --git a/tests/parallel/tdeepcopy2.nim b/tests/parallel/tdeepcopy2.nim
index 2ad623ed1..e8305173d 100644
--- a/tests/parallel/tdeepcopy2.nim
+++ b/tests/parallel/tdeepcopy2.nim
@@ -1,7 +1,10 @@
 discard """
-  output: '''called deepCopy for int
+  matrix: "--mm:refc"
+  output: '''
 called deepCopy for int
-done999 999'''
+called deepCopy for int
+done999 999
+'''
 """
 
 import threadpool
diff --git a/tests/parallel/tdisjoint_slice1.nim b/tests/parallel/tdisjoint_slice1.nim
index c1d0e52f8..6892e7383 100644
--- a/tests/parallel/tdisjoint_slice1.nim
+++ b/tests/parallel/tdisjoint_slice1.nim
@@ -1,21 +1,51 @@
 discard """
+  matrix: "--mm:refc"
   outputsub: "EVEN 28"
 """
 
-import threadpool
+import threadpool, locks
 
-proc odd(a: int) =  echo "ODD  ", a
-proc even(a: int) = echo "EVEN ", a
+block one:
+  proc odd(a: int) =  echo "ODD  ", a
+  proc even(a: int) = echo "EVEN ", a
 
-proc main() =
-  var a: array[0..30, int]
-  for i in low(a)..high(a): a[i] = i
-  parallel:
-    var i = 0
-    while i <= 29:
-      spawn even(a[i])
-      spawn odd(a[i+1])
-      inc i, 2
-      # is correct here
+  proc main() =
+    var a: array[0..30, int]
+    for i in low(a)..high(a): a[i] = i
+    parallel:
+      var i = 0
+      while i <= 29:
+        spawn even(a[i])
+        spawn odd(a[i+1])
+        inc i, 2
+        # is correct here
 
-main()
+  main()
+
+
+block two:
+  var echoLock: Lock
+  initLock echoLock
+
+  proc f(a: openArray[int]) =
+    for x in a:
+      withLock echoLock:
+        echo x
+
+  proc f(a: int) =
+    withLock echoLock:
+      echo a
+
+  proc main() =
+    var a: array[0..9, int] = [0,1,2,3,4,5,6,7,8,9]
+    parallel:
+      spawn f(a[0..2])
+      #spawn f(a[16..30])
+      var i = 3
+      while i <= 8:
+        spawn f(a[i])
+        spawn f(a[i+1])
+        inc i, 2
+        # is correct here
+
+  main()
diff --git a/tests/parallel/tdisjoint_slice2.nim b/tests/parallel/tdisjoint_slice2.nim
deleted file mode 100644
index 25cb2362f..000000000
--- a/tests/parallel/tdisjoint_slice2.nim
+++ /dev/null
@@ -1,40 +0,0 @@
-discard """
-  output: '''0
-1
-2
-3
-4
-5
-6
-7
-8'''
-  sortoutput: true
-"""
-
-import threadpool, locks
-
-var echoLock: Lock
-initLock echoLock
-
-proc f(a: openArray[int]) =
-  for x in a:
-    withLock echoLock:
-      echo x
-
-proc f(a: int) =
-  withLock echoLock:
-    echo a
-
-proc main() =
-  var a: array[0..9, int] = [0,1,2,3,4,5,6,7,8,9]
-  parallel:
-    spawn f(a[0..2])
-    #spawn f(a[16..30])
-    var i = 3
-    while i <= 8:
-      spawn f(a[i])
-      spawn f(a[i+1])
-      inc i, 2
-      # is correct here
-
-main()
diff --git a/tests/parallel/tflowvar.nim b/tests/parallel/tflowvar.nim
index fd3aa326e..e44b29a87 100644
--- a/tests/parallel/tflowvar.nim
+++ b/tests/parallel/tflowvar.nim
@@ -1,9 +1,11 @@
 discard """
+  matrix: "--mm:refc"
   output: '''foobarfoobar
 bazbearbazbear
 
 1'''
   cmd: "nim $target --threads:on $options $file"
+  disabled: "openbsd"
 """
 
 import threadpool
diff --git a/tests/parallel/tgc_unsafe2.nim b/tests/parallel/tgc_unsafe2.nim
index 40af728fb..7d98dafcb 100644
--- a/tests/parallel/tgc_unsafe2.nim
+++ b/tests/parallel/tgc_unsafe2.nim
@@ -1,9 +1,8 @@
 discard """
   errormsg: "'consumer' is not GC-safe as it calls 'track'"
-  line: 28
-  nimout: '''tgc_unsafe2.nim(22, 6) Warning: 'trick' is not GC-safe as it accesses 'global' which is a global using GC'ed memory [GcUnsafe2]
-tgc_unsafe2.nim(26, 6) Warning: 'track' is not GC-safe as it calls 'trick' [GcUnsafe2]
-tgc_unsafe2.nim(28, 6) Error: 'consumer' is not GC-safe as it calls 'track'
+  nimout: '''tgc_unsafe2.nim(21, 6) Warning: 'trick' is not GC-safe as it accesses 'global' which is a global using GC'ed memory [GcUnsafe2]
+tgc_unsafe2.nim(25, 6) Warning: 'track' is not GC-safe as it calls 'trick' [GcUnsafe2]
+tgc_unsafe2.nim(27, 6) Error: 'consumer' is not GC-safe as it calls 'track'
 '''
 """
 
diff --git a/tests/parallel/tguard1.nim b/tests/parallel/tguard1.nim
index b1eb7e7c5..f4c92319b 100644
--- a/tests/parallel/tguard1.nim
+++ b/tests/parallel/tguard1.nim
@@ -5,7 +5,7 @@ output: "90"
 
 when false:
   template lock(a, b: ptr Lock; body: stmt) =
-    if cast[ByteAddress](a) < cast[ByteAddress](b):
+    if cast[int](a) < cast[int](b):
       pthread_mutex_lock(a)
       pthread_mutex_lock(b)
     else:
diff --git a/tests/parallel/tinvalid_array_bounds.nim b/tests/parallel/tinvalid_array_bounds.nim
index 4c6065fd6..8dc93c33f 100644
--- a/tests/parallel/tinvalid_array_bounds.nim
+++ b/tests/parallel/tinvalid_array_bounds.nim
@@ -1,5 +1,6 @@
 discard """
-  errormsg: "can prove: i + 1 > 30"
+  matrix: "--mm:refc"
+  errormsg: "cannot prove (i)..(i) disjoint from (i + 1)..(i + 1)"
   line: 21
 """
 
diff --git a/tests/parallel/tlet_spawn.nim b/tests/parallel/tlet_spawn.nim
index 62341d8f0..853ffc443 100644
--- a/tests/parallel/tlet_spawn.nim
+++ b/tests/parallel/tlet_spawn.nim
@@ -4,7 +4,7 @@ done999 999
 '''
 """
 
-import threadpool
+import std/[threadpool, os]
 
 proc foo(): int = 999
 
@@ -17,3 +17,12 @@ proc main =
   echo "done", f, " ", b
 
 main()
+
+# bug #13781
+proc thread(): string =
+  os.sleep(1000)
+  return "ok"
+
+var fv = spawn thread()
+sync()
+doAssert ^fv == "ok"
diff --git a/tests/parallel/tmissing_deepcopy.nim b/tests/parallel/tmissing_deepcopy.nim
index 94e027b60..ea77936ad 100644
--- a/tests/parallel/tmissing_deepcopy.nim
+++ b/tests/parallel/tmissing_deepcopy.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   ccodeCheck: "@'genericDeepCopy(' .*"
   action: compile
 """
@@ -26,10 +27,10 @@ proc greet(p:Person) =
     " friend:", p.friend.name, "(", cast[int](addr p.friend.name),") }"
 
 proc setup =
-  for i in 0 ..< 20:
+  for i in 0 ..< 10:
     people.add newPerson("Person" & $(i + 1))
-  for i in 0 ..< 20:
-    people[i].friend = people[19-i]
+  for i in 0 ..< 10:
+    people[i].friend = people[9-i]
 
 proc update =
   parallel:
diff --git a/tests/parallel/tnon_disjoint_slice1.nim b/tests/parallel/tnon_disjoint_slice1.nim
index 72d008bbd..51762187d 100644
--- a/tests/parallel/tnon_disjoint_slice1.nim
+++ b/tests/parallel/tnon_disjoint_slice1.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:refc"
   errormsg: "cannot prove (i)..(i) disjoint from (i + 1)..(i + 1)"
-  line: 20
+  line: 21
 """
 
 import threadpool
diff --git a/tests/parallel/tparfind.nim b/tests/parallel/tparfind.nim
index 4b3610c67..cf1bc9336 100644
--- a/tests/parallel/tparfind.nim
+++ b/tests/parallel/tparfind.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   output: "500"
 """
 
diff --git a/tests/parallel/tpi.nim b/tests/parallel/tpi.nim
index 1abed6f23..cd965d585 100644
--- a/tests/parallel/tpi.nim
+++ b/tests/parallel/tpi.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   output: '''3.141792613595791
 3.141792613595791'''
 """
diff --git a/tests/parallel/tsendtwice.nim b/tests/parallel/tsendtwice.nim
index 0b3ce15a5..9f4a2e06e 100644
--- a/tests/parallel/tsendtwice.nim
+++ b/tests/parallel/tsendtwice.nim
@@ -1,25 +1,17 @@
 discard """
-  output: '''ob2 @[]
-ob @[]
-ob3 @[]
-3
-ob2 @[]
-ob @[]
-ob3 @[]
-'''
-  cmd: "nim c -r --threads:on $file"
+  matrix: "--mm:refc"
 """
 
 # bug #4776
 
-import tables
+import tables, algorithm
 
 type
   Base* = ref object of RootObj
     someSeq: seq[int]
-    baseData: array[400000, byte]
+    baseData: array[40000, byte]
   Derived* = ref object of Base
-    data: array[400000, byte]
+    data: array[40000, byte]
 
 type
   ThreadPool = ref object
@@ -35,20 +27,21 @@ globalTable.add("ob", d)
 globalTable.add("ob2", d)
 globalTable.add("ob3", d)
 
+proc `<`(x, y: seq[int]): bool = x.len < y.len
+proc kvs(t: TableRef[string, Base]): seq[(string, seq[int])] =
+  for k, v in t.pairs: result.add (k, v.someSeq)
+  result.sort
+
 proc testThread(channel: ptr TableChannel) {.thread.} =
   globalTable = channel[].recv()
-  for k, v in pairs globaltable:
-    echo k, " ", v.someSeq
   var myObj: Base
   deepCopy(myObj, globalTable["ob"])
   myObj.someSeq = newSeq[int](100)
   let table = channel[].recv() # same table
-  echo table.len
-  for k, v in mpairs table:
-    echo k, " ", v.someSeq
   assert(table.contains("ob")) # fails!
   assert(table.contains("ob2")) # fails!
   assert(table.contains("ob3")) # fails!
+  assert table.kvs == globalTable.kvs # Last to see above spot checks first
 
 var channel: TableChannel
 
diff --git a/tests/parallel/tsimple_array_checks.nim b/tests/parallel/tsimple_array_checks.nim
index 650b809e0..ab292f935 100644
--- a/tests/parallel/tsimple_array_checks.nim
+++ b/tests/parallel/tsimple_array_checks.nim
@@ -61,3 +61,15 @@ maino() # Doesn't work outside a proc
 
 when true:
   main()
+
+block two:
+  proc f(a: openArray[int]) =
+    discard
+
+  proc main() =
+    var a: array[0..9, int] = [0,1,2,3,4,5,6,7,8,9]
+    parallel:
+      spawn f(a[0..2])
+
+
+  main()
\ No newline at end of file
diff --git a/tests/parallel/tsysspawn.nim b/tests/parallel/tsysspawn.nim
index 7244a5ee6..b7ecd1264 100644
--- a/tests/parallel/tsysspawn.nim
+++ b/tests/parallel/tsysspawn.nim
@@ -1,7 +1,11 @@
 discard """
   output: '''4
-8'''
-  cmd: "nim $target --threads:on $options $file"
+8
+(a: 1)
+2
+2
+'''
+  matrix: "--mm:refc"
 """
 
 import threadpool
@@ -29,3 +33,32 @@ sync()
 
 echo x
 echo y
+
+
+#--------------------------------------------------------
+# issue #14014
+
+import threadpool
+
+type A = object
+    a: int
+
+proc f(t: typedesc): t =
+  t(a:1)
+
+let r = spawn f(A)
+echo ^r
+
+proc f2(x: static[int]): int =
+  x
+
+let r2 = spawn f2(2)
+echo ^r2
+
+type statint = static[int]
+
+proc f3(x: statint): int =
+  x
+
+let r3 = spawn f3(2)
+echo ^r3
diff --git a/tests/parallel/tuseafterdef.nim b/tests/parallel/tuseafterdef.nim
index 833c72a0a..64f835a1b 100644
--- a/tests/parallel/tuseafterdef.nim
+++ b/tests/parallel/tuseafterdef.nim
@@ -1,6 +1,9 @@
 discard """
+  matrix: "--mm:refc"
+  disabled: true
   errormsg: "(k)..(k) not disjoint from (k)..(k)"
-  line: 23
+  line: 24
+  action: compile
 """
 
 # bug #1597
diff --git a/tests/parallel/twaitany.nim b/tests/parallel/twaitany.nim
index 2be3d432f..d57c5f40f 100644
--- a/tests/parallel/twaitany.nim
+++ b/tests/parallel/twaitany.nim
@@ -1,9 +1,10 @@
 discard """
+  matrix: "--mm:refc"
   output: '''true'''
 """
 
 # bug #7638
-import threadpool, os, strformat
+import threadpool, os
 
 proc timer(d: int): int =
   #echo fmt"sleeping {d}"
@@ -11,7 +12,7 @@ proc timer(d: int): int =
   #echo fmt"done {d}"
   return d
 
-var durations = [1000, 1500, 2000, 2500, 3000]
+var durations = [1000, 1500, 2000]
 var tasks: seq[FlowVarBase] = @[]
 var results: seq[int] = @[]
 
@@ -25,11 +26,9 @@ while index != -1:
   #echo repr results
   index = blockUntilAny(tasks)
 
-doAssert results.len == 5
+doAssert results.len == 3
 doAssert 1000 in results
 doAssert 1500 in results
 doAssert 2000 in results
-doAssert 2500 in results
-doAssert 3000 in results
 sync()
 echo "true"
diff --git a/tests/parser/t12274.nim b/tests/parser/t12274.nim
new file mode 100644
index 000000000..6b7c9f55a
--- /dev/null
+++ b/tests/parser/t12274.nim
@@ -0,0 +1,13 @@
+discard """
+  joinable: false
+"""
+
+var s: seq[int]
+s.add block:
+  let i = 1
+  i
+s.add try:
+  2
+except:
+  3
+doAssert s == @[1, 2]
diff --git a/tests/parser/t15667.nim b/tests/parser/t15667.nim
new file mode 100644
index 000000000..fcb862825
--- /dev/null
+++ b/tests/parser/t15667.nim
@@ -0,0 +1,61 @@
+discard """
+  cmd: "nim check $options $file"
+  action: "reject"
+  nimout: '''
+t15667.nim(23, 5) Error: invalid indentation, maybe you forgot a '=' at t15667.nim(22, 13) ?
+t15667.nim(28, 5) Error: invalid indentation, maybe you forgot a '=' at t15667.nim(26, 13) ?
+t15667.nim(33, 5) Error: invalid indentation, maybe you forgot a '=' at t15667.nim(31, 25) ?
+t15667.nim(42, 5) Error: invalid indentation, maybe you forgot a '=' at t15667.nim(38, 12) ?
+t15667.nim(56, 5) Error: invalid indentation, maybe you forgot a '=' at t15667.nim(55, 13) ?
+t15667.nim(61, 48) Error: expression expected, but found ','
+'''
+"""
+
+
+
+
+
+
+
+# line 20
+block:
+  proc fn1()
+    discard
+
+block:
+  proc fn2()
+    #
+    discard
+
+block:
+  proc fn3() {.exportc.}
+    #
+    discard
+
+block: # complex example
+  proc asdfasdfsd() {. exportc, 
+      inline
+         .}     # foo
+    #[
+    bar
+    ]#
+    discard
+
+block: # xxx this doesn't work yet (only a bare `invalid indentation` error)
+  proc fn5()
+    ##
+    discard
+
+block: # ditto
+  proc fn6*()
+    ## foo bar
+    runnableExamples: discard
+
+block:
+  proc fn8()
+    runnableExamples:
+      discard
+    discard
+
+# semiStmtList loop issue
+proc bar(k:static bool):SomeNumber = (when k: 3, else: 3.0)
diff --git a/tests/parser/t19430.nim b/tests/parser/t19430.nim
new file mode 100644
index 000000000..c1aa6a92d
--- /dev/null
+++ b/tests/parser/t19430.nim
@@ -0,0 +1,3 @@
+let x = proc() = ## abc
+let y = 3 #[tt.Error
+^ invalid indentation]#
diff --git a/tests/parser/t19662.nim b/tests/parser/t19662.nim
new file mode 100644
index 000000000..7a1864ac6
--- /dev/null
+++ b/tests/parser/t19662.nim
@@ -0,0 +1,6 @@
+                var i: int # bug #19662
+echo i
+
+discard """
+  errormsg: "invalid indentation"
+"""
\ No newline at end of file
diff --git a/tests/parser/t20922.nim b/tests/parser/t20922.nim
new file mode 100644
index 000000000..110610fb1
--- /dev/null
+++ b/tests/parser/t20922.nim
@@ -0,0 +1,35 @@
+discard """
+  cmd: "nim check $options --verbosity:0 --hints:off $file"
+  action: "reject"
+  nimout: '''
+t20922.nim(26, 5) Error: expression expected, but found ':'
+t20922.nim(34, 7) Error: expression expected, but found ':'
+t20922.nim(35, 5) Error: ':' or '=' expected, but got 'keyword of'
+Error: in expression ' '+'': identifier expected, but found ''
+t20922.nim(26, 7) Error: attempting to call undeclared routine: '<Error>'
+Error: in expression ' '+'': identifier expected, but found ''
+t20922.nim(26, 7) Error: attempting to call undeclared routine: '<Error>'
+t20922.nim(26, 7) Error: expression '' cannot be called
+t20922.nim(26, 7) Error: expression '' has no type (or is ambiguous)
+t20922.nim(26, 7) Error: VM problem: dest register is not set
+'''
+"""
+# original test case issue #20922
+type Token = enum
+  incDataPtr,
+  incDataPtrByte
+
+proc mapInstrToToken(instr: char): Token =
+  case instr:
+  of '>':
+    incDataPtr
+  of: '+':
+    incDataPtrByte
+
+# same issue with `of` in object branches (different parser procs calling `exprList`)
+type
+  Bar = enum A, B
+  Foo = object
+    case kind: Bar
+    of: x: int
+    of B: y: float
diff --git a/tests/parser/tbinarynotindented.nim b/tests/parser/tbinarynotindented.nim
new file mode 100644
index 000000000..8d124aade
--- /dev/null
+++ b/tests/parser/tbinarynotindented.nim
@@ -0,0 +1,3 @@
+type Foo = ref int
+  not nil #[tt.Error
+  ^ invalid indentation]#
diff --git a/tests/parser/tbinarynotsameline.nim b/tests/parser/tbinarynotsameline.nim
new file mode 100644
index 000000000..ca417e023
--- /dev/null
+++ b/tests/parser/tbinarynotsameline.nim
@@ -0,0 +1,10 @@
+# issue #23565
+
+func foo: bool =
+  true
+
+const bar = block:
+  type T = int
+  not foo()
+
+doAssert not bar
diff --git a/tests/parser/tcommand_as_expr.nim b/tests/parser/tcommand_as_expr.nim
index b25ec4bd8..f37c34f63 100644
--- a/tests/parser/tcommand_as_expr.nim
+++ b/tests/parser/tcommand_as_expr.nim
@@ -36,3 +36,12 @@ echo f -4
 
 echo int -1 # doesn't compile
 echo int `-` 1 # compiles
+
+var num = 1
+num += int 2
+doAssert num == 3
+
+import options
+var opt = some some none int
+opt = some some none int
+opt = some none Option[int]
diff --git a/tests/parser/tcommandequals.nim b/tests/parser/tcommandequals.nim
new file mode 100644
index 000000000..f41b318ac
--- /dev/null
+++ b/tests/parser/tcommandequals.nim
@@ -0,0 +1,17 @@
+discard """
+  output: '''
+5
+'''
+"""
+
+proc foo(a, b: int) =
+  echo a + b
+
+foo a = 2, b = 3
+
+import macros
+
+macro bar(args: varargs[untyped]): untyped =
+  doAssert args[0].kind == nnkExprEqExpr
+
+bar "a" = 1
diff --git a/tests/parser/tcommandindent.nim b/tests/parser/tcommandindent.nim
new file mode 100644
index 000000000..449c218db
--- /dev/null
+++ b/tests/parser/tcommandindent.nim
@@ -0,0 +1,16 @@
+when false: # parse the following
+  let foo = Obj(
+    field1: proc (src: pointer, srcLen: Natural)
+                    {.nimcall, gcsafe, raises: [IOError, Defect].} =
+      var file = FileOutputStream(s).file
+
+      implementWrites s.buffers, src, srcLen, "FILE",
+                      writeStartAddr, writeLen,
+        file.writeBuffer(writeStartAddr, writeLen)
+    ,
+    field2: proc {.nimcall, gcsafe, raises: [IOError, Defect].} =
+      flushFile FileOutputStream(s).file
+    ,
+    field3: proc () {.nimcall, gcsafe, raises: [IOError, Defect].} =
+      close FileOutputStream(s).file
+  )
diff --git a/tests/parser/tdo.nim b/tests/parser/tdo.nim
index 7bd1f7411..382d03398 100644
--- a/tests/parser/tdo.nim
+++ b/tests/parser/tdo.nim
@@ -1,8 +1,12 @@
 discard """
-  output: '''true
+  output: '''
 true
 true
-true inner B'''
+true
+true inner B
+running with pragma
+ran with pragma
+'''
 """
 
 template withValue(a, b, c, d, e: untyped) =
@@ -77,3 +81,14 @@ proc main2 =
       echo "true inner B"
 
 main2()
+
+proc withPragma(foo: int, bar: proc() {.raises: [].}) =
+  echo "running with pragma"
+  bar()
+
+withPragma(3) do {.raises: [].}:
+  echo "ran with pragma"
+
+doAssert not (compiles do:
+  withPragma(3) do {.raises: [].}:
+    raise newException(Exception))
diff --git a/tests/parser/tdoc_comments.nim b/tests/parser/tdoc_comments.nim
index fa1374b45..3c86e69ea 100644
--- a/tests/parser/tdoc_comments.nim
+++ b/tests/parser/tdoc_comments.nim
@@ -69,3 +69,7 @@ type
 
   MyEnum3* = enum
     value5  ## only document the enum value
+
+# bug #18847
+proc close*() =   ## asdfasdfsdfa
+  discard         ## adsfasdfads
diff --git a/tests/parser/tdotlikeoperators.nim b/tests/parser/tdotlikeoperators.nim
new file mode 100644
index 000000000..c2d23bd15
--- /dev/null
+++ b/tests/parser/tdotlikeoperators.nim
@@ -0,0 +1,30 @@
+discard """
+  matrix: "-d:nimPreviewDotLikeOps"
+"""
+# test for https://github.com/nim-lang/RFCs/issues/341
+import std/json
+import std/jsonutils
+import std/macros
+
+macro fn1(a: untyped): string = newLit a.lispRepr
+
+doAssert fn1(a.?b.c) == """(DotExpr (Infix (Ident ".?") (Ident "a") (Ident "b")) (Ident "c"))"""
+
+template `.?`(a: JsonNode, b: untyped{ident}): JsonNode =
+  a[astToStr(b)]
+
+proc identity[T](a: T): T = a
+proc timesTwo[T](a: T): T = a * 2
+
+template main =
+  let a = (a1: 1, a2: "abc", a3: (a4: 2.5))
+  let j = a.toJson
+  doAssert j.?a1.getInt == 1
+  doAssert j.?a3.?a4.getFloat == 2.5
+  doAssert j.?a3.?a4.getFloat.timesTwo == 5.0
+  doAssert j.?a3.identity.?a4.getFloat.timesTwo == 5.0
+  doAssert j.identity.?a3.identity.?a4.identity.getFloat.timesTwo == 5.0
+  doAssert j.identity.?a3.?a4.identity.getFloat.timesTwo == 5.0
+
+static: main()
+main()
diff --git a/tests/parser/tdoublenotnil.nim b/tests/parser/tdoublenotnil.nim
new file mode 100644
index 000000000..c61008c54
--- /dev/null
+++ b/tests/parser/tdoublenotnil.nim
@@ -0,0 +1,3 @@
+when false:
+  type Foo = Bar not nil not nil #[tt.Error
+                         ^ invalid indentation]#
diff --git a/tests/parser/tifexprs.nim b/tests/parser/tifexprs.nim
new file mode 100644
index 000000000..3a7e2bddc
--- /dev/null
+++ b/tests/parser/tifexprs.nim
@@ -0,0 +1,12 @@
+discard """
+  output: '''
+1
+'''
+"""
+
+var a, b: int
+let x = if a > b:
+    0
+    else: 1
+
+echo x
diff --git a/tests/parser/tifextracolon.nim b/tests/parser/tifextracolon.nim
new file mode 100644
index 000000000..171569111
--- /dev/null
+++ b/tests/parser/tifextracolon.nim
@@ -0,0 +1,8 @@
+# issue #21982
+
+if true:
+  if true:
+    discard default int:
+else: #[tt.Error
+^ invalid indentation]#
+  discard
diff --git a/tests/parser/tinvifstmt.nim b/tests/parser/tinvifstmt.nim
new file mode 100644
index 000000000..0455bce60
--- /dev/null
+++ b/tests/parser/tinvifstmt.nim
@@ -0,0 +1,12 @@
+discard """
+  errormsg: "invalid indentation"
+  line: 9
+  column: 3
+"""
+
+if true:
+    echo "a"
+  elif:
+    echo "b"
+ else:
+   echo "c"
diff --git a/tests/parser/tpostexprblocks.nim b/tests/parser/tpostexprblocks.nim
index c27bbf321..6cd4a8350 100644
--- a/tests/parser/tpostexprblocks.nim
+++ b/tests/parser/tpostexprblocks.nim
@@ -406,6 +406,105 @@ StmtList
           DiscardStmt
             Empty
       IntLit 0
+  Command
+    Ident "foo390"
+    Call
+      Ident "x"
+      Do
+        Empty
+        Empty
+        Empty
+        FormalParams
+          Empty
+          IdentDefs
+            Ident "y"
+            Empty
+            Empty
+        Empty
+        Empty
+        StmtList
+          DiscardStmt
+            Empty
+      Do
+        Empty
+        Empty
+        Empty
+        FormalParams
+          Ident "int"
+          IdentDefs
+            Ident "z"
+            Empty
+            Empty
+        Empty
+        Empty
+        StmtList
+          DiscardStmt
+            Empty
+      Do
+        Empty
+        Empty
+        Empty
+        FormalParams
+          Ident "int"
+          IdentDefs
+            Ident "w"
+            Ident "int"
+            Empty
+        Empty
+        Empty
+        StmtList
+          DiscardStmt
+            Empty
+      StmtList
+        DiscardStmt
+          Empty
+      OfBranch
+        Ident "a"
+        StmtList
+          DiscardStmt
+            Empty
+      OfBranch
+        TupleConstr
+          Ident "a"
+          Ident "b"
+        StmtList
+          DiscardStmt
+            Empty
+      ElifBranch
+        Ident "a"
+        StmtList
+          DiscardStmt
+            Empty
+      ElifBranch
+        TupleConstr
+          Ident "a"
+          Ident "b"
+        StmtList
+          DiscardStmt
+            Empty
+      ExceptBranch
+        Ident "a"
+        StmtList
+          DiscardStmt
+            Empty
+      ExceptBranch
+        TupleConstr
+          Ident "a"
+          Ident "b"
+        StmtList
+          DiscardStmt
+            Empty
+      Finally
+        StmtList
+          DiscardStmt
+            Empty
+
+  Call
+    Ident "foo"
+    Finally
+      StmtList
+        DiscardStmt
+          Empty
 '''
 """
 
@@ -540,3 +639,30 @@ dumpTree:
   foo380.add((quote do:
     discard
   )[0])
+
+  foo390 x do (y):
+    discard
+  do (z) -> int:
+    discard
+  do (w: int) -> int:
+    discard
+  do:
+    discard
+  of a:
+    discard
+  of (a, b):
+    discard
+  elif a:
+    discard
+  elif (a, b):
+    discard
+  except a:
+    discard
+  except (a, b):
+    discard
+  finally:
+    discard
+
+  foo:
+  finally:
+    discard
diff --git a/tests/parser/tprecedence.nim b/tests/parser/tprecedence.nim
index 66a2922db..9be79543b 100644
--- a/tests/parser/tprecedence.nim
+++ b/tests/parser/tprecedence.nim
@@ -54,3 +54,10 @@ let
 const
   test =
     proc(): int = 1
+
+# bug #8759
+block:
+  template `=>`(a, b): untyped = (a, b)
+  template `+=`(a, b): untyped = a * b
+
+  doAssert ("abc" => 3 += 5) == ("abc", 15)
diff --git a/tests/parser/tprocexprasstmt.nim b/tests/parser/tprocexprasstmt.nim
new file mode 100644
index 000000000..22fb4a7c8
--- /dev/null
+++ b/tests/parser/tprocexprasstmt.nim
@@ -0,0 +1,14 @@
+func r(): auto =
+  func(): int = 2
+doAssert r()() == 2
+
+block: # issue #11726
+  let foo = block:
+    var x: int
+    proc = inc x # "identifier expected, but got '='"
+
+  template paint(): untyped =
+    proc (s: string): string = s
+
+  let s = paint()
+  doAssert s("abc") == "abc"
diff --git a/tests/parser/tstatementoperators.nim b/tests/parser/tstatementoperators.nim
new file mode 100644
index 000000000..d2b85bb4b
--- /dev/null
+++ b/tests/parser/tstatementoperators.nim
@@ -0,0 +1,12 @@
+discard """
+  nimout: '''
+Infix
+  Ident "from"
+  Ident "a"
+  Ident "b"
+'''
+"""
+
+from macros import dumpTree
+
+dumpTree(a from b)
\ No newline at end of file
diff --git a/tests/parser/tstmtlists.nim b/tests/parser/tstmtlists.nim
new file mode 100644
index 000000000..158c93340
--- /dev/null
+++ b/tests/parser/tstmtlists.nim
@@ -0,0 +1,180 @@
+discard """
+  output: '''
+2
+2
+2
+2
+2
+2
+2
+2
+2
+2
+hello
+1
+hello
+2
+hello
+3
+hello
+4
+hello
+5
+hello
+6
+hello
+7
+hello
+8
+hello
+9
+hello
+10
+hello
+1
+hello
+2
+hello
+3
+hello
+4
+hello
+5
+hello
+6
+hello
+7
+hello
+8
+hello
+9
+hello
+10
+lucky
+lucky
+'''
+"""
+
+block: (
+  discard;
+  echo 1 + 1;
+  )
+
+block: (
+  discard; #Haha
+    #haha
+  echo 1 + 1;
+)
+
+block: (
+  discard;
+  #Hmm
+  echo 1 +
+    1;
+)
+
+block: (
+  discard
+  echo "2"
+)
+
+block: (
+  discard;
+  echo 1 +
+    1
+)
+
+block: (
+  discard
+  echo 1 +
+    1
+)
+
+block: (
+  discard;
+  discard
+)
+
+block: (
+  discard
+  echo 1 + 1;
+  )
+
+block: (
+  discard
+  echo 1 + 1;
+)
+
+block: (
+  discard
+  echo 1 +
+    1;
+)
+
+block: (
+  discard;
+    )
+
+block: ( discard; echo 1 + #heh
+                         1;
+)
+
+for i in 1..10:
+    echo "hello"
+    echo i
+
+for i in 1..10: (
+    echo "hello";
+    echo i;
+)
+
+proc square(inSeq: seq[float]): seq[float] = (
+  result = newSeq[float](len(inSeq));
+  for i, v in inSeq: (
+    result[i] = v * v;
+  )
+)
+
+proc square2(inSeq: seq[float]): seq[float] =
+  result = newSeq[float](len(inSeq));
+  for i, v in inSeq: (
+    result[i] = v * v;
+  )
+
+proc cstringCheck(tracked: int; n: int) =
+  if true == false and (let a = high(int); let b = high(int);
+      a.int8 == 8 and a.int8 notin {3..9}):
+    echo(tracked, n)
+
+template dim: int =
+  (if int.high == 0:
+    int.high
+  else:
+    int.high)
+
+template dim2: int =
+  (if int.high == 0:
+    int.high
+   else:
+    int.high)
+
+template dim3: int =
+  (
+   if int.high == 0:
+     int.high
+   else:
+     int.high)
+
+# lenient indentation:
+
+echo (if 0 == 1:
+  "0 == 1"
+else:
+  "lucky")
+
+# bug #16426
+echo (when 0 == 1:
+  "0 == 1"
+else:
+  "lucky")
+
diff --git a/tests/parser/ttry.nim b/tests/parser/ttry.nim
new file mode 100644
index 000000000..190b0b8dc
--- /dev/null
+++ b/tests/parser/ttry.nim
@@ -0,0 +1,27 @@
+# bug #21144
+block:
+  try:
+    let c = try:
+        10
+      except ValueError as exc:
+        10
+  except ValueError as exc:
+    discard
+
+if true:
+  block:
+    let c = try:
+          10
+        except ValueError as exc:
+          10
+    except OSError:
+      99
+
+
+try:
+  let c = try:
+    10
+  except ValueError as exc:
+    10
+except ValueError as exc:
+  discard
\ No newline at end of file
diff --git a/tests/parser/ttupleunpack.nim b/tests/parser/ttupleunpack.nim
index c7ab9ea15..993501fbb 100644
--- a/tests/parser/ttupleunpack.nim
+++ b/tests/parser/ttupleunpack.nim
@@ -27,3 +27,68 @@ proc main() =
 
 main()
 main2()
+
+block: # nested unpacking
+  block: # simple let
+    let (a, (b, c), d) = (1, (2, 3), 4)
+    doAssert (a, b, c, d) == (1, 2, 3, 4)
+    let foo = (a, (b, c), d)
+    let (a2, (b2, c2), d2) = foo
+    doAssert (a, b, c, d) == (a2, b2, c2, d2)
+
+  block: # var and assignment
+    var (x, (y, z), t) = ('a', (true, @[123]), "abc")
+    doAssert (x, y, z, t) == ('a', true, @[123], "abc")
+    (x, (y, z), t) = ('b', (false, @[456]), "def")
+    doAssert (x, y, z, t) == ('b', false, @[456], "def")
+
+  block: # very nested
+    let (_, (_, (_, (_, (_, a))))) = (1, (2, (3, (4, (5, 6)))))
+    doAssert a == 6
+
+  block: # const
+    const (a, (b, c), d) = (1, (2, 3), 4)
+    doAssert (a, b, c, d) == (1, 2, 3, 4)
+    const foo = (a, (b, c), d)
+    const (a2, (b2, c2), d2) = foo
+    doAssert (a, b, c, d) == (a2, b2, c2, d2)
+  
+  block: # evaluation semantics preserved between literal and not literal
+    var s: seq[string]
+    block: # literal
+      let (a, (b, c), d) = ((s.add("a"); 1), ((s.add("b"); 2), (s.add("c"); 3)), (s.add("d"); 4))
+      doAssert (a, b, c, d) == (1, 2, 3, 4)
+      doAssert s == @["a", "b", "c", "d"]
+    block: # underscore
+      s = @[]
+      let (a, (_, c), _) = ((s.add("a"); 1), ((s.add("b"); 2), (s.add("c"); 3)), (s.add("d"); 4))
+      doAssert (a, c) == (1, 3)
+      doAssert s == @["a", "b", "c", "d"]
+    block: # temp
+      s = @[]
+      let foo = ((s.add("a"); 1), ((s.add("b"); 2), (s.add("c"); 3)), (s.add("d"); 4))
+      let (a, (b, c), d) = foo
+      doAssert (a, b, c, d) == (1, 2, 3, 4)
+      doAssert s == @["a", "b", "c", "d"]
+
+block: # unary assignment unpacking
+  var a: int
+  (a,) = (1,)
+  doAssert a == 1
+
+block: # type annotations
+  block: # basic
+    let (a, b): (int, int) = (1, 2)
+    doAssert (a, b) == (1, 2)
+  block: # type inference
+    let (a, b): (byte, float) = (1, 2)
+    doAssert (a, b) == (1.byte, 2.0)
+  block: # type mismatch
+    doAssert not (compiles do:
+      let (a, b): (int, string) = (1, 2))
+  block: # nested
+    let (a, (b, c)): (int, (int, int)) = (1, (2, 3))
+    doAssert (a, b, c) == (1, 2, 3)
+  block: # nested type inference
+    let (a, (b, c)): (byte, (float, cstring)) = (1, (2, "abc"))
+    doAssert (a, b, c) == (1.byte, 2.0, cstring"abc")
diff --git a/tests/parser/ttypeclasses.nim b/tests/parser/ttypeclasses.nim
index 06146dcb6..e6e7a48b8 100644
--- a/tests/parser/ttypeclasses.nim
+++ b/tests/parser/ttypeclasses.nim
@@ -16,31 +16,31 @@ var z: ptr int
 const C = @[1, 2, 3]
 
 static:
-  assert x is ref
-  assert y is distinct
-  assert z is ptr
-  assert C is static
-  assert C[1] is static[int]
-  assert C[0] is static[SomeInteger]
-  assert C isnot static[string]
-  assert C is SEQ|OBJ
-  assert C isnot OBJ|TPL
-  assert int is int
-  assert int is T
-  assert int is SomeInteger
-  assert seq[int] is type
-  assert seq[int] is type[seq]
-  assert seq[int] isnot type[seq[float]]
-  assert i isnot type[int]
-  assert type(i) is type[int]
-  assert x isnot T
-  assert y isnot S
-  assert z isnot enum
-  assert x isnot object
-  assert y isnot tuple
-  assert z isnot seq
+  doAssert x is ref
+  doAssert y is distinct
+  doAssert z is ptr
+  doAssert C is static
+  doAssert C[1] is static[int]
+  doAssert C[0] is static[SomeInteger]
+  doAssert C isnot static[string]
+  doAssert C is SEQ|OBJ
+  doAssert C isnot OBJ|TPL
+  doAssert int is int
+  doAssert int is T
+  doAssert int is SomeInteger
+  doAssert seq[int] is type
+  doAssert seq[int] is type[seq]
+  doAssert seq[int] isnot type[seq[float]]
+  doAssert i isnot type[int]
+  doAssert type(i) is type[int]
+  doAssert x isnot T
+  doAssert y isnot S
+  doAssert z isnot enum
+  doAssert x isnot object
+  doAssert y isnot tuple
+  doAssert z isnot seq
 
   # XXX: These cases don't work properly at the moment:
-  # assert type[int] isnot int
-  # assert type(int) isnot int
+  # doAssert type[int] isnot int
+  # doAssert type(int) isnot int
 
diff --git a/tests/parser/ttypecommandcomma.nim b/tests/parser/ttypecommandcomma.nim
new file mode 100644
index 000000000..7ca59a799
--- /dev/null
+++ b/tests/parser/ttypecommandcomma.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "invalid indentation"
+  line: 8
+  column: 19
+"""
+
+type
+  Foo = call(1, 2), 3:
+    4
\ No newline at end of file
diff --git a/tests/parser/ttypecommandindent1.nim b/tests/parser/ttypecommandindent1.nim
new file mode 100644
index 000000000..9aa274e2a
--- /dev/null
+++ b/tests/parser/ttypecommandindent1.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "invalid indentation"
+  line: 9
+  column: 3
+"""
+
+type
+  Foo = call x, y, z:
+  abc
diff --git a/tests/parser/ttypecommandindent2.nim b/tests/parser/ttypecommandindent2.nim
new file mode 100644
index 000000000..0883df90f
--- /dev/null
+++ b/tests/parser/ttypecommandindent2.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "invalid indentation"
+  line: 10
+  column: 5
+"""
+
+type
+  Foo = call x, y, z:
+      abc
+    do:
+        def
diff --git a/tests/parser/ttypecommandindent3.nim b/tests/parser/ttypecommandindent3.nim
new file mode 100644
index 000000000..f9fdcc1e4
--- /dev/null
+++ b/tests/parser/ttypecommandindent3.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "expression expected, but found 'keyword do'"
+  line: 10
+  column: 1
+"""
+
+type
+  Foo = call x, y, z:
+    abc
+do:
+    def
diff --git a/tests/parser/ttypeexprobject.nim b/tests/parser/ttypeexprobject.nim
new file mode 100644
index 000000000..6895f1731
--- /dev/null
+++ b/tests/parser/ttypeexprobject.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "invalid indentation"
+  line: 10
+  column: 14
+"""
+
+type
+  A = (object | tuple | int)
+  B = int | object | tuple
+  C = object | tuple | int # issue #8846
diff --git a/tests/parser/ttypeexprs.nim b/tests/parser/ttypeexprs.nim
new file mode 100644
index 000000000..e40efc7d9
--- /dev/null
+++ b/tests/parser/ttypeexprs.nim
@@ -0,0 +1,25 @@
+proc foo[T: ptr int | ptr string](x: T) = discard
+var x = "abc"
+foo(addr x)
+
+let n = 3'u32
+type Double = (
+  when n.sizeof == 4: uint64
+  elif n.sizeof == 2: uint32
+  else: uint16
+)
+
+type
+  A = (ref | ptr | pointer)
+  B = pointer | ptr | ref
+  C = ref | ptr | pointer
+
+template `+`(a, b): untyped = (b, a)
+template `*`(a, b): untyped = (a, b)
+
+doAssert (ref int + ref float * ref string + ref bool) is
+  (ref bool, ((ref float, ref string), ref int))
+type X = ref int + ref float * ref string + ref bool
+doAssert X is (ref bool, ((ref float, ref string), ref int))
+
+type SomePointer = proc | ref | ptr | pointer
diff --git a/tests/parser/ttypemodifiers.nim b/tests/parser/ttypemodifiers.nim
index 2c322b44b..9a1ccb1a5 100644
--- a/tests/parser/ttypemodifiers.nim
+++ b/tests/parser/ttypemodifiers.nim
@@ -21,7 +21,7 @@ StmtList
       Ident "PtrTuple"
       Empty
       PtrTy
-        Par
+        TupleConstr
           Ident "int"
           Ident "string"
     TypeDef
@@ -43,14 +43,14 @@ StmtList
       Ident "RefTupleType"
       Empty
       RefTy
-        Par
+        TupleConstr
           Ident "int"
           Ident "string"
     TypeDef
       Ident "RefTupleVars"
       Empty
       RefTy
-        Par
+        TupleConstr
           Ident "a"
           Ident "b"
     TypeDef
@@ -80,7 +80,7 @@ StmtList
       Empty
       Command
         Ident "static"
-        Par
+        TupleConstr
           Ident "int"
           Ident "string"
     TypeDef
@@ -155,7 +155,7 @@ StmtList
       Empty
       Command
         Ident "type"
-        Par
+        TupleConstr
           Ident "a"
           Ident "b"
     TypeDef
@@ -163,7 +163,7 @@ StmtList
       Empty
       Command
         Ident "type"
-        Par
+        TupleConstr
           Ident "int"
           Ident "string"
     TypeDef
@@ -287,7 +287,7 @@ StmtList
       IdentDefs
         Ident "refTuple2"
         RefTy
-          Par
+          TupleConstr
             Ident "int"
             Ident "string"
         Empty
@@ -524,4 +524,3 @@ dumpTree:
     static:
       staticStmtList1
       staticStmtList2
-
diff --git a/tests/parser/ttypesectioncalls.nim b/tests/parser/ttypesectioncalls.nim
new file mode 100644
index 000000000..003444fc5
--- /dev/null
+++ b/tests/parser/ttypesectioncalls.nim
@@ -0,0 +1,328 @@
+discard """
+nimout: '''
+StmtList
+  TypeSection
+    TypeDef
+      Ident "A"
+      Empty
+      Call
+        Ident "call"
+        IntLit 1
+  TypeSection
+    TypeDef
+      Ident "B"
+      Empty
+      Command
+        Ident "call"
+        IntLit 2
+    TypeDef
+      Ident "C"
+      Empty
+      Call
+        Ident "call"
+        StmtList
+          IntLit 3
+    TypeDef
+      Ident "D"
+      Empty
+      Call
+        Ident "call"
+        StmtList
+          IntLit 4
+  TypeSection
+    TypeDef
+      Ident "E"
+      Empty
+      Call
+        Ident "call"
+        IntLit 5
+        IntLit 6
+    TypeDef
+      Ident "F"
+      Empty
+      Command
+        Ident "call"
+        IntLit 7
+        IntLit 8
+    TypeDef
+      Ident "G"
+      Empty
+      Call
+        Ident "call"
+        IntLit 9
+        StmtList
+          IntLit 10
+    TypeDef
+      Ident "H"
+      Empty
+      Call
+        Ident "call"
+        IntLit 11
+        StmtList
+          IntLit 12
+    TypeDef
+      Ident "I"
+      Empty
+      Command
+        Ident "call"
+        IntLit 13
+        StmtList
+          IntLit 14
+    TypeDef
+      Ident "J"
+      Empty
+      Command
+        Ident "call"
+        IntLit 15
+        StmtList
+          IntLit 16
+  TypeSection
+    TypeDef
+      Ident "K"
+      Empty
+      Call
+        Ident "call"
+        IntLit 17
+        IntLit 18
+        IntLit 19
+    TypeDef
+      Ident "L"
+      Empty
+      Command
+        Ident "call"
+        IntLit 20
+        IntLit 21
+        IntLit 22
+    TypeDef
+      Ident "M"
+      Empty
+      Call
+        Ident "call"
+        IntLit 23
+        IntLit 24
+        StmtList
+          IntLit 25
+    TypeDef
+      Ident "N"
+      Empty
+      Command
+        Ident "call"
+        IntLit 26
+        IntLit 27
+        StmtList
+          IntLit 28
+    TypeDef
+      Ident "O"
+      Empty
+      Command
+        Ident "call"
+        IntLit 29
+        IntLit 30
+        StmtList
+          IntLit 31
+  TypeSection
+    TypeDef
+      Ident "P"
+      Empty
+      Command
+        Ident "call"
+        TupleConstr
+          IntLit 32
+          IntLit 33
+        Infix
+          Ident "+"
+          Infix
+            Ident "*"
+            IntLit 34
+            IntLit 35
+          IntLit 36
+        StmtList
+          IntLit 37
+    TypeDef
+      Ident "R"
+      Empty
+      Command
+        Ident "call"
+        Infix
+          Ident "@"
+          TupleConstr
+            IntLit 38
+            IntLit 39
+          Infix
+            Ident "shl"
+            IntLit 40
+            IntLit 41
+        Infix
+          Ident "-"
+          Infix
+            Ident "*"
+            IntLit 42
+            IntLit 43
+          IntLit 44
+        StmtList
+          IntLit 45
+    TypeDef
+      Ident "S"
+      Empty
+      Command
+        Ident "call"
+        IntLit 46
+        StmtList
+          IntLit 47
+        StmtList
+          IntLit 48
+    TypeDef
+      Ident "T"
+      Empty
+      Call
+        Ident "call"
+        StmtList
+          IntLit 49
+        StmtList
+          IntLit 50
+        StmtList
+          IntLit 51
+a: IntLit 1
+a: IntLit 2
+a: StmtList
+  IntLit 3
+a: StmtList
+  IntLit 4
+a: IntLit 5
+b: IntLit 6
+a: IntLit 7
+b: IntLit 8
+a: IntLit 9
+b: StmtList
+  IntLit 10
+a: IntLit 11
+b: StmtList
+  IntLit 12
+a: IntLit 13
+b: StmtList
+  IntLit 14
+a: IntLit 15
+b: StmtList
+  IntLit 16
+a: IntLit 17
+b: IntLit 18
+c: IntLit 19
+a: IntLit 20
+b: IntLit 21
+c: IntLit 22
+a: IntLit 23
+b: IntLit 24
+c: StmtList
+  IntLit 25
+a: IntLit 26
+b: IntLit 27
+c: StmtList
+  IntLit 28
+a: IntLit 29
+b: IntLit 30
+c: StmtList
+  IntLit 31
+a: TupleConstr
+  IntLit 32
+  IntLit 33
+b: Infix
+  Ident "+"
+  Infix
+    Ident "*"
+    IntLit 34
+    IntLit 35
+  IntLit 36
+c: StmtList
+  IntLit 37
+a: Infix
+  Ident "@"
+  TupleConstr
+    IntLit 38
+    IntLit 39
+  Infix
+    Ident "shl"
+    IntLit 40
+    IntLit 41
+b: Infix
+  Ident "-"
+  Infix
+    Ident "*"
+    IntLit 42
+    IntLit 43
+  IntLit 44
+c: StmtList
+  IntLit 45
+a: IntLit 46
+b: StmtList
+  IntLit 47
+c: StmtList
+  IntLit 48
+a: StmtList
+  IntLit 49
+b: StmtList
+  IntLit 50
+c: StmtList
+  IntLit 51
+'''
+"""
+import macros
+
+macro call(a): untyped =
+  echo "a: ", a.treeRepr
+  result = ident"int"
+macro call(a, b): untyped =
+  echo "a: ", a.treeRepr
+  echo "b: ", b.treeRepr
+  result = ident"int"
+macro call(a, b, c): untyped =
+  echo "a: ", a.treeRepr
+  echo "b: ", b.treeRepr
+  echo "c: ", c.treeRepr
+  result = ident"int"
+
+macro sections(x): untyped =
+  echo x.treeRepr
+  result = newStmtList(x)
+  for ts in x:
+    for td in ts:
+      let t = td[0]
+      result.add quote do:
+        doAssert `t` is int
+
+sections:
+  type A = call(1)
+  type
+    B = call 2
+    C = call: 3
+    D = call(): 4
+  type
+    E = call(5, 6)
+    F = call 7, 8
+    G = call(9): 10
+    H = call(11):
+      12
+    I = call 13: 14
+    J = call 15:
+      16
+  type
+    K = call(17, 18, 19)
+    L = call 20, 21, 22
+    M = call(23, 24): 25
+    N = call 26, 27: 28
+    O = call 29, 30:
+      31
+  type
+    P = call (32, 33), 34 * 35 + 36:
+      37
+    R = call (38, 39) @ 40 shl 41, 42 * 43 - 44:
+      45
+    S = call 46:
+      47
+    do:
+      48
+    T = call:
+      49
+    do:
+      50
+    do:
+      51
diff --git a/tests/pragmas/cfunction.c b/tests/pragmas/cfunction.c
new file mode 100644
index 000000000..bf49d6a29
--- /dev/null
+++ b/tests/pragmas/cfunction.c
@@ -0,0 +1,4 @@
+
+int cfunction(void) {
+  return NUMBER_HERE;
+}
diff --git a/tests/pragmas/monoff1.nim b/tests/pragmas/monoff1.nim
new file mode 100644
index 000000000..85d6c57b3
--- /dev/null
+++ b/tests/pragmas/monoff1.nim
@@ -0,0 +1 @@
+proc on*() = discard
diff --git a/tests/pragmas/mqualifiedmacro.nim b/tests/pragmas/mqualifiedmacro.nim
new file mode 100644
index 000000000..908973206
--- /dev/null
+++ b/tests/pragmas/mqualifiedmacro.nim
@@ -0,0 +1,10 @@
+template t*(x:untyped): untyped = 
+  echo "template t"
+
+import macros
+macro m*(name: static string, x: untyped): untyped =
+  let newName = ident(name)
+  result = quote do:
+    type `newName` = object
+  if result.kind == nnkStmtList:
+    result = result[^1]
diff --git a/tests/pragmas/t12558.nim b/tests/pragmas/t12558.nim
new file mode 100644
index 000000000..14fc74cee
--- /dev/null
+++ b/tests/pragmas/t12558.nim
@@ -0,0 +1,15 @@
+discard """
+  nimout: '''@["1", "2", "3"]'''
+"""
+
+import sequtils
+
+{.push compile_time.}
+
+proc foo =
+  echo map_it([1, 2, 3], $it)
+
+{.pop.}
+
+static:
+  foo()
diff --git a/tests/pragmas/t12640.nim b/tests/pragmas/t12640.nim
new file mode 100644
index 000000000..c85185699
--- /dev/null
+++ b/tests/pragmas/t12640.nim
@@ -0,0 +1,26 @@
+discard """
+  matrix: "--mm:refc"
+  nimout: '''1
+2
+3
+[1, 2, 3]'''
+
+  output: '''1
+2
+3
+[1, 2, 3]'''
+"""
+
+# todo fixme it doesn't work with ORC
+proc doIt(a: openArray[int]) =
+  echo a
+
+proc foo() = 
+  var bug {.global, compiletime.}: seq[int]
+  bug = @[1, 2 ,3]
+  for i in 0 .. high(bug): echo bug[i]
+  doIt(bug)
+
+static:
+  foo()
+foo()
diff --git a/tests/pragmas/t13306.nim b/tests/pragmas/t13306.nim
new file mode 100644
index 000000000..36713dd04
--- /dev/null
+++ b/tests/pragmas/t13306.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "'testEpo' can have side effects"
+  line: 8
+"""
+
+import times
+
+func testEpo(x: float): float = epochTime() + x
+
+echo testEpo(1.0)
diff --git a/tests/pragmas/t22713.nim b/tests/pragmas/t22713.nim
new file mode 100644
index 000000000..3d3384632
--- /dev/null
+++ b/tests/pragmas/t22713.nim
@@ -0,0 +1,12 @@
+import std/macros
+
+
+template myPragma(x: int) {.pragma.}
+
+type
+  A = object
+    x: int64
+
+  B {.myPragma(sizeof(A)).} = object
+
+doAssert B.getCustomPragmaVal(myPragma) == 8
\ No newline at end of file
diff --git a/tests/pragmas/t6448.nim b/tests/pragmas/t6448.nim
index ab2e3811f..6efb56e08 100644
--- a/tests/pragmas/t6448.nim
+++ b/tests/pragmas/t6448.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: '''ambiguous call; both foobar.async'''
+  errormsg: '''ambiguous call'''
   line: 10
   disabled: "32bit"
 """
diff --git a/tests/pragmas/t8741.nim b/tests/pragmas/t8741.nim
index 61a449c01..bf97b0e29 100644
--- a/tests/pragmas/t8741.nim
+++ b/tests/pragmas/t8741.nim
@@ -1,7 +1,7 @@
 discard """
-  cmd: "nim check --hint[processing]:off $file"
+  cmd: "nim check --hint:processing:off $file"
   errormsg: "3 is not two"
-  nimout: '''t8741.nim(13, 9) Error: cannot attach a custom pragma to 'a'
+  nimout: '''t8741.nim(13, 9) Error: invalid pragma: foobar
 t8741.nim(29, 15) template/generic instantiation of `onlyTwo` from here
 t8741.nim(25, 12) Error: 3 is not two
 '''
diff --git a/tests/pragmas/tbitsize.nim b/tests/pragmas/tbitsize.nim
index 7a44944d2..39aee445f 100644
--- a/tests/pragmas/tbitsize.nim
+++ b/tests/pragmas/tbitsize.nim
@@ -10,13 +10,13 @@ type
 var
   b: bits
 
-assert b.flag == 0
+doAssert b.flag == 0
 b.flag = 1
-assert b.flag == 1
+doAssert b.flag == 1
 b.flag = 2
-assert b.flag == 0
+doAssert b.flag == 0
 
 b.opts = 7
-assert b.opts == 7
+doAssert b.opts == 7
 b.opts = 9
-assert b.opts == -7
+doAssert b.opts == -7
diff --git a/tests/pragmas/tcompile_missing_file.nim b/tests/pragmas/tcompile_missing_file.nim
new file mode 100644
index 000000000..fd90bd57d
--- /dev/null
+++ b/tests/pragmas/tcompile_missing_file.nim
@@ -0,0 +1,5 @@
+discard """
+  joinable: false
+  errormsg: "cannot find: noexist.c"
+"""
+{.compile: "noexist.c".}
diff --git a/tests/pragmas/tcompile_pragma.nim b/tests/pragmas/tcompile_pragma.nim
new file mode 100644
index 000000000..5b99352dd
--- /dev/null
+++ b/tests/pragmas/tcompile_pragma.nim
@@ -0,0 +1,10 @@
+discard """
+  output: '''34'''
+  joinable: false
+"""
+
+{.compile("cfunction.c", "-DNUMBER_HERE=34").}
+
+proc cfunction(): cint {.importc.}
+
+echo cfunction()
diff --git a/tests/pragmas/tcustom_pragma.nim b/tests/pragmas/tcustom_pragma.nim
index 719af4d50..11a6df813 100644
--- a/tests/pragmas/tcustom_pragma.nim
+++ b/tests/pragmas/tcustom_pragma.nim
@@ -1,6 +1,6 @@
 {.experimental: "notnil".}
 
-import macros
+import macros, asyncmacro, asyncfutures
 
 block:
   template myAttr() {.pragma.}
@@ -8,7 +8,7 @@ block:
   proc myProc():int {.myAttr.} = 2
   const hasMyAttr = myProc.hasCustomPragma(myAttr)
   static:
-    assert(hasMyAttr)
+    doAssert(hasMyAttr)
 
 block:
   template myAttr(a: string) {.pragma.}
@@ -17,10 +17,26 @@ block:
     MyObj = object
       myField1, myField2 {.myAttr: "hi".}: int
 
+    MyGenericObj[T] = object
+      myField1, myField2 {.myAttr: "hi".}: int
+
+    MyOtherObj = MyObj
+
+
   var o: MyObj
   static:
-    assert o.myField2.hasCustomPragma(myAttr)
-    assert(not o.myField1.hasCustomPragma(myAttr))
+    doAssert o.myField2.hasCustomPragma(myAttr)
+    doAssert(not o.myField1.hasCustomPragma(myAttr))
+    doAssert(not o.myField1.hasCustomPragma(MyObj))
+    doAssert(not o.myField1.hasCustomPragma(MyOtherObj))
+
+  var ogen: MyGenericObj[int]
+  static:
+    doAssert ogen.myField2.hasCustomPragma(myAttr)
+    doAssert(not ogen.myField1.hasCustomPragma(myAttr))
+    doAssert(not ogen.myField1.hasCustomPragma(MyGenericObj))
+    doAssert(not ogen.myField1.hasCustomPragma(MyGenericObj))
+
 
 import custom_pragma
 block: # A bit more advanced case
@@ -42,31 +58,31 @@ block: # A bit more advanced case
   var s: MySerializable
 
   const aDefVal = s.a.getCustomPragmaVal(defaultValue)
-  static: assert(aDefVal == 5)
+  static: doAssert(aDefVal == 5)
 
   const aSerKey = s.a.getCustomPragmaVal(serializationKey)
-  static: assert(aSerKey == "asdf")
+  static: doAssert(aSerKey == "asdf")
 
   const cSerKey = getCustomPragmaVal(s.field.c, serializationKey)
-  static: assert(cSerKey == "cc")
+  static: doAssert(cSerKey == "cc")
 
   const procSerKey = getCustomPragmaVal(myproc, serializationKey)
-  static: assert(procSerKey == "myprocSS")
+  static: doAssert(procSerKey == "myprocSS")
 
-  static: assert(hasCustomPragma(myproc, alternativeKey))
+  static: doAssert(hasCustomPragma(myproc, alternativeKey))
 
   const hasFieldCustomPragma = s.field.hasCustomPragma(defaultValue)
-  static: assert(hasFieldCustomPragma == false)
+  static: doAssert(hasFieldCustomPragma == false)
 
   # pragma on an object
   static:
-    assert Subfield.hasCustomPragma(defaultValue)
-    assert(Subfield.getCustomPragmaVal(defaultValue) == "catman")
+    doAssert Subfield.hasCustomPragma(defaultValue)
+    doAssert(Subfield.getCustomPragmaVal(defaultValue) == "catman")
 
-    assert hasCustomPragma(type(s.field), defaultValue)
+    doAssert hasCustomPragma(type(s.field), defaultValue)
 
   proc foo(s: var MySerializable) =
-    static: assert(s.a.getCustomPragmaVal(defaultValue) == 5)
+    static: doAssert(s.a.getCustomPragmaVal(defaultValue) == 5)
 
   foo(s)
 
@@ -91,8 +107,8 @@ block: # ref types
     leftSerKey = getCustomPragmaVal(s.left, serializationKey)
     rightSerKey = getCustomPragmaVal(s.right, serializationKey)
   static:
-    assert leftSerKey == "l"
-    assert rightSerKey == "r"
+    doAssert leftSerKey == "l"
+    doAssert rightSerKey == "r"
 
   var specS = SpecialNodeRef()
 
@@ -100,25 +116,25 @@ block: # ref types
     dataDefVal = hasCustomPragma(specS.data, defaultValue)
     specLeftSerKey = hasCustomPragma(specS.left, serializationKey)
   static:
-    assert dataDefVal == true
-    assert specLeftSerKey == true
+    doAssert dataDefVal == true
+    doAssert specLeftSerKey == true
 
   var ptrS = NodePtr(nil)
   const
     ptrRightSerKey = getCustomPragmaVal(ptrS.right, serializationKey)
   static:
-    assert ptrRightSerKey == "r"
+    doAssert ptrRightSerKey == "r"
 
   var f = MyFile()
   const
     fileDefVal = f.getCustomPragmaVal(defaultValue)
     filePathDefVal = f.path.getCustomPragmaVal(defaultValue)
   static:
-    assert fileDefVal == "closed"
-    assert filePathDefVal == "invalid"
+    doAssert fileDefVal == "closed"
+    doAssert filePathDefVal == "invalid"
 
   static:
-    assert TypeWithoutPragma.hasCustomPragma(defaultValue) == false
+    doAssert TypeWithoutPragma.hasCustomPragma(defaultValue) == false
 
 block:
   type
@@ -144,9 +160,9 @@ block:
     nestedItemDefVal = vari.nestedItem.getCustomPragmaVal(defaultValue)
 
   static:
-    assert hasIntSerKey
-    assert strSerKey == "string"
-    assert nestedItemDefVal == "Nimmers of the world, unite!"
+    doAssert hasIntSerKey
+    doAssert strSerKey == "string"
+    doAssert nestedItemDefVal == "Nimmers of the world, unite!"
 
 block:
   template simpleAttr {.pragma.}
@@ -154,15 +170,25 @@ block:
   type Annotated {.simpleAttr.} = object
 
   proc generic_proc[T]() =
-    assert Annotated.hasCustomPragma(simpleAttr)
-
+    doAssert Annotated.hasCustomPragma(simpleAttr)
 
 #--------------------------------------------------------------------------
 # Pragma on proc type
 
-let a: proc(x: int) {.defaultValue(5).} = nil
+type
+  MyAnnotatedProcType {.defaultValue(4).} = proc(x: int)
+
+let a {.defaultValue(4).}: proc(x: int)  = nil
+var b: MyAnnotatedProcType = nil
+var c: proc(x: int): void {.defaultValue(5).}  = nil
+var d {.defaultValue(44).}: MyAnnotatedProcType = nil
 static:
-  doAssert hasCustomPragma(a.type, defaultValue)
+  doAssert hasCustomPragma(a, defaultValue)
+  doAssert hasCustomPragma(MyAnnotatedProcType, defaultValue)
+  doAssert hasCustomPragma(b, defaultValue)
+  doAssert hasCustomPragma(typeof(c), defaultValue)
+  doAssert getCustomPragmaVal(d, defaultValue) == 44
+  doAssert getCustomPragmaVal(typeof(d), defaultValue) == 4
 
 # bug #8371
 template thingy {.pragma.}
@@ -249,3 +275,266 @@ block:
   var e {.fooBar("foo", 123, 'u').}: int
   doAssert(hasCustomPragma(e, fooBar))
   doAssert(getCustomPragmaVal(e, fooBar).c == 123)
+
+block:
+  macro expectedAst(expectedRepr: static[string], input: untyped): untyped =
+    doAssert input.treeRepr & "\n" == expectedRepr
+    return input
+
+  macro expectedAstRepr(expectedRepr: static[string], input: untyped): untyped =
+    doAssert input.repr == expectedRepr
+    return input
+
+  const procTypeAst = """
+ProcTy
+  FormalParams
+    Empty
+    IdentDefs
+      Ident "x"
+      Ident "int"
+      Empty
+  Pragma
+    Ident "async"
+"""
+
+  type
+    Foo = proc (x: int) {.expectedAst(procTypeAst), async.}
+
+  static: doAssert Foo is proc(x: int): Future[void]
+
+  const asyncProcTypeAst = """
+proc (s: string): Future[void] {..}"""
+  # using expectedAst would show `OpenSymChoice` for Future[void], which is fragile.
+  type
+    Bar = proc (s: string) {.async, expectedAstRepr(asyncProcTypeAst).}
+
+  static: doAssert Bar is proc(x: string): Future[void]
+
+  const typeAst = """
+TypeDef
+  PragmaExpr
+    Ident "Baz"
+    Pragma
+  Empty
+  ObjectTy
+    Empty
+    Empty
+    RecList
+      IdentDefs
+        Ident "x"
+        Ident "string"
+        Empty
+"""
+
+  type
+    Baz {.expectedAst(typeAst).} = object
+      x: string
+
+  static: doAssert Baz.x is string
+
+  const procAst = """
+ProcDef
+  Ident "bar"
+  Empty
+  Empty
+  FormalParams
+    Ident "string"
+    IdentDefs
+      Ident "s"
+      Ident "string"
+      Empty
+  Empty
+  Empty
+  StmtList
+    ReturnStmt
+      Ident "s"
+"""
+
+  proc bar(s: string): string {.expectedAst(procAst).} =
+    return s
+
+  static: doAssert bar("x") == "x"
+
+#------------------------------------------------------
+# bug #13909
+
+template dependency*(id: string, weight = 0.0) {.pragma.}
+
+type
+  MyObject* = object
+    provider*: proc(obj: string): pointer {.dependency("Data/" & obj, 16.1), noSideEffect.}
+
+proc myproc(obj: string): string {.dependency("Data/" & obj, 16.1).} =
+  result = obj
+
+# bug 12523
+template myCustomPragma {.pragma.}
+
+type
+  RefType = ref object
+    field {.myCustomPragma.}: int
+
+  ObjType = object
+    field {.myCustomPragma.}: int
+  RefType2 = ref ObjType
+
+block:
+  let x = RefType()
+  for fieldName, fieldSym in fieldPairs(x[]):
+    doAssert hasCustomPragma(fieldSym, myCustomPragma)
+
+block:
+  let x = RefType2()
+  for fieldName, fieldSym in fieldPairs(x[]):
+    doAssert hasCustomPragma(fieldSym, myCustomPragma)
+
+# bug 8457
+block:
+  template world {.pragma.}
+
+  type
+    Hello = ref object
+      a: float32
+      b {.world.}: int
+
+  discard Hello(a: 1.0, b: 12)
+
+# test routines
+block:
+  template prag {.pragma.}
+  proc hello {.prag.} = discard
+  iterator hello2: int {.prag.} = discard
+  template hello3(x: int): int {.prag.} = x
+  macro hello4(x: int): int {.prag.} = x
+  func hello5(x: int): int {.prag.} = x
+  doAssert hello.hasCustomPragma(prag)
+  doAssert hello2.hasCustomPragma(prag)
+  doAssert hello3.hasCustomPragma(prag)
+  doAssert hello4.hasCustomPragma(prag)
+  doAssert hello5.hasCustomPragma(prag)
+
+# test push doesn't break
+block:
+  template prag {.pragma.}
+  {.push prag.}
+  proc hello = discard
+  iterator hello2: int = discard
+  template hello3(x: int): int = x
+  macro hello4(x: int): int = x
+  func hello5(x: int): int = x
+  type
+    Foo = enum a
+    Bar[T] = ref object of RootObj
+      x: T
+      case y: bool
+      of false: discard
+      else:
+        when true: discard
+  for a in [1]: discard a
+  {.pop.}
+
+# issue #11511
+when false:
+  template myAttr {.pragma.}
+
+  type TObj = object
+      a {.myAttr.}: int
+
+  macro hasMyAttr(t: typedesc): untyped =
+    let objTy = t.getType[1].getType
+    let recList = objTy[2]
+    let sym = recList[0]
+    assert sym.kind == nnkSym and sym.eqIdent("a")
+    let hasAttr = sym.hasCustomPragma(myAttr)
+    newLit(hasAttr)
+
+  doAssert hasMyAttr(TObj)
+
+
+# bug #11415
+template noserialize() {.pragma.}
+
+type
+  Point[T] = object
+    x, y: T
+
+  ReplayEventKind = enum
+    FoodAppeared, FoodEaten, DirectionChanged
+
+  ReplayEvent = object
+    case kind: ReplayEventKind
+    of FoodEaten, FoodAppeared: # foodPos is in multiple branches
+      foodPos {.noserialize.}: Point[float]
+    of DirectionChanged:
+      playerPos: float
+let ev = ReplayEvent(
+    kind: FoodEaten,
+    foodPos: Point[float](x: 5.0, y: 1.0)
+  )
+
+doAssert ev.foodPos.hasCustomPragma(noserialize)
+
+
+when false:
+  # misc
+  {.pragma: haha.}
+  {.pragma: hoho.}
+  template hehe(key, val: string, haha) {.pragma.}
+
+  type A {.haha, hoho, haha, hehe("hi", "hu", "he").} = int
+
+  assert A.getCustomPragmaVal(hehe) == (key: "hi", val: "hu", haha: "he")
+
+  template hehe(key, val: int) {.pragma.}
+
+  var bb {.haha, hoho, hehe(1, 2), haha, hehe("hi", "hu", "he").} = 3
+
+  # left-to-right priority/override order for getCustomPragmaVal
+  assert bb.getCustomPragmaVal(hehe) == (key: "hi", val: "hu", haha: "he")
+
+{.experimental: "dynamicBindSym".}
+
+# const
+block:
+  template myAttr() {.pragma.}
+  template myAttr2(x: int) {.pragma.}
+  template myAttr3(x: string) {.pragma.}
+
+  type
+    MyObj2 = ref object
+
+  const a {.myAttr,myAttr2(2),myAttr3:"test".}: int = 0
+  const b {.myAttr,myAttr2(2),myAttr3:"test".} = 0
+
+  macro forceHasCustomPragma(x: untyped, y: typed): untyped =
+    var x = bindSym(x.repr)
+    for c in x:
+      if c.symKind == nskConst:
+        x = c
+        break
+    result = getAst(hasCustomPragma(x, y))
+
+  macro forceGetCustomPragmaVal(x: untyped, y: typed): untyped =
+    var x = bindSym(x.repr)
+    for c in x:
+      if c.symKind == nskConst:
+        x = c
+        break
+    result = getAst(getCustomPragmaVal(x, y))
+
+  template check(s: untyped) =
+    doAssert forceHasCustomPragma(s, myAttr)
+    doAssert forceHasCustomPragma(s, myAttr2)
+    doAssert forceGetCustomPragmaVal(s, myAttr2) == 2
+    doAssert forceHasCustomPragma(s, myAttr3)
+    doAssert forceGetCustomPragmaVal(s, myAttr3) == "test"
+
+  check(a)
+  check(b)
+
+block: # https://forum.nim-lang.org/t/12522, backticks
+  template `mypragma`() {.pragma.}
+  # Error: invalid pragma: `mypragma`
+  type Test = object
+    field {.`mypragma`.}: int
+  doAssert Test().field.hasCustomPragma(mypragma)
diff --git a/tests/pragmas/thintprocessing.nim b/tests/pragmas/thintprocessing.nim
new file mode 100644
index 000000000..c608bc6e4
--- /dev/null
+++ b/tests/pragmas/thintprocessing.nim
@@ -0,0 +1,18 @@
+discard """
+  disabled: windows
+  matrix: "--hint:processing"
+  nimout: '''
+compile start
+..
+warn_module.nim(6, 6) Hint: 'test' is declared but not used [XDeclaredButNotUsed]
+compile end
+'''
+"""
+
+static:
+  echo "compile start"
+
+import warn_module
+
+static:
+  echo "compile end"
diff --git a/tests/pragmas/tinvalid_user_pragma.nim b/tests/pragmas/tinvalid_user_pragma.nim
new file mode 100644
index 000000000..3081db842
--- /dev/null
+++ b/tests/pragmas/tinvalid_user_pragma.nim
@@ -0,0 +1,9 @@
+discard """
+cmd: "nim check $file"
+"""
+
+{.pragma test: foo.} #[tt.Error
+^ invalid pragma:  {.pragma, test: foo.} ]#
+
+{.pragma: 1.} #[tt.Error
+^ invalid pragma:  {.pragma: 1.} ]#
diff --git a/tests/pragmas/tinvalidcustompragma.nim b/tests/pragmas/tinvalidcustompragma.nim
new file mode 100644
index 000000000..a31695809
--- /dev/null
+++ b/tests/pragmas/tinvalidcustompragma.nim
@@ -0,0 +1,23 @@
+discard """
+  cmd: "nim check $file"
+"""
+
+# issue #21652
+type Foo = object
+template foo() {.tags:[Foo].} = #[tt.Error
+                     ^ invalid pragma: tags: [Foo]]#
+  discard
+
+{.foobar.} #[tt.Error
+  ^ invalid pragma: foobar]#
+type A = enum a {.foobar.} #[tt.Error
+                  ^ invalid pragma: foobar]#
+for b {.foobar.} in [1]: discard #[tt.Error
+        ^ invalid pragma: foobar]#
+template foobar {.pragma.}
+{.foobar.} #[tt.Error
+  ^ cannot attach a custom pragma to 'tinvalidcustompragma'; custom pragmas are not supported for modules]#
+type A = enum a {.foobar.} #[tt.Error
+                  ^ cannot attach a custom pragma to 'a'; custom pragmas are not supported for enum fields]#
+for b {.foobar.} in [1]: discard #[tt.Error
+        ^ cannot attach a custom pragma to 'b'; custom pragmas are not supported for `for` loop variables]#
diff --git a/tests/pragmas/tlocks.nim b/tests/pragmas/tlocks.nim
index ba66a2dca..5d6fcdd9c 100644
--- a/tests/pragmas/tlocks.nim
+++ b/tests/pragmas/tlocks.nim
@@ -1,4 +1,3 @@
-
 type SomeBase* = ref object of RootObj
 type SomeDerived* = ref object of SomeBase
   memberProc*: proc ()
diff --git a/tests/pragmas/tnoreturn.nim b/tests/pragmas/tnoreturn.nim
index 6d0466df3..6a58055fe 100644
--- a/tests/pragmas/tnoreturn.nim
+++ b/tests/pragmas/tnoreturn.nim
@@ -1,4 +1,5 @@
 discard """
+matrix: "--mm:refc"
 ccodeCheck: "\\i @'__attribute__((noreturn))' .*"
 action: compile
 """
diff --git a/tests/pragmas/tonoff1.nim b/tests/pragmas/tonoff1.nim
new file mode 100644
index 000000000..20ba7def2
--- /dev/null
+++ b/tests/pragmas/tonoff1.nim
@@ -0,0 +1,8 @@
+# issue #23002
+
+import monoff1
+
+proc test() =
+  {.warning[ProveInit]: on.}
+
+test()
diff --git a/tests/pragmas/tonoff2.nim b/tests/pragmas/tonoff2.nim
new file mode 100644
index 000000000..9dff5ef11
--- /dev/null
+++ b/tests/pragmas/tonoff2.nim
@@ -0,0 +1,14 @@
+discard """
+    action: compile
+"""
+
+# issue #22841
+
+import unittest
+
+proc on() =
+    discard
+
+suite "some suite":
+    test "some test":
+        discard
diff --git a/tests/pragmas/tpragmas_misc.nim b/tests/pragmas/tpragmas_misc.nim
new file mode 100644
index 000000000..adb7e73c3
--- /dev/null
+++ b/tests/pragmas/tpragmas_misc.nim
@@ -0,0 +1,75 @@
+##[
+tests for misc pragmas that don't need a separate file
+]##
+
+block:
+  static: doAssert not defined(tpragmas_misc_def)
+  {.undef(tpragmas_misc_def).} # works even if not set
+  static: doAssert not defined(tpragmas_misc_def)
+  {.define(tpragmas_misc_def).}
+  static: doAssert defined(tpragmas_misc_def)
+  {.undef(tpragmas_misc_def).}
+  static: doAssert not defined(tpragmas_misc_def)
+
+block: # (partial fix) bug #15920
+  block: # var template pragmas don't work in templates
+    template foo(expr) =
+      expr
+    proc fun1()=
+      let a {.foo.} = 1
+    template fun2()=
+      let a {.foo.} = 1
+    fun1() # ok
+    fun2() # WAS bug
+
+  template foo2() = discard # distractor (template or other symbol kind)
+  block:
+    template foo2(expr) =
+      expr
+    proc fun1()=
+      let a {.foo2.} = 1
+    template fun2()=
+      let a {.foo2.} = 1
+    fun1() # ok
+    fun2() # bug: Error: invalid pragma: foo2
+
+  block: # template pragmas don't work for templates, #18212
+    # adapted from $nim/lib/std/private/since.nim
+    # case without overload
+    template since3(version: (int, int), body: untyped) {.dirty.} =
+      when (NimMajor, NimMinor) >= version:
+        body
+    when true: # bug
+      template fun3(): int {.since3: (1, 3).} = 12
+
+  block: # ditto, w
+    # case with overload
+    template since2(version: (int, int), body: untyped) {.dirty.} =
+      when (NimMajor, NimMinor) >= version:
+        body
+    template since2(version: (int, int, int), body: untyped) {.dirty.} =
+      when (NimMajor, NimMinor, NimPatch) >= version:
+        body
+    when true: # bug
+      template fun3(): int {.since2: (1, 3).} = 12
+
+when true: # D20210801T100514:here
+  from macros import genSym
+  block:
+    template fn() =
+      var ret {.gensym.}: int # must special case template pragmas so it doesn't get confused
+      discard ret
+    fn()
+    static: discard genSym()
+
+block: # issue #10994
+  macro foo(x): untyped = x
+  template bar {.pragma.}
+
+  proc a {.bar.} = discard # works
+  proc b {.bar, foo.} = discard # doesn't
+
+block: # issue #22525
+  macro catch(x: typed) = x
+  proc thing {.catch.} = discard
+  thing()
diff --git a/tests/pragmas/tpragmas_reorder.nim b/tests/pragmas/tpragmas_reorder.nim
new file mode 100644
index 000000000..c4b1a6b0a
--- /dev/null
+++ b/tests/pragmas/tpragmas_reorder.nim
@@ -0,0 +1,19 @@
+discard """
+  matrix: "--experimental:codeReordering"
+"""
+
+runnableExamples:
+  import strtabs
+  var t = newStringTable()
+  t["name"] = "John"
+  t["city"] = "Monaco"
+  doAssert t.len == 2
+  doAssert t.hasKey "name"
+  doAssert "name" in t
+
+include "system/inclrtl"
+
+{.pragma: rtlFunc, rtl.}
+
+proc hasKey*(): bool {.rtlFunc.} =
+  discard
\ No newline at end of file
diff --git a/tests/pragmas/tpush.nim b/tests/pragmas/tpush.nim
index 5ecfe9704..9c6b85c4e 100644
--- a/tests/pragmas/tpush.nim
+++ b/tests/pragmas/tpush.nim
@@ -1,3 +1,7 @@
+discard """
+  targets: "c js"
+"""
+
 # test the new pragmas
 
 {.push warnings: off, hints: off.}
@@ -13,3 +17,128 @@ proc WarnMe() =
     x: int
   echo(x)
 
+# bug #11852
+proc foo(x: string, y: int, res: int) =
+  {.push checks: off}
+  var a: ptr char = unsafeAddr(x[y])
+  {.pop.}
+  if x.len > y:
+    doAssert ord(a[]) == 51
+  else:
+    doAssert x.len + 48 == res
+
+foo("", 0, 48)
+foo("abc", 40, 51)
+
+# bug #22362
+{.push staticBoundChecks: on.}
+proc main(): void =
+  {.pop.}
+  discard
+  {.push staticBoundChecks: on.}
+
+main()
+
+
+proc timnFoo[T](obj: T) {.noSideEffect.} = discard # BUG
+
+{.push exportc.}
+proc foo1() =
+  var s1 = "bar"
+  timnFoo(s1)
+  var s2 = @[1]
+  timnFoo(s2)
+{.pop.}
+
+
+block: # bug #22913
+  block:
+    type r = object
+
+    template std[T](x: T) =
+      let ttt {.used.} = x
+      result = $ttt
+
+    proc bar[T](x: T): string =
+      std(x)
+
+    {.push exportc: "$1".}
+    proc foo(): r =
+      let s = bar(123)
+    {.pop.}
+
+    discard foo()
+
+  block:
+    type r = object
+    {.push exportc: "$1".}
+    proc foo2(): r =
+      let s = $result
+    {.pop.}
+
+    discard foo2()
+
+block: # bug #23019
+  proc f(x: bool)
+
+  proc a(x: int) =
+    if false: f(true)
+
+  proc f(x: bool) =
+    if false: a(0)
+
+  proc k(r: int|int) {.inline.} =  # seems to require being generic and inline
+    if false: a(0)
+
+
+  # {.push tags: [].}
+  {.push raises: [].}
+
+  {.push warning[ObservableStores]:off.}  # can be any warning, off or on
+  let w = 0
+  k(w)
+  {.pop.}
+  {.pop.}
+
+{.push exportC.}
+
+block:
+  proc foo11() =
+    const factor = [1, 2, 3, 4]
+    doAssert factor[0] == 1
+  proc foo21() =
+    const factor = [1, 2, 3, 4]
+    doAssert factor[0] == 1
+
+  foo11()
+  foo21()
+
+template foo31() =
+  let factor = [1, 2, 3, 4]
+  doAssert factor[0] == 1
+template foo41() =
+  let factor = [1, 2, 3, 4]
+  doAssert factor[0] == 1
+
+foo31()
+foo41()
+
+{.pop.}
+
+import macros
+
+block:
+  {.push deprecated.}
+  template test() = discard
+  test()
+  {.pop.}
+  macro foo(): bool =
+    let ast = getImpl(bindSym"test")
+    var found = false
+    if ast[4].kind == nnkPragma:
+      for x in ast[4]:
+        if x.eqIdent"deprecated":
+          found = true
+          break
+    result = newLit(found)
+  doAssert foo()
diff --git a/tests/pragmas/tpushnotes.nim b/tests/pragmas/tpushnotes.nim
new file mode 100644
index 000000000..27ba0bec4
--- /dev/null
+++ b/tests/pragmas/tpushnotes.nim
@@ -0,0 +1,13 @@
+discard """
+  matrix: "--warningAsError:HoleEnumConv"
+"""
+
+type
+  e = enum
+    a = 0
+    b = 2
+
+var i: int
+{.push warning[HoleEnumConv]:off.}
+discard i.e
+{.pop.}
diff --git a/tests/pragmas/tqualifiedmacro.nim b/tests/pragmas/tqualifiedmacro.nim
new file mode 100644
index 000000000..bc95ec1ea
--- /dev/null
+++ b/tests/pragmas/tqualifiedmacro.nim
@@ -0,0 +1,14 @@
+discard """
+  output: '''
+template t
+'''
+"""
+
+# issue #12696
+
+import mqualifiedmacro
+proc p() {. mqualifiedmacro.t .} = # errors with identifier expected but a.t found
+  echo "proc p"
+
+type Foo {. mqualifiedmacro.m("Bar") .} = object
+doAssert Bar is object
diff --git a/tests/pragmas/ttypedef_macro.nim b/tests/pragmas/ttypedef_macro.nim
new file mode 100644
index 000000000..dd4c87757
--- /dev/null
+++ b/tests/pragmas/ttypedef_macro.nim
@@ -0,0 +1,66 @@
+import macros
+
+macro makeref(s): untyped =
+  expectKind s, nnkTypeDef
+  result = newTree(nnkTypeDef, s[0], s[1], newTree(nnkRefTy, s[2]))
+
+type
+  Obj {.makeref.} = object
+    a: int
+
+doAssert Obj is ref
+doAssert Obj(a: 3)[].a == 3
+
+macro multiply(amount: static int, s): untyped =
+  let name = $s[0].basename
+  result = newNimNode(nnkTypeSection)
+  for i in 1 .. amount:
+    result.add(newTree(nnkTypeDef, ident(name & $i), s[1], s[2]))
+
+type
+  Foo = object
+  Bar {.multiply: 2.} = object
+    x, y, z: int
+  Baz = object
+
+let bar1 = Bar1(x: 1, y: 2, z: 3)
+let bar2 = Bar2(x: bar1.x, y: bar1.y, z: bar1.z)
+doAssert Bar1 isnot Bar2
+doAssert not declared(Bar)
+doAssert not declared(Bar3)
+
+# https://github.com/nim-lang/RFCs/issues/219
+
+macro inferKind(td): untyped =
+  let name = $td[0].basename
+  var rhs = td[2]
+  while rhs.kind in {nnkPtrTy, nnkRefTy}: rhs = rhs[0]
+  if rhs.kind != nnkObjectTy:
+    result = td
+  else:
+    for n in rhs[^1]:
+      if n.kind == nnkRecCase and n[0][^2].eqIdent"_":
+        let kindTypeName = ident(name & "Kind")
+        let en = newTree(nnkEnumTy, newEmptyNode())
+        for i in 1 ..< n.len:
+          let branch = n[i]
+          if branch.kind == nnkOfBranch:
+            for j in 0 ..< branch.len - 1:
+              en.add(branch[j])
+        n[0][^2] = kindTypeName
+        return newTree(nnkTypeSection,
+          newTree(nnkTypeDef, kindTypeName, newEmptyNode(), en),
+          td)
+
+type Node {.inferKind.} = ref object
+  case kind: _
+  of opValue: value: int
+  of opAdd, opSub, opMul, opCall: kids: seq[Node]
+
+doAssert opValue is NodeKind
+let node = Node(kind: opMul, kids: @[
+  Node(kind: opValue, value: 3),
+  Node(kind: opValue, value: 5)
+])
+doAssert node.kind == opMul
+doAssert node.kids[0].value * node.kids[1].value == 15
diff --git a/tests/pragmas/tuserpragma2.nim b/tests/pragmas/tuserpragma2.nim
index ce16c4649..c3f31cd5e 100644
--- a/tests/pragmas/tuserpragma2.nim
+++ b/tests/pragmas/tuserpragma2.nim
@@ -3,9 +3,10 @@ discard """
   file: "tuserpragma2.nim"
   line: 11
 """
-
+{.push warningAsError[Effect]: on.}
 # bug #7216
 {.pragma: my_pragma, raises: [].}
 
 proc test1 {.my_pragma.} =
   raise newException(Exception, "msg")
+{.pop.}
diff --git a/tests/pragmas/tuserpragmaargs.nim b/tests/pragmas/tuserpragmaargs.nim
new file mode 100644
index 000000000..791d703ac
--- /dev/null
+++ b/tests/pragmas/tuserpragmaargs.nim
@@ -0,0 +1,5 @@
+var foo {.exportc: "abc".} = 123
+{.pragma: importc2, importc.}
+var bar {.importc2: "abc".}: int #[tt.Error
+                  ^ user pragma cannot have arguments]#
+echo bar
diff --git a/tests/pragmas/tvar_macro.nim b/tests/pragmas/tvar_macro.nim
new file mode 100644
index 000000000..3fb6e3e53
--- /dev/null
+++ b/tests/pragmas/tvar_macro.nim
@@ -0,0 +1,128 @@
+import macros
+
+block: # test usage
+  macro modify(sec) =
+    result = copy sec
+    result[0][0] = ident(repr(result[0][0]) & "Modified")
+
+  block:
+    let foo {.modify.} = 3
+    doAssert fooModified == 3
+
+  block: # in section 
+    let
+      a = 1
+      b {.modify.} = 2
+      c = 3
+    doAssert (a, bModified, c) == (1, 2, 3)
+
+block: # with single argument
+  macro appendToName(name: static string, sec) =
+    result = sec
+    result[0][0] = ident(repr(result[0][0]) & name)
+
+  block:
+    let foo {.appendToName: "Bar".} = 3
+    doAssert fooBar == 3
+
+  block:
+    let
+      a = 1
+      b {.appendToName("").} = 2
+      c = 3
+    doAssert (a, b, c) == (1, 2, 3)
+
+macro appendToNameAndAdd(name: static string, incr: static int, sec) =
+  result = sec
+  result[0][0] = ident(repr(result[0][0]) & name)
+  result[0][2] = infix(result[0][2], "+", newLit(incr))
+
+block: # with multiple arguments
+  block:
+    let foo {.appendToNameAndAdd("Bar", 5).} = 3
+    doAssert fooBar == 8
+
+  block:
+    let
+      a = 1
+      b {.appendToNameAndAdd("", 15).} = 2
+      c = 3
+    doAssert (a, b, c) == (1, 17, 3)
+
+block: # in other kinds of sections
+  block:
+    const
+      a = 1
+      b {.appendToNameAndAdd("", 15).} = 2
+      c = 3
+    doAssert (a, b, c) == (1, 17, 3)
+    doAssert static(b) == b
+
+  block:
+    var
+      a = 1
+      b {.appendToNameAndAdd("", 15).} = 2
+      c = 3
+    doAssert (a, b, c) == (1, 17, 3)
+    b += a
+    c += b
+    doAssert (a, b, c) == (1, 18, 21)
+
+block: # with other pragmas
+  macro appendToNameAndAdd(name: static string, incr, sec) =
+    result = sec
+    result[0][0][0] = ident(repr(result[0][0][0]) & name)
+    result[0][0][1].add(ident"deprecated")
+    result[0][2] = infix(result[0][2], "+", incr)
+
+  var
+    a = 1
+    foo {.exportc: "exportedFooBar", appendToNameAndAdd("Bar", {'0'..'9'}), used.} = {'a'..'z', 'A'..'Z'}
+    b = 2
+  
+  doAssert (a, b) == (1, 2)
+
+  let importedFooBar {.importc: "exportedFooBar", nodecl.}: set[char]
+
+  doAssert importedFooBar == fooBar #[tt.Warning
+                             ^ fooBar is deprecated
+  ]#
+  
+
+block: # with stropping
+  macro `cast`(def) =
+    let def = def[0]
+    let
+      lhs = def[0]
+      typ = def[1]
+      ex = def[2]
+      addrTyp = if typ.kind == nnkEmpty: typ else: newTree(nnkPtrTy, typ)
+    result = quote do:
+      let tmp: `addrTyp` = unsafeAddr(`ex`)
+      template `lhs`: untyped = tmp[]
+  
+  macro assign(def) =
+    result = getAst(`cast`(def))
+
+  block:
+    let s = @["foo", "bar"]
+    let a {.`assign`.} = s[0]
+    doAssert a == "foo"
+    doAssert a[0].addr == s[0][0].addr
+
+  block:
+    let
+      s = @["foo", "bar"]
+      a {.`cast`.} = s[0]
+    doAssert a == "foo"
+    doAssert a[0].addr == s[0][0].addr
+
+block: # bug #15920
+  macro foo(def) =
+    result = def
+  proc fun1()=
+    let a {.foo.} = 1
+  template fun2()=
+    let a {.foo.} = 1
+  fun1() # ok
+  fun2() # BUG
diff --git a/tests/pragmas/twarning_off.nim b/tests/pragmas/twarning_off.nim
index f1de9076f..ccf07b9c4 100644
--- a/tests/pragmas/twarning_off.nim
+++ b/tests/pragmas/twarning_off.nim
@@ -1,8 +1,6 @@
 discard """
   nimout: '''
 compile start
-Hint: warn_module [Processing]
-Hint: hashes [Processing]
 warn_module.nim(6, 6) Hint: 'test' is declared but not used [XDeclaredButNotUsed]
 compile end
 '''
diff --git a/tests/defaultprocparam/mdefaultprocparam.nim b/tests/proc/mdefaultprocparam.nim
index 4a17277c0..4a17277c0 100644
--- a/tests/defaultprocparam/mdefaultprocparam.nim
+++ b/tests/proc/mdefaultprocparam.nim
diff --git a/tests/proc/t15949.nim b/tests/proc/t15949.nim
new file mode 100644
index 000000000..6467ed5d3
--- /dev/null
+++ b/tests/proc/t15949.nim
@@ -0,0 +1,16 @@
+# bug #15949 and RFC #480
+
+proc procWarn(a, b = 1): (int, int) = (a, b) #[tt.Warning
+              ^ a, b all have default value '1', this may be unintentional, either use ';' (semicolon) or explicitly write each default value [ImplicitDefaultValue]]#
+
+proc procGood(a = 1, b = 1): (int, int) = (a, b)
+
+doAssert procGood() == (1, 1)
+doAssert procGood(b = 3) == (1, 3)
+doAssert procGood(a = 2) == (2, 1)
+doAssert procGood(a = 5, b = 6) == (5, 6)
+
+# The type (and default value propagation breaks in the below example
+# as semicolon is used instead of comma.
+proc procBad(a; b = 1): (int, int) = (a, b) #[tt.Error
+             ^ parameter 'a' requires a type]#
diff --git a/tests/proc/t17157.nim b/tests/proc/t17157.nim
new file mode 100644
index 000000000..020e93fce
--- /dev/null
+++ b/tests/proc/t17157.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "'untyped' is only allowed in templates and macros or magic procs"
+"""
+
+template something(op: proc (v: untyped): void): void =
+  discard
diff --git a/tests/proc/t19795.nim b/tests/proc/t19795.nim
new file mode 100644
index 000000000..677ec0a63
--- /dev/null
+++ b/tests/proc/t19795.nim
@@ -0,0 +1,19 @@
+discard """
+  matrix: "--mm:arc"
+"""
+
+# bug #19795
+# bug #21085
+
+type Vector = seq[int]
+
+var vect: Vector = newSeq[int](5)
+doAssert vect == @[0, 0, 0, 0, 0]
+
+# Needed to get the problem. Could also use "var".
+let vectCopy = vect
+
+# Then some procedure definition is needed to get the problem.
+proc p(): int = 3
+
+doAssert vect == @[0, 0, 0, 0, 0]
\ No newline at end of file
diff --git a/tests/proc/t23874.nim b/tests/proc/t23874.nim
new file mode 100644
index 000000000..940bc4ac8
--- /dev/null
+++ b/tests/proc/t23874.nim
@@ -0,0 +1,26 @@
+block:
+  type Head[T] = object
+    wasc: bool
+
+  proc `=destroy`[T](x: var Head[T]) =
+    discard
+
+  proc `=copy`[T](x: var Head[T], y: Head[T]) =
+    x.wasc = true
+
+  proc `=dup`[T](x: Head[T]): Head[T] =
+    result.wasc = true
+
+  proc update(h: var Head) =
+    discard
+
+  proc digest(h: sink Head) =
+    assert h.wasc
+
+  var h = Head[int](wasc: false)
+  h.digest() # sink h
+  h.update() # use after sink
+
+block:
+  proc two(a: sink auto) =discard
+  assert typeof(two[int]) is proc(a: sink int) {.nimcall.}
diff --git a/tests/misc/tcolonisproc.nim b/tests/proc/tcolonisproc.nim
index c10dabcf1..c10dabcf1 100644
--- a/tests/misc/tcolonisproc.nim
+++ b/tests/proc/tcolonisproc.nim
diff --git a/tests/proc/tdefaultprocparam.nim b/tests/proc/tdefaultprocparam.nim
new file mode 100644
index 000000000..90edfa8c9
--- /dev/null
+++ b/tests/proc/tdefaultprocparam.nim
@@ -0,0 +1,90 @@
+discard """
+output: '''
+hi
+hi
+topLevel|topLevel|
+topLevel2|topLevel2|
+inProc|inProc|
+inProc2|inProc2|
+topLevel|9
+topLevel2|10
+inProc|7
+inProc2|8
+must have been the wind..
+I'm there
+must have been the wind..
+I'm there
+symbol'a'symbol'a'
+symbol'b'symbol'b'
+symbol'a'symbol'b'
+symbol'a'9
+symbol'b'9
+symbol'a'0
+'''
+"""
+import mdefaultprocparam
+
+p()
+
+proc testP =
+  p()
+
+testP()
+
+proc p2(s: string, count = s): string = s & count
+
+proc testP2 =
+  echo p2 """inProc|"""
+  echo p2 """inProc2|"""
+
+echo p2 """topLevel|"""
+echo p2 """topLevel2|"""
+
+testP2()
+
+import macros
+macro dTT(a: typed) = echo a.treeRepr
+
+proc p3(s: string, count = len(s)): string = s & $count
+
+proc testP3 =
+  echo p3 """inProc|"""
+  echo p3 """inProc2|"""
+
+echo p3 """topLevel|"""
+echo p3 """topLevel2|"""
+
+testP3()
+
+proc cut(s: string, c = len(s)): string =
+  s[0..<s.len-c]
+
+echo "must have been the wind.." & cut "I'm gone"
+echo cut("I'm gone", 4) & "there"
+
+proc testCut =
+  echo "must have been the wind.." & cut "I'm gone"
+  echo cut("I'm gone", 4) & "there"
+
+testCut()
+
+var a = "symbol'a'"
+var b = "symbol'b'"
+
+block:
+  echo p2(a)
+block:
+  echo p2(b)
+block:
+  echo p2(a, b)
+block:
+  echo p3(a)
+  echo p3(b)
+  echo p3(a, 0)
+
+# bug #12252
+proc foo(a = 0, b = a.high, c = high(typeof(a))) = 
+  discard
+
+foo()
+
diff --git a/tests/proc/texplicitgenericcount.nim b/tests/proc/texplicitgenericcount.nim
new file mode 100644
index 000000000..8654a1d13
--- /dev/null
+++ b/tests/proc/texplicitgenericcount.nim
@@ -0,0 +1,24 @@
+discard """
+  cmd: "nim check -d:testsConciseTypeMismatch $file"
+"""
+
+proc foo[T, U](x: T, y: U): (T, U) = (x, y)
+
+let x = foo[int](1, 2) #[tt.Error
+                ^ type mismatch
+Expression: foo[int](1, 2)
+  [1] 1: int literal(1)
+  [2] 2: int literal(2)
+
+Expected one of (first mismatch at [position]):
+[2] proc foo[T, U](x: T; y: U): (T, U)
+  missing generic parameter: U]#
+let y = foo[int, float, string](1, 2) #[tt.Error
+                               ^ type mismatch
+Expression: foo[int, float, string](1, 2)
+  [1] 1: int literal(1)
+  [2] 2: int literal(2)
+
+Expected one of (first mismatch at [position]):
+[3] proc foo[T, U](x: T; y: U): (T, U)
+  extra generic param given]#
diff --git a/tests/proc/texplicitgenericcountverbose.nim b/tests/proc/texplicitgenericcountverbose.nim
new file mode 100644
index 000000000..76228eeaf
--- /dev/null
+++ b/tests/proc/texplicitgenericcountverbose.nim
@@ -0,0 +1,22 @@
+discard """
+  cmd: "nim check $file"
+"""
+
+proc foo[T, U](x: T, y: U): (T, U) = (x, y)
+
+let x = foo[int](1, 2) #[tt.Error
+                ^ type mismatch: got <int literal(1), int literal(2)>
+but expected one of:
+proc foo[T, U](x: T; y: U): (T, U)
+  first type mismatch at position: 2 in generic parameters
+  missing generic parameter: U
+
+expression: foo[int](1, 2)]#
+let y = foo[int, float, string](1, 2) #[tt.Error
+                               ^ type mismatch: got <int literal(1), int literal(2)>
+but expected one of:
+proc foo[T, U](x: T; y: U): (T, U)
+  first type mismatch at position: 3 in generic parameters
+  extra generic param given
+
+expression: foo[int, float, string](1, 2)]#
diff --git a/tests/proc/texplicitgenerics.nim b/tests/proc/texplicitgenerics.nim
new file mode 100644
index 000000000..833d77b3b
--- /dev/null
+++ b/tests/proc/texplicitgenerics.nim
@@ -0,0 +1,55 @@
+block: # issue #16376
+  type
+    Matrix[T] = object
+      data: T
+  proc randMatrix[T](m, n: int, max: T): Matrix[T] = discard
+  proc randMatrix[T](m, n: int, x: Slice[T]): Matrix[T] = discard
+  template randMatrix[T](m, n: int): Matrix[T] = randMatrix[T](m, n, T(1.0))
+  let B = randMatrix[float32](20, 10)
+
+block: # different generic param counts 
+  type
+    Matrix[T] = object
+      data: T
+  proc randMatrix[T](m: T, n: T): Matrix[T] = Matrix[T](data: T(1.0))
+  proc randMatrix[T; U: not T](m: T, n: U): (Matrix[T], U) = (Matrix[T](data: T(1.0)), default(U))
+  let b = randMatrix[float32](20, 10)
+  doAssert b == Matrix[float32](data: 1.0)
+
+block: # above for templates 
+  type
+    Matrix[T] = object
+      data: T
+  template randMatrix[T](m: T, n: T): Matrix[T] = Matrix[T](data: T(1.0))
+  template randMatrix[T; U: not T](m: T, n: U): (Matrix[T], U) = (Matrix[T](data: T(1.0)), default(U))
+  let b = randMatrix[float32](20, 10)
+  doAssert b == Matrix[float32](data: 1.0)
+
+block: # sigmatch can't handle this without pre-instantiating the type:
+  # minimized from numericalnim
+  type Foo[T] = proc (x: T)
+  proc foo[T](x: T) = discard
+  proc bar[T](f: Foo[T]) = discard
+  bar[int](foo)
+
+block: # ditto but may be wrong minimization
+  # minimized from measuremancer
+  type Foo[T] = object
+  proc foo[T](): Foo[T] = Foo[T]()
+  # this is the actual issue but there are other instantiation problems
+  proc bar[T](x = foo[T]()) = discard
+  bar[int](Foo[int]())
+  bar[int]()
+  # alternative version, also causes instantiation issue
+  proc baz[T](x: typeof(foo[T]())) = discard
+  baz[int](Foo[int]())
+
+block: # issue #21346
+  type K[T] = object
+  template s[T](x: int) = doAssert T is K[K[int]]
+  proc b1(n: bool | bool) = s[K[K[int]]](3)
+  proc b2(n: bool)        = s[K[K[int]]](3)
+  template b3(n: bool)    = s[K[K[int]]](3)
+  b1(false)     # Error: cannot instantiate K; got: <T> but expected: <T>
+  b2(false)     # Builds, on its own
+  b3(false)
diff --git a/tests/proc/tfunc_type.nim b/tests/proc/tfunc_type.nim
index 2a583fcb9..93697acb1 100644
--- a/tests/proc/tfunc_type.nim
+++ b/tests/proc/tfunc_type.nim
@@ -1,6 +1,6 @@
 
 discard """
-  errmsg: "func keyword is not allowed in type descriptions, use proc with {.noSideEffect.} pragma instead"
+  errormsg: "func keyword is not allowed in type descriptions, use proc with {.noSideEffect.} pragma instead"
 """
 
 type
diff --git a/tests/proc/tgenericdefaultparam.nim b/tests/proc/tgenericdefaultparam.nim
new file mode 100644
index 000000000..7bce591ce
--- /dev/null
+++ b/tests/proc/tgenericdefaultparam.nim
@@ -0,0 +1,98 @@
+block: # issue #16700
+  type MyObject[T] = object
+    x: T
+  proc initMyObject[T](value = T.default): MyObject[T] =
+    MyObject[T](x: value)
+  var obj = initMyObject[int]()
+
+block: # issue #20916
+  type
+    SomeX = object
+      v: int
+  var val = 0
+  proc f(_: type int, x: SomeX, v = x.v) =
+    doAssert v == 42
+    val = v
+  proc a(): proc() =
+    let v = SomeX(v: 42)
+    var tmp = proc() =
+      int.f(v)
+    tmp
+  a()()
+  doAssert val == 42
+
+import std/typetraits
+
+block: # issue #24099, original example
+  type
+    ColorRGBU = distinct array[3, uint8] ## RGB range 0..255
+    ColorRGBAU = distinct array[4, uint8] ## RGB range 0..255
+    ColorRGBUAny = ColorRGBU | ColorRGBAU
+  template componentType(t: typedesc[ColorRGBUAny]): typedesc =
+    ## Returns component type of a given color type.
+    arrayType distinctBase t
+  func `~=`[T: ColorRGBUAny](a, b: T, e = componentType(T)(1.0e-11)): bool =
+    ## Compares colors with given accuracy.
+    abs(a[0] - b[0]) < e and abs(a[1] - b[1]) < e and abs(a[2] - b[2]) < e
+
+block: # issue #24099, modified to actually work
+  type
+    ColorRGBU = distinct array[3, uint8] ## RGB range 0..255
+    ColorRGBAU = distinct array[4, uint8] ## RGB range 0..255
+    ColorRGBUAny = ColorRGBU | ColorRGBAU
+  template arrayType[I, T](t: typedesc[array[I, T]]): typedesc =
+    T
+  template `[]`(a: ColorRGBUAny, i: untyped): untyped = distinctBase(a)[i]
+  proc abs(a: uint8): uint8 = a
+  template componentType(t: typedesc[ColorRGBUAny]): typedesc =
+    ## Returns component type of a given color type.
+    arrayType distinctBase t
+  func `~=`[T: ColorRGBUAny](a, b: T, e = componentType(T)(1.0e-11)): bool =
+    ## Compares colors with given accuracy.
+    abs(a[0] - b[0]) <= e and abs(a[1] - b[1]) <= e and abs(a[2] - b[2]) <= e
+  doAssert ColorRGBU([1.uint8, 1, 1]) ~= ColorRGBU([1.uint8, 1, 1])
+
+block: # issue #24099, modified to work but using float32
+  type
+    ColorRGBU = distinct array[3, float32] ## RGB range 0..255
+    ColorRGBAU = distinct array[4, float32] ## RGB range 0..255
+    ColorRGBUAny = ColorRGBU | ColorRGBAU
+  template arrayType[I, T](t: typedesc[array[I, T]]): typedesc =
+    T
+  template `[]`(a: ColorRGBUAny, i: untyped): untyped = distinctBase(a)[i]
+  template componentType(t: typedesc[ColorRGBUAny]): typedesc =
+    ## Returns component type of a given color type.
+    arrayType distinctBase t
+  func `~=`[T: ColorRGBUAny](a, b: T, e = componentType(T)(1.0e-11)): bool =
+    ## Compares colors with given accuracy.
+    abs(a[0] - b[0]) < e and abs(a[1] - b[1]) < e and abs(a[2] - b[2]) < e
+  doAssert ColorRGBU([1.float32, 1, 1]) ~= ColorRGBU([1.float32, 1, 1])
+
+block: # issue #13270
+  type
+    A = object
+    B = object
+  proc f(a: A) = discard
+  proc g[T](value: T, cb: (proc(a: T)) = f) =
+    cb value
+  g A()
+  # This should fail because there is no f(a: B) overload available
+  doAssert not compiles(g B())
+
+block: # issue #24121
+  type
+    Foo = distinct int
+    Bar = distinct int
+    FooBar = Foo | Bar
+
+  proc foo[T: distinct](x: T): string = "a"
+  proc foo(x: Foo): string = "b"
+  proc foo(x: Bar): string = "c"
+
+  proc bar(x: FooBar, y = foo(x)): string = y
+  doAssert bar(Foo(123)) == "b"
+  doAssert bar(Bar(123)) == "c"
+
+  proc baz[T: FooBar](x: T, y = foo(x)): string = y
+  doAssert baz(Foo(123)) == "b"
+  doAssert baz(Bar(123)) == "c"
diff --git a/tests/proc/tillegalreturntype.nim b/tests/proc/tillegalreturntype.nim
index e26c44bea..1076f7f75 100644
--- a/tests/proc/tillegalreturntype.nim
+++ b/tests/proc/tillegalreturntype.nim
@@ -1,6 +1,6 @@
 discard """
-  cmd: "nim check $file"
-  errmsg: ""
+  cmd: "nim check --hints:off $file"
+  errormsg: ""
   nimout: '''
 tillegalreturntype.nim(11, 11) Error: return type 'typed' is only valid for macros and templates
 tillegalreturntype.nim(14, 11) Error: return type 'untyped' is only valid for macros and templates
diff --git a/tests/proc/tinferlambdareturn.nim b/tests/proc/tinferlambdareturn.nim
new file mode 100644
index 000000000..e9e592871
--- /dev/null
+++ b/tests/proc/tinferlambdareturn.nim
@@ -0,0 +1,36 @@
+import std/[sugar, sequtils]
+
+block: # issue #23200
+  proc dosomething(iter: int -> (iterator: int)) =
+    discard
+  proc dosomething(iter: int -> seq[int]) =
+    discard
+  proc makeSeq(x: int): seq[int] =
+    @[x]
+  # Works fine with 1.6.12 and 1.6.14
+  dosomething(makeSeq)
+  # Works with 1.6.12, fails with 1.6.14
+  dosomething((y) => makeSeq(y))
+  dosomething(proc (y: auto): auto = makeSeq(y))
+  proc foo(y: auto): auto = makeSeq(y)
+  dosomething(foo)
+
+block: # issue #18866
+  proc somefn[T](list: openarray[T], op: proc (v: T): float) =
+    discard op(list[0])
+
+  type TimeD = object
+    year:  Natural
+    month: 1..12
+    day:   1..31
+
+  doAssert not compiles(@[TimeD()].somefn(proc (v: auto): auto =
+    v
+  ))
+  @[TimeD()].somefn(proc (v: auto): auto =
+    v.year.float
+  )
+  proc foo(v: auto): auto = v
+  doAssert not compiles(@[TimeD()].somefn(foo))
+  proc bar(v: auto): auto = v.year.float
+  @[TimeD()].somefn(bar)
diff --git a/tests/misc/tlambdadonotation.nim b/tests/proc/tlambdadonotation.nim
index af51efdbf..3160c0972 100644
--- a/tests/misc/tlambdadonotation.nim
+++ b/tests/proc/tlambdadonotation.nim
@@ -67,7 +67,7 @@ proc main2() =
   proc foo() =
     subscriber.consume()
 
-  emitter.on_event() do:
+  emitter.on_event() do ():
     subscriber.consume()
 
   # this works
diff --git a/tests/proc/tlambdapragma.nim b/tests/proc/tlambdapragma.nim
new file mode 100644
index 000000000..daa952b1e
--- /dev/null
+++ b/tests/proc/tlambdapragma.nim
@@ -0,0 +1,7 @@
+discard """
+  errormsg: "invalid pragma: exportc"
+"""
+
+let _ = proc () {.exportc.} =
+  # this would previously cause a codegen error
+  discard
diff --git a/tests/namedparams/tnamedparams.nim b/tests/proc/tnamedparams.nim
index d0774f0d8..d0774f0d8 100644
--- a/tests/namedparams/tnamedparams.nim
+++ b/tests/proc/tnamedparams.nim
diff --git a/tests/namedparams/tnamedparams2.nim b/tests/proc/tnamedparams2.nim
index 9acdeed87..9acdeed87 100644
--- a/tests/namedparams/tnamedparams2.nim
+++ b/tests/proc/tnamedparams2.nim
diff --git a/tests/namedparams/tnamedparams3.nim b/tests/proc/tnamedparams3.nim
index e736c338c..e736c338c 100644
--- a/tests/namedparams/tnamedparams3.nim
+++ b/tests/proc/tnamedparams3.nim
diff --git a/tests/misc/tparamsindefault.nim b/tests/proc/tparamsindefault.nim
index 3fe917f2b..3fe917f2b 100644
--- a/tests/misc/tparamsindefault.nim
+++ b/tests/proc/tparamsindefault.nim
diff --git a/tests/procvar/tprocvar.nim b/tests/proc/tprocvar.nim
index 14f24efdc..14f24efdc 100644
--- a/tests/procvar/tprocvar.nim
+++ b/tests/proc/tprocvar.nim
diff --git a/tests/procvar/tprocvarmismatch.nim b/tests/proc/tprocvarmismatch.nim
index 4d6be9be6..4d6be9be6 100644
--- a/tests/procvar/tprocvarmismatch.nim
+++ b/tests/proc/tprocvarmismatch.nim
diff --git a/tests/proc/tstaticsignature.nim b/tests/proc/tstaticsignature.nim
new file mode 100644
index 000000000..25aa09c5d
--- /dev/null
+++ b/tests/proc/tstaticsignature.nim
@@ -0,0 +1,268 @@
+block: # issue #4228
+  template seqType(t: typedesc): typedesc =
+    when t is int:
+      seq[int]
+    else:
+      seq[string]
+
+  proc mkSeq[T: int|string](v: T): seqType(T) =
+    result = newSeq[T](1)
+    result[0] = v
+
+  doAssert mkSeq("a") == @["a"]
+  doAssert mkSeq(1) == @[1]
+
+block: # expanded version of t8545
+  template bar(a: static[bool]): untyped =
+    when a:
+      int
+    else:
+      float
+
+  proc main() =
+    proc foo1(a: static[bool]): auto = 1
+    doAssert foo1(true) == 1
+
+    proc foo2(a: static[bool]): bar(a) = 1
+    doAssert foo2(true) == 1
+    doAssert foo2(true) is int
+    doAssert foo2(false) == 1.0
+    doAssert foo2(false) is float
+
+    proc foo3(a: static[bool]): bar(cast[bool](a)) = 1
+    doAssert foo3(true) == 1
+    doAssert foo3(true) is int
+    doAssert foo3(false) == 1.0
+    doAssert foo3(false) is float
+
+    proc foo4(a: static[bool]): bar(static(a)) = 1
+    doAssert foo4(true) == 1
+    doAssert foo4(true) is int
+    doAssert foo4(false) == 1.0
+    doAssert foo4(false) is float
+
+  static: main()
+  main()
+
+block: # issue #8406
+  macro f(x: static[int]): untyped = discard
+  proc g[X: static[int]](v: f(X)) = discard
+
+import macros
+
+block: # issue #8551
+  macro distinctBase2(T: typedesc): untyped =
+    let typeNode = getTypeImpl(T)
+    expectKind(typeNode, nnkBracketExpr)
+    if typeNode[0].typeKind != ntyTypeDesc:
+      error "expected typeDesc, got " & $typeNode[0]
+    var typeSym = typeNode[1]
+
+    typeSym = getTypeImpl(typeSym)
+
+    if typeSym.typeKind != ntyDistinct:
+      error "type is not distinct: " & $typeSym.typeKind
+
+    typeSym = typeSym[0]
+    typeSym
+
+  func distinctBase[T](a: T): distinctBase2(T) = distinctBase2(T)(a)
+
+  type T = distinct int
+  doAssert distinctBase(T(0)) is int
+
+block:
+  type Foo[T] = object
+    x: T
+
+  proc foo(x: Foo): Foo[x.T] =
+    doAssert typeof(result) is typeof(x)
+
+  var a: Foo[int]
+  let b: Foo[int] = foo(a)
+  doAssert b.x is int
+
+block:
+  type Foo[T: static int] = object
+    x: array[T, int]
+  
+  proc double(x: int): int = x * 2
+
+  proc foo[T: static int](x: Foo[T]): Foo[T.double] =
+    doAssert typeof(result).T == double(typeof(x).T)
+
+  var a: Foo[3]
+  let b: Foo[6] = foo(a)
+  doAssert $typeof(foo(a)) == "Foo[6]"
+
+block:
+  type Foo[T: static int] = object
+    x: array[T, int]
+
+  proc foo(x: Foo): Foo[x.T] =
+    doAssert typeof(result).T == typeof(x).T
+    doAssert typeof(result) is typeof(x)
+
+  var a: Foo[3]
+  let b: Foo[3] = foo(a)
+  doAssert $typeof(foo(a)) == "Foo[3]"
+
+block: # issue #7006
+  type
+    Node[T] = object
+      val: T
+      next: ref Node[T]
+    HHSet[T, Key] = object
+      data: seq[Node[T]]
+  proc rawGet(hhs:HHSet; key: hhs.Key): ptr Node[hhs.T] =
+    return nil # body doesn't matter
+  var hhs: HHSet[string, cstring]
+  discard hhs.rawGet("hello".cstring)
+
+block: # issue #7008
+  type Node[T] = object
+    val: T
+  # Compiles fine
+  proc concreteProc(s: Node[cstring]; key: s.T) = discard
+  # Also fine
+  proc implicitGenericProc1(s: Node; key: s.T) = discard
+  # still fine
+  proc explicitGenericProc1[T](s: Node[T]; key: T) = discard
+  # Internal Compiler Error!
+  proc explicitGenericProc2[T](s: Node[T]; key: s.T) = discard
+  let n = Node[int](val: 5)
+  implicitGenericProc1(n, 5) # works
+  explicitGenericProc1(n, 5) # works
+  explicitGenericProc2(n, 5) # doesn't
+
+block: # issue #20027
+  block:
+    type Test[T] = object
+    proc run(self: Test): self.T = discard
+    discard run(Test[int]())
+  block:
+    type Test[T] = object
+    proc run[T](self: Test[T]): self.T = discard
+    discard run(Test[int]())
+  block:
+    type Test[T] = object
+    proc run(self: Test[auto]): self.T = discard
+    discard run(Test[int]())
+
+block: # issue #11112
+  proc foo[A, B]: type(A.default + B.default) =
+    discard
+  doAssert foo[int, int]() is int
+
+block: # tyStatic and tyFromExpr instantiation mid-match
+  proc bar(x: int): int = x * 3
+  proc bar2(x: static int): int = x * 4
+  type Foo[T: static int] = distinct array[T, int]
+  proc foo[T: static int](x: Foo[T], y: Foo[bar(T)]) = discard
+  proc foo2[T: static int](x: Foo[T], y: Foo[bar2(T)]) = discard
+  foo(Foo[1]([1]), Foo[3]([1, 2, 3]))
+  foo2(Foo[1]([1]), Foo[4]([1, 2, 3, 4]))
+
+block: # issue #4990
+  type Foo[I: static[int], A: static[array[I, int]]] = object
+    curIndex: int
+
+  proc next[I: static[int], A: static[array[I, int]]](f: Foo[I, A]): string =
+    discard
+  const arr = [1, 2, 3]
+  var f: Foo[arr.len, arr]
+  discard next(f)
+
+block: # issue #4990 comment
+  type
+    Foo[A: static[int], B: static[int], TokenType: enum, EofToken: static[TokenType]] = object
+      curIndex: int
+    MyEnum = enum
+      meA, meB
+    Bar = Foo[2, 3, MyEnum, meA]
+  proc next[A: static[int], B: static[int], TokenType: enum,
+            EofToken: static[TokenType]](f: Foo[A, B, TokenType, EofToken],
+      a: static[(array[A, int], array[B, int])]): TokenType =
+    TokenType(a[0][f.curIndex])
+  const
+    a = [1, 2]
+    b = [3, 4, 5]
+  template next(bar: Bar): MyEnum =
+    next(Foo[2, 3, MyEnum, meA](bar), (a, b))
+  let bar = Bar(curIndex: 0)
+  doAssert bar.next() == meB
+
+block: # issue #14053
+  template returnType(value: static[int]): typedesc =
+    when value == 1:
+      int
+    else:
+      float
+  proc fun(value: static[int]): returnType(value) = discard
+  doAssert fun(1) is int
+  template returnType2(value: static[int]): typedesc =
+    int
+  proc fun2(value: static[int]): returnType2(value) = discard
+  doAssert fun2(1) is int
+
+block: # issue #7547
+  macro foo(N: static[int]): untyped =
+    result = getType(int)
+  type
+    Foo[N: static[int]] = foo(N)
+    ContainsFoo[N: static[int]] = object
+      Ffoo: Foo[N]
+  proc initFoo(N: static[int]): Foo[N] = discard
+  proc initContainsFoo(size: static[int]): ContainsFoo[size] = discard
+  var a: Foo[10] # Works
+  doAssert a is int
+  let b = initFoo(10) # Works
+  doAssert b is int
+  let c = ContainsFoo[5]() # Works
+  doAssert c.Ffoo is int
+  let z = initContainsFoo(5) # Error: undeclared identifier: 'N'
+  doAssert z.Ffoo is int
+
+block: # issue #22607, needs nkWhenStmt to be handled like nkRecWhen
+  proc test[x: static bool](
+    t: (
+      when x:
+        int
+      else:
+        float
+      )
+  ) = discard
+  test[true](1.int)
+  test[false](1.0)
+  doAssert not compiles(test[])
+
+block: # `when` in static signature
+  template ctAnd(a, b): bool =
+    when a:
+      when b: true
+      else: false
+    else: false
+  template test(): untyped =
+    when ctAnd(declared(SharedTable), typeof(result) is SharedTable):
+      result = SharedTable()
+    else:
+      result = 123
+  proc foo[T](): T = test()
+  proc bar[T](x = foo[T]()): T = x
+  doAssert bar[int]() == 123
+
+block: # issue #22276
+  type Foo = enum A, B
+  macro test(y: static[Foo]): untyped =
+    if y == A:
+      result = parseExpr("proc (x: int)")
+    else:
+      result = parseExpr("proc (x: float)")
+  proc foo(y: static[Foo], x: test(y)) = # We want to make the type of `x` depend on what `y` is
+    x(9)
+  foo(A, proc (x: int) = doAssert x == 9)
+  var a: int
+  foo(A, proc (x: int) =
+    a = x * 2)
+  doAssert a == 18
+  foo(B, proc (x: float) = doAssert x == 9)
diff --git a/tests/proc/tunderscoreparam.nim b/tests/proc/tunderscoreparam.nim
new file mode 100644
index 000000000..8d60603f1
--- /dev/null
+++ b/tests/proc/tunderscoreparam.nim
@@ -0,0 +1,122 @@
+discard """
+  targets: "c cpp js"
+"""
+
+import std/[assertions, sequtils]
+
+proc test() =
+  block:
+    proc ok(_, _, a: int): int =
+      doAssert not compiles(_)
+      a
+    doassert ok(4, 2, 5) == 5
+
+  block:
+    proc ok(_: int, _: int, a: int): int = a
+    doAssert ok(4, 2, 5) == 5
+
+  block:
+    proc ok(_: int, _: float, a: int): int = a
+    doAssert ok(1, 2.0, 5) == 5
+
+  block:
+    proc ok(_: int, _: float, _: string, a: int): int = a
+    doAssert ok(1, 2.6, "5", 5) == 5
+    
+  block:
+    proc ok[T](_, _, a: T): T =
+      doAssert not compiles(_)
+      a
+    doAssert ok(4, 2, 5) == 5
+    doAssert ok("a", "b", "c") == "c"
+    doAssert not compiles(ok(1, 2, "a"))
+  
+  block:
+    let ok = proc (_, _, a: int): int =
+      doAssert not compiles(_)
+      a
+    doAssert ok(4, 2, 5) == 5
+  
+  block:
+    proc foo(lam: proc (_, _, a: int): int): int =
+      lam(4, 2, 5)
+    doAssert foo(proc (_, _, a: auto): auto =
+      doAssert not compiles(_)
+      a) == 5
+    
+  block:
+    iterator fn(_, _: int, c: int): int = yield c
+    doAssert toSeq(fn(1,2,3)) == @[3]
+
+  block:
+    template ok(_, _, a: int): int = a
+    doAssert ok(4, 2, 5) == 5
+
+  block:
+    doAssert not (compiles do:
+      template bad(_: int): int = _
+      discard bad(3))
+
+  block:
+    template ok(_: int, _: int, a: int): int = a
+    doAssert ok(4, 2, 5) == 5
+
+  block:
+    template ok(_: int, _: float, a: int): int = a
+    doAssert ok(1, 2.0, 5) == 5
+
+  block:
+    template ok(_: int, _: float, _: string, a: int): int = a
+    doAssert ok(1, 2.6, "5", 5) == 5
+  
+  block:
+    template main2() =
+      iterator fn(_, _: int, c: int): int = yield c
+    main2()
+
+  block:
+    template main =
+      proc foo(_: int) =
+        let a = _
+    doAssert not compiles(main())
+  
+  block: # generic params
+    doAssert not (compiles do:
+      proc foo[_](t: typedesc[_]): seq[_] = @[default(_)]
+      doAssert foo[int]() == 0)
+  
+  block:
+    proc foo[_, _](): int = 123
+    doAssert foo[int, bool]() == 123
+  
+  block:
+    proc foo[T; U](_: typedesc[T]; _: typedesc[U]): (T, U) = (default(T), default(U))
+    doAssert foo(int, bool) == (0, false)
+
+proc closureTest() =
+  var x = 0
+
+  block:
+    proc foo(_, _: int) = x += 5
+
+    foo(1, 2)
+    doAssert x == 5
+
+  block:
+    proc foo(_: int, _: float) = x += 5
+
+    foo(1, 2)
+    doAssert x == 10
+
+  block:
+    proc foo(_: int, _: float, _: string) = x += 5
+
+    foo(1, 2, "5")
+    doAssert x == 15
+
+static: test()
+test()
+
+when not defined(js):
+  static: closureTest()
+closureTest()
diff --git a/tests/proc/twrongdefaultvalue.nim b/tests/proc/twrongdefaultvalue.nim
new file mode 100644
index 000000000..2c36c2247
--- /dev/null
+++ b/tests/proc/twrongdefaultvalue.nim
@@ -0,0 +1,25 @@
+discard """
+  cmd: "nim check $file"
+  action: reject
+  nimout: '''
+twrongdefaultvalue.nim(20, 12) template/generic instantiation of `doit` from here
+twrongdefaultvalue.nim(17, 37) Error: type mismatch: got <proc (p: int): Item[initItem.T]> but expected 'Item[system.string]'
+twrongdefaultvalue.nim(25, 3) template/generic instantiation of `foo` from here
+twrongdefaultvalue.nim(23, 33) Error: type mismatch: got <string> but expected 'int'
+'''
+"""
+
+block: # issue #21258
+  type Item[T] = object
+    pos: int
+  proc initItem[T](p:int=10000) : Item[T] = 
+    result = Item[T](p)
+  proc doit[T](x:Item[T], s:Item[T]=initItem) : string = 
+    return $x.pos
+  let x = Item[string](pos:100)
+  echo doit(x)
+
+block: # issue #21258, reduced case
+  proc foo[T](x: seq[T], y: T = "foo") =
+    discard
+  foo @[1, 2, 3]
diff --git a/tests/range/t19678.nim b/tests/range/t19678.nim
new file mode 100644
index 000000000..88f7eff89
--- /dev/null
+++ b/tests/range/t19678.nim
@@ -0,0 +1,17 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  errormsg: ""
+  nimout: '''
+t19678.nim(13, 13) Error: range of string is invalid
+
+
+
+'''
+"""
+
+case "5":
+  of "0" .. "9":
+    discard
+  else:
+    discard
+
diff --git a/tests/range/tcompiletime_range_checks.nim b/tests/range/tcompiletime_range_checks.nim
index 37095e0b7..2d3f292ec 100644
--- a/tests/range/tcompiletime_range_checks.nim
+++ b/tests/range/tcompiletime_range_checks.nim
@@ -1,8 +1,8 @@
 discard """
-  cmd: "nim check --hint[Processing]:off --hint[Conf]:off $file"
+  cmd: "nim check --hint:Processing:off --hint:Conf:off $file"
   errormsg: "18446744073709551615 can't be converted to int8"
-  nimout: '''tcompiletime_range_checks.nim(36, 21) Error: 2147483648 can't be converted to int32
-tcompiletime_range_checks.nim(37, 23) Error: -1 can't be converted to uint64
+  nimout: '''
+tcompiletime_range_checks.nim(36, 21) Error: 2147483648 can't be converted to int32
 tcompiletime_range_checks.nim(38, 34) Error: 255 can't be converted to FullNegativeRange
 tcompiletime_range_checks.nim(39, 34) Error: 18446744073709551615 can't be converted to HalfNegativeRange
 tcompiletime_range_checks.nim(40, 34) Error: 300 can't be converted to FullPositiveRange
diff --git a/tests/range/texplicitvarconv.nim b/tests/range/texplicitvarconv.nim
new file mode 100644
index 000000000..8da8a8878
--- /dev/null
+++ b/tests/range/texplicitvarconv.nim
@@ -0,0 +1,13 @@
+# related to issue #24032
+
+proc `++`(n: var int) =
+    n += 1
+
+type
+    r = range[ 0..15 ]
+
+var a: r = 14
+
+++int(a) # this should be mutable
+
+doAssert a == 15
diff --git a/tests/range/toutofrangevarconv.nim b/tests/range/toutofrangevarconv.nim
new file mode 100644
index 000000000..1ee4d340e
--- /dev/null
+++ b/tests/range/toutofrangevarconv.nim
@@ -0,0 +1,14 @@
+discard """
+  outputsub: "value out of range: 5 notin 0 .. 3 [RangeDefect]"
+  exitcode: "1"
+"""
+
+# make sure out of bounds range conversion is detected for `var` conversions
+
+type R = range[0..3]
+
+proc foo(x: var R) =
+  doAssert x in 0..3
+
+var x = 5
+foo(R(x))
diff --git a/tests/range/trange.nim b/tests/range/trange.nim
index c864387f6..abfa7d474 100644
--- a/tests/range/trange.nim
+++ b/tests/range/trange.nim
@@ -74,37 +74,37 @@ block tn8vsint16:
 
 import strutils
 block tcolors:
-  type TColor = distinct int32
+  type TColor = distinct uint32
 
   proc rgb(r, g, b: range[0..255]): TColor =
     result = TColor(r or g shl 8 or b shl 16)
   proc `$`(c: TColor): string =
-    result = "#" & toHex(int32(c), 6)
+    result = "#" & toHex(uint32(c), 6)
   echo rgb(34, 55, 255)
 
-  when false:
+  block:
     type
-      TColor = distinct int32
-      TColorComponent = distinct int8
+      TColor = distinct uint32
+      TColorComponent = distinct uint8
 
     proc red(a: TColor): TColorComponent =
-      result = TColorComponent(int32(a) and 0xff'i32)
+      result = TColorComponent(uint32(a) and 0xff'u32)
     proc green(a: TColor): TColorComponent =
-      result = TColorComponent(int32(a) shr 8'i32 and 0xff'i32)
+      result = TColorComponent(uint32(a) shr 8'u32 and 0xff'u32)
     proc blue(a: TColor): TColorComponent =
-      result = TColorComponent(int32(a) shr 16'i32 and 0xff'i32)
+      result = TColorComponent(uint32(a) shr 16'u32 and 0xff'u32)
     proc rgb(r, g, b: range[0..255]): TColor =
       result = TColor(r or g shl 8 or b shl 8)
 
     proc `+!` (a, b: TColorComponent): TColorComponent =
       ## saturated arithmetic:
-      result = TColorComponent(min(ze(int8(a)) + ze(int8(b)), 255))
+      result = TColorComponent(min(int(uint8(a)) + int(uint8(b)), 255))
 
     proc `+` (a, b: TColor): TColor =
       ## saturated arithmetic for colors makes sense, I think:
-      return rgb(red(a) +! red(b), green(a) +! green(b), blue(a) +! blue(b))
+      return rgb(int(red(a) +! red(b)), int(green(a) +! green(b)), int(blue(a) +! blue(b)))
 
-    rgb(34, 55, 255)
+    discard rgb(34, 55, 255)
 
 block:
   type
@@ -142,3 +142,15 @@ var a: array[4'u, string]
 
 for i in 0..<a.len:
   a[i] = "foo"
+
+# Check range to ordinal conversions
+block:
+  var
+    a: int16
+    b: range[0'i32..45'i32] = 3
+    c: uint16
+    d: range[0'u32..46'u32] = 3
+  a = b
+  c = d
+  doAssert a == b
+  doAssert c == d
diff --git a/tests/range/tsubrange2.nim b/tests/range/tsubrange2.nim
index e0fb71c5f..fbd1ca760 100644
--- a/tests/range/tsubrange2.nim
+++ b/tests/range/tsubrange2.nim
@@ -1,5 +1,5 @@
 discard """
-  outputsub: "value out of range: 50 [RangeError]"
+  outputsub: "value out of range: 50 notin 0 .. 40 [RangeDefect]"
   exitcode: "1"
 """
 
diff --git a/tests/range/tsubrange3.nim b/tests/range/tsubrange3.nim
index d3aae87df..55eb4618b 100644
--- a/tests/range/tsubrange3.nim
+++ b/tests/range/tsubrange3.nim
@@ -1,5 +1,5 @@
 discard """
-  outputsub: "value out of range: 50 [RangeError]"
+  outputsub: "value out of range: 50 notin 0 .. 40 [RangeDefect]"
   exitcode: "1"
 """
 
diff --git a/tests/readme.md b/tests/readme.md
index b9b8abd39..f638ddc10 100644
--- a/tests/readme.md
+++ b/tests/readme.md
@@ -2,21 +2,20 @@ This directory contains the test cases.
 
 Each test must have a filename of the form: ``t*.nim``
 
-**Note:** Tests are only compiled by default. In order to get the tester to
-execute the compiled binary, you need to specify a spec with an ``action`` key
-(see below for details).
+**Note:** [Testament](https://nim-lang.github.io/Nim/testament.html) is only aware of tests under a directory (eg `tests/foo/`) and will ignore
+top-level tests like `tests/tbar.nim`.
 
 # Specs
 
 Each test can contain a spec in a ``discard """ ... """`` block.
 
-**Check out the [``parseSpec`` procedure](https://github.com/nim-lang/Nim/blob/devel/testament/specs.nim#L132) in the ``specs`` module for a full and reliable reference**
+**Check out the [``parseSpec`` procedure](https://github.com/nim-lang/Nim/blob/devel/testament/specs.nim#L315) in the ``specs`` module for a full and reliable reference**
 
 ## action
 
 Specifies what action this test should take.
 
-**Default: compile**
+**Default: run**
 
 Options:
 
@@ -28,35 +27,13 @@ Options:
 There are certain spec keys that imply ``run``, including ``output`` and
 ``outputsub``.
 
-## cmd
-
-Specifies the Nim command to use for compiling the test.
-
-There are a number of variables that are replaced in this spec option:
-
-* ``$target`` - the compilation target, e.g. ``c``.
-* ``$options`` - the options for the compiler.
-* ``$file`` - the filename of the test.
-* ``$filedir`` - the directory of the test file.
-
-Example:
-
-```nim
-discard """
-  cmd: "nim $target --nimblePath:./nimbleDir/simplePkgs $options $file"
-"""
-```
-
 # Categories
 
 Each folder under this directory represents a test category, which can be
-tested by running `koch tests cat <category>`.
-
-The folder ``rodfiles`` contains special tests that test incremental
-compilation via symbol files.
+tested by running `koch tests pcat <category>` (or `cat` to avoid parallel
+testing, which is slower).
 
 The folder ``dll`` contains simple DLL tests.
 
 The folder ``realtimeGC`` contains a test for validating that the realtime GC
-can run properly without linking against the nimrtl.dll/so. It includes a C
-client and platform specific build files for manual compilation.
+can run properly without linking against the nimrtl.dll/so.
diff --git a/tests/realtimeGC/cmain.c b/tests/realtimeGC/cmain.c
deleted file mode 100644
index 0d4bb096a..000000000
--- a/tests/realtimeGC/cmain.c
+++ /dev/null
@@ -1,67 +0,0 @@
-#ifdef WIN
-#include <windows.h>
-#else
-#include <dlfcn.h>
-#include <unistd.h> /* for sleep(3) */
-#endif
-#include <stdio.h>
-#include <stdlib.h>
-#include <string.h>
-#include <assert.h>
-#include <time.h>
-
-#define RUNTIME (15*60)
-
-
-typedef void (*pFunc)(void);
-
-int main(int argc, char* argv[])
-{
-    int i;
-    void* hndl;
-    pFunc status;
-    pFunc count;
-    pFunc checkOccupiedMem;
-
-#ifdef WIN
-    hndl = (void*) LoadLibrary((char const*)"./tests/realtimeGC/shared.dll");
-    status = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"status");
-    count = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"count");
-    checkOccupiedMem = (pFunc)GetProcAddress((HMODULE) hndl, (char const*)"checkOccupiedMem");
-#else /* OSX || NIX */
-    hndl = (void*) dlopen((char const*)"./tests/realtimeGC/libshared.so", RTLD_LAZY);
-    status = (pFunc) dlsym(hndl, (char const*)"status");
-    count = (pFunc) dlsym(hndl, (char const*)"count");
-    checkOccupiedMem = (pFunc) dlsym(hndl, (char const*)"checkOccupiedMem");
-#endif
-
-    assert(hndl);
-    assert(status);
-    assert(count);
-    assert(checkOccupiedMem);
-
-    time_t startTime = time((time_t*)0);
-    time_t runTime = (time_t)(RUNTIME);
-    time_t accumTime = 0;
-    while (accumTime < runTime) {
-        for (i = 0; i < 10; i++)
-            count();
-        /* printf("1. sleeping...\n"); */
-        sleep(1);
-        for (i = 0; i < 10; i++)
-            status();
-        /* printf("2. sleeping...\n"); */
-        sleep(1);
-        checkOccupiedMem();
-        accumTime = time((time_t*)0) - startTime;
-        /* printf("--- Minutes left to run: %d\n", (int)(runTime-accumTime)/60); */
-    }
-    printf("Cleaning up the shared object pointer...\n");
-#ifdef WIN
-    FreeLibrary((HMODULE)hndl);
-#else /* OSX || NIX */
-    dlclose(hndl);
-#endif
-    printf("Done\n");
-    return 0;
-}
diff --git a/tests/realtimeGC/main.nim.cfg b/tests/realtimeGC/main.nim.cfg
deleted file mode 100644
index fed4fa471..000000000
--- a/tests/realtimeGC/main.nim.cfg
+++ /dev/null
@@ -1,6 +0,0 @@
-
---app:console
---threads:on
-
--d:release
--d:useRealtimeGC
diff --git a/tests/realtimeGC/nmain.nim b/tests/realtimeGC/nmain.nim
deleted file mode 100644
index c9f558dbc..000000000
--- a/tests/realtimeGC/nmain.nim
+++ /dev/null
@@ -1,46 +0,0 @@
-discard """
-  cmd: "nim $target --debuginfo $options $file"
-  output: "Done"
-"""
-
-import times, os, threadpool
-
-const RUNTIME = 15 * 60 # 15 minutes
-
-when defined(windows):
-  const dllname = "./tests/realtimeGC/shared.dll"
-elif defined(macosx):
-  const dllname = "./tests/realtimeGC/libshared.dylib"
-else:
-  const dllname = "./tests/realtimeGC/libshared.so"
-
-proc status() {.importc: "status", dynlib: dllname.}
-proc count() {.importc: "count", dynlib: dllname.}
-proc checkOccupiedMem() {.importc: "checkOccupiedMem", dynlib: dllname.}
-
-proc process() =
-  let startTime = getTime()
-  let runTime = cast[Time](RUNTIME) #
-  var accumTime: Time
-  while accumTime < runTime:
-    for i in 0..10:
-      count()
-    # echo("1. sleeping... ")
-    sleep(500)
-    for i in 0..10:
-      status()
-    # echo("2. sleeping... ")
-    sleep(500)
-    checkOccupiedMem()
-    accumTime = cast[Time]((getTime() - startTime))
-    # echo("--- Minutes left to run: ", int(int(runTime-accumTime)/60))
-
-proc main() =
-  process()
-  # parallel:
-  #   for i in 0..0:
-  #     spawn process()
-  # sync()
-  echo("Done")
-
-main()
diff --git a/tests/realtimeGC/readme.txt b/tests/realtimeGC/readme.txt
deleted file mode 100644
index b2e37a1f0..000000000
--- a/tests/realtimeGC/readme.txt
+++ /dev/null
@@ -1,21 +0,0 @@
-Test the realtime GC without linking nimrtl.dll/so.
-
-Note, this is a long running test, default is 35 minutes. To change the
-the run time see RUNTIME in nmain.nim and cmain.c.
-
-You can build shared.nim, nmain.nim, and cmain.c by running make (nix systems)
-or make.bat (Windows systems). They both assume GCC and that it's in your
-path. Output: shared.(dll/so), cmain(.exe), nmain(.exe).
-
-To run the test: execute either nmain or cmain in a shell window.
-
-To build by hand:
-
-  - build the shared object (shared.nim):
-
-    $ nim c tests/realtimeGC/shared.nim
-
-  - build the client executables:
-
-    $ nim c --threads:on tests/realtimeGC/nmain.nim
-    $ gcc -o tests/realtimeGC/cmain tests/realtimeGC/cmain.c -ldl
diff --git a/tests/realtimeGC/shared.nim b/tests/realtimeGC/shared.nim
index 1abe42089..8b5c05e47 100644
--- a/tests/realtimeGC/shared.nim
+++ b/tests/realtimeGC/shared.nim
@@ -1,8 +1,3 @@
-discard """
-cmd: "nim $target --debuginfo --hints:on --app:lib $options $file"
-action: compile
-"""
-
 import strutils
 
 # Global state, accessing with threads, no locks. Don't do this at
diff --git a/tests/realtimeGC/shared.nim.cfg b/tests/realtimeGC/shared.nim.cfg
deleted file mode 100644
index e153b26fa..000000000
--- a/tests/realtimeGC/shared.nim.cfg
+++ /dev/null
@@ -1,5 +0,0 @@
---app:lib
---threads:on
-
--d:release
--d:useRealtimeGC
diff --git a/tests/realtimeGC/tmain.nim b/tests/realtimeGC/tmain.nim
new file mode 100644
index 000000000..ca0177e3d
--- /dev/null
+++ b/tests/realtimeGC/tmain.nim
@@ -0,0 +1,62 @@
+discard """
+  cmd: "nim $target --threads:on -d:release -d:useRealtimeGC $options $file"
+  joinable:false
+"""
+
+#[
+was: cmd: "nim $target --debuginfo $options $file"
+these dont' seem needed --debuginfo
+nor these from the previous main.nim.cfg: --app:console
+]#
+
+#[
+Test the realtime GC without linking nimrtl.dll/so.
+
+To build by hand and run the test for 35 minutes:
+`nim r --threads:on -d:runtimeSecs:2100 tests/realtimeGC/tmain.nim`
+]#
+
+import times, os, strformat, strutils
+from stdtest/specialpaths import buildDir
+# import threadpool
+
+const runtimeSecs {.intdefine.} = 5
+
+const file = "shared.nim"
+const dllname = buildDir / (DynlibFormat % "shared_D20210524T180506")
+
+static:
+  # D20210524T180826:here we compile the dependency on the fly
+  let nim = getCurrentCompilerExe()
+  let (output, exitCode) = gorgeEx(fmt"{nim} c -o:{dllname} --debuginfo --app:lib --threads:on -d:release -d:useRealtimeGC {file}")
+  doAssert exitCode == 0, output
+
+proc status() {.importc: "status", dynlib: dllname.}
+proc count() {.importc: "count", dynlib: dllname.}
+proc checkOccupiedMem() {.importc: "checkOccupiedMem", dynlib: dllname.}
+
+proc process() =
+  let startTime = getTime()
+  let runTime = cast[Time](runtimeSecs)
+  var accumTime: Time
+  while accumTime < runTime:
+    for i in 0..10:
+      count()
+    # echo("1. sleeping... ")
+    sleep(500)
+    for i in 0..10:
+      status()
+    # echo("2. sleeping... ")
+    sleep(500)
+    checkOccupiedMem()
+    accumTime = cast[Time]((getTime() - startTime))
+    # echo("--- Minutes left to run: ", int(int(runTime-accumTime)/60))
+
+proc main() =
+  process()
+  # parallel:
+  #   for i in 0..0:
+  #     spawn process()
+  # sync()
+
+main()
diff --git a/tests/refc/tsinkbug.nim b/tests/refc/tsinkbug.nim
new file mode 100644
index 000000000..de2ec98a5
--- /dev/null
+++ b/tests/refc/tsinkbug.nim
@@ -0,0 +1,26 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+  output: '''
+Value is: 42
+Value is: 42'''
+"""
+
+type AnObject* = object of RootObj
+  value*: int
+
+proc mutate(a: sink AnObject) =
+  a.value = 1
+
+var obj = AnObject(value: 42)
+echo "Value is: ", obj.value
+mutate(obj)
+echo "Value is: ", obj.value
+
+proc p(x: sink string) = 
+  var y = move(x)
+  doAssert x.len == 0
+  doAssert y.len == 4
+
+p("1234")
+var s = "oooo"
+p(s)
diff --git a/tests/rodfiles/aconv.nim b/tests/rodfiles/aconv.nim
deleted file mode 100644
index ffd8f3648..000000000
--- a/tests/rodfiles/aconv.nim
+++ /dev/null
@@ -1,9 +0,0 @@
-discard """
-  output: "ugly conversion successful"
-"""
-
-import int2bool
-
-if 4:
-  echo "ugly conversion successful"
-
diff --git a/tests/rodfiles/amethods.nim b/tests/rodfiles/amethods.nim
deleted file mode 100644
index 29cf757f7..000000000
--- a/tests/rodfiles/amethods.nim
+++ /dev/null
@@ -1,13 +0,0 @@
-
-type
-  TBaseClass* = object of RootObj
-
-proc newBaseClass*: ref TBaseClass =
-  new result
-
-method echoType*(x: ref TBaseClass) {.base.} =
-  echo "base class"
-
-proc echoAlias*(x: ref TBaseClass) =
-  echoType x
-
diff --git a/tests/rodfiles/bconv.nim b/tests/rodfiles/bconv.nim
deleted file mode 100644
index 2289a7f97..000000000
--- a/tests/rodfiles/bconv.nim
+++ /dev/null
@@ -1,9 +0,0 @@
-discard """
-  output: "ugly conversion successful 2"
-"""
-
-import int2bool
-
-if 4:
-  echo "ugly conversion successful 2"
-
diff --git a/tests/rodfiles/bmethods.nim b/tests/rodfiles/bmethods.nim
deleted file mode 100644
index c77941e4a..000000000
--- a/tests/rodfiles/bmethods.nim
+++ /dev/null
@@ -1,29 +0,0 @@
-discard """
-  output: '''derived class
-base class
-'''
-"""
-
-import amethods
-
-
-type
-  TDerivedClass* = object of TBaseClass
-
-proc newDerivedClass: ref TDerivedClass =
-  new result
-
-method echoType*(x: ref TDerivedClass) =
-  echo "derived class"
-
-var b, d: ref TBaseClass
-
-b = newBaseClass()
-d = newDerivedClass()
-
-#b.echoType()
-#d.echoType()
-
-echoAlias d
-echoAlias b
-
diff --git a/tests/rodfiles/bmethods2.nim b/tests/rodfiles/bmethods2.nim
deleted file mode 100644
index c9d25eee4..000000000
--- a/tests/rodfiles/bmethods2.nim
+++ /dev/null
@@ -1,29 +0,0 @@
-discard """
-  output: '''derived class 2
-base class
-'''
-"""
-
-import amethods
-
-
-type
-  TDerivedClass* = object of TBaseClass
-
-proc newDerivedClass: ref TDerivedClass =
-  new result
-
-method echoType*(x: ref TDerivedClass) =
-  echo "derived class 2"
-
-var b, d: ref TBaseClass
-
-b = newBaseClass()
-d = newDerivedClass()
-
-#b.echoType()
-#d.echoType()
-
-echoAlias d
-echoAlias b
-
diff --git a/tests/rodfiles/deada.nim b/tests/rodfiles/deada.nim
deleted file mode 100644
index 3fa4192f8..000000000
--- a/tests/rodfiles/deada.nim
+++ /dev/null
@@ -1,8 +0,0 @@
-discard """
-  output: '''246
-'''
-"""
-
-import deadg, deadb
-
-
diff --git a/tests/rodfiles/deada2.nim b/tests/rodfiles/deada2.nim
deleted file mode 100644
index 2925b4d43..000000000
--- a/tests/rodfiles/deada2.nim
+++ /dev/null
@@ -1,12 +0,0 @@
-discard """
-  output: '''246
-xyzabc
-'''
-"""
-
-import deadg, deadb
-
-# now add call to previously unused proc p2:
-echo p2("xyz", "abc")
-
-
diff --git a/tests/rodfiles/deadb.nim b/tests/rodfiles/deadb.nim
deleted file mode 100644
index 776a07ac7..000000000
--- a/tests/rodfiles/deadb.nim
+++ /dev/null
@@ -1,7 +0,0 @@
-
-import deadg
-
-
-echo p1(123, 123)
-
-
diff --git a/tests/rodfiles/deadg.nim b/tests/rodfiles/deadg.nim
deleted file mode 100644
index 0aee59bb8..000000000
--- a/tests/rodfiles/deadg.nim
+++ /dev/null
@@ -1,7 +0,0 @@
-proc p1*(x, y: int): int =
-  result = x + y
-
-proc p2*(x, y: string): string =
-  result = x & y
-
-
diff --git a/tests/rodfiles/gtkex1.nim b/tests/rodfiles/gtkex1.nim
deleted file mode 100644
index 50779cb9e..000000000
--- a/tests/rodfiles/gtkex1.nim
+++ /dev/null
@@ -1,14 +0,0 @@
-import
-  cairo, glib2, gtk2
-
-proc destroy(widget: PWidget, data: Pgpointer) {.cdecl.} =
-  main_quit()
-
-var
-  window: PWidget
-nim_init()
-window = window_new(WINDOW_TOPLEVEL)
-discard signal_connect(window, "destroy",
-                       SIGNAL_FUNC(gtkex1.destroy), nil)
-show(window)
-main()
diff --git a/tests/rodfiles/gtkex2.nim b/tests/rodfiles/gtkex2.nim
deleted file mode 100644
index 0949e4872..000000000
--- a/tests/rodfiles/gtkex2.nim
+++ /dev/null
@@ -1,22 +0,0 @@
-
-import
-  glib2, gtk2
-
-proc destroy(widget: PWidget, data: Pgpointer){.cdecl.} =
-  main_quit()
-
-var
-  window: PWidget
-  button: PWidget
-
-nim_init()
-window = window_new(WINDOW_TOPLEVEL)
-button = button_new("Click me")
-set_border_width(PContainer(window), 5)
-add(PContainer(window), button)
-discard signal_connect(window, "destroy",
-                           SIGNAL_FUNC(gtkex2.destroy), nil)
-show(button)
-show(window)
-main()
-
diff --git a/tests/rodfiles/hallo.nim b/tests/rodfiles/hallo.nim
deleted file mode 100644
index ac45be9fa..000000000
--- a/tests/rodfiles/hallo.nim
+++ /dev/null
@@ -1,6 +0,0 @@
-discard """
-  output: "Hello World"
-"""
-
-echo "Hello World"
-
diff --git a/tests/rodfiles/hallo2.nim b/tests/rodfiles/hallo2.nim
deleted file mode 100644
index 40fe64cfd..000000000
--- a/tests/rodfiles/hallo2.nim
+++ /dev/null
@@ -1,17 +0,0 @@
-discard """
-  output: "Hello World"
-"""
-
-# Test incremental type information
-
-type
-  TNode = object {.pure.}
-    le, ri: ref TNode
-    data: string
-
-proc newNode(data: string): ref TNode =
-  new(result)
-  result.data = data
-
-echo newNode("Hello World").data
-
diff --git a/tests/rodfiles/int2bool.nim b/tests/rodfiles/int2bool.nim
deleted file mode 100644
index bb0682844..000000000
--- a/tests/rodfiles/int2bool.nim
+++ /dev/null
@@ -1,7 +0,0 @@
-
-{.overflowchecks: on.}
-
-converter uglyToBool*(x: int): bool =
-  result = x != 0
-
-
diff --git a/tests/rodfiles/nim.cfg b/tests/rodfiles/nim.cfg
deleted file mode 100644
index 78fc8db64..000000000
--- a/tests/rodfiles/nim.cfg
+++ /dev/null
@@ -1,2 +0,0 @@
---nimcache:"$projectPath/nimcache"
---symbolFiles:on
diff --git a/tests/rodfiles/tgeneric1.nim b/tests/rodfiles/tgeneric1.nim
deleted file mode 100644
index a3f7b870b..000000000
--- a/tests/rodfiles/tgeneric1.nim
+++ /dev/null
@@ -1,13 +0,0 @@
-discard """
-  output: "abcd"
-"""
-
-import tables
-
-var x = initTable[int, string]()
-
-x[2] = "ab"
-x[5] = "cd"
-
-echo x[2], x[5]
-
diff --git a/tests/rodfiles/tgeneric2.nim b/tests/rodfiles/tgeneric2.nim
deleted file mode 100644
index 552d60267..000000000
--- a/tests/rodfiles/tgeneric2.nim
+++ /dev/null
@@ -1,13 +0,0 @@
-discard """
-  output: "abef"
-"""
-
-import tables
-
-var x = initTable[int, string]()
-
-x[2] = "ab"
-x[5] = "ef"
-
-echo x[2], x[5]
-
diff --git a/tests/sandwich/generic_library.nim b/tests/sandwich/generic_library.nim
new file mode 100644
index 000000000..43e7bd65f
--- /dev/null
+++ b/tests/sandwich/generic_library.nim
@@ -0,0 +1,6 @@
+
+proc libraryFunc*[T](x: T) =
+  mixin mixedIn, indirectlyMixedIn
+  echo mixedIn()
+  echo indirectlyMixedIn()
+
diff --git a/tests/sandwich/helper_module.nim b/tests/sandwich/helper_module.nim
new file mode 100644
index 000000000..d003bf044
--- /dev/null
+++ b/tests/sandwich/helper_module.nim
@@ -0,0 +1,3 @@
+
+proc indirectlyMixedIn*: int =
+  200
diff --git a/tests/sandwich/module_using_generic_library.nim b/tests/sandwich/module_using_generic_library.nim
new file mode 100644
index 000000000..bbb0d92a4
--- /dev/null
+++ b/tests/sandwich/module_using_generic_library.nim
@@ -0,0 +1,12 @@
+
+import
+  generic_library, helper_module
+
+proc mixedIn: int = 100
+
+proc makeUseOfLibrary*[T](x: T) =
+  bind mixedIn, indirectlyMixedIn
+  libraryFunc(x)
+
+when isMainModule:
+  makeUseOfLibrary "test"
diff --git a/tests/sandwich/tmain.nim b/tests/sandwich/tmain.nim
new file mode 100644
index 000000000..aa50bfb04
--- /dev/null
+++ b/tests/sandwich/tmain.nim
@@ -0,0 +1,9 @@
+discard """
+  output: '''100
+200'''
+"""
+
+import
+  module_using_generic_library
+
+makeUseOfLibrary "test"
diff --git a/tests/sets/m17385.nim b/tests/sets/m17385.nim
new file mode 100644
index 000000000..3919e067a
--- /dev/null
+++ b/tests/sets/m17385.nim
@@ -0,0 +1,11 @@
+import std/sets
+
+type
+  Diff*[T] = object
+    data: T
+
+proc test*[T](diff: Diff[T]) =
+  var bPopular = initHashSet[T]()
+  for element in bPopular.items():
+    echo element
+
diff --git a/tests/sets/t13764.nim b/tests/sets/t13764.nim
new file mode 100644
index 000000000..1634f113d
--- /dev/null
+++ b/tests/sets/t13764.nim
@@ -0,0 +1,6 @@
+discard """
+errormsg: "conversion from int literal(1000000) to range 0..255(int) is invalid"
+line: 6
+"""
+
+let a = {1_000_000} # Compiles
diff --git a/tests/sets/t15435.nim b/tests/sets/t15435.nim
new file mode 100644
index 000000000..5ead7e641
--- /dev/null
+++ b/tests/sets/t15435.nim
@@ -0,0 +1,29 @@
+# bug #15435
+discard """
+errormsg: "type mismatch: got <set[uint8], set[range 1..5(uint8)]>"
+nimout: '''t15435.nim(28, 13) Error: type mismatch: got <set[uint8], set[range 1..5(uint8)]>
+but expected one of:
+proc `<`[T](x, y: set[T]): bool
+  first type mismatch at position: 2
+  required type for y: set[T]
+  but expression 'x' is of type: set[range 1..5(uint8)]
+20 other mismatching symbols have been suppressed; compile with --showAllMismatches:on to see them
+
+expression: {1'u8, 5} < x'''
+"""
+
+
+
+
+
+
+## line 20
+var
+  x: set[range[1u8..5u8]]
+
+x.incl(1)
+x.incl(3)
+x.incl(5)
+
+if {1u8, 5} < x:
+  echo "successful"
diff --git a/tests/sets/t17385.nim b/tests/sets/t17385.nim
new file mode 100644
index 000000000..cc08b4882
--- /dev/null
+++ b/tests/sets/t17385.nim
@@ -0,0 +1,4 @@
+import m17385
+
+let a = Diff[int]()
+a.test()
diff --git a/tests/sets/t20997.nim b/tests/sets/t20997.nim
new file mode 100644
index 000000000..b320eee1a
--- /dev/null
+++ b/tests/sets/t20997.nim
@@ -0,0 +1,18 @@
+discard """
+  joinable: false
+"""
+
+{.passC: "-flto".}
+{.passL: "-flto".}
+
+template f(n: int) = discard card(default(set[range[0 .. (1 shl n) - 1]]))
+f( 7)
+f( 8)
+f( 9)
+f(10)
+f(11)
+f(12)
+f(13)
+f(14)
+f(15)
+f(16)
diff --git a/tests/sets/t5792.nim b/tests/sets/t5792.nim
new file mode 100644
index 000000000..297a1fc15
--- /dev/null
+++ b/tests/sets/t5792.nim
@@ -0,0 +1,17 @@
+discard """
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+type
+  T = enum
+    a
+    b
+    c
+  U = object
+    case k: T
+    of a:
+      x: int
+    of {b, c} - {a}:
+      y: int
+
+doAssert U(k: b, y: 1).y == 1
diff --git a/tests/sets/thugeset.nim b/tests/sets/thugeset.nim
new file mode 100644
index 000000000..1d82ebede
--- /dev/null
+++ b/tests/sets/thugeset.nim
@@ -0,0 +1,10 @@
+let x = 20_000
+let s = {x, 123} #[tt.Warning
+        ^ type 'int' is too big to be a `set` element, assuming a range of 0..65535, explicitly write this range to get rid of warning [AboveMaxSizeSet]]#
+doAssert x in s
+doAssert 20_000 in s
+{.push warningAsError[AboveMaxSizeSet]: on.}
+let s2 = {range[0..65535](x), 123}
+doAssert x in s
+doAssert 20_000 in s
+{.pop.}
diff --git a/tests/misc/tnewsets.nim b/tests/sets/tnewsets.nim
index f239d4aa2..f239d4aa2 100644
--- a/tests/misc/tnewsets.nim
+++ b/tests/sets/tnewsets.nim
diff --git a/tests/sets/trangeincompatible.nim b/tests/sets/trangeincompatible.nim
new file mode 100644
index 000000000..554a50235
--- /dev/null
+++ b/tests/sets/trangeincompatible.nim
@@ -0,0 +1,32 @@
+block: # issue #20142
+  let
+    s1: set['a' .. 'g'] = {'a', 'e'}
+    s2: set['a' .. 'g'] = {'b', 'c', 'd', 'f'} # this works fine
+    s3 = {'b', 'c', 'd', 'f'}
+
+  doAssert s1 != s2
+  doAssert s1 == {range['a'..'g'] 'a', 'e'}
+  doAssert s2 == {range['a'..'g'] 'b', 'c', 'd', 'f'}
+  # literal conversion:
+  doAssert s1 == {'a', 'e'}
+  doAssert s2 == {'b', 'c', 'd', 'f'}
+  doAssert s3 == {'b', 'c', 'd', 'f'}
+  doAssert not compiles(s1 == s3)
+  doAssert not compiles(s2 == s3)
+  # can't convert literal 'z', overload match fails
+  doAssert not compiles(s1 == {'a', 'z'})
+
+block: # issue #18396
+  var s1: set[char] = {'a', 'b'}
+  var s2: set['a'..'z'] = {'a', 'b'}
+  doAssert s1 == {'a', 'b'}
+  doAssert s2 == {range['a'..'z'] 'a', 'b'}
+  doAssert s2 == {'a', 'b'}
+  doAssert not compiles(s1 == s2)
+
+block: # issue #16270
+  var s1: set[char] = {'a', 'b'}
+  var s2: set['a'..'z'] = {'a', 'c'}
+  doAssert not (compiles do: s2 = s2 + s1)
+  s2 = s2 + {'a', 'b'}
+  doAssert s2 == {'a', 'b', 'c'}
diff --git a/tests/sets/tsets.nim b/tests/sets/tsets.nim
index dbbeed543..6125a3715 100644
--- a/tests/sets/tsets.nim
+++ b/tests/sets/tsets.nim
@@ -1,207 +1,65 @@
 discard """
-output: '''
-Ha ein F ist in s!
-false
-'''
+  targets: "c cpp"
 """
-# Test the handling of sets
 
-import
-  strutils
+# Test builtin sets
+
+# xxx these tests are not very good, this should be revisited.
+
+when defined nimTestsTsetsGenerate:
+  # to generate enums for this test
+  var ret: string
+  for i in 0..<276:
+    ret.add "k" & $i & ", "
+  echo ret
 
 proc testSets(s: var set[char]) =
   s = {'A', 'B', 'C', 'E'..'G'} + {'Z'} + s
 
 # test sets if the first element is different from 0:
-type
-  TAZ = range['a'..'z']
-  TAZset = set[TAZ]
-
-  TTokType* = enum
-    tkInvalid, tkEof,
-    tkSymbol,
-    tkAddr, tkAnd, tkAs, tkAsm, tkBlock, tkBreak, tkCase, tkCast, tkConst,
-    tkContinue, tkConverter, tkDiscard, tkDiv, tkElif, tkElse, tkEnd, tkEnum,
-    tkExcept, tkException, tkFinally, tkFor, tkFrom, tkGeneric, tkIf, tkImplies,
-    tkImport, tkIn, tkInclude, tkIs, tkIsnot, tkIterator, tkLambda, tkMacro,
-    tkMethod, tkMod, tkNil, tkNot, tkNotin, tkObject, tkOf, tkOr, tkOut, tkProc,
-    tkPtr, tkRaise, tkRecord, tkRef, tkReturn, tkShl, tkShr, tkTemplate, tkTry,
-    tkType, tkVar, tkWhen, tkWhere, tkWhile, tkWith, tkWithout, tkXor, tkYield,
-    tkIntLit, tkInt8Lit, tkInt16Lit, tkInt32Lit, tkInt64Lit, tkFloatLit,
-    tkFloat32Lit, tkFloat64Lit, tkStrLit, tkRStrLit, tkTripleStrLit, tkCharLit,
-    tkRCharLit, tkParLe, tkParRi, tkBracketLe, tkBracketRi, tkCurlyLe,
-    tkCurlyRi, tkBracketDotLe, tkBracketDotRi,
-    tkCurlyDotLe, tkCurlyDotRi,
-    tkParDotLe, tkParDotRi,
-    tkComma, tkSemiColon, tkColon, tkEquals, tkDot, tkDotDot, tkHat, tkOpr,
-    tkComment, tkAccent, tkInd, tkSad, tkDed,
-    tkSpaces, tkInfixOpr, tkPrefixOpr, tkPostfixOpr
-  TTokTypeRange = range[tkSymbol..tkDed]
-  TTokTypes* = set[TTokTypeRange]
-
-const
-  toktypes: TTokTypes = {TTokTypeRange(tkSymbol)..pred(tkIntLit),
-                         tkStrLit..tkTripleStrLit}
-
-var
-  s: set[char]
-  a: TAZset
-s = {'0'..'9'}
-testSets(s)
-if 'F' in s: write(stdout, "Ha ein F ist in s!\n")
-else: write(stdout, "BUG: F ist nicht in s!\n")
-a = {} #{'a'..'z'}
-for x in low(TAZ) .. high(TAZ):
-  incl(a, x)
-  if x in a: discard
-  else: write(stdout, "BUG: something not in a!\n")
-
-for x in low(TTokTypeRange) .. high(TTokTypeRange):
-  if x in tokTypes:
-    discard
-    #writeLine(stdout, "the token '$1' is in the set" % repr(x))
-
-#OUT Ha ein F ist in s!
-
-
-type
-  TMsgKind* = enum
-    errUnknown, errIllFormedAstX, errInternal, errCannotOpenFile, errGenerated,
-    errXCompilerDoesNotSupportCpp, errStringLiteralExpected,
-    errIntLiteralExpected, errInvalidCharacterConstant,
-    errClosingTripleQuoteExpected, errClosingQuoteExpected,
-    errTabulatorsAreNotAllowed, errInvalidToken, errLineTooLong,
-    errInvalidNumber, errNumberOutOfRange, errNnotAllowedInCharacter,
-    errClosingBracketExpected, errMissingFinalQuote, errIdentifierExpected,
-    errNewlineExpected,
-    errInvalidModuleName,
-    errOperatorExpected, errTokenExpected, errStringAfterIncludeExpected,
-    errRecursiveDependencyX, errOnOrOffExpected, errNoneSpeedOrSizeExpected,
-    errInvalidPragma, errUnknownPragma, errInvalidDirectiveX,
-    errAtPopWithoutPush, errEmptyAsm, errInvalidIndentation,
-    errExceptionExpected, errExceptionAlreadyHandled,
-    errYieldNotAllowedHere, errYieldNotAllowedInTryStmt,
-    errInvalidNumberOfYieldExpr, errCannotReturnExpr, errAttemptToRedefine,
-    errStmtInvalidAfterReturn, errStmtExpected, errInvalidLabel,
-    errInvalidCmdLineOption, errCmdLineArgExpected, errCmdLineNoArgExpected,
-    errInvalidVarSubstitution, errUnknownVar, errUnknownCcompiler,
-    errOnOrOffExpectedButXFound, errNoneBoehmRefcExpectedButXFound,
-    errNoneSpeedOrSizeExpectedButXFound, errGuiConsoleOrLibExpectedButXFound,
-    errUnknownOS, errUnknownCPU, errGenOutExpectedButXFound,
-    errArgsNeedRunOption, errInvalidMultipleAsgn, errColonOrEqualsExpected,
-    errExprExpected, errUndeclaredIdentifier, errUseQualifier, errTypeExpected,
-    errSystemNeeds, errExecutionOfProgramFailed, errNotOverloadable,
-    errInvalidArgForX, errStmtHasNoEffect, errXExpectsTypeOrValue,
-    errXExpectsArrayType, errIteratorCannotBeInstantiated, errExprXAmbiguous,
-    errConstantDivisionByZero, errOrdinalTypeExpected,
-    errOrdinalOrFloatTypeExpected, errOverOrUnderflow,
-    errCannotEvalXBecauseIncompletelyDefined, errChrExpectsRange0_255,
-    errDynlibRequiresExportc, errUndeclaredFieldX, errNilAccess,
-    errIndexOutOfBounds, errIndexTypesDoNotMatch, errBracketsInvalidForType,
-    errValueOutOfSetBounds, errFieldInitTwice, errFieldNotInit,
-    errExprXCannotBeCalled, errExprHasNoType, errExprXHasNoType,
-    errCastNotInSafeMode, errExprCannotBeCastedToX, errCommaOrParRiExpected,
-    errCurlyLeOrParLeExpected, errSectionExpected, errRangeExpected,
-    errMagicOnlyInSystem, errPowerOfTwoExpected,
-    errStringMayNotBeEmpty, errCallConvExpected, errProcOnlyOneCallConv,
-    errSymbolMustBeImported, errExprMustBeBool, errConstExprExpected,
-    errDuplicateCaseLabel, errRangeIsEmpty, errSelectorMustBeOfCertainTypes,
-    errSelectorMustBeOrdinal, errOrdXMustNotBeNegative, errLenXinvalid,
-    errWrongNumberOfVariables, errExprCannotBeRaised, errBreakOnlyInLoop,
-    errTypeXhasUnknownSize, errConstNeedsConstExpr, errConstNeedsValue,
-    errResultCannotBeOpenArray, errSizeTooBig, errSetTooBig,
-    errBaseTypeMustBeOrdinal, errInheritanceOnlyWithNonFinalObjects,
-    errInheritanceOnlyWithEnums, errIllegalRecursionInTypeX,
-    errCannotInstantiateX, errExprHasNoAddress, errXStackEscape,
-    errVarForOutParamNeeded,
-    errPureTypeMismatch, errTypeMismatch, errButExpected, errButExpectedX,
-    errAmbiguousCallXYZ, errWrongNumberOfArguments,
-    errXCannotBePassedToProcVar,
-    errXCannotBeInParamDecl, errPragmaOnlyInHeaderOfProc, errImplOfXNotAllowed,
-    errImplOfXexpected, errNoSymbolToBorrowFromFound, errDiscardValueX,
-    errInvalidDiscard, errIllegalConvFromXtoY, errCannotBindXTwice,
-    errInvalidOrderInArrayConstructor,
-    errInvalidOrderInEnumX, errEnumXHasHoles, errExceptExpected, errInvalidTry,
-    errOptionExpected, errXisNoLabel, errNotAllCasesCovered,
-    errUnknownSubstitionVar, errComplexStmtRequiresInd, errXisNotCallable,
-    errNoPragmasAllowedForX, errNoGenericParamsAllowedForX,
-    errInvalidParamKindX, errDefaultArgumentInvalid, errNamedParamHasToBeIdent,
-    errNoReturnTypeForX, errConvNeedsOneArg, errInvalidPragmaX,
-    errXNotAllowedHere, errInvalidControlFlowX,
-    errXisNoType, errCircumNeedsPointer, errInvalidExpression,
-    errInvalidExpressionX, errEnumHasNoValueX, errNamedExprExpected,
-    errNamedExprNotAllowed, errXExpectsOneTypeParam,
-    errArrayExpectsTwoTypeParams, errInvalidVisibilityX, errInitHereNotAllowed,
-    errXCannotBeAssignedTo, errIteratorNotAllowed, errXNeedsReturnType,
-    errNoReturnTypeDeclared,
-    errInvalidCommandX, errXOnlyAtModuleScope,
-    errXNeedsParamObjectType,
-    errTemplateInstantiationTooNested, errInstantiationFrom,
-    errInvalidIndexValueForTuple, errCommandExpectsFilename,
-    errMainModuleMustBeSpecified,
-    errXExpected,
-    errTIsNotAConcreteType,
-    errInvalidSectionStart, errGridTableNotImplemented, errGeneralParseError,
-    errNewSectionExpected, errWhitespaceExpected, errXisNoValidIndexFile,
-    errCannotRenderX, errVarVarTypeNotAllowed, errInstantiateXExplicitly,
-    errOnlyACallOpCanBeDelegator, errUsingNoSymbol,
-    errMacroBodyDependsOnGenericTypes,
-    errDestructorNotGenericEnough,
-    errInlineIteratorsAsProcParams,
-    errXExpectsTwoArguments,
-    errXExpectsObjectTypes, errXcanNeverBeOfThisSubtype, errTooManyIterations,
-    errCannotInterpretNodeX, errFieldXNotFound, errInvalidConversionFromTypeX,
-    errAssertionFailed, errCannotGenerateCodeForX, errXRequiresOneArgument,
-    errUnhandledExceptionX, errCyclicTree, errXisNoMacroOrTemplate,
-    errXhasSideEffects, errIteratorExpected, errLetNeedsInit,
-    errThreadvarCannotInit, errWrongSymbolX, errIllegalCaptureX,
-    errXCannotBeClosure, errXMustBeCompileTime,
-    errCannotInferTypeOfTheLiteral,
-    errCannotInferReturnType,
-    errGenericLambdaNotAllowed,
-    errCompilerDoesntSupportTarget,
-    errUser,
-    warnCannotOpenFile,
-    warnOctalEscape, warnXIsNeverRead, warnXmightNotBeenInit,
-    warnDeprecated, warnConfigDeprecated,
-    warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel,
-    warnUnknownSubstitutionX, warnLanguageXNotSupported,
-    warnFieldXNotSupported, warnCommentXIgnored,
-    warnNilStatement, warnTypelessParam,
-    warnDifferentHeaps, warnWriteToForeignHeap, warnUnsafeCode,
-    warnEachIdentIsTuple,
-    warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2,
-    warnUninit, warnGcMem, warnDestructor, warnLockLevel, warnResultShadowed,
-    warnUser,
-    hintSuccess, hintSuccessX,
-    hintLineTooLong, hintXDeclaredButNotUsed, hintConvToBaseNotNeeded,
-    hintConvFromXtoItselfNotNeeded, hintExprAlwaysX, hintQuitCalled,
-    hintProcessing, hintCodeBegin, hintCodeEnd, hintConf, hintPath,
-    hintConditionAlwaysTrue, hintName, hintPattern,
-    hintUser
-
-const
-  fatalMin* = errUnknown
-  fatalMax* = errInternal
-  errMin* = errUnknown
-  errMax* = errUser
-  warnMin* = warnCannotOpenFile
-  warnMax* = pred(hintSuccess)
-  hintMin* = hintSuccess
-  hintMax* = high(TMsgKind)
+block:
+  type
+    TAZ = range['a'..'z']
+    TAZset = set[TAZ]
+    FakeTokType = enum
+      k0, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49, k50, k51, k52, k53, k54, k55, k56, k57, k58, k59, k60, k61, k62, k63, k64, k65, k66, k67, k68, k69, k70, k71, k72, k73, k74, k75, k76, k77, k78, k79, k80, k81, k82, k83, k84, k85, k86, k87, k88, k89, k90, k91, k92, k93, k94, k95, k96, k97, k98, k99, k100, k101, k102, k103, k104, k105, k106, k107, k108, k109, k110, k111, k112, k113, k114, k115, k116, k117, k118, k119, k120, k121, k122, k123, k124, k125, k126, k127, k128, k129, k130, k131, k132, k133, k134, k135, k136, k137, k138, k139, k140, k141, k142, k143, k144, k145, k146, k147, k148, k149, k150, k151, k152, k153, k154, k155, k156, k157, k158, k159, k160, k161, k162, k163, k164, k165, k166, k167, k168, k169, k170, k171, k172, k173, k174, k175, k176, k177, k178, k179, k180, k181, k182, k183, k184, k185, k186, k187, k188, k189, k190, k191, k192, k193, k194, k195, k196, k197, k198, k199, k200, k201, k202, k203, k204, k205, k206, k207, k208, k209, k210, k211, k212, k213, k214, k215, k216, k217, k218, k219, k220, k221, k222, k223, k224, k225, k226, k227, k228, k229, k230, k231, k232, k233, k234, k235, k236, k237, k238, k239, k240, k241, k242, k243, k244, k245, k246, k247, k248, k249
+    FakeTokTypeRange = range[k2..k101]
+    FakeTokTypes = set[FakeTokTypeRange]
+    Foo = object
+      field: set[Bar] #Bug: 6259
+    Bar = enum
+      bar1, bar2, bar3
+
+  const toktypes: FakeTokTypes = {FakeTokTypeRange(k2)..pred(k64), k72..k74}
+
+  var
+    s: set[char]
+    a: TAZset
+  s = {'0'..'9'}
+  testSets(s)
+  doAssert 'F' in s
+  a = {} #{'a'..'z'}
+  for x in low(TAZ) .. high(TAZ):
+    incl(a, x)
+    doAssert x in a
+
+  for x in low(FakeTokTypeRange) .. high(FakeTokTypeRange):
+    if x in tokTypes:
+      discard
 
 type
-  TNoteKind* = range[warnMin..hintMax] # "notes" are warnings or hints
-  TNoteKinds* = set[TNoteKind]
+  FakeMsgKind* = enum
+    k0, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49, k50, k51, k52, k53, k54, k55, k56, k57, k58, k59, k60, k61, k62, k63, k64, k65, k66, k67, k68, k69, k70, k71, k72, k73, k74, k75, k76, k77, k78, k79, k80, k81, k82, k83, k84, k85, k86, k87, k88, k89, k90, k91, k92, k93, k94, k95, k96, k97, k98, k99, k100, k101, k102, k103, k104, k105, k106, k107, k108, k109, k110, k111, k112, k113, k114, k115, k116, k117, k118, k119, k120, k121, k122, k123, k124, k125, k126, k127, k128, k129, k130, k131, k132, k133, k134, k135, k136, k137, k138, k139, k140, k141, k142, k143, k144, k145, k146, k147, k148, k149, k150, k151, k152, k153, k154, k155, k156, k157, k158, k159, k160, k161, k162, k163, k164, k165, k166, k167, k168, k169, k170, k171, k172, k173, k174, k175, k176, k177, k178, k179, k180, k181, k182, k183, k184, k185, k186, k187, k188, k189, k190, k191, k192, k193, k194, k195, k196, k197, k198, k199, k200, k201, k202, k203, k204, k205, k206, k207, k208, k209, k210, k211, k212, k213, k214, k215, k216, k217, k218, k219, k220, k221, k222, k223, k224, k225, k226, k227, k228, k229, k230, k231, k232, k233, k234, k235, k236, k237, k238, k239, k240, k241, k242, k243, k244, k245, k246, k247, k248, k249, k250, k251, k252, k253, k254, k255, k256, k257, k258, k259, k260, k261, k262, k263, k264, k265, k266, k267, k268, k269, k270, k271, k272, k273, k274, k275,
 
-var
-  gNotes*: TNoteKinds = {low(TNoteKind)..high(TNoteKind)} -
-                        {warnUninit, warnProveField, warnProveIndex, warnGcUnsafe}
+doAssert pred(k260) == k259
 
+type
+  FakeMsgKind2 = range[k230..high(FakeMsgKind)]
+  FakeMsgKind3 = set[FakeMsgKind2]
 
-#import compiler.msgs
+var gNotes: FakeMsgKind3 = {low(FakeMsgKind2)..high(FakeMsgKind2)} - {k233, k235}
 
-echo warnUninit in gNotes
+doAssert k233 notin gNotes
 
 # 7555
 doAssert {-1.int8, -2, -2}.card == 2
@@ -218,3 +76,58 @@ type Foo = enum
 
 let x = { Foo1, Foo2 }
 # bug #8425
+
+block:
+  # bug #2880
+  type
+    FakeMsgKind = enum
+      k0, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49, k50, k51, k52, k53, k54, k55, k56, k57, k58, k59, k60, k61, k62, k63, k64, k65, k66, k67, k68, k69, k70, k71, k72, k73, k74, k75, k76, k77, k78, k79, k80, k81, k82, k83, k84, k85, k86, k87, k88, k89, k90, k91, k92, k93, k94, k95, k96, k97, k98, k99, k100
+
+  type
+    FakeMsgKind2 = range[FakeMsgKind.k50..high(FakeMsgKind)]
+    FakeMsgKind2s = set[FakeMsgKind2]
+
+  const
+    a1: array[0..0, FakeMsgKind2s] = [{low(FakeMsgKind2)..high(FakeMsgKind2)} - {FakeMsgKind.k99}]
+    a2 = a1[0]
+
+  var
+    s1: FakeMsgKind2s = a1[0]
+    s2: FakeMsgKind2s = a2
+
+  doAssert k99 notin s1
+  doAssert k99 notin s2
+
+block: # bug #23422
+  block:
+    var a: set[uint8] = {1'u8}
+
+    proc printLen(x: set[uint8]): int =
+      doAssert x.len == card(x)
+      result = card(x)
+
+    proc printLenVar(x: var set[uint8]): int =
+      doAssert x.len == card(x)
+      result = card(x)
+
+    doAssert a.len == 1
+    doAssert printLen(a) == 1
+    doAssert printLenVar(a) == card(a)
+
+  block:
+    type Fruit = enum
+      Apple, Banana, Melon
+
+    var a: set[Fruit] = {Apple}
+
+    proc printLen(x: set[Fruit]): int =
+      doAssert x.len == card(x)
+      result = card(x)
+
+    proc printLenVar(x: var set[Fruit]): int =
+      doAssert x.len == card(x)
+      result = card(x)
+
+    doAssert a.len == 1
+    doAssert printLen(a) == 1
+    doAssert printLenVar(a) == card(a)
diff --git a/tests/sets/tsets_various.nim b/tests/sets/tsets_various.nim
index 8a63763b4..419bcfdcc 100644
--- a/tests/sets/tsets_various.nim
+++ b/tests/sets/tsets_various.nim
@@ -1,15 +1,18 @@
 discard """
-  output: '''
-set is empty
-'''
+  targets: "c cpp js"
 """
 
+import std/[sets, hashes]
 
-import sets, hashes
+from std/sequtils import toSeq
+from std/algorithm import sorted
+from stdtest/testutils import whenVMorJs
 
+proc sortedPairs[T](t: T): auto = toSeq(t.pairs).sorted
+template sortedItems(t: untyped): untyped = sorted(toSeq(t))
 
 block tsetpop:
-  var a = initSet[int]()
+  var a = initHashSet[int]()
   for i in 1..1000:
     a.incl(i)
   doAssert len(a) == 1000
@@ -17,10 +20,12 @@ block tsetpop:
     discard a.pop()
   doAssert len(a) == 0
 
+  var msg = ""
   try:
     echo a.pop()
   except KeyError as e:
-    echo e.msg
+    msg = e.msg
+  doAssert msg == "set is empty"
 
 
 
@@ -50,20 +55,20 @@ block tsets2:
       "80"]
 
   block tableTest1:
-    var t = initSet[tuple[x, y: int]]()
+    var t = initHashSet[tuple[x, y: int]]()
     t.incl((0,0))
     t.incl((1,0))
-    assert(not t.containsOrIncl((0,1)))
+    doAssert(not t.containsOrIncl((0,1)))
     t.incl((1,1))
 
     for x in 0..1:
       for y in 0..1:
-        assert((x,y) in t)
-    #assert($t ==
+        doAssert((x,y) in t)
+    #doAssert($t ==
     #  "{(x: 0, y: 0), (x: 0, y: 1), (x: 1, y: 0), (x: 1, y: 1)}")
 
   block setTest2:
-    var t = initSet[string]()
+    var t = initHashSet[string]()
     t.incl("test")
     t.incl("111")
     t.incl("123")
@@ -71,40 +76,40 @@ block tsets2:
     t.incl("012")
     t.incl("123") # test duplicates
 
-    assert "123" in t
-    assert "111" notin t # deleted
+    doAssert "123" in t
+    doAssert "111" notin t # deleted
 
-    assert t.missingOrExcl("000")
-    assert "000" notin t
-    assert t.missingOrExcl("012") == false
-    assert "012" notin t
+    doAssert t.missingOrExcl("000")
+    doAssert "000" notin t
+    doAssert t.missingOrExcl("012") == false
+    doAssert "012" notin t
 
-    assert t.containsOrIncl("012") == false
-    assert t.containsOrIncl("012")
-    assert "012" in t # added back
+    doAssert t.containsOrIncl("012") == false
+    doAssert t.containsOrIncl("012")
+    doAssert "012" in t # added back
 
     for key in items(data): t.incl(key)
-    for key in items(data): assert key in t
+    for key in items(data): doAssert key in t
 
     for key in items(data): t.excl(key)
-    for key in items(data): assert key notin t
+    for key in items(data): doAssert key notin t
 
   block orderedSetTest1:
     var t = data.toOrderedSet
-    for key in items(data): assert key in t
+    for key in items(data): doAssert key in t
     var i = 0
     # `items` needs to yield in insertion order:
     for key in items(t):
-      assert key == data[i]
+      doAssert key == data[i]
       inc(i)
 
 
 
 block tsets3:
   let
-    s1: HashSet[int] = toSet([1, 2, 4, 8, 16])
-    s2: HashSet[int] = toSet([1, 2, 3, 5, 8])
-    s3: HashSet[int] = toSet([3, 5, 7])
+    s1: HashSet[int] = toHashSet([1, 2, 4, 8, 16])
+    s2: HashSet[int] = toHashSet([1, 2, 3, 5, 8])
+    s3: HashSet[int] = toHashSet([3, 5, 7])
 
   block union:
     let
@@ -112,22 +117,22 @@ block tsets3:
       s1_s3 = s1 + s3
       s2_s3 = s2 + s3
 
-    assert s1_s2.len == 7
-    assert s1_s3.len == 8
-    assert s2_s3.len == 6
+    doAssert s1_s2.len == 7
+    doAssert s1_s3.len == 8
+    doAssert s2_s3.len == 6
 
     for i in s1:
-      assert i in s1_s2
-      assert i in s1_s3
+      doAssert i in s1_s2
+      doAssert i in s1_s3
     for i in s2:
-      assert i in s1_s2
-      assert i in s2_s3
+      doAssert i in s1_s2
+      doAssert i in s2_s3
     for i in s3:
-      assert i in s1_s3
-      assert i in s2_s3
+      doAssert i in s1_s3
+      doAssert i in s2_s3
 
-    assert((s1 + s1) == s1)
-    assert((s2 + s1) == s1_s2)
+    doAssert((s1 + s1) == s1)
+    doAssert((s2 + s1) == s1_s2)
 
   block intersection:
     let
@@ -135,22 +140,22 @@ block tsets3:
       s1_s3 = intersection(s1, s3)
       s2_s3 = s2 * s3
 
-    assert s1_s2.len == 3
-    assert s1_s3.len == 0
-    assert s2_s3.len == 2
+    doAssert s1_s2.len == 3
+    doAssert s1_s3.len == 0
+    doAssert s2_s3.len == 2
 
     for i in s1_s2:
-      assert i in s1
-      assert i in s2
+      doAssert i in s1
+      doAssert i in s2
     for i in s1_s3:
-      assert i in s1
-      assert i in s3
+      doAssert i in s1
+      doAssert i in s3
     for i in s2_s3:
-      assert i in s2
-      assert i in s3
+      doAssert i in s2
+      doAssert i in s3
 
-    assert((s2 * s2) == s2)
-    assert((s3 * s2) == s2_s3)
+    doAssert((s2 * s2) == s2)
+    doAssert((s3 * s2) == s2_s3)
 
   block symmetricDifference:
     let
@@ -158,22 +163,22 @@ block tsets3:
       s1_s3 = s1 -+- s3
       s2_s3 = s2 -+- s3
 
-    assert s1_s2.len == 4
-    assert s1_s3.len == 8
-    assert s2_s3.len == 4
+    doAssert s1_s2.len == 4
+    doAssert s1_s3.len == 8
+    doAssert s2_s3.len == 4
 
     for i in s1:
-      assert i in s1_s2 xor i in s2
-      assert i in s1_s3 xor i in s3
+      doAssert i in s1_s2 xor i in s2
+      doAssert i in s1_s3 xor i in s3
     for i in s2:
-      assert i in s1_s2 xor i in s1
-      assert i in s2_s3 xor i in s3
+      doAssert i in s1_s2 xor i in s1
+      doAssert i in s2_s3 xor i in s3
     for i in s3:
-      assert i in s1_s3 xor i in s1
-      assert i in s2_s3 xor i in s2
+      doAssert i in s1_s3 xor i in s1
+      doAssert i in s2_s3 xor i in s2
 
-    assert((s3 -+- s3) == initSet[int]())
-    assert((s3 -+- s1) == s1_s3)
+    doAssert((s3 -+- s3) == initHashSet[int]())
+    doAssert((s3 -+- s1) == s1_s3)
 
   block difference:
     let
@@ -181,20 +186,101 @@ block tsets3:
       s1_s3 = difference(s1, s3)
       s2_s3 = s2 - s3
 
-    assert s1_s2.len == 2
-    assert s1_s3.len == 5
-    assert s2_s3.len == 3
+    doAssert s1_s2.len == 2
+    doAssert s1_s3.len == 5
+    doAssert s2_s3.len == 3
 
     for i in s1:
-      assert i in s1_s2 xor i in s2
-      assert i in s1_s3 xor i in s3
+      doAssert i in s1_s2 xor i in s2
+      doAssert i in s1_s3 xor i in s3
     for i in s2:
-      assert i in s2_s3 xor i in s3
+      doAssert i in s2_s3 xor i in s3
 
-    assert((s2 - s2) == initSet[int]())
+    doAssert((s2 - s2) == initHashSet[int]())
 
   block disjoint:
-    assert(not disjoint(s1, s2))
-    assert disjoint(s1, s3)
-    assert(not disjoint(s2, s3))
-    assert(not disjoint(s2, s2))
+    doAssert(not disjoint(s1, s2))
+    doAssert disjoint(s1, s3)
+    doAssert(not disjoint(s2, s3))
+    doAssert(not disjoint(s2, s2))
+
+block: # https://github.com/nim-lang/Nim/issues/13496
+  template testDel(body) =
+    block:
+      body
+      t.incl(15)
+      t.incl(19)
+      t.incl(17)
+      t.incl(150)
+      t.excl(150)
+      doAssert t.len == 3
+      doAssert sortedItems(t) == @[15, 17, 19]
+      var s = newSeq[int]()
+      for v in t: s.add(v)
+      doAssert s.len == 3
+      doAssert sortedItems(s) == @[15, 17, 19]
+      when t is OrderedSet:
+        doAssert sortedPairs(t) == @[(a: 0, b: 15), (a: 1, b: 19), (a: 2, b: 17)]
+        doAssert toSeq(t) == @[15, 19, 17]
+
+  testDel(): (var t: HashSet[int])
+  testDel(): (var t: OrderedSet[int])
+
+block: # test correctness after a number of inserts/deletes
+  template testDel(body) =
+    block:
+      body
+      var expected: seq[int]
+      let n = 100
+      let n2 = n*2
+      for i in 0..<n:
+        t.incl(i)
+      for i in 0..<n:
+        if i mod 3 == 0:
+          t.excl(i)
+      for i in n..<n2:
+        t.incl(i)
+      for i in 0..<n2:
+        if i mod 7 == 0:
+          t.excl(i)
+
+      for i in 0..<n2:
+        if (i>=n or i mod 3 != 0) and i mod 7 != 0:
+          expected.add i
+
+      for i in expected: doAssert i in t
+      doAssert t.len == expected.len
+      doAssert sortedItems(t) == expected
+
+  testDel(): (var t: HashSet[int])
+  testDel(): (var t: OrderedSet[int])
+
+
+template main() =
+  # xxx move all tests inside this
+  block:
+    let a = {true, false}
+    doAssert $a == "{false, true}"
+    doAssert a.len == 2
+
+  block:
+    let a = {false .. true}
+    doAssert $a == "{false, true}"
+    doAssert a.len == 2
+
+  block:
+    let a = {false .. false}
+    doAssert $a == "{false}"
+    doAssert a.len == 1
+
+  block: # bug #16123
+    whenVMorJs: discard
+    do:
+      type CallType = proc() {.closure.}
+      var setA = initHashSet[CallType]()
+      let foo = proc() = discard
+      setA.incl(foo)
+      doAssert setA.contains(foo)
+
+static: main()
+main()
diff --git a/tests/sets/twrongenumrange.nim b/tests/sets/twrongenumrange.nim
new file mode 100644
index 000000000..a8d64ac44
--- /dev/null
+++ b/tests/sets/twrongenumrange.nim
@@ -0,0 +1,50 @@
+discard """
+  cmd: "nim check --hints:off $file"
+"""
+
+# issue #17848
+
+block:
+  # generate with:
+  # var a = ""
+  # for i in 0..<80: a.add "k" & $i & ", "
+  # echo a
+  type
+    TMsgKind = enum
+      k0, k1, k2, k3, k4, k5, k6, k7, k8, k9, k10, k11, k12, k13, k14, k15, k16, k17, k18, k19, k20, k21, k22, k23, k24, k25, k26, k27, k28, k29, k30, k31, k32, k33, k34, k35, k36, k37, k38, k39, k40, k41, k42, k43, k44, k45, k46, k47, k48, k49, k50, k51, k52, k53, k54, k55, k56, k57, k58, k59, k60, k61, k62, k63, k64, k65, k66, k67, k68, k69, k70, k71, k72, k73, k74, k75, k76, k77, k78, k79
+  type
+    TNoteKind = range[k10..k79]
+    Conf = ref object
+      notes: set[TNoteKind]
+  proc bad(conf: Conf, noteSet: set[TMsgKind]) =
+    conf.notes = noteSet #[tt.Error
+                 ^ type mismatch: got <set[TMsgKind]> but expected 'set[TNoteKind]']#
+  var conf = Conf()
+  bad(conf, {k10..k60})
+
+block:
+  type
+    TMsgKind = enum k0, k1, k2, k3
+    TNoteKind = range[k1..k2]
+    TNoteKinds = set[TNoteKind]
+  type Conf = ref object
+    notes: TNoteKinds
+  proc fn(conf: Conf, b: set[TMsgKind]) =
+    conf.notes = b #[tt.Error
+                 ^ type mismatch: got <set[TMsgKind]> but expected 'TNoteKinds = set[TNoteKind]']#
+  var conf = Conf()
+  conf.fn({k0..k3}) # BUG: this should give error
+  echo conf.notes # {k1, k2}
+
+block:
+  #[
+  compiler/bitsets.nim(43, 9) `elem >= 0`  [AssertionDefect]
+  ]#
+  type
+    TMsgKind = enum k0, k1, k2, k3
+    TNoteKind = range[k1..k2]
+  var notes: set[TNoteKind]
+  notes = {k0} #[tt.Error
+          ^ type mismatch: got <set[TMsgKind]> but expected 'set[TNoteKind]']#
+  notes = {k0..k3} #[tt.Error
+          ^ type mismatch: got <set[TMsgKind]> but expected 'set[TNoteKind]']#
diff --git a/tests/showoff/tdrdobbs_examples.nim b/tests/showoff/tdrdobbs_examples.nim
index 0e10c6dd8..c61e177dc 100644
--- a/tests/showoff/tdrdobbs_examples.nim
+++ b/tests/showoff/tdrdobbs_examples.nim
@@ -40,12 +40,12 @@ const msb3999 = mostSignificantBit(3999)
 
 echo msb3999, " ", mostSignificantBit(0), " ", square(44)
 
-proc filter[T](a: openarray[T], predicate: proc (x: T): bool): seq[T] =
+proc filter[T](a: openArray[T], predicate: proc (x: T): bool): seq[T] =
   result = @[] # @[] constructs the empty seq
   for x in a:
     if predicate(x): result.add(x)
 
-proc map[T, S](a: openarray[T], fn: proc (x: T): S): seq[S] =
+proc map[T, S](a: openArray[T], fn: proc (x: T): S): seq[S] =
   newSeq(result, a.len)
   for i in 0 ..< a.len: result[i] = fn(a[i])
 
diff --git a/tests/showoff/tformatopt.nim b/tests/showoff/tformatopt.nim
index 6e790c38e..420dd026b 100644
--- a/tests/showoff/tformatopt.nim
+++ b/tests/showoff/tformatopt.nim
@@ -37,7 +37,7 @@ macro optFormat{`%`(f, a)}(f: string{lit}, a: openArray[string]): untyped =
   result = newNimNode(nnkBracket)
   let f = f.strVal
   formatImpl(newLit)
-  result = nestList(!"&", result)
+  result = nestList(newIdentNode("&"), result)
 
 template optAdd1{x = y; add(x, z)}(x, y, z: string) =
   x = y & z
diff --git a/tests/showoff/tgenericmacrotypes.nim b/tests/showoff/tgenericmacrotypes.nim
new file mode 100644
index 000000000..cc07f4355
--- /dev/null
+++ b/tests/showoff/tgenericmacrotypes.nim
@@ -0,0 +1,55 @@
+# issue #7974
+
+import macros
+
+macro genTypeA(arg: typed): untyped =
+  if arg.typeKind != ntyTypeDesc:
+    error("expected typedesc", arg)
+
+  result = arg.getTypeInst[1]
+
+macro genTypeB(arg: typed): untyped =
+  if arg.typeKind != ntyTypeDesc:
+    error("expected typedesc", arg)
+
+
+  let typeSym = arg.getTypeInst[1]
+  result =
+    nnkTupleTy.newTree(
+      nnkIdentDefs.newTree(
+        ident"a", typeSym, newEmptyNode()
+      )
+    )
+
+type
+  # this is the trivial case, MyTypeA[T] is basically just T, nothing else. But it works.
+  MyTypeA[T] = genTypeA(T)
+  # in this case I generate `tuple[a: T]`. This this is something the compiler does not want
+  MyTypeB[T] = genTypeB(T)
+
+# these are just alias types for int32 and float32, nothing really happens, but it works
+var a1: MyTypeA[int32]
+doAssert a1 is MyTypeA[int32]
+doAssert a1 is int32
+a1 = 0'i32
+var a2: MyTypeA[float32]
+doAssert a2 is MyTypeA[float32]
+doAssert a2 is float32
+a2 = 0'f32
+var a3: MyTypeA[float32]
+doAssert a3 is MyTypeA[float32]
+doAssert a3 is float32
+a3 = 0'f32
+
+var b1: MyTypeB[int32]   # cannot generate VM code fur tuple[a: int32]
+doAssert b1 is MyTypeB[int32]
+doAssert b1 is tuple[a: int32]
+b1 = (a: 0'i32)
+var b2: MyTypeB[float32]
+doAssert b2 is MyTypeB[float32]
+doAssert b2 is tuple[a: float32]
+b2 = (a: 0'f32)
+var b3: MyTypeB[float32]
+doAssert b3 is MyTypeB[float32]
+doAssert b3 is tuple[a: float32]
+b3 = (a: 0'f32)
diff --git a/tests/specialops/tcallops.nim b/tests/specialops/tcallops.nim
new file mode 100644
index 000000000..c541a0c1d
--- /dev/null
+++ b/tests/specialops/tcallops.nim
@@ -0,0 +1,49 @@
+import macros
+
+{.experimental: "callOperator".}
+
+type Foo[T: proc] = object
+  callback: T
+
+macro `()`(foo: Foo, args: varargs[untyped]): untyped =
+  result = newCall(newDotExpr(foo, ident"callback"))
+  for a in args:
+    result.add(a)
+
+var f1Calls = 0
+var f = Foo[proc()](callback: proc() = inc f1Calls)
+doAssert f1Calls == 0
+f()
+doAssert f1Calls == 1
+var f2Calls = 0
+f.callback = proc() = inc f2Calls
+doAssert f2Calls == 0
+f()
+doAssert f2Calls == 1
+
+let g = Foo[proc (x: int): int](callback: proc (x: int): int = x * 2 + 1)
+doAssert g(15) == 31
+
+proc `()`(args: varargs[string]): string =
+  result = "("
+  for a in args: result.add(a)
+  result.add(')')
+
+let a = "1"
+let b = "2"
+let c = "3"
+
+doAssert a(b) == "(12)"
+doAssert a.b(c) == `()`(b, a, c)
+doAssert (a.b)(c) == `()`(a.b, c)
+doAssert `()`(a.b, c) == `()`(`()`(b, a), c)
+
+block: # bug #1072
+  var x: int
+
+  proc foo(some:int):int = some
+  proc `()`(l,r:string): string = discard
+
+  block:
+    var foo = 42
+    doAssert x.foo == 0
diff --git a/tests/specialops/tcallprecedence.nim b/tests/specialops/tcallprecedence.nim
new file mode 100644
index 000000000..6116f83d5
--- /dev/null
+++ b/tests/specialops/tcallprecedence.nim
@@ -0,0 +1,44 @@
+import macros
+
+{.experimental: "dotOperators".}
+{.experimental: "callOperator".}
+
+block:
+  template `.()`(foo: int, args: varargs[untyped]): untyped {.used.} =
+    ".()"
+
+  template `()`(foo: int, args: varargs[untyped]): untyped =
+    "()"
+
+  let a = (b: 1)
+  let c = 3
+
+  doAssert a.b(c) == "()"
+  doAssert not compiles(a(c))
+  doAssert (a.b)(c) == "()"
+
+macro `()`(args: varargs[typed]): untyped =
+  result = newLit("() " & args.treeRepr)
+
+macro `.`(args: varargs[typed]): untyped =
+  result = newLit(". " & args.treeRepr)
+
+block:
+  let a = 1
+  let b = 2
+  doAssert a.b == `()`(b, a)
+
+block:
+  let a = 1
+  proc b(): int {.used.} = 2
+  doAssert a.b == `.`(a, b)
+
+block:
+  let a = 1
+  proc b(x: int): int = x + 1
+  let c = 3
+
+  doAssert a.b(c) == `.`(a, b, c)
+  doAssert a(b) == `()`(a, b)
+  doAssert (a.b)(c) == `()`(a.b, c)
+  doAssert a.b == b(a)
diff --git a/tests/specialops/tdotops.nim b/tests/specialops/tdotops.nim
index 227204f51..ca5eee665 100644
--- a/tests/specialops/tdotops.nim
+++ b/tests/specialops/tdotops.nim
@@ -1,5 +1,6 @@
 discard """
   output: '''
+
 10
 assigning z = 20
 reading field y
@@ -12,9 +13,18 @@ no params call to b
 100
 one param call to c with 10
 100
-0 4'''
+0 4
+'''
 """
 
+block:
+  type Foo = object
+  var a: Foo
+  template `.`(a: Foo, b: untyped): untyped = astToStr(b)
+  template callme(a, f): untyped = a.f
+  doAssert callme(a, f2) == "f2" # not `f`
+  doAssert a.callme(f3) == "f3"
+
 type
   T1 = object
     x*: int
diff --git a/tests/specialops/terrmsgs.nim b/tests/specialops/terrmsgs.nim
new file mode 100644
index 000000000..081bca451
--- /dev/null
+++ b/tests/specialops/terrmsgs.nim
@@ -0,0 +1,76 @@
+discard """
+action: reject
+cmd: '''nim check $options $file'''
+matrix: "; -d:testWithout; --mm:refc"
+"""
+
+when not defined(testWithout): # test for same errors before and after
+  {.experimental: "dotOperators".}
+  {.experimental: "callOperator".}
+
+# issue #13063
+
+block:
+  type Foo = object
+  type Bar = object
+    x1: int
+  var b: Bar
+  block:
+    template `.`(a: Foo, b: untyped): untyped = 123
+    echo b.x #[tt.Error
+          ^ undeclared field: 'x' for type terrmsgs.Bar [type declared in terrmsgs.nim(15, 8)]]#
+  block:
+    template `.()`(a: Foo, b: untyped): untyped = 123
+    echo b.x() #[tt.Error
+          ^ attempting to call undeclared routine: 'x']#
+  block:
+    template `.=`(a: Foo, b: untyped, c: untyped) = b = c
+    b.x = 123 #[tt.Error
+        ^ undeclared field: 'x=' for type terrmsgs.Bar [type declared in terrmsgs.nim(15, 8)]]#
+    # yeah it says x= but does it matter in practice
+  block:
+    template `()`(a: Foo, b: untyped, c: untyped) = echo "something"
+
+    # completely undeclared::
+    xyz(123) #[tt.Error
+    ^ undeclared identifier: 'xyz']#
+
+    # already declared routine:
+    min(123) #[tt.Error
+       ^ type mismatch: got <int literal(123)>]#
+
+    # non-routine type shows `()` overloads:
+    b(123) #[tt.Error
+     ^ attempting to call routine: 'b']#
+
+    echo b.x #[tt.Error
+          ^ undeclared field: 'x' for type terrmsgs.Bar [type declared in terrmsgs.nim(15, 8)]]#
+    echo b.x() #[tt.Error
+          ^ attempting to call undeclared routine: 'x']#
+
+# issue #7777
+
+import macros
+
+block:
+  type TestType = object
+    private_field: string
+
+  when false:
+    template getField(obj, field: untyped): untyped = obj.field
+
+  macro `.`(obj: TestType, field: untyped): untyped =
+    let private = newIdentNode("private_" & $field)
+    result = quote do:
+      `obj`.getField(`private`) #[tt.Error
+           ^ attempting to call undeclared routine: 'getField']#
+
+  var tt: TestType
+  discard tt.field
+
+block: # related to issue #6981
+  proc `()`(a:string, b:string):string = a & b
+  proc mewSeq[T](a,b:int)=discard
+  proc mewSeq[T](c:int)= discard
+  mewSeq[int]() #[tt.Error
+             ^ type mismatch: got <>]#
diff --git a/tests/specialops/tnewseq.nim b/tests/specialops/tnewseq.nim
new file mode 100644
index 000000000..970a5a8c2
--- /dev/null
+++ b/tests/specialops/tnewseq.nim
@@ -0,0 +1,22 @@
+# issue #6981
+
+import std/assertions
+
+{.experimental: "callOperator".}
+
+block: # issue #6981
+  proc `()`(a:string, b:string):string = a & b
+
+  var s = newSeq[int](3)
+
+  doAssert s == @[0, 0, 0]
+
+block: # generalized example from #6981
+  proc mewSeq[T](a: int)=discard
+  proc mewSeq[T]()= discard
+  mewSeq[int]()
+
+block: # issue #9831
+  type Foo = object
+  proc `()`(foo: Foo) = discard
+  let x = newSeq[int]()
diff --git a/tests/specialops/tsetter.nim b/tests/specialops/tsetter.nim
new file mode 100644
index 000000000..6175cbec4
--- /dev/null
+++ b/tests/specialops/tsetter.nim
@@ -0,0 +1,10 @@
+block: # ensure RHS of setter statement is treated as call operand
+  proc `b=`(a: var int, c: proc (x: int): int) =
+    a = c(a)
+
+  proc foo(x: int): int = x + 1
+  proc foo(x: float): float = x - 1
+
+  var a = 123
+  a.b = foo
+  doAssert a == 124
diff --git a/tests/statictypes/t20148.nim b/tests/statictypes/t20148.nim
new file mode 100644
index 000000000..d74a7755e
--- /dev/null
+++ b/tests/statictypes/t20148.nim
@@ -0,0 +1,8 @@
+type Percent = range[0.0 .. 1.0]
+# type Percent = float # using unlimited `float` works fine
+
+proc initColor*(alpha: Percent): bool =
+  echo alpha
+
+const moduleInstanceStyle = initColor(1)
+# let moduleInstanceStyle = initColor(1) # using runtime conversion works fine
diff --git a/tests/statictypes/t5780.nim b/tests/statictypes/t5780.nim
new file mode 100644
index 000000000..85548aaad
--- /dev/null
+++ b/tests/statictypes/t5780.nim
@@ -0,0 +1,3 @@
+type StringArray[N:int] = array[N, string]
+let a = ["one", "two"]
+doAssert a is StringArray
diff --git a/tests/statictypes/t9255.nim b/tests/statictypes/t9255.nim
index 86bc8c7f1..aec2fbaf5 100644
--- a/tests/statictypes/t9255.nim
+++ b/tests/statictypes/t9255.nim
@@ -1,6 +1,6 @@
 discard """
   errormsg: '''
-type mismatch: got <static[proc (a0: int): string{.noSideEffect, gcsafe, locks: 0.}](bar)>
+type mismatch: got <proc (a0: int): string{.noSideEffect, gcsafe.}>
 '''
   line: 13
 """
diff --git a/tests/statictypes/tgenericcomputedrange.nim b/tests/statictypes/tgenericcomputedrange.nim
new file mode 100644
index 000000000..9e3a49ae0
--- /dev/null
+++ b/tests/statictypes/tgenericcomputedrange.nim
@@ -0,0 +1,125 @@
+import math
+
+block: # issue #19916
+  type
+    Test[S: static[Natural]] = object
+      a: array[ceilDiv(S, 8), uint8]
+
+  let a = Test[32]()
+  doAssert a.a.len == 4
+
+block: # issue #20514
+  type Foo[S:static[array[2, int]]] = object
+    values: array[prod(S), float]
+
+  doAssert Foo[[4,5]]().values.len == 20
+
+block: # issue #20937
+  type
+    Vec3[T: SomeNumber] {.bycopy.} = tuple[x, y, z: T]
+
+  func volume[T](v: Vec3[T]): T =
+    when T is SomeUnsignedInt:
+      v.x * v.y * v.z
+    else:
+      abs (v.x * v.y * v.z)
+
+  type
+    Matrix3[C: static Vec3[uint], T] = object
+      cells: array[C.volume, T]
+
+  let m = Matrix3[(1.uint, 1.uint, 1.uint), uint](cells: [0.uint])
+  doAssert m.cells.len == 1
+  let m2 = Matrix3[(4.uint, 3.uint, 5.uint), uint]()
+  doAssert m2.cells.len == 60
+
+block:  # issue #19284
+  type Board[N, M: static Slice[int]] = array[len(N)*len(M), int8]
+
+  var t: Board[0..4, 0..4]
+  doAssert t.len == 25
+
+block: # minimal issue #19284
+  proc foo[T](x: T): int =
+    result = 0
+  type Foo[N: static int] = array[0..foo(N), int]
+
+  var t: Foo[5]
+  doAssert t.len == 1
+
+block:
+  type Foo[T; U: static T] = range[T(0) .. U]
+
+  block:
+    var x: array[Foo[int, 1], int]
+    x[0] = 1
+    x[1] = 2
+    doAssert x == [0: 1, 1: 2]
+    doAssert x is array[0 .. 1, int]
+
+  block:
+    type Bar = enum a, b, c
+    var x: array[Foo[Bar, c], int]
+    x[a] = 1
+    x[b] = 2
+    x[c] = 3
+    doAssert x == [a: 1, b: 2, c: 3]
+    doAssert x is array[a .. c, int]
+
+block:
+  type Foo[T; U: static T] = array[T(0) .. U, int]
+
+  block:
+    var x: Foo[int, 1]
+    x[0] = 1
+    x[1] = 2
+    doAssert x == [0: 1, 1: 2]
+    doAssert x is array[0 .. 1, int]
+
+  block:
+    type Bar = enum a, b, c
+    var x: Foo[Bar, c]
+    x[a] = 1
+    x[b] = 2
+    x[c] = 3
+    doAssert x == [a: 1, b: 2, c: 3]
+    doAssert x is array[a .. c, int]
+
+block:
+  type Foo[T; U: static T] = array[T(0) .. U + 1, int]
+
+  block:
+    var x: Foo[int, 1]
+    x[0] = 1
+    x[1] = 2
+    x[2] = 3
+    doAssert x == [0: 1, 1: 2, 2: 3]
+    doAssert x is array[0 .. 2, int]
+
+block:
+  type Foo[T; U: static T] = array[T(0) .. (U * 2) + 1, int]
+
+  block:
+    var x: Foo[int, 1]
+    x[0] = 1
+    x[1] = 2
+    x[2] = 3
+    x[3] = 4
+    doAssert x == [0: 1, 1: 2, 2: 3, 3: 4]
+    doAssert x is array[0 .. 3, int]
+
+block: # issue #22187
+  template m(T: type, s: int64): int64 = s
+  func p(n: int64): int = int(n)
+  type F[T; s: static int64] = object
+    k: array[p(m(T, s)), int64]
+  var x: F[int, 3]
+  doAssert x.k is array[3, int64]
+
+block: # issue #22490
+  proc log2trunc(x: uint64): int =
+    if x == 0: int(0) else: int(0)
+  template maxChunkIdx(T: typedesc): int64 = 0'i64
+  template layer(vIdx: int64): int = log2trunc(0'u64)
+  type HashList[T] = object
+    indices: array[int(layer(maxChunkIdx(T))), int]
diff --git a/tests/statictypes/tpassthruarith.nim b/tests/statictypes/tpassthruarith.nim
index 857e5b0af..33e4e0303 100644
--- a/tests/statictypes/tpassthruarith.nim
+++ b/tests/statictypes/tpassthruarith.nim
@@ -1,13 +1,9 @@
 discard """
 output: '''
 [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
-
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-
 [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
-
 [1, 2, 3, 4]
 '''
 """
diff --git a/tests/statictypes/tstatic.nim b/tests/statictypes/tstatic.nim
new file mode 100644
index 000000000..aaa63534b
--- /dev/null
+++ b/tests/statictypes/tstatic.nim
@@ -0,0 +1,56 @@
+discard """
+  targets: "c cpp js"
+"""
+
+template main() =
+  block: # bug #17589
+    #[
+    # all those gave some variation of the same bug:
+    'intVal' is not accessible using discriminant 'kind' of type 'TFullReg'
+    'floatVal' is not accessible using discriminant 'kind' of type 'TFullReg'
+    ]#
+    block:
+      proc f(a: static uint64): uint64 =
+        a
+      const x = 3'u64
+      static: doAssert f(x) == 3'u64
+      doAssert f(x) == 3'u64
+
+    block:
+      proc f(a: static uint64): uint64 =
+        a
+      const x = 3'u64
+      static: doAssert f(x) == 3'u64
+      doAssert f(x) == 3'u64
+
+    block:
+      proc foo(x: uint8): uint8 = x
+      proc f(a: static uint8): auto = foo(a)
+      const x = 3'u8
+      static: doAssert f(x) == 3'u8
+      doAssert f(x) == 3'u8
+
+    block:
+      template foo2(x: float) =
+        let b = x == 0
+      proc foo(x: float) = foo2(x)
+      proc f(a: static float) = foo(a)
+      const x = 1.0
+      static: f(x)
+
+    block:
+      proc foo(x: int32) =
+        let b = x == 0
+      proc f(a: static int32) = foo(a)
+      static: f(32767) # was working
+      static: f(32768) # was failing because >= int16.high (see isInt16Lit)
+
+  block: # bug #14585
+    const foo_m0ninv = 0x1234'u64
+    proc foo(m0ninv: static uint64) =
+      let b = $m0ninv
+    static:
+      foo(foo_m0ninv)
+
+static: main()
+main()
diff --git a/tests/statictypes/tstaticgenericparam.nim b/tests/statictypes/tstaticgenericparam.nim
new file mode 100644
index 000000000..6acd05b70
--- /dev/null
+++ b/tests/statictypes/tstaticgenericparam.nim
@@ -0,0 +1,24 @@
+# static types that depend on a generic parameter
+
+block: # issue #19365
+  var ss: seq[string]
+  proc f[T](x: static T) =
+    ss.add($x & ": " & $T)
+
+  f(123)
+  doAssert ss == @["123: int"]
+  f("abc")
+  doAssert ss == @["123: int", "abc: string"]
+
+block: # issue #7209
+  type Modulo[A; M: static[A]] = distinct A
+
+  proc `$`[A; M: static[A]](x: Modulo[A, M]): string =
+    $(A(x)) & " mod " & $(M)
+
+  proc modulo[A](a: A, M: static[A]): Modulo[A, M] = Modulo[A, M](a %% M)
+
+  proc `+`[A; M: static[A]](x, y: Modulo[A, M]): Modulo[A, M] =
+    (A(x) + A(y)).modulo(M)
+
+  doAssert $(3.modulo(7) + 5.modulo(7)) == "1 mod 7"
diff --git a/tests/statictypes/tstaticimportcpp.nim b/tests/statictypes/tstaticimportcpp.nim
index 125dcb98d..ec4696379 100644
--- a/tests/statictypes/tstaticimportcpp.nim
+++ b/tests/statictypes/tstaticimportcpp.nim
@@ -23,12 +23,12 @@ struct SimpleStruct {
 """ .}
 
 type
-  GenericIntType {.importcpp: "GenericIntType<'0, '1>".} [N: static[int]; T] = object
+  GenericIntType[N: static[int]; T] {.importcpp: "GenericIntType<'0, '1>".} = object
     data: array[N, T]
 
-  GenericIntTypeAlt {.importcpp: "GenericIntType".} [N: static[int]; T] = object
+  GenericIntTypeAlt[N: static[int]; T] {.importcpp: "GenericIntType".} = object
 
-  GenericTType {.importcpp: "GenericTType<'0>".} [T] = object
+  GenericTType[T] {.importcpp: "GenericTType<'0>".} = object
     field: T
 
   GenInt4 = GenericIntType[4, int]
diff --git a/tests/statictypes/tstaticprocparams.nim b/tests/statictypes/tstaticprocparams.nim
new file mode 100644
index 000000000..75d8288ac
--- /dev/null
+++ b/tests/statictypes/tstaticprocparams.nim
@@ -0,0 +1,16 @@
+proc consumer[T: static proc(i: int): int{.nimcall.}](i: int): int = T(i)
+proc consumer(T: static proc(i: int): int{.nimcall.}, i: int): int = T(i)
+
+proc addIt(i: int): int = i + i
+proc add(i: int): int = i + i # Checks if we can use overloads
+proc squareIt(i: int): int = i * i
+
+assert consumer[addIt](10) == 20
+assert consumer[add](10) == 20
+assert consumer[squareIt](30) == 900
+assert consumer[proc(i: int): int{.nimcall.} = i * i + i](10) == 110
+
+assert consumer(addIt, 10) == 20
+assert consumer(add, 10) == 20
+assert consumer(squareIt, 30) == 900
+assert consumer(proc(i: int): int{.nimcall.} = i * i + i, 10) == 110
diff --git a/tests/statictypes/tstatictypes.nim b/tests/statictypes/tstatictypes.nim
index c95e499d7..572b8c4a5 100644
--- a/tests/statictypes/tstatictypes.nim
+++ b/tests/statictypes/tstatictypes.nim
@@ -1,7 +1,16 @@
 discard """
+nimoutFull: true
 nimout: '''
 staticAlialProc instantiated with 358
 staticAlialProc instantiated with 368
+0: Foo
+1: Bar
+0: Foo
+1: Bar
+0: Foo
+1: Bar
+0: Foo
+1: Bar
 '''
 output: '''
 16
@@ -9,19 +18,23 @@ output: '''
 b is 2 times a
 17
 ['\x00', '\x00', '\x00', '\x00']
+heyho
+Val1
+Val1
 '''
+matrix: "--hints:off --mm:orc; --hints:off --mm:refc"
 """
 
 import macros
 
-template ok(x) = assert(x)
-template no(x) = assert(not x)
+template ok(x) = doAssert(x)
+template no(x) = doAssert(not x)
 
 template accept(x) =
-  static: assert(compiles(x))
+  static: doAssert(compiles(x))
 
 template reject(x) =
-  static: assert(not compiles(x))
+  static: doAssert(not compiles(x))
 
 proc plus(a, b: int): int = a + b
 
@@ -51,8 +64,8 @@ when true:
                        b: static[int],
                        c: static int) =
     static:
-      assert a.isStatic and b.isStatic and c.isStatic
-      assert isStatic(a + plus(b, c))
+      doAssert a.isStatic and b.isStatic and c.isStatic
+      doAssert isStatic(a + plus(b, c))
       echo "staticAlialProc instantiated with ", a, b, c
 
     when b mod a == 0:
@@ -88,6 +101,10 @@ when true:
   reject:
     var x = static(v)
 
+block: # issue #13730
+  type Foo[T: static[float]] = object
+  doAssert Foo[0.0] is Foo[-0.0]
+
 when true:
   type
     ArrayWrapper1[S: static int] = object
@@ -104,9 +121,9 @@ when true:
   var aw3: ArrayWrapper3[(10, "str")]
 
   static:
-    assert aw1.data.high == 5
-    assert aw2.data.high == 6
-    assert aw3.data.high == 9
+    doAssert aw1.data.high == 5
+    doAssert aw2.data.high == 6
+    doAssert aw3.data.high == 9
 
 # #6077
 block:
@@ -166,3 +183,277 @@ var
   s: StringValue16
 
 echo s
+
+block: #13529
+  block:
+    type Foo[T: static type] = object
+    var foo: Foo["test"]
+    doAssert $foo == "()"
+    doAssert foo.T is string
+    static: doAssert foo.T == "test"
+    doAssert not compiles(
+      block:
+        type Foo2[T: static type] = object
+          x: T)
+
+  block:
+    type Foo[T: static[float]] = object
+    var foo: Foo[1.2]
+    doAssert $foo == "()"
+    doAssert foo.T == 1.2
+
+  block: # routines also work
+    proc fun(a: static) = (const a2 = a)
+    fun(1)
+    fun(1.2)
+  block: # routines also work
+    proc fun(a: static type) = (const a2 = a)
+    fun(1)
+    fun(1.2)
+
+  block: # this also works
+    proc fun[T](a: static[T]) = (const a2 = a)
+    fun(1)
+    fun(1.2)
+
+block: # #12713
+  block:
+    type Cell = object
+      c: int
+    proc test(c: static string) = discard #Remove this and it compiles
+    proc test(c: Cell) = discard
+    test Cell(c: 0)
+  block:
+    type Cell = object
+      c: int
+    proc test(c: static string) = discard #Remove this and it compiles
+    proc test(c: Cell) = discard
+    test Cell()
+
+block: # issue #14802
+  template fn(s: typed): untyped =
+    proc bar() = discard
+    12
+  const myConst = static(fn(1))
+  doAssert myConst == 12
+
+
+# bug #12571
+type
+  T[K: static bool] = object of RootObj
+    when K == true:
+      foo: string
+    else:
+      bar: string
+  U[K: static bool] = object of T[K]
+
+let t = T[true](foo: "hey")
+let u = U[false](bar: "ho")
+echo t.foo, u.bar
+
+
+#------------------------------------------------------------------------------
+# issue #9679
+
+type
+  Foo*[T] = object
+    bar*: int
+    dummy: T
+
+proc initFoo(T: type, bar: int): Foo[T] =
+  result.bar = 1
+
+proc fails[T](x: static Foo[T]) = # Change to non-static and it compiles
+  doAssert($x == "(bar: 1, dummy: 0)")
+
+block:
+  const foo = initFoo(int, 2)
+  fails(foo)
+
+
+import tables
+
+var foo{.compileTime.} = [
+  "Foo",
+  "Bar"
+]
+
+var bar{.compileTime.} = {
+  0: "Foo",
+  1: "Bar"
+}.toTable()
+
+macro fooM(): untyped =
+  for i, val in foo:
+    echo i, ": ", val
+
+macro barM(): untyped =
+  for i, val in bar:
+    echo i, ": ", val
+
+macro fooParam(x: static array[2, string]): untyped =
+  for i, val in x:
+    echo i, ": ", val
+
+macro barParam(x: static Table[int, string]): untyped =
+  let barParamInsides = proc(i: int, val: string): NimNode =
+    echo i, ": ", val
+  for i, val in x:
+    discard barParamInsides(i, val)
+
+fooM()
+barM()
+fooParam(foo)
+barParam(bar)
+
+
+#-----------------------------------------------------------------------------------------
+# issue #7546
+type
+  rangeB[N: static[int16]] = range[0'i16 .. N]
+  setB[N: static[int16]] = set[rangeB[N]]
+
+block:
+  var s : setB[14'i16]
+
+
+#-----------------------------------------------------------------------------------------
+# issue #9520
+
+type
+  MyEnum = enum
+    Val1, Val2
+
+proc myproc(a: static[MyEnum], b: int) =
+  if b < 0:
+    myproc(a, -b)
+
+  echo $a
+
+myproc(Val1, -10)
+
+
+#------------------------------------------------------------------------------------------
+# issue #6177
+
+type                                                                                                 
+  G[N,M:static[int], T] = object                                                                      
+    o: T                                                                                             
+                                                                                                     
+proc newG[N,M:static[int],T](x:var G[N,M,T], y:T) =                                                  
+  x.o = y+10*N+100*M                                                                                 
+                                                                                                     
+proc newG[N,M:static[int],T](x:T):G[N,M,T] = result.newG(x)                                          
+                                                                                                     
+var x:G[2,3,int]                                                                                     
+x.newG(4)                                                                                            
+var y = newG[2,3,int](4)
+
+
+#------------------------------------------------------------------------------------------
+# issue #12897
+
+type
+  TileCT[n: static int] = object
+    a: array[n, int]
+  Tile = TileCT #Commenting this out to make it work
+
+
+#------------------------------------------------------------------------------------------
+# issue #15858
+
+proc fn(N1: static int, N2: static int, T: typedesc): array[N1 * N2, T] = 
+  doAssert(len(result) == N1 * N2)
+
+let yy = fn(5, 10, float)
+
+
+block:
+  block:
+    type Foo[N: static int] = array[cint(0) .. cint(N), float]
+    type T = Foo[3]
+  block:
+    type Foo[N: static int] = array[int32(0) .. int32(N), float]
+    type T = Foo[3]
+
+
+#------------------------------------------------------------------------------------------
+# static proc/lambda param
+func isSorted2[T](a: openArray[T], cmp: static proc(x, y: T): bool {.inline.}): bool =
+  result = true
+  for i in 0..<len(a)-1:
+    if not cmp(a[i], a[i+1]):
+      return false
+
+proc compare(a, b: int): bool {.inline.} = a < b
+
+var sorted = newSeq[int](1000)
+for i in 0..<sorted.len: sorted[i] = i*2
+doAssert isSorted2(sorted, compare)
+doAssert isSorted2(sorted, proc (a, b: int): bool {.inline.} = a < b)
+
+
+block: # Ensure static descriminated objects compile
+  type
+    ObjKind = enum
+      KindA, KindB, KindC
+
+    MyObject[kind: static[ObjKind]] = object of RootObj
+      myNumber: int
+      when kind != KindA:
+        driverType: int
+        otherField: int
+      elif kind == KindC:
+        driverType: uint
+        otherField: int
+
+  var instance: MyObject[KindA]
+  discard instance
+  discard MyObject[KindC]()
+
+block: # more cases of above, issue #8446
+  type
+    Color = enum
+      red, green, blue
+    Blah[color: static[Color]] = object
+      when color == red:
+        a: string
+      else:
+        b: int
+
+  proc foo(blah: Blah) = discard
+  foo(Blah[red](a: "abc"))
+
+  type
+    Mytype[K: static[int]] = object
+      when K < 16:
+        data: uint8
+      else:
+        data: uint64
+  proc usingMyt(k: Mytype) = discard  # triggers Error: cannot generate code for: K
+
+block: # bug #22600
+  proc f(n: static int): int = n * 2 # same for template
+
+  type
+    a[N: static int] = object
+      field : array[N, uint8]
+
+    b[N: static int] = object
+      field : a[N]
+
+    c[N: static int] = object
+      f0    : a[N     ]         # works
+      f1    : a[N + 1 ]         # asserts
+      f2    : a[f(N)  ]         # asserts
+
+      f3    : b[N     ]         # works
+      f4    : b[N + 1 ]         # asserts
+      f5    : b[f(N)  ]         # asserts
+
+  proc init[N: static int](x : var a[N]) = discard
+  proc init[N: static int](x : var b[N]) = discard
+  proc init[N: static int](x : var c[N]) = x.f1.init() # this is needed
+
+  var x: c[2]
+  x.init()
diff --git a/tests/stdlib/concurrency/atomicSample.nim b/tests/stdlib/concurrency/atomicSample.nim
new file mode 100644
index 000000000..d56d867df
--- /dev/null
+++ b/tests/stdlib/concurrency/atomicSample.nim
@@ -0,0 +1,9 @@
+import atomics
+
+type
+  AtomicWithGeneric*[T] = object
+    value: Atomic[T]
+
+proc initAtomicWithGeneric*[T](value: T): AtomicWithGeneric[T] =
+  result.value.store(value)
+
diff --git a/tests/stdlib/concurrency/tatomic_import.nim b/tests/stdlib/concurrency/tatomic_import.nim
new file mode 100644
index 000000000..e8faaae20
--- /dev/null
+++ b/tests/stdlib/concurrency/tatomic_import.nim
@@ -0,0 +1,11 @@
+import atomicSample
+
+block crossFileObjectContainingAGenericWithAComplexObject:
+  discard initAtomicWithGeneric[string]("foo")
+
+block crossFileObjectContainingAGenericWithAnInteger:
+  discard initAtomicWithGeneric[int](1)
+  discard initAtomicWithGeneric[int8](1)
+  discard initAtomicWithGeneric[int16](1)
+  discard initAtomicWithGeneric[int32](1)
+  discard initAtomicWithGeneric[int64](1)
diff --git a/tests/stdlib/concurrency/tatomics.nim b/tests/stdlib/concurrency/tatomics.nim
new file mode 100644
index 000000000..08f2e7d3e
--- /dev/null
+++ b/tests/stdlib/concurrency/tatomics.nim
@@ -0,0 +1,637 @@
+discard """
+  # test C with -d:nimUseCppAtomics as well to check nothing breaks
+  matrix: "--mm:refc; --mm:orc; --mm:refc -d:nimUseCppAtomics; --mm:orc -d:nimUseCppAtomics"
+  targets: "c cpp"
+"""
+
+# test atomic operations
+
+import std/[atomics, bitops]
+import std/assertions
+
+
+type
+  Object = object
+    val: int
+
+
+# Atomic operations for trivial objects
+
+
+block trivialLoad:
+  var location: Atomic[int]
+  location.store(1)
+  doAssert location.load == 1
+  location.store(2)
+  doAssert location.load(moRelaxed) == 2
+  location.store(3)
+  doAssert location.load(moAcquire) == 3
+
+
+block trivialStore:
+  var location: Atomic[int]
+  location.store(1)
+  doAssert location.load == 1
+  location.store(2, moRelaxed)
+  doAssert location.load == 2
+  location.store(3, moRelease)
+  doAssert location.load == 3
+
+
+block trivialExchange:
+  var location: Atomic[int]
+  location.store(1)
+  doAssert location.exchange(2) == 1
+  doAssert location.exchange(3, moRelaxed) == 2
+  doAssert location.exchange(4, moAcquire) == 3
+  doAssert location.exchange(5, moRelease) == 4
+  doAssert location.exchange(6, moAcquireRelease) == 5
+  doAssert location.load == 6
+
+
+block trivialCompareExchangeDoesExchange:
+  var location: Atomic[int]
+  var expected = 1
+  location.store(1)
+  doAssert location.compareExchange(expected, 2)
+  doAssert expected == 1
+  doAssert location.load == 2
+  expected = 2
+  doAssert location.compareExchange(expected, 3, moRelaxed)
+  doAssert expected == 2
+  doAssert location.load == 3
+  expected = 3
+  doAssert location.compareExchange(expected, 4, moAcquire)
+  doAssert expected == 3
+  doAssert location.load == 4
+  expected = 4
+  doAssert location.compareExchange(expected, 5, moRelease)
+  doAssert expected == 4
+  doAssert location.load == 5
+  expected = 5
+  doAssert location.compareExchange(expected, 6, moAcquireRelease)
+  doAssert expected == 5
+  doAssert location.load == 6
+
+
+block trivialCompareExchangeDoesNotExchange:
+  var location: Atomic[int]
+  var expected = 10
+  location.store(1)
+  doAssert not location.compareExchange(expected, 2)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 3, moRelaxed)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 4, moAcquire)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 5, moRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 6, moAcquireRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+
+
+block trivialCompareExchangeSuccessFailureDoesExchange:
+  var location: Atomic[int]
+  var expected = 1
+  location.store(1)
+  doAssert location.compareExchange(expected, 2, moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == 1
+  doAssert location.load == 2
+  expected = 2
+  doAssert location.compareExchange(expected, 3, moRelaxed, moRelaxed)
+  doAssert expected == 2
+  doAssert location.load == 3
+  expected = 3
+  doAssert location.compareExchange(expected, 4, moAcquire, moAcquire)
+  doAssert expected == 3
+  doAssert location.load == 4
+  expected = 4
+  doAssert location.compareExchange(expected, 5, moRelease, moRelease)
+  doAssert expected == 4
+  doAssert location.load == 5
+  expected = 5
+  doAssert location.compareExchange(expected, 6, moAcquireRelease, moAcquireRelease)
+  doAssert expected == 5
+  doAssert location.load == 6
+
+
+block trivialCompareExchangeSuccessFailureDoesNotExchange:
+  var location: Atomic[int]
+  var expected = 10
+  location.store(1)
+  doAssert not location.compareExchange(expected, 2, moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 3, moRelaxed, moRelaxed)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 4, moAcquire, moAcquire)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 5, moRelease, moRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchange(expected, 6, moAcquireRelease, moAcquireRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+
+
+block trivialCompareExchangeWeakDoesExchange:
+  var location: Atomic[int]
+  var expected = 1
+  location.store(1)
+  doAssert location.compareExchangeWeak(expected, 2)
+  doAssert expected == 1
+  doAssert location.load == 2
+  expected = 2
+  doAssert location.compareExchangeWeak(expected, 3, moRelaxed)
+  doAssert expected == 2
+  doAssert location.load == 3
+  expected = 3
+  doAssert location.compareExchangeWeak(expected, 4, moAcquire)
+  doAssert expected == 3
+  doAssert location.load == 4
+  expected = 4
+  doAssert location.compareExchangeWeak(expected, 5, moRelease)
+  doAssert expected == 4
+  doAssert location.load == 5
+  expected = 5
+  doAssert location.compareExchangeWeak(expected, 6, moAcquireRelease)
+  doAssert expected == 5
+  doAssert location.load == 6
+
+
+block trivialCompareExchangeWeakDoesNotExchange:
+  var location: Atomic[int]
+  var expected = 10
+  location.store(1)
+  doAssert not location.compareExchangeWeak(expected, 2)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 3, moRelaxed)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 4, moAcquire)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 5, moRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 6, moAcquireRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+
+
+block trivialCompareExchangeWeakSuccessFailureDoesExchange:
+  var location: Atomic[int]
+  var expected = 1
+  location.store(1)
+  doAssert location.compareExchangeWeak(expected, 2, moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == 1
+  doAssert location.load == 2
+  expected = 2
+  doAssert location.compareExchangeWeak(expected, 3, moRelaxed, moRelaxed)
+  doAssert expected == 2
+  doAssert location.load == 3
+  expected = 3
+  doAssert location.compareExchangeWeak(expected, 4, moAcquire, moAcquire)
+  doAssert expected == 3
+  doAssert location.load == 4
+  expected = 4
+  doAssert location.compareExchangeWeak(expected, 5, moRelease, moRelease)
+  doAssert expected == 4
+  doAssert location.load == 5
+  expected = 5
+  doAssert location.compareExchangeWeak(expected, 6, moAcquireRelease, moAcquireRelease)
+  doAssert expected == 5
+  doAssert location.load == 6
+
+
+block trivialCompareExchangeWeakSuccessFailureDoesNotExchange:
+  var location: Atomic[int]
+  var expected = 10
+  location.store(1)
+  doAssert not location.compareExchangeWeak(expected, 2, moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 3, moRelaxed, moRelaxed)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 4, moAcquire, moAcquire)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 5, moRelease, moRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+  expected = 10
+  doAssert not location.compareExchangeWeak(expected, 6, moAcquireRelease, moAcquireRelease)
+  doAssert expected == 1
+  doAssert location.load == 1
+
+
+# Atomic operations for non-trivial objects
+
+
+block objectLoad:
+  var location: Atomic[Object]
+  location.store(Object(val: 1))
+  doAssert location.load == Object(val: 1)
+  location.store(Object(val: 2))
+  doAssert location.load(moRelaxed) == Object(val: 2)
+  location.store(Object(val: 3))
+  doAssert location.load(moAcquire) == Object(val: 3)
+
+
+block objectStore:
+  var location: Atomic[Object]
+  location.store(Object(val: 1))
+  doAssert location.load == Object(val: 1)
+  location.store(Object(val: 2), moRelaxed)
+  doAssert location.load == Object(val: 2)
+  location.store(Object(val: 3), moRelease)
+  doAssert location.load == Object(val: 3)
+
+
+block objectExchange:
+  var location: Atomic[Object]
+  location.store(Object(val: 1))
+  doAssert location.exchange(Object(val: 2)) == Object(val: 1)
+  doAssert location.exchange(Object(val: 3), moRelaxed) == Object(val: 2)
+  doAssert location.exchange(Object(val: 4), moAcquire) == Object(val: 3)
+  doAssert location.exchange(Object(val: 5), moRelease) == Object(val: 4)
+  doAssert location.exchange(Object(val: 6), moAcquireRelease) == Object(val: 5)
+  doAssert location.load == Object(val: 6)
+
+
+block objectCompareExchangeDoesExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 1)
+  location.store(Object(val: 1))
+  doAssert location.compareExchange(expected, Object(val: 2))
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 2)
+  expected = Object(val: 2)
+  doAssert location.compareExchange(expected, Object(val: 3), moRelaxed)
+  doAssert expected == Object(val: 2)
+  doAssert location.load == Object(val: 3)
+  expected = Object(val: 3)
+  doAssert location.compareExchange(expected, Object(val: 4), moAcquire)
+  doAssert expected == Object(val: 3)
+  doAssert location.load == Object(val: 4)
+  expected = Object(val: 4)
+  doAssert location.compareExchange(expected, Object(val: 5), moRelease)
+  doAssert expected == Object(val: 4)
+  doAssert location.load == Object(val: 5)
+  expected = Object(val: 5)
+  doAssert location.compareExchange(expected, Object(val: 6), moAcquireRelease)
+  doAssert expected == Object(val: 5)
+  doAssert location.load == Object(val: 6)
+
+
+block objectCompareExchangeDoesNotExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 10)
+  location.store(Object(val: 1))
+  doAssert not location.compareExchange(expected, Object(val: 2))
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 3), moRelaxed)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 4), moAcquire)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 5), moRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 6), moAcquireRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+
+
+block objectCompareExchangeSuccessFailureDoesExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 1)
+  location.store(Object(val: 1))
+  doAssert location.compareExchange(expected, Object(val: 2), moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 2)
+  expected = Object(val: 2)
+  doAssert location.compareExchange(expected, Object(val: 3), moRelaxed, moRelaxed)
+  doAssert expected == Object(val: 2)
+  doAssert location.load == Object(val: 3)
+  expected = Object(val: 3)
+  doAssert location.compareExchange(expected, Object(val: 4), moAcquire, moAcquire)
+  doAssert expected == Object(val: 3)
+  doAssert location.load == Object(val: 4)
+  expected = Object(val: 4)
+  doAssert location.compareExchange(expected, Object(val: 5), moRelease, moRelease)
+  doAssert expected == Object(val: 4)
+  doAssert location.load == Object(val: 5)
+  expected = Object(val: 5)
+  doAssert location.compareExchange(expected, Object(val: 6), moAcquireRelease, moAcquireRelease)
+  doAssert expected == Object(val: 5)
+  doAssert location.load == Object(val: 6)
+
+
+block objectCompareExchangeSuccessFailureDoesNotExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 10)
+  location.store(Object(val: 1))
+  doAssert not location.compareExchange(expected, Object(val: 2), moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 3), moRelaxed, moRelaxed)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 4), moAcquire, moAcquire)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 5), moRelease, moRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchange(expected, Object(val: 6), moAcquireRelease, moAcquireRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+
+
+block objectCompareExchangeWeakDoesExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 1)
+  location.store(Object(val: 1))
+  doAssert location.compareExchangeWeak(expected, Object(val: 2))
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 2)
+  expected = Object(val: 2)
+  doAssert location.compareExchangeWeak(expected, Object(val: 3), moRelaxed)
+  doAssert expected == Object(val: 2)
+  doAssert location.load == Object(val: 3)
+  expected = Object(val: 3)
+  doAssert location.compareExchangeWeak(expected, Object(val: 4), moAcquire)
+  doAssert expected == Object(val: 3)
+  doAssert location.load == Object(val: 4)
+  expected = Object(val: 4)
+  doAssert location.compareExchangeWeak(expected, Object(val: 5), moRelease)
+  doAssert expected == Object(val: 4)
+  doAssert location.load == Object(val: 5)
+  expected = Object(val: 5)
+  doAssert location.compareExchangeWeak(expected, Object(val: 6), moAcquireRelease)
+  doAssert expected == Object(val: 5)
+  doAssert location.load == Object(val: 6)
+
+
+block objectCompareExchangeWeakDoesNotExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 10)
+  location.store(Object(val: 1))
+  doAssert not location.compareExchangeWeak(expected, Object(val: 2))
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 3), moRelaxed)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 4), moAcquire)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 5), moRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 6), moAcquireRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+
+
+block objectCompareExchangeWeakSuccessFailureDoesExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 1)
+  location.store(Object(val: 1))
+  doAssert location.compareExchangeWeak(expected, Object(val: 2), moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 2)
+  expected = Object(val: 2)
+  doAssert location.compareExchangeWeak(expected, Object(val: 3), moRelaxed, moRelaxed)
+  doAssert expected == Object(val: 2)
+  doAssert location.load == Object(val: 3)
+  expected = Object(val: 3)
+  doAssert location.compareExchangeWeak(expected, Object(val: 4), moAcquire, moAcquire)
+  doAssert expected == Object(val: 3)
+  doAssert location.load == Object(val: 4)
+  expected = Object(val: 4)
+  doAssert location.compareExchangeWeak(expected, Object(val: 5), moRelease, moRelease)
+  doAssert expected == Object(val: 4)
+  doAssert location.load == Object(val: 5)
+  expected = Object(val: 5)
+  doAssert location.compareExchangeWeak(expected, Object(val: 6), moAcquireRelease, moAcquireRelease)
+  doAssert expected == Object(val: 5)
+  doAssert location.load == Object(val: 6)
+
+
+block objectCompareExchangeWeakSuccessFailureDoesNotExchange:
+  var location: Atomic[Object]
+  var expected = Object(val: 10)
+  location.store(Object(val: 1))
+  doAssert not location.compareExchangeWeak(expected, Object(val: 2), moSequentiallyConsistent, moSequentiallyConsistent)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 3), moRelaxed, moRelaxed)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 4), moAcquire, moAcquire)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 5), moRelease, moRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+  expected = Object(val: 10)
+  doAssert not location.compareExchangeWeak(expected, Object(val: 6), moAcquireRelease, moAcquireRelease)
+  doAssert expected == Object(val: 1)
+  doAssert location.load == Object(val: 1)
+
+
+# Numerical operations
+
+
+block fetchAdd:
+  var location: Atomic[int]
+  doAssert location.fetchAdd(1) == 0
+  doAssert location.fetchAdd(1, moRelaxed) == 1
+  doAssert location.fetchAdd(1, moRelease) == 2
+  doAssert location.load == 3
+
+
+block fetchSub:
+  var location: Atomic[int]
+  doAssert location.fetchSub(1) == 0
+  doAssert location.fetchSub(1, moRelaxed) == -1
+  doAssert location.fetchSub(1, moRelease) == -2
+  doAssert location.load == -3
+
+
+block fetchAnd:
+  var location: Atomic[int]
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchAnd(j) == i)
+      doAssert(location.load == i.bitand(j))
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchAnd(j, moRelaxed) == i)
+      doAssert(location.load == i.bitand(j))
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchAnd(j, moRelease) == i)
+      doAssert(location.load == i.bitand(j))
+
+
+block fetchOr:
+  var location: Atomic[int]
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchOr(j) == i)
+      doAssert(location.load == i.bitor(j))
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchOr(j, moRelaxed) == i)
+      doAssert(location.load == i.bitor(j))
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchOr(j, moRelease) == i)
+      doAssert(location.load == i.bitor(j))
+
+
+block fetchXor:
+  var location: Atomic[int]
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchXor(j) == i)
+      doAssert(location.load == i.bitxor(j))
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchXor(j, moRelaxed) == i)
+      doAssert(location.load == i.bitxor(j))
+
+  for i in 0..16:
+    for j in 0..16:
+      location.store(i)
+      doAssert(location.fetchXor(j, moRelease) == i)
+      doAssert(location.load == i.bitxor(j))
+
+
+block atomicInc:
+  var location: Atomic[int]
+  location.atomicInc
+  doAssert location.load == 1
+  location.atomicInc(1)
+  doAssert location.load == 2
+  location += 1
+  doAssert location.load == 3
+
+
+block atomicDec:
+  var location: Atomic[int]
+  location.atomicDec
+  doAssert location.load == -1
+  location.atomicDec(1)
+  doAssert location.load == -2
+  location -= 1
+  doAssert location.load == -3
+
+
+# Flag operations
+
+
+block testAndSet:
+  var location: AtomicFlag
+  doAssert not location.testAndSet
+  doAssert location.testAndSet
+  doAssert location.testAndSet
+  location.clear()
+  doAssert not location.testAndSet(moRelaxed)
+  doAssert location.testAndSet(moRelaxed)
+  doAssert location.testAndSet(moRelaxed)
+  location.clear()
+  doAssert not location.testAndSet(moRelease)
+  doAssert location.testAndSet(moRelease)
+  doAssert location.testAndSet(moRelease)
+
+
+block clear:
+  var location: AtomicFlag
+  discard location.testAndSet
+  location.clear
+  doAssert not location.testAndSet
+  location.clear(moRelaxed)
+  doAssert not location.testAndSet
+  location.clear(moRelease)
+  doAssert not location.testAndSet
+
+block: # bug #18844
+  when not defined(cpp): # cpp pending pr #18836
+    type
+      Deprivation = object of RootObj
+        memes: Atomic[int]
+      Zoomer = object
+        dopamine: Deprivation
+
+    block:
+      var x = Deprivation()
+      var y = Zoomer()
+      doAssert x.memes.load == 0
+      doAssert y.dopamine.memes.load == 0
+
+    block:
+      var x: Deprivation
+      var y: Zoomer
+      doAssert x.memes.load == 0
+      doAssert y.dopamine.memes.load == 0
diff --git a/tests/stdlib/concurrency/tatomics_size.nim b/tests/stdlib/concurrency/tatomics_size.nim
new file mode 100644
index 000000000..f64adb308
--- /dev/null
+++ b/tests/stdlib/concurrency/tatomics_size.nim
@@ -0,0 +1,21 @@
+discard """
+  # test C with -d:nimUseCppAtomics as well to check nothing breaks
+  matrix: "--mm:refc; --mm:orc; --mm:refc -d:nimUseCppAtomics; --mm:orc -d:nimUseCppAtomics"
+  targets: "c cpp"
+"""
+import std/atomics
+import std/assertions
+
+block testSize: # issue 12726
+  type
+    Node = ptr object
+      # works
+      next: Atomic[pointer]
+      f:AtomicFlag
+    MyChannel = object
+      # type not defined completely
+      back: Atomic[ptr int]
+      f: AtomicFlag
+  static:
+    doAssert sizeof(Node) == sizeof(pointer)
+    doAssert sizeof(MyChannel) == sizeof(pointer) * 2
diff --git a/tests/stdlib/config.nims b/tests/stdlib/config.nims
new file mode 100644
index 000000000..dffae2812
--- /dev/null
+++ b/tests/stdlib/config.nims
@@ -0,0 +1,5 @@
+switch("styleCheck", "usages")
+switch("styleCheck", "error")
+switch("define", "nimPreviewSlimSystem")
+switch("define", "nimPreviewCstringConversion")
+switch("define", "nimPreviewProcConversion")
diff --git a/tests/stdlib/mgenast.nim b/tests/stdlib/mgenast.nim
new file mode 100644
index 000000000..b0904847e
--- /dev/null
+++ b/tests/stdlib/mgenast.nim
@@ -0,0 +1,57 @@
+import std/genasts
+import std/macros
+
+# Using a enum instead of, say, int, to make apparent potential bugs related to
+# forgetting converting to NimNode via newLit, see bug #9607
+
+type Foo* = enum kfoo0, kfoo1, kfoo2, kfoo3, kfoo4
+
+proc myLocalPriv(): auto = kfoo1
+proc myLocalPriv2(): auto = kfoo1
+macro bindme2*(): untyped =
+  genAst: myLocalPriv()
+macro bindme3*(): untyped =
+  ## myLocalPriv must be captured explicitly
+  genAstOpt({kDirtyTemplate}, myLocalPriv): myLocalPriv()
+
+macro bindme4*(): untyped =
+  ## calling this won't compile because `myLocalPriv` isn't captured
+  genAstOpt({kDirtyTemplate}): myLocalPriv()
+
+macro bindme5UseExpose*(): untyped =
+  genAst: myLocalPriv2()
+
+macro bindme5UseExposeFalse*(): untyped =
+  genAstOpt({kDirtyTemplate}): myLocalPriv2()
+
+# example from bug #7889
+from std/streams import newStringStream, readData, writeData
+
+macro bindme6UseExpose*(): untyped =
+  genAst:
+    var tst = "sometext"
+    var ss = newStringStream("anothertext")
+    when defined(gcArc) or defined(gcOrc):
+      prepareMutation(tst)
+    writeData(ss, tst[0].addr, 2)
+    discard readData(ss, tst[0].addr, 2)
+
+macro bindme6UseExposeFalse*(): untyped =
+  ## with `kDirtyTemplate`, requires passing all referenced symbols
+  ## which can be tedious
+  genAstOpt({kDirtyTemplate}, newStringStream, writeData, readData):
+    var tst = "sometext"
+    var ss = newStringStream("anothertext")
+    when defined(gcArc) or defined(gcOrc):
+      prepareMutation(tst)
+    writeData(ss, tst[0].addr, 2)
+    discard readData(ss, tst[0].addr, 2)
+
+
+proc locafun1(): auto = "in locafun1"
+proc locafun2(): auto = "in locafun2"
+# locafun3 in caller scope only
+macro mixinExample*(): untyped =
+  genAst:
+    mixin locafun1
+    (locafun1(), locafun2(), locafun3())
diff --git a/tests/stdlib/mimportutils.nim b/tests/stdlib/mimportutils.nim
new file mode 100644
index 000000000..678d9ec02
--- /dev/null
+++ b/tests/stdlib/mimportutils.nim
@@ -0,0 +1,38 @@
+type
+  A* = object
+    a0*: int
+    ha1: float
+  B = object
+    b0*: int
+    hb1: float
+  C* = ref object
+    c0: int
+    hc1: float
+  D* = ptr object
+    d0: int
+    hd1: float
+  PA* = ref A
+  PtA* = ptr A
+  E*[T] = object
+    he1: int
+  FSub[T1, T2] = object
+    h3: T1
+    h4: T2
+  F*[T1, T2] = ref FSub[T1, T2]
+  G*[T] = ref E[T]
+  H3*[T] = object
+    h5: T
+  H2*[T] = H3[T]
+  H1*[T] = ref H2[T]
+  H*[T] = H1[T]
+
+  Pity[T] = object
+    a: T
+  PityRef*[T] = ref Pity[T]
+  Hope*[T] = ref object
+    a: T
+
+type BAalias* = typeof(B.default)
+  # typeof is not a transparent abstraction, creates a `tyAlias`
+
+proc initB*(): B = B()
diff --git a/tests/stdlib/mintsets.nim b/tests/stdlib/mintsets.nim
new file mode 100644
index 000000000..98786e9ba
--- /dev/null
+++ b/tests/stdlib/mintsets.nim
@@ -0,0 +1,11 @@
+import std/intsets
+import std/assertions
+
+proc test1*[]() =
+  let a = initIntSet()
+  doAssert len(a) == 0
+
+proc test2*[]() =
+  var a = initIntSet()
+  var b = initIntSet()
+  a.incl b
diff --git a/tests/stdlib/mstackframes.nim b/tests/stdlib/mstackframes.nim
new file mode 100644
index 000000000..f3daa1437
--- /dev/null
+++ b/tests/stdlib/mstackframes.nim
@@ -0,0 +1,38 @@
+import std/stackframes
+
+
+
+# line 5
+var count = 0
+
+proc main1(n: int) =
+  setFrameMsg $("main1", n)
+  if n > 0:
+    main1(n-1)
+
+proc main2(n: int) =
+  count.inc
+  setFrameMsg $("main2", n, count)
+  proc bar() =
+    setFrameMsg $("bar ",)
+    if n < 3: raise newException(CatchableError, "on purpose")
+  bar()
+  main2(n-1)
+
+proc main() =
+  var z = 0
+  setFrameMsg "\n  z: " & $z, prefix = ""
+  # multiple calls inside a frame are possible
+  z.inc
+  setFrameMsg "\n  z: " & $z, prefix = ""
+  try:
+    main2(5)
+  except CatchableError:
+    main1(10) # goes deep and then unwinds; sanity check to ensure `setFrameMsg` from inside
+              # `main1` won't invalidate the stacktrace; if StackTraceEntry.frameMsg
+              # were a reference instead of a copy, this would fail.
+    let e = getCurrentException()
+    let trace = e.getStackTrace
+    echo trace
+
+main()
diff --git a/tests/stdlib/nre/captures.nim b/tests/stdlib/nre/captures.nim
index bd5e83ecc..acc141baf 100644
--- a/tests/stdlib/nre/captures.nim
+++ b/tests/stdlib/nre/captures.nim
@@ -1,12 +1,12 @@
 import unittest, optional_nonstrict
 include nre
 
-suite "captures":
-  test "map capture names to numbers":
+block: # captures
+  block: # map capture names to numbers
     check(getNameToNumberTable(re("(?<v1>1(?<v2>2(?<v3>3))(?'v4'4))()")) ==
       { "v1" : 0, "v2" : 1, "v3" : 2, "v4" : 3 }.toTable())
 
-  test "capture bounds are correct":
+  block: # capture bounds are correct
     let ex1 = re("([0-9])")
     check("1 23".find(ex1).matchBounds == 0 .. 0)
     check("1 23".find(ex1).captureBounds[0] == 0 .. 0)
@@ -20,7 +20,7 @@ suite "captures":
     let ex3 = re("([0-9]+)")
     check("824".find(ex3).captureBounds[0] == 0 .. 2)
 
-  test "named captures":
+  block: # named captures
     let ex1 = "foobar".find(re("(?<foo>foo)(?<bar>bar)"))
     check(ex1.captures["foo"] == "foo")
     check(ex1.captures["bar"] == "bar")
@@ -32,7 +32,7 @@ suite "captures":
     expect KeyError:
         discard ex2.captures["bar"]
 
-  test "named capture bounds":
+  block: # named capture bounds
     let ex1 = "foo".find(re("(?<foo>foo)(?<bar>bar)?"))
     check("foo" in ex1.captureBounds)
     check(ex1.captureBounds["foo"] == 0..2)
@@ -40,12 +40,12 @@ suite "captures":
     expect KeyError:
         discard ex1.captures["bar"]
 
-  test "capture count":
+  block: # capture count
     let ex1 = re("(?<foo>foo)(?<bar>bar)?")
     check(ex1.captureCount == 2)
     check(ex1.captureNameId == {"foo" : 0, "bar" : 1}.toTable())
 
-  test "named capture table":
+  block: # named capture table
     let ex1 = "foo".find(re("(?<foo>foo)(?<bar>bar)?"))
     check(ex1.captures.toTable == {"foo" : "foo"}.toTable())
     check(ex1.captureBounds.toTable == {"foo" : 0..2}.toTable())
@@ -53,7 +53,7 @@ suite "captures":
     let ex2 = "foobar".find(re("(?<foo>foo)(?<bar>bar)?"))
     check(ex2.captures.toTable == {"foo" : "foo", "bar" : "bar"}.toTable())
 
-  test "capture sequence":
+  block: # capture sequence
     let ex1 = "foo".find(re("(?<foo>foo)(?<bar>bar)?"))
     check(ex1.captures.toSeq == @[some("foo"), none(string)])
     check(ex1.captureBounds.toSeq == @[some(0..2), none(Slice[int])])
diff --git a/tests/stdlib/nre/escape.nim b/tests/stdlib/nre/escape.nim
index db5e8a001..5e7dc0c0e 100644
--- a/tests/stdlib/nre/escape.nim
+++ b/tests/stdlib/nre/escape.nim
@@ -1,7 +1,7 @@
 import nre, unittest
 
-suite "escape strings":
-  test "escape strings":
+block: # escape strings
+  block: # escape strings
     check("123".escapeRe() == "123")
     check("[]".escapeRe() == r"\[\]")
     check("()".escapeRe() == r"\(\)")
diff --git a/tests/stdlib/nre/find.nim b/tests/stdlib/nre/find.nim
index caa953ff4..7e7555d73 100644
--- a/tests/stdlib/nre/find.nim
+++ b/tests/stdlib/nre/find.nim
@@ -3,23 +3,23 @@ import nre except toSeq
 import optional_nonstrict
 import times, strutils
 
-suite "find":
-  test "find text":
+block: # find
+  block: # find text
     check("3213a".find(re"[a-z]").match == "a")
     check(toSeq(findIter("1 2 3 4 5 6 7 8 ", re" ")).map(
       proc (a: RegexMatch): string = a.match
     ) == @[" ", " ", " ", " ", " ", " ", " ", " "])
 
-  test "find bounds":
+  block: # find bounds
     check(toSeq(findIter("1 2 3 4 5 ", re" ")).map(
       proc (a: RegexMatch): Slice[int] = a.matchBounds
     ) == @[1..1, 3..3, 5..5, 7..7, 9..9])
 
-  test "overlapping find":
+  block: # overlapping find
     check("222".findAll(re"22") == @["22"])
     check("2222".findAll(re"22") == @["22", "22"])
 
-  test "len 0 find":
+  block: # len 0 find
     check("".findAll(re"\ ") == newSeq[string]())
     check("".findAll(re"") == @[""])
     check("abc".findAll(re"") == @["", "", "", ""])
@@ -27,7 +27,7 @@ suite "find":
     check("word\r\lword".findAll(re"(*ANYCRLF)(?m)$") == @["", ""])
     check("слово слово".findAll(re"(*U)\b") == @["", "", "", ""])
 
-  test "bail early":
+  block: # bail early
     ## we expect nothing to be found and we should be bailing out early which means that
     ## the timing difference between searching in small and large data should be well
     ## within a tolerance margin
diff --git a/tests/stdlib/nre/init.nim b/tests/stdlib/nre/init.nim
index 26e668104..f0c8e0a00 100644
--- a/tests/stdlib/nre/init.nim
+++ b/tests/stdlib/nre/init.nim
@@ -1,12 +1,12 @@
 import unittest
 include nre
 
-suite "Test NRE initialization":
-  test "correct initialization":
+block: # Test NRE initialization
+  block: # correct initialization
     check(re("[0-9]+") != nil)
     check(re("(?i)[0-9]+") != nil)
 
-  test "options":
+  block: # options
     check(extractOptions("(*NEVER_UTF)") ==
           ("", pcre.NEVER_UTF, true))
     check(extractOptions("(*UTF8)(*ANCHORED)(*UCP)z") ==
@@ -19,14 +19,14 @@ suite "Test NRE initialization":
     check(extractOptions("(*LIMIT_MATCH=6)(*ANCHORED)z") ==
           ("(*LIMIT_MATCH=6)z", pcre.ANCHORED, true))
 
-  test "incorrect options":
+  block: # incorrect options
     for s in ["CR", "(CR", "(*CR", "(*abc)", "(*abc)CR",
               "(?i)",
               "(*LIMIT_MATCH=5", "(*NO_AUTO_POSSESS=5)"]:
       let ss = s & "(*NEVER_UTF)"
       check(extractOptions(ss) == (ss, 0, true))
 
-  test "invalid regex":
+  block: # invalid regex
     expect(SyntaxError): discard re("[0-9")
     try:
       discard re("[0-9")
diff --git a/tests/stdlib/nre/match.nim b/tests/stdlib/nre/match.nim
index 06b69fd04..7e09a4b2f 100644
--- a/tests/stdlib/nre/match.nim
+++ b/tests/stdlib/nre/match.nim
@@ -1,12 +1,12 @@
 include nre, unittest, optional_nonstrict
 
-suite "match":
-  test "upper bound must be inclusive":
+block: # match
+  block: # upper bound must be inclusive
     check("abc".match(re"abc", endpos = -1) == none(RegexMatch))
     check("abc".match(re"abc", endpos = 1) == none(RegexMatch))
     check("abc".match(re"abc", endpos = 2) != none(RegexMatch))
 
-  test "match examples":
+  block: # match examples
     check("abc".match(re"(\w)").captures[0] == "a")
     check("abc".match(re"(?<letter>\w)").captures["letter"] == "a")
     check("abc".match(re"(\w)\w").captures[-1] == "ab")
@@ -14,5 +14,5 @@ suite "match":
     check("abc".match(re"").captureBounds[-1] == 0 .. -1)
     check("abc".match(re"abc").captureBounds[-1] == 0 .. 2)
 
-  test "match test cases":
+  block: # match test cases
     check("123".match(re"").matchBounds == 0 .. -1)
diff --git a/tests/stdlib/nre/misc.nim b/tests/stdlib/nre/misc.nim
index f4a88b639..b7df08ee9 100644
--- a/tests/stdlib/nre/misc.nim
+++ b/tests/stdlib/nre/misc.nim
@@ -1,13 +1,13 @@
 import unittest, nre, strutils, optional_nonstrict
 
-suite "Misc tests":
-  test "unicode":
+block: # Misc tests
+  block: # unicode
     check("".find(re"(*UTF8)").match == "")
     check("перевірка".replace(re"(*U)\w", "") == "")
 
-  test "empty or non-empty match":
-    check("abc".findall(re"|.").join(":") == ":a::b::c:")
-    check("abc".findall(re".|").join(":") == "a:b:c:")
+  block: # empty or non-empty match
+    check("abc".findAll(re"|.").join(":") == ":a::b::c:")
+    check("abc".findAll(re".|").join(":") == "a:b:c:")
 
     check("abc".replace(re"|.", "x") == "xxxxxxx")
     check("abc".replace(re".|", "x") == "xxxx")
diff --git a/tests/stdlib/nre/replace.nim b/tests/stdlib/nre/replace.nim
index 812a7f384..5cf659f21 100644
--- a/tests/stdlib/nre/replace.nim
+++ b/tests/stdlib/nre/replace.nim
@@ -1,13 +1,13 @@
 include nre
 import unittest
 
-suite "replace":
-  test "replace with 0-length strings":
+block: # replace
+  block: # replace with 0-length strings
     check("".replace(re"1", proc (v: RegexMatch): string = "1") == "")
     check(" ".replace(re"", proc (v: RegexMatch): string = "1") == "1 1")
     check("".replace(re"", proc (v: RegexMatch): string = "1") == "1")
 
-  test "regular replace":
+  block: # regular replace
     check("123".replace(re"\d", "foo") == "foofoofoo")
     check("123".replace(re"(\d)", "$1$1") == "112233")
     check("123".replace(re"(\d)(\d)", "$1$2") == "123")
@@ -15,8 +15,8 @@ suite "replace":
     check("123".replace(re"(?<foo>\d)(\d)", "$foo$#$#") == "1123")
     check("123".replace(re"(?<foo>\d)(\d)", "${foo}$#$#") == "1123")
 
-  test "replacing missing captures should throw instead of segfaulting":
-    expect IndexError: discard "ab".replace(re"(a)|(b)", "$1$2")
-    expect IndexError: discard "b".replace(re"(a)?(b)", "$1$2")
+  block: # replacing missing captures should throw instead of segfaulting
+    expect IndexDefect: discard "ab".replace(re"(a)|(b)", "$1$2")
+    expect IndexDefect: discard "b".replace(re"(a)?(b)", "$1$2")
     expect KeyError: discard "b".replace(re"(a)?", "${foo}")
     expect KeyError: discard "b".replace(re"(?<foo>a)?", "${foo}")
diff --git a/tests/stdlib/nre/split.nim b/tests/stdlib/nre/split.nim
index 9d57ea7d8..3cd57bb82 100644
--- a/tests/stdlib/nre/split.nim
+++ b/tests/stdlib/nre/split.nim
@@ -1,8 +1,8 @@
 import unittest, strutils
 include nre
 
-suite "string splitting":
-  test "splitting strings":
+block: # string splitting
+  block: # splitting strings
     check("1 2 3 4 5 6 ".split(re" ") == @["1", "2", "3", "4", "5", "6", ""])
     check("1  2  ".split(re(" ")) == @["1", "", "2", "", ""])
     check("1 2".split(re(" ")) == @["1", "2"])
@@ -10,22 +10,22 @@ suite "string splitting":
     check("".split(re"foo") == @[""])
     check("9".split(re"\son\s") == @["9"])
 
-  test "captured patterns":
+  block: # captured patterns
     check("12".split(re"(\d)") == @["", "1", "", "2", ""])
 
-  test "maxsplit":
+  block: # maxsplit
     check("123".split(re"", maxsplit = 2) == @["1", "23"])
     check("123".split(re"", maxsplit = 1) == @["123"])
     check("123".split(re"", maxsplit = -1) == @["1", "2", "3"])
 
-  test "split with 0-length match":
+  block: # split with 0-length match
     check("12345".split(re("")) == @["1", "2", "3", "4", "5"])
     check("".split(re"") == newSeq[string]())
     check("word word".split(re"\b") == @["word", " ", "word"])
     check("word\r\lword".split(re"(*ANYCRLF)(?m)$") == @["word", "\r\lword"])
     check("слово слово".split(re"(*U)(\b)") == @["", "слово", "", " ", "", "слово", ""])
 
-  test "perl split tests":
+  block: # perl split tests
     check("forty-two"                    .split(re"")      .join(",") == "f,o,r,t,y,-,t,w,o")
     check("forty-two"                    .split(re"", 3)   .join(",") == "f,o,rty-two")
     check("split this string"            .split(re" ")     .join(",") == "split,this,string")
@@ -47,7 +47,7 @@ suite "string splitting":
     check(""                             .split(re"")      .len       == 0)
     check(":"                            .split(re"")      .len       == 1)
 
-  test "start position":
+  block: # start position
     check("abc".split(re"", start = 1) == @["b", "c"])
     check("abc".split(re"", start = 2) == @["c"])
     check("abc".split(re"", start = 3) == newSeq[string]())
diff --git a/tests/stdlib/t10231.nim b/tests/stdlib/t10231.nim
index 2bb64b475..3d09721aa 100644
--- a/tests/stdlib/t10231.nim
+++ b/tests/stdlib/t10231.nim
@@ -1,10 +1,11 @@
 discard """
-  target: cpp
+  targets: "cpp"
   action: run
   exitcode: 0
 """
 
 import os
+import std/assertions
 
 # consider moving this inside tosproc (taking care that it's for cpp mode)
 
diff --git a/tests/stdlib/t14139.nim b/tests/stdlib/t14139.nim
new file mode 100644
index 000000000..866bdb45f
--- /dev/null
+++ b/tests/stdlib/t14139.nim
@@ -0,0 +1,10 @@
+import std/heapqueue
+import std/assertions
+
+var test_queue : HeapQueue[int]
+
+test_queue.push(7)
+test_queue.push(3)
+test_queue.push(9)
+let i = test_queue.pushpop(10)
+doAssert i == 3
diff --git a/tests/stdlib/t15663.nim b/tests/stdlib/t15663.nim
new file mode 100644
index 000000000..8e8bfd9a8
--- /dev/null
+++ b/tests/stdlib/t15663.nim
@@ -0,0 +1,9 @@
+discard """
+  cmd: "nim c --gc:arc $file"
+  output: "Test"
+"""
+
+import std/widestrs
+
+let ws = newWideCString("Test")
+echo ws
diff --git a/tests/stdlib/t19304.nim b/tests/stdlib/t19304.nim
new file mode 100644
index 000000000..5e8795ac5
--- /dev/null
+++ b/tests/stdlib/t19304.nim
@@ -0,0 +1,7 @@
+import times
+
+type DjangoDateTime* = distinct DateTime
+
+# proc toTime*(x: DjangoDateTime): Time  {.borrow.} # <-- works
+proc format*(x: DjangoDateTime, f: TimeFormat,
+    loc: DateTimeLocale = DefaultLocale): string {.borrow.}
diff --git a/tests/stdlib/t20023.nim b/tests/stdlib/t20023.nim
new file mode 100644
index 000000000..8f12f8993
--- /dev/null
+++ b/tests/stdlib/t20023.nim
@@ -0,0 +1,10 @@
+import std/[tables, hashes, assertions]
+
+
+let t = ()
+var a = toTable({t:t})
+del(a,t)
+let b = default(typeof(a))
+
+doAssert a==b , "tables are not equal"
+doAssert hash(a) == hash(b), "table hashes are not equal"
diff --git a/tests/stdlib/t21251.nim b/tests/stdlib/t21251.nim
new file mode 100644
index 000000000..4402e9b7e
--- /dev/null
+++ b/tests/stdlib/t21251.nim
@@ -0,0 +1,6 @@
+import std / [tables, sets, sharedtables]
+
+var shared: SharedTable[int, int]
+shared.init
+
+shared[1] = 1
diff --git a/tests/stdlib/t21406.nim b/tests/stdlib/t21406.nim
new file mode 100644
index 000000000..86bf7b0c7
--- /dev/null
+++ b/tests/stdlib/t21406.nim
@@ -0,0 +1,7 @@
+import std/[times, strformat]
+import std/assertions
+
+let aTime = getTime()
+doAssert fmt"{aTime}" == $aTime
+let aNow = now()
+doAssert fmt"{aNow}" == $aNow
diff --git a/tests/stdlib/t21564.nim b/tests/stdlib/t21564.nim
new file mode 100644
index 000000000..0a5777d12
--- /dev/null
+++ b/tests/stdlib/t21564.nim
@@ -0,0 +1,32 @@
+discard """
+targets: "c js"
+"""
+
+import bitops
+import std/assertions
+
+proc main() =
+  block: # bug #21564
+    # tesk `bitops.bitsliced` patch
+    doAssert(0x17.bitsliced(4..7) == 0x01)
+    doAssert(0x17.bitsliced(0..3) == 0x07)
+
+  block:
+    # test in-place `bitops.bitslice`
+    var t = 0x12F4
+    t.bitslice(4..7)
+
+    doAssert(t == 0xF)
+
+  block:
+    # test `bitops.toMask` patch via bitops.masked
+    doAssert(0x12FFFF34.masked(8..23) == 0x00FFFF00)
+
+  block: # bug #22687
+    var a: uint8 = 0b1111_1111
+    doAssert a.bitsliced(4..7).int == 15
+
+main()
+
+static:
+  main()
diff --git a/tests/stdlib/t7686.nim b/tests/stdlib/t7686.nim
new file mode 100644
index 000000000..9902cfcb5
--- /dev/null
+++ b/tests/stdlib/t7686.nim
@@ -0,0 +1,10 @@
+import std/strutils
+import std/assertions
+
+type
+  MyEnum = enum
+    A,
+    a
+
+doAssert parseEnum[MyEnum]("A") == A
+doAssert parseEnum[MyEnum]("a") == a
diff --git a/tests/stdlib/t8925.nim b/tests/stdlib/t8925.nim
index dbf55fd88..c55e93e73 100644
--- a/tests/stdlib/t8925.nim
+++ b/tests/stdlib/t8925.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "type mismatch between pattern '$i' (position: 1) and HourRange var 'hour'"
+  errormsg: "type mismatch between pattern '$$i' (position: 1) and HourRange var 'hour'"
   file: "strscans.nim"
 """
 
diff --git a/tests/stdlib/t9754.nim b/tests/stdlib/t9754.nim
new file mode 100644
index 000000000..971b5a8fb
--- /dev/null
+++ b/tests/stdlib/t9754.nim
@@ -0,0 +1,6 @@
+discard """
+  joinable: false
+"""
+
+import tmarshal
+import tparsesql
\ No newline at end of file
diff --git a/tests/stdlib/talgorithm.nim b/tests/stdlib/talgorithm.nim
new file mode 100644
index 000000000..e2024df0c
--- /dev/null
+++ b/tests/stdlib/talgorithm.nim
@@ -0,0 +1,275 @@
+discard """
+  targets: "c js"
+  matrix: "--mm:refc; --mm:orc"
+  output:'''@["3", "2", "1"]
+'''
+"""
+#12928,10456
+
+import std/[sequtils, algorithm, json, sugar]
+import std/assertions
+
+proc test() = 
+  try: 
+    let info = parseJson("""
+    {"a": ["1", "2", "3"]}
+    """)
+    let prefixes = info["a"].getElems().mapIt(it.getStr()).sortedByIt(it).reversed()
+    echo prefixes
+  except:
+    discard
+
+test()
+
+block:
+  # Tests for lowerBound
+  var arr = @[1, 2, 3, 5, 6, 7, 8, 9]
+  doAssert arr.lowerBound(0) == 0
+  doAssert arr.lowerBound(4) == 3
+  doAssert arr.lowerBound(5) == 3
+  doAssert arr.lowerBound(10) == 8
+  arr = @[1, 5, 10]
+  doAssert arr.lowerBound(4) == 1
+  doAssert arr.lowerBound(5) == 1
+  doAssert arr.lowerBound(6) == 2
+  # Tests for isSorted
+  var srt1 = [1, 2, 3, 4, 4, 4, 4, 5]
+  var srt2 = ["iello", "hello"]
+  var srt3 = [1.0, 1.0, 1.0]
+  var srt4: seq[int]
+  doAssert srt1.isSorted(cmp) == true
+  doAssert srt2.isSorted(cmp) == false
+  doAssert srt3.isSorted(cmp) == true
+  doAssert srt4.isSorted(cmp) == true
+  var srtseq = newSeq[int]()
+  doAssert srtseq.isSorted(cmp) == true
+  # Tests for reversed
+  var arr1 = @[0, 1, 2, 3, 4]
+  doAssert arr1.reversed() == @[4, 3, 2, 1, 0]
+  for i in 0 .. high(arr1):
+    doAssert arr1.reversed(0, i) == arr1.reversed()[high(arr1) - i .. high(arr1)]
+    doAssert arr1.reversed(i, high(arr1)) == arr1.reversed()[0 .. high(arr1) - i]
+
+block:
+  var list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
+  let list2 = list.rotatedLeft(1 ..< 9, 3)
+  let expected = [0, 4, 5, 6, 7, 8, 1, 2, 3, 9, 10]
+
+  doAssert list.rotateLeft(1 ..< 9, 3) == 6
+  doAssert list == expected
+  doAssert list2 == @expected
+
+  var s0, s1, s2, s3, s4, s5 = "xxxabcdefgxxx"
+
+  doAssert s0.rotateLeft(3 ..< 10, 3) == 7
+  doAssert s0 == "xxxdefgabcxxx"
+  doAssert s1.rotateLeft(3 ..< 10, 2) == 8
+  doAssert s1 == "xxxcdefgabxxx"
+  doAssert s2.rotateLeft(3 ..< 10, 4) == 6
+  doAssert s2 == "xxxefgabcdxxx"
+  doAssert s3.rotateLeft(3 ..< 10, -3) == 6
+  doAssert s3 == "xxxefgabcdxxx"
+  doAssert s4.rotateLeft(3 ..< 10, -10) == 6
+  doAssert s4 == "xxxefgabcdxxx"
+  doAssert s5.rotateLeft(3 ..< 10, 11) == 6
+  doAssert s5 == "xxxefgabcdxxx"
+
+  block product:
+    doAssert product(newSeq[seq[int]]()) == newSeq[seq[int]](), "empty input"
+    doAssert product(@[newSeq[int](), @[], @[]]) == newSeq[seq[int]](), "bit more empty input"
+    doAssert product(@[@[1, 2]]) == @[@[1, 2]], "a simple case of one element"
+    doAssert product(@[@[1, 2], @[3, 4]]) == @[@[2, 4], @[1, 4], @[2, 3], @[1,
+        3]], "two elements"
+    doAssert product(@[@[1, 2], @[3, 4], @[5, 6]]) == @[@[2, 4, 6], @[1, 4, 6],
+        @[2, 3, 6], @[1, 3, 6], @[2, 4, 5], @[1, 4, 5], @[2, 3, 5], @[1, 3, 5]], "three elements"
+    doAssert product(@[@[1, 2], @[]]) == newSeq[seq[int]](), "two elements, but one empty"
+
+  block lowerBound:
+    doAssert lowerBound([1, 2, 4], 3, system.cmp[int]) == 2
+    doAssert lowerBound([1, 2, 2, 3], 4, system.cmp[int]) == 4
+    doAssert lowerBound([1, 2, 3, 10], 11) == 4
+
+  block upperBound:
+    doAssert upperBound([1, 2, 4], 3, system.cmp[int]) == 2
+    doAssert upperBound([1, 2, 2, 3], 3, system.cmp[int]) == 4
+    doAssert upperBound([1, 2, 3, 5], 3) == 3
+
+  block fillEmptySeq:
+    var s = newSeq[int]()
+    s.fill(0)
+
+  block testBinarySearch:
+    var noData: seq[int]
+    doAssert binarySearch(noData, 7) == -1
+    let oneData = @[1]
+    doAssert binarySearch(oneData, 1) == 0
+    doAssert binarySearch(oneData, 7) == -1
+    let someData = @[1, 3, 4, 7]
+    doAssert binarySearch(someData, 1) == 0
+    doAssert binarySearch(someData, 7) == 3
+    doAssert binarySearch(someData, -1) == -1
+    doAssert binarySearch(someData, 5) == -1
+    doAssert binarySearch(someData, 13) == -1
+    let moreData = @[1, 3, 5, 7, 4711]
+    doAssert binarySearch(moreData, -1) == -1
+    doAssert binarySearch(moreData, 1) == 0
+    doAssert binarySearch(moreData, 5) == 2
+    doAssert binarySearch(moreData, 6) == -1
+    doAssert binarySearch(moreData, 4711) == 4
+    doAssert binarySearch(moreData, 4712) == -1
+
+# merge
+proc main() =
+  block:
+    var x = @[1, 7, 8, 11, 21, 33, 45, 99]
+    var y = @[6, 7, 9, 12, 57, 66]
+
+    var merged: seq[int]
+    merged.merge(x, y)
+    doAssert merged.isSorted
+    doAssert merged == sorted(x & y)
+
+  block:
+    var x = @[111, 88, 76, 56, 45, 31, 22, 19, 11, 3]
+    var y = @[99, 85, 83, 82, 69, 64, 48, 42, 33, 31, 26, 13]
+
+    var merged: seq[int]
+    merged.merge(x, y, (x, y) => -system.cmp(x, y))
+    doAssert merged.isSorted((x, y) => -system.cmp(x, y))
+    doAssert merged == sorted(x & y, SortOrder.Descending)
+
+  block:
+    var x: seq[int] = @[]
+    var y = @[1]
+
+    var merged: seq[int]
+    merged.merge(x, y)
+    doAssert merged.isSorted
+    doAssert merged.isSorted(SortOrder.Descending)
+    doAssert merged == @[1]
+
+  block:
+    var x = [1, 3, 5, 5, 7]
+    var y: seq[int] = @[]
+
+    var merged: seq[int]
+    merged.merge(x, y)
+    doAssert merged.isSorted
+    doAssert merged == @x
+
+  block:
+    var x = [1, 3, 5, 5, 7]
+    var y: seq[int] = @[]
+
+    var merged: seq[int] = @[1, 2, 3, 5, 6, 56, 99, 2, 34]
+    merged.merge(x, y)
+    doAssert merged == @[1, 2, 3, 5, 6, 56, 99, 2, 34, 1, 3, 5, 5, 7]
+
+
+  block:
+    var x: array[0, int]
+    var y = [1, 4, 6, 7, 9]
+
+    var merged: seq[int]
+    merged.merge(x, y)
+    doAssert merged.isSorted
+    doAssert merged == @y
+
+  block:
+    var x: array[0, int]
+    var y: array[0, int]
+
+    var merged: seq[int]
+    merged.merge(x, y)
+    doAssert merged.isSorted
+    doAssert merged.len == 0
+
+  block:
+    var x: array[0, int]
+    var y: array[0, int]
+
+    var merged: seq[int] = @[99, 99, 99]
+    merged.setLen(0)
+    merged.merge(x, y)
+    doAssert merged.isSorted
+    doAssert merged.len == 0
+
+  block:
+    var x: seq[int]
+    var y: seq[int]
+
+    var merged: seq[int]
+    merged.merge(x, y)
+    doAssert merged.isSorted
+    doAssert merged.len == 0
+
+  block:
+    type
+      Record = object
+        id: int
+    
+    proc r(id: int): Record =
+      Record(id: id)
+
+    proc cmp(x, y: Record): int =
+      if x.id == y.id: return 0
+      if x.id < y.id: return -1
+      result = 1
+
+    var x = @[r(-12), r(1), r(3), r(8), r(13), r(88)]
+    var y = @[r(4), r(7), r(12), r(13), r(77), r(99)]
+
+    var merged: seq[Record] = @[]
+    merged.merge(x, y, cmp)
+    doAssert merged.isSorted(cmp)
+    doAssert merged.len == 12
+
+  block:
+    type
+      Record = object
+        id: int
+    
+    proc r(id: int): Record =
+      Record(id: id)
+
+    proc ascendingCmp(x, y: Record): int =
+      if x.id == y.id: return 0
+      if x.id < y.id: return -1
+      result = 1
+
+    proc descendingCmp(x, y: Record): int =
+      if x.id == y.id: return 0
+      if x.id < y.id: return 1
+      result = -1
+
+    var x = @[r(-12), r(1), r(3), r(8), r(13), r(88)]
+    var y = @[r(4), r(7), r(12), r(13), r(77), r(99)]
+
+    var merged: seq[Record]
+    merged.setLen(0)
+    merged.merge(x, y, ascendingCmp)
+    doAssert merged.isSorted(ascendingCmp)
+    doAssert merged == sorted(x & y, ascendingCmp)
+
+    reverse(x)
+    reverse(y)
+
+    merged.setLen(0)
+    merged.merge(x, y, descendingCmp)
+    doAssert merged.isSorted(descendingCmp)
+    doAssert merged == sorted(x & y, ascendingCmp, SortOrder.Descending)
+
+    reverse(x)
+    reverse(y)
+    merged.setLen(0)
+    merged.merge(x, y, proc (x, y: Record): int = -descendingCmp(x, y))
+    doAssert merged.isSorted(proc (x, y: Record): int = -descendingCmp(x, y))
+    doAssert merged == sorted(x & y, ascendingCmp)
+
+
+  var x: seq[(int, int)]
+  x.merge([(1,1)], [(1,2)], (a,b) => a[0] - b[0])
+  doAssert x == @[(1, 1), (1, 2)]
+
+static: main()
+main()
diff --git a/tests/stdlib/tarithmetics.nim b/tests/stdlib/tarithmetics.nim
new file mode 100644
index 000000000..0a6dd1fcf
--- /dev/null
+++ b/tests/stdlib/tarithmetics.nim
@@ -0,0 +1,50 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+import std/assertions
+# TODO: in future work move existing arithmetic tests (tests/arithm/*) into this file
+# FYI https://github.com/nim-lang/Nim/pull/17767
+
+template main =
+  # put all arithmetic tests
+
+  block tshr:
+    block: # Signed types
+      let
+        a1 = -3
+        a2 = -2
+        b1 = -4'i8
+        b2 = 1'i8
+        c1 = -5'i16
+        c2 = 1'i16
+        d1 = -7i32
+        d2 = 1'i32
+        e1 = -9'i64
+        e2 = 1'i64
+      doAssert a1 shr a2 == -1
+      doAssert b1 shr b2 == -2
+      doAssert c1 shr c2 == -3
+      doAssert d1 shr d2 == -4
+      doAssert e1 shr e2 == -5
+
+    block: # Unsigned types
+      let
+        a1 = 3'u
+        a2 = 2'u
+        b1 = 2'u8
+        b2 = 1'u8
+        c1 = 5'u16
+        c2 = 1'u16
+        d1 = 6'u32
+        d2 = 1'u32
+        e1 = 8'u64
+        e2 = 1'u64
+      doAssert a1 shr a2 == 0
+      doAssert b1 shr b2 == 1
+      doAssert c1 shr c2 == 2
+      doAssert d1 shr d2 == 3
+      doAssert e1 shr e2 == 4
+
+static: main()
+main()
diff --git a/tests/stdlib/tasynchttpserver.nim b/tests/stdlib/tasynchttpserver.nim
new file mode 100644
index 000000000..5a7e2da40
--- /dev/null
+++ b/tests/stdlib/tasynchttpserver.nim
@@ -0,0 +1,121 @@
+discard """
+  cmd: "nim c --threads:on $file"
+  exitcode: 0
+  output: "OK"
+  disabled: false
+"""
+
+import strutils
+from net import TimeoutError
+import std/assertions
+
+import httpclient, asynchttpserver, asyncdispatch, asyncfutures
+
+template runTest(
+    handler: proc (request: Request): Future[void] {.gcsafe.},
+    request: proc (server: AsyncHttpServer): Future[AsyncResponse],
+    test: proc (response: AsyncResponse, body: string): Future[void]) =
+
+  let server = newAsyncHttpServer()
+
+  discard server.serve(Port(64123), handler)
+
+  let
+    response = waitFor(request(server))
+    body = waitFor(response.body)
+
+  discard test(response, body)
+
+proc test200() {.async.} =
+  proc handler(request: Request) {.async.} =
+    await request.respond(Http200, "Hello World, 200")
+
+  proc request(server: AsyncHttpServer): Future[AsyncResponse] {.async.} =
+    let
+      client = newAsyncHttpClient()
+      clientResponse = await client.request("http://localhost:64123/")
+
+    server.close()
+
+    return clientResponse
+
+  proc test(response: AsyncResponse, body: string) {.async.} =
+    doAssert(response.status == $Http200)
+    doAssert(body == "Hello World, 200")
+    doAssert(response.headers.hasKey("Content-Length"))
+    doAssert(response.headers["Content-Length"] == "16")
+
+  runTest(handler, request, test)
+
+proc test404() {.async.} =
+  proc handler(request: Request) {.async.} =
+    await request.respond(Http404, "Hello World, 404")
+
+  proc request(server: AsyncHttpServer): Future[AsyncResponse] {.async.} =
+    let
+      client = newAsyncHttpClient()
+      clientResponse = await client.request("http://localhost:64123/")
+
+    server.close()
+
+    return clientResponse
+
+  proc test(response: AsyncResponse, body: string) {.async.} =
+    doAssert(response.status == $Http404)
+    doAssert(body == "Hello World, 404")
+    doAssert(response.headers.hasKey("Content-Length"))
+    doAssert(response.headers["Content-Length"] == "16")
+
+  runTest(handler, request, test)
+
+proc testCustomEmptyHeaders() {.async.} =
+  proc handler(request: Request) {.async.} =
+    await request.respond(Http200, "Hello World, 200", newHttpHeaders())
+
+  proc request(server: AsyncHttpServer): Future[AsyncResponse] {.async.} =
+    let
+      client = newAsyncHttpClient()
+      clientResponse = await client.request("http://localhost:64123/")
+
+    server.close()
+
+    return clientResponse
+
+  proc test(response: AsyncResponse, body: string) {.async.} =
+    doAssert(response.status == $Http200)
+    doAssert(body == "Hello World, 200")
+    doAssert(response.headers.hasKey("Content-Length"))
+    doAssert(response.headers["Content-Length"] == "16")
+
+  runTest(handler, request, test)
+
+proc testCustomContentLength() {.async.} =
+  proc handler(request: Request) {.async.} =
+    let headers = newHttpHeaders()
+    headers["Content-Length"] = "0"
+    await request.respond(Http200, "Hello World, 200", headers)
+
+  proc request(server: AsyncHttpServer): Future[AsyncResponse] {.async.} =
+    let
+      client = newAsyncHttpClient()
+      clientResponse = await client.request("http://localhost:64123/")
+
+    server.close()
+
+    return clientResponse
+
+  proc test(response: AsyncResponse, body: string) {.async.} =
+    doAssert(response.status == $Http200)
+    doAssert(body == "")
+    doAssert(response.headers.hasKey("Content-Length"))
+    doAssert(response.headers["Content-Length"] == "0")
+    doAssert contentLength(response) == 0 # bug #22778
+
+  runTest(handler, request, test)
+
+waitFor(test200())
+waitFor(test404())
+waitFor(testCustomEmptyHeaders())
+waitFor(testCustomContentLength())
+
+echo "OK"
diff --git a/tests/stdlib/tasynchttpserver_transferencoding.nim b/tests/stdlib/tasynchttpserver_transferencoding.nim
new file mode 100644
index 000000000..886ba0f33
--- /dev/null
+++ b/tests/stdlib/tasynchttpserver_transferencoding.nim
@@ -0,0 +1,91 @@
+discard """
+  matrix: "--mm:arc; --mm:arc -d:danger; --mm:refc"
+  disabled: "freebsd"
+"""
+
+import httpclient, asynchttpserver, asyncdispatch, asyncfutures
+import net
+
+import std/asyncnet
+import std/nativesockets
+import std/assertions
+
+const postBegin = """
+POST / HTTP/1.1
+Transfer-Encoding:chunked
+
+"""
+
+template genTest(input, expected: string) =
+  proc handler(request: Request, future: Future[bool]) {.async, gcsafe.} =
+    doAssert(request.body == expected)
+    doAssert(request.headers.hasKey("Transfer-Encoding"))
+    doAssert(not request.headers.hasKey("Content-Length"))
+    future.complete(true)
+    await request.respond(Http200, "Good")
+
+  proc sendData(data: string, port: Port) {.async.} =
+    var socket = newSocket()
+    defer: socket.close()
+
+    socket.connect("127.0.0.1", port)
+    socket.send(data)
+
+  proc runTest(): Future[bool] {.async.} =
+    var handlerFuture = newFuture[bool]("runTest")
+    let data = postBegin & input
+    let server = newAsyncHttpServer()
+    server.listen(Port(0))
+
+    proc wrapper(request: Request): Future[void] {.gcsafe, closure.} =
+      handler(request, handlerFuture)
+    
+    asyncCheck sendData(data, server.getPort)
+    asyncCheck server.acceptRequest(wrapper)
+    doAssert await handlerFuture
+    
+    server.close()
+    return true
+
+  doAssert waitFor runTest()
+
+block:
+  const expected = "hello=world"
+  const input = ("b\r\n" &
+                 "hello=world\r\n" &
+                 "0\r\n" &
+                 "\r\n")
+  genTest(input, expected)
+block:
+  const expected = "hello encoding"
+  const input = ("e\r\n" &
+                 "hello encoding\r\n" &
+                 "0\r\n" &
+                 "\r\n")
+  genTest(input, expected)
+block:
+  # https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Transfer-Encoding
+  const expected = "MozillaDeveloperNetwork"
+  const input = ("7\r\n" &
+                "Mozilla\r\n" &
+                "9\r\n" &
+                "Developer\r\n" &
+                "7\r\n" &
+                "Network\r\n" &
+                "0\r\n" &
+                "\r\n")
+  genTest(input, expected)
+block:
+  # https://en.wikipedia.org/wiki/Chunked_transfer_encoding#Example
+  const expected = "Wikipedia in \r\n\r\nchunks."
+  const input = ("4\r\n" &
+                "Wiki\r\n" &
+                "6\r\n" &
+                "pedia \r\n" &
+                "E\r\n" &
+                "in \r\n" &
+                "\r\n" &
+                "chunks.\r\n" &
+                "0\r\n" &
+                "\r\n")
+  genTest(input, expected)
diff --git a/tests/stdlib/tbase64.nim b/tests/stdlib/tbase64.nim
index 9db6e8802..c3bfb818e 100644
--- a/tests/stdlib/tbase64.nim
+++ b/tests/stdlib/tbase64.nim
@@ -1,9 +1,12 @@
 discard """
-  output: "OK"
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
 """
-import base64
+import std/assertions
+import std/base64
 
-proc main() =
+template main() =
+  doAssert encode("a") == "YQ=="
   doAssert encode("Hello World") == "SGVsbG8gV29ybGQ="
   doAssert encode("leasure.") == "bGVhc3VyZS4="
   doAssert encode("easure.") == "ZWFzdXJlLg=="
@@ -15,6 +18,8 @@ proc main() =
   doAssert encode("") == ""
   doAssert decode("") == ""
 
+  doAssert decode(" ") == ""
+
   const testInputExpandsTo76 = "+++++++++++++++++++++++++++++++++++++++++++++++++++++++++"
   const testInputExpands = "++++++++++++++++++++++++++++++"
   const longText = """Man is distinguished, not only by his reason, but by this
@@ -25,20 +30,34 @@ proc main() =
   const tests = ["", "abc", "xyz", "man", "leasure.", "sure.", "easure.",
                  "asure.", longText, testInputExpandsTo76, testInputExpands]
 
-  doAssert encodeMIME("foobarbaz", lineLen=4) == "Zm9v\r\nYmFy\r\nYmF6"
+  doAssert encodeMime("foobarbaz", lineLen=4) == "Zm9v\r\nYmFy\r\nYmF6"
   doAssert decode("Zm9v\r\nYmFy\r\nYmF6") == "foobarbaz"
 
   for t in items(tests):
     doAssert decode(encode(t)) == t
-    doAssert decode(encodeMIME(t, lineLen=40)) == t
-    doAssert decode(encodeMIME(t, lineLen=76)) == t
-
-  const invalid = "SGVsbG\x008gV29ybGQ="
-  try:
-    doAssert decode(invalid) == "will throw error"
-  except ValueError:
-    discard
-
-  echo "OK"
-
+    doAssert decode(encodeMime(t, lineLen=40)) == t
+    doAssert decode(encodeMime(t, lineLen=76)) == t
+
+  doAssertRaises(ValueError): discard decode("SGVsbG\x008gV29ybGQ=")
+
+  block base64urlSafe:
+    doAssert encode("c\xf7>", safe = true) == "Y_c-"
+    doAssert encode("c\xf7>", safe = false) == "Y/c+" # Not a nice URL :(
+    doAssert decode("Y/c+") == decode("Y_c-")
+    # Output must not change with safe=true
+    doAssert encode("Hello World", safe = true) == "SGVsbG8gV29ybGQ="
+    doAssert encode("leasure.", safe = true)  == "bGVhc3VyZS4="
+    doAssert encode("easure.", safe = true) == "ZWFzdXJlLg=="
+    doAssert encode("asure.", safe = true) == "YXN1cmUu"
+    doAssert encode("sure.", safe = true) == "c3VyZS4="
+    doAssert encode([1,2,3], safe = true) == "AQID"
+    doAssert encode(['h','e','y'], safe = true) == "aGV5"
+    doAssert encode("", safe = true) == ""
+    doAssert encode("the quick brown dog jumps over the lazy fox", safe = true) == "dGhlIHF1aWNrIGJyb3duIGRvZyBqdW1wcyBvdmVyIHRoZSBsYXp5IGZveA=="
+
+func mainNoSideEffects() = main()
+
+static: main()
 main()
+static: mainNoSideEffects()
+mainNoSideEffects()
diff --git a/tests/stdlib/tbitops.nim b/tests/stdlib/tbitops.nim
index e4461345e..3ecab2c64 100644
--- a/tests/stdlib/tbitops.nim
+++ b/tests/stdlib/tbitops.nim
@@ -1,8 +1,12 @@
 discard """
   nimout: "OK"
-  output: "OK"
+  matrix: "--mm:refc; --mm:orc"
+  output: '''
+OK
+'''
 """
 import bitops
+import std/assertions
 
 proc main() =
   const U8 = 0b0011_0010'u8
@@ -15,115 +19,123 @@ proc main() =
   const I64A = 0b01000100_00111111_01111100_10001010_10011001_01001000_01111010_00010001'i64
   const U64B = 0b00110010_11011101_10001111_00101000_00000000_00000000_00000000_00000000'u64
   const I64B = 0b00110010_11011101_10001111_00101000_00000000_00000000_00000000_00000000'i64
+  const U64C = 0b00101010_11110101_10001111_00101000_00000100_00000000_00000100_00000000'u64
+  const I64C = 0b00101010_11110101_10001111_00101000_00000100_00000000_00000100_00000000'i64
 
-  doAssert( (U8 and U8) == bitand(U8,U8) )
-  doAssert( (I8 and I8) == bitand(I8,I8) )
-  doAssert( (U16 and U16) == bitand(U16,U16) )
-  doAssert( (I16 and I16) == bitand(I16,I16) )
-  doAssert( (U32 and U32) == bitand(U32,U32) )
-  doAssert( (I32 and I32) == bitand(I32,I32) )
-  doAssert( (U64A and U64B) == bitand(U64A,U64B) )
-  doAssert( (I64A and I64B) == bitand(I64A,I64B) )
-
-  doAssert( (U8 or U8) == bitor(U8,U8) )
-  doAssert( (I8 or I8) == bitor(I8,I8) )
-  doAssert( (U16 or U16) == bitor(U16,U16) )
-  doAssert( (I16 or I16) == bitor(I16,I16) )
-  doAssert( (U32 or U32) == bitor(U32,U32) )
-  doAssert( (I32 or I32) == bitor(I32,I32) )
-  doAssert( (U64A or U64B) == bitor(U64A,U64B) )
-  doAssert( (I64A or I64B) == bitor(I64A,I64B) )
-
-  doAssert( (U8 xor U8) == bitxor(U8,U8) )
-  doAssert( (I8 xor I8) == bitxor(I8,I8) )
-  doAssert( (U16 xor U16) == bitxor(U16,U16) )
-  doAssert( (I16 xor I16) == bitxor(I16,I16) )
-  doAssert( (U32 xor U32) == bitxor(U32,U32) )
-  doAssert( (I32 xor I32) == bitxor(I32,I32) )
-  doAssert( (U64A xor U64B) == bitxor(U64A,U64B) )
-  doAssert( (I64A xor I64B) == bitxor(I64A,I64B) )
-
-  doAssert( not(U8) == bitnot(U8) )
-  doAssert( not(I8) == bitnot(I8) )
-  doAssert( not(U16) == bitnot(U16) )
-  doAssert( not(I16) == bitnot(I16) )
-  doAssert( not(U32) == bitnot(U32) )
-  doAssert( not(I32) == bitnot(I32) )
-  doAssert( not(U64A) == bitnot(U64A) )
-  doAssert( not(I64A) == bitnot(I64A) )
-
-  doAssert( U64A.fastLog2 == 62)
-  doAssert( I64A.fastLog2 == 62)
-  doAssert( U64A.countLeadingZeroBits == 1)
-  doAssert( I64A.countLeadingZeroBits == 1)
-  doAssert( U64A.countTrailingZeroBits == 0)
-  doAssert( I64A.countTrailingZeroBits == 0)
-  doAssert( U64A.firstSetBit == 1)
-  doAssert( I64A.firstSetBit == 1)
-  doAssert( U64A.parityBits == 1)
-  doAssert( I64A.parityBits == 1)
-  doAssert( U64A.countSetBits == 29)
-  doAssert( I64A.countSetBits == 29)
-  doAssert( U64A.rotateLeftBits(37) == 0b00101001_00001111_01000010_00101000_10000111_11101111_10010001_01010011'u64)
-  doAssert( U64A.rotateRightBits(37) == 0b01010100_11001010_01000011_11010000_10001010_00100001_11111011_11100100'u64)
-
-  doAssert( U64B.firstSetBit == 36)
-  doAssert( I64B.firstSetBit == 36)
-
-  doAssert( U32.fastLog2 == 31)
-  doAssert( I32.fastLog2 == 31)
-  doAssert( U32.countLeadingZeroBits == 0)
-  doAssert( I32.countLeadingZeroBits == 0)
-  doAssert( U32.countTrailingZeroBits == 4)
-  doAssert( I32.countTrailingZeroBits == 4)
-  doAssert( U32.firstSetBit == 5)
-  doAssert( I32.firstSetBit == 5)
-  doAssert( U32.parityBits == 0)
-  doAssert( I32.parityBits == 0)
-  doAssert( U32.countSetBits == 16)
-  doAssert( I32.countSetBits == 16)
-  doAssert( U32.rotateLeftBits(21) == 0b01001010_00011010_10110011_10011011'u32)
-  doAssert( U32.rotateRightBits(21) == 0b11100110_11010010_10000110_10101100'u32)
-
-  doAssert( U16.fastLog2 == 13)
-  doAssert( I16.fastLog2 == 13)
-  doAssert( U16.countLeadingZeroBits == 2)
-  doAssert( I16.countLeadingZeroBits == 2)
-  doAssert( U16.countTrailingZeroBits == 3)
-  doAssert( I16.countTrailingZeroBits == 3)
-  doAssert( U16.firstSetBit == 4)
-  doAssert( I16.firstSetBit == 4)
-  doAssert( U16.parityBits == 0)
-  doAssert( I16.parityBits == 0)
-  doAssert( U16.countSetBits == 6)
-  doAssert( I16.countSetBits == 6)
-  doAssert( U16.rotateLeftBits(12) == 0b10000010_01110010'u16)
-  doAssert( U16.rotateRightBits(12) == 0b01110010_10000010'u16)
-
-  doAssert( U8.fastLog2 == 5)
-  doAssert( I8.fastLog2 == 5)
-  doAssert( U8.countLeadingZeroBits == 2)
-  doAssert( I8.countLeadingZeroBits == 2)
-  doAssert( U8.countTrailingZeroBits == 1)
-  doAssert( I8.countTrailingZeroBits == 1)
-  doAssert( U8.firstSetBit == 2)
-  doAssert( I8.firstSetBit == 2)
-  doAssert( U8.parityBits == 1)
-  doAssert( I8.parityBits == 1)
-  doAssert( U8.countSetBits == 3)
-  doAssert( I8.countSetBits == 3)
-  doAssert( U8.rotateLeftBits(3) == 0b10010001'u8)
-  doAssert( U8.rotateRightBits(3) == 0b0100_0110'u8)
+  doAssert (U8 and U8) == bitand(U8,U8)
+  doAssert (I8 and I8) == bitand(I8,I8)
+  doAssert (U16 and U16) == bitand(U16,U16)
+  doAssert (I16 and I16) == bitand(I16,I16)
+  doAssert (U32 and U32) == bitand(U32,U32)
+  doAssert (I32 and I32) == bitand(I32,I32)
+  doAssert (U64A and U64B) == bitand(U64A,U64B)
+  doAssert (I64A and I64B) == bitand(I64A,I64B)
+  doAssert (U64A and U64B and U64C) == bitand(U64A,U64B,U64C)
+  doAssert (I64A and I64B and I64C) == bitand(I64A,I64B,I64C)
+
+  doAssert (U8 or U8) == bitor(U8,U8)
+  doAssert (I8 or I8) == bitor(I8,I8)
+  doAssert (U16 or U16) == bitor(U16,U16)
+  doAssert (I16 or I16) == bitor(I16,I16)
+  doAssert (U32 or U32) == bitor(U32,U32)
+  doAssert (I32 or I32) == bitor(I32,I32)
+  doAssert (U64A or U64B) == bitor(U64A,U64B)
+  doAssert (I64A or I64B) == bitor(I64A,I64B)
+  doAssert (U64A or U64B or U64C) == bitor(U64A,U64B,U64C)
+  doAssert (I64A or I64B or I64C) == bitor(I64A,I64B,I64C)
+
+  doAssert (U8 xor U8) == bitxor(U8,U8)
+  doAssert (I8 xor I8) == bitxor(I8,I8)
+  doAssert (U16 xor U16) == bitxor(U16,U16)
+  doAssert (I16 xor I16) == bitxor(I16,I16)
+  doAssert (U32 xor U32) == bitxor(U32,U32)
+  doAssert (I32 xor I32) == bitxor(I32,I32)
+  doAssert (U64A xor U64B) == bitxor(U64A,U64B)
+  doAssert (I64A xor I64B) == bitxor(I64A,I64B)
+  doAssert (U64A xor U64B xor U64C) == bitxor(U64A,U64B,U64C)
+  doAssert (I64A xor I64B xor I64C) == bitxor(I64A,I64B,I64C)
+
+  doAssert not(U8) == bitnot(U8)
+  doAssert not(I8) == bitnot(I8)
+  doAssert not(U16) == bitnot(U16)
+  doAssert not(I16) == bitnot(I16)
+  doAssert not(U32) == bitnot(U32)
+  doAssert not(I32) == bitnot(I32)
+  doAssert not(U64A) == bitnot(U64A)
+  doAssert not(I64A) == bitnot(I64A)
+
+  doAssert U64A.fastLog2 == 62
+  doAssert I64A.fastLog2 == 62
+  doAssert U64A.countLeadingZeroBits == 1
+  doAssert I64A.countLeadingZeroBits == 1
+  doAssert U64A.countTrailingZeroBits == 0
+  doAssert I64A.countTrailingZeroBits == 0
+  doAssert U64A.firstSetBit == 1
+  doAssert I64A.firstSetBit == 1
+  doAssert U64A.parityBits == 1
+  doAssert I64A.parityBits == 1
+  doAssert U64A.countSetBits == 29
+  doAssert I64A.countSetBits == 29
+  doAssert U64A.rotateLeftBits(37) == 0b00101001_00001111_01000010_00101000_10000111_11101111_10010001_01010011'u64
+  doAssert U64A.rotateRightBits(37) == 0b01010100_11001010_01000011_11010000_10001010_00100001_11111011_11100100'u64
+
+  doAssert U64B.firstSetBit == 36
+  doAssert I64B.firstSetBit == 36
+
+  doAssert U32.fastLog2 == 31
+  doAssert I32.fastLog2 == 31
+  doAssert U32.countLeadingZeroBits == 0
+  doAssert I32.countLeadingZeroBits == 0
+  doAssert U32.countTrailingZeroBits == 4
+  doAssert I32.countTrailingZeroBits == 4
+  doAssert U32.firstSetBit == 5
+  doAssert I32.firstSetBit == 5
+  doAssert U32.parityBits == 0
+  doAssert I32.parityBits == 0
+  doAssert U32.countSetBits == 16
+  doAssert I32.countSetBits == 16
+  doAssert U32.rotateLeftBits(21) == 0b01001010_00011010_10110011_10011011'u32
+  doAssert U32.rotateRightBits(21) == 0b11100110_11010010_10000110_10101100'u32
+
+  doAssert U16.fastLog2 == 13
+  doAssert I16.fastLog2 == 13
+  doAssert U16.countLeadingZeroBits == 2
+  doAssert I16.countLeadingZeroBits == 2
+  doAssert U16.countTrailingZeroBits == 3
+  doAssert I16.countTrailingZeroBits == 3
+  doAssert U16.firstSetBit == 4
+  doAssert I16.firstSetBit == 4
+  doAssert U16.parityBits == 0
+  doAssert I16.parityBits == 0
+  doAssert U16.countSetBits == 6
+  doAssert I16.countSetBits == 6
+  doAssert U16.rotateLeftBits(12) == 0b10000010_01110010'u16
+  doAssert U16.rotateRightBits(12) == 0b01110010_10000010'u16
+
+  doAssert U8.fastLog2 == 5
+  doAssert I8.fastLog2 == 5
+  doAssert U8.countLeadingZeroBits == 2
+  doAssert I8.countLeadingZeroBits == 2
+  doAssert U8.countTrailingZeroBits == 1
+  doAssert I8.countTrailingZeroBits == 1
+  doAssert U8.firstSetBit == 2
+  doAssert I8.firstSetBit == 2
+  doAssert U8.parityBits == 1
+  doAssert I8.parityBits == 1
+  doAssert U8.countSetBits == 3
+  doAssert I8.countSetBits == 3
+  doAssert U8.rotateLeftBits(3) == 0b10010001'u8
+  doAssert U8.rotateRightBits(3) == 0b0100_0110'u8
 
   template test_undefined_impl(ffunc: untyped; expected: int; is_static: bool) =
-    doAssert( ffunc(0'u8) == expected)
-    doAssert( ffunc(0'i8) == expected)
-    doAssert( ffunc(0'u16) == expected)
-    doAssert( ffunc(0'i16) == expected)
-    doAssert( ffunc(0'u32) == expected)
-    doAssert( ffunc(0'i32) == expected)
-    doAssert( ffunc(0'u64) == expected)
-    doAssert( ffunc(0'i64) == expected)
+    doAssert ffunc(0'u8) == expected
+    doAssert ffunc(0'i8) == expected
+    doAssert ffunc(0'u16) == expected
+    doAssert ffunc(0'i16) == expected
+    doAssert ffunc(0'u32) == expected
+    doAssert ffunc(0'i32) == expected
+    doAssert ffunc(0'u64) == expected
+    doAssert ffunc(0'i64) == expected
 
   template test_undefined(ffunc: untyped; expected: int) =
     test_undefined_impl(ffunc, expected, false)
@@ -140,37 +152,106 @@ proc main() =
     test_undefined(fastLog2, -1)
 
     # check for undefined behavior with rotate by zero.
-    doAssert( U8.rotateLeftBits(0) == U8)
-    doAssert( U8.rotateRightBits(0) == U8)
-    doAssert( U16.rotateLeftBits(0) == U16)
-    doAssert( U16.rotateRightBits(0) == U16)
-    doAssert( U32.rotateLeftBits(0) == U32)
-    doAssert( U32.rotateRightBits(0) == U32)
-    doAssert( U64A.rotateLeftBits(0) == U64A)
-    doAssert( U64A.rotateRightBits(0) == U64A)
+    doAssert U8.rotateLeftBits(0) == U8
+    doAssert U8.rotateRightBits(0) == U8
+    doAssert U16.rotateLeftBits(0) == U16
+    doAssert U16.rotateRightBits(0) == U16
+    doAssert U32.rotateLeftBits(0) == U32
+    doAssert U32.rotateRightBits(0) == U32
+    doAssert U64A.rotateLeftBits(0) == U64A
+    doAssert U64A.rotateRightBits(0) == U64A
 
     # check for undefined behavior with rotate by integer width.
-    doAssert( U8.rotateLeftBits(8) == U8)
-    doAssert( U8.rotateRightBits(8) == U8)
-    doAssert( U16.rotateLeftBits(16) == U16)
-    doAssert( U16.rotateRightBits(16) == U16)
-    doAssert( U32.rotateLeftBits(32) == U32)
-    doAssert( U32.rotateRightBits(32) == U32)
-    doAssert( U64A.rotateLeftBits(64) == U64A)
-    doAssert( U64A.rotateRightBits(64) == U64A)
+    doAssert U8.rotateLeftBits(8) == U8
+    doAssert U8.rotateRightBits(8) == U8
+    doAssert U16.rotateLeftBits(16) == U16
+    doAssert U16.rotateRightBits(16) == U16
+    doAssert U32.rotateLeftBits(32) == U32
+    doAssert U32.rotateRightBits(32) == U32
+    doAssert U64A.rotateLeftBits(64) == U64A
+    doAssert U64A.rotateRightBits(64) == U64A
 
   block:
-    # mask operations
+    # basic mask operations (mutating)
     var v: uint8
     v.setMask(0b1100_0000)
     v.setMask(0b0000_1100)
-    doAssert(v == 0b1100_1100)
+    doAssert v == 0b1100_1100
     v.flipMask(0b0101_0101)
-    doAssert(v == 0b1001_1001)
+    doAssert v == 0b1001_1001
     v.clearMask(0b1000_1000)
-    doAssert(v == 0b0001_0001)
+    doAssert v == 0b0001_0001
     v.clearMask(0b0001_0001)
-    doAssert(v == 0b0000_0000)
+    doAssert v == 0b0000_0000
+    v.setMask(0b0001_1110)
+    doAssert v == 0b0001_1110
+    v.mask(0b0101_0100)
+    doAssert v == 0b0001_0100
+  block:
+    # basic mask operations (non-mutating)
+    let v = 0b1100_0000'u8
+    doAssert v.masked(0b0000_1100) == 0b0000_0000
+    doAssert v.masked(0b1000_1100) == 0b1000_0000
+    doAssert v.setMasked(0b0000_1100) == 0b1100_1100
+    doAssert v.setMasked(0b1000_1110) == 0b1100_1110
+    doAssert v.flipMasked(0b1100_1000) == 0b0000_1000
+    doAssert v.flipMasked(0b0000_1100) == 0b1100_1100
+    let t = 0b1100_0110'u8
+    doAssert t.clearMasked(0b0100_1100) == 0b1000_0010
+    doAssert t.clearMasked(0b1100_0000) == 0b0000_0110
+  block:
+    # basic bitslice opeartions
+    let a = 0b1111_1011'u8
+    doAssert a.bitsliced(0 .. 3) == 0b1011
+    doAssert a.bitsliced(2 .. 3) == 0b10
+    doAssert a.bitsliced(4 .. 7) == 0b1111
+
+    # same thing, but with exclusive ranges.
+    doAssert a.bitsliced(0 ..< 4) == 0b1011
+    doAssert a.bitsliced(2 ..< 4) == 0b10
+    doAssert a.bitsliced(4 ..< 8) == 0b1111
+
+    # mutating
+    var b = 0b1111_1011'u8
+    b.bitslice(1 .. 3)
+    doAssert b == 0b101
+
+    # loop test:
+    let c = 0b1111_1111'u8
+    for i in 0 .. 7:
+      doAssert c.bitsliced(i .. 7) == c shr i
+  block:
+    # bitslice versions of mask operations (mutating)
+    var a = 0b1100_1100'u8
+    let b = toMask[uint8](2 .. 3)
+    a.mask(b)
+    doAssert a == 0b0000_1100
+    a.setMask(4 .. 7)
+    doAssert a == 0b1111_1100
+    a.flipMask(1 .. 3)
+    doAssert a == 0b1111_0010
+    a.flipMask(2 .. 4)
+    doAssert a == 0b1110_1110
+    a.clearMask(2 .. 4)
+    doAssert a == 0b1110_0010
+    a.mask(0 .. 3)
+    doAssert a == 0b0000_0010
+
+    # composition of mask from slices:
+    let c = bitor(toMask[uint8](2 .. 3), toMask[uint8](5 .. 7))
+    doAssert c == 0b1110_1100'u8
+  block:
+    # bitslice versions of mask operations (non-mutating)
+    let a = 0b1100_1100'u8
+    doAssert a.masked(toMask[uint8](2 .. 3)) == 0b0000_1100
+    doAssert a.masked(2 .. 3) == 0b0000_1100
+    doAssert a.setMasked(0 .. 3) == 0b1100_1111
+    doAssert a.setMasked(3 .. 4) == 0b1101_1100
+    doAssert a.flipMasked(0 .. 3) == 0b1100_0011
+    doAssert a.flipMasked(0 .. 7) == 0b0011_0011
+    doAssert a.flipMasked(2 .. 3) == 0b1100_0000
+    doAssert a.clearMasked(2 .. 3) == 0b1100_0000
+    doAssert a.clearMasked(3 .. 6) == 0b1000_0100
   block:
     # single bit operations
     var v: uint8
@@ -184,8 +265,8 @@ proc main() =
     doAssert v == 0b1000_0010
     v.flipBit(1)
     doAssert v == 0b1000_0000
-    doAssert v.testbit(7)
-    doAssert not v.testbit(6)
+    doAssert v.testBit(7)
+    doAssert not v.testBit(6)
   block:
     # multi bit operations
     var v: uint8
@@ -207,7 +288,7 @@ proc main() =
 
   block:
     proc testReverseBitsInvo(x: SomeUnsignedInt) =
-      doAssert(reverseBits(reverseBits(x)) == x)
+      doAssert reverseBits(reverseBits(x)) == x
 
     proc testReverseBitsPerType(x, reversed: uint64) =
       doAssert reverseBits(x) == reversed
@@ -249,13 +330,16 @@ proc main() =
 
   echo "OK"
 
+  # bug #7587
+  doAssert popcount(0b11111111'i8) == 8
+
 block: # not ready for vm because exception is compile error
   try:
     var v: uint32
     var i = 32
     v.setBit(i)
     doAssert false
-  except RangeError:
+  except RangeDefect:
     discard
   except:
     doAssert false
diff --git a/tests/stdlib/tbitops.nim.cfg b/tests/stdlib/tbitops.nim.cfg
index f0d7668a7..013e8d38e 100644
--- a/tests/stdlib/tbitops.nim.cfg
+++ b/tests/stdlib/tbitops.nim.cfg
@@ -1 +1 @@
--d:noUndefinedBitOps
+-d:noUndefinedBitOpts
diff --git a/tests/stdlib/tbitops2.nim b/tests/stdlib/tbitops2.nim
deleted file mode 100644
index e8c7318be..000000000
--- a/tests/stdlib/tbitops2.nim
+++ /dev/null
@@ -1,167 +0,0 @@
-discard """
-  output: "OK"
-"""
-import bitops
-
-
-proc main() =
-  const U8 = 0b0011_0010'u8
-  const I8 = 0b0011_0010'i8
-  const U16 = 0b00100111_00101000'u16
-  const I16 = 0b00100111_00101000'i16
-  const U32 = 0b11010101_10011100_11011010_01010000'u32
-  const I32 = 0b11010101_10011100_11011010_01010000'i32
-  const U64A = 0b01000100_00111111_01111100_10001010_10011001_01001000_01111010_00010001'u64
-  const I64A = 0b01000100_00111111_01111100_10001010_10011001_01001000_01111010_00010001'i64
-  const U64B = 0b00110010_11011101_10001111_00101000_00000000_00000000_00000000_00000000'u64
-  const I64B = 0b00110010_11011101_10001111_00101000_00000000_00000000_00000000_00000000'i64
-
-  doAssert( U64A.fastLog2 == 62)
-  doAssert( I64A.fastLog2 == 62)
-  doAssert( U64A.countLeadingZeroBits == 1)
-  doAssert( I64A.countLeadingZeroBits == 1)
-  doAssert( U64A.countTrailingZeroBits == 0)
-  doAssert( I64A.countTrailingZeroBits == 0)
-  doAssert( U64A.firstSetBit == 1)
-  doAssert( I64A.firstSetBit == 1)
-  doAssert( U64A.parityBits == 1)
-  doAssert( I64A.parityBits == 1)
-  doAssert( U64A.countSetBits == 29)
-  doAssert( I64A.countSetBits == 29)
-  doAssert( U64A.rotateLeftBits(37) == 0b00101001_00001111_01000010_00101000_10000111_11101111_10010001_01010011'u64)
-  doAssert( U64A.rotateRightBits(37) == 0b01010100_11001010_01000011_11010000_10001010_00100001_11111011_11100100'u64)
-
-  doAssert( U64B.firstSetBit == 36)
-  doAssert( I64B.firstSetBit == 36)
-
-  doAssert( U32.fastLog2 == 31)
-  doAssert( I32.fastLog2 == 31)
-  doAssert( U32.countLeadingZeroBits == 0)
-  doAssert( I32.countLeadingZeroBits == 0)
-  doAssert( U32.countTrailingZeroBits == 4)
-  doAssert( I32.countTrailingZeroBits == 4)
-  doAssert( U32.firstSetBit == 5)
-  doAssert( I32.firstSetBit == 5)
-  doAssert( U32.parityBits == 0)
-  doAssert( I32.parityBits == 0)
-  doAssert( U32.countSetBits == 16)
-  doAssert( I32.countSetBits == 16)
-  doAssert( U32.rotateLeftBits(21) == 0b01001010_00011010_10110011_10011011'u32)
-  doAssert( U32.rotateRightBits(21) == 0b11100110_11010010_10000110_10101100'u32)
-
-  doAssert( U16.fastLog2 == 13)
-  doAssert( I16.fastLog2 == 13)
-  doAssert( U16.countLeadingZeroBits == 2)
-  doAssert( I16.countLeadingZeroBits == 2)
-  doAssert( U16.countTrailingZeroBits == 3)
-  doAssert( I16.countTrailingZeroBits == 3)
-  doAssert( U16.firstSetBit == 4)
-  doAssert( I16.firstSetBit == 4)
-  doAssert( U16.parityBits == 0)
-  doAssert( I16.parityBits == 0)
-  doAssert( U16.countSetBits == 6)
-  doAssert( I16.countSetBits == 6)
-  doAssert( U16.rotateLeftBits(12) == 0b10000010_01110010'u16)
-  doAssert( U16.rotateRightBits(12) == 0b01110010_10000010'u16)
-
-  doAssert( U8.fastLog2 == 5)
-  doAssert( I8.fastLog2 == 5)
-  doAssert( U8.countLeadingZeroBits == 2)
-  doAssert( I8.countLeadingZeroBits == 2)
-  doAssert( U8.countTrailingZeroBits == 1)
-  doAssert( I8.countTrailingZeroBits == 1)
-  doAssert( U8.firstSetBit == 2)
-  doAssert( I8.firstSetBit == 2)
-  doAssert( U8.parityBits == 1)
-  doAssert( I8.parityBits == 1)
-  doAssert( U8.countSetBits == 3)
-  doAssert( I8.countSetBits == 3)
-  doAssert( U8.rotateLeftBits(3) == 0b10010001'u8)
-  doAssert( U8.rotateRightBits(3) == 0b0100_0110'u8)
-
-  static :
-    # test bitopts at compile time with vm
-    doAssert( U8.fastLog2 == 5)
-    doAssert( I8.fastLog2 == 5)
-    doAssert( U8.countLeadingZeroBits == 2)
-    doAssert( I8.countLeadingZeroBits == 2)
-    doAssert( U8.countTrailingZeroBits == 1)
-    doAssert( I8.countTrailingZeroBits == 1)
-    doAssert( U8.firstSetBit == 2)
-    doAssert( I8.firstSetBit == 2)
-    doAssert( U8.parityBits == 1)
-    doAssert( I8.parityBits == 1)
-    doAssert( U8.countSetBits == 3)
-    doAssert( I8.countSetBits == 3)
-    doAssert( U8.rotateLeftBits(3) == 0b10010001'u8)
-    doAssert( U8.rotateRightBits(3) == 0b0100_0110'u8)
-
-
-
-  template test_undefined_impl(ffunc: untyped; expected: int; is_static: bool) =
-    doAssert( ffunc(0'u8) == expected)
-    doAssert( ffunc(0'i8) == expected)
-    doAssert( ffunc(0'u16) == expected)
-    doAssert( ffunc(0'i16) == expected)
-    doAssert( ffunc(0'u32) == expected)
-    doAssert( ffunc(0'i32) == expected)
-    doAssert( ffunc(0'u64) == expected)
-    doAssert( ffunc(0'i64) == expected)
-
-  template test_undefined(ffunc: untyped; expected: int) =
-    test_undefined_impl(ffunc, expected, false)
-    static:
-      test_undefined_impl(ffunc, expected, true)
-
-  when defined(noUndefinedBitOpts):
-    # check for undefined behavior with zero.
-    test_undefined(countSetBits, 0)
-    test_undefined(parityBits, 0)
-    test_undefined(firstSetBit, 0)
-    test_undefined(countLeadingZeroBits, 0)
-    test_undefined(countTrailingZeroBits, 0)
-    test_undefined(fastLog2, -1)
-
-    # check for undefined behavior with rotate by zero.
-    doAssert( U8.rotateLeftBits(0) == U8)
-    doAssert( U8.rotateRightBits(0) == U8)
-    doAssert( U16.rotateLeftBits(0) == U16)
-    doAssert( U16.rotateRightBits(0) == U16)
-    doAssert( U32.rotateLeftBits(0) == U32)
-    doAssert( U32.rotateRightBits(0) == U32)
-    doAssert( U64A.rotateLeftBits(0) == U64A)
-    doAssert( U64A.rotateRightBits(0) == U64A)
-
-    # check for undefined behavior with rotate by integer width.
-    doAssert( U8.rotateLeftBits(8) == U8)
-    doAssert( U8.rotateRightBits(8) == U8)
-    doAssert( U16.rotateLeftBits(16) == U16)
-    doAssert( U16.rotateRightBits(16) == U16)
-    doAssert( U32.rotateLeftBits(32) == U32)
-    doAssert( U32.rotateRightBits(32) == U32)
-    doAssert( U64A.rotateLeftBits(64) == U64A)
-    doAssert( U64A.rotateRightBits(64) == U64A)
-
-    static:    # check for undefined behavior with rotate by zero.
-      doAssert( U8.rotateLeftBits(0) == U8)
-      doAssert( U8.rotateRightBits(0) == U8)
-      doAssert( U16.rotateLeftBits(0) == U16)
-      doAssert( U16.rotateRightBits(0) == U16)
-      doAssert( U32.rotateLeftBits(0) == U32)
-      doAssert( U32.rotateRightBits(0) == U32)
-      doAssert( U64A.rotateLeftBits(0) == U64A)
-      doAssert( U64A.rotateRightBits(0) == U64A)
-
-      # check for undefined behavior with rotate by integer width.
-      doAssert( U8.rotateLeftBits(8) == U8)
-      doAssert( U8.rotateRightBits(8) == U8)
-      doAssert( U16.rotateLeftBits(16) == U16)
-      doAssert( U16.rotateRightBits(16) == U16)
-      doAssert( U32.rotateLeftBits(32) == U32)
-      doAssert( U32.rotateRightBits(32) == U32)
-      doAssert( U64A.rotateLeftBits(64) == U64A)
-      doAssert( U64A.rotateRightBits(64) == U64A)
-
-  echo "OK"
-
-main()
diff --git a/tests/stdlib/tbitops2.nim.cfg b/tests/stdlib/tbitops2.nim.cfg
deleted file mode 100644
index e1cb77e82..000000000
--- a/tests/stdlib/tbitops2.nim.cfg
+++ /dev/null
@@ -1,2 +0,0 @@
--d:noIntrinsicsBitOpts
--d:noUndefinedBitOps
diff --git a/tests/stdlib/tbitops_utils.nim b/tests/stdlib/tbitops_utils.nim
new file mode 100644
index 000000000..e3f96fecc
--- /dev/null
+++ b/tests/stdlib/tbitops_utils.nim
@@ -0,0 +1,19 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/private/bitops_utils
+import std/assertions
+
+template chk(a, b) =
+  let a2 = castToUnsigned(a)
+  doAssert a2 == b
+  doAssert type(a2) is type(b)
+  doAssert type(b) is type(a2)
+
+chk 1'i8, 1'u8
+chk -1'i8, 255'u8
+chk 1'u8, 1'u8
+chk 1'u, 1'u
+chk -1, cast[uint](-1)
+chk -1'i64, cast[uint64](-1)
diff --git a/tests/stdlib/tcasts.nim b/tests/stdlib/tcasts.nim
new file mode 100644
index 000000000..e01c7e940
--- /dev/null
+++ b/tests/stdlib/tcasts.nim
@@ -0,0 +1,26 @@
+import std/[strutils]
+import std/[assertions, objectdollar]
+
+# bug #19101
+type
+  Small = object
+    a: int
+
+  Big = object
+    a, b, c, d: int
+
+proc main =
+  var
+    n = 1'i8
+    f = 2.0
+    s = Small(a: 1)
+    b = Big(a: 12345, b: 23456, c: 34567, d: 45678)
+
+  doAssert $cast[int](f).toBin(64) == "0100000000000000000000000000000000000000000000000000000000000000"
+  f = cast[float](n)
+  doAssert $cast[int](f).toBin(64) == "0000000000000000000000000000000000000000000000000000000000000001"
+
+  doAssert $b == "(a: 12345, b: 23456, c: 34567, d: 45678)"
+  b = cast[Big](s)
+  doAssert $b == "(a: 1, b: 0, c: 0, d: 0)"
+main()
diff --git a/tests/stdlib/tcgi.nim b/tests/stdlib/tcgi.nim
index bc177125e..ef39450da 100644
--- a/tests/stdlib/tcgi.nim
+++ b/tests/stdlib/tcgi.nim
@@ -1,10 +1,15 @@
-import unittest

-import cgi, strtabs

+discard """

+  matrix: "--mm:refc; --mm:orc"

+"""

 

-suite "Test cgi module":

+import std/unittest

+import std/[cgi, strtabs, sugar]

+import std/assertions

+

+block: # Test cgi module

   const queryString = "foo=bar&фу=бар&checked=✓&list=1,2,3&with_space=text%20with%20space"

 

-  test "test query parsing with readData":

+  block: # test query parsing with readData

     let parsedQuery = readData(queryString)

 

     check parsedQuery["foo"] == "bar"

@@ -15,3 +20,12 @@ suite "Test cgi module":
 

     expect KeyError:

       discard parsedQuery["not_existing_key"]

+

+# bug #15369

+let queryString = "a=1&b=0&c=3&d&e&a=5&a=t%20e%20x%20t&e=http%3A%2F%2Fw3schools.com%2Fmy%20test.asp%3Fname%3Dst%C3%A5le%26car%3Dsaab"

+

+doAssert collect(for pair in decodeData(queryString): pair) ==

+  @[("a", "1"), ("b", "0"), ("c", "3"),

+    ("d", ""),("e", ""), ("a", "5"), ("a", "t e x t"),

+  ("e", "http://w3schools.com/my test.asp?name=ståle&car=saab")

+]

diff --git a/tests/stdlib/tclosures.nim b/tests/stdlib/tclosures.nim
new file mode 100644
index 000000000..84b033fa8
--- /dev/null
+++ b/tests/stdlib/tclosures.nim
@@ -0,0 +1,47 @@
+discard """
+  targets: "c js"
+"""
+
+import std/assertions
+
+block: # bug #4299
+  proc scopeProc() =
+    proc normalProc() =
+      discard
+
+    proc genericProc[T]() =
+      normalProc()
+
+    genericProc[string]()
+
+  scopeProc()
+
+block: # bug #12492
+  proc foo() =
+    var i = 0
+    proc bar() =
+      inc i
+
+    bar()
+    doAssert i == 1
+
+  foo()
+  static:
+    foo()
+
+block: # bug #10849
+  type
+    Generic[T] = ref object
+      getState: proc(): T
+
+  proc newGeneric[T](): Generic[T] =
+    var state: T
+
+    proc getState[T](): T =
+      state
+
+    Generic[T](getState: getState)
+
+  let g = newGeneric[int]()
+  let state = g.getState()
+  doAssert state == 0
diff --git a/tests/stdlib/tcmdline.nim b/tests/stdlib/tcmdline.nim
new file mode 100644
index 000000000..8b428900b
--- /dev/null
+++ b/tests/stdlib/tcmdline.nim
@@ -0,0 +1,13 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+  joinable: false
+"""
+
+import std/os
+import std/assertions
+
+var params = paramCount()
+doAssert params == 0
+doAssert paramStr(0).len > 0
+doAssert commandLineParams().len == 0
diff --git a/tests/stdlib/tcomplex.nim b/tests/stdlib/tcomplex.nim
new file mode 100644
index 000000000..ca83314b9
--- /dev/null
+++ b/tests/stdlib/tcomplex.nim
@@ -0,0 +1,115 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/[complex, math]
+import std/assertions
+
+proc `=~`[T](x, y: Complex[T]): bool =
+  result = abs(x.re-y.re) < 1e-6 and abs(x.im-y.im) < 1e-6
+
+proc `=~`[T](x: Complex[T]; y: T): bool =
+  result = abs(x.re-y) < 1e-6 and abs(x.im) < 1e-6
+
+let
+  z: Complex64 = complex(0.0, 0.0)
+  oo: Complex64 = complex(1.0, 1.0)
+  a: Complex64 = complex(1.0, 2.0)
+  b: Complex64 = complex(-1.0, -2.0)
+  m1: Complex64 = complex(-1.0, 0.0)
+  i: Complex64 = complex(0.0, 1.0)
+  one: Complex64 = complex(1.0, 0.0)
+  tt: Complex64 = complex(10.0, 20.0)
+  ipi: Complex64 = complex(0.0, -PI)
+
+doAssert(a/2.0 =~ complex(0.5, 1.0))
+doAssert(a == a)
+doAssert((a-a) == z)
+doAssert((a+b) == z)
+doAssert((a+b) =~ 0.0)
+doAssert((a/b) == m1)
+doAssert((1.0/a) =~ complex(0.2, -0.4))
+doAssert((a*b) == complex(3.0, -4.0))
+doAssert(10.0*a == tt)
+doAssert(a*10.0 == tt)
+doAssert(tt/10.0 == a)
+doAssert(oo+(-1.0) == i)
+doAssert( (-1.0)+oo == i)
+doAssert(abs(oo) == sqrt(2.0))
+doAssert(conjugate(a) == complex(1.0, -2.0))
+doAssert(sqrt(m1) == i)
+doAssert(exp(ipi) =~ m1)
+
+doAssert(pow(a, b) =~ complex(-3.72999124927876, -1.68815826725068))
+doAssert(pow(z, a) =~ complex(0.0, 0.0))
+doAssert(pow(z, z) =~ complex(1.0, 0.0))
+doAssert(pow(a, one) =~ a)
+doAssert(pow(a, m1) =~ complex(0.2, -0.4))
+doAssert(pow(a, 2.0) =~ complex(-3.0, 4.0))
+doAssert(pow(a, 2) =~ complex(-3.0, 4.0))
+doAssert(not(pow(a, 2.0) =~ a))
+
+doAssert(ln(a) =~ complex(0.804718956217050, 1.107148717794090))
+doAssert(log10(a) =~ complex(0.349485002168009, 0.480828578784234))
+doAssert(log2(a) =~ complex(1.16096404744368, 1.59727796468811))
+
+doAssert(sin(a) =~ complex(3.16577851321617, 1.95960104142161))
+doAssert(cos(a) =~ complex(2.03272300701967, -3.05189779915180))
+doAssert(tan(a) =~ complex(0.0338128260798967, 1.0147936161466335))
+doAssert(cot(a) =~ 1.0 / tan(a))
+doAssert(sec(a) =~ 1.0 / cos(a))
+doAssert(csc(a) =~ 1.0 / sin(a))
+doAssert(arcsin(a) =~ complex(0.427078586392476, 1.528570919480998))
+doAssert(arccos(a) =~ complex(1.14371774040242, -1.52857091948100))
+doAssert(arctan(a) =~ complex(1.338972522294494, 0.402359478108525))
+doAssert(arccot(a) =~ complex(0.2318238045004031, -0.402359478108525))
+doAssert(arcsec(a) =~ complex(1.384478272687081, 0.3965682301123288))
+doAssert(arccsc(a) =~ complex(0.1863180541078155, -0.3965682301123291))
+
+doAssert(cosh(a) =~ complex(-0.642148124715520, 1.068607421382778))
+doAssert(sinh(a) =~ complex(-0.489056259041294, 1.403119250622040))
+doAssert(tanh(a) =~ complex(1.1667362572409199, -0.243458201185725))
+doAssert(sech(a) =~ 1.0 / cosh(a))
+doAssert(csch(a) =~ 1.0 / sinh(a))
+doAssert(coth(a) =~ 1.0 / tanh(a))
+doAssert(arccosh(a) =~ complex(1.528570919480998, 1.14371774040242))
+doAssert(arcsinh(a) =~ complex(1.469351744368185, 1.06344002357775))
+doAssert(arctanh(a) =~ complex(0.173286795139986, 1.17809724509617))
+doAssert(arcsech(a) =~ arccosh(1.0/a))
+doAssert(arccsch(a) =~ arcsinh(1.0/a))
+doAssert(arccoth(a) =~ arctanh(1.0/a))
+
+doAssert(phase(a) == 1.1071487177940904)
+let t = polar(a)
+doAssert(rect(t.r, t.phi) =~ a)
+doAssert(rect(1.0, 2.0) =~ complex(-0.4161468365471424, 0.9092974268256817))
+
+doAssert(almostEqual(a, a + complex(1e-16, 1e-16)))
+doAssert(almostEqual(a, a + complex(2e-15, 2e-15), unitsInLastPlace = 5))
+
+
+let
+  i64: Complex32 = complex(0.0f, 1.0f)
+  a64: Complex32 = 2.0f*i64 + 1.0.float32
+  b64: Complex32 = complex(-1.0'f32, -2.0'f32)
+
+doAssert(a64 == a64)
+doAssert(a64 == -b64)
+doAssert(a64 + b64 =~ 0.0'f32)
+doAssert(not(pow(a64, b64) =~ a64))
+doAssert(pow(a64, 0.5f) =~ sqrt(a64))
+doAssert(pow(a64, 2) =~ complex(-3.0'f32, 4.0'f32))
+doAssert(sin(arcsin(b64)) =~ b64)
+doAssert(cosh(arccosh(a64)) =~ a64)
+
+doAssert(phase(a64) - 1.107149f < 1e-6)
+let t64 = polar(a64)
+doAssert(rect(t64.r, t64.phi) =~ a64)
+doAssert(rect(1.0f, 2.0f) =~ complex(-0.4161468f, 0.90929742f))
+doAssert(sizeof(a64) == 8)
+doAssert(sizeof(a) == 16)
+
+doAssert 123.0.im + 456.0 == complex64(456, 123)
+
+let localA = complex(0.1'f32)
+doAssert localA.im is float32
diff --git a/tests/stdlib/tcookies.nim b/tests/stdlib/tcookies.nim
new file mode 100644
index 000000000..3ff0f3bae
--- /dev/null
+++ b/tests/stdlib/tcookies.nim
@@ -0,0 +1,22 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+
+import std/[cookies, times, strtabs]
+import std/assertions
+
+let expire = fromUnix(0) + 1.seconds
+
+let theCookies = [
+  setCookie("test", "value", expire),
+  setCookie("test", "value", expire.local),
+  setCookie("test", "value", expire.utc)
+]
+let expected = "Set-Cookie: test=value; Expires=Thu, 01 Jan 1970 00:00:01 GMT"
+doAssert theCookies == [expected, expected, expected]
+
+let table = parseCookies("uid=1; kp=2")
+doAssert table["uid"] == "1"
+doAssert table["kp"] == "2"
diff --git a/tests/stdlib/tcritbits.nim b/tests/stdlib/tcritbits.nim
new file mode 100644
index 000000000..e6282f045
--- /dev/null
+++ b/tests/stdlib/tcritbits.nim
@@ -0,0 +1,89 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import std/[sequtils,critbits]
+import std/assertions
+
+template main =
+  var r: CritBitTree[void]
+  r.incl "abc"
+  r.incl "xyz"
+  r.incl "def"
+  r.incl "definition"
+  r.incl "prefix"
+  r.incl "foo"
+
+  doAssert r.contains"def"
+
+  r.excl "def"
+  doAssert r.missingOrExcl("foo") == false
+  doAssert "foo" notin toSeq(r.items)
+
+  doAssert r.missingOrExcl("foo") == true
+
+  doAssert toSeq(r.items) == @["abc", "definition", "prefix", "xyz"]
+
+  doAssert toSeq(r.itemsWithPrefix("de")) == @["definition"]
+  var c = CritBitTree[int]()
+
+  c.inc("a")
+  doAssert c["a"] == 1
+
+  c.inc("a", 4)
+  doAssert c["a"] == 5
+
+  c.inc("a", -5)
+  doAssert c["a"] == 0
+
+  c.inc("b", 2)
+  doAssert c["b"] == 2
+
+  c.inc("c", 3)
+  doAssert c["c"] == 3
+
+  c.inc("a", 1)
+  doAssert c["a"] == 1
+
+  var cf = CritBitTree[float]()
+
+  cf.incl("a", 1.0)
+  doAssert cf["a"] == 1.0
+
+  cf.incl("b", 2.0)
+  doAssert cf["b"] == 2.0
+
+  cf.incl("c", 3.0)
+  doAssert cf["c"] == 3.0
+
+  doAssert cf.len == 3
+  cf.excl("c")
+  doAssert cf.len == 2
+
+  var cb: CritBitTree[string]
+  cb.incl("help", "help")
+  for k in cb.keysWithPrefix("helpp"):
+    doAssert false, "there is no prefix helpp"
+
+  block: # bug #14339
+    var strings: CritBitTree[int]
+    discard strings.containsOrIncl("foo", 3)
+    doAssert strings["foo"] == 3
+
+  block tcritbitsToString:
+    block:
+      var t: CritBitTree[int]
+      t["a"] = 1
+      doAssert $t == """{"a": 1}"""
+    block:
+      var t: CritBitTree[string]
+      t["a"] = "1"
+      doAssert $t == """{"a": "1"}"""
+    block:
+      var t: CritBitTree[char]
+      t["a"] = '1'
+      doAssert $t == """{"a": '1'}"""
+
+main()
+static: main()
diff --git a/tests/stdlib/tcstring.nim b/tests/stdlib/tcstring.nim
new file mode 100644
index 000000000..d7fdd7738
--- /dev/null
+++ b/tests/stdlib/tcstring.nim
@@ -0,0 +1,93 @@
+discard """
+  targets: "c cpp js"
+  matrix: "--gc:refc; --gc:arc"
+"""
+
+from std/sugar import collect
+from stdtest/testutils import whenRuntimeJs, whenVMorJs
+import std/assertions
+
+template testMitems() =
+  block:
+    var a = "abc"
+    var b = a.cstring
+    let s = collect:
+      for bi in mitems(b):
+        if bi == 'b': bi = 'B'
+        bi
+    whenRuntimeJs:
+      discard # xxx mitems should give CT error instead of @['\x00', '\x00', '\x00']
+    do:
+      doAssert s == @['a', 'B', 'c']
+
+  block:
+    var a = "abc\0def"
+    var b = a.cstring
+    let s = collect:
+      for bi in mitems(b):
+        if bi == 'b': bi = 'B'
+        bi
+    whenRuntimeJs:
+      discard # ditto
+    do:
+      doAssert s == @['a', 'B', 'c']
+
+proc mainProc() =
+  testMitems()
+
+template main() =
+  block: # bug #13859
+    let str = "abc".cstring
+    doAssert len(str).int8 == 3
+    doAssert len(str).int16 == 3
+    doAssert len(str).int32 == 3
+    var str2 = "cde".cstring
+    doAssert len(str2).int8 == 3
+    doAssert len(str2).int16 == 3
+    doAssert len(str2).int32 == 3
+
+    const str3 = "abc".cstring
+    doAssert len(str3).int32 == 3
+    doAssert len("abc".cstring).int16 == 3
+    doAssert len("abc".cstring).float32 == 3.0
+
+  block: # bug #17159
+    block:
+      var a = "abc"
+      var b = a.cstring
+      doAssert $(b, ) == """("abc",)"""
+      let s = collect:
+        for bi in b: bi
+      doAssert s == @['a', 'b', 'c']
+
+    block:
+      var a = "abc\0def"
+      var b = a.cstring
+      let s = collect:
+        for bi in b: bi
+      whenRuntimeJs:
+        doAssert $(b, ) == """("abc\x00def",)"""
+        doAssert s == @['a', 'b', 'c', '\x00', 'd', 'e', 'f']
+      do:
+        doAssert $(b, ) == """("abc",)"""
+        doAssert s == @['a', 'b', 'c']
+
+  block:
+    when defined(gcArc): # xxx SIGBUS
+      discard
+    else:
+      mainProc()
+    when false: # xxx bug vm: Error: unhandled exception: 'node' is not accessible using discriminant 'kind' of type 'TFullReg' [FieldDefect]
+      testMitems()
+
+  block: # bug #13321: [codegen] --gc:arc does not properly emit cstring, results in SIGSEGV
+    let a = "hello".cstring
+    doAssert $a == "hello"
+    doAssert $a[0] == "h"
+    doAssert $a[4] == "o"
+    whenVMorJs: discard # xxx this should work in vm, refs https://github.com/timotheecour/Nim/issues/619
+    do:
+      doAssert a[a.len] == '\0'
+
+static: main()
+main()
diff --git a/tests/stdlib/tcstrutils.nim b/tests/stdlib/tcstrutils.nim
new file mode 100644
index 000000000..e73b2b681
--- /dev/null
+++ b/tests/stdlib/tcstrutils.nim
@@ -0,0 +1,39 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+import std/cstrutils
+import std/assertions
+
+proc main() =
+  let s = cstring "abcdef"
+  doAssert s.startsWith("a")
+  doAssert not s.startsWith("b")
+  doAssert s.endsWith("f")
+  doAssert not s.endsWith("a")
+  doAssert s.startsWith("")
+  doAssert s.endsWith("")
+
+  let a = cstring "abracadabra"
+  doAssert a.startsWith("abra")
+  doAssert not a.startsWith("bra")
+  doAssert a.endsWith("abra")
+  doAssert not a.endsWith("dab")
+  doAssert a.startsWith("")
+  doAssert a.endsWith("")
+
+  doAssert cmpIgnoreCase(cstring "FooBar", "foobar") == 0
+  doAssert cmpIgnoreCase(cstring "bar", "Foo") < 0
+  doAssert cmpIgnoreCase(cstring "Foo5", "foo4") > 0
+
+  doAssert cmpIgnoreStyle(cstring "foo_bar", "FooBar") == 0
+  doAssert cmpIgnoreStyle(cstring "foo_bar_5", "FooBar4") > 0
+
+  doAssert cmpIgnoreCase(cstring "", cstring "") == 0
+  doAssert cmpIgnoreCase(cstring "", cstring "Hello") < 0
+  doAssert cmpIgnoreCase(cstring "wind", cstring "") > 0
+
+
+static: main()
+main()
diff --git a/tests/stdlib/tdb.nim b/tests/stdlib/tdb.nim
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/stdlib/tdb.nim
diff --git a/tests/stdlib/tdb.nims b/tests/stdlib/tdb.nims
new file mode 100644
index 000000000..d31d0b26f
--- /dev/null
+++ b/tests/stdlib/tdb.nims
@@ -0,0 +1 @@
+--styleCheck:off
\ No newline at end of file
diff --git a/tests/stdlib/tdb_mysql.nim b/tests/stdlib/tdb_mysql.nim
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/stdlib/tdb_mysql.nim
diff --git a/tests/stdlib/tdecls.nim b/tests/stdlib/tdecls.nim
new file mode 100644
index 000000000..42dc646f2
--- /dev/null
+++ b/tests/stdlib/tdecls.nim
@@ -0,0 +1,50 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+import std/assertions
+import std/decls
+
+template fun() =
+  var s = @[10,11,12]
+  var a {.byaddr.} = s[0]
+  a+=100
+  doAssert s == @[110,11,12]
+  doAssert a is int
+  var b {.byaddr.}: int = s[0]
+  doAssert a.addr == b.addr
+
+  {.push warningAsError[ImplicitTemplateRedefinition]: on.}
+  # in the future ImplicitTemplateRedefinition will be an error anyway
+  doAssert not compiles(block:
+    # redeclaration not allowed
+    var foo = 0
+    var foo {.byaddr.} = s[0])
+
+  doAssert not compiles(block:
+    # ditto
+    var foo {.byaddr.} = s[0]
+    var foo {.byaddr.} = s[0])
+  {.pop.}
+
+  block:
+    var b {.byaddr.} = s[1] # redeclaration ok in sub scope
+    b = 123
+
+  doAssert s == @[110,123,12]
+
+  b = b * 10
+  doAssert s == @[1100,123,12]
+
+  doAssert not compiles(block:
+    var b2 {.byaddr.}: float = s[2])
+
+  doAssert compiles(block:
+    var b2 {.byaddr.}: int = s[2])
+
+proc fun2() = fun()
+fun()
+fun2()
+static: fun2()
+when false: # pending bug #13887
+  static: fun()
diff --git a/tests/stdlib/tdecode_helpers.nim b/tests/stdlib/tdecode_helpers.nim
new file mode 100644
index 000000000..1c0735e05
--- /dev/null
+++ b/tests/stdlib/tdecode_helpers.nim
@@ -0,0 +1,27 @@
+import std/private/decode_helpers
+import std/assertions
+
+block:
+  var i = 0
+  let c = decodePercent("%t9", i)
+  doAssert (i, c) == (0, '%')
+
+block:
+  var i = 0
+  let c = decodePercent("19", i)
+  doAssert (i, c) == (0, '%')
+
+block:
+  var i = 0
+  let c = decodePercent("%19", i)
+  doAssert (i, c) == (2, '\x19')
+
+block:
+  var i = 0
+  let c = decodePercent("%A9", i)
+  doAssert (i, c) == (2, '\xA9')
+
+block:
+  var i = 0
+  let c = decodePercent("%Aa", i)
+  doAssert (i, c) == (2, '\xAA')
diff --git a/tests/stdlib/tdeques.nim b/tests/stdlib/tdeques.nim
new file mode 100644
index 000000000..39ff996d1
--- /dev/null
+++ b/tests/stdlib/tdeques.nim
@@ -0,0 +1,243 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+import std/deques
+from std/sequtils import toSeq
+import std/assertions
+
+block:
+  proc index(self: Deque[int], idx: Natural): int =
+    self[idx]
+
+  proc main =
+    var testDeque = initDeque[int]()
+    testDeque.addFirst(1)
+    doAssert testDeque.index(0) == 1
+
+  main()
+
+block:
+  var d = initDeque[int]()
+  d.addLast(1)
+  doAssert $d == "[1]"
+block:
+  var d = initDeque[string]()
+  d.addLast("1")
+  doAssert $d == """["1"]"""
+block:
+  var d = initDeque[char]()
+  d.addLast('1')
+  doAssert $d == "['1']"
+
+block:
+  var deq = initDeque[int](1)
+  deq.addLast(4)
+  deq.addFirst(9)
+  deq.addFirst(123)
+  var first = deq.popFirst()
+  deq.addLast(56)
+  doAssert(deq.peekLast() == 56)
+  deq.addLast(6)
+  doAssert(deq.peekLast() == 6)
+  var second = deq.popFirst()
+  deq.addLast(789)
+  doAssert(deq.peekLast() == 789)
+
+  doAssert first == 123
+  doAssert second == 9
+  doAssert($deq == "[4, 56, 6, 789]")
+  doAssert deq == [4, 56, 6, 789].toDeque
+
+  doAssert deq[0] == deq.peekFirst and deq.peekFirst == 4
+  #doAssert deq[^1] == deq.peekLast and deq.peekLast == 789
+  deq[0] = 42
+  deq[deq.len - 1] = 7
+
+  doAssert 6 in deq and 789 notin deq
+  doAssert deq.find(6) >= 0
+  doAssert deq.find(789) < 0
+
+  block:
+    var d = initDeque[int](1)
+    d.addLast 7
+    d.addLast 8
+    d.addLast 10
+    d.addFirst 5
+    d.addFirst 2
+    d.addFirst 1
+    d.addLast 20
+    d.shrink(fromLast = 2)
+    doAssert($d == "[1, 2, 5, 7, 8]")
+    d.shrink(2, 1)
+    doAssert($d == "[5, 7]")
+    d.shrink(2, 2)
+    doAssert d.len == 0
+
+  for i in -2 .. 10:
+    if i in deq:
+      doAssert deq.contains(i) and deq.find(i) >= 0
+    else:
+      doAssert(not deq.contains(i) and deq.find(i) < 0)
+
+  when compileOption("boundChecks"):
+    try:
+      echo deq[99]
+      doAssert false
+    except IndexDefect:
+      discard
+
+    try:
+      doAssert deq.len == 4
+      for i in 0 ..< 5: deq.popFirst()
+      doAssert false
+    except IndexDefect:
+      discard
+
+  # grabs some types of resize error.
+  deq = initDeque[int]()
+  for i in 1 .. 4: deq.addLast i
+  deq.popFirst()
+  deq.popLast()
+  for i in 5 .. 8: deq.addFirst i
+  doAssert $deq == "[8, 7, 6, 5, 2, 3]"
+
+  # Similar to proc from the documentation example
+  proc foo(a, b: Positive) = # assume random positive values for `a` and `b`.
+    var deq = initDeque[int]()
+    doAssert deq.len == 0
+    for i in 1 .. a: deq.addLast i
+
+    if b < deq.len: # checking before indexed access.
+      doAssert deq[b] == b + 1
+
+    # The following two lines don't need any checking on access due to the logic
+    # of the program, but that would not be the case if `a` could be 0.
+    doAssert deq.peekFirst == 1
+    doAssert deq.peekLast == a
+
+    while deq.len > 0: # checking if the deque is empty
+      doAssert deq.popFirst() > 0
+
+  #foo(0,0)
+  foo(8, 5)
+  foo(10, 9)
+  foo(1, 1)
+  foo(2, 1)
+  foo(1, 5)
+  foo(3, 2)
+
+import std/sets
+
+block t13310:
+  proc main() =
+    var q = initDeque[HashSet[int16]](2)
+    q.addFirst([1'i16].toHashSet)
+    q.addFirst([2'i16].toHashSet)
+    q.addFirst([3'i16].toHashSet)
+    doAssert $q == "[{3}, {2}, {1}]"
+
+  static:
+    main()
+
+
+proc main() =
+  block:
+    let a = [10, 20, 30].toDeque
+    doAssert toSeq(a.pairs) == @[(0, 10), (1, 20), (2, 30)]
+
+  block:
+    let q = [7, 9].toDeque
+    doAssert 7 in q
+    doAssert q.contains(7)
+    doAssert 8 notin q
+
+  block:
+    let a = [10, 20, 30, 40, 50].toDeque
+    doAssert $a == "[10, 20, 30, 40, 50]"
+    doAssert a.peekFirst == 10
+    doAssert len(a) == 5
+
+  block:
+    let a = [10, 20, 30, 40, 50].toDeque
+    doAssert $a == "[10, 20, 30, 40, 50]"
+    doAssert a.peekLast == 50
+    doAssert len(a) == 5
+
+  block:
+    var a = [10, 20, 30, 40, 50].toDeque
+    doAssert $a == "[10, 20, 30, 40, 50]"
+    doAssert a.popFirst == 10
+    doAssert $a == "[20, 30, 40, 50]"
+
+  block:
+    var a = [10, 20, 30, 40, 50].toDeque
+    doAssert $a == "[10, 20, 30, 40, 50]"
+    doAssert a.popLast == 50
+    doAssert $a == "[10, 20, 30, 40]"
+
+  block:
+    var a = [10, 20, 30, 40, 50].toDeque
+    doAssert $a == "[10, 20, 30, 40, 50]"
+    clear(a)
+    doAssert len(a) == 0
+
+  block: # bug #21278
+    var a = [10, 20, 30, 40].toDeque
+
+    a.shrink(fromFirst = 0, fromLast = 1)
+    doAssert $a == "[10, 20, 30]"
+
+  block:
+    var a, b: Deque[int]
+    for i in 1 .. 256:
+      a.addLast(i)
+    for i in 1 .. 255:
+      a.popLast
+    b.addLast(1)
+    doAssert a == b
+
+  block:
+    # Issue 23275
+    # Test `==`.
+    block:
+      var a, b = initDeque[int]()
+      doAssert a == b
+      doAssert a.hash == b.hash
+      a.addFirst(1)
+      doAssert a != b
+      doAssert a.hash != b.hash
+      b.addLast(1)
+      doAssert a == b
+      doAssert a.hash == b.hash
+      a.popFirst
+      b.popLast
+      doAssert a == b
+      doAssert a.hash == b.hash
+      a.addLast 2
+      doAssert a != b
+      doAssert a.hash != b.hash
+      b.addFirst 2
+      doAssert a == b
+      doAssert a.hash == b.hash
+
+    block:
+      var a, b = initDeque[int]()
+      for i in countDown(100, 1):
+        a.addFirst(i)
+      for i in 1..100:
+        b.addLast(i)
+      doAssert a == b
+      for i in 1..99:
+        a.popLast
+      let a1 = [1].toDeque
+      doAssert a == a1
+      doAssert a.hash == a1.hash
+      var c = initDeque[int]()
+      c.addLast(1)
+      doAssert a == c
+      doAssert a.hash == c.hash
+
+static: main()
+main()
diff --git a/tests/stdlib/tdiff.nim b/tests/stdlib/tdiff.nim
new file mode 100644
index 000000000..132f7120b
--- /dev/null
+++ b/tests/stdlib/tdiff.nim
@@ -0,0 +1,75 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import experimental/diff
+import std/strutils
+import std/assertions
+
+proc testHelper(f: seq[Item]): string =
+  for it in f:
+    result.add(
+      $it.deletedA & "." & $it.insertedB & "." & $it.startA & "." & $it.startB & "*"
+    )
+
+proc main() =
+  var a, b: string
+
+  # Diff Self Test
+  # test all changes
+  a = "a,b,c,d,e,f,g,h,i,j,k,l".replace(',', '\n')
+  b = "0,1,2,3,4,5,6,7,8,9".replace(',', '\n')
+  doAssert(testHelper(diffText(a, b)) ==
+    "12.10.0.0*",
+    "all-changes test failed.")
+  # test all same
+  a = "a,b,c,d,e,f,g,h,i,j,k,l".replace(',', '\n')
+  b = a
+  doAssert(testHelper(diffText(a, b)) ==
+    "",
+    "all-same test failed.")
+
+  # test snake
+  a = "a,b,c,d,e,f".replace(',', '\n')
+  b = "b,c,d,e,f,x".replace(',', '\n')
+  doAssert(testHelper(diffText(a, b)) ==
+    "1.0.0.0*0.1.6.5*",
+    "snake test failed.")
+
+  # 2002.09.20 - repro
+  a = "c1,a,c2,b,c,d,e,g,h,i,j,c3,k,l".replace(',', '\n')
+  b = "C1,a,C2,b,c,d,e,I1,e,g,h,i,j,C3,k,I2,l".replace(',', '\n')
+  doAssert(testHelper(diffText(a, b)) ==
+    "1.1.0.0*1.1.2.2*0.2.7.7*1.1.11.13*0.1.13.15*",
+    "repro20020920 test failed.")
+
+  # 2003.02.07 - repro
+  a = "F".replace(',', '\n')
+  b = "0,F,1,2,3,4,5,6,7".replace(',', '\n')
+  doAssert(testHelper(diffText(a, b)) ==
+    "0.1.0.0*0.7.1.2*",
+    "repro20030207 test failed.")
+
+  # Muegel - repro
+  a = "HELLO\nWORLD"
+  b = "\n\nhello\n\n\n\nworld\n"
+  doAssert(testHelper(diffText(a, b)) ==
+    "2.8.0.0*",
+    "repro20030409 test failed.")
+
+  # test some differences
+  a = "a,b,-,c,d,e,f,f".replace(',', '\n')
+  b = "a,b,x,c,e,f".replace(',', '\n')
+  doAssert(testHelper(diffText(a, b)) ==
+    "1.1.2.2*1.0.4.4*1.0.7.6*",
+    "some-changes test failed.")
+
+  # test one change within long chain of repeats
+  a = "a,a,a,a,a,a,a,a,a,a".replace(',', '\n')
+  b = "a,a,a,a,-,a,a,a,a,a".replace(',', '\n')
+  doAssert(testHelper(diffText(a, b)) ==
+    "0.1.4.4*1.0.9.10*",
+    "long chain of repeats test failed.")
+main()
+static: main()
diff --git a/tests/stdlib/tdistros_detect.nim b/tests/stdlib/tdistros_detect.nim
new file mode 100644
index 000000000..1176c8993
--- /dev/null
+++ b/tests/stdlib/tdistros_detect.nim
@@ -0,0 +1,16 @@
+import std/[assertions, distros]
+
+when defined(windows):
+    doAssert detectOs(Windows) == true
+    doAssert detectOs(Linux) == false
+    doAssert detectOs(MacOSX) == false
+
+when defined(linux):
+    doAssert detectOs(Linux) == true
+    doAssert detectOs(Windows) == false
+    doAssert detectOs(MacOSX) == false
+
+when defined(macosx):
+    doAssert detectOs(MacOSX) == true
+    doAssert detectOs(Windows) == false
+    doAssert detectOs(Linux) == false
diff --git a/tests/stdlib/tdochelpers.nim b/tests/stdlib/tdochelpers.nim
new file mode 100644
index 000000000..4d532b5d0
--- /dev/null
+++ b/tests/stdlib/tdochelpers.nim
@@ -0,0 +1,221 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  output: '''
+
+[Suite] Integration with Nim
+'''
+"""
+
+# tests for dochelpers.nim module
+
+import ../../lib/packages/docutils/[rstast, rst, dochelpers]
+import unittest
+import std/assertions
+
+proc testMsgHandler(filename: string, line, col: int, msgkind: MsgKind,
+                    arg: string) =
+  doAssert msgkind == mwBrokenLink
+
+proc fromRst(text: string): LangSymbol =
+  let r = rstParse(text, "-input-", LineRstInit, ColRstInit,
+                   {roNimFile},
+                   msgHandler=testMsgHandler)
+  assert r.node.kind == rnRstRef
+  result = toLangSymbol(r.node)
+
+proc fromMd(text: string): LangSymbol =
+  let r = rstParse(text, "-input-", LineRstInit, ColRstInit,
+                   {roPreferMarkdown, roSupportMarkdown, roNimFile},
+                   msgHandler=testMsgHandler)
+  assert r.node.kind == rnPandocRef
+  assert r.node.len == 2
+  # this son is the target:
+  assert r.node.sons[1].kind == rnInner
+  result = toLangSymbol(r.node.sons[1])
+
+suite "Integration with Nim":
+  test "simple symbol parsing (shortest form)":
+    let expected = LangSymbol(symKind: "", name: "g")
+    check "g_".fromRst == expected
+    check "[g]".fromMd == expected
+    # test also alternative syntax variants of Pandoc Markdown:
+    check "[g][]".fromMd == expected
+    check "[this symbol][g]".fromMd == expected
+
+  test "simple symbol parsing (group of words)":
+    #let input1 = "`Y`_".rstParseTest
+    let expected1 = LangSymbol(symKind: "", name: "Y")
+    check "`Y`_".fromRst == expected1
+    check "[Y]".fromMd == expected1
+
+    # this means not a statement 'type', it's a backticked identifier `type`:
+    let expected2 = LangSymbol(symKind: "", name: "type")
+    check "`type`_".fromRst == expected2
+    check "[type]".fromMd == expected2
+
+    let expected3 = LangSymbol(symKind: "", name: "[]")
+    check "`[]`_".fromRst == expected3
+    # Markdown syntax for this case is NOT [[]]
+    check "[`[]`]".fromMd == expected3
+
+    let expected4 = LangSymbol(symKind: "", name: "Xyz")
+    check "`X Y Z`_".fromRst == expected4
+    check "[X Y Z]".fromMd == expected4
+
+  test "simple proc parsing":
+    let expected = LangSymbol(symKind: "proc", name: "f")
+    check "`proc f`_".fromRst == expected
+    check "[proc f]".fromMd == expected
+
+  test "another backticked name":
+    let expected = LangSymbol(symKind: "template", name: "type")
+    check """`template \`type\``_""".fromRst == expected
+    # no backslash in Markdown:
+    check """[template `type`]""".fromMd == expected
+
+  test "simple proc parsing with parameters":
+    let expected = LangSymbol(symKind: "proc", name: "f",
+                              parametersProvided: true)
+    check "`proc f*()`_".fromRst == expected
+    check "`proc f()`_".fromRst == expected
+    check "[proc f*()]".fromMd == expected
+    check "[proc f()]".fromMd == expected
+
+  test "symbol parsing with 1 parameter":
+    let expected = LangSymbol(symKind: "", name: "f",
+                              parameters: @[("G[int]", "")],
+                              parametersProvided: true)
+    check "`f(G[int])`_".fromRst == expected
+    check "[f(G[int])]".fromMd == expected
+
+  test "more proc parsing":
+    let input1 = "`proc f[T](x:G[T]):M[T]`_".fromRst
+    let input2 = "`proc f[ T ] ( x: G [T] ): M[T]`_".fromRst
+    let input3 = "`proc f*[T](x: G[T]): M[T]`_".fromRst
+    let expected = LangSymbol(symKind: "proc",
+                              name: "f",
+                              generics: "[T]",
+                              parameters: @[("x", "G[T]")],
+                              parametersProvided: true,
+                              outType: "M[T]")
+    check(input1 == expected)
+    check(input2 == expected)
+    check(input3 == expected)
+
+  test "advanced proc parsing with Nim identifier normalization":
+    let inputRst = """`proc binarySearch*[T, K](a: openarray[T]; key: K;
+                       cmp: proc (x: T; y: K): int)`_"""
+    let inputMd = """[proc binarySearch*[T, K](a: openarray[T]; key: K;
+                       cmp: proc (x: T; y: K): int)]"""
+    let expected = LangSymbol(symKind: "proc",
+                              name: "binarysearch",
+                              generics: "[T,K]",
+                              parameters: @[
+                                ("a", "openarray[T]"),
+                                ("key", "K"),
+                                ("cmp", "proc(x:T;y:K):int")],
+                              parametersProvided: true,
+                              outType: "")
+    check(inputRst.fromRst == expected)
+    check(inputMd.fromMd == expected)
+
+  test "the same without proc":
+    let input = """`binarySearch*[T, K](a: openarray[T]; key: K;
+                    cmp: proc (x: T; y: K): int {.closure.})`_"""
+    let expected = LangSymbol(symKind: "",
+                              name: "binarysearch",
+                              generics: "[T,K]",
+                              parameters: @[
+                                ("a", "openarray[T]"),
+                                ("key", "K"),
+                                ("cmp", "proc(x:T;y:K):int")],
+                              parametersProvided: true,
+                              outType: "")
+    check(input.fromRst == expected)
+    let inputMd = """[binarySearch*[T, K](a: openarray[T]; key: K;
+                      cmp: proc (x: T; y: K): int {.closure.})]"""
+    check(inputMd.fromMd == expected)
+
+  test "operator $ with and without backticks":
+    let input1 = """`func \`$\`*[T](a: \`open Array\`[T]): string`_"""
+    let input1md = "[func `$`*[T](a: `open Array`[T]): string]"
+    let input2 = """`func $*[T](a: \`open Array\`[T]): string`_"""
+    let input2md = "[func $*[T](a: `open Array`[T]): string]"
+    let expected = LangSymbol(symKind: "func",
+                              name: "$",
+                              generics: "[T]",
+                              parameters: @[("a", "openarray[T]")],
+                              parametersProvided: true,
+                              outType: "string")
+    check input1.fromRst == expected
+    check input2.fromRst == expected
+    check input1md.fromMd == expected
+    check input2md.fromMd == expected
+
+  test "operator [] with and without backticks":
+    let input1 = """`func \`[]\`[T](a: \`open Array\`[T], idx: int): T`_"""
+    let input1md = "[func `[]`[T](a: `open Array`[T], idx: int): T]"
+    let input2 = """`func [][T](a: \`open Array\`[T], idx: int): T`_"""
+    let input2md = "[func [][T](a: `open Array`[T], idx: int): T]"
+    let expected = LangSymbol(symKind: "func",
+                              name: "[]",
+                              generics: "[T]",
+                              parameters: @[("a", "openarray[T]"),
+                                            ("idx", "int")],
+                              parametersProvided: true,
+                              outType: "T")
+    check input1.fromRst == expected
+    check input2.fromRst == expected
+    check input1md.fromMd == expected
+    check input2md.fromMd == expected
+
+  test "postfix symbol specifier #1":
+    let input = "`walkDir iterator`_"
+    let inputMd = "[walkDir iterator]"
+    let expected = LangSymbol(symKind: "iterator",
+                              name: "walkdir")
+    check input.fromRst == expected
+    check inputMd.fromMd == expected
+
+  test "postfix symbol specifier #2":
+    let input1 = """`\`[]\`[T](a: \`open Array\`[T], idx: int): T func`_"""
+    let input1md = "[`[]`[T](a: `open Array`[T], idx: int): T func]"
+    let input2 = """`[][T](a: \`open Array\`[T], idx: int): T func`_"""
+    # note again that ` is needed between 1st and second [
+    let input2md = "[`[]`[T](a: `open Array`[T], idx: int): T func]"
+    let expected = LangSymbol(symKind: "func",
+                              name: "[]",
+                              generics: "[T]",
+                              parameters: @[("a", "openarray[T]"),
+                                            ("idx", "int")],
+                              parametersProvided: true,
+                              outType: "T")
+    check input1.fromRst == expected
+    check input2.fromRst == expected
+    check input1md.fromMd == expected
+    check input2md.fromMd == expected
+
+  test "type of type":
+    let inputRst = "`CopyFlag enum`_"
+    let inputMd = "[CopyFlag enum]"
+    let expected = LangSymbol(symKind: "type",
+                              symTypeKind: "enum",
+                              name: "Copyflag")
+    check inputRst.fromRst == expected
+    check inputMd.fromMd == expected
+
+  test "prefixed module":
+    let inputRst = "`module std / paths`_"
+    let inputMd = "[module std / paths]"
+    let expected = LangSymbol(symKind: "module",
+                              name: "std/paths")
+    check inputRst.fromRst == expected
+    check inputMd.fromMd == expected
+
+  test "postfixed module":
+    let inputRst = "`std / paths module`_"
+    let inputMd = "[std / paths module]"
+    let expected = LangSymbol(symKind: "module",
+                              name: "std/paths")
+    check inputRst.fromRst == expected
+    check inputMd.fromMd == expected
diff --git a/tests/stdlib/teditdistance.nim b/tests/stdlib/teditdistance.nim
new file mode 100644
index 000000000..14ba6df97
--- /dev/null
+++ b/tests/stdlib/teditdistance.nim
@@ -0,0 +1,45 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/editdistance
+import std/assertions
+
+doAssert editDistance("", "") == 0
+doAssert editDistance("kitten", "sitting") == 3 # from Wikipedia
+doAssert editDistance("flaw", "lawn") == 2 # from Wikipedia
+
+doAssert editDistance("привет", "превет") == 1
+doAssert editDistance("Åge", "Age") == 1
+# editDistance, one string is longer in bytes, but shorter in rune length
+# first string: 4 bytes, second: 6 bytes, but only 3 runes
+doAssert editDistance("aaaa", "×××") == 4
+
+block veryLongStringEditDistanceTest:
+  const cap = 256
+  var
+    s1 = newStringOfCap(cap)
+    s2 = newStringOfCap(cap)
+  while len(s1) < cap:
+    s1.add 'a'
+  while len(s2) < cap:
+    s2.add 'b'
+  doAssert editDistance(s1, s2) == cap
+
+block combiningCodePointsEditDistanceTest:
+  const s = "A\xCC\x8Age"
+  doAssert editDistance(s, "Age") == 1
+
+doAssert editDistanceAscii("", "") == 0
+doAssert editDistanceAscii("kitten", "sitting") == 3 # from Wikipedia
+doAssert editDistanceAscii("flaw", "lawn") == 2 # from Wikipedia
+
+
+doAssert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffix") == 0)
+doAssert(editDistance("prefix__hallo_suffix", "prefix__hallo_suffi1") == 1)
+doAssert(editDistance("prefix__hallo_suffix", "prefix__HALLO_suffix") == 5)
+doAssert(editDistance("prefix__hallo_suffix", "prefix__ha_suffix") == 3)
+doAssert(editDistance("prefix__hallo_suffix", "prefix") == 14)
+doAssert(editDistance("prefix__hallo_suffix", "suffix") == 14)
+doAssert(editDistance("prefix__hallo_suffix", "prefix__hao_suffix") == 2)
+doAssert(editDistance("main", "malign") == 2)
\ No newline at end of file
diff --git a/tests/stdlib/tencodings.nim b/tests/stdlib/tencodings.nim
new file mode 100644
index 000000000..2f4daaba3
--- /dev/null
+++ b/tests/stdlib/tencodings.nim
@@ -0,0 +1,107 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/encodings
+import std/assertions
+
+var fromGBK = open("utf-8", "gbk")
+var toGBK = open("gbk", "utf-8")
+
+var fromGB2312 = open("utf-8", "gb2312")
+var toGB2312 = open("gb2312", "utf-8")
+
+
+block:
+  let data = "\215\237\186\243\178\187\214\170\204\236\212\218\203\174\163\172\194\250\180\178\208\199\195\206\209\185\208\199\186\211"
+  doAssert fromGBK.convert(data) == "醉后不知天在水,满床星梦压星河"
+
+block:
+  let data = "万两黄金容易得,知心一个也难求"
+  doAssert toGBK.convert(data) == "\205\242\193\189\187\198\189\240\200\221\210\215\181\195\163\172\214\170\208\196\210\187\184\246\210\178\196\209\199\243"
+
+
+block:
+  let data = "\215\212\208\197\200\203\201\250\182\254\176\217\196\234\163\172\187\225\181\177\203\174\187\247\200\253\199\167\192\239"
+  doAssert fromGB2312.convert(data) == "自信人生二百年,会当水击三千里"
+
+block:
+  let data = "谁怕?一蓑烟雨任平生"
+  doAssert toGB2312.convert(data) == "\203\173\197\194\163\191\210\187\203\242\209\204\211\234\200\206\198\189\201\250"
+
+
+when defined(windows):
+  block should_throw_on_unsupported_conversions:
+    let original = "some string"
+
+    doAssertRaises(EncodingError):
+      discard convert(original, "utf-8", "utf-32")
+
+    doAssertRaises(EncodingError):
+      discard convert(original, "utf-8", "unicodeFFFE")
+
+    doAssertRaises(EncodingError):
+      discard convert(original, "utf-8", "utf-32BE")
+
+    doAssertRaises(EncodingError):
+      discard convert(original, "unicodeFFFE", "utf-8")
+
+    doAssertRaises(EncodingError):
+      discard convert(original, "utf-32", "utf-8")
+
+    doAssertRaises(EncodingError):
+      discard convert(original, "utf-32BE", "utf-8")
+
+  block should_convert_from_utf16_to_utf8:
+    let original = "\x42\x04\x35\x04\x41\x04\x42\x04" # utf-16 little endian test string "тест"
+    let result = convert(original, "utf-8", "utf-16")
+    doAssert(result == "\xd1\x82\xd0\xb5\xd1\x81\xd1\x82")
+
+  block should_convert_from_utf16_to_win1251:
+    let original = "\x42\x04\x35\x04\x41\x04\x42\x04" # utf-16 little endian test string "тест"
+    let result = convert(original, "windows-1251", "utf-16")
+    doAssert(result == "\xf2\xe5\xf1\xf2")
+
+  block should_convert_from_win1251_to_koi8r:
+    let original = "\xf2\xe5\xf1\xf2" # win1251 test string "тест"
+    let result = convert(original, "koi8-r", "windows-1251")
+    doAssert(result == "\xd4\xc5\xd3\xd4")
+
+  block should_convert_from_koi8r_to_win1251:
+    let original = "\xd4\xc5\xd3\xd4" # koi8r test string "тест"
+    let result = convert(original, "windows-1251", "koi8-r")
+    doAssert(result == "\xf2\xe5\xf1\xf2")
+
+  block should_convert_from_utf8_to_win1251:
+    let original = "\xd1\x82\xd0\xb5\xd1\x81\xd1\x82" # utf-8 test string "тест"
+    let result = convert(original, "windows-1251", "utf-8")
+    doAssert(result == "\xf2\xe5\xf1\xf2")
+
+  block should_convert_from_utf8_to_utf16:
+    let original = "\xd1\x82\xd0\xb5\xd1\x81\xd1\x82" # utf-8 test string "тест"
+    let result = convert(original, "utf-16", "utf-8")
+    doAssert(result == "\x42\x04\x35\x04\x41\x04\x42\x04")
+
+  block should_handle_empty_string_for_any_conversion:
+    let original = ""
+    var result = convert(original, "utf-16", "utf-8")
+    doAssert(result == "")
+    result = convert(original, "utf-8", "utf-16")
+    doAssert(result == "")
+    result = convert(original, "windows-1251", "koi8-r")
+    doAssert(result == "")
+
+
+block:
+  let
+    orig = "öäüß"
+    cp1252 = convert(orig, "CP1252", "UTF-8")
+    ibm850 = convert(cp1252, "ibm850", "CP1252")
+    current = getCurrentEncoding()
+  doAssert orig == "\195\182\195\164\195\188\195\159"
+  doAssert ibm850 == "\148\132\129\225"
+  doAssert convert(ibm850, current, "ibm850") == orig
+
+block: # fixes about #23481
+  doAssertRaises EncodingError:
+    discard open(destEncoding="this is a invalid enc")
diff --git a/tests/stdlib/tenumerate.nim b/tests/stdlib/tenumerate.nim
new file mode 100644
index 000000000..2789ebe3a
--- /dev/null
+++ b/tests/stdlib/tenumerate.nim
@@ -0,0 +1,24 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/enumerate
+import std/assertions
+
+let a = @[1, 3, 5, 7]
+
+block:
+  var res: seq[(int, int)]
+  for i, x in enumerate(a):
+    res.add (i, x)
+  doAssert res == @[(0, 1), (1, 3), (2, 5), (3, 7)]
+block:
+  var res: seq[(int, int)]
+  for (i, x) in enumerate(a.items):
+    res.add (i, x)
+  doAssert res == @[(0, 1), (1, 3), (2, 5), (3, 7)]
+block:
+  var res: seq[(int, int)]
+  for i, x in enumerate(3, a):
+    res.add (i, x)
+  doAssert res == @[(3, 1), (4, 3), (5, 5), (6, 7)]
diff --git a/tests/stdlib/tenumutils.nim b/tests/stdlib/tenumutils.nim
new file mode 100644
index 000000000..2662a660d
--- /dev/null
+++ b/tests/stdlib/tenumutils.nim
@@ -0,0 +1,49 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import std/enumutils
+from std/sequtils import toSeq
+import std/assertions
+
+template main =
+  block: # items
+    type A = enum a0 = 2, a1 = 4, a2
+    type B[T] = enum b0 = 2, b1 = 4
+    doAssert A.toSeq == [a0, a1, a2]
+    doAssert B[float].toSeq == [B[float].b0, B[float].b1]
+
+  block: # symbolName
+    block:
+      type A2 = enum a20, a21, a22
+      doAssert $a21 == "a21"
+      doAssert a21.symbolName == "a21"
+      proc `$`(a: A2): string = "foo"
+      doAssert $a21 == "foo"
+      doAssert a21.symbolName == "a21"
+      var a = a22
+      doAssert $a == "foo"
+      doAssert a.symbolName == "a22"
+
+    type B = enum
+      b0 = (10, "kb0")
+      b1 = "kb1"
+      b2
+    let b = B.low
+    doAssert b.symbolName == "b0"
+    doAssert $b == "kb0"
+    static: doAssert B.high.symbolName == "b2"
+
+  block:
+    type
+      Color = enum
+        Red = "red", Yellow = "yellow", Blue = "blue"
+
+    var s = Red
+    doAssert symbolName(s) == "Red"
+    var x: range[Red..Blue] = Yellow
+    doAssert symbolName(x) == "Yellow"
+
+static: main()
+main()
diff --git a/tests/stdlib/tenvvars.nim b/tests/stdlib/tenvvars.nim
new file mode 100644
index 000000000..1a07f02b8
--- /dev/null
+++ b/tests/stdlib/tenvvars.nim
@@ -0,0 +1,162 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  joinable: false
+  targets: "c js cpp"
+"""
+
+import std/envvars
+from std/sequtils import toSeq
+import stdtest/testutils
+import std/[assertions]
+
+when not defined(js):
+  import std/typedthreads
+
+# "LATIN CAPITAL LETTER AE" in UTF-8 (0xc386)
+const unicodeUtf8 = "\xc3\x86"
+
+template main =
+  block: # delEnv, existsEnv, getEnv, envPairs
+    for val in ["val", "", unicodeUtf8]: # ensures empty val works too
+      const key = "NIM_TESTS_TOSENV_KEY"
+      doAssert not existsEnv(key)
+
+      putEnv(key, "tempval")
+      doAssert existsEnv(key)
+      doAssert getEnv(key) == "tempval"
+
+      putEnv(key, val) # change a key that already exists
+      doAssert existsEnv(key)
+      doAssert getEnv(key) == val
+
+      doAssert (key, val) in toSeq(envPairs())
+      delEnv(key)
+      doAssert (key, val) notin toSeq(envPairs())
+      doAssert not existsEnv(key)
+      delEnv(key) # deleting an already deleted env var
+      doAssert not existsEnv(key)
+
+    block:
+      doAssert getEnv("NIM_TESTS_TOSENV_NONEXISTENT", "") == ""
+      doAssert getEnv("NIM_TESTS_TOSENV_NONEXISTENT", " ") == " "
+      doAssert getEnv("NIM_TESTS_TOSENV_NONEXISTENT", "defval") == "defval"
+
+    whenVMorJs: discard # xxx improve
+    do:
+      doAssertRaises(OSError, putEnv("NIM_TESTS_TOSENV_PUT=DUMMY_VALUE", "NEW_DUMMY_VALUE"))
+      doAssertRaises(OSError, putEnv("", "NEW_DUMMY_VALUE"))
+      doAssert not existsEnv("")
+      doAssert not existsEnv("NIM_TESTS_TOSENV_PUT=DUMMY_VALUE")
+      doAssert not existsEnv("NIM_TESTS_TOSENV_PUT")
+
+static: main()
+main()
+
+when defined(windows):
+  import std/widestrs
+  proc c_wgetenv(env: WideCString): WideCString {.importc: "_wgetenv", header: "<stdlib.h>".}
+proc c_getenv(env: cstring): cstring {.importc: "getenv", header: "<stdlib.h>".}
+
+when not defined(js) and not defined(nimscript):
+  block: # bug #18533
+    var thr: Thread[void]
+    proc threadFunc {.thread.} = putEnv("foo", "fooVal2")
+
+    putEnv("foo", "fooVal1")
+    doAssert getEnv("foo") == "fooVal1"
+    createThread(thr, threadFunc)
+    joinThreads(thr)
+    when defined(windows):
+      doAssert getEnv("foo") == $c_wgetenv("foo".newWideCString)
+    else:
+      doAssert getEnv("foo") == $c_getenv("foo".cstring)
+
+    doAssertRaises(OSError): delEnv("foo=bar")
+
+when defined(windows) and not defined(nimscript):
+  import std/encodings
+
+  proc c_putenv(env: cstring): int32 {.importc: "putenv", header: "<stdlib.h>".}
+  proc c_wputenv(env: WideCString): int32 {.importc: "_wputenv", header: "<stdlib.h>".}
+
+  block: # Bug #20083
+    # These test that `getEnv`, `putEnv` and `existsEnv` handle Unicode
+    # characters correctly. This means that module X in the process calling the
+    # CRT environment variable API will get the correct string. Raw CRT API
+    # calls below represent module X.
+
+    # Getting an env. var. with unicode characters returns the correct UTF-8
+    # encoded string.
+    block:
+      const envName = "twin_envvars1"
+      doAssert c_wputenv(newWideCString(envName & "=" & unicodeUtf8)) == 0
+      doAssert existsEnv(envName)
+      doAssert getEnv(envName) == unicodeUtf8
+
+    # Putting an env. var. with unicode characters gives the correct UTF-16
+    # encoded string from low-level routine.
+    block:
+      const envName = "twin_envvars2"
+      putEnv(envName, unicodeUtf8)
+      doAssert $c_wgetenv(envName.newWideCString) == unicodeUtf8
+
+    # Env. name containing Unicode characters is retrieved correctly
+    block:
+      const envName = unicodeUtf8 & "1"
+      doAssert c_wputenv(newWideCString(envName & "=" & unicodeUtf8)) == 0
+      doAssert existsEnv(envName)
+      doAssert getEnv(envName) == unicodeUtf8
+
+    # Env. name containing Unicode characters is set correctly
+    block:
+      const envName = unicodeUtf8 & "2"
+      putEnv(envName, unicodeUtf8)
+      doAssert existsEnv(envName)
+      doAssert $c_wgetenv(envName.newWideCString) == unicodeUtf8
+
+    # Env. name containing Unicode characters and empty value is set correctly
+    block:
+      const envName = unicodeUtf8 & "3"
+      putEnv(envName, "")
+      doAssert existsEnv(envName)
+      doAssert $c_wgetenv(envName.newWideCString) == ""
+
+    # It's hard to test on Windows code pages, because there is no "change
+    # a process' locale" API.
+    if getCurrentEncoding(true) == "windows-1252":
+      const
+        unicodeAnsi = "\xc6" # `unicodeUtf8` in `windows-1252` encoding
+
+      # Test that env. var. ANSI API has correct encoding
+      block:
+        const
+          envName = unicodeUtf8 & "4"
+          envNameAnsi = unicodeAnsi & "4"
+        putEnv(envName, unicodeUtf8)
+        doAssert $c_getenv(envNameAnsi.cstring) == unicodeAnsi
+
+      block:
+        const
+          envName = unicodeUtf8 & "5"
+          envNameAnsi = unicodeAnsi & "5"
+        doAssert c_putenv((envNameAnsi & "=" & unicodeAnsi).cstring) == 0
+        doAssert getEnv(envName) == unicodeUtf8
+
+      # Env. name containing Unicode characters and empty value is set correctly;
+      # and, if env. name. characters cannot be represented in codepage, don't
+      # raise an error.
+      #
+      # `win_setenv.nim` converts UTF-16 to ANSI when setting empty env. var. The
+      # windows-1250 locale has no representation of `abreveUtf8` below, so the
+      # conversion will fail, but this must not be fatal. It is expected that the
+      # routine ignores updating MBCS environment (`environ` global) and carries
+      # on.
+      block:
+        const
+          # "LATIN SMALL LETTER A WITH BREVE" in UTF-8
+          abreveUtf8 = "\xc4\x83"
+          envName = abreveUtf8 & "6"
+        putEnv(envName, "")
+        doAssert existsEnv(envName)
+        doAssert $c_wgetenv(envName.newWideCString) == ""
+        doAssert getEnv(envName) == ""
diff --git a/tests/stdlib/texitprocs.nim b/tests/stdlib/texitprocs.nim
new file mode 100644
index 000000000..ea29d8f58
--- /dev/null
+++ b/tests/stdlib/texitprocs.nim
@@ -0,0 +1,22 @@
+discard """
+matrix: "--mm:refc; --mm:orc"
+targets: "c cpp js"
+output: '''
+ok4
+ok3
+ok2
+ok1
+'''
+"""
+
+import std/exitprocs
+
+proc fun1() {.noconv.} = echo "ok1"
+proc fun2() = echo "ok2"
+proc fun3() {.noconv.} = echo "ok3"
+proc fun4() = echo "ok4"
+
+addExitProc(fun1)
+addExitProc(fun2)
+addExitProc(fun3)
+addExitProc(fun4)
diff --git a/tests/stdlib/tfdleak.nim b/tests/stdlib/tfdleak.nim
new file mode 100644
index 000000000..272a7507c
--- /dev/null
+++ b/tests/stdlib/tfdleak.nim
@@ -0,0 +1,152 @@
+discard """
+  exitcode: 0
+  output: ""
+  matrix: "; -d:nimInheritHandles; --mm:refc"
+  joinable: false
+"""
+
+import os, osproc, strutils, nativesockets, net, selectors, memfiles,
+       asyncdispatch, asyncnet
+
+import std/[assertions, syncio]
+
+when defined(windows):
+  import winlean
+
+  # Note: Windows 10-only API
+  proc compareObjectHandles(first, second: Handle): WINBOOL
+                           {.stdcall, dynlib: "kernelbase",
+                             importc: "CompareObjectHandles".}
+else:
+  import posix
+
+proc leakCheck(f: AsyncFD | int | FileHandle | SocketHandle, msg: string,
+               expectLeak = defined(nimInheritHandles)) =
+  var args = @[$f.int, msg, $expectLeak]
+
+  when defined(windows):
+    var refFd: Handle
+    # NOTE: This function shouldn't be used to duplicate sockets,
+    #       as this function may mess with the socket internal refcounting.
+    #       but due to the lack of type segmentation in the stdlib for
+    #       Windows (AsyncFD can be a file or a socket), we will have to
+    #       settle with this.
+    #
+    #       Now, as a poor solution for the refcounting problem, we just
+    #       simply let the duplicated handle leak. This should not interfere
+    #       with the test since new handles can't occupy the slot held by
+    #       the leaked ones.
+    if duplicateHandle(getCurrentProcess(), f.Handle,
+                       getCurrentProcess(), addr refFd,
+                       0, 1, DUPLICATE_SAME_ACCESS) == 0:
+      raiseOSError osLastError(), "Couldn't create the reference handle"
+    args.add $refFd
+
+  discard startProcess(
+    getAppFilename(),
+    args = args,
+    options = {poParentStreams}
+  ).waitForExit
+
+proc isValidHandle(f: int): bool =
+  ## Check if a handle is valid. Requires OS-native handles.
+  when defined(windows):
+    var flags: DWORD
+    result = getHandleInformation(f.Handle, addr flags) != 0
+  else:
+    result = fcntl(f.cint, F_GETFD) != -1
+
+proc main() =
+  if paramCount() == 0:
+    # Parent process
+    let f = syncio.open("__test_fdleak", fmReadWrite)
+    defer: close f
+
+    leakCheck(f.getOsFileHandle, "system.open()")
+
+    doAssert f.reopen("__test_fdleak2", fmReadWrite), "reopen failed"
+
+    leakCheck(f.getOsFileHandle, "reopen")
+
+    let sock = createNativeSocket()
+    defer: close sock
+    leakCheck(sock, "createNativeSocket()")
+    if sock.setInheritable(not defined(nimInheritHandles)):
+      leakCheck(sock, "createNativeSocket()", not defined(nimInheritHandles))
+    else:
+      raiseOSError osLastError()
+
+    let server = newSocket()
+    defer: close server
+    server.bindAddr(address = "127.0.0.1")
+    server.listen()
+    let (_, port) = server.getLocalAddr
+
+    leakCheck(server.getFd, "newSocket()")
+
+    let client = newSocket()
+    defer: close client
+    client.connect("127.0.0.1", port)
+
+    var input: Socket
+    server.accept(input)
+
+    leakCheck(input.getFd, "accept()")
+
+    # ioselectors_select doesn't support returning a handle.
+    when not defined(windows):
+      let selector = newSelector[int]()
+      leakCheck(selector.getFd, "selector()", false)
+
+    var mf = memfiles.open("__test_fdleak3", fmReadWrite, newFileSize = 1)
+    defer: close mf
+    when defined(windows):
+      leakCheck(mf.mapHandle, "memfiles.open().mapHandle", false)
+    else:
+      leakCheck(mf.handle, "memfiles.open().handle", false)
+
+    let sockAsync = createAsyncNativeSocket()
+    defer: closeSocket sockAsync
+    leakCheck(sockAsync, "createAsyncNativeSocket()")
+    if sockAsync.setInheritable(not defined(nimInheritHandles)):
+      leakCheck(sockAsync, "createAsyncNativeSocket()", not defined(nimInheritHandles))
+    else:
+      raiseOSError osLastError()
+
+    let serverAsync = newAsyncSocket()
+    defer: close serverAsync
+    serverAsync.bindAddr(address = "127.0.0.1")
+    serverAsync.listen()
+    let (_, portAsync) = serverAsync.getLocalAddr
+
+    leakCheck(serverAsync.getFd, "newAsyncSocket()")
+
+    let clientAsync = newAsyncSocket()
+    defer: close clientAsync
+    waitFor clientAsync.connect("127.0.0.1", portAsync)
+
+    let inputAsync = waitFor serverAsync.accept()
+
+    leakCheck(inputAsync.getFd, "accept() async")
+  else:
+    let
+      fd = parseInt(paramStr 1)
+      expectLeak = parseBool(paramStr 3)
+      msg = (if expectLeak: "not " else: "") & "leaked " & paramStr 2
+    let validHandle =
+      when defined(windows):
+        # On Windows, due to the use of winlean, causes the program to open
+        # a handle to the various dlls that's loaded. This handle might
+        # collide with the handle sent for testing.
+        #
+        # As a walkaround, we pass an another handle that's purposefully leaked
+        # as a reference so that we can verify whether the "leaked" handle
+        # is the right one.
+        let refFd = parseInt(paramStr 4)
+        fd.isValidHandle and compareObjectHandles(fd, refFd) != 0
+      else:
+        fd.isValidHandle
+    if expectLeak xor validHandle:
+      echo msg
+
+when isMainModule: main()
diff --git a/tests/stdlib/tfdleak_multiple.nim b/tests/stdlib/tfdleak_multiple.nim
new file mode 100644
index 000000000..c26681217
--- /dev/null
+++ b/tests/stdlib/tfdleak_multiple.nim
@@ -0,0 +1,31 @@
+discard """
+joinable: false
+"""
+
+import os, osproc, strutils
+import std/assertions
+
+const Iterations = 200
+
+proc testFdLeak() =
+  var count = 0
+  let
+    test = getAppDir() / "tfdleak"
+    exe = test.addFileExt(ExeExt).quoteShell
+    options = ["", "-d:nimInheritHandles"]
+  for opt in options:
+    let
+      run = "nim c $1 $2" % [opt, quoteShell test]
+      (output, status) = execCmdEx run
+    doAssert status == 0, "Test complination failed:\n$1\n$2" % [run, output]
+    for i in 1..Iterations:
+      let (output, status) = execCmdEx exe
+      doAssert status == 0, "Execution of " & exe & " failed"
+      if "leaked" in output:
+        count.inc
+    doAssert count == 0, "Leaked " & $count & " times"
+
+when defined(windows):
+  # tfdleak was only flaky for windows (and for netbsd, there is still a bug)
+  # note that this test is quite slow, 87 sec on windows.
+  testFdLeak()
diff --git a/tests/stdlib/tfenv.nim b/tests/stdlib/tfenv.nim
new file mode 100644
index 000000000..a486b8a9d
--- /dev/null
+++ b/tests/stdlib/tfenv.nim
@@ -0,0 +1,8 @@
+import std/fenv
+import std/assertions
+
+
+func is_significant(x: float): bool =
+  x > minimumPositiveValue(float) and x < maximumPositiveValue(float)
+
+doAssert is_significant(10.0)
diff --git a/tests/stdlib/tfilesanddirs.nim b/tests/stdlib/tfilesanddirs.nim
new file mode 100644
index 000000000..a1920d4f2
--- /dev/null
+++ b/tests/stdlib/tfilesanddirs.nim
@@ -0,0 +1,36 @@
+import std/[paths, files, dirs, appdirs]
+
+from stdtest/specialpaths import buildDir
+import std/[syncio, assertions]
+
+block fileOperations:
+  let files = @[Path"these.txt", Path"are.x", Path"testing.r", Path"files.q"]
+  let dirs = @[Path"some", Path"created", Path"test", Path"dirs"]
+
+  let dname = Path"__really_obscure_dir_name"
+
+  createDir(dname.Path)
+  doAssert dirExists(Path(dname))
+ 
+  # Test creating files and dirs
+  for dir in dirs:
+    createDir(Path(dname/dir))
+    doAssert dirExists(Path(dname/dir))
+
+  for file in files:
+    let fh = open(string(dname/file), fmReadWrite) # createFile
+    fh.close()
+    doAssert fileExists(Path(dname/file))
+
+block: # getCacheDir
+  doAssert getCacheDir().dirExists
+
+block: # moveFile
+  let tempDir = getTempDir() / Path("D20221022T151608")
+  createDir(tempDir)
+  defer: removeDir(tempDir)
+
+block: # moveDir
+  let tempDir = getTempDir() / Path("D20220609T161443")
+  createDir(tempDir)
+  defer: removeDir(tempDir)
diff --git a/tests/stdlib/tfrexp1.nim b/tests/stdlib/tfrexp1.nim
index a32ecbc23..aa734ddac 100644
--- a/tests/stdlib/tfrexp1.nim
+++ b/tests/stdlib/tfrexp1.nim
@@ -1,9 +1,10 @@
 discard """
-  targets: "js c c++"
-  output: '''ok'''
+  matrix: "--mm:refc; --mm:orc"
+  targets: "js c cpp"
 """
 
-import math
+import std/math
+import std/assertions
 
 const manualTest = false
 
@@ -41,6 +42,14 @@ when manualTest:
 
   frexp_test(-1000.0, 1000.0, 0.0125)
 else:
-  frexp_test(-1000000.0, 1000000.0, 0.125)
+  frexp_test(-200000.0, 200000.0, 0.125)
 
-echo "ok"
+
+doAssert frexp(8.0) == (0.5, 4)
+doAssert frexp(-8.0) == (-0.5, 4)
+doAssert frexp(0.0) == (0.0, 0)
+
+block:
+  var x: int
+  doAssert frexp(5.0, x) == 0.625
+  doAssert x == 3
diff --git a/tests/stdlib/tgenast.nim b/tests/stdlib/tgenast.nim
new file mode 100644
index 000000000..d99c9312e
--- /dev/null
+++ b/tests/stdlib/tgenast.nim
@@ -0,0 +1,274 @@
+discard """
+  matrix: "--mm:orc; --mm:refc"
+"""
+
+# xxx also test on js
+
+import std/genasts
+import std/macros
+from std/strformat import `&`
+import std/assertions
+import ./mgenast
+
+proc main =
+  block:
+    macro bar(x0: static Foo, x1: Foo, x2: Foo, xignored: Foo): untyped =
+      let s0 = "not captured!"
+      let s1 = "not captured!"
+      let xignoredLocal = kfoo4
+
+      # newLit optional:
+      let x3 = newLit kfoo4
+      let x3b = kfoo4
+
+      result = genAstOpt({kDirtyTemplate}, s1=true, s2="asdf", x0, x1=x1, x2, x3, x3b):
+        doAssert not declared(xignored)
+        doAssert not declared(xignoredLocal)
+        (s1, s2, s0, x0, x1, x2, x3, x3b)
+
+    let s0 = "caller scope!"
+
+    doAssert bar(kfoo1, kfoo2, kfoo3, kfoo4) ==
+      (true, "asdf", "caller scope!", kfoo1, kfoo2, kfoo3, kfoo4, kfoo4)
+
+  block:
+    # doesn't have limitation mentioned in https://github.com/nim-lang/RFCs/issues/122#issue-401636535
+    macro abc(name: untyped): untyped =
+      result = genAst(name):
+        type name = object
+
+    abc(Bar)
+    doAssert Bar.default == Bar()
+
+  block:
+    # backticks parser limitations / ambiguities not are an issue with `genAst`:
+    # (#10326 #9745 are fixed but `quote do` still has underlying ambiguity issue
+    # with backticks)
+    type Foo = object
+      a: int
+
+    macro m1(): untyped =
+      # result = quote do: # Error: undeclared identifier: 'a1'
+      result = genAst:
+        template `a1=`(x: var Foo, val: int) =
+          x.a = val
+
+    m1()
+    var x0: Foo
+    x0.a1 = 10
+    doAssert x0 == Foo(a: 10)
+
+  block:
+    # avoids bug #7375
+    macro fun(b: static[bool], b2: bool): untyped =
+      result = newStmtList()
+    macro foo(c: bool): untyped =
+      var b = false
+      result = genAst(b, c):
+        fun(b, c)
+
+    foo(true)
+
+  block:
+    # avoids bug #7589
+    # since `==` works with genAst, the problem goes away
+    macro foo2(): untyped =
+      # result = quote do: # Error: '==' cannot be passed to a procvar
+      result = genAst:
+        `==`(3,4)
+    doAssert not foo2()
+
+  block:
+    # avoids bug #7726
+    # expressions such as `a.len` are just passed as arguments to `genAst`, and
+    # caller scope is not polluted with definitions such as `let b = newLit a.len`
+    macro foo(): untyped =
+      let a = @[1, 2, 3, 4, 5]
+      result = genAst(a, b = a.len): # shows 2 ways to get a.len
+        (a.len, b)
+    doAssert foo() == (5, 5)
+
+  block:
+    # avoids bug #9607
+    proc fun1(info:LineInfo): string = "bar1"
+    proc fun2(info:int): string = "bar2"
+
+    macro bar2(args: varargs[untyped]): untyped =
+      let info = args.lineInfoObj
+      let fun1 = bindSym"fun1" # optional; we can remove this and also the
+      # capture of fun1, as show in next example
+      result = genAst(info, fun1):
+        (fun1(info), fun2(info.line))
+    doAssert bar2() == ("bar1", "bar2")
+
+    macro bar3(args: varargs[untyped]): untyped =
+      let info = args.lineInfoObj
+      result = genAst(info):
+        (fun1(info), fun2(info.line))
+    doAssert bar3() == ("bar1", "bar2")
+
+    macro bar(args: varargs[untyped]): untyped =
+      let info = args.lineInfoObj
+      let fun1 = bindSym"fun1"
+      let fun2 = bindSym"fun2"
+      result = genAstOpt({kDirtyTemplate}, info):
+        (fun1(info), fun2(info.line))
+    doAssert bar() == ("bar1", "bar2")
+
+  block:
+    # example from bug #7889 works
+    # after changing method call syntax to regular call syntax; this is a
+    # limitation described in bug #7085
+    # note that `quote do` would also work after that change in this example.
+    doAssert bindme2() == kfoo1
+    doAssert bindme3() == kfoo1
+    doAssert not compiles(bindme4()) # correctly gives Error: undeclared identifier: 'myLocalPriv'
+    proc myLocalPriv2(): auto = kfoo2
+    doAssert bindme5UseExpose() == kfoo1
+
+    # example showing hijacking behavior when using `kDirtyTemplate`
+    doAssert bindme5UseExposeFalse() == kfoo2
+      # local `myLocalPriv2` hijacks symbol `mgenast.myLocalPriv2`. In most
+      # use cases this is probably not what macro writer intends as it's
+      # surprising; hence `kDirtyTemplate` is not the default.
+
+    when nimvm: # disabled because `newStringStream` is used
+      discard
+    else:
+      bindme6UseExpose()
+      bindme6UseExposeFalse()
+
+  block:
+    macro mbar(x3: Foo, x3b: static Foo): untyped =
+      var x1=kfoo3
+      var x2=newLit kfoo3
+      var x4=kfoo3
+      var xLocal=kfoo3
+
+      proc funLocal(): auto = kfoo4
+
+      result = genAst(x1, x2, x3, x4):
+        # local x1 overrides remote x1
+        when false:
+          # one advantage of using `kDirtyTemplate` is that these would hold:
+          doAssert not declared xLocal
+          doAssert not compiles(echo xLocal)
+          # however, even without it, we at least correctly generate CT error
+          # if trying to use un-captured symbol; this correctly gives:
+          # Error: internal error: environment misses: xLocal
+          echo xLocal
+
+        proc foo1(): auto =
+          # note that `funLocal` is captured implicitly, according to hygienic
+          # template rules; with `kDirtyTemplate` it would not unless
+          # captured in `genAst` capture list explicitly
+          (a0: xRemote, a1: x1, a2: x2, a3: x3, a4: x4, a5: funLocal())
+
+      return result
+
+    proc main()=
+      var xRemote=kfoo1
+      var x1=kfoo2
+      mbar(kfoo4, kfoo4)
+      doAssert foo1() == (a0: kfoo1, a1: kfoo3, a2: kfoo3, a3: kfoo4, a4: kfoo3, a5: kfoo4)
+
+    main()
+
+  block:
+    # With `kDirtyTemplate`, the example from #8220 works.
+    # See https://nim-lang.github.io/Nim/strformat.html#limitations for
+    # an explanation of why {.dirty.} is needed.
+    macro foo(): untyped =
+      result = genAstOpt({kDirtyTemplate}):
+        let bar = "Hello, World"
+        &"Let's interpolate {bar} in the string"
+    doAssert foo() == "Let's interpolate Hello, World in the string"
+
+
+  block: # nested application of genAst
+    macro createMacro(name, obj, field: untyped): untyped =
+      result = genAst(obj = newDotExpr(obj, field), lit = 10, name, field):
+        # can't reuse `result` here, would clash
+        macro name(arg: untyped): untyped =
+          genAst(arg2=arg): # somehow `arg2` rename is needed
+            (obj, astToStr(field), lit, arg2)
+
+    var x = @[1, 2, 3]
+    createMacro foo, x, len
+    doAssert (foo 20) == (3, "len", 10, 20)
+
+  block: # test with kNoNewLit
+    macro bar(): untyped =
+      let s1 = true
+      template boo(x): untyped =
+        fun(x)
+      result = genAstOpt({kNoNewLit}, s1=newLit(s1), s1b=s1): (s1, s1b)
+    doAssert bar() == (true, 1)
+
+  block: # sanity check: check passing `{}` also works
+    macro bar(): untyped =
+      result = genAstOpt({}, s1=true): s1
+    doAssert bar() == true
+
+  block: # test passing function and type symbols
+    proc z1(): auto = 41
+    type Z4 = type(1'i8)
+    macro bar(Z1: typedesc): untyped =
+      proc z2(): auto = 42
+      proc z3[T](a: T): auto = 43
+      let Z2 = genAst():
+        type(true)
+      let z4 = genAst():
+        proc myfun(): auto = 44
+        myfun
+      type Z3 = type(1'u8)
+      result = genAst(z4, Z1, Z2):
+        # z1, z2, z3, Z3, Z4 are captured automatically
+        # z1, z2, z3 can optionally be specified in capture list
+        (z1(), z2(), z3('a'), z4(), $Z1, $Z2, $Z3, $Z4)
+    type Z1 = type('c')
+    doAssert bar(Z1) == (41, 42, 43, 44, "char", "bool", "uint8", "int8")
+
+  block: # fix bug #11986
+    proc foo(): auto =
+      var s = { 'a', 'b' }
+      # var n = quote do: `s` # would print {97, 98}
+      var n = genAst(s): s
+      n.repr
+    static: doAssert foo() == "{'a', 'b'}"
+
+  block: # also from #11986
+    macro foo(): untyped =
+      var s = { 'a', 'b' }
+      # quote do:
+      #   let t = `s`
+      #   $typeof(t) # set[range 0..65535(int)]
+      genAst(s):
+        let t = s
+        $typeof(t)
+    doAssert foo() == "set[char]"
+
+  block:
+    macro foo(): untyped =
+      type Foo = object
+      template baz2(a: int): untyped = a*10
+      macro baz3(a: int): untyped = newLit 13
+      result = newStmtList()
+
+      result.add genAst(Foo, baz2, baz3) do: # shows you can pass types, templates etc
+        var x: Foo
+        $($typeof(x), baz2(3), baz3(4))
+
+      let ret = genAst() do: # shows you don't have to, since they're inject'd
+        var x: Foo
+        $($typeof(x), baz2(3), baz3(4))
+    doAssert foo() == """("Foo", 30, 13)"""
+
+  block: # illustrates how symbol visiblity can be controlled precisely using `mixin`
+    proc locafun1(): auto = "in locafun1 (caller scope)" # this will be used because of `mixin locafun1` => explicit hijacking is ok
+    proc locafun2(): auto = "in locafun2 (caller scope)" # this won't be used => no hijacking
+    proc locafun3(): auto = "in locafun3 (caller scope)"
+    doAssert mixinExample() == ("in locafun1 (caller scope)", "in locafun2", "in locafun3 (caller scope)")
+
+static: main()
+main()
diff --git a/tests/stdlib/tgetaddrinfo.nim b/tests/stdlib/tgetaddrinfo.nim
index 225546aa9..3a90034c8 100644
--- a/tests/stdlib/tgetaddrinfo.nim
+++ b/tests/stdlib/tgetaddrinfo.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   exitcode: 0
   output: ""
 """
@@ -6,6 +7,7 @@ discard """
 # bug: https://github.com/nim-lang/Nim/issues/10198
 
 import nativesockets
+import std/assertions
 
 block DGRAM_UDP:
   let aiList = getAddrInfo("127.0.0.1", 999.Port, AF_INET, SOCK_DGRAM, IPPROTO_UDP)
@@ -15,7 +17,7 @@ block DGRAM_UDP:
   doAssert aiList.ai_next == nil
   freeAddrInfo aiList
 
-when defined(posix) and not defined(haiku) and not defined(freebsd):
+when defined(posix) and not defined(haiku) and not defined(freebsd) and not defined(openbsd) and not defined(netbsd):
 
   block RAW_ICMP:
     # the port will be ignored
diff --git a/tests/stdlib/tgetfileinfo.nim b/tests/stdlib/tgetfileinfo.nim
index d5ccdea56..ae1480a4c 100644
--- a/tests/stdlib/tgetfileinfo.nim
+++ b/tests/stdlib/tgetfileinfo.nim
@@ -1,8 +1,11 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: "pcDir\npcFile\npcLinkToDir\npcLinkToFile\n"
+  joinable: false
 """
 
 import os, strutils
+import std/[syncio, assertions]
 # Cases
 #  1 - String : Existing File : Symlink true
 #  2 - String : Existing File : Symlink false
@@ -20,7 +23,7 @@ proc genBadFileName(limit = 100): string =
     var hitLimit = true
 
     for i in 0..100:
-      if existsFile(result):
+      if fileExists(result):
         result.add("a")
       else:
         hitLimit = false
@@ -125,10 +128,37 @@ proc testGetFileInfo =
       echo pcLinkToDir
       echo pcLinkToFile
 
+    doAssert dirInfo.isSpecial == false
+    doAssert fileInfo.isSpecial == false
+    when defined(posix):
+      doAssert linkDirInfo.isSpecial == false
+      doAssert linkFileInfo.isSpecial == false
+
     removeDir(dirPath)
     removeFile(filePath)
     when defined(posix):
       removeFile(linkDirPath)
       removeFile(linkFilePath)
 
+  # Test that `isSpecial` is set correctly
+  block:
+    when defined(posix):
+      let
+        tmp = getTempDir()
+        fifoPath     = tmp / "test-fifo"
+        linkFifoPath = tmp / "test-link-fifo"
+
+      doAssert execShellCmd("mkfifo " & fifoPath) == 0
+      createSymlink(fifoPath, linkFifoPath)
+
+      let
+        fifoInfo = getFileInfo(fifoPath)
+        linkFifoInfo = getFileInfo(linkFifoPath)
+
+      doAssert fifoInfo.isSpecial == true
+      doAssert linkFifoInfo.isSpecial == true
+
+      removeFile(fifoPath)
+      removeFile(linkFifoPath)
+
 testGetFileInfo()
diff --git a/tests/stdlib/tgetprotobyname.nim b/tests/stdlib/tgetprotobyname.nim
new file mode 100644
index 000000000..1fc060ffe
--- /dev/null
+++ b/tests/stdlib/tgetprotobyname.nim
@@ -0,0 +1,19 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import nativesockets
+import std/assertions
+
+doAssert getProtoByName("ipv6") == 41
+doAssert getProtoByName("tcp") == 6
+doAssert getProtoByName("udp") == 17
+doAssert getProtoByName("icmp") == 1
+doAssert getProtoByName("ipv6-icmp") == 58
+
+when defined(windows):
+  doAssertRaises(OSError):
+    discard getProtoByName("raw")
+
+doAssertRaises(OSError):
+  discard getProtoByName("Error")
diff --git a/tests/stdlib/tglobs.nim b/tests/stdlib/tglobs.nim
new file mode 100644
index 000000000..4aa21992c
--- /dev/null
+++ b/tests/stdlib/tglobs.nim
@@ -0,0 +1,25 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/private/globs
+import std/assertions
+
+template main =
+  when defined(windows):
+    doAssert nativeToUnixPath("C:") == "/C"
+    doAssert nativeToUnixPath(r"D:\") == "/D/"
+    doAssert nativeToUnixPath(r"E:\a") == "/E/a"
+    doAssert nativeToUnixPath(r"E:\a1\") == "/E/a1/"
+    doAssert nativeToUnixPath(r"E:\a1\bc") == "/E/a1/bc"
+    doAssert nativeToUnixPath(r"\a1\bc") == "/a1/bc"
+    doAssert nativeToUnixPath(r"a1\bc") == "a1/bc"
+    doAssert nativeToUnixPath("a1") == "a1"
+    doAssert nativeToUnixPath("") == ""
+    doAssert nativeToUnixPath(".") == "."
+    doAssert nativeToUnixPath("..") == ".."
+    doAssert nativeToUnixPath(r"..\") == "../"
+    doAssert nativeToUnixPath(r"..\..\.\") == "../.././"
+
+static: main()
+main()
diff --git a/tests/stdlib/thashes.nim b/tests/stdlib/thashes.nim
index 2cd1e4e47..4555fbcb3 100644
--- a/tests/stdlib/thashes.nim
+++ b/tests/stdlib/thashes.nim
@@ -1,17 +1,242 @@
-
 discard """
-output: '''
-[Suite] hashes
+  matrix: "--mm:refc; --mm:orc; --backend:cpp; --backend:js --jsbigint64:on; --backend:c -d:nimStringHash2; --backend:cpp -d:nimStringHash2; --backend:js -d:nimStringHash2"
+"""
 
-[Suite] hashing
+import std/hashes
+from stdtest/testutils import disableVm, whenVMorJs
+import std/assertions
 
-'''
-"""
+when not defined(js) and not defined(cpp):
+  block:
+    var x = 12
+    iterator hello(): int {.closure.} =
+      yield x
+
+    discard hash(hello)
+
+block hashes:
+  block hashing:
+    var dummy = 0.0
+    doAssert hash(dummy) == hash(-dummy)
+
+  # "VM and runtime should make the same hash value (hashIdentity)"
+  block:
+    const hi123 = hashIdentity(123)
+    doAssert hashIdentity(123) == hi123
+
+  # "VM and runtime should make the same hash value (hashWangYi1)"
+  block:
+    const wy123 = hashWangYi1(123)
+    doAssert wy123 != 0
+    doAssert hashWangYi1(123) == wy123
+    const wyNeg123 = hashWangYi1(-123)
+    doAssert wyNeg123 != 0
+    when not defined(js): # TODO: fixme it doesn't work for JS
+      doAssert hashWangYi1(-123) == wyNeg123
+
+
+  # "hashIdentity value incorrect at 456"
+  block:
+    doAssert hashIdentity(456) == 456
+
+  # "hashWangYi1 value incorrect at 456"
+  block:
+    when Hash.sizeof < 8:
+      doAssert hashWangYi1(456) == 1293320666
+    else:
+      doAssert hashWangYi1(456) == -6421749900419628582
+
+template jsNoInt64: untyped =
+  when defined js:
+    when compiles(compileOption("jsbigint64")):
+      when not compileOption("jsbigint64"): true
+      else: false
+    else: false
+  else: false
+const sHash2 = (when defined(nimStringHash2) or jsNoInt64(): true else: false)
+
+block empty:
+  const emptyStrHash = # Hash=int=4B on js even w/--jsbigint64:on => cast[Hash]
+    when sHash2: 0 else: cast[Hash](-7286425919675154353i64)
+  var
+    a = ""
+    b = newSeq[char]()
+    c = newSeq[int]()
+    d = cstring""
+    e = "abcd"
+  doAssert hash(a) == emptyStrHash
+  doAssert hash(b) == emptyStrHash
+  doAssert hash(c) == 0
+  doAssert hash(d) == emptyStrHash
+  doAssert hashIgnoreCase(a) == 0
+  doAssert hashIgnoreStyle(a) == 0
+  doAssert hash(e, 3, 2) == emptyStrHash
+
+block sameButDifferent:
+  doAssert hash("aa bb aaaa1234") == hash("aa bb aaaa1234", 0, 13)
+  doAssert hash("aa bb aaaa1234") == hash(cstring"aa bb aaaa1234")
+  doAssert hashIgnoreCase("aA bb aAAa1234") == hashIgnoreCase("aa bb aaaa1234")
+  doAssert hashIgnoreStyle("aa_bb_AAaa1234") == hashIgnoreCase("aaBBAAAa1234")
+
+block smallSize: # no multibyte hashing
+  let
+    xx = @['H', 'i']
+    ii = @[72'u8, 105]
+    ss = "Hi"
+  doAssert hash(xx) == hash(ii)
+  doAssert hash(xx) == hash(ss)
+  doAssert hash(xx) == hash(xx, 0, xx.high)
+  doAssert hash(ss) == hash(ss, 0, ss.high)
+
+block largeSize: # longer than 4 characters
+  let
+    xx = @['H', 'e', 'l', 'l', 'o']
+    xxl = @['H', 'e', 'l', 'l', 'o', 'w', 'e', 'e', 'n', 's']
+    ssl = "Helloweens"
+  doAssert hash(xxl) == hash(ssl)
+  doAssert hash(xxl) == hash(xxl, 0, xxl.high)
+  doAssert hash(ssl) == hash(ssl, 0, ssl.high)
+  doAssert hash(xx) == hash(xxl, 0, 4)
+  doAssert hash(xx) == hash(ssl, 0, 4)
+  doAssert hash(xx, 0, 3) == hash(xxl, 0, 3)
+  doAssert hash(xx, 0, 3) == hash(ssl, 0, 3)
+
+proc main() =
+  doAssert hash(0.0) == hash(0)
+  # bug #16061
+  when not sHash2: # Hash=int=4B on js even w/--jsbigint64:on => cast[Hash]
+    doAssert hash(cstring"abracadabra") == cast[Hash](-1119910118870047694i64)
+  else:
+    doAssert hash(cstring"abracadabra") == 97309975
+  doAssert hash(cstring"abracadabra") == hash("abracadabra")
+
+  when sizeof(int) == 8 or defined(js):
+    block:
+      var s: seq[Hash]
+      for a in [0.0, 1.0, -1.0, 1000.0, -1000.0]:
+        let b = hash(a)
+        doAssert b notin s
+        s.add b
+    when defined(js):
+      doAssert hash(0.345602) == 2035867618
+      doAssert hash(234567.45) == -20468103
+      doAssert hash(-9999.283456) == -43247422
+      doAssert hash(84375674.0) == 707542256
+    else:
+      doAssert hash(0.345602) == 387936373221941218
+      doAssert hash(234567.45) == -8179139172229468551
+      doAssert hash(-9999.283456) == 5876943921626224834
+      doAssert hash(84375674.0) == 1964453089107524848
+  else:
+    doAssert hash(0.345602) != 0
+    doAssert hash(234567.45) != 0
+    doAssert hash(-9999.283456) != 0
+    doAssert hash(84375674.0) != 0
+
+  block: # bug #16555
+    proc fn(): auto =
+      # avoids hardcoding values
+      var a = "abc\0def"
+      var b = a.cstring
+      result = (hash(a), hash(b))
+      doAssert result[0] != result[1]
+    when not defined(js):
+      doAssert fn() == static(fn())
+    else:
+      # xxx this is a tricky case; consistency of hashes for cstring's containing
+      # '\0\' matters for c backend but less for js backend since such strings
+      # are much less common in js backend; we make vm for js backend consistent
+      # with c backend instead of js backend because FFI code (or other) could
+      # run at CT, expecting c semantics.
+      discard
+
+  block: # hash(object)
+    type
+      Obj = object
+        x: int
+        y: string
+      Obj2[T] = object
+        x: int
+        y: string
+      Obj3 = object
+        x: int
+        y: string
+      Obj4 = object
+        case t: bool
+        of false:
+          x: int
+        of true:
+          y: int
+        z: int
+      Obj5 = object
+        case t: bool
+        of false:
+          x: int
+        of true:
+          y: int
+        z: int
+
+    proc hash(a: Obj2): Hash = hash(a.x)
+    proc hash(a: Obj3): Hash = hash((a.x,))
+    proc hash(a: Obj5): Hash =
+      case a.t
+      of false: hash(a.x)
+      of true: hash(a.y)
+
+    doAssert hash(Obj(x: 520, y: "Nim")) != hash(Obj(x: 520, y: "Nim2"))
+    doAssert hash(Obj2[float](x: 520, y: "Nim")) == hash(Obj2[float](x: 520, y: "Nim2"))
+    doAssert hash(Obj2[float](x: 520, y: "Nim")) != hash(Obj2[float](x: 521, y: "Nim2"))
+    doAssert hash(Obj3(x: 520, y: "Nim")) == hash(Obj3(x: 520, y: "Nim2"))
+
+    doAssert hash(Obj4(t: false, x: 1)) == hash(Obj4(t: false, x: 1))
+    doAssert hash(Obj4(t: false, x: 1)) != hash(Obj4(t: false, x: 2))
+    doAssert hash(Obj4(t: false, x: 1)) != hash(Obj4(t: true, y: 1))
+
+    doAssert hash(Obj5(t: false, x: 1)) != hash(Obj5(t: false, x: 2))
+    doAssert hash(Obj5(t: false, x: 1)) == hash(Obj5(t: true, y: 1))
+    doAssert hash(Obj5(t: false, x: 1)) != hash(Obj5(t: true, y: 2))
+
+  block: # hash(ref|ptr|pointer)
+    var a: array[10, uint8]
+    # disableVm:
+    whenVMorJs:
+      # pending fix proposed in https://github.com/nim-lang/Nim/issues/15952#issuecomment-786312417
+      discard
+    do:
+      doAssert a[0].addr.hash != a[1].addr.hash
+      doAssert cast[pointer](a[0].addr).hash == a[0].addr.hash
+
+  block: # hash(ref)
+    type A = ref object
+      x: int
+    let a = A(x: 3)
+    disableVm: # xxx Error: VM does not support 'cast' from tyRef to tyPointer
+      let ha = a.hash
+      doAssert ha != A(x: 3).hash # A(x: 3) is a different ref object from `a`.
+      a.x = 4
+      doAssert ha == a.hash # the hash only depends on the address
+
+  block: # hash(proc)
+    proc fn(a: int): auto = a*2
+    doAssert fn isnot "closure"
+    doAssert fn is (proc)
+    const fn2 = fn
+    let fn3 = fn
+    whenVMorJs: discard
+    do:
+      doAssert hash(fn2) == hash(fn)
+      doAssert hash(fn3) == hash(fn)
 
-import unittest, hashes
+  block: # hash(closure)
+    proc outer() =
+      var a = 0
+      proc inner() = a.inc
+      doAssert inner is "closure"
+      let inner2 = inner
+      whenVMorJs: discard
+      do:
+        doAssert hash(inner2) == hash(inner)
+    outer()
 
-suite "hashes":
-  suite "hashing":
-    test "0.0 and -0.0 should have the same hash value":
-      var dummy = 0.0
-      check hash(dummy) == hash(-dummy)
+static: main()
+main()
diff --git a/tests/stdlib/theapqueue.nim b/tests/stdlib/theapqueue.nim
new file mode 100644
index 000000000..afb09c7e3
--- /dev/null
+++ b/tests/stdlib/theapqueue.nim
@@ -0,0 +1,106 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/heapqueue
+import std/assertions
+
+proc toSortedSeq[T](h: HeapQueue[T]): seq[T] =
+  var tmp = h
+  result = @[]
+  while tmp.len > 0:
+    result.add(pop(tmp))
+
+proc heapProperty[T](h: HeapQueue[T]): bool =
+  for k in 0 .. h.len - 2: # the last element is always a leaf
+    let left = 2 * k + 1
+    if left < h.len and h[left] < h[k]:
+      return false
+    let right = left + 1
+    if right < h.len and h[right] < h[k]:
+      return false
+  true
+
+template main() =
+  block: # simple sanity test
+    var heap = initHeapQueue[int]()
+    let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
+    for item in data:
+      push(heap, item)
+    doAssert(heap == data.toHeapQueue)
+    doAssert(heap[0] == 0)
+    doAssert(heap.toSortedSeq == @[0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
+
+  block: # test del
+    var heap = initHeapQueue[int]()
+    let data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
+    for item in data: push(heap, item)
+
+    heap.del(0)
+    doAssert(heap[0] == 1)
+
+    heap.del(heap.find(7))
+    doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 5, 6, 8, 9])
+
+    heap.del(heap.find(5))
+    doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 6, 8, 9])
+
+    heap.del(heap.find(6))
+    doAssert(heap.toSortedSeq == @[1, 2, 3, 4, 8, 9])
+
+    heap.del(heap.find(2))
+    doAssert(heap.toSortedSeq == @[1, 3, 4, 8, 9])
+
+    doAssert(heap.find(2) == -1)
+
+  block: # test del last
+    var heap = initHeapQueue[int]()
+    let data = [1, 2, 3]
+    for item in data: push(heap, item)
+
+    heap.del(2)
+    doAssert(heap.toSortedSeq == @[1, 2])
+
+    heap.del(1)
+    doAssert(heap.toSortedSeq == @[1])
+
+    heap.del(0)
+    doAssert(heap.toSortedSeq == @[])
+
+  block: # testing the heap proeprty
+    var heap = [1, 4, 2, 5].toHeapQueue
+    doAssert heapProperty(heap)
+
+    heap.push(42)
+    doAssert heapProperty(heap)
+    heap.push(0)
+    doAssert heapProperty(heap)
+    heap.push(3)
+    doAssert heapProperty(heap)
+    heap.push(3)
+    doAssert heapProperty(heap)
+
+    # [0, 3, 1, 4, 42, 2, 3, 5]
+
+    discard heap.pop()
+    doAssert heapProperty(heap)
+    discard heap.pop()
+    doAssert heapProperty(heap)
+
+    heap.del(2)
+    doAssert heapProperty(heap)
+
+    # [2, 3, 5, 4, 42]
+
+    discard heap.replace(12)
+    doAssert heapProperty(heap)
+    discard heap.replace(1)
+    doAssert heapProperty(heap)
+
+    discard heap.pushpop(2)
+    doAssert heapProperty(heap)
+    discard heap.pushpop(0)
+    doAssert heapProperty(heap)
+
+static: main()
+main()
diff --git a/tests/stdlib/thighlite.nim b/tests/stdlib/thighlite.nim
new file mode 100644
index 000000000..0cd334254
--- /dev/null
+++ b/tests/stdlib/thighlite.nim
@@ -0,0 +1,45 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import unittest, strutils
+import ../../lib/packages/docutils/highlite
+import std/objectdollar
+
+block: # Nim tokenizing
+  test "string literals and escape seq":
+    check("\"ok1\\nok2\\nok3\"".tokenize(langNim) ==
+       @[("\"ok1", gtStringLit), ("\\n", gtEscapeSequence), ("ok2", gtStringLit),
+         ("\\n", gtEscapeSequence), ("ok3\"", gtStringLit)
+      ])
+    check("\"\"\"ok1\\nok2\\nok3\"\"\"".tokenize(langNim) ==
+       @[("\"\"\"ok1\\nok2\\nok3\"\"\"", gtLongStringLit)
+      ])
+
+  test "whitespace at beginning of line is preserved":
+    check("  discard 1".tokenize(langNim) ==
+       @[("  ", gtWhitespace), ("discard", gtKeyword), (" ", gtWhitespace),
+         ("1", gtDecNumber)
+       ])
+
+block: # Cmd (shell) tokenizing
+  test "cmd with dollar and output":
+    check(
+      dedent"""
+        $ nim c file.nim
+        out: file [SuccessX]"""
+        .tokenize(langConsole) ==
+      @[("$ ", gtPrompt), ("nim", gtProgram),
+        (" ", gtWhitespace), ("c", gtOption), (" ", gtWhitespace),
+        ("file.nim", gtIdentifier), ("\n", gtWhitespace),
+        ("out: file [SuccessX]", gtProgramOutput)
+      ])
+
+block: # bug #21232
+  let code = "/"
+  var toknizr: GeneralTokenizer
+
+  initGeneralTokenizer(toknizr, code)
+
+  getNextToken(toknizr, langC)
+  check $toknizr == """(kind: gtOperator, start: 0, length: 1, buf: "/", pos: 1, state: gtEof, lang: langC)"""
diff --git a/tests/stdlib/thtmlparser.nim b/tests/stdlib/thtmlparser.nim
index ccf2f6202..853a1c0cc 100644
--- a/tests/stdlib/thtmlparser.nim
+++ b/tests/stdlib/thtmlparser.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
   output: '''
-@[]
 true
 https://example.com/test?format=jpg&name=orig##
 https://example.com/test?format=jpg&name=orig##text
@@ -11,7 +12,7 @@ import htmlparser
 import xmltree
 import strutils
 from streams import newStringStream
-
+import std/assertions
 
 block t2813:
   const
@@ -40,14 +41,14 @@ block t2813:
     """
   var errors: seq[string] = @[]
   let tree = parseHtml(newStringStream(html), "test.html", errors)
-  echo errors # Errors: </thead> expected,...
+  doAssert errors.len == 0 # Errors: </thead> expected,...
 
   var len = tree.findAll("tr").len # len = 6
   var rows: seq[XmlNode] = @[]
   for n in tree.findAll("table"):
     n.findAll("tr", rows)  # len = 2
     break
-  assert tree.findAll("tr").len == rows.len
+  doAssert tree.findAll("tr").len == rows.len
 
 
 block t2814:
@@ -110,21 +111,21 @@ block t6154:
   doAssert ps[0].attrsLen == 2
   doAssert ps[0].attr("class") == "foo"
   doAssert ps[0].attr("id") == "bar"
-  doassert ps[0].len == 0
+  doAssert ps[0].len == 0
 
   doAssert ps[1].attrsLen == 1
   doAssert ps[1].attr("something") == "\tfoo\tbar²"
-  doassert ps[1].len == 0
+  doAssert ps[1].len == 0
 
   doAssert ps[2].attrsLen == 2
   doAssert ps[2].attr("something") == "\tfoo\tbar²"
   doAssert ps[2].attr("foo") == "bloo"
-  doassert ps[2].len == 0
+  doAssert ps[2].len == 0
 
   doAssert ps[3].attrsLen == 2
   doAssert ps[3].attr("class") == "foo2"
   doAssert ps[3].attr("id") == "bar2"
-  doassert ps[3].len == 0
+  doAssert ps[3].len == 0
 
   doAssert ps[4].attrsLen == 1
   doAssert ps[4].attr("wrong") == ""
@@ -133,12 +134,12 @@ block t6154:
   doAssert ps[5].attr("data-foo") == ""
   doAssert ps[5].attr("data-bar") == "correct!"
   doAssert ps[5].attr("enabled") == ""
-  doassert ps[5].len == 0
+  doAssert ps[5].len == 0
 
   doAssert ps[6].attrsLen == 2
   doAssert ps[6].attr("quux") == ""
   doAssert ps[6].attr("whatever") == ""
-  doassert ps[6].len == 0
+  doAssert ps[6].len == 0
 
 # bug #11713, #1034
 var content = """
diff --git a/tests/stdlib/thttpclient.nim b/tests/stdlib/thttpclient.nim
index 66fc123e3..0bd479670 100644
--- a/tests/stdlib/thttpclient.nim
+++ b/tests/stdlib/thttpclient.nim
@@ -1,23 +1,30 @@
 discard """
   cmd: "nim c --threads:on -d:ssl $file"
-  exitcode: 0
-  output: "OK"
-  disabled: true
+  disabled: "openbsd"
+  disabled: "freebsd"
+  disabled: "windows"
 """
 
+#[
+disabled: see https://github.com/timotheecour/Nim/issues/528
+]#
+
 import strutils
 from net import TimeoutError
 
 import nativesockets, os, httpclient, asyncdispatch
 
+import std/[assertions, syncio]
+from stdtest/testutils import enableRemoteNetworking
+
 const manualTests = false
 
 proc makeIPv6HttpServer(hostname: string, port: Port,
     message: string): AsyncFD =
-  let fd = newNativeSocket(AF_INET6)
+  let fd = createNativeSocket(AF_INET6)
   setSockOptInt(fd, SOL_SOCKET, SO_REUSEADDR, 1)
   var aiList = getAddrInfo(hostname, port, AF_INET6)
-  if bindAddr(fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32:
+  if bindAddr(fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
     freeAddrInfo(aiList)
     raiseOSError(osLastError())
   freeAddrInfo(aiList)
@@ -39,19 +46,20 @@ proc makeIPv6HttpServer(hostname: string, port: Port,
 
 proc asyncTest() {.async.} =
   var client = newAsyncHttpClient()
-  var resp = await client.request("http://example.com/")
+  var resp = await client.request("http://example.com/", HttpGet)
   doAssert(resp.code.is2xx)
   var body = await resp.body
   body = await resp.body # Test caching
   doAssert("<title>Example Domain</title>" in body)
 
   resp = await client.request("http://example.com/404")
-  doAssert(resp.code.is4xx)
-  doAssert(resp.code == Http404)
-  doAssert(resp.status == Http404)
+  doAssert(resp.code.is4xx or resp.code.is5xx)
+  doAssert(resp.code == Http404 or resp.code == Http500)
+  doAssert(resp.status == $Http404 or resp.status == $Http500)
 
-  resp = await client.request("https://google.com/")
-  doAssert(resp.code.is2xx or resp.code.is3xx)
+  when false: # occasionally does not give success code 
+    resp = await client.request("https://google.com/")
+    doAssert(resp.code.is2xx or resp.code.is3xx)
 
   # getContent
   try:
@@ -102,17 +110,18 @@ proc asyncTest() {.async.} =
 
 proc syncTest() =
   var client = newHttpClient()
-  var resp = client.request("http://example.com/")
+  var resp = client.request("http://example.com/", HttpGet)
   doAssert(resp.code.is2xx)
   doAssert("<title>Example Domain</title>" in resp.body)
 
   resp = client.request("http://example.com/404")
-  doAssert(resp.code.is4xx)
-  doAssert(resp.code == Http404)
-  doAssert(resp.status == Http404)
+  doAssert(resp.code.is4xx or resp.code.is5xx)
+  doAssert(resp.code == Http404 or resp.code == Http500)
+  doAssert(resp.status == $Http404 or resp.status == $Http500)
 
-  resp = client.request("https://google.com/")
-  doAssert(resp.code.is2xx or resp.code.is3xx)
+  when false: # occasionally does not give success code
+    resp = client.request("https://google.com/")
+    doAssert(resp.code.is2xx or resp.code.is3xx)
 
   # getContent
   try:
@@ -144,6 +153,12 @@ proc syncTest() =
 
   client.close()
 
+  # SIGSEGV on HEAD body read: issue #16743
+  block:
+    let client = newHttpClient()
+    let resp = client.head("http://httpbin.org/head")
+    doAssert(resp.body == "")
+
   when false:
     # Disabled for now because it causes troubles with AppVeyor
     # Timeout test.
@@ -166,7 +181,7 @@ proc ipv6Test() =
   client.close()
 
 ipv6Test()
-syncTest()
-waitFor(asyncTest())
 
-echo "OK"
+when enableRemoteNetworking:
+  syncTest()
+  waitFor(asyncTest())
diff --git a/tests/stdlib/thttpclient_ssl.nim b/tests/stdlib/thttpclient_ssl.nim
new file mode 100644
index 000000000..6b963f029
--- /dev/null
+++ b/tests/stdlib/thttpclient_ssl.nim
@@ -0,0 +1,150 @@
+discard """
+  cmd: "nim $target --mm:refc -d:ssl $options $file"
+  disabled: "openbsd"
+"""
+
+#            Nim - Basic SSL integration tests
+#        (c) Copyright 2018 Nim contributors
+#
+#    See the file "copying.txt", included in this
+#    distribution, for details about the copyright.
+#
+## Warning: this test performs local networking.
+## Test with:
+## ./bin/nim c -d:ssl -p:. --threads:on -r tests/stdlib/thttpclient_ssl.nim
+
+
+from stdtest/testutils import disableSSLTesting
+
+when not defined(windows) and not disableSSLTesting():
+  # Disabled on Windows due to old OpenSSL version
+  import std/[formatfloat, syncio]
+  import
+    httpclient,
+    net,
+    openssl,
+    os,
+    strutils,
+    threadpool,
+    times,
+    unittest
+
+  # bogus self-signed certificate
+  const
+    certFile = "tests/stdlib/thttpclient_ssl_cert.pem"
+    keyFile = "tests/stdlib/thttpclient_ssl_key.pem"
+
+  proc log(msg: string) =
+    when defined(ssldebug):
+      echo "    [" & $epochTime() & "] " & msg
+    # FIXME
+    echo "    [" & $epochTime() & "] " & msg
+    discard
+
+  proc runServer(port: Port): bool {.thread.} =
+    ## Run a trivial HTTPS server in a {.thread.}
+    ## Exit after serving one request
+
+    var socket = newSocket()
+    socket.setSockOpt(OptReusePort, true)
+    socket.bindAddr(port)
+
+    var ctx = newContext(certFile=certFile, keyFile=keyFile)
+
+    ##  Handle one connection
+    socket.listen()
+
+    var client: Socket
+    var address = ""
+
+    log "server: ready"
+    socket.acceptAddr(client, address)
+    log "server: incoming connection"
+
+    var ssl: SslPtr = SSL_new(ctx.context)
+    discard SSL_set_fd(ssl, client.getFd())
+    log "server: accepting connection"
+    ErrClearError()
+    if SSL_accept(ssl) <= 0:
+      ERR_print_errors_fp(stderr)
+    else:
+      const reply = "HTTP/1.0 200 OK\r\nServer: test\r\nContent-type: text/html\r\nContent-Length: 0\r\n\r\n"
+      log "server: sending reply"
+      discard SSL_write(ssl, reply.cstring, reply.len)
+
+    log "server: receiving a line"
+    let line = client.recvLine()
+    log "server: received $# bytes" % $line.len
+    log "closing"
+    SSL_free(ssl)
+    close(client)
+    close(socket)
+    log "server: exited"
+
+
+  suite "SSL self signed certificate check":
+
+    test "TCP socket":
+      const port = 12347.Port
+      let t = spawn runServer(port)
+      sleep(100)
+      var sock = newSocket()
+      var ctx = newContext()
+      ctx.wrapSocket(sock)
+      try:
+        log "client: connect"
+        sock.connect("127.0.0.1", port)
+        fail()
+      except:
+        let msg = getCurrentExceptionMsg()
+        check(msg.contains("certificate verify failed"))
+
+    test "HttpClient default: no check":
+      const port = 12345.Port
+      let t = spawn runServer(port)
+      sleep(100)
+
+      var client = newHttpClient(sslContext=newContext(verifyMode=CVerifyNone))
+      try:
+        log "client: connect"
+        discard client.getContent("https://127.0.0.1:12345")
+      except:
+        let msg = getCurrentExceptionMsg()
+        log "client: unexpected exception: " & msg
+        fail()
+
+    test "HttpClient with CVerifyPeer":
+      const port = 12346.Port
+      let t = spawn runServer(port)
+      sleep(100)
+
+      var client = newHttpClient(sslContext=newContext(verifyMode=CVerifyPeer))
+      try:
+        log "client: connect"
+        discard client.getContent("https://127.0.0.1:12346")
+        log "getContent should have raised an exception"
+        fail()
+      except:
+        let msg = getCurrentExceptionMsg()
+        log "client: exception: " & msg
+        # SSL_shutdown:shutdown while in init
+        if not (msg.contains("alert number 48") or
+          msg.contains("certificate verify failed")):
+          echo "CVerifyPeer exception: " & msg
+          check(false)
+
+    test "HttpClient with CVerifyPeerUseEnvVars":
+      const port = 12346.Port
+      let t = spawn runServer(port)
+      sleep(100)
+
+      putEnv("SSL_CERT_FILE", getCurrentDir() / certFile)
+      var client = newHttpClient(sslContext=newContext(verifyMode=CVerifyPeerUseEnvVars))
+      try:
+        log "client: connect"
+        discard client.getContent("https://127.0.0.1:12346")
+      except:
+        let msg = getCurrentExceptionMsg()
+        log "client: exception: " & msg
+        log "getContent should not have raised an exception"
+        fail()
diff --git a/tests/stdlib/thttpclient_ssl_cert.pem b/tests/stdlib/thttpclient_ssl_cert.pem
new file mode 100644
index 000000000..f15c15c52
--- /dev/null
+++ b/tests/stdlib/thttpclient_ssl_cert.pem
@@ -0,0 +1,29 @@
+-----BEGIN CERTIFICATE-----
+MIIFCTCCAvGgAwIBAgIURYQOmGzeh3Vy7Gk6Go4uAPwcNwAwDQYJKoZIhvcNAQEL
+BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTE5MDEyMzAwMTgzNFoXDTQ2MDYw
+OTAwMTgzNFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIICIjANBgkqhkiG9w0BAQEF
+AAOCAg8AMIICCgKCAgEAzoEVEl7yqY+RqIagXDD4JB7LyONDvh8aJvBMnJVBgjaL
+JdkfQjvPGUzUkEbU5nc6u7lqFxzEv7hXrssQCB7TwJwfS2PT1Rj14IFlYPyw4DEe
+P1RVS/awurtv3jwumarVl7LR+IQfo59kJ/P8jZt8H3HscDbyhXcHeOWI6q+XlfdV
+mTUJVvABdUuOiIFjgfFVTpo+CKxy7c5caRDK7g1s9xB1/M9PUfJvHY1WrBWFOZf0
+Bl8iwn+ahuxfIVqsFL9leqLykgi1f4L20p7RaAK95TXCo3CszZm4Fsw9zhzkjoU7
+2h0nuYl197LZvRs3u/JJjzZERmsfVPIs5BtO8/MN1MvRn6hIGU5Q3kOVWqWxSkSl
+njrf+uwUdn/24uSCnygNeDuJzwW/2q4N9YI3oovqNIGpkT3FbAm7UKwI4lwhwmqw
+7WH+92ELj0BinmsMMRPD2OqvK+vzLVqwUIQkYug+Hjys6QGXMlrL0krrj7XOKSc3
+SvZa4j0S/Y5CKkw5xuZXxITsdaV6hGi3d/kuT+1ttOSfIIXJXDEiu4pYRfziKU1a
+8EhHMEajEi6ueLw7QmEPVx398erRwiUuP2y43yZ4mwVwvN3i5jlVztl4XsglDmQ+
+hahstVdMMA34K2rK0U8q8YjdYm+z99NmGEPYrS6Qnpr1xrICN83FOWFI0k7ttyMC
+AwEAAaNTMFEwHQYDVR0OBBYEFLqMY6eP3h3gu+ANs77xDBRnElxyMB8GA1UdIwQY
+MBaAFLqMY6eP3h3gu+ANs77xDBRnElxyMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI
+hvcNAQELBQADggIBAJS+wyy0r+tVAlCa6V/xxlCDtW9n6L2nsqJXEjME0VvwGs3m
+ima68LyTQJqCSjjxSotaNOYKzUu4vRA3JssV+fUDR+NpmhpRuM74XmO05HUQkp9U
+dBEHyXp2aRQ9LSdvHo5D+RW+J4sHFb3PbU8NPx/t5Dg7il92S2QJQz1jNl+Nezc6
+2O8Vt1YbvWXfqM47URTpnQbWoo38pI44AgAuW3QagucKWsyounmhx65XcdtLn99g
+oZt496pU+hBpYu/IpXuBKNC4FvOrXTWAPkAbbYP39UFyiKwIyTosK+qdbhBlt1xi
+bBPn6N1W9L2BvUwM8fEB/qBuR9UfcMsIYJsWbbXMfyeF6lbaP7xD01rm+yU5PMMI
+Co40abixMntz4J3T2ixdCptf0He1U/UegOHwG1ZGgQzvOG6qI/xkNktDaSA75KR7
+BvPV1CmZC4ovVo1L4STrwnoRz5J49PNOHi9Okj9zJ99H7nsmsK16oxpIYkYHJWn+
+45jpG8SlDp7oev1OGGk/z+ZOTz+LcNxyvsRQVN8w5zNmjCSWiGqz+UUgppCZg8qd
+ECWokNQ5Lr20t1whynrX5bH0l887WPCQmm5VduRoyKFGhCRBSzcCtowSpiwZglUk
+CV0jgFKoteItdzZgsND5I1GaNOxZlnK3wN4H0pgZv7HlW6SP1OYd2Y67waJ7
+-----END CERTIFICATE-----
diff --git a/tests/stdlib/thttpclient_ssl_key.pem b/tests/stdlib/thttpclient_ssl_key.pem
new file mode 100644
index 000000000..6ab04122c
--- /dev/null
+++ b/tests/stdlib/thttpclient_ssl_key.pem
@@ -0,0 +1,52 @@
+-----BEGIN PRIVATE KEY-----
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDOgRUSXvKpj5Go
+hqBcMPgkHsvI40O+Hxom8EyclUGCNosl2R9CO88ZTNSQRtTmdzq7uWoXHMS/uFeu
+yxAIHtPAnB9LY9PVGPXggWVg/LDgMR4/VFVL9rC6u2/ePC6ZqtWXstH4hB+jn2Qn
+8/yNm3wfcexwNvKFdwd45Yjqr5eV91WZNQlW8AF1S46IgWOB8VVOmj4IrHLtzlxp
+EMruDWz3EHX8z09R8m8djVasFYU5l/QGXyLCf5qG7F8hWqwUv2V6ovKSCLV/gvbS
+ntFoAr3lNcKjcKzNmbgWzD3OHOSOhTvaHSe5iXX3stm9Gze78kmPNkRGax9U8izk
+G07z8w3Uy9GfqEgZTlDeQ5VapbFKRKWeOt/67BR2f/bi5IKfKA14O4nPBb/arg31
+gjeii+o0gamRPcVsCbtQrAjiXCHCarDtYf73YQuPQGKeawwxE8PY6q8r6/MtWrBQ
+hCRi6D4ePKzpAZcyWsvSSuuPtc4pJzdK9lriPRL9jkIqTDnG5lfEhOx1pXqEaLd3
++S5P7W205J8ghclcMSK7ilhF/OIpTVrwSEcwRqMSLq54vDtCYQ9XHf3x6tHCJS4/
+bLjfJnibBXC83eLmOVXO2XheyCUOZD6FqGy1V0wwDfgrasrRTyrxiN1ib7P302YY
+Q9itLpCemvXGsgI3zcU5YUjSTu23IwIDAQABAoICAQCdR60/57cUs/dxjs/2R4nH
+IPl/ELEYzeGCRMVlATz6qwZCFmN7c8ghceX32SrwOWEvd2G5Jr0ndIS76YdVV/1Z
+ls8zAV5m0HL8wjDvtKYWqvJps5afm80w+++RKO8pNPcnahgIGsFqQszqrSbux7y6
+ym8VbJQ8WNMFHnWwoXpnyxCT9tQdNgE2UAzIJRwf7SpXCp0yx/1k6CZ0E0ksFGeo
+qQ3kNhUoyegdbvfTazSkD/rZG36C+uM73i36Xm/wAXKN/CuaVC3AZ4QMGNBPUr9F
+IzQSfY/vrCOMoZR1NoZRkmJqlogaBPsnZD34jRFfAYNLIz7PD2m2rhjIx4/Tt4wQ
+5mUwga9ud0ly5wSzswudw07mTYtsLbWrUn6QdFxSwbQ0tXh9PJrqCSJDmYIptuu/
+6zjg8hQLg7y37xMDMCdKtviHx+ndVpW3StTwB/z7lDA6yuYY6nYN0dJTJS3qQheo
+maPG4Xf4FBcD4Is73BjBCf3QR6WIv0ZOG3/GZ1OqLRrPg1u/3UJkpa4LE/6qNUxf
+zdBZSPyQZExBvOqdklEI+1OcqofmWq2n7Amct45buDbFryehEhfJ1HHtkXkTEsut
+azfQeaGem/jKxcTD+1bWs/Q5Nn+QFfKr0NFjXSLoITWQkgQD1qISw3DC72jYXlsm
+S4CmCDW1dHZlmWZq+Mh34QKCAQEA+2JFRa1yYZ0tPt88sOjJYyw9yUxB9Nv9cKrs
+kdkhKHKevF+0BUbRLfp9bod+Wlv66pgQi6ZGKkGD7lCam/3FIBlmmiG8AOoXdoGy
+t17XCzlYy348mnHra2X+JBAN51ivPemdlGZShLbNMkGdL1khtjHL9vSr1KgFn3F/
+8nstVQ9nzHTCK0HWpBGn/EK3dd8lcYZDd7Fcgjz7E3xQDz/XZt0HMwwGaLnQ1L7T
+glIyeNdqLBp4v0NT6L1AAk5rQJONo57AepblwacYhoW9mR5K0bm/BMo5+xwMtYz9
+69ZuMNW8qdaWrzeEsxM1PDbcOoVqChF10w0Ih/MkhKGpN/GxUQKCAQEA0kvWUkEK
+1BBhwGyuKrMnUC3jnQ36KpsjlryMUArdjS2gVBztGW2p2CUWasEgZdxpwQmnqKyz
+4hcZaU/JUleutTI5raxzju4Ve87c+koOiamhw/zaiLCpLn2j0Rh2qxp7QvPPRO0V
+1MN347wjCTx/5/j8WffgWqWfqdrd8JheKal/OHlTZA3DG77FIVnUyov8Np+lTd1x
+NpWr/AOreZlMBq/X/kmWCe+fP901fGdi3cdsKcJcdLPv9KFciSjBlAlaLMnBgLWo
+RrIuNxdH3dRX4rzBSpdNq72n8NaH+A10eoXrlC4eWLo7vRSTe4WRgUAIbhVifnJk
+z4B5FqC/aVgkMwKCAQEAtq983h0lcbDy76z2Ay65I/xDzqU/jX3OGfHtSDS+NxHN
+L+JxBiCn5b0TKJ8JAQu1NoVaCNLGTPEdurQTF+f9OM2c1chMQ3HbqUCqKz6eEscT
+M5dC3Y6KYptVbMnKAOVfPSQoY29U6qOaTbqHS6B/slNQAeFfeoS8yVmHfSVtFVLD
+wT7c2OjY3pUCOn4Vq3CGWpETOMnJC9DbOhbua5aeqF9aWwuTIMpg7CrdtOidS1pp
+CzIVrBF2yj22ZbatlNlmZpD5Gl3NDMWtOh25Yqwz/WP6YLXCGy4QQmP7KEfF/nFl
+0RtkmGNFaYo89sx7kX/hRv3XXZAsMfhOAqElQ8W+cQKCAQAdL/lnIS/njv6CPpNN
+yd/C+RuGSNJX54BhA3pWAawOVC7Ufc9KoDXakgsydeuRN65V5IkomA+/aYVVYIWI
+sDLHY1kuCalgRRsmO+fftTefU7PoB8gtAJf6o+WAt+yAgwRonn4+Csnk5dxV917F
+gWgfQieENSsmaaZnZME5C2zGS4gkxnIUiPRzfV7O6jDmi9dNnYrL69gyw0NDjx7V
+mbk7lFxeJsh0SJXJv2IVCiRms68HfLpoWDENuvek8cssSMADR11cB9p7NW/Epa6L
+01T/W0NYnvdgxsnwW1Yzz2pDNyMjReNgXTi9XYW6tyci0UhaPw2Ujzv+sM4dneHz
+NRCRAoIBAHqXaeC1uTGSzfLvRz81ifgDRP8H9L1HLt7ZWL6XMp1ph+P6yYFXM4JK
+WeP3cdKO/kQOD/fLuhYT92T2hHEadT8CQqpsBMQt29Zlm4oYWHB7ERiZqaGX3/T0
+U1TlL0WxthoHPY2HwA6pmDTmUzDk3tFlgk+XOmLsDacBdC6EsFwA+tyEPVxmkb0J
+H+j7D4NxwysAyWCB9fWU1FV+JJJel+nz88i7Gb8uJ+kSktnFxjv/G9p+OkDYlaUt
+j8lc6LOuNOA9M7XT1BIKpZytnSVtwZWkMmu23OLMM/d07tPJYtHIa92On7XKBPc2
+6THbQsJpR5AalTVvXs3X1RnCLnHiNYg=
+-----END PRIVATE KEY-----
diff --git a/tests/stdlib/thttpclient_standalone.nim b/tests/stdlib/thttpclient_standalone.nim
new file mode 100644
index 000000000..2f432eede
--- /dev/null
+++ b/tests/stdlib/thttpclient_standalone.nim
@@ -0,0 +1,59 @@
+discard """
+  cmd: "nim c --threads:on $file"
+"""
+
+import asynchttpserver, httpclient, asyncdispatch, strutils, net
+
+import std/assertions
+
+block: # bug #16436
+  proc startServer(): AsyncHttpServer =
+    result = newAsyncHttpServer()
+    result.listen(Port(0))
+
+  proc processRequest(server: AsyncHttpServer) {.async.} =
+    proc cb(req: Request) {.async.} =
+      let headers = { "Content-length": "15"} # Provide invalid content-length
+      await req.respond(Http200, "Hello World", headers.newHttpHeaders())
+
+    await server.acceptRequest(cb)
+
+  proc runClient(port: Port) {.async.} =
+    let c = newAsyncHttpClient(headers = {"Connection": "close"}.newHttpHeaders)
+    discard await c.getContent("http://127.0.0.1:" & $port)
+    doAssert false, "should fail earlier"
+
+  let server = startServer()
+  asyncCheck processRequest(server)
+  let port = server.getPort()
+  doAssertRaises(ProtocolError):
+    waitFor runClient(port)
+
+block: # bug #14794 (And test for presence of content-length header when using postContent)
+  proc startServer(): AsyncHttpServer =
+    result = newAsyncHttpServer()
+    result.listen(Port(0))
+
+  proc runServer(server: AsyncHttpServer) {.async.} =
+    proc cb(req: Request) {.async.} =
+      doAssert(req.body.endsWith(httpNewLine), "Multipart body does not end with a newline.")
+      # this next line is probably not required because asynchttpserver does not call
+      # the callback when there is no content-length header.  It instead errors with 
+      # Error: unhandled exception: 411 Length Required
+      # Added for good measure in case the server becomes more permissive.
+      doAssert(req.headers.hasKey("content-length"), "Content-Length header is not present.")
+      asyncCheck req.respond(Http200, "OK")
+
+    await server.acceptRequest(cb)
+
+  proc runClient(port: Port) {.async.} =
+    let c = newAsyncHttpClient()
+    let data = newMultipartData()
+    data.add("file.txt", "This is intended to be an example text file.\r\nThis would be the second line.\r\n")
+    discard await c.postContent("http://127.0.0.1:" & $port, multipart = data)
+    c.close()
+
+  let server = startServer()
+  let port = server.getPort()
+  asyncCheck runServer(server)
+  waitFor runClient(port)
diff --git a/tests/stdlib/thttpcore.nim b/tests/stdlib/thttpcore.nim
index 889c734c5..93e7d85c6 100644
--- a/tests/stdlib/thttpcore.nim
+++ b/tests/stdlib/thttpcore.nim
@@ -1,31 +1,103 @@
 discard """
-output: "[Suite] httpcore"
+  matrix: "--mm:refc; --mm:orc"
 """
 
-import unittest
+import httpcore, strutils
+import std/assertions
 
-import httpcore
+block:
+  block HttpCode:
+    doAssert $Http418 == "418 I'm a teapot"
+    doAssert Http418.is4xx() == true
+    doAssert Http418.is2xx() == false
 
-suite "httpcore":
-
-  test "HttpCode":
-    assert $Http418 == "418 I'm a teapot"
-    assert Http418.is4xx() == true
-    assert Http418.is2xx() == false
-
-  test "headers":
+  block headers:
     var h = newHttpHeaders()
-    assert h.len == 0
+    doAssert h.len == 0
     h.add("Cookie", "foo")
-    assert h.len == 1
-    assert h.hasKey("cooKIE")
-    assert h["Cookie"] == "foo"
-    assert h["cookie"] == "foo"
+    doAssert h.len == 1
+    doAssert h.hasKey("cooKIE")
+    doAssert h["Cookie"] == "foo"
+    doAssert h["cookie"] == "foo"
     h["cookie"] = @["bar", "x"]
-    assert h["Cookie"] == "bar"
-    assert h["Cookie", 1] == "x"
-    assert h["Cookie"].contains("BaR") == true
-    assert h["Cookie"].contains("X") == true
-    assert "baR" in h["cookiE"]
+    doAssert h["Cookie"] == "bar"
+    doAssert h["Cookie", 1] == "x"
+    doAssert h["Cookie"].contains("BaR") == true
+    doAssert h["Cookie"].contains("X") == true
+    doAssert "baR" in h["cookiE"]
     h.del("coOKie")
-    assert h.len == 0
+    doAssert h.len == 0
+
+    # Test that header constructor works with repeated values
+    let h1 = newHttpHeaders({"a": "1", "a": "2", "A": "3"})
+
+    doAssert seq[string](h1["a"]).join(",") == "1,2,3"
+
+  block test_cookies_with_comma:
+    doAssert parseHeader("cookie: foo, bar") ==  ("cookie", @["foo, bar"])
+    doAssert parseHeader("cookie: foo, bar, prologue") == ("cookie", @["foo, bar, prologue"])
+    doAssert parseHeader("cookie: foo, bar, prologue, starlight") == ("cookie", @["foo, bar, prologue, starlight"])
+
+    doAssert parseHeader("cookie:   foo, bar") ==  ("cookie", @["foo, bar"])
+    doAssert parseHeader("cookie:  foo, bar, prologue") == ("cookie", @["foo, bar, prologue"])
+    doAssert parseHeader("cookie:   foo, bar, prologue, starlight") == ("cookie", @["foo, bar, prologue, starlight"])
+
+    doAssert parseHeader("Cookie: foo, bar") == (key: "Cookie", value: @["foo, bar"])
+    doAssert parseHeader("Cookie: foo, bar, prologue") == (key: "Cookie", value: @["foo, bar, prologue"])
+    doAssert parseHeader("Cookie: foo, bar, prologue, starlight") == (key: "Cookie", value: @["foo, bar, prologue, starlight"])
+
+    doAssert parseHeader("Accept: foo, bar") == (key: "Accept", value: @["foo", "bar"])
+    doAssert parseHeader("Accept: foo, bar, prologue") == (key: "Accept", value: @["foo", "bar", "prologue"])
+    doAssert parseHeader("Accept: foo, bar, prologue, starlight") == (key: "Accept", value: @["foo", "bar", "prologue", "starlight"])
+
+  block add_empty_sequence_to_HTTP_headers:
+    block:
+      var headers = newHttpHeaders()
+      headers["empty"] = @[]
+
+      doAssert not headers.hasKey("empty")
+
+    block:
+      var headers = newHttpHeaders()
+      headers["existing"] = "true"
+      headers["existing"] = @[]
+
+      doAssert not headers.hasKey("existing")
+
+    block:
+      var headers = newHttpHeaders()
+      headers["existing"] = @["true"]
+      headers["existing"] = @[]
+
+      doAssert not headers.hasKey("existing")
+
+    block:
+      var headers = newHttpHeaders()
+      headers["existing"] = @[]
+      headers["existing"] = @["true"]
+      doAssert headers.hasKey("existing")
+
+block:
+  var test = newHttpHeaders()
+  test["Connection"] = @["Upgrade", "Close"]
+  doAssert test["Connection", 0] == "Upgrade"
+  doAssert test["Connection", 1] == "Close"
+  test.add("Connection", "Test")
+  doAssert test["Connection", 2] == "Test"
+  doAssert "upgrade" in test["Connection"]
+
+  # Bug #5344.
+  doAssert parseHeader("foobar: ") == ("foobar", @[""])
+  let (key, value) = parseHeader("foobar: ")
+  test = newHttpHeaders()
+  test[key] = value
+  doAssert test["foobar"] == ""
+
+  doAssert parseHeader("foobar:") == ("foobar", @[""])
+
+  block: # test title case
+    var testTitleCase = newHttpHeaders(titleCase=true)
+    testTitleCase.add("content-length", "1")
+    doAssert testTitleCase.hasKey("Content-Length")
+    for key, val in testTitleCase:
+        doAssert key == "Content-Length"
diff --git a/tests/stdlib/timportutils.nim b/tests/stdlib/timportutils.nim
new file mode 100644
index 000000000..672092282
--- /dev/null
+++ b/tests/stdlib/timportutils.nim
@@ -0,0 +1,151 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/[importutils, assertions]
+import stdtest/testutils
+import mimportutils
+
+template main =
+  block: # privateAccess
+    assertAll:
+      var a: A
+      var b = initB() # B is private
+      compiles(a.a0)
+      compiles(b.b0)
+      not compiles(a.ha1)
+      not compiles(b.hb1)
+
+    block:
+      assertAll:
+        privateAccess A
+        compiles(a.ha1)
+        a.ha1 == 0.0
+        not compiles(a.hb1)
+        privateAccess b.typeof
+        b.hb1 = 3
+        type B2 = b.typeof
+        let b2 = B2(b0: 4, hb1: 5)
+        b.hb1 == 3
+        b2 == B2(b0: 4, hb1: 5)
+
+    assertAll:
+      not compiles(a.ha1)
+      not compiles(b.hb1)
+
+    block:
+      assertAll:
+        not compiles(C(c0: 1, hc1: 2))
+        privateAccess C
+        let c = C(c0: 1, hc1: 2)
+        c.hc1 == 2
+
+    block:
+      assertAll:
+        not compiles(E[int](he1: 1))
+        privateAccess E[int]
+        var e = E[int](he1: 1)
+        e.he1 == 1
+        e.he1 = 2
+        e.he1 == 2
+        e.he1 += 3
+        e.he1 == 5
+        # xxx caveat: this currently compiles but in future, we may want
+        # to make `privateAccess E[int]` only affect a specific instantiation;
+        # note that `privateAccess E` does work to cover all instantiations.
+        var e2 = E[float](he1: 1)
+
+    block:
+      assertAll:
+        not compiles(E[int](he1: 1))
+        privateAccess E
+        var e = E[int](he1: 1)
+        e.he1 == 1
+
+    block:
+      assertAll:
+        not compiles(F[int, int](h3: 1))
+        privateAccess F[int, int]
+        var e = F[int, int](h3: 1)
+        e.h3 == 1
+
+    block:
+      assertAll:
+        not compiles(F[int, int](h3: 1))
+        privateAccess F[int, int].default[].typeof
+        var e = F[int, int](h3: 1)
+        e.h3 == 1
+
+    block:
+      assertAll:
+        var a = G[int]()
+        var b = a.addr
+        privateAccess b.type
+        discard b.he1
+        discard b[][].he1
+
+    block:
+      assertAll:
+        privateAccess H[int]
+        var a = H[int](h5: 2)
+
+    block:
+      assertAll:
+        privateAccess PA
+        var pa = PA(a0: 1, ha1: 2)
+        pa.ha1 == 2
+        pa.ha1 = 3
+        pa.ha1 == 3
+
+    block:
+      assertAll:
+        var b = BAalias()
+        not compiles(b.hb1)
+        privateAccess BAalias
+        discard b.hb1
+
+    block:
+      assertAll:
+        var a = A(a0: 1)
+        var a2 = a.addr
+        not compiles(a2.ha1)
+        privateAccess PtA
+        a2.type is PtA
+        a2.ha1 = 2
+        a2.ha1 == 2
+        a.ha1 = 3
+        a2.ha1 == 3
+
+    block:
+      disableVm:
+        assertAll:
+          var a = A.create()
+          defer: dealloc(a)
+          a is PtA
+          a.typeof is PtA
+          not compiles(a.ha1)
+          privateAccess a.typeof
+          a.ha1 = 2
+          a.ha1 == 2
+          a[].ha1 = 3
+          a.ha1 == 3
+
+    block:
+      disableVm:
+        assertAll:
+          var a = A.create()
+          defer: dealloc(a)
+          privateAccess PtA
+          a.ha1 == 0
+
+    block:
+      privateAccess PityRef
+      let x = PityRef[int](a: 1)  # works
+      doAssert x.a == 1
+
+      privateAccess Hope
+      let y = Hope[int](a: 1)
+      doAssert y.a == 1
+
+static: main()
+main()
diff --git a/tests/stdlib/tintsets.nim b/tests/stdlib/tintsets.nim
new file mode 100644
index 000000000..191ef117e
--- /dev/null
+++ b/tests/stdlib/tintsets.nim
@@ -0,0 +1,6 @@
+import ./mintsets
+
+block: # bug https://github.com/nim-lang/Nim/pull/15564#issuecomment-729878104
+  # related to bug #11167
+  test1()
+  test2()
diff --git a/tests/stdlib/tio.nim b/tests/stdlib/tio.nim
new file mode 100644
index 000000000..80a119763
--- /dev/null
+++ b/tests/stdlib/tio.nim
@@ -0,0 +1,60 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+# xxx move to here other tests that belong here; io is a proper module
+
+import std/os
+from stdtest/specialpaths import buildDir
+import std/[assertions, syncio]
+
+block: # readChars
+  let file = buildDir / "D20201118T205105.txt"
+  let s = "he\0l\0lo"
+  writeFile(file, s)
+  defer: removeFile(file)
+  let f = open(file)
+  defer: close(f)
+  let n = f.getFileInfo.blockSize
+  var buf = newString(n)
+  template fn =
+    let n2 = f.readChars(buf)
+    doAssert n2 == s.len
+    doAssert buf[0..<n2] == s
+  fn()
+  setFilePos(f, 0)
+  fn()
+
+  block:
+    setFilePos(f, 0)
+    var s2: string
+    let nSmall = 2
+    for ai in buf.mitems: ai = '\0'
+    var n2s: seq[int]
+    while true:
+      let n2 = f.readChars(toOpenArray(buf, 0, nSmall-1))
+      # xxx: maybe we could support: toOpenArray(buf, 0..nSmall)
+      n2s.add n2
+      s2.add buf[0..<n2]
+      if n2 == 0:
+        break
+    doAssert n2s == @[2,2,2,1,0]
+    doAssert s2 == s
+
+
+import std/strutils
+
+block: # bug #21273
+  let FILE = buildDir / "D20220119T134305.txt"
+
+  let hex = "313632313920313632343720313632353920313632363020313632393020323035363520323037323120323131353020323239393820323331303520323332313020323332343820323332363820"
+
+
+  writeFile FILE, parseHexStr(hex)
+
+  doAssert readFile(FILE).toHex == hex
+
+  let f = open(FILE)
+  var s = newString(80)
+  while f.readLine(s):
+    doAssert s.toHex == hex
diff --git a/tests/stdlib/tisolation.nim b/tests/stdlib/tisolation.nim
new file mode 100644
index 000000000..18b83ea2e
--- /dev/null
+++ b/tests/stdlib/tisolation.nim
@@ -0,0 +1,135 @@
+discard """
+  targets: "c cpp"
+  matrix: "--gc:refc; --gc:orc"
+"""
+
+import std/[isolation, json]
+import std/[assertions, objectdollar]
+
+
+proc main(moveZeroesOut: static bool) =
+  block:
+    type
+      Empty = ref object
+
+
+    var x = isolate(Empty())
+    discard extract(x)
+
+  block: # string literals
+    var data = isolate("string")
+    doAssert data.extract == "string"
+    if moveZeroesOut:
+      doAssert data.extract == ""
+
+  block: # string literals
+    var data = isolate("")
+    doAssert data.extract == ""
+    if moveZeroesOut:
+      doAssert data.extract == ""
+
+  block:
+    var src = "string"
+    var data = isolate(move src)
+    doAssert data.extract == "string"
+    if moveZeroesOut:
+      doAssert src.len == 0
+
+  block: # int literals
+    var data = isolate(1)
+    doAssert data.extract == 1
+    if moveZeroesOut:
+      doAssert data.extract == 0
+
+  block: # float literals
+    var data = isolate(1.6)
+    doAssert data.extract == 1.6
+    if moveZeroesOut:
+      doAssert data.extract == 0.0
+
+  block:
+    var data = isolate(@["1", "2"])
+    doAssert data.extract == @["1", "2"]
+    if moveZeroesOut:
+      doAssert data.extract == @[]
+
+  block:
+    var data = isolate(@["1", "2", "3", "4", "5"])
+    doAssert data.extract == @["1", "2", "3", "4", "5"]
+    if moveZeroesOut:
+      doAssert data.extract == @[]
+
+  block:
+    var data = isolate(@["", ""])
+    doAssert data.extract == @["", ""]
+    if moveZeroesOut:
+      doAssert data.extract == @[]
+
+  block:
+    var src = @["1", "2"]
+    var data = isolate(move src)
+    doAssert data.extract == @["1", "2"]
+    if moveZeroesOut:
+      doAssert src.len == 0
+
+  block:
+    var data = isolate(@[1, 2])
+    doAssert data.extract == @[1, 2]
+    if moveZeroesOut:
+      doAssert data.extract == @[]
+
+  block:
+    var data = isolate(["1", "2"])
+    doAssert data.extract == ["1", "2"]
+    if moveZeroesOut:
+      doAssert data.extract == ["", ""]
+
+  block:
+    var data = isolate([1, 2])
+    doAssert data.extract == [1, 2]
+    if moveZeroesOut:
+      doAssert data.extract == [0, 0]
+
+  block:
+    type
+      Test = object
+        id: int
+
+    var data = isolate(Test(id: 12))
+    doAssert data.extract.id == 12
+
+  block:
+    type
+      Test = object
+        id: int
+
+    var src = Test(id: 12)
+    var data = isolate(src)
+    doAssert data.extract.id == 12
+
+  block:
+    type
+      Test = object
+        id: int
+
+    var src = Test(id: 12)
+    var data = isolate(move src)
+    doAssert data.extract.id == 12
+
+  block:
+    type
+      Test = ref object
+        id: int
+
+    var data = isolate(Test(id: 12))
+    doAssert data.extract.id == 12
+
+  block:
+    var x: seq[Isolated[JsonNode]]
+    x.add isolate(newJString("1234"))
+
+    doAssert $x == """@[(value: "1234")]"""
+
+
+static: main(moveZeroesOut = false)
+main(moveZeroesOut = true)
diff --git a/tests/stdlib/tjsbigints.nim b/tests/stdlib/tjsbigints.nim
new file mode 100644
index 000000000..29b0ac3e7
--- /dev/null
+++ b/tests/stdlib/tjsbigints.nim
@@ -0,0 +1,46 @@
+discard """
+  targets: "js"
+"""
+
+import std/[jsbigints, assertions]
+
+
+let big1: JsBigInt = big"2147483647"
+let big2: JsBigInt = big"666"
+var big3: JsBigInt = big"2"
+
+doAssert big3 == big"2"
+doAssert (big3 xor big2) == big"664"
+doAssert (big"555" and big"2") == big"2"
+doAssert (big"555" or big"2") == big"555"
+doAssert (big1 mod big2) == big"613"
+doAssert -big1 == big"-2147483647"
+doAssert big1 div big2 == big"3224449"
+doAssert big1 + big2 == big"2147484313"
+doAssert big1 - big2 == big"2147482981"
+doAssert big1 shl big3 == big"8589934588"
+doAssert big1 shr big3 == big"536870911"
+doAssert big1 * big2 == big"1430224108902"
+doAssert $big1 == "2147483647n"
+doAssert big1.toCstring(10) == "2147483647".cstring
+doAssert big2 ** big3 == big(443556)
+var huge = big"999999999999999999999999999999999999999999999999999999999999999999999999999999999999999"
+huge.inc
+huge = huge + -999999999999999999999999999999999999999999999999999999999999999999999999999999999999999'big
+doAssert huge == big"1"
+var list: seq[JsBigInt]
+for i in big"0" .. big"5":
+  doAssert i is JsBigInt
+  list.add i
+doAssert list == @[big"0", big"1", big"2", big"3", big"4", big"5"]
+list = @[]
+for i in big"0" ..< big"5":
+  doAssert i is JsBigInt
+  list.add i
+doAssert list == @[big"0", big"1", big"2", big"3", big"4"]
+
+block:
+  let b = 2'big
+  doAssert -b ** 3'big == -8'big
+  doAssert -b ** big"2" == big"4" # not -4 because of precedence
+  doAssert -big"3" == big"-3"
diff --git a/tests/stdlib/tjson.nim b/tests/stdlib/tjson.nim
new file mode 100644
index 000000000..e425501f6
--- /dev/null
+++ b/tests/stdlib/tjson.nim
@@ -0,0 +1,382 @@
+discard """
+  matrix: "; --backend:cpp; --backend:js --jsbigint64:off -d:nimStringHash2; --backend:js --jsbigint64:on"
+"""
+
+
+#[
+Note: Macro tests are in tests/stdlib/tjsonmacro.nim
+]#
+
+import std/[json,parsejson,strutils]
+import std/private/jsutils
+from std/math import isNaN
+when not defined(js):
+  import std/streams
+import stdtest/testutils
+from std/fenv import epsilon
+import std/[assertions, objectdollar]
+
+proc testRoundtrip[T](t: T, expected: string) =
+  # checks that `T => json => T2 => json2` is such that json2 = json
+  let j = %t
+  doAssert $j == expected, $j
+  doAssert %(j.to(T)) == j
+
+proc testRoundtripVal[T](t: T, expected: string) =
+  # similar to testRoundtrip, but also checks that the `T => json => T2` is such that `T2 == T`
+  # note that this isn't always possible, e.g. for pointer-like types or nans
+  let j = %t
+  doAssert $j == expected, $j
+  let j2 = ($j).parseJson
+  doAssert $j2 == expected, $(j2, t)
+  let t2 = j2.to(T)
+  doAssert t2 == t
+  doAssert $(%* t2) == expected # sanity check, because -0.0 = 0.0 but their json representation differs
+
+let testJson = parseJson"""{ "a": [1, 2, 3, 4], "b": "asd", "c": "\ud83c\udf83", "d": "\u00E6"}"""
+# nil passthrough
+doAssert(testJson{"doesnt_exist"}{"anything"}.isNil)
+testJson{["e", "f"]} = %true
+doAssert(testJson["e"]["f"].bval)
+
+# make sure UTF-16 decoding works.
+doAssert(testJson["c"].str == "🎃")
+doAssert(testJson["d"].str == "æ")
+
+# make sure no memory leek when parsing invalid string
+let startMemory = getOccupiedMem()
+for i in 0 .. 10000:
+  try:
+    discard parseJson"""{ invalid"""
+  except:
+    discard
+# memory diff should less than 4M
+doAssert(abs(getOccupiedMem() - startMemory) < 4 * 1024 * 1024)
+
+
+# test `$`
+let stringified = $testJson
+let parsedAgain = parseJson(stringified)
+doAssert(parsedAgain["b"].str == "asd")
+
+parsedAgain["abc"] = %5
+doAssert parsedAgain["abc"].num == 5
+
+# Bounds checking
+when compileOption("boundChecks"):
+  try:
+    let a = testJson["a"][9]
+    doAssert(false, "IndexDefect not thrown")
+  except IndexDefect:
+    discard
+  try:
+    let a = testJson["a"][-1]
+    doAssert(false, "IndexDefect not thrown")
+  except IndexDefect:
+    discard
+  try:
+    doAssert(testJson["a"][0].num == 1, "Index doesn't correspond to its value")
+  except:
+    doAssert(false, "IndexDefect thrown for valid index")
+
+doAssert(testJson{"b"}.getStr() == "asd", "Couldn't fetch a singly nested key with {}")
+doAssert(isNil(testJson{"nonexistent"}), "Non-existent keys should return nil")
+doAssert(isNil(testJson{"a", "b"}), "Indexing through a list should return nil")
+doAssert(isNil(testJson{"a", "b"}), "Indexing through a list should return nil")
+doAssert(testJson{"a"} == parseJson"[1, 2, 3, 4]", "Didn't return a non-JObject when there was one to be found")
+doAssert(isNil(parseJson("[1, 2, 3]"){"foo"}), "Indexing directly into a list should return nil")
+
+# Generator:
+var j = %* [{"name": "John", "age": 30}, {"name": "Susan", "age": 31}]
+doAssert j == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}]
+
+var j2 = %*
+  [
+    {
+      "name": "John",
+      "age": 30
+    },
+    {
+      "name": "Susan",
+      "age": 31
+    }
+  ]
+doAssert j2 == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}]
+
+var name = "John"
+let herAge = 30
+const hisAge = 31
+
+var j3 = %*
+  [ {"name": "John"
+    , "age": herAge
+    }
+  , {"name": "Susan"
+    , "age": hisAge
+    }
+  ]
+doAssert j3 == %[%{"name": %"John", "age": %30}, %{"name": %"Susan", "age": %31}]
+
+var j4 = %*{"test": nil}
+doAssert j4 == %{"test": newJNull()}
+
+let seqOfNodes = @[%1, %2]
+let jSeqOfNodes = %seqOfNodes
+doAssert(jSeqOfNodes[1].num == 2)
+
+type MyObj = object
+  a, b: int
+  s: string
+  f32: float32
+  f64: float64
+  next: ref MyObj
+var m: MyObj
+m.s = "hi"
+m.a = 5
+let jMyObj = %m
+doAssert(jMyObj["a"].num == 5)
+doAssert(jMyObj["s"].str == "hi")
+
+# Test loading of file.
+when not defined(js):
+  var parsed = parseFile("tests/testdata/jsontest.json")
+
+  try:
+    discard parsed["key2"][12123]
+    doAssert(false)
+  except IndexDefect: doAssert(true)
+
+  var parsed2 = parseFile("tests/testdata/jsontest2.json")
+  doAssert(parsed2{"repository", "description"}.str ==
+      "IRC Library for Haskell", "Couldn't fetch via multiply nested key using {}")
+
+doAssert escapeJsonUnquoted("\10Foo🎃barÄ") == "\\nFoo🎃barÄ"
+doAssert escapeJsonUnquoted("\0\7\20") == "\\u0000\\u0007\\u0014" # for #7887
+doAssert escapeJson("\10Foo🎃barÄ") == "\"\\nFoo🎃barÄ\""
+doAssert escapeJson("\0\7\20") == "\"\\u0000\\u0007\\u0014\"" # for #7887
+
+# Test with extra data
+when not defined(js):
+  try:
+    discard parseJson("123 456")
+    doAssert(false)
+  except JsonParsingError:
+    doAssert getCurrentExceptionMsg().contains(errorMessages[errEofExpected])
+
+  try:
+    discard parseFile("tests/testdata/jsonwithextradata.json")
+    doAssert(false)
+  except JsonParsingError:
+    doAssert getCurrentExceptionMsg().contains(errorMessages[errEofExpected])
+
+# bug #6438
+doAssert($ %*[] == "[]")
+doAssert($ %*{} == "{}")
+
+doAssert(not compiles(%{"error": "No messages"}))
+
+# bug #9111
+block:
+  type
+    Bar = string
+    Foo = object
+      a: int
+      b: Bar
+
+  let
+    js = """{"a": 123, "b": "abc"}""".parseJson
+    foo = js.to Foo
+
+  doAssert(foo.b == "abc")
+
+# Generate constructors for range[T] types
+block:
+  type
+    Q1 = range[0'u8 .. 50'u8]
+    Q2 = range[0'u16 .. 50'u16]
+    Q3 = range[0'u32 .. 50'u32]
+    Q4 = range[0'i8 .. 50'i8]
+    Q5 = range[0'i16 .. 50'i16]
+    Q6 = range[0'i32 .. 50'i32]
+    Q7 = range[0'f32 .. 50'f32]
+    Q8 = range[0'f64 .. 50'f64]
+    Q9 = range[0 .. 50]
+
+    X = object
+      m1: Q1
+      m2: Q2
+      m3: Q3
+      m4: Q4
+      m5: Q5
+      m6: Q6
+      m7: Q7
+      m8: Q8
+      m9: Q9
+
+  let obj = X(
+    m1: Q1(42),
+    m2: Q2(42),
+    m3: Q3(42),
+    m4: Q4(42),
+    m5: Q5(42),
+    m6: Q6(42),
+    m7: Q7(42),
+    m8: Q8(42),
+    m9: Q9(42)
+  )
+
+  doAssert(obj == to(%obj, type(obj)))
+
+  when not defined(js):
+    const fragments = """[1,2,3] {"hi":3} 12 [] """
+    var res = ""
+    for x in parseJsonFragments(newStringStream(fragments)):
+      res.add($x)
+      res.add " "
+    doAssert res == fragments
+
+
+# test isRefSkipDistinct
+type
+  MyRef = ref object
+  MyObject = object
+  MyDistinct = distinct MyRef
+  MyOtherDistinct = distinct MyRef
+
+var x0: ref int
+var x1: MyRef
+var x2: MyObject
+var x3: MyDistinct
+var x4: MyOtherDistinct
+
+doAssert isRefSkipDistinct(x0)
+doAssert isRefSkipDistinct(x1)
+doAssert not isRefSkipDistinct(x2)
+doAssert isRefSkipDistinct(x3)
+doAssert isRefSkipDistinct(x4)
+
+
+doAssert isRefSkipDistinct(ref int)
+doAssert isRefSkipDistinct(MyRef)
+doAssert not isRefSkipDistinct(MyObject)
+doAssert isRefSkipDistinct(MyDistinct)
+doAssert isRefSkipDistinct(MyOtherDistinct)
+
+let x = parseJson("9999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999999")
+
+doAssert x.kind == JString
+
+block: # bug #15835
+  type
+    Foo = object
+      ii*: int
+      data*: JsonNode
+
+  block:
+    const jt = """{"ii": 123, "data": ["some", "data"]}"""
+    let js = parseJson(jt)
+    discard js.to(Foo)
+
+  block:
+    const jt = """{"ii": 123}"""
+    let js = parseJson(jt)
+    doAssertRaises(KeyError):
+      echo js.to(Foo)
+
+type
+  ContentNodeKind* = enum
+    P,
+    Br,
+    Text,
+  ContentNode* = object
+    case kind*: ContentNodeKind
+    of P: pChildren*: seq[ContentNode]
+    of Br: nil
+    of Text: textStr*: string
+
+let mynode = ContentNode(kind: P, pChildren: @[
+  ContentNode(kind: Text, textStr: "mychild"),
+  ContentNode(kind: Br)
+])
+
+doAssert $mynode == """(kind: P, pChildren: @[(kind: Text, textStr: "mychild"), (kind: Br)])"""
+
+let jsonNode = %*mynode
+doAssert $jsonNode == """{"kind":"P","pChildren":[{"kind":"Text","textStr":"mychild"},{"kind":"Br"}]}"""
+doAssert $jsonNode.to(ContentNode) == """(kind: P, pChildren: @[(kind: Text, textStr: "mychild"), (kind: Br)])"""
+
+block: # bug #17383
+  testRoundtrip(int32.high): "2147483647"
+  testRoundtrip(uint32.high): "4294967295"
+  when int.sizeof == 4:
+    testRoundtrip(int.high): "2147483647"
+    testRoundtrip(uint.high): "4294967295"
+  else:
+    testRoundtrip(int.high): "9223372036854775807"
+    testRoundtrip(uint.high): "18446744073709551615"
+  whenJsNoBigInt64: discard
+  do:
+    testRoundtrip(int64.high): "9223372036854775807"
+    testRoundtrip(uint64.high): "18446744073709551615"
+
+block: # bug #18007
+  testRoundtrip([NaN, Inf, -Inf, 0.0, -0.0, 1.0]): """["nan","inf","-inf",0.0,-0.0,1.0]"""
+  # pending https://github.com/nim-lang/Nim/issues/18025 use:
+  # testRoundtrip([float32(NaN), Inf, -Inf, 0.0, -0.0, 1.0])
+  let inf = float32(Inf)
+  testRoundtrip([float32(NaN), inf, -inf, 0.0, -0.0, 1.0]): """["nan","inf","-inf",0.0,-0.0,1.0]"""
+  when not defined(js): # because of Infinity vs inf
+    testRoundtripVal([inf, -inf, 0.0, -0.0, 1.0]): """["inf","-inf",0.0,-0.0,1.0]"""
+  let a = parseJson($(%NaN)).to(float)
+  doAssert a.isNaN
+
+  whenRuntimeJs: discard # refs bug #18009
+  do:
+    testRoundtripVal(0.0): "0.0"
+    testRoundtripVal(-0.0): "-0.0"
+
+block: # bug #15397, bug #13196
+  testRoundtripVal(1.0 + epsilon(float64)): "1.0000000000000002"
+  testRoundtripVal(0.12345678901234567890123456789): "0.12345678901234568"
+
+block:
+  let a = "18446744073709551615"
+  let b = a.parseJson
+  doAssert b.kind == JString
+  let c = $b
+  when defined(js):
+    doAssert c == "18446744073709552000"
+  else:
+    doAssert c == "18446744073709551615"
+
+block:
+  let a = """
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+    [[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[[
+"""
+
+  when not defined(js):
+    try:
+      discard parseJson(a)
+    except JsonParsingError:
+      doAssert getCurrentExceptionMsg().contains("] expected")
diff --git a/tests/stdlib/tjsonmacro.nim b/tests/stdlib/tjsonmacro.nim
index 938030d8e..5a1b4b294 100644
--- a/tests/stdlib/tjsonmacro.nim
+++ b/tests/stdlib/tjsonmacro.nim
@@ -1,9 +1,11 @@
 discard """
   output: ""
+  matrix: "--mm:refc; --mm:orc"
   targets: "c js"
 """
 
 import json, strutils, options, tables
+import std/assertions
 
 # The definition of the `%` proc needs to be here, since the `% c` calls below
 # can only find our custom `%` proc for `Pix` if defined in global scope.
@@ -259,7 +261,7 @@ proc testJson() =
         colors: array[2, BirdColor]
 
     var red = BirdColor(name: "red", rgb: [1.0, 0.0, 0.0])
-    var blue = Birdcolor(name: "blue", rgb: [0.0, 0.0, 1.0])
+    var blue = BirdColor(name: "blue", rgb: [0.0, 0.0, 1.0])
     var b = Bird(age: 3, height: 1.734, name: "bardo", colors: [red, blue])
     let jnode = %b
     let data = jnode.to(Bird)
@@ -435,11 +437,7 @@ proc testJson() =
   block:
     let s = """{"a": 1, "b": 2}"""
     let t = parseJson(s).to(Table[string, int])
-    when not defined(js):
-      # For some reason on the JS backend `{"b": 2, "a": 0}` is
-      # sometimes the value of `t`. This needs investigation. I can't
-      # reproduce it right now in an isolated test.
-      doAssert t["a"] == 1
+    doAssert t["a"] == 1
     doAssert t["b"] == 2
 
   block:
@@ -497,7 +495,7 @@ proc testJson() =
     doAssert array[3, float](t.arr) == [1.0,2.0,7.0]
 
     doAssert MyRef(t.person).name == "boney"
-    doAssert MyObj(t.distFruit).color == 11
+    doAssert MyObj(t.distfruit).color == 11
     doAssert t.dog.name == "honey"
     doAssert t.fruit.color == 10
     doAssert seq[string](t.emails) == @["abc", "123"]
@@ -633,6 +631,18 @@ proc testJson() =
     except KeyError:
       doAssert getCurrentExceptionMsg().contains ".member.list[2].value"
 
+  block:
+    # Enum indexed array test
+    type Test = enum
+      one, two, three, four, five
+    let a = [
+      one: 300,
+      two: 20,
+      three: 10,
+      four: 0,
+      five: -10
+    ]
+    doAssert (%* a).to(a.typeof) == a
 
 
 testJson()
diff --git a/tests/stdlib/tjsonutils.nim b/tests/stdlib/tjsonutils.nim
new file mode 100644
index 000000000..9acf4c9e5
--- /dev/null
+++ b/tests/stdlib/tjsonutils.nim
@@ -0,0 +1,476 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+import std/jsonutils
+import std/json
+from std/math import isNaN, signbit
+from std/fenv import epsilon
+from stdtest/testutils import whenRuntimeJs
+import std/[assertions, objectdollar]
+
+proc testRoundtrip[T](t: T, expected: string) =
+  # checks that `T => json => T2 => json2` is such that json2 = json
+  let j = t.toJson
+  doAssert $j == expected, "\n" & $j & "\n" & expected
+  doAssert j.jsonTo(T).toJson == j
+  var t2: T
+  t2.fromJson(j)
+  doAssert t2.toJson == j
+
+proc testRoundtripVal[T](t: T, expected: string) =
+  # similar to testRoundtrip, but also checks that the `T => json => T2` is such that `T2 == T`
+  # note that this isn't always possible, e.g. for pointer-like types.
+  let j = t.toJson
+  let j2 = $j
+  doAssert j2 == expected, j2
+  let j3 = j2.parseJson
+  let t2 = j3.jsonTo(T)
+  doAssert t2 == t
+  doAssert $t2.toJson == j2 # still needed, because -0.0 = 0.0 but their json representation differs
+
+import tables, sets, algorithm, sequtils, options, strtabs
+from strutils import contains
+
+type Foo = ref object
+  id: int
+
+proc `==`(a, b: Foo): bool =
+  a.id == b.id
+
+type MyEnum = enum me0, me1 = "me1Alt", me2, me3, me4
+
+proc `$`(a: MyEnum): string =
+  # putting this here pending https://github.com/nim-lang/Nim/issues/13747
+  if a == me2: "me2Modif"
+  else: system.`$`(a)
+
+template fn() =
+  block: # toJson, jsonTo
+    type Foo = distinct float
+    testRoundtrip('x', """120""")
+    when not defined(js):
+      testRoundtrip(cast[pointer](12345)): """12345"""
+      when nimvm:
+        discard
+        # bugs:
+        # Error: unhandled exception: 'intVal' is not accessible using discriminant 'kind' of type 'TNode' [
+        # Error: VM does not support 'cast' from tyNil to tyPointer
+      else:
+        testRoundtrip(pointer(nil)): """0"""
+        testRoundtrip(cast[pointer](nil)): """0"""
+
+    # refs bug #9423
+    testRoundtrip(Foo(1.5)): """1.5"""
+
+  block: # OrderedTable
+    testRoundtrip({"z": "Z", "y": "Y"}.toOrderedTable): """{"z":"Z","y":"Y"}"""
+    doAssert toJson({"z": 10, "": 11}.newTable).`$`.contains """"":11""" # allows hash to change
+    testRoundtrip({"z".cstring: 1, "".cstring: 2}.toOrderedTable): """{"z":1,"":2}"""
+    testRoundtrip({"z": (f1: 'f'), }.toTable): """{"z":{"f1":102}}"""
+
+  block: # StringTable
+    testRoundtrip({"name": "John", "city": "Monaco"}.newStringTable): """{"mode":"modeCaseSensitive","table":{"city":"Monaco","name":"John"}}"""
+
+  block: # complex example
+    let t = {"z": "Z", "y": "Y"}.newStringTable
+    type A = ref object
+      a1: string
+    let a = (1.1, "fo", 'x', @[10,11], [true, false], [t,newStringTable()], [0'i8,3'i8], -4'i16, (foo: 0.5'f32, bar: A(a1: "abc"), bar2: A.default, cstring1: "foo", cstring2: "", cstring3: cstring(nil)))
+    testRoundtrip(a):
+      """[1.1,"fo",120,[10,11],[true,false],[{"mode":"modeCaseSensitive","table":{"y":"Y","z":"Z"}},{"mode":"modeCaseSensitive","table":{}}],[0,3],-4,{"foo":0.5,"bar":{"a1":"abc"},"bar2":null,"cstring1":"foo","cstring2":"","cstring3":null}]"""
+
+  block:
+    # edge case when user defined `==` doesn't handle `nil` well, e.g.:
+    # https://github.com/nim-lang/nimble/blob/63695f490728e3935692c29f3d71944d83bb1e83/src/nimblepkg/version.nim#L105
+    testRoundtrip(@[Foo(id: 10), nil]): """[{"id":10},null]"""
+
+  block: # enum
+    type Foo = enum f1, f2, f3, f4, f5
+    type Bar = enum b1, b2, b3, b4
+    let a = [f2: b2, f3: b3, f4: b4]
+    doAssert b2.ord == 1 # explains the `1`
+    testRoundtrip(a): """[1,2,3]"""
+
+  block: # JsonNode
+    let a = ((1, 2.5, "abc").toJson, (3, 4.5, "foo"))
+    testRoundtripVal(a): """[[1,2.5,"abc"],[3,4.5,"foo"]]"""
+
+    block:
+      template toInt(a): untyped = cast[int](a)
+
+      let a = 3.toJson
+      let b = (a, a)
+
+      let c1 = b.toJson
+      doAssert c1[0].toInt == a.toInt
+      doAssert c1[1].toInt == a.toInt
+
+      let c2 = b.toJson(ToJsonOptions(jsonNodeMode: joptJsonNodeAsCopy))
+      doAssert c2[0].toInt != a.toInt
+      doAssert c2[1].toInt != c2[0].toInt
+      doAssert c2[1] == c2[0]
+
+      let c3 = b.toJson(ToJsonOptions(jsonNodeMode: joptJsonNodeAsObject))
+      doAssert $c3 == """[{"isUnquoted":false,"kind":2,"num":3},{"isUnquoted":false,"kind":2,"num":3}]"""
+
+  block: # ToJsonOptions
+    let a = (me1, me2)
+    doAssert $a.toJson() == "[1,2]"
+    doAssert $a.toJson(ToJsonOptions(enumMode: joptEnumSymbol)) == """["me1","me2"]"""
+    doAssert $a.toJson(ToJsonOptions(enumMode: joptEnumString)) == """["me1Alt","me2Modif"]"""
+
+  block: # set
+    type Foo = enum f1, f2, f3, f4, f5
+    type Goo = enum g1 = 10, g2 = 15, g3 = 17, g4
+    let a = ({f1, f3}, {1'u8, 7'u8}, {'0'..'9'}, {123'u16, 456, 789, 1121, 1122, 1542}, {g2, g3})
+    testRoundtrip(a): """[[0,2],[1,7],[48,49,50,51,52,53,54,55,56,57],[123,456,789,1121,1122,1542],[15,17]]"""
+
+  block: # bug #17383
+    block:
+      let a = (int32.high, uint32.high)
+      testRoundtrip(a): "[2147483647,4294967295]"
+    when int.sizeof > 4:
+      block:
+        let a = (int64.high, uint64.high)
+        testRoundtrip(a): "[9223372036854775807,18446744073709551615]"
+    block:
+      let a = (int.high, uint.high)
+      when int.sizeof == 4:
+        testRoundtrip(a): "[2147483647,4294967295]"
+      else:
+        testRoundtrip(a): "[9223372036854775807,18446744073709551615]"
+
+  block: # bug #18007
+    testRoundtrip((NaN, Inf, -Inf, 0.0, -0.0, 1.0)): """["nan","inf","-inf",0.0,-0.0,1.0]"""
+    testRoundtrip((float32(NaN), Inf, -Inf, 0.0, -0.0, 1.0)): """["nan","inf","-inf",0.0,-0.0,1.0]"""
+    testRoundtripVal((Inf, -Inf, 0.0, -0.0, 1.0)): """["inf","-inf",0.0,-0.0,1.0]"""
+    doAssert ($NaN.toJson).parseJson.jsonTo(float).isNaN
+
+  block: # bug #18009; unfixable unless we change parseJson (which would have overhead),
+         # but at least we can guarantee that the distinction between 0.0 and -0.0 is preserved.
+    let a = (0, 0.0, -0.0, 0.5, 1, 1.0)
+    testRoundtripVal(a): "[0,0.0,-0.0,0.5,1,1.0]"
+    let a2 = $($a.toJson).parseJson
+    whenRuntimeJs:
+      doAssert a2 == "[0,0,-0.0,0.5,1,1]"
+    do:
+      doAssert a2 == "[0,0.0,-0.0,0.5,1,1.0]"
+    let b = a2.parseJson.jsonTo(type(a))
+    doAssert not b[1].signbit
+    doAssert b[2].signbit
+    doAssert not b[3].signbit
+
+  block: # bug #15397, bug #13196
+    let a = 0.1
+    let x = 0.12345678901234567890123456789
+    let b = (a + 0.2, 0.3, x)
+    testRoundtripVal(b): "[0.30000000000000004,0.3,0.12345678901234568]"
+
+    testRoundtripVal(0.12345678901234567890123456789): "0.12345678901234568"
+    testRoundtripVal(epsilon(float64)): "2.220446049250313e-16"
+    testRoundtripVal(1.0 + epsilon(float64)): "1.0000000000000002"
+
+  block: # case object
+    type Foo = object
+      x0: float
+      case t1: bool
+      of true: z1: int8
+      of false: z2: uint16
+      x1: string
+    testRoundtrip(Foo(t1: true, z1: 5, x1: "bar")): """{"x0":0.0,"t1":true,"z1":5,"x1":"bar"}"""
+    testRoundtrip(Foo(x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
+    type PFoo = ref Foo
+    testRoundtrip(PFoo(x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
+
+  block: # ref case object
+    type Foo = ref object
+      x0: float
+      case t1: bool
+      of true: z1: int8
+      of false: z2: uint16
+      x1: string
+    testRoundtrip(Foo(t1: true, z1: 5, x1: "bar")): """{"x0":0.0,"t1":true,"z1":5,"x1":"bar"}"""
+    testRoundtrip(Foo(x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
+
+  block: # generic case object
+    type Foo[T] = ref object
+      x0: float
+      case t1: bool
+      of true: z1: int8
+      of false: z2: uint16
+      x1: string
+    testRoundtrip(Foo[float](t1: true, z1: 5, x1: "bar")): """{"x0":0.0,"t1":true,"z1":5,"x1":"bar"}"""
+    testRoundtrip(Foo[int](x0: 1.5, t1: false, z2: 6)): """{"x0":1.5,"t1":false,"z2":6,"x1":""}"""
+    # sanity check: nesting inside a tuple
+    testRoundtrip((Foo[int](x0: 1.5, t1: false, z2: 6), "foo")): """[{"x0":1.5,"t1":false,"z2":6,"x1":""},"foo"]"""
+
+  block: # case object: 2 discriminants, `when` branch, range discriminant
+    type Foo[T] = object
+      case t1: bool
+      of true:
+        z1: int8
+      of false:
+        z2: uint16
+      when T is float:
+        case t2: range[0..3]
+        of 0: z3: int8
+        of 2,3: z4: uint16
+        else: discard
+    testRoundtrip(Foo[float](t1: true, z1: 5, t2: 3, z4: 12)): """{"t1":true,"z1":5,"t2":3,"z4":12}"""
+    testRoundtrip(Foo[int](t1: false, z2: 7)): """{"t1":false,"z2":7}"""
+    # pending https://github.com/nim-lang/Nim/issues/14698, test with `type Foo[T] = ref object`
+
+  block: # bug: pass opt params in fromJson
+    type Foo = object
+      a: int
+      b: string
+      c: float
+    type Bar = object
+      foo: Foo
+      boo: string
+    var f: seq[Foo]
+    try:
+      fromJson(f, parseJson """[{"b": "bbb"}]""")
+      doAssert false
+    except ValueError:
+      doAssert true
+    fromJson(f, parseJson """[{"b": "bbb"}]""", Joptions(allowExtraKeys: true, allowMissingKeys: true))
+    doAssert f == @[Foo(a: 0, b: "bbb", c: 0.0)]
+    var b: Bar
+    fromJson(b, parseJson """{"foo": {"b": "bbb"}}""", Joptions(allowExtraKeys: true, allowMissingKeys: true))
+    doAssert b == Bar(foo: Foo(a: 0, b: "bbb", c: 0.0))
+    block: # jsonTo with `opt`
+      let b2 = """{"foo": {"b": "bbb"}}""".parseJson.jsonTo(Bar,  Joptions(allowExtraKeys: true, allowMissingKeys: true))
+      doAssert b2 == Bar(foo: Foo(a: 0, b: "bbb", c: 0.0))
+
+  block testHashSet:
+    testRoundtrip(HashSet[string]()): "[]"
+    testRoundtrip([""].toHashSet): """[""]"""
+    testRoundtrip(["one"].toHashSet): """["one"]"""
+
+    var s: HashSet[string]
+    fromJson(s, parseJson("""["one","two"]"""))
+    doAssert s == ["one", "two"].toHashSet
+
+    let jsonNode = toJson(s)
+    doAssert jsonNode.elems.mapIt(it.str).sorted == @["one", "two"]
+
+  block testOrderedSet:
+    testRoundtrip(["one", "two", "three"].toOrderedSet):
+      """["one","two","three"]"""
+
+  block testOption:
+    testRoundtrip(some("test")): "\"test\""
+    testRoundtrip(none[string]()): "null"
+    testRoundtrip(some(42)): "42"
+    testRoundtrip(none[int]()): "null"
+
+  block testStrtabs:
+    testRoundtrip(newStringTable(modeStyleInsensitive)):
+      """{"mode":"modeStyleInsensitive","table":{}}"""
+
+    testRoundtrip(
+      newStringTable("name", "John", "surname", "Doe", modeCaseSensitive)):
+        """{"mode":"modeCaseSensitive","table":{"name":"John","surname":"Doe"}}"""
+
+  block testJoptions:
+    type
+      AboutLifeUniverseAndEverythingElse = object
+        question: string
+        answer: int
+
+    block testExceptionOnExtraKeys:
+      var guide: AboutLifeUniverseAndEverythingElse
+      let json = parseJson(
+        """{"question":"6*9=?","answer":42,"author":"Douglas Adams"}""")
+      doAssertRaises ValueError, fromJson(guide, json)
+      doAssertRaises ValueError,
+                     fromJson(guide, json, Joptions(allowMissingKeys: true))
+
+      type
+        A = object
+          a1,a2,a3: int
+      var a: A
+      let j = parseJson("""{"a3": 1, "a4": 2}""")
+      doAssertRaises ValueError,
+                     fromJson(a, j, Joptions(allowMissingKeys: true))
+
+    block testExceptionOnMissingKeys:
+      var guide: AboutLifeUniverseAndEverythingElse
+      let json = parseJson("""{"answer":42}""")
+      doAssertRaises ValueError, fromJson(guide, json)
+      doAssertRaises ValueError,
+                     fromJson(guide, json, Joptions(allowExtraKeys: true))
+
+    block testAllowExtraKeys:
+      var guide: AboutLifeUniverseAndEverythingElse
+      let json = parseJson(
+        """{"question":"6*9=?","answer":42,"author":"Douglas Adams"}""")
+      fromJson(guide, json, Joptions(allowExtraKeys: true))
+      doAssert guide == AboutLifeUniverseAndEverythingElse(
+        question: "6*9=?", answer: 42)
+
+      block refObject: #bug 17986
+        type A = ref object
+          case is_a: bool
+          of true:
+            a: int
+          else:
+            b: int
+
+        var a = A()
+        fromJson(a, """{"is_a": true, "a":1, "extra_key": 1}""".parseJson, Joptions(allowExtraKeys: true))
+        doAssert $a[] == "(is_a: true, a: 1)"
+
+    block testAllowMissingKeys:
+      var guide = AboutLifeUniverseAndEverythingElse(
+        question: "6*9=?", answer: 54)
+      let json = parseJson("""{"answer":42}""")
+      fromJson(guide, json, Joptions(allowMissingKeys: true))
+      doAssert guide == AboutLifeUniverseAndEverythingElse(
+        question: "6*9=?", answer: 42)
+
+    block testAllowExtraAndMissingKeys:
+      var guide = AboutLifeUniverseAndEverythingElse(
+        question: "6*9=?", answer: 54)
+      let json = parseJson(
+        """{"answer":42,"author":"Douglas Adams"}""")
+      fromJson(guide, json, Joptions(
+        allowExtraKeys: true, allowMissingKeys: true))
+      doAssert guide == AboutLifeUniverseAndEverythingElse(
+        question: "6*9=?", answer: 42)
+
+    type
+      Foo = object
+        a: array[2, string]
+        case b: bool
+        of false: f: float
+        of true: t: tuple[i: int, s: string]
+        case c: range[0 .. 2]
+        of 0: c0: int
+        of 1: c1: float
+        of 2: c2: string
+
+    block testExceptionOnMissingDiscriminantKey:
+      var foo: Foo
+      let json = parseJson("""{"a":["one","two"]}""")
+      doAssertRaises ValueError, fromJson(foo, json)
+
+    block testDoNotResetMissingFieldsWhenHaveDiscriminantKey:
+      var foo = Foo(a: ["one", "two"], b: true, t: (i: 42, s: "s"),
+                    c: 0, c0: 1)
+      let json = parseJson("""{"b":true,"c":2}""")
+      fromJson(foo, json, Joptions(allowMissingKeys: true))
+      doAssert foo.a == ["one", "two"]
+      doAssert foo.b
+      doAssert foo.t == (i: 42, s: "s")
+      doAssert foo.c == 2
+      doAssert foo.c2 == ""
+
+    block testAllowMissingDiscriminantKeys:
+      var foo: Foo
+      let json = parseJson("""{"a":["one","two"],"c":1,"c1":3.14159}""")
+      fromJson(foo, json, Joptions(allowMissingKeys: true))
+      doAssert foo.a == ["one", "two"]
+      doAssert not foo.b
+      doAssert foo.f == 0.0
+      doAssert foo.c == 1
+      doAssert foo.c1 == 3.14159
+
+    block testExceptionOnWrongDiscirminatBranchInJson:
+      var foo = Foo(b: false, f: 3.14159, c: 0, c0: 42)
+      let json = parseJson("""{"c2": "hello"}""")
+      doAssertRaises ValueError,
+                     fromJson(foo, json, Joptions(allowMissingKeys: true))
+      # Test that the original fields are not reset.
+      doAssert not foo.b
+      doAssert foo.f == 3.14159
+      doAssert foo.c == 0
+      doAssert foo.c0 == 42
+
+    block testNoExceptionOnRightDiscriminantBranchInJson:
+      var foo = Foo(b: false, f: 0, c:1, c1: 0)
+      let json = parseJson("""{"f":2.71828,"c1": 3.14159}""")
+      fromJson(foo, json, Joptions(allowMissingKeys: true))
+      doAssert not foo.b
+      doAssert foo.f == 2.71828
+      doAssert foo.c == 1
+      doAssert foo.c1 == 3.14159
+
+    block testAllowExtraKeysInJsonOnWrongDisciriminatBranch:
+      var foo = Foo(b: false, f: 3.14159, c: 0, c0: 42)
+      let json = parseJson("""{"c2": "hello"}""")
+      fromJson(foo, json, Joptions(allowMissingKeys: true,
+                                   allowExtraKeys: true))
+      # Test that the original fields are not reset.
+      doAssert not foo.b
+      doAssert foo.f == 3.14159
+      doAssert foo.c == 0
+      doAssert foo.c0 == 42
+
+
+    block testInvalidTupleLength:
+      let json = parseJson("[0]")
+      # Should raise ValueError instead of index error
+      doAssertRaises(ValueError):
+        discard json.jsonTo((int, int))
+
+    type
+      InnerEnum = enum
+        A
+        B
+        C
+      InnerObject = object
+        x: string
+        y: InnerEnum
+
+    block testOptionsArePassedWhenDeserialising:
+      let json = parseJson("""{"x": "hello"}""")
+      let inner = json.jsonTo(Option[InnerObject], Joptions(allowMissingKeys: true))
+      doAssert inner.isSome()
+      doAssert inner.get().x == "hello"
+      doAssert inner.get().y == A
+
+    block testOptionsArePassedWhenSerialising:
+      let inner = some InnerObject(x: "hello", y: A)
+      let json = inner.toJson(ToJsonOptions(enumMode: joptEnumSymbol))
+      doAssert $json == """{"x":"hello","y":"A"}"""
+
+    block: # bug #21638
+      type Something = object
+
+      doAssert "{}".parseJson.jsonTo(Something) == Something()
+
+    when false:
+      ## TODO: Implement support for nested variant objects allowing the tests
+      ## bellow to pass.
+      block testNestedVariantObjects:
+        type
+          Variant = object
+            case b: bool
+            of false:
+              case bf: bool
+              of false: bff: int
+              of true: bft: float
+            of true:
+              case bt: bool
+              of false: btf: string
+              of true: btt: char
+
+        testRoundtrip(Variant(b: false, bf: false, bff: 42)):
+          """{"b": false, "bf": false, "bff": 42}"""
+        testRoundtrip(Variant(b: false, bf: true, bft: 3.14159)):
+          """{"b": false, "bf": true, "bft": 3.14159}"""
+        testRoundtrip(Variant(b: true, bt: false, btf: "test")):
+          """{"b": true, "bt": false, "btf": "test"}"""
+        testRoundtrip(Variant(b: true, bt: true, btt: 'c')):
+          """{"b": true, "bt": true, "btt": "c"}"""
+
+        # TODO: Add additional tests with missing and extra JSON keys, both when
+        # allowed and forbidden analogous to the tests for the not nested
+        # variant objects.
+
+static: fn()
+fn()
diff --git a/tests/stdlib/tlists.nim b/tests/stdlib/tlists.nim
index a288af781..5993278c7 100644
--- a/tests/stdlib/tlists.nim
+++ b/tests/stdlib/tlists.nim
@@ -1,67 +1,277 @@
 discard """
-  output: '''true'''
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
 """
 
-import lists
+import std/[lists, sequtils]
+import std/assertions
 
 const
   data = [1, 2, 3, 4, 5, 6]
 
-block SinglyLinkedListTest1:
-  var L: SinglyLinkedList[int]
-  for d in items(data): L.prepend(d)
-  for d in items(data): L.append(d)
-  assert($L == "[6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6]")
 
-  assert(4 in L)
+template main =
+  block SinglyLinkedListTest1:
+    var L: SinglyLinkedList[int]
+    for d in items(data): L.prepend(d)
+    for d in items(data): L.add(d)
+    doAssert($L == "[6, 5, 4, 3, 2, 1, 1, 2, 3, 4, 5, 6]")
 
-block SinglyLinkedListTest2:
-  var L: SinglyLinkedList[string]
-  for d in items(data): L.prepend($d)
-  assert($L == """["6", "5", "4", "3", "2", "1"]""")
+    doAssert(4 in L)
 
-  assert("4" in L)
+  block SinglyLinkedListTest2:
+    var L: SinglyLinkedList[string]
+    for d in items(data): L.prepend($d)
+    doAssert($L == """["6", "5", "4", "3", "2", "1"]""")
 
+    doAssert("4" in L)
 
-block DoublyLinkedListTest1:
-  var L: DoublyLinkedList[int]
-  for d in items(data): L.prepend(d)
-  for d in items(data): L.append(d)
-  L.remove(L.find(1))
-  assert($L == "[6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6]")
 
-  assert(4 in L)
+  block DoublyLinkedListTest1:
+    var L: DoublyLinkedList[int]
+    for d in items(data): L.prepend(d)
+    for d in items(data): L.add(d)
+    L.remove(L.find(1))
+    doAssert($L == "[6, 5, 4, 3, 2, 1, 2, 3, 4, 5, 6]")
 
-block SinglyLinkedRingTest1:
-  var L: SinglyLinkedRing[int]
-  L.prepend(4)
-  assert($L == "[4]")
-  L.prepend(4)
+    doAssert(4 in L)
 
-  assert($L == "[4, 4]")
-  assert(4 in L)
+  block SinglyLinkedRingTest1:
+    var L: SinglyLinkedRing[int]
+    L.prepend(4)
+    doAssert($L == "[4]")
+    L.prepend(4)
 
+    doAssert($L == "[4, 4]")
+    doAssert(4 in L)
 
-block DoublyLinkedRingTest1:
-  var L: DoublyLinkedRing[int]
-  L.prepend(4)
-  assert($L == "[4]")
-  L.prepend(4)
 
-  assert($L == "[4, 4]")
-  assert(4 in L)
+  block DoublyLinkedRingTest1:
+    var L: DoublyLinkedRing[int]
+    L.prepend(4)
+    doAssert($L == "[4]")
+    L.prepend(4)
 
-  L.append(3)
-  L.append(5)
-  assert($L == "[4, 4, 3, 5]")
+    doAssert($L == "[4, 4]")
+    doAssert(4 in L)
 
-  L.remove(L.find(3))
-  L.remove(L.find(5))
-  L.remove(L.find(4))
-  L.remove(L.find(4))
-  assert($L == "[]")
-  assert(4 notin L)
+    L.add(3)
+    L.add(5)
+    doAssert($L == "[4, 4, 3, 5]")
 
+    L.remove(L.find(3))
+    L.remove(L.find(5))
+    L.remove(L.find(4))
+    L.remove(L.find(4))
+    doAssert($L == "[]")
+    doAssert(4 notin L)
 
-echo "true"
+  block tlistsToString:
+    block:
+      var l = initDoublyLinkedList[int]()
+      l.add(1)
+      l.add(2)
+      l.add(3)
+      doAssert $l == "[1, 2, 3]"
+    block:
+      var l = initDoublyLinkedList[string]()
+      l.add("1")
+      l.add("2")
+      l.add("3")
+      doAssert $l == """["1", "2", "3"]"""
+    block:
+      var l = initDoublyLinkedList[char]()
+      l.add('1')
+      l.add('2')
+      l.add('3')
+      doAssert $l == """['1', '2', '3']"""
 
+  # Copied here until it is merged into sequtils
+  template take(a: untyped, max: int): untyped =
+    type T = typeof(block: (for ai in a: ai))
+    var ret: seq[T]
+    var i = 0
+    if max > 0:
+      for ai in a:
+        ret.add ai
+        i.inc
+        if i >= max: break
+    ret
+
+  template testCommon(initList, toList) =
+
+    block: # toSinglyLinkedList, toDoublyLinkedList
+      let l = seq[int].default
+      doAssert l.toList.toSeq == []
+      doAssert [1].toList.toSeq == [1]
+      doAssert [1, 2, 3].toList.toSeq == [1, 2, 3]
+
+    block copy:
+      doAssert array[0, int].default.toList.copy.toSeq == []
+      doAssert [1].toList.copy.toSeq == [1]
+      doAssert [1, 2].toList.copy.toSeq == [1, 2]
+      doAssert [1, 2, 3].toList.copy.toSeq == [1, 2, 3]
+      type Foo = ref object
+        x: int
+      var f0 = Foo(x: 0)
+      let f1 = Foo(x: 1)
+      var a = [f0].toList
+      var b = a.copy
+      b.add f1
+      doAssert a.toSeq == [f0]
+      doAssert b.toSeq == [f0, f1]
+      f0.x = 42
+      doAssert a.head.value.x == 42
+      doAssert b.head.value.x == 42
+
+    block: # add, addMoved
+      block:
+        var
+          l0 = initList[int]()
+          l1 = [1].toList
+          l2 = [2, 3].toList
+          l3 = [4, 5, 6].toList
+        l0.add l3
+        l1.add l3
+        l2.addMoved l3
+        doAssert l0.toSeq == [4, 5, 6]
+        doAssert l1.toSeq == [1, 4, 5, 6]
+        doAssert l2.toSeq == [2, 3, 4, 5, 6]
+        doAssert l3.toSeq == []
+        l2.add l3 # re-adding l3 that was destroyed is now a no-op
+        doAssert l2.toSeq == [2, 3, 4, 5, 6]
+        doAssert l3.toSeq == []
+      block:
+        var
+          l0 = initList[int]()
+          l1 = [1].toList
+          l2 = [2, 3].toList
+          l3 = [4, 5, 6].toList
+        l3.addMoved l0
+        l2.addMoved l1
+        doAssert l3.toSeq == [4, 5, 6]
+        doAssert l2.toSeq == [2, 3, 1]
+        l3.add l0
+        doAssert l3.toSeq == [4, 5, 6]
+      block:
+        var c = [0, 1].toList
+        c.addMoved c
+        doAssert c.take(6) == [0, 1, 0, 1, 0, 1]
+
+    block: # prepend, prependMoved
+      block:
+        var
+          l0 = initList[int]()
+          l1 = [1].toList
+          l2 = [2, 3].toList
+          l3 = [4, 5, 6].toList
+        l0.prepend l3
+        l1.prepend l3
+        doAssert l3.toSeq == [4, 5, 6]
+        l2.prependMoved l3
+        doAssert l0.toSeq == [4, 5, 6]
+        doAssert l1.toSeq == [4, 5, 6, 1]
+        doAssert l2.toSeq == [4, 5, 6, 2, 3]
+        doAssert l3.toSeq == []
+        l2.prepend l3 # re-prepending l3 that was destroyed is now a no-op
+        doAssert l2.toSeq == [4, 5, 6, 2, 3]
+        doAssert l3.toSeq == []
+      block:
+        var
+          l0 = initList[int]()
+          l1 = [1].toList
+          l2 = [2, 3].toList
+          l3 = [4, 5, 6].toList
+        l3.prependMoved l0
+        l2.prependMoved l1
+        doAssert l3.toSeq == [4, 5, 6]
+        doAssert l2.toSeq == [1, 2, 3]
+        l3.prepend l0
+        doAssert l3.toSeq == [4, 5, 6]
+      block:
+        var c = [0, 1].toList
+        c.prependMoved c
+        doAssert c.take(6) == [0, 1, 0, 1, 0, 1]
+
+    block remove:
+      var l = [0, 1, 2, 3].toList
+      let
+        l0 = l.head
+        l1 = l0.next
+        l2 = l1.next
+        l3 = l2.next
+      l.remove l0
+      doAssert l.toSeq == [1, 2, 3]
+      l.remove l2
+      doAssert l.toSeq == [1, 3]
+      l.remove l2
+      doAssert l.toSeq == [1, 3]
+      l.remove l3
+      doAssert l.toSeq == [1]
+      l.remove l1
+      doAssert l.toSeq == []
+      # Cycle preservation
+      var a = [10, 11, 12].toList
+      a.addMoved a
+      doAssert a.take(6) == @[10, 11, 12, 10, 11, 12]
+      a.remove a.head.next
+      doAssert a.take(6) == @[10, 12, 10, 12, 10, 12]
+      a.remove a.head
+      doAssert a.take(6) == @[12, 12, 12, 12, 12, 12]
+
+  testCommon initSinglyLinkedList, toSinglyLinkedList
+  testCommon initDoublyLinkedList, toDoublyLinkedList
+
+  block remove: # return value check
+    var l = [0, 1, 2, 3].toSinglyLinkedList
+    let n = l.head.next.next
+    doAssert l.remove(n) == true
+    doAssert l.toSeq == [0, 1, 3]
+    doAssert l.remove(n) == false
+    doAssert l.toSeq == [0, 1, 3]
+    doAssert l.remove(l.head) == true
+    doAssert l.toSeq == [1, 3]
+    doAssert l.remove(l.head.next) == true
+    doAssert l.toSeq == [1]
+    doAssert l.remove(l.head) == true
+    doAssert l.toSeq == []
+  
+  block issue19297: # add (appends a shallow copy)
+    var a: SinglyLinkedList[int]
+    var b: SinglyLinkedList[int]
+
+    doAssert a.toSeq == @[]
+    a.add(1)
+    doAssert a.toSeq == @[1]
+    a.add(b)
+    doAssert a.toSeq == @[1]
+    a.add(2)
+    doAssert a.toSeq == @[1, 2]
+  
+  block issue19314: # add (appends a shallow copy)
+    var a: DoublyLinkedList[int]
+    var b: DoublyLinkedList[int]
+
+    doAssert a.toSeq == @[]
+    a.add(1)
+    doAssert a.toSeq == @[1]
+    a.add(b)
+    doAssert a.toSeq == @[1]
+    a.add(2)
+    doAssert a.toSeq == @[1, 2]
+
+  block RemoveLastNodeFromSinglyLinkedList:
+    var list = initSinglyLinkedList[string]()
+    let n1 = newSinglyLinkedNode("sonic")
+    let n2 = newSinglyLinkedNode("the")
+    let n3 = newSinglyLinkedNode("tiger")
+    let n4 = newSinglyLinkedNode("hedgehog")
+    list.add(n1)
+    list.add(n2)
+    list.add(n3)
+    list.remove(n3)
+    list.add(n4)
+    doAssert list.toSeq == @["sonic", "the", "hedgehog"]
+
+static: main()
+main()
diff --git a/tests/stdlib/tlocks.nim b/tests/stdlib/tlocks.nim
index e567cfde8..1c5f67119 100644
--- a/tests/stdlib/tlocks.nim
+++ b/tests/stdlib/tlocks.nim
@@ -1,10 +1,11 @@
 discard """
-  output: '''3'''
-  cmd: "nim $target --threads:on $options $file"
+  targets: "c cpp js"
+  matrix: "--mm:refc; --mm:orc"
 """
 
 #bug #6049
 import uselocks
+import std/assertions
 
 var m = createMyType[int]()
-echo $m.use()
+doAssert m.use() == 3
diff --git a/tests/stdlib/tlwip.nim b/tests/stdlib/tlwip.nim
new file mode 100644
index 000000000..fc53be592
--- /dev/null
+++ b/tests/stdlib/tlwip.nim
@@ -0,0 +1,30 @@
+discard """
+  targets: "c"
+  cmd: "nim $target --compileOnly --os:freertos --gc:arc $options $file"
+  disabled: "bsd"
+  disabled: "windows"
+  action: compile
+"""
+
+# Note:
+#   This file tests FreeRTOS/LwIP cross-compilation on UNIX platforms
+#   Windows should run when compiled with esp-idf, however I'm not
+#   sure how to test for only compilation on Windows without running 
+#   a test exe
+# 
+# Note:
+#   disabling *BSDs since they're not playing well with `gcc`
+
+import net
+import asynchttpserver, asyncdispatch
+
+proc cb*(req: Request) {.async.} =
+  await req.respond(Http200, "Hello World")
+
+proc run_http_server*() {.exportc.} =
+  echo "starting http server"
+  var server = newAsyncHttpServer()
+
+  waitFor server.serve(Port(8181), cb)
+
+echo("ok")
diff --git a/tests/stdlib/tmacros.nim b/tests/stdlib/tmacros.nim
new file mode 100644
index 000000000..06a9a9c27
--- /dev/null
+++ b/tests/stdlib/tmacros.nim
@@ -0,0 +1,349 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+#[
+xxx macros tests need to be reorganized to makes sure each API is tested once
+See also:
+  tests/macros/tdumpast.nim for treeRepr + friends
+]#
+
+import std/macros
+import std/assertions
+
+block: # hasArgOfName
+  macro m(u: untyped): untyped =
+    for name in ["s","i","j","k","b","xs","ys"]:
+      doAssert hasArgOfName(params u,name)
+    doAssert not hasArgOfName(params u,"nonexistent")
+
+  proc p(s: string; i,j,k: int; b: bool; xs,ys: seq[int] = @[]) {.m.} = discard
+
+block: # bug #17454
+  proc f(v: NimNode): string {.raises: [].} = $v
+
+block: # unpackVarargs
+  block:
+    proc bar1(a: varargs[int]): string =
+      for ai in a: result.add " " & $ai
+    proc bar2(a: varargs[int]) =
+      let s1 = bar1(a)
+      let s2 = unpackVarargs(bar1, a) # `unpackVarargs` makes no difference here
+      doAssert s1 == s2
+    bar2(1, 2, 3)
+    bar2(1)
+    bar2()
+
+  block:
+    template call1(fun: typed; args: varargs[untyped]): untyped =
+      unpackVarargs(fun, args)
+    template call2(fun: typed; args: varargs[untyped]): untyped =
+      # fun(args) # works except for last case with empty `args`, pending bug #9996
+      when varargsLen(args) > 0: fun(args)
+      else: fun()
+
+    proc fn1(a = 0, b = 1) = discard (a, b)
+
+    call1(fn1)
+    call1(fn1, 10)
+    call1(fn1, 10, 11)
+
+    call2(fn1)
+    call2(fn1, 10)
+    call2(fn1, 10, 11)
+
+  block:
+    template call1(fun: typed; args: varargs[typed]): untyped =
+      unpackVarargs(fun, args)
+    template call2(fun: typed; args: varargs[typed]): untyped =
+      # xxx this would give a confusing error message:
+      # required type for a: varargs[typed] [varargs] but expression '[10]' is of type: varargs[typed] [varargs]
+      when varargsLen(args) > 0: fun(args)
+      else: fun()
+    macro toString(a: varargs[typed, `$`]): string =
+      var msg = genSym(nskVar, "msg")
+      result = newStmtList()
+      result.add quote do:
+        var `msg` = ""
+      for ai in a:
+        result.add quote do: `msg`.add $`ai`
+      result.add quote do: `msg`
+    doAssert call1(toString) == ""
+    doAssert call1(toString, 10) == "10"
+    doAssert call1(toString, 10, 11) == "1011"
+
+block: # SameType
+  type
+    A = int
+    B = distinct int
+    C = object
+    Generic[T, Y] = object
+  macro isSameType(a, b: typed): untyped =
+    newLit(sameType(a, b))
+
+  static:
+    assert Generic[int, int].isSameType(Generic[int, int])
+    assert Generic[A, string].isSameType(Generic[int, string])
+    assert not Generic[A, string].isSameType(Generic[B, string])
+    assert not Generic[int, string].isSameType(Generic[int, int])
+    assert isSameType(int, A)
+    assert isSameType(10, 20)
+    assert isSameType("Hello", "world")
+    assert not isSameType("Hello", cstring"world")
+    assert not isSameType(int, B)
+    assert not isSameType(int, Generic[int, int])
+    assert not isSameType(C, string)
+    assert not isSameType(C, int)
+
+
+  #[
+    # compiler sameType fails for the following, read more in `types.nim`'s `sameTypeAux`.
+    type
+      D[T] = C
+      G[T] = T
+    static:
+      assert isSameType(D[int], C)
+      assert isSameType(D[int], D[float])
+      assert isSameType(G[float](1.0), float(1.0))
+      assert isSameType(float(1.0), G[float](1.0))
+  ]#
+
+  type Tensor[T] = object
+    data: T
+
+  macro testTensorInt(x: typed): untyped =
+    let
+      tensorIntType = getTypeInst(Tensor[int])[1]
+      xTyp = x.getTypeInst
+    
+    newLit(xTyp.sameType(tensorIntType))
+
+  var
+    x: Tensor[int]
+    x1 = Tensor[float]()
+    x2 = Tensor[A]()
+    x3 = Tensor[B]()
+
+  static: 
+    assert testTensorInt(x)
+    assert not testTensorInt(x1)
+    assert testTensorInt(x2)
+    assert not testTensorInt(x3)
+
+block: # extractDocCommentsAndRunnables
+  macro checkRunnables(prc: untyped) =
+    let runnables = prc.body.extractDocCommentsAndRunnables()
+    doAssert runnables[0][0].eqIdent("runnableExamples")
+
+  macro checkComments(comment: static[string], prc: untyped) =
+    let comments = prc.body.extractDocCommentsAndRunnables()
+    doAssert comments[0].strVal == comment
+    
+  proc a() {.checkRunnables.} =
+    runnableExamples: discard
+    discard
+
+  proc b() {.checkRunnables.} =
+    runnableExamples "-d:ssl": discard
+    discard
+    
+  proc c() {.checkComments("Hello world").} =
+    ## Hello world
+
+block: # bug #19020
+  type
+    foo = object
+
+  template typ(T:typedesc) {.pragma.}
+
+  proc bar() {.typ: foo.} = discard
+
+  static:
+    doAssert $bar.getCustomPragmaVal(typ) == "foo"
+  doAssert $bar.getCustomPragmaVal(typ) == "foo"
+
+block hasCustomPragmaGeneric:
+  template examplePragma() {.pragma.}
+  type
+    Foo[T] {.examplePragma.} = object
+      x {.examplePragma.}: T
+  var f: Foo[string]
+  doAssert f.hasCustomPragma(examplePragma)
+  doAssert f.x.hasCustomPragma(examplePragma)
+
+block getCustomPragmaValGeneric:
+  template examplePragma(x: int) {.pragma.}
+  type
+    Foo[T] {.examplePragma(42).} = object
+      x {.examplePragma(25).}: T
+  var f: Foo[string]
+  doAssert f.getCustomPragmaVal(examplePragma) == 42
+  doAssert f.x.getCustomPragmaVal(examplePragma) == 25
+
+block: # bug #21326
+  macro foo(body: untyped): untyped =
+    let a = body.lineInfoObj()
+    let aLit = a.newLit
+    result = quote do:
+      doAssert $`a` == $`aLit`
+
+  foo:
+    let c = 1
+
+  template name(a: LineInfo): untyped =
+    discard a # `aLit` works though
+
+  macro foo3(body: untyped): untyped =
+    let a = body.lineInfoObj()
+    # let ax = newLit(a)
+    result = getAst(name(a))
+
+  foo3:
+    let c = 1
+
+block: # bug #7375
+  macro fails(b: static[bool]): untyped =
+    doAssert b == false
+    result = newStmtList()
+
+  macro foo(): untyped =
+
+    var b = false
+
+    ## Fails
+    result = quote do:
+      fails(`b`)
+
+  foo()
+
+  macro someMacro(): untyped =
+    template tmpl(boolean: bool) =
+      when boolean:
+        discard "it's true!"
+      else:
+        doAssert false
+    result = getAst(tmpl(true))
+
+  someMacro()
+
+block:
+  macro foo(): untyped =
+    result = quote do: `littleEndian`
+
+  doAssert littleEndian == foo()
+
+block:
+  macro eqSym(x, y: untyped): untyped =
+    let eq = $x == $y # Unfortunately eqIdent compares to string.
+    result = quote do: `eq`
+
+  var r, a, b: int
+
+  template fma(result: var int, a, b: int, op: untyped) =
+    # fused multiple-add
+    when eqSym(op, `+=`):
+      discard "+="
+    else:
+      discard "+"
+
+  fma(r, a, b, `+=`)
+
+block:
+  template test(boolArg: bool) =
+    static:
+      doAssert typeof(boolArg) is bool
+    let x: bool = boolArg # compile error here, because boolArg became an int
+
+  macro testWrapped1(boolArg: bool): untyped =
+    # forwarding boolArg directly works
+    result = getAst(test(boolArg))
+
+  macro testWrapped2(boolArg: bool): untyped =
+    # forwarding boolArg via a local variable also works
+    let b = boolArg
+    result = getAst(test(b))
+
+  macro testWrapped3(boolArg: bool): untyped =
+    # but using a literal `true` as a local variable will be converted to int
+    let b = true
+    result = getAst(test(b))
+
+  test(true) # ok
+  testWrapped1(true) # ok
+  testWrapped2(true) # ok
+  testWrapped3(true) 
+
+block:
+  macro foo(): untyped =
+    var s = { 'a', 'b' }
+    quote do:              
+      let t = `s`         
+      doAssert $typeof(t) == "set[char]"
+
+  foo()
+
+block: # bug #9607
+  proc fun1(info:LineInfo): string = "bar"
+  proc fun2(info:int): string = "bar"
+
+  macro echoL(args: varargs[untyped]): untyped =
+    let info = args.lineInfoObj
+    let fun1 = bindSym"fun1"
+    let fun2 = bindSym"fun2"
+
+    # this would work instead
+    # result = newCall(bindSym"fun2", info.line.newLit)
+
+    result = quote do:
+
+      # BUG1: ???(0, 0) Error: internal error: genLiteral: ty is nil
+      `fun1`(`info`)
+
+  macro echoM(args: varargs[untyped]): untyped =
+    let info = args.lineInfoObj
+    let fun1 = bindSym"fun1"
+    let fun2 = bindSym"fun2"
+
+    # this would work instead
+    # result = newCall(bindSym"fun2", info.line.newLit)
+
+    result = quote do:
+
+      # BUG1: ???(0, 0) Error: internal error: genLiteral: ty is nil
+      `fun2`(`info`.line)
+
+
+  doAssert echoL() == "bar"
+  doAssert echoM() == "bar"
+
+block:
+  macro hello[T](x: T): untyped =
+    result = quote do:
+      let m: `T` = `x`
+      discard m
+
+  hello(12)
+
+block:
+  proc hello(x: int, y: typedesc) =
+    discard
+
+  macro main =
+    let x = 12
+    result = quote do:
+      `hello`(12, type(x))
+
+  main()
+
+block: # bug #22947
+  macro bar[N: static int](a: var array[N, int]) =
+    result = quote do:
+      for i in 0 ..< `N`:
+        `a`[i] = i
+
+  func foo[N: static int](a: var array[N, int]) =
+    bar(a)
+
+
+  var a: array[4, int]
+  foo(a)
diff --git a/tests/stdlib/tmarshal.nim b/tests/stdlib/tmarshal.nim
index a6fc6c1a5..32991ccc9 100644
--- a/tests/stdlib/tmarshal.nim
+++ b/tests/stdlib/tmarshal.nim
@@ -1,23 +1,24 @@
 discard """
-  output: '''{"age": 12, "bio": "Я Cletus", "blob": [65, 66, 67, 128], "name": "Cletus"}
-true
-true
-alpha 100
-omega 200
-'''
+  matrix: "--mm:orc; --mm:refc"
 """
 
-import marshal
+import std/marshal
+import std/[assertions, objectdollar, streams]
 
-template testit(x) = discard $$to[type(x)]($$x)
+# TODO: add static tests
 
-var x: array[0..4, array[0..4, string]] = [
-  ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
-  ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
-  ["test", "1", "2", "3", "4"]]
-testit(x)
-var test2: tuple[name: string, s: int] = ("tuple test", 56)
-testit(test2)
+proc testit[T](x: T): string = $$to[T]($$x)
+
+template check1 =
+  let test1: array[0..1, array[0..4, string]] = [
+    ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"]]
+  doAssert testit(test1) ==
+    """[["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"]]"""
+  let test2: tuple[name: string, s: int] = ("tuple test", 56)
+  doAssert testit(test2) == """{"Field0": "tuple test", "Field1": 56}"""
+
+static: check1()
+check1()
 
 type
   TE = enum
@@ -48,73 +49,185 @@ proc buildList(): PNode =
   result.prev.next = result
   result.prev.prev = result.next
 
-var test3: TestObj
-test3.test = 42
-test3.test2 = blah
-testit(test3)
+let test3 = TestObj(test: 42, test2: blah)
+doAssert testit(test3) ==
+  """{"test": 42, "asd": 0, "test2": "blah", "help": ""}"""
 
 var test4: ref tuple[a, b: string]
 new(test4)
 test4.a = "ref string test: A"
 test4.b = "ref string test: B"
-testit(test4)
+discard testit(test4) # serialization uses the pointer address, which is not consistent
 
-var test5 = @[(0,1),(2,3),(4,5)]
-testit(test5)
+let test5 = @[(0,1),(2,3),(4,5)]
+doAssert testit(test5) ==
+  """[{"Field0": 0, "Field1": 1}, {"Field0": 2, "Field1": 3}, {"Field0": 4, "Field1": 5}]"""
 
-var test7 = buildList()
-testit(test7)
+let test6: set[char] = {'A'..'Z', '_'}
+doAssert testit(test6) ==
+  """[65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 95]"""
 
-var test6: set[char] = {'A'..'Z', '_'}
-testit(test6)
+let test7 = buildList()
+discard testit(test7) # serialization uses the pointer address, which is not consistent
 
 
 # bug #1352
+block:
+  type
+    Entity = object of RootObj
+      name: string
+
+    Person = object of Entity
+      age: int
+      bio: string
+      blob: string
+
+  let instance1 = Person(name: "Cletus", age: 12,
+                         bio: "Я Cletus",
+                         blob: "ABC\x80")
+  doAssert $$instance1 == """{"age": 12, "bio": "Я Cletus", "blob": [65, 66, 67, 128], "name": "Cletus"}"""
+  doAssert to[Person]($$instance1).bio == instance1.bio
+  doAssert to[Person]($$instance1).blob == instance1.blob
+
+# bug #5757
+block:
+  type
+    Something = object
+      x: string
+      y: int
+
+  let data1 = """{"x": "alpha", "y": 100}"""
+  let data2 = """{"x": "omega", "y": 200}"""
+
+  var r = to[Something](data1)
+  doAssert $r.x & " " & $r.y == "alpha 100"
+  r = to[Something](data2)
+  doAssert $r.x & " " & $r.y == "omega 200"
+
+block:
+  type
+    Foo = object
+      a1: string
+      a2: string
+      a3: seq[string]
+      a4: seq[int]
+      a5: seq[int]
+      a6: seq[int]
+  var foo = Foo(a2: "", a4: @[], a6: @[1])
+  foo.a6.setLen 0
+  doAssert $$foo == """{"a1": "", "a2": "", "a3": [], "a4": [], "a5": [], "a6": []}"""
+  doAssert testit(foo) == """{"a1": "", "a2": "", "a3": [], "a4": [], "a5": [], "a6": []}"""
+
+import std/[options, json]
+
+# bug #15934
+block:
+  let
+    a1 = some(newJNull())
+    a2 = none(JsonNode)
+  doAssert $($$a1).to[:Option[JsonNode]] == "some(null)"
+  doAssert $($$a2).to[:Option[JsonNode]] == "none(JsonNode)"
+  doAssert ($$a1).to[:Option[JsonNode]] == some(newJNull())
+  doAssert ($$a2).to[:Option[JsonNode]] == none(JsonNode)
+
+# bug #15620
+block:
+  let str = """{"numeric": null}"""
+
+  type
+    LegacyEntry = object
+      numeric: string
+
+  let test = to[LegacyEntry](str)
+  doAssert $test == """(numeric: "")"""
+
+block:
+  let str = """{"numeric": null}"""
+
+  type
+    LegacyEntry = object
+      numeric: seq[int]
+
+  var test = to[LegacyEntry](str)
+  doAssert $test == """(numeric: @[])"""
+
+# bug #16022
+block:
+  let p: proc (): string = proc (): string = "hello world"
+  let poc = to[typeof(p)]($$p)
+  doAssert poc() == "hello world"
+
+block:
+  type
+    A {.inheritable.} = object
+    B = object of A
+      f: int
+
+  let a: ref A = new(B)
+  doAssert $$a[] == "{}" # not "{f: 0}"
+
+# bug #16496
+block:
+  type
+    A = ref object
+      data: seq[int]
+
+    B = ref object
+      x: A
+  let o = A(data: @[1, 2, 3, 4])
+  let s1 = @[B(x: o), B(x: o)]
+  let m  = $$ s1
+  let s2 = to[seq[B]](m)
+  doAssert s2[0].x.data == s2[1].x.data
+  doAssert s1[0].x.data == s2[1].x.data
+
+
+block:
+  type
+    Obj = ref object
+      i: int
+      b: bool
+
+  let
+    strm = newStringStream()
+
+  var
+    o = Obj(i: 1, b: false)
+    t1 = @[o, o]
+    t2: seq[Obj]
+
+  doAssert t1[0] == t1[1]
+
+  strm.store(t1)
+  strm.setPosition(0)
+  strm.load(t2)
+  strm.close()
+
+  doAssert t2[0] == t2[1]
+
+
+template checkMarshal(data: typed) =
+  let orig = data
+  let m = $$orig
+
+  let old = to[typeof(orig)](m)
+  doAssert data == old
+
+template main() =
+  type
+    Book = object
+      page: int
+      name: string
+
+  let book = Book(page: 12, name: "persona")
+
+  checkMarshal(486)
+  checkMarshal(3.14)
+  checkMarshal("azure sky")
+  checkMarshal(book)
+  checkMarshal([1, 2, 3])
+  checkMarshal(@[1.5, 2.7, 3.9, 4.2])
+  checkMarshal(@["dream", "is", "possible"])
 
-type
-  Entity = object of RootObj
-    name: string
-
-  Person = object of Entity
-    age: int
-    bio: string
-    blob: string
-
-var instance1 = Person(name: "Cletus", age: 12,
-                       bio: "Я Cletus",
-                       blob: "ABC\x80")
-echo($$instance1)
-echo(to[Person]($$instance1).bio == instance1.bio)
-echo(to[Person]($$instance1).blob == instance1.blob)
-
-# bug 5757
-
-type
-  Something = object
-    x: string
-    y: int
-
-var data1 = """{"x": "alpha", "y": 100}"""
-var data2 = """{"x": "omega", "y": 200}"""
-
-var r = to[Something](data1)
-
-echo r.x, " ", r.y
-
-r = to[Something](data2)
-
-echo r.x, " ", r.y
-
-
-type
-  Foo = object
-    a1: string
-    a2: string
-    a3: seq[string]
-    a4: seq[int]
-    a5: seq[int]
-    a6: seq[int]
-var foo = Foo(a2: "", a4: @[], a6: @[1])
-foo.a6.setLen 0
-doAssert $$foo == """{"a1": "", "a2": "", "a3": [], "a4": [], "a5": [], "a6": []}"""
-testit(foo)
+static: main()
+main()
diff --git a/tests/stdlib/tmarshalsegfault.nim b/tests/stdlib/tmarshalsegfault.nim
new file mode 100644
index 000000000..71f2766c8
--- /dev/null
+++ b/tests/stdlib/tmarshalsegfault.nim
@@ -0,0 +1,54 @@
+# issue #12405
+
+import std/[marshal, streams, times, tables, os, assertions]
+
+type AiredEpisodeState * = ref object
+    airedAt * : DateTime
+    tvShowId * : string
+    seasonNumber * : int
+    number * : int
+    title * : string
+
+type ShowsWatchlistState * = ref object
+    aired * : seq[AiredEpisodeState]
+
+type UiState * = ref object
+    shows: ShowsWatchlistState
+
+# Helpers to marshal and unmarshal
+proc load * ( state : var UiState, file : string ) =
+    var strm = newFileStream( file, fmRead )
+
+    strm.load( state )
+
+    strm.close()
+
+proc store * ( state : UiState, file : string ) =
+    var strm = newFileStream( file, fmWrite )
+
+    strm.store( state )
+
+    strm.close()
+
+# 1. We fill the state initially
+var state : UiState = UiState( shows: ShowsWatchlistState( aired: @[] ) )
+
+# VERY IMPORTANT: For some reason, small numbers (like 2 or 3) don't trigger the bug. Anything above 7 or 8 on my machine triggers though
+for i in 0..30:
+    var episode = AiredEpisodeState( airedAt: now(), tvShowId: "1", seasonNumber: 1, number: 1, title: "string" )
+
+    state.shows.aired.add( episode )
+
+# 2. Store it in a file with the marshal module, and then load it back up
+store( state, "tmarshalsegfault_data" )
+load( state, "tmarshalsegfault_data" )
+removeFile("tmarshalsegfault_data")
+
+# 3. VERY IMPORTANT: Without this line, for some reason, everything works fine
+state.shows.aired[ 0 ] = AiredEpisodeState( airedAt: now(), tvShowId: "1", seasonNumber: 1, number: 1, title: "string" )
+
+# 4. And formatting the airedAt date will now trigger the exception
+for ep in state.shows.aired:
+    let x = $ep.seasonNumber & "x" & $ep.number & " (" & $ep.airedAt & ")"
+    let y = $ep.seasonNumber & "x" & $ep.number & " (" & $ep.airedAt & ")"
+    doAssert x == y
diff --git a/tests/stdlib/tmath.nim b/tests/stdlib/tmath.nim
index a023be86c..22e5f7d88 100644
--- a/tests/stdlib/tmath.nim
+++ b/tests/stdlib/tmath.nim
@@ -1,147 +1,473 @@
 discard """
-  action: run
-  output: '''[Suite] random int
+  targets: "c cpp js"
+  matrix:"; -d:danger; --mm:refc"
+"""
 
-[Suite] random float
+# xxx: there should be a test with `-d:nimTmathCase2 -d:danger --passc:-ffast-math`,
+# but it requires disabling certain lines with `when not defined(nimTmathCase2)`
 
-[Suite] cumsum
+import std/math
+import std/assertions
 
-[Suite] random sample
 
-[Suite] ^
+# Function for approximate comparison of floats
+proc `==~`(x, y: float): bool = abs(x - y) < 1e-9
 
-'''
-"""
 
-import math, random, os
-import unittest
-import sets, tables
-
-suite "random int":
-  test "there might be some randomness":
-    var set = initHashSet[int](128)
-
-    for i in 1..1000:
-      incl(set, random(high(int)))
-    check len(set) == 1000
-  test "single number bounds work":
-
-    var rand: int
-    for i in 1..1000:
-      rand = random(1000)
-      check rand < 1000
-      check rand > -1
-  test "slice bounds work":
-
-    var rand: int
-    for i in 1..1000:
-      rand = random(100..1000)
-      check rand < 1000
-      check rand >= 100
-  test " again gives new numbers":
-
-    var rand1 = random(1000000)
-    os.sleep(200)
-
-    var rand2 = random(1000000)
-    check rand1 != rand2
-
-
-suite "random float":
-  test "there might be some randomness":
-    var set = initSet[float](128)
-
-    for i in 1..100:
-      incl(set, random(1.0))
-    check len(set) == 100
-  test "single number bounds work":
-
-    var rand: float
-    for i in 1..1000:
-      rand = random(1000.0)
-      check rand < 1000.0
-      check rand > -1.0
-  test "slice bounds work":
-
-    var rand: float
-    for i in 1..1000:
-      rand = random(100.0..1000.0)
-      check rand < 1000.0
-      check rand >= 100.0
-  test " again gives new numbers":
-
-    var rand1:float = random(1000000.0)
-    os.sleep(200)
-
-    var rand2:float = random(1000000.0)
-    check rand1 != rand2
-
-suite "cumsum":
-  test "cumsum int seq return":
-    let counts = [ 1, 2, 3, 4 ]
-    check counts.cumsummed == [ 1, 3, 6, 10 ]
-
-  test "cumsum float seq return":
-    let counts = [ 1.0, 2.0, 3.0, 4.0 ]
-    check counts.cumsummed == [ 1.0, 3.0, 6.0, 10.0 ]
-
-  test "cumsum int in-place":
-    var counts = [ 1, 2, 3, 4 ]
-    counts.cumsum
-    check counts == [ 1, 3, 6, 10 ]
-
-  test "cumsum float in-place":
-    var counts = [ 1.0, 2.0, 3.0, 4.0 ]
-    counts.cumsum
-    check counts == [ 1.0, 3.0, 6.0, 10.0 ]
-
-suite "random sample":
-  test "non-uniform array sample unnormalized int CDF":
-    let values = [ 10, 20, 30, 40, 50 ] # values
-    let counts = [ 4, 3, 2, 1, 0 ]      # weights aka unnormalized probabilities
-    var histo = initCountTable[int]()
-    let cdf = counts.cumsummed          # unnormalized CDF
-    for i in 0 ..< 5000:
-      histo.inc(sample(values, cdf))
-    check histo.len == 4                # number of non-zero in `counts`
-    # Any one bin is a binomial random var for n samples, each with prob p of
-    # adding a count to k; E[k]=p*n, Var k=p*(1-p)*n, approximately Normal for
-    # big n.  So, P(abs(k - p*n)/sqrt(p*(1-p)*n))>3.0) =~ 0.0027, while
-    # P(wholeTestFails) =~ 1 - P(binPasses)^4 =~ 1 - (1-0.0027)^4 =~ 0.01.
-    for i, c in counts:
-      if c == 0:
-        check values[i] notin histo
-        continue
-      let p = float(c) / float(cdf[^1])
-      let n = 5000.0
-      let expected = p * n
-      let stdDev = sqrt(n * p * (1.0 - p))
-      check abs(float(histo[values[i]]) - expected) <= 3.0 * stdDev
-
-  test "non-uniform array sample normalized float CDF":
-    let values = [ 10, 20, 30, 40, 50 ]     # values
-    let counts = [ 0.4, 0.3, 0.2, 0.1, 0 ]  # probabilities
-    var histo = initCountTable[int]()
-    let cdf = counts.cumsummed              # normalized CDF
-    for i in 0 ..< 5000:
-      histo.inc(sample(values, cdf))
-    check histo.len == 4                    # number of non-zero in ``counts``
-    for i, c in counts:
-      if c == 0:
-        check values[i] notin histo
-        continue
-      let p = float(c) / float(cdf[^1])
-      let n = 5000.0
-      let expected = p * n
-      let stdDev = sqrt(n * p * (1.0 - p))
-      # NOTE: like unnormalized int CDF test, P(wholeTestFails) =~ 0.01.
-      check abs(float(histo[values[i]]) - expected) <= 3.0 * stdDev
-
-suite "^":
-  test "compiles for valid types":
-    check: compiles(5 ^ 2)
-    check: compiles(5.5 ^ 2)
-    check: compiles(5.5 ^ 2.int8)
-    check: compiles(5.5 ^ 2.uint)
-    check: compiles(5.5 ^ 2.uint8)
-    check: not compiles(5.5 ^ 2.2)
\ No newline at end of file
+template main() =
+  block:
+    when not defined(js):
+      # check for no side effect annotation
+      proc mySqrt(num: float): float {.noSideEffect.} =
+        # xxx unused
+        sqrt(num)
+
+      # check gamma function
+      doAssert gamma(5.0) == 24.0 # 4!
+      doAssert almostEqual(gamma(0.5), sqrt(PI))
+      doAssert almostEqual(gamma(-0.5), -2 * sqrt(PI))
+      doAssert lgamma(1.0) == 0.0 # ln(1.0) == 0.0
+      doAssert almostEqual(lgamma(0.5), 0.5 * ln(PI))
+      doAssert erf(6.0) > erf(5.0)
+      doAssert erfc(6.0) < erfc(5.0)
+
+  block: # sgn() tests
+    doAssert sgn(1'i8) == 1
+    doAssert sgn(1'i16) == 1
+    doAssert sgn(1'i32) == 1
+    doAssert sgn(1'i64) == 1
+    doAssert sgn(1'u8) == 1
+    doAssert sgn(1'u16) == 1
+    doAssert sgn(1'u32) == 1
+    doAssert sgn(1'u64) == 1
+    doAssert sgn(-12342.8844'f32) == -1
+    doAssert sgn(123.9834'f64) == 1
+    doAssert sgn(0'i32) == 0
+    doAssert sgn(0'f32) == 0
+    doAssert sgn(-0.0'f64) == 0
+    doAssert sgn(NegInf) == -1
+    doAssert sgn(Inf) == 1
+    doAssert sgn(NaN) == 0
+
+  block: # fac() tests
+    when nimvm: discard
+    else:
+      try:
+        discard fac(-1)
+      except AssertionDefect:
+        discard
+
+    doAssert fac(0) == 1
+    doAssert fac(1) == 1
+    doAssert fac(2) == 2
+    doAssert fac(3) == 6
+    doAssert fac(4) == 24
+    doAssert fac(5) == 120
+
+  block: # floorMod/floorDiv
+    doAssert floorDiv(8, 3) == 2
+    doAssert floorMod(8, 3) == 2
+
+    doAssert floorDiv(8, -3) == -3
+    doAssert floorMod(8, -3) == -1
+
+    doAssert floorDiv(-8, 3) == -3
+    doAssert floorMod(-8, 3) == 1
+
+    doAssert floorDiv(-8, -3) == 2
+    doAssert floorMod(-8, -3) == -2
+
+    doAssert floorMod(8.0, -3.0) == -1.0
+    doAssert floorMod(-8.5, 3.0) == 0.5
+
+  block: # euclDiv/euclMod
+    doAssert euclDiv(8, 3) == 2
+    doAssert euclMod(8, 3) == 2
+
+    doAssert euclDiv(8, -3) == -2
+    doAssert euclMod(8, -3) == 2
+
+    doAssert euclDiv(-8, 3) == -3
+    doAssert euclMod(-8, 3) == 1
+
+    doAssert euclDiv(-8, -3) == 3
+    doAssert euclMod(-8, -3) == 1
+
+    doAssert euclMod(8.0, -3.0) == 2.0
+    doAssert euclMod(-8.5, 3.0) == 0.5
+
+    doAssert euclDiv(9, 3) == 3
+    doAssert euclMod(9, 3) == 0
+
+    doAssert euclDiv(9, -3) == -3
+    doAssert euclMod(9, -3) == 0
+
+    doAssert euclDiv(-9, 3) == -3
+    doAssert euclMod(-9, 3) == 0
+
+    doAssert euclDiv(-9, -3) == 3
+    doAssert euclMod(-9, -3) == 0
+
+  block: # ceilDiv
+    doAssert ceilDiv(8,  3) ==  3
+    doAssert ceilDiv(8,  4) ==  2
+    doAssert ceilDiv(8,  5) ==  2
+    doAssert ceilDiv(11, 3) ==  4
+    doAssert ceilDiv(12, 3) ==  4
+    doAssert ceilDiv(13, 3) ==  5
+    doAssert ceilDiv(41, 7) ==  6
+    doAssert ceilDiv(0,  1) ==  0
+    doAssert ceilDiv(1,  1) ==  1
+    doAssert ceilDiv(1,  2) ==  1
+    doAssert ceilDiv(2,  1) ==  2
+    doAssert ceilDiv(2,  2) ==  1
+    doAssert ceilDiv(0, high(int)) == 0
+    doAssert ceilDiv(1, high(int)) == 1
+    doAssert ceilDiv(0, high(int) - 1) == 0
+    doAssert ceilDiv(1, high(int) - 1) == 1
+    doAssert ceilDiv(high(int) div 2, high(int) div 2 + 1) == 1
+    doAssert ceilDiv(high(int) div 2, high(int) div 2 + 2) == 1
+    doAssert ceilDiv(high(int) div 2 + 1, high(int) div 2) == 2
+    doAssert ceilDiv(high(int) div 2 + 2, high(int) div 2) == 2
+    doAssert ceilDiv(high(int) div 2 + 1, high(int) div 2 + 1) == 1
+    doAssert ceilDiv(high(int), 1) == high(int)
+    doAssert ceilDiv(high(int) - 1, 1) == high(int) - 1
+    doAssert ceilDiv(high(int) - 1, 2) == high(int) div 2
+    doAssert ceilDiv(high(int) - 1, high(int)) == 1
+    doAssert ceilDiv(high(int) - 1, high(int) - 1) == 1
+    doAssert ceilDiv(high(int) - 1, high(int) - 2) == 2
+    doAssert ceilDiv(high(int), high(int)) == 1
+    doAssert ceilDiv(high(int), high(int) - 1) == 2
+    doAssert ceilDiv(255'u8,  1'u8) == 255'u8
+    doAssert ceilDiv(254'u8,  2'u8) == 127'u8
+    when not defined(danger):
+      doAssertRaises(AssertionDefect): discard ceilDiv(41,  0)
+      doAssertRaises(AssertionDefect): discard ceilDiv(41, -1)
+      doAssertRaises(AssertionDefect): discard ceilDiv(-1,  1)
+      doAssertRaises(AssertionDefect): discard ceilDiv(-1, -1)
+      doAssertRaises(AssertionDefect): discard ceilDiv(254'u8, 3'u8)
+      doAssertRaises(AssertionDefect): discard ceilDiv(255'u8, 2'u8)
+
+  block: # splitDecimal() tests
+    doAssert splitDecimal(54.674).intpart == 54.0
+    doAssert splitDecimal(54.674).floatpart ==~ 0.674
+    doAssert splitDecimal(-693.4356).intpart == -693.0
+    doAssert splitDecimal(-693.4356).floatpart ==~ -0.4356
+    doAssert splitDecimal(0.0).intpart == 0.0
+    doAssert splitDecimal(0.0).floatpart == 0.0
+
+  block: # trunc tests for vcc
+    doAssert trunc(-1.1) == -1
+    doAssert trunc(1.1) == 1
+    doAssert trunc(-0.1) == -0
+    doAssert trunc(0.1) == 0
+
+    # special case
+    doAssert classify(trunc(1e1000000)) == fcInf
+    doAssert classify(trunc(-1e1000000)) == fcNegInf
+    when not defined(nimTmathCase2):
+      doAssert classify(trunc(0.0/0.0)) == fcNan
+    doAssert classify(trunc(0.0)) == fcZero
+
+    # trick the compiler to produce signed zero
+    let
+      f_neg_one = -1.0
+      f_zero = 0.0
+      f_nan = f_zero / f_zero
+
+    doAssert classify(trunc(f_neg_one*f_zero)) == fcNegZero
+
+    doAssert trunc(-1.1'f32) == -1
+    doAssert trunc(1.1'f32) == 1
+    doAssert trunc(-0.1'f32) == -0
+    doAssert trunc(0.1'f32) == 0
+    doAssert classify(trunc(1e1000000'f32)) == fcInf
+    doAssert classify(trunc(-1e1000000'f32)) == fcNegInf
+    when not defined(nimTmathCase2):
+      doAssert classify(trunc(f_nan.float32)) == fcNan
+    doAssert classify(trunc(0.0'f32)) == fcZero
+  
+  block: # divmod
+    doAssert divmod(int.high, 1) == (int.high, 0)
+    doAssert divmod(-1073741823, 17) == (-63161283, -12)
+    doAssert divmod(int32.high, 1.int32) == (int32.high, 0.int32)
+    doAssert divmod(1073741823.int32, 5.int32) == (214748364.int32, 3.int32)
+    doAssert divmod(4611686018427387903.int64, 5.int64) == (922337203685477580.int64, 3.int64)
+    when not defined(js) and (not compileOption("panics")) and compileOption("overflowChecks"):
+      when nimvm:
+        discard # cannot catch OverflowDefect here
+      else:
+        doAssertRaises(OverflowDefect, (discard divmod(cint.low, -1.cint)))
+        doAssertRaises(OverflowDefect, (discard divmod(clong.low, -1.clong)))
+        doAssertRaises(OverflowDefect, (discard divmod(clonglong.low, -1.clonglong)))
+        doAssertRaises(DivByZeroDefect, (discard divmod(1, 0)))
+  
+  block: # log
+    doAssert log(4.0, 3.0) ==~ ln(4.0) / ln(3.0)
+    doAssert log2(8.0'f64) == 3.0'f64
+    doAssert log2(4.0'f64) == 2.0'f64
+    doAssert log2(2.0'f64) == 1.0'f64
+    doAssert log2(1.0'f64) == 0.0'f64
+    doAssert classify(log2(0.0'f64)) == fcNegInf
+
+    doAssert log2(8.0'f32) == 3.0'f32
+    doAssert log2(4.0'f32) == 2.0'f32
+    doAssert log2(2.0'f32) == 1.0'f32
+    doAssert log2(1.0'f32) == 0.0'f32
+    doAssert classify(log2(0.0'f32)) == fcNegInf
+
+  block: # cumsum
+    block: # cumsum int seq return
+      let counts = [1, 2, 3, 4]
+      doAssert counts.cumsummed == @[1, 3, 6, 10]
+      let empty: seq[int] = @[]
+      doAssert empty.cumsummed == @[]
+
+    block: # cumsum float seq return
+      let counts = [1.0, 2.0, 3.0, 4.0]
+      doAssert counts.cumsummed == @[1.0, 3.0, 6.0, 10.0]
+      let empty: seq[float] = @[]
+      doAssert empty.cumsummed == @[]
+
+    block: # cumsum int in-place
+      var counts = [1, 2, 3, 4]
+      counts.cumsum
+      doAssert counts == [1, 3, 6, 10]
+      var empty: seq[int] = @[]
+      empty.cumsum
+      doAssert empty == @[]
+
+    block: # cumsum float in-place
+      var counts = [1.0, 2.0, 3.0, 4.0]
+      counts.cumsum
+      doAssert counts == [1.0, 3.0, 6.0, 10.0]
+      var empty: seq[float] = @[]
+      empty.cumsum
+      doAssert empty == @[]
+
+  block: # ^ compiles for valid types
+    doAssert: compiles(5 ^ 2)
+    doAssert: compiles(5.5 ^ 2)
+    doAssert: compiles(5.5 ^ 2.int8)
+    doAssert: compiles(5.5 ^ 2.uint)
+    doAssert: compiles(5.5 ^ 2.uint8)
+    doAssert: not compiles(5.5 ^ 2.2)
+
+  block: # isNaN
+    doAssert NaN.isNaN
+    doAssert not Inf.isNaN
+    doAssert isNaN(Inf - Inf)
+    doAssert not isNaN(0.0)
+    doAssert not isNaN(3.1415926)
+    doAssert not isNaN(0'f32)
+
+  block: # signbit
+    doAssert not signbit(0.0)
+    doAssert signbit(-0.0)
+    doAssert signbit(-0.1)
+    doAssert not signbit(0.1)
+
+    doAssert not signbit(Inf)
+    doAssert signbit(-Inf)
+    doAssert not signbit(NaN)
+
+    let x1 = NaN
+    let x2 = -NaN
+    let x3 = -x1
+
+    doAssert isNaN(x1)
+    doAssert isNaN(x2)
+    doAssert isNaN(x3)
+    doAssert not signbit(x1)
+    doAssert signbit(x2)
+    doAssert signbit(x3)
+
+  block: # copySign
+    doAssert copySign(10.0, 1.0) == 10.0
+    doAssert copySign(10.0, -1.0) == -10.0
+    doAssert copySign(-10.0, -1.0) == -10.0
+    doAssert copySign(-10.0, 1.0) == 10.0
+    doAssert copySign(float(10), -1.0) == -10.0
+
+    doAssert copySign(10.0'f64, 1.0) == 10.0
+    doAssert copySign(10.0'f64, -1.0) == -10.0
+    doAssert copySign(-10.0'f64, -1.0) == -10.0
+    doAssert copySign(-10.0'f64, 1.0) == 10.0
+    doAssert copySign(10'f64, -1.0) == -10.0
+
+    doAssert copySign(10.0'f32, 1.0) == 10.0
+    doAssert copySign(10.0'f32, -1.0) == -10.0
+    doAssert copySign(-10.0'f32, -1.0) == -10.0
+    doAssert copySign(-10.0'f32, 1.0) == 10.0
+    doAssert copySign(10'f32, -1.0) == -10.0
+
+    doAssert copySign(Inf, -1.0) == -Inf
+    doAssert copySign(-Inf, 1.0) == Inf
+    doAssert copySign(Inf, 1.0) == Inf
+    doAssert copySign(-Inf, -1.0) == -Inf
+    doAssert copySign(Inf, 0.0) == Inf
+    doAssert copySign(Inf, -0.0) == -Inf
+    doAssert copySign(-Inf, 0.0) == Inf
+    doAssert copySign(-Inf, -0.0) == -Inf
+    doAssert copySign(1.0, -0.0) == -1.0
+    doAssert copySign(0.0, -0.0) == -0.0
+    doAssert copySign(-1.0, 0.0) == 1.0
+    doAssert copySign(10.0, 0.0) == 10.0
+    doAssert copySign(-1.0, NaN) == 1.0
+    doAssert copySign(10.0, NaN) == 10.0
+
+    doAssert copySign(NaN, NaN).isNaN
+    doAssert copySign(-NaN, NaN).isNaN
+    doAssert copySign(NaN, -NaN).isNaN
+    doAssert copySign(-NaN, -NaN).isNaN
+    doAssert copySign(NaN, 0.0).isNaN
+    doAssert copySign(NaN, -0.0).isNaN
+    doAssert copySign(-NaN, 0.0).isNaN
+    doAssert copySign(-NaN, -0.0).isNaN
+
+    doAssert copySign(-1.0, NaN) == 1.0
+    doAssert copySign(-1.0, -NaN) == -1.0
+    doAssert copySign(1.0, copySign(NaN, -1.0)) == -1.0
+
+  block: # almostEqual
+    doAssert almostEqual(3.141592653589793, 3.1415926535897936)
+    doAssert almostEqual(1.6777215e7'f32, 1.6777216e7'f32)
+    doAssert almostEqual(Inf, Inf)
+    doAssert almostEqual(-Inf, -Inf)
+    doAssert not almostEqual(Inf, -Inf)
+    doAssert not almostEqual(-Inf, Inf)
+    doAssert not almostEqual(Inf, NaN)
+    doAssert not almostEqual(NaN, NaN)
+
+  block: # round
+    block: # Round to 0 decimal places
+      doAssert round(54.652) == 55.0
+      doAssert round(54.352) == 54.0
+      doAssert round(-54.652) == -55.0
+      doAssert round(-54.352) == -54.0
+      doAssert round(0.0) == 0.0
+      doAssert 1 / round(0.0) == Inf
+      doAssert 1 / round(-0.0) == -Inf
+      doAssert round(Inf) == Inf
+      doAssert round(-Inf) == -Inf
+      doAssert round(NaN).isNaN
+      doAssert round(-NaN).isNaN
+      doAssert round(-0.5) == -1.0
+      doAssert round(0.5) == 1.0
+      doAssert round(-1.5) == -2.0
+      doAssert round(1.5) == 2.0
+      doAssert round(-2.5) == -3.0
+      doAssert round(2.5) == 3.0
+      doAssert round(2.5'f32) == 3.0'f32
+      doAssert round(2.5'f64) == 3.0'f64
+
+    block: # func round*[T: float32|float64](x: T, places: int): T
+      doAssert round(54.345, 0) == 54.0
+      template fn(x) =
+        doAssert round(x, 2).almostEqual 54.35
+        doAssert round(x, 2).almostEqual 54.35
+        doAssert round(x, -1).almostEqual 50.0
+        doAssert round(x, -2).almostEqual 100.0
+        doAssert round(x, -3).almostEqual 0.0
+      fn(54.346)
+      fn(54.346'f32)
+
+  block: # abs
+    doAssert 1.0 / abs(-0.0) == Inf
+    doAssert 1.0 / abs(0.0) == Inf
+    doAssert -1.0 / abs(-0.0) == -Inf
+    doAssert -1.0 / abs(0.0) == -Inf
+    doAssert abs(0.0) == 0.0
+    doAssert abs(0.0'f32) == 0.0'f32
+
+    doAssert abs(Inf) == Inf
+    doAssert abs(-Inf) == Inf
+    doAssert abs(NaN).isNaN
+    doAssert abs(-NaN).isNaN
+
+  block: # classify
+    doAssert classify(0.3) == fcNormal
+    doAssert classify(-0.3) == fcNormal
+    doAssert classify(5.0e-324) == fcSubnormal
+    doAssert classify(-5.0e-324) == fcSubnormal
+    doAssert classify(0.0) == fcZero
+    doAssert classify(-0.0) == fcNegZero
+    doAssert classify(NaN) == fcNan
+    doAssert classify(0.3 / 0.0) == fcInf
+    doAssert classify(Inf) == fcInf
+    doAssert classify(-0.3 / 0.0) == fcNegInf
+    doAssert classify(-Inf) == fcNegInf
+
+  block: # sum
+    let empty: seq[int] = @[]
+    doAssert sum(empty) == 0
+    doAssert sum([1, 2, 3, 4]) == 10
+    doAssert sum([-4, 3, 5]) == 4
+
+  block: # prod
+    let empty: seq[int] = @[]
+    doAssert prod(empty) == 1
+    doAssert prod([1, 2, 3, 4]) == 24
+    doAssert prod([-4, 3, 5]) == -60
+    doAssert almostEqual(prod([1.5, 3.4]), 5.1)
+    let x: seq[float] = @[]
+    doAssert prod(x) == 1.0
+
+  block: # clamp range
+    doAssert clamp(10, 1..5) == 5
+    doAssert clamp(3, 1..5) == 3
+    doAssert clamp(5, 1..5) == 5
+    doAssert clamp(42.0, 1.0 .. 3.1415926535) == 3.1415926535
+    doAssert clamp(NaN, 1.0 .. 2.0).isNaN
+    doAssert clamp(-Inf, -Inf .. -1.0) == -Inf
+    type A = enum a0, a1, a2, a3, a4, a5
+    doAssert a1.clamp(a2..a4) == a2
+    doAssert clamp((3, 0), (1, 0) .. (2, 9)) == (2, 9)
+
+  block: # edge cases
+    doAssert sqrt(-4.0).isNaN
+
+    doAssert ln(0.0) == -Inf
+    doAssert ln(-0.0) == -Inf
+    doAssert ln(-12.0).isNaN
+
+    doAssert log10(0.0) == -Inf
+    doAssert log10(-0.0) == -Inf
+    doAssert log10(-12.0).isNaN
+
+    doAssert log2(0.0) == -Inf
+    doAssert log2(-0.0) == -Inf
+    doAssert log2(-12.0).isNaN
+
+    when nimvm: discard
+    else:
+      doAssert frexp(0.0) == (0.0, 0)
+      doAssert frexp(-0.0) == (-0.0, 0)
+      doAssert classify(frexp(-0.0)[0]) == fcNegZero
+
+    when not defined(js):
+      doAssert gamma(0.0) == Inf
+      doAssert gamma(-0.0) == -Inf
+      doAssert gamma(-1.0).isNaN
+
+      doAssert lgamma(0.0) == Inf
+      doAssert lgamma(-0.0) == Inf
+      doAssert lgamma(-1.0) == Inf
+
+static: main()
+main()
+
+when not defined(js) and not defined(danger):
+  block: # bug #21792
+    block:
+      type Digit = 0..9
+      var x = [Digit 4, 7]
+
+      doAssertRaises(RangeDefect):
+        discard sum(x)
+
+    block:
+      var x = [int8 124, 127]
+
+      doAssertRaises(OverflowDefect):
+        discard sum(x)
diff --git a/tests/stdlib/tmemfiles1.nim b/tests/stdlib/tmemfiles1.nim
index 21a65369f..33657256c 100644
--- a/tests/stdlib/tmemfiles1.nim
+++ b/tests/stdlib/tmemfiles1.nim
@@ -1,4 +1,6 @@
 import memfiles, os
+import std/syncio
+
 var
   mm: MemFile
   fn = "test.mmap"
diff --git a/tests/stdlib/tmemfiles2.nim b/tests/stdlib/tmemfiles2.nim
index 1b249898e..c79f85ebf 100644
--- a/tests/stdlib/tmemfiles2.nim
+++ b/tests/stdlib/tmemfiles2.nim
@@ -4,6 +4,9 @@ discard """
 Half read size: 10 Data: Hello'''
 """
 import memfiles, os
+import std/syncio
+
+
 const
   fn = "test.mmap"
 var
@@ -12,8 +15,9 @@ var
 
 if fileExists(fn): removeFile(fn)
 
-# Create a new file, data all zeros
-mm = memfiles.open(fn, mode = fmReadWrite, newFileSize = 20)
+# Create a new file, data all zeros, starting at size 10
+mm = memfiles.open(fn, mode = fmReadWrite, newFileSize = 10, allowRemap=true)
+mm.resize 20  # resize up to 20
 mm.close()
 
 # read, change
diff --git a/tests/stdlib/tmemlinesBuf.nim b/tests/stdlib/tmemlinesBuf.nim
index 97ad751ee..7bd89d4f2 100644
--- a/tests/stdlib/tmemlinesBuf.nim
+++ b/tests/stdlib/tmemlinesBuf.nim
@@ -1,15 +1,9 @@
-discard """
-output: "15"
-disabled: "appveyor"
-"""
-
-import memfiles
+import std/[memfiles, assertions]
 var inp = memfiles.open("tests/stdlib/tmemlinesBuf.nim")
-var buffer: TaintedString = ""
+var buffer: string = ""
 var lineCount = 0
 for line in lines(inp, buffer):
   lineCount += 1
 
 close(inp)
-
-echo lineCount
+doAssert lineCount == 9, $lineCount # this file's number of lines
diff --git a/tests/stdlib/tmemmapstreams.nim b/tests/stdlib/tmemmapstreams.nim
index dd011d777..9cfae62c7 100644
--- a/tests/stdlib/tmemmapstreams.nim
+++ b/tests/stdlib/tmemmapstreams.nim
@@ -12,6 +12,8 @@ Readed line: Hello!
 Position after reading line: 7'''
 """
 import os, streams, memfiles
+import std/syncio
+
 const
   fn = "test.mmapstream"
 var
diff --git a/tests/stdlib/tmersenne.nim b/tests/stdlib/tmersenne.nim
new file mode 100644
index 000000000..64450a045
--- /dev/null
+++ b/tests/stdlib/tmersenne.nim
@@ -0,0 +1,13 @@
+import std/mersenne
+import std/assertions
+
+template main() =
+  var mt = newMersenneTwister(2525)
+
+  doAssert mt.getNum == 407788156'u32
+  doAssert mt.getNum == 1071751096'u32
+  doAssert mt.getNum == 3805347140'u32
+
+
+static: main()
+main()
diff --git a/tests/stdlib/tmget.nim b/tests/stdlib/tmget.nim
index 5e2e327f4..f41963f02 100644
--- a/tests/stdlib/tmget.nim
+++ b/tests/stdlib/tmget.nim
@@ -1,16 +1,21 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: '''Can't access 6
 10
 11
+2
 Can't access 6
 10
 11
+2
 Can't access 6
 10
 11
+2
 Can't access 6
 10
 11
+2
 0
 10
 11
@@ -40,6 +45,9 @@ block:
   x[5] += 1
   var c = x[5]
   echo c
+  x.mgetOrPut(7).inc
+  x.mgetOrPut(7).inc
+  echo x[7]
 
 block:
   var x = newTable[int, int]()
@@ -52,6 +60,9 @@ block:
   x[5] += 1
   var c = x[5]
   echo c
+  x.mgetOrPut(7).inc
+  x.mgetOrPut(7).inc
+  echo x[7]
 
 block:
   var x = initOrderedTable[int, int]()
@@ -64,6 +75,9 @@ block:
   x[5] += 1
   var c = x[5]
   echo c
+  x.mgetOrPut(7).inc
+  x.mgetOrPut(7).inc
+  echo x[7]
 
 block:
   var x = newOrderedTable[int, int]()
@@ -76,6 +90,9 @@ block:
   x[5] += 1
   var c = x[5]
   echo c
+  x.mgetOrPut(7).inc
+  x.mgetOrPut(7).inc
+  echo x[7]
 
 block:
   var x = initCountTable[int]()
@@ -104,7 +121,7 @@ block:
 import sets
 
 block:
-  var x = initSet[int]()
+  var x = initHashSet[int]()
   x.incl 5
   try:
     echo x[6]
diff --git a/tests/stdlib/tmimetypes.nim b/tests/stdlib/tmimetypes.nim
new file mode 100644
index 000000000..fd66ebd97
--- /dev/null
+++ b/tests/stdlib/tmimetypes.nim
@@ -0,0 +1,28 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import std/mimetypes
+import std/assertions
+
+
+template main() =
+  var m = newMimetypes()
+  doAssert m.getMimetype("mp4") == "video/mp4"
+  doAssert m.getExt("application/json") == "json"
+  doAssert m.getMimetype("json") == "application/json"
+  m.register("foo", "baa")
+  doAssert m.getMimetype("foo") == "baa"
+  doAssert m.getMimetype("txt") == "text/plain"
+  doAssert m.getExt("text/plain") == "txt"
+  # see also `runnableExamples`.
+  # xxx we should have a way to avoid duplicating code between runnableExamples and tests
+
+  doAssert m.getMimetype("nim") == "text/nim"
+  doAssert m.getMimetype("nimble") == "text/nimble"
+  doAssert m.getMimetype("nimf") == "text/nim"
+  doAssert m.getMimetype("nims") == "text/nim"
+
+static: main()
+main()
diff --git a/tests/stdlib/tmisc_issues.nim b/tests/stdlib/tmisc_issues.nim
new file mode 100644
index 000000000..86dcf4162
--- /dev/null
+++ b/tests/stdlib/tmisc_issues.nim
@@ -0,0 +1,39 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+import std/assertions
+
+# bug #20227
+type
+  Data = object
+    id: int
+
+  Test = distinct Data
+
+  Object = object
+    data: Test
+
+
+var x: Object = Object(data: Test(Data(id: 12)))
+doAssert Data(x.data).id == 12
+
+block: # bug #16771
+  type A = object
+    n: int
+
+  proc foo(a, b: var A) =
+    swap a, b
+
+  var a, b: A
+  a.n = 42
+  b.n = 1
+  doAssert a.n == 42
+  doAssert b.n == 1
+  a.swap b
+  doAssert a.n == 1
+  doAssert b.n == 42
+  a.foo b
+  doAssert a.n == 42
+  doAssert b.n == 1
diff --git a/tests/stdlib/tmitems.nim b/tests/stdlib/tmitems.nim
index 17265e1f7..cc515a175 100644
--- a/tests/stdlib/tmitems.nim
+++ b/tests/stdlib/tmitems.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: '''@[11, 12, 13]
 @[11, 12, 13]
 @[1, 3, 5]
@@ -16,7 +17,18 @@ fpqeew
 <Students>
   <Student Name="Aprilfoo" />
   <Student Name="bar" />
-</Students>'''
+</Students>
+<chapter>
+    <title>This is a Docbook title</title>
+    <para>
+        This is a Docbook paragraph containing <emphasis>emphasized</emphasis>,
+        <literal>literal</literal> and <replaceable>replaceable</replaceable>
+        text. Sometimes scrunched together like this:
+        <literal>literal</literal><replaceable>replaceable</replaceable>
+        and sometimes not:
+        <literal>literal</literal> <replaceable>replaceable</replaceable>
+    </para>
+</chapter>'''
 """
 
 block:
@@ -51,6 +63,7 @@ block:
 
 block:
   var x = "foobar"
+  prepareMutation(x)
   var y = cast[cstring](addr x[0])
   for c in y.mitems:
     inc c
@@ -64,6 +77,7 @@ block:
 
 block:
   var x = "foobar"
+  prepareMutation(x)
   var y = cast[cstring](addr x[0])
   for i, c in y.mpairs:
     inc c, i
@@ -123,7 +137,7 @@ block:
     x.num += 10
   echo j
 
-import xmltree, xmlparser, streams, strtabs
+import xmltree, xmlparser, parsexml, streams, strtabs
 
 block:
   var d = parseXml(newStringStream """<Students>
@@ -134,3 +148,17 @@ block:
     x = <>Student(Name=x.attrs["Name"] & "foo")
   d[1].attrs["Name"] = "bar"
   echo d
+
+block:
+  var d = parseXml(newStringStream """<chapter>
+    <title>This is a Docbook title</title>
+    <para>
+        This is a Docbook paragraph containing <emphasis>emphasized</emphasis>,
+        <literal>literal</literal> and <replaceable>replaceable</replaceable>
+        text. Sometimes scrunched together like this:
+        <literal>literal</literal><replaceable>replaceable</replaceable>
+        and sometimes not:
+        <literal>literal</literal> <replaceable>replaceable</replaceable>
+    </para>
+</chapter>""",{reportComments, reportWhitespace})
+  echo d
diff --git a/tests/stdlib/tmonotimes.nim b/tests/stdlib/tmonotimes.nim
new file mode 100644
index 000000000..1366dbfe9
--- /dev/null
+++ b/tests/stdlib/tmonotimes.nim
@@ -0,0 +1,22 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import std/[monotimes, times]
+import std/assertions
+
+let d = initDuration(nanoseconds = 10)
+let t1 = getMonoTime()
+let t2 = t1 + d
+
+doAssert t2 - t1 == d
+doAssert t1 == t1
+doAssert t1 != t2
+doAssert t2 - d == t1
+doAssert t1 < t2
+doAssert t1 <= t2
+doAssert t1 <= t1
+doAssert not(t2 < t1)
+doAssert t1 < high(MonoTime)
+doAssert low(MonoTime) < t1
diff --git a/tests/stdlib/tnativesockets.nim b/tests/stdlib/tnativesockets.nim
new file mode 100644
index 000000000..8242beb83
--- /dev/null
+++ b/tests/stdlib/tnativesockets.nim
@@ -0,0 +1,30 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/nativesockets
+import stdtest/testutils
+import std/assertions
+
+block:
+  let hostname = getHostname()
+  doAssert hostname.len > 0
+
+when defined(windows):
+  assertAll:
+    toInt(IPPROTO_IP) == 0
+    toInt(IPPROTO_ICMP) == 1
+    toInt(IPPROTO_TCP) == 6
+    toInt(IPPROTO_UDP) == 17
+    toInt(IPPROTO_IPV6) == 41
+    toInt(IPPROTO_ICMPV6) == 58
+    toInt(IPPROTO_RAW) == 20
+
+    # no changes to enum value
+    ord(IPPROTO_TCP) == 6
+    ord(IPPROTO_UDP) == 17
+    ord(IPPROTO_IP) == 18
+    ord(IPPROTO_IPV6) == 19
+    ord(IPPROTO_RAW) == 20
+    ord(IPPROTO_ICMP) == 21
+    ord(IPPROTO_ICMPV6) == 22
diff --git a/tests/stdlib/tnet.nim b/tests/stdlib/tnet.nim
index 2dd22796c..27a6ac49c 100644
--- a/tests/stdlib/tnet.nim
+++ b/tests/stdlib/tnet.nim
@@ -1,55 +1,92 @@
 discard """
+matrix: "--mm:refc; --mm:orc"
 outputsub: ""
 """
 
 import net, nativesockets
 import unittest
+import std/assertions
 
-suite "isIpAddress tests":
-  test "127.0.0.1 is valid":
+block: # isIpAddress tests
+  block: # 127.0.0.1 is valid
     check isIpAddress("127.0.0.1") == true
 
-  test "ipv6 localhost is valid":
+  block: # ipv6 localhost is valid
     check isIpAddress("::1") == true
 
-  test "fqdn is not an ip address":
+  block: # fqdn is not an ip address
     check isIpAddress("example.com") == false
 
-  test "random string is not an ipaddress":
+  block: # random string is not an ipaddress
     check isIpAddress("foo bar") == false
 
-  test "5127.0.0.1 is invalid":
+  block: # 5127.0.0.1 is invalid
     check isIpAddress("5127.0.0.1") == false
 
-  test "ipv6 is valid":
+  block: # ipv6 is valid
     check isIpAddress("2001:cdba:0000:0000:0000:0000:3257:9652") == true
 
-  test "invalid ipv6":
+  block: # invalid ipv6
     check isIpAddress("gggg:cdba:0000:0000:0000:0000:3257:9652") == false
 
 
-suite "parseIpAddress tests":
-  test "127.0.0.1 is valid":
+block: # parseIpAddress tests
+  block: # 127.0.0.1 is valid
     discard parseIpAddress("127.0.0.1")
 
-  test "ipv6 localhost is valid":
+  block: # ipv6 localhost is valid
     discard parseIpAddress("::1")
 
-  test "fqdn is not an ip address":
+  block: # fqdn is not an ip address
     expect(ValueError):
       discard parseIpAddress("example.com")
 
-  test "random string is not an ipaddress":
+  block: # random string is not an ipaddress
     expect(ValueError):
       discard parseIpAddress("foo bar")
 
-  test "ipv6 is valid":
+  block: # ipv6 is valid
     discard parseIpAddress("2001:cdba:0000:0000:0000:0000:3257:9652")
 
-  test "invalid ipv6":
+  block: # invalid ipv6
     expect(ValueError):
       discard parseIpAddress("gggg:cdba:0000:0000:0000:0000:3257:9652")
 
+  block: # ipv4-compatible ipv6 address (embedded ipv4 address)
+    check parseIpAddress("::ffff:10.0.0.23") == parseIpAddress("::ffff:0a00:0017")
+
+  block: # octal number in ipv4 address
+    expect(ValueError):
+      discard parseIpAddress("010.8.8.8")
+    expect(ValueError):
+      discard parseIpAddress("8.010.8.8")
+
+  block: # hexadecimal number in ipv4 address
+    expect(ValueError):
+      discard parseIpAddress("0xc0.168.0.1")
+    expect(ValueError):
+      discard parseIpAddress("192.0xa8.0.1")
+
+  block: # less than 4 numbers in ipv4 address
+    expect(ValueError):
+      discard parseIpAddress("127.0.1")
+
+  block: # octal number in embedded ipv4 address
+    expect(ValueError):
+      discard parseIpAddress("::ffff:010.8.8.8")
+    expect(ValueError):
+      discard parseIpAddress("::ffff:8.010.8.8")
+
+  block: # hexadecimal number in embedded ipv4 address
+    expect(ValueError):
+      discard parseIpAddress("::ffff:0xc0.168.0.1")
+    expect(ValueError):
+      discard parseIpAddress("::ffff:192.0xa8.0.1")
+
+  block: # less than 4 numbers in embedded ipv4 address
+    expect(ValueError):
+      discard parseIpAddress("::ffff:127.0.1")
+
 block: # "IpAddress/Sockaddr conversion"
   proc test(ipaddrstr: string) =
     var ipaddr_1 = parseIpAddress(ipaddrstr)
@@ -58,7 +95,7 @@ block: # "IpAddress/Sockaddr conversion"
     doAssert($ipaddrstr == $ipaddr_1)
 
     var sockaddr: Sockaddr_storage
-    var socklen: Socklen
+    var socklen: SockLen
     var ipaddr_2: IpAddress
     var port_2: Port
 
diff --git a/tests/stdlib/tnet_ll.nim b/tests/stdlib/tnet_ll.nim
index 2ac272fd1..199946482 100644
--- a/tests/stdlib/tnet_ll.nim
+++ b/tests/stdlib/tnet_ll.nim
@@ -1,42 +1,52 @@
-discard """

-  action: run

-  output: '''

-[Suite] inet_ntop tests

-'''

-"""

-

-when defined(windows):

-  import winlean

-elif defined(posix):

-  import posix

-else:

-  {.error: "Unsupported OS".}

-

-import unittest, strutils

-

-suite "inet_ntop tests":

-

-  setup:

-    when defined(windows):

-      var wsa: WSAData

-      discard wsaStartup(0x101'i16, wsa.addr)

-  

-  test "IP V4":

-    var ip4 = 0x10111213

-    var buff: array[0..255, char]

-    let r = inet_ntop(AF_INET, ip4.addr, buff[0].addr, buff.sizeof.int32)

-    let res = if r == nil: "" else: $r

-    check: res == "19.18.17.16"

-      

-

-  test "IP V6":

-    when defined(windows):

-      let ipv6Support = (getVersion() and 0xff) > 0x5

-    else:

-      let ipv6Support = true

-          

-    var ip6 = [0x1000'u16, 0x1001, 0x2000, 0x2001, 0x3000, 0x3001, 0x4000, 0x4001]

-    var buff: array[0..255, char]

-    let r = inet_ntop(AF_INET6, ip6[0].addr, buff[0].addr, buff.sizeof.int32)

-    let res = if r == nil: "" else: $r

-    check: not ipv6Support or res == "10:110:20:120:30:130:40:140"

+discard """
+  action: run
+  matrix: "--mm:refc; --mm:orc"
+  output: '''
+
+[Suite] inet_ntop tests
+'''
+"""
+
+when defined(windows):
+  import winlean
+elif defined(posix):
+  import posix
+else:
+  {.error: "Unsupported OS".}
+
+import unittest, strutils
+
+suite "inet_ntop tests":
+
+  setup:
+    when defined(windows):
+      var wsa: WSAData
+      discard wsaStartup(0x101'i16, wsa.addr)
+  
+  test "IP V4":
+    # regular
+    var ip4 = InAddr()
+    ip4.s_addr = 0x10111213'u32
+    check: ip4.s_addr == 0x10111213'u32
+
+    var buff: array[0..255, char]
+    let r = inet_ntop(AF_INET, cast[pointer](ip4.s_addr.addr), cast[cstring](buff[0].addr), buff.len.int32)
+    let res = if r == nil: "" else: $r
+    check: res == "19.18.17.16"
+      
+  test "IP V6":
+    when defined(windows):
+      let ipv6Support = (getVersion() and 0xff) > 0x5
+    else:
+      let ipv6Support = true
+          
+    var ip6 = [0x1000'u16, 0x1001, 0x2000, 0x2001, 0x3000, 0x3001, 0x4000, 0x4001]
+    var buff: array[0..255, char]
+    let r = inet_ntop(AF_INET6, cast[pointer](ip6[0].addr), cast[cstring](buff[0].addr), buff.len.int32)
+    let res = if r == nil: "" else: $r
+    check: not ipv6Support or res == "10:110:20:120:30:130:40:140"
+
+  test "InAddr":
+    # issue 19244
+    var ip4 = InAddr(s_addr: 0x10111213'u32)
+    check: ip4.s_addr == 0x10111213'u32
diff --git a/tests/stdlib/tnetbind.nim b/tests/stdlib/tnetbind.nim
index b2bcf4b05..84f9ac464 100644
--- a/tests/stdlib/tnetbind.nim
+++ b/tests/stdlib/tnetbind.nim
@@ -1,3 +1,14 @@
+discard """
+matrix: "--mm:refc; --mm:orc"
+joinable: false
+"""
+
+#[
+joinable: false
+otherwise:
+Error: unhandled exception: Address already in use [OSError]
+]#
+
 import net
 
 ## Test for net.bindAddr
diff --git a/tests/stdlib/tnetconnect.nim b/tests/stdlib/tnetconnect.nim
new file mode 100644
index 000000000..ae654aed9
--- /dev/null
+++ b/tests/stdlib/tnetconnect.nim
@@ -0,0 +1,30 @@
+discard """
+  disabled: "i386"
+  matrix: "-d:ssl"
+"""
+
+import std/net
+from std/strutils import `%`
+from stdtest/testutils import enableRemoteNetworking
+
+# bug #15215
+proc test() =
+  let ctx = newContext()
+
+  proc fn(url: string) =
+    let socket = newSocket()
+    defer: close(socket)
+    connect(socket, url, Port(443), 5000) # typically 20 could be enough
+    send(socket, "GET / HTTP/1.0\nHost: $#\nConnection: close\n\n" % [url])
+    wrapSocket(ctx, socket)
+
+  # trying 2 sites makes it more resilent: refs #17458 this could give:
+  # * Call to 'connect' timed out. [TimeoutError]
+  # * No route to host [OSError]
+  try:
+    fn("www.nim-lang.org")
+  except TimeoutError, OSError:
+    fn("www.google.com")
+
+when enableRemoteNetworking:
+  test()
diff --git a/tests/stdlib/tnetdial.nim b/tests/stdlib/tnetdial.nim
index 695150179..a1e147ad5 100644
--- a/tests/stdlib/tnetdial.nim
+++ b/tests/stdlib/tnetdial.nim
@@ -2,20 +2,20 @@ discard """
   cmd: "nim c --threads:on $file"
   exitcode: 0
   output: "OK"
-  disabled: "travis"
 """
 
 import os, net, nativesockets, asyncdispatch
+import std/[assertions, typedthreads]
 
 ## Test for net.dial
 
 const port = Port(28431)
 
 proc initIPv6Server(hostname: string, port: Port): AsyncFD =
-  let fd = newNativeSocket(AF_INET6)
+  let fd = createNativeSocket(AF_INET6)
   setSockOptInt(fd, SOL_SOCKET, SO_REUSEADDR, 1)
   var aiList = getAddrInfo(hostname, port, AF_INET6)
-  if bindAddr(fd, aiList.ai_addr, aiList.ai_addrlen.Socklen) < 0'i32:
+  if bindAddr(fd, aiList.ai_addr, aiList.ai_addrlen.SockLen) < 0'i32:
     freeAddrInfo(aiList)
     raiseOSError(osLastError())
   freeAddrInfo(aiList)
@@ -39,10 +39,10 @@ proc testThread() {.thread.} =
   fd.close()
 
 proc test() =
+  let serverFd = initIPv6Server("::1", port)
   var t: Thread[void]
   createThread(t, testThread)
 
-  let serverFd = initIPv6Server("::1", port)
   var done = false
 
   serverFd.accept().callback = proc(fut: Future[AsyncFD]) =
@@ -58,4 +58,5 @@ proc test() =
 
   joinThread(t)
 
+# this would cause #13132 `for i in 0..<10000: test()`
 test()
diff --git a/tests/stdlib/tnre.nim b/tests/stdlib/tnre.nim
index 0929956cb..3b40e9e83 100644
--- a/tests/stdlib/tnre.nim
+++ b/tests/stdlib/tnre.nim
@@ -1,24 +1,8 @@
 discard """
+matrix: "--mm:refc; --mm:orc"
 # Since the tests for nre are all bundled together we treat failure in one test as an nre failure
 # When running 'testament/tester' a failed check() in the test suite will cause the exit
 # codes to differ and be reported as a failure
-
-  output:
-    '''[Suite] Test NRE initialization
-
-[Suite] captures
-
-[Suite] find
-
-[Suite] string splitting
-
-[Suite] match
-
-[Suite] replace
-
-[Suite] escape strings
-
-[Suite] Misc tests'''
 """
 
 import nre
diff --git a/tests/stdlib/tntpath.nim b/tests/stdlib/tntpath.nim
new file mode 100644
index 000000000..8efdd6bd0
--- /dev/null
+++ b/tests/stdlib/tntpath.nim
@@ -0,0 +1,50 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/private/ntpath
+import std/assertions
+
+block: # From Python's `Lib/test/test_ntpath.py`
+  doAssert splitDrive(r"c:\foo\bar") == (r"c:", r"\foo\bar")
+  doAssert splitDrive(r"c:/foo/bar") == (r"c:", r"/foo/bar")
+  doAssert splitDrive(r"\\conky\mountpoint\foo\bar") == (r"\\conky\mountpoint", r"\foo\bar")
+  doAssert splitDrive(r"//conky/mountpoint/foo/bar") == (r"//conky/mountpoint", r"/foo/bar")
+  doAssert splitDrive(r"\\\conky\mountpoint\foo\bar") == (r"", r"\\\conky\mountpoint\foo\bar")
+  doAssert splitDrive(r"///conky/mountpoint/foo/bar") == (r"", r"///conky/mountpoint/foo/bar")
+  doAssert splitDrive(r"\\conky\\mountpoint\foo\bar") == (r"", r"\\conky\\mountpoint\foo\bar")
+  doAssert splitDrive(r"//conky//mountpoint/foo/bar") == (r"", r"//conky//mountpoint/foo/bar")
+  # Issue #19911: UNC part containing U+0130
+  doAssert splitDrive(r"//conky/MOUNTPOİNT/foo/bar") == (r"//conky/MOUNTPOİNT", r"/foo/bar")
+  # gh-81790: support device namespace, including UNC drives.
+  doAssert splitDrive(r"//?/c:") == (r"//?/c:", r"")
+  doAssert splitDrive(r"//?/c:/") == (r"//?/c:", r"/")
+  doAssert splitDrive(r"//?/c:/dir") == (r"//?/c:", r"/dir")
+  doAssert splitDrive(r"//?/UNC") == (r"", r"//?/UNC")
+  doAssert splitDrive(r"//?/UNC/") == (r"", r"//?/UNC/")
+  doAssert splitDrive(r"//?/UNC/server/") == (r"//?/UNC/server/", r"")
+  doAssert splitDrive(r"//?/UNC/server/share") == (r"//?/UNC/server/share", r"")
+  doAssert splitDrive(r"//?/UNC/server/share/dir") == (r"//?/UNC/server/share", r"/dir")
+  doAssert splitDrive(r"//?/VOLUME{00000000-0000-0000-0000-000000000000}/spam") == (r"//?/VOLUME{00000000-0000-0000-0000-000000000000}", r"/spam")
+  doAssert splitDrive(r"//?/BootPartition/") == (r"//?/BootPartition", r"/")
+
+  doAssert splitDrive(r"\\?\c:") == (r"\\?\c:", r"")
+  doAssert splitDrive(r"\\?\c:\") == (r"\\?\c:", r"\")
+  doAssert splitDrive(r"\\?\c:\dir") == (r"\\?\c:", r"\dir")
+  doAssert splitDrive(r"\\?\UNC") == (r"", r"\\?\UNC")
+  doAssert splitDrive(r"\\?\UNC\") == (r"", r"\\?\UNC\")
+  doAssert splitDrive(r"\\?\UNC\server\") == (r"\\?\UNC\server\", r"")
+  doAssert splitDrive(r"\\?\UNC\server\share") == (r"\\?\UNC\server\share", r"")
+  doAssert splitDrive(r"\\?\UNC\server\share\dir") == (r"\\?\UNC\server\share", r"\dir")
+  doAssert splitDrive(r"\\?\VOLUME{00000000-0000-0000-0000-000000000000}\spam") == (r"\\?\VOLUME{00000000-0000-0000-0000-000000000000}", r"\spam")
+  doAssert splitDrive(r"\\?\BootPartition\") == (r"\\?\BootPartition", r"\")
+
+block:
+  doAssert splitDrive(r"C:") == (r"C:", r"")
+  doAssert splitDrive(r"C:\") == (r"C:", r"\")
+  doAssert splitDrive(r"non/absolute/path") == (r"", r"non/absolute/path")
+
+  # Special for `\`-rooted paths on Windows. I don't know if this is correct,
+  # rbut `\` is not recognized as a drive, in contrast to `C:` or `\?\c:`.
+  # This behavior is the same for Python's `splitdrive` function.
+  doAssert splitDrive(r"\\") == (r"", r"\\")
diff --git a/tests/stdlib/tobjectdollar.nim b/tests/stdlib/tobjectdollar.nim
new file mode 100644
index 000000000..cf78fa255
--- /dev/null
+++ b/tests/stdlib/tobjectdollar.nim
@@ -0,0 +1,14 @@
+discard """
+  matrix: "-d:nimPreviewSlimSystem"
+"""
+
+import std/assertions
+
+type Foo = object
+  a, b: int
+
+let x = Foo(a: 23, b: 45)
+doAssert not compiles($x)
+import std/objectdollar
+doAssert compiles($x)
+doAssert $x == "(a: 23, b: 45)"
diff --git a/tests/stdlib/toids.nim b/tests/stdlib/toids.nim
new file mode 100644
index 000000000..dd5b84c51
--- /dev/null
+++ b/tests/stdlib/toids.nim
@@ -0,0 +1,15 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/oids
+import std/assertions
+
+block: # genOid
+  let x = genOid()
+  doAssert ($x).len == 24
+
+block:
+  let x = genOid()
+  let y = parseOid(cstring($x))
+  doAssert x == y
diff --git a/tests/stdlib/topenssl.nim b/tests/stdlib/topenssl.nim
new file mode 100644
index 000000000..af259627f
--- /dev/null
+++ b/tests/stdlib/topenssl.nim
@@ -0,0 +1,46 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/wordwrap
+import openssl
+import std/assertions
+
+const PubKey = r"MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAknKWvrdnncCIzBnIGrZ5qtZrPH+Yo3t7ag9WZIu6Gmc/JgIDDaZhJeyGW0YSnifeAEhooWvM4jDWhTEARzktalSHqYtmwI/1Oxwp6NTYH8akMe2LCpZ5pX9FVA6m9o2tkbdXatbDKRqeD4UA8Ow7Iyrdo6eb1SU8vk+26i+uXHTtsb25p8uf2ppOJrJCy+1vr8Gsnuwny1UdoYZTxMsxRFPf+UX/LrSXMHVq/oPVa3SJ4VHMpYrG/httAugVP6K58xiZ93jst63/dd0JL85mWJu1uS3uz92aL5O97xzth3wR4BbdmDUlN4LuTIwi6DtEcC7gUOTnOzH4zgp2b5RyHwIDAQAB"
+const PrivateKey = r"MIIEpAIBAAKCAQEAknKWvrdnncCIzBnIGrZ5qtZrPH+Yo3t7ag9WZIu6Gmc/JgIDDaZhJeyGW0YSnifeAEhooWvM4jDWhTEARzktalSHqYtmwI/1Oxwp6NTYH8akMe2LCpZ5pX9FVA6m9o2tkbdXatbDKRqeD4UA8Ow7Iyrdo6eb1SU8vk+26i+uXHTtsb25p8uf2ppOJrJCy+1vr8Gsnuwny1UdoYZTxMsxRFPf+UX/LrSXMHVq/oPVa3SJ4VHMpYrG/httAugVP6K58xiZ93jst63/dd0JL85mWJu1uS3uz92aL5O97xzth3wR4BbdmDUlN4LuTIwi6DtEcC7gUOTnOzH4zgp2b5RyHwIDAQABAoIBACSOxmLFlfAjaALLTNCeTLEA5bQshgYJhT1sprxixQpiS7lJN0npBsdYzBFs5KjmetzHNpdVOcgdOO/204L0Gwo4H8WLLxNS3HztAulEeM813zc3fUYfWi6eHshk//j8VR/TDNd21TElm99z7FA4KGsXAE0iQhxrN0aqz5aWYIhjprtHA5KxXIiESnTkof5Cud8oXEnPiwPGNhq93QeQzh7xQIKSaDKBcdAa6edTFhzc4RLUQRfrik/GqJzouEDQ9v6H/uiOLTB3FxxwErQIf6dvSVhD9gs1nSLQfyj3S2Hxe9S2zglTl07EsawTQUxtVQkdZUOok67c7CPBxecZ2wECgYEA2c31gr/UJwczT+P/AE52GkHHETXMxqE3Hnh9n4CitfAFSD5X0VwZvGjZIlln2WjisTd92Ymf65eDylX2kCm93nzZ2GfXgS4zl4oY1N87+VeNQlx9f2+6GU7Hs0HFdfu8bGd+0sOuWA1PFqQCobxCACMPTkuzsG9M7knUTN59HS8CgYEArCEoP4ReYoOFveXUE0AteTPb4hryvR9VDEolP+LMoiPe8AzBMeB5fP493TPdjtnWmrPCXNLc7UAFSj2CZsRhau4PuiqnNrsb5iz/7iXVl3E8wZvS4w7WYpO4m33L0cijA6MdcdqilQu4Z5tw4nG45lAW9UYyOc9D4hJTzgtGHhECgYA6QyDoj931brSoK0ocT+DB11Sj4utbOuberMaV8zgTSRhwodSl+WgdAUMMMDRacPcrBrgQiAMSZ15msqYZHEFhEa7Id8arFKvSXquTzf9iDKyJ0unzO/ThLjS3W+GxVNyrdufzA0tQ3IaKfOcDUrOpC7fdbtyrVqqSl4dF5MI9GwKBgQCl3OF6qyOEDDZgsUk1L59h7k3QR6VmBf4e9IeGUxZamvQlHjU/yY1nm1mjgGnbUB/SPKtqZKoMV6eBTVoNiuhQcItpGda9D3mnx+7p3T0/TBd+fJeuwcplfPDjrEktogcq5w/leQc3Ve7gr1EMcwb3r28f8/9L42QHQR/OKODs8QKBgQCFAvxDRPyYg7V/AgD9rt1KzXi4+b3Pls5NXZa2g/w+hmdhHUNxV5IGmHlqFnptGyshgYgQGxMMkW0iJ1j8nLamFnkbFQOp5/UKbdPLRKiB86oPpxsqYtPXucDUqEfcMsp57mD1CpGVODbspogFpSUvQpMECkhvI0XLMbolMdo53g=="
+
+proc rsaPublicEncrypt(fr: string): string =
+  let mKey = "-----BEGIN PUBLIC KEY-----\n" & PubKey.wrapWords(64) & "\n-----END PUBLIC KEY-----"
+  let bio = bioNew(bioSMem())
+  doAssert BIO_write(bio, mKey.cstring, mKey.len.cint) >= 0
+  let rsa = PEM_read_bio_RSA_PUBKEY(bio, nil, nil, nil)
+  doAssert rsa != nil
+  doAssert BIO_free(bio) >= 0
+  result = newString(RSA_size(rsa))
+  let frdata = cast[ptr uint8](fr.cstring)
+  var todata = cast[ptr uint8](result.cstring)
+  doAssert RSA_public_encrypt(fr.len.cint, frdata, todata, rsa, RSA_PKCS1_PADDING) != -1
+  RSA_free(rsa)
+
+proc rasPrivateDecrypt(fr: string): string =
+  let mKey = "-----BEGIN RSA PRIVATE KEY-----\n" & PrivateKey.wrapWords(64) & "\n-----END RSA PRIVATE KEY-----"
+  let bio = bioNew(bioSMem())
+  doAssert BIO_write(bio, mKey.cstring, mKey.len.cint) >= 0
+  let rsa = PEM_read_bio_RSAPrivateKey(bio, nil, nil, nil)
+  doAssert rsa != nil
+  doAssert BIO_free(bio) >= 0
+  let rsaLen = RSA_size(rsa)
+  result = newString(rsaLen)
+  let frdata = cast[ptr uint8](fr.cstring)
+  var todata = cast[ptr uint8](result.cstring)
+  let lenOrig = RSA_private_decrypt(rsaLen, frdata, todata, rsa, RSA_PKCS1_PADDING)
+  doAssert lenOrig >= 0 and lenOrig < result.len
+  doAssert result[lenOrig] == '\0'
+  result.setLen lenOrig
+  RSA_free(rsa)
+
+let res = "TEST"
+let miwen = rsaPublicEncrypt(res)
+let mingwen = rasPrivateDecrypt(miwen)
+doAssert mingwen == res
+
diff --git a/tests/stdlib/toptions.nim b/tests/stdlib/toptions.nim
new file mode 100644
index 000000000..63a10e746
--- /dev/null
+++ b/tests/stdlib/toptions.nim
@@ -0,0 +1,207 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import std/[json, options]
+
+import std/assertions
+import std/objectdollar
+
+
+# RefPerson is used to test that overloaded `==` operator is not called by
+# options. It is defined here in the global scope, because otherwise the test
+# will not even consider the `==` operator. Different bug?
+type RefPerson = ref object
+  name: string
+
+proc `==`(a, b: RefPerson): bool =
+  assert(not a.isNil and not b.isNil)
+  a.name == b.name
+
+
+template disableJsVm(body) =
+  # something doesn't work in JS VM
+  when defined(js):
+    when nimvm: discard
+    else: body
+  else:
+    body
+
+proc main() =
+  type
+    Foo = ref object
+      test: string
+    Test = object
+      foo: Option[Foo]
+
+  let js = """{"foo": {"test": "123"}}"""
+  let parsed = parseJson(js)
+  let a = parsed.to(Test)
+  doAssert $(%*a) == """{"foo":{"test":"123"}}"""
+
+  block options:
+    # work around a bug in unittest
+    let intNone = none(int)
+    let stringNone = none(string)
+
+    block example:
+      proc find(haystack: string, needle: char): Option[int] =
+        for i, c in haystack:
+          if c == needle:
+            return some i
+
+      doAssert("abc".find('c').get() == 2)
+
+      let result = "team".find('i')
+
+      doAssert result == intNone
+      doAssert result.isNone
+
+    block some:
+      doAssert some(6).get() == 6
+      doAssert some("a").unsafeGet() == "a"
+      doAssert some(6).isSome
+      doAssert some("a").isSome
+
+    block none:
+      doAssertRaises UnpackDefect:
+        discard none(int).get()
+      doAssert(none(int).isNone)
+      doAssert(not none(string).isSome)
+
+    block equality:
+      doAssert some("a") == some("a")
+      doAssert some(7) != some(6)
+      doAssert some("a") != stringNone
+      doAssert intNone == intNone
+
+      when compiles(some("a") == some(5)):
+        doAssert false
+      when compiles(none(string) == none(int)):
+        doAssert false
+
+    block get_with_a_default_value:
+      doAssert(some("Correct").get("Wrong") == "Correct")
+      doAssert(stringNone.get("Correct") == "Correct")
+
+    block stringify:
+      doAssert($(some("Correct")) == "some(\"Correct\")")
+      doAssert($(stringNone) == "none(string)")
+
+    disableJsVm:
+      block map_with_a_void_result:
+        var procRan = 0
+        # TODO closure anonymous functions doesn't work in VM with JS
+        # Error: cannot evaluate at compile time: procRan
+        some(123).map(proc (v: int) = procRan = v)
+        doAssert procRan == 123
+        intNone.map(proc (v: int) = doAssert false)
+
+    block map:
+      doAssert(some(123).map(proc (v: int): int = v * 2) == some(246))
+      doAssert(intNone.map(proc (v: int): int = v * 2).isNone)
+
+    block filter:
+      doAssert(some(123).filter(proc (v: int): bool = v == 123) == some(123))
+      doAssert(some(456).filter(proc (v: int): bool = v == 123).isNone)
+      doAssert(intNone.filter(proc (v: int): bool = doAssert false).isNone)
+
+    block flatMap:
+      proc addOneIfNotZero(v: int): Option[int] =
+        if v != 0:
+          result = some(v + 1)
+        else:
+          result = none(int)
+
+      doAssert(some(1).flatMap(addOneIfNotZero) == some(2))
+      doAssert(some(0).flatMap(addOneIfNotZero) == none(int))
+      doAssert(some(1).flatMap(addOneIfNotZero).flatMap(addOneIfNotZero) == some(3))
+
+      proc maybeToString(v: int): Option[string] =
+        if v != 0:
+          result = some($v)
+        else:
+          result = none(string)
+
+      doAssert(some(1).flatMap(maybeToString) == some("1"))
+
+      proc maybeExclaim(v: string): Option[string] =
+        if v != "":
+          result = some v & "!"
+        else:
+          result = none(string)
+
+      doAssert(some(1).flatMap(maybeToString).flatMap(maybeExclaim) == some("1!"))
+      doAssert(some(0).flatMap(maybeToString).flatMap(maybeExclaim) == none(string))
+
+    block SomePointer:
+      var intref: ref int
+      doAssert(option(intref).isNone)
+      intref.new
+      doAssert(option(intref).isSome)
+
+      let tmp = option(intref)
+      doAssert(sizeof(tmp) == sizeof(ptr int))
+
+      var prc = proc (x: int): int = x + 1
+      doAssert(option(prc).isSome)
+      prc = nil
+      doAssert(option(prc).isNone)
+
+    block:
+      doAssert(none[int]().isNone)
+      doAssert(none(int) == none[int]())
+
+    # "$ on typed with .name"
+    block:
+      type Named = object
+        name: string
+
+      let nobody = none(Named)
+      doAssert($nobody == "none(Named)")
+
+    # "$ on type with name()"
+    block:
+      type Person = object
+        myname: string
+
+      let noperson = none(Person)
+      doAssert($noperson == "none(Person)")
+
+    # "Ref type with overloaded `==`"
+    block:
+      let p = some(RefPerson.new())
+      doAssert p.isSome
+
+    block: # test cstring
+      block:
+        let x = some("".cstring)
+        doAssert x.isSome
+        doAssert x.get == ""
+
+      block:
+        let x = some("12345".cstring)
+        doAssert x.isSome
+        doAssert x.get == "12345"
+
+      block:
+        let x = "12345".cstring
+        let y = some(x)
+        doAssert y.isSome
+        doAssert y.get == "12345"
+
+      block:
+        let x = none(cstring)
+        doAssert x.isNone
+        doAssert $x == "none(cstring)"
+
+static: main()
+main()
+
+when not defined(js):
+  block: # bug #22932
+    var it = iterator: int {.closure.} = discard
+    doAssert it.option.isSome # Passes.
+    it = nil
+    doAssert it.option.isNone # Passes.
diff --git a/tests/stdlib/tos.nim b/tests/stdlib/tos.nim
index 03fc1f1e9..611659fdb 100644
--- a/tests/stdlib/tos.nim
+++ b/tests/stdlib/tos.nim
@@ -22,10 +22,13 @@ __really_obscure_dir_name/test
 Raises
 Raises
 '''
+  matrix: "--mm:refc; --mm:orc"
+  joinable: false
 """
 # test os path creation, iteration, and deletion
 
-import os, strutils, pathnorm
+from stdtest/specialpaths import buildDir
+import std/[syncio, assertions, osproc, os, strutils, pathnorm]
 
 block fileOperations:
   let files = @["these.txt", "are.x", "testing.r", "files.q"]
@@ -36,6 +39,30 @@ block fileOperations:
   createDir(dname)
   doAssert dirExists(dname)
 
+  block: # copyFile, copyFileToDir
+    doAssertRaises(OSError): copyFile(dname/"nonexistent.txt", dname/"nonexistent.txt")
+    let fname = "D20201009T112235"
+    let fname2 = "D20201009T112235.2"
+    let str = "foo1\0foo2\nfoo3\0"
+    let file = dname/fname
+    let file2 = dname/fname2
+    writeFile(file, str)
+    doAssert readFile(file) == str
+    let sub = "sub"
+    doAssertRaises(OSError): copyFile(file, dname/sub/fname2)
+    doAssertRaises(OSError): copyFileToDir(file, dname/sub)
+    doAssertRaises(ValueError): copyFileToDir(file, "")
+    copyFile(file, file2)
+    doAssert fileExists(file2)
+    doAssert readFile(file2) == str
+    createDir(dname/sub)
+    copyFileToDir(file, dname/sub)
+    doAssert fileExists(dname/sub/fname)
+    removeDir(dname/sub)
+    doAssert not dirExists(dname/sub)
+    removeFile(file)
+    removeFile(file2)
+
   # Test creating files and dirs
   for dir in dirs:
     createDir(dname/dir)
@@ -130,6 +157,172 @@ block fileOperations:
   doAssert fileExists("../dest/a/file.txt")
   removeDir("../dest")
 
+  # createDir should not fail if `dir` is empty
+  createDir("")
+
+
+  when defined(linux): # bug #24174
+    createDir("a/b")
+    open("a/file.txt", fmWrite).close
+
+    if not fileExists("a/fifoFile"):
+      doAssert execCmd("mkfifo -m 600 a/fifoFile") == 0
+
+    copyDir("a/", "../dest/a/", skipSpecial = true)
+    copyDirWithPermissions("a/", "../dest2/a/", skipSpecial = true)
+    removeDir("a")
+
+  # Symlink handling in `copyFile`, `copyFileWithPermissions`, `copyFileToDir`,
+  # `copyDir`, `copyDirWithPermissions`, `moveFile`, and `moveDir`.
+  block:
+    const symlinksAreHandled = not defined(windows)
+    const dname = buildDir/"D20210116T140629"
+    const subDir = dname/"sub"
+    const subDir2 = dname/"sub2"
+    const brokenSymlinkName = "D20210101T191320_BROKEN_SYMLINK"
+    const brokenSymlink = dname/brokenSymlinkName
+    const brokenSymlinkSrc = "D20210101T191320_nonexistent"
+    const brokenSymlinkCopy = brokenSymlink & "_COPY"
+    const brokenSymlinkInSubDir = subDir/brokenSymlinkName
+    const brokenSymlinkInSubDir2 = subDir2/brokenSymlinkName
+
+    createDir(subDir)
+    createSymlink(brokenSymlinkSrc, brokenSymlink)
+
+    # Test copyFile
+    when symlinksAreHandled:
+      doAssertRaises(OSError):
+        copyFile(brokenSymlink, brokenSymlinkCopy)
+      doAssertRaises(OSError):
+        copyFile(brokenSymlink, brokenSymlinkCopy, {cfSymlinkFollow})
+    copyFile(brokenSymlink, brokenSymlinkCopy, {cfSymlinkIgnore})
+    doAssert not fileExists(brokenSymlinkCopy)
+    copyFile(brokenSymlink, brokenSymlinkCopy, {cfSymlinkAsIs})
+    when symlinksAreHandled:
+      doAssert expandSymlink(brokenSymlinkCopy) == brokenSymlinkSrc
+      removeFile(brokenSymlinkCopy)
+    else:
+      doAssert not fileExists(brokenSymlinkCopy)
+    doAssertRaises(AssertionDefect):
+      copyFile(brokenSymlink, brokenSymlinkCopy,
+               {cfSymlinkAsIs, cfSymlinkFollow})
+
+    # Test copyFileWithPermissions
+    when symlinksAreHandled:
+      doAssertRaises(OSError):
+        copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy)
+      doAssertRaises(OSError):
+        copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
+                                options = {cfSymlinkFollow})
+    copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
+                            options = {cfSymlinkIgnore})
+    doAssert not fileExists(brokenSymlinkCopy)
+    copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
+                            options = {cfSymlinkAsIs})
+    when symlinksAreHandled:
+      doAssert expandSymlink(brokenSymlinkCopy) == brokenSymlinkSrc
+      removeFile(brokenSymlinkCopy)
+    else:
+      doAssert not fileExists(brokenSymlinkCopy)
+    doAssertRaises(AssertionDefect):
+      copyFileWithPermissions(brokenSymlink, brokenSymlinkCopy,
+                              options = {cfSymlinkAsIs, cfSymlinkFollow})
+
+    # Test copyFileToDir
+    when symlinksAreHandled:
+      doAssertRaises(OSError):
+        copyFileToDir(brokenSymlink, subDir)
+      doAssertRaises(OSError):
+        copyFileToDir(brokenSymlink, subDir, {cfSymlinkFollow})
+    copyFileToDir(brokenSymlink, subDir, {cfSymlinkIgnore})
+    doAssert not fileExists(brokenSymlinkInSubDir)
+    copyFileToDir(brokenSymlink, subDir, {cfSymlinkAsIs})
+    when symlinksAreHandled:
+      doAssert expandSymlink(brokenSymlinkInSubDir) == brokenSymlinkSrc
+      removeFile(brokenSymlinkInSubDir)
+    else:
+      doAssert not fileExists(brokenSymlinkInSubDir)
+
+    createSymlink(brokenSymlinkSrc, brokenSymlinkInSubDir)
+
+    # Test copyDir
+    copyDir(subDir, subDir2)
+    when symlinksAreHandled:
+      doAssert expandSymlink(brokenSymlinkInSubDir2) == brokenSymlinkSrc
+    else:
+      doAssert not fileExists(brokenSymlinkInSubDir2)
+    removeDir(subDir2)
+
+    # Test copyDirWithPermissions
+    copyDirWithPermissions(subDir, subDir2)
+    when symlinksAreHandled:
+      doAssert expandSymlink(brokenSymlinkInSubDir2) == brokenSymlinkSrc
+    else:
+      doAssert not fileExists(brokenSymlinkInSubDir2)
+    removeDir(subDir2)
+
+    # Test moveFile
+    moveFile(brokenSymlink, brokenSymlinkCopy)
+    when not defined(windows):
+      doAssert expandSymlink(brokenSymlinkCopy) == brokenSymlinkSrc
+    else:
+      doAssert symlinkExists(brokenSymlinkCopy)
+    removeFile(brokenSymlinkCopy)
+
+    # Test moveDir
+    moveDir(subDir, subDir2)
+    when not defined(windows):
+      doAssert expandSymlink(brokenSymlinkInSubDir2) == brokenSymlinkSrc
+    else:
+      doAssert symlinkExists(brokenSymlinkInSubDir2)
+
+    removeDir(dname)
+
+block: # moveFile
+  let tempDir = getTempDir() / "D20210609T151608"
+  createDir(tempDir)
+  defer: removeDir(tempDir)
+
+  writeFile(tempDir / "a.txt", "")
+  moveFile(tempDir / "a.txt", tempDir / "b.txt")
+  doAssert not fileExists(tempDir / "a.txt")
+  doAssert fileExists(tempDir / "b.txt")
+  removeFile(tempDir / "b.txt")
+
+  createDir(tempDir / "moveFile_test")
+  writeFile(tempDir / "moveFile_test/a.txt", "")
+  moveFile(tempDir / "moveFile_test/a.txt", tempDir / "moveFile_test/b.txt")
+  doAssert not fileExists(tempDir / "moveFile_test/a.txt")
+  doAssert fileExists(tempDir / "moveFile_test/b.txt")
+  removeDir(tempDir / "moveFile_test")
+
+  createDir(tempDir / "moveFile_test")
+  writeFile(tempDir / "a.txt", "")
+  moveFile(tempDir / "a.txt", tempDir / "moveFile_test/b.txt")
+  doAssert not fileExists(tempDir / "a.txt")
+  doAssert fileExists(tempDir / "moveFile_test/b.txt")
+  removeDir(tempDir / "moveFile_test")
+
+block: # moveDir
+  let tempDir = getTempDir() / "D20210609T161443"
+  createDir(tempDir)
+  defer: removeDir(tempDir)
+
+  createDir(tempDir / "moveDir_test")
+  moveDir(tempDir / "moveDir_test/", tempDir / "moveDir_test_dest")
+  doAssert not dirExists(tempDir / "moveDir_test")
+  doAssert dirExists(tempDir / "moveDir_test_dest")
+  removeDir(tempDir / "moveDir_test_dest")
+
+  createDir(tempDir / "moveDir_test")
+  writeFile(tempDir / "moveDir_test/a.txt", "")
+  moveDir(tempDir / "moveDir_test", tempDir / "moveDir_test_dest")
+  doAssert not dirExists(tempDir / "moveDir_test")
+  doAssert not fileExists(tempDir / "moveDir_test/a.txt")
+  doAssert dirExists(tempDir / "moveDir_test_dest")
+  doAssert fileExists(tempDir / "moveDir_test_dest/a.txt")
+  removeDir(tempDir / "moveDir_test_dest")
+
 import times
 block modificationTime:
   # Test get/set modification times
@@ -154,7 +347,7 @@ block walkDirRec:
     doAssert p.startsWith("walkdir_test")
 
   var s: seq[string]
-  for p in walkDirRec("walkdir_test", {pcFile}, {pcDir}, relative=true):
+  for p in walkDirRec("walkdir_test", {pcFile}, {pcDir}, relative = true):
     s.add(p)
 
   doAssert s.len == 2
@@ -163,13 +356,36 @@ block walkDirRec:
 
   removeDir("walkdir_test")
 
-when not defined(windows):
-  block walkDirRelative:
-    createDir("walkdir_test")
-    createSymlink(".", "walkdir_test/c")
-    for k, p in walkDir("walkdir_test", true):
-      doAssert k == pcLinkToDir
-    removeDir("walkdir_test")
+import std/sequtils
+
+block: # walkDir
+  doAssertRaises(OSError):
+    for a in walkDir("nonexistent", checkDir = true): discard
+  doAssertRaises(OSError):
+    for p in walkDirRec("nonexistent", checkDir = true): discard
+
+  when not defined(windows):
+    block walkDirRelative:
+      createDir("walkdir_test")
+      createSymlink(".", "walkdir_test/c")
+      for k, p in walkDir("walkdir_test", true):
+        doAssert k == pcLinkToDir
+      removeDir("walkdir_test")
+
+  when defined(posix):
+    block walkDirSpecial:
+      createDir("walkdir_test")
+      doAssert execShellCmd("mkfifo walkdir_test/fifo") == 0
+      createSymlink("fifo", "walkdir_test/fifo_link")
+      let withSpecialFiles = toSeq(walkDir("walkdir_test", relative = true))
+      doAssert (withSpecialFiles.len == 2 and
+                (pcFile, "fifo") in withSpecialFiles and
+                (pcLinkToFile, "fifo_link") in withSpecialFiles)
+      # now Unix special files are excluded from walkdir output:
+      let skipSpecialFiles = toSeq(walkDir("walkdir_test", relative = true,
+                                           skipSpecial = true))
+      doAssert skipSpecialFiles.len == 0
+      removeDir("walkdir_test")
 
 block normalizedPath:
   doAssert normalizedPath("") == ""
@@ -216,7 +432,7 @@ block absolutePath:
   doAssertRaises(ValueError): discard absolutePath("a", "b")
   doAssert absolutePath("a") == getCurrentDir() / "a"
   doAssert absolutePath("a", "/b") == "/b" / "a"
-  when defined(Posix):
+  when defined(posix):
     doAssert absolutePath("a", "/b/") == "/b" / "a"
     doAssert absolutePath("a", "/b/c") == "/b/c" / "a"
     doAssert absolutePath("/a", "b/") == "/a"
@@ -325,19 +541,30 @@ block ospaths:
   doAssert relativePath("/Users/me/bar/z.nim", "/Users/other/bad", '/') == "../../me/bar/z.nim"
 
   doAssert relativePath("/Users/me/bar/z.nim", "/Users/other", '/') == "../me/bar/z.nim"
-  doAssert relativePath("/Users///me/bar//z.nim", "//Users/", '/') == "me/bar/z.nim"
+
+  # `//` is a UNC path, `/` is the current working directory's drive, so can't
+  # run this test on Windows.
+  when not doslikeFileSystem:
+    doAssert relativePath("/Users///me/bar//z.nim", "//Users/", '/') == "me/bar/z.nim"
   doAssert relativePath("/Users/me/bar/z.nim", "/Users/me", '/') == "bar/z.nim"
   doAssert relativePath("", "/users/moo", '/') == ""
   doAssert relativePath("foo", "", '/') == "foo"
-  doAssert relativePath("/foo", "/Foo", '/') == (when FileSystemCaseSensitive: "../foo" else: "")
-  doAssert relativePath("/Foo", "/foo", '/') == (when FileSystemCaseSensitive: "../Foo" else: "")
-  doAssert relativePath("/foo", "/fOO", '/') == (when FileSystemCaseSensitive: "../foo" else: "")
-  doAssert relativePath("/foO", "/foo", '/') == (when FileSystemCaseSensitive: "../foO" else: "")
+  doAssert relativePath("/foo", "/Foo", '/') == (when FileSystemCaseSensitive: "../foo" else: ".")
+  doAssert relativePath("/Foo", "/foo", '/') == (when FileSystemCaseSensitive: "../Foo" else: ".")
+  doAssert relativePath("/foo", "/fOO", '/') == (when FileSystemCaseSensitive: "../foo" else: ".")
+  doAssert relativePath("/foO", "/foo", '/') == (when FileSystemCaseSensitive: "../foO" else: ".")
 
   doAssert relativePath("foo", ".", '/') == "foo"
   doAssert relativePath(".", ".", '/') == "."
   doAssert relativePath("..", ".", '/') == ".."
 
+  doAssert relativePath("foo", "foo") == "."
+  doAssert relativePath("", "foo") == ""
+  doAssert relativePath("././/foo", "foo//./") == "."
+
+  doAssert relativePath(getCurrentDir() / "bar", "foo") == "../bar".unixToNativePath
+  doAssert relativePath("bar", getCurrentDir() / "foo") == "../bar".unixToNativePath
+
   when doslikeFileSystem:
     doAssert relativePath(r"c:\foo.nim", r"C:\") == r"foo.nim"
     doAssert relativePath(r"c:\foo\bar\baz.nim", r"c:\foo") == r"bar\baz.nim"
@@ -353,10 +580,50 @@ block ospaths:
     doAssert relativePath(r"\\foo\bar\baz.nim", r"\foo") == r"\\foo\bar\baz.nim"
     doAssert relativePath(r"c:\foo.nim", r"\foo") == r"c:\foo.nim"
 
-  doAssert joinPath("usr", "") == unixToNativePath"usr/"
+  doAssert joinPath("usr", "") == unixToNativePath"usr"
   doAssert joinPath("", "lib") == "lib"
   doAssert joinPath("", "/lib") == unixToNativePath"/lib"
   doAssert joinPath("usr/", "/lib") == unixToNativePath"usr/lib"
+  doAssert joinPath("", "") == unixToNativePath"" # issue #13455
+  doAssert joinPath("", "/") == unixToNativePath"/"
+  doAssert joinPath("/", "/") == unixToNativePath"/"
+  doAssert joinPath("/", "") == unixToNativePath"/"
+  doAssert joinPath("/" / "") == unixToNativePath"/" # weird test case...
+  doAssert joinPath("/", "/a/b/c") == unixToNativePath"/a/b/c"
+  doAssert joinPath("foo/", "") == unixToNativePath"foo/"
+  doAssert joinPath("foo/", "abc") == unixToNativePath"foo/abc"
+  doAssert joinPath("foo//./", "abc/.//") == unixToNativePath"foo/abc/"
+  doAssert joinPath("foo", "abc") == unixToNativePath"foo/abc"
+  doAssert joinPath("", "abc") == unixToNativePath"abc"
+
+  doAssert joinPath("zook/.", "abc") == unixToNativePath"zook/abc"
+
+  # controversial: inconsistent with `joinPath("zook/.","abc")`
+  # on linux, `./foo` and `foo` are treated a bit differently for executables
+  # but not `./foo/bar` and `foo/bar`
+  doAssert joinPath(".", "/lib") == unixToNativePath"./lib"
+  doAssert joinPath(".", "abc") == unixToNativePath"./abc"
+
+  # cases related to issue #13455
+  doAssert joinPath("foo", "", "") == "foo"
+  doAssert joinPath("foo", "") == "foo"
+  doAssert joinPath("foo/", "") == unixToNativePath"foo/"
+  doAssert joinPath("foo/", ".") == "foo"
+  doAssert joinPath("foo", "./") == unixToNativePath"foo/"
+  doAssert joinPath("foo", "", "bar/") == unixToNativePath"foo/bar/"
+
+  # issue #13579
+  doAssert joinPath("/foo", "../a") == unixToNativePath"/a"
+  doAssert joinPath("/foo/", "../a") == unixToNativePath"/a"
+  doAssert joinPath("/foo/.", "../a") == unixToNativePath"/a"
+  doAssert joinPath("/foo/.b", "../a") == unixToNativePath"/foo/a"
+  doAssert joinPath("/foo///", "..//a/") == unixToNativePath"/a/"
+  doAssert joinPath("foo/", "../a") == unixToNativePath"a"
+
+  when doslikeFileSystem:
+    doAssert joinPath("C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\", "..\\..\\VC\\vcvarsall.bat") == r"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat"
+    doAssert joinPath("C:\\foo", "..\\a") == r"C:\a"
+    doAssert joinPath("C:\\foo\\", "..\\a") == r"C:\a"
 
 block getTempDir:
   block TMPDIR:
@@ -372,16 +639,8 @@ block getTempDir:
       else:
         doAssert getTempDir() == "/tmp/"
 
-block osenv:
-  block delEnv:
-    const dummyEnvVar = "DUMMY_ENV_VAR" # This env var wouldn't be likely to exist to begin with
-    doAssert existsEnv(dummyEnvVar) == false
-    putEnv(dummyEnvVar, "1")
-    doAssert existsEnv(dummyEnvVar) == true
-    delEnv(dummyEnvVar)
-    doAssert existsEnv(dummyEnvVar) == false
-    delEnv(dummyEnvVar)         # deleting an already deleted env var
-    doAssert existsEnv(dummyEnvVar) == false
+block: # getCacheDir
+  doAssert getCacheDir().dirExists
 
 block isRelativeTo:
   doAssert isRelativeTo("/foo", "/")
@@ -394,3 +653,223 @@ block isRelativeTo:
   doAssert isRelativeTo("foo/bar", ".")
   doAssert not isRelativeTo("foo/bar.nims", "foo/bar.nim")
   doAssert not isRelativeTo("/foo2", "/foo")
+
+block: # quoteShellWindows
+  doAssert quoteShellWindows("aaa") == "aaa"
+  doAssert quoteShellWindows("aaa\"") == "aaa\\\""
+  doAssert quoteShellWindows("") == "\"\""
+
+block: # quoteShellCommand
+  when defined(windows):
+    doAssert quoteShellCommand(["a b c", "d", "e"]) == """"a b c" d e"""
+    doAssert quoteShellCommand(["""ab"c""", r"\", "d"]) == """ab\"c \ d"""
+    doAssert quoteShellCommand(["""ab"c""", """ \""", "d"]) == """ab\"c " \\" d"""
+    doAssert quoteShellCommand(["""a\\\b""", """de fg""", "h"]) == """a\\\b "de fg" h"""
+    doAssert quoteShellCommand(["""a\"b""", "c", "d"]) == """a\\\"b c d"""
+    doAssert quoteShellCommand(["""a\\b c""", "d", "e"]) == """"a\\b c" d e"""
+    doAssert quoteShellCommand(["""a\\b\ c""", "d", "e"]) == """"a\\b\ c" d e"""
+    doAssert quoteShellCommand(["ab", ""]) == """ab """""
+
+block: # quoteShellPosix
+  doAssert quoteShellPosix("aaa") == "aaa"
+  doAssert quoteShellPosix("aaa a") == "'aaa a'"
+  doAssert quoteShellPosix("") == "''"
+  doAssert quoteShellPosix("a'a") == "'a'\"'\"'a'"
+
+block: # quoteShell
+  when defined(posix):
+    doAssert quoteShell("") == "''"
+
+block: # normalizePathEnd
+  # handle edge cases correctly: shouldn't affect whether path is
+  # absolute/relative
+  doAssert "".normalizePathEnd(true) == ""
+  doAssert "".normalizePathEnd(false) == ""
+  doAssert "/".normalizePathEnd(true) == $DirSep
+  doAssert "/".normalizePathEnd(false) == $DirSep
+
+  when defined(posix):
+    doAssert "//".normalizePathEnd(false) == "/"
+    doAssert "foo.bar//".normalizePathEnd == "foo.bar"
+    doAssert "bar//".normalizePathEnd(trailingSep = true) == "bar/"
+  when defined(windows):
+    doAssert r"C:\foo\\".normalizePathEnd == r"C:\foo"
+    doAssert r"C:\foo".normalizePathEnd(trailingSep = true) == r"C:\foo\"
+    # this one is controversial: we could argue for returning `D:\` instead,
+    # but this is simplest.
+    doAssert r"D:\".normalizePathEnd == r"D:"
+    doAssert r"E:/".normalizePathEnd(trailingSep = true) == r"E:\"
+    doAssert "/".normalizePathEnd == r"\"
+
+
+import sugar
+
+block: # normalizeExe
+  doAssert "".dup(normalizeExe) == ""
+  when defined(posix):
+    doAssert "foo".dup(normalizeExe) == "./foo"
+    doAssert "foo/../bar".dup(normalizeExe) == "foo/../bar"
+  when defined(windows):
+    doAssert "foo".dup(normalizeExe) == "foo"
+
+block: # isAdmin
+  let isAzure = existsEnv("TF_BUILD") # xxx factor with testament.specs.isAzure
+  # In Azure on Windows tests run as an admin user
+  if isAzure and defined(windows): doAssert isAdmin()
+  # In Azure on POSIX tests run as a normal user
+  if isAzure and defined(posix): doAssert not isAdmin()
+
+
+import sugar
+
+block: # normalizeExe
+  doAssert "".dup(normalizeExe) == ""
+  when defined(posix):
+    doAssert "foo".dup(normalizeExe) == "./foo"
+    doAssert "foo/../bar".dup(normalizeExe) == "foo/../bar"
+  when defined(windows):
+    doAssert "foo".dup(normalizeExe) == "foo"
+
+block: # isAdmin
+  let isAzure = existsEnv("TF_BUILD") # xxx factor with testament.specs.isAzure
+  # In Azure on Windows tests run as an admin user
+  if isAzure and defined(windows): doAssert isAdmin()
+  # In Azure on POSIX tests run as a normal user
+  if isAzure and defined(posix): doAssert not isAdmin()
+
+when doslikeFileSystem:
+  import std/private/ntpath
+
+  block: # Bug #19103 UNC paths
+
+    # Easiest way of generating a valid, readable and writable UNC path
+    let tempDir = r"\\?\" & getTempDir()
+    doAssert dirExists tempDir
+    createDir tempDir / "test"
+    removeDir tempDir / "test"
+    createDir tempDir / "recursive" / "test"
+    removeDir tempDir / "recursive" / "test"
+
+    let tempDir2 = getTempDir()
+    let (drive, pathNoDrive) = splitDrive(tempDir2)
+    setCurrentDir drive
+    doAssert cmpIgnoreCase(getCurrentDir().splitDrive.drive, drive) == 0
+
+    # Test `\Users` path syntax on Windows by stripping away drive. `\`
+    # resolves to the drive in current working directory. This drive will be
+    # the same as `tempDir2` because of the `setCurrentDir` above.
+    doAssert pathNoDrive[0] == '\\'
+    createDir pathNoDrive / "test"
+    doAssert dirExists pathNoDrive / "test"
+    removeDir pathNoDrive / "test"
+
+    doAssert splitPath("//?/c:") == ("//?/c:", "")
+
+    doAssert relativePath("//?/c:///Users//me", "//?/c:", '/') == "Users/me"
+
+    doAssert parentDir(r"\\?\c:") == r""
+    doAssert parentDir(r"//?/c:/Users") == r"\\?\c:"
+    doAssert parentDir(r"\\localhost\c$") == r""
+    doAssert parentDir(r"\Users") == r"\"
+
+    doAssert tailDir("//?/c:") == ""
+    doAssert tailDir("//?/c:/Users") == "Users"
+    doAssert tailDir(r"\\localhost\c$\Windows\System32") == r"Windows\System32"
+
+    doAssert isRootDir("//?/c:")
+    doAssert isRootDir("//?/UNC/localhost/c$")
+    doAssert not isRootDir(r"\\?\c:\Users")
+
+    doAssert parentDirs(r"C:\Users", fromRoot = true).toSeq == @[r"C:\", r"C:\Users"]
+    doAssert parentDirs(r"C:\Users", fromRoot = false).toSeq == @[r"C:\Users", r"C:"]
+    doAssert parentDirs(r"\\?\c:\Users", fromRoot = true).toSeq ==
+      @[r"\\?\c:\", r"\\?\c:\Users"]
+    doAssert parentDirs(r"\\?\c:\Users", fromRoot = false).toSeq ==
+      @[r"\\?\c:\Users", r"\\?\c:"]
+    doAssert parentDirs(r"//localhost/c$/Users", fromRoot = true).toSeq ==
+      @[r"//localhost/c$/", r"//localhost/c$/Users"]
+    doAssert parentDirs(r"//?/UNC/localhost/c$/Users", fromRoot = false).toSeq ==
+      @[r"//?/UNC/localhost/c$/Users", r"\\?\UNC\localhost\c$"]
+    doAssert parentDirs(r"\Users", fromRoot = true).toSeq == @[r"\", r"\Users"]
+    doAssert parentDirs(r"\Users", fromRoot = false).toSeq == @[r"\Users", r"\"]
+
+    doAssert r"//?/c:" /../ "d/e" == r"\\?\c:\d\e"
+    doAssert r"//?/c:/Users" /../ "d/e" == r"\\?\c:\d\e"
+    doAssert r"\\localhost\c$" /../ "d/e" == r"\\localhost\c$\d\e"
+
+    doAssert splitFile("//?/c:") == ("//?/c:", "", "")
+    doAssert splitFile("//?/c:/Users") == ("//?/c:", "Users", "")
+    doAssert splitFile(r"\\localhost\c$\test.txt") == (r"\\localhost\c$", "test", ".txt")
+
+else:
+  block: # parentDirs
+    doAssert parentDirs("/home", fromRoot=true).toSeq == @["/", "/home"]
+    doAssert parentDirs("/home", fromRoot=false).toSeq == @["/home", "/"]
+    doAssert parentDirs("home", fromRoot=true).toSeq == @["home"]
+    doAssert parentDirs("home", fromRoot=false).toSeq == @["home"]
+
+    doAssert parentDirs("/home/user", fromRoot=true).toSeq == @["/", "/home/", "/home/user"]
+    doAssert parentDirs("/home/user", fromRoot=false).toSeq == @["/home/user", "/home", "/"]
+    doAssert parentDirs("home/user", fromRoot=true).toSeq == @["home/", "home/user"]
+    doAssert parentDirs("home/user", fromRoot=false).toSeq == @["home/user", "home"]
+
+
+# https://github.com/nim-lang/Nim/pull/19643#issuecomment-1235102314
+block:  # isValidFilename
+  # Negative Tests.
+  doAssert not isValidFilename("abcd", maxLen = 2)
+  doAssert not isValidFilename("0123456789", maxLen = 8)
+  doAssert not isValidFilename("con")
+  doAssert not isValidFilename("aux")
+  doAssert not isValidFilename("prn")
+  doAssert not isValidFilename("OwO|UwU")
+  doAssert not isValidFilename(" foo")
+  doAssert not isValidFilename("foo ")
+  doAssert not isValidFilename("foo.")
+  doAssert not isValidFilename("con.txt")
+  doAssert not isValidFilename("aux.bat")
+  doAssert not isValidFilename("prn.exe")
+  doAssert not isValidFilename("nim>.nim")
+  doAssert not isValidFilename(" foo.log")
+  # Positive Tests.
+  doAssert isValidFilename("abcd", maxLen = 42.Positive)
+  doAssert isValidFilename("c0n")
+  doAssert isValidFilename("foo.aux")
+  doAssert isValidFilename("bar.prn")
+  doAssert isValidFilename("OwO_UwU")
+  doAssert isValidFilename("cron")
+  doAssert isValidFilename("ux.bat")
+  doAssert isValidFilename("nim.nim")
+  doAssert isValidFilename("foo.log")
+
+block: # searchExtPos
+  doAssert "foo.nim".searchExtPos == 3
+  doAssert "/foo.nim".searchExtPos == 4
+  doAssert "".searchExtPos == -1
+  doAssert "/".searchExtPos == -1
+  doAssert "a.b/foo".searchExtPos == -1
+  doAssert ".".searchExtPos == -1
+  doAssert "foo.".searchExtPos == 3
+  doAssert "foo..".searchExtPos == 4
+  doAssert "..".searchExtPos == -1
+  doAssert "...".searchExtPos == -1
+  doAssert "./".searchExtPos == -1
+  doAssert "../".searchExtPos == -1
+  doAssert "/.".searchExtPos == -1
+  doAssert "/..".searchExtPos == -1
+  doAssert ".b".searchExtPos == -1
+  doAssert "..b".searchExtPos == -1
+  doAssert "/.b".searchExtPos == -1
+  doAssert "a/.b".searchExtPos == -1
+  doAssert ".a.b".searchExtPos == 2
+  doAssert "a/.b.c".searchExtPos == 4
+  doAssert "a/..b".searchExtPos == -1
+  doAssert "a/b..c".searchExtPos == 4
+
+  when doslikeFileSystem:
+    doAssert "c:a.b".searchExtPos == 3
+    doAssert "c:.a".searchExtPos == -1
+    doAssert r"c:\.a".searchExtPos == -1
+    doAssert "c:..a".searchExtPos == -1
+    doAssert r"c:\..a".searchExtPos == -1
+    doAssert "c:.a.b".searchExtPos == 4
diff --git a/tests/stdlib/tos_unc.nim b/tests/stdlib/tos_unc.nim
index e55de11ce..194deeb42 100644
--- a/tests/stdlib/tos_unc.nim
+++ b/tests/stdlib/tos_unc.nim
@@ -1,9 +1,11 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   disabled: "posix"
 """
 
 # bug 10952, UNC paths
 import os
+import std/assertions
 
 doAssert r"\\hostname\foo\bar" / "baz" == r"\\hostname\foo\bar\baz"
 doAssert r"\\?\C:\foo" / "bar" == r"\\?\C:\foo\bar"
diff --git a/tests/stdlib/tosenv.nim b/tests/stdlib/tosenv.nim
new file mode 100644
index 000000000..17e397987
--- /dev/null
+++ b/tests/stdlib/tosenv.nim
@@ -0,0 +1,163 @@
+discard """
+  matrix: "--mm:refc; --mm:arc"
+  joinable: false
+  targets: "c js cpp"
+"""
+
+import std/os
+from std/sequtils import toSeq
+import stdtest/testutils
+
+when defined(nimPreviewSlimSystem):
+  import std/[assertions]
+
+# "LATIN CAPITAL LETTER AE" in UTF-8 (0xc386)
+const unicodeUtf8 = "\xc3\x86"
+
+template main =
+  block: # delEnv, existsEnv, getEnv, envPairs
+    for val in ["val", "", unicodeUtf8]: # ensures empty val works too
+      const key = "NIM_TESTS_TOSENV_KEY"
+      doAssert not existsEnv(key)
+
+      putEnv(key, "tempval")
+      doAssert existsEnv(key)
+      doAssert getEnv(key) == "tempval"
+
+      putEnv(key, val) # change a key that already exists
+      doAssert existsEnv(key)
+      doAssert getEnv(key) == val
+
+      doAssert (key, val) in toSeq(envPairs())
+      delEnv(key)
+      doAssert (key, val) notin toSeq(envPairs())
+      doAssert not existsEnv(key)
+      delEnv(key) # deleting an already deleted env var
+      doAssert not existsEnv(key)
+
+    block:
+      doAssert getEnv("NIM_TESTS_TOSENV_NONEXISTENT", "") == ""
+      doAssert getEnv("NIM_TESTS_TOSENV_NONEXISTENT", " ") == " "
+      doAssert getEnv("NIM_TESTS_TOSENV_NONEXISTENT", "defval") == "defval"
+
+    whenVMorJs: discard # xxx improve
+    do:
+      doAssertRaises(OSError, putEnv("NIM_TESTS_TOSENV_PUT=DUMMY_VALUE", "NEW_DUMMY_VALUE"))
+      doAssertRaises(OSError, putEnv("", "NEW_DUMMY_VALUE"))
+      doAssert not existsEnv("")
+      doAssert not existsEnv("NIM_TESTS_TOSENV_PUT=DUMMY_VALUE")
+      doAssert not existsEnv("NIM_TESTS_TOSENV_PUT")
+
+static: main()
+main()
+
+when defined(windows):
+  import std/widestrs
+  proc c_wgetenv(env: WideCString): WideCString {.importc: "_wgetenv", header: "<stdlib.h>".}
+proc c_getenv(env: cstring): cstring {.importc: "getenv", header: "<stdlib.h>".}
+
+when not defined(js) and not defined(nimscript):
+  when defined(nimPreviewSlimSystem):
+    import std/typedthreads
+  block: # bug #18533
+    var thr: Thread[void]
+    proc threadFunc {.thread.} = putEnv("foo", "fooVal2")
+
+    putEnv("foo", "fooVal1")
+    doAssert getEnv("foo") == "fooVal1"
+    createThread(thr, threadFunc)
+    joinThreads(thr)
+    when defined(windows):
+      doAssert getEnv("foo") == $c_wgetenv("foo".newWideCString)
+    else:
+      doAssert getEnv("foo") == $c_getenv("foo".cstring)
+
+    doAssertRaises(OSError): delEnv("foo=bar")
+
+when defined(windows) and not defined(nimscript):
+  import std/encodings
+
+  proc c_putenv(env: cstring): int32 {.importc: "putenv", header: "<stdlib.h>".}
+  proc c_wputenv(env: WideCString): int32 {.importc: "_wputenv", header: "<stdlib.h>".}
+
+  block: # Bug #20083
+    # These test that `getEnv`, `putEnv` and `existsEnv` handle Unicode
+    # characters correctly. This means that module X in the process calling the
+    # CRT environment variable API will get the correct string. Raw CRT API
+    # calls below represent module X.
+
+    # Getting an env. var. with unicode characters returns the correct UTF-8
+    # encoded string.
+    block:
+      const envName = "twin_envvars1"
+      doAssert c_wputenv(newWideCString(envName & "=" & unicodeUtf8)) == 0
+      doAssert existsEnv(envName)
+      doAssert getEnv(envName) == unicodeUtf8
+
+    # Putting an env. var. with unicode characters gives the correct UTF-16
+    # encoded string from low-level routine.
+    block:
+      const envName = "twin_envvars2"
+      putEnv(envName, unicodeUtf8)
+      doAssert $c_wgetenv(envName.newWideCString) == unicodeUtf8
+
+    # Env. name containing Unicode characters is retrieved correctly
+    block:
+      const envName = unicodeUtf8 & "1"
+      doAssert c_wputenv(newWideCString(envName & "=" & unicodeUtf8)) == 0
+      doAssert existsEnv(envName)
+      doAssert getEnv(envName) == unicodeUtf8
+
+    # Env. name containing Unicode characters is set correctly
+    block:
+      const envName = unicodeUtf8 & "2"
+      putEnv(envName, unicodeUtf8)
+      doAssert existsEnv(envName)
+      doAssert $c_wgetenv(envName.newWideCString) == unicodeUtf8
+
+    # Env. name containing Unicode characters and empty value is set correctly
+    block:
+      const envName = unicodeUtf8 & "3"
+      putEnv(envName, "")
+      doAssert existsEnv(envName)
+      doAssert $c_wgetenv(envName.newWideCString) == ""
+
+    # It's hard to test on Windows code pages, because there is no "change
+    # a process' locale" API.
+    if getCurrentEncoding(true) == "windows-1252":
+      const
+        unicodeAnsi = "\xc6" # `unicodeUtf8` in `windows-1252` encoding
+
+      # Test that env. var. ANSI API has correct encoding
+      block:
+        const
+          envName = unicodeUtf8 & "4"
+          envNameAnsi = unicodeAnsi & "4"
+        putEnv(envName, unicodeUtf8)
+        doAssert $c_getenv(envNameAnsi.cstring) == unicodeAnsi
+
+      block:
+        const
+          envName = unicodeUtf8 & "5"
+          envNameAnsi = unicodeAnsi & "5"
+        doAssert c_putenv((envNameAnsi & "=" & unicodeAnsi).cstring) == 0
+        doAssert getEnv(envName) == unicodeUtf8
+
+      # Env. name containing Unicode characters and empty value is set correctly;
+      # and, if env. name. characters cannot be represented in codepage, don't
+      # raise an error.
+      #
+      # `win_setenv.nim` converts UTF-16 to ANSI when setting empty env. var. The
+      # windows-1250 locale has no representation of `abreveUtf8` below, so the
+      # conversion will fail, but this must not be fatal. It is expected that the
+      # routine ignores updating MBCS environment (`environ` global) and carries
+      # on.
+      block:
+        const
+          # "LATIN SMALL LETTER A WITH BREVE" in UTF-8
+          abreveUtf8 = "\xc4\x83"
+          envName = abreveUtf8 & "6"
+        putEnv(envName, "")
+        doAssert existsEnv(envName)
+        doAssert $c_wgetenv(envName.newWideCString) == ""
+        doAssert getEnv(envName) == ""
diff --git a/tests/stdlib/toserrors.nim b/tests/stdlib/toserrors.nim
new file mode 100644
index 000000000..e907dfe63
--- /dev/null
+++ b/tests/stdlib/toserrors.nim
@@ -0,0 +1,9 @@
+discard """
+  action: compile
+"""
+
+import std/oserrors
+
+let x1 = osLastError()
+raiseOSError(x1)
+echo osErrorMsg(x1)
diff --git a/tests/stdlib/tosproc.nim b/tests/stdlib/tosproc.nim
index 1859877e7..da4f6252d 100644
--- a/tests/stdlib/tosproc.nim
+++ b/tests/stdlib/tosproc.nim
@@ -1,11 +1,20 @@
-# test the osproc module
+discard """
+matrix: "--mm:refc; --mm:orc"
+joinable: false
+"""
 
-import stdtest/specialpaths
-import "../.." / compiler/unittest_light
+#[
+joinable: false
+because it'd need cleanup up stdout
+
+see also: tests/osproc/*.nim; consider merging those into a single test here
+(easier to factor and test more things as a single self contained test)
+]#
+import std/[assertions, syncio]
 
 when defined(case_testfile): # compiled test file for child process
   from posix import exitnow
-  proc c_exit2(code: c_int): void {.importc: "_exit", header: "<unistd.h>".}
+  proc c_exit2(code: cint): void {.importc: "_exit", header: "<unistd.h>".}
   import os
   var a = 0
   proc fun(b = 0) =
@@ -22,6 +31,12 @@ when defined(case_testfile): # compiled test file for child process
     case arg
     of "exit_0":
       if true: quit(0)
+    of "exit_1":
+      if true: quit(1)
+    of "exit_2":
+      if true: quit(2)
+    of "exit_42":
+      if true: quit(42)
     of "exitnow_139":
       if true: exitnow(139)
     of "c_exit2_139":
@@ -45,22 +60,56 @@ when defined(case_testfile): # compiled test file for child process
       echo args[1]
   main()
 
-else:
+elif defined(case_testfile2):
+  import strutils
+  let x = stdin.readLine()
+  echo x.parseInt + 5
+
+elif defined(case_testfile3):
+  echo "start ta_out"
+  stdout.writeLine("to stdout")
+  stdout.flushFile()
+  stdout.writeLine("to stdout")
+  stdout.flushFile()
+
+  stderr.writeLine("to stderr")
+  stderr.flushFile()
+  stderr.writeLine("to stderr")
+  stderr.flushFile()
+
+  stdout.writeLine("to stdout")
+  stdout.flushFile()
+  stdout.writeLine("to stdout")
+  stdout.flushFile()
+  echo "end ta_out"
 
-  import os, osproc, strutils, posix
+elif defined(case_testfile4):
+  import system # we could remove that
+  quit(QuitFailure)
+
+else: # main driver
+  import stdtest/[specialpaths, unittest_light]
+  import os, osproc, strutils
   const nim = getCurrentCompilerExe()
+  const sourcePath = currentSourcePath()
+  let dir = getCurrentDir() / "tests" / "osproc"
+
+  template deferring(cleanup, body) =
+    try: body
+    finally: cleanup
+
+  # we're testing `execShellCmd` so don't rely on it to compile test file
+  # note: this should be exported in posix.nim
+  proc c_system(cmd: cstring): cint {.importc: "system", header: "<stdlib.h>".}
+
+  proc compileNimProg(opt: string, name: string): string =
+    result = buildDir / name.addFileExt(ExeExt)
+    let cmd = "$# c -o:$# --hints:off $# $#" % [nim.quoteShell, result.quoteShell, opt, sourcePath.quoteShell]
+    doAssert c_system(cmd) == 0, $cmd
+    doAssert result.fileExists
 
   block execShellCmdTest:
-    ## first, compile child program
-    const sourcePath = currentSourcePath()
-    let output = buildDir / "D20190111T024543".addFileExt(ExeExt)
-    let cmd = "$# c -o:$# -d:release -d:case_testfile $#" % [nim, output,
-        sourcePath]
-    # we're testing `execShellCmd` so don't rely on it to compile test file
-    # note: this should be exported in posix.nim
-    proc c_system(cmd: cstring): cint {.importc: "system",
-      header: "<stdlib.h>".}
-    assertEquals c_system(cmd), 0
+    let output = compileNimProg("-d:release -d:case_testfile", "D20190111T024543")
 
     ## use it
     template runTest(arg: string, expected: int) =
@@ -70,11 +119,23 @@ else:
     runTest("exit_0", 0)
     runTest("exitnow_139", 139)
     runTest("c_exit2_139", 139)
-    runTest("quit_139", 139)
+    when defined(posix):
+      runTest("quit_139", 127) # The quit value gets saturated to 127
+    else:
+      runTest("quit_139", 139)
+
+  block execCmdTest:
+    let output = compileNimProg("-d:release -d:case_testfile", "D20220705T221100")
+    doAssert execCmd(output & " exit_0") == 0
+    doAssert execCmd(output & " exit_1") == 1
+    doAssert execCmd(output & " exit_2") == 2
+    doAssert execCmd(output & " exit_42") == 42
+
+  import std/streams
 
   block execProcessTest:
-    let dir = parentDir(currentSourcePath())
-    let (outp, err) = execCmdEx(nim & " c " & quoteShell(dir / "osproctest.nim"))
+    let dir = sourcePath.parentDir
+    let (_, err) = execCmdEx(nim & " c " & quoteShell(dir / "osproctest.nim"))
     doAssert err == 0
     let exePath = dir / addFileExt("osproctest", ExeExt)
     let outStr1 = execProcess(exePath, workingDir = dir, args = ["foo",
@@ -89,7 +150,167 @@ else:
     doAssert outStr2 == absolutePath(testDir) & "\nx yz\n"
 
     removeDir(testDir)
+
+    # test for PipeOutStream
+    var
+      p = startProcess(exePath, args = ["abcdefghi", "foo", "bar", "0123456"])
+      outStrm = p.peekableOutputStream
+
+    var tmp: string
+    doAssert outStrm.readLine(tmp)
+    doAssert outStrm.readChar == 'a'
+    doAssert outStrm.peekChar == 'b'
+    doAssert outStrm.readChar == 'b'
+    doAssert outStrm.readChar == 'c'
+    doAssert outStrm.peekChar == 'd'
+    doAssert outStrm.peekChar == 'd'
+    doAssert outStrm.readChar == 'd'
+    doAssert outStrm.readStr(2) == "ef"
+    doAssert outStrm.peekStr(2) == "gh"
+    doAssert outStrm.peekStr(2) == "gh"
+    doAssert outStrm.readStr(1) == "g"
+    doAssert outStrm.readStr(3) == "hi\n"
+
+    doAssert outStrm.readLine == "foo"
+    doAssert outStrm.readChar == 'b'
+    doAssert outStrm.peekChar == 'a'
+    doAssert outStrm.readLine == "ar"
+
+    tmp.setLen(4)
+    tmp[0] = 'n'
+    doAssert outStrm.readDataStr(tmp, 1..3) == 3
+    doAssert tmp == "n012"
+    doAssert outStrm.peekStr(3) == "345"
+    doAssert outStrm.readDataStr(tmp, 1..2) == 2
+    doAssert tmp == "n342"
+    doAssert outStrm.peekStr(2) == "56"
+    doAssert outStrm.readDataStr(tmp, 0..3) == 3
+    doAssert tmp == "56\n2"
+    p.close
+
+    p = startProcess(exePath, args = ["123"])
+    outStrm = p.peekableOutputStream
+    let c = outStrm.peekChar
+    doAssert outStrm.readLine(tmp)
+    doAssert tmp[0] == c
+    tmp.setLen(7)
+    doAssert outStrm.peekData(addr tmp[0], 7) == 4
+    doAssert tmp[0..3] == "123\n"
+    doAssert outStrm.peekData(addr tmp[0], 7) == 4
+    doAssert tmp[0..3] == "123\n"
+    doAssert outStrm.readData(addr tmp[0], 7) == 4
+    doAssert tmp[0..3] == "123\n"
+    p.close
+
     try:
       removeFile(exePath)
     except OSError:
       discard
+
+  block: # test for startProcess (more tests needed)
+    # bugfix: windows stdin.close was a noop and led to blocking reads
+    proc startProcessTest(command: string, options: set[ProcessOption] = {
+                    poStdErrToStdOut, poUsePath}, input = ""): tuple[
+                    output: string,
+                    exitCode: int] {.tags:
+                    [ExecIOEffect, ReadIOEffect, RootEffect], gcsafe.} =
+      var p = startProcess(command, options = options + {poEvalCommand})
+      var outp = outputStream(p)
+      if input.len > 0: inputStream(p).write(input)
+      close inputStream(p)
+      result = ("", -1)
+      var line = newStringOfCap(120)
+      while true:
+        if outp.readLine(line):
+          result[0].add(line)
+          result[0].add("\n")
+        else:
+          result[1] = peekExitCode(p)
+          if result[1] != -1: break
+      close(p)
+
+    var result = startProcessTest("nim r --hints:off -", options = {}, input = "echo 3*4")
+    doAssert result == ("12\n", 0)
+
+  block: # startProcess stdin (replaces old test `tstdin` + `ta_in`)
+    let output = compileNimProg("-d:case_testfile2", "D20200626T215919")
+    var p = startProcess(output, dir) # dir not needed though
+    p.inputStream.write("5\n")
+    p.inputStream.flush()
+    var line = ""
+    var s: seq[string]
+    while p.outputStream.readLine(line):
+      s.add line
+    doAssert s == @["10"]
+
+  block:
+    let output = compileNimProg("-d:case_testfile3", "D20200626T221233")
+    var x = newStringOfCap(120)
+    block: # startProcess stdout poStdErrToStdOut (replaces old test `tstdout` + `ta_out`)
+      var p = startProcess(output, dir, options={poStdErrToStdOut})
+      deferring: p.close()
+      do:
+        var sout: seq[string]
+        while p.outputStream.readLine(x): sout.add x
+        doAssert sout == @["start ta_out", "to stdout", "to stdout", "to stderr", "to stderr", "to stdout", "to stdout", "end ta_out"]
+    block: # startProcess stderr (replaces old test `tstderr` + `ta_out`)
+      var p = startProcess(output, dir, options={})
+      deferring: p.close()
+      do:
+        var serr, sout: seq[string]
+        while p.errorStream.readLine(x): serr.add x
+        while p.outputStream.readLine(x): sout.add x
+        doAssert serr == @["to stderr", "to stderr"]
+        doAssert sout == @["start ta_out", "to stdout", "to stdout", "to stdout", "to stdout", "end ta_out"]
+
+  block: # startProcess exit code (replaces old test `texitcode` + `tafalse`)
+    let output = compileNimProg("-d:case_testfile4", "D20200626T224758")
+    var p = startProcess(output, dir)
+    doAssert waitForExit(p) == QuitFailure
+    p = startProcess(output, dir)
+    var running = true
+    while running:
+      # xxx: avoid busyloop?
+      running = running(p)
+    doAssert waitForExit(p) == QuitFailure
+
+    # make sure that first call to running() after process exit returns false
+    p = startProcess(output, dir)
+    for j in 0..<30: # refs #13449
+      os.sleep(50)
+      if not running(p): break
+    doAssert not running(p)
+    doAssert waitForExit(p) == QuitFailure # avoid zombies
+
+  import std/strtabs
+  block execProcessTest:
+    var result = execCmdEx("nim r --hints:off -", options = {}, input = "echo 3*4")
+    stripLineEnd(result[0])
+    doAssert result == ("12", 0)
+    when not defined(windows):
+      doAssert execCmdEx("ls --nonexistent").exitCode != 0
+    when false:
+      # bug: on windows, this raises; on posix, passes
+      doAssert execCmdEx("nonexistent").exitCode != 0
+    when defined(posix):
+      doAssert execCmdEx("echo $FO", env = newStringTable({"FO": "B"})) == ("B\n", 0)
+      doAssert execCmdEx("echo $PWD", workingDir = "/") == ("/\n", 0)
+
+  block: # bug #17749
+    let output = compileNimProg("-d:case_testfile4", "D20210417T011153")
+    var p = startProcess(output, dir)
+    let inp = p.inputStream
+    var count = 0
+    when defined(windows):
+      # xxx we should make osproc.hsWriteData raise IOError on windows, consistent
+      # with posix; we could also (in addition) make IOError a subclass of OSError.
+      type SIGPIPEError = OSError
+    else:
+      type SIGPIPEError = IOError
+    doAssertRaises(SIGPIPEError):
+      for i in 0..<100000:
+        count.inc
+        inp.writeLine "ok" # was giving SIGPIPE and crashing
+    doAssert count >= 100
+    doAssert waitForExit(p) == QuitFailure
+    close(p) # xxx isn't that missing in other places?
diff --git a/tests/stdlib/tosprocterminate.nim b/tests/stdlib/tosprocterminate.nim
index a46d91d68..93b0317f7 100644
--- a/tests/stdlib/tosprocterminate.nim
+++ b/tests/stdlib/tosprocterminate.nim
@@ -1,11 +1,16 @@
 discard """
-outputsub: "SUCCESS"
+  cmd: "nim $target $options -r $file"
+  targets: "c cpp"
+  matrix: "--mm:refc; --mm:orc"
 """
 
-import os, osproc
+import os, osproc, times, std / monotimes
+import std/assertions
 
-when defined(Windows):
+when defined(windows):
   const ProgramWhichDoesNotEnd = "notepad"
+elif defined(openbsd):
+  const ProgramWhichDoesNotEnd = "/bin/cat"
 else:
   const ProgramWhichDoesNotEnd = "/bin/sh"
 
@@ -19,7 +24,21 @@ while process.running() and TimeToWait > 0:
   sleep(100)
   TimeToWait = TimeToWait - 100
 
-if process.running():
-  echo("FAILED")
-else:
-  echo("SUCCESS")
+doAssert not process.running()
+echo("stopped process")
+
+process.close()
+
+echo("starting " & ProgramWhichDoesNotEnd)
+process = startProcess(ProgramWhichDoesNotEnd)
+echo("process should be stopped after 2s")
+
+let start = getMonoTime()
+discard process.waitForExit(2000)
+let took = getMonoTime() - start
+
+doAssert not process.running()
+# some additional time to account for overhead
+doAssert took < initDuration(seconds = 3)
+
+echo("stopped process after ", took)
diff --git a/tests/stdlib/tpackedsets.nim b/tests/stdlib/tpackedsets.nim
new file mode 100644
index 000000000..f519c08a7
--- /dev/null
+++ b/tests/stdlib/tpackedsets.nim
@@ -0,0 +1,265 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/packedsets
+import std/sets
+
+import sequtils
+import algorithm
+
+import std/assertions
+
+block basicIntSetTests:
+  var y = initPackedSet[int]()
+  y.incl(1)
+  y.incl(2)
+  y.incl(7)
+  y.incl(1056)
+
+  y.incl(1044)
+  y.excl(1044)
+
+  doAssert y == [1, 2, 7, 1056].toPackedSet
+  doAssert toSeq(y.items) == [1, 2, 7, 1056]
+
+  doAssert y.containsOrIncl(888) == false
+  doAssert 888 in y
+  doAssert y.containsOrIncl(888) == true
+
+  doAssert y.missingOrExcl(888) == false
+  doAssert 888 notin y
+  doAssert y.missingOrExcl(888) == true
+
+proc sortedPairs[T](t: T): auto = toSeq(t.pairs).sorted
+template sortedItems(t: untyped): untyped = sorted(toSeq(t))
+
+type Id = distinct int
+proc `$`(x: Id): string {.borrow.}
+proc cmp(a: Id, b: Id): int {.borrow.}
+proc `==`(a: Id, b: Id): bool {.borrow.}
+proc `<`(a: Id, b: Id): bool {.borrow.}
+
+block genericTests: 
+  # we use HashSet as groundtruth, it's well tested elsewhere
+  template testDel(A: typedesc, t: typed, t0: typed) =
+
+    block:
+      template checkEquals() =
+        doAssert t.len == t0.len
+        for k in t0:
+          doAssert k in t
+        for k in t:
+          doAssert k in t0
+
+        doAssert sortedItems(t) == sortedItems(t0)
+
+      template incl2(i) =
+        t.incl i
+        t0.incl i
+
+      template excl2(i) =
+        t.excl i
+        t0.excl i
+
+      var expected: seq[A]
+      let n = 100
+      let n2 = n*2
+      for i in 0..<n:
+        incl2(A(i))
+      checkEquals()
+      for i in 0..<n:
+        if i mod 3 == 0:
+          if i < n div 2:
+            excl2(A(i))
+          else:
+            t0.excl A(i)
+            doAssert A(i) in t
+            doAssert not t.missingOrExcl A(i)
+
+      checkEquals()
+      for i in n..<n2:
+        incl2(A(i))
+      checkEquals()
+      for i in 0..<n2:
+        if i mod 7 == 0:
+          excl2(A(i))
+      checkEquals()
+
+      # notin check
+      for i in 0..<t.len:
+        if i mod 7 == 0:
+          doAssert A(i) notin t0
+          doAssert A(i) notin t
+          # issue #13505
+          doAssert t.missingOrExcl(A(i))
+
+  var t: PackedSet[int]
+  var t0: HashSet[int]
+  testDel(int, t, t0)
+
+  var distT: PackedSet[Id]
+  var distT0: HashSet[Id]
+  testDel(Id, distT, distT0)
+
+  doAssert union(distT, initPackedSet[Id]()) == distT
+
+  var charT: PackedSet[char]
+  var charT0: HashSet[char]
+  testDel(char, charT, charT0)
+
+
+block typeSafetyTest:
+  # mixing sets of different types shouldn't compile
+  doAssert not compiles( union(initPackedSet[Id](), initPackedSet[int]()) )
+  doAssert     compiles( union(initPackedSet[Id](), initPackedSet[Id]()))
+
+  var ids: PackedSet[Id]
+  doAssert not compiles( ids.incl(3) )
+  doAssert     compiles( ids.incl(Id(3)) )
+
+  type NonOrdinal = string
+  doAssert not compiles( initPackedSet[NonOrdinal]() )
+
+type EnumABCD = enum A, B, C, D
+
+block enumTest:
+  var letterSet = initPackedSet[EnumABCD]()
+
+  for x in [A, C]:
+    letterSet.incl(x)
+
+  doAssert A in letterSet
+  doAssert B notin letterSet
+  doAssert C in letterSet
+  doAssert D notin letterSet
+
+type Foo = distinct int16
+proc `$`(a: Foo): string {.borrow.} # `echo a` below won't work without `$` defined, as expected
+
+block printTest:
+  var a = initPackedSet[EnumABCD]()
+  a.incl A
+  a.incl C 
+  doAssert $a == "{A, C}"
+
+import intsets
+
+block legacyMainModuleTests:
+  template genericTests(A: typedesc[Ordinal], x: typed) =
+    block:
+      proc typSeq(s: seq[int]): seq[A] = s.map(proc (i: int): A = A(i))
+      x.incl(A(1))
+      x.incl(A(2))
+      x.incl(A(7))
+      x.incl(A(1056))
+
+      x.incl(A(1044))
+      x.excl(A(1044))
+
+      doAssert x == typSeq(@[1, 2, 7, 1056]).toPackedSet
+
+      doAssert x.containsOrIncl(A(888)) == false
+      doAssert A(888) in x
+      doAssert x.containsOrIncl(A(888)) == true
+
+      doAssert x.missingOrExcl(A(888)) == false
+      doAssert A(888) notin x
+      doAssert x.missingOrExcl(A(888)) == true
+
+      var xs = toSeq(items(x))
+      xs.sort(cmp[A])
+      doAssert xs == typSeq(@[1, 2, 7, 1056])
+
+      var y: PackedSet[A]
+      assign(y, x)
+      var ys = toSeq(items(y))
+      ys.sort(cmp[A])
+      doAssert ys == typSeq(@[1, 2, 7, 1056])
+
+      doAssert x == y
+
+      var z: PackedSet[A]
+      for i in 0..1000:
+        incl z, A(i)
+        doAssert z.len() == i+1
+      for i in 0..1000:
+        doAssert z.contains(A(i))
+
+      var w = initPackedSet[A]()
+      w.incl(A(1))
+      w.incl(A(4))
+      w.incl(A(50))
+      w.incl(A(1001))
+      w.incl(A(1056))
+
+      var xuw = x.union(w)
+      var xuws = toSeq(items(xuw))
+      xuws.sort(cmp)
+      doAssert xuws == typSeq(@[1, 2, 4, 7, 50, 1001, 1056])
+
+      var xiw = x.intersection(w)
+      var xiws = toSeq(items(xiw))
+      xiws.sort(cmp)
+      doAssert xiws == @[A(1), A(1056)]
+
+      var xdw = x.difference(w)
+      var xdws = toSeq(items(xdw))
+      xdws.sort(cmp[A])
+      doAssert xdws == @[A(2), A(7)]
+
+      var xsw = x.symmetricDifference(w)
+      var xsws = toSeq(items(xsw))
+      xsws.sort(cmp[A])
+      doAssert xsws == typSeq(@[2, 4, 7, 50, 1001])
+
+      x.incl(w)
+      xs = toSeq(items(x))
+      xs.sort(cmp[A])
+      doAssert xs == typSeq(@[1, 2, 4, 7, 50, 1001, 1056])
+
+      doAssert w <= x
+
+      doAssert w < x
+
+      doAssert(not disjoint(w, x))
+
+      var u = initPackedSet[A]()
+      u.incl(A(3))
+      u.incl(A(5))
+      u.incl(A(500))
+      doAssert disjoint(u, x)
+
+      var v = initPackedSet[A]()
+      v.incl(A(2))
+      v.incl(A(50))
+
+      x.excl(v)
+      xs = toSeq(items(x))
+      xs.sort(cmp[A])
+      doAssert xs == typSeq(@[1, 4, 7, 1001, 1056])
+
+      proc bug12366 =
+        var
+          x = initPackedSet[A]()
+          y = initPackedSet[A]()
+          n = 3584
+
+        for i in 0..n:
+          x.incl(A(i))
+          y.incl(A(i))
+
+        let z = symmetricDifference(x, y)
+        doAssert z.len == 0
+        doAssert $z == "{}"
+
+      bug12366()
+
+  var legacyInit = initIntSet()
+  genericTests(int, legacyInit)
+
+  var intGenericInit = initPackedSet[int]()
+  genericTests(int, intGenericInit)
+
+  var intDistinct = initPackedSet[Id]()
+  genericTests(Id, intDistinct)
diff --git a/tests/stdlib/tparscfg.nim b/tests/stdlib/tparscfg.nim
deleted file mode 100644
index fc735f3eb..000000000
--- a/tests/stdlib/tparscfg.nim
+++ /dev/null
@@ -1,69 +0,0 @@
-discard """
-output: '''
-utf-8
-on
-hello
-lihf8515
-10214028
-lihaifeng@wxm.com
-===
-charset=utf-8
-[Package]
-name=hello
---threads:on
-[Author]
-name=lhf
-qq=10214028
-email="lihaifeng@wxm.com"
-===
-charset=utf-8
-[Package]
-name=hello
---threads:on
-[Author]
-name=lihf8515
-qq=10214028
-'''
-"""
-import parsecfg, streams
-
-## Creating a configuration file.
-var dict1=newConfig()
-dict1.setSectionKey("","charset","utf-8")
-dict1.setSectionKey("Package","name","hello")
-dict1.setSectionKey("Package","--threads","on")
-dict1.setSectionKey("Author","name","lihf8515")
-dict1.setSectionKey("Author","qq","10214028")
-dict1.setSectionKey("Author","email","lihaifeng@wxm.com")
-var ss = newStringStream()
-dict1.writeConfig(ss)
-
-## Reading a configuration file.
-var dict2 = loadConfig(newStringStream(ss.data))
-var charset = dict2.getSectionValue("","charset")
-var threads = dict2.getSectionValue("Package","--threads")
-var pname = dict2.getSectionValue("Package","name")
-var name = dict2.getSectionValue("Author","name")
-var qq = dict2.getSectionValue("Author","qq")
-var email = dict2.getSectionValue("Author","email")
-echo charset
-echo threads
-echo pname
-echo name
-echo qq
-echo email
-
-echo "==="
-
-## Modifying a configuration file.
-var dict3 = loadConfig(newStringStream(ss.data))
-dict3.setSectionKey("Author","name","lhf")
-write(stdout, $dict3)
-
-echo "==="
-
-## Deleting a section key in a configuration file.
-var dict4 = loadConfig(newStringStream(ss.data))
-dict4.delSectionKey("Author","email")
-write(stdout, $dict4)
-
diff --git a/tests/stdlib/tparsecfg.nim b/tests/stdlib/tparsecfg.nim
index 1c214e5d2..2600d6f66 100644
--- a/tests/stdlib/tparsecfg.nim
+++ b/tests/stdlib/tparsecfg.nim
@@ -1,23 +1,132 @@
 discard """
-  output: '''OK'''
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
 """
 
-#bug #6046
-import parsecfg
-
-var config = newConfig()
-config.setSectionKey("foo","bar","-1")
-config.setSectionKey("foo","foo","abc")
-config.writeConfig("test.ini")
-
-# test.ini now contains
-# [foo]
-# bar=-1
-# foo=abc
-
-var config2 = loadConfig("test.ini")
-let bar = config2.getSectionValue("foo","bar")
-let foo = config2.getSectionValue("foo","foo")
-assert(bar == "-1")
-assert(foo == "abc")
-echo "OK"
+import parsecfg, streams, sequtils
+import std/assertions
+
+when not defined(js):
+  from stdtest/specialpaths import buildDir
+  import os
+  # bug #6046
+  block:
+    var config = newConfig()
+    config.setSectionKey("foo", "bar", "-1")
+    config.setSectionKey("foo", "foo", "abc")
+
+    const file = buildDir / "tparsecfg.ini"
+    config.writeConfig(file)
+
+    # file now contains
+    # [foo]
+    # bar=-1
+    # foo=abc
+
+    var config2 = loadConfig(file)
+    let bar = config2.getSectionValue("foo", "bar")
+    let foo = config2.getSectionValue("foo", "foo")
+    doAssert(bar == "-1")
+    doAssert(foo == "abc")
+
+## Creating a configuration file.
+var dict1 = newConfig()
+dict1.setSectionKey("", "charset", "utf-8")
+dict1.setSectionKey("Package", "name", "hello")
+dict1.setSectionKey("Package", "--threads", "on")
+dict1.setSectionKey("Author", "name", "lihf8515")
+dict1.setSectionKey("Author", "qq", "10214028")
+dict1.setSectionKey("Author", "email", "lihaifeng@wxm.com")
+var ss = newStringStream()
+dict1.writeConfig(ss)
+
+## Reading a configuration file.
+let dict2 = loadConfig(newStringStream(ss.data))
+doAssert dict2.getSectionValue("", "charset") == "utf-8"
+doAssert dict2.getSectionValue("Package", "--threads") == "on"
+doAssert dict2.getSectionValue("Package", "name") == "hello"
+doAssert dict2.getSectionValue("Author", "name") == "lihf8515"
+doAssert dict2.getSectionValue("Author", "qq") == "10214028"
+doAssert dict2.getSectionValue("Author", "email") == "lihaifeng@wxm.com"
+doAssert toSeq(dict2.sections) == @["", "Package", "Author"]
+
+## Modifying a configuration file.
+var dict3 = loadConfig(newStringStream(ss.data))
+dict3.setSectionKey("Author", "name", "lhf")
+doAssert $dict3 == """charset=utf-8
+[Package]
+name=hello
+--threads:on
+[Author]
+name=lhf
+qq=10214028
+email="lihaifeng@wxm.com"
+"""
+
+## Deleting a section key in a configuration file.
+var dict4 = loadConfig(newStringStream(ss.data))
+dict4.delSectionKey("Author", "email")
+doAssert $dict4 == """charset=utf-8
+[Package]
+name=hello
+--threads:on
+[Author]
+name=lihf8515
+qq=10214028
+"""
+
+block:
+  var dict = loadConfig(newStringStream("""[Simple Values]
+  key=value
+  spaces in keys=allowed
+  spaces in values=allowed as well
+  spaces around the delimiter = obviously
+  you can also use : to delimit keys from values
+  [All Values Are Strings]
+  values like this: 19990429
+  or this: 3.14159265359
+  are they treated as numbers : no
+  integers floats and booleans are held as: strings
+  can use the API to get converted values directly: true
+  [No Values]
+  key_without_value
+  # empty string value is not allowed =
+  [ Seletion A   ]
+  space around section name will be ignored
+  [You can use comments]
+  # like this
+  ; or this
+  # By default only in an empty line.
+  # Inline comments can be harmful because they prevent users
+  # from using the delimiting characters as parts of values.
+  # That being said, this can be customized.
+      [Sections Can Be Indented]
+          can_values_be_as_well = True
+          does_that_mean_anything_special = False
+          purpose = formatting for readability
+          # Did I mention we can indent comments, too?
+  """)
+  )
+
+  let section1 = "Simple Values"
+  doAssert dict.getSectionValue(section1, "key") == "value"
+  doAssert dict.getSectionValue(section1, "spaces in keys") == "allowed"
+  doAssert dict.getSectionValue(section1, "spaces in values") == "allowed as well"
+  doAssert dict.getSectionValue(section1, "spaces around the delimiter") == "obviously"
+  doAssert dict.getSectionValue(section1, "you can also use") == "to delimit keys from values"
+
+  let section2 = "All Values Are Strings"
+  doAssert dict.getSectionValue(section2, "values like this") == "19990429"
+  doAssert dict.getSectionValue(section2, "or this") == "3.14159265359"
+  doAssert dict.getSectionValue(section2, "are they treated as numbers") == "no"
+  doAssert dict.getSectionValue(section2, "integers floats and booleans are held as") == "strings"
+  doAssert dict.getSectionValue(section2, "can use the API to get converted values directly") == "true"
+
+  let section3 = "Seletion A"
+  doAssert dict.getSectionValue(section3, 
+    "space around section name will be ignored", "not an empty value") == ""
+
+  let section4 = "Sections Can Be Indented"
+  doAssert dict.getSectionValue(section4, "can_values_be_as_well") == "True"
+  doAssert dict.getSectionValue(section4, "does_that_mean_anything_special") == "False"
+  doAssert dict.getSectionValue(section4, "purpose") == "formatting for readability"
diff --git a/tests/stdlib/tparsecsv.nim b/tests/stdlib/tparsecsv.nim
new file mode 100644
index 000000000..5a1e41bce
--- /dev/null
+++ b/tests/stdlib/tparsecsv.nim
@@ -0,0 +1,36 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+include parsecsv
+import strutils, os
+import std/assertions
+
+block: # Tests for reading the header row
+  let content = "\nOne,Two,Three,Four\n1,2,3,4\n10,20,30,40,\n100,200,300,400\n"
+  writeFile("temp.csv", content)
+
+  var p: CsvParser
+  p.open("temp.csv")
+  p.readHeaderRow()
+  while p.readRow():
+    let zeros = repeat('0', p.currRow-2)
+    doAssert p.rowEntry("One") == "1" & zeros
+    doAssert p.rowEntry("Two") == "2" & zeros
+    doAssert p.rowEntry("Three") == "3" & zeros
+    doAssert p.rowEntry("Four") == "4" & zeros
+  p.close()
+
+  when not defined(testing):
+    var parser: CsvParser
+    parser.open("temp.csv")
+    parser.readHeaderRow()
+    while parser.readRow():
+      echo "new row: "
+      for col in items(parser.headers):
+        echo "##", col, ":", parser.rowEntry(col), "##"
+    parser.close()
+    removeFile("temp.csv")
+
+  # Tidy up
+  removeFile("temp.csv")
diff --git a/tests/stdlib/tparseipv6.nim b/tests/stdlib/tparseipv6.nim
index 3e1c23e58..31ec4ecfb 100644
--- a/tests/stdlib/tparseipv6.nim
+++ b/tests/stdlib/tparseipv6.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: "all ok"
 """
 
@@ -8,23 +9,23 @@ const
   positives = [
     "::f:8:a8f:218.17.235.229",
     "::b:228.19.241.2",
-    "::8:c:a:f:8.35.8.096",
-    "::3:e:a:bc:04.19.2.9",
+    "::8:c:a:f:8.35.8.96",
+    "::3:e:a:bc:4.19.2.9",
     "::2:212.242.248.19",
     "::df:a5f:3.250.208.9",
     "::8:c:5:e63:250.208.249.0",
     "::b:f:181.12.9.98",
-    "::a:f8:77.08.243.232",
-    "::a:b:85:e4d9:252.9.229.056",
+    "::a:f8:77.8.243.232",
+    "::a:b:85:e4d9:252.9.229.56",
     "941:c:8a:c:e::917",
     "e8:7a:e:ad:88a:8:203.235.225.46",
-    "139c:9e::f8:254.08.21.249",
+    "139c:9e::f8:254.8.21.249",
     "b38:f0:e::f9:89.6.12.18",
     "ef::8",
     "5::ab",
     "a::8:255.247.96.253",
     "b:c0::c:254.248.95.254",
-    "::8c:2:99.251.024.3",
+    "::8c:2:99.251.24.3",
     "98::c:247.240.249.57",
     "9::9",
     "628::f1ed:f",
@@ -106,68 +107,68 @@ const
     "::315",
     "::a:a",
     "::aed3:a",
-    "f0eb:0:e8:b:c:a:254.098.233.17",
+    "f0eb:0:e8:b:c:a:254.98.233.17",
     "bfa:7fc:c66d:15:e9a:ded:254.119.9.9",
-    "d:ffa8:9:a:879:3:202.39.08.245",
+    "d:ffa8:9:a:879:3:202.39.8.245",
     "8e:2:8:fa8a:f1d1:1aa8:252.254.245.81",
-    "5:d4:a:e9:8:8:06.38.98.253",
-    "9c5:4:a5c:f:a6:8c9d:05.250.8.2",
+    "5:d4:a:e9:8:8:6.38.98.253",
+    "9c5:4:a5c:f:a6:8c9d:5.250.8.2",
     "d19a:2:f808:be:f:c:98.86.197.249",
-    "8:26ac:8:8:cb:f:242.00.254.85",
+    "8:26ac:8:8:cb:f:242.0.254.85",
     "38:e:1:0b88:f:0:8.89.248.92",
-    "e7:ff96:a:f:f:b:253.91.052.195",
+    "e7:ff96:a:f:f:b:253.91.52.195",
     "d:8:2:5:894:5:254.0.240.199",
     "2:98:9:8aa:9c8f:fa:252.98.248.17",
-    "e9:d4f:890:ccbe:5:8:088.200.228.216",
+    "e9:d4f:890:ccbe:5:8:88.200.228.216",
     "3:3:9:5:6a:df5:255.251.8.12",
-    "0280:3:8:8:4:9:255.000.251.249",
+    "0280:3:8:8:4:9:255.0.251.249",
     "8:af7:db:aa:0:9:238.248.250.255",
-    "ff:ee:9a:9252:a:289:059.083.18.255",
+    "ff:ee:9a:9252:a:289:59.83.18.255",
     "9f6:5:fc9:b:a89:a:142.1.250.254",
     "e:981a:da:bf94:9:f8:254.242.18.95",
     "3c:1:4:f2:89:f:8.91.255.14",
-    "e::9a2:c:9.050.80.8",
+    "e::9a2:c:9.50.80.8",
     "9::4a:07:fb:211.241.254.228",
     "9be::2:e:215.189.48.188",
-    "f::f:d:069.148.99.168",
+    "f::f:d:69.148.99.168",
     "f::a:97.18.240.47",
     "c::a98e:1:251.253.252.254",
     "668::82:214.87.208.9",
     "9c0::cf0:ecb:253.208.238.255",
-    "a::0:f1:210.240.238.049",
-    "8::a:1:251.238.34.09",
+    "a::0:f1:210.240.238.49",
+    "8::a:1:251.238.34.9",
     "81:dfe::b8:8.255.249.248",
-    "d3::7:b:9:83.189.08.244",
-    "8::9:8:8:00.7.11.252",
+    "d3::7:b:9:83.189.8.244",
+    "8::9:8:8:0.7.11.252",
     "2:8::c:a8:250.221.9.249",
     "2::f:99.8.249.247",
     "c:22f5::5:2c:243.15.79.89",
     "e:8e::da:251.243.255.2",
     "f15f:9::a:255.70.247.218",
-    "f:b::9f38:31.220.94.022",
-    "9::9a48:03.98.249.119",
+    "f:b::9f38:31.220.94.22",
+    "9::9a48:3.98.249.119",
     "d:d:9b87::2d:a:249.253.38.8",
     "d86d:99b::a9b:5:242.236.8.244",
     "eb:3::f:9cf:1.253.1.228",
     "b::ba2:255.247.114.64",
-    "2f:ec:bcb::9:219.254.250.094",
+    "2f:ec:bcb::9:219.254.250.94",
     "da8a:f6::a:e0:19.251.241.251",
-    "5e:c1::a:021.250.8.254",
+    "5e:c1::a:21.250.8.254",
     "c:9::8c9b:248.219.212.252",
     "2:a::8d4a:216.255.198.223",
-    "1f::66:255.30.08.150",
+    "1f::66:255.30.8.150",
     "bc2b:8f::2ff9:6.245.99.230",
     "a:8::a8:9.251.246.255",
-    "f:7:7::98:06.14.1.208",
+    "f:7:7::98:6.14.1.208",
     "e:2::9:218.249.255.254",
     "79:f::6:250.255.98.246",
-    "47:9:fb9f::9:038.136.17.251",
+    "47:9:fb9f::9:38.136.17.251",
     "ed::a:247.9.23.239",
     "6f::f1:88.254.119.9",
     "a::d:218.199.236.0",
-    "fc88::9:203.196.04.95",
-    "::8.048.255.85",
-    "::253.07.255.36",
+    "fc88::9:203.196.4.95",
+    "::8.48.255.85",
+    "::253.7.255.36",
     "9:d::253.7.178.229",
     "::250.84.158.253",
     "::8.55.204.248",
@@ -175,39 +176,47 @@ const
     "df9:88ca::248.255.108.17",
     "8e9b::250.206.0.82",
     "::209.8.254.209",
-    "::247.088.8.8",
+    "::247.88.8.8",
     "::cb:f:ba41:250.208.19.249",
     "::fe:0e8:243.240.229.5",
     "::c:223.251.5.226",
-    "::8:08.03.8.250",
+    "::8:8.3.8.250",
     "::f:8.88.11.255",
-    "::fda:48:aa:05.189.07.2",
-    "::8:c3f:f:240.06.212.255",
+    "::fda:48:aa:5.189.7.2",
+    "::8:c3f:f:240.6.212.255",
     "::f:0aa:244.123.99.16",
-    "::c9b5:c:034.8.090.196",
+    "::c9b5:c:34.8.90.196",
     "::98:c9:254.14.241.81"
   ]
   negatives = ["foo.bar",
     "::::::::::::",
     "yet another failure",
-    "de:6:c:ab5:6a::9:252.06.06.249",
-    "f9:5f7:fa38:9:b::b6:09.255.248.252",
+    "de:6:c:ab5:6a::9:252.6.6.249",
+    "f9:5f7:fa38:9:b::b6:9.255.248.252",
     "97:c:5b:81:8a::f5dd:144.252.250.9",
-    "9:8:cd:8:a9::f:247.255.09.255",
+    "9:8:cd:8:a9::f:247.255.9.255",
     "18:1:8c:2:3::9:8.254.252.139",
-    "e:c298:3:e:a::bb12:254.246.05.250",
+    "e:c298:3:e:a::bb12:254.246.5.250",
     "e:e:c:8e:fd::8:253.8.49.231",
     "9:97f:f:e929:8a::c9:0.8.252.10",
-    "0df:b24:7:89:c::2b:16.249.240.092",
+    "0df:b24:7:89:c::2b:16.249.240.92",
     "b:8f5f:485:c:9a::84c:178.7.249.34",
+    "::3:e:a:bc:091.19.2.9",
+    "::a:f8:77.08.243.232",
+    "::8c:2:99.251.029.3",
+    "::8:c:a:f:8.35.8.096",
+    "d:ffa8:9:a:879:3:0202.39.8.245",
+    "139c:9e::f8:254.07.21.249",
+    "f0eb:0:e8:b:c:a:254.233.043.17",
+    "::a:b:85:e4d9:252.9.229.056",
   ]
 
-proc ok(pos: openarray[string]) =
+proc ok(pos: openArray[string]) =
   for p in pos:
     if not isIpAddress(p):
       echo "failure ", p
 
-proc notok(neg: openarray[string]) =
+proc notok(neg: openArray[string]) =
   for n in neg:
     if isIpAddress(n):
       echo "failure ", n
diff --git a/tests/stdlib/tparsesql.nim b/tests/stdlib/tparsesql.nim
index 8cf8fa848..cd582551d 100644
--- a/tests/stdlib/tparsesql.nim
+++ b/tests/stdlib/tparsesql.nim
@@ -1,7 +1,23 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
 import parsesql
+import std/assertions
 
-doAssert $parseSQL("SELECT foo FROM table;") == "select foo from table;"
-doAssert $parseSQL("""
+doAssert treeRepr(parseSql("INSERT INTO STATS VALUES (10, 5.5); ")
+) == """
+
+nkStmtList
+  nkInsert
+    nkIdent STATS
+    nkNone
+    nkValueList
+      nkIntegerLit 10
+      nkNumericLit 5.5"""
+
+doAssert $parseSql("SELECT foo FROM table;") == "select foo from table;"
+doAssert $parseSql("""
 SELECT
   CustomerName,
   ContactName,
@@ -17,26 +33,26 @@ SELECT
   Country
 FROM table;""") == "select CustomerName, ContactName, Address, City, PostalCode, Country, CustomerName, ContactName, Address, City, PostalCode, Country from table;"
 
-doAssert $parseSQL("SELECT foo FROM table limit 10") == "select foo from table limit 10;"
-doAssert $parseSQL("SELECT foo, bar, baz FROM table limit 10") == "select foo, bar, baz from table limit 10;"
-doAssert $parseSQL("SELECT foo AS bar FROM table") == "select foo as bar from table;"
-doAssert $parseSQL("SELECT foo AS foo_prime, bar AS bar_prime, baz AS baz_prime FROM table") == "select foo as foo_prime, bar as bar_prime, baz as baz_prime from table;"
-doAssert $parseSQL("SELECT * FROM table") == "select * from table;"
-doAssert $parseSQL("SELECT count(*) FROM table") == "select count(*) from table;"
-doAssert $parseSQL("SELECT count(*) as 'Total' FROM table") == "select count(*) as 'Total' from table;"
-doAssert $parseSQL("SELECT count(*) as 'Total', sum(a) as 'Aggr' FROM table") == "select count(*) as 'Total', sum(a) as 'Aggr' from table;"
+doAssert $parseSql("SELECT foo FROM table limit 10") == "select foo from table limit 10;"
+doAssert $parseSql("SELECT foo, bar, baz FROM table limit 10") == "select foo, bar, baz from table limit 10;"
+doAssert $parseSql("SELECT foo AS bar FROM table") == "select foo as bar from table;"
+doAssert $parseSql("SELECT foo AS foo_prime, bar AS bar_prime, baz AS baz_prime FROM table") == "select foo as foo_prime, bar as bar_prime, baz as baz_prime from table;"
+doAssert $parseSql("SELECT * FROM table") == "select * from table;"
+doAssert $parseSql("SELECT count(*) FROM table") == "select count(*) from table;"
+doAssert $parseSql("SELECT count(*) as 'Total' FROM table") == "select count(*) as 'Total' from table;"
+doAssert $parseSql("SELECT count(*) as 'Total', sum(a) as 'Aggr' FROM table") == "select count(*) as 'Total', sum(a) as 'Aggr' from table;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 WHERE a = b and c = d
 """) == "select * from table where a = b and c = d;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 WHERE not b
 """) == "select * from table where not b;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT
   *
 FROM
@@ -45,63 +61,63 @@ WHERE
   a and not b
 """) == "select * from table where a and not b;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 ORDER BY 1
 """) == "select * from table order by 1;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 GROUP BY 1
 ORDER BY 1
 """) == "select * from table group by 1 order by 1;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 ORDER BY 1
 LIMIT 100
 """) == "select * from table order by 1 limit 100;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 WHERE a = b and c = d or n is null and not b + 1 = 3
 """) == "select * from table where a = b and c = d or n is null and not b + 1 = 3;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 WHERE (a = b and c = d) or (n is null and not b + 1 = 3)
 """) == "select * from table where(a = b and c = d) or (n is null and not b + 1 = 3);"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM table
 HAVING a = b and c = d
 """) == "select * from table having a = b and c = d;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT a, b FROM table
 GROUP BY a
 """) == "select a, b from table group by a;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT a, b FROM table
 GROUP BY 1, 2
 """) == "select a, b from table group by 1, 2;"
 
-doAssert $parseSQL("SELECT t.a FROM t as t") == "select t.a from t as t;"
+doAssert $parseSql("SELECT t.a FROM t as t") == "select t.a from t as t;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT a, b FROM (
   SELECT * FROM t
 )
 """) == "select a, b from(select * from t);"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT a, b FROM (
   SELECT * FROM t
 ) as foo
 """) == "select a, b from(select * from t) as foo;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT a, b FROM (
   SELECT * FROM (
     SELECT * FROM (
@@ -113,49 +129,49 @@ SELECT a, b FROM (
 ) as inner5
 """) == "select a, b from(select * from(select * from(select * from(select * from innerTable as inner1) as inner2) as inner3) as inner4) as inner5;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT a, b FROM
   (SELECT * FROM a),
   (SELECT * FROM b),
   (SELECT * FROM c)
 """) == "select a, b from(select * from a),(select * from b),(select * from c);"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM Products
 WHERE Price BETWEEN 10 AND 20;
 """) == "select * from Products where Price between 10 and 20;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT id FROM a
 JOIN b
 ON a.id == b.id
 """) == "select id from a join b on a.id == b.id;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT id FROM a
 JOIN (SELECT id from c) as b
 ON a.id == b.id
 """) == "select id from a join(select id from c) as b on a.id == b.id;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT id FROM a
 INNER JOIN b
 ON a.id == b.id
 """) == "select id from a inner join b on a.id == b.id;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT id FROM a
 OUTER JOIN b
 ON a.id == b.id
 """) == "select id from a outer join b on a.id == b.id;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT id FROM a
 CROSS JOIN b
 ON a.id == b.id
 """) == "select id from a cross join b on a.id == b.id;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 CREATE TYPE happiness AS ENUM ('happy', 'very happy', 'ecstatic');
 CREATE TABLE holidays (
   num_weeks int,
@@ -165,31 +181,54 @@ CREATE INDEX table1_attr1 ON table1(attr1);
 SELECT * FROM myTab WHERE col1 = 'happy';
 """) == "create type happiness as enum ('happy' , 'very happy' , 'ecstatic' ); create table holidays(num_weeks  int , happiness  happiness );; create index table1_attr1 on table1(attr1 );; select * from myTab where col1 = 'happy';"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 INSERT INTO Customers (CustomerName, ContactName, Address, City, PostalCode, Country)
 VALUES ('Cardinal', 'Tom B. Erichsen', 'Skagen 21', 'Stavanger', '4006', 'Norway');
 """) == "insert into Customers (CustomerName , ContactName , Address , City , PostalCode , Country ) values ('Cardinal' , 'Tom B. Erichsen' , 'Skagen 21' , 'Stavanger' , '4006' , 'Norway' );"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 INSERT INTO TableName DEFAULT VALUES
 """) == "insert into TableName default values;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 UPDATE Customers
 SET ContactName = 'Alfred Schmidt', City= 'Frankfurt'
 WHERE CustomerID = 1;
 """) == "update Customers set ContactName  = 'Alfred Schmidt' , City  = 'Frankfurt' where CustomerID = 1;"
 
-doAssert $parseSQL("DELETE FROM table_name;") == "delete from table_name;"
+doAssert treeRepr(parseSql("""UPDATE Customers
+                              SET ContactName = 'Alice', City= 'Frankfurt';""")
+) == """
+
+nkStmtList
+  nkUpdate
+    nkIdent Customers
+    nkAsgn
+      nkIdent ContactName
+      nkStringLit Alice
+    nkAsgn
+      nkIdent City
+      nkStringLit Frankfurt
+    nkNone"""
+
+doAssert $parseSql("DELETE FROM table_name;") == "delete from table_name;"
+
+doAssert treeRepr(parseSql("DELETE FROM table_name;")
+) == """
+
+nkStmtList
+  nkDelete
+    nkIdent table_name
+    nkNone"""
 
-doAssert $parseSQL("DELETE * FROM table_name;") == "delete from table_name;"
+doAssert $parseSql("DELETE * FROM table_name;") == "delete from table_name;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 --Select all:
 SELECT * FROM Customers;
 """) == "select * from Customers;"
 
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT * FROM Customers WHERE (CustomerName LIKE 'L%'
 OR CustomerName LIKE 'R%' /*OR CustomerName LIKE 'S%'
 OR CustomerName LIKE 'T%'*/ OR CustomerName LIKE 'W%')
@@ -198,9 +237,9 @@ ORDER BY CustomerName;
 """) == "select * from Customers where(CustomerName like 'L%' or CustomerName like 'R%' or CustomerName like 'W%') and Country = 'USA' order by CustomerName;"
 
 # parse quoted keywords as identifires
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT `SELECT`, `FROM` as `GROUP` FROM `WHERE`;
 """) == """select "SELECT", "FROM" as "GROUP" from "WHERE";"""
-doAssert $parseSQL("""
+doAssert $parseSql("""
 SELECT "SELECT", "FROM" as "GROUP" FROM "WHERE";
 """) == """select "SELECT", "FROM" as "GROUP" from "WHERE";"""
diff --git a/tests/stdlib/tparseuints.nim b/tests/stdlib/tparseuints.nim
index 6b228d933..9c71a27d6 100644
--- a/tests/stdlib/tparseuints.nim
+++ b/tests/stdlib/tparseuints.nim
@@ -1,13 +1,11 @@
 discard """
-  action: run
-  output: '''
-[Suite] parseutils'''
+  matrix: "--mm:refc; --mm:orc"
 """
+
 import unittest, strutils
 
-suite "parseutils":
-  test "uint":
-    check: parseBiggestUInt("0") == 0'u64
-    check: parseBiggestUInt("18446744073709551615") == 0xFFFF_FFFF_FFFF_FFFF'u64
-    expect(ValueError):
-      discard parseBiggestUInt("18446744073709551616")
+block: # parseutils
+  check: parseBiggestUInt("0") == 0'u64
+  check: parseBiggestUInt("18446744073709551615") == 0xFFFF_FFFF_FFFF_FFFF'u64
+  expect(ValueError):
+    discard parseBiggestUInt("18446744073709551616")
diff --git a/tests/stdlib/tparseutils.nim b/tests/stdlib/tparseutils.nim
new file mode 100644
index 000000000..b69900864
--- /dev/null
+++ b/tests/stdlib/tparseutils.nim
@@ -0,0 +1,112 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp"
+"""
+
+import std/[parseutils, sequtils, sugar, formatfloat]
+import std/assertions
+
+proc test() =
+  let input = "$test{}  $this is ${an{  example}}  "
+  let expected = @[(ikVar, "test"), (ikStr, "{}  "), (ikVar, "this"),
+                    (ikStr, " is "), (ikExpr, "an{  example}"), (ikStr, "  ")]
+  doAssert toSeq(interpolatedFragments(input)) == expected
+
+  var value = 0
+  discard parseHex("0x38", value)
+  doAssert value == 56
+
+  value = -1
+  doAssert(parseSaturatedNatural("848", value) == 3)
+  doAssert value == 848
+
+  value = -1
+  discard parseSaturatedNatural("84899999999999999999324234243143142342135435342532453", value)
+  doAssert value == high(int)
+
+  value = -1
+  discard parseSaturatedNatural("9223372036854775808", value)
+  doAssert value == high(int)
+
+  value = -1
+  discard parseSaturatedNatural("9223372036854775807", value)
+  doAssert value == high(int)
+
+  value = -1
+  discard parseSaturatedNatural("18446744073709551616", value)
+  doAssert value == high(int)
+
+  value = -1
+  discard parseSaturatedNatural("18446744073709551615", value)
+  doAssert value == high(int)
+
+  value = -1
+  doAssert(parseSaturatedNatural("1_000_000", value) == 9)
+  doAssert value == 1_000_000
+
+  var i64Value: int64
+  discard parseBiggestInt("9223372036854775807", i64Value)
+  doAssert i64Value == 9223372036854775807
+
+  block:
+    var f: float
+    let res = collect:
+      for x in ["9.123456789012345+","11.123456789012345+","9.123456789012345-","8.123456789012345+","9.12345678901234-","9.123456789012345"]:
+        (parseFloat(x, f, 0), $f)
+    doAssert res == @[(17, "9.123456789012344"), (18, "11.123456789012344"),
+                      (17, "9.123456789012344"), (17, "8.123456789012344"),
+                      (16, "9.12345678901234"), (17, "9.123456789012344")]
+
+test()
+static: test()
+
+block:  # With this included, static: test() crashes the compiler (from a
+        # VM problem with parseSize calling parseFloat).
+  var sz: int64
+  template checkParseSize(s, expectLen, expectVal) =
+    if (let got = parseSize(s, sz); got != expectLen):
+      raise newException(IOError, "got len " & $got & " != " & $expectLen)
+    if sz != expectVal:
+      raise newException(IOError, "got sz " & $sz & " != " & $expectVal)
+  #              STRING    LEN SZ
+  # Good, complete parses
+  checkParseSize "1  b"   , 4, 1
+  checkParseSize "1  B"   , 4, 1
+  checkParseSize "1k"     , 2, 1000
+  checkParseSize "1 kib"  , 5, 1024
+  checkParseSize "1 ki"   , 4, 1024
+  checkParseSize "1mi"    , 3, 1048576
+  checkParseSize "1 mi"   , 4, 1048576
+  checkParseSize "1 mib"  , 5, 1048576
+  checkParseSize "1 Mib"  , 5, 1048576
+  checkParseSize "1 MiB"  , 5, 1048576
+  checkParseSize "1.23GiB", 7, 1320702444 # 1320702443.52 rounded
+  checkParseSize "0.001k" , 6, 1
+  checkParseSize "0.0004k", 7, 0
+  checkParseSize "0.0006k", 7, 1
+  # Incomplete parses
+  checkParseSize "1  "    , 1, 1          # Trailing white IGNORED
+  checkParseSize "1  B "  , 4, 1          # Trailing white IGNORED
+  checkParseSize "1  B/s" , 4, 1          # Trailing junk IGNORED
+  checkParseSize "1 kX"   , 3, 1000
+  checkParseSize "1 kiX"  , 4, 1024
+  checkParseSize "1j"     , 1, 1          # Unknown prefix IGNORED
+  checkParseSize "1 jib"  , 2, 1          # Unknown prefix post space
+  checkParseSize "1  ji"  , 3, 1
+  # Bad parses; `sz` should stay last good|incomplete value
+  checkParseSize "-1b"    , 0, 1          # Negative numbers
+  checkParseSize "abc"    , 0, 1          # Non-numeric
+  checkParseSize " 12"    , 0, 1          # Leading white
+  # Value Edge cases
+  checkParseSize "9223372036854775807", 19, int64.high
+
+block: # bug #23936
+  func parsePyFloat(
+      a: openArray[char],  # here must be openArray instead of string to reproduce this bug
+      res: var BiggestFloat): int =
+    result = parseFloat(a, res)
+
+  static:
+    var f = 0.0
+    doAssert "1.0".parsePyFloat(f) == 3
+    doAssert f == 1.0
diff --git a/tests/stdlib/tparsopt.nim b/tests/stdlib/tparsopt.nim
index 948bc8d5f..f3a9a9798 100644
--- a/tests/stdlib/tparsopt.nim
+++ b/tests/stdlib/tparsopt.nim
@@ -9,6 +9,8 @@ disabled: true
 import
   parseopt
 
+import std/[assertions, syncio]
+
 proc writeHelp() =
   writeLine(stdout, "Usage: tparsopt [options] filename [options]")
 
@@ -27,7 +29,7 @@ for kind, key, val in getopt():
     of "version", "v": writeVersion()
     else:
       writeLine(stdout, "Unknown command line option: ", key, ": ", val)
-  of cmdEnd: assert(false) # cannot happen
+  of cmdEnd: doAssert(false) # cannot happen
 if filename == "":
   # no filename has been given, so we show the help:
   writeHelp()
diff --git a/tests/stdlib/tpathnorm.nim b/tests/stdlib/tpathnorm.nim
new file mode 100644
index 000000000..3dd287a77
--- /dev/null
+++ b/tests/stdlib/tpathnorm.nim
@@ -0,0 +1,36 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/os
+import std/assertions
+
+when doslikeFileSystem:
+  import std/pathnorm
+
+  template initVars =
+    var state {.inject.} = 0
+    var result {.inject.}: string
+
+  block: # / -> /
+    initVars
+    addNormalizePath("//?/c:/./foo//bar/../baz", result, state, '/')
+    doAssert result == "//?/c:/foo/baz"
+    addNormalizePath("me", result, state, '/')
+    doAssert result == "//?/c:/foo/baz/me"
+
+  block: # / -> \
+    initVars
+    addNormalizePath(r"//?/c:/./foo//bar/../baz", result, state, '\\')
+    doAssert result == r"\\?\c:\foo\baz"
+    addNormalizePath("me", result, state, '\\')
+    doAssert result == r"\\?\c:\foo\baz\me"
+
+  block: # Append path component to UNC drive
+    initVars
+    addNormalizePath(r"//?/c:", result, state, '\\')
+    doAssert result == r"\\?\c:"
+    addNormalizePath("Users", result, state, '\\')
+    doAssert result == r"\\?\c:\Users"
+    addNormalizePath("me", result, state, '\\')
+    doAssert result == r"\\?\c:\Users\me"
diff --git a/tests/stdlib/tpaths.nim b/tests/stdlib/tpaths.nim
new file mode 100644
index 000000000..edb56209a
--- /dev/null
+++ b/tests/stdlib/tpaths.nim
@@ -0,0 +1,238 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/paths
+import std/assertions
+import pathnorm
+from std/private/ospaths2 {.all.} import joinPathImpl
+import std/[sugar, sets]
+
+
+proc normalizePath*(path: Path; dirSep = DirSep): Path =
+  result = Path(pathnorm.normalizePath(path.string, dirSep))
+
+func joinPath*(parts: varargs[Path]): Path =
+  var estimatedLen = 0
+  var state = 0
+  for p in parts: estimatedLen += p.string.len
+  var res = newStringOfCap(estimatedLen)
+  for i in 0..high(parts):
+    joinPathImpl(res, state, parts[i].string)
+  result = Path(res)
+
+
+func joinPath(head, tail: Path): Path {.inline.} =
+  head / tail
+
+block absolutePath:
+  doAssertRaises(ValueError): discard absolutePath(Path"a", Path"b")
+  doAssert absolutePath(Path"a") == getCurrentDir() / Path"a"
+  doAssert absolutePath(Path"a", Path"/b") == Path"/b" / Path"a"
+  when defined(posix):
+    doAssert absolutePath(Path"a", Path"/b/") == Path"/b" / Path"a"
+    doAssert absolutePath(Path"a", Path"/b/c") == Path"/b/c" / Path"a"
+    doAssert absolutePath(Path"/a", Path"b/") == Path"/a"
+
+block splitFile:
+  doAssert splitFile(Path"") == (Path"", Path"", "")
+  doAssert splitFile(Path"abc/") == (Path"abc", Path"", "")
+  doAssert splitFile(Path"/") == (Path"/", Path"", "")
+  doAssert splitFile(Path"./abc") == (Path".", Path"abc", "")
+  doAssert splitFile(Path".txt") == (Path"", Path".txt", "")
+  doAssert splitFile(Path"abc/.txt") == (Path"abc", Path".txt", "")
+  doAssert splitFile(Path"abc") == (Path"", Path"abc", "")
+  doAssert splitFile(Path"abc.txt") == (Path"", Path"abc", ".txt")
+  doAssert splitFile(Path"/abc.txt") == (Path"/", Path"abc", ".txt")
+  doAssert splitFile(Path"/foo/abc.txt") == (Path"/foo", Path"abc", ".txt")
+  doAssert splitFile(Path"/foo/abc.txt.gz") == (Path"/foo", Path"abc.txt", ".gz")
+  doAssert splitFile(Path".") == (Path"", Path".", "")
+  doAssert splitFile(Path"abc/.") == (Path"abc", Path".", "")
+  doAssert splitFile(Path"..") == (Path"", Path"..", "")
+  doAssert splitFile(Path"a/..") == (Path"a", Path"..", "")
+  doAssert splitFile(Path"/foo/abc....txt") == (Path"/foo", Path"abc...", ".txt")
+
+# execShellCmd is tested in tosproc
+
+block ospaths:
+  doAssert unixToNativePath(Path"") == Path""
+  doAssert unixToNativePath(Path".") == Path($CurDir)
+  doAssert unixToNativePath(Path"..") == Path($ParDir)
+  doAssert isAbsolute(unixToNativePath(Path"/"))
+  doAssert isAbsolute(unixToNativePath(Path"/", Path"a"))
+  doAssert isAbsolute(unixToNativePath(Path"/a"))
+  doAssert isAbsolute(unixToNativePath(Path"/a", Path"a"))
+  doAssert isAbsolute(unixToNativePath(Path"/a/b"))
+  doAssert isAbsolute(unixToNativePath(Path"/a/b", Path"a"))
+  doAssert unixToNativePath(Path"a/b") == joinPath(Path"a", Path"b")
+
+  when defined(macos):
+    doAssert unixToNativePath(Path"./") == Path":"
+    doAssert unixToNativePath(Path"./abc") == Path":abc"
+    doAssert unixToNativePath(Path"../abc") == Path"::abc"
+    doAssert unixToNativePath(Path"../../abc") == Path":::abc"
+    doAssert unixToNativePath(Path"/abc", Path"a") == Path"abc"
+    doAssert unixToNativePath(Path"/abc/def", Path"a") == Path"abc:def"
+  elif doslikeFileSystem:
+    doAssert unixToNativePath(Path"./") == Path(".\\")
+    doAssert unixToNativePath(Path"./abc") == Path(".\\abc")
+    doAssert unixToNativePath(Path"../abc") == Path("..\\abc")
+    doAssert unixToNativePath(Path"../../abc") == Path("..\\..\\abc")
+    doAssert unixToNativePath(Path"/abc", Path"a") == Path("a:\\abc")
+    doAssert unixToNativePath(Path"/abc/def", Path"a") == Path("a:\\abc\\def")
+  else:
+    #Tests for unix
+    doAssert unixToNativePath(Path"./") == Path"./"
+    doAssert unixToNativePath(Path"./abc") == Path"./abc"
+    doAssert unixToNativePath(Path"../abc") == Path"../abc"
+    doAssert unixToNativePath(Path"../../abc") == Path"../../abc"
+    doAssert unixToNativePath(Path"/abc", Path"a") == Path"/abc"
+    doAssert unixToNativePath(Path"/abc/def", Path"a") == Path"/abc/def"
+
+  block extractFilenameTest:
+    doAssert extractFilename(Path"") == Path""
+    when defined(posix):
+      doAssert extractFilename(Path"foo/bar") == Path"bar"
+      doAssert extractFilename(Path"foo/bar.txt") == Path"bar.txt"
+      doAssert extractFilename(Path"foo/") == Path""
+      doAssert extractFilename(Path"/") == Path""
+    when doslikeFileSystem:
+      doAssert extractFilename(Path(r"foo\bar")) == Path"bar"
+      doAssert extractFilename(Path(r"foo\bar.txt")) == Path"bar.txt"
+      doAssert extractFilename(Path(r"foo\")) == Path""
+      doAssert extractFilename(Path(r"C:\")) == Path""
+
+  block lastPathPartTest:
+    doAssert lastPathPart(Path"") == Path""
+    when defined(posix):
+      doAssert lastPathPart(Path"foo/bar.txt") == Path"bar.txt"
+      doAssert lastPathPart(Path"foo/") == Path"foo"
+      doAssert lastPathPart(Path"/") == Path""
+    when doslikeFileSystem:
+      doAssert lastPathPart(Path(r"foo\bar.txt")) == Path"bar.txt"
+      doAssert lastPathPart(Path(r"foo\")) == Path"foo"
+
+  template canon(x): Path = normalizePath(Path(x), '/')
+  doAssert canon"/foo/../bar" == Path"/bar"
+  doAssert canon"foo/../bar" == Path"bar"
+
+  doAssert canon"/f/../bar///" == Path"/bar"
+  doAssert canon"f/..////bar" == Path"bar"
+
+  doAssert canon"../bar" == Path"../bar"
+  doAssert canon"/../bar" == Path"/../bar"
+
+  doAssert canon("foo/../../bar/") == Path"../bar"
+  doAssert canon("./bla/blob/") == Path"bla/blob"
+  doAssert canon(".hiddenFile") == Path".hiddenFile"
+  doAssert canon("./bla/../../blob/./zoo.nim") == Path"../blob/zoo.nim"
+
+  doAssert canon("C:/file/to/this/long") == Path"C:/file/to/this/long"
+  doAssert canon("") == Path""
+  doAssert canon("foobar") == Path"foobar"
+  doAssert canon("f/////////") == Path"f"
+
+  doAssert relativePath(Path"/foo/bar//baz.nim", Path"/foo", '/') == Path"bar/baz.nim"
+  doAssert normalizePath(Path"./foo//bar/../baz", '/') == Path"foo/baz"
+
+  doAssert relativePath(Path"/Users/me/bar/z.nim", Path"/Users/other/bad", '/') == Path"../../me/bar/z.nim"
+
+  doAssert relativePath(Path"/Users/me/bar/z.nim", Path"/Users/other", '/') == Path"../me/bar/z.nim"
+
+  # `//` is a UNC path, `/` is the current working directory's drive, so can't
+  # run this test on Windows.
+  when not doslikeFileSystem:
+    doAssert relativePath(Path"/Users///me/bar//z.nim", Path"//Users/", '/') == Path"me/bar/z.nim"
+  doAssert relativePath(Path"/Users/me/bar/z.nim", Path"/Users/me", '/') == Path"bar/z.nim"
+  doAssert relativePath(Path"", Path"/users/moo", '/') == Path""
+  doAssert relativePath(Path"foo", Path"", '/') == Path"foo"
+  doAssert relativePath(Path"/foo", Path"/Foo", '/') == (when FileSystemCaseSensitive: Path"../foo" else: Path".")
+  doAssert relativePath(Path"/Foo", Path"/foo", '/') == (when FileSystemCaseSensitive: Path"../Foo" else: Path".")
+  doAssert relativePath(Path"/foo", Path"/fOO", '/') == (when FileSystemCaseSensitive: Path"../foo" else: Path".")
+  doAssert relativePath(Path"/foO", Path"/foo", '/') == (when FileSystemCaseSensitive: Path"../foO" else: Path".")
+
+  doAssert relativePath(Path"foo", Path".", '/') == Path"foo"
+  doAssert relativePath(Path".", Path".", '/') == Path"."
+  doAssert relativePath(Path"..", Path".", '/') == Path".."
+
+  doAssert relativePath(Path"foo", Path"foo") == Path"."
+  doAssert relativePath(Path"", Path"foo") == Path""
+  doAssert relativePath(Path"././/foo", Path"foo//./") == Path"."
+
+  doAssert relativePath(getCurrentDir() / Path"bar", Path"foo") == Path"../bar".unixToNativePath
+  doAssert relativePath(Path"bar", getCurrentDir() / Path"foo") == Path"../bar".unixToNativePath
+
+  when doslikeFileSystem:
+    doAssert relativePath(r"c:\foo.nim".Path, r"C:\".Path) == r"foo.nim".Path
+    doAssert relativePath(r"c:\foo\bar\baz.nim".Path, r"c:\foo".Path) == r"bar\baz.nim".Path
+    doAssert relativePath(r"c:\foo\bar\baz.nim".Path, r"d:\foo".Path) == r"c:\foo\bar\baz.nim".Path
+    doAssert relativePath(r"\foo\baz.nim".Path, r"\foo".Path) == r"baz.nim".Path
+    doAssert relativePath(r"\foo\bar\baz.nim".Path, r"\bar".Path) == r"..\foo\bar\baz.nim".Path
+    doAssert relativePath(r"\\foo\bar\baz.nim".Path, r"\\foo\bar".Path) == r"baz.nim".Path
+    doAssert relativePath(r"\\foo\bar\baz.nim".Path, r"\\foO\bar".Path) == r"baz.nim".Path
+    doAssert relativePath(r"\\foo\bar\baz.nim".Path, r"\\bar\bar".Path) == r"\\foo\bar\baz.nim".Path
+    doAssert relativePath(r"\\foo\bar\baz.nim".Path, r"\\foo\car".Path) == r"\\foo\bar\baz.nim".Path
+    doAssert relativePath(r"\\foo\bar\baz.nim".Path, r"\\goo\bar".Path) == r"\\foo\bar\baz.nim".Path
+    doAssert relativePath(r"\\foo\bar\baz.nim".Path, r"c:\".Path) == r"\\foo\bar\baz.nim".Path
+    doAssert relativePath(r"\\foo\bar\baz.nim".Path, r"\foo".Path) == r"\\foo\bar\baz.nim".Path
+    doAssert relativePath(r"c:\foo.nim".Path, r"\foo".Path) == r"c:\foo.nim".Path
+
+  doAssert joinPath(Path"usr", Path"") == unixToNativePath(Path"usr")
+  doAssert joinPath(Path"usr", Path"") == (Path"usr").dup(add Path"")
+  doAssert joinPath(Path"", Path"lib") == Path"lib"
+  doAssert joinPath(Path"", Path"lib") == Path"".dup(add Path"lib")
+  doAssert joinPath(Path"", Path"/lib") == unixToNativePath(Path"/lib")
+  doAssert joinPath(Path"", Path"/lib") == unixToNativePath(Path"/lib")
+  doAssert joinPath(Path"usr/", Path"/lib") == Path"usr/".dup(add Path"/lib")
+  doAssert joinPath(Path"", Path"") == unixToNativePath(Path"") # issue #13455
+  doAssert joinPath(Path"", Path"") == Path"".dup(add Path"")
+  doAssert joinPath(Path"", Path"/") == unixToNativePath(Path"/")
+  doAssert joinPath(Path"", Path"/") == Path"".dup(add Path"/")
+  doAssert joinPath(Path"/", Path"/") == unixToNativePath(Path"/")
+  doAssert joinPath(Path"/", Path"/") == Path"/".dup(add Path"/")
+  doAssert joinPath(Path"/", Path"") == unixToNativePath(Path"/")
+  doAssert joinPath(Path"/" / Path"") == unixToNativePath(Path"/") # weird test case...
+  doAssert joinPath(Path"/", Path"/a/b/c") == unixToNativePath(Path"/a/b/c")
+  doAssert joinPath(Path"foo/", Path"") == unixToNativePath(Path"foo/")
+  doAssert joinPath(Path"foo/", Path"abc") == unixToNativePath(Path"foo/abc")
+  doAssert joinPath(Path"foo//./", Path"abc/.//") == unixToNativePath(Path"foo/abc/")
+  doAssert Path"foo//./".dup(add Path"abc/.//") == unixToNativePath(Path"foo/abc/")
+  doAssert joinPath(Path"foo", Path"abc") == unixToNativePath(Path"foo/abc")
+  doAssert Path"foo".dup(add Path"abc") == unixToNativePath(Path"foo/abc")
+  doAssert joinPath(Path"", Path"abc") == unixToNativePath(Path"abc")
+
+  doAssert joinPath(Path"zook/.", Path"abc") == unixToNativePath(Path"zook/abc")
+
+  # controversial: inconsistent with `joinPath("zook/.","abc")`
+  # on linux, `./foo` and `foo` are treated a bit differently for executables
+  # but not `./foo/bar` and `foo/bar`
+  doAssert joinPath(Path".", Path"/lib") == unixToNativePath(Path"./lib")
+  doAssert joinPath(Path".", Path"abc") == unixToNativePath(Path"./abc")
+
+  # cases related to issue #13455
+  doAssert joinPath(Path"foo", Path"", Path"") == Path"foo"
+  doAssert joinPath(Path"foo", Path"") == Path"foo"
+  doAssert joinPath(Path"foo/", Path"") == unixToNativePath(Path"foo/")
+  doAssert joinPath(Path"foo/", Path".") == Path"foo"
+  doAssert joinPath(Path"foo", Path"./") == unixToNativePath(Path"foo/")
+  doAssert joinPath(Path"foo", Path"", Path"bar/") == unixToNativePath(Path"foo/bar/")
+
+  # issue #13579
+  doAssert joinPath(Path"/foo", Path"../a") == unixToNativePath(Path"/a")
+  doAssert joinPath(Path"/foo/", Path"../a") == unixToNativePath(Path"/a")
+  doAssert joinPath(Path"/foo/.", Path"../a") == unixToNativePath(Path"/a")
+  doAssert joinPath(Path"/foo/.b", Path"../a") == unixToNativePath(Path"/foo/a")
+  doAssert joinPath(Path"/foo///", Path"..//a/") == unixToNativePath(Path"/a/")
+  doAssert joinPath(Path"foo/", Path"../a") == unixToNativePath(Path"a")
+
+  when doslikeFileSystem:
+    doAssert joinPath(Path"C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\Tools\\", Path"..\\..\\VC\\vcvarsall.bat") == r"C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\vcvarsall.bat".Path
+    doAssert joinPath(Path"C:\\foo", Path"..\\a") == r"C:\a".Path
+    doAssert joinPath(Path"C:\\foo\\", Path"..\\a") == r"C:\a".Path
+
+
+block: # bug #23663
+  var s: HashSet[Path]
+  s.incl("/a/b/c/..".Path)
+  doAssert "/a/b/".Path in s
+  doAssert "/a/b/c".Path notin s
diff --git a/tests/stdlib/tpegs.nim b/tests/stdlib/tpegs.nim
index b07442dcb..da3fc14b7 100644
--- a/tests/stdlib/tpegs.nim
+++ b/tests/stdlib/tpegs.nim
@@ -1,4 +1,6 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
   output: '''
 PEG AST traversal output
 ------------------------
@@ -50,8 +52,10 @@ Event parser output
 '''
 """
 
-import strutils, streams
-import pegs
+when defined(nimHasEffectsOf):
+  {.experimental: "strictEffects".}
+
+import std/[strutils, streams, pegs, assertions]
 
 const
   indent = "  "
@@ -103,9 +107,9 @@ block:
 
 block:
   var
-    pStack: seq[string] = @[]
-    valStack: seq[float] = @[]
-    opStack = ""
+    pStack {.threadvar.}: seq[string]
+    valStack {.threadvar.}: seq[float]
+    opStack {.threadvar.}: string
   let
     parseArithExpr = pegAst.eventParser:
       pkNonTerminal:
@@ -124,7 +128,7 @@ block:
                 discard
             of "Sum", "Product":
               try:
-                let val = matchStr.parseFloat
+                let val {.used.} = matchStr.parseFloat
               except ValueError:
                 if valStack.len > 1 and opStack.len > 0:
                   valStack[^2] = case opStack[^1]
@@ -145,4 +149,196 @@ block:
   echo "Event parser output"
   echo "-------------------"
   let pLen = parseArithExpr(txt)
-  assert txt.len == pLen
+  doAssert txt.len == pLen
+
+
+import std/importutils
+
+block:
+  proc pegsTest() =
+    privateAccess(NonTerminal)
+    privateAccess(Captures)
+
+    if "test" =~ peg"s <- {{\ident}}": # bug #19104
+      doAssert matches[0] == "test"
+      doAssert matches[1] == "test", $matches[1]
+
+    doAssert escapePeg("abc''def'") == r"'abc'\x27\x27'def'\x27"
+    doAssert match("(a b c)", peg"'(' @ ')'")
+    doAssert match("W_HI_Le", peg"\y 'while'")
+    doAssert(not match("W_HI_L", peg"\y 'while'"))
+    doAssert(not match("W_HI_Le", peg"\y v'while'"))
+    doAssert match("W_HI_Le", peg"y'while'")
+
+    doAssert($ +digits == $peg"\d+")
+    doAssert "0158787".match(peg"\d+")
+    doAssert "ABC 0232".match(peg"\w+\s+\d+")
+    doAssert "ABC".match(peg"\d+ / \w+")
+
+    var accum: seq[string] = @[]
+    for word in split("00232this02939is39an22example111", peg"\d+"):
+      accum.add(word)
+    doAssert(accum == @["this", "is", "an", "example"])
+
+    doAssert matchLen("key", ident) == 3
+
+    var pattern = sequence(ident, *whitespace, term('='), *whitespace, ident)
+    doAssert matchLen("key1=  cal9", pattern) == 11
+
+    var ws = newNonTerminal("ws", 1, 1)
+    ws.rule = *whitespace
+
+    var expr = newNonTerminal("expr", 1, 1)
+    expr.rule = sequence(capture(ident), *sequence(
+                  nonterminal(ws), term('+'), nonterminal(ws), nonterminal(expr)))
+
+    var c: Captures
+    var s = "a+b +  c +d+e+f"
+    doAssert rawMatch(s, expr.rule, 0, c) == len(s)
+    var a = ""
+    for i in 0..c.ml-1:
+      a.add(substr(s, c.matches[i][0], c.matches[i][1]))
+    doAssert a == "abcdef"
+    #echo expr.rule
+
+    #const filename = "lib/devel/peg/grammar.txt"
+    #var grammar = parsePeg(newFileStream(filename, fmRead), filename)
+    #echo "a <- [abc]*?".match(grammar)
+    doAssert find("_____abc_______", term("abc"), 2) == 5
+    doAssert match("_______ana", peg"A <- 'ana' / . A")
+    doAssert match("abcs%%%", peg"A <- ..A / .A / '%'")
+
+    var matches: array[0..MaxSubpatterns-1, string]
+    if "abc" =~ peg"{'a'}'bc' 'xyz' / {\ident}":
+      doAssert matches[0] == "abc"
+    else:
+      doAssert false
+
+    var g2 = peg"""S <- A B / C D
+                   A <- 'a'+
+                   B <- 'b'+
+                   C <- 'c'+
+                   D <- 'd'+
+                """
+    doAssert($g2 == "((A B) / (C D))")
+    doAssert match("cccccdddddd", g2)
+    doAssert("var1=key; var2=key2".replacef(peg"{\ident}'='{\ident}", "$1<-$2$2") ==
+           "var1<-keykey; var2<-key2key2")
+    doAssert("var1=key; var2=key2".replace(peg"{\ident}'='{\ident}", "$1<-$2$2") ==
+           "$1<-$2$2; $1<-$2$2")
+    doAssert "var1=key; var2=key2".endsWith(peg"{\ident}'='{\ident}")
+
+    if "aaaaaa" =~ peg"'aa' !. / ({'a'})+":
+      doAssert matches[0] == "a"
+    else:
+      doAssert false
+
+    if match("abcdefg", peg"c {d} ef {g}", matches, 2):
+      doAssert matches[0] == "d"
+      doAssert matches[1] == "g"
+    else:
+      doAssert false
+
+    accum = @[]
+    for x in findAll("abcdef", peg".", 3):
+      accum.add(x)
+    doAssert(accum == @["d", "e", "f"])
+
+    for x in findAll("abcdef", peg"^{.}", 3):
+      doAssert x == "d"
+
+    if "f(a, b)" =~ peg"{[0-9]+} / ({\ident} '(' {@} ')')":
+      doAssert matches[0] == "f"
+      doAssert matches[1] == "a, b"
+    else:
+      doAssert false
+
+    doAssert match("eine übersicht und außerdem", peg"(\letter \white*)+")
+    # ß is not a lower cased letter?!
+    doAssert match("eine übersicht und auerdem", peg"(\lower \white*)+")
+    doAssert match("EINE ÜBERSICHT UND AUSSERDEM", peg"(\upper \white*)+")
+    doAssert(not match("456678", peg"(\letter)+"))
+
+    doAssert("var1 = key; var2 = key2".replacef(
+      peg"\skip(\s*) {\ident}'='{\ident}", "$1<-$2$2") ==
+           "var1<-keykey;var2<-key2key2")
+
+    doAssert match("prefix/start", peg"^start$", 7)
+
+    if "foo" =~ peg"{'a'}?.*":
+      doAssert matches[0].len == 0
+    else: doAssert false
+
+    if "foo" =~ peg"{''}.*":
+      doAssert matches[0] == ""
+    else: doAssert false
+
+    if "foo" =~ peg"{'foo'}":
+      doAssert matches[0] == "foo"
+    else: doAssert false
+
+    let empty_test = peg"^\d*"
+    let str = "XYZ"
+
+    doAssert(str.find(empty_test) == 0)
+    doAssert(str.match(empty_test))
+
+    proc handleMatches(m: int, n: int, c: openArray[string]): string =
+      result = ""
+
+      if m > 0:
+        result.add ", "
+
+      result.add case n:
+        of 2: toLowerAscii(c[0]) & ": '" & c[1] & "'"
+        of 1: toLowerAscii(c[0]) & ": ''"
+        else: ""
+
+    doAssert("Var1=key1;var2=Key2;   VAR3".
+      replace(peg"{\ident}('='{\ident})* ';'* \s*",
+      handleMatches) == "var1: 'key1', var2: 'Key2', var3: ''")
+
+
+    doAssert "test1".match(peg"""{@}$""")
+    doAssert "test2".match(peg"""{(!$ .)*} $""")
+
+    doAssert "abbb".match(peg"{a} {b} $2 $^1")
+    doAssert "abBA".match(peg"{a} {b} i$2 i$^2")
+
+    doAssert "abba".match(peg"{a} {b} $^1 {} $^1")
+
+    block:
+      let grammar = peg"""
+program <- {''} stmt* $
+stmt <- call / block
+call <- 'call()' EOL
+EOL <- \n / $
+block <- 'block:' \n indBody
+indBody <- {$^1 ' '+} stmt ($^1 stmt)* {}
+"""
+      let program = """
+call()
+block:
+  block:
+    call()
+    call()
+  call()
+call()
+"""
+      var c: Captures
+      doAssert program.len == program.rawMatch(grammar, 0, c)
+      doAssert c.ml == 1
+
+    block:
+      # bug #21632
+
+      let p = peg"""
+        atext <- \w / \d
+      """
+
+      doAssert "a".match(p)
+      doAssert "1".match(p)
+
+  pegsTest()
+  static:
+    pegsTest()
diff --git a/tests/stdlib/tposix.nim b/tests/stdlib/tposix.nim
index 14f1fd6e2..060482229 100644
--- a/tests/stdlib/tposix.nim
+++ b/tests/stdlib/tposix.nim
@@ -1,5 +1,6 @@
 discard """
-outputsub: ""
+  matrix: "--mm:refc; --mm:orc"
+  disabled: windows
 """
 
 # Test Posix interface
@@ -7,6 +8,7 @@ outputsub: ""
 when not defined(windows):
 
   import posix
+  import std/[assertions, syncio]
 
   var
     u: Utsname
@@ -17,3 +19,70 @@ when not defined(windows):
   writeLine(stdout, u.nodename)
   writeLine(stdout, u.release)
   writeLine(stdout, u.machine)
+
+  when not (defined(nintendoswitch) or defined(macos) or defined(macosx)):
+    block:
+      type Message = object
+        value: int
+
+      const MQ_PATH: cstring = "/top_level_file"
+      const MQ_PRIORITY: cuint = 170
+      const MQ_MESSAGE_SIZE: csize_t = csize_t(sizeof(Message))
+
+      let mqd_a: posix.MqAttr = MqAttr(mq_maxmsg: 10, mq_msgsize: clong(MQ_MESSAGE_SIZE))
+      let writable: posix.Mqd = posix.mq_open(
+        MQ_PATH,
+        posix.O_CREAT or posix.O_WRONLY or posix.O_NONBLOCK,
+        posix.S_IRWXU,
+        addr(mqd_a)
+      )
+      let readable: posix.Mqd = posix.mq_open(
+        MQ_PATH,
+        posix.O_RDONLY or posix.O_NONBLOCK,
+        posix.S_IRWXU,
+        addr(mqd_a)
+      )
+
+      let sent: Message = Message(value: 88)
+      block:
+        let success: int = writable.mq_send(
+          cast[cstring](sent.addr),
+          MQ_MESSAGE_SIZE,
+          MQ_PRIORITY
+        )
+        doAssert success == 0, $success
+
+      block:
+        var buffer: Message
+        var priority: cuint
+        let bytesRead: int = readable.mq_receive(
+          cast[cstring](buffer.addr),
+          MQ_MESSAGE_SIZE,
+          priority
+        )
+        doAssert buffer == sent
+        doAssert bytesRead == int(MQ_MESSAGE_SIZE)
+
+  block:
+    var rl: RLimit
+    var res = getrlimit(RLIMIT_STACK, rl)
+    doAssert res == 0
+
+    # save old value
+    let oldrlim = rl.rlim_cur
+
+    # set new value
+    rl.rlim_cur = rl.rlim_max - 1
+    res = setrlimit(RLIMIT_STACK, rl)
+    doAssert res == 0
+
+    # get new value
+    var rl1: RLimit
+    res = getrlimit(RLIMIT_STACK, rl1)
+    doAssert res == 0
+    doAssert rl1.rlim_cur == rl.rlim_max - 1
+
+    # restore old value
+    rl.rlim_cur = oldrlim
+    res = setrlimit(RLIMIT_STACK, rl)
+    doAssert res == 0
diff --git a/tests/stdlib/tprelude.nim b/tests/stdlib/tprelude.nim
new file mode 100644
index 000000000..47f46b511
--- /dev/null
+++ b/tests/stdlib/tprelude.nim
@@ -0,0 +1,16 @@
+discard """
+  targets: "c js"
+  matrix: "; -d:nimTestTpreludeCase1"
+"""
+
+when defined nimTestTpreludeCase1:
+  include std/prelude
+else:
+  include prelude
+
+import std/assertions
+
+template main() =
+  doAssert toSeq(1..3) == @[1,2,3]
+static: main()
+main()
diff --git a/tests/stdlib/tquit.nim b/tests/stdlib/tquit.nim
deleted file mode 100644
index 1f9283ec4..000000000
--- a/tests/stdlib/tquit.nim
+++ /dev/null
@@ -1,13 +0,0 @@
-discard """
-output: '''
-just exiting...
-'''
-joinable: false
-"""
-
-# Test the new beforeQuit variable:
-
-proc myExit() {.noconv.} =
-  write(stdout, "just exiting...\n")
-
-addQuitProc(myExit)
diff --git a/tests/stdlib/trandom.nim b/tests/stdlib/trandom.nim
new file mode 100644
index 000000000..eb32f7757
--- /dev/null
+++ b/tests/stdlib/trandom.nim
@@ -0,0 +1,310 @@
+discard """
+  joinable: false # to avoid messing with global rand state
+  matrix: "--mm:refc; --mm:orc; --backend:js --jsbigint64:off -d:nimStringHash2; --backend:js --jsbigint64:on"
+"""
+import std/[assertions, formatfloat]
+import std/[random, math, stats, sets, tables]
+import std/private/jsutils
+when not defined(js):
+  import std/os
+
+randomize(233)
+
+proc main() =
+  var occur: array[1000, int]
+
+  for i in 0..100_000:
+    let x = rand(high(occur))
+    inc occur[x]
+
+  doAssert max(occur) <= 140 and min(occur) >= 60 # gives some slack
+
+  var a = [0, 1]
+  shuffle(a)
+  doAssert a in [[0,1], [1,0]]
+
+  doAssert rand(0) == 0
+  when not defined(nimscript):
+    doAssert sample("a") == 'a'
+
+  when compileOption("rangeChecks") and not defined(nimscript):
+    doAssertRaises(RangeDefect):
+      discard rand(-1)
+
+    doAssertRaises(RangeDefect):
+      discard rand(-1.0)
+
+  # don't use causes integer overflow
+  doAssert compiles(rand[int](low(int) .. high(int)))
+
+main()
+
+block:
+  when not defined(js):
+    doAssert almostEqual(rand(12.5), 7.355175342026979)
+    doAssert almostEqual(rand(2233.3322), 499.342386778917)
+
+  type DiceRoll = range[0..6]
+  when not defined(js):
+    doAssert rand(DiceRoll).int == 3
+  elif compileOption("jsbigint64"):
+    doAssert rand(DiceRoll).int == 1
+  else:
+    doAssert rand(DiceRoll).int == 6
+
+var rs: RunningStat
+for j in 1..5:
+  for i in 1 .. 100_000:
+    rs.push(gauss())
+  doAssert abs(rs.mean-0) < 0.08, $rs.mean
+  doAssert abs(rs.standardDeviation()-1.0) < 0.1
+  let bounds = [3.5, 5.0]
+  for a in [rs.max, -rs.min]:
+    doAssert a >= bounds[0] and a <= bounds[1]
+  rs.clear()
+
+block:
+  type DiceRoll = range[3..6]
+  var flag = false
+  for i in 0..<100:
+    if rand(5.DiceRoll) < 3:
+      flag = true
+  doAssert flag # because of: rand(max: int): int
+
+
+block: # random int
+  block: # there might be some randomness
+    var set = initHashSet[int](128)
+
+    for i in 1..1000:
+      incl(set, rand(high(int)))
+    doAssert len(set) == 1000
+
+  block: # single number bounds work
+    var rand: int
+    for i in 1..1000:
+      rand = rand(1000)
+      doAssert rand <= 1000
+      doAssert rand >= 0
+
+  block: # slice bounds work
+    var rand: int
+    for i in 1..1000:
+      rand = rand(100..1000)
+      doAssert rand <= 1000
+      doAssert rand >= 100
+
+  block: # again gives new numbers
+    var rand1 = rand(1000000)
+    when not (defined(js) or defined(nimscript)):
+      os.sleep(200)
+
+    var rand2 = rand(1000000)
+    doAssert rand1 != rand2
+
+block: # random float
+  block: # there might be some randomness
+    var set = initHashSet[float](128)
+
+    for i in 1..100:
+      incl(set, rand(1.0))
+    doAssert len(set) == 100
+
+  block: # single number bounds work
+    var rand: float
+    for i in 1..1000:
+      rand = rand(1000.0)
+      doAssert rand <= 1000.0
+      doAssert rand >= 0.0
+
+  block: # slice bounds work
+    var rand: float
+    for i in 1..1000:
+      rand = rand(100.0..1000.0)
+      doAssert rand <= 1000.0
+      doAssert rand >= 100.0
+
+  block: # again gives new numbers
+    var rand1: float = rand(1000000.0)
+    when not (defined(js) or defined(nimscript)):
+      os.sleep(200)
+
+    var rand2: float = rand(1000000.0)
+    doAssert rand1 != rand2
+
+block: # random sample
+  block: # "non-uniform array sample unnormalized int CDF
+    let values = [10, 20, 30, 40, 50] # values
+    let counts = [4, 3, 2, 1, 0]      # weights aka unnormalized probabilities
+    var histo = initCountTable[int]()
+    let cdf = counts.cumsummed        # unnormalized CDF
+    for i in 0 ..< 5000:
+      histo.inc(sample(values, cdf))
+    doAssert histo.len == 4              # number of non-zero in `counts`
+    # Any one bin is a binomial random var for n samples, each with prob p of
+    # adding a count to k; E[k]=p*n, Var k=p*(1-p)*n, approximately Normal for
+    # big n.  So, P(abs(k - p*n)/sqrt(p*(1-p)*n))>3.0) =~ 0.0027, while
+    # P(wholeTestFails) =~ 1 - P(binPasses)^4 =~ 1 - (1-0.0027)^4 =~ 0.01.
+    for i, c in counts:
+      if c == 0:
+        doAssert values[i] notin histo
+        continue
+      let p = float(c) / float(cdf[^1])
+      let n = 5000.0
+      let expected = p * n
+      let stdDev = sqrt(n * p * (1.0 - p))
+      doAssert abs(float(histo[values[i]]) - expected) <= 3.0 * stdDev
+
+  block: # non-uniform array sample normalized float CDF
+    let values = [10, 20, 30, 40, 50]     # values
+    let counts = [0.4, 0.3, 0.2, 0.1, 0]  # probabilities
+    var histo = initCountTable[int]()
+    let cdf = counts.cumsummed            # normalized CDF
+    for i in 0 ..< 5000:
+      histo.inc(sample(values, cdf))
+    doAssert histo.len == 4                  # number of non-zero in ``counts``
+    for i, c in counts:
+      if c == 0:
+        doAssert values[i] notin histo
+        continue
+      let p = float(c) / float(cdf[^1])
+      let n = 5000.0
+      let expected = p * n
+      let stdDev = sqrt(n * p * (1.0 - p))
+      # NOTE: like unnormalized int CDF test, P(wholeTestFails) =~ 0.01.
+      doAssert abs(float(histo[values[i]]) - expected) <= 3.0 * stdDev
+
+block:
+  # 0 is a valid seed
+  var r = initRand(0)
+  doAssert r.rand(1.0) != r.rand(1.0)
+  r = initRand(10)
+  doAssert r.rand(1.0) != r.rand(1.0)
+  # changing the seed changes the sequence
+  var r1 = initRand(123)
+  var r2 = initRand(124)
+  doAssert r1.rand(1.0) != r2.rand(1.0)
+
+block: # bug #17467
+  let n = 1000
+  for i in -n .. n:
+    var r = initRand(i)
+    let x = r.rand(1.0)
+    doAssert x > 1e-4, $(x, i)
+      # This used to fail for each i in 0..<26844, i.e. the 1st produced value
+      # was predictable and < 1e-4, skewing distributions.
+
+block: # bug #16360, Natural overload
+  var r = initRand()
+  template test(a) =
+    let a2 = a
+    block:
+      let a3 = r.rand(a2)
+      doAssert a3 <= a2
+      doAssert a3.type is a2.type
+    block:
+      let a3 = rand(a2)
+      doAssert a3 <= a2
+      doAssert a3.type is a2.type
+  test int.high
+  test int.high - 1
+  test int.high - 2
+  test 0
+
+block: # same as above but use slice overload
+  var r = initRand()
+  template test[T](a: T) =
+    let a2: T = a
+    block:
+      let a3 = r.rand(T(0) .. a2)
+      doAssert a3 <= a2
+      doAssert a3.type is a2.type
+    block:
+      let a3 = rand(T(0) .. a2)
+      doAssert a3 <= a2
+      doAssert a3.type is a2.type
+  test cast[uint](int.high)
+  test cast[uint](int.high) + 1
+  whenJsNoBigInt64: discard
+  do:
+    test uint64.high
+    test uint64.high - 1
+  test uint.high - 2
+  test uint.high - 1
+  test uint.high
+  test int.high
+  test int.high - 1
+  test int.high - 2
+  test 0
+  test 0'u
+  test 0'u64
+
+block: # bug #16296
+  var r = initRand()
+  template test(x) =
+    let a2 = x
+    let a3 = r.rand(a2)
+    doAssert a3 <= a2.b
+    doAssert a3 >= a2.a
+    doAssert a3.type is a2.a.type
+  test(-2 .. int.high-1)
+  test(int.low .. int.high)
+  test(int.low+1 .. int.high)
+  test(int.low .. int.high-1)
+  test(int.low .. 0)
+  test(int.low .. -1)
+  test(int.low .. 1)
+  test(int64.low .. 1'i64)
+  test(10'u64 .. uint64.high)
+
+block: # bug #17670
+  type UInt48 = range[0'u64..2'u64^48-1]
+  let x = rand(UInt48)
+  doAssert x is UInt48
+
+block: # bug #17898
+  # Checks whether `initRand()` generates unique states.
+  # size should be 2^64, but we don't have time and space.
+
+  # Disable this test for js until js gets proper skipRandomNumbers.
+  when not defined(js):
+    const size = 1000
+    var
+      rands: array[size, Rand]
+      randSet: HashSet[Rand]
+    for i in 0..<size:
+      rands[i] = initRand()
+      randSet.incl rands[i]
+
+    doAssert randSet.len == size
+
+    # Checks random number sequences overlapping.
+    const numRepeat = 100
+    for i in 0..<size:
+      for j in 0..<numRepeat:
+        discard rands[i].next
+        doAssert rands[i] notin randSet
+
+block: # bug #22360
+  const size = 1000
+  var fc = 0
+  var tc = 0
+
+  for _ in 1..size:
+    let s = rand(bool)
+
+    if s:
+      inc tc
+    else:
+      inc fc
+
+  when defined(js) and not compileOption("jsbigint64"):
+    doAssert (tc, fc) == (515, 485), $(tc, fc)
+  else:
+    doAssert (tc, fc) == (510, 490), $(tc, fc)
+
+block:
+  when defined(js) and not compileOption("jsbigint64"):
+    doAssert rand(int32.high) == 335507522
+  else:
+    doAssert rand(int32.high) == 607539621
diff --git a/tests/rational/trat_float.nim b/tests/stdlib/trat_float.nim
index 663973bf9..663973bf9 100644
--- a/tests/rational/trat_float.nim
+++ b/tests/stdlib/trat_float.nim
diff --git a/tests/rational/trat_init.nim b/tests/stdlib/trat_init.nim
index 360a48537..2be0c0099 100644
--- a/tests/rational/trat_init.nim
+++ b/tests/stdlib/trat_init.nim
@@ -10,5 +10,5 @@ var
 try:
   var
     r = initRational(1, 0)  # this fails - no zero denominator
-except AssertionError:
+except AssertionDefect:
   echo "true"
diff --git a/tests/stdlib/trationals.nim b/tests/stdlib/trationals.nim
new file mode 100644
index 000000000..22d7f5c2d
--- /dev/null
+++ b/tests/stdlib/trationals.nim
@@ -0,0 +1,117 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/[rationals, math]
+import std/assertions
+
+template main() =
+  var
+    z = Rational[int](num: 0, den: 1)
+    o = initRational(num = 1, den = 1)
+    a = initRational(1, 2)
+    u = 3u // 2
+    b = -1 // -2
+    m1 = -1 // 1
+    tt = 10 // 2
+
+  doAssert a == a
+  doAssert a - a == z
+  doAssert a + b == o
+  doAssert a / b == o
+  doAssert a * b == 1 // 4
+  doAssert 3 / a == 6 // 1
+  doAssert a / 3 == 1 // 6
+  doAssert tt * z == z
+  doAssert 10 * a == tt
+  doAssert a * 10 == tt
+  doAssert tt / 10 == a
+  doAssert a - m1 == 3 // 2
+  doAssert a + m1 == -1 // 2
+  doAssert m1 + tt == 16 // 4
+  doAssert m1 - tt == 6 // -1
+
+  doAssert z < o
+  doAssert z <= o
+  doAssert z == z
+  doAssert cmp(z, o) < 0
+  doAssert cmp(o, z) > 0
+
+  doAssert o == o
+  doAssert o >= o
+  doAssert not(o > o)
+  doAssert cmp(o, o) == 0
+  doAssert cmp(z, z) == 0
+  doAssert hash(o) == hash(o)
+
+  doAssert a == b
+  doAssert a >= b
+  doAssert not(b > a)
+  doAssert cmp(a, b) == 0
+  doAssert hash(a) == hash(b)
+
+  var x = 1 // 3
+
+  x *= 5 // 1
+  doAssert x == 5 // 3
+  x += 2 // 9
+  doAssert x == 17 // 9
+  x -= 9 // 18
+  doAssert x == 25 // 18
+  x /= 1 // 2
+  doAssert x == 50 // 18
+
+  var y = 1 // 3
+
+  y *= 4
+  doAssert y == 4 // 3
+  y += 5
+  doAssert y == 19 // 3
+  y -= 2
+  doAssert y == 13 // 3
+  y /= 9
+  doAssert y == 13 // 27
+
+  doAssert toRational(5) == 5 // 1
+  doAssert abs(toFloat(y) - 0.4814814814814815) < 1.0e-7
+  doAssert toInt(z) == 0
+
+  when sizeof(int) == 8:
+    doAssert toRational(0.98765432) == 2111111029 // 2137499919
+    doAssert toRational(PI) == 817696623 // 260280919
+  when sizeof(int) == 4:
+    doAssert toRational(0.98765432) == 80 // 81
+    doAssert toRational(PI) == 355 // 113
+
+  doAssert toRational(0.1) == 1 // 10
+  doAssert toRational(0.9) == 9 // 10
+
+  doAssert toRational(0.0) == 0 // 1
+  doAssert toRational(-0.25) == 1 // -4
+  doAssert toRational(3.2) == 16 // 5
+  doAssert toRational(0.33) == 33 // 100
+  doAssert toRational(0.22) == 11 // 50
+  doAssert toRational(10.0) == 10 // 1
+
+  doAssert (1 // 1) div (3 // 10) == 3
+  doAssert (-1 // 1) div (3 // 10) == -3
+  doAssert (3 // 10) mod (1 // 1) == 3 // 10
+  doAssert (-3 // 10) mod (1 // 1) == -3 // 10
+  doAssert floorDiv(1 // 1, 3 // 10) == 3
+  doAssert floorDiv(-1 // 1, 3 // 10) == -4
+  doAssert floorMod(3 // 10, 1 // 1) == 3 // 10
+  doAssert floorMod(-3 // 10, 1 // 1) == 7 // 10
+
+  when sizeof(int) == 8:
+    doAssert almostEqual(PI.toRational.toFloat, PI)
+
+  # unsigned
+  doAssert u == u
+  doAssert u + u == 3u // 1
+  doAssert 3u.toRational - u == u
+  doAssert u * 2 == 3u // 1
+
+
+
+static: main()
+main()
diff --git a/tests/stdlib/tre.nim b/tests/stdlib/tre.nim
new file mode 100644
index 000000000..39637434d
--- /dev/null
+++ b/tests/stdlib/tre.nim
@@ -0,0 +1,122 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/re
+import std/assertions
+
+proc testAll() =
+  doAssert match("(a b c)", rex"\( .* \)")
+  doAssert match("WHiLe", re("while", {reIgnoreCase}))
+
+  doAssert "0158787".match(re"\d+")
+  doAssert "ABC 0232".match(re"\w+\s+\d+")
+  doAssert "ABC".match(rex"\d+ | \w+")
+
+  {.push warnings:off.}
+  doAssert matchLen("key", re"\b[a-zA-Z_]+[a-zA-Z_0-9]*\b") == 3
+  {.pop.}
+
+  var pattern = re"[a-z0-9]+\s*=\s*[a-z0-9]+"
+  doAssert matchLen("key1=  cal9", pattern) == 11
+
+  doAssert find("_____abc_______", re"abc") == 5
+  doAssert findBounds("_____abc_______", re"abc") == (5,7)
+
+  var matches: array[6, string]
+  if match("abcdefg", re"c(d)ef(g)", matches, 2):
+    doAssert matches[0] == "d"
+    doAssert matches[1] == "g"
+  else:
+    doAssert false
+
+  if "abc" =~ re"(a)bcxyz|(\w+)":
+    doAssert matches[1] == "abc"
+  else:
+    doAssert false
+
+  if "abc" =~ re"(cba)?.*":
+    doAssert matches[0] == ""
+  else: doAssert false
+
+  if "abc" =~ re"().*":
+    doAssert matches[0] == ""
+  else: doAssert false
+
+  doAssert "var1=key; var2=key2".endsWith(re"\w+=\w+")
+  doAssert("var1=key; var2=key2".replacef(re"(\w+)=(\w+)", "$1<-$2$2") ==
+         "var1<-keykey; var2<-key2key2")
+  doAssert("var1=key; var2=key2".replace(re"(\w+)=(\w+)", "$1<-$2$2") ==
+         "$1<-$2$2; $1<-$2$2")
+
+  var accum: seq[string] = @[]
+  for word in split("00232this02939is39an22example111", re"\d+"):
+    accum.add(word)
+  doAssert(accum == @["", "this", "is", "an", "example", ""])
+
+  accum = @[]
+  for word in split("00232this02939is39an22example111", re"\d+", maxsplit=2):
+    accum.add(word)
+  doAssert(accum == @["", "this", "is39an22example111"])
+
+  accum = @[]
+  for word in split("AAA :   : BBB", re"\s*:\s*"):
+    accum.add(word)
+  doAssert(accum == @["AAA", "", "BBB"])
+
+  doAssert(split("abc", re"") == @["a", "b", "c"])
+  doAssert(split("", re"") == @[])
+
+  doAssert(split("a;b;c", re";") == @["a", "b", "c"])
+  doAssert(split(";a;b;c", re";") == @["", "a", "b", "c"])
+  doAssert(split(";a;b;c;", re";") == @["", "a", "b", "c", ""])
+  doAssert(split("a;b;c;", re";") == @["a", "b", "c", ""])
+  doAssert(split("00232this02939is39an22example111", re"\d+", maxsplit=2) == @["", "this", "is39an22example111"])
+
+
+  for x in findAll("abcdef", re"^{.}", 3):
+    doAssert x == "d"
+  accum = @[]
+  for x in findAll("abcdef", re".", 3):
+    accum.add(x)
+  doAssert(accum == @["d", "e", "f"])
+
+  doAssert("XYZ".find(re"^\d*") == 0)
+  doAssert("XYZ".match(re"^\d*") == true)
+
+  block:
+    var matches: array[16, string]
+    if match("abcdefghijklmnop", re"(a)(b)(c)(d)(e)(f)(g)(h)(i)(j)(k)(l)(m)(n)(o)(p)", matches):
+      for i in 0..matches.high:
+        doAssert matches[i] == $chr(i + 'a'.ord)
+    else:
+      doAssert false
+
+  block:   # Buffer based RE
+    var cs: cstring = "_____abc_______"
+    doAssert(cs.find(re"abc", bufSize=15) == 5)
+    doAssert(cs.matchLen(re"_*abc", bufSize=15) == 8)
+    doAssert(cs.matchLen(re"abc", start=5, bufSize=15) == 3)
+    doAssert(cs.matchLen(re"abc", start=5, bufSize=7) == -1)
+    doAssert(cs.matchLen(re"abc_*", start=5, bufSize=10) == 5)
+    var accum: seq[string] = @[]
+    for x in cs.findAll(re"[a-z]", start=3, bufSize=15):
+      accum.add($x)
+    doAssert(accum == @["a","b","c"])
+
+  block: # bug #9306
+    doAssert replace("bar", re"^", "foo") == "foobar"
+    doAssert replace("foo", re"$", "bar") == "foobar"
+
+
+  block: # bug #9437
+    doAssert replace("foo", re"", "-") == "-f-o-o-"
+    doAssert replace("ooo", re"o", "-") == "---"
+
+  block: # bug #14468
+    accum = @[]
+    for word in split("this is an example", re"\b"):
+      accum.add(word)
+    doAssert(accum == @["this", " ", "is", " ", "an", " ", "example"])
+
+testAll()
diff --git a/tests/misc/treadln.nim b/tests/stdlib/treadln.nim
index b716c4711..4a070e848 100644
--- a/tests/misc/treadln.nim
+++ b/tests/stdlib/treadln.nim
@@ -6,6 +6,8 @@ Macintosh, Unix or Windows text format.
 '''
 """
 
+import std/syncio
+
 # test the improved readline handling that does not care whether its
 # Macintosh, Unix or Windows text format.
 
@@ -13,7 +15,7 @@ var
   inp: File
   line: string
 
-if open(inp, "tests/misc/treadln.nim"):
+if open(inp, "tests/stdlib/treadln.nim"):
   while not endOfFile(inp):
     line = readLine(inp)
     if line.len >= 2 and line[0] == '#' and line[1] == ' ':
diff --git a/tests/stdlib/tregex.nim b/tests/stdlib/tregex.nim
index 21f4e6743..9dd66cd60 100644
--- a/tests/stdlib/tregex.nim
+++ b/tests/stdlib/tregex.nim
@@ -1,5 +1,6 @@
 discard """
   output: "key: keyAYes!"
+  matrix: "--mm:refc; --mm:orc"
 """
 # Test the new regular expression module
 # which is based on the PCRE library
@@ -11,7 +12,7 @@ when defined(powerpc64):
 else:
   import
     re
-
+  import std/syncio
   if "keyA = valueA" =~ re"\s*(\w+)\s*\=\s*(\w+)":
     write(stdout, "key: ", matches[0])
   elif "# comment!" =~ re.re"\s*(\#.*)":
diff --git a/tests/stdlib/tregistry.nim b/tests/stdlib/tregistry.nim
new file mode 100644
index 000000000..25aed8df8
--- /dev/null
+++ b/tests/stdlib/tregistry.nim
@@ -0,0 +1,16 @@
+discard """
+  disabled: "unix"
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+when defined(windows):
+  import std/registry
+  import std/assertions
+
+  block: # bug #14010
+    let path = "Environment"
+    let key = "D20210328T202842_key"
+    let val = "D20210328T202842_val"
+    let handle = HKEY_CURRENT_USER
+    setUnicodeValue("Environment", key, val, handle)
+    doAssert getUnicodeValue(path, key, handle) == val
diff --git a/tests/stdlib/trepr.nim b/tests/stdlib/trepr.nim
index c1941bd38..3956b98f9 100644
--- a/tests/stdlib/trepr.nim
+++ b/tests/stdlib/trepr.nim
@@ -1,36 +1,328 @@
 discard """
-  output: '''{a, b}{'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'}
-[1, 2, 3, 4, 5, 6]'''
+  targets: "c cpp js"
+  matrix: "--mm:refc;--mm:arc"
 """
 
-type
-  TEnum = enum
-    a, b
-
-var val = {a, b}
-stdout.write(repr(val))
-stdout.writeLine(repr({'a'..'z', 'A'..'Z'}))
-
-type
-  TObj {.pure, inheritable.} = object
-    data: int
-  TFoo = ref object of TObj
-    d2: float
-var foo: TFoo
-new(foo)
-
-when false:
-  # cannot capture this output as it contains a memory address :-/
-  echo foo.repr
-#var testseq: seq[string] = @[
-#  "a", "b", "c", "d", "e"
-#]
-#echo(repr(testseq))
-
-# bug #7878
-proc test(variable: var openarray[int]) =
-  echo repr(variable)
-
-var arr = [1, 2, 3, 4, 5, 6]
-
-test(arr)
+# if excessive, could remove 'cpp' from targets
+
+from strutils import endsWith, contains, strip
+from std/macros import newLit
+import std/assertions
+
+macro deb(a): string = newLit a.repr.strip
+macro debTyped(a: typed): string = newLit a.repr.strip
+
+template main() =
+  doAssert repr({3,5}) == "{3, 5}"
+
+  block:
+    type TEnum = enum a, b
+    var val = {a, b}
+    when nimvm:
+      discard
+      #[
+      # BUG:
+      {0, 1}
+      {97..99, 65..67}
+      ]#
+    else:
+      doAssert repr(val) == "{a, b}"
+      doAssert repr({'a'..'c', 'A'..'C'}) == "{'A', 'B', 'C', 'a', 'b', 'c'}"
+
+    type
+      TObj {.pure, inheritable.} = object
+        data: int
+      TFoo = ref object of TObj
+        d2: float
+    var foo: TFoo
+    new(foo)
+
+  #[
+  BUG:
+  --gc:arc returns `"abc"`
+  regular gc returns with address, e.g. 0x1068aae60"abc", but only
+  for c,cpp backends (not js, vm)
+  ]#
+  block:
+    doAssert repr("abc").endsWith "\"abc\""
+    var b: cstring = "def"
+    doAssert repr(b).endsWith "\"def\""
+
+  block:
+    var c = @[1,2]
+    when nimvm:
+      discard # BUG: this shows [1, 2] instead of @[1, 2]
+    else:
+      # BUG (already mentioned above): some backends / gc show address, others don't
+      doAssert repr(c).endsWith "@[1, 2]"
+
+    let d = @["foo", "bar"]
+    let s = repr(d)
+    # depending on backend/gc, we get 0x106a1c350@[0x106a1c390"foo", 0x106a1c3c0"bar"]
+    doAssert "\"foo\"," in s
+
+  var arr = [1, 2, 3]
+  doAssert repr(arr) == "[1, 2, 3]"
+
+  block: # bug #7878
+    proc reprOpenarray(variable: var openArray[int]): string = repr(variable)
+    when defined(js): discard # BUG: doesn't work
+    else:
+      doAssert reprOpenarray(arr) == "[1, 2, 3]"
+
+  block: # bug #17292 repr with `do`
+    template foo(a, b, c, d) = discard
+    block:
+      let a = deb:
+        foo(1, 2, 3, 4)
+      doAssert a == "foo(1, 2, 3, 4)"
+    block:
+      let a = deb:
+        foo(1, 2, 3): 4
+      doAssert a == """
+foo(1, 2, 3):
+  4"""
+
+    block:
+      let a = deb:
+        foo(1, 2): 3
+        do: 4
+      doAssert a == """
+foo(1, 2):
+  3
+do:
+  4"""
+
+    block:
+      let a = deb:
+        foo(1): 3
+        do: 3
+        do: 4
+      doAssert a == """
+foo(1):
+  3
+do:
+  3
+do:
+  4"""
+
+    block:
+      let a = deb:
+        foo(1):
+          3
+        do:
+          discard
+          3
+        do:
+          discard
+          4
+
+      doAssert a == """
+foo(1):
+  3
+do:
+  discard
+  3
+do:
+  discard
+  4"""
+
+    block:
+      let a = deb:
+        foo: 1
+        do: 2
+        do: 3
+        do: 4
+      doAssert a == """
+foo:
+  1
+do:
+  2
+do:
+  3
+do:
+  4"""
+
+  block: # bug #17292 repr with `(discard)` (`discard` would result in illegal code)
+    let a = deb:
+      let f {.inject.} = () => (discard)
+    doAssert a == """
+let f {.inject.} = () =>
+    (discard )"""
+
+    let a2 = deb:
+      block:
+        discard
+      discard
+
+      block:
+        when true: discard
+
+      # let a = b => discard # illegal
+      discard b => (discard) # legal
+
+      block:
+        return
+    doAssert a2 == """
+block:
+  discard
+discard
+block:
+  when true:
+    discard
+discard b =>
+    (discard )
+block:
+  return"""
+
+  block: # bug #17292 (bug 4)
+    let a = deb:
+      proc `=destroy`() = discard
+      proc `'foo`(): int = discard
+      proc `foo bar baz`(): int = discard
+    let a2 = """
+proc `=destroy`() =
+  discard
+
+proc `'foo`(): int =
+  discard
+
+proc `foo bar baz`(): int =
+  discard"""
+    doAssert a2 == a
+
+  block: # setters: `foo=`
+    let a = deb:
+      proc `foo=`() = discard
+    doAssert a == """
+proc `foo=`() =
+  discard"""
+
+  block: # bug #14850
+    block:
+      let a = deb:
+        template bar(): untyped =
+          foo1:
+            discard
+            4
+          foo2(1):
+            discard
+            4
+          foo3(1):
+            discard
+            4
+          do: 1
+          do: 2
+          x.add foo4
+          x.add: foo5: 3
+          x.add foo6 do: 4
+          a.add(foo7 do:
+            echo "baz"
+            4)
+
+      doAssert a == """
+template bar(): untyped =
+  foo1:
+    discard
+    4
+  foo2(1):
+    discard
+    4
+  foo3(1):
+    discard
+    4
+  do:
+    1
+  do:
+    2
+  x.add foo4
+  x.add:
+    foo5:
+      3
+  x.add foo6 do:
+    4
+  a.add(foo7 do:
+    echo "baz"
+    4)"""
+
+  block: # one liner doc comments
+    let a1 = deb:
+      func fn1(): int = 1  ## comment
+      func fn2(): int = 1
+        ## comment
+    let a2 = debTyped:
+      func fn1(): int = 1  ## comment
+      func fn2(): int = 1
+        ## comment
+    doAssert a1 == """
+func fn1(): int =
+  ## comment
+  1
+
+func fn2(): int =
+  ## comment
+  1"""
+    doAssert a2 == """
+func fn1(): int =
+  ## comment
+  result = 1
+
+func fn2(): int =
+  ## comment
+  result = 1"""
+
+  block: # block calls
+    let a = deb:
+      foo(a, b, (c, d)):
+        e
+        f
+      do: g
+      of h: i
+      elif j: k
+      except m: n
+      do () -> u: v
+      finally: o
+
+      a + b:
+        c
+        d
+      do:
+        e
+        f
+      else: g
+
+      *a: b
+      do: c
+
+    doAssert a == """foo(a, b, (c, d)):
+  e
+  f
+do:
+  g
+of h:
+  i
+elif j:
+  k
+except m:
+  n
+do -> u:
+  v
+finally:
+  o
+a + b:
+  c
+  d
+do:
+  e
+  f
+else:
+  g
+*a:
+  b
+do:
+  c"""
+
+  doAssert repr(1..2) == "1 .. 2"
+
+static: main()
+main()
diff --git a/tests/stdlib/trepr2.nim b/tests/stdlib/trepr2.nim
deleted file mode 100644
index 7b9f9db28..000000000
--- a/tests/stdlib/trepr2.nim
+++ /dev/null
@@ -1,37 +0,0 @@
-discard """
-outputsub: ""
-"""
-
-# output not testable because repr prints pointer addresses
-# test the new "repr" built-in proc
-
-type
-  TEnum = enum
-    en1, en2, en3, en4, en5, en6
-
-  TPoint {.final.} = object
-    x, y, z: int
-    s: array[0..1, string]
-    e: TEnum
-
-var
-  p: TPoint
-  q: ref TPoint
-  s: seq[ref TPoint]
-
-p.x = 0
-p.y = 13
-p.z = 45
-p.s[0] = "abc"
-p.s[1] = "xyz"
-p.e = en6
-
-new(q)
-q[] = p
-
-s = @[q, q, q, q]
-
-writeLine(stdout, repr(p))
-writeLine(stdout, repr(q))
-writeLine(stdout, repr(s))
-writeLine(stdout, repr(en4))
diff --git a/tests/stdlib/trlocks.nim b/tests/stdlib/trlocks.nim
new file mode 100644
index 000000000..135d9b028
--- /dev/null
+++ b/tests/stdlib/trlocks.nim
@@ -0,0 +1,14 @@
+discard """
+  action: "compile"
+  # Disallow joining to ensure it can compile in isolation.
+  # See #15584
+  joinable: false
+  cmd: "nim $target --threads:on $options $file"
+"""
+
+# bugfix #15584
+
+import rlocks
+
+var r: RLock
+r.initRLock()
diff --git a/tests/stdlib/tropes.nim b/tests/stdlib/tropes.nim
new file mode 100644
index 000000000..eb0edc364
--- /dev/null
+++ b/tests/stdlib/tropes.nim
@@ -0,0 +1,104 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import std/ropes
+import std/assertions
+
+template main() =
+  block:
+    let r: Rope = nil
+    doAssert r[0] == '\0'
+    doAssert $r == ""
+
+  block:
+    var
+      r1 = rope("Hello, ")
+      r2 = rope("Nim-Lang")
+
+    let r = r1 & r2
+    let s = $r
+    doAssert s == "Hello, Nim-Lang"
+    for i in 0 ..< r.len:
+      doAssert r[i] == s[i]
+
+    doAssert r[66] == '\0'
+
+  block:
+    let r = rope("Hello, Nim-Lang")
+
+    let s = $r
+    doAssert s == "Hello, Nim-Lang"
+    for i in 0 ..< r.len:
+      doAssert r[i] == s[i]
+
+    doAssert r[66] == '\0'
+
+  block:
+    var r: Rope
+    r.add rope("Nim ")
+    r.add rope("is ")
+    r.add rope("a ")
+    r.add rope("great ")
+    r.add rope("language")
+
+    let s = $r
+    doAssert s == "Nim is a great language"
+    for i in 0 ..< r.len:
+      doAssert r[i] == s[i]
+
+    doAssert r[66] == '\0'
+
+  block:
+    var r: Rope
+    r.add rope("My Conquest")
+    r.add rope(" is ")
+    r.add rope("the Sea of Stars")
+
+    let s = $r
+    doAssert s == "My Conquest is the Sea of Stars"
+    for i in 0 ..< r.len:
+      doAssert r[i] == s[i]
+
+    doAssert r[66] == '\0'
+
+  block:
+    var r: Rope
+    r.add rope("My Conquest")
+    r.add rope(" is ")
+    r.add rope("the Sea of Stars")
+
+    doAssert $r == "My Conquest is the Sea of Stars"
+
+    var i: int
+    for item in r:
+      doAssert r[i] == item
+      inc i
+
+    doAssert r[66] == '\0'
+
+  block:
+    let r1 = "$1 $2 $3" % [rope("Nim"), rope("is"), rope("a great language")]
+    doAssert $r1 == "Nim is a great language"
+
+    let r2 = "$# $# $#" % [rope("Nim"), rope("is"), rope("a great language")]
+    doAssert $r2 == "Nim is a great language"
+
+  block: # `[]`
+    let r1 = rope("Hello, Nim!")
+
+    doAssert r1[-2] == '\0'
+    doAssert r1[0] == 'H'
+    doAssert r1[7] == 'N'
+    doAssert r1[22] == '\0'
+
+    let r2 = rope("Hello") & rope(", Nim!")
+
+    doAssert r2[-2] == '\0'
+    doAssert r2[0] == 'H'
+    doAssert r2[7] == 'N'
+    doAssert r2[22] == '\0'
+
+static: main()
+main()
diff --git a/tests/stdlib/trst.nim b/tests/stdlib/trst.nim
index 6b1bd6897..ceab34bc9 100644
--- a/tests/stdlib/trst.nim
+++ b/tests/stdlib/trst.nim
@@ -1,15 +1,1565 @@
+discard """
+  output: '''
+
+[Suite] RST parsing
+
+[Suite] RST tables
+
+[Suite] RST indentation
+
+[Suite] Markdown indentation
+
+[Suite] Warnings
+
+[Suite] RST include directive
+
+[Suite] RST escaping
+
+[Suite] RST inline markup
+
+[Suite] Misc isssues
+'''
+matrix: "--mm:refc; --mm:orc"
+"""
+
 # tests for rst module
 
-import ../../lib/packages/docutils/rstgen
-import ../../lib/packages/docutils/rst
-import unittest
+import ../../lib/packages/docutils/[rstgen, rst, rstast]
+import unittest, strutils
+import std/private/miscdollars
 import os
+import std/[assertions, syncio]
+
+const preferMarkdown = {roPreferMarkdown, roSupportMarkdown, roNimFile, roSandboxDisabled}
+# legacy nimforum / old default mode:
+const preferRst = {roSupportMarkdown, roNimFile, roSandboxDisabled}
+const pureRst = {roNimFile, roSandboxDisabled}
+
+proc toAst(input: string,
+            rstOptions: RstParseOptions = preferMarkdown,
+            error: ref string = nil,
+            warnings: ref seq[string] = nil): string =
+  ## If `error` is nil then no errors should be generated.
+  ## The same goes for `warnings`.
+  proc testMsgHandler(filename: string, line, col: int, msgkind: MsgKind,
+                      arg: string) =
+    let mc = msgkind.whichMsgClass
+    let a = $msgkind % arg
+    var message: string
+    toLocation(message, filename, line, col + ColRstOffset)
+    message.add " $1: $2" % [$mc, a]
+    if mc == mcError:
+      if error == nil:
+        raise newException(EParseError, "[unexpected error] " & message)
+      error[] = message
+      # we check only first error because subsequent ones may be meaningless
+      raise newException(EParseError, "")
+    else:
+      doAssert warnings != nil, "unexpected RST warning '" & message & "'"
+      warnings[].add message
+  try:
+    const filen = "input"
+
+    proc myFindFile(filename: string): string =
+      # we don't find any files in online mode:
+      result = ""
+
+    var (rst, _, _) = rstParse(input, filen, line=LineRstInit, column=ColRstInit,
+                               rstOptions, myFindFile, nil, testMsgHandler)
+    result = treeRepr(rst)
+  except EParseError as e:
+    if e.msg != "":
+      result = e.msg
+
+suite "RST parsing":
+  test "Standalone punctuation is not parsed as heading overlines":
+    check(dedent"""
+        Paragraph
+
+        !""".toAst ==
+      dedent"""
+        rnInner
+          rnParagraph
+            rnLeaf  'Paragraph'
+          rnParagraph
+            rnLeaf  '!'
+      """)
+
+    check(dedent"""
+        Paragraph1
+
+        ...
+
+        Paragraph2""".toAst ==
+      dedent"""
+        rnInner
+          rnParagraph
+            rnLeaf  'Paragraph1'
+          rnParagraph
+            rnLeaf  '...'
+          rnParagraph
+            rnLeaf  'Paragraph2'
+      """)
+
+    check(dedent"""
+        ---
+        Paragraph""".toAst ==
+      dedent"""
+        rnInner
+          rnLeaf  '---'
+          rnLeaf  ' '
+          rnLeaf  'Paragraph'
+      """)
+
+  test "References are whitespace-neutral and case-insensitive":
+    # refname is 'lexical-analysis', the same for all the 3 variants:
+    check(dedent"""
+        Lexical Analysis
+        ================
+
+        Ref. `Lexical Analysis`_ or `Lexical analysis`_ or `lexical analysis`_.
+        """.toAst ==
+      dedent"""
+        rnInner
+          rnHeadline  level=1  anchor='lexical-analysis'
+            rnLeaf  'Lexical'
+            rnLeaf  ' '
+            rnLeaf  'Analysis'
+          rnParagraph
+            rnLeaf  'Ref'
+            rnLeaf  '.'
+            rnLeaf  ' '
+            rnInternalRef
+              rnInner
+                rnLeaf  'Lexical'
+                rnLeaf  ' '
+                rnLeaf  'Analysis'
+              rnLeaf  'lexical-analysis'
+            rnLeaf  ' '
+            rnLeaf  'or'
+            rnLeaf  ' '
+            rnInternalRef
+              rnInner
+                rnLeaf  'Lexical'
+                rnLeaf  ' '
+                rnLeaf  'analysis'
+              rnLeaf  'lexical-analysis'
+            rnLeaf  ' '
+            rnLeaf  'or'
+            rnLeaf  ' '
+            rnInternalRef
+              rnInner
+                rnLeaf  'lexical'
+                rnLeaf  ' '
+                rnLeaf  'analysis'
+              rnLeaf  'lexical-analysis'
+            rnLeaf  '.'
+            rnLeaf  ' '
+      """)
+
+  test "RST quoted literal blocks":
+    let expected =
+      dedent"""
+        rnInner
+          rnLeaf  'Paragraph'
+          rnLeaf  ':'
+          rnLiteralBlock
+            rnLeaf  '>x'
+        """
+
+    check(dedent"""
+        Paragraph::
+
+        >x""".toAst(rstOptions = preferRst) == expected)
+
+    check(dedent"""
+        Paragraph::
+
+            >x""".toAst(rstOptions = preferRst) == expected)
+
+  test "RST quoted literal blocks, :: at a separate line":
+    let expected =
+      dedent"""
+        rnInner
+          rnInner
+            rnLeaf  'Paragraph'
+          rnLiteralBlock
+            rnLeaf  '>x
+        >>y'
+      """
+
+    check(dedent"""
+        Paragraph
+
+        ::
+
+        >x
+        >>y""".toAst(rstOptions = preferRst) == expected)
+
+    check(dedent"""
+        Paragraph
+
+        ::
+
+          >x
+          >>y""".toAst(rstOptions = preferRst) == expected)
+
+  test "Markdown quoted blocks":
+    check(dedent"""
+        Paragraph.
+        >x""".toAst ==
+      dedent"""
+        rnInner
+          rnLeaf  'Paragraph'
+          rnLeaf  '.'
+          rnMarkdownBlockQuote
+            rnMarkdownBlockQuoteItem  quotationDepth=1
+              rnLeaf  'x'
+      """)
+
+    # bug #17987
+    check(dedent"""
+        foo https://github.com/nim-lang/Nim/issues/8258
+
+        > bar""".toAst ==
+      dedent"""
+        rnInner
+          rnInner
+            rnLeaf  'foo'
+            rnLeaf  ' '
+            rnStandaloneHyperlink
+              rnLeaf  'https://github.com/nim-lang/Nim/issues/8258'
+          rnMarkdownBlockQuote
+            rnMarkdownBlockQuoteItem  quotationDepth=1
+              rnLeaf  'bar'
+      """)
+
+    let expected = dedent"""
+        rnInner
+          rnLeaf  'Paragraph'
+          rnLeaf  '.'
+          rnMarkdownBlockQuote
+            rnMarkdownBlockQuoteItem  quotationDepth=1
+              rnInner
+                rnLeaf  'x1'
+                rnLeaf  ' '
+                rnLeaf  'x2'
+            rnMarkdownBlockQuoteItem  quotationDepth=2
+              rnInner
+                rnLeaf  'y1'
+                rnLeaf  ' '
+                rnLeaf  'y2'
+            rnMarkdownBlockQuoteItem  quotationDepth=1
+              rnLeaf  'z'
+        """
+
+    check(dedent"""
+        Paragraph.
+        >x1 x2
+        >>y1 y2
+        >z""".toAst == expected)
+
+    check(dedent"""
+        Paragraph.
+        > x1 x2
+        >> y1 y2
+        > z""".toAst == expected)
+
+    check(dedent"""
+        >x
+        >y
+        >z""".toAst ==
+      dedent"""
+        rnMarkdownBlockQuote
+          rnMarkdownBlockQuoteItem  quotationDepth=1
+            rnInner
+              rnLeaf  'x'
+              rnLeaf  ' '
+              rnLeaf  'y'
+              rnLeaf  ' '
+              rnLeaf  'z'
+      """)
+
+    check(dedent"""
+        > z
+        > > >y
+        """.toAst ==
+      dedent"""
+        rnMarkdownBlockQuote
+          rnMarkdownBlockQuoteItem  quotationDepth=1
+            rnLeaf  'z'
+          rnMarkdownBlockQuoteItem  quotationDepth=3
+            rnLeaf  'y'
+        """)
+
+  test "Markdown quoted blocks: lazy":
+    let expected = dedent"""
+        rnInner
+          rnMarkdownBlockQuote
+            rnMarkdownBlockQuoteItem  quotationDepth=2
+              rnInner
+                rnLeaf  'x'
+                rnLeaf  ' '
+                rnLeaf  'continuation1'
+                rnLeaf  ' '
+                rnLeaf  'continuation2'
+          rnParagraph
+            rnLeaf  'newParagraph'
+      """
+    check(dedent"""
+        >>x
+        continuation1
+        continuation2
+
+        newParagraph""".toAst == expected)
+
+    check(dedent"""
+        >> x
+        continuation1
+        continuation2
+
+        newParagraph""".toAst == expected)
+
+    # however mixing more than 1 non-lazy line and lazy one(s) splits quote
+    # in our parser, which appeared the easiest way to handle such cases:
+    var warnings = new seq[string]
+    check(dedent"""
+        >> x
+        >> continuation1
+        continuation2
+
+        newParagraph""".toAst(warnings=warnings) ==
+      dedent"""
+        rnInner
+          rnMarkdownBlockQuote
+            rnMarkdownBlockQuoteItem  quotationDepth=2
+              rnLeaf  'x'
+            rnMarkdownBlockQuoteItem  quotationDepth=2
+              rnInner
+                rnLeaf  'continuation1'
+                rnLeaf  ' '
+                rnLeaf  'continuation2'
+          rnParagraph
+            rnLeaf  'newParagraph'
+        """)
+    check(warnings[] == @[
+        "input(2, 1) Warning: RST style: two or more quoted lines " &
+        "are followed by unquoted line 3"])
+
+  test "Markdown quoted blocks: not lazy":
+    # here is where we deviate from CommonMark specification: 'bar' below is
+    # not considered as continuation of 2-level '>> foo' quote.
+    check(dedent"""
+        >>> foo
+        > bar
+        >> baz
+        """.toAst() ==
+      dedent"""
+        rnMarkdownBlockQuote
+          rnMarkdownBlockQuoteItem  quotationDepth=3
+            rnLeaf  'foo'
+          rnMarkdownBlockQuoteItem  quotationDepth=1
+            rnLeaf  'bar'
+          rnMarkdownBlockQuoteItem  quotationDepth=2
+            rnLeaf  'baz'
+        """)
+
+
+  test "Markdown quoted blocks: inline markup works":
+    check(dedent"""
+        > hi **bold** text
+        """.toAst == dedent"""
+          rnMarkdownBlockQuote
+            rnMarkdownBlockQuoteItem  quotationDepth=1
+              rnInner
+                rnLeaf  'hi'
+                rnLeaf  ' '
+                rnStrongEmphasis
+                  rnLeaf  'bold'
+                rnLeaf  ' '
+                rnLeaf  'text'
+        """)
+
+  test "Markdown quoted blocks: blank line separator":
+    let expected = dedent"""
+      rnInner
+        rnMarkdownBlockQuote
+          rnMarkdownBlockQuoteItem  quotationDepth=1
+            rnInner
+              rnLeaf  'x'
+              rnLeaf  ' '
+              rnLeaf  'y'
+        rnMarkdownBlockQuote
+          rnMarkdownBlockQuoteItem  quotationDepth=1
+            rnInner
+              rnLeaf  'z'
+              rnLeaf  ' '
+              rnLeaf  't'
+      """
+    check(dedent"""
+        >x
+        >y
+
+        > z
+        > t""".toAst == expected)
+
+    check(dedent"""
+        >x
+        y
+
+        > z
+         t""".toAst == expected)
+
+  test "Markdown quoted blocks: nested body blocks/elements work #1":
+    let expected = dedent"""
+      rnMarkdownBlockQuote
+        rnMarkdownBlockQuoteItem  quotationDepth=1
+          rnBulletList
+            rnBulletItem
+              rnInner
+                rnLeaf  'x'
+            rnBulletItem
+              rnInner
+                rnLeaf  'y'
+      """
+
+    check(dedent"""
+        > - x
+          - y
+        """.toAst == expected)
+
+    # TODO: if bug #17340 point 28 is resolved then this may work:
+    # check(dedent"""
+    #     > - x
+    #     - y
+    #     """.toAst == expected)
+
+    check(dedent"""
+        > - x
+        > - y
+        """.toAst == expected)
+
+    check(dedent"""
+        >
+        > - x
+        >
+        > - y
+        >
+        """.toAst == expected)
+
+  test "Markdown quoted blocks: nested body blocks/elements work #2":
+    let expected = dedent"""
+      rnAdmonition  adType=note
+        [nil]
+        [nil]
+        rnDefList
+          rnDefItem
+            rnDefName
+              rnLeaf  'deflist'
+              rnLeaf  ':'
+            rnDefBody
+              rnMarkdownBlockQuote
+                rnMarkdownBlockQuoteItem  quotationDepth=2
+                  rnInner
+                    rnLeaf  'quote'
+                    rnLeaf  ' '
+                    rnLeaf  'continuation'
+      """
+
+    check(dedent"""
+        .. Note:: deflist:
+                    >> quote
+                    continuation
+        """.toAst(rstOptions = preferRst) == expected)
+
+    check(dedent"""
+        .. Note::
+           deflist:
+             >> quote
+             continuation
+        """.toAst(rstOptions = preferRst) == expected)
+
+    check(dedent"""
+        .. Note::
+           deflist:
+             >> quote
+             >> continuation
+        """.toAst(rstOptions = preferRst) == expected)
+
+    # spaces are not significant between `>`:
+    check(dedent"""
+        .. Note::
+           deflist:
+             > > quote
+             > > continuation
+        """.toAst(rstOptions = preferRst) == expected)
+
+  test "Markdown quoted blocks: de-indent handled well":
+    check(dedent"""
+        >
+        >   - x
+        >   - y
+        >
+        > Paragraph.
+        """.toAst(rstOptions = preferRst) == dedent"""
+          rnMarkdownBlockQuote
+            rnMarkdownBlockQuoteItem  quotationDepth=1
+              rnInner
+                rnBlockQuote
+                  rnBulletList
+                    rnBulletItem
+                      rnInner
+                        rnLeaf  'x'
+                    rnBulletItem
+                      rnInner
+                        rnLeaf  'y'
+                rnParagraph
+                  rnLeaf  'Paragraph'
+                  rnLeaf  '.'
+          """)
+
+  let expectCodeBlock = dedent"""
+      rnCodeBlock
+        [nil]
+        rnFieldList
+          rnField
+            rnFieldName
+              rnLeaf  'default-language'
+            rnFieldBody
+              rnLeaf  'Nim'
+        rnLiteralBlock
+          rnLeaf  'let a = 1
+      ```'
+      """
+
+  test "Markdown footnotes":
+    # Testing also 1) correct order of manually-numbered and automatically-
+    # numbered footnotes; 2) no spaces between references (html & 3 below):
+
+    check(dedent"""
+        Paragraph [^1] [^html-hyphen][^3] and [^latex]
+
+        [^1]: footnote1
+
+        [^html-hyphen]: footnote2
+           continuation2
+
+        [^latex]: footnote4
+
+        [^3]: footnote3
+            continuation3
+        """.toAst ==
+      dedent"""
+        rnInner
+          rnInner
+            rnLeaf  'Paragraph'
+            rnLeaf  ' '
+            rnFootnoteRef
+              rnInner
+                rnLeaf  '1'
+              rnLeaf  'footnote-1'
+            rnLeaf  ' '
+            rnFootnoteRef
+              rnInner
+                rnLeaf  '2'
+              rnLeaf  'footnote-htmlminushyphen'
+            rnFootnoteRef
+              rnInner
+                rnLeaf  '3'
+              rnLeaf  'footnote-3'
+            rnLeaf  ' '
+            rnLeaf  'and'
+            rnLeaf  ' '
+            rnFootnoteRef
+              rnInner
+                rnLeaf  '4'
+              rnLeaf  'footnote-latex'
+          rnFootnoteGroup
+            rnFootnote  anchor='footnote-1'
+              rnInner
+                rnLeaf  '1'
+              rnLeaf  'footnote1'
+            rnFootnote  anchor='footnote-htmlminushyphen'
+              rnInner
+                rnLeaf  '2'
+              rnInner
+                rnLeaf  'footnote2'
+                rnLeaf  ' '
+                rnLeaf  'continuation2'
+            rnFootnote  anchor='footnote-latex'
+              rnInner
+                rnLeaf  '4'
+              rnLeaf  'footnote4'
+            rnFootnote  anchor='footnote-3'
+              rnInner
+                rnLeaf  '3'
+              rnInner
+                rnLeaf  'footnote3'
+                rnLeaf  ' '
+                rnLeaf  'continuation3'
+      """)
+
+  test "Markdown code blocks with more > 3 backticks":
+    check(dedent"""
+        ````
+        let a = 1
+        ```
+        ````""".toAst == expectCodeBlock)
+
+  test "Markdown code blocks with ~~~":
+    check(dedent"""
+        ~~~
+        let a = 1
+        ```
+        ~~~""".toAst == expectCodeBlock)
+    check(dedent"""
+        ~~~~~
+        let a = 1
+        ```
+        ~~~~~""".toAst == expectCodeBlock)
+
+  test "Markdown code blocks with Nim-specific arguments":
+    check(dedent"""
+        ```nim number-lines=1 test
+        let a = 1
+        ```""".toAst ==
+      dedent"""
+        rnCodeBlock
+          rnDirArg
+            rnLeaf  'nim'
+          rnFieldList
+            rnField
+              rnFieldName
+                rnLeaf  'number-lines'
+              rnFieldBody
+                rnLeaf  '1'
+            rnField
+              rnFieldName
+                rnLeaf  'test'
+              rnFieldBody
+          rnLiteralBlock
+            rnLeaf  'let a = 1'
+        """)
+
+    check(dedent"""
+        ```nim test = "nim c $1"  number-lines = 1
+        let a = 1
+        ```""".toAst ==
+      dedent"""
+        rnCodeBlock
+          rnDirArg
+            rnLeaf  'nim'
+          rnFieldList
+            rnField
+              rnFieldName
+                rnLeaf  'test'
+              rnFieldBody
+                rnLeaf  '"nim c $1"'
+            rnField
+              rnFieldName
+                rnLeaf  'number-lines'
+              rnFieldBody
+                rnLeaf  '1'
+          rnLiteralBlock
+            rnLeaf  'let a = 1'
+        """)
+
+  test "additional indentation < 4 spaces is handled fine":
+    check(dedent"""
+        Indentation
+
+          ```nim
+            let a = 1
+          ```""".toAst ==
+      dedent"""
+        rnInner
+          rnParagraph
+            rnLeaf  'Indentation'
+          rnParagraph
+            rnCodeBlock
+              rnDirArg
+                rnLeaf  'nim'
+              [nil]
+              rnLiteralBlock
+                rnLeaf  '  let a = 1'
+      """)
+      # | |
+      # |  \ indentation of exactly two spaces before 'let a = 1'
+
+  test "no blank line is required before or after Markdown code block":
+    let inputBacktick = dedent"""
+        Some text
+        ```
+        CodeBlock()
+        ```
+        Other text"""
+    let inputTilde = dedent"""
+        Some text
+        ~~~~~~~~~
+        CodeBlock()
+        ~~~~~~~~~
+        Other text"""
+    let expected = dedent"""
+        rnInner
+          rnParagraph
+            rnLeaf  'Some'
+            rnLeaf  ' '
+            rnLeaf  'text'
+          rnParagraph
+            rnCodeBlock
+              [nil]
+              rnFieldList
+                rnField
+                  rnFieldName
+                    rnLeaf  'default-language'
+                  rnFieldBody
+                    rnLeaf  'Nim'
+              rnLiteralBlock
+                rnLeaf  'CodeBlock()'
+            rnLeaf  ' '
+            rnLeaf  'Other'
+            rnLeaf  ' '
+            rnLeaf  'text'
+      """
+    check inputBacktick.toAst == expected
+    check inputTilde.toAst == expected
+
+  test "option list has priority over definition list":
+    for opt in [preferMarkdown, preferRst]:
+      check(dedent"""
+          --defusages
+                        file
+          -o            set
+          """.toAst(rstOptions = opt) ==
+        dedent"""
+          rnOptionList
+            rnOptionListItem  order=1
+              rnOptionGroup
+                rnLeaf  '--'
+                rnLeaf  'defusages'
+              rnDescription
+                rnInner
+                  rnLeaf  'file'
+            rnOptionListItem  order=2
+              rnOptionGroup
+                rnLeaf  '-'
+                rnLeaf  'o'
+              rnDescription
+                rnLeaf  'set'
+          """)
+
+  test "items of 1 option list can be separated by blank lines":
+    check(dedent"""
+        -a  desc1
+
+        -b  desc2
+        """.toAst ==
+      dedent"""
+        rnOptionList
+          rnOptionListItem  order=1
+            rnOptionGroup
+              rnLeaf  '-'
+              rnLeaf  'a'
+            rnDescription
+              rnLeaf  'desc1'
+          rnOptionListItem  order=2
+            rnOptionGroup
+              rnLeaf  '-'
+              rnLeaf  'b'
+            rnDescription
+              rnLeaf  'desc2'
+      """)
+
+  test "definition list does not gobble up the following blocks":
+    check(dedent"""
+        defName
+            defBody
+
+        -b  desc2
+        """.toAst(rstOptions = preferRst) ==
+      dedent"""
+        rnInner
+          rnDefList
+            rnDefItem
+              rnDefName
+                rnLeaf  'defName'
+              rnDefBody
+                rnInner
+                  rnLeaf  'defBody'
+          rnOptionList
+            rnOptionListItem  order=1
+              rnOptionGroup
+                rnLeaf  '-'
+                rnLeaf  'b'
+              rnDescription
+                rnLeaf  'desc2'
+      """)
+
+  test "definition lists work correctly with additional indentation in Markdown":
+    check(dedent"""
+        Paragraph:
+          -c  desc1
+          -b  desc2
+        """.toAst() ==
+      dedent"""
+        rnInner
+          rnInner
+            rnLeaf  'Paragraph'
+            rnLeaf  ':'
+          rnOptionList
+            rnOptionListItem  order=1
+              rnOptionGroup
+                rnLeaf  '-'
+                rnLeaf  'c'
+              rnDescription
+                rnLeaf  'desc1'
+            rnOptionListItem  order=2
+              rnOptionGroup
+                rnLeaf  '-'
+                rnLeaf  'b'
+              rnDescription
+                rnLeaf  'desc2'
+      """)
+
+  test "RST comment":
+    check(dedent"""
+        .. comment1
+         comment2
+        someParagraph""".toAst ==
+      dedent"""
+        rnLeaf  'someParagraph'
+        """)
+
+    check(dedent"""
+        ..
+         comment1
+         comment2
+        someParagraph""".toAst ==
+      dedent"""
+        rnLeaf  'someParagraph'
+        """)
+
+  test "check that additional line right after .. ends comment":
+    check(dedent"""
+        ..
+
+         notAcomment1
+         notAcomment2
+        someParagraph""".toAst(rstOptions = preferRst) ==
+      dedent"""
+        rnInner
+          rnBlockQuote
+            rnInner
+              rnLeaf  'notAcomment1'
+              rnLeaf  ' '
+              rnLeaf  'notAcomment2'
+          rnParagraph
+            rnLeaf  'someParagraph'
+        """)
+
+  test "check that additional line right after .. ends comment (Markdown mode)":
+    # in Markdown small indentation does not matter so this should
+    # just be split to 2 paragraphs.
+    check(dedent"""
+        ..
+
+         notAcomment1
+         notAcomment2
+        someParagraph""".toAst ==
+      dedent"""
+        rnInner
+          rnInner
+            rnLeaf  'notAcomment1'
+            rnLeaf  ' '
+            rnLeaf  'notAcomment2'
+          rnParagraph
+            rnLeaf  'someParagraph'
+        """)
+
+  test "but blank lines after 2nd non-empty line don't end the comment":
+    check(dedent"""
+        ..
+           comment1
+
+
+         comment2
+        someParagraph""".toAst ==
+      dedent"""
+        rnLeaf  'someParagraph'
+        """)
+
+  test "using .. as separator b/w directives and block quotes":
+    check(dedent"""
+        .. note:: someNote
+
+        ..
+
+          someBlockQuote""".toAst(rstOptions = preferRst) ==
+      dedent"""
+        rnInner
+          rnAdmonition  adType=note
+            [nil]
+            [nil]
+            rnLeaf  'someNote'
+          rnBlockQuote
+            rnInner
+              rnLeaf  'someBlockQuote'
+        """)
+
+  test "no redundant blank lines in literal blocks":
+    check(dedent"""
+      Check::
+
+
+        code
+
+      """.toAst(rstOptions = preferRst) ==
+      dedent"""
+        rnInner
+          rnLeaf  'Check'
+          rnLeaf  ':'
+          rnLiteralBlock
+            rnLeaf  'code'
+      """)
+
+  test "Markdown indented code blocks":
+    check(dedent"""
+      See
+
+          some code""".toAst ==
+      dedent"""
+        rnInner
+          rnInner
+            rnLeaf  'See'
+          rnLiteralBlock
+            rnLeaf  'some code'
+      """)
+
+    # not a code block -- no blank line before:
+    check(dedent"""
+      See
+          some code""".toAst ==
+      dedent"""
+        rnInner
+          rnLeaf  'See'
+          rnLeaf  ' '
+          rnLeaf  'some'
+          rnLeaf  ' '
+          rnLeaf  'code'
+      """)
+
+suite "RST tables":
+
+  test "formatting in tables works":
+    check(
+      dedent"""
+        =========  ===
+        `build`    `a`
+        =========  ===
+        """.toAst ==
+      dedent"""
+        rnTable  colCount=2
+          rnTableRow
+            rnTableDataCell
+              rnInlineCode
+                rnDirArg
+                  rnLeaf  'nim'
+                [nil]
+                rnLiteralBlock
+                  rnLeaf  'build'
+            rnTableDataCell
+              rnInlineCode
+                rnDirArg
+                  rnLeaf  'nim'
+                [nil]
+                rnLiteralBlock
+                  rnLeaf  'a'
+      """)
+
+  test "tables with slightly overflowed cells cause an error (1)":
+    var error = new string
+    check(
+      dedent"""
+        ======   ======
+         Inputs  Output
+        ======   ======
+        """.toAst(rstOptions = pureRst, error = error) == "")
+    check(error[] == "input(2, 2) Error: Illformed table: " &
+                     "this word crosses table column from the right")
+
+    # In nimforum compatibility mode & Markdown we raise a warning instead:
+    let expected = dedent"""
+      rnTable  colCount=2
+        rnTableRow
+          rnTableDataCell
+            rnLeaf  'Inputs'
+          rnTableDataCell
+            rnLeaf  'Output'
+      """
+    for opt in [preferRst, preferMarkdown]:
+      var warnings = new seq[string]
+
+      check(
+        dedent"""
+          ======   ======
+           Inputs  Output
+          ======   ======
+          """.toAst(rstOptions = opt, warnings = warnings) == expected)
+      check(warnings[] == @[
+        "input(2, 2) Warning: RST style: this word crosses table column from the right"])
+
+  test "tables with slightly overflowed cells cause an error (2)":
+    var error = new string
+    check("" == dedent"""
+      =====  =====  ======
+      Input  Output
+      =====  =====  ======
+      False  False  False
+      =====  =====  ======
+      """.toAst(rstOptions = pureRst, error = error))
+    check(error[] == "input(2, 8) Error: Illformed table: " &
+                     "this word crosses table column from the right")
+
+  test "tables with slightly underflowed cells cause an error":
+    var error = new string
+    check("" == dedent"""
+      =====  =====  ======
+      Input Output
+      =====  =====  ======
+      False  False  False
+      =====  =====  ======
+      """.toAst(rstOptions = pureRst, error = error))
+    check(error[] == "input(2, 7) Error: Illformed table: " &
+                     "this word crosses table column from the left")
+
+  test "tables with unequal underlines should be reported (1)":
+    var error = new string
+    error[] = "none"
+    check("" == dedent"""
+      =====  ======
+      Input  Output
+      =====  ======
+      False  False
+      =====  =======
+      """.toAst(rstOptions = pureRst, error = error))
+    check(error[] == "input(5, 14) Error: Illformed table: " &
+                     "end of table column #2 should end at position 13")
+
+  test "tables with unequal underlines should be reported (2)":
+    var error = new string
+    check("" == dedent"""
+      =====  ======
+      Input  Output
+      =====  =======
+      False  False
+      =====  ======
+      """.toAst(rstOptions = pureRst, error = error))
+    check(error[] == "input(3, 14) Error: Illformed table: " &
+                     "end of table column #2 should end at position 13")
+
+  test "tables with empty first cells":
+    check(
+      dedent"""
+          = = =
+          x y z
+              t
+          = = =
+          """.toAst ==
+      dedent"""
+        rnTable  colCount=3
+          rnTableRow
+            rnTableDataCell
+              rnLeaf  'x'
+            rnTableDataCell
+              rnInner
+                rnLeaf  'y'
+                rnLeaf  ' '
+            rnTableDataCell
+              rnInner
+                rnLeaf  'z'
+                rnLeaf  ' '
+                rnLeaf  't'
+        """)
+
+  test "tables with spanning cells & separators":
+    check(
+      dedent"""
+        =====  =====  ======
+           Inputs     Output
+        ------------  ------
+          A      B    A or B
+        =====  =====  ======
+        False  False  False
+        True   False  True
+        -----  -----  ------
+        False  True   True
+        True   True   True
+        =====  =====  ======
+        """.toAst ==
+      dedent"""
+        rnTable  colCount=3
+          rnTableRow
+            rnTableHeaderCell  span=2
+              rnLeaf  'Inputs'
+            rnTableHeaderCell  span=1
+              rnLeaf  'Output'
+          rnTableRow  endsHeader
+            rnTableHeaderCell
+              rnLeaf  'A'
+            rnTableHeaderCell
+              rnLeaf  'B'
+            rnTableHeaderCell
+              rnInner
+                rnLeaf  'A'
+                rnLeaf  ' '
+                rnLeaf  'or'
+                rnLeaf  ' '
+                rnLeaf  'B'
+          rnTableRow
+            rnTableDataCell
+              rnLeaf  'False'
+            rnTableDataCell
+              rnLeaf  'False'
+            rnTableDataCell
+              rnLeaf  'False'
+          rnTableRow
+            rnTableDataCell  span=1
+              rnLeaf  'True'
+            rnTableDataCell  span=1
+              rnLeaf  'False'
+            rnTableDataCell  span=1
+              rnLeaf  'True'
+          rnTableRow
+            rnTableDataCell
+              rnLeaf  'False'
+            rnTableDataCell
+              rnLeaf  'True'
+            rnTableDataCell
+              rnLeaf  'True'
+          rnTableRow
+            rnTableDataCell
+              rnLeaf  'True'
+            rnTableDataCell
+              rnLeaf  'True'
+            rnTableDataCell
+              rnLeaf  'True'
+      """)
+
+  test "tables with spanning cells with uneqal underlines cause an error":
+    var error = new string
+    check(
+      dedent"""
+        =====  =====  ======
+           Inputs     Output
+        ------------- ------
+          A      B    A or B
+        =====  =====  ======
+        """.toAst(error=error) == "")
+    check(error[] == "input(3, 1) Error: Illformed table: " &
+                     "spanning underline does not match main table columns")
+
+  let expTable = dedent"""
+      rnTable  colCount=2
+        rnTableRow
+          rnTableDataCell
+            rnLeaf  'Inputs'
+          rnTableDataCell
+            rnLeaf  'Output'
+      """
+
+  test "only tables with `=` columns specs are allowed (1)":
+    var warnings = new seq[string]
+    check(
+      dedent"""
+        ------  ------
+        Inputs  Output
+        ------  ------
+        """.toAst(warnings=warnings) ==
+      expTable)
+    check(warnings[] ==
+          @["input(1, 1) Warning: RST style: " &
+              "only tables with `=` columns specification are allowed",
+            "input(3, 1) Warning: RST style: " &
+              "only tables with `=` columns specification are allowed"])
+
+  test "only tables with `=` columns specs are allowed (2)":
+    var warnings = new seq[string]
+    check(
+      dedent"""
+        ======  ======
+        Inputs  Output
+        ~~~~~~  ~~~~~~
+        """.toAst(warnings=warnings) ==
+      expTable)
+    check(warnings[] ==
+          @["input(3, 1) Warning: RST style: "&
+              "only tables with `=` columns specification are allowed"])
+
+
+suite "RST indentation":
+  test "nested bullet lists":
+    let input = dedent """
+      * - bullet1
+        - bullet2
+      * - bullet3
+        - bullet4
+      """
+    let output = input.toAst
+    check(output == dedent"""
+      rnBulletList
+        rnBulletItem
+          rnBulletList
+            rnBulletItem
+              rnInner
+                rnLeaf  'bullet1'
+            rnBulletItem
+              rnInner
+                rnLeaf  'bullet2'
+        rnBulletItem
+          rnBulletList
+            rnBulletItem
+              rnInner
+                rnLeaf  'bullet3'
+            rnBulletItem
+              rnInner
+                rnLeaf  'bullet4'
+      """)
+
+  test "nested markup blocks":
+    let input = dedent"""
+      #) .. Hint:: .. Error:: none
+      #) .. Warning:: term0
+                        Definition0
+      #) some
+         paragraph1
+      #) term1
+           Definition1
+         term2
+           Definition2
+    """
+    check(input.toAst(rstOptions = preferRst) == dedent"""
+      rnEnumList  labelFmt=1)
+        rnEnumItem
+          rnAdmonition  adType=hint
+            [nil]
+            [nil]
+            rnAdmonition  adType=error
+              [nil]
+              [nil]
+              rnLeaf  'none'
+        rnEnumItem
+          rnAdmonition  adType=warning
+            [nil]
+            [nil]
+            rnDefList
+              rnDefItem
+                rnDefName
+                  rnLeaf  'term0'
+                rnDefBody
+                  rnInner
+                    rnLeaf  'Definition0'
+        rnEnumItem
+          rnInner
+            rnLeaf  'some'
+            rnLeaf  ' '
+            rnLeaf  'paragraph1'
+        rnEnumItem
+          rnDefList
+            rnDefItem
+              rnDefName
+                rnLeaf  'term1'
+              rnDefBody
+                rnInner
+                  rnLeaf  'Definition1'
+            rnDefItem
+              rnDefName
+                rnLeaf  'term2'
+              rnDefBody
+                rnInner
+                  rnLeaf  'Definition2'
+      """)
+
+  test "code-block parsing":
+    let input1 = dedent"""
+      .. code-block:: nim
+          :test: "nim c $1"
+
+        template additive(typ: typedesc) =
+          discard
+      """
+    let input2 = dedent"""
+      .. code-block:: nim
+        :test: "nim c $1"
+
+        template additive(typ: typedesc) =
+          discard
+      """
+    let input3 = dedent"""
+      .. code-block:: nim
+         :test: "nim c $1"
+         template additive(typ: typedesc) =
+           discard
+      """
+    let inputWrong = dedent"""
+      .. code-block:: nim
+       :test: "nim c $1"
+
+         template additive(typ: typedesc) =
+           discard
+      """
+    let ast = dedent"""
+      rnCodeBlock
+        rnDirArg
+          rnLeaf  'nim'
+        rnFieldList
+          rnField
+            rnFieldName
+              rnLeaf  'test'
+            rnFieldBody
+              rnInner
+                rnLeaf  '"'
+                rnLeaf  'nim'
+                rnLeaf  ' '
+                rnLeaf  'c'
+                rnLeaf  ' '
+                rnLeaf  '$'
+                rnLeaf  '1'
+                rnLeaf  '"'
+          rnField
+            rnFieldName
+              rnLeaf  'default-language'
+            rnFieldBody
+              rnLeaf  'Nim'
+        rnLiteralBlock
+          rnLeaf  'template additive(typ: typedesc) =
+        discard'
+      """
+    check input1.toAst == ast
+    check input2.toAst == ast
+    check input3.toAst == ast
+    # "template..." should be parsed as a definition list attached to ":test:":
+    check inputWrong.toAst != ast
+
+  test "Markdown definition lists work in conjunction with bullet lists":
+    check(dedent"""
+        * some term
+          : the definition
+
+        Paragraph.""".toAst ==
+      dedent"""
+        rnInner
+          rnBulletList
+            rnBulletItem
+              rnMdDefList
+                rnDefItem
+                  rnDefName
+                    rnLeaf  'some'
+                    rnLeaf  ' '
+                    rnLeaf  'term'
+                  rnDefBody
+                    rnInner
+                      rnLeaf  'the'
+                      rnLeaf  ' '
+                      rnLeaf  'definition'
+          rnParagraph
+            rnLeaf  'Paragraph'
+            rnLeaf  '.'
+      """)
+
+  test "Markdown definition lists work with blank lines and extra paragraphs":
+    check(dedent"""
+        Term1
+
+        :   Definition1
+
+        Term2 *inline markup*
+
+        :   Definition2
+
+            Paragraph2
+
+        Term3
+        : * point1
+          * point2
+        : term3definition2
+      """.toAst == dedent"""
+        rnMdDefList
+          rnDefItem
+            rnDefName
+              rnLeaf  'Term1'
+            rnDefBody
+              rnInner
+                rnLeaf  'Definition1'
+          rnDefItem
+            rnDefName
+              rnLeaf  'Term2'
+              rnLeaf  ' '
+              rnEmphasis
+                rnLeaf  'inline'
+                rnLeaf  ' '
+                rnLeaf  'markup'
+            rnDefBody
+              rnParagraph
+                rnLeaf  'Definition2'
+              rnParagraph
+                rnLeaf  'Paragraph2'
+          rnDefItem
+            rnDefName
+              rnLeaf  'Term3'
+            rnDefBody
+              rnBulletList
+                rnBulletItem
+                  rnInner
+                    rnLeaf  'point1'
+                rnBulletItem
+                  rnInner
+                    rnLeaf  'point2'
+            rnDefBody
+              rnInner
+                rnLeaf  'term3definition2'
+      """)
+
+suite "Markdown indentation":
+  test "Markdown paragraph indentation":
+    # Additional spaces (<=3) of indentation does not break the paragraph.
+    # TODO: in 2nd case de-indentation causes paragraph to break, this is
+    # reasonable but does not seem to conform the Markdown spec.
+    check(dedent"""
+      Start1
+        stop1
+
+        Start2
+      stop2
+      """.toAst ==
+      dedent"""
+        rnInner
+          rnParagraph
+            rnLeaf  'Start1'
+            rnLeaf  ' '
+            rnLeaf  'stop1'
+          rnParagraph
+            rnLeaf  'Start2'
+          rnParagraph
+            rnLeaf  'stop2'
+            rnLeaf  ' '
+      """)
+
+suite "Warnings":
+  test "warnings for broken footnotes/links/substitutions":
+    let input = dedent"""
+      firstParagraph
+
+      footnoteRef [som]_
+
+      link `a broken Link`_
+
+      substitution |undefined subst|
+
+      link short.link_
+
+      lastParagraph
+      """
+    var warnings = new seq[string]
+    let output = input.toAst(rstOptions=preferRst, warnings=warnings)
+    check(warnings[] == @[
+        "input(3, 14) Warning: broken link 'citation-som'",
+        "input(5, 7) Warning: broken link 'a broken Link'",
+        "input(7, 15) Warning: unknown substitution 'undefined subst'",
+        "input(9, 6) Warning: broken link 'short.link'"
+        ])
+
+  test "Pandoc Markdown concise link warning points to target":
+    var warnings = new seq[string]
+    check(
+      "ref [here][target]".toAst(warnings=warnings) ==
+      dedent"""
+        rnInner
+          rnLeaf  'ref'
+          rnLeaf  ' '
+          rnPandocRef
+            rnInner
+              rnLeaf  'here'
+            rnInner
+              rnLeaf  'target'
+      """)
+    check warnings[] == @["input(1, 12) Warning: broken link 'target'"]
+
+  test "With include directive and blank lines at the beginning":
+    "other.rst".writeFile(dedent"""
+
+
+        firstParagraph
+
+        here brokenLink_""")
+    let input = ".. include:: other.rst"
+    var warnings = new seq[string]
+    let output = input.toAst(warnings=warnings)
+    check warnings[] == @["other.rst(5, 6) Warning: broken link 'brokenLink'"]
+    check(output == dedent"""
+      rnInner
+        rnParagraph
+          rnLeaf  'firstParagraph'
+        rnParagraph
+          rnLeaf  'here'
+          rnLeaf  ' '
+          rnRstRef
+            rnLeaf  'brokenLink'
+      """)
+    removeFile("other.rst")
+
+  test "warnings for ambiguous links (references + anchors)":
+    # Reference like `x`_ generates a link alias x that may clash with others
+    let input = dedent"""
+      Manual reference: `foo <#foo,string,string>`_
+
+      .. _foo:
+
+      Paragraph.
+
+      Ref foo_
+      """
+    var warnings = new seq[string]
+    let output = input.toAst(warnings=warnings)
+    check(warnings[] == @[
+      dedent """
+      input(7, 5) Warning: ambiguous doc link `foo`
+        clash:
+          (3, 8): (manual directive anchor)
+          (1, 45): (implicitly-generated hyperlink alias)"""
+    ])
+    # reference should be resolved to the manually set anchor:
+    check(output ==
+      dedent"""
+        rnInner
+          rnParagraph
+            rnLeaf  'Manual'
+            rnLeaf  ' '
+            rnLeaf  'reference'
+            rnLeaf  ':'
+            rnLeaf  ' '
+            rnHyperlink
+              rnInner
+                rnLeaf  'foo'
+              rnInner
+                rnLeaf  '#foo,string,string'
+          rnParagraph  anchor='foo'
+            rnLeaf  'Paragraph'
+            rnLeaf  '.'
+          rnParagraph
+            rnLeaf  'Ref'
+            rnLeaf  ' '
+            rnInternalRef
+              rnInner
+                rnLeaf  'foo'
+              rnLeaf  'foo'
+            rnLeaf  ' '
+      """)
 
 suite "RST include directive":
   test "Include whole":
     "other.rst".writeFile("**test1**")
     let input = ".. include:: other.rst"
-    assert "<strong>test1</strong>" == rstTohtml(input, {}, defaultConfig())
+    doAssert "<strong>test1</strong>" == rstToHtml(input, {roSandboxDisabled}, defaultConfig())
     removeFile("other.rst")
 
   test "Include starting from":
@@ -23,7 +1573,7 @@ OtherStart
 .. include:: other.rst
              :start-after: OtherStart
 """
-    assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
+    check "<em>Visible</em>" == rstToHtml(input, {roSandboxDisabled}, defaultConfig())
     removeFile("other.rst")
 
   test "Include everything before":
@@ -37,7 +1587,7 @@ And this should **NOT** be visible in `docs.html`
 .. include:: other.rst
              :end-before: OtherEnd
 """
-    assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
+    doAssert "<em>Visible</em>" == rstToHtml(input, {roSandboxDisabled}, defaultConfig())
     removeFile("other.rst")
 
 
@@ -55,7 +1605,7 @@ And this should **NOT** be visible in `docs.html`
              :start-after: OtherStart
              :end-before: OtherEnd
 """
-    assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
+    check "<em>Visible</em>" == rstToHtml(input, {roSandboxDisabled}, defaultConfig())
     removeFile("other.rst")
 
 
@@ -75,5 +1625,370 @@ And this should **NOT** be visible in `docs.html`
              :start-after: OtherStart
              :end-before: OtherEnd
 """
-    assert "<em>Visible</em>" == rstTohtml(input, {}, defaultConfig())
+    doAssert "<em>Visible</em>" == rstToHtml(input, {roSandboxDisabled}, defaultConfig())
     removeFile("other.rst")
+
+suite "RST escaping":
+  test "backspaces":
+    check("""\ this""".toAst == dedent"""
+      rnLeaf  'this'
+      """)
+
+    check("""\\ this""".toAst == dedent"""
+      rnInner
+        rnLeaf  '\'
+        rnLeaf  ' '
+        rnLeaf  'this'
+      """)
+
+    check("""\\\ this""".toAst == dedent"""
+      rnInner
+        rnLeaf  '\'
+        rnLeaf  'this'
+      """)
+
+    check("""\\\\ this""".toAst == dedent"""
+      rnInner
+        rnLeaf  '\'
+        rnLeaf  '\'
+        rnLeaf  ' '
+        rnLeaf  'this'
+      """)
+
+suite "RST inline markup":
+  test "* and ** surrounded by spaces are not inline markup":
+    check("a * b * c ** d ** e".toAst == dedent"""
+      rnInner
+        rnLeaf  'a'
+        rnLeaf  ' '
+        rnLeaf  '*'
+        rnLeaf  ' '
+        rnLeaf  'b'
+        rnLeaf  ' '
+        rnLeaf  '*'
+        rnLeaf  ' '
+        rnLeaf  'c'
+        rnLeaf  ' '
+        rnLeaf  '**'
+        rnLeaf  ' '
+        rnLeaf  'd'
+        rnLeaf  ' '
+        rnLeaf  '**'
+        rnLeaf  ' '
+        rnLeaf  'e'
+      """)
+
+  test "end-string has repeating symbols":
+    check("*emphasis content****".toAst == dedent"""
+      rnEmphasis
+        rnLeaf  'emphasis'
+        rnLeaf  ' '
+        rnLeaf  'content'
+        rnLeaf  '***'
+      """)
+
+    check("""*emphasis content\****""".toAst == dedent"""
+      rnEmphasis
+        rnLeaf  'emphasis'
+        rnLeaf  ' '
+        rnLeaf  'content'
+        rnLeaf  '*'
+        rnLeaf  '**'
+      """)  # exact configuration of leafs with * is not really essential,
+            # only total number of * is essential
+
+    check("**strong content****".toAst == dedent"""
+      rnStrongEmphasis
+        rnLeaf  'strong'
+        rnLeaf  ' '
+        rnLeaf  'content'
+        rnLeaf  '**'
+      """)
+
+    check("""**strong content*\****""".toAst == dedent"""
+      rnStrongEmphasis
+        rnLeaf  'strong'
+        rnLeaf  ' '
+        rnLeaf  'content'
+        rnLeaf  '*'
+        rnLeaf  '*'
+        rnLeaf  '*'
+      """)
+
+    check("``lit content`````".toAst == dedent"""
+      rnInlineLiteral
+        rnLeaf  'lit'
+        rnLeaf  ' '
+        rnLeaf  'content'
+        rnLeaf  '```'
+      """)
+
+  test "interpreted text parsing: code fragments":
+    check(dedent"""
+        .. default-role:: option
+
+        `--gc:refc`""".toAst ==
+      dedent"""
+        rnInner
+          rnDefaultRole
+            rnDirArg
+              rnLeaf  'option'
+            [nil]
+            [nil]
+          rnParagraph
+            rnCodeFragment
+              rnInner
+                rnLeaf  '--'
+                rnLeaf  'gc'
+                rnLeaf  ':'
+                rnLeaf  'refc'
+              rnLeaf  'option'
+        """)
+
+  test """interpreted text can be ended with \` """:
+    let output = (".. default-role:: literal\n" & """`\``""").toAst
+    check(output.endsWith """
+  rnParagraph
+    rnInlineLiteral
+      rnLeaf  '`'""" & "\n")
+
+    let output2 = """`\``""".toAst
+    check(output2 == dedent"""
+      rnInlineCode
+        rnDirArg
+          rnLeaf  'nim'
+        [nil]
+        rnLiteralBlock
+          rnLeaf  '`'
+      """)
+
+    let output3 = """`proc \`+\``""".toAst
+    check(output3 == dedent"""
+      rnInlineCode
+        rnDirArg
+          rnLeaf  'nim'
+        [nil]
+        rnLiteralBlock
+          rnLeaf  'proc `+`'
+      """)
+
+    check("""`\\`""".toAst ==
+      dedent"""
+        rnInlineCode
+          rnDirArg
+            rnLeaf  'nim'
+          [nil]
+          rnLiteralBlock
+            rnLeaf  '\\'
+        """)
+
+  test "Markdown-style code/backtick":
+    # no whitespace is required before `
+    check("`try`...`except`".toAst ==
+      dedent"""
+        rnInner
+          rnInlineCode
+            rnDirArg
+              rnLeaf  'nim'
+            [nil]
+            rnLiteralBlock
+              rnLeaf  'try'
+          rnLeaf  '...'
+          rnInlineCode
+            rnDirArg
+              rnLeaf  'nim'
+            [nil]
+            rnLiteralBlock
+              rnLeaf  'except'
+        """)
+
+
+  test """inline literals can contain \ anywhere""":
+    check("""``\``""".toAst == dedent"""
+      rnInlineLiteral
+        rnLeaf  '\'
+      """)
+
+    check("""``\\``""".toAst == dedent"""
+      rnInlineLiteral
+        rnLeaf  '\'
+        rnLeaf  '\'
+      """)
+
+    check("""``\```""".toAst == dedent"""
+      rnInlineLiteral
+        rnLeaf  '\'
+        rnLeaf  '`'
+      """)
+
+    check("""``\\```""".toAst == dedent"""
+      rnInlineLiteral
+        rnLeaf  '\'
+        rnLeaf  '\'
+        rnLeaf  '`'
+      """)
+
+    check("""``\````""".toAst == dedent"""
+      rnInlineLiteral
+        rnLeaf  '\'
+        rnLeaf  '`'
+        rnLeaf  '`'
+      """)
+
+  test "references with _ at the end":
+    check(dedent"""
+      .. _lnk: https
+
+      lnk_""".toAst ==
+      dedent"""
+        rnHyperlink
+          rnInner
+            rnLeaf  'lnk'
+          rnInner
+            rnLeaf  'https'
+      """)
+
+  test "not a hyper link":
+    check(dedent"""
+      .. _lnk: https
+
+      lnk___""".toAst ==
+      dedent"""
+        rnInner
+          rnLeaf  'lnk'
+          rnLeaf  '___'
+      """)
+
+  test "no punctuation in the end of a standalone URI is allowed":
+    check(dedent"""
+        [see (http://no.org)], end""".toAst(rstOptions = preferRst) ==
+      dedent"""
+        rnInner
+          rnLeaf  '['
+          rnLeaf  'see'
+          rnLeaf  ' '
+          rnLeaf  '('
+          rnStandaloneHyperlink
+            rnLeaf  'http://no.org'
+          rnLeaf  ')'
+          rnLeaf  ']'
+          rnLeaf  ','
+          rnLeaf  ' '
+          rnLeaf  'end'
+        """)
+
+    # but `/` at the end is OK
+    check(
+      dedent"""
+        See http://no.org/ end""".toAst ==
+      dedent"""
+        rnInner
+          rnLeaf  'See'
+          rnLeaf  ' '
+          rnStandaloneHyperlink
+            rnLeaf  'http://no.org/'
+          rnLeaf  ' '
+          rnLeaf  'end'
+        """)
+
+    # a more complex URL with some made-up ending '&='.
+    # Github Markdown would include final &= and
+    # so would rst2html.py in contradiction with RST spec.
+    check(
+      dedent"""
+        See https://www.google.com/url?sa=t&source=web&cd=&cad=rja&url=https%3A%2F%2Fnim-lang.github.io%2FNim%2Frst.html%23features&usg=AO&= end""".toAst ==
+      dedent"""
+        rnInner
+          rnLeaf  'See'
+          rnLeaf  ' '
+          rnStandaloneHyperlink
+            rnLeaf  'https://www.google.com/url?sa=t&source=web&cd=&cad=rja&url=https%3A%2F%2Fnim-lang.github.io%2FNim%2Frst.html%23features&usg=AO'
+          rnLeaf  '&'
+          rnLeaf  '='
+          rnLeaf  ' '
+          rnLeaf  'end'
+        """)
+
+  test "Markdown-style link can be split to a few lines":
+    check(dedent"""
+        is [term-rewriting
+        macros](manual.html#term-rewriting-macros)""".toAst ==
+      dedent"""
+        rnInner
+          rnLeaf  'is'
+          rnLeaf  ' '
+          rnHyperlink
+            rnLeaf  'term-rewriting macros'
+            rnLeaf  'manual.html#term-rewriting-macros'
+      """)
+
+  test "URL with balanced parentheses (Markdown rule)":
+    # 2 balanced parens, 1 unbalanced:
+    check(dedent"""
+        https://en.wikipedia.org/wiki/APL_((programming_language)))""".toAst ==
+      dedent"""
+        rnInner
+          rnStandaloneHyperlink
+            rnLeaf  'https://en.wikipedia.org/wiki/APL_((programming_language))'
+          rnLeaf  ')'
+      """)
+
+    # the same for Markdown-style link:
+    check(dedent"""
+        [foo [bar]](https://en.wikipedia.org/wiki/APL_((programming_language))))""".toAst ==
+      dedent"""
+        rnInner
+          rnHyperlink
+            rnLeaf  'foo [bar]'
+            rnLeaf  'https://en.wikipedia.org/wiki/APL_((programming_language))'
+          rnLeaf  ')'
+      """)
+
+    # unbalanced (here behavior is more RST-like actually):
+    check(dedent"""
+        https://en.wikipedia.org/wiki/APL_(programming_language(""".toAst ==
+      dedent"""
+        rnInner
+          rnStandaloneHyperlink
+            rnLeaf  'https://en.wikipedia.org/wiki/APL_(programming_language'
+          rnLeaf  '('
+      """)
+
+    # unbalanced [, but still acceptable:
+    check(dedent"""
+        [my {link example](http://example.com/bracket_(symbol_[))""".toAst ==
+      dedent"""
+        rnHyperlink
+          rnLeaf  'my {link example'
+          rnLeaf  'http://example.com/bracket_(symbol_[)'
+      """)
+
+  test "not a Markdown link":
+    # bug #17340 (27) `f` will be considered as a protocol and blocked as unsafe
+    var warnings = new seq[string]
+    check("[T](f: var Foo)".toAst(warnings = warnings) ==
+      dedent"""
+        rnInner
+          rnLeaf  '['
+          rnLeaf  'T'
+          rnLeaf  ']'
+          rnLeaf  '('
+          rnLeaf  'f'
+          rnLeaf  ':'
+          rnLeaf  ' '
+          rnLeaf  'var'
+          rnLeaf  ' '
+          rnLeaf  'Foo'
+          rnLeaf  ')'
+      """)
+    check(warnings[] == @["input(1, 5) Warning: broken link 'f'"])
+
+suite "Misc isssues":
+  test "Markdown CodeblockFields in one line (lacking enclosing ```)":
+    let message = """
+    ```llvm-profdata merge first.profraw second.profraw third.profraw <more stuff maybe> -output data.profdata```"""
+
+    try:
+      echo rstgen.rstToHtml(message, {roSupportMarkdown}, nil)
+    except EParseError:
+      discard
diff --git a/tests/stdlib/trstgen.nim b/tests/stdlib/trstgen.nim
index 8fdbf3911..6253e7146 100644
--- a/tests/stdlib/trstgen.nim
+++ b/tests/stdlib/trstgen.nim
@@ -1,4 +1,5 @@
 discard """
+matrix: "--mm:refc; --mm:orc"
 outputsub: ""
 """
 
@@ -6,7 +7,53 @@ outputsub: ""
 
 import ../../lib/packages/docutils/rstgen
 import ../../lib/packages/docutils/rst
-import unittest
+import unittest, strutils, strtabs
+import std/private/miscdollars
+import std/assertions
+
+const
+  NoSandboxOpts = {roPreferMarkdown, roSupportMarkdown, roNimFile, roSandboxDisabled}
+  preferMarkdown = {roPreferMarkdown, roSupportMarkdown, roNimFile}
+  preferRst = {roSupportMarkdown, roNimFile}
+
+proc toHtml(input: string,
+            rstOptions: RstParseOptions = preferMarkdown,
+            error: ref string = nil,
+            warnings: ref seq[string] = nil): string =
+  ## If `error` is nil then no errors should be generated.
+  ## The same goes for `warnings`.
+  proc testMsgHandler(filename: string, line, col: int, msgkind: MsgKind,
+                      arg: string) =
+    let mc = msgkind.whichMsgClass
+    let a = $msgkind % arg
+    var message: string
+    toLocation(message, filename, line, col + ColRstOffset)
+    message.add " $1: $2" % [$mc, a]
+    if mc == mcError:
+      if error == nil:
+        raise newException(EParseError, "[unexpected error] " & message)
+      error[] = message
+      # we check only first error because subsequent ones may be meaningless
+      raise newException(EParseError, "")
+    else:
+      doAssert warnings != nil, "unexpected RST warning '" & message & "'"
+      warnings[].add message
+  try:
+    result = rstToHtml(input, rstOptions, defaultConfig(),
+                       msgHandler=testMsgHandler)
+  except EParseError as e:
+    if e.msg != "":
+      result = e.msg
+
+# inline code tags (for parsing originated from highlite.nim)
+proc id(str: string): string = """<span class="Identifier">"""  & str & "</span>"
+proc op(str: string): string = """<span class="Operator">"""    & str & "</span>"
+proc pu(str: string): string = """<span class="Punctuation">""" & str & "</span>"
+proc optionListLabel(opt: string): string =
+  """<div class="option-list-label"><tt><span class="option">""" &
+  opt &
+  "</span></tt></div>"
+
 
 suite "YAML syntax highlighting":
   test "Basics":
@@ -21,8 +68,8 @@ suite "YAML syntax highlighting":
     ? key
     : value
     ..."""
-    let output = rstTohtml(input, {}, defaultConfig())
-    assert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span>
+    let output = input.toHtml({})
+    doAssert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span>
 <span class="Keyword">---</span>
 <span class="StringLit">a string</span><span class="Punctuation">:</span> <span class="StringLit">string</span>
 <span class="StringLit">a list</span><span class="Punctuation">:</span>
@@ -47,8 +94,8 @@ suite "YAML syntax highlighting":
     another literal block scalar:
       |+ # comment after header
      allowed, since more indented than parent"""
-    let output = rstToHtml(input, {}, defaultConfig())
-    assert output == """<pre class = "listing"><span class="StringLit">a literal block scalar</span><span class="Punctuation">:</span> <span class="Command">|</span><span class="Command"></span><span class="LongStringLit">
+    let output = input.toHtml({})
+    doAssert output == """<pre class = "listing"><span class="StringLit">a literal block scalar</span><span class="Punctuation">:</span> <span class="Command">|</span><span class="Command"></span><span class="LongStringLit">
   some text
   # not a comment
  </span><span class="Comment"># a comment, since less indented</span>
@@ -73,8 +120,8 @@ suite "YAML syntax highlighting":
     % not a directive
     ...
     %TAG ! !foo:"""
-    let output = rstToHtml(input, {}, defaultConfig())
-    assert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span>
+    let output = input.toHtml({})
+    doAssert output == """<pre class = "listing"><span class="Directive">%YAML 1.2</span>
 <span class="Keyword">---</span>
 <span class="StringLit">%not a directive</span>
 <span class="Keyword">...</span>
@@ -94,8 +141,8 @@ suite "YAML syntax highlighting":
       more numbers: [-783, 11e78],
       not numbers: [ 42e, 0023, +32.37, 8 ball]
     }"""
-    let output = rstToHtml(input, {}, defaultConfig())
-    assert output == """<pre class = "listing"><span class="Punctuation">{</span>
+    let output = input.toHtml({})
+    doAssert output == """<pre class = "listing"><span class="Punctuation">{</span>
   <span class="StringLit">&quot;</span><span class="StringLit">quoted string&quot;</span><span class="Punctuation">:</span> <span class="DecNumber">42</span><span class="Punctuation">,</span>
   <span class="StringLit">'single quoted string'</span><span class="Punctuation">:</span> <span class="StringLit">false</span><span class="Punctuation">,</span>
   <span class="Punctuation">[</span> <span class="StringLit">list</span><span class="Punctuation">,</span> <span class="StringLit">&quot;</span><span class="StringLit">with&quot;</span><span class="Punctuation">,</span> <span class="StringLit">'entries'</span> <span class="Punctuation">]</span><span class="Punctuation">:</span> <span class="FloatNumber">73.32e-73</span><span class="Punctuation">,</span>
@@ -103,6 +150,25 @@ suite "YAML syntax highlighting":
   <span class="StringLit">not numbers</span><span class="Punctuation">:</span> <span class="Punctuation">[</span> <span class="StringLit">42e</span><span class="Punctuation">,</span> <span class="StringLit">0023</span><span class="Punctuation">,</span> <span class="StringLit">+32.37</span><span class="Punctuation">,</span> <span class="StringLit">8 ball</span><span class="Punctuation">]</span>
 <span class="Punctuation">}</span></pre>"""
 
+  test "Directives: warnings":
+    let input = dedent"""
+      .. non-existent-warning: Paragraph.
+
+      .. another.wrong:warning::: Paragraph.
+      """
+    var warnings = new seq[string]
+    let output = input.toHtml(warnings=warnings)
+    check output == ""
+    doAssert warnings[].len == 2
+    check "(1, 24) Warning: RST style:" in warnings[0]
+    check "double colon :: may be missing at end of 'non-existent-warning'" in warnings[0]
+    check "(3, 25) Warning: RST style:" in warnings[1]
+    check "RST style: too many colons for a directive (should be ::)" in warnings[1]
+
+  test "not a directive":
+    let input = "..warning:: I am not a warning."
+    check input.toHtml == input
+
   test "Anchors, Aliases, Tags":
     let input = """.. code-block:: yaml
     --- !!map
@@ -111,8 +177,8 @@ suite "YAML syntax highlighting":
     : !localtag foo
     alias: *anchor
     """
-    let output = rstToHtml(input, {}, defaultConfig())
-    assert output == """<pre class = "listing"><span class="Keyword">---</span> <span class="TagStart">!!map</span>
+    let output = input.toHtml({})
+    doAssert output == """<pre class = "listing"><span class="Keyword">---</span> <span class="TagStart">!!map</span>
 <span class="TagStart">!!str</span> <span class="StringLit">string</span><span class="Punctuation">:</span> <span class="TagStart">!&lt;tag:yaml.org,2002:int&gt;</span> <span class="DecNumber">42</span>
 <span class="Punctuation">?</span> <span class="Label">&amp;anchor</span> <span class="TagStart">!!seq</span> <span class="Punctuation">[</span><span class="Punctuation">]</span><span class="Punctuation">:</span>
 <span class="Punctuation">:</span> <span class="TagStart">!localtag</span> <span class="StringLit">foo</span>
@@ -131,8 +197,8 @@ suite "YAML syntax highlighting":
     example.com/not/a#comment:
       ?not a map key
     """
-    let output = rstToHtml(input, {}, defaultConfig())
-    assert output == """<pre class = "listing"><span class="Keyword">...</span>
+    let output = input.toHtml({})
+    doAssert output == """<pre class = "listing"><span class="Keyword">...</span>
  <span class="StringLit">%a string</span><span class="Punctuation">:</span>
   <span class="StringLit">a:string:not:a:map</span>
 <span class="Keyword">...</span>
@@ -144,12 +210,1483 @@ suite "YAML syntax highlighting":
   <span class="StringLit">?not a map key</span></pre>"""
 
 
+suite "RST/Markdown general":
+  test "RST emphasis":
+    doAssert rstToHtml("*Hello* **world**!", {},
+      newStringTable(modeStyleInsensitive)) ==
+      "<em>Hello</em> <strong>world</strong>!"
+
   test "Markdown links":
-    let
-      a = rstToHtml("(( [Nim](https://nim-lang.org/) ))", {roSupportMarkdown}, defaultConfig())
-      b = rstToHtml("(([Nim](https://nim-lang.org/)))", {roSupportMarkdown}, defaultConfig())
-      c = rstToHtml("[[Nim](https://nim-lang.org/)]", {roSupportMarkdown}, defaultConfig())
-
-    assert a == """(( <a class="reference external" href="https://nim-lang.org/">Nim</a> ))"""
-    assert b == """((<a class="reference external" href="https://nim-lang.org/">Nim</a>))"""
-    assert c == """[<a class="reference external" href="https://nim-lang.org/">Nim</a>]"""
+    check("(( [Nim](https://nim-lang.org/) ))".toHtml ==
+        """(( <a class="reference external" href="https://nim-lang.org/">Nim</a> ))""")
+    check("(([Nim](https://nim-lang.org/)))".toHtml ==
+        """((<a class="reference external" href="https://nim-lang.org/">Nim</a>))""")
+    check("[[Nim](https://nim-lang.org/)]".toHtml ==
+        """[<a class="reference external" href="https://nim-lang.org/">Nim</a>]""")
+
+  test "Markdown tables":
+    let input1 = """
+| A1 header    | A2 \| not fooled
+| :---         | ----:       |
+| C1           | C2 **bold** | ignored |
+| D1 `code \|` | D2          | also ignored
+| E1 \| text   |
+|              | F2 without pipe
+not in table"""
+    let output1 = input1.toHtml
+    #[
+    TODO: `\|` inside a table cell should render as `|`
+        `|` outside a table cell should render as `\|`
+    consistently with markdown, see https://stackoverflow.com/a/66557930/1426932
+    ]#
+    check(output1 == """
+<table border="1" class="docutils"><tr><th>A1 header</th><th>A2 | not fooled</th></tr>
+<tr><td>C1</td><td>C2 <strong>bold</strong></td></tr>
+<tr><td>D1 <tt class="docutils literal"><span class="pre">""" & id"code" & " " & op"\|" & """</span></tt></td><td>D2</td></tr>
+<tr><td>E1 | text</td><td></td></tr>
+<tr><td></td><td>F2 without pipe</td></tr>
+</table><p>not in table</p>""")
+    let input2 = """
+| A1 header | A2 |
+| --- | --- |"""
+    let output2 = input2.toHtml
+    doAssert output2 == """<table border="1" class="docutils"><tr><th>A1 header</th><th>A2</th></tr>
+</table>"""
+
+  test "RST tables":
+    let input1 = """
+Test 2 column/4 rows table:
+====   ===
+H0     H1
+====   ===
+A0     A1
+====   ===
+A2     A3
+====   ===
+A4     A5
+====   === """
+    let output1 = rstToLatex(input1, {})
+    doAssert "{LL}" in output1  # 2 columns
+    doAssert count(output1, "\\\\") == 4  # 4 rows
+    for cell in ["H0", "H1", "A0", "A1", "A2", "A3", "A4", "A5"]:
+      doAssert cell in output1
+
+    let input2 = """
+Now test 3 columns / 2 rows, and also borders containing 4 =, 3 =, 1 = signs:
+
+====   ===  =
+H0     H1   H
+====   ===  =
+A0     A1   X
+       Ax   Y
+====   ===  = """
+    let output2 = rstToLatex(input2, {})
+    doAssert "{LLL}" in output2  # 3 columns
+    doAssert count(output2, "\\\\") == 2  # 2 rows
+    for cell in ["H0", "H1", "H", "A0", "A1", "X", "Ax", "Y"]:
+      doAssert cell in output2
+
+
+  test "RST adornments":
+    let input1 = """
+Check that a few punctuation symbols are not parsed as adornments:
+:word1: word2 .... word3 """
+    let output1 = input1.toHtml
+    discard output1
+
+  test "RST sections":
+    let input1 = """
+Long chapter name
+'''''''''''''''''''
+"""
+    let output1 = input1.toHtml
+    doAssert "Long chapter name" in output1 and "<h1" in output1
+
+    let input2 = """
+Short chapter name:
+
+ChA
+===
+"""
+    let output2 = input2.toHtml
+    doAssert "ChA" in output2 and "<h1" in output2
+
+    let input3 = """
+Very short chapter name:
+
+X
+~
+"""
+    let output3 = input3.toHtml
+    doAssert "X" in output3 and "<h1" in output3
+
+    let input4 = """
+Check that short underline is not enough to make section:
+
+Wrong chapter
+------------
+
+"""
+    var error4 = new string
+    let output4 = input4.toHtml(error = error4)
+    check(error4[] == "input(3, 1) Error: new section expected (underline " &
+            "\'------------\' is too short)")
+
+    let input5 = """
+Check that punctuation after adornment and indent are not detected as adornment.
+
+Some chapter
+--------------
+
+  "punctuation symbols" """
+    let output5 = input5.toHtml
+    doAssert "&quot;punctuation symbols&quot;" in output5 and "<h1" in output5
+
+    # check that EOF after adornment does not prevent it parsing as heading
+    let input6 = dedent """
+      Some chapter
+      ------------"""
+    let output6 = input6.toHtml
+    doAssert "<h1 id=\"some-chapter\">Some chapter</h1>" in output6
+
+    # check that overline and underline match
+    let input7 = dedent """
+      ------------
+      Some chapter
+      -----------
+      """
+    var error7 = new string
+    let output7 = input7.toHtml(error=error7)
+    check(error7[] == "input(1, 1) Error: new section expected (underline " &
+            "\'-----------\' does not match overline \'------------\')")
+
+    let input8 = dedent """
+      -----------
+          Overflow
+      -----------
+      """
+    var error8 = new string
+    let output8 = input8.toHtml(error=error8)
+    check(error8[] == "input(1, 1) Error: new section expected (overline " &
+            "\'-----------\' is too short)")
+
+    # check that hierarchy of title styles works
+    let input9good = dedent """
+      Level1
+      ======
+
+      Level2
+      ------
+
+      Level3
+      ~~~~~~
+
+      L1
+      ==
+
+      Another2
+      --------
+
+      More3
+      ~~~~~
+
+      """
+    let output9good = input9good.toHtml(preferRst)
+    doAssert "<h1 id=\"level1\">Level1</h1>" in output9good
+    doAssert "<h2 id=\"level2\">Level2</h2>" in output9good
+    doAssert "<h3 id=\"level3\">Level3</h3>" in output9good
+    doAssert "<h1 id=\"l1\">L1</h1>" in output9good
+    doAssert "<h2 id=\"another2\">Another2</h2>" in output9good
+    doAssert "<h3 id=\"more3\">More3</h3>" in output9good
+
+    # check that swap causes an exception
+    let input9Bad = dedent """
+      Level1
+      ======
+
+      Level2
+      ------
+
+      Level3
+      ~~~~~~
+
+      L1
+      ==
+
+      More
+      ~~~~
+
+      Another
+      -------
+
+      """
+    var error9Bad = new string
+    let output9Bad = input9Bad.toHtml(preferRst, error=error9Bad)
+    check(error9Bad[] == "input(15, 1) Error: new section expected (section " &
+            "level inconsistent: underline ~~~~~ unexpectedly found, while " &
+            "the following intermediate section level(s) are missing on " &
+            "lines 12..15: underline -----)")
+
+  test "RST sections overline":
+    # the same as input9good but with overline headings
+    # first overline heading has a special meaning: document title
+    let input = dedent """
+      ======
+      Title0
+      ======
+
+      +++++++++
+      SubTitle0
+      +++++++++
+
+      ------
+      Level1
+      ------
+
+      Level2
+      ------
+
+      ~~~~~~
+      Level3
+      ~~~~~~
+
+      --
+      L1
+      --
+
+      Another2
+      --------
+
+      ~~~~~
+      More3
+      ~~~~~
+
+      """
+    var rstGenera: RstGenerator
+    var output: string
+    let (rst, files, _) = rstParse(input, "", 1, 1, {})
+    rstGenera.initRstGenerator(outHtml, defaultConfig(), "input", filenames = files)
+    rstGenera.renderRstToOut(rst, output)
+    doAssert rstGenera.meta[metaTitle] == "Title0"
+    doAssert rstGenera.meta[metaSubtitle] == "SubTitle0"
+    doAssert "<h1 id=\"level1\"><center>Level1</center></h1>" in output
+    doAssert "<h2 id=\"level2\">Level2</h2>" in output
+    doAssert "<h3 id=\"level3\"><center>Level3</center></h3>" in output
+    doAssert "<h1 id=\"l1\"><center>L1</center></h1>" in output
+    doAssert "<h2 id=\"another2\">Another2</h2>" in output
+    doAssert "<h3 id=\"more3\"><center>More3</center></h3>" in output
+
+  test "RST sections overline 2":
+    # check that a paragraph prevents interpreting overlines as document titles
+    let input = dedent """
+      Paragraph
+
+      ======
+      Title0
+      ======
+
+      +++++++++
+      SubTitle0
+      +++++++++
+      """
+    var rstGenera: RstGenerator
+    var output: string
+    let (rst, files, _) = rstParse(input, "", 1, 1, {})
+    rstGenera.initRstGenerator(outHtml, defaultConfig(), "input", filenames=files)
+    rstGenera.renderRstToOut(rst, output)
+    doAssert rstGenera.meta[metaTitle] == ""
+    doAssert rstGenera.meta[metaSubtitle] == ""
+    doAssert "<h1 id=\"title0\"><center>Title0</center></h1>" in output
+    doAssert "<h2 id=\"subtitle0\"><center>SubTitle0</center></h2>" in output
+
+  test "RST+Markdown sections":
+    # check that RST and Markdown headings don't interfere
+    let input = dedent """
+      ======
+      Title0
+      ======
+
+      MySection1a
+      +++++++++++
+
+      # MySection1b
+
+      MySection1c
+      +++++++++++
+
+      ##### MySection5a
+
+      MySection2a
+      -----------
+      """
+    var rstGenera: RstGenerator
+    var output: string
+    let (rst, files, _) = rstParse(input, "", 1, 1, {roSupportMarkdown})
+    rstGenera.initRstGenerator(outHtml, defaultConfig(), "input", filenames=files)
+    rstGenera.renderRstToOut(rst, output)
+    doAssert rstGenera.meta[metaTitle] == "Title0"
+    doAssert rstGenera.meta[metaSubtitle] == ""
+    doAssert output ==
+             "\n<h1 id=\"mysection1a\">MySection1a</h1>" & # RST
+             "\n<h1 id=\"mysection1b\">MySection1b</h1>" & # Markdown
+             "\n<h1 id=\"mysection1c\">MySection1c</h1>" & # RST
+             "\n<h5 id=\"mysection5a\">MySection5a</h5>" & # Markdown
+             "\n<h2 id=\"mysection2a\">MySection2a</h2>"   # RST
+
+  test "RST inline text":
+    let input1 = "GC_step"
+    let output1 = input1.toHtml
+    doAssert output1 == "GC_step"
+
+  test "RST anchors/links to headings":
+    # Currently in TOC mode anchors are modified (for making links from
+    # the TOC unique)
+    let inputNoToc = dedent"""
+        Type relations
+        ==============
+
+        Convertible relation
+        --------------------
+
+        Ref. `Convertible relation`_
+        """
+    let outputNoToc = inputNoToc.toHtml
+    check outputNoToc.count("id=\"type-relations\"") == 1
+    check outputNoToc.count("id=\"convertible-relation\"") == 1
+    check outputNoToc.count("href=\"#convertible-relation\"") == 1
+
+    let inputTocCases = @[
+      dedent"""
+        .. contents::
+
+        Type relations
+        ==============
+
+        Convertible relation
+        --------------------
+
+        Ref. `Convertible relation`_
+
+        Guards and locks
+        ================
+        """,
+      dedent"""
+        Ref. `Convertible relation`_
+
+        .. contents::
+
+        Type relations
+        ==============
+
+        Convertible relation
+        --------------------
+
+        Guards and locks
+        ================
+        """
+    ]
+    for inputToc in inputTocCases:
+      let outputToc = inputToc.toHtml
+      check outputToc.count("id=\"type-relations\"") == 1
+      check outputToc.count("id=\"type-relations-convertible-relation\"") == 1
+      check outputToc.count("id=\"convertible-relation\">") == 0
+      # Besides "Ref.", heading also contains link to itself:
+      check outputToc.count(
+          "href=\"#type-relations-convertible-relation\">") == 2
+      check outputToc.count("href=\"#convertible-relation\"") == 0
+
+  test "RST links":
+    let input1 = """
+Want to learn about `my favorite programming language`_?
+
+.. _my favorite programming language: https://nim-lang.org"""
+    let output1 = input1.toHtml
+    doAssert "<a" in output1 and "href=\"https://nim-lang.org\"" in output1
+
+  test "RST transitions":
+    let input1 = """
+context1
+
+~~~~
+
+context2
+"""
+    let output1 = input1.toHtml(preferRst)
+    doAssert "<hr" in output1
+
+    let input2 = """
+This is too short to be a transition:
+
+---
+context2
+---
+"""
+    var error2 = new string
+    let output2 = input2.toHtml(error=error2)
+    check(error2[] == "input(3, 1) Error: new section expected (overline " &
+            "\'---\' is too short)")
+
+  test "RST literal block":
+    let input1 = """
+Test literal block
+
+::
+
+  check """
+    let output1 = input1.toHtml(preferRst)
+    doAssert "<pre>" in output1
+
+  test "Markdown code block":
+    let input1 = """
+```
+let x = 1
+``` """
+    let output1 = input1.toHtml({roSupportMarkdown, roPreferMarkdown})
+    doAssert "<pre" in output1 and "class=\"Keyword\"" notin output1
+
+    # Check Nim highlighting by default in .nim files:
+    let output1nim = input1.toHtml({roSupportMarkdown, roPreferMarkdown,
+                                    roNimFile})
+    doAssert "<pre" in output1nim and "class=\"Keyword\"" in output1nim
+
+    let input2 = """
+Parse the block with language specifier:
+```Nim
+let x = 1
+``` """
+    let output2 = input2.toHtml
+    doAssert "<pre" in output2 and "class=\"Keyword\"" in output2
+
+  test "interpreted text":
+    check("""`foo.bar`""".toHtml ==
+      """<tt class="docutils literal"><span class="pre">""" &
+      id"foo" & op"." & id"bar" & "</span></tt>")
+    check("""`foo\`\`bar`""".toHtml ==
+      """<tt class="docutils literal"><span class="pre">""" &
+      id"foo" & pu"`" & pu"`" & id"bar" & "</span></tt>")
+    check("""`foo\`bar`""".toHtml ==
+      """<tt class="docutils literal"><span class="pre">""" &
+      id"foo" & pu"`" & id"bar" & "</span></tt>")
+    check("""`\`bar`""".toHtml ==
+      """<tt class="docutils literal"><span class="pre">""" &
+      pu"`" & id"bar" & "</span></tt>")
+    check("""`a\b\x\\ar`""".toHtml ==
+      """<tt class="docutils literal"><span class="pre">""" &
+      id"a" & op"""\""" & id"b" & op"""\""" & id"x" & op"""\\""" & id"ar" &
+      "</span></tt>")
+
+  test "inline literal":
+    check """``foo.bar``""".toHtml == """<tt class="docutils literal"><span class="pre">foo.bar</span></tt>"""
+    check """``foo\bar``""".toHtml == """<tt class="docutils literal"><span class="pre">foo\bar</span></tt>"""
+    check """``f\`o\\o\b`ar``""".toHtml == """<tt class="docutils literal"><span class="pre">f\`o\\o\b`ar</span></tt>"""
+
+  test "default-role":
+    # nim(default) -> literal -> nim -> code(=literal)
+    let input = dedent"""
+      Par1 `value1`.
+
+      .. default-role:: literal
+
+      Par2 `value2`.
+
+      .. default-role:: nim
+
+      Par3 `value3`.
+
+      .. default-role:: code
+
+      Par4 `value4`."""
+    let p1 = """Par1 <tt class="docutils literal"><span class="pre">""" & id"value1" & "</span></tt>."
+    let p2 = """<p>Par2 <tt class="docutils literal"><span class="pre">value2</span></tt>.</p>"""
+    let p3 = """<p>Par3 <tt class="docutils literal"><span class="pre">""" & id"value3" & "</span></tt>.</p>"
+    let p4 = """<p>Par4 <tt class="docutils literal"><span class="pre">value4</span></tt>.</p>"""
+    let expected = p1 & p2 & "\n" & p3 & "\n" & p4
+    check(
+      input.toHtml(NoSandboxOpts) == expected
+    )
+
+  test "role directive":
+    let input = dedent"""
+      .. role:: y(code)
+         :language: yaml
+
+      .. role:: brainhelp(code)
+         :language: brainhelp
+    """
+    var warnings = new seq[string]
+    let output = input.toHtml(
+      NoSandboxOpts,
+      warnings=warnings
+    )
+    check(warnings[].len == 1 and "language 'brainhelp' not supported" in warnings[0])
+
+  test "RST comments":
+    let input1 = """
+
+Check that comment disappears:
+
+..
+  some comment """
+    let output1 = input1.toHtml
+    doAssert output1 == "Check that comment disappears:"
+
+  test "RST line blocks + headings":
+    let input = """
+=====
+Test1
+=====
+
+|
+|
+| line block
+| other line
+
+"""
+    var rstGenera: RstGenerator
+    var output: string
+    let (rst, files, _) = rstParse(input, "", 1, 1, {})
+    rstGenera.initRstGenerator(outHtml, defaultConfig(), "input", filenames=files)
+    rstGenera.renderRstToOut(rst, output)
+    doAssert rstGenera.meta[metaTitle] == "Test1"
+      # check that title was not overwritten to '|'
+    doAssert output == "<p><br/><br/>line block<br/>other line<br/></p>"
+    let output1l = rstToLatex(input, {})
+    doAssert "line block\n\n" in output1l
+    doAssert "other line\n\n" in output1l
+    doAssert output1l.count("\\vspace") == 2 + 2  # +2 surrounding paddings
+
+  test "RST line blocks":
+    let input2 = dedent"""
+      Paragraph1
+
+      |
+
+      Paragraph2"""
+
+    let output2 = input2.toHtml
+    doAssert "Paragraph1<p><br/></p> <p>Paragraph2</p>" == output2
+
+    let input3 = dedent"""
+      | xxx
+      |   yyy
+      |     zzz"""
+
+    let output3 = input3.toHtml
+    doAssert "xxx<br/>" in output3
+    doAssert "<span style=\"margin-left: 1.0em\">yyy</span><br/>" in output3
+    doAssert "<span style=\"margin-left: 2.0em\">zzz</span><br/>" in output3
+
+    # check that '|   ' with a few spaces is still parsed as new line
+    let input4 = dedent"""
+      | xxx
+      |
+      |     zzz"""
+
+    let output4 = input4.toHtml
+    doAssert "xxx<br/><br/>" in output4
+    doAssert "<span style=\"margin-left: 2.0em\">zzz</span><br/>" in output4
+
+  test "RST enumerated lists":
+    let input1 = dedent """
+      1. line1
+         1
+      2. line2
+         2
+
+      3. line3
+         3
+
+
+      4. line4
+         4
+
+
+
+      5. line5
+         5
+      """
+    let output1 = input1.toHtml
+    for i in 1..5:
+      doAssert ($i & ". line" & $i) notin output1
+      doAssert ("<li>line" & $i & " " & $i & "</li>") in output1
+
+    let input2 = dedent """
+      3. line3
+
+      4. line4
+
+
+      5. line5
+
+
+
+      7. line7
+
+
+
+
+      8. line8
+      """
+    let output2 = input2.toHtml
+    for i in [3, 4, 5, 7, 8]:
+      doAssert ($i & ". line" & $i) notin output2
+      doAssert ("<li>line" & $i & "</li>") in output2
+
+    # check that nested enumerated lists work
+    let input3 = dedent """
+      1.  a) string1
+      2. string2
+      """
+    let output3 = input3.toHtml
+    doAssert count(output3, "<ol ") == 2
+    doAssert count(output3, "</ol>") == 2
+    doAssert "<li>string1</li>" in output3 and "<li>string2</li>" in output3
+
+    let input4 = dedent """
+      Check that enumeration specifiers are respected
+
+      9. string1
+      10. string2
+      12. string3
+
+      b) string4
+      c) string5
+      e) string6
+      """
+    let output4 = input4.toHtml
+    doAssert count(output4, "<ol ") == 4
+    doAssert count(output4, "</ol>") == 4
+    for enumerator in [9, 12]:
+      doAssert "start=\"$1\"" % [$enumerator] in output4
+    for enumerator in [2, 5]:  # 2=b, 5=e
+      doAssert "start=\"$1\"" % [$enumerator] in output4
+
+    let input5 = dedent """
+      Check that auto-numbered enumeration lists work.
+
+      #. string1
+
+      #. string2
+
+      #. string3
+
+      #) string5
+      #) string6
+      """
+    let output5 = input5.toHtml
+    doAssert count(output5, "<ol ") == 2
+    doAssert count(output5, "</ol>") == 2
+    doAssert count(output5, "<li>") == 5
+
+    let input5a = dedent """
+      Auto-numbered RST list can start with 1 even when Markdown support is on.
+
+      1. string1
+      #. string2
+      #. string3
+      """
+    let output5a = input5a.toHtml
+    doAssert count(output5a, "<ol ") == 1
+    doAssert count(output5a, "</ol>") == 1
+    doAssert count(output5a, "<li>") == 3
+
+    let input6 = dedent """
+      ... And for alphabetic enumerators too!
+
+      b. string1
+      #. string2
+      #. string3
+      """
+    let output6 = input6.toHtml
+    doAssert count(output6, "<ol ") == 1
+    doAssert count(output6, "</ol>") == 1
+    doAssert count(output6, "<li>") == 3
+    doAssert "start=\"2\"" in output6 and "class=\"loweralpha simple\"" in output6
+
+    let input7 = dedent """
+      ... And for uppercase alphabetic enumerators.
+
+      C. string1
+      #. string2
+      #. string3
+      """
+    let output7 = input7.toHtml
+    doAssert count(output7, "<ol ") == 1
+    doAssert count(output7, "</ol>") == 1
+    doAssert count(output7, "<li>") == 3
+    doAssert "start=\"3\"" in output7 and "class=\"upperalpha simple\"" in output7
+
+    # check that it's not recognized as enum.list without indentation on 2nd line
+    let input8 = dedent """
+      Paragraph.
+
+      A. stringA
+      B. stringB
+      C. string1
+      string2
+      """
+    var warnings8 = new seq[string]
+    let output8 = input8.toHtml(warnings = warnings8)
+    check(warnings8[].len == 1)
+    check("input(6, 1) Warning: RST style: \n" &
+          "not enough indentation on line 6" in warnings8[0])
+    doAssert output8 == "Paragraph.<ol class=\"upperalpha simple\">" &
+        "<li>stringA</li>\n<li>stringB</li>\n</ol>\n<p>C. string1 string2 </p>"
+
+  test "Markdown enumerated lists":
+    let input1 = dedent """
+      Below are 2 enumerated lists: Markdown-style (5 items) and RST (1 item)
+      1. line1
+      1. line2
+      1. line3
+      1. line4
+
+      1. line5
+
+      #. lineA
+      """
+    let output1 = input1.toHtml
+    for i in 1..5:
+      doAssert ($i & ". line" & $i) notin output1
+      doAssert ("<li>line" & $i & "</li>") in output1
+    doAssert count(output1, "<ol ") == 2
+    doAssert count(output1, "</ol>") == 2
+
+  test "RST bullet lists":
+    let input1 = dedent """
+      * line1
+        1
+      * line2
+        2
+
+      * line3
+        3
+
+
+      * line4
+        4
+
+
+
+      * line5
+        5
+      """
+    let output1 = input1.toHtml
+    for i in 1..5:
+      doAssert ("<li>line" & $i & " " & $i & "</li>") in output1
+    doAssert count(output1, "<ul ") == 1
+    doAssert count(output1, "</ul>") == 1
+
+  test "Nim RST footnotes and citations":
+    # check that auto-label footnote enumerated properly after a manual one
+    let input1 = dedent """
+      .. [1] Body1.
+      .. [#note] Body2
+
+      Ref. [#note]_
+      """
+    let output1 = input1.toHtml(preferRst)
+    doAssert output1.count(">[1]</a>") == 1
+    doAssert output1.count(">[2]</a>") == 2
+    doAssert "href=\"#footnote-note\"" in output1
+    doAssert ">[-1]" notin output1
+    doAssert "Body1." in output1
+    doAssert "Body2" in output1
+
+    # check that there are NO footnotes/citations, only comments:
+    let input2 = dedent """
+      .. [1 #] Body1.
+      .. [# note] Body2.
+      .. [wrong citation] That gives you a comment.
+
+      .. [not&allowed] That gives you a comment.
+
+      Not references[#note]_[1 #]_ [wrong citation]_ and [not&allowed]_.
+      """
+    let output2 = input2.toHtml(preferRst)
+    doAssert output2 == "Not references[#note]_[1 #]_ [wrong citation]_ and [not&amp;allowed]_."
+
+    # check that auto-symbol footnotes work:
+    let input3 = dedent """
+      Ref. [*]_ and [*]_ and [*]_.
+
+      .. [*] Body1
+      .. [*] Body2.
+
+
+      .. [*] Body3.
+      .. [*] Body4
+
+      And [*]_.
+      """
+    let output3 = input3.toHtml(preferRst)
+    # both references and footnotes. Footnotes have link to themselves.
+    doAssert output3.count("href=\"#footnotesym-1\">[*]</a>") == 2
+    doAssert output3.count("href=\"#footnotesym-2\">[**]</a>") == 2
+    doAssert output3.count("href=\"#footnotesym-3\">[***]</a>") == 2
+    doAssert output3.count("href=\"#footnotesym-4\">[^]</a>") == 2
+    # footnote group
+    doAssert output3.count("<hr class=\"footnote\">" &
+                           "<div class=\"footnote-group\">") == 1
+    # footnotes
+    doAssert output3.count("<div class=\"footnote-label\"><sup><strong>" &
+               "<a href=\"#footnotesym-1\">[*]</a></strong></sup></div>") == 1
+    doAssert output3.count("<div class=\"footnote-label\"><sup><strong>" &
+               "<a href=\"#footnotesym-2\">[**]</a></strong></sup></div>") == 1
+    doAssert output3.count("<div class=\"footnote-label\"><sup><strong>" &
+               "<a href=\"#footnotesym-3\">[***]</a></strong></sup></div>") == 1
+    doAssert output3.count("<div class=\"footnote-label\"><sup><strong>" &
+               "<a href=\"#footnotesym-4\">[^]</a></strong></sup></div>") == 1
+    for i in 1 .. 4: doAssert ("Body" & $i) in output3
+
+    # check manual, auto-number and auto-label footnote enumeration
+    let input4 = dedent """
+      .. [3] Manual1.
+      .. [#] Auto-number1.
+      .. [#mylabel] Auto-label1.
+      .. [#note] Auto-label2.
+      .. [#] Auto-number2.
+
+      Ref. [#note]_ and [#]_ and [#]_.
+      """
+    let output4 = input4.toHtml(preferRst)
+    doAssert ">[-1]" notin output1
+    let order = @[
+        "footnote-3", "[3]", "Manual1.",
+        "footnoteauto-1", "[1]", "Auto-number1",
+        "footnote-mylabel", "[2]", "Auto-label1",
+        "footnote-note", "[4]", "Auto-label2",
+        "footnoteauto-2", "[5]", "Auto-number2",
+        ]
+    for i in 0 .. order.len-2:
+      let pos1 = output4.find(order[i])
+      let pos2 = output4.find(order[i+1])
+      doAssert pos1 >= 0
+      doAssert pos2 >= 0
+      doAssert pos1 < pos2
+
+    # forgot [#]_
+    let input5 = dedent """
+      .. [3] Manual1.
+      .. [#] Auto-number1.
+      .. [#note] Auto-label2.
+
+      Ref. [#note]_
+      """
+    var error5 = new string
+    let output5 = input5.toHtml(preferRst, error=error5)
+    check(error5[] == "input(1, 1) Error: mismatch in number of footnotes " &
+            "and their refs: 1 (lines 2) != 0 (lines ) for auto-numbered " &
+            "footnotes")
+
+    # extra [*]_
+    let input6 = dedent """
+      Ref. [*]_
+
+      .. [*] Auto-Symbol.
+
+      Ref. [*]_
+      """
+    var error6 = new string
+    let output6 = input6.toHtml(preferRst, error=error6)
+    check(error6[] == "input(1, 1) Error: mismatch in number of footnotes " &
+            "and their refs: 1 (lines 3) != 2 (lines 2, 6) for auto-symbol " &
+            "footnotes")
+
+    let input7 = dedent """
+      .. [Some:CITATION-2020] Citation.
+
+      Ref. [some:citation-2020]_.
+      """
+    let output7 = input7.toHtml(preferRst)
+    doAssert output7.count("href=\"#citation-somecoloncitationminus2020\"") == 2
+    doAssert output7.count("[Some:CITATION-2020]") == 1
+    doAssert output7.count("[some:citation-2020]") == 1
+    doAssert output3.count("<hr class=\"footnote\">" &
+                           "<div class=\"footnote-group\">") == 1
+
+    let input8 = dedent """
+      .. [Some] Citation.
+
+      Ref. [som]_.
+      """
+    var warnings8 = new seq[string]
+    let output8 = input8.toHtml(preferRst, warnings=warnings8)
+    check(warnings8[] == @["input(3, 7) Warning: broken link 'citation-som'"])
+
+    # check that footnote group does not break parsing of other directives:
+    let input9 = dedent """
+      .. [Some] Citation.
+
+      .. _`internal anchor`:
+
+      .. [Another] Citation.
+      .. just comment.
+      .. [Third] Citation.
+
+      Paragraph1.
+
+      Paragraph2 ref `internal anchor`_.
+      """
+    let output9 = input9.toHtml(preferRst)
+    # _`internal anchor` got erased:
+    check "href=\"#internal-anchor\"" notin output9
+    check "href=\"#citation-another\"" in output9
+    doAssert output9.count("<hr class=\"footnote\">" &
+                           "<div class=\"footnote-group\">") == 1
+    doAssert output9.count("<div class=\"footnote-label\">") == 3
+    doAssert "just comment" notin output9
+
+    # check that nested citations/footnotes work
+    let input10 = dedent """
+      Paragraph1 [#]_.
+
+      .. [First] Citation.
+
+         .. [#] Footnote.
+
+            .. [Third] Citation.
+      """
+    let output10 = input10.toHtml(preferRst)
+    doAssert output10.count("<hr class=\"footnote\">" &
+                            "<div class=\"footnote-group\">") == 3
+    doAssert output10.count("<div class=\"footnote-label\">") == 3
+    doAssert "<a href=\"#citation-first\">[First]</a>" in output10
+    doAssert "<a href=\"#footnoteauto-1\">[1]</a>" in output10
+    doAssert "<a href=\"#citation-third\">[Third]</a>" in output10
+
+    let input11 = ".. [note]\n"  # should not crash
+    let output11 = input11.toHtml(preferRst)
+    doAssert "<a href=\"#citation-note\">[note]</a>" in output11
+
+    # check that references to auto-numbered footnotes work
+    let input12 = dedent """
+      Ref. [#]_ and [#]_ STOP.
+
+      .. [#] Body1.
+      .. [#] Body3
+      .. [2] Body2.
+      """
+    let output12 = input12.toHtml(preferRst)
+    let orderAuto = @[
+        "#footnoteauto-1", "[1]",
+        "#footnoteauto-2", "[3]",
+        "STOP.",
+        "Body1.", "Body3", "Body2."
+        ]
+    for i in 0 .. orderAuto.len-2:
+      let pos1 = output12.find(orderAuto[i])
+      let pos2 = output12.find(orderAuto[i+1])
+      doAssert pos1 >= 0
+      doAssert pos2 >= 0
+      doAssert pos1 < pos2
+
+  test "Nim (RST extension) code-block":
+    # check that presence of fields doesn't consume the following text as
+    # its code (which is a literal block)
+    let input0 = dedent """
+      .. code-block:: nim
+         :number-lines: 0
+
+      Paragraph1"""
+    let output0 = input0.toHtml
+    doAssert "<p>Paragraph1</p>" in output0
+
+  test "Nim code-block :number-lines:":
+    let input = dedent """
+      .. code-block:: nim
+         :number-lines: 55
+
+         x
+         y
+      """
+    check "<pre class=\"line-nums\">55\n56\n</pre>" in input.toHtml
+
+  test "Nim code-block indentation":
+    let input = dedent """
+      .. code-block:: nim
+        :number-lines: 55
+
+       x
+      """
+    let output = input.toHtml
+    check "<pre class=\"line-nums\">55\n</pre>" in output
+    check "<span class=\"Identifier\">x</span>" in output
+
+  test "Nim code-block indentation":
+    let input = dedent """
+      .. code-block:: nim
+        :number-lines: 55
+         let a = 1
+      """
+    var error = new string
+    let output = input.toHtml(error=error)
+    check(error[] == "input(2, 3) Error: invalid field: " &
+                     "extra arguments were given to number-lines: ' let a = 1'")
+    check "" == output
+
+  test "code-block warning":
+    let input = dedent """
+      .. code:: Nim
+         :unsupportedField: anything
+
+      .. code:: unsupportedLang
+
+         anything
+
+      ```anotherLang
+      someCode
+      ```
+      """
+    let warnings = new seq[string]
+    let output = input.toHtml(warnings=warnings)
+    check(warnings[] == @[
+        "input(2, 4) Warning: field 'unsupportedField' not supported",
+        "input(4, 11) Warning: language 'unsupportedLang' not supported",
+        "input(8, 4) Warning: language 'anotherLang' not supported"
+        ])
+    check(output == "<pre class = \"listing\">anything</pre>" &
+                    "<p><pre class = \"listing\">someCode</pre> </p>")
+
+  test "RST admonitions":
+    # check that all admonitions are implemented
+    let input0 = dedent """
+      .. admonition:: endOf admonition
+      .. attention:: endOf attention
+      .. caution:: endOf caution
+      .. danger:: endOf danger
+      .. error:: endOf error
+      .. hint:: endOf hint
+      .. important:: endOf important
+      .. note:: endOf note
+      .. tip:: endOf tip
+      .. warning:: endOf warning
+    """
+    let output0 = input0.toHtml(
+      NoSandboxOpts
+    )
+    for a in ["admonition", "attention", "caution", "danger", "error", "hint",
+        "important", "note", "tip", "warning" ]:
+      doAssert "endOf " & a & "</div>" in output0
+
+    # Test that admonition does not swallow up the next paragraph.
+    let input1 = dedent """
+      .. error:: endOfError
+
+      Test paragraph.
+    """
+    let output1 = input1.toHtml(
+      NoSandboxOpts
+    )
+    doAssert "endOfError</div>" in output1
+    doAssert "<p>Test paragraph. </p>" in output1
+    doAssert "class=\"admonition admonition-error\"" in output1
+
+    # Test that second line is parsed as continuation of the first line.
+    let input2 = dedent """
+      .. error:: endOfError
+        Test2p.
+
+      Test paragraph.
+    """
+    let output2 = input2.toHtml(
+      NoSandboxOpts
+    )
+    doAssert "endOfError Test2p.</div>" in output2
+    doAssert "<p>Test paragraph. </p>" in output2
+    doAssert "class=\"admonition admonition-error\"" in output2
+
+    let input3 = dedent """
+      .. note:: endOfNote
+    """
+    let output3 = input3.toHtml(
+      NoSandboxOpts
+    )
+    doAssert "endOfNote</div>" in output3
+    doAssert "class=\"admonition admonition-info\"" in output3
+
+  test "RST internal links":
+    let input1 = dedent """
+      Start.
+
+      .. _target000:
+
+      Paragraph.
+
+      .. _target001:
+
+      * bullet list
+      * Y
+
+      .. _target002:
+
+      1. enumeration list
+      2. Y
+
+      .. _target003:
+
+      term 1
+        Definition list 1.
+
+      .. _target004:
+
+      | line block
+
+      .. _target005:
+
+      :a: field list value
+
+      .. _target006:
+
+      -a  option description
+
+      .. _target007:
+
+      ::
+
+        Literal block
+
+      .. _target008:
+
+      Doctest blocks are not implemented.
+
+      .. _target009:
+
+          block quote
+
+      .. _target010:
+
+      =====  =====  =======
+        A      B    A and B
+      =====  =====  =======
+      False  False  False
+      =====  =====  =======
+
+      .. _target100:
+
+      .. CAUTION:: admonition
+
+      .. _target101:
+
+      .. code:: nim
+
+         const pi = 3.14
+
+      .. _target102:
+
+      .. code-block::
+
+         const pi = 3.14
+
+      Paragraph2.
+
+      .. _target202:
+
+      ----
+
+      That was a transition.
+    """
+    let output1 = input1.toHtml(
+      preferRst
+    )
+    doAssert "<p id=\"target000\""     in output1
+    doAssert "<ul id=\"target001\""    in output1
+    doAssert "<ol id=\"target002\""    in output1
+    doAssert "<dl id=\"target003\""    in output1
+    doAssert "<p id=\"target004\""     in output1
+    doAssert "<table id=\"target005\"" in output1  # field list
+    doAssert "<div id=\"target006\""   in output1  # option list
+    doAssert "<pre id=\"target007\""   in output1
+    doAssert "<blockquote id=\"target009\"" in output1
+    doAssert "<table id=\"target010\"" in output1  # just table
+    doAssert "<span id=\"target100\""  in output1
+    doAssert "<pre id=\"target101\""   in output1  # code
+    doAssert "<pre id=\"target102\""   in output1  # code-block
+    doAssert "<hr id=\"target202\""    in output1
+
+  test "RST internal links for sections":
+    let input1 = dedent """
+      .. _target101:
+      .. _target102:
+
+      Section xyz
+      -----------
+
+      Ref. target101_
+    """
+    let output1 = input1.toHtml
+    # "target101" should be erased and changed to "section-xyz":
+    check "href=\"#target101\"" notin output1
+    check "id=\"target101\""    notin output1
+    check "href=\"#target102\"" notin output1
+    check "id=\"target102\""    notin output1
+    check "id=\"section-xyz\""     in output1
+    check "href=\"#section-xyz\""  in output1
+
+    let input2 = dedent """
+      .. _target300:
+
+      Section xyz
+      ===========
+
+      .. _target301:
+
+      SubsectionA
+      -----------
+
+      Ref. target300_ and target301_.
+
+      .. _target103:
+
+      .. [cit2020] note.
+
+      Ref. target103_.
+
+    """
+    let output2 = input2.toHtml(preferRst)
+    # "target101" should be erased and changed to "section-xyz":
+    doAssert "href=\"#target300\"" notin output2
+    doAssert "id=\"target300\""    notin output2
+    doAssert "href=\"#target301\"" notin output2
+    doAssert "id=\"target301\""    notin output2
+    doAssert "<h1 id=\"section-xyz\"" in output2
+    doAssert "<h2 id=\"subsectiona\"" in output2
+    # links should preserve their original names but point to section labels:
+    doAssert "href=\"#section-xyz\">target300" in output2
+    doAssert "href=\"#subsectiona\">target301" in output2
+    doAssert "href=\"#citation-cit2020\">target103" in output2
+
+    let output2l = rstToLatex(input2, {})
+    doAssert "\\label{section-xyz}\\hypertarget{section-xyz}{}" in output2l
+    doAssert "\\hyperlink{section-xyz}{target300}"  in output2l
+    doAssert "\\hyperlink{subsectiona}{target301}"  in output2l
+
+  test "RST internal links (inline)":
+    let input1 = dedent """
+      Paragraph with _`some definition`.
+
+      Ref. `some definition`_.
+    """
+    let output1 = input1.toHtml
+    doAssert "<span class=\"target\" " &
+        "id=\"some-definition\">some definition</span>" in output1
+    doAssert "Ref. <a class=\"reference internal\" " &
+        "href=\"#some-definition\">some definition</a>" in output1
+
+  test "RST references (additional symbols)":
+    # check that ., _, -, +, : are allowed symbols in references without ` `
+    let input1 = dedent """
+      sec.1
+      -----
+
+      2-other:sec+c_2
+      ^^^^^^^^^^^^^^^
+
+      .. _link.1_2021:
+
+      Paragraph
+
+      Ref. sec.1_! and 2-other:sec+c_2_;and link.1_2021_.
+    """
+    let output1 = input1.toHtml
+    doAssert "id=\"secdot1\"" in output1
+    doAssert "id=\"Z2minusothercolonsecplusc-2\"" in output1
+    check "id=\"linkdot1-2021\"" in output1
+    let ref1 = "<a class=\"reference internal\" href=\"#secdot1\">sec.1</a>"
+    let ref2 = "<a class=\"reference internal\" href=\"#Z2minusothercolonsecplusc-2\">2-other:sec+c_2</a>"
+    let ref3 = "<a class=\"reference internal\" href=\"#linkdot1-2021\">link.1_2021</a>"
+    let refline = "Ref. " & ref1 & "! and " & ref2 & ";and " & ref3 & "."
+    doAssert refline in output1
+
+  test "Option lists 1":
+    # check that "* b" is not consumed by previous bullet item because of
+    # incorrect indentation handling in option lists
+    let input = dedent """
+      * a
+        -m   desc
+        -n   very long
+             desc
+      * b"""
+    let output = input.toHtml
+    check(output.count("<ul") == 1)
+    check(output.count("<li>") == 2)
+    check(output.count("<div class=\"option-list\"") == 1)
+    check(optionListLabel("-m") &
+          """<div class="option-list-description">desc</div></div>""" in
+          output)
+    check(optionListLabel("-n") &
+          """<div class="option-list-description">very long desc</div></div>""" in
+          output)
+
+  test "Option lists 2":
+    # check that 2nd option list is not united with the 1st
+    let input = dedent """
+      * a
+        -m   desc
+        -n   very long
+             desc
+      -d  option"""
+    let output = input.toHtml
+    check(output.count("<ul") == 1)
+    check output.count("<div class=\"option-list\"") == 2
+    check(optionListLabel("-m") &
+          """<div class="option-list-description">desc</div></div>""" in
+          output)
+    check(optionListLabel("-n") &
+          """<div class="option-list-description">very long desc</div></div>""" in
+          output)
+    check(optionListLabel("-d") &
+          """<div class="option-list-description">option</div></div>""" in
+          output)
+    check "<p>option</p>" notin output
+
+  test "Option list 3 (double /)":
+    let input = dedent """
+      * a
+        //compile  compile1
+        //doc      doc1
+                   cont
+      -d  option"""
+    let output = input.toHtml
+    check(output.count("<ul") == 1)
+    check output.count("<div class=\"option-list\"") == 2
+    check(optionListLabel("compile") &
+          """<div class="option-list-description">compile1</div></div>""" in
+          output)
+    check(optionListLabel("doc") &
+          """<div class="option-list-description">doc1 cont</div></div>""" in
+          output)
+    check(optionListLabel("-d") &
+          """<div class="option-list-description">option</div></div>""" in
+          output)
+    check "<p>option</p>" notin output
+
+  test "Roles: subscript prefix/postfix":
+    let expected = "See <sub>some text</sub>."
+    check "See :subscript:`some text`.".toHtml == expected
+    check "See `some text`:subscript:.".toHtml == expected
+
+  test "Roles: correct parsing from beginning of line":
+    let expected = "<sup>3</sup>He is an isotope of helium."
+    check """:superscript:`3`\ He is an isotope of helium.""".toHtml == expected
+    check """:sup:`3`\ He is an isotope of helium.""".toHtml == expected
+    check """`3`:sup:\ He is an isotope of helium.""".toHtml == expected
+    check """`3`:superscript:\ He is an isotope of helium.""".toHtml == expected
+
+  test "Roles: warnings":
+    let input = dedent"""
+      See function :py:func:`spam`.
+
+      See also `egg`:py:class:.
+      """
+    var warnings = new seq[string]
+    let output = input.toHtml(warnings=warnings)
+    doAssert warnings[].len == 2
+    check "(1, 14) Warning: " in warnings[0]
+    check "language 'py:func' not supported" in warnings[0]
+    check "(3, 15) Warning: " in warnings[1]
+    check "language 'py:class' not supported" in warnings[1]
+    check("""<p>See function <span class="py:func">spam</span>.</p>""" & "\n" &
+          """<p>See also <span class="py:class">egg</span>. </p>""" ==
+          output)
+
+  test "(not) Roles: check escaping 1":
+    let expected = """See :subscript:<tt class="docutils literal">""" &
+                   """<span class="pre">""" & id"some" & " " & id"text" &
+                   "</span></tt>."
+    check """See \:subscript:`some text`.""".toHtml == expected
+    check """See :subscript\:`some text`.""".toHtml == expected
+
+  test "(not) Roles: check escaping 2":
+    check("""See :subscript:\`some text\`.""".toHtml ==
+          "See :subscript:`some text`.")
+
+  test "Field list":
+    check(":field: text".toHtml ==
+            """<table class="docinfo" frame="void" rules="none">""" &
+            """<col class="docinfo-name" /><col class="docinfo-content" />""" &
+            """<tbody valign="top"><tr><th class="docinfo-name">field:</th>""" &
+            """<td>text</td></tr>""" & "\n</tbody></table>")
+
+  test "Field list: body after newline":
+    let output = dedent"""
+      :field:
+        text1""".toHtml
+    check "<table class=\"docinfo\"" in output
+    check ">field:</th>" in output
+    check "<td>text1</td>" in output
+
+  test "Field list (incorrect)":
+    check ":field:text".toHtml == ":field:text"
+
+suite "RST/Code highlight":
+  test "Basic Python code highlight":
+    let pythonCode = """
+    .. code-block:: python
+
+      def f_name(arg=42):
+          print(f"{arg}")
+
+    """
+
+    let expected = """<blockquote><p><span class="Keyword">def</span> f_name<span class="Punctuation">(</span><span class="Punctuation">arg</span><span class="Operator">=</span><span class="DecNumber">42</span><span class="Punctuation">)</span><span class="Punctuation">:</span>
+    print<span class="Punctuation">(</span><span class="RawData">f&quot;{arg}&quot;</span><span class="Punctuation">)</span></p></blockquote>"""
+
+    check strip(rstToHtml(pythonCode, {}, newStringTable(modeCaseSensitive))) ==
+      strip(expected)
+
+
+suite "invalid targets":
+  test "invalid image target":
+    let input1 = dedent """.. image:: /images/myimage.jpg
+      :target: https://bar.com
+      :alt: Alt text for the image"""
+    let output1 = input1.toHtml
+    check output1 == """<a class="reference external" href="https://bar.com"><img src="/images/myimage.jpg" alt="Alt text for the image"/></a>"""
+
+    let input2 = dedent """.. image:: /images/myimage.jpg
+      :target: javascript://bar.com
+      :alt: Alt text for the image"""
+    let output2 = input2.toHtml
+    check output2 == """<img src="/images/myimage.jpg" alt="Alt text for the image"/>"""
+
+    let input3 = dedent """.. image:: /images/myimage.jpg
+      :target: bar.com
+      :alt: Alt text for the image"""
+    let output3 = input3.toHtml
+    check output3 == """<a class="reference external" href="bar.com"><img src="/images/myimage.jpg" alt="Alt text for the image"/></a>"""
+
+  test "invalid links":
+    check("(([Nim](https://nim-lang.org/)))".toHtml ==
+        """((<a class="reference external" href="https://nim-lang.org/">Nim</a>))""")
+    # unknown protocol is treated just like plain text, not a link
+    var warnings = new seq[string]
+    check("(([Nim](javascript://nim-lang.org/)))".toHtml(warnings=warnings) ==
+        """(([Nim](javascript://nim-lang.org/)))""")
+    check(warnings[] == @["input(1, 9) Warning: broken link 'javascript'"])
+    warnings[].setLen 0
+    check("`Nim <javascript://nim-lang.org/>`_".toHtml(warnings=warnings) ==
+      """Nim &lt;javascript://nim-lang.org/&gt;""")
+    check(warnings[] == @["input(1, 33) Warning: broken link 'javascript'"])
+
+suite "local file inclusion":
+  test "cannot include files in sandboxed mode":
+    var error = new string
+    discard ".. include:: ./readme.md".toHtml(error=error)
+    check(error[] == "input(1, 11) Error: disabled directive: 'include'")
+
+  test "code-block file directive is disabled":
+    var error = new string
+    discard ".. code-block:: nim\n    :file: ./readme.md".toHtml(error=error)
+    check(error[] == "input(2, 20) Error: disabled directive: 'file'")
+
+  test "code-block file directive is disabled - Markdown":
+    var error = new string
+    discard "```nim file = ./readme.md\n```".toHtml(error=error)
+    check(error[] == "input(1, 23) Error: disabled directive: 'file'")
+
+proc documentToHtml*(doc: string, isMarkdown: bool = false): string {.gcsafe.} =
+  var options = {roSupportMarkdown}
+  if isMarkdown:
+    options.incl roPreferMarkdown
+  result = rstToHtml(doc, options, defaultConfig())
diff --git a/tests/stdlib/tsequtils.nim b/tests/stdlib/tsequtils.nim
new file mode 100644
index 000000000..1094ae233
--- /dev/null
+++ b/tests/stdlib/tsequtils.nim
@@ -0,0 +1,547 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+# xxx move all tests under `main`
+
+import std/sequtils
+import strutils
+from algorithm import sorted
+import std/assertions
+
+{.experimental: "strictEffects".}
+{.push warningAsError[Effect]: on.}
+{.experimental: "strictFuncs".}
+
+# helper for testing double substitution side effects which are handled
+# by `evalOnceAs`
+var counter = 0
+proc identity[T](a: T): auto =
+  counter.inc
+  a
+
+block: # concat test
+  let
+    s1 = @[1, 2, 3]
+    s2 = @[4, 5]
+    s3 = @[6, 7]
+    total = concat(s1, s2, s3)
+  doAssert total == @[1, 2, 3, 4, 5, 6, 7]
+
+block: # count test
+  let
+    s1 = @[1, 2, 3, 2]
+    s2 = @['a', 'b', 'x', 'a']
+    a1 = [1, 2, 3, 2]
+    a2 = ['a', 'b', 'x', 'a']
+    r0 = count(s1, 0)
+    r1 = count(s1, 1)
+    r2 = count(s1, 2)
+    r3 = count(s2, 'y')
+    r4 = count(s2, 'x')
+    r5 = count(s2, 'a')
+    ar0 = count(a1, 0)
+    ar1 = count(a1, 1)
+    ar2 = count(a1, 2)
+    ar3 = count(a2, 'y')
+    ar4 = count(a2, 'x')
+    ar5 = count(a2, 'a')
+  doAssert r0 == 0
+  doAssert r1 == 1
+  doAssert r2 == 2
+  doAssert r3 == 0
+  doAssert r4 == 1
+  doAssert r5 == 2
+  doAssert ar0 == 0
+  doAssert ar1 == 1
+  doAssert ar2 == 2
+  doAssert ar3 == 0
+  doAssert ar4 == 1
+  doAssert ar5 == 2
+
+block: # cycle tests
+  let
+    a = @[1, 2, 3]
+    b: seq[int] = @[]
+    c = [1, 2, 3]
+
+  doAssert a.cycle(3) == @[1, 2, 3, 1, 2, 3, 1, 2, 3]
+  doAssert a.cycle(0) == @[]
+  #doAssert a.cycle(-1) == @[] # will not compile!
+  doAssert b.cycle(3) == @[]
+  doAssert c.cycle(3) == @[1, 2, 3, 1, 2, 3, 1, 2, 3]
+  doAssert c.cycle(0) == @[]
+
+block: # repeat tests
+  doAssert repeat(10, 5) == @[10, 10, 10, 10, 10]
+  doAssert repeat(@[1, 2, 3], 2) == @[@[1, 2, 3], @[1, 2, 3]]
+  doAssert repeat([1, 2, 3], 2) == @[[1, 2, 3], [1, 2, 3]]
+
+block: # deduplicates test
+  let
+    dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4]
+    dup2 = @["a", "a", "c", "d", "d"]
+    dup3 = [1, 1, 3, 4, 2, 2, 8, 1, 4]
+    dup4 = ["a", "a", "c", "d", "d"]
+    unique1 = deduplicate(dup1)
+    unique2 = deduplicate(dup2)
+    unique3 = deduplicate(dup3)
+    unique4 = deduplicate(dup4)
+    unique5 = deduplicate(dup1.sorted, true)
+    unique6 = deduplicate(dup2, true)
+    unique7 = deduplicate(dup3.sorted, true)
+    unique8 = deduplicate(dup4, true)
+  doAssert unique1 == @[1, 3, 4, 2, 8]
+  doAssert unique2 == @["a", "c", "d"]
+  doAssert unique3 == @[1, 3, 4, 2, 8]
+  doAssert unique4 == @["a", "c", "d"]
+  doAssert unique5 == @[1, 2, 3, 4, 8]
+  doAssert unique6 == @["a", "c", "d"]
+  doAssert unique7 == @[1, 2, 3, 4, 8]
+  doAssert unique8 == @["a", "c", "d"]
+
+block: # zip test
+  let
+    short = @[1, 2, 3]
+    long = @[6, 5, 4, 3, 2, 1]
+    words = @["one", "two", "three"]
+    ashort = [1, 2, 3]
+    along = [6, 5, 4, 3, 2, 1]
+    awords = ["one", "two", "three"]
+    zip1 = zip(short, long)
+    zip2 = zip(short, words)
+    zip3 = zip(ashort, along)
+  doAssert zip1 == @[(1, 6), (2, 5), (3, 4)]
+  doAssert zip2 == @[(1, "one"), (2, "two"), (3, "three")]
+  doAssert zip3 == @[(1, 6), (2, 5), (3, 4)]
+  doAssert zip1[2][1] == 4
+  doAssert zip2[2][1] == "three"
+  doAssert zip3[2][1] == 4
+  when (NimMajor, NimMinor) <= (1, 0):
+    let
+      # In Nim 1.0.x and older, zip returned a seq of tuple strictly
+      # with fields named "a" and "b".
+      zipAb = zip(ashort, awords)
+    doAssert zipAb == @[(a: 1, b: "one"), (2, "two"), (3, "three")]
+    doAssert zipAb[2].b == "three"
+  else:
+    let
+      # As zip returns seq of anonymous tuples, they can be assigned
+      # to any variable that's a sequence of named tuples too.
+      zipXy: seq[tuple[x: int, y: string]] = zip(ashort, awords)
+      zipMn: seq[tuple[m: int, n: string]] = zip(ashort, words)
+    doAssert zipXy == @[(x: 1, y: "one"), (2, "two"), (3, "three")]
+    doAssert zipMn == @[(m: 1, n: "one"), (2, "two"), (3, "three")]
+    doAssert zipXy[2].y == "three"
+    doAssert zipMn[2].n == "three"
+
+block: # distribute tests
+  let numbers = @[1, 2, 3, 4, 5, 6, 7]
+  doAssert numbers.distribute(3) == @[@[1, 2, 3], @[4, 5], @[6, 7]]
+  doAssert numbers.distribute(6)[0] == @[1, 2]
+  doAssert numbers.distribute(6)[5] == @[7]
+  let a = @[1, 2, 3, 4, 5, 6, 7]
+  doAssert a.distribute(1, true) == @[@[1, 2, 3, 4, 5, 6, 7]]
+  doAssert a.distribute(1, false) == @[@[1, 2, 3, 4, 5, 6, 7]]
+  doAssert a.distribute(2, true) == @[@[1, 2, 3, 4], @[5, 6, 7]]
+  doAssert a.distribute(2, false) == @[@[1, 2, 3, 4], @[5, 6, 7]]
+  doAssert a.distribute(3, true) == @[@[1, 2, 3], @[4, 5], @[6, 7]]
+  doAssert a.distribute(3, false) == @[@[1, 2, 3], @[4, 5, 6], @[7]]
+  doAssert a.distribute(4, true) == @[@[1, 2], @[3, 4], @[5, 6], @[7]]
+  doAssert a.distribute(4, false) == @[@[1, 2], @[3, 4], @[5, 6], @[7]]
+  doAssert a.distribute(5, true) == @[@[1, 2], @[3, 4], @[5], @[6], @[7]]
+  doAssert a.distribute(5, false) == @[@[1, 2], @[3, 4], @[5, 6], @[7], @[]]
+  doAssert a.distribute(6, true) == @[@[1, 2], @[3], @[4], @[5], @[6], @[7]]
+  doAssert a.distribute(6, false) == @[
+    @[1, 2], @[3, 4], @[5, 6], @[7], @[], @[]]
+  doAssert a.distribute(8, false) == a.distribute(8, true)
+  doAssert a.distribute(90, false) == a.distribute(90, true)
+  var b = @[0]
+  for f in 1 .. 25: b.add(f)
+  doAssert b.distribute(5, true)[4].len == 5
+  doAssert b.distribute(5, false)[4].len == 2
+
+block: # map test
+  let
+    numbers = @[1, 4, 5, 8, 9, 7, 4]
+    anumbers = [1, 4, 5, 8, 9, 7, 4]
+    m1 = map(numbers, proc(x: int): int = 2*x)
+    m2 = map(anumbers, proc(x: int): int = 2*x)
+  doAssert m1 == @[2, 8, 10, 16, 18, 14, 8]
+  doAssert m2 == @[2, 8, 10, 16, 18, 14, 8]
+
+block: # apply test
+  var a = @["1", "2", "3", "4"]
+  apply(a, proc(x: var string) = x &= "42")
+  doAssert a == @["142", "242", "342", "442"]
+
+block: # filter proc test
+  let
+    colors = @["red", "yellow", "black"]
+    acolors = ["red", "yellow", "black"]
+    f1 = filter(colors, proc(x: string): bool = x.len < 6)
+    f2 = filter(colors) do (x: string) -> bool: x.len > 5
+    f3 = filter(acolors, proc(x: string): bool = x.len < 6)
+    f4 = filter(acolors) do (x: string) -> bool: x.len > 5
+  doAssert f1 == @["red", "black"]
+  doAssert f2 == @["yellow"]
+  doAssert f3 == @["red", "black"]
+  doAssert f4 == @["yellow"]
+
+block: # filter iterator test
+  let numbers = @[1, 4, 5, 8, 9, 7, 4]
+  let anumbers = [1, 4, 5, 8, 9, 7, 4]
+  doAssert toSeq(filter(numbers, proc (x: int): bool = x mod 2 == 0)) ==
+    @[4, 8, 4]
+  doAssert toSeq(filter(anumbers, proc (x: int): bool = x mod 2 == 0)) ==
+    @[4, 8, 4]
+
+block: # keepIf test
+  var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1]
+  keepIf(floats, proc(x: float): bool = x > 10)
+  doAssert floats == @[13.0, 12.5, 10.1]
+
+block: # insert tests
+  var dest = @[1, 1, 1, 1, 1, 1, 1, 1]
+  let
+    src = @[2, 2, 2, 2, 2, 2]
+    outcome = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
+  dest.insert(src, 3)
+  doAssert dest == outcome, """\
+  Inserting [2,2,2,2,2,2] into [1,1,1,1,1,1,1,1]
+  at 3 is [1,1,1,2,2,2,2,2,2,1,1,1,1,1]"""
+
+block: # filterIt test
+  let
+    temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44]
+    acceptable = filterIt(temperatures, it < 50 and it > -10)
+    notAcceptable = filterIt(temperatures, it > 50 or it < -10)
+  doAssert acceptable == @[-2.0, 24.5, 44.31]
+  doAssert notAcceptable == @[-272.15, 99.9, -113.44]
+
+block: # keepItIf test
+  var candidates = @["foo", "bar", "baz", "foobar"]
+  keepItIf(candidates, it.len == 3 and it[0] == 'b')
+  doAssert candidates == @["bar", "baz"]
+
+block: # all
+  let
+    numbers = @[1, 4, 5, 8, 9, 7, 4]
+    anumbers = [1, 4, 5, 8, 9, 7, 4]
+    len0seq: seq[int] = @[]
+  doAssert all(numbers, proc (x: int): bool = return x < 10) == true
+  doAssert all(numbers, proc (x: int): bool = return x < 9) == false
+  doAssert all(len0seq, proc (x: int): bool = return false) == true
+  doAssert all(anumbers, proc (x: int): bool = return x < 10) == true
+  doAssert all(anumbers, proc (x: int): bool = return x < 9) == false
+
+block: # allIt
+  let
+    numbers = @[1, 4, 5, 8, 9, 7, 4]
+    anumbers = [1, 4, 5, 8, 9, 7, 4]
+    len0seq: seq[int] = @[]
+  doAssert allIt(numbers, it < 10) == true
+  doAssert allIt(numbers, it < 9) == false
+  doAssert allIt(len0seq, false) == true
+  doAssert allIt(anumbers, it < 10) == true
+  doAssert allIt(anumbers, it < 9) == false
+
+block: # any
+  let
+    numbers = @[1, 4, 5, 8, 9, 7, 4]
+    anumbers = [1, 4, 5, 8, 9, 7, 4]
+    len0seq: seq[int] = @[]
+  doAssert any(numbers, proc (x: int): bool = return x > 8) == true
+  doAssert any(numbers, proc (x: int): bool = return x > 9) == false
+  doAssert any(len0seq, proc (x: int): bool = return true) == false
+  doAssert any(anumbers, proc (x: int): bool = return x > 8) == true
+  doAssert any(anumbers, proc (x: int): bool = return x > 9) == false
+
+block: # anyIt
+  let
+    numbers = @[1, 4, 5, 8, 9, 7, 4]
+    anumbers = [1, 4, 5, 8, 9, 7, 4]
+    len0seq: seq[int] = @[]
+  doAssert anyIt(numbers, it > 8) == true
+  doAssert anyIt(numbers, it > 9) == false
+  doAssert anyIt(len0seq, true) == false
+  doAssert anyIt(anumbers, it > 8) == true
+  doAssert anyIt(anumbers, it > 9) == false
+
+block: # toSeq test
+  block:
+    let
+      numeric = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
+      oddNumbers = toSeq(filter(numeric) do (x: int) -> bool:
+        if x mod 2 == 1:
+          result = true)
+    doAssert oddNumbers == @[1, 3, 5, 7, 9]
+
+  block:
+    doAssert [1, 2].toSeq == @[1, 2]
+    doAssert @[1, 2].toSeq == @[1, 2]
+
+    doAssert @[1, 2].toSeq == @[1, 2]
+    doAssert toSeq(@[1, 2]) == @[1, 2]
+
+  block:
+    iterator myIter(seed: int): auto =
+      for i in 0..<seed:
+        yield i
+    doAssert toSeq(myIter(2)) == @[0, 1]
+
+  block:
+    iterator myIter(): auto {.inline.} =
+      yield 1
+      yield 2
+
+    doAssert myIter.toSeq == @[1, 2]
+    doAssert toSeq(myIter) == @[1, 2]
+
+  when not defined(js):
+    # pending #4695
+    block:
+        iterator myIter(): int {.closure.} =
+          yield 1
+          yield 2
+
+        doAssert myIter.toSeq == @[1, 2]
+        doAssert toSeq(myIter) == @[1, 2]
+
+    block:
+      proc myIter(): auto =
+        iterator ret(): int {.closure.} =
+          yield 1
+          yield 2
+        result = ret
+
+      doAssert myIter().toSeq == @[1, 2]
+      doAssert toSeq(myIter()) == @[1, 2]
+
+    block:
+      proc myIter(n: int): auto =
+        var counter = 0
+        iterator ret(): int {.closure.} =
+          while counter < n:
+            yield counter
+            counter.inc
+        result = ret
+
+      block:
+        let myIter3 = myIter(3)
+        doAssert myIter3.toSeq == @[0, 1, 2]
+      block:
+        let myIter3 = myIter(3)
+        doAssert toSeq(myIter3) == @[0, 1, 2]
+      block:
+        # makes sure this does not hang forever
+        doAssert myIter(3).toSeq == @[0, 1, 2]
+        doAssert toSeq(myIter(3)) == @[0, 1, 2]
+
+block:
+  # tests https://github.com/nim-lang/Nim/issues/7187
+  counter = 0
+  let ret = toSeq(@[1, 2, 3].identity().filter(proc (x: int): bool = x < 3))
+  doAssert ret == @[1, 2]
+  doAssert counter == 1
+block: # foldl tests
+  let
+    numbers = @[5, 9, 11]
+    addition = foldl(numbers, a + b)
+    subtraction = foldl(numbers, a - b)
+    multiplication = foldl(numbers, a * b)
+    words = @["nim", "is", "cool"]
+    concatenation = foldl(words, a & b)
+  doAssert addition == 25, "Addition is (((5)+9)+11)"
+  doAssert subtraction == -15, "Subtraction is (((5)-9)-11)"
+  doAssert multiplication == 495, "Multiplication is (((5)*9)*11)"
+  doAssert concatenation == "nimiscool"
+
+block: # foldr tests
+  let
+    numbers = @[5, 9, 11]
+    addition = foldr(numbers, a + b)
+    subtraction = foldr(numbers, a - b)
+    multiplication = foldr(numbers, a * b)
+    words = @["nim", "is", "cool"]
+    concatenation = foldr(words, a & b)
+  doAssert addition == 25, "Addition is (5+(9+(11)))"
+  doAssert subtraction == 7, "Subtraction is (5-(9-(11)))"
+  doAssert multiplication == 495, "Multiplication is (5*(9*(11)))"
+  doAssert concatenation == "nimiscool"
+  doAssert toSeq(1..3).foldr(a + b) == 6 # issue #14404
+
+block: # mapIt + applyIt test
+  counter = 0
+  var
+    nums = @[1, 2, 3, 4]
+    strings = nums.identity.mapIt($(4 * it))
+  doAssert counter == 1
+  nums.applyIt(it * 3)
+  doAssert nums[0] + nums[3] == 15
+  doAssert strings[2] == "12"
+
+block: # newSeqWith tests
+  var seq2D = newSeqWith(4, newSeq[bool](2))
+  seq2D[0][0] = true
+  seq2D[1][0] = true
+  seq2D[0][1] = true
+  doAssert seq2D == @[@[true, true], @[true, false], @[false, false], @[false, false]]
+
+block: # bug #21538
+  var x: seq[int] = @[2, 4]
+  var y = newSeqWith(x.pop(), true)
+  doAssert y == @[true, true, true, true]
+
+block: # mapLiterals tests
+  let x = mapLiterals([0.1, 1.2, 2.3, 3.4], int)
+  doAssert x is array[4, int]
+  doAssert mapLiterals((1, ("abc"), 2), float, nested = false) ==
+    (float(1), "abc", float(2))
+  doAssert mapLiterals(([1], ("abc"), 2), `$`, nested = true) ==
+    (["1"], "abc", "2")
+
+block: # mapIt with openArray
+  counter = 0
+  proc foo(x: openArray[int]): seq[int] = x.mapIt(it * 10)
+  doAssert foo([identity(1), identity(2)]) == @[10, 20]
+  doAssert counter == 2
+
+block: # mapIt with direct openArray
+  proc foo1(x: openArray[int]): seq[int] = x.mapIt(it * 10)
+  counter = 0
+  doAssert foo1(openArray[int]([identity(1), identity(2)])) == @[10, 20]
+  doAssert counter == 2
+
+  # Corner cases (openArray literals should not be common)
+  template foo2(x: openArray[int]): seq[int] = x.mapIt(it * 10)
+  counter = 0
+  doAssert foo2(openArray[int]([identity(1), identity(2)])) == @[10, 20]
+  doAssert counter == 2
+
+  counter = 0
+  doAssert openArray[int]([identity(1), identity(2)]).mapIt(it) == @[1, 2]
+  doAssert counter == 2
+
+block: # mapIt empty test, see https://github.com/nim-lang/Nim/pull/8584#pullrequestreview-144723468
+  # NOTE: `[].mapIt(it)` is illegal, just as `let a = @[]` is (lacks type
+  # of elements)
+  doAssert: not compiles(mapIt(@[], it))
+  doAssert: not compiles(mapIt([], it))
+  doAssert newSeq[int](0).mapIt(it) == @[]
+
+block: # mapIt redifinition check, see https://github.com/nim-lang/Nim/issues/8580
+  let s2 = [1, 2].mapIt(it)
+  doAssert s2 == @[1, 2]
+
+block:
+  counter = 0
+  doAssert [1, 2].identity().mapIt(it*2).mapIt(it*10) == @[20, 40]
+  # https://github.com/nim-lang/Nim/issues/7187 test case
+  doAssert counter == 1
+
+block: # mapIt with invalid RHS for `let` (#8566)
+  type X = enum
+    A, B
+  doAssert mapIt(X, $it) == @["A", "B"]
+
+block:
+  # bug #9093
+  let inp = "a:b,c:d"
+
+  let outp = inp.split(",").mapIt(it.split(":"))
+  doAssert outp == @[@["a", "b"], @["c", "d"]]
+
+
+block:
+  proc iter(len: int): auto =
+    result = iterator(): int =
+      for i in 0..<len:
+        yield i
+
+  # xxx: obscure CT error: basic_types.nim(16, 16) Error: internal error: symbol has no generated name: true
+  when not defined(js):
+    doAssert: iter(3).mapIt(2*it).foldl(a + b) == 6
+
+block: # strictFuncs tests with ref object
+  type Foo = ref object
+
+  let foo1 = Foo()
+  let foo2 = Foo()
+  let foos = @[foo1, foo2]
+
+  # Procedures that are `func`
+  discard concat(foos, foos)
+  discard count(foos, foo1)
+  discard cycle(foos, 3)
+  discard deduplicate(foos)
+  discard minIndex(foos)
+  discard maxIndex(foos)
+  discard distribute(foos, 2)
+  var mutableFoos = foos
+  mutableFoos.delete(0..1)
+  mutableFoos.insert(foos)
+
+  # Some procedures that are `proc`, but were reverted from `func`
+  discard repeat(foo1, 3)
+  discard zip(foos, foos)
+  let fooTuples = @[(foo1, 1), (foo2, 2)]
+  discard unzip(fooTuples)
+
+template main =
+  # xxx move all tests here
+  block: # delete tests
+    let outcome = @[1, 1, 1, 1, 1, 1, 1, 1]
+    var dest = @[1, 1, 1, 2, 2, 2, 2, 2, 2, 1, 1, 1, 1, 1]
+    dest.delete(3, 8)
+    doAssert outcome == dest, """\
+    Deleting range 3-9 from [1,1,1,2,2,2,2,2,2,1,1,1,1,1]
+    is [1,1,1,1,1,1,1,1]"""
+    var x = @[1, 2, 3]
+    x.delete(100, 100)
+    doAssert x == @[1, 2, 3]
+
+  block: # delete tests
+    var a = @[10, 11, 12, 13, 14]
+    doAssertRaises(IndexDefect): a.delete(4..5)
+    doAssertRaises(IndexDefect): a.delete(4..<6)
+    doAssertRaises(IndexDefect): a.delete(-1..1)
+    doAssertRaises(IndexDefect): a.delete(-1 .. -1)
+    doAssertRaises(IndexDefect): a.delete(5..5)
+    doAssertRaises(IndexDefect): a.delete(5..3)
+    doAssertRaises(IndexDefect): a.delete(5..<5) # edge case
+    doAssert a == @[10, 11, 12, 13, 14]
+    a.delete(4..4)
+    doAssert a == @[10, 11, 12, 13]
+    a.delete(1..2)
+    doAssert a == @[10, 13]
+    a.delete(1..<1) # empty slice
+    doAssert a == @[10, 13]
+    a.delete(0..<0)
+    doAssert a == @[10, 13]
+    a.delete(0..0)
+    doAssert a == @[13]
+    a.delete(0..0)
+    doAssert a == @[]
+    doAssertRaises(IndexDefect): a.delete(0..0)
+    doAssertRaises(IndexDefect): a.delete(0..<0) # edge case
+    block:
+      type A = object
+        a0: int
+      var a = @[A(a0: 10), A(a0: 11), A(a0: 12)]
+      a.delete(0..1)
+      doAssert a == @[A(a0: 12)]
+    block:
+      type A = ref object
+      let a0 = A()
+      let a1 = A()
+      let a2 = A()
+      var a = @[a0, a1, a2]
+      a.delete(0..1)
+      doAssert a == @[a2]
+
+static: main()
+main()
+
+{.pop.}
diff --git a/tests/stdlib/tsetutils.nim b/tests/stdlib/tsetutils.nim
new file mode 100644
index 000000000..c8498f23e
--- /dev/null
+++ b/tests/stdlib/tsetutils.nim
@@ -0,0 +1,49 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+import std/setutils
+import std/assertions
+
+type 
+  Colors = enum
+    red, green = 5, blue = 10
+  Bar = enum
+    bar0 = -1, bar1, bar2
+
+template main =
+  block: # toSet
+    doAssert "abcbb".toSet == {'a', 'b', 'c'}
+    doAssert toSet([10u8, 12, 13]) == {10u8, 12, 13}
+    doAssert toSet(0u16..30) == {0u16..30}
+    type A = distinct char
+    doAssert [A('x')].toSet == {A('x')}
+
+  block: # fullSet
+    doAssert fullSet(Colors) == {red, green, blue}
+    doAssert fullSet(char) == {0.chr..255.chr}
+    doAssert fullSet(Bar) == {bar0, bar1, bar2}
+    doAssert fullSet(bool) == {true, false}
+
+  block: # complement
+    doAssert {red, blue}.complement == {green}
+    doAssert (complement {red, green, blue}).card == 0
+    doAssert (complement {false}) == {true}
+    doAssert {bar0}.complement == {bar1, bar2}
+    doAssert {range[0..10](0), 1, 2, 3}.complement == {range[0..10](4), 5, 6, 7, 8, 9, 10}
+    doAssert {'0'..'9'}.complement == {0.char..255.char} - {'0'..'9'}
+
+  block: # `[]=`
+    type A = enum
+      a0, a1, a2, a3
+    var s = {a0, a3}
+    s[a0] = false
+    s[a1] = false
+    doAssert s == {a3}
+    s[a2] = true
+    s[a3] = true
+    doAssert s == {a2, a3}
+
+main()
+static: main()
diff --git a/tests/stdlib/tsharedlist.nim b/tests/stdlib/tsharedlist.nim
new file mode 100644
index 000000000..b91302d19
--- /dev/null
+++ b/tests/stdlib/tsharedlist.nim
@@ -0,0 +1,49 @@
+discard """
+  matrix: "--mm:orc; --mm:refc"
+"""
+
+import std/sharedlist
+import std/assertions
+
+block:
+  var
+    list: SharedList[int]
+    count: int
+
+  init(list)
+
+  for i in 1 .. 250:
+    list.add i
+
+  for i in list:
+    inc count
+
+  doAssert count == 250
+
+  deinitSharedList(list)
+
+
+block: # bug #17696
+  var keysList = SharedList[string]()
+  init(keysList)
+
+  keysList.add("a")
+  keysList.add("b")
+  keysList.add("c")
+  keysList.add("d")
+  keysList.add("e")
+  keysList.add("f")
+
+
+  # Remove element "b" and "d" from the list. 
+  keysList.iterAndMutate(proc (key: string): bool =
+    if key == "b" or key == "d": # remove only "b" and "d"
+      return true
+    return false
+  )
+
+  var results: seq[string]
+  for key in keysList.items:
+    results.add key
+
+  doAssert results == @["a", "f", "c", "e"]
diff --git a/tests/stdlib/tsharedtable.nim b/tests/stdlib/tsharedtable.nim
index 99d20e08a..10ad5f658 100644
--- a/tests/stdlib/tsharedtable.nim
+++ b/tests/stdlib/tsharedtable.nim
@@ -1,15 +1,90 @@
 discard """
-cmd: "nim $target --threads:on $options $file"
+matrix: "--mm:refc; --mm:orc"
 output: '''
 '''
 """
 
 import sharedtables
+import std/assertions
 
-var table: SharedTable[int, int]
+block:
+  var table: SharedTable[int, int]
 
-init(table)
-table[1] = 10
-assert table.mget(1) == 10
-assert table.mgetOrPut(3, 7) == 7
-assert table.mgetOrPut(3, 99) == 7
+  init(table)
+  table[1] = 10
+  doAssert table.mget(1) == 10
+  doAssert table.mgetOrPut(3, 7) == 7
+  doAssert table.mgetOrPut(3, 99) == 7
+  deinitSharedTable(table)
+
+import sequtils, algorithm
+proc sortedPairs[T](t: T): auto = toSeq(t.pairs).sorted
+template sortedItems(t: untyped): untyped = sorted(toSeq(t))
+
+import tables # refs issue #13504
+
+block: # we use Table as groundtruth, it's well tested elsewhere
+  template testDel(t, t0) =
+    template put2(i) =
+      t[i] = i
+      t0[i] = i
+
+    template add2(i, val) =
+      t.add(i, val)
+      t0.add(i, val)
+
+    template del2(i) =
+      t.del(i)
+      t0.del(i)
+
+    template checkEquals() =
+      doAssert t.len == t0.len
+      for k,v in t0:
+        doAssert t.mgetOrPut(k, -1) == v # sanity check
+        doAssert t.mget(k) == v
+
+    let n = 100
+    let n2 = n*2
+    let n3 = n*3
+    let n4 = n*4
+    let n5 = n*5
+
+    for i in 0..<n:
+      put2(i)
+    for i in 0..<n:
+      if i mod 3 == 0:
+        del2(i)
+    for i in n..<n2:
+      put2(i)
+    for i in 0..<n2:
+      if i mod 7 == 0:
+        del2(i)
+
+    checkEquals()
+
+    for i in n2..<n3:
+      t0[i] = -2
+      doAssert t.mgetOrPut(i, -2) == -2
+      doAssert t.mget(i) == -2
+
+    for i in 0..<n4:
+      let ok = i in t0
+      if not ok: t0[i] = -i
+      doAssert t.hasKeyOrPut(i, -i) == ok
+
+    checkEquals()
+
+    for i in n4..<n5:
+      add2(i, i*10)
+      add2(i, i*11)
+      add2(i, i*12)
+      del2(i)
+      del2(i)
+
+    checkEquals()
+
+  var t: SharedTable[int, int]
+  init(t) # ideally should be auto-init
+  var t0: Table[int, int]
+  testDel(t, t0)
+  deinitSharedTable(t)
diff --git a/tests/stdlib/tsince.nim b/tests/stdlib/tsince.nim
new file mode 100644
index 000000000..a0a4229cb
--- /dev/null
+++ b/tests/stdlib/tsince.nim
@@ -0,0 +1,32 @@
+import std/private/since
+import std/assertions
+
+proc fun1(): int {.since: (1, 3).} = 12
+proc fun1Bad(): int {.since: (99, 3).} = 12
+proc fun2(): int {.since: (1, 3, 1).} = 12
+proc fun2Bad(): int {.since: (99, 3, 1).} = 12
+
+doAssert fun1() == 12
+doAssert declared(fun1)
+doAssert not declared(fun1Bad)
+
+doAssert fun2() == 12
+doAssert declared(fun2)
+doAssert not declared(fun2Bad)
+
+var ok = false
+since (1, 3):
+  ok = true
+doAssert ok
+
+ok = false
+since (1, 3, 1):
+  ok = true
+doAssert ok
+
+since (99, 3):
+  doAssert false
+
+template fun3(): int {.since: (1, 3).} = 12
+
+doAssert declared(fun3)
diff --git a/tests/stdlib/tsocketstreams.nim b/tests/stdlib/tsocketstreams.nim
new file mode 100644
index 000000000..a37e7c34c
--- /dev/null
+++ b/tests/stdlib/tsocketstreams.nim
@@ -0,0 +1,65 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  output: '''
+OM
+NIM
+3
+NIM
+NIM
+Hello server!
+Hi there client!
+'''"""
+import std/socketstreams, net, streams
+
+block UDP:
+  var recvSocket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
+  var recvStream = newReadSocketStream(recvSocket)
+  recvSocket.bindAddr(Port(12345), "127.0.0.1")
+
+  var sendSocket = newSocket(AF_INET, SOCK_DGRAM, IPPROTO_UDP)
+  sendSocket.connect("127.0.0.1", Port(12345))
+  var sendStream = newWriteSocketStream(sendSocket)
+  sendStream.write "NOM\n"
+  sendStream.setPosition(1)
+  echo sendStream.peekStr(2)
+  sendStream.write "I"
+  sendStream.setPosition(0)
+  echo sendStream.readStr(3)
+  echo sendStream.getPosition()
+  sendStream.flush()
+
+  echo recvStream.readLine()
+  recvStream.setPosition(0)
+  echo recvStream.readLine()
+  recvStream.close()
+
+block TCP:
+  var server = newSocket()
+  server.setSockOpt(OptReusePort, true)
+  server.bindAddr(Port(12345))
+  server.listen()
+
+  var
+    client = newSocket()
+    clientRequestStream = newWriteSocketStream(client)
+    clientResponseStream = newReadSocketStream(client)
+  client.connect("127.0.0.1", Port(12345))
+  clientRequestStream.writeLine("Hello server!")
+  clientRequestStream.flush()
+
+  var
+    incoming: Socket
+    address: string
+  server.acceptAddr(incoming, address)
+  var
+    serverRequestStream = newReadSocketStream(incoming)
+    serverResponseStream = newWriteSocketStream(incoming)
+  echo serverRequestStream.readLine()
+  serverResponseStream.writeLine("Hi there client!")
+  serverResponseStream.flush()
+  serverResponseStream.close()
+  serverRequestStream.close()
+
+  echo clientResponseStream.readLine()
+  clientResponseStream.close()
+  clientRequestStream.close()
diff --git a/tests/stdlib/tsortcall.nim b/tests/stdlib/tsortcall.nim
index 242e3fe4c..32e004921 100644
--- a/tests/stdlib/tsortcall.nim
+++ b/tests/stdlib/tsortcall.nim
@@ -1,5 +1,5 @@
 discard """
-outputsub: ""
+  matrix: "--mm:refc; --mm:orc"
 """
 
 import algorithm
diff --git a/tests/stdlib/tsqlitebindatas.nim b/tests/stdlib/tsqlitebindatas.nim
new file mode 100644
index 000000000..e69de29bb
--- /dev/null
+++ b/tests/stdlib/tsqlitebindatas.nim
diff --git a/tests/stdlib/tsqlparser.nim b/tests/stdlib/tsqlparser.nim
index 11ee22e2b..6f123f21d 100644
--- a/tests/stdlib/tsqlparser.nim
+++ b/tests/stdlib/tsqlparser.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: '''true'''
 """
 
diff --git a/tests/stdlib/tssl.nim b/tests/stdlib/tssl.nim
new file mode 100644
index 000000000..1628b9326
--- /dev/null
+++ b/tests/stdlib/tssl.nim
@@ -0,0 +1,138 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  joinable: false
+  disabled: "freebsd" # see #15713
+  disabled: "openbsd" # see #15713
+  disabled: "netbsd" # see #15713
+"""
+
+import std/[net, nativesockets, assertions, typedthreads]
+
+when defined(posix): import os, posix
+else:
+  import winlean
+  const SD_SEND = 1
+
+when not defined(ssl):
+  {.error: "This test must be compiled with -d:ssl".}
+
+const DummyData = "dummy data\n"
+
+proc abruptShutdown(port: Port) {.thread.} =
+  let clientContext = newContext(verifyMode = CVerifyNone)
+  var client = newSocket(buffered = false)
+  clientContext.wrapSocket(client)
+  client.connect("localhost", port)
+
+  discard client.recvLine()
+  client.getFd.close()
+
+proc notifiedShutdown(port: Port) {.thread.} =
+  let clientContext = newContext(verifyMode = CVerifyNone)
+  var client = newSocket(buffered = false)
+  clientContext.wrapSocket(client)
+  client.connect("localhost", port)
+
+  discard client.recvLine()
+  client.close()
+
+proc main() =
+  when defined(posix):
+    var
+      ignoreAction = Sigaction(sa_handler: SIG_IGN)
+      oldSigPipeHandler: Sigaction
+    if sigemptyset(ignoreAction.sa_mask) == -1:
+      raiseOSError(osLastError(), "Couldn't create an empty signal set")
+    if sigaction(SIGPIPE, ignoreAction, oldSigPipeHandler) == -1:
+      raiseOSError(osLastError(), "Couldn't ignore SIGPIPE")
+
+  let serverContext = newContext(verifyMode = CVerifyNone,
+                                 certFile = "tests/testdata/mycert.pem",
+                                 keyFile = "tests/testdata/mycert.pem")
+
+  block peer_close_during_write_without_shutdown:
+    var server = newSocket(buffered = false)
+    defer: server.close()
+    serverContext.wrapSocket(server)
+    server.bindAddr(address = "localhost")
+    let (_, port) = server.getLocalAddr()
+    server.listen()
+
+    var clientThread: Thread[Port]
+    createThread(clientThread, abruptShutdown, port)
+
+    var peer: Socket
+    try:
+      server.accept(peer)
+      peer.send(DummyData)
+
+      joinThread clientThread
+
+      while true:
+        # Send data until we get EPIPE.
+        peer.send(DummyData, {})
+    except OSError:
+      discard
+    finally:
+      peer.close()
+
+  when defined(posix):
+    if sigaction(SIGPIPE, oldSigPipeHandler, nil) == -1:
+      raiseOSError(osLastError(), "Couldn't restore SIGPIPE handler")
+
+  block peer_close_before_received_shutdown:
+    var server = newSocket(buffered = false)
+    defer: server.close()
+    serverContext.wrapSocket(server)
+    server.bindAddr(address = "localhost")
+    let (_, port) = server.getLocalAddr()
+    server.listen()
+
+    var clientThread: Thread[Port]
+    createThread(clientThread, abruptShutdown, port)
+
+    var peer: Socket
+    try:
+      server.accept(peer)
+      peer.send(DummyData)
+
+      joinThread clientThread
+
+      # Tell the OS to close off the write side so shutdown attempts will
+      # be met with SIGPIPE.
+      when defined(posix):
+        discard peer.getFd.shutdown(SHUT_WR)
+      else:
+        discard peer.getFd.shutdown(SD_SEND)
+    finally:
+      peer.close()
+
+  block peer_close_after_received_shutdown:
+    var server = newSocket(buffered = false)
+    defer: server.close()
+    serverContext.wrapSocket(server)
+    server.bindAddr(address = "localhost")
+    let (_, port) = server.getLocalAddr()
+    server.listen()
+
+    var clientThread: Thread[Port]
+    createThread(clientThread, notifiedShutdown, port)
+
+    var peer: Socket
+    try:
+      server.accept(peer)
+      peer.send(DummyData)
+
+      doAssert peer.recv(1024) == "" # Get the shutdown notification
+      joinThread clientThread
+
+      # Tell the OS to close off the write side so shutdown attempts will
+      # be met with SIGPIPE.
+      when defined(posix):
+        discard peer.getFd.shutdown(SHUT_WR)
+      else:
+        discard peer.getFd.shutdown(SD_SEND)
+    finally:
+      peer.close()
+
+when isMainModule: main()
diff --git a/tests/stdlib/tssl.nims b/tests/stdlib/tssl.nims
new file mode 100644
index 000000000..4739e7f07
--- /dev/null
+++ b/tests/stdlib/tssl.nims
@@ -0,0 +1,5 @@
+--threads:on
+--d:ssl
+when defined(freebsd) or defined(netbsd):
+  # See https://github.com/nim-lang/Nim/pull/15066#issuecomment-665541265 and https://github.com/nim-lang/Nim/issues/15493
+  --tlsEmulation:off
diff --git a/tests/stdlib/tstackframes.nim b/tests/stdlib/tstackframes.nim
new file mode 100644
index 000000000..b0f05d51d
--- /dev/null
+++ b/tests/stdlib/tstackframes.nim
@@ -0,0 +1,34 @@
+import std/[strformat,os,osproc,assertions]
+import stdtest/unittest_light
+
+proc main(opt: string, expected: string) =
+  const nim = getCurrentCompilerExe()
+  const file = currentSourcePath().parentDir / "mstackframes.nim"
+  let cmd = fmt"{nim} c -r --excessiveStackTrace:off --stacktraceMsgs:{opt} --hints:off {file}"
+  let (output, exitCode) = execCmdEx(cmd)
+  assertEquals output, expected
+  doAssert exitCode == 0
+
+main("on"): """
+mstackframes.nim(38)     mstackframes
+mstackframes.nim(29)     main
+  z: 0
+  z: 1
+mstackframes.nim(20)     main2 ("main2", 5, 1)
+mstackframes.nim(20)     main2 ("main2", 4, 2)
+mstackframes.nim(20)     main2 ("main2", 3, 3)
+mstackframes.nim(19)     main2 ("main2", 2, 4)
+mstackframes.nim(18)     bar ("bar ",)
+
+"""
+
+main("off"): """
+mstackframes.nim(38)     mstackframes
+mstackframes.nim(29)     main
+mstackframes.nim(20)     main2
+mstackframes.nim(20)     main2
+mstackframes.nim(20)     main2
+mstackframes.nim(19)     main2
+mstackframes.nim(18)     bar
+
+"""
diff --git a/tests/stdlib/tstaticos.nim b/tests/stdlib/tstaticos.nim
new file mode 100644
index 000000000..41ab995dd
--- /dev/null
+++ b/tests/stdlib/tstaticos.nim
@@ -0,0 +1,8 @@
+import std/[assertions, staticos, os]
+
+block:
+  static:
+    doAssert staticDirExists("MISSINGFILE") == false
+    doAssert staticFileExists("MISSINGDIR") == false
+    doAssert staticDirExists(currentSourcePath().parentDir)
+    doAssert staticFileExists(currentSourcePath())
diff --git a/tests/stdlib/tstats.nim b/tests/stdlib/tstats.nim
new file mode 100644
index 000000000..728d93d09
--- /dev/null
+++ b/tests/stdlib/tstats.nim
@@ -0,0 +1,61 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/[stats, assertions]
+import std/math
+
+
+func `~=`(x, y: float32): bool =
+  math.almostEqual(x, y)
+
+template main() =
+  var rs: RunningStat
+  rs.push(@[1.0, 2.0, 1.0, 4.0, 1.0, 4.0, 1.0, 2.0])
+  doAssert(rs.n == 8)
+  doAssert rs.mean ~= 2.0
+  doAssert rs.variance() ~= 1.5
+  doAssert rs.varianceS() ~= 1.71428571
+  doAssert rs.skewness() ~= 0.81649658
+  doAssert rs.skewnessS() ~= 1.01835015
+  doAssert rs.kurtosis() ~= -1.0
+  doAssert rs.kurtosisS() ~= -0.7000000000000001
+
+  var rs1, rs2: RunningStat
+  rs1.push(@[1.0, 2.0, 1.0, 4.0])
+  rs2.push(@[1.0, 4.0, 1.0, 2.0])
+  let rs3 = rs1 + rs2
+  doAssert rs3.variance ~= rs.variance
+  doAssert rs3.skewness ~= rs.skewness
+  doAssert rs3.kurtosis ~= rs.kurtosis
+  rs1 += rs2
+  doAssert rs1.variance ~= rs.variance
+  doAssert rs1.skewness ~= rs.skewness
+  doAssert rs1.kurtosis ~= rs.kurtosis
+  rs1.clear()
+  rs1.push(@[1.0, 2.2, 1.4, 4.9])
+  doAssert rs1.sum ~= 9.5
+  doAssert rs1.mean() ~= 2.375
+
+  when not defined(cpu32):
+    # XXX For some reason on 32bit CPUs these results differ
+    var rr: RunningRegress
+    rr.push(@[0.0, 1.0, 2.8, 3.0, 4.0], @[0.0, 1.0, 2.3, 3.0, 4.0])
+    doAssert rr.slope() ~= 0.9695585996955861
+    doAssert rr.intercept() ~= -0.03424657534246611
+    doAssert rr.correlation() ~= 0.9905100362239381
+    var rr1, rr2: RunningRegress
+    rr1.push(@[0.0, 1.0], @[0.0, 1.0])
+    rr2.push(@[2.8, 3.0, 4.0], @[2.3, 3.0, 4.0])
+    let rr3 = rr1 + rr2
+    doAssert rr3.correlation() ~= rr.correlation()
+    doAssert rr3.slope() ~= rr.slope()
+    doAssert rr3.intercept() ~= rr.intercept()
+
+  block: # bug #18718
+    var rs: RunningStat
+    rs.push(-1.0)
+    doAssert rs.max == -1.0
+
+static: main()
+main()
diff --git a/tests/stdlib/tstdlib_issues.nim b/tests/stdlib/tstdlib_issues.nim
index b5a1c8206..b7b806db8 100644
--- a/tests/stdlib/tstdlib_issues.nim
+++ b/tests/stdlib/tstdlib_issues.nim
@@ -1,4 +1,5 @@
 discard """
+matrix: "--mm:refc; --mm:orc"
 output: '''
 02
 1
@@ -17,7 +18,7 @@ Second readLine raised an exception
 '''
 """
 
-import terminal, colors, re, encodings, strutils, os
+import std/[terminal, colors, re, encodings, strutils, os, assertions, syncio]
 
 
 block t9394:
@@ -43,7 +44,7 @@ block tcount:
 
   # bubble sort
   for i in low(arr)..high(arr):
-    for j in i+1..high(arr): # Error: unhandled exception: value out of range: 5 [RangeError]
+    for j in i+1..high(arr): # Error: unhandled exception: value out of range: 5 [RangeDefect]
       if arr[i] > arr[j]:
         let tmp = arr[i]
         arr[i] = arr[j]
@@ -77,7 +78,7 @@ block t5349:
   const fn = "file9char.txt"
   writeFile(fn, "123456789")
 
-  var f = system.open(fn)
+  var f = syncio.open(fn)
   echo getFileSize(f)
 
   var line = newString(10)
diff --git a/tests/stdlib/tstdlib_various.nim b/tests/stdlib/tstdlib_various.nim
index d1723df78..bac5018fa 100644
--- a/tests/stdlib/tstdlib_various.nim
+++ b/tests/stdlib/tstdlib_various.nim
@@ -1,4 +1,5 @@
 discard """
+matrix: "--mm:refc"
 output: '''
 abc
 def
@@ -20,27 +21,20 @@ Hi Andreas! How do you feel, Rumpf?
 @[0, 2, 1]
 @[0, 1, 2]
 055this should be the casehugh@["(", "+", " 1", " 2", ")"]
-caught a crash!
-caught a crash!
-caught a crash!
-caught a crash!
-caught a crash!
-caught a crash!
 [5]
 [4, 5]
 [3, 4, 5]
 [2, 3, 4, 5]
 [2, 3, 4, 5, 6]
 [1, 2, 3, 4, 5, 6]
-true
 <h1><a href="http://force7.de/nim">Nim</a></h1>
 '''
 """
 
 import
-  critbits, sets, strutils, tables, random, algorithm, re, ropes, segfaults,
-  lists, parsesql, streams, os, htmlgen, xmltree, strtabs
-
+  std/[critbits, sets, strutils, tables, random, algorithm, re, ropes,
+  segfaults, lists, parsesql, streams, os, htmlgen, xmltree, strtabs]
+import std/[syncio, assertions]
 
 block tcritbits:
   var r: CritBitTree[void]
@@ -60,15 +54,15 @@ block tcritbits:
 
 
 block testequivalence:
-  doAssert(toSet(@[1,2,3]) <= toSet(@[1,2,3,4]), "equivalent or subset")
-  doAssert(toSet(@[1,2,3]) <= toSet(@[1,2,3]), "equivalent or subset")
-  doAssert((not(toSet(@[1,2,3]) <= toSet(@[1,2]))), "equivalent or subset")
-  doAssert(toSet(@[1,2,3]) <= toSet(@[1,2,3,4]), "strict subset")
-  doAssert((not(toSet(@[1,2,3]) < toSet(@[1,2,3]))), "strict subset")
-  doAssert((not(toSet(@[1,2,3]) < toSet(@[1,2]))), "strict subset")
-  doAssert((not(toSet(@[1,2,3]) == toSet(@[1,2,3,4]))), "==")
-  doAssert(toSet(@[1,2,3]) == toSet(@[1,2,3]), "==")
-  doAssert((not(toSet(@[1,2,3]) == toSet(@[1,2]))), "==")
+  doAssert(toHashSet(@[1,2,3]) <= toHashSet(@[1,2,3,4]), "equivalent or subset")
+  doAssert(toHashSet(@[1,2,3]) <= toHashSet(@[1,2,3]), "equivalent or subset")
+  doAssert((not(toHashSet(@[1,2,3]) <= toHashSet(@[1,2]))), "equivalent or subset")
+  doAssert(toHashSet(@[1,2,3]) <= toHashSet(@[1,2,3,4]), "strict subset")
+  doAssert((not(toHashSet(@[1,2,3]) < toHashSet(@[1,2,3]))), "strict subset")
+  doAssert((not(toHashSet(@[1,2,3]) < toHashSet(@[1,2]))), "strict subset")
+  doAssert((not(toHashSet(@[1,2,3]) == toHashSet(@[1,2,3,4]))), "==")
+  doAssert(toHashSet(@[1,2,3]) == toHashSet(@[1,2,3]), "==")
+  doAssert((not(toHashSet(@[1,2,3]) == toHashSet(@[1,2]))), "==")
 
 
 
@@ -161,18 +155,21 @@ block tropes:
 
 
 block tsegfaults:
-  proc main =
-    try:
-      var x: ptr int
-      echo x[]
+  when not defined(arm64):
+    var crashes = 0
+    proc main =
       try:
-        raise newException(ValueError, "not a crash")
-      except ValueError:
-        discard
-    except NilAccessError:
-      echo "caught a crash!"
-  for i in 0..5:
-    main()
+        var x: ptr int
+        echo x[]
+        try:
+          raise newException(ValueError, "not a crash")
+        except ValueError:
+          discard
+      except NilAccessDefect:
+        inc crashes
+    for i in 0..5:
+      main()
+    assert crashes == 6
 
 
 
@@ -209,11 +206,7 @@ block tsplit2:
     s.add("#")
     s.add(w)
 
-  try:
-    discard "hello".split("")
-    echo "false"
-  except AssertionError:
-    echo "true"
+  doAssert "true".split("") == @["true"]
 
 
 
diff --git a/tests/stdlib/tstrbasics.nim b/tests/stdlib/tstrbasics.nim
new file mode 100644
index 000000000..a965ff15f
--- /dev/null
+++ b/tests/stdlib/tstrbasics.nim
@@ -0,0 +1,103 @@
+discard """
+  targets: "c cpp js"
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/[strbasics, sugar, assertions]
+
+template strip2(input: string, args: varargs[untyped]): untyped =
+  var a = input
+  when varargsLen(args) > 0:
+    strip(a, args)
+  else:
+    strip(a)
+  a
+
+proc main() =
+  block: # strip
+    block: # bug #17173
+      var a = "  vhellov   "
+      strip(a)
+      doAssert a == "vhellov"
+
+    doAssert strip2("  vhellov   ") == "vhellov"
+    doAssert strip2("  vhellov   ", leading = false) == "  vhellov"
+    doAssert strip2("  vhellov   ", trailing = false) == "vhellov   "
+    doAssert strip2("vhellov", chars = {'v'}) == "hello"
+    doAssert strip2("vhellov", leading = false, chars = {'v'}) == "vhello"
+    doAssert strip2("blaXbla", chars = {'b', 'a'}) == "laXbl"
+    doAssert strip2("blaXbla", chars = {'b', 'a', 'l'}) == "X"
+    doAssert strip2("xxxxxx", chars={'x'}) == ""
+    doAssert strip2("x", chars={'x'}) == ""
+    doAssert strip2("x", chars={'1'}) == "x"
+    doAssert strip2("", chars={'x'}) == ""
+    doAssert strip2("xxx xxx", chars={'x'}) == " "
+    doAssert strip2("xxx  wind", chars={'x'}) == "  wind"
+    doAssert strip2("xxx  iii", chars={'i'}) == "xxx  "
+
+    block:
+      var a = "xxx  iii"
+      doAssert a.dup(strip(chars = {'i'})) == "xxx  "
+      doAssert a.dup(strip(chars = {' '})) == "xxx  iii"
+      doAssert a.dup(strip(chars = {'x'})) == "  iii"
+      doAssert a.dup(strip(chars = {'x', ' '})) == "iii"
+      doAssert a.dup(strip(chars = {'x', 'i'})) == "  "
+      doAssert a.dup(strip(chars = {'x', 'i', ' '})).len == 0
+
+    block:
+      var a = "x  i"
+      doAssert a.dup(strip(chars = {'i'})) == "x  "
+      doAssert a.dup(strip(chars = {' '})) == "x  i"
+      doAssert a.dup(strip(chars = {'x'})) == "  i"
+      doAssert a.dup(strip(chars = {'x', ' '})) == "i"
+      doAssert a.dup(strip(chars = {'x', 'i'})) == "  "
+      doAssert a.dup(strip(chars = {'x', 'i', ' '})).len == 0
+
+    block:
+      var a = ""
+      doAssert a.dup(strip(chars = {'i'})).len == 0
+      doAssert a.dup(strip(chars = {' '})).len == 0
+      doAssert a.dup(strip(chars = {'x'})).len == 0
+      doAssert a.dup(strip(chars = {'x', ' '})).len == 0
+      doAssert a.dup(strip(chars = {'x', 'i'})).len == 0
+      doAssert a.dup(strip(chars = {'x', 'i', ' '})).len == 0
+
+    block:
+      var a = " "
+      doAssert a.dup(strip(chars = {'i'})) == " "
+      doAssert a.dup(strip(chars = {' '})).len == 0
+      doAssert a.dup(strip(chars = {'x'})) == " "
+      doAssert a.dup(strip(chars = {'x', ' '})).len == 0
+      doAssert a.dup(strip(chars = {'x', 'i'})) == " "
+      doAssert a.dup(strip(chars = {'x', 'i', ' '})).len == 0
+
+  block: # setSlice
+    var a = "Hello, Nim!"
+    doAssert a.dup(setSlice(7 .. 9)) == "Nim"
+    doAssert a.dup(setSlice(0 .. 0)) == "H"
+    doAssert a.dup(setSlice(0 .. 1)) == "He"
+    doAssert a.dup(setSlice(0 .. 10)) == a
+    doAssert a.dup(setSlice(1 .. 0)).len == 0
+    doAssert a.dup(setSlice(20 .. -1)).len == 0
+
+    doAssertRaises(AssertionDefect):
+      discard a.dup(setSlice(-1 .. 1))
+
+    doAssertRaises(AssertionDefect):
+      discard a.dup(setSlice(1 .. 11))
+
+  block: # add
+    var a0 = "hi"
+    var b0 = "foobar"
+    when nimvm:
+      discard # pending bug #15952
+    else:
+      a0.add b0.toOpenArray(1,3)
+      doAssert a0 == "hioob"
+    proc fn(c: openArray[char]): string =
+      result.add c
+    doAssert fn("def") == "def"
+    doAssert fn(['d','\0', 'f'])[2] == 'f'
+
+static: main()
+main()
diff --git a/tests/stdlib/tstreams.nim b/tests/stdlib/tstreams.nim
index 559824d85..60c63b450 100644
--- a/tests/stdlib/tstreams.nim
+++ b/tests/stdlib/tstreams.nim
@@ -1,17 +1,22 @@
 discard """
-input: "Arne"
-output: '''
+  matrix: "--mm:refc; --mm:orc"
+  input: "Arne"
+  output: '''
 Hello! What is your name?
 Nice name: Arne
 fs is: nil
-
 threw exception
+_heh_
+'''
+  nimout: '''
+I
+AM
+GROOT
 '''
-disabled: "windows"
 """
 
 
-import streams
+import std/[syncio, streams, assertions]
 
 
 block tstreams:
@@ -36,5 +41,67 @@ block tstreams2:
 block tstreams3:
   try:
     var fs = openFileStream("shouldneverexist.txt")
-  except IoError:
+  except IOError:
     echo "threw exception"
+
+  static:
+    var s = newStringStream("I\nAM\nGROOT")
+    for line in s.lines:
+      echo line
+    s.close
+
+
+block:
+  let fs = newFileStream("amissingfile.txt")
+  defer: fs.close()
+  doAssert isNil(fs)
+
+# bug #12410
+
+var a = newStringStream "hehohihahuhyh"
+a.readDataStrImpl = nil
+
+var buffer = "_ooo_"
+
+doAssert a.readDataStr(buffer, 1..3) == 3
+
+echo buffer
+
+
+block:
+  var ss = newStringStream("The quick brown fox jumped over the lazy dog.\nThe lazy dog ran")
+  doAssert(ss.getPosition == 0)
+  doAssert(ss.peekStr(5) == "The q")
+  doAssert(ss.getPosition == 0) # haven't moved
+  doAssert(ss.readStr(5) == "The q")
+  doAssert(ss.getPosition == 5) # did move
+  doAssert(ss.peekLine() == "uick brown fox jumped over the lazy dog.")
+  doAssert(ss.getPosition == 5) # haven't moved
+  var str = newString(100)
+  doAssert(ss.peekLine(str))
+  doAssert(str == "uick brown fox jumped over the lazy dog.")
+  doAssert(ss.getPosition == 5) # haven't moved
+  # bug #19707 - Ensure we dont error with writing over literals on arc/orc
+  ss.setPosition(0)
+  ss.write("hello")
+  ss.setPosition(0)
+  doAssert(ss.peekStr(5) == "hello")
+
+# bug #19716
+static: # Ensure streams it doesnt break with nimscript on arc/orc #19716
+  let s = newStringStream("a")
+  doAssert s.data == "a"
+
+static: # issue #24054, readStr
+  var s = newStringStream("foo bar baz")
+  doAssert s.readStr(3) == "foo"
+
+template main =
+  var strm = newStringStream("abcde")
+  var buffer = "12345"
+  doAssert strm.readDataStr(buffer, 0..3) == 4
+  doAssert buffer == "abcd5"
+  strm.close()
+
+static: main()
+main()
diff --git a/tests/stdlib/tstreams2.nim b/tests/stdlib/tstreams2.nim
deleted file mode 100644
index 70f0bac32..000000000
--- a/tests/stdlib/tstreams2.nim
+++ /dev/null
@@ -1,12 +0,0 @@
-discard """
-  output: '''fs is: nil'''
-"""
-import streams
-var
-  fs = newFileStream("amissingfile.txt")
-  line = ""
-echo "fs is: ",repr(fs)
-if not isNil(fs):
-  while fs.readLine(line):
-    echo line
-  fs.close()
diff --git a/tests/stdlib/tstreams3.nim b/tests/stdlib/tstreams3.nim
deleted file mode 100644
index 89f45f275..000000000
--- a/tests/stdlib/tstreams3.nim
+++ /dev/null
@@ -1,20 +0,0 @@
-discard """
-  output: "threw exception"
-  nimout: '''
-I
-AM
-GROOT
-'''
-"""
-import streams
-
-try:
-  var fs = openFileStream("shouldneverexist.txt")
-except IoError:
-  echo "threw exception"
-
-static:
-  var s = newStringStream("I\nAM\nGROOT")
-  for line in s.lines:
-    echo line
-  s.close
diff --git a/tests/stdlib/tstrformat.nim b/tests/stdlib/tstrformat.nim
index 403372aed..ff406f898 100644
--- a/tests/stdlib/tstrformat.nim
+++ b/tests/stdlib/tstrformat.nim
@@ -1,175 +1,590 @@
 discard """
-action: "run"
-output: '''Received (name: "Foo", species: "Bar")'''
+  matrix: "--mm:refc; --mm:orc"
 """
 
-# issue #7632
-
 import genericstrformat
+import std/[strformat, strutils, times, tables, json]
+
+import std/[assertions, formatfloat]
+import std/objectdollar
+
+proc main() =
+  block: # issue #7632
+    doAssert works(5) == "formatted  5"
+    doAssert fails0(6) == "formatted  6"
+    doAssert fails(7) == "formatted  7"
+    doAssert fails2[0](8) == "formatted  8"
+
+  block: # other tests
+    type Obj = object
+
+    proc `$`(o: Obj): string = "foobar"
+
+    # for custom types, formatValue needs to be overloaded.
+    template formatValue(result: var string; value: Obj; specifier: string) =
+      result.formatValue($value, specifier)
+
+    var o: Obj
+    doAssert fmt"{o}" == "foobar"
+    doAssert fmt"{o:10}" == "foobar    "
+
+    doAssert fmt"{o=}" == "o=foobar"
+    doAssert fmt"{o=:10}" == "o=foobar    "
+
+  block: # see issue #7933
+    var str = "abc"
+    doAssert fmt">7.1 :: {str:>7.1}" == ">7.1 ::       a"
+    doAssert fmt">7.2 :: {str:>7.2}" == ">7.2 ::      ab"
+    doAssert fmt">7.3 :: {str:>7.3}" == ">7.3 ::     abc"
+    doAssert fmt">7.9 :: {str:>7.9}" == ">7.9 ::     abc"
+    doAssert fmt">7.0 :: {str:>7.0}" == ">7.0 ::        "
+    doAssert fmt" 7.1 :: {str:7.1}" == " 7.1 :: a      "
+    doAssert fmt" 7.2 :: {str:7.2}" == " 7.2 :: ab     "
+    doAssert fmt" 7.3 :: {str:7.3}" == " 7.3 :: abc    "
+    doAssert fmt" 7.9 :: {str:7.9}" == " 7.9 :: abc    "
+    doAssert fmt" 7.0 :: {str:7.0}" == " 7.0 ::        "
+    doAssert fmt"^7.1 :: {str:^7.1}" == "^7.1 ::    a   "
+    doAssert fmt"^7.2 :: {str:^7.2}" == "^7.2 ::   ab   "
+    doAssert fmt"^7.3 :: {str:^7.3}" == "^7.3 ::   abc  "
+    doAssert fmt"^7.9 :: {str:^7.9}" == "^7.9 ::   abc  "
+    doAssert fmt"^7.0 :: {str:^7.0}" == "^7.0 ::        "
+
+    doAssert fmt">7.1 :: {str=:>7.1}" == ">7.1 :: str=      a"
+    doAssert fmt">7.2 :: {str=:>7.2}" == ">7.2 :: str=     ab"
+    doAssert fmt">7.3 :: {str=:>7.3}" == ">7.3 :: str=    abc"
+    doAssert fmt">7.9 :: {str=:>7.9}" == ">7.9 :: str=    abc"
+    doAssert fmt">7.0 :: {str=:>7.0}" == ">7.0 :: str=       "
+    doAssert fmt" 7.1 :: {str=:7.1}" == " 7.1 :: str=a      "
+    doAssert fmt" 7.2 :: {str=:7.2}" == " 7.2 :: str=ab     "
+    doAssert fmt" 7.3 :: {str=:7.3}" == " 7.3 :: str=abc    "
+    doAssert fmt" 7.9 :: {str=:7.9}" == " 7.9 :: str=abc    "
+    doAssert fmt" 7.0 :: {str=:7.0}" == " 7.0 :: str=       "
+    doAssert fmt"^7.1 :: {str=:^7.1}" == "^7.1 :: str=   a   "
+    doAssert fmt"^7.2 :: {str=:^7.2}" == "^7.2 :: str=  ab   "
+    doAssert fmt"^7.3 :: {str=:^7.3}" == "^7.3 :: str=  abc  "
+    doAssert fmt"^7.9 :: {str=:^7.9}" == "^7.9 :: str=  abc  "
+    doAssert fmt"^7.0 :: {str=:^7.0}" == "^7.0 :: str=       "
+    str = "äöüe\u0309\u0319o\u0307\u0359"
+    doAssert fmt"^7.1 :: {str:^7.1}" == "^7.1 ::    ä   "
+    doAssert fmt"^7.2 :: {str:^7.2}" == "^7.2 ::   äö   "
+    doAssert fmt"^7.3 :: {str:^7.3}" == "^7.3 ::   äöü  "
+    doAssert fmt"^7.0 :: {str:^7.0}" == "^7.0 ::        "
+
+    doAssert fmt"^7.1 :: {str=:^7.1}" == "^7.1 :: str=   ä   "
+    doAssert fmt"^7.2 :: {str=:^7.2}" == "^7.2 :: str=  äö   "
+    doAssert fmt"^7.3 :: {str=:^7.3}" == "^7.3 :: str=  äöü  "
+    doAssert fmt"^7.0 :: {str=:^7.0}" == "^7.0 :: str=       "
+    # this is actually wrong, but the unicode module has no support for graphemes
+    doAssert fmt"^7.4 :: {str:^7.4}" == "^7.4 ::  äöüe  "
+    doAssert fmt"^7.9 :: {str:^7.9}" == "^7.9 :: äöüe\u0309\u0319o\u0307\u0359"
+
+    doAssert fmt"^7.4 :: {str=:^7.4}" == "^7.4 :: str= äöüe  "
+    doAssert fmt"^7.9 :: {str=:^7.9}" == "^7.9 :: str=äöüe\u0309\u0319o\u0307\u0359"
 
-doAssert works(5) == "formatted  5"
-doAssert fails0(6) == "formatted  6"
-doAssert fails(7) == "formatted  7"
-doAssert fails2[0](8) == "formatted  8"
-
-# other tests
-
-import strformat
-
-type Obj = object
-
-proc `$`(o: Obj): string = "foobar"
-
-# for custom types, formatValue needs to be overloaded.
-template formatValue(result: var string; value: Obj; specifier: string) =
-  result.formatValue($value, specifier)
-
-var o: Obj
-doAssert fmt"{o}" == "foobar"
-doAssert fmt"{o:10}" == "foobar    "
-
-# see issue #7933
-var str = "abc"
-doAssert fmt">7.1 :: {str:>7.1}" == ">7.1 ::       a"
-doAssert fmt">7.2 :: {str:>7.2}" == ">7.2 ::      ab"
-doAssert fmt">7.3 :: {str:>7.3}" == ">7.3 ::     abc"
-doAssert fmt">7.9 :: {str:>7.9}" == ">7.9 ::     abc"
-doAssert fmt">7.0 :: {str:>7.0}" == ">7.0 ::        "
-doAssert fmt" 7.1 :: {str:7.1}" == " 7.1 :: a      "
-doAssert fmt" 7.2 :: {str:7.2}" == " 7.2 :: ab     "
-doAssert fmt" 7.3 :: {str:7.3}" == " 7.3 :: abc    "
-doAssert fmt" 7.9 :: {str:7.9}" == " 7.9 :: abc    "
-doAssert fmt" 7.0 :: {str:7.0}" == " 7.0 ::        "
-doAssert fmt"^7.1 :: {str:^7.1}" == "^7.1 ::    a   "
-doAssert fmt"^7.2 :: {str:^7.2}" == "^7.2 ::   ab   "
-doAssert fmt"^7.3 :: {str:^7.3}" == "^7.3 ::   abc  "
-doAssert fmt"^7.9 :: {str:^7.9}" == "^7.9 ::   abc  "
-doAssert fmt"^7.0 :: {str:^7.0}" == "^7.0 ::        "
-str = "äöüe\u0309\u0319o\u0307\u0359"
-doAssert fmt"^7.1 :: {str:^7.1}" == "^7.1 ::    ä   "
-doAssert fmt"^7.2 :: {str:^7.2}" == "^7.2 ::   äö   "
-doAssert fmt"^7.3 :: {str:^7.3}" == "^7.3 ::   äöü  "
-doAssert fmt"^7.0 :: {str:^7.0}" == "^7.0 ::        "
-# this is actually wrong, but the unicode module has no support for graphemes
-doAssert fmt"^7.4 :: {str:^7.4}" == "^7.4 ::  äöüe  "
-doAssert fmt"^7.9 :: {str:^7.9}" == "^7.9 :: äöüe\u0309\u0319o\u0307\u0359"
-
-# see issue #7932
-doAssert fmt"{15:08}" == "00000015" # int, works
-doAssert fmt"{1.5:08}" == "000001.5" # float, works
-doAssert fmt"{1.5:0>8}" == "000001.5" # workaround using fill char works for positive floats
-doAssert fmt"{-1.5:0>8}" == "0000-1.5" # even that does not work for negative floats
-doAssert fmt"{-1.5:08}" == "-00001.5" # works
-doAssert fmt"{1.5:+08}" == "+00001.5" # works
-doAssert fmt"{1.5: 08}" == " 00001.5" # works
-
-# only add explicitly requested sign if value != -0.0 (neg zero)
-doAssert fmt"{-0.0:g}" == "-0"
-doassert fmt"{-0.0:+g}" == "-0"
-doassert fmt"{-0.0: g}" == "-0"
-doAssert fmt"{0.0:g}" == "0"
-doAssert fmt"{0.0:+g}" == "+0"
-doAssert fmt"{0.0: g}" == " 0"
-
-# seq format
-
-let data1 = [1'i64, 10000'i64, 10000000'i64]
-let data2 = [10000000'i64, 100'i64, 1'i64]
-
-proc formatValue(result: var string; value: (array|seq|openArray); specifier: string) =
-  result.add "["
-  for i, it in value:
-    if i != 0:
+  block: # see issue #7932
+    doAssert fmt"{15:08}" == "00000015" # int, works
+    doAssert fmt"{1.5:08}" == "000001.5" # float, works
+    doAssert fmt"{1.5:0>8}" == "000001.5" # workaround using fill char works for positive floats
+    doAssert fmt"{-1.5:0>8}" == "0000-1.5" # even that does not work for negative floats
+    doAssert fmt"{-1.5:08}" == "-00001.5" # works
+    doAssert fmt"{1.5:+08}" == "+00001.5" # works
+    doAssert fmt"{1.5: 08}" == " 00001.5" # works
+
+    doAssert fmt"{15=:08}" == "15=00000015" # int, works
+    doAssert fmt"{1.5=:08}" == "1.5=000001.5" # float, works
+    doAssert fmt"{1.5=:0>8}" == "1.5=000001.5" # workaround using fill char works for positive floats
+    doAssert fmt"{-1.5=:0>8}" == "-1.5=0000-1.5" # even that does not work for negative floats
+    doAssert fmt"{-1.5=:08}" == "-1.5=-00001.5" # works
+    doAssert fmt"{1.5=:+08}" == "1.5=+00001.5" # works
+    doAssert fmt"{1.5=: 08}" == "1.5= 00001.5" # works
+
+  block: # only add explicitly requested sign if value != -0.0 (neg zero)
+    doAssert fmt"{-0.0:g}" == "-0"
+    doAssert fmt"{-0.0:+g}" == "-0"
+    doAssert fmt"{-0.0: g}" == "-0"
+    doAssert fmt"{0.0:g}" == "0"
+    doAssert fmt"{0.0:+g}" == "+0"
+    doAssert fmt"{0.0: g}" == " 0"
+
+    doAssert fmt"{-0.0=:g}" == "-0.0=-0"
+    doAssert fmt"{-0.0=:+g}" == "-0.0=-0"
+    doAssert fmt"{-0.0=: g}" == "-0.0=-0"
+    doAssert fmt"{0.0=:g}" == "0.0=0"
+    doAssert fmt"{0.0=:+g}" == "0.0=+0"
+    doAssert fmt"{0.0=: g}" == "0.0= 0"
+
+  block: # seq format
+    let data1 = [1'i64, 10000'i64, 10000000'i64]
+    let data2 = [10000000'i64, 100'i64, 1'i64]
+
+    proc formatValue(result: var string; value: (array|seq|openArray); specifier: string) =
+      result.add "["
+      for i, it in value:
+        if i != 0:
+          result.add ", "
+        result.formatValue(it, specifier)
+      result.add "]"
+
+    doAssert fmt"data1: {data1:8} #" == "data1: [       1,    10000, 10000000] #"
+    doAssert fmt"data2: {data2:8} =" == "data2: [10000000,      100,        1] ="
+
+    doAssert fmt"data1: {data1=:8} #" == "data1: data1=[       1,    10000, 10000000] #"
+    doAssert fmt"data2: {data2=:8} =" == "data2: data2=[10000000,      100,        1] ="
+
+  block: # custom format Value
+    type
+      Vec2[T] = object
+        x,y: T
+
+    proc formatValue[T](result: var string; value: Vec2[T]; specifier: string) =
+      result.add '['
+      result.formatValue value.x, specifier
       result.add ", "
-    result.formatValue(it, specifier)
-  result.add "]"
-
-doAssert fmt"data1: {data1:8} #" == "data1: [       1,    10000, 10000000] #"
-doAssert fmt"data2: {data2:8} =" == "data2: [10000000,      100,        1] ="
-
-# custom format Value
-
-type
-  Vec2[T] = object
-    x,y: T
-
-proc formatValue[T](result: var string; value: Vec2[T]; specifier: string) =
-  result.add '['
-  result.formatValue value.x, specifier
-  result.add ", "
-  result.formatValue value.y, specifier
-  result.add "]"
-
-let v1 = Vec2[float32](x:1.0, y: 2.0)
-let v2 = Vec2[int32](x:1, y: 1337)
-doAssert fmt"v1: {v1:+08}  v2: {v2:>4}" == "v1: [+0000001, +0000002]  v2: [   1, 1337]"
-
-# bug #11012
-
-type
-  Animal = object
-    name, species: string
-  AnimalRef = ref Animal
-
-proc print_object(animalAddr: AnimalRef) =
-  echo fmt"Received {animalAddr[]}"
-
-print_object(AnimalRef(name: "Foo", species: "Bar"))
-
-# bug #11723
-
-let pos: Positive = 64
-doAssert fmt"{pos:3}" == " 64"
-doAssert fmt"{pos:3b}" == "1000000"
-doAssert fmt"{pos:3d}" == " 64"
-doAssert fmt"{pos:3o}" == "100"
-doAssert fmt"{pos:3x}" == " 40"
-doAssert fmt"{pos:3X}" == " 40"
-
-let nat: Natural = 64
-doAssert fmt"{nat:3}" == " 64"
-doAssert fmt"{nat:3b}" == "1000000"
-doAssert fmt"{nat:3d}" == " 64"
-doAssert fmt"{nat:3o}" == "100"
-doAssert fmt"{nat:3x}" == " 40"
-doAssert fmt"{nat:3X}" == " 40"
-
-# bug #12612
-proc my_proc =
-  const value = "value"
-  const a = &"{value}"
-  assert a == value
-
-my_proc()
-
-block:
-  template fmt(pattern: string; openCloseChar: char): untyped =
-    fmt(pattern, openCloseChar, openCloseChar)
-
-  let
-    testInt = 123
-    testStr = "foobar"
-    testFlt = 3.141592
-  doAssert ">><<".fmt('<', '>') == "><"
-  doAssert " >> << ".fmt('<', '>') == " > < "
-  doAssert "<<>>".fmt('<', '>') == "<>"
-  doAssert " << >> ".fmt('<', '>') == " < > "
-  doAssert "''".fmt('\'') == "'"
-  doAssert "''''".fmt('\'') == "''"
-  doAssert "'' ''".fmt('\'') == "' '"
-  doAssert "<testInt>".fmt('<', '>') == "123"
-  doAssert "<testInt>".fmt('<', '>') == "123"
-  doAssert "'testFlt:1.2f'".fmt('\'') == "3.14"
-  doAssert "<testInt><testStr>".fmt('<', '>') == "123foobar"
-  doAssert """ ""{"123+123"}"" """.fmt('"') == " \"{246}\" "
-  doAssert "(((testFlt:1.2f)))((111))".fmt('(', ')') == "(3.14)(111)"
-  doAssert """(()"foo" & "bar"())""".fmt(')', '(') == "(foobar)"
-  doAssert "{}abc`testStr' `testFlt:1.2f' `1+1' ``".fmt('`', '\'') == "{}abcfoobar 3.14 2 `"
-  doAssert """x = '"foo" & "bar"'
-              y = '123 + 111'
-              z = '3 in {2..7}'
-           """.fmt('\'') ==
-           """x = foobar
-              y = 234
-              z = true
-           """
+      result.formatValue value.y, specifier
+      result.add "]"
+
+    let v1 = Vec2[float32](x:1.0, y: 2.0)
+    let v2 = Vec2[int32](x:1, y: 1337)
+    doAssert fmt"v1: {v1:+08}  v2: {v2:>4}" == "v1: [+0000001, +0000002]  v2: [   1, 1337]"
+    doAssert fmt"v1: {v1=:+08}  v2: {v2=:>4}" == "v1: v1=[+0000001, +0000002]  v2: v2=[   1, 1337]"
+
+  block: # bug #11012
+    type
+      Animal = object
+        name, species: string
+      AnimalRef = ref Animal
+
+    proc print_object(animalAddr: AnimalRef): string =
+      fmt"Received {animalAddr[]}"
+
+    doAssert print_object(AnimalRef(name: "Foo", species: "Bar")) == """Received (name: "Foo", species: "Bar")"""
+
+  block: # bug #11723
+    let pos: Positive = 64
+    doAssert fmt"{pos:3}" == " 64"
+    doAssert fmt"{pos:3b}" == "1000000"
+    doAssert fmt"{pos:3d}" == " 64"
+    doAssert fmt"{pos:3o}" == "100"
+    doAssert fmt"{pos:3x}" == " 40"
+    doAssert fmt"{pos:3X}" == " 40"
+
+    doAssert fmt"{pos=:3}" == "pos= 64"
+    doAssert fmt"{pos=:3b}" == "pos=1000000"
+    doAssert fmt"{pos=:3d}" == "pos= 64"
+    doAssert fmt"{pos=:3o}" == "pos=100"
+    doAssert fmt"{pos=:3x}" == "pos= 40"
+    doAssert fmt"{pos=:3X}" == "pos= 40"
+
+    let nat: Natural = 64
+    doAssert fmt"{nat:3}" == " 64"
+    doAssert fmt"{nat:3b}" == "1000000"
+    doAssert fmt"{nat:3d}" == " 64"
+    doAssert fmt"{nat:3o}" == "100"
+    doAssert fmt"{nat:3x}" == " 40"
+    doAssert fmt"{nat:3X}" == " 40"
+
+    doAssert fmt"{nat=:3}" == "nat= 64"
+    doAssert fmt"{nat=:3b}" == "nat=1000000"
+    doAssert fmt"{nat=:3d}" == "nat= 64"
+    doAssert fmt"{nat=:3o}" == "nat=100"
+    doAssert fmt"{nat=:3x}" == "nat= 40"
+    doAssert fmt"{nat=:3X}" == "nat= 40"
+
+  block: # bug #12612
+    proc my_proc() =
+      const value = "value"
+      const a = &"{value}"
+      doAssert a == value
+
+      const b = &"{value=}"
+      doAssert b == "value=" & value
+
+    my_proc()
+
+  block:
+    template fmt(pattern: string; openCloseChar: char): untyped =
+      fmt(pattern, openCloseChar, openCloseChar)
+
+    let
+      testInt = 123
+      testStr = "foobar"
+      testFlt = 3.141592
+    doAssert ">><<".fmt('<', '>') == "><"
+    doAssert " >> << ".fmt('<', '>') == " > < "
+    doAssert "<<>>".fmt('<', '>') == "<>"
+    doAssert " << >> ".fmt('<', '>') == " < > "
+    doAssert "''".fmt('\'') == "'"
+    doAssert "''''".fmt('\'') == "''"
+    doAssert "'' ''".fmt('\'') == "' '"
+    doAssert "<testInt>".fmt('<', '>') == "123"
+    doAssert "<testInt>".fmt('<', '>') == "123"
+    doAssert "'testFlt:1.2f'".fmt('\'') == "3.14"
+    doAssert "<testInt><testStr>".fmt('<', '>') == "123foobar"
+    doAssert """ ""{"123+123"}"" """.fmt('"') == " \"{246}\" "
+    doAssert "(((testFlt:1.2f)))((111))".fmt('(', ')') == "(3.14)(111)"
+    doAssert """(()"foo" & "bar"())""".fmt(')', '(') == "(foobar)"
+    doAssert "{}abc`testStr' `testFlt:1.2f' `1+1' ``".fmt('`', '\'') == "{}abcfoobar 3.14 2 `"
+    doAssert """x = '"foo" & "bar"'
+                y = '123 + 111'
+                z = '3 in {2..7}'
+             """.fmt('\'') ==
+             """x = foobar
+                y = 234
+                z = true
+             """
+
+  block: # tests from the very own strformat documentation!
+    let msg = "hello"
+    doAssert fmt"{msg}\n" == "hello\\n"
+
+    doAssert &"{msg}\n" == "hello\n"
+
+    doAssert fmt"{msg}{'\n'}" == "hello\n"
+    doAssert fmt("{msg}\n") == "hello\n"
+    doAssert "{msg}\n".fmt == "hello\n"
+
+    doAssert fmt"{msg=}\n" == "msg=hello\\n"
+
+    doAssert &"{msg=}\n" == "msg=hello\n"
+
+    doAssert fmt"{msg=}{'\n'}" == "msg=hello\n"
+    doAssert fmt("{msg=}\n") == "msg=hello\n"
+    doAssert "{msg=}\n".fmt == "msg=hello\n"
+
+    doAssert &"""{"abc":>4}""" == " abc"
+    doAssert &"""{"abc":<4}""" == "abc "
+
+    doAssert fmt"{-12345:08}" == "-0012345"
+    doAssert fmt"{-1:3}" == " -1"
+    doAssert fmt"{-1:03}" == "-01"
+    doAssert fmt"{16:#X}" == "0x10"
+
+    doAssert fmt"{123.456}" == "123.456"
+    doAssert fmt"{123.456:>9.3f}" == "  123.456"
+    doAssert fmt"{123.456:9.3f}" == "  123.456"
+    doAssert fmt"{123.456:9.4f}" == " 123.4560"
+    doAssert fmt"{123.456:>9.0f}" == "     123."
+    doAssert fmt"{123.456:<9.4f}" == "123.4560 "
+
+    doAssert fmt"{123.456:e}" == "1.234560e+02"
+    doAssert fmt"{123.456:>13e}" == " 1.234560e+02"
+    doAssert fmt"{123.456:13e}" == " 1.234560e+02"
+
+    doAssert &"""{"abc"=:>4}""" == "\"abc\"= abc"
+    doAssert &"""{"abc"=:<4}""" == "\"abc\"=abc "
+
+    doAssert fmt"{-12345=:08}" == "-12345=-0012345"
+    doAssert fmt"{-1=:3}" == "-1= -1"
+    doAssert fmt"{-1=:03}" == "-1=-01"
+    doAssert fmt"{16=:#X}" == "16=0x10"
+
+    doAssert fmt"{123.456=}" == "123.456=123.456"
+    doAssert fmt"{123.456=:>9.3f}" == "123.456=  123.456"
+    doAssert fmt"{123.456=:9.3f}" == "123.456=  123.456"
+    doAssert fmt"{123.456=:9.4f}" == "123.456= 123.4560"
+    doAssert fmt"{123.456=:>9.0f}" == "123.456=     123."
+    doAssert fmt"{123.456=:<9.4f}" == "123.456=123.4560 "
+
+    doAssert fmt"{123.456=:e}" == "123.456=1.234560e+02"
+    doAssert fmt"{123.456=:>13e}" == "123.456= 1.234560e+02"
+    doAssert fmt"{123.456=:13e}" == "123.456= 1.234560e+02"
+
+    let x = 3.14
+    doAssert fmt"{(if x!=0: 1.0/x else: 0):.5}" == "0.31847"
+    doAssert fmt"""{(block:
+      var res: string
+      for i in 1..15:
+        res.add (if i mod 15 == 0: "FizzBuzz"
+          elif i mod 5 == 0: "Buzz"
+          elif i mod 3 == 0: "Fizz"
+          else: $i) & " "
+      res)}""" == "1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz "
+
+    doAssert fmt"""{ "\{(" & msg & ")\}" }""" == "{(hello)}"
+    doAssert fmt"""{{({ msg })}}""" == "{(hello)}"
+    doAssert fmt"""{ $(\{msg:1,"world":2\}) }""" == """[("hello", 1), ("world", 2)]"""
+  block: # tests for debug format string
+    var name = "hello"
+    let age = 21
+    const hobby = "swim"
+    doAssert fmt"{age*9 + 16=}" == "age*9 + 16=205"
+    doAssert &"name: {name    =}\nage: {  age  =: >7}\nhobby: {   hobby=  : 8}" ==
+          "name: name    =hello\nage:   age  =     21\nhobby:    hobby=  swim    "
+    doAssert fmt"{age  ==  12}" == "false"
+    doAssert fmt"{name.toUpperAscii() = }" == "name.toUpperAscii() = HELLO"
+    doAssert fmt"{name.toUpperAscii( ) =  }" == "name.toUpperAscii( ) =  HELLO"
+    doAssert fmt"{  toUpperAscii(  s  =  name  )  =   }" == "  toUpperAscii(  s  =  name  )  =   HELLO"
+    doAssert fmt"{  strutils.toUpperAscii(  s  =  name  )  =   }" == "  strutils.toUpperAscii(  s  =  name  )  =   HELLO"
+    doAssert fmt"{age==12}" == "false"
+    doAssert fmt"{age!= 12}" == "true"
+    doAssert fmt"{age  <=  12}" == "false"
+    for i in 1 .. 10:
+      doAssert fmt"{age.float =: .2f}" == "age.float = 21.00"
+    doAssert fmt"{age.float() =:.3f}" == "age.float() =21.000"
+    doAssert fmt"{float age=  :.3f}" == "float age=  21.000"
+    doAssert fmt"{12 == int(`!=`(age, 12))}" == "false"
+    doAssert fmt"{0==1}" == "false"
+
+  block: # It is space sensitive.
+    let x = "12"
+    doAssert fmt"{x=:}" == "x=12"
+    doAssert fmt"{x=}" == "x=12"
+    doAssert fmt"{x =:}" == "x =12"
+    doAssert fmt"{x =}" == "x =12"
+    doAssert fmt"{x= :}" == "x= 12"
+    doAssert fmt"{x= }" == "x= 12"
+    doAssert fmt"{x = :}" == "x = 12"
+    doAssert fmt"{x = }" == "x = 12"
+    doAssert fmt"{x   =  :}" == "x   =  12"
+    doAssert fmt"{x   =  }" == "x   =  12"
+
+  block:
+    let x = "hello"
+    doAssert fmt"{x=}" == "x=hello"
+    doAssert fmt"{x =}" == "x =hello"
+
+    let y = 3.1415926
+    doAssert fmt"{y=:.2f}" == fmt"y={y:.2f}"
+    doAssert fmt"{y=}" == fmt"y={y}"
+    doAssert fmt"{y = : <8}" == fmt"y = 3.14159 "
+
+    proc hello(a: string, b: float): int = 12
+    template foo(a: string, b: float): int = 18
+
+    doAssert fmt"{hello(x, y)=}" == "hello(x, y)=12"
+    doAssert fmt"{hello(x, y) =}" == "hello(x, y) =12"
+    doAssert fmt"{hello(x, y)= }" == "hello(x, y)= 12"
+    doAssert fmt"{hello(x, y) = }" == "hello(x, y) = 12"
+
+    doAssert fmt"{hello x, y=}" == "hello x, y=12"
+    doAssert fmt"{hello x, y =}" == "hello x, y =12"
+    doAssert fmt"{hello x, y= }" == "hello x, y= 12"
+    doAssert fmt"{hello x, y = }" == "hello x, y = 12"
+
+    doAssert fmt"{x.hello(y)=}" == "x.hello(y)=12"
+    doAssert fmt"{x.hello(y) =}" == "x.hello(y) =12"
+    doAssert fmt"{x.hello(y)= }" == "x.hello(y)= 12"
+    doAssert fmt"{x.hello(y) = }" == "x.hello(y) = 12"
+
+    doAssert fmt"{foo(x, y)=}" == "foo(x, y)=18"
+    doAssert fmt"{foo(x, y) =}" == "foo(x, y) =18"
+    doAssert fmt"{foo(x, y)= }" == "foo(x, y)= 18"
+    doAssert fmt"{foo(x, y) = }" == "foo(x, y) = 18"
+
+    doAssert fmt"{x.foo(y)=}" == "x.foo(y)=18"
+    doAssert fmt"{x.foo(y) =}" == "x.foo(y) =18"
+    doAssert fmt"{x.foo(y)= }" == "x.foo(y)= 18"
+    doAssert fmt"{x.foo(y) = }" == "x.foo(y) = 18"
+
+  block:
+    template check(actual, expected: string) =
+      doAssert actual == expected
+
+    # Basic tests
+    let s = "string"
+    check &"{0} {s}", "0 string"
+    check &"{s[0..2].toUpperAscii}", "STR"
+    check &"{-10:04}", "-010"
+    check &"{-10:<04}", "-010"
+    check &"{-10:>04}", "-010"
+    check &"0x{10:02X}", "0x0A"
+
+    check &"{10:#04X}", "0x0A"
+
+    check &"""{"test":#>5}""", "#test"
+    check &"""{"test":>5}""", " test"
+
+    check &"""{"test":#^7}""", "#test##"
+
+    check &"""{"test": <5}""", "test "
+    check &"""{"test":<5}""", "test "
+    check &"{1f:.3f}", "1.000"
+    check &"Hello, {s}!", "Hello, string!"
+
+    # Tests for identifiers without parenthesis
+    check &"{s} works{s}", "string worksstring"
+    check &"{s:>7}", " string"
+    doAssert(not compiles(&"{s_works}")) # parsed as identifier `s_works`
+
+    # Misc general tests
+    check &"{{}}", "{}"
+    check &"{0}%", "0%"
+    check &"{0}%asdf", "0%asdf"
+    check &("\n{\"\\n\"}\n"), "\n\n\n"
+    check &"""{"abc"}s""", "abcs"
+
+    # String tests
+    check &"""{"abc"}""", "abc"
+    check &"""{"abc":>4}""", " abc"
+    check &"""{"abc":<4}""", "abc "
+    check &"""{"":>4}""", "    "
+    check &"""{"":<4}""", "    "
+
+    # Int tests
+    check &"{12345}", "12345"
+    check &"{ - 12345}", "-12345"
+    check &"{12345:6}", " 12345"
+    check &"{12345:>6}", " 12345"
+    check &"{12345:4}", "12345"
+    check &"{12345:08}", "00012345"
+    check &"{-12345:08}", "-0012345"
+    check &"{0:0}", "0"
+    check &"{0:02}", "00"
+    check &"{-1:3}", " -1"
+    check &"{-1:03}", "-01"
+    check &"{10}", "10"
+    check &"{16:#X}", "0x10"
+    check &"{16:^#7X}", " 0x10  "
+    check &"{16:^+#7X}", " +0x10 "
+
+    # Hex tests
+    check &"{0:x}", "0"
+    check &"{-0:x}", "0"
+    check &"{255:x}", "ff"
+    check &"{255:X}", "FF"
+    check &"{-255:x}", "-ff"
+    check &"{-255:X}", "-FF"
+    check &"{255:x} uNaffeCteD CaSe", "ff uNaffeCteD CaSe"
+    check &"{255:X} uNaffeCteD CaSe", "FF uNaffeCteD CaSe"
+    check &"{255:4x}", "  ff"
+    check &"{255:04x}", "00ff"
+    check &"{-255:4x}", " -ff"
+    check &"{-255:04x}", "-0ff"
+
+    # Float tests
+    check &"{123.456}", "123.456"
+    check &"{-123.456}", "-123.456"
+    check &"{123.456:.3f}", "123.456"
+    check &"{123.456:+.3f}", "+123.456"
+    check &"{-123.456:+.3f}", "-123.456"
+    check &"{-123.456:.3f}", "-123.456"
+    check &"{123.456:1g}", "123.456"
+    check &"{123.456:.1f}", "123.5"
+    check &"{123.456:.0f}", "123."
+    check &"{123.456:>9.3f}", "  123.456"
+    check &"{123.456:9.3f}", "  123.456"
+    check &"{123.456:>9.4f}", " 123.4560"
+    check &"{123.456:>9.0f}", "     123."
+    check &"{123.456:<9.4f}", "123.4560 "
+
+    # Float (scientific) tests
+    check &"{123.456:e}", "1.234560e+02"
+    check &"{123.456:>13e}", " 1.234560e+02"
+    check &"{123.456:<13e}", "1.234560e+02 "
+    check &"{123.456:.1e}", "1.2e+02"
+    check &"{123.456:.2e}", "1.23e+02"
+    check &"{123.456:.3e}", "1.235e+02"
+
+    # Note: times.format adheres to the format protocol. Test that this
+    # works:
+    when nimvm:
+      discard
+    else:
+      var dt = dateTime(2000, mJan, 01, 00, 00, 00)
+      check &"{dt:yyyy-MM-dd}", "2000-01-01"
+
+      var tm = fromUnix(0)
+      discard &"{tm}"
+
+      var noww = now()
+      check &"{noww}", $noww
+
+    # Unicode string tests
+    check &"""{"αβγ"}""", "αβγ"
+    check &"""{"αβγ":>5}""", "  αβγ"
+    check &"""{"αβγ":<5}""", "αβγ  "
+    check &"""a{"a"}α{"α"}€{"€"}𐍈{"𐍈"}""", "aaαα€€𐍈𐍈"
+    check &"""a{"a":2}α{"α":2}€{"€":2}𐍈{"𐍈":2}""", "aa αα €€ 𐍈𐍈 "
+    # Invalid unicode sequences should be handled as plain strings.
+    # Invalid examples taken from: https://stackoverflow.com/a/3886015/1804173
+    let invalidUtf8 = [
+      "\xc3\x28", "\xa0\xa1",
+      "\xe2\x28\xa1", "\xe2\x82\x28",
+      "\xf0\x28\x8c\xbc", "\xf0\x90\x28\xbc", "\xf0\x28\x8c\x28"
+    ]
+    for s in invalidUtf8:
+      check &"{s:>5}", repeat(" ", 5-s.len) & s
+
+    # bug #11089
+    let flfoo: float = 1.0
+    check &"{flfoo}", "1.0"
+
+    # bug #11092
+    check &"{high(int64)}", "9223372036854775807"
+    check &"{low(int64)}", "-9223372036854775808"
+
+    doAssert fmt"{'a'} {'b'}" == "a b"
+
+  block: # test low(int64)
+    doAssert &"{low(int64):-}" == "-9223372036854775808"
+  block: #expressions plus formatting
+    doAssert fmt"{if true\: 123.456 else\: 0=:>9.3f}" == "if true: 123.456 else: 0=  123.456"
+    doAssert fmt"{(if true: 123.456 else: 0)=}" == "(if true: 123.456 else: 0)=123.456"
+    doAssert fmt"{if true\: 123.456 else\: 0=:9.3f}" == "if true: 123.456 else: 0=  123.456"
+    doAssert fmt"{(if true: 123.456 else: 0)=:9.4f}" == "(if true: 123.456 else: 0)= 123.4560"
+    doAssert fmt"{(if true: 123.456 else: 0)=:>9.0f}" == "(if true: 123.456 else: 0)=     123."
+    doAssert fmt"{if true\: 123.456 else\: 0=:<9.4f}" == "if true: 123.456 else: 0=123.4560 "
+
+    doAssert fmt"""{(case true
+      of false: 0.0
+      of true: 123.456)=:e}""" == """(case true
+      of false: 0.0
+      of true: 123.456)=1.234560e+02"""
+
+    doAssert fmt"""{block\:
+      var res = 0.000123456
+      for _ in 0..5\:
+        res *= 10
+      res=:>13e}""" == """block:
+      var res = 0.000123456
+      for _ in 0..5:
+        res *= 10
+      res= 1.234560e+02"""
+    #side effects
+    var x = 5
+    doAssert fmt"{(x=7;123.456)=:13e}" == "(x=7;123.456)= 1.234560e+02"
+    doAssert x==7
+  block: #curly bracket expressions and tuples
+    proc formatValue(result: var string; value:Table|bool|JsonNode; specifier:string) = result.add $value
+
+    doAssert fmt"""{\{"a"\:1,"b"\:2\}.toTable() = }""" == """{"a":1,"b":2}.toTable() = {"a": 1, "b": 2}"""
+    doAssert fmt"""{(\{3: (1,"hi",0.9),4: (4,"lo",1.1)\}).toTable()}""" == """{3: (1, "hi", 0.9), 4: (4, "lo", 1.1)}"""
+    doAssert fmt"""{ (%* \{"name": "Isaac", "books": ["Robot Dreams"]\}) }""" == """{"name":"Isaac","books":["Robot Dreams"]}"""
+    doAssert """%( \%\* {"name": "Isaac"})*""".fmt('%','*') == """{"name":"Isaac"}"""
+  block: #parens in quotes that fool my syntax highlighter
+    doAssert fmt"{(if true: ')' else: '(')}" == ")"
+    doAssert fmt"{(if true: ']' else: ')')}" == "]"
+    doAssert fmt"""{(if true: "\")\"" else: "\"(")}""" == """")""""
+    doAssert &"""{(if true: "\")" else: "")}""" == "\")"
+    doAssert &"{(if true: \"\\\")\" else: \"\")}" == "\")"
+    doAssert fmt"""{(if true: "')" else: "")}""" == "')"
+    doAssert fmt"""{(if true: "'" & "'" & ')' else: "")}""" == "'')"
+    doAssert &"""{(if true: "'" & "'" & ')' else: "")}""" == "'')"
+    doAssert &"{(if true: \"\'\" & \"'\" & ')' else: \"\")}" == "'')"
+    doAssert fmt"""{(if true: "'" & ')' else: "")}""" == "')"
+
+  block: # issue #20381
+    var ss: seq[string]
+    template myTemplate(s: string) =
+      ss.add s
+      ss.add s
+    proc foo() =
+      myTemplate fmt"hello"
+    foo()
+    doAssert ss == @["hello", "hello"]
+
+  block:
+    proc noraises() {.raises: [].} =
+      const
+        flt = 0.0
+        str = "str"
+
+      doAssert fmt"{flt} {str}" == "0.0 str"
+
+    noraises()
+
+  block:
+    doAssert not compiles(fmt"{formatting errors detected at compile time")
+
+static: main()
+main()
diff --git a/tests/stdlib/tstrformatlineinfo.nim b/tests/stdlib/tstrformatlineinfo.nim
new file mode 100644
index 000000000..3a7bf0d33
--- /dev/null
+++ b/tests/stdlib/tstrformatlineinfo.nim
@@ -0,0 +1,8 @@
+# issue #21759
+
+{.hint[ConvFromXToItselfNotNeeded]: on.}
+
+import std/strformat
+
+echo fmt"{string ""abc""}" #[tt.Hint
+        ^ conversion from string to itself is pointless]#
diff --git a/tests/stdlib/tstrimpl.nim b/tests/stdlib/tstrimpl.nim
new file mode 100644
index 000000000..a8933e53f
--- /dev/null
+++ b/tests/stdlib/tstrimpl.nim
@@ -0,0 +1,12 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/private/strimpl
+
+import std/assertions
+
+doAssert find(cstring"Hello Nim", cstring"Nim") == 6
+doAssert find(cstring"Hello Nim", cstring"N") == 6
+doAssert find(cstring"Hello Nim", cstring"I") == -1
+doAssert find(cstring"Hello Nim", cstring"O") == -1
diff --git a/tests/stdlib/tstring.nim b/tests/stdlib/tstring.nim
index 36a2e9800..b9b3c78a3 100644
--- a/tests/stdlib/tstring.nim
+++ b/tests/stdlib/tstring.nim
@@ -1,93 +1,124 @@
 discard """
-  output: '''OK
-@[@[], @[], @[], @[], @[]]
-'''
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
 """
-const characters = "abcdefghijklmnopqrstuvwxyz"
-const numbers = "1234567890"
-
-var s: string
-
-proc test_string_slice() =
-  # test "slice of length == len(characters)":
-  # replace characters completely by numbers
-  s = characters
-  s[0..^1] = numbers
-  doAssert s == numbers
-
-  # test "slice of length > len(numbers)":
-  # replace characters by slice of same length
-  s = characters
-  s[1..16] = numbers
-  doAssert s == "a1234567890rstuvwxyz"
-
-  # test "slice of length == len(numbers)":
-  # replace characters by slice of same length
-  s = characters
-  s[1..10] = numbers
-  doAssert s == "a1234567890lmnopqrstuvwxyz"
-
-  # test "slice of length < len(numbers)":
-  # replace slice of length. and insert remaining chars
-  s = characters
-  s[1..4] = numbers
-  doAssert s == "a1234567890fghijklmnopqrstuvwxyz"
-
-  # test "slice of length == 1":
-  # replace first character. and insert remaining 9 chars
-  s = characters
-  s[1..1] = numbers
-  doAssert s == "a1234567890cdefghijklmnopqrstuvwxyz"
-
-  # test "slice of length == 0":
-  # insert chars at slice start index
-  s = characters
-  s[2..1] = numbers
-  doAssert s == "ab1234567890cdefghijklmnopqrstuvwxyz"
-
-  # test "slice of negative length":
-  # same as slice of zero length
-  s = characters
-  s[2..0] = numbers
-  doAssert s == "ab1234567890cdefghijklmnopqrstuvwxyz"
-
-  # bug #6223
-  doAssertRaises(IndexError):
-    discard s[0..999]
-
-  echo("OK")
-
-proc test_string_cmp() =
-  let world = "hello\0world"
-  let earth = "hello\0earth"
-  let short = "hello\0"
-  let hello = "hello"
-  let goodbye = "goodbye"
-
-  doAssert world == world
-  doAssert world != earth
-  doAssert world != short
-  doAssert world != hello
-  doAssert world != goodbye
-
-  doAssert cmp(world, world) == 0
-  doAssert cmp(world, earth) > 0
-  doAssert cmp(world, short) > 0
-  doAssert cmp(world, hello) > 0
-  doAssert cmp(world, goodbye) > 0
-
-test_string_slice()
-test_string_cmp()
-
-
-#--------------------------
-# bug #7816
-import sugar
-import sequtils
+
+from std/sequtils import toSeq, map
+from std/sugar import `=>`
+import std/assertions
 
 proc tester[T](x: T) =
   let test = toSeq(0..4).map(i => newSeq[int]())
-  echo test
-
-tester(1)
-
+  doAssert $test == "@[@[], @[], @[], @[], @[]]"
+
+func reverse*(a: string): string =
+  result = a
+  for i in 0 ..< a.len div 2:
+    swap(result[i], result[^(i + 1)])
+
+proc main() =
+  block: # ..
+    const
+      characters = "abcdefghijklmnopqrstuvwxyz"
+      numbers = "1234567890"
+
+    # test "slice of length == len(characters)":
+    # replace characters completely by numbers
+    var s: string
+    s = characters
+    s[0..^1] = numbers
+    doAssert s == numbers
+
+    # test "slice of length > len(numbers)":
+    # replace characters by slice of same length
+    s = characters
+    s[1..16] = numbers
+    doAssert s == "a1234567890rstuvwxyz"
+
+    # test "slice of length == len(numbers)":
+    # replace characters by slice of same length
+    s = characters
+    s[1..10] = numbers
+    doAssert s == "a1234567890lmnopqrstuvwxyz"
+
+    # test "slice of length < len(numbers)":
+    # replace slice of length. and insert remaining chars
+    s = characters
+    s[1..4] = numbers
+    doAssert s == "a1234567890fghijklmnopqrstuvwxyz"
+
+    # test "slice of length == 1":
+    # replace first character. and insert remaining 9 chars
+    s = characters
+    s[1..1] = numbers
+    doAssert s == "a1234567890cdefghijklmnopqrstuvwxyz"
+
+    # test "slice of length == 0":
+    # insert chars at slice start index
+    s = characters
+    s[2..1] = numbers
+    doAssert s == "ab1234567890cdefghijklmnopqrstuvwxyz"
+
+    # test "slice of negative length":
+    # same as slice of zero length
+    s = characters
+    s[2..0] = numbers
+    doAssert s == "ab1234567890cdefghijklmnopqrstuvwxyz"
+
+    when nimvm:
+      discard
+    else:
+      # bug #6223
+      doAssertRaises(IndexDefect):
+        discard s[0..999]
+
+  block: # ==, cmp
+    let world = "hello\0world"
+    let earth = "hello\0earth"
+    let short = "hello\0"
+    let hello = "hello"
+    let goodbye = "goodbye"
+
+    doAssert world == world
+    doAssert world != earth
+    doAssert world != short
+    doAssert world != hello
+    doAssert world != goodbye
+
+    doAssert cmp(world, world) == 0
+    doAssert cmp(world, earth) > 0
+    doAssert cmp(world, short) > 0
+    doAssert cmp(world, hello) > 0
+    doAssert cmp(world, goodbye) > 0
+
+  block: # bug #7816
+    tester(1)
+
+  block: # bug #14497, reverse
+    doAssert reverse("hello") == "olleh"
+
+  block: # len, high
+    var a = "ab\0cd"
+    var b = a.cstring
+    doAssert a.len == 5
+    block: # bug #16405
+      when defined(js):
+        when nimvm: doAssert b.len == 2
+        else: doAssert b.len == 5
+      else: doAssert b.len == 2
+
+    doAssert a.high == a.len - 1
+    doAssert b.high == b.len - 1
+
+    doAssert "".len == 0
+    doAssert "".high == -1
+    doAssert "".cstring.len == 0
+    doAssert "".cstring.high == -1
+
+    block: # bug #16674
+      var c: cstring = nil
+      doAssert c.len == 0
+      doAssert c.high == -1
+
+static: main()
+main()
diff --git a/tests/stdlib/tstrmiscs.nim b/tests/stdlib/tstrmiscs.nim
new file mode 100644
index 000000000..b42f2e1fe
--- /dev/null
+++ b/tests/stdlib/tstrmiscs.nim
@@ -0,0 +1,27 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/strmisc
+import std/assertions
+
+
+doAssert expandTabs("\t", 4) == "    "
+doAssert expandTabs("\tfoo\t", 4) == "    foo "
+doAssert expandTabs("\tfoo\tbar", 4) == "    foo bar"
+doAssert expandTabs("\tfoo\tbar\t", 4) == "    foo bar "
+doAssert expandTabs("", 4) == ""
+doAssert expandTabs("", 0) == ""
+doAssert expandTabs("\t\t\t", 0) == ""
+
+doAssert partition("foo:bar", ":") == ("foo", ":", "bar")
+doAssert partition("foobarbar", "bar") == ("foo", "bar", "bar")
+doAssert partition("foobarbar", "bank") == ("foobarbar", "", "")
+doAssert partition("foobarbar", "foo") == ("", "foo", "barbar")
+doAssert partition("foofoobar", "bar") == ("foofoo", "bar", "")
+
+doAssert rpartition("foo:bar", ":") == ("foo", ":", "bar")
+doAssert rpartition("foobarbar", "bar") == ("foobar", "bar", "")
+doAssert rpartition("foobarbar", "bank") == ("", "", "foobarbar")
+doAssert rpartition("foobarbar", "foo") == ("", "foo", "barbar")
+doAssert rpartition("foofoobar", "bar") == ("foofoo", "bar", "")
diff --git a/tests/stdlib/tstrscans.nim b/tests/stdlib/tstrscans.nim
index 08fc14e45..ae7fd98ca 100644
--- a/tests/stdlib/tstrscans.nim
+++ b/tests/stdlib/tstrscans.nim
@@ -1,8 +1,8 @@
 discard """
-  output: ""
+  matrix: "--mm:refc; --mm:orc"
 """
 
-import strscans
+import std/[strscans, strutils, assertions]
 
 block ParsePasswd:
   proc parsePasswd(content: string): seq[string] =
@@ -15,7 +15,7 @@ block ParsePasswd:
       else:
         break
 
-  const etc_passwd = """root:x:0:0:root:/root:/bin/bash
+  const etcPasswd = """root:x:0:0:root:/root:/bin/bash
 daemon:x:1:1:daemon:/usr/sbin:/bin/sh
 bin:x:2:2:bin:/bin:/bin/sh
 sys:x:3:3:sys:/dev:/bin/sh
@@ -23,7 +23,7 @@ nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
 messagebus:x:103:107::/var/run/dbus:/bin/false
 """
 
-  const parsed_etc_passwd = @[
+  const parsedEtcPasswd = @[
     "root:x:0:0:root:/root:/bin/bash",
     "daemon:x:1:1:daemon:/usr/sbin:/bin/sh",
     "bin:x:2:2:bin:/bin:/bin/sh",
@@ -31,7 +31,7 @@ messagebus:x:103:107::/var/run/dbus:/bin/false
     "nobody:x:65534:65534:nobody:/nonexistent:/bin/sh",
     "messagebus:x:103:107::/var/run/dbus:/bin/false",
     ]
-  doAssert etc_passwd.parsePasswd == parsed_etc_passwd
+  doAssert etcPasswd.parsePasswd == parsedEtcPasswd
 
 block LastNot:
   var idx : int
@@ -79,8 +79,210 @@ block EmptyTuple:
 block Arrow:
   let text = "foo;bar;baz;"
   var idx = 0
-  var res = ""
   doAssert scanp(text, idx, +(~{';','\0'} -> (discard $_)), ';')
   doAssert scanp(text, idx, +(~{';','\0'} -> (discard $_)), ';')
   doAssert scanp(text, idx, +(~{';','\0'} -> (discard $_)), ';')
   doAssert scanp(text, idx, +(~{';','\0'} -> (discard $_)), ';') == false
+
+
+block issue15064:
+  var nick1, msg1: string
+  doAssert scanf("<abcd> a", "<$+> $+", nick1, msg1)
+  doAssert nick1 == "abcd"
+  doAssert msg1 == "a"
+
+  var nick2, msg2: string
+  doAssert(not scanf("<abcd> ", "<$+> $+", nick2, msg2))
+
+  var nick3, msg3: string
+  doAssert scanf("<abcd> ", "<$+> $*", nick3, msg3)
+  doAssert nick3 == "abcd"
+  doAssert msg3 == ""
+
+
+block:
+  proc twoDigits(input: string; x: var int; start: int): int =
+    if start+1 < input.len and input[start] == '0' and input[start+1] == '0':
+      result = 2
+      x = 13
+    else:
+      result = 0
+
+  proc someSep(input: string; start: int; seps: set[char] = {';', ',', '-', '.'}): int =
+    result = 0
+    while start+result < input.len and input[start+result] in seps: inc result
+
+  proc demangle(s: string; res: var string; start: int): int =
+    while result+start < s.len and s[result+start] in {'_', '@'}: inc result
+    res = ""
+    while result+start < s.len and s[result+start] > ' ' and s[result+start] != '_':
+      res.add s[result+start]
+      inc result
+    while result+start < s.len and s[result+start] > ' ':
+      inc result
+
+  proc parseGDB(resp: string): seq[string] =
+    const
+      digits = {'0'..'9'}
+      hexdigits = digits + {'a'..'f', 'A'..'F'}
+      whites = {' ', '\t', '\C', '\L'}
+    result = @[]
+    var idx = 0
+    while true:
+      var prc = ""
+      var info = ""
+      if scanp(resp, idx, *`whites`, '#', *`digits`, +`whites`, ?("0x", *`hexdigits`, " in "),
+               demangle($input, prc, $index), *`whites`, '(', * ~ ')', ')',
+                *`whites`, "at ", +(~{'\C', '\L'} -> info.add($_))):
+        result.add prc & " " & info
+      else:
+        break
+
+  var key, val: string
+  var intVal: int
+  var floatVal: float
+  doAssert scanf("abc:: xyz 89  33.25", "$w$s::$s$w$s$i  $f", key, val, intVal, floatVal)
+  doAssert key == "abc"
+  doAssert val == "xyz"
+  doAssert intVal == 89
+  doAssert floatVal == 33.25
+
+  var binVal: int
+  var octVal: int
+  var hexVal: int
+  doAssert scanf("0b0101 0o1234 0xabcd", "$b$s$o$s$h", binVal, octVal, hexVal)
+  doAssert binVal == 0b0101
+  doAssert octVal == 0o1234
+  doAssert hexVal == 0xabcd
+
+  let xx = scanf("$abc", "$$$i", intVal)
+  doAssert xx == false
+
+
+  let xx2 = scanf("$1234", "$$$i", intVal)
+  doAssert xx2
+
+  let yy = scanf(";.--Breakpoint00 [output]",
+      "$[someSep]Breakpoint${twoDigits}$[someSep({';','.','-'})] [$+]$.",
+      intVal, key)
+  doAssert yy
+  doAssert key == "output"
+  doAssert intVal == 13
+
+  var ident = ""
+  var idx = 0
+  let zz = scanp("foobar x x  x   xWZ", idx, +{'a'..'z'} -> add(ident, $_), *(*{
+      ' ', '\t'}, "x"), ~'U', "Z")
+  doAssert zz
+  doAssert ident == "foobar"
+
+  const digits = {'0'..'9'}
+  var year = 0
+  var idx2 = 0
+  if scanp("201655-8-9", idx2, `digits`{4, 6} -> (year = year * 10 + ord($_) -
+      ord('0')), "-8", "-9"):
+    doAssert year == 201655
+
+  const gdbOut = """
+      #0  @foo_96013_1208911747@8 (x0=...)
+          at c:/users/anwender/projects/nim/temp.nim:11
+      #1  0x00417754 in tempInit000 () at c:/users/anwender/projects/nim/temp.nim:13
+      #2  0x0041768d in NimMainInner ()
+          at c:/users/anwender/projects/nim/lib/system.nim:2605
+      #3  0x004176b1 in NimMain ()
+          at c:/users/anwender/projects/nim/lib/system.nim:2613
+      #4  0x004176db in main (argc=1, args=0x712cc8, env=0x711ca8)
+          at c:/users/anwender/projects/nim/lib/system.nim:2620"""
+  const result = @["foo c:/users/anwender/projects/nim/temp.nim:11",
+          "tempInit000 c:/users/anwender/projects/nim/temp.nim:13",
+          "NimMainInner c:/users/anwender/projects/nim/lib/system.nim:2605",
+          "NimMain c:/users/anwender/projects/nim/lib/system.nim:2613",
+          "main c:/users/anwender/projects/nim/lib/system.nim:2620"]
+  doAssert parseGDB(gdbOut) == result
+
+  # bug #6487
+  var count = 0
+
+  proc test(): string =
+    inc count
+    result = ",123123"
+
+  var a: int
+  discard scanf(test(), ",$i", a)
+  doAssert count == 1
+
+
+block:
+  let input = """1-3 s: abc
+15-18 9: def
+15-18 A: ghi
+15-18 _: jkl
+"""
+  var
+    lo, hi: int
+    w: string
+    c: char
+    res: int
+  for line in input.splitLines:
+    if line.scanf("$i-$i $c: $w", lo, hi, c, w):
+      inc res
+  doAssert res == 4
+
+block:
+  #whenscanf testing
+  let input = """1-3 s: abc
+15-18 9: def
+15-18 A: ghi
+15-18 _: jkl
+"""
+  proc twoDigits(input: string; x: var int; start: int): int =
+    if start+1 < input.len and input[start] == '0' and input[start+1] == '0':
+      result = 2
+      x = 13
+    else:
+      result = 0
+
+  proc someSep(input: string; start: int; seps: set[char] = {';', ',', '-', '.'}): int =
+    result = 0
+    while start+result < input.len and input[start+result] in seps: inc result
+
+  type
+    ScanRetType = tuple
+      success: bool
+      lo: int
+      hi: int
+      ch: char
+      word: string
+
+  var res = 0
+  for line in input.splitLines:
+    let ret: ScanRetType = scanTuple(line, "$i-$i $c: $w")
+    if ret.success:
+      inc res
+  doAssert res == 4
+
+  let (_, key, val, intVal, floatVal) = scanTuple("abc:: xyz 89  33.25", "$w$s::$s$w$s$i  $f")
+  doAssert key == "abc"
+  doAssert val == "xyz"
+  doAssert intVal == 89
+  doAssert floatVal == 33.25
+
+
+  let (_, binVal, octVal, hexVal) = scanTuple("0b0101 0o1234 0xabcd", "$b$s$o$s$h", binVal, octVal, hexVal)
+  doAssert binVal == 0b0101
+  doAssert octVal == 0o1234
+  doAssert hexVal == 0xabcd
+
+  var (xx,_) = scanTuple("$abc", "$$$i")
+  doAssert xx == false
+
+
+  let (xx2, _) = block: scanTuple("$1234", "$$$i")
+  doAssert xx2
+
+  var (yy, intVal2, key2) = scanTuple(";.--Breakpoint00 [output]",
+      "$[someSep]Breakpoint${twoDigits}$[someSep({';','.','-'})] [$+]$.",
+      int)
+  doAssert yy
+  doAssert key2 == "output"
+  doAssert intVal2 == 13
diff --git a/tests/stdlib/tstrset.nim b/tests/stdlib/tstrset.nim
index 1b253f862..bbb6c2677 100644
--- a/tests/stdlib/tstrset.nim
+++ b/tests/stdlib/tstrset.nim
@@ -1,12 +1,16 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
 # test a simple yet highly efficient set of strings
 
 type
   TRadixNodeKind = enum rnLinear, rnFull, rnLeaf
   PRadixNode = ref TRadixNode
-  TRadixNode = object {.inheritable.}
+  TRadixNode {.inheritable.} = object
     kind: TRadixNodeKind
   TRadixNodeLinear = object of TRadixNode
-    len: int8
+    len: uint8
     keys: array[0..31, char]
     vals: array[0..31, PRadixNode]
   TRadixNodeFull = object of TRadixNode
@@ -24,7 +28,7 @@ proc search(r: PRadixNode, s: string): PRadixNode =
     case r.kind
     of rnLinear:
       var x = PRadixNodeLinear(r)
-      for j in 0..ze(x.len)-1:
+      for j in 0..int(x.len)-1:
         if x.keys[j] == s[i]:
           if s[i] == '\0': return r
           r = x.vals[j]
@@ -50,7 +54,7 @@ proc search(r: PRadixNode, s: string): PRadixNode =
 proc contains*(r: PRadixNode, s: string): bool =
   return search(r, s) != nil
 
-proc testOrincl*(r: var PRadixNode, s: string): bool =
+proc testOrIncl*(r: var PRadixNode, s: string): bool =
   nil
 
 proc incl*(r: var PRadixNode, s: string) = discard testOrIncl(r, s)
@@ -63,9 +67,9 @@ proc excl*(r: var PRadixNode, s: string) =
   of rnFull: PRadixNodeFull(x).b['\0'] = nil
   of rnLinear:
     var x = PRadixNodeLinear(x)
-    for i in 0..ze(x.len)-1:
+    for i in 0..int(x.len)-1:
       if x.keys[i] == '\0':
-        swap(x.keys[i], x.keys[ze(x.len)-1])
+        swap(x.keys[i], x.keys[int(x.len)-1])
         dec(x.len)
         break
 
diff --git a/tests/stdlib/tstrtabs.nim b/tests/stdlib/tstrtabs.nim
index 5d7e8c762..d261abe76 100644
--- a/tests/stdlib/tstrtabs.nim
+++ b/tests/stdlib/tstrtabs.nim
@@ -1,4 +1,5 @@
 discard """
+matrix: "--mm:refc; --mm:orc"
 sortoutput: true
 output: '''
 key1: value1
@@ -88,7 +89,7 @@ value1 = value2
 '''
 """
 
-import strtabs
+import std/[strtabs, assertions, syncio]
 
 var tab = newStringTable({"key1": "val1", "key2": "val2"},
                          modeStyleInsensitive)
@@ -102,3 +103,15 @@ writeLine(stdout, "length of table ", $tab.len)
 writeLine(stdout, `%`("$key1 = $key2", tab, {useEnvironment}))
 tab.clear
 writeLine(stdout, "length of table ", $tab.len)
+
+block:
+  var x = {"k": "v", "11": "22", "565": "67"}.newStringTable
+  doAssert x["k"] == "v"
+  doAssert x["11"] == "22"
+  doAssert x["565"] == "67"
+  x["11"] = "23"
+  doAssert x["11"] == "23"
+
+  x.clear(modeCaseInsensitive)
+  x["11"] = "22"
+  doAssert x["11"] == "22"
diff --git a/tests/stdlib/tstrtabs.nims b/tests/stdlib/tstrtabs.nims
new file mode 100644
index 000000000..3563ad0ad
--- /dev/null
+++ b/tests/stdlib/tstrtabs.nims
@@ -0,0 +1,5 @@
+import std/[strtabs, assertions]
+
+static:
+  let t = {"name": "John", "city": "Monaco"}.newStringTable
+  doAssert "${name} lives in ${city}" % t == "John lives in Monaco"
diff --git a/tests/stdlib/tstrtabs2.nim b/tests/stdlib/tstrtabs2.nim
new file mode 100644
index 000000000..a4030ec77
--- /dev/null
+++ b/tests/stdlib/tstrtabs2.nim
@@ -0,0 +1,32 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+import std/strtabs
+import std/assertions
+
+macro m =
+  var t = {"name": "John"}.newStringTable
+  doAssert t["name"] == "John"
+
+block:
+  var t = {"name": "John"}.newStringTable
+  doAssert t["name"] == "John"
+
+m()
+
+proc fun()=
+  let ret = newStringTable(modeCaseSensitive)
+  ret["foo"] = "bar"
+
+  doAssert $ret == "{foo: bar}"
+
+  let b = ret["foo"]
+  doAssert b == "bar"
+
+proc main()=
+  static: fun()
+  fun()
+
+main()
diff --git a/tests/stdlib/tstrutil.nim b/tests/stdlib/tstrutil.nim
deleted file mode 100644
index 9dbc98912..000000000
--- a/tests/stdlib/tstrutil.nim
+++ /dev/null
@@ -1,350 +0,0 @@
-discard """
-  output: "ha/home/a1xyz/usr/bin"
-"""
-# test the new strutils module
-
-import
-  strutils
-
-import macros
-
-template rejectParse(e) =
-  try:
-    discard e
-    raise newException(AssertionError, "This was supposed to fail: $#!" % astToStr(e))
-  except ValueError: discard
-
-proc testStrip() =
-  write(stdout, strip("  ha  "))
-
-proc testRemoveSuffix =
-  var s = "hello\n\r"
-  s.removeSuffix
-  assert s == "hello"
-  s.removeSuffix
-  assert s == "hello"
-
-  s = "hello\n\n"
-  s.removeSuffix
-  assert s == "hello"
-
-  s = "hello\r"
-  s.removeSuffix
-  assert s == "hello"
-
-  s = "hello \n there"
-  s.removeSuffix
-  assert s == "hello \n there"
-
-  s = "hello"
-  s.removeSuffix("llo")
-  assert s == "he"
-  s.removeSuffix('e')
-  assert s == "h"
-
-  s = "hellos"
-  s.removeSuffix({'s','z'})
-  assert s == "hello"
-  s.removeSuffix({'l','o'})
-  assert s == "he"
-
-  s = "aeiou"
-  s.removeSuffix("")
-  assert s == "aeiou"
-
-  s = ""
-  s.removeSuffix("")
-  assert s == ""
-
-  s = "  "
-  s.removeSuffix
-  assert s == "  "
-
-  s = "  "
-  s.removeSuffix("")
-  assert s == "  "
-
-  s = "    "
-  s.removeSuffix(" ")
-  assert s == "   "
-
-  s = "    "
-  s.removeSuffix(' ')
-  assert s == ""
-
-  # Contrary to Chomp in other languages
-  # empty string does not change behaviour
-  s = "hello\r\n\r\n"
-  s.removeSuffix("")
-  assert s == "hello\r\n\r\n"
-
-proc testRemovePrefix =
-  var s = "\n\rhello"
-  s.removePrefix
-  assert s == "hello"
-  s.removePrefix
-  assert s == "hello"
-
-  s = "\n\nhello"
-  s.removePrefix
-  assert s == "hello"
-
-  s = "\rhello"
-  s.removePrefix
-  assert s == "hello"
-
-  s = "hello \n there"
-  s.removePrefix
-  assert s == "hello \n there"
-
-  s = "hello"
-  s.removePrefix("hel")
-  assert s == "lo"
-  s.removePrefix('l')
-  assert s == "o"
-
-  s = "hellos"
-  s.removePrefix({'h','e'})
-  assert s == "llos"
-  s.removePrefix({'l','o'})
-  assert s == "s"
-
-  s = "aeiou"
-  s.removePrefix("")
-  assert s == "aeiou"
-
-  s = ""
-  s.removePrefix("")
-  assert s == ""
-
-  s = "  "
-  s.removePrefix
-  assert s == "  "
-
-  s = "  "
-  s.removePrefix("")
-  assert s == "  "
-
-  s = "    "
-  s.removePrefix(" ")
-  assert s == "   "
-
-  s = "    "
-  s.removePrefix(' ')
-  assert s == ""
-
-  # Contrary to Chomp in other languages
-  # empty string does not change behaviour
-  s = "\r\n\r\nhello"
-  s.removePrefix("")
-  assert s == "\r\n\r\nhello"
-
-proc main() =
-  testStrip()
-  testRemoveSuffix()
-  testRemovePrefix()
-  for p in split("/home/a1:xyz:/usr/bin", {':'}):
-    write(stdout, p)
-
-proc testDelete =
-  var s = "0123456789ABCDEFGH"
-  delete(s, 4, 5)
-  assert s == "01236789ABCDEFGH"
-  delete(s, s.len-1, s.len-1)
-  assert s == "01236789ABCDEFG"
-  delete(s, 0, 0)
-  assert s == "1236789ABCDEFG"
-
-proc testFind =
-  assert "0123456789ABCDEFGH".find('A') == 10
-  assert "0123456789ABCDEFGH".find('A', 5) == 10
-  assert "0123456789ABCDEFGH".find('A', 5, 10) == 10
-  assert "0123456789ABCDEFGH".find('A', 5, 9) == -1
-  assert "0123456789ABCDEFGH".find("A") == 10
-  assert "0123456789ABCDEFGH".find("A", 5) == 10
-  assert "0123456789ABCDEFGH".find("A", 5, 10) == 10
-  assert "0123456789ABCDEFGH".find("A", 5, 9) == -1
-  assert "0123456789ABCDEFGH".find({'A'..'C'}) == 10
-  assert "0123456789ABCDEFGH".find({'A'..'C'}, 5) == 10
-  assert "0123456789ABCDEFGH".find({'A'..'C'}, 5, 10) == 10
-  assert "0123456789ABCDEFGH".find({'A'..'C'}, 5, 9) == -1
-
-proc testRFind =
-  assert "0123456789ABCDEFGAH".rfind('A') == 17
-  assert "0123456789ABCDEFGAH".rfind('A', last=13) == 10
-  assert "0123456789ABCDEFGAH".rfind('H', last=13) == -1
-  assert "0123456789ABCDEFGAH".rfind("A") == 17
-  assert "0123456789ABCDEFGAH".rfind("A", last=13) == 10
-  assert "0123456789ABCDEFGAH".rfind("H", last=13) == -1
-  assert "0123456789ABCDEFGAH".rfind({'A'..'C'}) == 17
-  assert "0123456789ABCDEFGAH".rfind({'A'..'C'}, last=13) == 12
-  assert "0123456789ABCDEFGAH".rfind({'G'..'H'}, last=13) == -1
-  assert "0123456789ABCDEFGAH".rfind('A', start=18) == -1
-  assert "0123456789ABCDEFGAH".rfind('A', start=11, last=17) == 17
-  assert "0123456789ABCDEFGAH".rfind("0", start=0) == 0
-  assert "0123456789ABCDEFGAH".rfind("0", start=1) == -1
-  assert "0123456789ABCDEFGAH".rfind("H", start=11) == 18
-  assert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=5) == 9
-  assert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=10) == -1
-
-proc testTrimZeros() =
-  var x = "1200"
-  x.trimZeros()
-  assert x == "1200"
-  x = "120.0"
-  x.trimZeros()
-  assert x == "120"
-  x = "0."
-  x.trimZeros()
-  assert x == "0"
-  x = "1.0e2"
-  x.trimZeros()
-  assert x == "1e2"
-  x = "78.90"
-  x.trimZeros()
-  assert x == "78.9"
-  x = "1.23e4"
-  x.trimZeros()
-  assert x == "1.23e4"
-  x = "1.01"
-  x.trimZeros()
-  assert x == "1.01"
-  x = "1.1001"
-  x.trimZeros()
-  assert x == "1.1001"
-  x = "0.0"
-  x.trimZeros()
-  assert x == "0"
-  x = "0.01"
-  x.trimZeros()
-  assert x == "0.01"
-  x = "1e0"
-  x.trimZeros()
-  assert x == "1e0"
-
-proc testSplitLines() =
-  let fixture = "a\nb\rc\r\nd"
-  assert len(fixture.splitLines) == 4
-  assert splitLines(fixture) == @["a", "b", "c", "d"]
-  assert splitLines(fixture, keepEol=true) == @["a\n", "b\r", "c\r\n", "d"]
-
-proc testCountLines =
-  proc assertCountLines(s: string) = assert s.countLines == s.splitLines.len
-  assertCountLines("")
-  assertCountLines("\n")
-  assertCountLines("\n\n")
-  assertCountLines("abc")
-  assertCountLines("abc\n123")
-  assertCountLines("abc\n123\n")
-  assertCountLines("\nabc\n123")
-  assertCountLines("\nabc\n123\n")
-
-proc testParseInts =
-  # binary
-  assert "0b1111".parseBinInt == 15
-  assert "0B1111".parseBinInt == 15
-  assert "1111".parseBinInt == 15
-  assert "1110".parseBinInt == 14
-  assert "1_1_1_1".parseBinInt == 15
-  assert "0b1_1_1_1".parseBinInt == 15
-  rejectParse "".parseBinInt
-  rejectParse "_".parseBinInt
-  rejectParse "0b".parseBinInt
-  rejectParse "0b1234".parseBinInt
-  # hex
-  assert "0x72".parseHexInt == 114
-  assert "0X72".parseHexInt == 114
-  assert "#72".parseHexInt == 114
-  assert "72".parseHexInt == 114
-  assert "FF".parseHexInt == 255
-  assert "ff".parseHexInt == 255
-  assert "fF".parseHexInt == 255
-  assert "0x7_2".parseHexInt == 114
-  rejectParse "".parseHexInt
-  rejectParse "_".parseHexInt
-  rejectParse "0x".parseHexInt
-  rejectParse "0xFFG".parseHexInt
-  rejectParse "reject".parseHexInt
-  # octal
-  assert "0o17".parseOctInt == 15
-  assert "0O17".parseOctInt == 15
-  assert "17".parseOctInt == 15
-  assert "10".parseOctInt == 8
-  assert "0o1_0_0".parseOctInt == 64
-  rejectParse "".parseOctInt
-  rejectParse "_".parseOctInt
-  rejectParse "0o".parseOctInt
-  rejectParse "9".parseOctInt
-  rejectParse "0o9".parseOctInt
-  rejectParse "reject".parseOctInt
-
-testDelete()
-testFind()
-testRFind()
-testTrimZeros()
-testSplitLines()
-testCountLines()
-testParseInts()
-
-assert(insertSep($1000_000) == "1_000_000")
-assert(insertSep($232) == "232")
-assert(insertSep($12345, ',') == "12,345")
-assert(insertSep($0) == "0")
-
-assert "/1/2/3".rfind('/') == 4
-assert "/1/2/3".rfind('/', last=1) == 0
-assert "/1/2/3".rfind('0') == -1
-
-assert(toHex(100i16, 32) == "00000000000000000000000000000064")
-assert(toHex(-100i16, 32) == "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9C")
-
-assert "".parseHexStr == ""
-assert "00Ff80".parseHexStr == "\0\xFF\x80"
-try:
-  discard "00Ff8".parseHexStr
-  assert false, "Should raise ValueError"
-except ValueError:
-  discard
-
-try:
-  discard "0k".parseHexStr
-  assert false, "Should raise ValueError"
-except ValueError:
-  discard
-
-assert "".toHex == ""
-assert "\x00\xFF\x80".toHex == "00FF80"
-assert "0123456789abcdef".parseHexStr.toHex == "0123456789ABCDEF"
-
-assert(' '.repeat(8) == "        ")
-assert(" ".repeat(8) == "        ")
-assert(spaces(8) == "        ")
-
-assert(' '.repeat(0) == "")
-assert(" ".repeat(0) == "")
-assert(spaces(0) == "")
-
-# bug #11369
-
-var num: int64 = -1
-assert num.toBin(64) == "1111111111111111111111111111111111111111111111111111111111111111"
-assert num.toOct(24) == "001777777777777777777777"
-
-
-# bug #8911
-when true:
-  static:
-    let a = ""
-    let a2 = a.replace("\n", "\\n")
-
-when true:
-  static:
-    let b = "b"
-    let b2 = b.replace("\n", "\\n")
-
-when true:
-  let c = ""
-  let c2 = c.replace("\n", "\\n")
-
-main()
-#OUT ha/home/a1xyz/usr/bin
diff --git a/tests/stdlib/tstrutils.nim b/tests/stdlib/tstrutils.nim
new file mode 100644
index 000000000..35f6bc669
--- /dev/null
+++ b/tests/stdlib/tstrutils.nim
@@ -0,0 +1,913 @@
+discard """
+  matrix: "--mm:refc; --mm:orc; --backend:cpp; --backend:js --jsbigint64:off -d:nimStringHash2; --backend:js --jsbigint64:on"
+"""
+
+import std/strutils
+from stdtest/testutils import disableVm
+import std/assertions
+import std/private/jsutils
+# xxx each instance of `disableVm` and `when not defined js:` should eventually be fixed
+
+template rejectParse(e) =
+  try:
+    discard e
+    raise newException(AssertionDefect, "This was supposed to fail: $#!" % astToStr(e))
+  except ValueError: discard
+
+template main() =
+  block: # strip
+    doAssert strip("  ha  ") == "ha"
+    doAssert strip("  foofoofoo  ") == "foofoofoo"
+    doAssert strip("sfoofoofoos", chars = {'s'}) == "foofoofoo"
+    doAssert strip("barfoofoofoobar", chars = {'b', 'a', 'r'}) == "foofoofoo"
+    doAssert strip("stripme but don't strip this stripme",
+                   chars = {'s', 't', 'r', 'i', 'p', 'm', 'e'}) ==
+                   " but don't strip this "
+    doAssert strip("sfoofoofoos", leading = false, chars = {'s'}) == "sfoofoofoo"
+    doAssert strip("sfoofoofoos", trailing = false, chars = {'s'}) == "foofoofoos"
+
+    block:
+      let a = "xxxxxx"
+      doAssert a.strip(chars={'x'}).len == 0
+
+    doAssert "".strip(chars={'x'}).len == 0
+    doAssert "         ".strip(chars={'x'}) == "         "
+    doAssert "xxx xxx".strip(chars={'x'}) == " "
+    doAssert "xxx  wind".strip(chars={'x'}) == "  wind"
+    doAssert "xxx  iii".strip(chars={'i'}) == "xxx  "
+    doAssert "x".strip(leading = false, chars={'x'}).len == 0
+    doAssert "x".strip(trailing = false, chars={'x'}).len == 0
+    doAssert "x".strip(leading = false, trailing = false, chars={'x'}) == "x"
+
+  block: # split
+    var ret: seq[string] # or use `toSeq` or `collect`
+    for p in split("/home/a1:xyz:/usr/bin", {':'}): ret.add p
+    doAssert ret == @["/home/a1", "xyz", "/usr/bin"]
+
+    let s = " this is an example  "
+    let s2 = ":this;is;an:example;;"
+
+    doAssert s.split() == @["", "this", "is", "an", "example", "", ""]
+    doAssert s2.split(seps = {':', ';'}) == @["", "this", "is", "an", "example",
+        "", ""]
+    doAssert s.split(maxsplit = 4) == @["", "this", "is", "an", "example  "]
+    doAssert s.split(' ', maxsplit = 1) == @["", "this is an example  "]
+    doAssert s.split(" ", maxsplit = 4) == @["", "this", "is", "an", "example  "]
+    # Empty string:
+    doAssert "".split() == @[""]
+    doAssert "".split(" ") == @[""]
+    doAssert "".split({' '}) == @[""]
+    # Empty separators:
+    doAssert "".split({}) == @[""]
+    doAssert "".split("") == @[""]
+    doAssert s.split({}) == @[s]
+    doAssert s.split("") == @[s]
+
+  block: # splitLines
+    let fixture = "a\nb\rc\r\nd"
+    doAssert len(fixture.splitLines) == 4
+    doAssert splitLines(fixture) == @["a", "b", "c", "d"]
+    doAssert splitLines(fixture, keepEol=true) == @["a\n", "b\r", "c\r\n", "d"]
+
+  block: # rsplit
+    doAssert rsplit("foo bar", seps = Whitespace) == @["foo", "bar"]
+    doAssert rsplit(" foo bar", seps = Whitespace, maxsplit = 1) == @[" foo", "bar"]
+    doAssert rsplit(" foo bar ", seps = Whitespace, maxsplit = 1) == @[" foo bar", ""]
+    doAssert rsplit(":foo:bar", sep = ':') == @["", "foo", "bar"]
+    doAssert rsplit(":foo:bar", sep = ':', maxsplit = 2) == @["", "foo", "bar"]
+    doAssert rsplit(":foo:bar", sep = ':', maxsplit = 3) == @["", "foo", "bar"]
+    doAssert rsplit("foothebar", sep = "the") == @["foo", "bar"]
+    # Empty string:
+    doAssert "".rsplit() == @[""]
+    doAssert "".rsplit(" ") == @[""]
+    doAssert "".rsplit({' '}) == @[""]
+    # Empty separators:
+    let s = " this is an example  "
+    doAssert "".rsplit({}) == @[""]
+    doAssert "".rsplit("") == @[""]
+    doAssert s.rsplit({}) == @[s]
+    doAssert s.rsplit("") == @[s]
+
+  block: # splitWhitespace
+    let s = " this is an example  "
+    doAssert s.splitWhitespace() == @["this", "is", "an", "example"]
+    doAssert s.splitWhitespace(maxsplit = 1) == @["this", "is an example  "]
+    doAssert s.splitWhitespace(maxsplit = 2) == @["this", "is", "an example  "]
+    doAssert s.splitWhitespace(maxsplit = 3) == @["this", "is", "an", "example  "]
+    doAssert s.splitWhitespace(maxsplit = 4) == @["this", "is", "an", "example"]
+
+  block: # removeSuffix
+    var s = "hello\n\r"
+    s.removeSuffix
+    doAssert s == "hello"
+    s.removeSuffix
+    doAssert s == "hello"
+
+    s = "hello\n\n"
+    s.removeSuffix
+    doAssert s == "hello"
+
+    s = "hello\r"
+    s.removeSuffix
+    doAssert s == "hello"
+
+    s = "hello \n there"
+    s.removeSuffix
+    doAssert s == "hello \n there"
+
+    s = "hello"
+    s.removeSuffix("llo")
+    doAssert s == "he"
+    s.removeSuffix('e')
+    doAssert s == "h"
+
+    s = "hellos"
+    s.removeSuffix({'s','z'})
+    doAssert s == "hello"
+    s.removeSuffix({'l','o'})
+    doAssert s == "he"
+
+    s = "aeiou"
+    s.removeSuffix("")
+    doAssert s == "aeiou"
+
+    s = ""
+    s.removeSuffix("")
+    doAssert s == ""
+
+    s = "  "
+    s.removeSuffix
+    doAssert s == "  "
+
+    s = "  "
+    s.removeSuffix("")
+    doAssert s == "  "
+
+    s = "    "
+    s.removeSuffix(" ")
+    doAssert s == "   "
+
+    s = "    "
+    s.removeSuffix(' ')
+    doAssert s == ""
+
+    # Contrary to Chomp in other languages
+    # empty string does not change behaviour
+    s = "hello\r\n\r\n"
+    s.removeSuffix("")
+    doAssert s == "hello\r\n\r\n"
+
+  block: # removePrefix
+    var s = "\n\rhello"
+    s.removePrefix
+    doAssert s == "hello"
+    s.removePrefix
+    doAssert s == "hello"
+
+    s = "\n\nhello"
+    s.removePrefix
+    doAssert s == "hello"
+
+    s = "\rhello"
+    s.removePrefix
+    doAssert s == "hello"
+
+    s = "hello \n there"
+    s.removePrefix
+    doAssert s == "hello \n there"
+
+    s = "hello"
+    s.removePrefix("hel")
+    doAssert s == "lo"
+    s.removePrefix('l')
+    doAssert s == "o"
+
+    s = "hellos"
+    s.removePrefix({'h','e'})
+    doAssert s == "llos"
+    s.removePrefix({'l','o'})
+    doAssert s == "s"
+
+    s = "aeiou"
+    s.removePrefix("")
+    doAssert s == "aeiou"
+
+    s = ""
+    s.removePrefix("")
+    doAssert s == ""
+
+    s = "  "
+    s.removePrefix
+    doAssert s == "  "
+
+    s = "  "
+    s.removePrefix("")
+    doAssert s == "  "
+
+    s = "    "
+    s.removePrefix(" ")
+    doAssert s == "   "
+
+    s = "    "
+    s.removePrefix(' ')
+    doAssert s == ""
+
+    # Contrary to Chomp in other languages
+    # empty string does not change behaviour
+    s = "\r\n\r\nhello"
+    s.removePrefix("")
+    doAssert s == "\r\n\r\nhello"
+
+  block: # delete(slice)
+    var s = "0123456789ABCDEFGH"
+    delete(s, 4 .. 5)
+    doAssert s == "01236789ABCDEFGH"
+    delete(s, s.len-1 .. s.len-1)
+    doAssert s == "01236789ABCDEFG"
+    delete(s, 0..0)
+    doAssert s == "1236789ABCDEFG"
+    s = ""
+    doAssertRaises(IndexDefect): delete(s, 0..0)
+    doAssert s == ""
+    s = "abc"
+    doAssertRaises(IndexDefect): delete(s, -1 .. -2)
+    doAssertRaises(IndexDefect): delete(s, 2..3)
+    doAssertRaises(IndexDefect): delete(s, 3..2)
+    delete(s, 2..2)
+    doAssert s == "ab"
+    delete(s, 1..0)
+    doAssert s == "ab"
+    delete(s, 0..0)
+    doAssert s == "b"
+
+  block: # delete(first, last)
+    {.push warning[deprecated]:off.}
+    var s = "0123456789ABCDEFGH"
+    delete(s, 4, 5)
+    doAssert s == "01236789ABCDEFGH"
+    delete(s, s.len-1, s.len-1)
+    doAssert s == "01236789ABCDEFG"
+    delete(s, 0, 0)
+    doAssert s == "1236789ABCDEFG"
+    {.pop.}
+
+  block: # find
+    const haystack: string = "0123456789ABCDEFGH"
+    doAssert haystack.find('A') == 10
+    doAssert haystack.find('A', 5) == 10
+    doAssert haystack.find('A', 5, 10) == 10
+    doAssert haystack.find('A', 5, 9) == -1
+    doAssert haystack.find("A") == 10
+    doAssert haystack.find("A", 5) == 10
+    doAssert haystack.find("A", 5, 10) == 10
+    doAssert haystack.find("A", 5, 9) == -1
+    doAssert haystack.find({'A'..'C'}) == 10
+    doAssert haystack.find({'A'..'C'}, 5) == 10
+    doAssert haystack.find({'A'..'C'}, 5, 10) == 10
+    doAssert haystack.find({'A'..'C'}, 5, 9) == -1
+    doAssert haystack.find('A', 0, 0) == -1 # search limited to the first char
+    doAssert haystack.find('A', 5, 0) == -1 # last < start
+    doAssert haystack.find('A', 5, 4) == -1 # last < start
+
+    block:
+      const haystack: string = "ABCABABABABCAB"
+      doAssert haystack.len == 14
+
+      # only last argument
+      doAssert haystack.find("ABC") == 0
+      doAssert haystack.find("ABC", last=13) == 0 # after the second ABC
+      doAssert haystack.find("ABC", last=5) == 0 # before the second ABC
+
+      # only start argument
+      doAssert haystack.find("ABC", start=0) == 0
+      doAssert haystack.find("ABC", start=1) == 9
+      doAssert haystack.find("ABC", start=9) == 9
+      doAssert haystack.find("ABC", start=10) == -1
+
+      # both start and last arguments
+      doAssert haystack.find("ABC", start=0, last=14) == 0
+      doAssert haystack.find("ABC", start=0, last=13) == 0
+      doAssert haystack.find("ABC", start=0, last=12) == 0
+      doAssert haystack.find("ABC", start=1, last=13) == 9
+      doAssert haystack.find("ABC", start=1, last=12) == 9
+      doAssert haystack.find("ABC", start=1, last=11) == 9
+      doAssert haystack.find("ABC", start=1, last=10) == -1
+
+    doAssert "".find("/") == -1
+    doAssert "/".find("/") == 0
+    doAssert "/".find("//") == -1
+    doAssert "///".find("//", start=3) == -1
+
+    # searching for empty string
+    doAssert "".find("") == 0
+    doAssert "abc".find("") == 0
+    doAssert "abc".find("", start=1) == 1
+    doAssert "abc".find("", start=2) == 2
+    doAssert "abc".find("", start=3) == 3
+    doAssert "abc".find("", start=4) == -1
+    doAssert "abc".find("", start=400) == -1
+    doAssert "abc".find("", start=1, last=3) == 1
+    doAssert "abc".find("", start=1, last=2) == 1
+    doAssert "abc".find("", start=1, last=1) == 1
+    doAssert "abc".find("", start=1, last=0) == 1
+    doAssert "abc".find("", start=1, last = -1) == 1
+
+    # when last <= start, searching for non-empty string
+    block:
+      let last: int = -1 # searching through whole line
+      doAssert "abcd".find("ab", start=0, last=last) == 0
+      doAssert "abcd".find("ab", start=1, last=last) == -1
+      doAssert "abcd".find("bc", start=1, last=last) == 1
+      doAssert "abcd".find("bc", start=2, last=last) == -1
+    block:
+      let last: int = 0
+      doAssert "abcd".find("ab", start=0, last=last) == -1
+      doAssert "abcd".find("ab", start=1, last=last) == -1
+      doAssert "abcd".find("bc", start=1, last=last) == -1
+      doAssert "abcd".find("bc", start=2, last=last) == -1
+    block:
+      let last: int = 1
+      doAssert "abcd".find("ab", start=0, last=last) == 0
+      doAssert "abcd".find("ab", start=1, last=last) == -1
+      doAssert "abcd".find("bc", start=1, last=last) == -1
+      doAssert "abcd".find("bc", start=2, last=last) == -1
+
+  block: # rfind
+    doAssert "0123456789ABCDEFGAH".rfind('A') == 17
+    doAssert "0123456789ABCDEFGAH".rfind('A', last=13) == 10
+    doAssert "0123456789ABCDEFGAH".rfind('H', last=13) == -1
+    doAssert "0123456789ABCDEFGAH".rfind("A") == 17
+    doAssert "0123456789ABCDEFGAH".rfind("A", last=13) == 10
+    doAssert "0123456789ABCDEFGAH".rfind("H", last=13) == -1
+    doAssert "0123456789ABCDEFGAH".rfind({'A'..'C'}) == 17
+    doAssert "0123456789ABCDEFGAH".rfind({'A'..'C'}, last=13) == 12
+    doAssert "0123456789ABCDEFGAH".rfind({'G'..'H'}, last=13) == -1
+    doAssert "0123456789ABCDEFGAH".rfind('A', start=18) == -1
+    doAssert "0123456789ABCDEFGAH".rfind('A', start=11, last=17) == 17
+    doAssert "0123456789ABCDEFGAH".rfind("0", start=0) == 0
+    doAssert "0123456789ABCDEFGAH".rfind("0", start=1) == -1
+    doAssert "0123456789ABCDEFGAH".rfind("H", start=11) == 18
+    doAssert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=5) == 9
+    doAssert "0123456789ABCDEFGAH".rfind({'0'..'9'}, start=10) == -1
+
+    doAssert "/1/2/3".rfind('/') == 4
+    doAssert "/1/2/3".rfind('/', last=1) == 0
+    doAssert "/1/2/3".rfind('0') == -1
+
+    block:
+      const haystack: string = "ABCABABABABCAB"
+      doAssert haystack.len == 14
+      doAssert haystack.rfind("ABC") == 9
+      doAssert haystack.rfind("ABC", last=13) == 9
+      doAssert haystack.rfind("ABC", last=12) == 9
+      doAssert haystack.rfind("ABC", last=11) == 9
+      doAssert haystack.rfind("ABC", last=10) == 0
+
+      doAssert haystack.rfind("ABC", start=0) == 9
+      doAssert haystack.rfind("ABC", start=1) == 9
+      doAssert haystack.rfind("ABC", start=9) == 9
+      doAssert haystack.rfind("ABC", start=10) == -1
+
+      doAssert haystack.rfind("ABC", start=0, last=13) == 9
+      doAssert haystack.rfind("ABC", start=0, last=12) == 9
+      doAssert haystack.rfind("ABC", start=0, last=11) == 9
+      doAssert haystack.rfind("ABC", start=0, last=10) == 0
+      doAssert haystack.rfind("ABC", start=1, last=10) == -1
+
+    doAssert "".rfind("/") == -1
+    doAssert "/".rfind("/") == 0
+    doAssert "/".rfind("//") == -1
+    doAssert "///".rfind("//", start=3) == -1
+
+    # searching for empty string
+    doAssert "".rfind("") == 0
+    doAssert "abc".rfind("") == 3
+    doAssert "abc".rfind("", start=1) == 3
+    doAssert "abc".rfind("", start=2) == 3
+    doAssert "abc".rfind("", start=3) == 3
+    doAssert "abc".rfind("", start=4) == 4
+    doAssert "abc".rfind("", start=400) == 400
+
+    doAssert "abc".rfind("", start=1, last=3) == 3
+    doAssert "abc".rfind("", start=1, last=2) == 2
+    doAssert "abc".rfind("", start=1, last=1) == 1
+    # This returns the start index instead of the last index
+    # because start > last
+    doAssert "abc".rfind("", start=1, last=0) == 1
+    doAssert "abc".rfind("", start=1, last = -1) == 3
+    
+    doAssert "abc".rfind("", start=0, last=0) == 0
+
+    # when last <= start, searching for non-empty string
+    block:
+      let last: int = -1
+      doAssert "abcd".rfind("ab", start=0, last=last) == 0
+      doAssert "abcd".rfind("ab", start=1, last=last) == -1
+      doAssert "abcd".rfind("bc", start=1, last=last) == 1
+      doAssert "abcd".rfind("bc", start=2, last=last) == -1
+    block:
+      let last: int = 0
+      doAssert "abcd".rfind("ab", start=0, last=last) == -1
+      doAssert "abcd".rfind("ab", start=1, last=last) == -1
+      doAssert "abcd".rfind("bc", start=1, last=last) == -1
+      doAssert "abcd".rfind("bc", start=2, last=last) == -1
+    block:
+      let last: int = 1
+      doAssert "abcd".rfind("ab", start=0, last=last) == 0
+      doAssert "abcd".rfind("ab", start=1, last=last) == -1
+      doAssert "abcd".rfind("bc", start=1, last=last) == -1
+      doAssert "abcd".rfind("bc", start=2, last=last) == -1
+
+  block: # trimZeros
+    var x = "1200"
+    x.trimZeros()
+    doAssert x == "1200"
+    x = "120.0"
+    x.trimZeros()
+    doAssert x == "120"
+    x = "0."
+    x.trimZeros()
+    doAssert x == "0"
+    x = "1.0e2"
+    x.trimZeros()
+    doAssert x == "1e2"
+    x = "78.90"
+    x.trimZeros()
+    doAssert x == "78.9"
+    x = "1.23e4"
+    x.trimZeros()
+    doAssert x == "1.23e4"
+    x = "1.01"
+    x.trimZeros()
+    doAssert x == "1.01"
+    x = "1.1001"
+    x.trimZeros()
+    doAssert x == "1.1001"
+    x = "0.0"
+    x.trimZeros()
+    doAssert x == "0"
+    x = "0.01"
+    x.trimZeros()
+    doAssert x == "0.01"
+    x = "1e0"
+    x.trimZeros()
+    doAssert x == "1e0"
+    x = "1.23"
+    x.trimZeros()
+    doAssert x == "1.23"
+
+  block: # countLines
+    proc assertCountLines(s: string) = doAssert s.countLines == s.splitLines.len
+    assertCountLines("")
+    assertCountLines("\n")
+    assertCountLines("\n\n")
+    assertCountLines("abc")
+    assertCountLines("abc\n123")
+    assertCountLines("abc\n123\n")
+    assertCountLines("\nabc\n123")
+    assertCountLines("\nabc\n123\n")
+
+  block: # parseBinInt, parseHexInt, parseOctInt
+    # binary
+    doAssert "0b1111".parseBinInt == 15
+    doAssert "0B1111".parseBinInt == 15
+    doAssert "1111".parseBinInt == 15
+    doAssert "1110".parseBinInt == 14
+    doAssert "1_1_1_1".parseBinInt == 15
+    doAssert "0b1_1_1_1".parseBinInt == 15
+    rejectParse "".parseBinInt
+    rejectParse "_".parseBinInt
+    rejectParse "0b".parseBinInt
+    rejectParse "0b1234".parseBinInt
+    # hex
+    doAssert "0x72".parseHexInt == 114
+    doAssert "0X72".parseHexInt == 114
+    doAssert "#72".parseHexInt == 114
+    doAssert "72".parseHexInt == 114
+    doAssert "FF".parseHexInt == 255
+    doAssert "ff".parseHexInt == 255
+    doAssert "fF".parseHexInt == 255
+    doAssert "0x7_2".parseHexInt == 114
+    rejectParse "".parseHexInt
+    rejectParse "_".parseHexInt
+    rejectParse "0x".parseHexInt
+    rejectParse "0xFFG".parseHexInt
+    rejectParse "reject".parseHexInt
+    # octal
+    doAssert "0o17".parseOctInt == 15
+    doAssert "0O17".parseOctInt == 15
+    doAssert "17".parseOctInt == 15
+    doAssert "10".parseOctInt == 8
+    doAssert "0o1_0_0".parseOctInt == 64
+    rejectParse "".parseOctInt
+    rejectParse "_".parseOctInt
+    rejectParse "0o".parseOctInt
+    rejectParse "9".parseOctInt
+    rejectParse "0o9".parseOctInt
+    rejectParse "reject".parseOctInt
+
+  block: # parseHexStr
+    doAssert "".parseHexStr == ""
+    doAssert "00Ff80".parseHexStr == "\0\xFF\x80"
+    try:
+      discard "00Ff8".parseHexStr
+      doAssert false, "Should raise ValueError"
+    except ValueError:
+      discard
+
+    try:
+      discard "0k".parseHexStr
+      doAssert false, "Should raise ValueError"
+    except ValueError:
+      discard
+
+    doAssert "".toHex == ""
+    doAssert "\x00\xFF\x80".toHex == "00FF80"
+    doAssert "0123456789abcdef".parseHexStr.toHex == "0123456789ABCDEF"
+
+  block: # toHex
+    doAssert(toHex(100i16, 32) == "00000000000000000000000000000064")
+    whenJsNoBigInt64: discard
+    do:
+      doAssert(toHex(-100i16, 32) == "FFFFFFFFFFFFFFFFFFFFFFFFFFFFFF9C")
+      doAssert(toHex(high(uint64)) == "FFFFFFFFFFFFFFFF")
+      doAssert(toHex(high(uint64), 16) == "FFFFFFFFFFFFFFFF")
+      doAssert(toHex(high(uint64), 32) == "0000000000000000FFFFFFFFFFFFFFFF")
+
+  block: # insertSep
+    doAssert(insertSep($1000_000) == "1_000_000")
+    doAssert(insertSep($232) == "232")
+    doAssert(insertSep($12345, ',') == "12,345")
+    doAssert(insertSep($0) == "0")
+
+  block: # repeat, spaces
+    doAssert(' '.repeat(8) == "        ")
+    doAssert(" ".repeat(8) == "        ")
+    doAssert(spaces(8) == "        ")
+
+    doAssert(' '.repeat(0) == "")
+    doAssert(" ".repeat(0) == "")
+    doAssert(spaces(0) == "")
+
+  block: # toBin, toOct
+    whenJsNoBigInt64: # bug #11369
+      discard
+    do:
+      var num: int64 = -1
+      doAssert num.toBin(64) == "1111111111111111111111111111111111111111111111111111111111111111"
+      doAssert num.toOct(24) == "001777777777777777777777"
+
+  block: # replace
+    doAssert "oo".replace("", "abc") == "oo"
+    # bug #8911
+    static:
+      let a = ""
+      let a2 = a.replace("\n", "\\n")
+
+    static:
+      let b = "b"
+      let b2 = b.replace("\n", "\\n")
+
+    block:
+      let c = ""
+      let c2 = c.replace("\n", "\\n")
+
+  block: # replaceWord
+    doAssert "-ld a-ldz -ld".replaceWord("-ld") == " a-ldz "
+    doAssert "-lda-ldz -ld abc".replaceWord("-ld") == "-lda-ldz  abc"
+    doAssert "-lda-ldz -ld abc".replaceWord("") == "-lda-ldz -ld abc"
+
+  block: # multiReplace
+    doAssert "abba".multiReplace(("a", "b"), ("b", "a")) == "baab"
+    doAssert "Hello World.".multiReplace(("ello", "ELLO"), ("World.",
+        "PEOPLE!")) == "HELLO PEOPLE!"
+    doAssert "aaaa".multiReplace(("a", "aa"), ("aa", "bb")) == "aaaaaaaa"
+
+  # `parseEnum`, ref issue #14030
+  # check enum defined at top level # xxx this is probably irrelevant, and pollutes scope
+  # for remaining tests
+  type
+    Foo = enum
+      A = -10
+      B = "bb"
+      C = (-5, "ccc")
+      D = 15
+      E = "ee" # check that we count enum fields correctly
+
+  block: # parseEnum
+    block:
+      let a = parseEnum[Foo]("A")
+      let b = parseEnum[Foo]("bb")
+      let c = parseEnum[Foo]("ccc")
+      let d = parseEnum[Foo]("D")
+      let e = parseEnum[Foo]("ee")
+      doAssert a == A
+      doAssert b == B
+      doAssert c == C
+      doAssert d == D
+      doAssert e == E
+      try:
+        let f = parseEnum[Foo]("Bar")
+        doAssert false
+      except ValueError:
+        discard
+
+      # finally using default
+      let g = parseEnum[Foo]("Bar", A)
+      doAssert g == A
+
+    block: # bug #19463
+      const CAMPAIGN_TABLE = "wikientries_campaign"
+      const CHARACTER_TABLE = "wikientries_character"
+
+      type Tables = enum
+        a = CAMPAIGN_TABLE,
+        b = CHARACTER_TABLE,
+
+      let myA = CAMPAIGN_TABLE
+      doAssert $parseEnum[Tables](myA) == "wikientries_campaign"
+
+    block: # check enum defined in block
+      type
+        Bar = enum
+          V
+          W = "ww"
+          X = (3, "xx")
+          Y = 10
+          Z = "zz" # check that we count enum fields correctly
+
+      let a = parseEnum[Bar]("V")
+      let b = parseEnum[Bar]("ww")
+      let c = parseEnum[Bar]("xx")
+      let d = parseEnum[Bar]("Y")
+      let e = parseEnum[Bar]("zz")
+      doAssert a == V
+      doAssert b == W
+      doAssert c == X
+      doAssert d == Y
+      doAssert e == Z
+      try:
+        let f = parseEnum[Bar]("Baz")
+        doAssert false
+      except ValueError:
+        discard
+
+      # finally using default
+      let g = parseEnum[Bar]("Baz", V)
+      doAssert g == V
+
+    block: # check ambiguous enum fails to parse
+      type
+        Ambig = enum
+          f1 = "A"
+          f2 = "B"
+          f3 = "A"
+
+      doAssert not compiles((let a = parseEnum[Ambig]("A")))
+
+    block: # check almost ambiguous enum
+      type
+        AlmostAmbig = enum
+          f1 = "someA"
+          f2 = "someB"
+          f3 = "SomeA"
+
+      let a = parseEnum[AlmostAmbig]("someA")
+      let b = parseEnum[AlmostAmbig]("someB")
+      let c = parseEnum[AlmostAmbig]("SomeA")
+      doAssert a == f1
+      doAssert b == f2
+      doAssert c == f3
+
+    block:
+      type MyEnum = enum enA, enB, enC, enuD, enE
+      doAssert parseEnum[MyEnum]("enu_D") == enuD
+
+      doAssert parseEnum("invalid enum value", enC) == enC
+    
+    block: # issue #22726
+      type SomeEnum = enum A, B, C
+
+      proc assignEnum(dest: var enum, s: string) =
+        type ty = typeof(dest)
+        dest = parseEnum[ty](s)
+      
+      var v: SomeEnum
+      v.assignEnum("A")
+      doAssert v == A
+
+  block: # indentation
+    doAssert 0 == indentation """
+hey
+  low
+    there
+"""
+    doAssert 2 == indentation """
+  hey
+    low
+      there
+"""
+    doAssert 2 == indentation """  hey
+    low
+      there
+"""
+    doAssert 2 == indentation """  hey
+    low
+      there"""
+    doAssert 0 == indentation ""
+    doAssert 0 == indentation "  \n  \n"
+    doAssert 0 == indentation "    "
+
+  block: # indent
+    doAssert "  foo\n  bar".indent(4, "Q") == "QQQQ  foo\nQQQQ  bar"
+
+  block: # unindent
+    doAssert """~~!!foo
+~~!!bar
+~~!!baz""".unindent(2, "~~!!") == "foo\nbar\nbaz"
+
+    doAssert """~~!!foo
+~~!!bar
+~~!!baz""".unindent(2, "~~!!aa") == "~~!!foo\n~~!!bar\n~~!!baz"
+    doAssert """~~foo
+~~  bar
+~~  baz""".unindent(4, "~") == "foo\n  bar\n  baz"
+    doAssert """foo
+bar
+    baz
+  """.unindent(4) == "foo\nbar\nbaz\n"
+    doAssert """foo
+    bar
+    baz
+  """.unindent(2) == "foo\n  bar\n  baz\n"
+    doAssert """foo
+    bar
+    baz
+  """.unindent(100) == "foo\nbar\nbaz\n"
+
+    doAssert """foo
+    foo
+    bar
+  """.unindent() == "foo\nfoo\nbar\n"
+
+  block: # formatBiggestFloat
+    disableVm:
+      doAssert formatBiggestFloat(1234.567, ffDecimal, -1) == "1234.567000"
+      when not defined(js):
+        doAssert formatBiggestFloat(1234.567, ffDecimal, 0) == "1235." # bugs 8242, 12586
+      doAssert formatBiggestFloat(1234.567, ffDecimal, 1) == "1234.6"
+      doAssert formatBiggestFloat(0.00000000001, ffDecimal, 11) == "0.00000000001"
+      doAssert formatBiggestFloat(0.00000000001, ffScientific, 1, ',') in
+                                                      ["1,0e-11", "1,0e-011"]
+  block: # formatFloat
+    disableVm:
+      # bug #6589
+      when not defined(js):
+        doAssert formatFloat(123.456, ffScientific, precision = -1) == "1.234560e+02"
+
+  block: # `%`
+    doAssert "$# $3 $# $#" % ["a", "b", "c"] == "a c b c"
+    doAssert "${1}12 ${-1}$2" % ["a", "b"] == "a12 bb"
+    doAssert "$animal eats $food." % ["animal", "The cat", "food", "fish"] ==
+             "The cat eats fish."
+
+  block: # formatSize
+    disableVm:
+      whenJsNoBigInt64: discard
+      do:
+        doAssert formatSize((1'i64 shl 31) + (300'i64 shl 20)) == "2.293GiB" # <=== bug #8231
+      doAssert formatSize((2.234*1024*1024).int) == "2.234MiB"
+      doAssert formatSize(4096) == "4KiB"
+      doAssert formatSize(4096, prefix = bpColloquial, includeSpace = true) == "4 kB"
+      doAssert formatSize(4096, includeSpace = true) == "4 KiB"
+      doAssert formatSize(5_378_934, prefix = bpColloquial, decimalSep = ',') == "5,13MB"
+
+  block: # formatEng
+    disableVm:
+      doAssert formatEng(0, 2, trim = false) == "0.00"
+      doAssert formatEng(0, 2) == "0"
+      doAssert formatEng(53, 2, trim = false) == "53.00"
+      doAssert formatEng(0.053, 2, trim = false) == "53.00e-3"
+      doAssert formatEng(0.053, 4, trim = false) == "53.0000e-3"
+      doAssert formatEng(0.053, 4, trim = true) == "53e-3"
+      doAssert formatEng(0.053, 0) == "53e-3"
+      doAssert formatEng(52731234) == "52.731234e6"
+      doAssert formatEng(-52731234) == "-52.731234e6"
+      doAssert formatEng(52731234, 1) == "52.7e6"
+      doAssert formatEng(-52731234, 1) == "-52.7e6"
+      doAssert formatEng(52731234, 1, decimalSep = ',') == "52,7e6"
+      doAssert formatEng(-52731234, 1, decimalSep = ',') == "-52,7e6"
+
+      doAssert formatEng(4100, siPrefix = true, unit = "V") == "4.1 kV"
+      doAssert formatEng(4.1, siPrefix = true, unit = "V",
+          useUnitSpace = true) == "4.1 V"
+      doAssert formatEng(4.1, siPrefix = true) == "4.1" # Note lack of space
+      doAssert formatEng(4100, siPrefix = true) == "4.1 k"
+      doAssert formatEng(4.1, siPrefix = true, unit = "",
+          useUnitSpace = true) == "4.1 " # Includes space
+      doAssert formatEng(4100, siPrefix = true, unit = "") == "4.1 k"
+      doAssert formatEng(4100) == "4.1e3"
+      doAssert formatEng(4100, unit = "V", useUnitSpace = true) == "4.1e3 V"
+      doAssert formatEng(4100, unit = "", useUnitSpace = true) == "4.1e3 "
+      # Don't use SI prefix as number is too big
+      doAssert formatEng(3.1e22, siPrefix = true, unit = "a",
+          useUnitSpace = true) == "31e21 a"
+      # Don't use SI prefix as number is too small
+      doAssert formatEng(3.1e-25, siPrefix = true, unit = "A",
+          useUnitSpace = true) == "310e-27 A"
+
+  block: # align
+    doAssert align("abc", 4) == " abc"
+    doAssert align("a", 0) == "a"
+    doAssert align("1232", 6) == "  1232"
+    doAssert align("1232", 6, '#') == "##1232"
+
+  block: # alignLeft
+    doAssert alignLeft("abc", 4) == "abc "
+    doAssert alignLeft("a", 0) == "a"
+    doAssert alignLeft("1232", 6) == "1232  "
+    doAssert alignLeft("1232", 6, '#') == "1232##"
+
+  block: # center
+    doAssert center("foo", 13) == "     foo     "
+    doAssert center("foo", 0) == "foo"
+    doAssert center("foo", 3, fillChar = 'a') == "foo"
+    doAssert center("foo", 10, fillChar = '\t') == "\t\t\tfoo\t\t\t\t"
+
+  block: # count
+    doAssert count("foofoofoo", "foofoo") == 1
+    doAssert count("foofoofoo", "foofoo", overlapping = true) == 2
+    doAssert count("foofoofoo", 'f') == 3
+    doAssert count("foofoofoobar", {'f', 'b'}) == 4
+
+  block: # isAlphaAscii
+    doAssert isAlphaAscii('r')
+    doAssert isAlphaAscii('A')
+    doAssert(not isAlphaAscii('$'))
+
+  block: # isAlphaNumeric
+    doAssert isAlphaNumeric('3')
+    doAssert isAlphaNumeric('R')
+    doAssert(not isAlphaNumeric('!'))
+
+  block: # isDigit
+    doAssert isDigit('3')
+    doAssert(not isDigit('a'))
+    doAssert(not isDigit('%'))
+
+  block: # isSpaceAscii
+    doAssert isSpaceAscii('\t')
+    doAssert isSpaceAscii('\l')
+    doAssert(not isSpaceAscii('A'))
+
+  block: # isEmptyOrWhitespace
+    doAssert(isEmptyOrWhitespace(""))
+    doAssert(isEmptyOrWhitespace("       "))
+    doAssert(isEmptyOrWhitespace("\t\l \v\r\f"))
+    doAssert(not isEmptyOrWhitespace("ABc   \td"))
+
+  block: # isLowerAscii
+    doAssert isLowerAscii('a')
+    doAssert isLowerAscii('z')
+    doAssert(not isLowerAscii('A'))
+    doAssert(not isLowerAscii('5'))
+    doAssert(not isLowerAscii('&'))
+    doAssert(not isLowerAscii(' '))
+
+  block: # isUpperAscii
+    doAssert isUpperAscii('A')
+    doAssert(not isUpperAscii('b'))
+    doAssert(not isUpperAscii('5'))
+    doAssert(not isUpperAscii('%'))
+
+  block: # unescape
+    doAssert(unescape(r"\x013", "", "") == "\x013")
+
+  block: # join
+    doAssert join(["foo", "bar", "baz"]) == "foobarbaz"
+    doAssert join(@["foo", "bar", "baz"], ", ") == "foo, bar, baz"
+    doAssert join([1, 2, 3]) == "123"
+    doAssert join(@[1, 2, 3], ", ") == "1, 2, 3"
+
+  block: # startsWith / endsWith
+    var s = "abcdef"
+    doAssert s.startsWith('a')
+    doAssert s.startsWith('b') == false
+    doAssert s.endsWith('f')
+    doAssert s.endsWith('a') == false
+    doAssert s.endsWith('\0') == false
+
+  block: # nimIdentNormalize
+    doAssert nimIdentNormalize("") == ""
+    doAssert nimIdentNormalize("foo") == "foo"
+    doAssert nimIdentNormalize("foo_bar") == "foobar"
+    doAssert nimIdentNormalize("Foo_bar") == "Foobar"
+    doAssert nimIdentNormalize("_Foo_bar") == "_foobar"
+
+  block: # bug #19500
+    doAssert "abc \0 def".find("def") == 6
+    doAssert "abc \0 def".find('d') == 6
+
+
+static: main()
+main()
diff --git a/tests/stdlib/tsugar.nim b/tests/stdlib/tsugar.nim
new file mode 100644
index 000000000..2ea96cfbb
--- /dev/null
+++ b/tests/stdlib/tsugar.nim
@@ -0,0 +1,310 @@
+discard """
+  targets: "c js"
+  matrix: "--mm:refc; --mm:orc"
+  output: '''
+x + y = 30
+'''
+"""
+import std/[sugar, algorithm, random, sets, tables, strutils, sequtils]
+import std/[syncio, assertions]
+
+type # for capture test, ref #20679
+  FooCapture = ref object
+    x: int
+
+proc mainProc() =
+  block: # bug #16967
+    var s = newSeq[proc (): int](5)
+    {.push exportc.}
+    proc bar() =
+      for i in 0 ..< s.len:
+        let foo = i + 1
+        capture foo:
+          s[i] = proc(): int = foo
+    {.pop.}
+
+    bar()
+
+    for i, p in s.pairs:
+      let foo = i + 1
+      doAssert p() == foo
+
+template main() =
+  block: # `=>`
+    block:
+      let f1 = () => 42
+      doAssert f1() == 42
+
+      let f2 = (x: int) => x + 1
+      doAssert f2(42) == 43
+
+      let f3 = (x, y: int) => x + y
+      doAssert f3(1, 2) == 3
+
+      var x = 0
+      let f4 = () => (x = 12)
+      f4()
+      doAssert x == 12
+
+      let f5 = () => (discard) # simplest proc that returns void
+      f5()
+
+    block:
+      proc call1(f: () -> int): int = f()
+      doAssert call1(() => 12) == 12
+
+      proc call2(f: int -> int): int = f(42)
+      doAssert call2(x => x) == 42
+      doAssert call2((x) => x) == 42
+      doAssert call2((x: int) => x) == 42
+
+      proc call3(f: (int, int) -> int): int = f(1, 2)
+      doAssert call3((x, y) => x + y) == 3
+      doAssert call3((x, y: int) => x + y) == 3
+      doAssert call3((x: int, y: int) => x + y) == 3
+
+      var a = 0
+      proc call4(f: int -> void) = f(42)
+      call4((x: int) => (a = x))
+      doAssert a == 42
+
+      proc call5(f: (int {.noSideEffect.} -> int)): int = f(42)
+      doAssert call5(x {.noSideEffect.} => x + 1) == 43
+
+  block: # `->`
+    doAssert $(() -> int) == "proc (): int{.closure.}"
+    doAssert $(float -> int) == "proc (i0: float): int{.closure.}"
+    doAssert $((float) -> int) == "proc (i0: float): int{.closure.}"
+    doAssert $((float, bool) -> int) == "proc (i0: float, i1: bool): int{.closure.}"
+
+    doAssert $(() -> void) == "proc (){.closure.}"
+    doAssert $(float -> void) == "proc (i0: float){.closure.}"
+    doAssert $((float) -> void) == "proc (i0: float){.closure.}"
+    doAssert $((float, bool) -> void) == "proc (i0: float, i1: bool){.closure.}"
+
+    doAssert $(() {.inline.} -> int) == "proc (): int{.inline.}"
+    doAssert $(float {.inline.} -> int) == "proc (i0: float): int{.inline.}"
+    doAssert $((float) {.inline.} -> int) == "proc (i0: float): int{.inline.}"
+    doAssert $((float, bool) {.inline.} -> int) == "proc (i0: float, i1: bool): int{.inline.}"
+
+  block: # capture
+    var closure1: () -> int
+    for i in 0 .. 10:
+      if i == 5:
+        capture i:
+          closure1 = () => i
+    doAssert closure1() == 5
+
+    var closure2: () -> (int, int)
+    for i in 0 .. 10:
+      for j in 0 .. 10:
+        if i == 5 and j == 3:
+          capture i, j:
+            closure2 = () => (i, j)
+    doAssert closure2() == (5, 3)
+
+    block: # issue #20679
+      # this should compile. Previously was broken as `var int` is an `nnkHiddenDeref`
+      # which was not handled correctly
+
+      block:
+        var x = 5
+        var s1 = newSeq[proc (): int](2)
+        proc function(data: var int) =
+          for i in 0 ..< 2:
+            data = (i+1) * data
+            capture data:
+              s1[i] = proc(): int = data
+        function(x)
+        doAssert s1[0]() == 5
+        doAssert s1[1]() == 10
+
+
+      block:
+        var y = @[5, 10]
+        var s2 = newSeq[proc (): seq[int]](2)
+        proc functionS(data: var seq[int]) =
+          for i in 0 ..< 2:
+            data.add (i+1) * 5
+            capture data:
+              s2[i] = proc(): seq[int] = data
+        functionS(y)
+        doAssert s2[0]() == @[5, 10, 5]
+        doAssert s2[1]() == @[5, 10, 5, 10]
+
+
+      template typeT(typ, val: untyped): untyped =
+        var x = val
+        var s = newSeq[proc (): typ](2)
+
+        proc functionT[T](data: var T) =
+          for i in 0 ..< 2:
+            if i == 1:
+              data = default(T)
+            capture data:
+              s[i] = proc (): T = data
+
+        functionT(x)
+        doAssert s[0]() == val
+        doAssert s[1]() == x # == default
+        doAssert s[1]() == default(typ)
+
+      block:
+        var x = 1.1
+        typeT(float, x)
+      block:
+        var x = "hello"
+        typeT(string, x)
+      block:
+        var f = FooCapture(x: 5)
+        typeT(FooCapture, f)
+
+  block: # dup
+    block dup_with_field:
+      type
+        Foo = object
+          col, pos: int
+          name: string
+
+      proc inc_col(foo: var Foo) = inc(foo.col)
+      proc inc_pos(foo: var Foo) = inc(foo.pos)
+      proc name_append(foo: var Foo, s: string) = foo.name &= s
+
+      let a = Foo(col: 1, pos: 2, name: "foo")
+      block:
+        let b = a.dup(inc_col, inc_pos):
+          _.pos = 3
+          name_append("bar")
+          inc_pos
+
+        doAssert(b == Foo(col: 2, pos: 4, name: "foobar"))
+
+      block:
+        let b = a.dup(inc_col, pos = 3, name = "bar"):
+          name_append("bar")
+          inc_pos
+
+        doAssert(b == Foo(col: 2, pos: 4, name: "barbar"))
+
+    block:
+      var a = @[1, 2, 3, 4, 5, 6, 7, 8, 9]
+      doAssert dup(a, sort(_)) == sorted(a)
+      doAssert a.dup(sort) == sorted(a)
+      # Chaining:
+      var aCopy = a
+      aCopy.insert(10)
+      doAssert a.dup(insert(10)).dup(sort()) == sorted(aCopy)
+
+    block:
+      when nimvm: discard
+      else:
+        const b = @[0, 1, 2]
+        discard b.dup shuffle()
+        doAssert b[0] == 0
+        doAssert b[1] == 1
+
+  block: # collect
+    let data = @["bird", "word"] # if this gets stuck in your head, its not my fault
+
+    doAssert collect(newSeq, for (i, d) in data.pairs: (if i mod 2 == 0: d)) == @["bird"]
+    doAssert collect(initTable(2), for (i, d) in data.pairs: {i: d}) ==
+      {0: "bird", 1: "word"}.toTable
+    doAssert collect(initHashSet(), for d in data.items: {d}) == data.toHashSet
+
+    block:
+      let x = collect(newSeqOfCap(4)):
+          for (i, d) in data.pairs:
+            if i mod 2 == 0: d
+      doAssert x == @["bird"]
+
+    block: # bug #12874
+      let bug = collect(
+          newSeq,
+          for (i, d) in data.pairs:(
+            block:
+              if i mod 2 == 0:
+                d
+              else:
+                d & d
+            )
+      )
+      doAssert bug == @["bird", "wordword"]
+
+    block:
+      let y = collect(newSeq):
+        for (i, d) in data.pairs:
+          try: parseInt(d) except: 0
+      doAssert y == @[0, 0]
+
+    block:
+      let z = collect(newSeq):
+        for (i, d) in data.pairs:
+          case d
+          of "bird": "word"
+          else: d
+      doAssert z == @["word", "word"]
+
+    block:
+      proc tforum(): seq[int] =
+        collect(newSeq):
+          for y in 0..10:
+            if y mod 5 == 2:
+              for x in 0..y:
+                x
+      doAssert tforum() == @[0, 1, 2, 0, 1, 2, 3, 4, 5, 6, 7]
+
+    block:
+      let x = collect:
+        for d in data.items:
+          when d is int: "word"
+          else: d
+      doAssert x == @["bird", "word"]
+
+    block:
+      doAssert collect(for (i, d) in pairs(data): (i, d)) == @[(0, "bird"), (1, "word")]
+      doAssert collect(for d in data.items: (try: parseInt(d) except: 0)) == @[0, 0]
+      doAssert collect(for (i, d) in pairs(data): {i: d}) ==
+        {1: "word", 0: "bird"}.toTable
+      doAssert collect(for d in data.items: {d}) == data.toHashSet
+
+    block: # bug #14332
+      template foo =
+        discard collect(newSeq, for i in 1..3: i)
+      foo()
+
+  block: # dump
+    # symbols in templates are gensym'd
+    let
+      x {.inject.} = 10
+      y {.inject.} = 20
+    dump(x + y) # x + y = 30
+
+  block: # dumpToString
+    template square(x): untyped = x * x
+    let x {.inject.} = 10
+    doAssert dumpToString(square(x)) == "square(x): x * x = 100"
+    let s = dumpToString(doAssert 1+1 == 2)
+    doAssert "failedAssertImpl" in s
+    let s2 = dumpToString:
+      doAssertRaises(AssertionDefect): doAssert false
+    doAssert "except AssertionDefect" in s2
+
+  block: # bug #20704
+    proc test() =
+      var xs, ys: seq[int]
+      for i in 0..5:
+        xs.add(i)
+
+      xs.apply(proc (d: auto) = ys.add(d))
+      # ^ can be turned into d => ys.add(d) when we can infer void return type, #16906
+      doAssert ys == @[0, 1, 2, 3, 4, 5]
+
+    test()
+
+  mainProc()
+
+when not defined(js): # TODO fixme JS VM
+  static:
+    main()
+
+main()
diff --git a/tests/stdlib/tsums.nim b/tests/stdlib/tsums.nim
new file mode 100644
index 000000000..cf410cddf
--- /dev/null
+++ b/tests/stdlib/tsums.nim
@@ -0,0 +1,27 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/sums
+from math import pow
+import std/assertions
+
+var epsilon = 1.0
+while 1.0 + epsilon != 1.0:
+  epsilon /= 2.0
+let data = @[1.0, epsilon, -epsilon]
+doAssert sumKbn(data) == 1.0
+# doAssert sumPairs(data) != 1.0 # known to fail in 64 bits
+doAssert (1.0 + epsilon) - epsilon != 1.0
+
+var tc1: seq[float]
+for n in 1 .. 1000:
+  tc1.add 1.0 / n.float
+doAssert sumKbn(tc1) == 7.485470860550345
+doAssert sumPairs(tc1) == 7.485470860550345
+
+var tc2: seq[float]
+for n in 1 .. 1000:
+  tc2.add pow(-1.0, n.float) / n.float
+doAssert sumKbn(tc2) == -0.6926474305598203
+doAssert sumPairs(tc2) == -0.6926474305598204
diff --git a/tests/stdlib/tsysrand.nim b/tests/stdlib/tsysrand.nim
new file mode 100644
index 000000000..7b7a0fc34
--- /dev/null
+++ b/tests/stdlib/tsysrand.nim
@@ -0,0 +1,34 @@
+discard """
+  targets: "c cpp js"
+  matrix: "--experimental:vmopsDanger; --experimental:vmopsDanger --mm:refc"
+"""
+
+import std/sysrand
+import std/assertions
+
+template main() =
+  block:
+    var x = array[5, byte].default
+    doAssert urandom(x)
+
+  block:
+    var x = newSeq[byte](5)
+    doAssert urandom(x)
+
+  block:
+    var x = @[byte(0), 0, 0, 0, 0]
+    doAssert urandom(x)
+
+  block:
+    var x = @[byte(1), 2, 3, 4, 5]
+    doAssert urandom(x)
+
+  block:
+    doAssert urandom(0).len == 0
+    doAssert urandom(10).len == 10
+    doAssert urandom(20).len == 20
+    doAssert urandom(120).len == 120
+    doAssert urandom(113).len == 113
+    doAssert urandom(1234) != urandom(1234) # unlikely to fail in practice
+
+main()
diff --git a/tests/stdlib/tsystem.nim b/tests/stdlib/tsystem.nim
new file mode 100644
index 000000000..f634ce0c2
--- /dev/null
+++ b/tests/stdlib/tsystem.nim
@@ -0,0 +1,200 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+import stdtest/testutils
+import std/[assertions, formatfloat]
+
+# TODO: in future work move existing `system` tests here, where they belong
+
+
+template main =
+  block: # closure
+    proc outer() =
+      var a = 0
+      proc inner1 = a.inc
+      proc inner2 = discard
+      doAssert inner1 is "closure"
+      doAssert inner2 isnot "closure"
+      doAssert inner1 is (proc)
+      doAssert inner2 is (proc)
+      let inner1b = inner1
+      doAssert inner1b is "closure"
+      doAssert inner1b == inner1
+    outer()
+
+  block: # rawProc, rawProc, bug #17911
+    proc outer() =
+      var a = 0
+      var b = 0
+      proc inner1() = a.inc
+      proc inner2() = a += 2
+      proc inner3() = b.inc
+      let inner1b = inner1
+      doAssert inner2 != inner1
+      doAssert inner3 != inner1
+      whenVMorJs: discard
+      do:
+        doAssert rawProc(inner1b) == rawProc(inner1)
+        doAssert rawProc(inner2) != rawProc(inner1)
+        doAssert rawProc(inner3) != rawProc(inner1)
+
+        doAssert rawEnv(inner1b) == rawEnv(inner1)
+        doAssert rawEnv(inner2) == rawEnv(inner1) # because both use `a`
+        # doAssert rawEnv(inner3) != rawEnv(inner1) # because `a` vs `b` # this doesn't hold
+    outer()
+
+  block: # system.delete
+    block:
+      var s = @[1]
+      s.delete(0)
+      doAssert s == @[]
+
+    block:
+      var s = @["foo", "bar"]
+      s.delete(1)
+      doAssert s == @["foo"]
+
+    when false:
+      var s: seq[string]
+      doAssertRaises(IndexDefect):
+        s.delete(0)
+
+    block:
+      doAssert not compiles(@["foo"].delete(-1))
+
+    block: # bug #6710
+      var s = @["foo"]
+      s.delete(0)
+      doAssert s == @[]
+
+    when false: # bug #16544: deleting out of bounds index should raise
+      var s = @["foo"]
+      doAssertRaises(IndexDefect):
+        s.delete(1)
+
+static: main()
+main()
+
+# bug #19967
+block:
+  type
+    X = object
+      a: string
+      b: set[char]
+      c: int
+      d: float
+      e: int64
+
+
+  var x = X(b: {'a'}, e: 10)
+
+  var y = move x
+
+  doAssert x.a == ""
+  doAssert x.b == {}
+  doAssert x.c == 0
+  doAssert x.d == 0.0
+  doAssert x.e == 0
+
+  reset(y)
+
+  doAssert y.a == ""
+  doAssert y.b == {}
+  doAssert y.c == 0
+  doAssert y.d == 0.0
+  doAssert y.e == 0
+
+block:
+  var x = 2
+  var y = move x
+  doAssert y == 2
+  doAssert x == 0
+  reset y
+  doAssert y == 0
+
+block:
+  type
+    X = object
+      a: string
+      b: float
+
+  var y = X(b: 1314.521)
+
+  reset(y)
+
+  doAssert y.b == 0.0
+
+block:
+  type
+    X = object
+      a: string
+      b: string
+
+  var y = X(b: "1314")
+
+  reset(y)
+
+  doAssert y.b == ""
+
+block:
+  type
+    X = object
+      a: string
+      b: seq[int]
+
+  var y = X(b: @[1, 3])
+
+  reset(y)
+
+  doAssert y.b == @[]
+
+block:
+  type
+    X = object
+      a: string
+      b: tuple[a: int, b: string]
+
+  var y = X(b: (1, "cc"))
+
+  reset(y)
+
+  doAssert y.b == (0, "")
+
+block:
+  type
+    Color = enum
+      Red, Blue, Yellow
+    X = object
+      a: string
+      b: set[Color]
+
+  var y = X(b: {Red, Blue})
+
+  reset(y)
+  doAssert y.b == {}
+
+block: # bug #20516
+  type Foo = object
+    x {.bitsize:4.}: uint
+    y {.bitsize:4.}: uint
+
+  when not defined(js):
+    let a = create(Foo)
+
+block: # bug #6549
+  when not defined(js):
+    block:
+      const v = 18446744073709551615'u64
+
+      doAssert $v == "18446744073709551615"
+      doAssert $float32(v) == "1.8446744e+19", $float32(v)
+      doAssert $float64(v) == "1.8446744073709552e+19", $float64(v)
+
+    block:
+      let v = 18446744073709551615'u64
+
+      doAssert $v == "18446744073709551615"
+      doAssert $float32(v) == "1.8446744e+19"
+      doAssert $float64(v) == "1.8446744073709552e+19"
diff --git a/tests/stdlib/ttables.nim b/tests/stdlib/ttables.nim
new file mode 100644
index 000000000..c529aff9f
--- /dev/null
+++ b/tests/stdlib/ttables.nim
@@ -0,0 +1,316 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import tables, hashes
+import std/assertions
+
+type
+  Person = object
+    firstName, lastName: string
+
+proc hash(x: Person): Hash =
+  ## Piggyback on the already available string hash proc.
+  ##
+  ## Without this proc nothing works!
+  result = x.firstName.hash !& x.lastName.hash
+  result = !$result
+
+var
+  salaries = initTable[Person, int]()
+  p1, p2: Person
+p1.firstName = "Jon"
+p1.lastName = "Ross"
+salaries[p1] = 30_000
+p2.firstName = "소진"
+p2.lastName = "박"
+salaries[p2] = 45_000
+var
+  s2 = initOrderedTable[Person, int]()
+  s3 = initCountTable[Person]()
+s2[p1] = 30_000
+s2[p2] = 45_000
+s3[p1] = 30_000
+s3[p2] = 45_000
+
+block: # Ordered table should preserve order after deletion
+  var
+    s4 = initOrderedTable[int, int]()
+  s4[1] = 1
+  s4[2] = 2
+  s4[3] = 3
+
+  var prev = 0
+  for i in s4.values:
+    doAssert(prev < i)
+    prev = i
+
+  s4.del(2)
+  doAssert(2 notin s4)
+  doAssert(s4.len == 2)
+  prev = 0
+  for i in s4.values:
+    doAssert(prev < i)
+    prev = i
+
+block: # Deletion from OrderedTable should account for collision groups. See issue #5057.
+  # The bug is reproducible only with exact keys
+  const key1 = "boy_jackpot.inGamma"
+  const key2 = "boy_jackpot.outBlack"
+
+  var t = {
+      key1: 0,
+      key2: 0
+  }.toOrderedTable()
+
+  t.del(key1)
+  doAssert(t.len == 1)
+  doAssert(key2 in t)
+
+var
+  t1 = initCountTable[string]()
+  t2 = initCountTable[string]()
+t1.inc("foo")
+t1.inc("bar", 2)
+t1.inc("baz", 3)
+t2.inc("foo", 4)
+t2.inc("bar")
+t2.inc("baz", 11)
+merge(t1, t2)
+doAssert(t1["foo"] == 5)
+doAssert(t1["bar"] == 3)
+doAssert(t1["baz"] == 14)
+
+let
+  t1r = newCountTable[string]()
+  t2r = newCountTable[string]()
+t1r.inc("foo")
+t1r.inc("bar", 2)
+t1r.inc("baz", 3)
+t2r.inc("foo", 4)
+t2r.inc("bar")
+t2r.inc("baz", 11)
+merge(t1r, t2r)
+doAssert(t1r["foo"] == 5)
+doAssert(t1r["bar"] == 3)
+doAssert(t1r["baz"] == 14)
+
+var
+  t1l = initCountTable[string]()
+  t2l = initCountTable[string]()
+t1l.inc("foo")
+t1l.inc("bar", 2)
+t1l.inc("baz", 3)
+t2l.inc("foo", 4)
+t2l.inc("bar")
+t2l.inc("baz", 11)
+
+block:
+  const testKey = "TESTKEY"
+  let t: CountTableRef[string] = newCountTable[string]()
+
+  # Before, does not compile with error message:
+  #test_counttable.nim(7, 43) template/generic instantiation from here
+  #lib/pure/collections/tables.nim(117, 21) template/generic instantiation from here
+  #lib/pure/collections/tableimpl.nim(32, 27) Error: undeclared field: 'hcode
+  doAssert 0 == t[testKey]
+  t.inc(testKey, 3)
+  doAssert 3 == t[testKey]
+
+block:
+  # Clear tests
+  var clearTable = newTable[int, string]()
+  clearTable[42] = "asd"
+  clearTable[123123] = "piuyqwb "
+  doAssert clearTable[42] == "asd"
+  clearTable.clear()
+  doAssert(not clearTable.hasKey(123123))
+  doAssert clearTable.getOrDefault(42) == ""
+
+block: #5482
+  var a = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable()
+  var b = newOrderedTable[string, string](initialSize = 2)
+  b["wrong?"] = "foo"
+  b["wrong?"] = "foo2"
+  doAssert a == b
+
+block: #5482
+  var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
+  var b = newOrderedTable[string, string](initialSize = 2)
+  b["wrong?"] = "foo"
+  b["wrong?"] = "foo2"
+  doAssert a == b
+
+block: #5487
+  var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
+  var b = newOrderedTable[string, string]()         # notice, default size!
+  b["wrong?"] = "foo"
+  b["wrong?"] = "foo2"
+  doAssert a == b
+
+block: #5487
+  var a = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable()
+  var b = newOrderedTable[string, string]()         # notice, default size!
+  b["wrong?"] = "foo"
+  b["wrong?"] = "foo2"
+  doAssert a == b
+
+block:
+  var a = {"wrong?": "foo", "wrong?": "foo2"}.newOrderedTable()
+  var b = [("wrong?", "foo"), ("wrong?", "foo2")].newOrderedTable()
+  var c = newOrderedTable[string, string]()         # notice, default size!
+  c["wrong?"] = "foo"
+  c["wrong?"] = "foo2"
+  doAssert a == b
+  doAssert a == c
+
+block: #6250
+  let
+    a = {3: 1}.toOrderedTable
+    b = {3: 2}.toOrderedTable
+  doAssert((a == b) == false)
+  doAssert((b == a) == false)
+
+block: #6250
+  let
+    a = {3: 2}.toOrderedTable
+    b = {3: 2}.toOrderedTable
+  doAssert((a == b) == true)
+  doAssert((b == a) == true)
+
+block: # CountTable.smallest
+  let t = toCountTable([0, 0, 5, 5, 5])
+  doAssert t.smallest == (0, 2)
+
+block: #10065
+  let t = toCountTable("abracadabra")
+  doAssert t['z'] == 0
+
+  var t_mut = toCountTable("abracadabra")
+  doAssert t_mut['z'] == 0
+  # the previous read may not have modified the table.
+  doAssert t_mut.hasKey('z') == false
+  t_mut['z'] = 1
+  doAssert t_mut['z'] == 1
+  doAssert t_mut.hasKey('z') == true
+
+block: #12813 #13079
+  var t = toCountTable("abracadabra")
+  doAssert len(t) == 5
+
+  t['a'] = 0 # remove a key
+  doAssert len(t) == 4
+
+block:
+  var tp: Table[string, string] = initTable[string, string]()
+  doAssert "test1" == tp.getOrDefault("test1", "test1")
+  tp["test2"] = "test2"
+  doAssert "test2" == tp.getOrDefault("test2", "test1")
+  var tr: TableRef[string, string] = newTable[string, string]()
+  doAssert "test1" == tr.getOrDefault("test1", "test1")
+  tr["test2"] = "test2"
+  doAssert "test2" == tr.getOrDefault("test2", "test1")
+  var op: OrderedTable[string, string] = initOrderedTable[string, string]()
+  doAssert "test1" == op.getOrDefault("test1", "test1")
+  op["test2"] = "test2"
+  doAssert "test2" == op.getOrDefault("test2", "test1")
+  var orf: OrderedTableRef[string, string] = newOrderedTable[string, string]()
+  doAssert "test1" == orf.getOrDefault("test1", "test1")
+  orf["test2"] = "test2"
+  doAssert "test2" == orf.getOrDefault("test2", "test1")
+
+block tableWithoutInit:
+  var
+    a: Table[string, int]
+    b: Table[string, int]
+    c: Table[string, int]
+    d: Table[string, int]
+    e: Table[string, int]
+
+  a["a"] = 7
+  doAssert a.hasKey("a")
+  doAssert a.len == 1
+  doAssert a["a"] == 7
+  a["a"] = 9
+  doAssert a.len == 1
+  doAssert a["a"] == 9
+
+  doAssert b.hasKeyOrPut("b", 5) == false
+  doAssert b.hasKey("b")
+  doAssert b.hasKeyOrPut("b", 8)
+  doAssert b["b"] == 5
+
+  doAssert c.getOrDefault("a") == 0
+  doAssert c.getOrDefault("a", 3) == 3
+  c["a"] = 6
+  doAssert c.getOrDefault("a", 3) == 6
+
+  doAssert d.mgetOrPut("a", 3) == 3
+  doAssert d.mgetOrPut("a", 6) == 3
+
+  var x = 99
+  doAssert e.pop("a", x) == false
+  doAssert x == 99
+  e["a"] = 77
+  doAssert e.pop("a", x)
+  doAssert x == 77
+
+block orderedTableWithoutInit:
+  var
+    a: OrderedTable[string, int]
+    b: OrderedTable[string, int]
+    c: OrderedTable[string, int]
+    d: OrderedTable[string, int]
+
+  a["a"] = 7
+  doAssert a.hasKey("a")
+  doAssert a.len == 1
+  doAssert a["a"] == 7
+  a["a"] = 9
+  doAssert a.len == 1
+  doAssert a["a"] == 9
+
+  doAssert b.hasKeyOrPut("b", 5) == false
+  doAssert b.hasKey("b")
+  doAssert b.hasKeyOrPut("b", 8)
+  doAssert b["b"] == 5
+
+  doAssert c.getOrDefault("a") == 0
+  doAssert c.getOrDefault("a", 3) == 3
+  c["a"] = 6
+  doAssert c.getOrDefault("a", 3) == 6
+
+  doAssert d.mgetOrPut("a", 3) == 3
+  doAssert d.mgetOrPut("a", 6) == 3
+
+block countTableWithoutInit:
+  var
+    a: CountTable[string]
+    b: CountTable[string]
+    c: CountTable[string]
+    d: CountTable[string]
+    e: CountTable[string]
+
+  a["a"] = 7
+  doAssert a.hasKey("a")
+  doAssert a.len == 1
+  doAssert a["a"] == 7
+  a["a"] = 9
+  doAssert a.len == 1
+  doAssert a["a"] == 9
+
+  doAssert b["b"] == 0
+  b.inc("b")
+  doAssert b["b"] == 1
+
+  doAssert c.getOrDefault("a") == 0
+  doAssert c.getOrDefault("a", 3) == 3
+  c["a"] = 6
+  doAssert c.getOrDefault("a", 3) == 6
+
+  e["f"] = 3
+  merge(d, e)
+  doAssert d.hasKey("f")
+  d.inc("f")
+  merge(d, e)
+  doAssert d["f"] == 7
diff --git a/tests/stdlib/ttasks.nim b/tests/stdlib/ttasks.nim
new file mode 100644
index 000000000..ba65590d9
--- /dev/null
+++ b/tests/stdlib/ttasks.nim
@@ -0,0 +1,561 @@
+discard """
+  targets: "c cpp"
+  matrix: "--gc:orc --threads:off"
+"""
+
+import std/[tasks, strformat]
+import std/assertions
+
+block:
+  var s = ""
+  proc `+`(x: int, y: string) =
+    s.add $x & y
+
+  let literal = "Nim"
+  let t = toTask(521 + literal)
+  t.invoke()
+
+  doAssert s == "521Nim"
+
+block:
+  var s = ""
+  proc `!`(x: int) =
+    s.add $x
+
+  let t = toTask !12
+  t.invoke()
+
+  doAssert s == "12"
+
+
+block:
+  block:
+    var called = 0
+    proc hello(x: static range[1 .. 5]) =
+      called += x
+
+    let b = toTask hello(3)
+    b.invoke()
+    doAssert called == 3
+    b.invoke()
+    doAssert called == 6
+
+  block:
+    var called = 0
+    proc hello(x: range[1 .. 5]) =
+      called += x
+
+    let b = toTask hello(3)
+    b.invoke()
+    doAssert called == 3
+    b.invoke()
+    doAssert called == 6
+
+  block:
+    var called = 0
+    proc hello(x: 1 .. 5) =
+      called += x
+
+    let b = toTask hello(3)
+    b.invoke()
+    doAssert called == 3
+    b.invoke()
+    doAssert called == 6
+
+  block:
+    var temp = ""
+    proc hello(a: int or seq[string]) =
+      when a is seq[string]:
+        for s in a:
+          temp.add s
+      else:
+        temp.addInt a
+
+    let x = @["1", "2", "3", "4"]
+    let b = toTask hello(x)
+    b.invoke()
+    doAssert temp == "1234"
+    b.invoke()
+    doAssert temp == "12341234"
+
+
+  block:
+    var temp = ""
+
+    proc hello(a: int or string) =
+      when a is string:
+        temp.add a
+
+    let x = "!2"
+
+    let b = toTask hello(x)
+    b.invoke()
+    doAssert temp == x
+
+  block:
+    var temp = ""
+    proc hello(a: int or string) =
+      when a is string:
+        temp.add a
+
+    let x = "!2"
+    let b = toTask hello(x)
+    b.invoke()
+    doAssert temp == x
+
+  block:
+    var x = 0
+    proc hello(typ: typedesc) =
+      x += typ(12)
+
+    let b = toTask hello(int)
+    b.invoke()
+    doAssert x == 12
+
+  block:
+    var temp = ""
+    proc hello(a: int or seq[string]) =
+      when a is seq[string]:
+        for s in a:
+          temp.add s
+
+    let x = @["1", "2", "3", "4"]
+    let b = toTask hello(x)
+    b.invoke()
+    doAssert temp == "1234"
+
+  block:
+    var temp = ""
+    proc hello(a: int | string) =
+      when a is string:
+        temp.add a
+
+    let x = "!2"
+    let b = toTask hello(x)
+    b.invoke()
+    doAssert temp == x
+
+  block:
+    var x = 0
+    proc hello(a: int | string) =
+      when a is int:
+        x = a
+
+    let b = toTask hello(12)
+    b.invoke()
+    doAssert x == 12
+
+  block:
+    var a1: seq[int]
+    var a2 = 0
+    proc hello(c: seq[int], a: int) =
+      a1 = c
+      a2 = a
+
+    let x = 12
+    var y = @[1, 3, 1, 4, 5, x, 1]
+    let b = toTask hello(y, 12)
+    b.invoke()
+
+    doAssert a1 == y
+    doAssert a2 == x
+
+  block:
+    var a1: seq[int]
+    var a2 = 0
+    proc hello(c: seq[int], a: int) =
+      a1 = c
+      a2 = a
+    var x = 2
+    let b = toTask hello(@[1, 3, 1, 4, 5, x, 1], 12)
+    b.invoke()
+
+    doAssert a1 == @[1, 3, 1, 4, 5, x, 1]
+    doAssert a2 == 12
+
+  block:
+    var a1: array[7, int]
+    var a2 = 0
+    proc hello(c: array[7, int], a: int) =
+      a1 = c
+      a2 = a
+
+    let b = toTask hello([1, 3, 1, 4, 5, 2, 1], 12)
+    b.invoke()
+
+    doAssert a1 == [1, 3, 1, 4, 5, 2, 1]
+    doAssert a2 == 12
+
+  block:
+    var a1: seq[int]
+    var a2 = 0
+    proc hello(c: seq[int], a: int) =
+      a1 = c
+      a2 = a
+
+    let b = toTask hello(@[1, 3, 1, 4, 5, 2, 1], 12)
+    b.invoke()
+
+    doAssert a1 == @[1, 3, 1, 4, 5, 2, 1]
+    doAssert a2 == 12
+
+  block:
+    var a1: seq[int]
+    var a2 = 0
+    proc hello(a: int, c: seq[int]) =
+      a1 = c
+      a2 = a
+
+    let b = toTask hello(8, @[1, 3, 1, 4, 5, 2, 1])
+    b.invoke()
+
+    doAssert a1 == @[1, 3, 1, 4, 5, 2, 1]
+    doAssert a2 == 8
+
+    let c = toTask 8.hello(@[1, 3, 1, 4, 5, 2, 1])
+    c.invoke()
+
+    doAssert a1 == @[1, 3, 1, 4, 5, 2, 1]
+    doAssert a2 == 8
+
+  block:
+    var a1: seq[seq[int]]
+    var a2: int
+    proc hello(a: int, c: openArray[seq[int]]) =
+      a1 = @c
+      a2 = a
+
+    let b = toTask hello(8, @[@[3], @[4], @[5], @[6], @[12], @[7]])
+    b.invoke()
+
+    doAssert a1 ==  @[@[3], @[4], @[5], @[6], @[12], @[7]]
+    doAssert a2 == 8
+
+  block:
+    var a1: seq[int]
+    var a2: int
+    proc hello(a: int, c: openArray[int]) =
+      a1 = @c
+      a2 = a
+
+    let b = toTask hello(8, @[3, 4, 5, 6, 12, 7])
+    b.invoke()
+
+    doAssert a1 == @[3, 4, 5, 6, 12, 7]
+    doAssert a2 == 8
+
+  block:
+    var a1: seq[int]
+    var a2: int
+    proc hello(a: int, c: static varargs[int]) =
+      a1 = @c
+      a2 = a
+
+    let b = toTask hello(8, @[3, 4, 5, 6, 12, 7])
+    b.invoke()
+
+    doAssert a1 == @[3, 4, 5, 6, 12, 7]
+    doAssert a2 == 8
+
+  block:
+    var a1: seq[int]
+    var a2: int
+    proc hello(a: int, c: static varargs[int]) =
+      a1 = @c
+      a2 = a
+
+    let b = toTask hello(8, [3, 4, 5, 6, 12, 7])
+    b.invoke()
+
+    doAssert a1 == @[3, 4, 5, 6, 12, 7]
+    doAssert a2 == 8
+
+  block:
+    var a1: seq[int]
+    var a2: int
+    proc hello(a: int, c: varargs[int]) =
+      a1 = @c
+      a2 = a
+
+    let x = 12
+    let b = toTask hello(8, 3, 4, 5, 6, x, 7)
+    b.invoke()
+
+    doAssert a1 == @[3, 4, 5, 6, 12, 7]
+    doAssert a2 == 8
+
+  block:
+    var x = 12
+
+    proc hello(x: ptr int) =
+      x[] += 12
+
+    let b = toTask hello(addr x)
+    b.invoke()
+
+    doAssert x == 24
+
+    let c = toTask x.addr.hello
+    invoke(c)
+
+    doAssert x == 36
+  block:
+    type
+      Test = ref object
+        id: int
+
+    var x = 0
+    proc hello(a: int, c: static Test) =
+      x += a
+      x += c.id
+
+    let b = toTask hello(8, Test(id: 12))
+    b.invoke()
+
+    doAssert x == 20
+
+  block:
+    type
+      Test = object
+        id: int
+
+    var x = 0
+    proc hello(a: int, c: static Test) =
+      x += a
+      x += c.id
+
+    let b = toTask hello(8, Test(id: 12))
+    b.invoke()
+    doAssert x == 20
+
+  block:
+    var x = 0
+    proc hello(a: int, c: static seq[int]) =
+      x += a
+      for i in c:
+        x += i
+
+    let b = toTask hello(8, @[3, 4, 5, 6, 12, 7])
+    b.invoke()
+    doAssert x == 45
+
+  block:
+    var x = 0
+    proc hello(a: int, c: static array[5, int]) =
+      x += a
+      for i in c:
+        x += i
+
+    let b = toTask hello(8, [3, 4, 5, 6, 12])
+    b.invoke()
+    doAssert x == 38
+
+  block:
+    var aVal = 0
+    var cVal = ""
+
+    proc hello(a: int, c: static string) =
+      aVal += a
+      cVal.add c
+
+    var x = 1314
+    let b = toTask hello(x, "hello")
+    b.invoke()
+
+    doAssert aVal == x
+    doAssert cVal == "hello"
+
+  block:
+    var aVal = ""
+
+    proc hello(a: static string) =
+      aVal.add a
+    let b = toTask hello("hello")
+    b.invoke()
+
+    doAssert aVal == "hello"
+
+  block:
+    var aVal = 0
+    var cVal = ""
+
+    proc hello(a: static int, c: static string) =
+      aVal += a
+      cVal.add c
+    let b = toTask hello(8, "hello")
+    b.invoke()
+
+    doAssert aVal == 8
+    doAssert cVal == "hello"
+
+  block:
+    var aVal = 0
+    var cVal = 0
+
+    proc hello(a: static int, c: int) =
+      aVal += a
+      cVal += c
+
+    let b = toTask hello(c = 0, a = 8)
+    b.invoke()
+
+    doAssert aVal == 8
+    doAssert cVal == 0
+
+  block:
+    var aVal = 0
+    var cVal = 0
+
+    proc hello(a: int, c: static int) =
+      aVal += a
+      cVal += c
+
+    let b = toTask hello(c = 0, a = 8)
+    b.invoke()
+
+    doAssert aVal == 8
+    doAssert cVal == 0
+
+  block:
+    var aVal = 0
+    var cVal = 0
+
+    proc hello(a: static int, c: static int) =
+      aVal += a
+      cVal += c
+
+    let b = toTask hello(0, 8)
+    b.invoke()
+
+    doAssert aVal == 0
+    doAssert cVal == 8
+
+  block:
+    var temp = ""
+    proc hello(x: int, y: seq[string], d = 134) =
+      temp = fmt"{x=} {y=} {d=}"
+
+
+    proc main() =
+      var x = @["23456"]
+      let t = toTask hello(2233, x)
+      t.invoke()
+
+      doAssert temp == """x=2233 y=@["23456"] d=134"""
+
+    main()
+
+
+  block:
+    var temp = ""
+    proc hello(x: int, y: seq[string], d = 134) =
+      temp.add fmt"{x=} {y=} {d=}"
+
+    proc ok() =
+      temp = "ok"
+
+    proc main() =
+      var x = @["23456"]
+      let t = toTask hello(2233, x)
+      t.invoke()
+      t.invoke()
+
+      doAssert temp == """x=2233 y=@["23456"] d=134x=2233 y=@["23456"] d=134"""
+
+    main()
+
+    var x = @["4"]
+    let m = toTask hello(2233, x, 7)
+    m.invoke()
+
+    doAssert temp == """x=2233 y=@["23456"] d=134x=2233 y=@["23456"] d=134x=2233 y=@["4"] d=7"""
+
+    let n = toTask ok()
+    n.invoke()
+
+    doAssert temp == "ok"
+
+  block:
+    var called = 0
+    block:
+      proc hello() =
+        inc called
+
+      let a = toTask hello()
+      invoke(a)
+
+    doAssert called == 1
+
+    block:
+      proc hello(a: int) =
+        inc called, a
+
+      let b = toTask hello(13)
+      let c = toTask hello(a = 14)
+      b.invoke()
+      c.invoke()
+
+    doAssert called == 28
+
+    block:
+      proc hello(a: int, c: int) =
+        inc called, a
+
+      let b = toTask hello(c = 0, a = 8)
+      b.invoke()
+
+    doAssert called == 36
+
+  block:
+    proc returnsSomething(a, b: int): int = a + b
+
+    proc noArgsButReturnsSomething(): string = "abcdef"
+
+    proc testReturnValues() =
+      let t = toTask returnsSomething(2233, 11)
+      var res: int
+      t.invoke(addr res)
+      doAssert res == 2233+11
+
+      let tb = toTask noArgsButReturnsSomething()
+      var resB: string
+      tb.invoke(addr resB)
+      doAssert resB == "abcdef"
+
+    testReturnValues()
+
+
+block: # bug #23635
+  block:
+    type
+      Store = object
+        run: proc (a: int) {.nimcall, gcsafe.}
+
+    block:
+      var count = 0
+      proc hello(a: int) =
+        inc count, a
+
+      var store = Store()
+      store.run = hello
+
+      let b = toTask store.run(13)
+      b.invoke()
+      doAssert count == 13
+
+  block:
+    type
+      Store = object
+        run: proc () {.nimcall, gcsafe.}
+
+    block:
+      var count = 0
+      proc hello() =
+        inc count, 1
+
+      var store = Store()
+      store.run = hello
+
+      let b = toTask store.run()
+      b.invoke()
+      doAssert count == 1
diff --git a/tests/stdlib/ttempfiles.nim b/tests/stdlib/ttempfiles.nim
new file mode 100644
index 000000000..352788c42
--- /dev/null
+++ b/tests/stdlib/ttempfiles.nim
@@ -0,0 +1,51 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  joinable: false # not strictly necessary
+"""
+
+import std/tempfiles
+import std/[os, nre]
+import std/[assertions, syncio]
+
+const
+  prefix = "D20210502T100442" # safety precaution to only affect files/dirs with this prefix
+  suffix = ".tmp"
+
+block:
+  var t1 = createTempFile(prefix, suffix)
+  var t2 = createTempFile(prefix, suffix)
+  defer:
+    close(t1.cfile)
+    close(t2.cfile)
+    removeFile(t1.path)
+    removeFile(t2.path)
+
+  doAssert t1.path != t2.path
+
+  let s = "1234"
+  write(t1.cfile, s)
+  doAssert readAll(t2.cfile) == ""
+  doAssert readAll(t1.cfile) == ""
+  t1.cfile.setFilePos 0
+  doAssert readAll(t1.cfile) == s
+
+block: # createTempDir
+  doAssertRaises(OSError): discard createTempDir(prefix, suffix, "nonexistent")
+
+  block:
+    let dir1 = createTempDir(prefix, suffix)
+    let dir2 = createTempDir(prefix, suffix)
+    defer:
+      removeDir(dir1)
+      removeDir(dir2)
+    doAssert dir1 != dir2
+
+    doAssert dirExists(dir1)
+    doAssert dir1.lastPathPart.contains(re"^D20210502T100442(\w+).tmp$")
+    doAssert dir1.parentDir == getTempDir().normalizePathEnd()
+
+  block:
+    let dir3 = createTempDir(prefix, "_mytmp", ".")
+    doAssert dir3.lastPathPart.contains(re"^D20210502T100442(\w+)_mytmp$")
+    doAssert dir3.parentDir == "." # not getCurrentDir(): we honor the absolute/relative state of input `dir`
+    removeDir(dir3)
diff --git a/tests/stdlib/tterminal.nim b/tests/stdlib/tterminal.nim
new file mode 100644
index 000000000..16365e71c
--- /dev/null
+++ b/tests/stdlib/tterminal.nim
@@ -0,0 +1,7 @@
+discard """
+  action: compile
+"""
+import terminal, colors
+
+styledEcho fgColor, colRed, "Test"
+styledEcho bgColor, colBlue, "Test"
diff --git a/tests/stdlib/tterminal_12759.nim b/tests/stdlib/tterminal_12759.nim
new file mode 100644
index 000000000..e9ea3127c
--- /dev/null
+++ b/tests/stdlib/tterminal_12759.nim
@@ -0,0 +1,11 @@
+discard """
+  action: "compile"
+"""
+
+import terminal
+import std/syncio
+
+proc test() {.raises:[IOError, ValueError].} =
+  setBackgroundColor(stdout, bgRed)
+
+test()
diff --git a/tests/stdlib/tterminal_15874.nim b/tests/stdlib/tterminal_15874.nim
new file mode 100644
index 000000000..c3455c350
--- /dev/null
+++ b/tests/stdlib/tterminal_15874.nim
@@ -0,0 +1,8 @@
+discard """
+  cmd: "nim c --app:console $file"
+  action: "compile"
+"""
+
+import terminal
+
+writeStyled("hello", {styleBright})
diff --git a/tests/stdlib/ttestutils.nim b/tests/stdlib/ttestutils.nim
new file mode 100644
index 000000000..0f8bf16cf
--- /dev/null
+++ b/tests/stdlib/ttestutils.nim
@@ -0,0 +1,40 @@
+import stdtest/testutils
+import std/assertions
+
+block: # assertAll
+  assertAll:
+    1+1 == 2
+    var a = 3
+    a == 3
+
+  doAssertRaises(AssertionDefect):
+    assertAll:
+      1+1 == 2
+      var a = 3
+      a == 4
+
+block: # greedyOrderedSubsetLines
+  assertAll:
+    greedyOrderedSubsetLines("a1\na3", "a0\na1\na2\na3\na4")
+    not greedyOrderedSubsetLines("a3\na1", "a0\na1\na2\na3\na4") # out of order
+    not greedyOrderedSubsetLines("a1\na5", "a0\na1\na2\na3\na4") # a5 not in lhs
+
+    not greedyOrderedSubsetLines("a1\na5", "a0\na1\na2\na3\na4\nprefix:a5")
+    not greedyOrderedSubsetLines("a1\na5", "a0\na1\na2\na3\na4\na5:suffix")
+    not greedyOrderedSubsetLines("a5", "a0\na1\na2\na3\na4\nprefix:a5")
+    not greedyOrderedSubsetLines("a5", "a0\na1\na2\na3\na4\na5:suffix")
+
+block: # greedyOrderedSubsetLines with allowPrefixMatch = true
+  template fn(a, b): bool =
+    greedyOrderedSubsetLines(a, b, allowPrefixMatch = true)
+  assertAll:
+    fn("a1\na3", "a0\na1\na2\na3_suffix\na4")
+    not fn("a1\na3", "a0\na1\na2\nprefix_a3\na4")
+    # these are same as above, could be refactored
+    not fn("a3\na1", "a0\na1\na2\na3\na4") # out of order
+    not fn("a1\na5", "a0\na1\na2\na3\na4") # a5 not in lhs
+
+    not fn("a1\na5", "a0\na1\na2\na3\na4\nprefix:a5")
+    fn("a1\na5", "a0\na1\na2\na3\na4\na5:suffix")
+    not fn("a5", "a0\na1\na2\na3\na4\nprefix:a5")
+    fn("a5", "a0\na1\na2\na3\na4\na5:suffix")
diff --git a/tests/stdlib/tthreadpool.nim b/tests/stdlib/tthreadpool.nim
new file mode 100644
index 000000000..1947074be
--- /dev/null
+++ b/tests/stdlib/tthreadpool.nim
@@ -0,0 +1,14 @@
+discard """
+  matrix: "--mm:arc; --mm:refc"
+  disabled: "freebsd"
+  output: "42"
+"""
+import std/assertions
+from std/threadpool import spawn, `^`, sync
+block: # bug #12005
+  proc doworkok(i: int) {.thread.} = echo i
+  spawn(doworkok(42))
+  sync() # this works when returning void!
+
+  proc doworkbad(i: int): int {.thread.} = i
+  doAssert ^spawn(doworkbad(42)) == 42 # bug was here
diff --git a/tests/stdlib/ttimes.nim b/tests/stdlib/ttimes.nim
index 97945b21d..0f04168dc 100644
--- a/tests/stdlib/ttimes.nim
+++ b/tests/stdlib/ttimes.nim
@@ -1,32 +1,27 @@
 discard """
-  target: "c js"
+  matrix: "--mm:refc; --mm:orc; --backend:js --jsbigint64:on; --backend:js --jsbigint64:off -d:nimStringHash2"
 """
 
 import times, strutils, unittest
+import std/assertions
 
 when not defined(js):
   import os
 
-# Normally testament configures unittest with environment variables,
-# but that doesn't work for the JS target. So instead we must set the correct
-# settings here.
-addOutputFormatter(
-  newConsoleOutputFormatter(PRINT_FAILURES, colorOutput = false))
-
 proc staticTz(hours, minutes, seconds: int = 0): Timezone {.noSideEffect.} =
   let offset = hours * 3600 + minutes * 60 + seconds
 
-  proc zonedTimeFromAdjTime(adjTime: Time): ZonedTime {.locks: 0.} =
+  proc zonedTimeFromAdjTime(adjTime: Time): ZonedTime =
     result.isDst = false
     result.utcOffset = offset
     result.time = adjTime + initDuration(seconds = offset)
 
-  proc zonedTimeFromTime(time: Time): ZonedTime {.locks: 0.}=
+  proc zonedTimeFromTime(time: Time): ZonedTime =
     result.isDst = false
     result.utcOffset = offset
     result.time = time
 
-  newTimezone("", zonedTimeFromTime, zonedTImeFromAdjTime)
+  newTimezone("", zonedTimeFromTime, zonedTimeFromAdjTime)
 
 template parseTest(s, f, sExpected: string, ydExpected: int) =
   let
@@ -76,7 +71,7 @@ template runTimezoneTests() =
       "2006-01-12T22:04:05Z", 11)
   # RFC3339Nano = "2006-01-02T15:04:05.999999999Z07:00"
   parseTest("2006-01-12T15:04:05.999999999Z-07:00",
-      "yyyy-MM-dd'T'HH:mm:ss'.999999999Z'zzz", "2006-01-12T22:04:05Z", 11)
+      "yyyy-MM-dd'T'HH:mm:ss.'999999999Z'zzz", "2006-01-12T22:04:05Z", 11)
   for tzFormat in ["z", "zz", "zzz"]:
     # formatting timezone as 'Z' for UTC
     parseTest("2001-01-12T22:04:05Z", "yyyy-MM-dd'T'HH:mm:ss" & tzFormat,
@@ -90,6 +85,10 @@ template runTimezoneTests() =
       "2001-01-12T08:04:05Z", 11)
   parseTest("2001-01-12T15:04:05 +07:30:59", "yyyy-MM-dd'T'HH:mm:ss zzzz",
       "2001-01-12T07:33:06Z", 11)
+  parseTest("2001-01-12T15:04:05 +0700", "yyyy-MM-dd'T'HH:mm:ss ZZZ",
+      "2001-01-12T08:04:05Z", 11)
+  parseTest("2001-01-12T15:04:05 +073059", "yyyy-MM-dd'T'HH:mm:ss ZZZZ",
+      "2001-01-12T07:33:06Z", 11)
   # Kitchen     = "3:04PM"
   parseTestTimeOnly("3:04PM", "h:mmtt", "15:04:00")
 
@@ -122,7 +121,7 @@ template usingTimezone(tz: string, body: untyped) =
     body
     putEnv("TZ", oldZone)
 
-suite "ttimes":
+block: # ttimes
 
   # Generate tests for multiple timezone files where available
   # Set the TZ env var for each test
@@ -149,7 +148,7 @@ suite "ttimes":
     test "parseTest":
       runTimezoneTests()
 
-  test "dst handling":
+  block: # dst handling
     usingTimezone("Europe/Stockholm"):
       # In case of an impossible time, the time is moved to after the
       # impossible time period
@@ -169,7 +168,7 @@ suite "ttimes":
       check initDateTime(21, mOct, 2017, 01, 00, 00).format(f) ==
         "2017-10-21 01:00 +02:00"
 
-  test "issue #6520":
+  block: # issue #6520
     usingTimezone("Europe/Stockholm"):
       var local = fromUnix(1469275200).local
       var utc = fromUnix(1469275200).utc
@@ -178,19 +177,19 @@ suite "ttimes":
       local.utcOffset = 0
       check claimedOffset == utc.toTime - local.toTime
 
-  test "issue #5704":
+  block: # issue #5704
     usingTimezone("Asia/Seoul"):
       let diff = parse("19700101-000000", "yyyyMMdd-hhmmss").toTime -
         parse("19000101-000000", "yyyyMMdd-hhmmss").toTime
       check diff == initDuration(seconds = 2208986872)
 
-  test "issue #6465":
+  block: # issue #6465
     usingTimezone("Europe/Stockholm"):
       let dt = parse("2017-03-25 12:00", "yyyy-MM-dd hh:mm")
       check $(dt + initTimeInterval(days = 1)) == "2017-03-26T12:00:00+02:00"
       check $(dt + initDuration(days = 1)) == "2017-03-26T13:00:00+02:00"
 
-  test "adding/subtracting time across dst":
+  block: # adding/subtracting time across dst
     usingTimezone("Europe/Stockholm"):
       let dt1 = initDateTime(26, mMar, 2017, 03, 00, 00)
       check $(dt1 - 1.seconds) == "2017-03-26T01:59:59+01:00"
@@ -198,55 +197,55 @@ suite "ttimes":
       var dt2 = initDateTime(29, mOct, 2017, 02, 59, 59)
       check  $(dt2 + 1.seconds) == "2017-10-29T02:00:00+01:00"
 
-  test "datetime before epoch":
+  block: # datetime before epoch
     check $fromUnix(-2147483648).utc == "1901-12-13T20:45:52Z"
 
-  test "incorrect inputs: empty string":
+  block: # incorrect inputs: empty string
     parseTestExcp("", "yyyy-MM-dd")
 
-  test "incorrect inputs: year":
+  block: # incorrect inputs: year
     parseTestExcp("20-02-19", "yyyy-MM-dd")
 
-  test "incorrect inputs: month number":
+  block: # incorrect inputs: month number
     parseTestExcp("2018-2-19", "yyyy-MM-dd")
 
-  test "incorrect inputs: month name":
+  block: # incorrect inputs: month name
     parseTestExcp("2018-Fe", "yyyy-MMM-dd")
 
-  test "incorrect inputs: day":
+  block: # incorrect inputs: day
     parseTestExcp("2018-02-1", "yyyy-MM-dd")
 
-  test "incorrect inputs: day of week":
+  block: # incorrect inputs: day of week
     parseTestExcp("2018-Feb-Mo", "yyyy-MMM-ddd")
 
-  test "incorrect inputs: hour":
+  block: # incorrect inputs: hour
     parseTestExcp("2018-02-19 1:30", "yyyy-MM-dd hh:mm")
 
-  test "incorrect inputs: minute":
+  block: # incorrect inputs: minute
     parseTestExcp("2018-02-19 16:3", "yyyy-MM-dd hh:mm")
 
-  test "incorrect inputs: second":
+  block: # incorrect inputs: second
     parseTestExcp("2018-02-19 16:30:0", "yyyy-MM-dd hh:mm:ss")
 
-  test "incorrect inputs: timezone (z)":
+  block: # incorrect inputs: timezone (z)
     parseTestExcp("2018-02-19 16:30:00 ", "yyyy-MM-dd hh:mm:ss z")
 
-  test "incorrect inputs: timezone (zz) 1":
+  block: # incorrect inputs: timezone (zz) 1
     parseTestExcp("2018-02-19 16:30:00 ", "yyyy-MM-dd hh:mm:ss zz")
 
-  test "incorrect inputs: timezone (zz) 2":
+  block: # incorrect inputs: timezone (zz) 2
     parseTestExcp("2018-02-19 16:30:00 +1", "yyyy-MM-dd hh:mm:ss zz")
 
-  test "incorrect inputs: timezone (zzz) 1":
+  block: # incorrect inputs: timezone (zzz) 1
     parseTestExcp("2018-02-19 16:30:00 ", "yyyy-MM-dd hh:mm:ss zzz")
 
-  test "incorrect inputs: timezone (zzz) 2":
+  block: # incorrect inputs: timezone (zzz) 2
     parseTestExcp("2018-02-19 16:30:00 +01:", "yyyy-MM-dd hh:mm:ss zzz")
 
-  test "incorrect inputs: timezone (zzz) 3":
+  block: # incorrect inputs: timezone (zzz) 3
     parseTestExcp("2018-02-19 16:30:00 +01:0", "yyyy-MM-dd hh:mm:ss zzz")
 
-  test "incorrect inputs: year (yyyy/uuuu)":
+  block: # incorrect inputs: year (yyyy/uuuu)
     parseTestExcp("-0001", "yyyy")
     parseTestExcp("-0001", "YYYY")
     parseTestExcp("1", "yyyy")
@@ -255,7 +254,7 @@ suite "ttimes":
     parseTestExcp("12345", "uuuu")
     parseTestExcp("-1 BC", "UUUU g")
 
-  test "incorrect inputs: invalid sign":
+  block: # incorrect inputs: invalid sign
     parseTestExcp("+1", "YYYY")
     parseTestExcp("+1", "dd")
     parseTestExcp("+1", "MM")
@@ -263,10 +262,10 @@ suite "ttimes":
     parseTestExcp("+1", "mm")
     parseTestExcp("+1", "ss")
 
-  test "_ as a separator":
+  block: # _ as a separator
     discard parse("2000_01_01", "YYYY'_'MM'_'dd")
 
-  test "dynamic timezone":
+  block: # dynamic timezone
     let tz = staticTz(seconds = -9000)
     let dt = initDateTime(1, mJan, 2000, 12, 00, 00, tz)
     check dt.utcOffset == -9000
@@ -275,13 +274,13 @@ suite "ttimes":
     check $dt.utc == "2000-01-01T09:30:00Z"
     check $dt.utc.inZone(tz) == $dt
 
-  test "isLeapYear":
+  block: # isLeapYear
     check isLeapYear(2016)
     check (not isLeapYear(2015))
     check isLeapYear(2000)
     check (not isLeapYear(1900))
 
-  test "TimeInterval":
+  block: # TimeInterval
     let t = fromUnix(876124714).utc # Mon 6 Oct 08:58:34 BST 1997
     # Interval tests
     let t2 = t - 2.years
@@ -293,7 +292,7 @@ suite "ttimes":
     check (t + 1.hours).toTime.toUnix == t.toTime.toUnix + 60 * 60
     check (t - 1.hours).toTime.toUnix == t.toTime.toUnix - 60 * 60
 
-  test "TimeInterval - months":
+  block: # TimeInterval - months
     var dt = initDateTime(1, mFeb, 2017, 00, 00, 00, utc())
     check $(dt - initTimeInterval(months = 1)) == "2017-01-01T00:00:00Z"
     dt = initDateTime(15, mMar, 2017, 00, 00, 00, utc())
@@ -302,14 +301,14 @@ suite "ttimes":
     # This happens due to monthday overflow. It's consistent with Phobos.
     check $(dt - initTimeInterval(months = 1)) == "2017-03-03T00:00:00Z"
 
-  test "duration":
+  block: # duration
     let d = initDuration
     check d(hours = 48) + d(days = 5) == d(weeks = 1)
     let dt = initDateTime(01, mFeb, 2000, 00, 00, 00, 0, utc()) + d(milliseconds = 1)
     check dt.nanosecond == convert(Milliseconds, Nanoseconds, 1)
     check d(seconds = 1, milliseconds = 500) * 2 == d(seconds = 3)
     check d(seconds = 3) div 2 == d(seconds = 1, milliseconds = 500)
-    check d(milliseconds = 1001).seconds == 1
+    check d(milliseconds = 1001).inSeconds == 1
     check d(seconds = 1, milliseconds = 500) - d(milliseconds = 1250) ==
       d(milliseconds = 250)
     check d(seconds = 1, milliseconds = 1) < d(seconds = 1, milliseconds = 2)
@@ -322,7 +321,7 @@ suite "ttimes":
     check (initDuration(seconds = 1, nanoseconds = 3) <=
       initDuration(seconds = 1, nanoseconds = 1)).not
 
-  test "large/small dates":
+  block: # large/small dates
     discard initDateTime(1, mJan, -35_000, 12, 00, 00, utc())
     # with local tz
     discard initDateTime(1, mJan, -35_000, 12, 00, 00)
@@ -334,7 +333,7 @@ suite "ttimes":
     let dt2 = dt + 35_001.years
     check $dt2 == "0001-01-01T12:00:01Z"
 
-  test "compare datetimes":
+  block: # compare datetimes
     var dt1 = now()
     var dt2 = dt1
     check dt1 == dt2
@@ -342,23 +341,27 @@ suite "ttimes":
     dt2 = dt2 + 1.seconds
     check dt1 < dt2
 
-  test "adding/subtracting TimeInterval":
+  block: # adding/subtracting TimeInterval
     # add/subtract TimeIntervals and Time/TimeInfo
     let now = getTime().utc
+    let isSpecial = now.isLeapDay
     check now + convert(Seconds, Nanoseconds, 1).nanoseconds == now + 1.seconds
     check now + 1.weeks == now + 7.days
     check now - 1.seconds == now - 3.seconds + 2.seconds
     check now + 65.seconds == now + 1.minutes + 5.seconds
     check now + 60.minutes == now + 1.hours
     check now + 24.hours == now + 1.days
-    check now + 13.months == now + 1.years + 1.months
+    if not isSpecial:
+      check now + 13.months == now + 1.years + 1.months
     check toUnix(fromUnix(0) + 2.seconds) == 2
     check toUnix(fromUnix(0) - 2.seconds) == -2
     var ti1 = now + 1.years
     ti1 = ti1 - 1.years
-    check ti1 == now
+    if not isSpecial:
+      check ti1 == now
     ti1 = ti1 + 1.days
-    check ti1 == now + 1.days
+    if not isSpecial:
+      check ti1 == now + 1.days
 
     # Bug with adding a day to a Time
     let day = 24.hours
@@ -376,14 +379,14 @@ suite "ttimes":
       check initTime(0, 101).toWinTime.fromWinTime.nanosecond == 100
       check initTime(0, 101).toWinTime.fromWinTime.nanosecond == 100
 
-  test "issue 7620":
+  block: # issue 7620
     let layout = "M/d/yyyy' 'h:mm:ss' 'tt' 'z"
     let t7620_am = parse("4/15/2017 12:01:02 AM +0", layout, utc())
     check t7620_am.format(layout) == "4/15/2017 12:01:02 AM Z"
     let t7620_pm = parse("4/15/2017 12:01:02 PM +0", layout, utc())
     check t7620_pm.format(layout) == "4/15/2017 12:01:02 PM Z"
 
-  test "format":
+  block: # format
     var dt = initDateTime(1, mJan, -0001,
                           17, 01, 02, 123_456_789,
                           staticTz(hours = 1, minutes = 2, seconds = 3))
@@ -452,7 +455,7 @@ suite "ttimes":
       doAssert dt.format("zz") == tz[2]
       doAssert dt.format("zzz") == tz[3]
 
-  test "format locale":
+  block: # format locale
     let loc = DateTimeLocale(
       MMM: ["Fir","Sec","Thi","Fou","Fif","Six","Sev","Eig","Nin","Ten","Ele","Twe"],
       MMMM: ["Firsty", "Secondy", "Thirdy", "Fourthy", "Fifthy", "Sixthy", "Seventhy", "Eighthy", "Ninthy", "Tenthy", "Eleventhy", "Twelfthy"],
@@ -469,7 +472,7 @@ suite "ttimes":
     check dt.format("MMM", loc) == "Fir"
     check dt.format("MMMM", loc) == "Firsty"
 
-  test "parse":
+  block: # parse
     check $parse("20180101", "yyyyMMdd", utc()) == "2018-01-01T00:00:00Z"
     parseTestExcp("+120180101", "yyyyMMdd")
 
@@ -490,7 +493,7 @@ suite "ttimes":
 
     parseTestExcp("2000 A", "yyyy g")
 
-  test "parse locale":
+  block: # parse locale
     let loc = DateTimeLocale(
       MMM: ["Fir","Sec","Thi","Fou","Fif","Six","Sev","Eig","Nin","Ten","Ele","Twe"],
       MMMM: ["Firsty", "Secondy", "Thirdy", "Fourthy", "Fifthy", "Sixthy", "Seventhy", "Eighthy", "Ninthy", "Tenthy", "Eleventhy", "Twelfthy"],
@@ -500,13 +503,7 @@ suite "ttimes":
     check $parse("02 Fir 2019", "dd MMM yyyy", utc(), loc) == "2019-01-02T00:00:00Z"
     check $parse("Fourthy 6, 2017", "MMMM d, yyyy", utc(), loc) == "2017-04-06T00:00:00Z"
 
-  test "countLeapYears":
-    # 1920, 2004 and 2020 are leap years, and should be counted starting at the following year
-    check countLeapYears(1920) + 1 == countLeapYears(1921)
-    check countLeapYears(2004) + 1 == countLeapYears(2005)
-    check countLeapYears(2020) + 1 == countLeapYears(2021)
-
-  test "timezoneConversion":
+  block: # timezoneConversion
     var l = now()
     let u = l.utc
     l = u.local
@@ -514,7 +511,7 @@ suite "ttimes":
     check l.timezone == local()
     check u.timezone == utc()
 
-  test "getDayOfWeek":
+  block: # getDayOfWeek
     check getDayOfWeek(01, mJan, 0000) == dSat
     check getDayOfWeek(01, mJan, -0023) == dSat
     check getDayOfWeek(21, mSep, 1900) == dFri
@@ -523,29 +520,29 @@ suite "ttimes":
     check getDayOfWeek(01, mJan, 2000) == dSat
     check getDayOfWeek(01, mJan, 2021) == dFri
 
-  test "between - simple":
+  block: # between - simple
     let x = initDateTime(10, mJan, 2018, 13, 00, 00)
     let y = initDateTime(11, mJan, 2018, 12, 00, 00)
     doAssert x + between(x, y) == y
 
-  test "between - dst start":
+  block: # between - dst start
     usingTimezone("Europe/Stockholm"):
       let x = initDateTime(25, mMar, 2018, 00, 00, 00)
       let y = initDateTime(25, mMar, 2018, 04, 00, 00)
       doAssert x + between(x, y) == y
 
-  test "between - empty interval":
+  block: # between - empty interval
     let x = now()
     let y = x
     doAssert x + between(x, y) == y
 
-  test "between - dst end":
+  block: # between - dst end
     usingTimezone("Europe/Stockholm"):
       let x = initDateTime(27, mOct, 2018, 02, 00, 00)
       let y = initDateTime(28, mOct, 2018, 01, 00, 00)
       doAssert x + between(x, y) == y
 
-  test "between - long day":
+  block: # between - long day
     usingTimezone("Europe/Stockholm"):
       # This day is 25 hours long in Europe/Stockholm
       let x = initDateTime(28, mOct, 2018, 00, 30, 00)
@@ -553,7 +550,7 @@ suite "ttimes":
       doAssert between(x, y) == 24.hours + 30.minutes
       doAssert x + between(x, y) == y
 
-  test "between - offset change edge case":
+  block: # between - offset change edge case
     # This test case is important because in this case
     # `x + between(x.utc, y.utc) == y` is not true, which is very rare.
     usingTimezone("America/Belem"):
@@ -562,19 +559,19 @@ suite "ttimes":
       doAssert x + between(x, y) == y
       doAssert y + between(y, x) == x
 
-  test "between - all units":
+  block: # between - all units
     let x = initDateTime(1, mJan, 2000, 00, 00, 00, utc())
     let ti = initTimeInterval(1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
     let y = x + ti
     doAssert between(x, y) == ti
     doAssert between(y, x) == -ti
 
-  test "between - monthday overflow":
+  block: # between - monthday overflow
       let x = initDateTime(31, mJan, 2001, 00, 00, 00, utc())
       let y = initDateTime(1, mMar, 2001, 00, 00, 00, utc())
       doAssert x + between(x, y) == y
 
-  test "between - misc":
+  block: # between - misc
     block:
       let x = initDateTime(31, mDec, 2000, 12, 00, 00, utc())
       let y = initDateTime(01, mJan, 2001, 00, 00, 00, utc())
@@ -616,7 +613,33 @@ suite "ttimes":
       doAssert x + between(x, y) == y
       doAssert between(x, y) == 1.months + 1.weeks
 
-  test "inX procs":
+  block: # default DateTime https://github.com/nim-lang/RFCs/issues/211
+    var num = 0
+    for ai in Month: num.inc
+    check num == 12
+
+    var a: DateTime
+    check a == DateTime.default
+    check not a.isInitialized
+    check $a == "Uninitialized DateTime"
+
+    expect(AssertionDefect): discard getDayOfWeek(a.monthday, a.month, a.year)
+    expect(AssertionDefect): discard a.toTime
+    expect(AssertionDefect): discard a.utc()
+    expect(AssertionDefect): discard a.local()
+    expect(AssertionDefect): discard a.inZone(utc())
+    expect(AssertionDefect): discard a + initDuration(seconds = 1)
+    expect(AssertionDefect): discard a + initTimeInterval(seconds = 1)
+    expect(AssertionDefect): discard a.isLeapDay
+    expect(AssertionDefect): discard a < a
+    expect(AssertionDefect): discard a <= a
+    expect(AssertionDefect): discard getDateStr(a)
+    expect(AssertionDefect): discard getClockStr(a)
+    expect(AssertionDefect): discard a.format "yyyy"
+    expect(AssertionDefect): discard a.format initTimeFormat("yyyy")
+    expect(AssertionDefect): discard between(a, a)
+
+  block: # inX procs
     doAssert initDuration(seconds = 1).inSeconds == 1
     doAssert initDuration(seconds = -1).inSeconds == -1
     doAssert initDuration(seconds = -1, nanoseconds = 1).inSeconds == 0
@@ -624,3 +647,138 @@ suite "ttimes":
     doAssert initDuration(milliseconds = 500).inMilliseconds == 500
     doAssert initDuration(milliseconds = -500).inMilliseconds == -500
     doAssert initDuration(nanoseconds = -999999999).inMilliseconds == -999
+
+  block: # getIsoWeekAndYear
+    doAssert getIsoWeekAndYear(initDateTime(04, mNov, 2019, 00, 00, 00)) == (isoweek: 45.IsoWeekRange, isoyear: 2019.IsoYear)
+    doAssert initDateTime(dMon, 45, 2019.IsoYear, 00, 00, 00) == initDateTime(04, mNov, 2019, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(28, mDec, 2019, 00, 00, 00)) == (isoweek: 52.IsoWeekRange, isoyear: 2019.IsoYear)
+    doAssert initDateTime(dSat, 52, 2019.IsoYear, 00, 00, 00) == initDateTime(28, mDec, 2019, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(29, mDec, 2019, 00, 00, 00)) == (isoweek: 52.IsoWeekRange, isoyear: 2019.IsoYear)
+    doAssert initDateTime(dSun, 52, 2019.IsoYear, 00, 00, 00) == initDateTime(29, mDec, 2019, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(30, mDec, 2019, 00, 00, 00)) == (isoweek: 01.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dMon, 01, 2020.IsoYear, 00, 00, 00) == initDateTime(30, mDec, 2019, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(31, mDec, 2019, 00, 00, 00)) == (isoweek: 01.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dTue, 01, 2020.IsoYear, 00, 00, 00) == initDateTime(31, mDec, 2019, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(01, mJan, 2020, 00, 00, 00)) == (isoweek: 01.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dWed, 01, 2020.IsoYear, 00, 00, 00) == initDateTime(01, mJan, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(02, mJan, 2020, 00, 00, 00)) == (isoweek: 01.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dThu, 01, 2020.IsoYear, 00, 00, 00) == initDateTime(02, mJan, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(05, mApr, 2020, 00, 00, 00)) == (isoweek: 14.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dSun, 14, 2020.IsoYear, 00, 00, 00) == initDateTime(05, mApr, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(06, mApr, 2020, 00, 00, 00)) == (isoweek: 15.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dMon, 15, 2020.IsoYear, 00, 00, 00) == initDateTime(06, mApr, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(10, mApr, 2020, 00, 00, 00)) == (isoweek: 15.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dFri, 15, 2020.IsoYear, 00, 00, 00) == initDateTime(10, mApr, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(12, mApr, 2020, 00, 00, 00)) == (isoweek: 15.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dSun, 15, 2020.IsoYear, 00, 00, 00) == initDateTime(12, mApr, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(13, mApr, 2020, 00, 00, 00)) == (isoweek: 16.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dMon, 16, 2020.IsoYear, 00, 00, 00) == initDateTime(13, mApr, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(15, mApr, 2020, 00, 00, 00)) == (isoweek: 16.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dThu, 16, 2020.IsoYear, 00, 00, 00) == initDateTime(16, mApr, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(17, mJul, 2020, 00, 00, 00)) == (isoweek: 29.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dFri, 29, 2020.IsoYear, 00, 00, 00) == initDateTime(17, mJul, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(19, mJul, 2020, 00, 00, 00)) == (isoweek: 29.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dSun, 29, 2020.IsoYear, 00, 00, 00) == initDateTime(19, mJul, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(20, mJul, 2020, 00, 00, 00)) == (isoweek: 30.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dMon, 30, 2020.IsoYear, 00, 00, 00) == initDateTime(20, mJul, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(23, mJul, 2020, 00, 00, 00)) == (isoweek: 30.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dThu, 30, 2020.IsoYear, 00, 00, 00) == initDateTime(23, mJul, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(31, mDec, 2020, 00, 00, 00)) == (isoweek: 53.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dThu, 53, 2020.IsoYear, 00, 00, 00) == initDateTime(31, mDec, 2020, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(01, mJan, 2021, 00, 00, 00)) == (isoweek: 53.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dFri, 53, 2020.IsoYear, 00, 00, 00) == initDateTime(01, mJan, 2021, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(02, mJan, 2021, 00, 00, 00)) == (isoweek: 53.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dSat, 53, 2020.IsoYear, 00, 00, 00) == initDateTime(02, mJan, 2021, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(03, mJan, 2021, 00, 00, 00)) == (isoweek: 53.IsoWeekRange, isoyear: 2020.IsoYear)
+    doAssert initDateTime(dSun, 53, 2020.IsoYear, 00, 00, 00) == initDateTime(03, mJan, 2021, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(04, mJan, 2021, 00, 00, 00)) == (isoweek: 01.IsoWeekRange, isoyear: 2021.IsoYear)
+    doAssert initDateTime(dMon, 01, 2021.IsoYear, 00, 00, 00) == initDateTime(04, mJan, 2021, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(01, mFeb, 2021, 00, 00, 00)) == (isoweek: 05.IsoWeekRange, isoyear: 2021.IsoYear)
+    doAssert initDateTime(dMon, 05, 2021.IsoYear, 00, 00, 00) == initDateTime(01, mFeb, 2021, 00, 00, 00)
+
+    doAssert getIsoWeekAndYear(initDateTime(01, mFeb, 2021, 01, 02, 03, 400_000_000, staticTz(hours=1))) == (isoweek: 05.IsoWeekRange, isoyear: 2021.IsoYear)
+    doAssert initDateTime(dMon, 05, 2021.IsoYear, 01, 02, 03, 400_000_000, staticTz(hours=1)) == initDateTime(01, mFeb, 2021, 01, 02, 03, 400_000_000, staticTz(hours=1))
+
+    doAssert getIsoWeekAndYear(initDateTime(01, mApr, +0001, 00, 00, 00)) == (isoweek: 13.IsoWeekRange, isoyear: 0001.IsoYear)
+    doAssert initDateTime(dSun, 13, 0001.IsoYear, 00, 00, 00) == initDateTime(01, mApr, 0001, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(01, mApr, +0000, 00, 00, 00)) == (isoweek: 13.IsoWeekRange, isoyear: 0000.IsoYear)
+    doAssert initDateTime(dSat, 13, 0000.IsoYear, 00, 00, 00) == initDateTime(01, mApr, 0000, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(01, mApr, -0001, 00, 00, 00)) == (isoweek: 13.IsoWeekRange, isoyear: (-0001).IsoYear)
+    doAssert initDateTime(dThu, 13, (-0001).IsoYear, 00, 00, 00) == initDateTime(01, mApr, -0001, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(01, mApr, -0002, 00, 00, 00)) == (isoweek: 14.IsoWeekRange, isoyear: (-0002).IsoYear)
+    doAssert initDateTime(dWed, 14, (-0002).IsoYear, 00, 00, 00) == initDateTime(01, mApr, -0002, 00, 00, 00)
+    doAssert getIsoWeekAndYear(initDateTime(01, mApr, -0753, 00, 00, 00)) == (isoweek: 14.IsoWeekRange, isoyear: (-0753).IsoYear)
+    doAssert initDateTime(dMon, 14, (-0753).IsoYear, 00, 00, 00) == initDateTime(01, mApr, -0753, 00, 00, 00)
+
+  block: # getWeeksInIsoYear
+    doAssert getWeeksInIsoYear((-0014).IsoYear) == 52
+    doAssert getWeeksInIsoYear((-0013).IsoYear) == 53
+    doAssert getWeeksInIsoYear((-0012).IsoYear) == 52
+
+    doAssert getWeeksInIsoYear((-0009).IsoYear) == 52
+    doAssert getWeeksInIsoYear((-0008).IsoYear) == 53
+    doAssert getWeeksInIsoYear((-0007).IsoYear) == 52
+
+    doAssert getWeeksInIsoYear((-0003).IsoYear) == 52
+    doAssert getWeeksInIsoYear((-0002).IsoYear) == 53
+    doAssert getWeeksInIsoYear((-0001).IsoYear) == 52
+
+    doAssert getWeeksInIsoYear(0003.IsoYear) == 52
+    doAssert getWeeksInIsoYear(0004.IsoYear) == 53
+    doAssert getWeeksInIsoYear(0005.IsoYear) == 52
+
+    doAssert getWeeksInIsoYear(1653.IsoYear) == 52
+    doAssert getWeeksInIsoYear(1654.IsoYear) == 53
+    doAssert getWeeksInIsoYear(1655.IsoYear) == 52
+
+    doAssert getWeeksInIsoYear(1997.IsoYear) == 52
+    doAssert getWeeksInIsoYear(1998.IsoYear) == 53
+    doAssert getWeeksInIsoYear(1999.IsoYear) == 52
+
+    doAssert getWeeksInIsoYear(2008.IsoYear) == 52
+    doAssert getWeeksInIsoYear(2009.IsoYear) == 53
+    doAssert getWeeksInIsoYear(2010.IsoYear) == 52
+
+    doAssert getWeeksInIsoYear(2014.IsoYear) == 52
+    doAssert getWeeksInIsoYear(2015.IsoYear) == 53
+    doAssert getWeeksInIsoYear(2016.IsoYear) == 52
+
+  block: # parse and generate iso years
+    # short calendar week with text
+    parseTest("KW 23 2023", "'KW' VV GGGG",
+      "2023-06-05T00:00:00Z", 155)
+    parseTest("KW 5 2023", "'KW' V GGGG",
+      "2023-01-30T00:00:00Z", 29)
+    parseTest("KW 05 23 Saturday", "'KW' V GG dddd",
+      "2023-02-04T00:00:00Z", 34)
+    parseTest("KW 53 20 Fri", "'KW' VV GG ddd",
+      "2021-01-01T00:00:00Z", 0)
+
+    parseTestExcp("KW 23", "'KW' VV") # no year
+    parseTestExcp("KW 23", "'KW' V") # no year
+    parseTestExcp("KW 23", "'KW' GG") # no week
+    parseTestExcp("KW 2023", "'KW' GGGG") # no week
+    
+    var dt = initDateTime(5, mJan, 2023, 0, 0, 0, utc())
+    check dt.format("V") == "1"
+    check dt.format("VV") == "01"
+    check dt.format("GG") == "23"
+    check dt.format("GGGG") == "2023"
+    check dt.format("dddd 'KW'V GGGG") == "Thursday KW1 2023"
+
+  block: # Can be used inside gcsafe proc
+    proc test(): DateTime {.gcsafe.} =
+      result = "1970".parse("yyyy")
+    doAssert test().year == 1970
+
+  block: # test FormatLiterals
+    # since #23861
+    block:
+      let dt = dateTime(2024, mJul, 21, 17, 01, 02, 123_321_123, utc())
+      check dt.format("ss.fff") == "02.123"
+      check dt.format("fff.ffffff") == "123.123321"
+    block:
+      let dt = parse("2024.07.21", "yyyy.MM.dd")
+      check dt.year == 2024
+      check dt.month == mJul
+      check dt.monthday == 21
diff --git a/tests/stdlib/ttypeinfo.nim b/tests/stdlib/ttypeinfo.nim
new file mode 100644
index 000000000..9bbc2e92c
--- /dev/null
+++ b/tests/stdlib/ttypeinfo.nim
@@ -0,0 +1,93 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/typeinfo
+import std/assertions
+
+type
+  TE = enum
+    blah, blah2
+
+  TestObj = object
+    test, asd: int
+    case test2: TE
+    of blah:
+      help: string
+    else:
+      nil
+
+
+var test = @[0,1,2,3,4]
+var x = toAny(test)
+var y = 78
+x[4] = toAny(y)
+doAssert x[2].getInt == 2
+
+var test2: tuple[name: string, s: int] = ("test", 56)
+var x2 = toAny(test2)
+var i = 0
+for n, a in fields(x2):
+  case i
+  of 0: doAssert n == "Field0" and $a.kind == "akString"
+  of 1: doAssert n == "Field1" and $a.kind == "akInt"
+  else: doAssert false
+  inc i
+
+var test3: TestObj
+test3.test = 42
+test3 = TestObj(test2: blah2)
+var x3 = toAny(test3)
+i = 0
+for n, a in fields(x3):
+  case i
+  of 0: doAssert n == "test" and $a.kind == "akInt"
+  of 1: doAssert n == "asd" and $a.kind == "akInt"
+  of 2: doAssert n == "test2" and $a.kind == "akEnum"
+  else: doAssert false
+  inc i
+
+var test4: ref string
+new(test4)
+test4[] = "test"
+var x4 = toAny(test4)
+doAssert($x4[].kind() == "akString")
+
+block:
+  # gimme a new scope dammit
+  var myArr: array[0..4, array[0..4, string]] = [
+    ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
+    ["test", "1", "2", "3", "4"], ["test", "1", "2", "3", "4"],
+    ["test", "1", "2", "3", "4"]]
+  var m = toAny(myArr)
+  for i in 0 .. m.len-1:
+    for j in 0 .. m[i].len-1:
+      doAssert getString(m[i][j]) == myArr[i][j]
+
+block:
+  type
+    Test = enum
+      Hello, he_llo
+
+  var x = hello
+  var y = x.toAny
+
+  doAssert getEnumOrdinal(y, "Hello") == 0
+  doAssert getEnumOrdinal(y, "hello") == 1
+
+block: # bug #23556
+  proc test =
+    var
+      t: seq[int]
+      aseq = toAny(t)
+
+    invokeNewSeq(aseq, 0)
+
+    # Got random value only when loop 8 times.
+    for i in 1 .. 8:
+      extendSeq(aseq)
+
+    doAssert t == @[0, 0, 0, 0, 0, 0, 0, 0]
+
+  for i in 1 .. 7:
+    test()
diff --git a/tests/stdlib/ttypeinfo.nims b/tests/stdlib/ttypeinfo.nims
new file mode 100644
index 000000000..d31d0b26f
--- /dev/null
+++ b/tests/stdlib/ttypeinfo.nims
@@ -0,0 +1 @@
+--styleCheck:off
\ No newline at end of file
diff --git a/tests/stdlib/ttypetraits.nim b/tests/stdlib/ttypetraits.nim
new file mode 100644
index 000000000..6851b9220
--- /dev/null
+++ b/tests/stdlib/ttypetraits.nim
@@ -0,0 +1,94 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+# xxx merge with tests/metatype/ttypetraits.nim
+
+import std/typetraits
+import std/assertions
+
+macro testClosure(fn: typed, flag: static bool) =
+  if flag:
+    doAssert hasClosure(fn)
+  else:
+    doAssert not hasClosure(fn)
+
+block:
+  proc h1() =
+    echo 1
+
+  testClosure(h1, false)
+
+  proc h2() {.nimcall.} =
+    echo 2
+
+  testClosure(h2, false)
+
+
+block:
+  proc fn(): auto =
+    proc hello() {.nimcall.} =
+      echo 3
+    hello
+
+  let name = fn()
+  testClosure(name, false)
+
+block:
+  proc fn(): auto =
+    proc hello() =
+      echo 3
+    hello
+
+  let name = fn()
+  testClosure(name, false)
+
+block:
+  proc fn(): auto =
+    var x = 0
+    proc hello() =
+      echo 3
+      inc x
+    hello
+
+  let name = fn()
+  testClosure(name, true)
+
+block:
+  proc fn(): auto =
+    var x = 0
+    proc hello() {.closure.} =
+      echo 3
+      inc x
+    hello
+
+  let name = fn()
+  testClosure(name, true)
+
+block:
+  proc fn(): auto =
+    var x = 0
+    proc hello() {.closure.} =
+      echo 3
+      inc x
+    hello
+
+  let name = fn()
+  testClosure(name, true)
+
+  let name2 = name
+  testClosure(name2, true)
+
+block:
+  iterator hello(): int =
+    yield 1
+
+  testClosure(hello, false)
+
+when not defined(js):
+  block:
+    iterator hello(): int {.closure.}=
+      yield 1
+
+    testClosure(hello, true)
diff --git a/tests/stdlib/tunicode.nim b/tests/stdlib/tunicode.nim
new file mode 100644
index 000000000..b9e68b15b
--- /dev/null
+++ b/tests/stdlib/tunicode.nim
@@ -0,0 +1,228 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/unicode
+import std/assertions
+
+proc asRune(s: static[string]): Rune =
+  ## Compile-time conversion proc for converting string literals to a Rune
+  ## value. Returns the first Rune of the specified string.
+  ##
+  ## Shortcuts code like ``"å".runeAt(0)`` to ``"å".asRune`` and returns a
+  ## compile-time constant.
+  if s.len == 0: Rune(0)
+  else: s.runeAt(0)
+
+let
+  someString = "öÑ"
+  someRunes = toRunes(someString)
+  compared = (someString == $someRunes)
+doAssert compared == true
+
+proc testReplacements(word: string): string =
+  case word
+  of "two":
+    return "2"
+  of "foo":
+    return "BAR"
+  of "βeta":
+    return "beta"
+  of "alpha":
+    return "αlpha"
+  else:
+    return "12345"
+
+doAssert translate("two not alpha foo βeta", testReplacements) == "2 12345 αlpha BAR beta"
+doAssert translate("  two not foo βeta  ", testReplacements) == "  2 12345 BAR beta  "
+
+doAssert title("foo bar") == "Foo Bar"
+doAssert title("αlpha βeta γamma") == "Αlpha Βeta Γamma"
+doAssert title("") == ""
+
+doAssert capitalize("βeta") == "Βeta"
+doAssert capitalize("foo") == "Foo"
+doAssert capitalize("") == ""
+
+doAssert swapCase("FooBar") == "fOObAR"
+doAssert swapCase(" ") == " "
+doAssert swapCase("Αlpha Βeta Γamma") == "αLPHA βETA γAMMA"
+doAssert swapCase("a✓B") == "A✓b"
+doAssert swapCase("Јамогујестистаклоитоминештети") == "јАМОГУЈЕСТИСТАКЛОИТОМИНЕШТЕТИ"
+doAssert swapCase("ὕαλονϕαγεῖνδύναμαιτοῦτοοὔμεβλάπτει") == "ὝΑΛΟΝΦΑΓΕῖΝΔΎΝΑΜΑΙΤΟῦΤΟΟὔΜΕΒΛΆΠΤΕΙ"
+doAssert swapCase("Կրնամապակիուտեևինծիանհանգիստչըներ") == "կՐՆԱՄԱՊԱԿԻՈՒՏԵևԻՆԾԻԱՆՀԱՆԳԻՍՏՉԸՆԵՐ"
+doAssert swapCase("") == ""
+
+doAssert isAlpha("r")
+doAssert isAlpha("α")
+doAssert isAlpha("ϙ")
+doAssert isAlpha("ஶ")
+doAssert isAlpha("网")
+doAssert(not isAlpha("$"))
+doAssert(not isAlpha(""))
+
+doAssert isAlpha("Βeta")
+doAssert isAlpha("Args")
+doAssert isAlpha("𐌼𐌰𐌲𐌲𐌻𐌴𐍃𐍄𐌰𐌽")
+doAssert isAlpha("ὕαλονϕαγεῖνδύναμαιτοῦτοοὔμεβλάπτει")
+doAssert isAlpha("Јамогујестистаклоитоминештети")
+doAssert isAlpha("Կրնամապակիուտեևինծիանհանգիստչըներ")
+doAssert isAlpha("编程语言")
+doAssert(not isAlpha("$Foo✓"))
+doAssert(not isAlpha("⠙⠕⠑⠎⠝⠞"))
+
+doAssert isSpace("\t")
+doAssert isSpace("\l")
+doAssert(not isSpace("Β"))
+doAssert(not isSpace("Βeta"))
+
+doAssert isSpace("\t\l \v\r\f")
+doAssert isSpace("       ")
+doAssert(not isSpace(""))
+doAssert(not isSpace("ΑΓc   \td"))
+
+doAssert(not isLower(' '.Rune))
+
+doAssert(not isUpper(' '.Rune))
+
+doAssert toUpper("Γ") == "Γ"
+doAssert toUpper("b") == "B"
+doAssert toUpper("α") == "Α"
+doAssert toUpper("✓") == "✓"
+doAssert toUpper("ϙ") == "Ϙ"
+doAssert toUpper("") == ""
+
+doAssert toUpper("ΑΒΓ") == "ΑΒΓ"
+doAssert toUpper("AAccβ") == "AACCΒ"
+doAssert toUpper("A✓$β") == "A✓$Β"
+
+doAssert toLower("a") == "a"
+doAssert toLower("γ") == "γ"
+doAssert toLower("Γ") == "γ"
+doAssert toLower("4") == "4"
+doAssert toLower("Ϙ") == "ϙ"
+doAssert toLower("") == ""
+
+doAssert toLower("abcdγ") == "abcdγ"
+doAssert toLower("abCDΓ") == "abcdγ"
+doAssert toLower("33aaΓ") == "33aaγ"
+
+doAssert reversed("Reverse this!") == "!siht esreveR"
+doAssert reversed("先秦兩漢") == "漢兩秦先"
+doAssert reversed("as⃝df̅") == "f̅ds⃝a"
+doAssert reversed("a⃞b⃞c⃞") == "c⃞b⃞a⃞"
+doAssert reversed("ὕαλονϕαγεῖνδύναμαιτοῦτοοὔμεβλάπτει") == "ιετπάλβεμὔοοτῦοτιαμανύδνῖεγαϕνολαὕ"
+doAssert reversed("Јамогујестистаклоитоминештети") == "итетшенимотиолкатситсејугомаЈ"
+doAssert reversed("Կրնամապակիուտեևինծիանհանգիստչըներ") == "րենըչտսիգնահնաիծնիևետւոիկապամանրԿ"
+doAssert len(toRunes("as⃝df̅")) == runeLen("as⃝df̅")
+const test = "as⃝"
+doAssert lastRune(test, test.len-1)[1] == 3
+doAssert graphemeLen("è", 0) == 2
+
+# test for rune positioning and runeSubStr()
+let s = "Hänsel  ««: 10,00€"
+
+var t = ""
+for c in s.utf8:
+  t.add c
+
+doAssert(s == t)
+
+doAssert(runeReverseOffset(s, 1) == (20, 18))
+doAssert(runeReverseOffset(s, 19) == (-1, 18))
+
+doAssert(runeStrAtPos(s, 0) == "H")
+doAssert(runeSubStr(s, 0, 1) == "H")
+doAssert(runeStrAtPos(s, 10) == ":")
+doAssert(runeSubStr(s, 10, 1) == ":")
+doAssert(runeStrAtPos(s, 9) == "«")
+doAssert(runeSubStr(s, 9, 1) == "«")
+doAssert(runeStrAtPos(s, 17) == "€")
+doAssert(runeSubStr(s, 17, 1) == "€")
+# echo runeStrAtPos(s, 18) # index error
+
+doAssert(runeSubStr(s, 0) == "Hänsel  ««: 10,00€")
+doAssert(runeSubStr(s, -18) == "Hänsel  ««: 10,00€")
+doAssert(runeSubStr(s, 10) == ": 10,00€")
+doAssert(runeSubStr(s, 18) == "")
+doAssert(runeSubStr(s, 0, 10) == "Hänsel  ««")
+
+doAssert(runeSubStr(s, 12) == "10,00€")
+doAssert(runeSubStr(s, -6) == "10,00€")
+
+doAssert(runeSubStr(s, 12, 5) == "10,00")
+doAssert(runeSubStr(s, 12, -1) == "10,00")
+doAssert(runeSubStr(s, -6, 5) == "10,00")
+doAssert(runeSubStr(s, -6, -1) == "10,00")
+
+doAssert(runeSubStr(s, 0, 100) == "Hänsel  ««: 10,00€")
+doAssert(runeSubStr(s, -100, 100) == "Hänsel  ««: 10,00€")
+doAssert(runeSubStr(s, 0, -100) == "")
+doAssert(runeSubStr(s, 100, -100) == "")
+
+block splitTests:
+  let s = " this is an example  "
+  let s2 = ":this;is;an:example;;"
+  let s3 = ":this×is×an:example××"
+  doAssert s.split() == @["", "this", "is", "an", "example", "", ""]
+  doAssert s2.split(seps = [':'.Rune, ';'.Rune]) == @["", "this", "is", "an",
+      "example", "", ""]
+  doAssert s3.split(seps = [':'.Rune, "×".asRune]) == @["", "this", "is",
+      "an", "example", "", ""]
+  doAssert s.split(maxsplit = 4) == @["", "this", "is", "an", "example  "]
+  doAssert s.split(' '.Rune, maxsplit = 1) == @["", "this is an example  "]
+  doAssert s3.split("×".runeAt(0)) == @[":this", "is", "an:example", "", ""]
+
+block stripTests:
+  doAssert(strip("") == "")
+  doAssert(strip(" ") == "")
+  doAssert(strip("y") == "y")
+  doAssert(strip("  foofoofoo  ") == "foofoofoo")
+  doAssert(strip("sfoofoofoos", runes = ['s'.Rune]) == "foofoofoo")
+
+  block:
+    let stripTestRunes = ['b'.Rune, 'a'.Rune, 'r'.Rune]
+    doAssert(strip("barfoofoofoobar", runes = stripTestRunes) == "foofoofoo")
+  doAssert(strip("sfoofoofoos", leading = false, runes = ['s'.Rune]) == "sfoofoofoo")
+  doAssert(strip("sfoofoofoos", trailing = false, runes = ['s'.Rune]) == "foofoofoos")
+
+  block:
+    let stripTestRunes = ["«".asRune, "»".asRune]
+    doAssert(strip("«TEXT»", runes = stripTestRunes) == "TEXT")
+  doAssert(strip("copyright©", leading = false, runes = ["©".asRune]) == "copyright")
+  doAssert(strip("¿Question?", trailing = false, runes = ["¿".asRune]) == "Question?")
+  doAssert(strip("×text×", leading = false, runes = ["×".asRune]) == "×text")
+  doAssert(strip("×text×", trailing = false, runes = ["×".asRune]) == "text×")
+
+block repeatTests:
+  doAssert repeat('c'.Rune, 5) == "ccccc"
+  doAssert repeat("×".asRune, 5) == "×××××"
+
+block alignTests:
+  doAssert align("abc", 4) == " abc"
+  doAssert align("a", 0) == "a"
+  doAssert align("1232", 6) == "  1232"
+  doAssert align("1232", 6, '#'.Rune) == "##1232"
+  doAssert align("1232", 6, "×".asRune) == "××1232"
+  doAssert alignLeft("abc", 4) == "abc "
+  doAssert alignLeft("a", 0) == "a"
+  doAssert alignLeft("1232", 6) == "1232  "
+  doAssert alignLeft("1232", 6, '#'.Rune) == "1232##"
+  doAssert alignLeft("1232", 6, "×".asRune) == "1232××"
+
+block differentSizes:
+  # upper and lower variants have different number of bytes
+  doAssert toLower("AẞC") == "aßc"
+  doAssert toLower("ȺẞCD") == "ⱥßcd"
+  doAssert toUpper("ⱥbc") == "ȺBC"
+  doAssert toUpper("rsⱦuv") == "RSȾUV"
+  doAssert swapCase("ⱥbCd") == "ȺBcD"
+  doAssert swapCase("XyꟆaB") == "xYᶎAb"
+  doAssert swapCase("aᵹcᲈd") == "AꝽCꙊD"
+
+block: # bug #17768
+  let s1 = "abcdef"
+  let s2 = "abcdéf"
+
+  doAssert s1.runeSubStr(0, -1) == "abcde"
+  doAssert s2.runeSubStr(0, -1) == "abcdé"
diff --git a/tests/stdlib/tunidecode.nim b/tests/stdlib/tunidecode.nim
index 689453c76..653016ea9 100644
--- a/tests/stdlib/tunidecode.nim
+++ b/tests/stdlib/tunidecode.nim
@@ -1,12 +1,13 @@
 discard """
   cmd: "nim $target --hints:on -d:embedUnidecodeTable $options $file"
-  output: "Ausserst"
 """
 
 import unidecode
 
-loadUnidecodeTable("lib/pure/unidecode/unidecode.dat")
+import std/unidecode # #14112
+import std/assertions
 
-#assert unidecode("\x53\x17\x4E\xB0") == "Bei Jing"
-echo unidecode("Äußerst")
+loadUnidecodeTable("lib/pure/unidecode/unidecode.dat")
 
+doAssert unidecode("北京") == "Bei Jing "
+doAssert unidecode("Äußerst") == "Ausserst"
diff --git a/tests/stdlib/tunittest.nim b/tests/stdlib/tunittest.nim
index 65baefef0..0442c7863 100644
--- a/tests/stdlib/tunittest.nim
+++ b/tests/stdlib/tunittest.nim
@@ -1,5 +1,7 @@
 discard """
-  output: '''[Suite] suite with only teardown
+  output: '''
+
+[Suite] suite with only teardown
 
 [Suite] suite with only setup
 
@@ -16,11 +18,13 @@ discard """
 [Suite] test suite
 
 [Suite] test name filtering
-
 '''
+matrix: "--mm:refc; --mm:orc"
+targets: "c js"
 """
 
-import unittest, sequtils
+import std/[unittest, sequtils, assertions]
+from std/unittest {.all.} import matchFilter
 
 proc doThings(spuds: var int): int =
   spuds = 24
@@ -31,12 +35,12 @@ test "#964":
   check spuds == 24
 
 
-from strutils import toUpperAscii
+from std/strutils import toUpperAscii
 test "#1384":
   check(@["hello", "world"].map(toUpperAscii) == @["HELLO", "WORLD"])
 
 
-import options
+import std/options
 test "unittest typedescs":
   check(none(int) == none(int))
   check(none(int) != some(1))
@@ -47,16 +51,16 @@ test "unittest multiple requires":
   require(true)
 
 
-import math, random
-from strutils import parseInt
+import std/random
+from std/strutils import parseInt
 proc defectiveRobot() =
-  case random(1..4)
+  case rand(1..4)
   of 1: raise newException(OSError, "CANNOT COMPUTE!")
   of 2: discard parseInt("Hello World!")
   of 3: raise newException(IOError, "I can't do that Dave.")
-  else: assert 2 + 2 == 5
+  else: doAssert 2 + 2 == 5
 test "unittest expect":
-  expect IOError, OSError, ValueError, AssertionError:
+  expect IOError, OSError, ValueError, AssertionDefect:
     defectiveRobot()
 
 var
@@ -141,38 +145,50 @@ suite "test suite":
 
         check(a == b)
 
-when defined(testing):
-  suite "test name filtering":
-    test "test name":
-      check matchFilter("suite1", "foo", "")
-      check matchFilter("suite1", "foo", "foo")
-      check matchFilter("suite1", "foo", "::")
-      check matchFilter("suite1", "foo", "*")
-      check matchFilter("suite1", "foo", "::foo")
-      check matchFilter("suite1", "::foo", "::foo")
-
-    test "test name - glob":
-      check matchFilter("suite1", "foo", "f*")
-      check matchFilter("suite1", "foo", "*oo")
-      check matchFilter("suite1", "12345", "12*345")
-      check matchFilter("suite1", "q*wefoo", "q*wefoo")
-      check false == matchFilter("suite1", "foo", "::x")
-      check false == matchFilter("suite1", "foo", "::x*")
-      check false == matchFilter("suite1", "foo", "::*x")
-      #  overlap
-      check false == matchFilter("suite1", "12345", "123*345")
-      check matchFilter("suite1", "ab*c::d*e::f", "ab*c::d*e::f")
-
-    test "suite name":
-      check matchFilter("suite1", "foo", "suite1::")
-      check false == matchFilter("suite1", "foo", "suite2::")
-      check matchFilter("suite1", "qwe::foo", "qwe::foo")
-      check matchFilter("suite1", "qwe::foo", "suite1::qwe::foo")
-
-    test "suite name - glob":
-      check matchFilter("suite1", "foo", "::*")
-      check matchFilter("suite1", "foo", "*::*")
-      check matchFilter("suite1", "foo", "*::foo")
-      check false == matchFilter("suite1", "foo", "*ite2::")
-      check matchFilter("suite1", "q**we::foo", "q**we::foo")
-      check matchFilter("suite1", "a::b*c::d*e", "a::b*c::d*e")
+suite "test name filtering":
+  test "test name":
+    check matchFilter("suite1", "foo", "")
+    check matchFilter("suite1", "foo", "foo")
+    check matchFilter("suite1", "foo", "::")
+    check matchFilter("suite1", "foo", "*")
+    check matchFilter("suite1", "foo", "::foo")
+    check matchFilter("suite1", "::foo", "::foo")
+
+  test "test name - glob":
+    check matchFilter("suite1", "foo", "f*")
+    check matchFilter("suite1", "foo", "*oo")
+    check matchFilter("suite1", "12345", "12*345")
+    check matchFilter("suite1", "q*wefoo", "q*wefoo")
+    check false == matchFilter("suite1", "foo", "::x")
+    check false == matchFilter("suite1", "foo", "::x*")
+    check false == matchFilter("suite1", "foo", "::*x")
+    #  overlap
+    check false == matchFilter("suite1", "12345", "123*345")
+    check matchFilter("suite1", "ab*c::d*e::f", "ab*c::d*e::f")
+
+  test "suite name":
+    check matchFilter("suite1", "foo", "suite1::")
+    check false == matchFilter("suite1", "foo", "suite2::")
+    check matchFilter("suite1", "qwe::foo", "qwe::foo")
+    check matchFilter("suite1", "qwe::foo", "suite1::qwe::foo")
+
+  test "suite name - glob":
+    check matchFilter("suite1", "foo", "::*")
+    check matchFilter("suite1", "foo", "*::*")
+    check matchFilter("suite1", "foo", "*::foo")
+    check false == matchFilter("suite1", "foo", "*ite2::")
+    check matchFilter("suite1", "q**we::foo", "q**we::foo")
+    check matchFilter("suite1", "a::b*c::d*e", "a::b*c::d*e")
+
+
+block:
+  type MyFoo = object
+  var obj = MyFoo()
+  let check = 1
+  check(obj == obj)
+
+block:
+  let check = 123
+  var a = 1
+  var b = 1
+  check(a == b)
diff --git a/tests/stdlib/tunittest_error.nim b/tests/stdlib/tunittest_error.nim
new file mode 100644
index 000000000..7f05ec2a9
--- /dev/null
+++ b/tests/stdlib/tunittest_error.nim
@@ -0,0 +1,22 @@
+discard """
+  exitcode: 1
+  outputsub: "failed: 1 == 3"
+  matrix: "-d:case1; -d:case2"
+  targets: "c js"
+  joinable: false
+"""
+
+when defined case1:
+  import unittest
+  suite "Test":
+    test "test require":
+      check 1==2
+      check 1==3
+
+when defined case2:
+  import unittest
+  suite "Test":
+    test "test require":
+      require 1 == 3
+      if true:
+        quit 0 # intentional
diff --git a/tests/stdlib/tunittestpass.nim b/tests/stdlib/tunittestpass.nim
new file mode 100644
index 000000000..d8de277b7
--- /dev/null
+++ b/tests/stdlib/tunittestpass.nim
@@ -0,0 +1,20 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c js"
+"""
+
+
+import unittest
+
+block:
+  check (type(1.0)) is float
+  check type(1.0) is float
+  check (typeof(1)) isnot float
+  check typeof(1) isnot float
+
+  check 1.0 is float
+  check 1 isnot float
+
+  type T = type(0.1)
+  check T is float
+  check T isnot int
diff --git a/tests/stdlib/tunittesttemplate.nim b/tests/stdlib/tunittesttemplate.nim
new file mode 100644
index 000000000..c29e0de01
--- /dev/null
+++ b/tests/stdlib/tunittesttemplate.nim
@@ -0,0 +1,25 @@
+discard """
+  exitcode: 1
+  outputsub: '''
+    tunittesttemplate.nim(20, 12): Check failed: a.b == 2
+    a.b was 0
+  [FAILED] 1
+'''
+"""
+
+
+
+# bug #6736
+import std/unittest
+
+type
+  A = object
+    b: int
+
+template t: untyped =
+  check(a.b == 2)
+
+suite "1":
+  test "1":
+    var a = A(b: 0)
+    t()
diff --git a/tests/stdlib/tunixsocket.nim b/tests/stdlib/tunixsocket.nim
new file mode 100644
index 000000000..636fd08c6
--- /dev/null
+++ b/tests/stdlib/tunixsocket.nim
@@ -0,0 +1,35 @@
+import std/[assertions, net, os, osproc]
+
+# XXX: Make this test run on Windows too when we add support for Unix sockets on Windows
+when defined(posix) and not defined(nimNetLite):
+  const nim = getCurrentCompilerExe()
+  let
+    dir = currentSourcePath().parentDir()
+    serverPath = dir / "unixsockettest"
+
+  let (_, err) = execCmdEx(nim & " c " & quoteShell(dir / "unixsockettest.nim"))
+  doAssert err == 0
+
+  let svproc = startProcess(serverPath, workingDir = dir)
+  doAssert svproc.running()
+  # Wait for the server to open the socket and listen from it
+  sleep(400)
+
+  block unixSocketSendRecv:
+    let
+      unixSocketPath = dir / "usox"
+      socket = newSocket(AF_UNIX, SOCK_STREAM, IPPROTO_NONE)
+
+    socket.connectUnix(unixSocketPath)
+    # for a blocking Unix socket this should never fail
+    socket.send("data sent through the socket\c\l", maxRetries = 0)
+    var resp: string
+    socket.readLine(resp)
+    doAssert resp == "Hello from server"
+
+    socket.send("bye\c\l")
+    socket.readLine(resp)
+    doAssert resp == "bye"
+    socket.close()
+
+  svproc.close()
diff --git a/tests/stdlib/turi.nim b/tests/stdlib/turi.nim
new file mode 100644
index 000000000..9c717c5b1
--- /dev/null
+++ b/tests/stdlib/turi.nim
@@ -0,0 +1,323 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets:  "c js"
+"""
+
+import std/uri
+from std/uri {.all.} as uri2 import removeDotSegments
+from std/sequtils import toSeq
+import std/assertions
+
+template main() =
+  block: # encodeUrl, decodeUrl
+    const test1 = "abc\L+def xyz"
+    doAssert encodeUrl(test1) == "abc%0A%2Bdef+xyz"
+    doAssert decodeUrl(encodeUrl(test1)) == test1
+    doAssert encodeUrl(test1, false) == "abc%0A%2Bdef%20xyz"
+    doAssert decodeUrl(encodeUrl(test1, false), false) == test1
+    doAssert decodeUrl(encodeUrl(test1)) == test1
+
+  block: # removeDotSegments
+    doAssert removeDotSegments("/foo/bar/baz") == "/foo/bar/baz"
+    doAssert removeDotSegments("") == "" # empty test
+    doAssert removeDotSegments(".") == "." # trailing period
+    doAssert removeDotSegments("a1/a2/../a3/a4/a5/./a6/a7/././") == "a1/a3/a4/a5/a6/a7/"
+    doAssert removeDotSegments("https://a1/a2/../a3/a4/a5/./a6/a7/././") == "https://a1/a3/a4/a5/a6/a7/"
+    doAssert removeDotSegments("http://a1/a2") == "http://a1/a2"
+    doAssert removeDotSegments("http://www.ai.") == "http://www.ai."
+    when false: # xxx these cases are buggy
+      # this should work, refs https://webmasters.stackexchange.com/questions/73934/how-can-urls-have-a-dot-at-the-end-e-g-www-bla-de
+      doAssert removeDotSegments("http://www.ai./") == "http://www.ai./" # fails
+      echo removeDotSegments("http://www.ai./")  # http://www.ai/
+      echo removeDotSegments("a/b.../c") # b.c
+      echo removeDotSegments("a/b../c") # bc
+      echo removeDotSegments("a/.../c") # .c
+      echo removeDotSegments("a//../b") # a/b
+      echo removeDotSegments("a/b/c//") # a/b/c//
+
+  block: # parseUri
+    block:
+      let org = "udp://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:8080"
+      let url = parseUri(org)
+      doAssert url.hostname == "2001:0db8:85a3:0000:0000:8a2e:0370:7334" # true
+      let newUrl = parseUri($url)
+      doAssert newUrl.hostname == "2001:0db8:85a3:0000:0000:8a2e:0370:7334" # true
+
+    block:
+      let str = "http://localhost"
+      let test = parseUri(str)
+      doAssert test.path == ""
+
+    block:
+      let str = "http://localhost/"
+      let test = parseUri(str)
+      doAssert test.path == "/"
+
+    block:
+      let str = "http://localhost:8080/test"
+      let test = parseUri(str)
+      doAssert test.scheme == "http"
+      doAssert test.port == "8080"
+      doAssert test.path == "/test"
+      doAssert test.hostname == "localhost"
+      doAssert($test == str)
+
+    block:
+      let str = "foo://username:password@example.com:8042/over/there" &
+                "/index.dtb?type=animal&name=narwhal#nose"
+      let test = parseUri(str)
+      doAssert test.scheme == "foo"
+      doAssert test.username == "username"
+      doAssert test.password == "password"
+      doAssert test.hostname == "example.com"
+      doAssert test.port == "8042"
+      doAssert test.path == "/over/there/index.dtb"
+      doAssert test.query == "type=animal&name=narwhal"
+      doAssert test.anchor == "nose"
+      doAssert($test == str)
+
+    block:
+      # IPv6 address
+      let str = "foo://[::1]:1234/bar?baz=true&qux#quux"
+      let uri = parseUri(str)
+      doAssert uri.scheme == "foo"
+      doAssert uri.hostname == "::1"
+      doAssert uri.port == "1234"
+      doAssert uri.path == "/bar"
+      doAssert uri.query == "baz=true&qux"
+      doAssert uri.anchor == "quux"
+
+    block:
+      let str = "urn:example:animal:ferret:nose"
+      let test = parseUri(str)
+      doAssert test.scheme == "urn"
+      doAssert test.path == "example:animal:ferret:nose"
+      doAssert($test == str)
+
+    block:
+      let str = "mailto:username@example.com?subject=Topic"
+      let test = parseUri(str)
+      doAssert test.scheme == "mailto"
+      doAssert test.username == "username"
+      doAssert test.hostname == "example.com"
+      doAssert test.query == "subject=Topic"
+      doAssert($test == str)
+
+    block:
+      let str = "magnet:?xt=urn:sha1:72hsga62ba515sbd62&dn=foobar"
+      let test = parseUri(str)
+      doAssert test.scheme == "magnet"
+      doAssert test.query == "xt=urn:sha1:72hsga62ba515sbd62&dn=foobar"
+      doAssert($test == str)
+
+    block:
+      let str = "/test/foo/bar?q=2#asdf"
+      let test = parseUri(str)
+      doAssert test.scheme == ""
+      doAssert test.path == "/test/foo/bar"
+      doAssert test.query == "q=2"
+      doAssert test.anchor == "asdf"
+      doAssert($test == str)
+
+    block:
+      let str = "test/no/slash"
+      let test = parseUri(str)
+      doAssert test.path == "test/no/slash"
+      doAssert($test == str)
+
+    block:
+      let str = "//git@github.com:dom96/packages"
+      let test = parseUri(str)
+      doAssert test.scheme == ""
+      doAssert test.username == "git"
+      doAssert test.hostname == "github.com"
+      doAssert test.port == "dom96"
+      doAssert test.path == "/packages"
+
+    block:
+      let str = "file:///foo/bar/baz.txt"
+      let test = parseUri(str)
+      doAssert test.scheme == "file"
+      doAssert test.username == ""
+      doAssert test.hostname == ""
+      doAssert test.port == ""
+      doAssert test.path == "/foo/bar/baz.txt"
+
+  block: # combine
+    block:
+      let concat = combine(parseUri("http://google.com/foo/bar/"), parseUri("baz"))
+      doAssert concat.path == "/foo/bar/baz"
+      doAssert concat.hostname == "google.com"
+      doAssert concat.scheme == "http"
+
+    block:
+      let concat = combine(parseUri("http://google.com/foo"), parseUri("/baz"))
+      doAssert concat.path == "/baz"
+      doAssert concat.hostname == "google.com"
+      doAssert concat.scheme == "http"
+
+    block:
+      let concat = combine(parseUri("http://google.com/foo/test"), parseUri("bar"))
+      doAssert concat.path == "/foo/bar"
+
+    block:
+      let concat = combine(parseUri("http://google.com/foo/test"), parseUri("/bar"))
+      doAssert concat.path == "/bar"
+
+    block:
+      let concat = combine(parseUri("http://google.com/foo/test"), parseUri("bar"))
+      doAssert concat.path == "/foo/bar"
+
+    block:
+      let concat = combine(parseUri("http://google.com/foo/test/"), parseUri("bar"))
+      doAssert concat.path == "/foo/test/bar"
+
+    block:
+      let concat = combine(parseUri("http://google.com/foo/test/"), parseUri("bar/"))
+      doAssert concat.path == "/foo/test/bar/"
+
+    block:
+      let concat = combine(parseUri("http://google.com/foo/test/"), parseUri("bar/"),
+                           parseUri("baz"))
+      doAssert concat.path == "/foo/test/bar/baz"
+
+  block: # `/`
+    block:
+      let test = parseUri("http://example.com/foo") / "bar/asd"
+      doAssert test.path == "/foo/bar/asd"
+
+    block:
+      let test = parseUri("http://example.com/foo/") / "/bar/asd"
+      doAssert test.path == "/foo/bar/asd"
+
+  block: # bug #3207
+    doAssert parseUri("http://qq/1").combine(parseUri("https://qqq")).`$` == "https://qqq"
+
+  block: # bug #4959
+    let foo = parseUri("http://example.com") / "/baz"
+    doAssert foo.path == "/baz"
+
+  block: # bug found on stream 13/10/17
+    let foo = parseUri("http://localhost:9515") / "status"
+    doAssert $foo == "http://localhost:9515/status"
+
+  block: # bug #6649 #6652
+    var foo = parseUri("http://example.com")
+    foo.hostname = "example.com"
+    foo.path = "baz"
+    doAssert $foo == "http://example.com/baz"
+
+    foo.hostname = "example.com/"
+    foo.path = "baz"
+    doAssert $foo == "http://example.com/baz"
+
+    foo.hostname = "example.com"
+    foo.path = "/baz"
+    doAssert $foo == "http://example.com/baz"
+
+    foo.hostname = "example.com/"
+    foo.path = "/baz"
+    doAssert $foo == "http://example.com/baz"
+
+    foo.hostname = "example.com/"
+    foo.port = "8000"
+    foo.path = "baz"
+    doAssert $foo == "http://example.com:8000/baz"
+
+    foo = parseUri("file:/dir/file")
+    foo.path = "relative"
+    doAssert $foo == "file:relative"
+
+  block: # isAbsolute tests
+    doAssert "www.google.com".parseUri().isAbsolute() == false
+    doAssert "http://www.google.com".parseUri().isAbsolute() == true
+    doAssert "file:/dir/file".parseUri().isAbsolute() == true
+    doAssert "file://localhost/dir/file".parseUri().isAbsolute() == true
+    doAssert "urn:ISSN:1535-3613".parseUri().isAbsolute() == true
+
+    # path-relative URL *relative
+    doAssert "about".parseUri().isAbsolute == false
+    doAssert "about/staff.html".parseUri().isAbsolute == false
+    doAssert "about/staff.html?".parseUri().isAbsolute == false
+    doAssert "about/staff.html?parameters".parseUri().isAbsolute == false
+
+    # absolute-path-relative URL *relative
+    doAssert "/".parseUri().isAbsolute == false
+    doAssert "/about".parseUri().isAbsolute == false
+    doAssert "/about/staff.html".parseUri().isAbsolute == false
+    doAssert "/about/staff.html?".parseUri().isAbsolute == false
+    doAssert "/about/staff.html?parameters".parseUri().isAbsolute == false
+
+    # scheme-relative URL *relative
+    doAssert "//username:password@example.com:8888".parseUri().isAbsolute == false
+    doAssert "//username@example.com".parseUri().isAbsolute == false
+    doAssert "//example.com".parseUri().isAbsolute == false
+    doAssert "//example.com/".parseUri().isAbsolute == false
+    doAssert "//example.com/about".parseUri().isAbsolute == false
+    doAssert "//example.com/about/staff.html".parseUri().isAbsolute == false
+    doAssert "//example.com/about/staff.html?".parseUri().isAbsolute == false
+    doAssert "//example.com/about/staff.html?parameters".parseUri().isAbsolute == false
+
+    # absolute URL *absolute
+    doAssert "https://username:password@example.com:8888".parseUri().isAbsolute == true
+    doAssert "https://username@example.com".parseUri().isAbsolute == true
+    doAssert "https://example.com".parseUri().isAbsolute == true
+    doAssert "https://example.com/".parseUri().isAbsolute == true
+    doAssert "https://example.com/about".parseUri().isAbsolute == true
+    doAssert "https://example.com/about/staff.html".parseUri().isAbsolute == true
+    doAssert "https://example.com/about/staff.html?".parseUri().isAbsolute == true
+    doAssert "https://example.com/about/staff.html?parameters".parseUri().isAbsolute == true
+
+  block: # encodeQuery tests
+    doAssert encodeQuery({:}) == ""
+    doAssert encodeQuery({"foo": "bar"}) == "foo=bar"
+    doAssert encodeQuery({"foo": "bar & baz"}) == "foo=bar+%26+baz"
+    doAssert encodeQuery({"foo": "bar & baz"}, usePlus = false) == "foo=bar%20%26%20baz"
+    doAssert encodeQuery({"foo": ""}) == "foo"
+    doAssert encodeQuery({"foo": ""}, omitEq = false) == "foo="
+    doAssert encodeQuery({"a": "1", "b": "", "c": "3"}) == "a=1&b&c=3"
+    doAssert encodeQuery({"a": "1", "b": "", "c": "3"}, sep = ';') == "a=1;b;c=3"
+    doAssert encodeQuery({"a": "1", "b": "", "c": "3"}, omitEq = false) == "a=1&b=&c=3"
+    doAssert encodeQuery({"a": "1", "b": "", "c": "3"}, omitEq = false, sep = ';') == "a=1;b=;c=3"
+
+  block: # `?`
+    block:
+      var foo = parseUri("http://example.com") / "foo" ? {"bar": "1", "baz": "qux"}
+      var foo1 = parseUri("http://example.com/foo?bar=1&baz=qux")
+      doAssert foo == foo1
+    block:
+      var foo = parseUri("http://example.com") / "foo" ? {"do": "do", "bar": ""}
+      var foo1 = parseUri("http://example.com/foo?do=do&bar")
+      doAssert foo == foo1
+
+  block: # getDataUri, dataUriBase64
+    doAssert getDataUri("", "text/plain") == "data:text/plain;charset=utf-8;base64,"
+    doAssert getDataUri(" ", "text/plain") == "data:text/plain;charset=utf-8;base64,IA=="
+    doAssert getDataUri("c\xf7>", "text/plain") == "data:text/plain;charset=utf-8;base64,Y/c+"
+    doAssert getDataUri("Hello World", "text/plain") == "data:text/plain;charset=utf-8;base64,SGVsbG8gV29ybGQ="
+    doAssert getDataUri("leasure.", "text/plain") == "data:text/plain;charset=utf-8;base64,bGVhc3VyZS4="
+    doAssert getDataUri("""!@#$%^&*()_+""", "text/plain") == "data:text/plain;charset=utf-8;base64,IUAjJCVeJiooKV8r"
+    doAssert(getDataUri("the quick brown dog jumps over the lazy fox", "text/plain") ==
+      "data:text/plain;charset=utf-8;base64,dGhlIHF1aWNrIGJyb3duIGRvZyBqdW1wcyBvdmVyIHRoZSBsYXp5IGZveA==")
+    doAssert(getDataUri("The present is theirs\n      The future, for which I really worked, is mine.", "text/plain") ==
+      "data:text/plain;charset=utf-8;base64,VGhlIHByZXNlbnQgaXMgdGhlaXJzCiAgICAgIFRoZSBmdXR1cmUsIGZvciB3aGljaCBJIHJlYWxseSB3b3JrZWQsIGlzIG1pbmUu")
+
+  block: # decodeQuery
+    doAssert toSeq(decodeQuery("a=1&b=0")) == @[("a", "1"), ("b", "0")]
+    doAssert toSeq(decodeQuery("a=1;b=0", sep = ';')) == @[("a", "1"), ("b", "0")]
+    doAssert toSeq(decodeQuery("a=1&b=2c=6")) == @[("a", "1"), ("b", "2c=6")]
+    doAssert toSeq(decodeQuery("a=1;b=2c=6", sep = ';')) == @[("a", "1"), ("b", "2c=6")]
+
+  block: # bug #17481
+    let u1 = parseUri("./")
+    let u2 = parseUri("./path")
+    let u3 = parseUri("a/path")
+    doAssert u1.scheme.len == 0
+    doAssert u1.path == "./"
+    doAssert u2.scheme.len == 0
+    doAssert u2.path == "./path"
+    doAssert u3.scheme.len == 0
+    doAssert u3.path == "a/path"
+
+static: main()
+main()
diff --git a/tests/stdlib/tuserlocks.nim b/tests/stdlib/tuserlocks.nim
new file mode 100644
index 000000000..927077120
--- /dev/null
+++ b/tests/stdlib/tuserlocks.nim
@@ -0,0 +1,21 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/rlocks
+import std/assertions
+
+var r: RLock
+r.initRLock()
+doAssert r.tryAcquire()
+doAssert r.tryAcquire()
+r.release()
+r.release()
+
+block:
+  var x = 12
+  withRLock r:
+    inc x
+  doAssert x == 13
+
+r.deinitRLock()
diff --git a/tests/stdlib/tvarargs.nim b/tests/stdlib/tvarargs.nim
new file mode 100644
index 000000000..2edc26264
--- /dev/null
+++ b/tests/stdlib/tvarargs.nim
@@ -0,0 +1,18 @@
+discard """
+  targets: "c js"
+  matrix: "--mm:refc; --mm:orc"
+"""
+import std/assertions
+
+template main =
+  proc hello(x: varargs[string]): seq[string] =
+    var s: seq[string]
+    s.add x
+    s
+
+  doAssert hello() == @[]
+  doAssert hello("a1") == @["a1"]
+  doAssert hello("a1", "a2") == @["a1", "a2"]
+
+static: main()
+main()
diff --git a/tests/stdlib/tvarints.nim b/tests/stdlib/tvarints.nim
new file mode 100644
index 000000000..f9624ee5b
--- /dev/null
+++ b/tests/stdlib/tvarints.nim
@@ -0,0 +1,73 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/varints
+import std/assertions
+
+# xxx doesn't work with js: tvarints.nim(18, 14) `wrLen == rdLen`  [AssertionDefect]
+
+block:
+  var dest: array[50, byte]
+  var got: uint64
+
+  for test in [0xFFFF_FFFF_FFFFF_FFFFu64, 77u64, 0u64, 10_000_000u64, uint64(high(int64)),
+              uint64(high(int32)), uint64(high(int32)), uint64(high(int64))]:
+    let wrLen = writeVu64(dest, test)
+    let rdLen = readVu64(dest, got)
+    doAssert wrLen == rdLen
+    doAssert got == test
+
+  for test in 0u64..300u64:
+    let wrLen = writeVu64(dest, test)
+    let rdLen = readVu64(dest, got)
+    doAssert wrLen == rdLen
+    doAssert got == test
+
+  # check this also works for floats:
+  for test in [0.0, 0.1, 2.0, +Inf, NegInf]:
+    let t = cast[uint64](test)
+    let wrLenB = writeVu64(dest, t)
+    let rdLenB = readVu64(dest, got)
+    doAssert wrLenB == rdLenB
+    doAssert cast[float64](got) == test
+
+block:
+  var hugeIntArray: array[9, byte]
+  var readedInt: uint64
+
+  template chk(a) =
+    let b = cast[uint64](a)
+    doAssert writeVu64(hugeIntArray, b) == readVu64(hugeIntArray, readedInt)
+    doAssert readedInt == b
+
+  chk 0
+  chk uint64.high
+  chk int64.high
+  chk int32.high
+  chk int16.high
+  chk int16.high
+  chk int8.high
+  chk 0.0
+  chk -0.0
+  chk 0.1
+  chk Inf
+  chk NegInf
+  chk NaN
+  chk 3.1415926535897932384626433
+
+block:
+  template chk(a) =
+    let b = cast[uint64](a)
+    doAssert encodeZigzag(decodeZigzag(b)) == b
+  chk 0
+  chk uint32.high
+  chk int32.high
+  chk int16.high
+  chk int8.high
+  chk 0.0
+  chk 0.1
+  chk 0.9555555555555555555555501
+  chk Inf
+  chk 3.1415926535897932384626433
+  chk 2.71828182845904523536028747
diff --git a/tests/stdlib/tvmutils.nim b/tests/stdlib/tvmutils.nim
new file mode 100644
index 000000000..63804c136
--- /dev/null
+++ b/tests/stdlib/tvmutils.nim
@@ -0,0 +1,31 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  joinable: false
+  nimout: '''
+0
+1
+2
+tvmutils.nim(28, 13) [opcLdImmInt]     if i == 4:
+tvmutils.nim(28, 10) [opcEqInt]     if i == 4:
+tvmutils.nim(28, 10) [opcFJmp]     if i == 4:
+tvmutils.nim(28, 13) [opcLdImmInt]     if i == 4:
+tvmutils.nim(28, 10) [opcEqInt]     if i == 4:
+tvmutils.nim(28, 10) [opcFJmp]     if i == 4:
+tvmutils.nim(29, 7) [opcLdConst]       vmTrace(false)
+tvmutils.nim(29, 15) [opcLdImmInt]       vmTrace(false)
+tvmutils.nim(29, 14) [opcIndCall]       vmTrace(false)
+5
+6
+'''
+"""
+# line 20 (only showing a subset of nimout to avoid making the test rigid)
+import std/vmutils
+proc main() =
+  for i in 0..<7:
+    echo i
+    if i == 2:
+      vmTrace(true)
+    if i == 4:
+      vmTrace(false)
+
+static: main()
diff --git a/tests/stdlib/tvolatile.nim b/tests/stdlib/tvolatile.nim
new file mode 100644
index 000000000..c097f9723
--- /dev/null
+++ b/tests/stdlib/tvolatile.nim
@@ -0,0 +1,15 @@
+import std/[volatile, assertions]
+
+var st: int
+var foo: ptr int = addr st
+volatileStore(foo, 12)
+doAssert volatileLoad(foo) == 12
+
+# bug #14623
+proc bar =
+  var st: int
+  var foo: ptr int = addr st
+  volatileStore(foo, 12)
+  doAssert volatileLoad(foo) == 12
+
+bar()
diff --git a/tests/stdlib/twchartoutf8.nim b/tests/stdlib/twchartoutf8.nim
index a6602e3e3..e437177ac 100644
--- a/tests/stdlib/twchartoutf8.nim
+++ b/tests/stdlib/twchartoutf8.nim
@@ -1,13 +1,17 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: '''OK'''
 """
 
+import std/[syncio, assertions]
+
 #assume WideCharToMultiByte always produce correct result
 #windows only
 
 when not defined(windows):
   echo "OK"
 else:
+  import std/widestrs
   {.push gcsafe.}
 
   const CP_UTF8 = 65001'i32
@@ -66,8 +70,7 @@ else:
 
   #RFC-2781 "UTF-16, an encoding of ISO 10646"
 
-  var wc: WideCString
-  unsafeNew(wc, 1024 * 4 + 2)
+  var wc: WideCString = newWideCString(1024 * 2)
 
   #U+0000 to U+D7FF
   #skip the U+0000
diff --git a/tests/stdlib/twith.nim b/tests/stdlib/twith.nim
new file mode 100644
index 000000000..ceadbe7bf
--- /dev/null
+++ b/tests/stdlib/twith.nim
@@ -0,0 +1,44 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/with
+import std/[assertions, formatfloat]
+
+type
+  Foo = object
+    col, pos: string
+    name: string
+
+proc setColor(f: var Foo; r, g, b: int) = f.col = $(r, g, b)
+proc setPosition(f: var Foo; x, y: float) = f.pos = $(x, y)
+
+var f: Foo
+with(f, setColor(2, 3, 4), setPosition(0.0, 1.0))
+doAssert f.col == "(2, 3, 4)"
+doAssert f.pos == "(0.0, 1.0)"
+
+f = Foo()
+with f:
+  col = $(2, 3, 4)
+  pos = $(0.0, 1.0)
+  _.name = "bar"
+doAssert f.col == "(2, 3, 4)"
+doAssert f.pos == "(0.0, 1.0)"
+doAssert f.name == "bar"
+
+type
+  Baz* = object
+    a*, b*: int
+  Bar* = object
+    x*: int
+    baz*: Baz
+
+var bar: Bar
+with bar:
+  x = 1
+  with baz:
+    a = 2
+
+doAssert bar.x == 1
+doAssert bar.baz.a == 2
diff --git a/tests/stdlib/twordwrap.nim b/tests/stdlib/twordwrap.nim
new file mode 100644
index 000000000..5d49477d3
--- /dev/null
+++ b/tests/stdlib/twordwrap.nim
@@ -0,0 +1,48 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/wordwrap
+import std/assertions
+
+when true:
+  let
+    inp = """ this is a long text --  muchlongerthan10chars and here
+                it goes"""
+    outp = " this is a\nlong text\n--\nmuchlongerthan10chars\nand here\nit goes"
+  doAssert wrapWords(inp, 10, false) == outp
+
+  let
+    longInp = """ThisIsOneVeryLongStringWhichWeWillSplitIntoEightSeparatePartsNow"""
+    longOutp = "ThisIsOn\neVeryLon\ngStringW\nhichWeWi\nllSplitI\nntoEight\nSeparate\nPartsNow"
+  doAssert wrapWords(longInp, 8, true) == longOutp
+
+# test we don't break Umlauts into invalid bytes:
+let fies = "äöüöäöüöäöüöäöüööäöüöäößßßßüöäößßßßßß"
+let fiesRes = "ä\nö\nü\nö\nä\nö\nü\nö\nä\nö\nü\nö\nä\nö\nü\nö\nö\nä\nö\nü\nö\nä\nö\nß\nß\nß\nß\nü\nö\nä\nö\nß\nß\nß\nß\nß\nß"
+doAssert wrapWords(fies, 1, true) == fiesRes
+
+let longlongword = """abc uitdaeröägfßhydüäpydqfü,träpydqgpmüdträpydföägpydörztdüöäfguiaeowäzjdtrüöäp psnrtuiydrözenrüöäpyfdqazpesnrtulocjtüö
+äzydgyqgfqfgprtnwjlcydkqgfüöezmäzydydqüüöäpdtrnvwfhgckdumböäpydfgtdgfhtdrntdrntydfogiayqfguiatrnydrntüöärtniaoeydfgaoeiqfglwcßqfgxvlcwgtfhiaoen
+rsüöäapmböäptdrniaoydfglckqfhouenrtsüöäptrniaoeyqfgulocfqclgwxßqflgcwßqfxglcwrniatrnmüböäpmöäbpümöäbpüöämpbaoestnriaesnrtdiaesrtdniaesdrtnaetdr
+iaoenvlcyfglwckßqfgvwkßqgfvlwkßqfgvlwckßqvlwkgfUIαοιαοιαχολωχσωχνωκψρχκψρτιεαοσηζϵηζιοεννκεωνιαλωσωκνκψρκγτφγτχκγτεκργτιχνκιωχσιλωσλωχξλξλξωχωχ
+ξχλωωχαοεοιαεοαεοιαεοαεοιαοεσναοεκνρκψγκψφϵιηαααοε"""
+let longlongwordRes = """
+abc uitdaeröägfßhydüäpydqfü,träpydqgpmüdträpydföägpydörztdüöäfguiaeowäzjdtrüöäp
+psnrtuiydrözenrüöäpyfdqazpesnrtulocjtüöäzydgyqgfqfgprtnwjlcydkqgfüöezmäzydydqüü
+öäpdtrnvwfhgckdumböäpydfgtdgfhtdrntdrntydfogiayqfguiatrnydrntüöärtniaoeydfgaoeiq
+fglwcßqfgxvlcwgtfhiaoenrsüöäapmböäptdrniaoydfglckqfhouenrtsüöäptrniaoeyqfgulocf
+qclgwxßqflgcwßqfxglcwrniatrnmüböäpmöäbpümöäbpüöämpbaoestnriaesnrtdiaesrtdniaesdr
+tnaetdriaoenvlcyfglwckßqfgvwkßqgfvlwkßqfgvlwckßqvlwkgfUIαοιαοιαχολωχσωχνωκψρχκψ
+ρτιεαοσηζϵηζιοεννκεωνιαλωσωκνκψρκγτφγτχκγτεκργτιχνκιωχσιλωσλωχξλξλξωχωχ
+ξχλωωχαοεοιαεοαεοιαεοαεοιαοεσναοεκνρκψγκψφϵιηαααοε"""
+doAssert wrapWords(longlongword) == longlongwordRes
+
+# bug #14579
+const input60 = """
+This string is wrapped to 60 characters. If we call
+wrapwords on it it will be re-wrapped to 80 characters.
+"""
+const input60Res = """This string is wrapped to 60 characters. If we call wrapwords on it it will be
+re-wrapped to 80 characters."""
+doAssert wrapWords(input60) == input60Res
\ No newline at end of file
diff --git a/tests/stdlib/twrapnils.nim b/tests/stdlib/twrapnils.nim
index b20c67479..3da230b5e 100644
--- a/tests/stdlib/twrapnils.nim
+++ b/tests/stdlib/twrapnils.nim
@@ -1,82 +1,224 @@
-import std/wrapnils
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
 
-const wrapnilExtendedExports = declared(wrapnil)
-  # for now, wrapnil, isValid, unwrap are not exported
+import std/wrapnils
+from std/options import get, isSome
+import std/assertions
 
 proc checkNotZero(x: float): float =
   doAssert x != 0
   x
 
-var witness = 0
-
 proc main() =
-  type Bar = object
-    b1: int
-    b2: ptr string
-
-  type Foo = ref object
-    x1: float
-    x2: Foo
-    x3: string
-    x4: Bar
-    x5: seq[int]
-    x6: ptr Bar
-    x7: array[2, string]
-    x8: seq[int]
-    x9: ref Bar
-
-  type Gook = ref object
-    foo: Foo
-
-  proc fun(a: Bar): auto = a.b2
-
-  var a: Foo
-  var x6 = create(Bar)
-  x6.b1 = 42
-  var a2 = Foo(x1: 1.0, x5: @[10, 11], x6: x6)
-  var a3 = Foo(x1: 1.2, x3: "abc")
-  a3.x2 = a3
-
-  var gook = Gook(foo: a)
-
-  proc initFoo(x1: float): auto =
-    witness.inc
-    result = Foo(x1: x1)
-
-  doAssert ?.a.x2.x2.x1 == 0.0
-  doAssert ?.a3.x2.x2.x1 == 1.2
-  doAssert ?.a3.x2.x2.x3[1] == 'b'
-
-  doAssert ?.a3.x2.x2.x5.len == 0
-  doAssert a3.x2.x2.x3.len == 3
-
-  when wrapnilExtendedExports:
-    # example calling wrapnil directly, with and without unwrap
-    doAssert a3.wrapnil.x2.x2.x3.len == wrapnil(3)
-    doAssert a3.wrapnil.x2.x2.x3.len.unwrap == 3
-    doAssert a2.wrapnil.x4.isValid
-    doAssert not a.wrapnil.x4.isValid
-
-  doAssert ?.a.x2.x2.x3[1] == default(char)
-  # here we only apply wrapnil around gook.foo, not gook (and assume gook is not nil)
-  doAssert ?.(gook.foo).x2.x2.x1 == 0.0
-
-  doAssert ?.a2.x6[] == Bar(b1: 42) # deref for ptr Bar
-
-  doAssert ?.a2.x1.checkNotZero == 1.0
-  doAssert a == nil
-  # shows that checkNotZero won't be called if a nil is found earlier in chain
-  doAssert ?.a.x1.checkNotZero == 0.0
-
-  # checks that a chain without nil but with an empty seq still throws IndexError
-  doAssertRaises(IndexError): discard ?.a2.x8[3]
-
-  # make sure no double evaluation bug
-  doAssert witness == 0
-  doAssert ?.initFoo(1.3).x1 == 1.3
-  doAssert witness == 1
-
-  # here, it's used twice, to deref `ref Bar` and then `ptr string`
-  doAssert ?.a.x9[].fun[] == ""
+  var witness = 0
+  block:
+    type Bar = object
+      b1: int
+      b2: ptr string
+
+    type Foo = ref object
+      x1: float
+      x2: Foo
+      x3: string
+      x4: Bar
+      x5: seq[int]
+      x6: ptr Bar
+      x7: array[2, string]
+      x8: seq[int]
+      x9: ref Bar
+
+    type Goo = ref object
+      foo: Foo
+
+    proc fun(a: Bar): auto = a.b2
+
+    var a: Foo
+
+    var x6: ptr Bar
+    when nimvm: discard # pending https://github.com/timotheecour/Nim/issues/568
+    else:
+      x6 = create(Bar)
+      x6.b1 = 42
+    var a2 = Foo(x1: 1.0, x5: @[10, 11], x6: x6)
+    var a3 = Foo(x1: 1.2, x3: "abc")
+    a3.x2 = a3
+
+    var goo = Goo(foo: a)
+
+    proc initFoo(x1: float): auto =
+      witness.inc
+      result = Foo(x1: x1)
+
+    doAssert ?.a.x2.x2.x1 == 0.0
+    doAssert ?.a3.x2.x2.x1 == 1.2
+    doAssert ?.a3.x2.x2.x3[1] == 'b'
+
+    doAssert ?.a3.x2.x2.x5.len == 0
+    doAssert a3.x2.x2.x3.len == 3
+
+    doAssert ?.a.x2.x2.x3[1] == default(char)
+    # here we only apply wrapnil around goo.foo, not goo (and assume goo is not nil)
+    doAssert ?.(goo.foo).x2.x2.x1 == 0.0
+
+    when nimvm: discard
+    else:
+      doAssert ?.a2.x6[] == Bar(b1: 42) # deref for ptr Bar
+
+    doAssert ?.a2.x1.checkNotZero == 1.0
+    doAssert a == nil
+    # shows that checkNotZero won't be called if a nil is found earlier in chain
+    doAssert ?.a.x1.checkNotZero == 0.0
+
+    when nimvm: discard
+    else:
+      # checks that a chain without nil but with an empty seq still raises
+      doAssertRaises(IndexDefect): discard ?.a2.x8[3]
+
+    # make sure no double evaluation bug
+    doAssert witness == 0
+    doAssert ?.initFoo(1.3).x1 == 1.3
+    doAssert witness == 1
+
+    # here, it's used twice, to deref `ref Bar` and then `ptr string`
+    doAssert ?.a.x9[].fun[] == ""
+
+    block: # `??.`
+      doAssert (??.a3.x2.x2.x3.len).get == 3
+      doAssert (??.a2.x4).isSome
+      doAssert not (??.a.x4).isSome
+
+  block:
+    type
+      A = object
+        b: B
+      B = object
+        c: C
+      C = object
+        d: D
+      D = ref object
+        e: E
+        e2: array[2, E]
+        e3: seq[E]
+        d3: D
+        i4: int
+      E = object
+        f: int
+        d2: D
+    proc identity[T](a: T): T = a
+    proc identity2[T](a: T, ignore: int): T = a
+    var a: A
+    doAssert ?.a.b.c.d.e.f == 0
+    doAssert ?.a.b.c.d.e.d2.d3[].d3.e.d2.e.f == 0
+    doAssert ?.a.b.c.d.d3[].e.f == 0
+    doAssert ?.a.b.c.d.e2[0].d2.e3[0].f == 0
+    doAssert ?.a == A.default
+    doAssert ?.a.b.c.d.e == E.default
+    doAssert ?.a.b.c.d.e.d2 == nil
+
+    doAssert ?.a.identity.b.c.identity2(12).d.d3.e.f == 0
+    doAssert ?.a.b.c.d.d3.e2[0].f == 0
+    a.b.c.d = D()
+    a.b.c.d.d3 = a.b.c.d
+    a.b.c.d.e2[0].f = 5
+    doAssert ?.a.b.c.d.d3.e2[0].f == 5
+
+    var d: D = nil
+    doAssert ?.d.identity.i4 == 0
+    doAssert ?.d.i4.identity == 0
+
+  block: # case objects
+    type
+      Kind = enum k0, k1, k2
+      V = object
+        case kind: Kind
+        of k0:
+          x0: int
+        of k1:
+          x1: int
+        of k2:
+          x2: int
+      A = object
+        v0: V
+
+    block:
+      var a = V(kind: k0, x0: 3)
+      doAssert ?.a.x0 == 3
+      doAssert ?.a.x1 == 0
+      a = V(kind: k1, x1: 5)
+      doAssert ?.a.x0 == 0
+      doAssert ?.a.x1 == 5
+
+    block:
+      var a = A(v0: V(kind: k0, x0: 10))
+      doAssert ?.a.v0.x0 == 10
+      doAssert ?.a.v0.x1 == 0
+      a.v0 = V(kind: k2, x2: 8)
+      doAssert ?.a.v0.x0 == 0
+      doAssert ?.a.v0.x1 == 0
+      doAssert ?.a.v0.x2 == 8
+
+  block: # `nnkCall`
+    type
+      A = object
+        a0: int
+        d: D
+      D = ref object
+        i4: int
+
+    proc identity[T](a: T): T = a
+    var d: D = nil
+    doAssert ?.d.i4.identity == 0
+    doAssert ?.identity(?.d.i4) == 0
+    doAssert ?.identity(d.i4) == 0
+    doAssert ?.identity(d) == nil
+    doAssert ?.identity(d[]) == default(typeof(d[]))
+    doAssert ?.identity(d[]).i4 == 0
+    var a: A
+    doAssert ?.identity(a) == default(A)
+    doAssert ?.identity(a.a0) == 0
+    doAssert ?.identity(a.d) == nil
+    doAssert ?.identity(a.d.i4) == 0
+
+  block: # lvalue semantic propagation
+    type
+      A = ref object
+        a0: A
+        a1: seq[A]
+        a2: int
+
+      B = object
+        b0: int
+        case cond: bool
+        of false: discard
+        of true:
+          b1: float
+
+    block:
+      var a: A
+      doAssert ?.a.a0.a1[0].a2.addr == nil
+      a = A(a2: 3)
+      doAssert ?.a.a0.a1[0].a2.addr == nil
+      a.a0 = a
+      a.a1 = @[a]
+      let p = ?.a.a0.a1[0].a2.addr
+      doAssert p != nil
+      p[] = 5
+      doAssert a.a2 == 5
+
+    block:
+      var b = B(cond: false, b0: 3)
+      let p = ?.b.b1.addr
+      doAssert p == nil
+      b = B(cond: true, b1: 4.5)
+      let p2 = ?.b.b1.addr
+      doAssert p2 != nil
+      p2[] = 4.6
+      doAssert b.b1 == 4.6
+      # useful pattern, impossible with Options
+      if (let p3 = ?.b.b1.addr; p3 != nil):
+        p3[] = 4.7
+      doAssert b.b1 == 4.7
 
 main()
+static: main()
diff --git a/tests/stdlib/twrongstattype.nim b/tests/stdlib/twrongstattype.nim
new file mode 100644
index 000000000..4a1fc30c6
--- /dev/null
+++ b/tests/stdlib/twrongstattype.nim
@@ -0,0 +1,14 @@
+# issue #24076
+
+when defined(macosx) or defined(freebsd) or defined(openbsd) or defined(netbsd):
+  import std/posix
+  proc uid(x: uint32): Uid = Uid(x)
+  var y: uint32
+  let myUid = geteuid()
+  discard myUid == uid(y)
+  proc dev(x: uint32): Dev = Dev(x)
+  let myDev = 1.Dev
+  discard myDev == dev(y)
+  proc nlink(x: uint32): Nlink = Nlink(x)
+  let myNlink = 1.Nlink
+  discard myNlink == nlink(y)
diff --git a/tests/stdlib/txmltree.nim b/tests/stdlib/txmltree.nim
new file mode 100644
index 000000000..add12a3fc
--- /dev/null
+++ b/tests/stdlib/txmltree.nim
@@ -0,0 +1,120 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+"""
+
+import std/[xmltree, assertions, xmlparser]
+
+
+block:
+  var
+    x: XmlNode
+
+  x = <>a(href = "http://nim-lang.org", newText("Nim rules."))
+  doAssert $x == """<a href="http://nim-lang.org">Nim rules.</a>"""
+
+  x = <>outer(<>inner())
+  doAssert $x == """<outer>
+  <inner />
+</outer>"""
+
+  x = <>outer(<>middle(<>inner1(), <>inner2(), <>inner3(), <>inner4()))
+  doAssert $x == """<outer>
+  <middle>
+    <inner1 />
+    <inner2 />
+    <inner3 />
+    <inner4 />
+  </middle>
+</outer>"""
+
+  x = <>l0(<>l1(<>l2(<>l3(<>l4()))))
+  doAssert $x == """<l0>
+  <l1>
+    <l2>
+      <l3>
+        <l4 />
+      </l3>
+    </l2>
+  </l1>
+</l0>"""
+
+  x = <>l0(<>l1p1(), <>l1p2(), <>l1p3())
+  doAssert $x == """<l0>
+  <l1p1 />
+  <l1p2 />
+  <l1p3 />
+</l0>"""
+
+  x = <>l0(<>l1(<>l2p1(), <>l2p2()))
+  doAssert $x == """<l0>
+  <l1>
+    <l2p1 />
+    <l2p2 />
+  </l1>
+</l0>"""
+
+  x = <>l0(<>l1(<>l2_1(), <>l2_2(<>l3_1(), <>l3_2(), <>l3_3(<>l4_1(), <>l4_2(), <>l4_3())), <>l2_3(), <>l2_4()))
+  doAssert $x == """<l0>
+  <l1>
+    <l2_1 />
+    <l2_2>
+      <l3_1 />
+      <l3_2 />
+      <l3_3>
+        <l4_1 />
+        <l4_2 />
+        <l4_3 />
+      </l3_3>
+    </l2_2>
+    <l2_3 />
+    <l2_4 />
+  </l1>
+</l0>"""
+
+  let
+    innermost = newElement("innermost")
+    middle = newXmlTree("middle", [innermost])
+  innermost.add newText("innermost text")
+  x = newXmlTree("outer", [middle])
+  doAssert $x == """<outer>
+  <middle>
+    <innermost>innermost text</innermost>
+  </middle>
+</outer>"""
+
+  x = newElement("myTag")
+  x.add newText("my text")
+  x.add newElement("sonTag")
+  x.add newEntity("my entity")
+  doAssert $x == "<myTag>my text<sonTag />&my entity;</myTag>"
+
+block: # bug #21290
+  let x = newXmlTree("foo",[
+    newXmlTree("bar",[
+      newText("Hola"),
+      newXmlTree("qux",[
+        newXmlTree("plugh",[])
+      ])
+    ])
+  ])
+
+  let s = $x
+  doAssert $parseXml(s) == s
+  doAssert s == """<foo>
+  <bar>Hola<qux>    <plugh />  </qux></bar>
+</foo>"""
+
+block: #21541
+  let root = <>root()
+  root.add <>child(newText("hello"))
+  root.add <>more(newVerbatimText("hola"))
+  let s = $root
+  doAssert s == """<root>
+  <child>hello</child>
+  <more>hola</more>
+</root>"""
+
+  let temp = newVerbatimText("Hello!")
+  doAssert temp.text == "Hello!"
+  temp.text = "Hola!"
+  doAssert temp.text == "Hola!"
diff --git a/tests/stdlib/tyield.nim b/tests/stdlib/tyield.nim
new file mode 100644
index 000000000..f385ddd05
--- /dev/null
+++ b/tests/stdlib/tyield.nim
@@ -0,0 +1,258 @@
+discard """
+  matrix: "--mm:refc; --mm:orc"
+  targets: "c cpp js"
+"""
+
+import std/[sugar, algorithm]
+import std/assertions
+
+block:
+  var x = @[(6.0, 6, '6'),
+            (5.0, 5, '5'),
+            (4.0, 4, '4'),
+            (3.0, 3, '3'),
+            (2.0, 2, '2'),
+            (1.0, 1, '1')]
+
+  let y = x.reversed
+
+  block:
+    let res = collect:
+      for (f, i, c) in x:
+        (f, i, c)
+
+    doAssert res == x
+
+  iterator popAscending[T](q: var seq[T]): T =
+    while q.len > 0: yield q.pop
+
+  block:
+    var res = collect:
+      for f, i, c in popAscending(x):
+        (f, i, c)
+
+    doAssert res == y
+
+    let z = reversed(res)
+    let res2 = collect:
+      for (f, i, c) in popAscending(res):
+        (f, i, c)
+
+    doAssert res2 == z
+
+
+block:
+  var visits = 0
+  block:
+    proc bar(): (int, int) =
+      inc visits
+      (visits, visits)
+
+    iterator foo(): (int, int) =
+      yield bar()
+
+    for a, b in foo():
+      doAssert a == b
+
+    doAssert visits == 1
+
+  block:
+    proc iterAux(a: seq[int], i: var int): (int, string) =
+      result = (a[i], $a[i])
+      inc i
+
+    iterator pairs(a: seq[int]): (int, string) =
+      var i = 0
+      while i < a.len:
+        yield iterAux(a, i)
+
+    var x = newSeq[int](10)
+    for i in 0 ..< x.len:
+      x[i] = i
+
+    let res = collect:
+      for k, v in x:
+        (k, v)
+
+    let expected = collect:
+      for i in 0 ..< x.len:
+        (i, $i)
+
+    doAssert res == expected
+
+  block:
+    proc bar(): (int, int, int) =
+      inc visits
+      (visits, visits, visits)
+
+    iterator foo(): (int, int, int) =
+      yield bar()
+
+    for a, b, c in foo():
+      doAssert a == b
+
+    doAssert visits == 2
+
+
+  block:
+
+    proc bar(): int =
+      inc visits
+      visits
+
+    proc car(): int =
+      inc visits
+      visits
+
+    iterator foo(): (int, int) =
+      yield (bar(), car())
+      yield (bar(), car())
+
+    for a, b in foo():
+      doAssert b == a + 1
+
+    doAssert visits == 6
+
+
+  block:
+    proc bar(): (int, int) =
+      inc visits
+      (visits, visits)
+
+    proc t2(): int = 99
+
+    iterator foo(): (int, int) =
+      yield (12, t2())
+      yield bar()
+
+    let res = collect:
+      for (a, b) in foo():
+        (a, b)
+
+    doAssert res == @[(12, 99), (7, 7)]
+    doAssert visits == 7
+
+  block:
+    proc bar(): (int, int) =
+      inc visits
+      (visits, visits)
+
+    proc t2(): int = 99
+
+    iterator foo(): (int, int) =
+      yield ((12, t2()))
+      yield (bar())
+
+    let res = collect:
+      for (a, b) in foo():
+        (a, b)
+
+    doAssert res == @[(12, 99), (8, 8)]
+    doAssert visits == 8
+
+  block:
+    proc bar(): (int, int) =
+      inc visits
+      (visits, visits)
+
+    proc t1(): int = 99
+    proc t2(): int = 99
+
+    iterator foo(): (int, int) =
+      yield (t1(), t2())
+      yield bar()
+
+    let res = collect:
+      for a, b in foo():
+        (a, b)
+
+    doAssert res == @[(99, 99), (9, 9)]
+    doAssert visits == 9
+
+
+  block:
+    proc bar(): ((int, int), string) =
+      inc visits
+      ((visits, visits), $visits)
+
+    proc t2(): int = 99
+
+    iterator foo(): ((int, int), string) =
+      yield ((1, 2), $t2())
+      yield bar()
+
+    let res = collect:
+      for a, b in foo():
+        (a, b)
+
+    doAssert res == @[((1, 2), "99"), ((10, 10), "10")]
+    doAssert visits == 10
+
+
+  block:
+    proc bar(): (int, int) =
+      inc visits
+      (visits, visits)
+
+    iterator foo(): (int, int) =
+      yield (for i in 0 ..< 10: discard bar(); bar())
+      yield (bar())
+
+    let res = collect:
+      for (a, b) in foo():
+        (a, b)
+
+    doAssert res == @[(21, 21), (22, 22)]
+
+  block:
+    proc bar(): (int, int) =
+      inc visits
+      (visits, visits)
+
+    proc t2(): int = 99
+
+    iterator foo(): (int, int) =
+      yield if true: bar() else: (t2(), t2())
+      yield (bar())
+
+    let res = collect:
+      for a, b in foo():
+        (a, b)
+
+    doAssert res == @[(23, 23), (24, 24)]
+
+
+block:
+  iterator foo(): (int, int, int) =
+    var time = 777
+    yield (1, time, 3)
+
+  let res = collect:
+    for a, b, c in foo():
+      (a, b, c)
+
+  doAssert res == @[(1, 777, 3)]
+
+block:
+  iterator foo(): (int, int, int) =
+    var time = 777
+    yield (1, time, 3)
+
+  let res = collect:
+    for t in foo():
+      (t[0], t[1], t[2])
+
+  doAssert res == @[(1, 777, 3)]
+
+
+block:
+  proc bar(): (int, int, int) =
+    (1, 2, 3)
+  iterator foo(): (int, int, int) =
+    yield bar()
+
+  let res = collect:
+    for a, b, c in foo():
+      (a, b, c)
+
+  doAssert res == @[(1, 2, 3)]
diff --git a/tests/stdlib/unixsockettest.nim b/tests/stdlib/unixsockettest.nim
new file mode 100644
index 000000000..8f95d0808
--- /dev/null
+++ b/tests/stdlib/unixsockettest.nim
@@ -0,0 +1,26 @@
+import std/[assertions, net, os]
+
+let unixSocketPath = getCurrentDir() / "usox"
+
+removeFile(unixSocketPath)
+
+let socket = newSocket(AF_UNIX, SOCK_STREAM, IPPROTO_NONE)
+socket.bindUnix(unixSocketPath)
+socket.listen()
+
+var
+  clientSocket: Socket
+  data: string
+
+socket.accept(clientSocket)
+clientSocket.readLine(data)
+doAssert data == "data sent through the socket"
+clientSocket.send("Hello from server\c\l")
+
+clientSocket.readLine(data)
+doAssert data == "bye"
+clientSocket.send("bye\c\l")
+
+clientSocket.close()
+socket.close()
+removeFile(unixSocketPath)
diff --git a/tests/stdlib/uselocks.nim b/tests/stdlib/uselocks.nim
index cde9641b2..f87623b5e 100644
--- a/tests/stdlib/uselocks.nim
+++ b/tests/stdlib/uselocks.nim
@@ -1,4 +1,5 @@
 import locks
+import std/assertions
 
 type MyType* [T] = object
   lock: Lock
@@ -9,3 +10,7 @@ proc createMyType*[T]: MyType[T] =
 proc use* (m: var MyType): int =
   withLock m.lock:
     result = 3
+
+block:
+  var l: Lock
+  doAssert $l == "()"
diff --git a/tests/stmt/tforloop_tuple_multiple_underscore.nim b/tests/stmt/tforloop_tuple_multiple_underscore.nim
new file mode 100644
index 000000000..96804df18
--- /dev/null
+++ b/tests/stmt/tforloop_tuple_multiple_underscore.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "the special identifier '_' is ignored in declarations and cannot be used"
+"""
+
+iterator iter(): (int, int, int) =
+  yield (1, 1, 2)
+
+
+for (_, i, _) in iter():
+  echo _
diff --git a/tests/stmt/tforloop_tuple_underscore.nim b/tests/stmt/tforloop_tuple_underscore.nim
new file mode 100644
index 000000000..eda42d527
--- /dev/null
+++ b/tests/stmt/tforloop_tuple_underscore.nim
@@ -0,0 +1,16 @@
+discard """
+  errormsg: "the special identifier '_' is ignored in declarations and cannot be used"
+"""
+
+iterator iter(): (int, int) =
+  yield (1, 2)
+  yield (3, 4)
+  yield (1, 2)
+  yield (3, 4)
+  yield (1, 2)
+  yield (3, 4)
+
+
+for (_, i) in iter():
+  echo _
+
diff --git a/tests/stmt/tforloop_underscore.nim b/tests/stmt/tforloop_underscore.nim
new file mode 100644
index 000000000..ce1c86386
--- /dev/null
+++ b/tests/stmt/tforloop_underscore.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "the special identifier '_' is ignored in declarations and cannot be used"
+"""
+
+for _ in ["a"]:
+  echo _
diff --git a/tests/stmt/tgenericsunderscore.nim b/tests/stmt/tgenericsunderscore.nim
new file mode 100644
index 000000000..be2b8ec78
--- /dev/null
+++ b/tests/stmt/tgenericsunderscore.nim
@@ -0,0 +1,4 @@
+# issue #21435
+
+proc foo[_](x: typedesc[_]): string = "BAR" #[tt.Error
+                        ^ the special identifier '_' is ignored in declarations and cannot be used]#
diff --git a/tests/stmt/tmiscunderscore.nim b/tests/stmt/tmiscunderscore.nim
new file mode 100644
index 000000000..c4bae1c3d
--- /dev/null
+++ b/tests/stmt/tmiscunderscore.nim
@@ -0,0 +1,15 @@
+import std/assertions
+
+block:
+  proc _() = echo "one"
+  doAssert not compiles(_())
+  proc _() = echo "two"
+  doAssert not compiles(_())
+
+block:
+  type _ = int
+  doAssert not (compiles do:
+    let x: _ = 3)
+  type _ = float
+  doAssert not (compiles do:
+    let x: _ = 3)
diff --git a/tests/strictnotnil/tnilcheck.nim b/tests/strictnotnil/tnilcheck.nim
new file mode 100644
index 000000000..b8057de74
--- /dev/null
+++ b/tests/strictnotnil/tnilcheck.nim
@@ -0,0 +1,381 @@
+discard """
+action: compile
+"""
+
+import tables
+
+{.experimental: "strictNotNil".}
+
+type
+  Nilable* = ref object
+    a*: int
+    field*: Nilable
+    
+  NonNilable* = Nilable not nil
+
+  Nilable2* = nil NonNilable
+
+
+# proc `[]`(a: Nilable, b: int): Nilable =
+#   nil
+
+
+# Nilable tests
+
+
+
+# test deref
+proc testDeref(a: Nilable) =
+  echo a.a > 0 #[tt.Warning
+       ^ can't deref a, it might be nil
+  ]#
+
+
+
+# # # test if else
+proc testIfElse(a: Nilable) =
+  if a.isNil:
+    echo a.a #[tt.Warning
+         ^ can't deref a, it is nil
+    ]#
+  else:
+    echo a.a # ok
+
+proc testIfNoElse(a: Nilable) =
+  if a.isNil:
+    echo a.a #[tt.Warning
+         ^ can't deref a, it is nil
+         ]#
+  echo a.a #[tt.Warning
+       ^ can't deref a, it might be nil
+   ]#
+
+proc testIfReturn(a: Nilable) =
+  if not a.isNil:
+    return
+  echo a.a #[tt.Warning
+       ^ can't deref a, it is nil
+  ]#
+
+proc testIfBreak(a: seq[Nilable]) =
+  for b in a:
+    if not b.isNil:
+      break
+    echo b.a #[tt.Warning
+         ^ can't deref b, it is nil
+    ]#
+
+proc testIfContinue(a: seq[Nilable]) =
+  for b in a:
+    if not b.isNil:
+      continue
+    echo b.a #[tt.Warning
+         ^ can't deref b, it is nil
+    ]#
+
+proc testIfRaise(a: Nilable) =
+  if not a.isNil:
+    raise newException(ValueError, "")
+  echo a.a #[tt.Warning
+       ^ can't deref a, it is nil
+  ]#
+
+proc testIfElif(a: Nilable) =
+  var c = 0
+  if c == 0:
+    echo a.a #[tt.Warning
+         ^ can't deref a, it might be nil
+      ]#
+  elif c == 1:
+    echo a.a #[tt.Warning
+         ^ can't deref a, it might be nil
+      ]#
+  elif not a.isNil:
+    echo a.a # ok
+  elif c == 2:
+    echo 0
+  else:
+    echo a.a #[tt.Warning
+         ^ can't deref a, it is nil
+    ]#
+
+proc testAssignUnify(a: Nilable, b: int) =
+  var a2 = a
+  if b == 0:
+    a2 = Nilable()
+  echo a2.a #[tt.Warning
+       ^ can't deref a2, it might be nil
+  ]#
+
+
+# # test assign in branch and unifiying that with the main block after end of branch
+proc testAssignUnifyNil(a: Nilable, b: int) =
+  var a2 = a
+  if b == 0:
+    a2 = nil
+  echo a2.a #[tt.Warning
+       ^ can't deref a2, it might be nil
+  ]#
+
+# test loop
+proc testForLoop(a: Nilable) =
+  var b = Nilable()
+  for i in 0 .. 5:
+    echo b.a #[tt.Warning
+         ^ can't deref b, it might be nil
+    ]#
+    if i == 2:
+      b = a
+  echo b.a #[tt.Warning
+       ^ can't deref b, it might be nil
+  ]#
+
+
+
+# # TODO implement this after discussion
+# # proc testResultCompoundNonNilableElement(a: Nilable): (NonNilable, NonNilable) = #[t t.Warning
+# #      ^ result might be not initialized, so it or an element might be nil
+# # ]#
+# #   if not a.isNil:
+# #     result[0] = a #[t t.Warning
+# #                 ^ can't assign nilable to non nilable: it might be nil
+# #     #]
+
+# # proc testNonNilDeref(a: NonNilable) =
+# #   echo a.a # ok
+
+
+
+# # # not only calls: we can use partitions for dependencies for field aliases
+# # # so we can detect on change what does this affect or was this mutated between us and the original field
+
+# # proc testRootAliasField(a: Nilable) =
+# #   var aliasA = a
+# #   if not a.isNil and not a.field.isNil:
+# #     aliasA.field = nil
+# #     # a.field = nil
+# #     # aliasA = nil 
+# #     echo a.field.a # [tt.Warning
+# #          ^ can't deref a.field, it might be nil
+# #     ]#
+
+
+proc testAliasChanging(a: Nilable) =
+  var b = a
+  var aliasA = b
+  b = Nilable()
+  if not b.isNil:
+    echo aliasA.a #[tt.Warning
+         ^ can't deref aliasA, it might be nil
+    ]#
+
+# # TODO
+# # proc testAliasUnion(a: Nilable) =
+# #   var a2 = a
+# #   var b = a2
+# #   if a.isNil:
+# #     b = Nilable()
+# #     a2 = nil
+# #   else:
+# #     a2 = Nilable()
+# #     b = a2
+# #   if not b.isNil:
+# #     echo a2.a #[ tt.Warning
+# #          ^ can't deref a2, it might be nil
+# #     ]#
+
+# # TODO after alias support
+# #proc callVar(a: var Nilable) =
+# #  a.field = nil
+
+
+# # TODO ptr support
+# # proc testPtrAlias(a: Nilable) =
+# #   # pointer to a: hm.
+# #   # alias to a?
+# #   var ptrA = a.addr # {0, 1} 
+# #   if not a.isNil: # {0, 1}
+# #     ptrA[] = nil # {0, 1} 0: MaybeNil 1: MaybeNil
+# #     echo a.a #[ tt.Warning
+# #          ^ can't deref a, it might be nil
+# #     ]#
+
+# # TODO field stuff
+# # currently it just doesnt support dot, so accidentally it shows a warning but because that
+# # not alias i think
+# # proc testFieldAlias(a: Nilable) =
+# #   var b = a # {0, 1} {2} 
+# #   if not a.isNil and not a.field.isNil: # {0, 1} {2}
+# #     callVar(b) # {0, 1} {2} 0: Safe 1: Safe
+# #     echo a.field.a #[ tt.Warning
+# #           ^ can't deref a.field, it might be nil
+# #     ]#
+# #
+# # proc testUniqueHashTree(a: Nilable): Nilable =
+# #   # TODO what would be a clash
+# #   var field = 0
+# #   if not a.isNil and not a.field.isNil:
+# #     # echo a.field.a
+# #     echo a[field].a
+# #   result = Nilable()
+  
+# # proc testSeparateShadowingResult(a: Nilable): Nilable =
+# #   result = Nilable()
+# #   if not a.isNil:
+# #     var result: Nilable = nil
+# #   echo result.a
+
+
+proc testCStringDeref(a: cstring) =
+  echo a[0] #[tt.Warning
+       ^ can't deref a, it might be nil
+  ]#
+
+
+proc testNilablePtr(a: ptr int) =
+  if not a.isNil:
+    echo a[] # ok
+  echo a[] #[tt.Warning
+       ^ can't deref a, it might be nil
+  ]#
+
+# # proc testNonNilPtr(a: ptr int not nil) =
+# #   echo a[] # ok
+
+proc raiseCall: NonNilable = #[tt.Warning
+^ return value is nil
+]#
+  raise newException(ValueError, "raise for test") 
+
+# proc testTryCatch(a: Nilable) =
+#   var other = a
+#   try:
+#     other = raiseCall()
+#   except:
+#     discard
+#   echo other.a #[ tt.Warning
+#             ^ can't deref other, it might be nil
+#   ]#
+
+# # proc testTryCatchDetectNoRaise(a: Nilable) =
+# #   var other = Nilable()
+# #   try:
+# #     other = nil
+# #     other = a
+# #     other = Nilable()
+# #   except:
+# #     other = nil
+# #   echo other.a # ok
+
+# # proc testTryCatchDetectFinally =
+# #   var other = Nilable()
+# #   try:
+# #     other = nil
+# #     other = Nilable()
+# #   except:
+# #     other = Nilable()
+# #   finally:
+# #     other = nil
+# #   echo other.a # can't deref other: it is nil
+
+# # proc testTryCatchDetectNilableWithRaise(b: bool) =
+# #   var other = Nilable()
+# #   try:
+# #     if b:
+# #       other = nil
+# #     else:
+# #       other = Nilable()
+# #       var other2 = raiseCall()
+# #   except:
+# #     echo other.a # ok
+
+# #   echo other.a # can't deref a: it might be nil
+
+# # proc testRaise(a: Nilable) =
+# #   if a.isNil:
+# #     raise newException(ValueError, "a == nil")
+# #   echo a.a # ok
+
+
+# # proc testBlockScope(a: Nilable) =
+# #   var other = a
+# #   block:
+# #     var other = Nilable()
+# #     echo other.a # ok
+# #   echo other.a # can't deref other: it might be nil
+
+# # ok we can't really get the nil value from here, so should be ok
+# # proc testDirectRaiseCall: NonNilable =
+# #   var a = raiseCall()
+# #   result = NonNilable()
+
+# # proc testStmtList =
+# #   var a = Nilable()
+# #   block:
+# #     a = nil
+# #     a = Nilable()
+# #   echo a.a # ok
+
+proc callChange(a: Nilable) =
+  if not a.isNil:
+    a.field = nil
+
+proc testCallChangeField =
+  var a = Nilable()
+  a.field = Nilable()
+  callChange(a)
+  echo a.field.a #[ tt.Warning
+        ^ can't deref a.field, it might be nil
+       ]#
+
+proc testReassignVarWithField =
+  var a = Nilable()
+  a.field = Nilable()
+  echo a.field.a # ok
+  a = Nilable()
+  echo a.field.a #[ tt.Warning
+        ^ can't deref a.field, it might be nil
+        ]#
+
+
+proc testItemDeref(a: var seq[Nilable]) =
+  echo a[0].a #[tt.Warning
+        ^ can't deref a[0], it might be nil
+       ]#
+  a[0] = Nilable() # good: now .. if we dont track, how do we know 
+  echo a[0].a # ok
+  echo a[1].a #[tt.Warning
+        ^ can't deref a[1], it might be nil
+  ]#
+  var b = 1
+  if a[b].isNil:
+    echo a[1].a #[tt.Warning
+          ^ can't deref a[1], it might be nil
+    ]#
+    var c = 0
+    echo a[c].a #[tt.Warning
+          ^ can't deref a[c], it might be nil
+    ]#
+
+  # known false positive
+  if not a[b].isNil:
+    echo a[b].a #[tt.Warning
+          ^ can't deref a[b], it might be nil
+    ]#
+
+  const c = 0
+  if a[c].isNil:
+    echo a[0].a #[tt.Warning
+          ^ can't deref a[0], it is nil
+    ]#
+  a[c] = Nilable()
+  echo a[0].a # ok
+
+
+
+# # # proc test10(a: Nilable) =
+# # #   if not a.isNil and not a.b.isNil:
+# # #     c_memset(globalA.addr, 0, globalA.sizeOf.csize_t)
+# # #     globalA = nil
+# # #     echo a.a # can't deref a: it might be nil
+
diff --git a/tests/strictnotnil/tnilcheck_no_warnings.nim b/tests/strictnotnil/tnilcheck_no_warnings.nim
new file mode 100644
index 000000000..5ec9bc575
--- /dev/null
+++ b/tests/strictnotnil/tnilcheck_no_warnings.nim
@@ -0,0 +1,182 @@
+discard """
+cmd: "nim check --warningAsError:StrictNotNil $file"
+action: "compile"
+"""
+
+import tables
+
+{.experimental: "strictNotNil".}
+
+type
+  Nilable* = ref object
+    a*: int
+    field*: Nilable
+    
+  NonNilable* = Nilable not nil
+
+  Nilable2* = nil NonNilable
+
+
+# proc `[]`(a: Nilable, b: int): Nilable =
+#   nil
+
+
+# Nilable tests
+
+
+
+# # test and
+proc testAnd(a: Nilable) =
+  echo not a.isNil and a.a > 0 # ok
+
+
+# test else branch and inferring not isNil
+# proc testElse(a: Nilable, b: int) =
+#   if a.isNil:
+#     echo 0
+#   else:
+#     echo a.a
+
+# test that here we can infer that n can't be nil anymore
+proc testNotNilAfterAssign(a: Nilable, b: int) =
+  var n = a # a: MaybeNil n: MaybeNil
+  if n.isNil: # n: Safe a: MaybeNil
+    n = Nilable() # n: Safe a: MaybeNil
+  echo n.a # ok
+
+proc callVar(a: var Nilable) =
+   a = nil
+
+proc testVarAlias(a: Nilable) = # a: 0 aliasA: 1 {0} {1} 
+  var aliasA = a # {0, 1} 0 MaybeNil 1 MaybeNil
+  if not a.isNil: # {0, 1} 0 Safe 1 Safe
+    callVar(aliasA) # {0, 1} 0 MaybeNil 1 MaybeNil
+    # if aliasA stops being in alias: it might be nil, but then a is still not nil
+    # if not: it cant be nil as it still points here
+    echo a.a # ok 
+
+proc testAliasCheck(a: Nilable) =
+  var aliasA = a
+  if not a.isNil:
+    echo aliasA.a # ok
+
+proc testFieldCheck(a: Nilable) =
+  if not a.isNil and not a.field.isNil:
+    echo a.field.a # ok
+
+proc testTrackField =
+  var a = Nilable(field: Nilable())
+  echo a.field.a # ok
+
+proc testNonNilDeref(a: NonNilable) =
+  echo a.a # ok
+
+# # not only calls: we can use partitions for dependencies for field aliases
+# # so we can detect on change what does this affect or was this mutated between us and the original field
+
+
+# proc testUniqueHashTree(a: Nilable): Nilable =
+#   # TODO what would be a clash
+#   var field = 0
+#   if not a.isNil and not a.field.isNil:
+#     # echo a.field.a
+#     echo a[field].a
+#   result = Nilable()
+  
+proc testSeparateShadowingResult(a: Nilable): Nilable =
+  result = Nilable()
+  if not a.isNil:
+    var result: Nilable = nil
+  echo result.a
+
+
+proc testNonNilCString(a: cstring not nil) =
+  echo a[0] # ok
+
+proc testNonNilPtr(a: ptr int not nil) =
+  echo a[] # ok
+
+
+# proc testTryCatchDetectNoRaise(a: Nilable) =
+#   var other = Nilable()
+#   try:
+#     other = nil
+#     other = a
+#     other = Nilable()
+#   except:
+#     other = nil
+#   echo other.a # ok
+
+# proc testTryCatchDetectFinally =
+#   var other = Nilable()
+#   try:
+#     other = nil
+#     other = Nilable()
+#   except:
+#     other = Nilable()
+#   finally:
+#     other = nil
+#   echo other.a # can't deref other: it is nil
+
+# proc testTryCatchDetectNilableWithRaise(b: bool) =
+#   var other = Nilable()
+#   try:
+#     if b:
+#       other = nil
+#     else:
+#       other = Nilable()
+#       var other2 = raiseCall()
+#   except:
+#     echo other.a # ok
+
+#   echo other.a # can't deref a: it might be nil
+
+proc testRaise(a: Nilable) =
+  if a.isNil:
+    raise newException(ValueError, "a == nil")
+  echo a.a # ok
+
+# proc testBlockScope(a: Nilable) =
+#   var other = a
+#   block:
+#     var other = Nilable()
+#     echo other.a # ok
+#   echo other.a # can't deref other: it might be nil
+
+# # (ask Araq about this: not supported yet) ok we can't really get the nil value from here, so should be ok
+# proc testDirectRaiseCall: NonNilable =
+#   var a = raiseCall()
+#   result = NonNilable()
+
+proc testStmtList =
+  var a = Nilable()
+  block:
+    a = nil
+    a = Nilable()
+  echo a.a # ok
+
+proc testItemDerefNoWarning(a: var seq[Nilable]) =
+  a[0] = Nilable() # good: now .. if we dont track, how do we know 
+  echo a[0].a # ok
+  var b = 1
+
+  const c = 0
+  a[c] = Nilable()
+  echo a[0].a # ok
+
+# proc callChange(a: Nilable) =
+#   a.field = nil
+
+# proc testCallAlias =
+#   var a = Nilable(field: Nilable())
+#   callChange(a)
+#   echo a.field.a # can't deref a.field, it might be nil
+
+# # proc test10(a: Nilable) =
+# #   if not a.isNil and not a.b.isNil:
+# #     c_memset(globalA.addr, 0, globalA.sizeOf.csize_t)
+# #     globalA = nil
+# #     echo a.a # can't deref a: it might be nil
+
+var nilable: Nilable
+var withField = Nilable(a: 0, field: Nilable())
diff --git a/tests/stylecheck/fileinfo.nim b/tests/stylecheck/fileinfo.nim
new file mode 100644
index 000000000..d6faf0c73
--- /dev/null
+++ b/tests/stylecheck/fileinfo.nim
@@ -0,0 +1,2 @@
+# fileinfo.nim
+type FileInfo* = object
\ No newline at end of file
diff --git a/tests/stylecheck/foreign_package/foreign_package.nim b/tests/stylecheck/foreign_package/foreign_package.nim
new file mode 100644
index 000000000..f95be006c
--- /dev/null
+++ b/tests/stylecheck/foreign_package/foreign_package.nim
@@ -0,0 +1 @@
+include ../thint
\ No newline at end of file
diff --git a/tests/stylecheck/foreign_package/foreign_package.nimble b/tests/stylecheck/foreign_package/foreign_package.nimble
new file mode 100644
index 000000000..a2c49e389
--- /dev/null
+++ b/tests/stylecheck/foreign_package/foreign_package.nimble
@@ -0,0 +1,2 @@
+# See `tstyleCheck`
+# Needed to mark `mstyleCheck` as a foreign package.
diff --git a/tests/stylecheck/t20397.nim b/tests/stylecheck/t20397.nim
new file mode 100644
index 000000000..486a97d73
--- /dev/null
+++ b/tests/stylecheck/t20397.nim
@@ -0,0 +1,4 @@
+{.hintAsError[Name]:on.}
+var a_b = 1
+discard a_b
+{.hintAsError[Name]:off.}
\ No newline at end of file
diff --git a/tests/stylecheck/t20397_1.nim b/tests/stylecheck/t20397_1.nim
new file mode 100644
index 000000000..76c03dca1
--- /dev/null
+++ b/tests/stylecheck/t20397_1.nim
@@ -0,0 +1,8 @@
+discard """
+  matrix: "--styleCheck:off --hint:Name:on"
+"""
+
+{.hintAsError[Name]:on.}
+var a_b = 1
+discard a_b
+{.hintAsError[Name]:off.}
diff --git a/tests/stylecheck/t20397_2.nim b/tests/stylecheck/t20397_2.nim
new file mode 100644
index 000000000..3b8e1c4d6
--- /dev/null
+++ b/tests/stylecheck/t20397_2.nim
@@ -0,0 +1,7 @@
+discard """
+  errormsg: "'a_b' should be: 'aB'"
+  matrix: "--styleCheck:error"
+"""
+
+var a_b = 1
+discard a_b
\ No newline at end of file
diff --git a/tests/stylecheck/taccept.nim b/tests/stylecheck/taccept.nim
new file mode 100644
index 000000000..43a9ab71f
--- /dev/null
+++ b/tests/stylecheck/taccept.nim
@@ -0,0 +1,22 @@
+discard """
+  matrix: "--styleCheck:error --styleCheck:usages"
+"""
+
+import std/[asyncdispatch, nre]
+
+type
+  Name = object
+    id: int
+
+template hello =
+  var iD = "string"
+  var name: Name
+  doAssert name.id == 0
+  doAssert iD == "string"
+
+hello()
+
+# bug #12955
+import os
+import fileinfo
+var xs: seq[fileinfo.FileInfo]
diff --git a/tests/stylecheck/tforeign_package.nim b/tests/stylecheck/tforeign_package.nim
new file mode 100644
index 000000000..8594ad802
--- /dev/null
+++ b/tests/stylecheck/tforeign_package.nim
@@ -0,0 +1,16 @@
+discard """
+  matrix: "--errorMax:0 --styleCheck:error"
+  action: compile
+"""
+
+import foreign_package/foreign_package
+
+# This call tests that:
+#   - an instantiation of a generic in a foreign package doesn't raise errors
+#     when the generic body contains:
+#     - definition and usage violations
+#     - builtin pragma usage violations
+#     - user pragma usage violations
+#   - definition violations in foreign packages are ignored
+#   - usage violations in foreign packages are ignored
+genericProc[int]()
diff --git a/tests/stylecheck/thint.nim b/tests/stylecheck/thint.nim
new file mode 100644
index 000000000..c19aac1b8
--- /dev/null
+++ b/tests/stylecheck/thint.nim
@@ -0,0 +1,43 @@
+discard """
+  matrix: "--styleCheck:hint"
+  action: compile
+"""
+
+# Test violating ident definition:
+{.pragma: user_pragma.} #[tt.Hint
+        ^ 'user_pragma' should be: 'userPragma' [Name] ]#
+
+# Test violating ident usage style matches definition style:
+{.userPragma.} #[tt.Hint
+  ^ 'userPragma' should be: 'user_pragma' [template declared in thint.nim(7, 9)] [Name] ]#
+
+# Test violating builtin pragma usage style:
+{.no_side_effect.}: #[tt.Hint
+  ^ 'no_side_effect' should be: 'noSideEffect' [Name] ]#
+  discard 0
+
+# Test:
+#  - definition style violation
+#  - user pragma usage style violation
+#  - builtin pragma usage style violation
+proc generic_proc*[T] {.no_destroy, userPragma.} = #[tt.Hint
+     ^ 'generic_proc' should be: 'genericProc' [Name]; tt.Hint
+                        ^ 'no_destroy' should be: 'nodestroy' [Name]; tt.Hint
+                                    ^ 'userPragma' should be: 'user_pragma' [template declared in thint.nim(7, 9)] [Name] ]#
+  # Test definition style violation:
+  let snake_case = 0 #[tt.Hint
+      ^ 'snake_case' should be: 'snakeCase' [Name] ]#
+  # Test user pragma definition style violation:
+  {.pragma: another_user_pragma.} #[tt.Hint
+          ^ 'another_user_pragma' should be: 'anotherUserPragma' [Name] ]#
+  # Test user pragma usage style violation:
+  {.anotherUserPragma.} #[tt.Hint
+    ^ 'anotherUserPragma' should be: 'another_user_pragma' [template declared in thint.nim(31, 11)] [Name] ]#
+  # Test violating builtin pragma usage style:
+  {.no_side_effect.}: #[tt.Hint
+    ^ 'no_side_effect' should be: 'noSideEffect' [Name] ]#
+    # Test usage style violation:
+    discard snakeCase #[tt.Hint
+            ^ 'snakeCase' should be: 'snake_case' [let declared in thint.nim(28, 7)] [Name] ]#
+
+generic_proc[int]()
diff --git a/tests/stylecheck/treject.nim b/tests/stylecheck/treject.nim
new file mode 100644
index 000000000..458a2d039
--- /dev/null
+++ b/tests/stylecheck/treject.nim
@@ -0,0 +1,17 @@
+discard """
+  action: reject
+  nimout: '''treject.nim(14, 13) Error: 'iD' should be: 'id' [field declared in treject.nim(9, 5)]'''
+  matrix: "--styleCheck:error --styleCheck:usages  --hint:Name:on"
+"""
+
+type
+  Name = object
+    id: int
+
+template hello =
+  var iD = "string"
+  var name: Name
+  echo name.iD
+  echo iD
+
+hello()
diff --git a/tests/stylecheck/tusages.nim b/tests/stylecheck/tusages.nim
new file mode 100644
index 000000000..b689dabb3
--- /dev/null
+++ b/tests/stylecheck/tusages.nim
@@ -0,0 +1,22 @@
+discard """
+  action: reject
+  nimout: '''tusages.nim(20, 5) Error: 'BAD_STYLE' should be: 'BADSTYLE' [proc declared in tusages.nim(9, 6)]'''
+  matrix: "--styleCheck:error --styleCheck:usages --hint:all:off --hint:Name:on"
+"""
+
+import strutils
+
+proc BADSTYLE(c: char) = discard
+
+proc toSnakeCase(s: string): string =
+  result = newStringOfCap(s.len + 3)
+  for i in 0..<s.len:
+    if s[i] in {'A'..'Z'}:
+      if i > 0 and s[i-1] in {'a'..'z'}:
+        result.add '_'
+      result.add toLowerAscii(s[i])
+    else:
+      result.add s[i]
+    BAD_STYLE(s[i])
+
+echo toSnakeCase("fooBarBaz Yes")
diff --git a/tests/system/t10307.nim b/tests/system/t10307.nim
new file mode 100644
index 000000000..b5a93c5c6
--- /dev/null
+++ b/tests/system/t10307.nim
@@ -0,0 +1,24 @@
+discard """
+  cmd: "nim c --mm:refc -d:useGcAssert $file"
+  output: '''running someProc(true)
+res: yes
+yes
+running someProc(false)
+res: 
+
+'''
+"""
+
+proc someProc(x:bool):cstring =
+  var res:string = ""
+  if x:
+    res = "yes"
+  echo "res: ", res
+  GC_ref(res)
+  result = res
+
+echo "running someProc(true)"
+echo someProc(true)
+
+echo "running someProc(false)"
+echo someProc(false)
diff --git a/tests/system/t20938.nim b/tests/system/t20938.nim
new file mode 100644
index 000000000..7341cbb91
--- /dev/null
+++ b/tests/system/t20938.nim
@@ -0,0 +1,12 @@
+discard """
+  cmd: "nim c --mm:refc $file"
+  action: "compile"
+"""
+
+template foo(x: typed) =
+  discard x
+
+foo:
+  var x = "hello"
+  x.shallowCopy("test")
+  true
diff --git a/tests/system/talloc.nim b/tests/system/talloc.nim
index 9b970fda0..a81fef481 100644
--- a/tests/system/talloc.nim
+++ b/tests/system/talloc.nim
@@ -1,8 +1,4 @@
-discard """
-disabled: "appveyor"
-"""
-
-# appveyor is "out of memory"
+# was: appveyor is "out of memory"
 
 var x: ptr int
 
diff --git a/tests/system/talloc2.nim b/tests/system/talloc2.nim
index a321fe741..9d1687f34 100644
--- a/tests/system/talloc2.nim
+++ b/tests/system/talloc2.nim
@@ -1,10 +1,11 @@
 discard """
 disabled: "windows"
+disabled: "openbsd"
 joinable: false
 disabled: 32bit
 """
 # no point to test this on system with smaller address space
-# appveyor is "out of memory"
+# was: appveyor is "out of memory"
 
 const
   nmax = 2*1024*1024*1024
diff --git a/tests/system/tatomics1.nim b/tests/system/tatomics1.nim
new file mode 100644
index 000000000..217fd07fa
--- /dev/null
+++ b/tests/system/tatomics1.nim
@@ -0,0 +1,9 @@
+discard """
+  targets: "c cpp js"
+"""
+
+var x = 10
+atomicInc(x)
+doAssert x == 11
+atomicDec(x)
+doAssert x == 10
diff --git a/tests/system/tcomparisons.nim b/tests/system/tcomparisons.nim
new file mode 100644
index 000000000..a661b14a1
--- /dev/null
+++ b/tests/system/tcomparisons.nim
@@ -0,0 +1,51 @@
+discard """
+  targets: "c cpp js"
+"""
+
+template main =
+  block: # proc equality
+    var prc: proc(): int {.closure.}
+    prc = nil
+    doAssert prc == nil
+    doAssert prc.isNil
+    prc = proc(): int =
+      result = 123
+    doAssert prc != nil
+    doAssert not prc.isNil
+    doAssert prc == prc
+    let prc2 = prc
+    doAssert prc == prc2
+    doAssert prc2 != nil
+    doAssert not prc2.isNil
+    doAssert not prc.isNil
+    prc = proc(): int =
+      result = 456
+    doAssert prc != nil
+    doAssert not prc.isNil
+    doAssert prc != prc2
+  block: # iterator equality
+    when nimvm: discard # vm does not support closure iterators
+    else:
+      when not defined(js): # js also does not support closure iterators
+        var iter: iterator(): int {.closure.}
+        iter = nil
+        doAssert iter == nil
+        doAssert iter.isNil
+        iter = iterator(): int =
+          yield 123
+        doAssert iter != nil
+        doAssert not iter.isNil
+        doAssert iter == iter
+        let iter2 = iter
+        doAssert iter == iter2
+        doAssert iter2 != nil
+        doAssert not iter2.isNil
+        doAssert not iter.isNil
+        iter = iterator(): int =
+          yield 456
+        doAssert iter != nil
+        doAssert not iter.isNil
+        doAssert iter != iter2
+
+static: main()
+main()
diff --git a/tests/concat/tconcat.nim b/tests/system/tconcat.nim
index fdce3ea00..fdce3ea00 100644
--- a/tests/concat/tconcat.nim
+++ b/tests/system/tconcat.nim
diff --git a/tests/system/tdeepcopy.nim b/tests/system/tdeepcopy.nim
index 383d2e8d1..92ba48115 100644
--- a/tests/system/tdeepcopy.nim
+++ b/tests/system/tdeepcopy.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc --deepcopy:on"
   output: "ok"
 """
 
diff --git a/tests/system/tdollars.nim b/tests/system/tdollars.nim
new file mode 100644
index 000000000..eabee81b3
--- /dev/null
+++ b/tests/system/tdollars.nim
@@ -0,0 +1,199 @@
+discard """
+  matrix: "--mm:refc; --mm:orc; --backend:cpp; --backend:js --jsbigint64:off -d:nimStringHash2; --backend:js --jsbigint64:on"
+"""
+
+#[
+if https://github.com/nim-lang/Nim/pull/14043 is merged (or at least its
+tests/system/tostring.nim diff subset), merge
+tests/system/tostring.nim into this file, named after dollars.nim
+
+The goal is to increase test coverage across backends while minimizing test code
+duplication (which always results in weaker test coverage in practice).
+]#
+
+import std/unittest
+import std/private/jsutils
+template test[T](a: T, expected: string) =
+  check $a == expected
+  var b = a
+  check $b == expected
+  static:
+    doAssert $a == expected
+
+template testType(T: typedesc) =
+  when T is bool:
+    test true, "true"
+    test false, "false"
+  elif T is char:
+    test char, "\0"
+    test char.high, static($T.high)
+  else:
+    test T.default, "0"
+    test 1.T, "1"
+    test T.low, static($T.low)
+    test T.high, static($T.high)
+
+block: # `$`(SomeInteger)
+  # direct tests
+  check $0'u8 == "0"
+  check $255'u8 == "255"
+  check $(-127'i8) == "-127"
+
+  # known limitation: Error: number out of range: '128'i8',
+  # see https://github.com/timotheecour/Nim/issues/125
+  # check $(-128'i8) == "-128"
+
+  check $int8.low == "-128"
+  check $int8(-128) == "-128"
+  check $cast[int8](-128) == "-128"
+
+  var a = 12345'u16
+  check $a == "12345"
+  check $12345678'u64 == "12345678"
+  check $12345678'i64 == "12345678"
+  check $(-12345678'i64) == "-12345678"
+
+  # systematic tests
+  testType uint8
+  testType uint16
+  testType uint32
+  testType uint
+
+  testType int8
+  testType int16
+  testType int32
+
+  testType int
+  testType bool
+
+  whenJsNoBigInt64: discard
+  do:
+    testType uint64
+    testType int64
+    testType BiggestInt
+
+block: # #14350, #16674, #16686 for JS
+  var cstr: cstring
+  doAssert cstr == cstring(nil)
+  doAssert cstr == nil
+  doAssert cstr.isNil
+  doAssert cstr != cstring("")
+  doAssert cstr.len == 0
+
+  when defined(js):
+    cstr.add(cstring("abc"))
+    doAssert cstr == cstring("abc")
+
+    var nil1, nil2: cstring = nil
+
+    nil1.add(nil2)
+    doAssert nil1 == cstring(nil)
+    doAssert nil2 == cstring(nil)
+
+    nil1.add(cstring(""))
+    doAssert nil1 == cstring("")
+    doAssert nil2 == cstring(nil)
+
+    nil1.add(nil2)
+    doAssert nil1 == cstring("")
+    doAssert nil2 == cstring(nil)
+
+    nil2.add(nil1)
+    doAssert nil1 == cstring("")
+    doAssert nil2 == cstring("")
+
+block:
+  when defined(js): # bug #18591
+    let a1 = -1'i8
+    let a2 = uint8(a1)
+    # if `uint8(a1)` changes meaning to `cast[uint8](a1)` in future, update this test;
+    # until then, this is the correct semantics.
+    let a3 = $a2
+    doAssert a2 == 255'u8
+    doAssert a3 == "255"
+    proc intToStr(a: uint8): cstring {.importjs: "(# + \"\")".}
+    doAssert $intToStr(a2) == "255"
+  else:
+    block:
+      let x = -1'i8
+      let y = uint32(x)
+      doAssert $y == "4294967295"
+    block:
+      let x = -1'i16
+      let y = uint32(x)
+      doAssert $y == "4294967295"
+    block:
+      let x = -1'i32
+      let y = uint32(x)
+      doAssert $y == "4294967295"
+    block:
+      proc foo1(arg: int): string =
+        let x = uint32(arg)
+        $x
+      doAssert $foo1(-1) == "4294967295"
+
+  block:
+    let x = 4294967295'u32
+    doAssert $x == "4294967295"
+  block:
+    doAssert $(4294967295'u32) == "4294967295"
+
+proc main()=
+  block:
+    let a = -0.0
+    doAssert $a == "-0.0"
+    doAssert $(-0.0) == "-0.0"
+
+  block:
+    let a = 0.0
+    doAssert $a == "0.0"
+    doAssert $(0.0) == "0.0"
+
+  block:
+    let b = -0
+    doAssert $b == "0"
+    doAssert $(-0) == "0"
+
+  block:
+    let b = 0
+    doAssert $b == "0"
+    doAssert $(0) == "0"
+
+  doAssert $uint32.high == "4294967295"
+
+  block: # addInt
+    var res = newStringOfCap(24)
+    template test2(a, b) =
+      res.setLen(0)
+      res.addInt a
+      doAssert res == b
+
+    for i in 0 .. 9:
+      res.addInt int64(i)
+    doAssert res == "0123456789"
+
+    res.setLen(0)
+    for i in -9 .. 0:
+      res.addInt int64(i)
+    doAssert res == "-9-8-7-6-5-4-3-2-10"
+
+    whenJsNoBigInt64: discard
+    do:
+      test2 high(int64), "9223372036854775807"
+      test2 low(int64), "-9223372036854775808"
+    test2 high(int32), "2147483647"
+    test2 low(int32), "-2147483648"
+    test2 high(int16), "32767"
+    test2 low(int16), "-32768"
+    test2 high(int8), "127"
+    test2 low(int8), "-128"
+
+  block:
+    const
+      a: array[3, char] = ['N', 'i', 'm']
+      aStr = $(a)
+
+    doAssert aStr == """['N', 'i', 'm']"""
+
+static: main()
+main()
diff --git a/tests/system/temptyecho.nim b/tests/system/temptyecho.nim
new file mode 100644
index 000000000..a3c407897
--- /dev/null
+++ b/tests/system/temptyecho.nim
@@ -0,0 +1,6 @@
+discard """
+output: "\n"
+"""
+
+echo()
+
diff --git a/tests/system/tensuremove.nim b/tests/system/tensuremove.nim
new file mode 100644
index 000000000..668d5aed1
--- /dev/null
+++ b/tests/system/tensuremove.nim
@@ -0,0 +1,131 @@
+discard """
+  targets: "c js"
+  matrix: "--cursorinference:on; --cursorinference:off"
+"""
+
+block:
+  type
+    X = object
+      s: string
+
+  proc `=copy`(x: var X, y: X) =
+    x.s = "copied " & y.s
+
+  proc `=sink`(x: var X, y: X) =
+    `=destroy`(x)
+    wasMoved(x)
+    x.s = "moved " & y.s
+
+  proc consume(x: sink X) =
+    discard x.s
+
+  proc main =
+    let m = "abcdefg"
+    var x = X(s: ensureMove m)
+    consume(ensureMove x)
+
+  static: main()
+  main()
+
+block:
+  type
+    String = object
+      id: string
+
+  proc hello =
+    var s = String(id: "1")
+    var m = ensureMove s
+    doAssert m.id == "1"
+
+  hello()
+
+block:
+  type
+    String = object
+      id: string
+
+  proc hello =
+    var n = "1"
+    var s = String(id: ensureMove n)
+    var m = ensureMove s
+    doAssert m.id == "1"
+
+  hello()
+
+block:
+  type
+    String = object
+      id: string
+
+  proc hello =
+    var n = "1"
+    var s = [ensureMove n]
+    var m = ensureMove s
+    doAssert m[0] == "1"
+
+  hello()
+
+block:
+  type
+    String = object
+      id: string
+
+  proc hello =
+    var n = "1"
+    var s = @[ensureMove n]
+    var m = ensureMove s
+    doAssert m[0] == "1"
+
+  hello()
+
+block:
+  type
+    String = object
+      id: string
+
+  proc hello =
+    var s = String(id: "1")
+    var m = ensureMove s.id
+    doAssert m == "1"
+
+  hello()
+
+block:
+  proc foo =
+    var x = 1
+    let y = ensureMove x # move
+    when not defined(js):
+      doAssert (y, x) == (1, 0) # (1, 0)
+  foo()
+
+block:
+  proc foo =
+    var x = 1
+    let y = ensureMove x # move
+    doAssert y == 1
+  foo()
+
+block:
+  proc foo =
+    var x = @[1, 2, 3]
+    let y = ensureMove x[0] # move
+    doAssert y == 1
+    when not defined(js):
+      doAssert x == @[0, 2, 3]
+  foo()
+
+block:
+  proc foo =
+    var x = [1, 2, 3]
+    let y = ensureMove x[0] # move
+    doAssert y == 1
+    when not defined(js):
+      doAssert x == @[0, 2, 3]
+  foo()
+
+block:
+  proc foo =
+    var x = @["1", "2", "3"]
+    let y = ensureMove x[0] # move
+    doAssert y == "1"
+  foo()
diff --git a/tests/system/tensuremove1.nim b/tests/system/tensuremove1.nim
new file mode 100644
index 000000000..b7e19c4fb
--- /dev/null
+++ b/tests/system/tensuremove1.nim
@@ -0,0 +1,16 @@
+discard """
+  errormsg: "cannot move 's', which introduces an implicit copy"
+  matrix: "--cursorinference:on; --cursorinference:off"
+"""
+
+type
+  String = object
+    id: string
+
+proc hello =
+  var s = String(id: "1")
+  var m = ensureMove s
+  discard m
+  discard s
+
+hello()
\ No newline at end of file
diff --git a/tests/system/tensuremove2.nim b/tests/system/tensuremove2.nim
new file mode 100644
index 000000000..39bbeb22e
--- /dev/null
+++ b/tests/system/tensuremove2.nim
@@ -0,0 +1,15 @@
+discard """
+  errormsg: "Nested expressions cannot be moved: 'if true: s else: String()'"
+"""
+
+type
+  String = object
+    id: string
+
+proc hello =
+  var s = String(id: "1")
+  var m = ensureMove(if true: s else: String())
+  discard m
+  discard s
+
+hello()
\ No newline at end of file
diff --git a/tests/system/tensuremove3.nim b/tests/system/tensuremove3.nim
new file mode 100644
index 000000000..eca032673
--- /dev/null
+++ b/tests/system/tensuremove3.nim
@@ -0,0 +1,28 @@
+discard """
+  errormsg: "cannot move 'x', passing 'x' to a sink parameter introduces an implicit copy"
+  matrix: "--cursorinference:on; --cursorinference:off"
+"""
+
+block:
+  type
+    X = object
+      s: string
+
+  proc `=copy`(x: var X, y: X) =
+    x.s = "copied " & y.s
+
+  proc `=sink`(x: var X, y: X) =
+    `=destroy`(x)
+    wasMoved(x)
+    x.s = "moved " & y.s
+
+  proc consume(x: sink X) =
+    discard x.s
+
+  proc main =
+    var s = "abcdefg"
+    var x = X(s: ensureMove s)
+    consume(ensureMove x)
+    discard x
+
+  main()
\ No newline at end of file
diff --git a/tests/system/tenum_array_repr.nim b/tests/system/tenum_array_repr.nim
index 3634692e3..39b1a5f9a 100644
--- a/tests/system/tenum_array_repr.nim
+++ b/tests/system/tenum_array_repr.nim
@@ -2,10 +2,8 @@ discard """
   output: '''
 1
 [a, b]
-
 2
 [c, d]
-
 4
 [e, f]'''
 """
diff --git a/tests/fields/tfielditerator.nim b/tests/system/tfielditerator.nim
index 877e4454c..7e063c6cf 100644
--- a/tests/fields/tfielditerator.nim
+++ b/tests/system/tfielditerator.nim
@@ -60,12 +60,12 @@ block titerator1:
   for key, val in fieldPairs(x):
     echo key, ": ", val
 
-  assert x != y
-  assert x == x
-  assert(not (x < x))
-  assert x <= x
-  assert y < x
-  assert y <= x
+  doAssert x != y
+  doAssert x == x
+  doAssert(not (x < x))
+  doAssert x <= x
+  doAssert y < x
+  doAssert y <= x
 
 
 block titerator2:
@@ -109,4 +109,18 @@ block titerator2:
     echo key, ": ", val
 
   for val in fields(co):
-    echo val
\ No newline at end of file
+    echo val
+
+block:
+  type
+    Enum = enum A, B
+    Object = object
+      case a: Enum
+      of A:
+        integer: int
+      of B:
+        time: string
+
+  let x = A
+  let s = Object(a: x)
+  doAssert s.integer == 0
diff --git a/tests/fields/tfields.nim b/tests/system/tfields.nim
index 0bf3a4e1a..0bf3a4e1a 100644
--- a/tests/fields/tfields.nim
+++ b/tests/system/tfields.nim
diff --git a/tests/system/tgcnone.nim b/tests/system/tgcnone.nim
new file mode 100644
index 000000000..1ccb9e29c
--- /dev/null
+++ b/tests/system/tgcnone.nim
@@ -0,0 +1,7 @@
+discard """
+  matrix: "--mm:none -d:useMalloc"
+"""
+# bug #15617
+# bug #22262
+let x = 4
+doAssert x == 4
diff --git a/tests/misc/tgcregions.nim b/tests/system/tgcregions.nim
index e14865be3..e14865be3 100644
--- a/tests/misc/tgcregions.nim
+++ b/tests/system/tgcregions.nim
diff --git a/tests/misc/tinc.nim b/tests/system/timmutableinc.nim
index 91f6223e2..e857800b3 100644
--- a/tests/misc/tinc.nim
+++ b/tests/system/timmutableinc.nim
@@ -1,6 +1,6 @@
 discard """
   errormsg: "type mismatch: got <int>"
-  file: "tinc.nim"
+  file: "timmutableinc.nim"
   line: 8
 """
 var x = 0
diff --git a/tests/misc/tnot.nim b/tests/system/tinvalidnot.nim
index a3669705b..df0291a8a 100644
--- a/tests/misc/tnot.nim
+++ b/tests/system/tinvalidnot.nim
@@ -1,6 +1,6 @@
 discard """
   errormsg: "type mismatch"
-  file: "tnot.nim"
+  file: "tinvalidnot.nim"
   line: 14
 """
 # BUG: following compiles, but should not:
diff --git a/tests/system/tio.nim b/tests/system/tio.nim
index c4d041560..52a21837a 100644
--- a/tests/system/tio.nim
+++ b/tests/system/tio.nim
@@ -22,12 +22,12 @@ proc echoLoop(str: string): string =
   while not output.atEnd:
     result.add(output.readLine)
 
-suite "io":
-  suite "readAll":
-    test "stdin":
+block: # io
+  block: # readAll
+    block: # stdin
       check:
         echoLoop(STRING_DATA) == STRING_DATA
-    test "file":
+    block: # file
       check:
         readFile(TEST_FILE).strip == STRING_DATA
 
diff --git a/tests/misc/tlocals.nim b/tests/system/tlocals.nim
index ad9e7d032..e59976102 100644
--- a/tests/misc/tlocals.nim
+++ b/tests/system/tlocals.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc; --mm:orc"
   output: '''(x: "string here", a: 1)
 b is 5
 x is 12'''
@@ -62,3 +63,14 @@ proc foo3[T](y: T) =
   bar2(y)
 
 foo3(12)
+
+block: # bug #12682
+  template foo(): untyped =
+    var c1 = locals()
+    1
+
+  proc testAll()=
+    doAssert foo() == 1
+    let c2=locals()
+
+  testAll()
diff --git a/tests/misc/tlowhigh.nim b/tests/system/tlowhigh.nim
index 6ae871255..6ae871255 100644
--- a/tests/misc/tlowhigh.nim
+++ b/tests/system/tlowhigh.nim
diff --git a/tests/magics/tmagics.nim b/tests/system/tmagics.nim
index fa138320c..6088c9600 100644
--- a/tests/magics/tmagics.nim
+++ b/tests/system/tmagics.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   output: '''
 true
 true
@@ -18,7 +19,7 @@ block tlowhigh:
   for i in low(a) .. high(a):
     a[i] = 0
 
-  proc sum(a: openarray[int]): int =
+  proc sum(a: openArray[int]): int =
     result = 0
     for i in low(a)..high(a):
       inc(result, a[i])
@@ -55,3 +56,7 @@ block t9442:
   GC_unref(v2)
   GC_ref(v3)
   GC_unref(v3)
+
+block: # bug #12229
+  proc foo(T: typedesc) = discard
+  foo(ref)
diff --git a/tests/system/tmemory.nim b/tests/system/tmemory.nim
new file mode 100644
index 000000000..553037011
--- /dev/null
+++ b/tests/system/tmemory.nim
@@ -0,0 +1,16 @@
+import std/assertions
+
+block: # cmpMem
+  type
+    SomeHash = array[15, byte]
+
+  var
+    a: SomeHash
+    b: SomeHash
+
+  a[^1] = byte(1)
+  let c = a
+
+  doAssert cmpMem(a.addr, b.addr, sizeof(SomeHash)) > 0
+  doAssert cmpMem(b.addr, a.addr, sizeof(SomeHash)) < 0
+  doAssert cmpMem(a.addr, c.addr, sizeof(SomeHash)) == 0
diff --git a/tests/misc/tnew.nim b/tests/system/tnew.nim
index 2d9a64461..c28c1187f 100644
--- a/tests/misc/tnew.nim
+++ b/tests/system/tnew.nim
@@ -1,4 +1,5 @@
 discard """
+matrix: "--mm:refc; --mm:orc"
 outputsub: '''
 Simple tree node allocation worked!
 Simple cycle allocation worked!
@@ -24,7 +25,10 @@ proc finalizer(n: PNode) =
   write(stdout, " is now freed\n")
 
 proc newNode(data: int, le, ri: PNode): PNode =
-  new(result, finalizer)
+  when defined(gcDestructors): # using finalizer breaks the test for orc
+    new(result)
+  else:
+    new(result, finalizer)
   result.le = le
   result.ri = ri
   result.data = data
diff --git a/tests/misc/tnewderef.nim b/tests/system/tnewderef.nim
index 3394dbddf..3394dbddf 100644
--- a/tests/misc/tnewderef.nim
+++ b/tests/system/tnewderef.nim
diff --git a/tests/system/tnewstring_uninitialized.nim b/tests/system/tnewstring_uninitialized.nim
new file mode 100644
index 000000000..9bc0e1622
--- /dev/null
+++ b/tests/system/tnewstring_uninitialized.nim
@@ -0,0 +1,11 @@
+discard """
+  matrix: "--mm:refc;"
+"""
+
+# bug #22555
+var x = newStringUninit(10)
+doAssert x.len == 10
+for i in 0..<x.len:
+  x[i] = chr(ord('a') + i)
+
+doAssert x == "abcdefghij"
diff --git a/tests/system/tnilconcats.nim b/tests/system/tnilconcats.nim
index c1126405c..69fc3913c 100644
--- a/tests/system/tnilconcats.nim
+++ b/tests/system/tnilconcats.nim
@@ -26,7 +26,8 @@ when true:
 
   # casting an empty string as sequence with shallow() should not segfault
   var s2: string
-  shallow(s2)
+  when defined(gcRefc):
+    shallow(s2)
   s2 &= "foo"
   doAssert s2 == "foo"
 
diff --git a/tests/system/tnim_stacktrace_override.nim b/tests/system/tnim_stacktrace_override.nim
new file mode 100644
index 000000000..c75da9d9b
--- /dev/null
+++ b/tests/system/tnim_stacktrace_override.nim
@@ -0,0 +1,18 @@
+discard """
+  cmd: "nim c -d:nimStacktraceOverride $file"
+  output: '''begin
+Traceback (most recent call last, using override)
+Error: unhandled exception: stack trace produced [ValueError]
+'''
+  exitcode: 1
+"""
+
+import asyncfutures
+
+proc main =
+  echo "begin"
+  if true:
+    raise newException(ValueError, "stack trace produced")
+  echo "unreachable"
+
+main()
diff --git a/tests/system/tostring.nim b/tests/system/tostring.nim
index ea4a44417..bb6e453fb 100644
--- a/tests/system/tostring.nim
+++ b/tests/system/tostring.nim
@@ -1,7 +1,3 @@
-discard """
-  output: "DONE: tostring.nim"
-"""
-
 doAssert "@[23, 45]" == $(@[23, 45])
 doAssert "[32, 45]" == $([32, 45])
 doAssert """@["", "foo", "bar"]""" == $(@["", "foo", "bar"])
@@ -51,7 +47,7 @@ import strutils
 
 let arr = ['H','e','l','l','o',' ','W','o','r','l','d','!','\0']
 doAssert $arr == "['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd', '!', '\\x00']"
-doAssert $cstring(unsafeAddr arr) == "Hello World!"
+doAssert $cast[cstring](addr arr) == "Hello World!"
 
 proc takes(c: cstring) =
   doAssert c == cstring""
@@ -72,7 +68,7 @@ doAssert yy == ""
 proc bar(arg: cstring) =
   doAssert arg[0] == '\0'
 
-proc baz(arg: openarray[char]) =
+proc baz(arg: openArray[char]) =
   doAssert arg.len == 0
 
 proc stringCompare() =
@@ -83,9 +79,9 @@ proc stringCompare() =
   doAssert b == "bee"
   b.add g
   doAssert b == "bee"
-  c.add 123.456
+  c.addFloat 123.456
   doAssert c == "123.456"
-  d.add 123456
+  d.addInt 123456
   doAssert d == "123456"
 
   doAssert e == ""
@@ -108,7 +104,7 @@ bar(nilstring)
 static:
   stringCompare()
 
-# bug 8847
+# issue #8847
 var a2: cstring = "fo\"o2"
 
 block:
@@ -116,5 +112,14 @@ block:
   s.addQuoted a2
   doAssert s == "\"fo\\\"o2\""
 
-
-echo "DONE: tostring.nim"
+# issue #16650
+template fn() =
+  doAssert len(cstring"ab\0c") == 5
+  doAssert len(cstring("ab\0c")) == 2
+  when nimvm:
+    discard
+  else:
+    let c = cstring("ab\0c")
+    doAssert len(c) == 2
+fn()
+static: fn()
diff --git a/tests/system/trealloc.nim b/tests/system/trealloc.nim
index 7180b8eda..1d3e00aff 100644
--- a/tests/system/trealloc.nim
+++ b/tests/system/trealloc.nim
@@ -1,6 +1,7 @@
 discard """
   output: '''success'''
   joinable: false
+  disabled: "openbsd"
 """
 
 # bug #4818
@@ -11,12 +12,12 @@ const BUFFER_SIZE = 5000
 var buffer = cast[ptr uint16](alloc(BUFFER_SIZE))
 
 var total_size: int64 = 0
-for i in 0 .. 4000:
-    let size = BUFFER_SIZE * i
-    #echo "requesting ", size
-    total_size += size.int64
-    buffer = cast[ptr uint16](realloc(buffer, size))
-    #echo totalSize, " total: ", getTotalMem(), " occupied: ", getOccupiedMem(), " free: ", getFreeMem()
+for i in 0 .. 1000:
+  let size = BUFFER_SIZE * i
+  #echo "requesting ", size
+  total_size += size.int64
+  buffer = cast[ptr uint16](realloc(buffer, size))
+  #echo totalSize, " total: ", getTotalMem(), " occupied: ", getOccupiedMem(), " free: ", getFreeMem()
 
 dealloc(buffer)
 echo "success"
diff --git a/tests/system/trefs.nim b/tests/system/trefs.nim
new file mode 100644
index 000000000..8c36aec52
--- /dev/null
+++ b/tests/system/trefs.nim
@@ -0,0 +1,15 @@
+discard """
+  targets: "c js"
+"""
+
+# bug #21317
+proc parseHook*(v: var ref int) =
+  var a: ref int
+  new(a)
+  a[] = 123
+  v = a
+
+proc fromJson2*(): ref int =
+  parseHook(result)
+
+doAssert fromJson2()[] == 123
diff --git a/tests/system/tsigexitcode.nim b/tests/system/tsigexitcode.nim
new file mode 100644
index 000000000..249256b40
--- /dev/null
+++ b/tests/system/tsigexitcode.nim
@@ -0,0 +1,23 @@
+discard """
+  joinable: false
+  disabled: windows
+"""
+
+import os, osproc, posix, strutils
+
+proc main() =
+  if paramCount() > 0:
+    let signal = cint parseInt paramStr(1)
+    discard posix.raise(signal)
+  else:
+    # synchronize this list with lib/system/except.nim:registerSignalHandler()
+    let sigs = [SIGINT, SIGSEGV, SIGABRT, SIGFPE, SIGILL, SIGBUS, SIGPIPE]
+    for s in sigs:
+      let (_, exitCode) = execCmdEx(quoteShellCommand [getAppFilename(), $s])
+      if s == SIGPIPE:
+        # SIGPIPE should be ignored
+        doAssert exitCode == 0, $(exitCode, s)
+      else:
+        doAssert exitCode == 128+s, $(exitCode, s)
+
+main()
diff --git a/tests/misc/tslices.nim b/tests/system/tslices.nim
index d063c5ebf..d0c68f8cb 100644
--- a/tests/misc/tslices.nim
+++ b/tests/system/tslices.nim
@@ -11,10 +11,9 @@ verichtetd
 
 # Test the new slices.
 
-import strutils
-
 var mystr = "Abgrund"
-mystr[..1] = "Zu"
+# mystr[..1] = "Zu" # deprecated
+mystr[0..1] = "Zu"
 
 mystr[4..4] = "5"
 
@@ -23,7 +22,8 @@ type
 
 var myarr: array[TEnum, int] = [1, 2, 3, 4, 5, 6]
 myarr[e1..e3] = myarr[e4..e6]
-myarr[..e3] = myarr[e4..e6]
+# myarr[..e3] = myarr[e4..e6] # deprecated
+myarr[0..e3] = myarr[e4..e6]
 
 for x in items(myarr): stdout.write(x)
 echo()
@@ -46,7 +46,8 @@ echo mystr
 mystr[4..4] = "u"
 
 # test full replacement
-mystr[.. ^2] = "egerichtet"
+# mystr[.. ^2] = "egerichtet"  # deprecated
+mystr[0 .. ^2] = "egerichtet"
 
 echo mystr
 
@@ -56,3 +57,9 @@ echo mystr
 var s = "abcdef"
 s[1 .. ^2] = "xyz"
 assert s == "axyzf"
+
+# issue mentioned in PR #19219
+type Foo = distinct uint64
+# < here calls `pred` which used to cause a codegen error
+# `pred` compiles because distinct ordinals are considered ordinal
+const slice = 0 ..< 42.Foo
diff --git a/tests/system/tslimsystem.nim b/tests/system/tslimsystem.nim
new file mode 100644
index 000000000..4815306b5
--- /dev/null
+++ b/tests/system/tslimsystem.nim
@@ -0,0 +1,6 @@
+discard """
+  output: "123"
+  matrix: "-d:nimPreviewSlimSystem --mm:refc; -d:nimPreviewSlimSystem --mm:arc"
+"""
+
+echo 123
\ No newline at end of file
diff --git a/tests/system/tstatic.nim b/tests/system/tstatic.nim
new file mode 100644
index 000000000..6e2893e2b
--- /dev/null
+++ b/tests/system/tstatic.nim
@@ -0,0 +1,58 @@
+discard """
+  targets: "c cpp js"
+"""
+
+import std/strutils
+
+# bug #6133
+template main() =
+  block:
+    block:
+      proc foo(q: string, a: int): int =
+        result = q.len
+
+      proc foo(q: static[string]): int =
+        result = foo(q, 5)
+
+      doAssert foo("123") == 3
+
+    block:
+      type E = enum A
+
+      if false:
+        var e = A
+        discard $e
+
+      proc foo(a: string): int =
+        len(a) # 16640
+
+      proc foo(a: static[bool]): int {.used.} =
+        discard
+
+      doAssert foo("") == 0
+
+    block:
+      proc foo(a: string): int =
+        len(a)
+
+      proc foo(a: static[bool]): int {.used.} =
+        discard
+
+      doAssert foo("abc") == 3
+
+    block:
+      proc parseInt(f: static[bool]): int {.used.} = discard
+
+      doAssert "123".parseInt == 123
+  block:
+    type
+      MyType = object
+        field: float32
+      AType[T: static MyType] = distinct range[0f32 .. T.field]
+    var a: AType[MyType(field: 5f32)]
+    proc n(S: static Slice[int]): range[S.a..S.b] = discard
+    assert typeof(n 1..2) is range[1..2]
+
+
+static: main()
+main()
diff --git a/tests/system/tstatic_callable.nim b/tests/system/tstatic_callable.nim
new file mode 100644
index 000000000..92d1fca8d
--- /dev/null
+++ b/tests/system/tstatic_callable.nim
@@ -0,0 +1,12 @@
+# bug #16987
+
+proc getNum(a: int): int = a
+
+# Below calls "doAssert getNum(123) == 123" at compile time.
+static:
+  doAssert getNum(123) == 123
+
+# Below calls evaluate the "getNum(123)" at compile time, but the
+# results of those calls get used at run time.
+doAssert (static getNum(123)) == 123
+doAssert (static(getNum(123))) == 123
diff --git a/tests/system/tstatic_callable_error.nim b/tests/system/tstatic_callable_error.nim
new file mode 100644
index 000000000..c6f1e3d07
--- /dev/null
+++ b/tests/system/tstatic_callable_error.nim
@@ -0,0 +1,14 @@
+# bug #16987
+
+discard """
+errormsg: "cannot evaluate at compile time: inp"
+nimout: '''
+tstatic_callable_error.nim(14, 21) Error: cannot evaluate at compile time: inp'''
+"""
+
+
+# line 10
+proc getNum(a: int): int = a
+
+let inp = 123
+echo (static getNum(inp))
diff --git a/tests/system/tsystem_misc.nim b/tests/system/tsystem_misc.nim
index 38be01a13..1debb7c48 100644
--- a/tests/system/tsystem_misc.nim
+++ b/tests/system/tsystem_misc.nim
@@ -59,11 +59,6 @@ doAssert high(float) > low(float)
 doAssert high(float32) > low(float32)
 doAssert high(float64) > low(float64)
 
-# bug #6710
-var s = @[1]
-s.delete(0)
-
-
 proc foo(a: openArray[int]) =
   for x in a: echo x
 
@@ -81,13 +76,13 @@ foo(toOpenArray(seqq, 1, 3))
 # empty openArray issue #7904
 foo(toOpenArray(seqq, 0, -1))
 foo(toOpenArray(seqq, 1, 0))
-doAssertRaises(IndexError):
+doAssertRaises(IndexDefect):
   foo(toOpenArray(seqq, 0, -2))
 
 foo(toOpenArray(arr, 9, 8))
 foo(toOpenArray(arr, 0, -1))
 foo(toOpenArray(arr, 1, 0))
-doAssertRaises(IndexError):
+doAssertRaises(IndexDefect):
   foo(toOpenArray(arr, 10, 8))
 
 # test openArray of openArray
@@ -106,11 +101,11 @@ var arrNeg: array[-3 .. -1, int] = [1, 2, 3]
 foo(toOpenArray(arrNeg, -3, -1))
 foo(toOpenArray(arrNeg, 0, -1))
 foo(toOpenArray(arrNeg, -3, -4))
-doAssertRaises(IndexError):
+doAssertRaises(IndexDefect):
   foo(toOpenArray(arrNeg, -4, -1))
-doAssertRaises(IndexError):
+doAssertRaises(IndexDefect):
   foo(toOpenArray(arrNeg, -1, 0))
-doAssertRaises(IndexError):
+doAssertRaises(IndexDefect):
   foo(toOpenArray(arrNeg, -1, -3))
 doAssertRaises(Exception):
   raise newException(Exception, "foo")
@@ -118,9 +113,9 @@ doAssertRaises(Exception):
 block:
   var didThrow = false
   try:
-    doAssertRaises(IndexError): # should fail since it's wrong exception
-      raise newException(FieldError, "foo")
-  except AssertionError:
+    doAssertRaises(IndexDefect): # should fail since it's wrong exception
+      raise newException(FieldDefect, "foo")
+  except AssertionDefect:
     # ok, throwing was correct behavior
     didThrow = true
   doAssert didThrow
@@ -136,12 +131,12 @@ let str = "0123456789"
 foo(toOpenArrayByte(str, 0, str.high))
 
 
-template boundedOpenArray[T](x: seq[T], first, last: int): openarray[T] =
+template boundedOpenArray[T](x: seq[T], first, last: int): openArray[T] =
   toOpenarray(x, max(0, first), min(x.high, last))
 
 # bug #9281
 
-proc foo[T](x: openarray[T]) =
+proc foo[T](x: openArray[T]) =
   echo x.len
 
 let a = @[1, 2, 3]
@@ -184,3 +179,49 @@ proc testMinMax(a,b: float32) =
 
 testMinMax(0.0, NaN)
 testMinMax(NaN, 0.0)
+
+
+block:
+  type Foo = enum
+    k1, k2
+  var
+    a = {k1}
+    b = {k1,k2}
+  doAssert a < b
+
+
+block: # Ordinal
+  doAssert int is Ordinal
+  doAssert uint is Ordinal
+  doAssert int64 is Ordinal
+  doAssert uint64 is Ordinal
+  doAssert char is Ordinal
+  type Foo = enum k1, k2
+  doAssert Foo is Ordinal
+  doAssert Foo is SomeOrdinal
+  doAssert enum is SomeOrdinal
+
+  # these fail:
+  # doAssert enum is Ordinal # fails
+  # doAssert Ordinal is SomeOrdinal
+  # doAssert SomeOrdinal is Ordinal
+
+block:
+  proc p() = discard
+
+  doAssert not compiles(echo p.rawProc.repr)
+  doAssert not compiles(echo p.rawEnv.repr)
+  doAssert not compiles(echo p.finished)
+
+proc bug23223 = # bug #23223
+  var stuff = "hello"
+  stuff.insert ""
+  doAssert stuff == "hello"
+
+bug23223()
+
+block: # bug #23894
+  let v = high(uint) div 2
+  let s = v + 1 # 9223372036854775808
+  let m = succ v
+  doAssert s == m
diff --git a/tests/system/tuse_version16.nim b/tests/system/tuse_version16.nim
new file mode 100644
index 000000000..802b617ad
--- /dev/null
+++ b/tests/system/tuse_version16.nim
@@ -0,0 +1,49 @@
+discard """
+  matrix: "-d:NimMajor=1 -d:NimMinor=6 -d:NimPatch=100"
+"""
+
+{.warning[UnusedImport]: off.}
+
+import std/[
+  # Core:
+  bitops, typetraits, lenientops, macros, volatile,
+
+  # Algorithms:
+  algorithm, sequtils,
+
+  # Collections:
+  critbits, deques, heapqueue, intsets, lists, options, sets,
+  sharedlist, tables,
+
+  # Strings:
+  editdistance, wordwrap, parseutils, ropes,
+  pegs, strformat, strmisc, strscans, strtabs,
+  strutils, unicode, unidecode,
+
+  # Generic operator system services:
+  os, streams,
+
+  # Math libraries:
+  complex, math, mersenne, random, rationals, stats, sums,
+
+  # Internet protocols:
+  httpcore, mimetypes, uri,
+
+  # Parsers:
+  htmlparser, json, lexbase, parsecfg, parsecsv, parsesql, parsexml,
+
+  # XML processing:
+  xmltree, xmlparser,
+
+  # Generators:
+  htmlgen,
+
+  # Hashing:
+  base64, hashes,
+
+  # Miscellaneous:
+  colors, sugar, varints,
+]
+
+
+doAssert NimVersion == "1.6.100"
diff --git a/tests/system/tlenvarargs.nim b/tests/system/tvarargslen.nim
index ca12c8171..24b54a1e0 100644
--- a/tests/system/tlenvarargs.nim
+++ b/tests/system/tvarargslen.nim
@@ -1,9 +1,9 @@
 discard """
   output: '''
-tlenvarargs.nim:35:9 (1, 2)
-tlenvarargs.nim:36:9 12
-tlenvarargs.nim:37:9 1
-tlenvarargs.nim:38:8 
+tvarargslen.nim:35:2 (1, 2)
+tvarargslen.nim:36:2 12
+tvarargslen.nim:37:2 1
+tvarargslen.nim:38:8 
 done
 '''
 """
@@ -14,19 +14,19 @@ template myecho*(a: varargs[untyped]) =
   ## on macros.nim) so can be used in more contexts
   const info = instantiationInfo(-1, false)
   const loc = info.filename & ":" & $info.line & ":" & $info.column & " "
-  when lenVarargs(a) > 0:
+  when varargsLen(a) > 0:
     echo(loc, a)
   else:
     echo(loc)
 
 template fun*(a: varargs[untyped]): untyped =
-  lenVarargs(a)
+  varargsLen(a)
 
 template fun2*(a: varargs[typed]): untyped =
-  a.lenVarargs
+  a.varargsLen
 
 template fun3*(a: varargs[int]): untyped =
-  a.lenVarargs
+  a.varargsLen
 
 template fun4*(a: varargs[untyped]): untyped =
   len(a)
@@ -49,11 +49,12 @@ proc main()=
   doAssert fun3(10) == 1
   doAssert fun3(10, 11) == 2
 
-  ## shows why `lenVarargs` can't be named `len`
+  ## shows why `varargsLen` can't be named `len`
   doAssert fun4("abcdef") == len("abcdef")
 
   ## workaround for BUG:D20191218T171447 whereby if testament expected output ends
   ## in space, testament strips it from expected output but not actual output,
   ## which leads to a mismatch when running test via megatest
   echo "done"
+
 main()
diff --git a/tests/template/m1027a.nim b/tests/template/m1027a.nim
new file mode 100644
index 000000000..fad915a2f
--- /dev/null
+++ b/tests/template/m1027a.nim
@@ -0,0 +1 @@
+const version_str* = "mod a"
diff --git a/tests/template/m1027b.nim b/tests/template/m1027b.nim
new file mode 100644
index 000000000..5ff0b9714
--- /dev/null
+++ b/tests/template/m1027b.nim
@@ -0,0 +1 @@
+const version_str* = "mod b"
diff --git a/tests/template/m19277_1.nim b/tests/template/m19277_1.nim
new file mode 100644
index 000000000..840bd4767
--- /dev/null
+++ b/tests/template/m19277_1.nim
@@ -0,0 +1,2 @@
+template foo*(x: untyped) =
+  echo "got: ", x
diff --git a/tests/template/m19277_2.nim b/tests/template/m19277_2.nim
new file mode 100644
index 000000000..de72dad45
--- /dev/null
+++ b/tests/template/m19277_2.nim
@@ -0,0 +1,2 @@
+proc foo*(a: string) =
+  echo "got string: ", a
diff --git a/tests/template/mdotcall.nim b/tests/template/mdotcall.nim
new file mode 100644
index 000000000..fecd8ee26
--- /dev/null
+++ b/tests/template/mdotcall.nim
@@ -0,0 +1,82 @@
+# issue #20073
+
+type Foo = object
+proc foo(f: Foo) = discard
+
+template works*() =
+  var f: Foo
+  foo(f)
+
+template boom*() =
+  var f: Foo
+  f.foo() # Error: attempting to call undeclared routine: 'foo'
+  f.foo # Error: undeclared field: 'foo' for type a.Foo
+
+# issue #7085
+
+proc bar(a: string): string =
+  return a & "bar"
+
+template baz*(a: string): string =
+  var b = a.bar()
+  b
+
+# issue #7223
+
+import mdotcall2
+
+type
+  Bytes* = seq[byte]
+  
+  BytesRange* = object
+    bytes*: Bytes
+    ibegin*, iend*: int
+
+proc privateProc(r: BytesRange): int = r.ibegin
+
+template rangeBeginAddr*(r: BytesRange): pointer =
+  r.bytes.baseAddr.shift(r.privateProc)
+
+# issue #11733
+
+type ObjA* = object
+
+proc foo2(o: var ObjA) = discard
+proc bar2(o: var ObjA, arg: Natural) = discard
+
+template publicTemplateObjSyntax*(o: var ObjA, arg: Natural, doStuff: untyped) =
+  o.foo2()
+  doStuff
+  o.bar2(arg)
+
+# issue #15246
+import os
+
+template sourceBaseName*(): string =
+  bind splitFile
+  instantiationInfo().filename.splitFile().name
+
+# issue #12683
+
+import unicode
+template toRune(s: string): Rune = s.runeAt(0)
+proc heh*[T](x: Slice[T], chars: string) = discard chars.toRune
+
+# issue #7889
+
+from streams import newStringStream, readData, writeData
+
+template bindmeTemplate*(): untyped =
+  var tst = "sometext"
+  var ss = newStringStream("anothertext")
+  ss.writeData(tst[0].addr, 2)
+  discard ss.readData(tst[0].addr, 2) # <= comment this out to make compilation successful
+
+from macros import quote, newIdentNode
+
+macro bindmeQuote*(): untyped =
+  quote do:
+    var tst = "sometext"
+    var ss = newStringStream("anothertext")
+    ss.writeData(tst[0].addr, 2)
+    discard ss.readData(tst[0].addr, 2) # <= comment this out to make compilation successful
diff --git a/tests/template/mdotcall2.nim b/tests/template/mdotcall2.nim
new file mode 100644
index 000000000..e906ac9d6
--- /dev/null
+++ b/tests/template/mdotcall2.nim
@@ -0,0 +1,7 @@
+# imported by mdotcall
+
+proc baseAddr*[T](x: openarray[T]): pointer =
+  cast[pointer](x)
+
+proc shift*(p: pointer, delta: int): pointer =
+  cast[pointer](cast[int](p) + delta)
diff --git a/tests/template/mqualifiedtype1.nim b/tests/template/mqualifiedtype1.nim
new file mode 100644
index 000000000..46569107f
--- /dev/null
+++ b/tests/template/mqualifiedtype1.nim
@@ -0,0 +1,2 @@
+type A* = object
+  x*: int
diff --git a/tests/template/mqualifiedtype2.nim b/tests/template/mqualifiedtype2.nim
new file mode 100644
index 000000000..6a61c14bd
--- /dev/null
+++ b/tests/template/mqualifiedtype2.nim
@@ -0,0 +1,2 @@
+type A* = object
+  x*: array[1000, byte]
diff --git a/tests/template/otests.nim b/tests/template/otests.nim
index 120146343..9cb9d7fcb 100644
--- a/tests/template/otests.nim
+++ b/tests/template/otests.nim
@@ -163,7 +163,7 @@ when true: #embeddingTest
     """
 
     # Expression template
-    proc test_expression(nums: openarray[int] = []): string =
+    proc test_expression(nums: openArray[int] = []): string =
         var i = 2
         tmpli html"""
             $(no_substitution())
@@ -171,7 +171,7 @@ when true: #embeddingTest
             <div id="age">Age: $($nums[i] & "!!")</div>
         """
 
-    proc test_statements(nums: openarray[int] = []): string =
+    proc test_statements(nums: openArray[int] = []): string =
         tmpli html"""
             $(test_expression(nums))
             $if true {
diff --git a/tests/template/sunset.nimf b/tests/template/sunset.nimf
index 465b12a5e..bd57bb8e1 100644
--- a/tests/template/sunset.nimf
+++ b/tests/template/sunset.nimf
@@ -1,6 +1,6 @@
 #? stdtmpl
 #proc sunsetTemplate*(current, ticker, content: string,
-#                     tabs: openarray[array[0..1, string]]): string = 
+#                     tabs: openArray[array[0..1, string]]): string = 
 #  result = ""
 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
 <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
diff --git a/tests/template/t1027.nim b/tests/template/t1027.nim
new file mode 100644
index 000000000..fe03c4ea9
--- /dev/null
+++ b/tests/template/t1027.nim
@@ -0,0 +1,22 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  errormsg: ""
+  nimout: '''
+t1027.nim(20, 19) Error: ambiguous identifier: 'version_str' -- use one of the following:
+  m1027a.version_str: string
+  m1027b.version_str: string
+'''
+"""
+
+
+
+
+
+
+import m1027a, m1027b
+
+# bug #1027
+template wrap_me(stuff): untyped =
+  echo "Using " & version_str
+
+wrap_me("hey")
diff --git a/tests/template/t11705.nim b/tests/template/t11705.nim
new file mode 100644
index 000000000..65ddc7e6c
--- /dev/null
+++ b/tests/template/t11705.nim
@@ -0,0 +1,17 @@
+type RefObj = ref object
+
+proc `[]`(val: static[int]) = # works with different name/overload or without static arg
+  discard
+
+template noRef*(T: typedesc): typedesc = # works without template indirection
+  typeof(default(T)[])
+
+proc `=destroy`(x: var noRef(RefObj)) =
+  discard
+
+proc foo =
+  var x = new RefObj
+  doAssert $(x[]) == "()"
+
+# bug #11705
+foo()
diff --git a/tests/template/t13426.nim b/tests/template/t13426.nim
new file mode 100644
index 000000000..f7f44749c
--- /dev/null
+++ b/tests/template/t13426.nim
@@ -0,0 +1,87 @@
+discard """
+  cmd: "nim check --hints:off $file"
+  errormsg: ""
+  nimout: '''
+t13426.nim(81, 6) template/generic instantiation of `fun` from here
+t13426.nim(80, 24) Error: type mismatch: got <int> but expected 'string'
+t13426.nim(81, 6) template/generic instantiation of `fun` from here
+t13426.nim(80, 17) Error: type mismatch: got <uint, string>
+but expected one of:
+proc `and`(x, y: uint): uint
+  first type mismatch at position: 2
+  required type for y: uint
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: uint64): uint64
+  first type mismatch at position: 2
+  required type for y: uint64
+  but expression 'high(@[1])' is of type: string
+10 other mismatching symbols have been suppressed; compile with --showAllMismatches:on to see them
+
+expression: 1'u and high(@[1])
+t13426.nim(81, 6) template/generic instantiation of `fun` from here
+t13426.nim(80, 17) Error: expression '' has no type (or is ambiguous)
+t13426.nim(87, 6) template/generic instantiation of `fun` from here
+t13426.nim(86, 22) Error: type mismatch: got <int> but expected 'string'
+t13426.nim(87, 6) template/generic instantiation of `fun` from here
+t13426.nim(86, 15) Error: type mismatch: got <int literal(1), string>
+but expected one of:
+proc `and`(x, y: int): int
+  first type mismatch at position: 2
+  required type for y: int
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: int16): int16
+  first type mismatch at position: 2
+  required type for y: int16
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: int32): int32
+  first type mismatch at position: 2
+  required type for y: int32
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: int64): int64
+  first type mismatch at position: 2
+  required type for y: int64
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: int8): int8
+  first type mismatch at position: 2
+  required type for y: int8
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: uint): uint
+  first type mismatch at position: 2
+  required type for y: uint
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: uint16): uint16
+  first type mismatch at position: 2
+  required type for y: uint16
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: uint32): uint32
+  first type mismatch at position: 2
+  required type for y: uint32
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: uint64): uint64
+  first type mismatch at position: 2
+  required type for y: uint64
+  but expression 'high(@[1])' is of type: string
+proc `and`(x, y: uint8): uint8
+  first type mismatch at position: 2
+  required type for y: uint8
+  but expression 'high(@[1])' is of type: string
+2 other mismatching symbols have been suppressed; compile with --showAllMismatches:on to see them
+
+expression: 1 and high(@[1])
+t13426.nim(87, 6) template/generic instantiation of `fun` from here
+t13426.nim(86, 15) Error: expression '' has no type (or is ambiguous)
+'''
+"""
+
+# bug # #13426
+block:
+  template bar(t): string = high(t)
+  proc fun[A](key: A) =
+    var h = 1'u and bar(@[1])
+  fun(0)
+
+block:
+  template bar(t): string = high(t)
+  proc fun[A](key: A) =
+    var h = 1 and bar(@[1])
+  fun(0)
diff --git a/tests/template/t17433.nim b/tests/template/t17433.nim
new file mode 100644
index 000000000..053d33ff0
--- /dev/null
+++ b/tests/template/t17433.nim
@@ -0,0 +1,16 @@
+# Inside template bodies, ensure return types referencing a param are replaced.
+# This helps guarantee that return parameter analysis happens after argument
+# analysis.
+ 
+# bug #17433
+
+from std/macros import expandMacros
+
+proc bar(a: typedesc): a = default(a)
+doAssert bar(float) == 0.0
+doAssert bar(string) == ""
+
+template main =
+  proc baz(a: typedesc): a = default(a)
+  doAssert baz(float) == 0.0
+main()
diff --git a/tests/template/t18113.nim b/tests/template/t18113.nim
new file mode 100644
index 000000000..a84b3fd0e
--- /dev/null
+++ b/tests/template/t18113.nim
@@ -0,0 +1,14 @@
+# ensure template pragma handling doesn't eagerly attempt to add an implicit
+# 'pushed' pragma to the evaluation of any intermediate AST prior to
+# substitution.
+ 
+# bug #18113
+
+import sequtils
+
+{.push raises: [Defect].}
+
+var a = toSeq([1, 2, 3, 5, 10]).filterIt(it > 5)
+
+doAssert a.len == 1
+doAssert a[0] == 10
diff --git a/tests/template/t19149.nim b/tests/template/t19149.nim
new file mode 100644
index 000000000..631e8fc30
--- /dev/null
+++ b/tests/template/t19149.nim
@@ -0,0 +1,19 @@
+type Foo = tuple[active: bool, index: int]
+
+
+var f: Foo
+
+# template result type during match stage
+# f:var Foo
+# a:Foo
+# tyVar
+# tyTuple
+# after change to proc
+# f:Foo
+# a:Foo
+# tyTuple
+# tyTuple
+
+template cursor(): var Foo = f
+discard cursor()
+
diff --git a/tests/template/t19277.nim b/tests/template/t19277.nim
new file mode 100644
index 000000000..16435a09c
--- /dev/null
+++ b/tests/template/t19277.nim
@@ -0,0 +1,19 @@
+discard """
+  output: '''
+got: 0
+'''
+"""
+
+# issue #19277
+
+import m19277_1, m19277_2
+
+template injector(val: untyped): untyped =
+  template subtemplate: untyped = val
+  subtemplate()
+
+template methodCall(val: untyped): untyped = val
+
+{.push raises: [Defect].}
+
+foo(injector(0).methodCall())
diff --git a/tests/template/t19700.nim b/tests/template/t19700.nim
new file mode 100644
index 000000000..cc2944944
--- /dev/null
+++ b/tests/template/t19700.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "type mismatch: got <Obj, Obj, template (x: untyped, y: untyped): untyped>"
+"""
+
+type Obj = object
+
+proc apply[T, R](a, b: T; f: proc(x, y: T): R): R = f(a, b)
+
+let a, b = Obj()
+discard apply(a, b, `!=`)
diff --git a/tests/template/t21231.nim b/tests/template/t21231.nim
new file mode 100644
index 000000000..51e96cdd6
--- /dev/null
+++ b/tests/template/t21231.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "undeclared identifier: 'x'"
+"""
+
+var x: int
+# bug #21231
+template f(y: untyped) = echo y.x
+for i in 1 .. 10:
+  x = i
+  f(system)
diff --git a/tests/template/t21532.nim b/tests/template/t21532.nim
new file mode 100644
index 000000000..3193b0dc3
--- /dev/null
+++ b/tests/template/t21532.nim
@@ -0,0 +1,8 @@
+
+template elementType(a: untyped): typedesc =
+  typeof(block: (for ai in a: ai))
+
+func fn[T](a: T) =
+  doAssert elementType(a) is int
+
+@[1,2,3].fn
\ No newline at end of file
diff --git a/tests/template/t24112.nim b/tests/template/t24112.nim
new file mode 100644
index 000000000..175fc7d5e
--- /dev/null
+++ b/tests/template/t24112.nim
@@ -0,0 +1,19 @@
+discard """
+  matrix: "--skipParentCfg --filenames:legacyRelProj --hints:off"
+  action: reject
+"""
+
+# issue #24112, needs --experimental:openSym disabled
+
+block: # simplified
+  type
+    SomeObj = ref object # Doesn't error if you make SomeObj be non-ref
+  template foo = yield SomeObj()
+  when compiles(foo): discard
+
+import std/asyncdispatch
+block:
+  proc someProc(): Future[void] {.async.} = discard
+  proc foo() =
+    await someProc() #[tt.Error
+                  ^ Can only 'await' inside a proc marked as 'async'. Use 'waitFor' when calling an 'async' proc in a non-async scope instead]#
diff --git a/tests/template/t6217.nim b/tests/template/t6217.nim
new file mode 100644
index 000000000..b27b61881
--- /dev/null
+++ b/tests/template/t6217.nim
@@ -0,0 +1,19 @@
+discard """
+  output: '''
+start
+side effect!
+end
+'''
+"""
+
+# bug #6217
+
+template optMul{`*`(a, 2)}(a: int{noSideEffect}): int = a+a
+
+proc f(): int =
+  echo "side effect!"
+  result = 55
+
+echo "start"
+doAssert f() * 2 == 110
+echo "end"
diff --git a/tests/template/t9534.nim b/tests/template/t9534.nim
new file mode 100644
index 000000000..8d66f42a0
--- /dev/null
+++ b/tests/template/t9534.nim
@@ -0,0 +1,21 @@
+discard """
+  targets: "c cpp"
+"""
+
+# bug #9534
+type
+  Object = object
+    data: int
+
+template test() =
+  proc methodName(o: Object): int =
+    var p: pointer
+    doAssert o.data == 521
+    let f {.used.} = cast[proc (o: int): int {.nimcall.}](p)
+    doAssert o.data == 521
+    result = 1314
+
+  var a = Object(data: 521)
+  doAssert methodName(a) == 1314
+
+test()
diff --git a/tests/template/taliassyntax.nim b/tests/template/taliassyntax.nim
new file mode 100644
index 000000000..2d8237d93
--- /dev/null
+++ b/tests/template/taliassyntax.nim
@@ -0,0 +1,74 @@
+type Foo = object
+  bar: int
+
+var foo = Foo(bar: 10)
+template bar: int = foo.bar
+doAssert bar == 10
+bar = 15
+doAssert bar == 15
+var foo2 = Foo(bar: -10)
+doAssert bar == 15
+# works in generics
+proc genericProc[T](x: T): string =
+  $(x, bar)
+doAssert genericProc(true) == "(true, 15)"
+# redefine
+template bar: int {.redefine.} = foo2.bar
+doAssert bar == -10
+
+block: # subscript
+  var bazVal = @[1, 2, 3]
+  template baz: seq[int] = bazVal
+  doAssert baz[1] == 2
+  proc genericProc2[T](x: T): string =
+    result = $(x, baz[1])
+    baz[1] = 7
+  doAssert genericProc2(true) == "(true, 2)"
+  doAssert baz[1] == 7
+  baz[1] = 14
+  doAssert baz[1] == 14
+
+block: # type alias
+  template Int2: untyped = int
+  let x: Int2 = 123
+  proc generic[T](): string =
+    template U: untyped = T
+    var x: U
+    result = $typeof(x)
+    doAssert result == $U
+    doAssert result == $T
+  doAssert generic[int]() == "int"
+  doAssert generic[Int2]() == "int"
+  doAssert generic[string]() == "string"
+  doAssert generic[seq[int]]() == "seq[int]"
+  doAssert generic[seq[Int2]]() == "seq[int]"
+  discard generic[123]()
+  proc genericStatic[X; T: static[X]](): string =
+    template U: untyped = T
+    result = $U
+    doAssert result == $T
+  doAssert genericStatic[int, 123]() == "123"
+  doAssert genericStatic[Int2, 123]() == "123"
+  doAssert genericStatic[(string, bool), ("a", true)]() == "(\"a\", true)"
+
+block: # issue #13515
+  template test: bool = true
+  # compiles:
+  if not test:
+    doAssert false
+  # does not compile:
+  template x =
+    if not test:
+      doAssert false
+  x
+
+import macros
+
+block: # issue #21727
+  template debugAnnotation(s: typed): string =
+    astToStr s
+
+  macro cpsJump(x: int): untyped =
+    result = newLit(debugAnnotation(cpsJump))
+  
+  doAssert cpsJump(13) == "cpsJump"
diff --git a/tests/template/taliassyntaxerrors.nim b/tests/template/taliassyntaxerrors.nim
new file mode 100644
index 000000000..f16acaf91
--- /dev/null
+++ b/tests/template/taliassyntaxerrors.nim
@@ -0,0 +1,28 @@
+discard """
+  cmd: "nim check --hints:off $file"
+"""
+
+block: # with params
+  type Foo = object
+    bar: int
+
+  var foo = Foo(bar: 10)
+  template bar(x: int): int = x + foo.bar
+  let a = bar #[tt.Error
+      ^ invalid type: 'template (x: int): int' for let. Did you mean to call the template with '()'?]#
+  bar = 15 #[tt.Error
+  ^ 'bar' cannot be assigned to]#
+
+block: # generic template
+  type Foo = object
+    bar: int
+
+  var foo = Foo(bar: 10)
+  template bar[T]: T = T(foo.bar)
+  let a = bar #[tt.Error
+      ^ invalid type: 'template (): T' for let. Did you mean to call the template with '()'?; tt.Error
+          ^ 'bar' has unspecified generic parameters]#
+  let b = bar[float]()
+  doAssert b == 10.0
+  bar = 15 #[tt.Error
+  ^ 'bar' cannot be assigned to]#
diff --git a/tests/template/tcallsitelineinfo.nim b/tests/template/tcallsitelineinfo.nim
new file mode 100644
index 000000000..5fed93363
--- /dev/null
+++ b/tests/template/tcallsitelineinfo.nim
@@ -0,0 +1,17 @@
+discard """
+  nimout: '''
+tcallsitelineinfo.nim(17, 4) Warning: abc [User]
+'''
+  exitcode: 1
+  outputsub: '''
+tcallsitelineinfo.nim(17) tcallsitelineinfo
+Error: unhandled exception: def [ValueError]
+'''
+"""
+
+template foo(): untyped {.callsite.} =
+  {.warning: "abc".}
+  raise newException(ValueError, "def")
+  echo "hello"
+
+foo()
diff --git a/tests/template/tcallsitelineinfo2.nim b/tests/template/tcallsitelineinfo2.nim
new file mode 100644
index 000000000..d5f257474
--- /dev/null
+++ b/tests/template/tcallsitelineinfo2.nim
@@ -0,0 +1,20 @@
+discard """
+  nimout: '''
+tcallsitelineinfo2.nim(18, 1) Warning: abc [User]
+tcallsitelineinfo2.nim(19, 12) Warning: def [User]
+'''
+  exitcode: 1
+  outputsub: '''
+tcallsitelineinfo2.nim(20) tcallsitelineinfo2
+Error: unhandled exception: ghi [ValueError]
+'''
+"""
+
+template foo(a: untyped): untyped {.callsite.} =
+  {.warning: "abc".}
+  a
+  echo "hello"
+
+foo: # with `{.line.}:`, the following do not keep their line information:
+  {.warning: "def".}
+  raise newException(ValueError, "ghi")
diff --git a/tests/template/tdefaultparam.nim b/tests/template/tdefaultparam.nim
new file mode 100644
index 000000000..7ea0b2b25
--- /dev/null
+++ b/tests/template/tdefaultparam.nim
@@ -0,0 +1,56 @@
+block:
+  template foo(a: untyped, b: untyped = a(0)): untyped =
+    let x = a(0)
+    let y = b
+    (x, y)
+  proc bar(x: int): int = x + 1
+  doAssert foo(bar, b = bar(0)) == (1, 1)
+  doAssert foo(bar) == (1, 1)
+
+block: # issue #23506
+  var a: string
+  template foo(x: int; y = x) =
+    a = $($x, $y)
+  foo(1)
+  doAssert a == "(\"1\", \"1\")"
+
+block: # untyped params with default value
+  macro foo(x: typed): untyped =
+    result = x
+  template test(body: untyped, alt: untyped = (;), maxTries = 3): untyped {.foo.} =
+    body
+    alt
+  var s = "a"
+  test:
+    s.add "b"
+  do:
+    s.add "c"
+  doAssert s == "abc"
+  template test2(body: untyped, alt: untyped = s.add("e"), maxTries = 3): untyped =
+    body
+    alt
+  test2:
+    s.add "d"
+  doAssert s == "abcde"
+  template test3(body: untyped = willNotCompile) =
+    discard
+  test3()
+
+block: # typed params with `void` default value
+  macro foo(x: typed): untyped =
+    result = x
+  template test(body: untyped, alt: typed = (;), maxTries = 3): untyped {.foo.} =
+    body
+    alt
+  var s = "a"
+  test:
+    s.add "b"
+  do:
+    s.add "c"
+  doAssert s == "abc"
+  template test2(body: untyped, alt: typed = s.add("e"), maxTries = 3): untyped =
+    body
+    alt
+  test2:
+    s.add "d"
+  doAssert s == "abcde"
diff --git a/tests/template/tdotcall.nim b/tests/template/tdotcall.nim
new file mode 100644
index 000000000..dc97fd52e
--- /dev/null
+++ b/tests/template/tdotcall.nim
@@ -0,0 +1,32 @@
+import mdotcall
+
+block: # issue #20073
+  works()
+  boom()
+
+block: # issue #7085
+  doAssert baz("hello") == "hellobar"
+  doAssert baz"hello" == "hellobar"
+  doAssert "hello".baz == "hellobar"
+
+block: # issue #7223
+  var r = BytesRange(bytes: @[1.byte, 2, 3], ibegin: 0, iend: 2)
+  var a = r.rangeBeginAddr
+
+block: # issue #11733
+  var a: ObjA
+  var evaluated = false
+  a.publicTemplateObjSyntax(42): evaluated = true
+  doAssert evaluated
+
+block: # issue #15246
+  doAssert sourceBaseName() == "tdotcall"
+
+block: # issue #12683
+  heh(0..40, "|")
+
+block: # issue #7889
+  if false:
+    bindmeQuote()
+  if false:
+    bindmeTemplate()
diff --git a/tests/template/template_issues.nim b/tests/template/template_issues.nim
index e56d44480..58c40941d 100644
--- a/tests/template/template_issues.nim
+++ b/tests/template/template_issues.nim
@@ -8,6 +8,11 @@ hi
 Hello, World!
 (e: 42)
 hey
+foo
+foo
+foo
+false
+true
 '''
 """
 
@@ -168,7 +173,7 @@ block t2585:
       st
       echo "a ", $fb
 
-  proc render(rdat: var RenderData; passes: var openarray[RenderPass]; proj: Mat2;
+  proc render(rdat: var RenderData; passes: var openArray[RenderPass]; proj: Mat2;
               indexType = 1) =
       for i in 0 ..< len(passes):
           echo "blah ", repr(passes[i])
@@ -245,3 +250,55 @@ proc foo(): auto =
     echo "hey"
 
 discard foo()
+
+
+# bug #4722
+type
+  IteratorF*[In] = iterator() : In {.closure.}
+
+template foof(In: untyped) : untyped =
+  proc ggg*(arg: IteratorF[In]) =
+    for i in arg():
+      echo "foo"
+
+
+iterator hello() : int {.closure.} =
+  for i in 1 .. 3:
+    yield i
+
+foof(int)
+ggg(hello)
+
+
+# bug #2586
+var z = 10'u8
+echo z < 9 # Works
+echo z > 9 # Error: type mismatch
+
+
+# bug #5993
+template foo(p: proc) =
+  var bla = 5
+  p(bla)
+
+foo() do(t: var int):
+  discard
+  t = 5
+
+proc bar(t: var int) =
+  t = 5
+
+foo(bar)
+
+block: # bug #12595
+  template test() =
+    let i = 42
+    discard {i: ""}
+
+  test()
+
+block: # bug #21920
+  template t[T](): T =
+    discard
+
+  t[void]() # Error: expression has no type: discard
diff --git a/tests/template/template_pragmas.nim b/tests/template/template_pragmas.nim
index d6c99080d..da532b010 100644
--- a/tests/template/template_pragmas.nim
+++ b/tests/template/template_pragmas.nim
@@ -3,7 +3,7 @@ proc output_x:string {.compileTime.} = "x"
 template t =
   const x = output_x()
   let
-    bar {.exportC:"bar" & x.} = 100
+    bar {.exportc:"bar" & x.} = 100
 
 static:
   doAssert(compiles (t()))
diff --git a/tests/template/template_various.nim b/tests/template/template_various.nim
index ac7e91fa2..2088b1739 100644
--- a/tests/template/template_various.nim
+++ b/tests/template/template_various.nim
@@ -10,6 +10,28 @@ bar7
 4true
 132
 20
+1
+-1
+4
+11
+26
+57
+-1-1-1
+  4
+4
+  4
+  11
+11
+  4
+  11
+  26
+26
+  4
+  11
+  26
+  57
+57
+-1-1-1
 '''
 """
 
@@ -72,7 +94,7 @@ block generic_templates:
 
   var i3: int = t1[int]("xx")
 
-
+from strutils import contains
 
 block tgetast_typeliar:
   proc error(s: string) = quit s
@@ -85,11 +107,13 @@ block tgetast_typeliar:
           error("Assertion failed: " & $(`message`) & "\n" & `line`)
           return
 
-  macro assertOrReturn(condition: bool): typed =
+  macro assertOrReturn(condition: bool) =
     var message : NimNode = newLit(condition.repr)
     # echo message
     result = getAst assertOrReturn2(condition, message)
-    echo result.repr
+    # echo result.repr
+    let s = result.repr
+    doAssert """error("Assertion failed:""" in s
 
   proc point(size: int16): tuple[x, y: int16] =
     # returns random point in square area with given `size`
@@ -245,3 +269,138 @@ template parse9(body: untyped): untyped =
 
 parse9:
   echo val9("1")
+
+
+block gensym1:
+  template x: untyped = -1
+  template t1() =
+    template x: untyped {.gensym, redefine.} = 1
+    echo x()  # 1
+  template t2() =
+    template x: untyped {.redefine.} = 1  # defaults to {.inject.}
+    echo x()  # -1  injected x not available during template definition
+  t1()
+  t2()
+
+block gensym2:
+  let x,y,z = -1
+  template `!`(xx,yy: typed): untyped =
+    template x: untyped {.gensym.} = xx
+    template y: untyped {.gensym.} = yy
+    let z = x + x + y
+    z
+  var
+    a = 1
+    b = 2
+    c = 3
+    d = 4
+    e = 5
+  echo a ! b
+  echo a ! b ! c
+  echo a ! b ! c ! d
+  echo a ! b ! c ! d ! e
+  echo x,y,z
+
+block gensym3:
+  macro liftStmts(body: untyped): auto =
+    # convert
+    #   template x: untyped {.gensym.} =
+    #     let z = a + a + b
+    #     echo z
+    #     z
+    # to
+    #   let z = a + a + b
+    #   echo z
+    #   template x: untyped {.gensym.} =
+    #     z
+    #echo body.repr
+    body.expectKind nnkStmtList
+    result = newNimNode nnkStmtList
+    for s in body:
+      s.expectKind nnkTemplateDef
+      var sle = s[6]
+      while sle.kind == nnkStmtList:
+        doAssert(sle.len==1)
+        sle = sle[0]
+      if sle.kind == nnkStmtListExpr:
+        let n = sle.len
+        for i in 0..(n-2):
+          result.add sle[i]
+        var td = newNimNode nnkTemplateDef
+        for i in 0..5:
+          td.add s[i]
+        td.add sle[n-1]
+        result.add td
+      else:
+        result.add s
+    #echo result.repr
+  let x,y,z = -1
+  template `!`(xx,yy: typed): untyped =
+    liftStmts:
+      template x: untyped {.gensym.} = xx
+      template y: untyped {.gensym.} = yy
+    let z = x + x + y
+    echo "  ", z
+    z
+  var
+    a = 1
+    b = 2
+    c = 3
+    d = 4
+    e = 5
+  echo a ! b
+  echo a ! b ! c
+  echo a ! b ! c ! d
+  echo a ! b ! c ! d ! e
+  echo x,y,z
+
+block: # issue #2465
+  template t() =
+    template declX(str: string) {.gensym.} =
+      var x {.inject.} : string = str
+
+  t()
+  doAssert not declared(declX)
+  doAssert not compiles(declX("a string"))
+
+  template t2() =
+    template fooGensym() {.gensym.} =
+      echo 42
+
+  t2()
+  doAssert not declared(fooGensym)
+  doAssert not compiles(fooGensym())
+
+
+block identifier_construction_with_overridden_symbol:
+  # could use add, but wanna make sure it's an override no matter what
+  func examplefn = discard
+  func examplefn(x: int) = discard
+
+  # the function our template wants to use
+  func examplefn1 = discard
+
+  template exampletempl(n) =
+    # attempt to build a name using the overridden symbol "examplefn"
+    `examplefn n`()
+
+  exampletempl(1)
+
+import typetraits
+
+block: # issue #4596
+  type
+    T0 = object
+    T1 = object
+
+  template printFuncsT() =
+    proc getV[A](a: typedesc[A]): string =
+      var s {. global .} = name(A)
+      return s
+
+  printFuncsT()
+
+  doAssert getV(T1) == "T1"
+  doAssert getV(T0) == "T0"
+  doAssert getV(T0) == "T0"
+  doAssert getV(T1) == "T1"
diff --git a/tests/template/tgenericparam.nim b/tests/template/tgenericparam.nim
new file mode 100644
index 000000000..becf75d36
--- /dev/null
+++ b/tests/template/tgenericparam.nim
@@ -0,0 +1,93 @@
+block: # basic template generic parameter substitution
+  block: # issue #13527
+    template typeNameTempl[T](a: T): string = $T
+    proc typeNameProc[T](a: T): string = $T
+    doAssert typeNameTempl(1) == typeNameProc(1)
+    doAssert typeNameTempl(true) == typeNameProc(true)
+    doAssert typeNameTempl(1.0) == typeNameProc(1.0)
+    doAssert typeNameTempl(1u8) == typeNameProc(1u8)
+
+    template isDefault[T](a: T): bool = a == default(T)
+    doAssert isDefault(0.0)
+
+  block: # issue #17240
+    func to(c: int, t: typedesc[float]): t = discard
+    template converted[I, T](i: seq[I], t: typedesc[T]): seq[T] =
+      var result = newSeq[T](2)
+      result[0] = i[0].to(T)
+      result
+    doAssert newSeq[int](3).converted(float) == @[0.0, 0.0]
+
+  block: # issue #6340
+    type A[T] = object
+      v: T
+    proc foo(x: int): string = "int"
+    proc foo(x: typedesc[int]): string = "typedesc[int]"
+    template fooT(x: int): string = "int"
+    template fooT(x: typedesc[int]): string = "typedesc[int]"
+    proc foo[T](x: A[T]): (string, string) =
+      (foo(T), fooT(T))
+    template fooT[T](x: A[T]): (string, string) =
+      (foo(T), fooT(T))
+    var x: A[int]
+    doAssert foo(x) == fooT(x)
+
+  block: # issue #20033
+    template run[T](): T = default(T)
+    doAssert run[int]() == 0
+
+import options, tables, typetraits
+
+block: # complex cases of above with imports
+  block: # issue #19576, complex case
+    type RegistryKey = object
+      key, val: string
+    var regKey = @[RegistryKey(key: "abc", val: "def")]
+    template findFirst[T](s: seq[T], pred: proc(x: T): bool): Option[T] =
+      var res = none(T) # important line
+      for x in s:
+        if pred(x):
+          res = some(x)
+          break
+      res
+    proc getval(searchKey: string): Option[string] =
+      let found = regKey.findFirst(proc (rk: RegistryKey): bool = rk.key == searchKey)
+      if found.isNone: none(string)
+      else: some(found.get().val)
+    doAssert getval("strange") == none(string)
+    doAssert getval("abc") == some("def")
+  block: # issue #19076
+    block: # case 1
+      var tested: Table[string,int]
+      template `[]`[V](t:Table[string,V],key:string):untyped =
+        $V
+      doAssert tested["abc"] == "int"
+      template `{}`[V](t:Table[string,V],key:string):untyped =
+        ($V, tables.`[]`(t, key))
+      doAssert (try: tested{"abc"} except KeyError: ("not there", 123)) == ("not there", 123)
+      tables.`[]=`(tested, "abc", 456)
+      doAssert tested["abc"] == "int"
+      doAssert tested{"abc"} == ("int", 456)
+    block: # case 2
+      type Foo[A,T] = object
+        t:T
+      proc init[A,T](f:type Foo,a:typedesc[A],t:T):Foo[A,T] = Foo[A,T](t:t)
+      template fromOption[A](o:Option[A]):auto =
+        when o.isSome:
+          Foo.init(A,35)
+        else:
+          Foo.init(A,"hi")
+      let op = fromOption(some(5))
+  block: # issue #7461
+    template p[T](): untyped = none(T)
+    doAssert p[int]() == none(int)
+  block: # issue #7995
+    var res: string
+    template copyRange[T](dest: seq[T], destOffset: int) =
+      when supportsCopyMem(T):
+        res = "A"
+      else:    
+        res = "B"
+    var a = @[1, 2, 3]
+    copyRange(a, 0)
+    doAssert res == "A"
diff --git a/tests/template/tgensym_instantiationinfo.nim b/tests/template/tgensym_instantiationinfo.nim
index 305e7e1c3..4b997ed6a 100644
--- a/tests/template/tgensym_instantiationinfo.nim
+++ b/tests/template/tgensym_instantiationinfo.nim
@@ -5,7 +5,7 @@ discard """
 # bug #7937
 
 template printError(error: typed) =
-  # Error: inconsistent typing for reintroduced symbol 'instInfo': previous type was: tuple[filename: string, line: int, column: int]; new type is: tuple of (string, int, int)
+  # Error: inconsistent typing for reintroduced symbol 'instInfo': previous type was: tuple[filename: string, line: int, column: int]; new type is: (string, int, int)
   let instInfo {.gensym.} = instantiationInfo()
   echo "Error at ", instInfo.filename, ':', instInfo.line, ": ", error
 
diff --git a/tests/template/tgensymhijack.nim b/tests/template/tgensymhijack.nim
new file mode 100644
index 000000000..72ff3d495
--- /dev/null
+++ b/tests/template/tgensymhijack.nim
@@ -0,0 +1,37 @@
+# issue #23326
+
+type Result*[E] = object
+  e*: E
+
+proc error*[E](v: Result[E]): E = discard
+
+template valueOr*[E](self: Result[E], def: untyped): int =
+  when E isnot void:
+    when false:
+      # Comment line below to make it work
+      template error(): E {.used, gensym.} = s.e
+      discard
+    else:
+      template error(): E {.used, inject.} =
+        self.e
+
+      def
+  else:
+    def
+
+
+block:
+  let rErr = Result[string](e: "a")
+  let rErrV = rErr.valueOr:
+    ord(error[0])
+
+block:
+  template foo(x: static bool): untyped =
+    when x:
+      let a = 123
+    else:
+      template a: untyped {.gensym.} = 456
+    a
+  
+  doAssert foo(false) == 456
+  doAssert foo(true) == 123
diff --git a/tests/template/tgensymregression.nim b/tests/template/tgensymregression.nim
index a743d3a08..2a5dca934 100644
--- a/tests/template/tgensymregression.nim
+++ b/tests/template/tgensymregression.nim
@@ -1,8 +1,6 @@
 discard """
   output: '''[0.0, 0.0, 0.0]
-
 [0.0, 0.0, 0.0, 0.0]
-
 5050
 123'''
 """
@@ -57,7 +55,7 @@ converter int2string(x: int): string = $x
 template wrap(body: typed): untyped =
   body
 
-macro makeProc(): typed =
+macro makeProc() =
   # Make a template tree
   result = quote do:
     proc someProc* =
diff --git a/tests/misc/tidentconcatenations.nim b/tests/template/tidentconcatenations.nim
index ddd2e49cc..ddd2e49cc 100644
--- a/tests/misc/tidentconcatenations.nim
+++ b/tests/template/tidentconcatenations.nim
diff --git a/tests/template/tinnerouterproc.nim b/tests/template/tinnerouterproc.nim
new file mode 100644
index 000000000..56e0d02df
--- /dev/null
+++ b/tests/template/tinnerouterproc.nim
@@ -0,0 +1,20 @@
+block: # #20002
+  proc bar(x: int): int = 10
+  template foo =
+    proc bar(x: int): int {.gensym.} = x + 2
+    doAssert bar(3) == 5
+    discard 3.bar # evaluates to 10 but only check if it compiles for now
+  block:
+    foo()
+
+block: # issue #23813
+  template r(body: untyped) =
+    proc x() {.gensym.} =
+      body
+  template g() =
+    r:
+      let y = 0
+    r:
+      proc y() = discard
+      y()
+  g()
diff --git a/tests/template/tmodulealias.nim b/tests/template/tmodulealias.nim
index 6681379fb..79b5ec9c6 100644
--- a/tests/template/tmodulealias.nim
+++ b/tests/template/tmodulealias.nim
@@ -7,7 +7,7 @@ when defined(windows):
 else:
   import posix
 
-when defined(Windows):
+when defined(windows):
   template orig: expr =
     winlean
 else:
diff --git a/tests/template/tnested.nim b/tests/template/tnested.nim
new file mode 100644
index 000000000..81e416a76
--- /dev/null
+++ b/tests/template/tnested.nim
@@ -0,0 +1,38 @@
+block: # issue #22775
+  proc h(c: int) = discard
+  template k(v: int) =
+    template p() = v.h()
+    p()
+  let a = @[0]
+  k(0 and not a[0])
+
+block: # issue #22775 case 2
+  proc h(c: int, q: int) = discard
+  template k(v: int) =
+    template p() = h(v, v)
+    p()
+  let a = [0]
+  k(0 and not a[0])
+
+block: # issue #22775 minimal cases
+  proc h(c: int) = discard
+  template k(v: int) =
+    template p() = h(v)
+    p()
+  let a = [0]
+  k(not a[0])
+  block:
+    k(-a[0])
+  block:
+    proc f(x: int): int = x
+    k(f a[0])
+
+block: # bracket assignment case of above tests
+  proc h(c: int) = discard
+  template k(v: int) =
+    template p() = h(v)
+    p()
+  var a = [0]
+  k(not (block:
+    a[0] = 1
+    1))
diff --git a/tests/template/tobjectdeclfield.nim b/tests/template/tobjectdeclfield.nim
new file mode 100644
index 000000000..afce2cae8
--- /dev/null
+++ b/tests/template/tobjectdeclfield.nim
@@ -0,0 +1,21 @@
+block: # issue #16005
+  var x = 0
+
+  block:
+    type Foo = object
+      x: float # ok
+
+  template main() =
+    block:
+      type Foo = object
+        x: float # Error: cannot use symbol of kind 'var' as a 'field'
+
+  main()
+
+block: # issue #19552
+  template test =
+    type
+      test2 = ref object
+        reset: int
+
+  test()
diff --git a/tests/template/topensym.nim b/tests/template/topensym.nim
new file mode 100644
index 000000000..2f930407b
--- /dev/null
+++ b/tests/template/topensym.nim
@@ -0,0 +1,209 @@
+{.experimental: "openSym".}
+
+block: # issue #24002
+  type Result[T, E] = object
+  func value[T, E](self: Result[T, E]): T {.inline.} =
+    discard
+  func value[T: not void, E](self: var Result[T, E]): var T {.inline.} =
+    discard
+  template unrecognizedFieldWarning =
+    doAssert value == 123
+    let x = value
+    doAssert value == x
+  proc readValue(value: var int) =
+    unrecognizedFieldWarning()
+  var foo: int = 123
+  readValue(foo)
+
+block: # issue #22605 for templates, normal call syntax
+  const error = "bad"
+
+  template valueOr(self: int, def: untyped): untyped =
+    case false
+    of true: ""
+    of false:
+      template error: untyped {.used, inject.} = "good"
+      def
+
+  template g(T: type): string =
+    var res = "ok"
+    let x = valueOr 123:
+      res = $error
+      "dummy"
+    res
+
+  doAssert g(int) == "good"
+
+  template g2(T: type): string =
+    bind error # use the bad version on purpose
+    var res = "ok"
+    let x = valueOr 123:
+      res = $error
+      "dummy"
+    res
+
+  doAssert g2(int) == "bad"
+
+block: # issue #22605 for templates, method call syntax
+  const error = "bad"
+
+  template valueOr(self: int, def: untyped): untyped =
+    case false
+    of true: ""
+    of false:
+      template error: untyped {.used, inject.} = "good"
+      def
+
+  template g(T: type): string =
+    var res = "ok"
+    let x = 123.valueOr:
+      res = $error
+      "dummy"
+    res
+
+  doAssert g(int) == "good"
+
+  template g2(T: type): string =
+    bind error # use the bad version on purpose
+    var res = "ok"
+    let x = 123.valueOr:
+      res = $error
+      "dummy"
+    res
+
+  doAssert g2(int) == "bad"
+
+block: # issue #22605 for templates, original complex example
+  type Xxx = enum
+    error
+    value
+
+  type
+    Result[T, E] = object
+      when T is void:
+        when E is void:
+          oResultPrivate*: bool
+        else:
+          case oResultPrivate*: bool
+          of false:
+            eResultPrivate*: E
+          of true:
+            discard
+      else:
+        when E is void:
+          case oResultPrivate*: bool
+          of false:
+            discard
+          of true:
+            vResultPrivate*: T
+        else:
+          case oResultPrivate*: bool
+          of false:
+            eResultPrivate*: E
+          of true:
+            vResultPrivate*: T
+
+  template valueOr[T: not void, E](self: Result[T, E], def: untyped): untyped =
+    let s = (self) # TODO avoid copy
+    case s.oResultPrivate
+    of true:
+      s.vResultPrivate
+    of false:
+      when E isnot void:
+        template error: untyped {.used, inject.} = s.eResultPrivate
+      def
+
+  proc f(): Result[int, cstring] =
+    Result[int, cstring](oResultPrivate: false, eResultPrivate: "f")
+
+  template g(T: type): string =
+    var res = "ok"
+    let x = f().valueOr:
+      res = $error
+      123
+    res
+
+  doAssert g(int) == "f"
+
+  template g2(T: type): string =
+    bind error # use the bad version on purpose
+    var res = "ok"
+    let x = f().valueOr:
+      res = $error
+      123
+    res
+
+  doAssert g2(int) == "error"
+
+block: # issue #23865 for templates
+  type Xxx = enum
+    error
+    value
+
+  type
+    Result[T, E] = object
+      when T is void:
+        when E is void:
+          oResultPrivate: bool
+        else:
+          case oResultPrivate: bool
+          of false:
+            eResultPrivate: E
+          of true:
+            discard
+      else:
+        when E is void:
+          case oResultPrivate: bool
+          of false:
+            discard
+          of true:
+            vResultPrivate: T
+        else:
+          case oResultPrivate: bool
+          of false:
+            eResultPrivate: E
+          of true:
+            vResultPrivate: T
+
+  func error[T, E](self: Result[T, E]): E =
+    ## Fetch error of result if set, or raise Defect
+    case self.oResultPrivate
+    of true:
+      when T isnot void:
+        raiseResultDefect("Trying to access error when value is set", self.vResultPrivate)
+      else:
+        raiseResultDefect("Trying to access error when value is set")
+    of false:
+      when E isnot void:
+        self.eResultPrivate
+
+  template valueOr[T: not void, E](self: Result[T, E], def: untyped): untyped =
+    let s = (self) # TODO avoid copy
+    case s.oResultPrivate
+    of true:
+      s.vResultPrivate
+    of false:
+      when E isnot void:
+        template error: untyped {.used, inject.} = s.eResultPrivate
+      def
+  proc f(): Result[int, cstring] =
+    Result[int, cstring](oResultPrivate: false, eResultPrivate: "f")
+  template g(T: type): string =
+    var res = "ok"
+    let x = f().valueOr:
+      res = $error
+      123
+    res
+  doAssert g(int) == "f"
+
+import std/sequtils
+
+block: # issue #15314
+  var it: string
+  var nums = @[1,2,3]
+
+  template doubleNums() =
+    nums.applyIt(it * 2)
+
+  doubleNums()
+  doAssert nums == @[2, 4, 6]
diff --git a/tests/template/topensymoverride.nim b/tests/template/topensymoverride.nim
new file mode 100644
index 000000000..3d4bb59f1
--- /dev/null
+++ b/tests/template/topensymoverride.nim
@@ -0,0 +1,39 @@
+discard """
+  matrix: "--skipParentCfg --filenames:legacyRelProj"
+"""
+
+const value = "captured"
+template fooOld(x: int, body: untyped): untyped =
+  let value {.inject.} = "injected"
+  body
+template foo(x: int, body: untyped): untyped =
+  let value {.inject.} = "injected"
+  {.push experimental: "genericsOpenSym".}
+  body
+  {.pop.}
+
+proc old[T](): string =
+  fooOld(123):
+    return value
+doAssert old[int]() == "captured"
+
+template oldTempl(): string =
+  block:
+    var res: string
+    fooOld(123):
+      res = value
+    res
+doAssert oldTempl() == "captured"
+
+proc bar[T](): string =
+  foo(123):
+    return value
+doAssert bar[int]() == "injected"
+
+template barTempl(): string =
+  block:
+    var res: string
+    foo(123):
+      res = value
+    res
+doAssert barTempl() == "injected"
diff --git a/tests/template/topensymwarning.nim b/tests/template/topensymwarning.nim
new file mode 100644
index 000000000..0bbe0a9fb
--- /dev/null
+++ b/tests/template/topensymwarning.nim
@@ -0,0 +1,60 @@
+discard """
+  matrix: "--skipParentCfg --filenames:legacyRelProj"
+"""
+
+type Xxx = enum
+  error
+  value
+
+type
+  Result[T, E] = object
+    when T is void:
+      when E is void:
+        oResultPrivate*: bool
+      else:
+        case oResultPrivate*: bool
+        of false:
+          eResultPrivate*: E
+        of true:
+          discard
+    else:
+      when E is void:
+        case oResultPrivate*: bool
+        of false:
+          discard
+        of true:
+          vResultPrivate*: T
+      else:
+        case oResultPrivate*: bool
+        of false:
+          eResultPrivate*: E
+        of true:
+          vResultPrivate*: T
+
+template valueOr[T: not void, E](self: Result[T, E], def: untyped): untyped =
+  let s = (self) # TODO avoid copy
+  case s.oResultPrivate
+  of true:
+    s.vResultPrivate
+  of false:
+    when E isnot void:
+      template error: untyped {.used, inject.} = s.eResultPrivate
+    def
+
+proc f(): Result[int, cstring] =
+  Result[int, cstring](oResultPrivate: false, eResultPrivate: "f")
+
+template g(T: type): string =
+  var res = "ok"
+  let x = f().valueOr:
+    {.push warningAsError[IgnoredSymbolInjection]: on.}
+    # test spurious error
+    discard true
+    let _ = f
+    {.pop.}
+    res = $error #[tt.Warning
+           ^ a new symbol 'error' has been injected during template or generic instantiation, however 'error' [enumField declared in topensymwarning.nim(6, 3)] captured at the proc declaration will be used instead; either enable --experimental:openSym to use the injected symbol, or `bind` this captured symbol explicitly [IgnoredSymbolInjection]]#
+    123
+  res
+
+discard g(int)
diff --git a/tests/template/tparams_gensymed.nim b/tests/template/tparams_gensymed.nim
index a35d878d5..b559c2d9e 100644
--- a/tests/template/tparams_gensymed.nim
+++ b/tests/template/tparams_gensymed.nim
@@ -15,6 +15,8 @@ wth
 0
 (total: 6)
 S1
+5
+abc
 '''
 """
 # bug #1915
@@ -71,7 +73,7 @@ proc concreteProc(x: int) =
   forStatic i, 0..3:
     echo i
 
-proc genericProc(x: any) =
+proc genericProc(x: auto) =
   forStatic i, 0..3:
     echo i
 
@@ -195,3 +197,209 @@ mystate_machine:
   state_push(S1)
   echo state_current()
   state_pop()
+
+# bug #15075
+block: #Doesn't work
+  template genGenTempl: untyped =
+    proc loop(locals: int)
+    proc loop(locals: int) = discard
+  genGenTempl()
+  let pool = loop
+
+block: #Doesn't work
+  macro genGenMacro: untyped =
+    quote do:
+      proc loop(locals: int)
+      proc loop(locals: int) = discard
+  genGenMacro()
+  let pool = loop
+
+block: #This works
+  proc loop(locals: int)
+  proc loop(locals: int) = discard
+  let pool = loop
+
+#Now somewhat recursive:
+type Cont = ref object of RootObj
+  fn*: proc(c: Cont): Cont {.nimcall.}
+
+block: #Doesn't work
+  template genGenTempl(): untyped =
+    proc loop(locals: Cont): Cont
+    proc loop(locals: Cont): Cont =
+      return Cont(fn: loop)
+    proc doServer(): Cont =
+      return Cont(fn: loop)
+  genGenTempl()
+  discard doServer()
+
+block: #Doesn't work
+  macro genGenMacro(): untyped =
+    quote:
+      proc loop(locals: Cont): Cont
+      proc loop(locals: Cont): Cont =
+        return Cont(fn: loop)
+      proc doServer(): Cont =
+        return Cont(fn: loop)
+  genGenMacro()
+  discard doServer()
+
+block: #This works
+  proc loop(locals: Cont): Cont
+  proc loop(locals: Cont): Cont =
+    return Cont(fn: loop)
+  proc doServer(): Cont =
+    return Cont(fn: loop)
+  discard doServer()
+
+#And fully recursive:
+block: #Doesn't work
+  template genGenTempl: untyped =
+    proc loop(locals: int)
+    proc loop(locals: int) = loop(locals)
+  genGenTempl()
+  let pool = loop
+
+block: #Doesn't work
+  macro genGenMacro: untyped =
+    quote do:
+      proc loop(locals: int)
+      proc loop(locals: int) = loop(locals)
+  genGenMacro()
+  let pool = loop
+
+block: #This works
+  proc loop(locals: int)
+  proc loop(locals: int) = loop(locals)
+  let pool = loop
+
+block:
+  template genAndCallLoop: untyped =
+    proc loop() {.gensym.}
+    proc loop() {.gensym.} =
+      discard
+    loop()
+  genAndCallLoop
+
+block: #Fully recursive and gensymmed:
+  template genGenTempl: untyped =
+    proc loop(locals: int) {.gensym.}
+    proc loop(locals: int) {.gensym.} = loop(locals)
+    let pool = loop
+  genGenTempl()
+
+block: #Make sure gensymmed symbol doesn't overwrite the forward decl
+  proc loop()
+  proc loop() = discard
+  template genAndCallLoop: untyped =
+    proc loop() {.gensym.} =
+      discard
+    loop()
+  genAndCallLoop()
+
+template genLoopDecl: untyped =
+  proc loop()
+template genLoopDef: untyped =
+  proc loop() = discard
+block:
+  genLoopDecl
+  genLoopDef
+  loop()
+block:
+  proc loop()
+  genLoopDef
+  loop()
+block:
+  genLoopDecl
+  proc loop() = discard
+  loop()
+
+block: #Gensymmed sym sharing forward decl
+  macro genGenMacro: untyped =
+    let sym = genSym(nskProc, "loop")
+    nnkStmtList.newTree(
+      newProc(sym, body = newEmptyNode()),
+      newCall(sym),
+      newProc(sym, body = newStmtList()),
+    )
+  genGenMacro
+
+# inject pragma on params
+
+template test(procname, body: untyped): untyped = 
+  proc procname(data {.inject.}: var int = 0) =
+    body
+
+test(hello):
+  echo data
+  data = 3
+
+var data = 5
+
+hello(data)
+
+# bug #5691
+
+template bar(x: typed) = discard
+macro barry(x: typed) = discard
+
+var a = 0
+
+bar:
+  var a = 10
+
+barry:
+  var a = 20
+
+bar:
+  var b = 10
+
+barry:
+  var b = 20
+
+var b = 30
+
+# template bar(x: static int) = discard
+#You may think that this should work:
+# bar((var c = 1; echo "hey"; c))
+# echo c
+#But it must not! Since this would be incorrect:
+# bar((var b = 3; const c = 1; echo "hey"; c))
+# echo b # <- b wouldn't exist
+
+discard not (let xx = 1; true)
+discard xx
+
+template barrel(a: typed): untyped = a
+
+barrel:
+  var aa* = 1
+  var bb = 3
+  export bb
+
+# Test declaredInScope within params
+template test1: untyped =
+  when not declaredInScope(thing):
+    var thing {.inject.}: int
+
+proc chunkedReadLoop =
+  test1
+  test1
+
+template test2: untyped =
+  when not not not declaredInScope(thing):
+    var thing {.inject.}: int
+
+proc chunkedReadLoop2 =
+  test2
+  test2
+
+test1(); test2()
+
+block: # bug #22846
+  template foo2(x: proc (y: string)) =
+    let f = x
+    f("abc")
+
+  foo2(proc (y: string) = echo y)
+
diff --git a/tests/template/tparamscope.nim b/tests/template/tparamscope.nim
new file mode 100644
index 000000000..177c682cf
--- /dev/null
+++ b/tests/template/tparamscope.nim
@@ -0,0 +1,10 @@
+discard """
+  errormsg: "undeclared identifier: 'a'"
+  line: 10
+"""
+
+
+template secondArg(a, b: typed): untyped =
+  b
+
+echo secondArg((var a = 1; 1), a)
diff --git a/tests/template/tqualifiedident.nim b/tests/template/tqualifiedident.nim
new file mode 100644
index 000000000..463b14ee7
--- /dev/null
+++ b/tests/template/tqualifiedident.nim
@@ -0,0 +1,8 @@
+block: # issue #19865
+  template f() = discard default(system.int)
+  f()
+
+# issue #21221, same as above
+type M = object
+template r() = discard default(tqualifiedident.M)
+r()
diff --git a/tests/template/tqualifiedtype.nim b/tests/template/tqualifiedtype.nim
new file mode 100644
index 000000000..6497af6ee
--- /dev/null
+++ b/tests/template/tqualifiedtype.nim
@@ -0,0 +1,25 @@
+# issue #19866
+
+# Switch module import order to switch which of last two
+# doAsserts fails
+import mqualifiedtype1
+import mqualifiedtype2
+
+# this isn't officially supported but needed to point out the issue:
+template f(moduleName: untyped): int = sizeof(`moduleName`.A)
+template g(someType:   untyped): int = sizeof(someType)
+
+# These are legitimately true.
+doAssert sizeof(mqualifiedtype1.A) != sizeof(mqualifiedtype2.A)
+doAssert g(mqualifiedtype1.A) != g(mqualifiedtype2.A)
+
+# Which means that this should not be true, but is in Nim 1.6
+doAssert f(`mqualifiedtype1`) != f(`mqualifiedtype2`)
+doAssert f(mqualifiedtype1) != f(mqualifiedtype2)
+
+# These should be true, but depending on import order, exactly one
+# fails in Nim 1.2, 1.6 and devel.
+doAssert f(`mqualifiedtype1`) == g(mqualifiedtype1.A)
+doAssert f(`mqualifiedtype2`) == g(mqualifiedtype2.A)
+doAssert f(mqualifiedtype1) == g(mqualifiedtype1.A)
+doAssert f(mqualifiedtype2) == g(mqualifiedtype2.A)
diff --git a/tests/template/tredefinition_override.nim b/tests/template/tredefinition_override.nim
new file mode 100644
index 000000000..7ae232bba
--- /dev/null
+++ b/tests/template/tredefinition_override.nim
@@ -0,0 +1,33 @@
+{.push warningAsError[ImplicitTemplateRedefinition]: on.}
+
+doAssert not (compiles do:
+  template foo(): int = 1
+  template foo(): int = 2)
+doAssert (compiles do:
+  template foo(): int = 1
+  template foo(): int {.redefine.} = 2)
+doAssert not (compiles do:
+  block:
+    template foo() =
+      template bar: string {.gensym.} = "a"
+      template bar: string {.gensym.} = "b"
+    foo())
+doAssert (compiles do:
+  block:
+    template foo() =
+      template bar: string {.gensym.} = "a"
+      template bar: string {.gensym, redefine.} = "b"
+    foo())
+
+block:
+  template foo(): int = 1
+  template foo(): int {.redefine.} = 2
+  doAssert foo() == 2
+block:
+  template foo(): string =
+    template bar: string {.gensym.} = "a"
+    template bar: string {.gensym, redefine.} = "b"
+    bar()
+  doAssert foo() == "b"
+
+{.pop.}
diff --git a/tests/template/tshadow.nim b/tests/template/tshadow.nim
new file mode 100644
index 000000000..a4de71592
--- /dev/null
+++ b/tests/template/tshadow.nim
@@ -0,0 +1,29 @@
+discard """
+  output: '''fish
+fish'''
+"""
+
+import macros
+
+block:
+  template init(initHook: proc(s: string)) =
+    proc dostuff =
+      var s = "fish"
+      initHook(s)
+    dostuff()
+
+  init do(s: string):
+    echo s
+
+block:
+  macro init(initHook: proc(s: string)) =
+    result = newStmtList(
+      newProc(name = ident("dostuff"), body = newStmtList(
+        newVarStmt(ident("s"), newStrLitNode("fish")),
+        newCall(initHook, ident("s"))
+      )),
+      newCall("dostuff")
+    )
+
+  init proc(s: string) =
+    echo s
diff --git a/tests/template/tunderscore1.nim b/tests/template/tunderscore1.nim
new file mode 100644
index 000000000..d74e5ba63
--- /dev/null
+++ b/tests/template/tunderscore1.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "the special identifier '_' is ignored in declarations and cannot be used"
+"""
+
+# issue #12094, #13804
+
+template foo =
+  let _ = 1
+  echo _
+
+foo()
diff --git a/tests/template/twhenintemplates.nim b/tests/template/twhenintemplates.nim
new file mode 100644
index 000000000..6fded856d
--- /dev/null
+++ b/tests/template/twhenintemplates.nim
@@ -0,0 +1,11 @@
+# bug #3670
+
+template someTempl(someConst: bool) =
+  when someConst:
+    var a : int
+  if true:
+    when not someConst:
+      var a : int
+    a = 5
+
+someTempl(true)
diff --git a/tests/template/twrongmapit.nim b/tests/template/twrongmapit.nim
index 5b8663cf9..2d53d03f5 100644
--- a/tests/template/twrongmapit.nim
+++ b/tests/template/twrongmapit.nim
@@ -1,8 +1,6 @@
 discard """
-  output: "####"
+  joinable: false
 """
-# unfortunately our tester doesn't support multiple lines of compiler
-# error messages yet...
 
 # bug #1562
 type Foo* {.pure, final.} = object
@@ -29,4 +27,4 @@ import sequtils
 
 (var i = @[""];i).applyIt(it)
 # now works:
-echo "##", i[0], "##"
+doAssert i[0] == ""
diff --git a/tests/template/utemplates.nim b/tests/template/utemplates.nim
index 017166250..d70746578 100644
--- a/tests/template/utemplates.nim
+++ b/tests/template/utemplates.nim
@@ -3,11 +3,11 @@ import unittest
 template t(a: int): string = "int"
 template t(a: string): string = "string"
 
-test "templates can be overloaded":
+block: # templates can be overloaded
   check t(10) == "int"
   check t("test") == "string"
 
-test "previous definitions can be further overloaded or hidden in local scopes":
+block: # previous definitions can be further overloaded or hidden in local scopes
   template t(a: bool): string = "bool"
 
   check t(true) == "bool"
@@ -17,12 +17,12 @@ test "previous definitions can be further overloaded or hidden in local scopes":
   check t(10) == "inner int"
   check t("test") == "string"
 
-test "templates can be redefined multiple times":
+block: # templates can be redefined multiple times
   template customAssert(cond: bool, msg: string): typed {.dirty.} =
     if not cond: fail(msg)
 
   template assertionFailed(body: untyped) {.dirty.} =
-    template fail(msg: string): typed =
+    template fail(msg: string): typed {.redefine.} =
       body
 
   assertionFailed:
diff --git a/tests/test_nimscript.nims b/tests/test_nimscript.nims
index 3efbb0a4c..32b7d1416 100644
--- a/tests/test_nimscript.nims
+++ b/tests/test_nimscript.nims
@@ -1,25 +1,138 @@
 # This nimscript is used to test if the following modules can be imported
 # http://nim-lang.org/docs/nims.html
 
-import algorithm
-import base64
-import colors
-import hashes
-import lists
-import math
-# import marshal
-import options
-import os
-# import parsecfg
-# import parseopt
-import parseutils
-# import pegs
-import deques
-import sequtils
-import strutils
-import tables
-import unicode
-import uri
-import macros
+{.warning[UnusedImport]: off.}
+
+from stdtest/specialpaths import buildDir
+
+when defined(nimPreviewSlimSystem):
+  import std/[
+    syncio, assertions, formatfloat, objectdollar, widestrs
+  ]
+
+import std/[
+  # Core:
+  bitops, typetraits, lenientops, macros, volatile,
+  # fails due to FFI: typeinfo
+  # fails due to cstring cast/copyMem: endians
+  # works but uses FFI: cpuinfo, rlocks, locks
+
+  # Algorithms:
+  algorithm, enumutils, sequtils, setutils,
+
+  # Collections:
+  critbits, deques, heapqueue, intsets, lists, options, sets,
+  tables, packedsets,
+
+  # Strings:
+  editdistance, wordwrap, parseutils, ropes,
+  pegs, strformat, strmisc, strscans, strtabs,
+  strutils, unicode, unidecode, cstrutils,
+  # works but uses FFI: encodings
+
+  # Time handling:
+  # fails due to FFI: monotimes, times
+  # but times.getTime() implemented for VM
+
+  # Generic operator system services:
+  os, streams, distros,
+  # fails due to FFI: memfiles, osproc, terminal
+  # works but uses FFI: dynlib
+  # intentionally fails: marshal
+
+  # Math libraries:
+  complex, math, random, rationals, stats, sums,
+  # works but uses FFI: fenv, sysrand
+
+  # Internet protocols:
+  httpcore, mimetypes, uri,
+  # fails due to FFI: asyncdispatch, asyncfile, asyncftpclient, asynchttpserver,
+  # asyncnet, cgi, cookies, httpclient, nativesockets, net, selectors, smtp
+  # works but no need to test: asyncstreams, asyncfutures
+
+  # Threading:
+  # fails due to FFI: threadpool
+
+  # Parsers:
+  htmlparser, json, lexbase, parsecfg, parsecsv, parsesql, parsexml,
+  parseopt, jsonutils,
+
+  # XML processing:
+  xmltree, xmlparser,
+
+  # Generators:
+  htmlgen,
+
+  # Hashing:
+  base64, hashes,
+  # fails due to cstring cast/times import/endians import: oids
+  # fails due to copyMem/endians import: sha1
+
+  # Miscellaneous:
+  colors, sugar, varints, enumerate, with,
+  # fails due to FFI: browsers, coro, segfaults
+  # fails due to times import/methods: logging
+  # fails due to methods: unittest
+
+  # Modules for JS backend:
+  # fails intentionally: asyncjs, dom, jsconsole, jscore, jsffi, jsbigints,
+  # jsfetch, jsformdata, jsheaders
+
+  # Unlisted in lib.html:
+  decls, compilesettings, wrapnils, effecttraits, genasts,
+  importutils, isolation
+]
+
+# non-std imports
+import stdtest/testutils
+# tests (increase coverage via code reuse)
+import stdlib/trandom
+import stdlib/tosenv
 
 echo "Nimscript imports are successful."
+
+block:
+  doAssert "./foo//./bar/".normalizedPath == "foo/bar".unixToNativePath
+block:
+  doAssert $3'u == "3"
+  doAssert $3'u64 == "3"
+
+block: # #14142
+  discard dirExists("/usr")
+  discard fileExists("/usr/foo")
+  discard findExe("nim")
+
+block:
+  doAssertRaises(AssertionDefect): doAssert false
+  try: doAssert false
+  except Exception as e:
+    discard
+
+block:  # cpDir, cpFile, dirExists, fileExists, mkDir, mvDir, mvFile, rmDir, rmFile
+  const dname = buildDir/"D20210121T175016"
+  const subDir = dname/"sub"
+  const subDir2 = dname/"sub2"
+  const fpath = subDir/"f"
+  const fpath2 = subDir/"f2"
+  const fpath3 = subDir2/"f"
+  mkDir(subDir)
+  writeFile(fpath, "some text")
+  cpFile(fpath, fpath2)
+  doAssert fileExists(fpath2)
+  rmFile(fpath2)
+  cpDir(subDir, subDir2)
+  doAssert fileExists(fpath3)
+  rmDir(subDir2)
+  mvFile(fpath, fpath2)
+  doAssert not fileExists(fpath)
+  doAssert fileExists(fpath2)
+  mvFile(fpath2, fpath)
+  mvDir(subDir, subDir2)
+  doAssert not dirExists(subDir)
+  doAssert dirExists(subDir2)
+  mvDir(subDir2, subDir)
+  rmDir(dname)
+
+block:
+  # check parseopt can get command line:
+  discard initOptParser()
diff --git a/tests/testament/t16576.nim b/tests/testament/t16576.nim
new file mode 100644
index 000000000..8d0dd57e3
--- /dev/null
+++ b/tests/testament/t16576.nim
@@ -0,0 +1,7 @@
+discard """
+  matrix:"-d:nimTest_t16576"
+"""
+
+# bug #16576
+doAssert defined(nimTest_t16576)
+doAssert not defined(nimMegatest)
diff --git a/tests/testament/tinlinemsg.nim b/tests/testament/tinlinemsg.nim
new file mode 100644
index 000000000..199c263e9
--- /dev/null
+++ b/tests/testament/tinlinemsg.nim
@@ -0,0 +1,8 @@
+discard """
+  matrix: "--errorMax:0 --styleCheck:error"
+"""
+
+proc generic_proc*[T](a_a: int) = #[tt.Error
+     ^ 'generic_proc' should be: 'genericProc'; tt.Error
+                      ^ 'a_a' should be: 'aA' ]#
+  discard
diff --git a/tests/testament/tjoinable.nim b/tests/testament/tjoinable.nim
new file mode 100644
index 000000000..c651780de
--- /dev/null
+++ b/tests/testament/tjoinable.nim
@@ -0,0 +1,9 @@
+discard """
+  output: "ok"
+"""
+
+# checks that this is joinable
+# checks that megatest allows duplicate names, see also `tests/misc/tjoinable.nim`
+doAssert defined(testing)
+doAssert defined(nimMegatest)
+echo "ok" # intentional to make sure this doesn't prevent `isJoinableSpec`
diff --git a/tests/testament/treject.nim b/tests/testament/treject.nim
new file mode 100644
index 000000000..be2db86a9
--- /dev/null
+++ b/tests/testament/treject.nim
@@ -0,0 +1,6 @@
+discard """
+action: "reject"
+"""
+
+# this line does not compile, so the test should pass, since action="reject"
+let x: int = "type mismatch"
diff --git a/tests/testament/tshould_not_work.nim b/tests/testament/tshould_not_work.nim
index aca73c308..8c99510a0 100644
--- a/tests/testament/tshould_not_work.nim
+++ b/tests/testament/tshould_not_work.nim
@@ -1,33 +1,53 @@
 discard """
-cmd: "testament/testament --directory:testament --colors:off --backendLogging:off --nim:../compiler/nim category shouldfail"
-action: compile
-nimout: '''
-FAIL: tests/shouldfail/tccodecheck.nim C
+  joinable: false
+"""
+
+const expected = """
+FAIL: tests/shouldfail/tccodecheck.nim
 Failure: reCodegenFailure
 Expected:
 baz
-FAIL: tests/shouldfail/tcolumn.nim C
+FAIL: tests/shouldfail/tcolumn.nim
 Failure: reLinesDiffer
-FAIL: tests/shouldfail/terrormsg.nim C
+FAIL: tests/shouldfail/terrormsg.nim
 Failure: reMsgsDiffer
-FAIL: tests/shouldfail/texitcode1.nim C
+FAIL: tests/shouldfail/texitcode1.nim
 Failure: reExitcodesDiffer
-FAIL: tests/shouldfail/tfile.nim C
+FAIL: tests/shouldfail/tfile.nim
 Failure: reFilesDiffer
-FAIL: tests/shouldfail/tline.nim C
+FAIL: tests/shouldfail/tline.nim
 Failure: reLinesDiffer
-FAIL: tests/shouldfail/tmaxcodesize.nim C
+FAIL: tests/shouldfail/tmaxcodesize.nim
 Failure: reCodegenFailure
 max allowed size: 1
-FAIL: tests/shouldfail/tnimout.nim C
+FAIL: tests/shouldfail/tnimout.nim
+Failure: reMsgsDiffer
+FAIL: tests/shouldfail/tnimoutfull.nim
 Failure: reMsgsDiffer
-FAIL: tests/shouldfail/toutput.nim C
+FAIL: tests/shouldfail/toutput.nim
 Failure: reOutputsDiffer
-FAIL: tests/shouldfail/toutputsub.nim C
+FAIL: tests/shouldfail/toutputsub.nim
 Failure: reOutputsDiffer
-FAIL: tests/shouldfail/tsortoutput.nim C
+FAIL: tests/shouldfail/treject.nim
+Failure: reFilesDiffer
+FAIL: tests/shouldfail/tsortoutput.nim
 Failure: reOutputsDiffer
-FAIL: tests/shouldfail/ttimeout.nim C
+FAIL: tests/shouldfail/ttimeout.nim
 Failure: reTimeout
-'''
+FAIL: tests/shouldfail/tvalgrind.nim
+Failure: reExitcodesDiffer
 """
+
+import std/[os,strformat,osproc]
+import stdtest/testutils
+
+proc main =
+  const nim = getCurrentCompilerExe()
+  let testamentExe = "bin/testament"
+  let cmd = fmt"{testamentExe} --directory:testament --colors:off --backendLogging:off --nim:{nim} category shouldfail"
+  let (outp, status) = execCmdEx(cmd)
+  doAssert status == 1, $status
+
+  let ok = greedyOrderedSubsetLines(expected, outp, allowPrefixMatch = true)
+  doAssert ok, &"\nexpected:\n{expected}\noutp:\n{outp}"
+main()
diff --git a/tests/testament/tspecialpaths.nim b/tests/testament/tspecialpaths.nim
new file mode 100644
index 000000000..3c97dc88a
--- /dev/null
+++ b/tests/testament/tspecialpaths.nim
@@ -0,0 +1,9 @@
+import stdtest/specialpaths
+import std/os
+block: # splitTestFile
+  doAssert splitTestFile("tests/fakedir/tfakename.nim") == ("fakedir", "tests/fakedir/tfakename.nim".unixToNativePath)
+  doAssert splitTestFile("/pathto/tests/fakedir/tfakename.nim") == ("fakedir", "/pathto/tests/fakedir/tfakename.nim".unixToNativePath)
+  doAssert splitTestFile(getCurrentDir() / "tests/fakedir/tfakename.nim") == ("fakedir", "tests/fakedir/tfakename.nim".unixToNativePath)
+  doAssert splitTestFile(getCurrentDir() / "sub/tests/fakedir/tfakename.nim") == ("fakedir", "sub/tests/fakedir/tfakename.nim".unixToNativePath)
+  doAssertRaises(AssertionDefect): discard splitTestFile("testsbad/fakedir/tfakename.nim")
+  doAssertRaises(AssertionDefect): discard splitTestFile("tests/tfakename.nim")
diff --git a/tests/testdata/mycert.pem b/tests/testdata/mycert.pem
index 69039fe04..61dcb685c 100644
--- a/tests/testdata/mycert.pem
+++ b/tests/testdata/mycert.pem
@@ -1,32 +1,81 @@
 -----BEGIN PRIVATE KEY-----
-MIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAL9QXX/nuiFbizdI
-Uhg1D9gG0GIANENvKwdWTlOlZAoOqvjXPFLGh+87yhvkq4f5FcICkSDao2SfeZcP
-JsgD7T01owt8x48898+d91i7nIpr6IXGPyBxHOuaxAITY1D+MbbkhIGUVrEqKEOm
-qfS9cqPZaDNkx8xVef0HPCmqEme9AgMBAAECgYBxqrQCvJFQJG3QiL2N+GjTdyj0
-MR7cOf6cu2CKPifz+ccHVgpXO/Gj6Cgq7nAjt5B/1rqXhI+zxzSc1bm6+OpIfakS
-E0DLCFacECmL0v3c+XLxTtMhFZF5u7Yq0UMsuWmDSfRb4sbRjC+s+c51i5N0485k
-b3un/MDI/i/jD/YZGQJBAPLtcuMIwEblUR1uw7NFezXdauXCRFkekoSlJNvpdM/Z
-XDRcuWioek5yD8FvMpTz7H2e26Ev645JT5lIuN4Eti8CQQDJm+Qt9NYUohRsU279
-GYI3vXsXKKqmA22at4I3KRXPSeYV1vtQLYWWqGAXzgGkUEVBY0chmHyDcNwkUsNw
-svHTAkEAwOTpD/vX6bOXOD7GqKgoULozcqNScE2FXExhuzliJtTakT17f+4fyABs
-IFWynXIevBUTIqeRbJcr3HRRTwIAwwJBAJQ8XkL4IaxcG/4mPpY0ek13sZiumwKj
-xKQcx869E78tS9LFFlW2kuHafYUjQIvLRZC1aWinUO3oPsUqYW9s82cCQFjoods5
-YsWEJB2RKCT5nhyAXEZLehxF+FXr+JjLMHkuEINKTnHHKjHJ7LbMcTCKUJAcKDTA
-qZFEq5N1aT6DrAU=
+MIIJQwIBADANBgkqhkiG9w0BAQEFAASCCS0wggkpAgEAAoICAQDgpWhnNdNSUbwJ
+39mKf+PA879K1wyT23LC3Ipo5g5vaRjB4vrSh5vzrjK5Q/z42yRDLQ2ojEdUne19
+1xMaM+WqTXnfkf9sou4VJ0HsdQ6jOU1LDRPrPvCjHLZjyMu18sGvQf4FATBwWN3n
+QhmvcbleTeyv2pgMNeQDfjuIhRJ/aCIi/WYQ466+Rcj0y3/udYX1yPYf2mszXnSE
+i2iWgdsjx0qkDU/nJhnKXhKfucAm9Ds0YfQdZYN3rEzfGkJzZUhDG1n30ghu+vUg
+qqLi6HU/HqBxKxBlJf2HdMNK4VLkJuFC+wCI0JfF6VYhcNmtZzlQy3M9WjYvbXUY
+nvMkQzUECaSaAtmbhFFfgey1Q3IEQS/j1lsVxtuGUE3YaoyaK22/CkVInDz0aka9
+CKq77x7S/V5PP/wwPV4s8XsbT6/34KemuY3oU84+bf5SBuWdzBY0hnDO9c/FaOnZ
+4yjLMQi285HLpK417Z32DmzIkb7GjKtP9WLvsWGgbgquEjcFaIT+erkN09cDjsG/
+URWbKcsQkz8v9E4zj0rxdanXoJEtg1gm+dPsiXokZOLTeaMVtDoTkWeCM/VAp25J
+MTc656QRUTSzUODK5tXQ3JgE2XIPGV/PsMi7T/q9xFBQmhUk5kfLNlQ1cy/aiTWK
+8pjHcmxbyD121AimuTtv9CFYnYtzyQIDAQABAoICAAMYZFrfs/yzYZrlObMd1f6H
+nUAjvGmhIXCr50BQwywnz46EWR5jffOal9pTpH2tT0+ZpFGJNUZmMqqENyAqTOTO
+0noRIerWR9+EvfTLHBuFo5oAISEhqeEleSHg12W3ZZHLn/tjq84we0Y/c+kl8P7q
+pfM6WNP6Ph0KNTnJU5rrzWScBzb+XB8FCSLOVwHrHqBnV3TS5p07lPFqllNUkLdq
+fI3MHSi7LqnKKAmJXqtqvBIZs2pgRrJ0bk64pue+IoPCMbgnbbRRwuTjVQE5YLww
+6NcGV+B86IRgSHyUpDa+jmYE3VoFPcIdV/F4A5fPD0wcsYbL4mk+4dkn/4OlZWqV
+NZILp2IGejKaKtM1fr7fV2IRUbGUBN/+rX4I0SRnuq6Q4Ipx8VASbpgXQPBo9XTg
+SHHsFbEu2DL8BHVgXdOy4PW6jQ0Ux2LhuJk6AQ5nIlFBYA+c8rSlZQXJbEbk1VZu
+1i7iSOn/kx3ULMjUfhI/Ddm6rQqtiLbXSubXCzu1HMPT1FG9LUfAbq6EpiVkpAk1
+TqlciBHsyz//mk2RmIEx0Bt+0bX8FFGTIUiGyrp5s4hAHbgQZbXBAUYMRzWxhZ2Q
+G0KBXx46bv3hJUb0GOgbNVxcaPnyrXaS/Hafcbx2LXlEtKiwGnC/yKJ7Hmcrt+AQ
+RTaqNU1o/bkSYC7vHMZdAoIBAQD79uYPZPv5GLCKPZ64gc3+tbFXNqkmL7qv14yD
+Gr3VubRbJe3Fx+T1cS+t9cjgOofhjFnwsDaFRoyWOYqRV/znwFsvvsDhHOLBr1u6
+qWQiF2CT1uMdXR3P6KD8h2DUVNNccxKqqIJNCR5oD/ngnnByWkQobzlsnoIdXgZm
+ozBZjGr2XUMO5dJqUxaXZwY3j4I2hk/Ka9uroApyptl+DTVbPHvjk3MzU9QKUNor
+vXEtQ8EmM8Oy6v/33HBmNs6cF5fMpgWz6u+B357OTxAfu8B42jZ18OeLrvkHFxzu
+phOB1uXvqtQ0tdksSHHWj3IIZRK7GDGudnDEZ23vbCaxH4zbAoIBAQDkPn+5N3px
+7UAECWrvT10TD3xKeqMkFhqRA9gmDE4N9AdoN6T6PzD7Tr3gOgGLq1tXjCjBqAlx
+ZIDTnih3IK3xoRk2zmhq5+LfM8LQRAxAC8IsoQMXAsmW1KlS6MR70m50pFR8NK6r
+UmOdrwVUKp3K6Mecid3LmMVLXGMUKwIJc1k7LJHtwrfi0i5xfBtiqQeaR0lJg4Zr
++zEL/4rHfcq06/P3k0+4uLKZ1LGOvwLPiTA3DADPWZbzUXo7McKOFWF/ycGQBrJq
+AJikx15dVLnB16bnHXdxrlrd0LON2R+XfT4+dfRymqZLzrBI3L39t/elTmVYnD3P
+punkmZuVwNErAoIBAQD5xOiOPibh6S2n/CmI8XQImIgx0kefSRUhFuV9WVbxtOMq
+r9CijONUw1zmb40vahYk6gKGa8fAGg1nJadNKRHVkoNSMx/0h7PpGDIwOZa/jLj6
+FLyS8SmKXiqn6nN8SJI1RQUuE1kHkJCJy7yCg80oLn7+LjOYjxCgmAJ0YDSfsGif
+zBebfws0xyTP9RrenO4RqtcR7BWYbk+tE+Tp5aIMzUpqcFJ0gRbjGv8K+QJmQpIH
+kqzegcI4LFdnm9D4PxMFlVZ14eCGt+wuy4VKT84efwIZrDN77nmCI9FUaWFRBnxt
+NsShc9rS4QWoEg6Sb88/lF47ecGTkIwUGPvJ/WKdAoIBAQClF7/zDPn4Zg+j29wJ
+dXJxUwYoKUTP2V0l/43dF5Ft7lFdRMKEcCjR3kbhZZOwnyXW0X65dP4/kt7MMt46
+LN0kpc5DIlHM4iXsJNiJJG9n9BljhqNhhZajDvfbDJrypWdX33Vs0f511YZQjERi
+eODh4DZiOCbCGaK7u/u+ns0+YLzuXHLBc9Lmsfj+BTMZzgG9ykpsbkJQ4MS9VP3h
+BlAVRYaWUWucxZwKQRqdkfRKgYTqjDgZw0e4f/rVzkxX0YdQk3L65p0up3fB2KOd
+BqfGWmJTUbEP/XmkcE0wERkUznazX0aNjucydjJ0wZZ7axIp8+bCjWD4TldoDuPH
+Ek05AoIBAECgPfBHLQTAsI+wHbFsu/are28BOiJCSEXjRv88CbUbj/qgAppFuXbx
+900WwJ1rVWd5x3LFa3VfyuAqYMi5jzmX9kWgEsC0WhgfyIRFiynw45LlcT4u3fWg
+vJEx01lGgFVjnYfFUDS9d1MuiXGxIHrNhzHOP2x2CsS5vrFHav7iwG9YULEk8tJr
+My0wzjF3UJ2/5DjGK56WuzauLYKrQ6Faw8dWUy4e/bNYId8wglhQQW548JwJEGmq
+nq+EzTfEupXH57Bw7MGEOfdlhv98zNT9VcvBAN09vHeF3Hh6AM4aiGSUIt2HIkto
+zvw+fqZ2Sk9O5qva+KE1QMVtY1EICI8=
 -----END PRIVATE KEY-----
 -----BEGIN CERTIFICATE-----
-MIICgDCCAemgAwIBAgIJANpVfZSDAyNgMA0GCSqGSIb3DQEBBQUAMFkxCzAJBgNV
-BAYTAkFVMRMwEQYDVQQIDApTb21lLVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBX
-aWRnaXRzIFB0eSBMdGQxEjAQBgNVBAMMCWxvY2FsaG9zdDAeFw0xMjA2MDMxMjI4
-MDhaFw0xMzA2MDMxMjI4MDhaMFkxCzAJBgNVBAYTAkFVMRMwEQYDVQQIDApTb21l
-LVN0YXRlMSEwHwYDVQQKDBhJbnRlcm5ldCBXaWRnaXRzIFB0eSBMdGQxEjAQBgNV
-BAMMCWxvY2FsaG9zdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAv1Bdf+e6
-IVuLN0hSGDUP2AbQYgA0Q28rB1ZOU6VkCg6q+Nc8UsaH7zvKG+Srh/kVwgKRINqj
-ZJ95lw8myAPtPTWjC3zHjzz3z533WLucimvohcY/IHEc65rEAhNjUP4xtuSEgZRW
-sSooQ6ap9L1yo9loM2THzFV5/Qc8KaoSZ70CAwEAAaNQME4wHQYDVR0OBBYEFF2n
-Of61swO+XSNrYb4T02tGx8afMB8GA1UdIwQYMBaAFF2nOf61swO+XSNrYb4T02tG
-x8afMAwGA1UdEwQFMAMBAf8wDQYJKoZIhvcNAQEFBQADgYEAEPHofdf4acaph5/e
-+BzZGsMfRqdPgwp5sxjFKeTQI1A49VL7ykkb0iLKGfKZtvE8MjMrYjzt20E2bIZj
-8eCivT6TbNrVRoACCly/lH9fZfWOG6dBu/85IrTAhSKi8yjbRzmjWUkdrcEJ+ZtV
-1cahfFar4l4QwYgqp2pDd6ie+zE=
+MIIFCTCCAvGgAwIBAgIUKqDcJ71wiMObIQ5sga2sZItNseowDQYJKoZIhvcNAQEL
+BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTIyMDUwNDExMzAwN1oXDTIyMDYw
+MzExMzAwN1owFDESMBAGA1UEAwwJbG9jYWxob3N0MIICIjANBgkqhkiG9w0BAQEF
+AAOCAg8AMIICCgKCAgEA4KVoZzXTUlG8Cd/Zin/jwPO/StcMk9tywtyKaOYOb2kY
+weL60oeb864yuUP8+NskQy0NqIxHVJ3tfdcTGjPlqk1535H/bKLuFSdB7HUOozlN
+Sw0T6z7woxy2Y8jLtfLBr0H+BQEwcFjd50IZr3G5Xk3sr9qYDDXkA347iIUSf2gi
+Iv1mEOOuvkXI9Mt/7nWF9cj2H9prM150hItoloHbI8dKpA1P5yYZyl4Sn7nAJvQ7
+NGH0HWWDd6xM3xpCc2VIQxtZ99IIbvr1IKqi4uh1Px6gcSsQZSX9h3TDSuFS5Cbh
+QvsAiNCXxelWIXDZrWc5UMtzPVo2L211GJ7zJEM1BAmkmgLZm4RRX4HstUNyBEEv
+49ZbFcbbhlBN2GqMmittvwpFSJw89GpGvQiqu+8e0v1eTz/8MD1eLPF7G0+v9+Cn
+prmN6FPOPm3+UgblncwWNIZwzvXPxWjp2eMoyzEItvORy6SuNe2d9g5syJG+xoyr
+T/Vi77FhoG4KrhI3BWiE/nq5DdPXA47Bv1EVmynLEJM/L/ROM49K8XWp16CRLYNY
+JvnT7Il6JGTi03mjFbQ6E5FngjP1QKduSTE3OuekEVE0s1DgyubV0NyYBNlyDxlf
+z7DIu0/6vcRQUJoVJOZHyzZUNXMv2ok1ivKYx3JsW8g9dtQIprk7b/QhWJ2Lc8kC
+AwEAAaNTMFEwHQYDVR0OBBYEFEZcUeqH6MfIzC56BlD3NSs2mCgGMB8GA1UdIwQY
+MBaAFEZcUeqH6MfIzC56BlD3NSs2mCgGMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZI
+hvcNAQELBQADggIBADGc7WONP6I6Trb7ici9fQ9qT3wh/RGDcmUDmDtARn9SFtOF
+hsbszOMZg1Flj10fuD6OYDonKz4rv+Ieo5VkAYXxxd3J+bx2x1pqd1YSIsvugTwv
+pnx39uBR9cjOmt4W7RyzhFnXoVfuSBE6LpkBUjcrqi5xwrQ31mOSCPwe8uDZYEWS
+pX49MiHXGTyjQ481QLiOtTBZJa5igfnHUJbJbyZMa86zBQ/clS7+OeDwkvaEpjov
+2VQf3QouVLghfLZYWSxWdEKD9+IWHn8rV6qksEb/Ogu4ZtzDRGqJow4j0DeSSEu7
+ns1YeT2mVTFwHjGXCWS+0iE885NDVX/b5YptlwH5PW7aqeXyCS9Hrd1C1GnXoXGp
+NHltYRTyNWm974xWg7eu2gbbB8Ng02chXysdkBq7l+7OyA0a2EfX3Cbz3/49+Mqn
+viqwNO5toSHVCdfV9Jd0p0CcqryYgyt2YNpJB+2nUQpiW4jviAs49PZg2PpCVw/2
+0cqtaPeUh26Si8UzDOuT697PIuGkZ9Q9QVwccVXtCyA0UpJ13P0fMrA+yEMhtwSs
+k1tRm0pUQa6t3v26/cAy+kMhviHBJFwi5dx+y3OMvqQqpQJrgfZawm/o2ZQHy1KP
+8m4ngrJzb13evKf216qCwllmQo6Ts4yeI1Ddx8UpdX7RUWpD8Uw4zSi7Th4r
 -----END CERTIFICATE-----
diff --git a/tests/threads/t7172.nim b/tests/threads/t7172.nim
new file mode 100644
index 000000000..87e89417b
--- /dev/null
+++ b/tests/threads/t7172.nim
@@ -0,0 +1,34 @@
+discard """
+  disabled: i386
+  output: '''
+In doStuff()
+In initProcess()
+TEST
+initProcess() done
+Crashes before getting here!
+'''
+  joinable: false
+"""
+
+import std/os
+import std/typedthreads
+
+proc whatever() {.thread, nimcall.} =
+  echo("TEST")
+
+proc initProcess(): void =
+  echo("In initProcess()")
+  var thread: Thread[void]
+  createThread(thread, whatever)
+  joinThread(thread)
+  echo("initProcess() done")
+
+proc doStuff(): void =
+  echo("In doStuff()")
+  # ...
+  initProcess()
+  sleep(500)
+  # ...
+  echo("Crashes before getting here!")
+
+doStuff()
diff --git a/tests/threads/t8535.nim b/tests/threads/t8535.nim
index dfc95547d..a4296df11 100644
--- a/tests/threads/t8535.nim
+++ b/tests/threads/t8535.nim
@@ -1,4 +1,5 @@
 discard """
+  disabled: i386
   output: '''0
 hello'''
 """
@@ -22,7 +23,7 @@ import asyncdispatch
 import threadpool
 
 proc f1() =
-  waitFor sleepAsync(100)
+  waitFor sleepAsync(20)
   echo "hello"
 
 spawn f1()
diff --git a/tests/threads/threadex.nim b/tests/threads/threadex.nim
index 50a1a4d34..90119aee7 100644
--- a/tests/threads/threadex.nim
+++ b/tests/threads/threadex.nim
@@ -1,4 +1,5 @@
 discard """
+  disabled: i386
   outputsub: "Just a simple text for test"
 """
 
diff --git a/tests/threads/tjsthreads.nim b/tests/threads/tjsthreads.nim
new file mode 100644
index 000000000..5122c9cd6
--- /dev/null
+++ b/tests/threads/tjsthreads.nim
@@ -0,0 +1,6 @@
+discard """
+  targets: "js"
+  matrix: "--threads:on"
+"""
+
+echo 123
diff --git a/tests/threads/tmanyjoin.nim b/tests/threads/tmanyjoin.nim
index 2c1cda494..af5bc460e 100644
--- a/tests/threads/tmanyjoin.nim
+++ b/tests/threads/tmanyjoin.nim
@@ -1,4 +1,5 @@
 discard """
+  disabled: i386
   outputsub: "129"
 """
 
@@ -12,7 +13,7 @@ type
 
 const
   ThreadsCount = 129
-  SleepTime = 1000
+  SleepTime = 250
 
 proc worker(p: Marker) {.thread.} =
   acquire(p.lock)
diff --git a/tests/threads/tmembug.nim b/tests/threads/tmembug.nim
new file mode 100644
index 000000000..3618f0ecc
--- /dev/null
+++ b/tests/threads/tmembug.nim
@@ -0,0 +1,51 @@
+
+import std / [atomics, strutils, sequtils]
+
+type
+  BackendMessage* = object
+    field*: seq[int]
+
+var
+  chan1: Channel[BackendMessage]
+  chan2: Channel[BackendMessage]
+
+chan1.open()
+chan2.open()
+
+proc routeMessage*(msg: BackendMessage) =
+  discard chan2.trySend(msg)
+
+var
+  recv: Thread[void]
+  stopToken: Atomic[bool]
+
+proc recvMsg() =
+  while not stopToken.load(moRelaxed):
+    let resp = chan1.tryRecv()
+    if resp.dataAvailable:
+      routeMessage(resp.msg)
+      echo "child consumes ", formatSize getOccupiedMem()
+
+createThread[void](recv, recvMsg)
+
+const MESSAGE_COUNT = 100
+
+proc main() =
+  let msg: BackendMessage = BackendMessage(field: (0..500).toSeq())
+  for j in 0..0: #100:
+    echo "New iteration"
+
+    for _ in 1..MESSAGE_COUNT:
+      chan1.send(msg)
+    echo "After sending"
+
+    var counter = 0
+    while counter < MESSAGE_COUNT:
+      let resp = recv(chan2)
+      counter.inc
+    echo "After receiving ", formatSize getOccupiedMem()
+
+  stopToken.store true, moRelaxed
+  joinThreads(recv)
+
+main()
diff --git a/tests/threads/tonthreadcreation.nim b/tests/threads/tonthreadcreation.nim
index f588a21c9..61529477d 100644
--- a/tests/threads/tonthreadcreation.nim
+++ b/tests/threads/tonthreadcreation.nim
@@ -1,4 +1,6 @@
 discard """
+  disabled: i386
+  matrix: "--mm:refc; --mm:orc --deepcopy:on"
   output: '''some string here
 dying some string here'''
 """
diff --git a/tests/threads/tracy_allocator.nim b/tests/threads/tracy_allocator.nim
index e8f0ec927..f3b39f4dc 100644
--- a/tests/threads/tracy_allocator.nim
+++ b/tests/threads/tracy_allocator.nim
@@ -1,4 +1,5 @@
 discard """
+  disabled: i386
   output: '''true'''
 """
 
diff --git a/tests/threads/treusetvar.nim b/tests/threads/treusetvar.nim
index 672da6bdd..f0337801a 100644
--- a/tests/threads/treusetvar.nim
+++ b/tests/threads/treusetvar.nim
@@ -1,8 +1,9 @@
 discard """
-  outputsub: "129"
+  disabled: i386
+  outputsub: "65"
 """
 
-import os, locks
+import locks
 
 type
   MarkerObj = object
@@ -11,7 +12,7 @@ type
   Marker = ptr MarkerObj
 
 const
-  ThreadsCount = 129
+  ThreadsCount = 65
 
 proc worker(p: Marker) {.thread.} =
   acquire(p.lock)
diff --git a/tests/threads/tthreadanalysis2.nim b/tests/threads/tthreadanalysis2.nim
deleted file mode 100644
index 067e186a8..000000000
--- a/tests/threads/tthreadanalysis2.nim
+++ /dev/null
@@ -1,51 +0,0 @@
-discard """
-  errormsg: "'threadFunc' is not GC-safe"
-  file: "tthreadanalysis2.nim"
-  line: 37
-  cmd: "nim $target --hints:on --threads:on $options $file"
-"""
-
-import os
-
-var
-  thr: array[0..5, Thread[tuple[a, b: int]]]
-
-proc doNothing() = discard
-
-type
-  PNode = ref TNode
-  TNode = object {.pure.}
-    le, ri: PNode
-    data: string
-
-var
-  root: PNode
-
-proc buildTree(depth: int): PNode =
-  if depth == 3: return nil
-  new(result)
-  result.le = buildTree(depth-1)
-  result.ri = buildTree(depth-1)
-  result.data = $depth
-
-proc echoLeTree(n: PNode) =
-  var it = n
-  while it != nil:
-    echo it.data
-    it = it.le
-
-proc threadFunc(interval: tuple[a, b: int]) {.thread.} =
-  doNothing()
-  for i in interval.a..interval.b:
-    var r = buildTree(i)
-    echoLeTree(r) # for local data
-  root = buildTree(2) # BAD!
-  #echoLeTree(root) # and the same for foreign data :-)
-
-proc main =
-  root = buildTree(5)
-  for i in 0..high(thr):
-    createThread(thr[i], threadFunc, (i*100, i*100+50))
-  joinThreads(thr)
-
-main()
diff --git a/tests/threads/tthreadvars.nim b/tests/threads/tthreadvars.nim
index 81aa2e5ec..745e3562c 100644
--- a/tests/threads/tthreadvars.nim
+++ b/tests/threads/tthreadvars.nim
@@ -1,4 +1,5 @@
 discard """
+disabled: i386
 output: '''
 10
 1111
diff --git a/tests/threads/ttryrecv.nim b/tests/threads/ttryrecv.nim
index 87dec6e79..fcff94e78 100644
--- a/tests/threads/ttryrecv.nim
+++ b/tests/threads/ttryrecv.nim
@@ -1,4 +1,5 @@
 discard """
+  matrix: "--mm:refc"
   outputsub: "channel is empty"
 """
 
@@ -11,7 +12,7 @@ type PComm = ptr Channel[int]
 
 proc doAction(outC: PComm) {.thread.} =
   for i in 0 ..< 5:
-    sleep(rand(100))
+    sleep(rand(50))
     send(outC[], i)
 
 var
diff --git a/tests/tools/compile/config.nims b/tests/tools/compile/config.nims
new file mode 100644
index 000000000..a19545668
--- /dev/null
+++ b/tests/tools/compile/config.nims
@@ -0,0 +1 @@
+switch("path", "$lib/../")
\ No newline at end of file
diff --git a/tests/tools/compile/readme.md b/tests/tools/compile/readme.md
new file mode 100644
index 000000000..cb5058e02
--- /dev/null
+++ b/tests/tools/compile/readme.md
@@ -0,0 +1 @@
+Test whether the tools compile.
\ No newline at end of file
diff --git a/tests/flags/tgenscript.nim b/tests/tools/compile/tdeps.nim
index bf83ab972..971ca1b8e 100644
--- a/tests/flags/tgenscript.nim
+++ b/tests/tools/compile/tdeps.nim
@@ -1,6 +1,5 @@
 discard """
-  target: "c"
   action: compile
 """
 
-echo "--genscript"
+include tools/deps
diff --git a/tests/tools/compile/tdetect.nim b/tests/tools/compile/tdetect.nim
new file mode 100644
index 000000000..253fc0d39
--- /dev/null
+++ b/tests/tools/compile/tdetect.nim
@@ -0,0 +1,5 @@
+discard """
+  action: compile
+"""
+
+include tools/detect/detect
diff --git a/tests/tools/compile/tkoch.nim b/tests/tools/compile/tkoch.nim
new file mode 100644
index 000000000..008721dc0
--- /dev/null
+++ b/tests/tools/compile/tkoch.nim
@@ -0,0 +1,5 @@
+discard """
+  action: compile
+"""
+
+include koch
\ No newline at end of file
diff --git a/tests/tools/compile/tniminst.nim b/tests/tools/compile/tniminst.nim
new file mode 100644
index 000000000..78c736af0
--- /dev/null
+++ b/tests/tools/compile/tniminst.nim
@@ -0,0 +1,5 @@
+discard """
+  action: compile
+"""
+
+include tools/niminst/niminst
\ No newline at end of file
diff --git a/tests/tools/config.nims b/tests/tools/config.nims
new file mode 100644
index 000000000..0f0cba8b4
--- /dev/null
+++ b/tests/tools/config.nims
@@ -0,0 +1,3 @@
+--d:nimPreviewSlimSystem
+--d:nimPreviewCstringConversion
+--d:nimPreviewProcConversion
diff --git a/tests/tools/second.nim b/tests/tools/second.nim
index 0dbe72adb..ee94af25f 100644
--- a/tests/tools/second.nim
+++ b/tests/tools/second.nim
@@ -1,3 +1,3 @@
-import tables

-

-let dataEx* = {1: 2, 3: 4}.toTable

+import tables
+
+let dataEx* = {1: 2, 3: 4}.toTable
diff --git a/tests/tools/tlinter.nim b/tests/tools/tlinter.nim
index a0ed9bfc2..16f67905e 100644
--- a/tests/tools/tlinter.nim
+++ b/tests/tools/tlinter.nim
@@ -1,13 +1,13 @@
 discard """
   cmd: '''nim c --styleCheck:hint $file'''
   nimout: '''
+tlinter.nim(25, 1) Hint: 'tyPE' should be: 'type' [Name]
 tlinter.nim(21, 14) Hint: 'nosideeffect' should be: 'noSideEffect' [Name]
-tlinter.nim(21, 28) Hint: 'myown' should be: 'myOwn' [Name]
+tlinter.nim(21, 28) Hint: 'myown' should be: 'myOwn' [template declared in tlinter.nim(19, 9)] [Name]
 tlinter.nim(21, 35) Hint: 'inLine' should be: 'inline' [Name]
-tlinter.nim(25, 1) Hint: 'tyPE' should be: 'type' [Name]
-tlinter.nim(23, 1) Hint: 'foO' should be: 'foo' [Name]
-tlinter.nim(27, 14) Hint: 'Foo_bar' should be: 'FooBar' [Name]
-tlinter.nim(29, 6) Hint: 'someVAR' should be: 'someVar' [Name]
+tlinter.nim(23, 1) Hint: 'foO' should be: 'foo' [proc declared in tlinter.nim(21, 6)] [Name]
+tlinter.nim(27, 14) Hint: 'Foo_bar' should be: 'FooBar' [type declared in tlinter.nim(25, 6)] [Name]
+tlinter.nim(29, 6) Hint: 'someVAR' should be: 'someVar' [var declared in tlinter.nim(27, 5)] [Name]
 tlinter.nim(32, 7) Hint: 'i_fool' should be: 'iFool' [Name]
 tlinter.nim(39, 5) Hint: 'meh_field' should be: 'mehField' [Name]
 '''
diff --git a/tests/tools/tnimgrep.nim b/tests/tools/tnimgrep.nim
new file mode 100644
index 000000000..890a36e79
--- /dev/null
+++ b/tests/tools/tnimgrep.nim
@@ -0,0 +1,404 @@
+discard """
+  output: '''
+
+[Suite] nimgrep filesystem
+
+[Suite] nimgrep contents filtering
+'''
+"""
+## Authors: quantimnot, a-mr
+
+import std/[osproc, os, streams, unittest, strutils]
+
+import std/syncio
+
+#=======
+# setup
+#=======
+
+var process: Process
+var ngStdOut, ngStdErr: string
+var ngExitCode: int
+let previousDir = getCurrentDir()
+let tempDir = getTempDir()
+let testFilesRoot = tempDir / "nimgrep_test_files"
+
+template nimgrep(optsAndArgs): untyped =
+  process = startProcess(previousDir / "bin/nimgrep " & optsAndArgs,
+                         options = {poEvalCommand})
+  ngExitCode = process.waitForExit
+  ngStdOut = process.outputStream.readAll
+  ngStdErr = process.errorStream.readAll
+
+func fixSlash(s: string): string =
+  if DirSep == '/':
+    result = s
+  else:  # on Windows
+    result = s.replace('/', DirSep)
+
+func initString(len = 1000, val = ' '): string =
+  result = newString(len)
+  for i in 0..<len:
+    result[i] = val
+
+# Create test file hierarchy.
+createDir testFilesRoot
+setCurrentDir testFilesRoot
+createDir "a" / "b"
+createDir "c" / "b"
+createDir ".hidden"
+writeFile("do_not_create_another_file_with_this_pattern_KJKJHSFSFKASHFBKAF", "PATTERN")
+writeFile("a" / "b" / "only_the_pattern", "PATTERN")
+writeFile("c" / "b" / "only_the_pattern", "PATTERN")
+writeFile(".hidden" / "only_the_pattern", "PATTERN")
+writeFile("null_in_first_1k", "\0PATTERN")
+writeFile("null_after_first_1k", initString(1000) & "\0")
+writeFile("empty", "")
+writeFile("context_match_filtering", """
+-
+CONTEXTPAT
+-
+PATTERN
+-
+-
+-
+
+-
+-
+-
+PATTERN
+-
+-
+-
+""")
+writeFile("only_the_pattern.txt", "PATTERN")
+writeFile("only_the_pattern.ascii", "PATTERN")
+
+
+#=======
+# tests
+#=======
+
+suite "nimgrep filesystem":
+
+  test "`--filename` with matching file":
+    nimgrep "-r --filename:KJKJHSFSFKASHFBKAF PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == fixSlash dedent"""
+        ./do_not_create_another_file_with_this_pattern_KJKJHSFSFKASHFBKAF:1: PATTERN
+        1 matches
+        """
+
+
+  test "`--dirname` with matching dir":
+    nimgrep "-r --dirname:.hid PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == fixSlash dedent"""
+        .hidden/only_the_pattern:1: PATTERN
+        1 matches
+        """
+
+  let only_the_pattern = fixSlash dedent"""
+        a/b/only_the_pattern:1: PATTERN
+        c/b/only_the_pattern:1: PATTERN
+        2 matches
+        """
+
+  let only_a = fixSlash dedent"""
+        a/b/only_the_pattern:1: PATTERN
+        1 matches
+        """
+
+  test "`--dirname` with matching grandparent path segment":
+    nimgrep "-r --dirname:a PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == only_a
+
+  test "`--dirpath` with matching grandparent path segment":
+    nimgrep "-r --dirp:a PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == only_a
+
+  test "`--dirpath` with matching grandparent path segment":
+    nimgrep "-r --dirpath:a/b PATTERN".fixSlash
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == only_a
+
+
+  test "`--dirname` with matching parent path segment":
+    nimgrep "-r --dirname:b PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == only_the_pattern
+
+  test "`--dirpath` with matching parent path segment":
+    nimgrep "-r --dirpath:b PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == only_the_pattern
+
+
+  let patterns_without_directory_a_b = fixSlash dedent"""
+        ./context_match_filtering:4: PATTERN
+        ./context_match_filtering:12: PATTERN
+        ./do_not_create_another_file_with_this_pattern_KJKJHSFSFKASHFBKAF:1: PATTERN
+        ./null_in_first_1k:1: """ & "\0PATTERN\n" & dedent"""
+        ./only_the_pattern.ascii:1: PATTERN
+        ./only_the_pattern.txt:1: PATTERN
+        .hidden/only_the_pattern:1: PATTERN
+        c/b/only_the_pattern:1: PATTERN
+        8 matches
+        """
+
+  let patterns_without_directory_b = fixSlash dedent"""
+        ./context_match_filtering:4: PATTERN
+        ./context_match_filtering:12: PATTERN
+        ./do_not_create_another_file_with_this_pattern_KJKJHSFSFKASHFBKAF:1: PATTERN
+        ./null_in_first_1k:1: """ & "\0PATTERN\n" & dedent"""
+        ./only_the_pattern.ascii:1: PATTERN
+        ./only_the_pattern.txt:1: PATTERN
+        .hidden/only_the_pattern:1: PATTERN
+        7 matches
+        """
+
+  test "`--ndirname` not matching grandparent path segment":
+    nimgrep "-r --ndirname:a PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == patterns_without_directory_a_b
+
+  test "`--ndirname` not matching parent path segment":
+    nimgrep "-r --ndirname:b PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == patterns_without_directory_b
+
+  test "`--notdirpath` not matching grandparent path segment":
+    nimgrep "-r --notdirpath:a PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == patterns_without_directory_a_b
+
+  test "`--notdirpath` not matching parent path segment":
+    nimgrep "-r --ndirp:b PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == patterns_without_directory_b
+
+  test "`--notdirpath` with matching grandparent/parent path segment":
+    nimgrep "-r --ndirp:a/b PATTERN".fixSlash
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == patterns_without_directory_a_b
+
+
+  test "`--text`, `-t`, `--bin:off` with file containing a null in first 1k chars":
+    nimgrep "-r --text PATTERN null_in_first_1k"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == "0 matches\n"
+    checkpoint "`--text`"
+    nimgrep "-r -t PATTERN null_in_first_1k"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == "0 matches\n"
+    checkpoint "`-t`"
+    nimgrep "-r --bin:off PATTERN null_in_first_1k"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == "0 matches\n"
+    checkpoint "`--binary:off`"
+
+
+  test "`--bin:only` with file containing a null in first 1k chars":
+    nimgrep "--bin:only -@ PATTERN null_in_first_1k null_after_first_1k only_the_pattern.txt"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == dedent"""
+        null_in_first_1k:1: ^@PATTERN
+        1 matches
+        """
+
+
+  test "`--bin:only` with file containing a null after first 1k chars":
+    nimgrep "--bin:only PATTERN null_after_first_1k only_the_pattern.txt"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == "0 matches\n"
+
+
+  # TODO: we need to throw a warning if e.g. both extension was provided and
+  # inappropriate filename was directly provided via command line
+  #
+  #  test "`--ext:doesnotexist` without a matching file":
+  #    # skip() # FIXME: this test fails
+  #    nimgrep "--ext:doesnotexist PATTERN context_match_filtering only_the_pattern.txt"
+  #    check ngExitCode == 0
+  #    check ngStdErr.len == 0
+  #    check ngStdOut == """
+  #0 matches
+  #"""
+  #
+  #
+  #  test "`--ext:txt` with a matching file":
+  #    nimgrep "--ext:txt PATTERN context_match_filtering only_the_pattern.txt"
+  #    check ngExitCode == 0
+  #    check ngStdErr.len == 0
+  #    check ngStdOut == """
+  #only_the_pattern.txt:1: PATTERN
+  #1 matches
+  #"""
+  #
+  #
+  #  test "`--ext:txt|doesnotexist` with some matching files":
+  #    nimgrep "--ext:txt|doesnotexist PATTERN context_match_filtering only_the_pattern.txt only_the_pattern.ascii"
+  #    check ngExitCode == 0
+  #    check ngStdErr.len == 0
+  #    check ngStdOut == """
+  #only_the_pattern.txt:1: PATTERN
+  #1 matches
+  #"""
+  #
+  #
+  #  test "`--ext` with some matching files":
+  #    nimgrep "--ext PATTERN context_match_filtering only_the_pattern.txt only_the_pattern.ascii"
+  #    check ngExitCode == 0
+  #    check ngStdErr.len == 0
+  #    check ngStdOut == """
+  #context_match_filtering:4: PATTERN
+  #context_match_filtering:12: PATTERN
+  #2 matches
+  #"""
+  #
+  #
+  #  test "`--ext:txt --ext` with some matching files":
+  #    nimgrep "--ext:txt --ext PATTERN context_match_filtering only_the_pattern.txt only_the_pattern.ascii"
+  #    check ngExitCode == 0
+  #    check ngStdErr.len == 0
+  #    check ngStdOut == """
+  #context_match_filtering:4: PATTERN
+  #context_match_filtering:12: PATTERN
+  #only_the_pattern.txt:1: PATTERN
+  #3 matches
+  #"""
+
+
+suite "nimgrep contents filtering":
+
+  test "`--inFile` with matching file":
+    nimgrep "-r --inf:CONTEXTPAT PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == fixSlash dedent"""
+        ./context_match_filtering:4: PATTERN
+        ./context_match_filtering:12: PATTERN
+        2 matches
+        """
+
+
+  test "`--notinFile` with matching files":
+    nimgrep "-r --ninf:CONTEXTPAT PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == fixSlash dedent"""
+        ./do_not_create_another_file_with_this_pattern_KJKJHSFSFKASHFBKAF:1: PATTERN
+        ./null_in_first_1k:1: """ & "\0PATTERN\n" & dedent"""
+        ./only_the_pattern.ascii:1: PATTERN
+        ./only_the_pattern.txt:1: PATTERN
+        .hidden/only_the_pattern:1: PATTERN
+        a/b/only_the_pattern:1: PATTERN
+        c/b/only_the_pattern:1: PATTERN
+        7 matches
+        """
+
+
+  test "`--inContext` with missing context option":
+    # Using `--inContext` implies default -c:1 is used
+    nimgrep "-r --inContext:CONTEXTPAT PATTERN"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == "0 matches\n"
+
+
+  test "`--inContext` with PAT matching PATTERN":
+    # This tests the scenario where PAT always matches PATTERN and thus
+    # has the same effect as excluding the `inContext` option.
+    # I'm not sure of the desired behaviour here.
+    nimgrep "--context:2 --inc:PAT PATTERN context_match_filtering"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == dedent"""
+        context_match_filtering:2  CONTEXTPAT
+        context_match_filtering:3  -
+        context_match_filtering:4: PATTERN
+        context_match_filtering:5  -
+        context_match_filtering:6  -
+
+        context_match_filtering:10  -
+        context_match_filtering:11  -
+        context_match_filtering:12: PATTERN
+        context_match_filtering:13  -
+        context_match_filtering:14  -
+
+        2 matches
+        """
+
+
+  test "`--inContext` with PAT in context":
+    nimgrep "--context:2 --inContext:CONTEXTPAT PATTERN context_match_filtering"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == dedent"""
+        context_match_filtering:2  CONTEXTPAT
+        context_match_filtering:3  -
+        context_match_filtering:4: PATTERN
+        context_match_filtering:5  -
+        context_match_filtering:6  -
+
+        1 matches
+        """
+
+
+  test "`--notinContext` with PAT matching some contexts":
+    nimgrep "--context:2 --ninContext:CONTEXTPAT PATTERN context_match_filtering"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == dedent"""
+        context_match_filtering:10  -
+        context_match_filtering:11  -
+        context_match_filtering:12: PATTERN
+        context_match_filtering:13  -
+        context_match_filtering:14  -
+
+        1 matches
+        """
+
+
+  test "`--notinContext` with PAT not matching any of the contexts":
+    nimgrep "--context:1 --ninc:CONTEXTPAT PATTERN context_match_filtering"
+    check ngExitCode == 0
+    check ngStdErr.len == 0
+    check ngStdOut == dedent"""
+        context_match_filtering:3  -
+        context_match_filtering:4: PATTERN
+        context_match_filtering:5  -
+
+        context_match_filtering:11  -
+        context_match_filtering:12: PATTERN
+        context_match_filtering:13  -
+
+        2 matches
+        """
+
+
+#=========
+# cleanup
+#=========
+
+setCurrentDir previousDir
+removeDir testFilesRoot
diff --git a/tests/tools/tunused_imports.nim b/tests/tools/tunused_imports.nim
index bce906634..539608ad6 100644
--- a/tests/tools/tunused_imports.nim
+++ b/tests/tools/tunused_imports.nim
@@ -1,9 +1,12 @@
 discard """
-  cmd: '''nim c --hint[Processing]:off $file'''
+  cmd: '''nim c --hint:Processing:off $file'''
   nimout: '''
-tunused_imports.nim(11, 10) Warning: BEGIN [User]
-tunused_imports.nim(36, 10) Warning: END [User]
-tunused_imports.nim(34, 8) Warning: imported and not used: 'strutils' [UnusedImport]
+tunused_imports.nim(14, 10) Warning: BEGIN [User]
+tunused_imports.nim(41, 10) Warning: END [User]
+tunused_imports.nim(37, 8) Warning: imported and not used: 'strutils' [UnusedImport]
+tunused_imports.nim(38, 13) Warning: imported and not used: 'strtabs' [UnusedImport]
+tunused_imports.nim(38, 22) Warning: imported and not used: 'cstrutils' [UnusedImport]
+tunused_imports.nim(39, 12) Warning: imported and not used: 'macrocache' [UnusedImport]
 '''
   action: "compile"
 """
@@ -32,5 +35,7 @@ macro bar(): untyped =
 bar()
 
 import strutils
+import std/[strtabs, cstrutils]
+import std/macrocache
 
 {.warning: "END".}
diff --git a/tests/trmacros/tdisallowif.nim b/tests/trmacros/tdisallowif.nim
index 36f60800e..8d83f6ddf 100644
--- a/tests/trmacros/tdisallowif.nim
+++ b/tests/trmacros/tdisallowif.nim
@@ -1,7 +1,6 @@
 discard """
-  errormsg: "usage of 'disallowIf' is a user-defined error"
+  errormsg: "usage of 'disallowIf' is an {.error.} defined at tdisallowif.nim(10, 1)"
   line: 24
-  disabled: true
 """
 
 template optZero{x+x}(x: int): int = x*3
@@ -11,7 +10,7 @@ template optSubstr1{x = substr(x, 0, b)}(x: string, b: int) = setlen(x, b+1)
 template disallowIf{
   if cond: action
   else: action2
-}(cond: bool, action, action2: stmt) {.error.} = action
+}(cond: bool, action, action2: typed) {.error.} = action
 
 var y = 12
 echo y+y
diff --git a/tests/trmacros/tnorewrite.nim b/tests/trmacros/tnorewrite.nim
new file mode 100644
index 000000000..e6769246f
--- /dev/null
+++ b/tests/trmacros/tnorewrite.nim
@@ -0,0 +1,20 @@
+block:
+  proc get(x: int): int = x
+
+  template t{get(a)}(a: int): int =
+    {.noRewrite.}:
+      get(a) + 1
+
+  doAssert get(0) == 1
+
+block:
+  var x: int
+
+  template asgn{a = b}(a: int{lvalue}, b: int) =
+    let newVal = b + 1
+    # ^ this is needed but should it be?
+    {.noRewrite.}:
+      a = newVal
+
+  x = 10
+  doAssert x == 11, $x
diff --git a/tests/trmacros/tor.nim b/tests/trmacros/tor.nim
index 087dc0d68..9defc4d1b 100644
--- a/tests/trmacros/tor.nim
+++ b/tests/trmacros/tor.nim
@@ -1,11 +1,23 @@
 discard """
-  output: '''0
+  output: '''
+3
+30
 true
-3'''
+'''
 """
 
+
+# bug #798
+template t012{(0|1|2){x}}(x: untyped): untyped = x+1
+let z = 1
+# outputs 3 thanks to fixpoint iteration:
+echo z
+
+
 template arithOps: untyped = (`+` | `-` | `*`)
-template testOr{ (arithOps{f})(a, b) }(a, b, f: untyped): untyped = f(a mod 10, b)
+template testOr{ (arithOps{f})(a, b) }(a, b, f: untyped): untyped =
+  {.noRewrite.}:
+    f(a mod 10, b)
 
 let xx = 10
 echo 10*xx
@@ -20,9 +32,3 @@ var
   c = false
 a = b and a
 echo a
-
-# bug #798
-template t012{(0|1|2){x}}(x: untyped): untyped = x+1
-let z = 1
-# outputs 3 thanks to fixpoint iteration:
-echo z
diff --git a/tests/trmacros/trmacros_various.nim b/tests/trmacros/trmacros_various.nim
index 74b248739..8fe51e548 100644
--- a/tests/trmacros/trmacros_various.nim
+++ b/tests/trmacros/trmacros_various.nim
@@ -33,7 +33,8 @@ block tcse:
 
 block hoist:
   template optPeg{peg(pattern)}(pattern: string{lit}): Peg =
-    var gl {.global, gensym.} = peg(pattern)
+    {.noRewrite.}:
+      var gl {.global, gensym.} = peg(pattern)
     gl
   doAssert match("(a b c)", peg"'(' @ ')'")
   doAssert match("W_HI_Le", peg"\y 'while'")
diff --git a/tests/trmacros/trmacros_various2.nim b/tests/trmacros/trmacros_various2.nim
index c1367cb1b..981df4ca6 100644
--- a/tests/trmacros/trmacros_various2.nim
+++ b/tests/trmacros/trmacros_various2.nim
@@ -33,8 +33,8 @@ block tpartial:
   proc p(x, y: int; cond: bool): int =
     result = if cond: x + y else: x - y
 
-  template optP{p(x, y, true)}(x, y): untyped = x - y
-  template optP{p(x, y, false)}(x, y): untyped = x + y
+  template optPTrue{p(x, y, true)}(x, y): untyped = x - y
+  template optPFalse{p(x, y, false)}(x, y): untyped = x + y
 
   echo p(2, 4, true)
 
@@ -70,7 +70,9 @@ block tstar:
     for i in 1..len(s)-1: result.add s[i]
     inc calls
 
-  template optConc{ `&&` * a }(a: string): string = &&a
+  template optConc{ `&&` * a }(a: string): string =
+    {.noRewrite.}:
+      &&a
 
   let space = " "
   echo "my" && (space & "awe" && "some " ) && "concat"
diff --git a/tests/tuples/mnimsconstunpack.nim b/tests/tuples/mnimsconstunpack.nim
new file mode 100644
index 000000000..65fafc12f
--- /dev/null
+++ b/tests/tuples/mnimsconstunpack.nim
@@ -0,0 +1,4 @@
+proc foo(): tuple[a, b: string] =
+  result = ("a", "b")
+
+const (a, b*) = foo()
diff --git a/tests/tuples/t12892.nim b/tests/tuples/t12892.nim
new file mode 100644
index 000000000..d69e99c7f
--- /dev/null
+++ b/tests/tuples/t12892.nim
@@ -0,0 +1,8 @@
+discard """
+  disabled: i386
+"""
+
+template works[T](): auto = T.high - 1
+template breaks[T](): auto = (T.high - 1, true)
+doAssert $works[uint]() == "18446744073709551614"
+doAssert $breaks[uint]() == "(18446744073709551614, true)"
diff --git a/tests/tuples/t18125_1.nim b/tests/tuples/t18125_1.nim
new file mode 100644
index 000000000..74fdfe8f5
--- /dev/null
+++ b/tests/tuples/t18125_1.nim
@@ -0,0 +1,14 @@
+# issue #18125 solved with type inference
+
+type
+  Parent = ref object of RootObj
+
+  Child = ref object of Parent
+    c: char
+
+func foo(c: char): (Parent, int) =
+  # Works if you use (Parent(Child(c: c)), 0)
+  (Child(c: c), 0)
+
+let x = foo('x')[0]
+doAssert Child(x).c == 'x'
diff --git a/tests/tuples/t18125_2.nim b/tests/tuples/t18125_2.nim
new file mode 100644
index 000000000..fe0a4a8bb
--- /dev/null
+++ b/tests/tuples/t18125_2.nim
@@ -0,0 +1,20 @@
+discard """
+  errormsg: "type mismatch: got <(Child, int)> but expected '(Parent, int)'"
+  line: 17
+"""
+
+# issue #18125 solved with correct type relation
+
+type
+  Parent = ref object of RootObj
+
+  Child = ref object of Parent
+    c: char
+
+func foo(c: char): (Parent, int) =
+  # Works if you use (Parent(Child(c: c)), 0)
+  let x = (Child(c: c), 0)
+  x
+
+let x = foo('x')[0]
+doAssert Child(x).c == 'x'
diff --git a/tests/tuples/t7012.nim b/tests/tuples/t7012.nim
new file mode 100644
index 000000000..32d441ddd
--- /dev/null
+++ b/tests/tuples/t7012.nim
@@ -0,0 +1,7 @@
+discard """
+  errormsg: "illegal recursion in type 'Node'"
+"""
+
+type Node[T] = tuple
+    next: ref Node[T]
+var n: Node[int]
\ No newline at end of file
diff --git a/tests/tuples/tinferred_generic_const.nim b/tests/tuples/tinferred_generic_const.nim
new file mode 100644
index 000000000..5ab730c38
--- /dev/null
+++ b/tests/tuples/tinferred_generic_const.nim
@@ -0,0 +1,14 @@
+discard """
+  action: run
+"""
+block:
+  proc something(a: string or int or float) =
+    const (c, d) = (default a.type, default a.type)
+
+block:
+  proc something(a: string or int) =
+    const c = default a.type
+
+block:
+  proc something(a: string or int) =
+    const (c, d, e) = (default a.type, default a.type, default a.type)
diff --git a/tests/tuples/tnimsconstunpack.nim b/tests/tuples/tnimsconstunpack.nim
new file mode 100644
index 000000000..7860fc0a4
--- /dev/null
+++ b/tests/tuples/tnimsconstunpack.nim
@@ -0,0 +1,8 @@
+discard """
+  action: compile
+  cmd: "nim e $file"
+"""
+
+import mnimsconstunpack
+
+doAssert b == "b"
diff --git a/tests/tuples/ttuples_issues.nim b/tests/tuples/ttuples_issues.nim
index 9380bd027..70defdfce 100644
--- a/tests/tuples/ttuples_issues.nim
+++ b/tests/tuples/ttuples_issues.nim
@@ -1,77 +1,133 @@
 discard """
-output: '''
-'''
+  targets: "c cpp js"
 """
 
-
-import tables
-
-
-block t4479:
-  type
-    MyTuple = tuple
-      num: int
-      strings: seq[string]
-      ints: seq[int]
-
-  var foo = MyTuple((
-    num: 7,
-    strings: @[],
-    ints: @[],
-  ))
-
-  var bar = (
-    num: 7,
-    strings: @[],
-    ints: @[],
-  ).MyTuple
-
-  var fooUnnamed = MyTuple((7, @[], @[]))
-  var n = 7
-  var fooSym = MyTuple((num: n, strings: @[], ints: @[]))
-
-
-block t1910:
-  var p = newOrderedTable[tuple[a:int], int]()
-  var q = newOrderedTable[tuple[x:int], int]()
-  for key in p.keys:
-    echo key.a
-  for key in q.keys:
-    echo key.x
-
-
-block t2121:
-  type
-    Item[K,V] = tuple
-      key: K
-      value: V
-
-  var q = newseq[Item[int,int]](1)
-  let (x,y) = q[0]
-
-
-block t2369:
-  type HashedElem[T] = tuple[num: int, storedVal: ref T]
-
-  proc append[T](tab: var seq[HashedElem[T]], n: int, val: ref T) =
-      #tab.add((num: n, storedVal: val))
-      var he: HashedElem[T] = (num: n, storedVal: val)
-      #tab.add(he)
-
-  var g: seq[HashedElem[int]] = @[]
-
-  proc foo() =
-      var x: ref int
-      new(x)
-      x[] = 77
-      g.append(44, x)
-
-
-block t1986:
-  proc test(): int64 =
-    return 0xdeadbeef.int64
-
-  const items = [
-    (var1: test(), var2: 100'u32),
-    (var1: test(), var2: 192'u32)
-  ]
+# targets include `cpp` because in the past, there were several cpp-specific bugs with tuples.
+
+import std/tables
+
+template main() =
+  block: # bug #4479
+    type
+      MyTuple = tuple
+        num: int
+        strings: seq[string]
+        ints: seq[int]
+
+    var foo = MyTuple((
+      num: 7,
+      strings: @[],
+      ints: @[],
+    ))
+
+    var bar = MyTuple (
+      num: 7,
+      strings: @[],
+      ints: @[],
+    )
+
+    var fooUnnamed = MyTuple((7, @[], @[]))
+    var n = 7
+    var fooSym = MyTuple((num: n, strings: @[], ints: @[]))
+
+  block: # bug #1910
+    var p = newOrderedTable[tuple[a:int], int]()
+    var q = newOrderedTable[tuple[x:int], int]()
+    for key in p.keys:
+      echo key.a
+    for key in q.keys:
+      echo key.x
+
+  block: # bug #2121
+    type
+      Item[K,V] = tuple
+        key: K
+        value: V
+
+    var q = newseq[Item[int,int]](1)
+    let (x,y) = q[0]
+
+  block: # bug #2369
+    type HashedElem[T] = tuple[num: int, storedVal: ref T]
+
+    proc append[T](tab: var seq[HashedElem[T]], n: int, val: ref T) =
+        #tab.add((num: n, storedVal: val))
+        var he: HashedElem[T] = (num: n, storedVal: val)
+        #tab.add(he)
+
+    var g: seq[HashedElem[int]] = @[]
+
+    proc foo() =
+        var x: ref int
+        new(x)
+        x[] = 77
+        g.append(44, x)
+
+  block: # bug #1986
+    proc test(): int64 =
+      return 0xdeadbeef.int64
+
+    const items = [
+      (var1: test(), var2: 100'u32),
+      (var1: test(), var2: 192'u32)
+    ]
+
+  block: # bug #14911
+    doAssert $(a: 1) == "(a: 1)" # works
+    doAssert $(`a`: 1) == "(a: 1)"  # works
+    doAssert $(`a`: 1, `b`: 2) == "(a: 1, b: 2)" # was: Error: named expression expected
+
+  block: # bug #16822
+    var scores: seq[(set[char], int)] = @{{'/'} : 10}
+
+    var x1: set[char]
+    for item in items(scores):
+      x1 = item[0]
+
+    doAssert x1 == {'/'}
+
+    var x2: set[char]
+    for (chars, value) in items(scores):
+      x2 = chars
+
+    doAssert x2 == {'/'}
+
+  block: # bug #14574
+    proc fn(): auto =
+      let a = @[("foo", (12, 13))]
+      for (k,v) in a:
+        return (k,v)
+    doAssert fn() == ("foo", (12, 13))
+
+  block: # bug #14574
+    iterator fn[T](a:T): lent T = yield a
+    let a = (10, (11,))
+    proc bar(): auto =
+      for (x,y) in fn(a):
+        return (x,y)
+    doAssert bar() == (10, (11,))
+
+  block: # bug #16331
+    type T1 = tuple[a, b: int]
+
+    proc p(b: bool): T1 =
+      var x: T1 = (10, 20)
+      x = if b: (x.b, x.a) else: (-x.b, -x.a)
+      x
+
+    doAssert p(false) == (-20, -10)
+    doAssert p(true) == (20, 10)
+
+
+proc mainProc() =
+  # other tests should be in `main`
+  block:
+    type A = tuple[x: int, y: int]
+    doAssert (x: 1, y: 2).A == A (x: 1, y: 2) # MCS => can't use a template
+
+static:
+  main()
+  mainProc()
+
+main()
+mainProc()
diff --git a/tests/tuples/ttuples_various.nim b/tests/tuples/ttuples_various.nim
index dc060da1e..e392731d2 100644
--- a/tests/tuples/ttuples_various.nim
+++ b/tests/tuples/ttuples_various.nim
@@ -171,3 +171,41 @@ block tuple_with_seq:
     echo s
     (s, 7)
   t = test(t.a)
+
+block: # bug #22049
+  type A = object
+    field: tuple[a, b, c: seq[int]]
+
+  func value(v: var A): var tuple[a, b, c: seq[int]] =
+    v.field
+  template get(v: A): tuple[a, b, c: seq[int]] = v.value
+
+  var v = A(field: (@[1], @[2], @[3]))
+  var (a, b, c) = v.get()
+
+  doAssert a == @[1]
+  doAssert b == @[2]
+  doAssert c == @[3]
+
+block: # bug #22054
+  type A = object
+    field: tuple[a: int]
+
+  func value(v: var A): var tuple[a: int] =
+    v.field
+  template get(v: A): tuple[a: int] = v.value
+
+  var v = A(field: (a: 1314))
+  doAssert get(v)[0] == 1314
+
+block: # tuple unpacking assignment with underscore
+  var
+    a = 1
+    b = 2
+  doAssert (a, b) == (1, 2)
+  (a, _) = (3, 4)
+  doAssert (a, b) == (3, 2)
+  (_, a) = (5, 6)
+  doAssert (a, b) == (6, 2)
+  (b, _) = (7, 8)
+  doAssert (a, b) == (6, 7)
diff --git a/tests/tuples/tuple_with_nil.nim b/tests/tuples/tuple_with_nil.nim
index b3ed2a96b..9cad6eccd 100644
--- a/tests/tuples/tuple_with_nil.nim
+++ b/tests/tuples/tuple_with_nil.nim
@@ -1,23 +1,16 @@
 import macros
-from strutils import IdentStartChars
 import parseutils
 import unicode
 import math
-import fenv
 import pegs
 import streams
 
 type
-  FormatError = object of Exception ## Error in the format string.
+  FormatError = object of CatchableError ## Error in the format string.
 
   Writer = concept W
     ## Writer to output a character `c`.
-    when (NimMajor, NimMinor, NimPatch) > (0, 10, 2):
-      write(W, 'c')
-    else:
-      block:
-        var x: W
-        write(x, char)
+    write(W, 'c')
 
   FmtAlign = enum ## Format alignment
     faDefault  ## default for given format type
@@ -484,7 +477,7 @@ proc writeformat(o: var Writer; b: bool; fmt: Format) =
   else:
     raise newException(FormatError, "Boolean values must of one of the following types: s,b,o,x,X,d,n")
 
-proc writeformat(o: var Writer; ary: openarray[system.any]; fmt: Format) =
+proc writeformat(o: var Writer; ary: openArray[system.any]; fmt: Format) =
   ## Write array `ary` according to format `fmt` using output object
   ## `o` and output function `add`.
   if ary.len == 0: return
@@ -664,7 +657,7 @@ proc literal[T](x: T): NimNode {.compiletime, nosideeffect.} =
     result = newLit(x)
 
 proc generatefmt(fmtstr: string;
-                 args: var openarray[tuple[arg:NimNode, cnt:int]];
+                 args: var openArray[tuple[arg:NimNode, cnt:int]];
                  arg: var int;): seq[tuple[val, fmt:NimNode]] {.compiletime.} =
   ## fmtstr
   ##   the format string
diff --git a/tests/typerel/t4799_1.nim b/tests/typerel/t4799_1.nim
index e66aa1a9a..03d2a0cfa 100644
--- a/tests/typerel/t4799_1.nim
+++ b/tests/typerel/t4799_1.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:refc"
   targets: "c cpp"
-  outputsub: '''ObjectAssignmentError'''
+  outputsub: '''ObjectAssignmentDefect'''
   exitcode: "1"
 """
 
diff --git a/tests/typerel/t4799_2.nim b/tests/typerel/t4799_2.nim
index ff20c2426..ef8571f25 100644
--- a/tests/typerel/t4799_2.nim
+++ b/tests/typerel/t4799_2.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:refc"
   targets: "c cpp"
-  outputsub: '''ObjectAssignmentError'''
+  outputsub: '''ObjectAssignmentDefect'''
   exitcode: "1"
 """
 
diff --git a/tests/typerel/t4799_3.nim b/tests/typerel/t4799_3.nim
index 4a8a158dd..26258b983 100644
--- a/tests/typerel/t4799_3.nim
+++ b/tests/typerel/t4799_3.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:refc"
   targets: "c cpp"
-  outputsub: '''ObjectAssignmentError'''
+  outputsub: '''ObjectAssignmentDefect'''
   exitcode: "1"
 """
 
diff --git a/tests/typerel/t7600_1.nim b/tests/typerel/t7600_1.nim
index e9d01bd0d..83f93ae7f 100644
--- a/tests/typerel/t7600_1.nim
+++ b/tests/typerel/t7600_1.nim
@@ -1,6 +1,6 @@
 discard """
 errormsg: "type mismatch: got <Thin[system.int]>"
-nimout: '''t7600_1.nim(21, 6) Error: type mismatch: got <Thin[system.int]>
+nimout: '''t7600_1.nim(21, 1) Error: type mismatch: got <Thin[system.int]>
 but expected one of:
 proc test[T](x: Paper[T])
   first type mismatch at position: 1
diff --git a/tests/typerel/t7600_2.nim b/tests/typerel/t7600_2.nim
index 371707f4c..9488a44bc 100644
--- a/tests/typerel/t7600_2.nim
+++ b/tests/typerel/t7600_2.nim
@@ -1,6 +1,6 @@
 discard """
 errormsg: "type mismatch: got <Thin>"
-nimout: '''t7600_2.nim(20, 6) Error: type mismatch: got <Thin>
+nimout: '''t7600_2.nim(20, 1) Error: type mismatch: got <Thin>
 but expected one of:
 proc test(x: Paper)
   first type mismatch at position: 1
diff --git a/tests/typerel/tcommontype.nim b/tests/typerel/tcommontype.nim
index 8215ebd5e..f32228177 100644
--- a/tests/typerel/tcommontype.nim
+++ b/tests/typerel/tcommontype.nim
@@ -1,5 +1,5 @@
 type
-  TAnimal=object {.inheritable.}
+  TAnimal{.inheritable.}=object
   PAnimal=ref TAnimal
 
   TDog=object of TAnimal
@@ -12,7 +12,7 @@ type
 
 proc newDog():PDog = new(result)
 proc newCat():PCat = new(result)
-proc test(a:openarray[PAnimal])=
+proc test(a:openArray[PAnimal])=
   echo("dummy")
 
 #test(newDog(),newCat()) #does not work
diff --git a/tests/typerel/texplicitcmp.nim b/tests/typerel/texplicitcmp.nim
index b11aa2f4e..57f1e81b6 100644
--- a/tests/typerel/texplicitcmp.nim
+++ b/tests/typerel/texplicitcmp.nim
@@ -8,7 +8,7 @@ discard """
 
 import json, tables, algorithm
 
-proc outp(a: openarray[int]) =
+proc outp(a: openArray[int]) =
   stdout.write "["
   for i in a: stdout.write($i & " ")
   stdout.write "]\n"
diff --git a/tests/typerel/tnoargopenarray.nim b/tests/typerel/tnoargopenarray.nim
deleted file mode 100644
index 9e2b2fb86..000000000
--- a/tests/typerel/tnoargopenarray.nim
+++ /dev/null
@@ -1,8 +0,0 @@
-discard """
-action: compile
-"""
-
-import db_sqlite
-
-var db: DbConn
-exec(db, sql"create table blabla()")
diff --git a/tests/typerel/tproctypeclass.nim b/tests/typerel/tproctypeclass.nim
new file mode 100644
index 000000000..e8fab9780
--- /dev/null
+++ b/tests/typerel/tproctypeclass.nim
@@ -0,0 +1,89 @@
+import std/assertions
+
+proc main =
+  iterator closureIter(): int {.closure.} =
+    yield 1
+    yield 2
+  iterator inlineIter(): int {.inline.} =
+    yield 1
+    yield 2
+  proc procNotIter(): int = 1
+
+  doAssert closureIter is iterator
+  doAssert inlineIter is iterator
+  doAssert procNotIter isnot iterator
+
+  doAssert closureIter isnot proc
+  doAssert inlineIter isnot proc
+  doAssert procNotIter is proc
+
+  doAssert typeof(closureIter) is iterator
+  doAssert typeof(inlineIter) is iterator
+  doAssert typeof(procNotIter) isnot iterator
+
+  doAssert typeof(closureIter) isnot proc
+  doAssert typeof(inlineIter) isnot proc
+  doAssert typeof(procNotIter) is proc
+
+  block:
+    proc fn1(iter: iterator {.closure.}) = discard
+    proc fn2[T: iterator {.closure.}](iter: T) = discard
+
+    fn1(closureIter)
+    fn2(closureIter)
+
+    doAssert not compiles(fn1(procNotIter))
+    doAssert not compiles(fn2(procNotIter))
+
+    doAssert not compiles(fn1(inlineIter))
+    doAssert not compiles(fn2(inlineIter))
+
+  block: # concrete iterator type
+    proc fn1(iter: iterator(): int) = discard
+    proc fn2[T: iterator(): int](iter: T) = discard
+
+    fn1(closureIter)
+    fn2(closureIter)
+
+    doAssert not compiles(fn1(procNotIter))
+    doAssert not compiles(fn2(procNotIter))
+
+    doAssert not compiles(fn1(inlineIter))
+    doAssert not compiles(fn2(inlineIter))
+
+  proc takesNimcall[T: proc {.nimcall.}](p: T) = discard
+  proc takesClosure[T: proc {.closure.}](p: T) = discard
+  proc takesAnyProc[T: proc](p: T) = discard
+
+  proc nimcallProc(): int {.nimcall.} = 1
+  proc closureProc(): int {.closure.} = 2
+
+  doAssert nimcallProc is proc {.nimcall.}
+  takesNimcall(nimcallProc)
+  doAssert closureProc isnot proc {.nimcall.}
+  doAssert not compiles(takesNimcall(closureProc))
+
+  doAssert nimcallProc isnot proc {.closure.}
+  doAssert not compiles(takesClosure(nimcallProc))
+  doAssert closureProc is proc {.closure.}
+  takesClosure(closureProc)
+  
+  doAssert nimcallProc is proc
+  takesAnyProc(nimcallProc)
+  doAssert closureProc is proc
+  takesAnyProc(closureProc)
+
+  block: # supposed to test that sameType works 
+    template ensureNotRedefine(Ty): untyped =
+      proc foo[T: Ty](x: T) = discard
+      doAssert not (compiles do:
+        proc bar[T: Ty](x: T) = discard
+        proc bar[T: Ty](x: T) = discard)
+    ensureNotRedefine proc
+    ensureNotRedefine iterator
+    ensureNotRedefine proc {.nimcall.}
+    ensureNotRedefine iterator {.nimcall.}
+    ensureNotRedefine proc {.closure.}
+    ensureNotRedefine iterator {.closure.}
+
+main()
diff --git a/tests/typerel/tregionptrs.nim b/tests/typerel/tregionptrs.nim
deleted file mode 100644
index 504ec1011..000000000
--- a/tests/typerel/tregionptrs.nim
+++ /dev/null
@@ -1,16 +0,0 @@
-discard """
-  errormsg: "type mismatch: got <BPtr> but expected 'APtr = ptr[RegionA, int]'"
-  line: 16
-"""
-
-type
-  RegionA = object
-  APtr = RegionA ptr int
-  RegionB = object
-  BPtr = RegionB ptr int
-
-var x,xx: APtr
-var y: BPtr
-x = nil
-x = xx
-x = y
diff --git a/tests/typerel/tsigmatch.nim b/tests/typerel/tsigmatch.nim
new file mode 100644
index 000000000..7541f2028
--- /dev/null
+++ b/tests/typerel/tsigmatch.nim
@@ -0,0 +1,6 @@
+block: # bug #13618
+  proc test(x: Natural or BackwardsIndex): int =
+    int(x)
+
+  doAssert test(^1) == 1
+  doAssert test(1) == 1
diff --git a/tests/typerel/tstr_as_openarray.nim b/tests/typerel/tstr_as_openarray.nim
index fc28d6c93..14cd21479 100644
--- a/tests/typerel/tstr_as_openarray.nim
+++ b/tests/typerel/tstr_as_openarray.nim
@@ -3,18 +3,18 @@ discard """
 """
 var s = "HI"
 
-proc x (zz: openarray[char]) =
+proc x (zz: openArray[char]) =
   discard
 
 x s
 
-proc z [T] (zz: openarray[T]) =
+proc z [T] (zz: openArray[T]) =
   discard
 
 z s
 z([s,s,s])
 
-proc y [T] (arg: var openarray[T]) =
+proc y [T] (arg: var openArray[T]) =
   arg[0] = 'X'
 y s
 doAssert s == "XI"
diff --git a/tests/typerel/ttynilinstantiation.nim b/tests/typerel/ttynilinstantiation.nim
new file mode 100644
index 000000000..303506689
--- /dev/null
+++ b/tests/typerel/ttynilinstantiation.nim
@@ -0,0 +1,7 @@
+proc foo[T: proc](x: T) =
+  # old error here:
+  let y = x
+  # invalid type: 'typeof(nil)' for let
+
+foo(nil) #[tt.Error
+   ^ type mismatch: got <typeof(nil)>]#
diff --git a/tests/typerel/ttypedesc_as_genericparam1.nim b/tests/typerel/ttypedesc_as_genericparam1.nim
index b7c3e727d..8fdcf217e 100644
--- a/tests/typerel/ttypedesc_as_genericparam1.nim
+++ b/tests/typerel/ttypedesc_as_genericparam1.nim
@@ -1,6 +1,7 @@
 discard """
-  errormsg: "type mismatch: got <type int>"
-  line: 6
+  matrix: "--mm:refc"
+  errormsg: "type mismatch: got <typedesc[int]>"
+  line: 7
 """
 # bug #3079, #1146
-echo repr(int)
+echo repr(int)
\ No newline at end of file
diff --git a/tests/typerel/ttypedesc_as_genericparam1_orc.nim b/tests/typerel/ttypedesc_as_genericparam1_orc.nim
new file mode 100644
index 000000000..d528a7421
--- /dev/null
+++ b/tests/typerel/ttypedesc_as_genericparam1_orc.nim
@@ -0,0 +1,5 @@
+discard """
+  matrix: "--mm:orc"
+"""
+
+doAssert repr(int) == "int"
diff --git a/tests/typerel/ttypedesc_as_genericparam2.nim b/tests/typerel/ttypedesc_as_genericparam2.nim
index ea06606f9..882f66584 100644
--- a/tests/typerel/ttypedesc_as_genericparam2.nim
+++ b/tests/typerel/ttypedesc_as_genericparam2.nim
@@ -1,6 +1,7 @@
 discard """
+  matrix: "--mm:refc"
   errormsg: "'repr' doesn't support 'void' type"
-  line: 9
+  line: 10
 """
 
 # bug #2879
diff --git a/tests/typerel/ttypelessemptyset.nim b/tests/typerel/ttypelessemptyset.nim
index 5f49c33fd..a4b6f003a 100644
--- a/tests/typerel/ttypelessemptyset.nim
+++ b/tests/typerel/ttypelessemptyset.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "internal error: invalid kind for lastOrd(tyEmpty)"
+  errormsg: "statement returns no value that can be discarded"
 """
 var q = false
 discard (if q: {} else: {})
diff --git a/tests/typerel/ttypenoval.nim b/tests/typerel/ttypenoval.nim
index c7829f9dd..ca6c920ec 100644
--- a/tests/typerel/ttypenoval.nim
+++ b/tests/typerel/ttypenoval.nim
@@ -1,5 +1,5 @@
 discard """
-  errormsg: "type mismatch: got <type int> but expected 'int'"
+  errormsg: "type mismatch: got <typedesc[int]> but expected 'int'"
   file: "ttypenoval.nim"
   line: 38
 """
diff --git a/tests/typerel/ttypenovalue.nim b/tests/typerel/ttypenovalue.nim
index b86baf8b4..4664253ea 100644
--- a/tests/typerel/ttypenovalue.nim
+++ b/tests/typerel/ttypenovalue.nim
@@ -1,7 +1,6 @@
 discard """
-  errormsg: "value expected, but got a type"
+  errormsg: "invalid type: 'typedesc[seq[tuple[title: string, body: string]]]' for var"
   line: 7
-  disabled: true
 """
 
 proc crashAndBurn() =
diff --git a/tests/typerel/tuncheckedarray_eq.nim b/tests/typerel/tuncheckedarray_eq.nim
new file mode 100644
index 000000000..c07696b5f
--- /dev/null
+++ b/tests/typerel/tuncheckedarray_eq.nim
@@ -0,0 +1,2 @@
+type p = ptr UncheckedArray[char]
+doAssert p is ptr UncheckedArray
\ No newline at end of file
diff --git a/tests/typerel/tvoid.nim b/tests/typerel/tvoid.nim
index 1e46d016e..8bb5691b8 100644
--- a/tests/typerel/tvoid.nim
+++ b/tests/typerel/tvoid.nim
@@ -35,3 +35,64 @@ ReturnT[void]()
 echo ReturnT[string]("abc")
 nothing()
 
+block: # typeof(stmt)
+  proc fn1(): auto =
+    discard
+  proc fn2(): auto =
+    1
+  doAssert type(fn1()) is void
+  doAssert typeof(fn1()) is void
+  doAssert typeof(fn1()) isnot int
+
+  doAssert type(fn2()) isnot void
+  doAssert typeof(fn2()) isnot void
+  when typeof(fn1()) is void: discard
+  else: doAssert false
+
+  doAssert typeof(1+1) is int
+  doAssert typeof((discard)) is void
+
+  type A1 = typeof(fn1())
+  doAssert A1 is void
+  type A2 = type(fn1())
+  doAssert A2 is void
+  doAssert A2 is A1
+
+  when false:
+    # xxx: MCS/UFCS doesn't work here: Error: expression 'fn1()' has no type (or is ambiguous)
+    type A3 = fn1().type
+  proc bar[T](a: T): string = $T
+  doAssert bar(1) == "int"
+  doAssert bar(fn1()) == "void"
+
+  proc bar2[T](a: T): bool = T is void
+  doAssert not bar2(1)
+  doAssert bar2(fn1())
+
+  block:
+    proc bar3[T](a: T): T = a
+    let a1 = bar3(1)
+    doAssert compiles(block:
+      let a1 = bar3(fn2()))
+    doAssert not compiles(block:
+      let a2 = bar3(fn1()))
+    doAssert compiles(block: bar3(fn1()))
+    doAssert compiles(bar3(fn1()))
+    doAssert typeof(bar3(fn1())) is void
+    doAssert not compiles(sizeof(bar3(fn1())))
+
+  block:
+    var a = 1
+    doAssert typeof((a = 2)) is void
+    doAssert typeof((a = 2; a = 3)) is void
+    doAssert typeof(block:
+      a = 2; a = 3) is void
+
+  block:
+    var a = 1
+    template bad1 = echo (a; a = 2)
+    doAssert not compiles(bad1())
+
+  block:
+    template bad2 = echo (nonexistent; discard)
+    doAssert not compiles(bad2())
diff --git a/tests/typerel/typedescs.nim b/tests/typerel/typedescs.nim
index 23b9ce64f..faf919e13 100644
--- a/tests/typerel/typedescs.nim
+++ b/tests/typerel/typedescs.nim
@@ -5,3 +5,18 @@ p(type((5, 6)))       # Compiles
 (type((5, 6))).p      # Doesn't compile (SIGSEGV: Illegal storage access.)
 type T = type((5, 6)) # Doesn't compile (SIGSEGV: Illegal storage access.)
 
+block: # issue #21677
+  type
+    Uints = uint16|uint32
+
+  template constructor(name: untyped, typ: typedesc[Uints], typ2: typedesc[Uints]) =
+    type
+      name = object
+        data: typ
+        data2: typ2
+
+    proc `init name`(data: typ, data2: typ2): name =
+      result.data = data
+      result.data2 = data2
+
+  constructor(Test, uint32, uint16)
diff --git a/tests/typerel/typedescs2.nim b/tests/typerel/typedescs2.nim
index 43cd48ca6..a0308719d 100644
--- a/tests/typerel/typedescs2.nim
+++ b/tests/typerel/typedescs2.nim
@@ -1,10 +1,10 @@
 discard """
-  errormsg: "'typedesc' metatype is not valid here; typed '=' instead of ':'?"
+  errormsg: "invalid type: 'typedesc[Table]' for const"
   file: "typedescs2.nim"
   line: 16
 """
 
-# issue #9961
+# bug #9961
 
 import typetraits
 import tables
diff --git a/tests/types/t14127_cast_number.nim b/tests/types/t14127_cast_number.nim
new file mode 100644
index 000000000..4bb23f22f
--- /dev/null
+++ b/tests/types/t14127_cast_number.nim
@@ -0,0 +1,30 @@
+discard """
+  targets: "c cpp js"
+"""
+block: # bug #14127
+  template int2uint(T) =
+    var a = -1
+    let b = cast[T](a)
+    doAssert b < 0
+    let c = b + 1
+    doAssert c is T
+    doAssert c == 0
+
+  int2uint(int8)
+  int2uint(int16)
+  int2uint(int32)
+  int2uint(int64)
+
+block: # maybe related
+  template uint2int(T) =
+    var a = 3
+    let b = cast[T](a)
+    doAssert b > 0
+    let c = b - 1
+    doAssert c is T
+    doAssert c == 2
+
+  uint2int(uint8)
+  uint2int(uint16)
+  uint2int(uint32)
+  uint2int(uint64)
diff --git a/tests/types/t15836.nim b/tests/types/t15836.nim
new file mode 100644
index 000000000..27d3ad0d0
--- /dev/null
+++ b/tests/types/t15836.nim
@@ -0,0 +1,11 @@
+discard """
+  errormsg: "type mismatch: got <int literal(1), proc (a: GenericParam): auto>"
+  line: 11
+""" 
+
+proc takesProc[T](x: T, f: proc(x: T): int) =
+    echo f(x) + 2
+
+takesProc(1, proc (a: int): int = 2) # ok, prints 4
+takesProc(1, proc (a: auto): auto = 2) # ok, prints 4
+takesProc(1, proc (a: auto): auto = "uh uh") # prints garbage
diff --git a/tests/types/t15836_2.nim b/tests/types/t15836_2.nim
new file mode 100644
index 000000000..6a16e2d22
--- /dev/null
+++ b/tests/types/t15836_2.nim
@@ -0,0 +1,21 @@
+import std/sugar
+
+type Tensor[T] = object
+  x: T
+
+proc numerical_gradient*[T](input: T, f: (proc(x: T): T), h = T(1e-5)): T {.inline.} =
+  result = default(T)
+
+proc numerical_gradient*[T](input: Tensor[T], f: (proc(x: Tensor[T]): T), h = T(1e-5)): Tensor[T] {.noinit.} =
+  result = default(Tensor[T])
+
+proc conv2d*[T](input: Tensor[T]): Tensor[T] {.inline.} =
+  result = default(Tensor[T])
+
+proc sum*[T](arg: Tensor[T]): T = default(T)
+
+proc sum*[T](arg: Tensor[T], axis: int): Tensor[T] {.noinit.} = default(Tensor[T])
+
+let dinput = Tensor[int](x: 1)
+let target_grad_input = dinput.numerical_gradient(
+    x => conv2d(x).sum())
diff --git a/tests/types/t21027.nim b/tests/types/t21027.nim
new file mode 100644
index 000000000..3a992177a
--- /dev/null
+++ b/tests/types/t21027.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "Invalid usage of cast, cast requires a type to convert to, e.g., cast[int](0d)."
+"""
+# bug #21027
+let x: uint64 = cast(5)
diff --git a/tests/types/t21260.nim b/tests/types/t21260.nim
new file mode 100644
index 000000000..90d6613c1
--- /dev/null
+++ b/tests/types/t21260.nim
@@ -0,0 +1,13 @@
+discard """
+  errormsg: "illegal recursion in type 'Foo'"
+  line: 8
+"""
+
+type
+  Kind = enum kA, kB
+  Foo = object
+    case k: Kind:
+    of kA:
+      foo: Foo
+    of kB:
+      discard
diff --git a/tests/types/t5648.nim b/tests/types/t5648.nim
new file mode 100644
index 000000000..b3bd406b3
--- /dev/null
+++ b/tests/types/t5648.nim
@@ -0,0 +1,32 @@
+discard """
+  output: '''
+ptr Foo
+'''
+joinable: false
+"""
+# not joinable because it causes out of memory with --gc:boehm
+
+# issue #5648
+
+import typetraits
+
+type Foo = object
+  bar: int
+
+proc main() =
+  var f = create(Foo)
+  f.bar = 3
+  echo f.type.name
+
+  discard realloc(f, 0)
+
+  var g = Foo()
+  g.bar = 3
+
+var
+  mainPtr = cast[pointer](main)
+  mainFromPtr = cast[typeof(main)](mainPtr)
+
+doAssert main == mainFromPtr
+
+main()
diff --git a/tests/types/tcast1.nim b/tests/types/tcast1.nim
index 10e876ded..ab375b8b2 100644
--- a/tests/types/tcast1.nim
+++ b/tests/types/tcast1.nim
@@ -19,3 +19,45 @@ proc remap2[T](s: seq[int], typ: typedesc[T]): seq[T] =
 
 echo remap1(@[1,2,3], float)
 echo remap2(@[1,2,3], float)
+
+
+#--------------------------------------------------------------------
+# conversion to bool, issue #13744
+proc test_conv_to_bool = 
+  var 
+    i0 = 0
+    i1 = 1
+    ih = high(uint)
+    il = low(int)
+
+    f0 = 0.0
+    f1 = 1.0
+    fh = Inf
+    fl = -Inf
+    f_nan = NaN
+
+  doAssert(bool(i0) == false)
+  doAssert(bool(i1) == true)
+  doAssert(bool(-i1) == true)
+  doAssert(bool(il) == true)
+  doAssert(bool(ih) == true)
+
+  doAssert(bool(f0) == false)
+  doAssert(bool(-f0) == false)
+  doAssert(bool(f1) == true)
+  doAssert(bool(-f1) == true)
+  doAssert(bool(fh) == true)
+  doAssert(bool(fl) == true)
+  doAssert(bool(fnan) == true) # NaN to bool gives true according to standard
+
+
+static:
+  doAssert(bool(0) == false)
+  doAssert(bool(-1) == true)
+  doAssert(bool(2) == true)
+  doAssert(bool(NaN) == true)
+  doAssert(bool(0.0) == false)
+  doAssert(bool(-0.0) == false)
+  test_conv_to_bool()
+test_conv_to_bool()
+
diff --git a/tests/types/tcyclic.nim b/tests/types/tcyclic.nim
new file mode 100644
index 000000000..651394c8b
--- /dev/null
+++ b/tests/types/tcyclic.nim
@@ -0,0 +1,135 @@
+## todo publish the `isCyclic` when it's mature.
+proc isCyclic(t: typedesc): bool {.magic: "TypeTrait".} =
+  ## Returns true if the type can potentially form a cyclic type
+
+template cyclicYes(x: typed) =
+  doAssert isCyclic(x)
+
+template cyclicNo(x: typed) =
+  doAssert not isCyclic(x)
+
+# atomic types are not cyclic
+cyclicNo(int)
+cyclicNo(float)
+cyclicNo(string)
+cyclicNo(char)
+cyclicNo(void)
+
+type
+  Object = object
+  Ref = ref object
+
+cyclicNo(Object)
+cyclicNo(Ref)
+
+type
+  Data1 = ref object
+  Data2 = ref object
+    id: Data1
+
+cyclicNo(Data2)
+
+type
+  Cyclone = ref object
+    data: Cyclone
+
+  Alias = Cyclone
+
+  Acyclic {.acyclic.} = ref object
+    data: Acyclic
+
+  LinkedNode = object
+    next: ref LinkedNode
+
+  LinkedNodeWithCursor = object
+    next {.cursor.} : ref LinkedNodeWithCursor
+
+cyclicYes(Cyclone)
+cyclicYes(Alias)
+cyclicNo(seq[Cyclone])
+cyclicNo((Cyclone, ))
+cyclicNo(Acyclic)
+
+cyclicYes(LinkedNode)
+cyclicNo(LinkedNodeWithCursor) # cursor doesn't increase rc, cannot form a cycle
+
+type
+  ObjectWithoutCycles = object
+    data: seq[ObjectWithoutCycles]
+
+cyclicNo(ObjectWithoutCycles)
+
+
+block:
+  type
+    Try = object
+      id: Best
+    Best = object
+      name: ref Try
+    Best2 = ref Best
+
+  cyclicYes(Best)
+  cyclicYes(Try)
+  cyclicNo(Best2)
+
+  type
+    Base = object
+      data: ref seq[Base]
+    Base2 = ref Base
+
+  cyclicYes(Base)
+  cyclicNo(Base2)
+
+
+  type
+    Base3 = ref object
+      id: Base3
+
+    Base4 = object
+      id: ref Base4
+
+  cyclicYes(Base3)
+  cyclicYes(Base4)
+  cyclicYes(ref Base4)
+
+block:
+  type Cyclic2 = object
+    x: ref (Cyclic2, int)
+
+  cyclicYes (Cyclic2, int)
+  cyclicYes (ref (Cyclic2, int))
+
+block:
+  type
+    myseq[T] = object
+      data: ptr UncheckedArray[T]
+    Node = ref object
+      kids: myseq[Node]
+
+  cyclicNo(Node)
+
+block:
+  type
+    myseq[T] = object
+      data: ptr UncheckedArray[T]
+    Node = ref object
+      kids: myseq[Node]
+
+  proc `=trace`(x: var myseq[Node]; env: pointer) = discard
+
+  cyclicYes(Node)
+
+block:
+  type
+    Foo = object
+      id: ptr ref Foo
+
+  cyclicNo(Foo)
+
+block:
+  type
+    InheritableObj = object of RootObj
+    InheritableRef = ref object of RootObj
+
+  cyclicYes(InheritableObj)
+  cyclicYes(InheritableRef)
diff --git a/tests/types/temptyseqs.nim b/tests/types/temptyseqs.nim
index 28c3b87b8..6e7b58ced 100644
--- a/tests/types/temptyseqs.nim
+++ b/tests/types/temptyseqs.nim
@@ -75,16 +75,16 @@ varargso("foo", "bar", "baz")
 
 type
   Flago = enum
-    tfNeedsInit, tfNotNil
+    tfRequiresInit, tfNotNil
 
-var s: set[Flago] = {tfNeedsInit}
+var s: set[Flago] = {tfRequiresInit}
 
-if {tfNeedsInit, tfNotNil} * s != {}:
+if {tfRequiresInit, tfNotNil} * s != {}:
   echo "yes"
 else:
   echo "no"
 
-if {tfNeedsInit, tfNotNil} * s <= {tfNotNil}:
+if {tfRequiresInit, tfNotNil} * s <= {tfNotNil}:
   echo "yes"
 else:
   echo "no"
diff --git a/tests/types/texportgeneric.nim b/tests/types/texportgeneric.nim
new file mode 100644
index 000000000..9e6be2bb6
--- /dev/null
+++ b/tests/types/texportgeneric.nim
@@ -0,0 +1,8 @@
+discard """
+  errormsg: "{.exportc.} not allowed for generic types"
+  line: 6
+"""
+
+type Struct[T] {.exportc.} = object
+  a:int
+  b: T
\ No newline at end of file
diff --git a/tests/types/tfinalobj.nim b/tests/types/tfinalobj.nim
index 94f2e4f0e..ad3085132 100644
--- a/tests/types/tfinalobj.nim
+++ b/tests/types/tfinalobj.nim
@@ -3,7 +3,7 @@ discard """
 """
 
 type
-  TA = object {.pure, final.}
+  TA {.pure, final.} = object
     x: string
 
 var
diff --git a/tests/types/tillegalseqrecursion.nim b/tests/types/tillegalseqrecursion.nim
new file mode 100644
index 000000000..9221bb38a
--- /dev/null
+++ b/tests/types/tillegalseqrecursion.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "illegal recursion in type 'CyclicSeq'"
+"""
+# issue #13715
+type
+  CyclicSeq = seq[ref CyclicSeq]
diff --git a/tests/types/tillegaltuplerecursion.nim b/tests/types/tillegaltuplerecursion.nim
index c822e8880..cb75ad9c3 100644
--- a/tests/types/tillegaltuplerecursion.nim
+++ b/tests/types/tillegaltuplerecursion.nim
@@ -35,4 +35,6 @@ type
     children: ptr MyType9
 
   MyType9 = tuple
-    children: MyType0
+    children: MyType10
+
+  MyType10 = distinct seq[MyType0]
diff --git a/tests/types/tillegaltyperecursion.nim b/tests/types/tillegaltyperecursion.nim
index 4c53a8b0e..372615c4d 100644
--- a/tests/types/tillegaltyperecursion.nim
+++ b/tests/types/tillegaltyperecursion.nim
@@ -1,66 +1,17 @@
 discard """
   cmd: "nim $target --threads:on $options $file"
   errormsg: "illegal recursion in type 'TIRC'"
-  line: 16
+  line: 12
 """
 
-import events
 import net
 import strutils
 import os
 
 type
-    TMessageReceivedEventArgs = object of EventArgs
-        Nick*: string
-        Message*: string
     TIRC = object
-        EventEmitter: EventEmitter
-        MessageReceivedHandler*: EventHandler
         Socket: Socket
         Thread: Thread[TIRC]
 
 proc initIRC*(): TIRC =
     result.Socket = socket()
-    result.EventEmitter = initEventEmitter()
-    result.MessageReceivedHandler = initEventHandler("MessageReceived")
-
-proc IsConnected*(irc: var TIRC): bool =
-    return running(irc.Thread)
-
-
-proc sendRaw*(irc: var TIRC, message: string) =
-    irc.Socket.send(message & "\r\L")
-proc handleData(irc: TIRC) {.thread.} =
-    var connected = False
-    while connected:
-        var tup = @[irc.Socket]
-        var o = select(tup, 200)
-        echo($o)
-        echo($len(tup))
-        if len(tup) == 1:
-            #Connected
-            connected = True
-
-            #Parse data here
-
-        else:
-            #Disconnected
-            connected = False
-            return
-
-proc Connect*(irc: var TIRC, nick: string, host: string, port: int = 6667) =
-    connect(irc.Socket, host, TPort(port), TDomain.AF_INET)
-    send(irc.Socket,"USER " & nick & " " & nick & " " & nick & " " & nick & "\r\L")
-    send(irc.Socket,"NICK " & nick & "\r\L")
-    var thread: Thread[TIRC]
-    createThread(thread, handleData, irc)
-    irc.Thread = thread
-
-
-
-
-when true:
-    var irc = initIRC()
-    irc.Connect("AmryBot[Nim]","irc.freenode.net",6667)
-    irc.sendRaw("JOIN #nim")
-    os.Sleep(4000)
diff --git a/tests/types/tinheritgenericparameter.nim b/tests/types/tinheritgenericparameter.nim
new file mode 100644
index 000000000..d0d313635
--- /dev/null
+++ b/tests/types/tinheritgenericparameter.nim
@@ -0,0 +1,39 @@
+discard """
+  cmd: "nim check --hints:off --warnings:off $file"
+  action: "reject"
+  nimout:'''
+tinheritgenericparameter.nim(36, 15) Error: Cannot inherit from: 'MyObject'
+tinheritgenericparameter.nim(36, 15) Error: Cannot inherit from: 'MyObject'
+tinheritgenericparameter.nim(36, 23) Error: object constructor needs an object type [error]
+tinheritgenericparameter.nim(36, 23) Error: expression '' has no type (or is ambiguous)
+tinheritgenericparameter.nim(37, 15) Error: Cannot inherit from: 'int'
+tinheritgenericparameter.nim(37, 15) Error: Cannot inherit from: 'int'
+tinheritgenericparameter.nim(37, 23) Error: object constructor needs an object type [error]
+tinheritgenericparameter.nim(37, 23) Error: expression '' has no type (or is ambiguous)
+'''
+"""
+
+type
+  MyObject = object
+  HorzLayout[Base, T] = ref object of Base
+    data: seq[T]
+  VertLayout[T, Base] = ref object of Base
+    data: seq[T]
+  UiElement = ref object of RootObj
+    a: int
+  MyType[T] = ref object of RootObj
+    data: seq[T]
+  OtherElement[T] = ref object of T
+  Child[T] = ref object of HorzLayout[UiElement, T]
+  Child2[T] = ref object of VertLayout[T, UiElement]
+  Child3[T] = ref object of HorzLayout[MyObject, T]
+  Child4[T] = ref object of HorzLayout[int, T]
+static:
+  var a = Child[int](a: 300, data: @[100, 200, 300])
+  assert a.a == 300
+  assert a.data == @[100, 200, 300]
+discard Child2[string]()
+discard Child3[string]()
+discard Child4[string]()
+discard OtherElement[MyType[int]]()
+
diff --git a/tests/types/tinheritref.nim b/tests/types/tinheritref.nim
index 01f2307c0..c03e3bcab 100644
--- a/tests/types/tinheritref.nim
+++ b/tests/types/tinheritref.nim
@@ -11,11 +11,11 @@ ob = T[int](elem: 23)
 doAssert ob.elem == 23
 
 type
-  TTreeIteratorA* = ref object {.inheritable.}
-
   TKeysIteratorA* = ref object of TTreeIteratorA  #compiles
 
-  TTreeIterator* [T,D] = ref object {.inheritable.}
+  TTreeIteratorA* {.inheritable.} = ref object
+
+  TTreeIterator* [T,D] {.inheritable.} = ref object
 
   TKeysIterator* [T,D] = ref object of TTreeIterator[T,D]  #this not
 
diff --git a/tests/types/tisop.nim b/tests/types/tisop.nim
deleted file mode 100644
index ad5928016..000000000
--- a/tests/types/tisop.nim
+++ /dev/null
@@ -1,48 +0,0 @@
-discard """
-  disabled: true
-"""
-
-import typetraits
-
-type
-  TRecord = (tuple) or (object)
-
-  TFoo[T, U] = object
-    x: int
-
-    when T is string:
-      y: float
-    else:
-      y: string
-
-    when U is TRecord:
-      z: float
-
-  E = enum A, B, C
-
-macro m(t: typedesc): typedesc =
-  if t is enum:
-    result = string
-  else:
-    result = int
-
-var f: TFoo[int, int]
-static: assert(f.y.type.name == "string")
-
-when compiles(f.z):
-  {.error: "Foo should not have a `z` field".}
-
-proc p(a, b: auto) =
-  when a.type is int:
-    static: assert false
-
-  var f: TFoo[m(a.type), b.type]
-  static:
-    assert f.x.type.name == "int"
-    echo  f.y.type.name
-    assert f.y.type.name == "float"
-    echo  f.z.type.name
-    assert f.z.type.name == "float"
-
-p(A, f)
-
diff --git a/tests/types/tisopr.nim b/tests/types/tisopr.nim
index 636377301..c95b63c90 100644
--- a/tests/types/tisopr.nim
+++ b/tests/types/tisopr.nim
@@ -89,3 +89,83 @@ proc test[T](x: T) =
     echo "no"
 
 test(7)
+
+block:
+  # bug #13066
+  type Bar[T1,T2] = object
+  type Foo[T1,T2] = object
+  type Foo2 = Foo
+  doAssert Foo2 is Foo
+  doAssert Foo is Foo2
+  doAssert Foo is Foo
+  doAssert Foo2 is Foo2
+  doAssert Foo2 isnot Bar
+  doAssert Foo[int,float] is Foo2[int,float]
+
+  # other
+  doAssert Foo[int,float] isnot Foo2[float,float]
+  doAssert Foo[int,float] is Foo2
+  doAssert Foo[int,float|int] is Foo2
+  doAssert Foo2[int,float|int] is Foo
+  doAssert Foo2[int,float|int] isnot Bar
+  doAssert int is (int|float)
+
+
+block:
+  # Slice[T] as static type issue
+  type
+    MyEnum = enum
+      x1, x2, x3, x4, x5, x6
+
+  proc enumGen[T: enum](s: static[Slice[T]]) = 
+    doAssert($s.a & "  " & $s.b == "x1  x3")
+
+  enumGen(x1..x3)
+
+block:
+  # issue #11142
+  type
+    MyObjParam[N: static int] = object
+      x: int
+
+    MyObj[P: static MyObjParam] = object
+      y: int
+
+  const P = MyObjParam[256](x: 2)
+  let Q = MyObj[P](y: 2)
+  doAssert($Q  == "(y: 2)")
+
+block: # previously tisop.nim
+  type
+    TRecord = (tuple) or (object)
+    TFoo[T, U] = object
+      x: int
+      when T is string:
+        y: float
+      else:
+        y: string
+      when U is TRecord:
+        z: float
+    E = enum A, B, C
+  template m(t: typedesc): typedesc =
+    when t is enum:
+      string
+    else:
+      int
+  var f: TFoo[int, int]
+  static: doAssert(typeof(f.y) is string)
+  when compiles(f.z):
+    {.error: "Foo should not have a `z` field".}
+  proc p(a, b: auto) =
+    when typeof(a) is int:
+      static: doAssert false
+    var f: TFoo[m(a.typeof), b.typeof]
+    static:
+      doAssert f.x.typeof is int
+      doAssert f.y.typeof is float
+      doAssert f.z.typeof is float
+  p(A, f)
+
+block: # issue #22850
+  doAssert not (type is int)
+  doAssert not (typedesc is int)
diff --git a/tests/types/tissues_types.nim b/tests/types/tissues_types.nim
index e5039fa61..6bb1258f4 100644
--- a/tests/types/tissues_types.nim
+++ b/tests/types/tissues_types.nim
@@ -3,16 +3,14 @@ discard """
 true
 true
 true
-ptr Foo
 (member: "hello world")
 (member: 123.456)
 (member: "hello world", x: ...)
 (member: 123.456, x: ...)
+0
+false
 '''
-joinable: false
 """
-# not joinable because it causes out of memory with --gc:boehm
-import typetraits
 
 block t1252:
   echo float32 isnot float64
@@ -27,29 +25,6 @@ block t5640:
 
   var v = vec2([0.0'f32, 0.0'f32])
 
-block t5648:
-  type Foo = object
-    bar: int
-
-  proc main() =
-    var f = create(Foo)
-    f.bar = 3
-    echo f.type.name
-
-    discard realloc(f, 0)
-
-    var g = Foo()
-    g.bar = 3
-
-  var
-    mainPtr1: pointer = main
-    mainPtr2 = pointer(main)
-    mainPtr3 = cast[pointer](main)
-
-  doAssert mainPtr1 == mainPtr2 and mainPtr2 == mainPtr3
-
-  main()
-
 block t7581:
   discard int -1
 
@@ -78,3 +53,66 @@ block t7905:
 
   foobarRec("hello world")
   foobarRec(123.456'f64)
+
+# bug #5170
+
+when true:
+  type Foo = object
+    bar: bool
+
+  type Bar = object
+    sameBody: string
+
+  var b0: Bar
+  b0.sameBody = "abc"
+
+block:
+  type Foo = object
+    baz: int
+
+  type Bar = object
+    sameBody: string
+
+  var b1: Bar
+  b1.sameBody = "def"
+
+  var f2: Foo
+  echo f2.baz
+
+var f1: Foo
+echo f1.bar
+
+import macros
+
+block: # issue #12582
+  macro foo(T: type): type =
+    nnkBracketExpr.newTree(bindSym "array", newLit 1, T)
+  var
+    _: foo(int) # fine
+  type
+    Foo = object
+      x: foo(int) # fine
+    Bar = ref object
+      x: foo(int) # error
+  let b = Bar()
+  let b2 = Bar(x: [123])
+
+block:
+  when true: # bug #14710
+    type Foo[T] = object
+      x1: int
+      when T.sizeof == 4: discard # SIGSEGV
+      when sizeof(T) == 4: discard # ok
+    let t = Foo[float](x1: 1)
+    doAssert t.x1 == 1
+
+block:
+  template s(d: varargs[typed])=discard
+
+  proc something(x:float)=discard
+  proc something(x:int)=discard
+  proc otherthing()=discard
+
+  s(something)
+  s(otherthing, something)
+  s(something, otherthing)
diff --git a/tests/types/titerable.nim b/tests/types/titerable.nim
new file mode 100644
index 000000000..fe27de4fd
--- /dev/null
+++ b/tests/types/titerable.nim
@@ -0,0 +1,143 @@
+discard """
+  targets: "c js"
+"""
+
+from stdtest/testutils import accept, reject, whenVMorJs
+
+# toSeq-like templates
+
+template toSeq2(a: iterable): auto =
+  var ret: seq[typeof(a)]
+  for ai in a: ret.add ai
+  ret
+
+template toSeq3(a: iterable[string]): auto =
+  var ret: seq[typeof(a)]
+  for ai in a: ret.add ai
+  ret
+
+template toSeq4[T](a: iterable[T]): auto =
+  var ret: seq[typeof(a)]
+  for ai in a: ret.add ai
+  ret
+
+template toSeq5[T: SomeInteger](a: iterable[T]): auto =
+  var ret: seq[typeof(a)]
+  for ai in a: ret.add ai
+  ret
+
+template toSeq6(a: iterable[int | float]): auto =
+  var ret: seq[typeof(a)]
+  for ai in a: ret.add ai
+  ret
+
+template toSeq7(a: iterable[seq]): auto =
+  var ret: seq[typeof(a)]
+  for ai in a: ret.add ai
+  ret
+
+template fn7b(a: untyped) = discard
+template fn7c(a: typed) = discard
+template fn7d(a: auto) = discard
+template fn7e[T](a: T) = discard
+
+template fn8a(a: iterable) = discard
+template fn8b[T](a: iterable[T]) = discard
+template fn8c(a: iterable[int]) = discard
+
+template bad1 =
+  template fn4(a: int, b: iterable[float, int]) =
+    discard
+
+template bad2 =
+  proc fn4(a: iterable) = discard
+
+template bad3 =
+  proc fn4(a: iterable[int]) = discard
+
+template good4 =
+  template fn1(a: iterable) = discard
+  template fn2(a: iterable[int]) = discard
+
+# iterators
+iterator iota(n: int): auto =
+  for i in 0..<n: yield i
+
+iterator repeat[T](a: T, n: int): T =
+  for i in 0..<n:
+    yield a
+
+iterator myiter(n: int): auto =
+  for i in 0..<n: yield $(i*2)
+
+when not defined(js):
+  iterator iotaClosure(n: int): auto {.closure.} =
+    for i in 0..<n: yield i
+
+template main() =
+  let expected1 = @[0, 1, 2]
+  let expected2 = @["0", "2"]
+
+  doAssert toSeq2(myiter(2)) == expected2
+  doAssert toSeq2(iota(3)) == expected1
+  doAssert toSeq2(1.1.repeat(2)) == @[1.1, 1.1]
+
+  whenVMorJs: discard
+  do:
+    doAssert toSeq2(iotaClosure(3)) == expected1
+
+  when true:
+    # MCS/UFCS
+    doAssert iota(3).toSeq2() == expected1
+
+  doAssert toSeq3(myiter(2)) == expected2
+  accept toSeq3(myiter(2))
+  reject toSeq3(iota(3))
+
+  doAssert toSeq4(iota(3)) == expected1
+  doAssert toSeq4(myiter(2)) == expected2
+  
+  doAssert toSeq4(0..2) == expected1
+  doAssert toSeq4(items(0..2)) == expected1
+  doAssert toSeq4(items(@[0,1,2])) == expected1
+  reject toSeq4(@[0,1,2])
+  reject toSeq4(13)
+
+  block:
+    accept fn8a(iota(3))
+    accept fn7b(iota(3))
+    reject fn7c(iota(3))
+    reject fn7d(iota(3))
+    reject fn7e(iota(3))
+
+  block:
+    fn8a(iota(3))
+    reject fn8a(123)
+    reject fn8c(123)
+    reject fn8c(123.3)
+    accept fn8c(items(@[1,2]))
+
+  block:
+    # shows that iterable is more restrictive than untyped
+    reject fn8a(nonexistent)
+    accept fn7b(nonexistent)
+    reject fn7c(nonexistent)
+    reject fn7d(nonexistent)
+    reject fn7e(nonexistent)
+
+  doAssert toSeq5(iota(3)) == expected1
+  reject toSeq5(myiter(2))
+
+  doAssert toSeq6(iota(3)) == expected1
+  reject toSeq6(myiter(2))
+
+  doAssert toSeq2("abc".repeat(3)) == @["abc", "abc", "abc"]
+  doAssert toSeq2(@['x', 'y'].repeat(2)) == @[@['x', 'y'], @['x', 'y']]
+
+  reject bad1
+  reject bad2
+  reject bad3
+  accept good4
+
+static: main()
+main()
diff --git a/tests/types/tlent_var.nim b/tests/types/tlent_var.nim
index 491f6fde8..73b5bef9b 100644
--- a/tests/types/tlent_var.nim
+++ b/tests/types/tlent_var.nim
@@ -15,7 +15,7 @@ proc test_var(x: var MyObj): var int =
 var x = MyObj(a: 5)
 
 doAssert: test_var(x).addr == x.a.addr
-doAssert: test_lent(x).unsafeAddr == x.a.addr
+doAssert: test_lent(x).addr == x.a.addr
 
 proc varProc(x: var int) =
   x = 100
diff --git a/tests/types/tnontype.nim b/tests/types/tnontype.nim
new file mode 100644
index 000000000..4e2bafb32
--- /dev/null
+++ b/tests/types/tnontype.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "expected type, but got: 3"
+"""
+
+type
+  Foo = (block:
+    int)
+  
+  Bar = 3
diff --git a/tests/types/told_pragma_syntax1.nim b/tests/types/told_pragma_syntax1.nim
new file mode 100644
index 000000000..49823662d
--- /dev/null
+++ b/tests/types/told_pragma_syntax1.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "invalid indentation"
+"""
+
+type Foo = object {.final.}
diff --git a/tests/types/told_pragma_syntax2.nim b/tests/types/told_pragma_syntax2.nim
new file mode 100644
index 000000000..eea185725
--- /dev/null
+++ b/tests/types/told_pragma_syntax2.nim
@@ -0,0 +1,5 @@
+discard """
+  errormsg: "invalid indentation"
+"""
+
+type Bar {.final.} [T] = object
diff --git a/tests/types/ttopdowninference.nim b/tests/types/ttopdowninference.nim
new file mode 100644
index 000000000..765761e99
--- /dev/null
+++ b/tests/types/ttopdowninference.nim
@@ -0,0 +1,333 @@
+block:
+  var s: seq[string] = (discard; @[])
+
+  var x: set[char] =
+    if true:
+      try:
+        case 1
+        of 1:
+          if false:
+            {'4'}
+          else:
+            block:
+              s.add "a"
+              {}
+        else: {'3'}
+      except: {'2'}
+    else: {'1'}
+  doAssert x is set[char]
+  doAssert x == {}
+  doAssert s == @["a"]
+
+  x = {'a', 'b'}
+  doAssert x == {'a', 'b'}
+
+  x = (s.add "b"; {})
+  doAssert x == {}
+  doAssert s == @["a", "b"]
+
+  let x2: set[byte] = {1}
+  doAssert x2 == {1u8}
+
+block:
+  let x3: array[0..2, byte] = [1, 2, 3]
+  #let x4: openarray[byte] = [1, 2, 3]
+  #let x5: openarray[byte] = @[1, 2, 3]
+  let x6: seq[byte] = @[1, 2, 3]
+  let x7: seq[seq[float32]] = @[@[1, 2, 3], @[4.3, 5, 6]]
+  type ABC = enum a, b, c
+  let x8: array[ABC, byte] = [1, 2, 3]
+  doAssert x8[a] == 1
+  doAssert x8[a] + x8[b] == x8[c]
+
+  const x9: array[-2..2, float] = [0, 1, 2, 3, 4]
+  let x10: array[ABC, byte] = block:
+    {.gcsafe.}:
+      [a: 1, b: 2, c: 3]
+  proc `@`(x: float): float = x + 1
+  doAssert @1 == 2
+  let x11: seq[byte] = system.`@`([1, 2, 3])
+
+block:
+  type Foo = object
+    x: BiggestInt
+  var foo: Foo
+  foo.x = case true
+  of true: ord(1)
+  else: 0
+  foo.x = if true: ord(1) else: 0
+
+block:
+  type Foo = object
+    x: (float, seq[(byte, seq[byte])])
+    
+  let foo = Foo(x: (1, @{2: @[], 3: @[4, 5]}))
+  doAssert foo.x == (1.0, @{2u8: @[], 3u8: @[4u8, 5]})
+
+block:
+  type Foo = object
+    x: tuple[a: float, b: seq[(byte, seq[byte])]]
+    
+  let foo = Foo(x: (a: 1, b: @{2: @[3, 4], 5: @[]}))
+  doAssert foo.x == (1.0, @{2u8: @[3u8, 4], 5u8: @[]})
+
+block:
+  proc foo(): seq[float] = @[1]
+
+  let fooLamb = proc(): seq[float] = @[1]
+
+  doAssert foo() == fooLamb()
+
+block:
+  type Foo[T] = float32
+
+  let x: seq[Foo[int32]] = @[1]
+
+block:
+  type Foo = ref object
+  type Bar[T] = ptr object
+
+  let x1: seq[Foo] = @[nil]
+  let x2: seq[Bar[int]] = @[nil]
+  let x3: seq[cstring] = @[nil]
+
+block:
+  let x: seq[cstring] = @["abc", nil, "def"]
+  doAssert x.len == 3
+  doAssert x[0] == cstring"abc"
+  doAssert x[1].isNil
+  doAssert x[2] == "def".cstring
+
+block:
+  type Foo = object
+    x: tuple[a: float, b: seq[(byte, seq[cstring])]]
+    
+  let foo = Foo(x: (a: 1, b: @{2: @[nil, "abc"]}))
+  doAssert foo.x == (1.0, @{2u8: @[cstring nil, cstring "abc"]})
+
+block:
+  type Foo = object
+    x: tuple[a: float, b: seq[(byte, seq[ptr int])]]
+    
+  let foo = Foo(x: (a: 1, b: @{2: @[nil, nil]}))
+  doAssert foo.x == (1.0, @{2u8: @[(ptr int)(nil), nil]})
+
+when false: # unsupported
+  block: # type conversion
+    let x = seq[(cstring, float32)](@{"abc": 1.0, "def": 2.0})
+    doAssert x[0] == (cstring"abc", 1.0'f32)
+    doAssert x[1] == (cstring"def", 2.0'f32)
+
+block: # enum
+  type Foo {.pure.} = enum a
+  type Bar {.pure.} = enum a, b, c
+
+  var s: seq[Bar] = @[a, b, c]
+
+block: # overload selection
+  proc foo(x, y: int): int = x + y + 1
+  proc foo(x: int): int = x - 1
+  var s: seq[proc (x, y: int): int] = @[nil, foo, foo]
+  var s2: seq[int]
+  for a in s:
+    if not a.isNil: s2.add(a(1, 2))
+  doAssert s2 == @[4, 4]
+
+block: # with generics?
+  proc foo(x, y: int): int = x + y + 1
+  proc foo(x: int): int = x - 1
+  proc bar[T](x, y: T): T = x - y
+  var s: seq[proc (x, y: int): int] = @[nil, foo, foo, bar]
+  var s2: seq[int]
+  for a in s:
+    if not a.isNil: s2.add(a(1, 2))
+  doAssert s2 == @[4, 4, -1]
+  proc foo(x, y: float): float = x + y + 1.0
+  var s3: seq[proc (x, y: float): float] = @[nil, foo, foo, bar]
+  var s4: seq[float]
+  for a in s3:
+    if not a.isNil: s4.add(a(1, 2))
+  doAssert s4 == @[4.0, 4, -1]
+
+block: # range types
+  block:
+    let x: set[range[1u8..5u8]] = {1, 3}
+    doAssert x == {range[1u8..5u8](1), 3}
+    doAssert $x == "{1, 3}"
+  block:
+    let x: seq[set[range[1u8..5u8]]] = @[{1, 3}]
+    doAssert x == @[{range[1u8..5u8](1), 3}]
+    doAssert $x[0] == "{1, 3}"
+  block:
+    let x: seq[range[1u8..5u8]] = @[1, 3]
+    doAssert x == @[range[1u8..5u8](1), 3]
+    doAssert $x == "@[1, 3]"
+  block: # already worked before, make sure it still works
+    let x: set[range['a'..'e']] = {'a', 'c'}
+    doAssert x == {range['a'..'e']('a'), 'c'}
+    doAssert $x == "{'a', 'c'}"
+  block: # extended
+    let x: seq[set[range['a'..'e']]] = @[{'a', 'c'}]
+    doAssert x[0] == {range['a'..'e']('a'), 'c'}
+    doAssert $x == "@[{'a', 'c'}]"
+  block:
+    type Foo = object
+      x: (range[1u8..5u8], seq[(range[1f32..5f32], seq[range['a'..'e']])])
+      
+    let foo = Foo(x: (1, @{2: @[], 3: @['c', 'd']}))
+    doAssert foo.x == (range[1u8..5u8](1u8), @{range[1f32..5f32](2f32): @[], 3f32: @[range['a'..'e']('c'), 'd']})
+  block:
+    type Foo = object
+      x: (range[1u8..5u8], seq[(range[1f32..5f32], seq[set[range['a'..'e']]])])
+      
+    let foo = Foo(x: (1, @{2: @[], 3: @[{'c', 'd'}]}))
+    doAssert foo.x == (range[1u8..5u8](1u8), @{range[1f32..5f32](2f32): @[], 3f32: @[{range['a'..'e']('c'), 'd'}]})
+
+block: # templates
+  template foo: untyped = (1, 2, "abc")
+  let x: (float, byte, cstring) = foo()
+  doAssert x[0] == float(1)
+  doAssert x[1] == byte(2)
+  doAssert x[2] == cstring("abc")
+  let (a, b, c) = x
+  doAssert a == float(1)
+  doAssert b == byte(2)
+  doAssert c == cstring("abc")
+
+
+proc foo(): set[char] = # bug #11259
+  discard "a"
+  {}
+
+discard foo()
+
+block: # bug #11085
+  const ok1: set[char] = {}
+  var ok1b: set[char] = {}
+
+  const ok2: set[char] = block:
+    {}
+
+  const ok3: set[char] = block:
+    var x: set[char] = {}
+    x
+  var ok3b: set[char] = block:
+    var x: set[char] = {}
+    x
+
+  var bad: set[char] = block:
+    {}
+
+# bug #6213
+block:
+  block:
+    type MyEnum = enum a, b
+    type MyTuple = tuple[x: set[MyEnum]]
+
+    var myVar: seq[MyTuple] = @[ (x: {}) ]
+    doAssert myVar.len == 1
+
+  block:
+    type
+      Foo = tuple
+        f: seq[string]
+        s: string
+
+    proc e(): seq[Foo] =
+      return @[
+        (@[], "asd")
+      ]
+
+    doAssert e()[0].f == @[]
+
+block: # bug #11777
+  type S = set[0..5]
+  var s: S = {1, 2}
+  doAssert 1 in s
+
+block: # bug #20807
+  var s: seq[string]
+  template fail =
+    s = @[]
+  template test(body: untyped) =
+    body
+  proc test(a: string) = discard
+  test: fail()
+  doAssert not (compiles do:
+    let x: seq[int] = `@`[string]([]))
+
+block: # bug #21377
+  proc b[T](v: T): seq[int] =
+    let x = 0
+    @[]
+
+  doAssert b(0) == @[]
+
+block: # bug #21377
+  proc b[T](v: T): seq[T] =
+    let x = 0
+    @[]
+
+  doAssert b(0) == @[]
+
+block: # bug #21377
+  proc b[T](v: T): set[bool] =
+    let x = 0
+    {}
+
+  doAssert b(0) == {}
+
+block: # bug #21377
+  proc b[T](v: T): array[0, int] =
+    let x = 0
+    []
+
+  doAssert b(0) == []
+
+block: # bug #21377
+  proc b[T](v: T): array[0, (string, string)] =
+    let x = 0
+    {:}
+
+  doAssert b(0) == {:}
+
+block: # bug #22180
+  type A = object
+  proc j() = discard
+
+  let x =
+    if false:
+      (ref A)(nil)
+    else:
+      if false:
+        quit 1
+      else:
+        if true:
+          j()
+          nil  # compiles with (ref A)(nil) here
+        else:
+          (ref A)(nil)
+  doAssert x.isNil
+  
+  let y =
+    case true
+    of false:
+      (ref A)(nil)
+    else:
+      case true
+      of false:
+        quit 1
+      else:
+        case true
+        of true:
+          j()
+          nil  # compiles with (ref A)(nil) here
+        else:
+          (ref A)(nil)
+  doAssert y.isNil
+
+block: # issue #24164, related regression
+  proc foo(x: proc ()) = discard
+  template bar(x: untyped = nil) =
+    foo(x)
+  bar()
diff --git a/tests/types/tyet_another_generic_regression.nim b/tests/types/tyet_another_generic_regression.nim
index 083993757..2e5f9bb23 100644
--- a/tests/types/tyet_another_generic_regression.nim
+++ b/tests/types/tyet_another_generic_regression.nim
@@ -30,3 +30,12 @@ const
   }.toTable
 
 #map["test"]()
+
+#-------------------------------------------------------------------
+# bug
+const val = 10
+ 
+type 
+  t = object
+    when val >= 10:
+      a: int
diff --git a/tests/untestable/gdb/gdb_pretty_printer_test.py b/tests/untestable/gdb/gdb_pretty_printer_test.py
index f002941ec..aed0cfeb0 100644
--- a/tests/untestable/gdb/gdb_pretty_printer_test.py
+++ b/tests/untestable/gdb/gdb_pretty_printer_test.py
@@ -1,36 +1,64 @@
 import gdb
+import re
+import sys
 # this test should test the gdb pretty printers of the nim
 # library. But be aware this test is not complete. It only tests the
 # command line version of gdb. It does not test anything for the
 # machine interface of gdb. This means if if this test passes gdb
 # frontends might still be broken.
 
-gdb.execute("source ../../../tools/nim-gdb.py")
-# debug all instances of the generic function `myDebug`, should be 8
+gdb.execute("set python print-stack full")
+gdb.execute("source ../../../tools/debug/nim-gdb.py")
+# debug all instances of the generic function `myDebug`, should be 14
 gdb.execute("rbreak myDebug")
 gdb.execute("run")
 
 outputs = [
   'meTwo',
+  '""',
   '"meTwo"',
   '{meOne, meThree}',
   'MyOtherEnum(1)',
-  '5',
+  '{MyOtherEnum(0), MyOtherEnum(2)}',
   'array = {1, 2, 3, 4, 5}',
+  'seq(0, 0)',
+  'seq(0, 10)',
+  'array = {"one", "two"}',
+  'seq(3, 3) = {1, 2, 3}',
   'seq(3, 3) = {"one", "two", "three"}',
-  'Table(3, 64) = {["two"] = 2, ["three"] = 3, ["one"] = 1}',
+  'Table(3, 64) = {[4] = "four", [5] = "five", [6] = "six"}',
+  'Table(3, 8) = {["two"] = 2, ["three"] = 3, ["one"] = 1}',
+  '{a = 1, b = "some string"}',
+  '("hello", 42)'
 ]
 
-for i, expected in enumerate(outputs):
-  functionSymbol = gdb.selected_frame().block().function
-  assert functionSymbol.line == 21
+argRegex = re.compile("^.* = (?:No suitable Nim \$ operator found for type: \w+\s*)*(.*)$")
+# Remove this error message which can pop up
+noSuitableRegex = re.compile("(No suitable Nim \$ operator found for type: \w+\s*)")
 
-  if i == 5:
+for i, expected in enumerate(outputs):
+  gdb.write(f"\x1b[38;5;105m{i+1}) expecting: {expected}: \x1b[0m", gdb.STDLOG)
+  gdb.flush()
+  currFrame = gdb.selected_frame()
+  functionSymbol = currFrame.block().function
+  assert functionSymbol.line == 24, str(functionSymbol.line)
+  raw = ""
+  if i == 6:
     # myArray is passed as pointer to int to myDebug. I look up myArray up in the stack
     gdb.execute("up")
-    output = str(gdb.parse_and_eval("myArray"))
+    raw = gdb.parse_and_eval("myArray")    
+  elif i == 9:
+    # myOtherArray is passed as pointer to int to myDebug. I look up myOtherArray up in the stack
+    gdb.execute("up")
+    raw = gdb.parse_and_eval("myOtherArray")
   else:
-    output = str(gdb.parse_and_eval("arg"))
+    rawArg = re.sub(noSuitableRegex, "", gdb.execute("info args", to_string = True))
+    raw = rawArg.split("=", 1)[-1].strip()
+  output = str(raw)
 
-  assert output == expected, output + " != " + expected
+  if output != expected:
+    gdb.write(f"\x1b[38;5;196m ({output}) != expected: ({expected})\x1b[0m\n", gdb.STDERR)
+    gdb.execute("quit 1")
+  else:
+    gdb.write("\x1b[38;5;34mpassed\x1b[0m\n", gdb.STDLOG)
   gdb.execute("continue")
diff --git a/tests/untestable/gdb/gdb_pretty_printer_test_output.txt b/tests/untestable/gdb/gdb_pretty_printer_test_output.txt
deleted file mode 100644
index 73d26016f..000000000
--- a/tests/untestable/gdb/gdb_pretty_printer_test_output.txt
+++ /dev/null
@@ -1,3 +0,0 @@
-Loading Nim Runtime support.
-NimEnumPrinter: lookup global symbol 'NTI__z9cu80OJCfNgw9bUdzn5ZEzw_ failed for tyEnum_MyOtherEnum__z9cu80OJCfNgw9bUdzn5ZEzw.
-8
diff --git a/tests/untestable/gdb/gdb_pretty_printer_test_program.nim b/tests/untestable/gdb/gdb_pretty_printer_test_program.nim
index 458435c1a..163c99860 100644
--- a/tests/untestable/gdb/gdb_pretty_printer_test_program.nim
+++ b/tests/untestable/gdb/gdb_pretty_printer_test_program.nim
@@ -14,7 +14,10 @@ type
     moTwo,
     moThree,
     moFoure,
-
+  
+  MyObj = object
+    a*: int
+    b*: string
 
 var counter = 0
 
@@ -23,31 +26,64 @@ proc myDebug[T](arg: T): void =
 
 proc testProc(): void =
   var myEnum = meTwo
-  myDebug(myEnum)
+  myDebug(myEnum) #1
+  
+  # create a string, but don't allocate it
+  var myString: string
+  myDebug(myString) #2
+
   # create a string object but also make the NTI for MyEnum is generated
-  var myString = $myEnum
-  myDebug(myString)
+  myString = $myEnum
+  myDebug(myString) #3
+  
   var mySet = {meOne,meThree}
-  myDebug(mySet)
+  myDebug(mySet) #4
 
   # for MyOtherEnum there is no NTI. This tests the fallback for the pretty printer.
   var moEnum = moTwo
-  myDebug(moEnum)
+  myDebug(moEnum) #5
+
   var moSet = {moOne,moThree}
-  myDebug(moSet)
+  myDebug(moSet) #6
 
   let myArray = [1,2,3,4,5]
-  myDebug(myArray)
-  let mySeq   = @["one","two","three"]
-  myDebug(mySeq)
+  myDebug(myArray) #7
+
+  # implicitly initialized seq test
+  var mySeq: seq[string]
+  myDebug(mySeq) #8
+
+  # len not equal to capacity
+  let myOtherSeq = newSeqOfCap[string](10)
+  myDebug(myOtherSeq) #9
+
+  let myOtherArray = ["one","two"]
+  myDebug(myOtherArray) #10
+
+  # numeric sec
+  var mySeq3 = @[1,2,3]
+  myDebug(mySeq3) #11
+
+  # seq had to grow
+  var mySeq4 = @["one","two","three"]
+  myDebug(mySeq4) #12
+
+  var myTable = initTable[int, string]()
+  myTable[4] = "four"
+  myTable[5] = "five"
+  myTable[6] = "six"
+  myDebug(myTable) #13
+
+  var myOtherTable = {"one": 1, "two": 2, "three": 3}.toTable
+  myDebug(myOtherTable) #14
+
+  var obj = MyObj(a: 1, b: "some string")
+  myDebug(obj) #15
 
-  var myTable = initTable[string, int]()
-  myTable["one"] = 1
-  myTable["two"] = 2
-  myTable["three"] = 3
-  myDebug(myTable)
+  var tup = ("hello", 42)
+  myDebug(tup) # 16
 
-  echo(counter)
+  assert counter == 16
 
 
 testProc()
diff --git a/tests/untestable/gdb/gdb_pretty_printer_test_run.sh b/tests/untestable/gdb/gdb_pretty_printer_test_run.sh
index 525f54705..411c68435 100644..100755
--- a/tests/untestable/gdb/gdb_pretty_printer_test_run.sh
+++ b/tests/untestable/gdb/gdb_pretty_printer_test_run.sh
@@ -1,15 +1,13 @@
 #!/usr/bin/env bash
-# Exit if anything fails
 set -e
-#!/usr/bin/env bash
 # Compile the test project with fresh debug information.
-nim c --debugger:native gdb_pretty_printer_test_program.nim &> /dev/null
+nim c --debugger:native --mm:orc --out:gdbNew gdb_pretty_printer_test_program.nim
+echo "Running new runtime tests..."
 # 2>&1 redirects stderr to stdout (all output in stdout)
-# <(...) is a bash feature that makes the output of a command into a
-# file handle.
-# diff compares the two files, the expected output, and the file
-# handle that is created by the execution of gdb.
-diff ./gdb_pretty_printer_test_output.txt <(gdb -x gdb_pretty_printer_test.py --batch-silent --args gdb_pretty_printer_test_program 2>&1)
-# The exit code of diff is forwarded as the exit code of this
-# script. So when the comparison fails, the exit code of this script
-# won't be 0. So this script should be embeddable in a test suite.
+gdb -x gdb_pretty_printer_test.py --batch-silent --args gdbNew 2>&1
+
+
+# Do it all again, but with old runtime
+nim c --debugger:native --mm:refc --out:gdbOld gdb_pretty_printer_test_program.nim &> /dev/null
+echo "Running old runtime tests"
+gdb -x gdb_pretty_printer_test.py --batch-silent --args gdbOld 2>&1
diff --git a/tests/untestable/thttpclient_ssl_disabled.nim b/tests/untestable/thttpclient_ssl_disabled.nim
new file mode 100644
index 000000000..b95dad2c6
--- /dev/null
+++ b/tests/untestable/thttpclient_ssl_disabled.nim
@@ -0,0 +1,36 @@
+#
+#            Nim - SSL integration tests
+#        (c) Copyright 2017 Nim contributors
+#
+#    See the file "copying.txt", included in this
+#    distribution, for details about the copyright.
+#
+## Compile and run with:
+## nim r --putenv:NIM_TESTAMENT_REMOTE_NETWORKING:1 -d:nimDisableCertificateValidation -d:ssl -p:. tests/untestable/thttpclient_ssl_disabled.nim
+
+from stdtest/testutils import enableRemoteNetworking
+when enableRemoteNetworking and (defined(nimTestsEnableFlaky) or not defined(openbsd)):
+  import httpclient, net, unittest
+
+  const expired = "https://expired.badssl.com/"
+
+  doAssert defined(nimDisableCertificateValidation)
+
+  suite "SSL certificate check - disabled":
+
+    test "httpclient in insecure mode":
+      var ctx = newContext(verifyMode = CVerifyPeer)
+      var client = newHttpClient(sslContext = ctx)
+      let a = $client.getContent(expired)
+
+    test "httpclient in insecure mode":
+      var ctx = newContext(verifyMode = CVerifyPeerUseEnvVars)
+      var client = newHttpClient(sslContext = ctx)
+      let a = $client.getContent(expired)
+
+    test "net socket in insecure mode":
+      var sock = newSocket()
+      var ctx = newContext(verifyMode = CVerifyPeerUseEnvVars)
+      ctx.wrapSocket(sock)
+      sock.connect("expired.badssl.com", 443.Port)
+      sock.close
diff --git a/tests/untestable/thttpclient_ssl_env_var.nim b/tests/untestable/thttpclient_ssl_env_var.nim
new file mode 100644
index 000000000..3f25a6ff4
--- /dev/null
+++ b/tests/untestable/thttpclient_ssl_env_var.nim
@@ -0,0 +1,74 @@
+#
+#            Nim - SSL integration tests
+#        (c) Copyright 2017 Nim contributors
+#
+#    See the file "copying.txt", included in this
+#    distribution, for details about the copyright.
+#
+## Warning: this test performs external networking.
+## Compile with:
+## ./bin/nim c -d:ssl -p:. tests/untestable/thttpclient_ssl_env_var.nim
+##
+## Test with:
+##  SSL_CERT_FILE=BogusInexistentFileName tests/untestable/thttpclient_ssl_env_var
+##  SSL_CERT_DIR=BogusInexistentDirName tests/untestable/thttpclient_ssl_env_var
+
+import httpclient, unittest, os
+from net import newSocket, newContext, wrapSocket, connect, close, Port,
+  CVerifyPeerUseEnvVars
+from strutils import contains
+
+const
+  expired = "https://expired.badssl.com/"
+  good = "https://google.com/"
+
+
+suite "SSL certificate check":
+
+  test "httpclient with inexistent file":
+    if existsEnv("SSL_CERT_FILE"):
+      var ctx = newContext(verifyMode=CVerifyPeerUseEnvVars)
+      var client = newHttpClient(sslContext=ctx)
+      checkpoint("Client created")
+      check client.getContent("https://google.com").contains("doctype")
+      checkpoint("Google ok")
+      try:
+        let a = $client.getContent(good)
+        echo "Connection should have failed"
+        fail()
+      except:
+        echo getCurrentExceptionMsg()
+        check getCurrentExceptionMsg().contains("certificate verify failed")
+
+    elif existsEnv("SSL_CERT_DIR"):
+      try:
+        var ctx = newContext(verifyMode=CVerifyPeerUseEnvVars)
+        var client = newHttpClient(sslContext=ctx)
+        echo "Should have raised 'No SSL/TLS CA certificates found.'"
+        fail()
+      except:
+        check getCurrentExceptionMsg() ==
+          "No SSL/TLS CA certificates found."
+
+  test "net socket with inexistent file":
+    if existsEnv("SSL_CERT_FILE"):
+      var sock = newSocket()
+      var ctx = newContext(verifyMode=CVerifyPeerUseEnvVars)
+      ctx.wrapSocket(sock)
+      checkpoint("Socket created")
+      try:
+        sock.connect("expired.badssl.com", 443.Port)
+        fail()
+      except:
+        sock.close
+        check getCurrentExceptionMsg().contains("certificate verify failed")
+
+    elif existsEnv("SSL_CERT_DIR"):
+      var sock = newSocket()
+      checkpoint("Socket created")
+      try:
+        var ctx = newContext(verifyMode=CVerifyPeerUseEnvVars) # raises here
+        fail()
+      except:
+        check getCurrentExceptionMsg() ==
+          "No SSL/TLS CA certificates found."
diff --git a/tests/untestable/thttpclient_ssl_remotenetwork.nim b/tests/untestable/thttpclient_ssl_remotenetwork.nim
new file mode 100644
index 000000000..3cb759516
--- /dev/null
+++ b/tests/untestable/thttpclient_ssl_remotenetwork.nim
@@ -0,0 +1,230 @@
+#
+#
+#            Nim - SSL integration tests
+#        (c) Copyright 2017 Nim contributors
+#
+#    See the file "copying.txt", included in this
+#    distribution, for details about the copyright.
+#
+## Test with:
+## nim r --putenv:NIM_TESTAMENT_REMOTE_NETWORKING:1 -d:ssl -p:. --threads:on tests/untestable/thttpclient_ssl_remotenetwork.nim
+##
+## See https://github.com/FedericoCeratto/ssl-comparison/blob/master/README.md
+## for a comparison with other clients.
+
+from stdtest/testutils import enableRemoteNetworking
+when enableRemoteNetworking and (defined(nimTestsEnableFlaky) or not defined(windows) and not defined(openbsd)):
+  # Not supported on Windows due to old openssl version
+  import
+    httpclient,
+    net,
+    strutils,
+    threadpool,
+    unittest
+
+
+  type
+    # bad and dubious tests should not pass SSL validation
+    # "_broken" mark the test as skipped. Some tests have different
+    # behavior depending on OS and SSL version!
+    # TODO: chase and fix the broken tests
+    Category = enum
+      good, bad, dubious, good_broken, bad_broken, dubious_broken
+    CertTest = tuple[url:string, category:Category, desc: string]
+
+  # badssl certs sometimes expire, set to false when that happens
+  when true:
+    const certificate_tests: array[0..54, CertTest] = [
+      ("https://wrong.host.badssl.com/", bad, "wrong.host"),
+      ("https://captive-portal.badssl.com/", bad, "captive-portal"),
+      ("https://expired.badssl.com/", bad, "expired"),
+      ("https://google.com/", good, "good"),
+      ("https://self-signed.badssl.com/", bad, "self-signed"),
+      ("https://untrusted-root.badssl.com/", bad, "untrusted-root"),
+      ("https://revoked.badssl.com/", bad_broken, "revoked"),
+      ("https://pinning-test.badssl.com/", bad_broken, "pinning-test"),
+      ("https://no-common-name.badssl.com/", bad, "no-common-name"),
+      ("https://no-subject.badssl.com/", bad, "no-subject"),
+      ("https://sha1-intermediate.badssl.com/", bad, "sha1-intermediate"),
+      ("https://sha256.badssl.com/", good, "sha256"),
+      ("https://sha384.badssl.com/", bad, "sha384"),
+      ("https://sha512.badssl.com/", bad, "sha512"),
+      ("https://1000-sans.badssl.com/", bad, "1000-sans"),
+      ("https://10000-sans.badssl.com/", good_broken, "10000-sans"),
+      ("https://ecc256.badssl.com/", good_broken, "ecc256"),
+      ("https://ecc384.badssl.com/", good_broken, "ecc384"),
+      ("https://rsa2048.badssl.com/", good, "rsa2048"),
+      ("https://rsa8192.badssl.com/", dubious_broken, "rsa8192"),
+      ("http://http.badssl.com/", good, "regular http"),
+      ("https://http.badssl.com/", bad_broken, "http on https URL"),  # FIXME
+      ("https://cbc.badssl.com/", dubious, "cbc"),
+      ("https://rc4-md5.badssl.com/", bad, "rc4-md5"),
+      ("https://rc4.badssl.com/", bad, "rc4"),
+      ("https://3des.badssl.com/", bad, "3des"),
+      ("https://null.badssl.com/", bad, "null"),
+      ("https://mozilla-old.badssl.com/", bad_broken, "mozilla-old"),
+      ("https://mozilla-intermediate.badssl.com/", dubious_broken, "mozilla-intermediate"),
+      ("https://mozilla-modern.badssl.com/", good, "mozilla-modern"),
+      ("https://dh480.badssl.com/", bad, "dh480"),
+      ("https://dh512.badssl.com/", bad, "dh512"),
+      ("https://dh1024.badssl.com/", dubious_broken, "dh1024"),
+      ("https://dh2048.badssl.com/", good, "dh2048"),
+      ("https://dh-small-subgroup.badssl.com/", bad_broken, "dh-small-subgroup"),
+      ("https://dh-composite.badssl.com/", bad_broken, "dh-composite"),
+      ("https://static-rsa.badssl.com/", dubious, "static-rsa"),
+      ("https://tls-v1-0.badssl.com:1010/", dubious, "tls-v1-0"),
+      ("https://tls-v1-1.badssl.com:1011/", dubious, "tls-v1-1"),
+      ("https://invalid-expected-sct.badssl.com/", bad, "invalid-expected-sct"),
+      ("https://hsts.badssl.com/", good, "hsts"),
+      ("https://upgrade.badssl.com/", good, "upgrade"),
+      ("https://preloaded-hsts.badssl.com/", good, "preloaded-hsts"),
+      ("https://subdomain.preloaded-hsts.badssl.com/", bad, "subdomain.preloaded-hsts"),
+      ("https://https-everywhere.badssl.com/", good, "https-everywhere"),
+      ("https://long-extended-subdomain-name-containing-many-letters-and-dashes.badssl.com/", good,
+        "long-extended-subdomain-name-containing-many-letters-and-dashes"),
+      ("https://longextendedsubdomainnamewithoutdashesinordertotestwordwrapping.badssl.com/", good,
+        "longextendedsubdomainnamewithoutdashesinordertotestwordwrapping"),
+      ("https://superfish.badssl.com/", bad, "(Lenovo) Superfish"),
+      ("https://edellroot.badssl.com/", bad, "(Dell) eDellRoot"),
+      ("https://dsdtestprovider.badssl.com/", bad, "(Dell) DSD Test Provider"),
+      ("https://preact-cli.badssl.com/", bad, "preact-cli"),
+      ("https://webpack-dev-server.badssl.com/", bad, "webpack-dev-server"),
+      ("https://mitm-software.badssl.com/", bad, "mitm-software"),
+      ("https://sha1-2016.badssl.com/", dubious, "sha1-2016"),
+      ("https://sha1-2017.badssl.com/", bad, "sha1-2017"),
+    ]
+  else:
+    const certificate_tests: array[0..0, CertTest] = [
+      ("https://google.com/", good, "good")
+    ]
+
+
+  template evaluate(exception_msg: string, category: Category, desc: string) =
+    # Evaluate test outcome. Tests flagged as `_broken` are evaluated and skipped
+    let raised = (exception_msg.len > 0)
+    let should_not_raise = category in {good, dubious_broken, bad_broken}
+    if should_not_raise xor raised:
+      # we are seeing a known behavior
+      if category in {good_broken, dubious_broken, bad_broken}:
+        skip()
+      if raised:
+        # check exception_msg == "No SSL certificate found." or
+        doAssert exception_msg == "No SSL certificate found." or
+          exception_msg == "SSL Certificate check failed." or
+          exception_msg.contains("certificate verify failed") or
+          exception_msg.contains("key too small") or
+          exception_msg.contains("alert handshake failure") or
+          exception_msg.contains("bad dh p length") or
+          # TODO: This one should only triggers for 10000-sans
+          exception_msg.contains("excessive message size"), exception_msg
+
+    else:
+      # this is unexpected
+      var fatal = true
+      var msg = ""
+      if raised:
+        msg = "         $# ($#) raised: $#" % [desc, $category, exception_msg]
+        if "500 Internal Server Error" in exception_msg:
+          # refs https://github.com/nim-lang/Nim/issues/16338#issuecomment-804300278
+          # we got: `good (good) raised: 500 Internal Server Error`
+          fatal = false
+          msg.add " (http 500 => assuming this is not our problem)"
+      else:
+        msg = "         $# ($#) did not raise" % [desc, $category]
+
+      if category in {good, dubious, bad} and fatal:
+        echo "D20210322T121353: error: " & msg
+        fail()
+      else:
+        echo "D20210322T121353: warning: " & msg
+
+
+  suite "SSL certificate check - httpclient":
+
+    for i, ct in certificate_tests:
+
+      test ct.desc:
+        var ctx = newContext(verifyMode=CVerifyPeer)
+        var client = newHttpClient(sslContext=ctx)
+        let exception_msg =
+          try:
+            let a = $client.getContent(ct.url)
+            ""
+          except:
+            getCurrentExceptionMsg()
+
+        evaluate(exception_msg, ct.category, ct.desc)
+
+
+
+  # threaded tests
+
+
+  type
+    TTOutcome = ref object
+      desc, exception_msg: string
+      category: Category
+
+  proc run_t_test(ct: CertTest): TTOutcome {.thread.} =
+    ## Run test in a {.thread.} - return by ref
+    result = TTOutcome(desc:ct.desc, exception_msg:"", category: ct.category)
+    try:
+      var ctx = newContext(verifyMode=CVerifyPeer)
+      var client = newHttpClient(sslContext=ctx)
+      let a = $client.getContent(ct.url)
+    except:
+      result.exception_msg = getCurrentExceptionMsg()
+
+
+  suite "SSL certificate check - httpclient - threaded":
+    when defined(nimTestsEnableFlaky) or not defined(linux): # xxx pending bug #16338
+      # Spawn threads before the "test" blocks
+      var outcomes = newSeq[FlowVar[TTOutcome]](certificate_tests.len)
+      for i, ct in certificate_tests:
+        let t = spawn run_t_test(ct)
+        outcomes[i] = t
+
+      # create "test" blocks and handle thread outputs
+      for t in outcomes:
+        let outcome = ^t  # wait for a thread to terminate
+        test outcome.desc:
+          evaluate(outcome.exception_msg, outcome.category, outcome.desc)
+    else:
+      echo "skipped test"
+
+  # net tests
+
+
+  type NetSocketTest = tuple[hostname: string, port: Port, category:Category, desc: string]
+  # badssl certs sometimes expire, set to false when that happens
+  when true:
+    const net_tests:array[0..3, NetSocketTest] = [
+      ("imap.gmail.com", 993.Port, good, "IMAP"),
+      ("wrong.host.badssl.com", 443.Port, bad, "wrong.host"),
+      ("captive-portal.badssl.com", 443.Port, bad, "captive-portal"),
+      ("expired.badssl.com", 443.Port, bad, "expired"),
+    ]
+  else:
+    const net_tests: array[0..0, NetSocketTest] = [
+      ("imap.gmail.com", 993.Port, good, "IMAP")
+    ]
+  # TODO: ("null.badssl.com", 443.Port, bad_broken, "null"),
+
+
+  suite "SSL certificate check - sockets":
+
+    for ct in net_tests:
+
+      test ct.desc:
+
+        var sock = newSocket()
+        var ctx = newContext()
+        ctx.wrapSocket(sock)
+        let exception_msg =
+          try:
+            sock.connect(ct.hostname, ct.port)
+            ""
+          except:
+            getCurrentExceptionMsg()
+
+        evaluate(exception_msg, ct.category, ct.desc)
diff --git a/tests/untestable/tpostgres.nim b/tests/untestable/tpostgres.nim
index d3397e53a..8b1378917 100644
--- a/tests/untestable/tpostgres.nim
+++ b/tests/untestable/tpostgres.nim
@@ -1,328 +1 @@
-import db_postgres, strutils
-
-
-let db = open("localhost", "dom", "", "test")
-db.exec(sql"DROP TABLE IF EXISTS myTable")
-db.exec(sql("""CREATE TABLE myTable (
-                  id integer PRIMARY KEY,
-                  name varchar(50) not null)"""))
-let name = "Dom"
-db.exec(sql"INSERT INTO myTable (id, name) VALUES (0, ?)",
-        name)
-doAssert db.getValue(sql"SELECT name FROM myTable") == name
-# Check issue #3513
-doAssert db.getValue(sql"SELECT name FROM myTable") == name
-
-
-# issue #3560
-proc addToDb(conn: DbConn, fileId: int, fileName: string): int64 =
-  result = conn.insertId(sql("INSERT into files (id, filename) VALUES (?, ?)"), fileId, fileName)
-
-db.exec(sql"DROP TABLE IF EXISTS files")
-db.exec(sql"DROP TABLE IF EXISTS fileobjects")
-db.exec(sql("""CREATE TABLE FILEOBJECTS(
-               ID             SERIAL PRIMARY KEY,
-               FILE_SIZE      INT,
-               MD5            CHAR(32)  NOT NULL UNIQUE
-            );"""))
-
-db.exec(sql("""CREATE TABLE FILES(
-               ID                  SERIAL PRIMARY KEY,
-               OBJECT_ID           INT,
-               FILENAME            TEXT NOT NULL,
-               URI                 TEXT,
-               SCHEME              CHAR(10),
-               PUBLIC              BOOLEAN DEFAULT FALSE,
-               CONSTRAINT fk1_fileobjs FOREIGN KEY (object_id)
-               REFERENCES fileobjects (id) MATCH SIMPLE
-               ON DELETE CASCADE
-            );"""))
-
-let f1 = db.addToDb(1, "hello.tmp")
-doAssert f1 == 1
-let f2 = db.addToDb(2, "hello2.tmp")
-doAssert f2 == 2
-
-# PreparedStmt vs. normal query
-try:
-  echo db.getValue(sql("select * from files where id = $1"), 1)
-  doAssert false, "Exception expected"
-except DbError:
-  let msg = getCurrentExceptionMsg().normalize
-  doAssert "expects" in msg
-  doAssert "?" in msg
-  doAssert "parameter substitution" in msg
-
-doAssert db.getValue(sql("select filename from files where id = ?"), 1) == "hello.tmp"
-
-var first = prepare(db, "one", sql"select filename from files where id = $1", 1)
-doAssert db.getValue(first, 1) == "hello.tmp"
-
-try:
-  var second = prepare(db, "two", sql"select filename from files where id = ?", 1)
-  doAssert false, "Exception expected"
-except:
-  let msg = getCurrentExceptionMsg().normalize
-  doAssert "expects" in msg
-  doAssert "$1" in msg
-  doAssert "parameter substitution" in msg
-
-# issue #3569
-db.exec(SqlQuery("DROP TABLE IF EXISTS tags"))
-db.exec(SqlQuery("CREATE TABLE tags(id serial UNIQUE, name varchar(255))"))
-
-for i in 1..10:
-  var name = "t" & $i
-  echo(name)
-  discard db.getRow(
-    SqlQuery("INSERT INTO tags(name) VALUES(\'$1\') RETURNING id" % [name]))
-    
-# get column details
-db.exec(SqlQuery("DROP TABLE IF EXISTS dbtypes;"))
-db.exec(SqlQuery("DROP TYPE IF EXISTS custom_enum;"))
-db.exec(SqlQuery("CREATE TYPE custom_enum AS ENUM ('1', '2', '3');"))
-db.exec(SqlQuery("DROP TYPE IF EXISTS custom_composite;"))
-db.exec(SqlQuery("CREATE TYPE custom_composite AS (r double precision, i double precision);"))
-db.exec(SqlQuery("""CREATE TABLE dbtypes(
-                    id serial UNIQUE,
-                    bytea_col bytea,
-                    smallint_col smallint,
-                    integer_col integer,
-                    bigint_col bigint,
-                    decimal_col decimal,
-                    numeric_col numeric,
-                    real_col real,
-                    double_precision_col double precision,
-                    smallserial_col smallserial,
-                    serial_col serial,
-                    bigserial_col bigserial,
-                    money_col money,
-                    varchar_col varchar(10),
-                    character_col character(1),
-                    text_col text,
-                    timestamp_col timestamp,
-                    date_col date,
-                    time_col time,
-                    interval_col interval,
-                    bool_col boolean,
-                    custom_enum_col custom_enum,
-                    point_col point,
-                    line_col line,
-                    lseg_col lseg,
-                    box_col box,
-                    path_col path,
-                    polygon_col polygon,
-                    circle_col circle,
-                    cidr_col cidr,
-                    inet_col inet,
-                    macaddr_col macaddr,
-                    bit_col bit,
-                    varbit_col bit(3),
-                    tsvector_col tsvector,
-                    tsquery_col tsquery,
-                    uuid_col uuid,
-                    xml_col xml,
-                    json_col json,
-                    array_col integer[],
-                    custom_composite_col custom_composite,
-                    range_col int4range
-                    );"""))
-db.exec(SqlQuery("INSERT INTO dbtypes (id) VALUES(0);"))
-
-var dbCols : DbColumns = @[]
-for row in db.instantRows(dbCols, sql"SELECT * FROM dbtypes"):
-  doAssert len(dbCols) == 42
-
-doAssert dbCols[0].name == "id"
-doAssert dbCols[0].typ.kind == DbTypeKind.dbInt
-doAssert dbCols[0].typ.name == "int4"
-doAssert dbCols[0].typ.size == 4
-
-doAssert dbCols[1].name == "bytea_col"
-doAssert dbCols[1].typ.kind == DbTypeKind.dbBlob
-doAssert dbCols[1].typ.name == "bytea"
-
-doAssert dbCols[2].name == "smallint_col"
-doAssert dbCols[2].typ.kind == DbTypeKind.dbInt
-doAssert dbCols[2].typ.name == "int2"
-doAssert dbCols[2].typ.size == 2
-
-doAssert dbCols[3].name == "integer_col"
-doAssert dbCols[3].typ.kind == DbTypeKind.dbInt
-doAssert dbCols[3].typ.name == "int4"
-doAssert dbCols[3].typ.size == 4
-
-doAssert dbCols[4].name == "bigint_col"
-doAssert dbCols[4].typ.kind == DbTypeKind.dbInt
-doAssert dbCols[4].typ.name == "int8"
-doAssert dbCols[4].typ.size == 8
-
-doAssert dbCols[5].name == "decimal_col"
-doAssert dbCols[5].typ.kind == DbTypeKind.dbDecimal
-doAssert dbCols[5].typ.name == "numeric"
-
-doAssert dbCols[6].name == "numeric_col"
-doAssert dbCols[6].typ.kind == DbTypeKind.dbDecimal
-doAssert dbCols[6].typ.name == "numeric"
-
-doAssert dbCols[7].name == "real_col"
-doAssert dbCols[7].typ.kind == DbTypeKind.dbFloat
-doAssert dbCols[7].typ.name == "float4"
-
-doAssert dbCols[8].name == "double_precision_col"
-doAssert dbCols[8].typ.kind == DbTypeKind.dbFloat
-doAssert dbCols[8].typ.name == "float8"
-
-doAssert dbCols[9].name == "smallserial_col"
-doAssert dbCols[9].typ.kind == DbTypeKind.dbInt
-doAssert dbCols[9].typ.name == "int2"
-
-doAssert dbCols[10].name == "serial_col"
-doAssert dbCols[10].typ.kind == DbTypeKind.dbInt
-doAssert dbCols[10].typ.name == "int4"
-
-doAssert dbCols[11].name == "bigserial_col"
-doAssert dbCols[11].typ.kind == DbTypeKind.dbInt
-doAssert dbCols[11].typ.name == "int8"
-
-doAssert dbCols[12].name == "money_col"
-doAssert dbCols[12].typ.kind == DbTypeKind.dbDecimal
-doAssert dbCols[12].typ.name == "money"    
-    
-doAssert dbCols[13].name == "varchar_col"
-doAssert dbCols[13].typ.kind == DbTypeKind.dbVarchar
-doAssert dbCols[13].typ.name == "varchar"
-
-doAssert dbCols[14].name == "character_col"
-doAssert dbCols[14].typ.kind == DbTypeKind.dbFixedChar
-doAssert dbCols[14].typ.name == "bpchar"
-
-doAssert dbCols[15].name == "text_col"
-doAssert dbCols[15].typ.kind == DbTypeKind.dbVarchar
-doAssert dbCols[15].typ.name == "text"
-
-doAssert dbCols[16].name == "timestamp_col"
-doAssert dbCols[16].typ.kind == DbTypeKind.dbTimestamp
-doAssert dbCols[16].typ.name == "timestamp"
-
-doAssert dbCols[17].name == "date_col"
-doAssert dbCols[17].typ.kind == DbTypeKind.dbDate
-doAssert dbCols[17].typ.name == "date"
-
-doAssert dbCols[18].name == "time_col"
-doAssert dbCols[18].typ.kind == DbTypeKind.dbTime
-doAssert dbCols[18].typ.name == "time"
-
-doAssert dbCols[19].name == "interval_col"
-doAssert dbCols[19].typ.kind == DbTypeKind.dbTimeInterval
-doAssert dbCols[19].typ.name == "interval"
-
-doAssert dbCols[20].name == "bool_col"
-doAssert dbCols[20].typ.kind == DbTypeKind.dbBool
-doAssert dbCols[20].typ.name == "bool"
-
-doAssert dbCols[21].name == "custom_enum_col"
-doAssert dbCols[21].typ.kind == DbTypeKind.dbUnknown
-doAssert parseInt(dbCols[21].typ.name) > 0
-    
-doAssert dbCols[22].name == "point_col"
-doAssert dbCols[22].typ.kind == DbTypeKind.dbPoint
-doAssert dbCols[22].typ.name == "point"    
-
-doAssert dbCols[23].name == "line_col"
-doAssert dbCols[23].typ.kind == DbTypeKind.dbLine
-doAssert dbCols[23].typ.name == "line"    
-
-doAssert dbCols[24].name == "lseg_col"
-doAssert dbCols[24].typ.kind == DbTypeKind.dbLseg
-doAssert dbCols[24].typ.name == "lseg"    
-
-doAssert dbCols[25].name == "box_col"
-doAssert dbCols[25].typ.kind == DbTypeKind.dbBox
-doAssert dbCols[25].typ.name == "box"    
-
-doAssert dbCols[26].name == "path_col"
-doAssert dbCols[26].typ.kind == DbTypeKind.dbPath
-doAssert dbCols[26].typ.name == "path"    
-
-doAssert dbCols[27].name == "polygon_col"
-doAssert dbCols[27].typ.kind == DbTypeKind.dbPolygon
-doAssert dbCols[27].typ.name == "polygon"
-
-doAssert dbCols[28].name == "circle_col"
-doAssert dbCols[28].typ.kind == DbTypeKind.dbCircle
-doAssert dbCols[28].typ.name == "circle"
-
-doAssert dbCols[29].name == "cidr_col"
-doAssert dbCols[29].typ.kind == DbTypeKind.dbInet
-doAssert dbCols[29].typ.name == "cidr"
-
-doAssert dbCols[30].name == "inet_col"
-doAssert dbCols[30].typ.kind == DbTypeKind.dbInet
-doAssert dbCols[30].typ.name == "inet"
-
-doAssert dbCols[31].name == "macaddr_col"
-doAssert dbCols[31].typ.kind == DbTypeKind.dbMacAddress
-doAssert dbCols[31].typ.name == "macaddr"
-
-doAssert dbCols[32].name == "bit_col"
-doAssert dbCols[32].typ.kind == DbTypeKind.dbBit
-doAssert dbCols[32].typ.name == "bit"
-
-doAssert dbCols[33].name == "varbit_col"
-doAssert dbCols[33].typ.kind == DbTypeKind.dbBit
-doAssert dbCols[33].typ.name == "bit"
-
-doAssert dbCols[34].name == "tsvector_col"
-doAssert dbCols[34].typ.kind == DbTypeKind.dbVarchar
-doAssert dbCols[34].typ.name == "tsvector"
-
-doAssert dbCols[35].name == "tsquery_col"
-doAssert dbCols[35].typ.kind == DbTypeKind.dbVarchar
-doAssert dbCols[35].typ.name == "tsquery"
-
-doAssert dbCols[36].name == "uuid_col"
-doAssert dbCols[36].typ.kind == DbTypeKind.dbVarchar
-doAssert dbCols[36].typ.name == "uuid"
-
-doAssert dbCols[37].name == "xml_col"
-doAssert dbCols[37].typ.kind == DbTypeKind.dbXml
-doAssert dbCols[37].typ.name == "xml"
-
-doAssert dbCols[38].name == "json_col"
-doAssert dbCols[38].typ.kind == DbTypeKind.dbJson
-doAssert dbCols[38].typ.name == "json"
-
-doAssert dbCols[39].name == "array_col"
-doAssert dbCols[39].typ.kind == DbTypeKind.dbArray
-doAssert dbCols[39].typ.name == "int4[]"
-
-doAssert dbCols[40].name == "custom_composite_col"
-doAssert dbCols[40].typ.kind == DbTypeKind.dbUnknown
-doAssert parseInt(dbCols[40].typ.name) > 0
-
-doAssert dbCols[41].name == "range_col"
-doAssert dbCols[41].typ.kind == DbTypeKind.dbComposite
-doAssert dbCols[41].typ.name == "int4range"
-
-# issue 6571
-db.exec(sql"DROP TABLE IF EXISTS DICTIONARY")
-db.exec(sql("""CREATE TABLE DICTIONARY(
-               id             SERIAL PRIMARY KEY,
-               entry      VARCHAR(1000) NOT NULL,
-               definition VARCHAR(4000) NOT NULL
-            );"""))
-var entry = "あっそ"
-var definition = "(int) (See ああそうそう) oh, really (uninterested)/oh yeah?/hmmmmm"
-discard db.getRow(
-  SqlQuery("INSERT INTO DICTIONARY(entry, definition) VALUES(\'$1\', \'$2\') RETURNING id" % [entry, definition]))
-doAssert db.getValue(sql"SELECT definition FROM DICTIONARY WHERE entry = ?", entry) == definition
-entry = "Format string entry"
-definition = "Format string definition"
-db.exec(sql"INSERT INTO DICTIONARY(entry, definition) VALUES (?, ?)", entry, definition)
-doAssert db.getValue(sql"SELECT definition FROM DICTIONARY WHERE entry = ?", entry) == definition
-
-echo("All tests succeeded!")
-
-db.close()
 
diff --git a/tests/usingstmt/tthis.nim b/tests/usingstmt/tthis.nim
deleted file mode 100644
index 83d75d08c..000000000
--- a/tests/usingstmt/tthis.nim
+++ /dev/null
@@ -1,15 +0,0 @@
-
-# bug #4177
-
-type
-  Parent = object of RootObj
-    parentField: int
-  Child = object of Parent
-    childField: int
-
-{.this: self.}
-proc sumFields(self: Child): int =
-  result = parentField + childField # Error: undeclared identifier: 'parentField'
-
-proc sumFieldsWorks(self: Child): int =
-  result = self.parentField + childField
diff --git a/tests/usingstmt/tusingstmt.nim b/tests/usingstmt/tusingstmt.nim
new file mode 100644
index 000000000..11803878e
--- /dev/null
+++ b/tests/usingstmt/tusingstmt.nim
@@ -0,0 +1,16 @@
+type
+  Foo = object
+
+using
+  c: Foo
+  x, y: int
+
+proc usesSig(c) = discard
+
+proc foobar(c, y) = discard
+
+usesSig(Foo())
+foobar(Foo(), 123)
+doAssert not compiles(usesSig(123))
+doAssert not compiles(foobar(Foo(), Foo()))
+doAssert not compiles(foobar(123, 123))
diff --git a/tests/valgrind/tleak_arc.nim b/tests/valgrind/tleak_arc.nim
new file mode 100644
index 000000000..c47ee137a
--- /dev/null
+++ b/tests/valgrind/tleak_arc.nim
@@ -0,0 +1,14 @@
+discard """
+valgrind: true
+cmd: "nim $target --gc:arc -d:useMalloc $options $file"
+exitcode: 1
+outputsub: "   definitely lost: 7 bytes in 2 blocks"
+disabled: "freebsd"
+disabled: "osx"
+disabled: "openbsd"
+disabled: "windows"
+disabled: "32bit"
+"""
+
+discard alloc(3)
+discard alloc(4)
diff --git a/tests/varres/tprevent_forloopvar_mutations.nim b/tests/varres/tprevent_forloopvar_mutations.nim
index 398191658..c9aeb94d8 100644
--- a/tests/varres/tprevent_forloopvar_mutations.nim
+++ b/tests/varres/tprevent_forloopvar_mutations.nim
@@ -1,11 +1,10 @@
 discard """
-  errmsg: "type mismatch: got <int>"
-  line: 17
-  nimout: '''type mismatch: got <int>
+  errormsg: "type mismatch: got <int>"
+  nimout: '''tprevent_forloopvar_mutations.nim(16, 3) Error: type mismatch: got <int>
 but expected one of:
-proc inc[T: Ordinal | uint | uint64](x: var T; y = 1)
+proc inc[T, V: Ordinal](x: var T; y: V = 1)
   first type mismatch at position: 1
-  required type for x: var T: Ordinal or uint or uint64
+  required type for x: var T: Ordinal
   but expression 'i' is immutable, not 'var'
 
 expression: inc i
diff --git a/tests/varres/tvarres0.nim b/tests/varres/tvarres0.nim
index fd10a73bd..94bdb4a06 100644
--- a/tests/varres/tvarres0.nim
+++ b/tests/varres/tvarres0.nim
@@ -4,6 +4,7 @@ discard """
 123
 1234
 12345
+123456
 '''
 """
 
@@ -28,3 +29,113 @@ getF().a = 1234
 echo getF().a
 getF() = Foo(a: 12345)
 echo getF().a
+(addr getF())[] = Foo(a: 123456)
+echo getF().a
+
+
+block: # #13848
+  template fun() =
+    block:
+      var m = 1
+
+      proc identity(o: var int): var int =
+        result = o
+        result += 5
+
+      identity(m) += 3
+      doAssert m == 5+4
+
+    block:
+      var m = 10
+      proc identity2(o: var int): var int =
+        result = m
+        result += 100
+
+      var ignored = 27
+      identity2(ignored) += 7
+      doAssert m == 10 + 100 + 7
+
+    block:
+      iterator test3(o: var int): var int = yield o
+      var m = 1
+      for m2 in test3(m): m2+=3
+      doAssert m == 4
+
+  static: fun()
+  fun()
+
+  template fun2() =
+    block:
+      var m = 1
+      var m2 = 1
+      iterator test3(o: var int): (var int, var int) =
+        yield (o, m2)
+
+      for ti in test3(m):
+        ti[0]+=3
+        ti[1]+=4
+
+      doAssert (m, m2) == (4, 5)
+  fun2()
+  # static: fun2() # BUG: Error: attempt to access a nil address kind: rkInt
+
+  template fun3() =
+    block:
+      proc test4[T1](o: var T1): var int = o[1]
+      block:
+        var m = @[1,2]
+        test4(m) += 10
+        doAssert m[1] == 2+10
+      block:
+        var m = [1,2]
+        test4(m) += 10
+        doAssert m[1] == 2+10
+      block:
+        var m = (1, 2)
+        test4(m) += 10
+        doAssert m[1] == 2+10
+
+      proc test5[T1](o: var T1): var int = o.x
+      block:
+        type Foo = object
+          x: int
+        var m = Foo(x: 2)
+        test5(m) += 10
+        doAssert m.x == 2+10
+      block:
+        type Foo = ref object
+          x: int
+        var m = Foo(x: 2)
+        test5(m) += 10
+        doAssert m.x == 2+10
+
+      proc test6[T1](o: T1): var int = o.x
+      block:
+        type Foo = ref object
+          x: int
+        var m = Foo(x: 2)
+        test6(m) += 10
+        doAssert m.x == 2+10
+
+  fun3()
+  static: fun3()
+
+  when false:
+    # BUG:
+    # c: SIGSEGV
+    # cpp: error: call to implicitly-deleted default constructor of 'tyTuple__ILZebuYefUeQLAzY85QkHA'
+    proc test7[T](o: var T): (var int,) =
+      (o[1], )
+    var m = @[1,2]
+    test7(m)[0] += 10
+
+block:
+  # example from #13848
+  type
+    MyType[T] = object
+      a,b: T
+    MyTypeAlias = MyType[float32]
+
+  var m: MyTypeAlias
+  proc identity(o: var MyTypeAlias): var MyTypeAlias = o
+  discard identity(m)
diff --git a/tests/varstmt/tvardecl.nim b/tests/varstmt/tvardecl.nim
index 37bc4bad7..d5ccfafb7 100644
--- a/tests/varstmt/tvardecl.nim
+++ b/tests/varstmt/tvardecl.nim
@@ -2,6 +2,7 @@ discard """
   output: "44"
 """
 # Test the new variable declaration syntax
+import std/sequtils
 
 var
   x = 0
@@ -10,3 +11,9 @@ var
 
 write(stdout, a)
 writeLine(stdout, b) #OUT 44
+
+proc p() = # bug #18104
+  var x, y = newSeqWith(10, newString(3))
+  discard (x, y)
+
+p()
diff --git a/tests/views/t19986.nim b/tests/views/t19986.nim
new file mode 100644
index 000000000..85a7cf97d
--- /dev/null
+++ b/tests/views/t19986.nim
@@ -0,0 +1,42 @@
+discard """
+  cmd: '''nim check --hints:off $file'''
+  action: reject
+nimout: '''
+t19986.nim(19, 7) Error: 'foo' borrows from the immutable location 'a' and attempts to mutate it
+t19986.nim(28, 7) Error: 'foo' borrows from the immutable location 'a' and attempts to mutate it
+t19986.nim(37, 7) Error: 'foo' borrows from the immutable location 'a' and attempts to mutate it
+'''
+"""
+
+{.experimental: "views".}
+
+type
+  Object = object
+    id: int
+
+proc foo() =
+  let a = Object(id: 3)
+  var foo: var Object = a
+
+  foo.id = 777
+  echo a
+
+foo()
+
+proc bar() =
+  let a = "123"
+  var foo: var string = a
+
+  foo[0] = '7'
+  echo a
+
+bar()
+
+proc main() =
+  let a = 3
+  var foo: var int = a
+
+  foo = 777
+  echo a
+
+main()
diff --git a/tests/views/tcan_compile_nim.nim b/tests/views/tcan_compile_nim.nim
new file mode 100644
index 000000000..e990606cd
--- /dev/null
+++ b/tests/views/tcan_compile_nim.nim
@@ -0,0 +1,4 @@
+discard """
+  cmd: "nim check --hints:on --experimental:strictFuncs --experimental:views compiler/nim.nim"
+  action: "compile"
+"""
diff --git a/tests/views/tcannot_borrow.nim b/tests/views/tcannot_borrow.nim
new file mode 100644
index 000000000..0b8793159
--- /dev/null
+++ b/tests/views/tcannot_borrow.nim
@@ -0,0 +1,22 @@
+discard """
+  errormsg: "cannot borrow"
+  nimout: '''tcannot_borrow.nim(20, 7) Error: cannot borrow meh; what it borrows from is potentially mutated
+tcannot_borrow.nim(21, 3) the mutation is here'''
+"""
+
+
+{.experimental: "views".}
+
+type
+  Foo = object
+    field: string
+
+proc valid(s: var seq[Foo]) =
+  let v: lent Foo = s[0]  # begin of borrow
+  echo v.field            # end of borrow
+  s.setLen 0  # valid because 'v' isn't used afterwards
+
+proc dangerous(s: var seq[Foo]) =
+  let meh: lent Foo = s[0]
+  s.setLen 0
+  echo meh.field
diff --git a/tests/views/tconst_views.nim b/tests/views/tconst_views.nim
new file mode 100644
index 000000000..a85b03864
--- /dev/null
+++ b/tests/views/tconst_views.nim
@@ -0,0 +1,37 @@
+discard """
+  cmd: "nim c --experimental:views $file"
+  output: '''(data: [1, 2, 3], other: 4)
+[1, 20, 3]'''
+"""
+
+type
+  Foo = object
+    data: openArray[int]
+    other: int
+
+const
+  c = Foo(data: [1, 2, 3], other: 4)
+
+  c2 = Foo(data: [1, 20, 3], other: 4)
+
+proc `$`(x: openArray[int]): string =
+  result = "["
+  for i in x:
+    if result.len > 1: result.add ", "
+    result.add $i
+  result.add "]"
+
+echo c
+echo c2.data
+
+
+type MyObj = object
+  data: openarray[char]
+
+const
+  val1 = Foo(data: toOpenArray([1, 2, 3], 1, 1))
+  val2 = Foo(data: toOpenArray([1, 2, 3], 0, 2))
+  val3 = MyObj(data: "Hello".toOpenArray(0, 2))
+assert val1.data == [2]
+assert val2.data == [1, 2, 3]
+assert val3.data == "Hel"
diff --git a/tests/views/tdont_mutate.nim b/tests/views/tdont_mutate.nim
new file mode 100644
index 000000000..eb5a82cbf
--- /dev/null
+++ b/tests/views/tdont_mutate.nim
@@ -0,0 +1,58 @@
+discard """
+  cmd: "nim check --hints:off $file"
+"""
+
+import tables
+
+{.experimental: "views".}
+
+const
+  Whitespace = {' ', '\t', '\n', '\r'}
+
+proc split*(s: string, seps: set[char] = Whitespace, maxsplit: int = -1): Table[int, openArray[char]] #[tt.Error
+^ 'result' borrows from the immutable location 's' and attempts to mutate it
+    ]# =
+  var last = 0
+  var splits = maxsplit
+  result = initTable[int, openArray[char]]()
+
+  while last <= len(s):
+    var first = last
+    while last < len(s) and s[last] notin seps:
+      inc(last)
+    if splits == 0: last = len(s)
+    result[first] = toOpenArray(s, first, last-1)
+
+    result[first][0] = 'c'
+
+    if splits == 0: break
+    dec(splits)
+    inc(last)
+
+proc `$`(x: openArray[char]): string =
+  result = newString(x.len)
+  for i in 0..<x.len: result[i] = x[i]
+
+proc otherTest(x: int) =
+  var y: var int = x #[tt.Error
+      ^ 'y' borrows from the immutable location 'x' and attempts to mutate it
+  ]#
+  y = 3
+
+proc main() =
+  let words = split("asdf 231")
+  for i, x in words:
+    echo i, ": ", x
+
+main()
+
+# This has to continue to work:
+
+type
+  PNode = ref object
+  TSrcGen = object
+    comStack: seq[PNode]
+
+proc pushCom(g: var TSrcGen, n: PNode) =
+  setLen(g.comStack, g.comStack.len + 1)
+  g.comStack[^1] = n
diff --git a/tests/views/tmust_borrow_from_first_parameter.nim b/tests/views/tmust_borrow_from_first_parameter.nim
new file mode 100644
index 000000000..b2decfb38
--- /dev/null
+++ b/tests/views/tmust_borrow_from_first_parameter.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "'result' must borrow from the first parameter"
+  line: 9
+"""
+
+{.experimental: "views".}
+
+proc p(a, b: openArray[char]): openArray[char] =
+  result = b
diff --git a/tests/views/tsplit_into_openarray.nim b/tests/views/tsplit_into_openarray.nim
new file mode 100644
index 000000000..3ea290d89
--- /dev/null
+++ b/tests/views/tsplit_into_openarray.nim
@@ -0,0 +1,37 @@
+discard """
+  output: '''asdf
+231
+'''
+  cmd: "nim c --gc:arc -d:useMalloc -g $file"
+  valgrind: true
+"""
+
+{.experimental: "views".}
+
+const
+  Whitespace = {' ', '\t', '\n', '\r'}
+
+iterator split*(s: string, seps: set[char] = Whitespace,
+                maxsplit: int = -1): openArray[char] =
+  var last = 0
+  var splits = maxsplit
+
+  while last <= len(s):
+    var first = last
+    while last < len(s) and s[last] notin seps:
+      inc(last)
+    if splits == 0: last = len(s)
+    yield toOpenArray(s, first, last-1)
+    if splits == 0: break
+    dec(splits)
+    inc(last)
+
+proc `$`(x: openArray[char]): string =
+  result = newString(x.len)
+  for i in 0..<x.len: result[i] = x[i]
+
+proc main() =
+  for x in split("asdf 231"):
+    echo x
+
+main()
diff --git a/tests/views/tsplit_into_seq.nim b/tests/views/tsplit_into_seq.nim
new file mode 100644
index 000000000..a0861458b
--- /dev/null
+++ b/tests/views/tsplit_into_seq.nim
@@ -0,0 +1,41 @@
+discard """
+  output: '''asdf
+asdf
+231
+231
+'''
+  cmd: "nim c --gc:orc $file"
+"""
+
+{.experimental: "views".}
+
+const
+  Whitespace = {' ', '\t', '\n', '\r'}
+
+proc split*(s: string, seps: set[char] = Whitespace,
+                maxsplit: int = -1): seq[openArray[char]] =
+  var last = 0
+  var splits = maxsplit
+  result = @[]
+
+  while last <= len(s):
+    var first = last
+    while last < len(s) and s[last] notin seps:
+      inc(last)
+    if splits == 0: last = len(s)
+    result.add toOpenArray(s, first, last-1)
+    result.add toOpenArray(s, first, last-1)
+    if splits == 0: break
+    dec(splits)
+    inc(last)
+
+proc `$`(x: openArray[char]): string =
+  result = newString(x.len)
+  for i in 0..<x.len: result[i] = x[i]
+
+proc main() =
+  let words = split("asdf 231")
+  for x in words:
+    echo x
+
+main()
diff --git a/tests/views/tsplit_into_table.nim b/tests/views/tsplit_into_table.nim
new file mode 100644
index 000000000..49371b9a7
--- /dev/null
+++ b/tests/views/tsplit_into_table.nim
@@ -0,0 +1,40 @@
+discard """
+  output: '''5: 231
+0: asdf
+'''
+"""
+
+import tables
+
+{.experimental: "views".}
+
+const
+  Whitespace = {' ', '\t', '\n', '\r'}
+
+proc split*(s: string, seps: set[char] = Whitespace,
+                maxsplit: int = -1): Table[int, openArray[char]] =
+  var last = 0
+  var splits = maxsplit
+  result = initTable[int, openArray[char]]()
+
+  while last <= len(s):
+    var first = last
+    while last < len(s) and s[last] notin seps:
+      inc(last)
+    if splits == 0: last = len(s)
+    result[first] = toOpenArray(s, first, last-1)
+
+    if splits == 0: break
+    dec(splits)
+    inc(last)
+
+proc `$`(x: openArray[char]): string =
+  result = newString(x.len)
+  for i in 0..<x.len: result[i] = x[i]
+
+proc main() =
+  let words = split("asdf 231")
+  for i, x in words:
+    echo i, ": ", x
+
+main()
diff --git a/tests/views/tviews1.nim b/tests/views/tviews1.nim
new file mode 100644
index 000000000..9785d25e5
--- /dev/null
+++ b/tests/views/tviews1.nim
@@ -0,0 +1,136 @@
+discard """
+  output: '''11
+22
+33
+3
+2
+3
+3
+15
+(oa: [1, 3, 4])'''
+  targets: "c cpp"
+"""
+
+{.experimental: "views".}
+
+proc take(a: openArray[int]) =
+  echo a.len
+
+proc main(s: seq[int]) =
+  var x: openArray[int] = s
+  for i in 0 .. high(x):
+    echo x[i]
+  take(x)
+
+  take(x.toOpenArray(0, 1))
+  let y = x
+  take y
+  take x
+
+main(@[11, 22, 33])
+
+var x: int
+
+proc foo(x: var int): var int =
+  once: x = 42
+  return x
+
+var y: var int = foo(x)
+y = 15
+echo foo(x)
+# bug #16132
+
+# bug #18690
+
+type
+  F = object
+    oa: openArray[int]
+
+let s1 = @[1,3,4,5,6]
+var test = F(oa: toOpenArray(s1, 0, 2))
+echo test
+
+type
+  Foo = object
+    x: string
+    y: seq[int]
+    data: array[10000, byte]
+
+  View[T] = object
+    x: lent T
+
+proc mainB =
+  let f = Foo(y: @[1, 2, 3])
+  let foo = View[Foo](x: f)
+  assert foo.x.x == ""
+  assert foo.x.y == @[1, 2, 3]
+
+mainB()
+
+
+# bug #15897
+type Outer = ref object 
+  value: int
+type Inner = object
+  owner: var Outer
+  
+var o = Outer(value: 1234)
+var v = Inner(owner: o).owner.value
+doAssert v == 1234
+
+block: # bug #21674
+  type
+    Lent = object
+      data: lent int
+
+  proc foo(s: Lent) =
+    var m = 12
+    discard cast[lent int](m)
+
+  proc main =
+    var m1 = 123
+    var x = Lent(data: m1)
+    foo(x)
+
+  main()
+
+block: # bug #22117
+  proc main: int =
+    var a = 10
+    defer: discard a # extend a's lifetime
+
+    var aref: var int = a
+      #└──── 'aref' borrows from location 'a' which does not live long enough
+
+    result = aref
+
+  doAssert main() == 10
+
+type
+  Slice*[T] = object
+    first, last: int
+    p: ptr UncheckedArray[T]
+
+var i = 0
+
+converter autoToOpenArray*[T](s: Slice[T]): openArray[T] =
+  inc i
+  result = toOpenArray(s.p, s.first, s.last)
+
+proc acceptOpenArray(s: openArray[byte]) = discard
+
+proc bug22597 = # bug #22597
+  acceptOpenArray(Slice[byte]())
+  doAssert i == 1
+
+bug22597()
+
+block: # bug #20048
+  type
+    Test = object
+      tokens: openArray[string]
+
+  func init(Self: typedesc[Test], tokens: openArray[string]): Self = Self(tokens: tokens)
+
+  let data = Test.init(["123"])
+  doAssert @(data.tokens) == @["123"] 
diff --git a/tests/views/tviews2.nim b/tests/views/tviews2.nim
new file mode 100644
index 000000000..29aff76df
--- /dev/null
+++ b/tests/views/tviews2.nim
@@ -0,0 +1,90 @@
+discard """
+  targets: "c js"
+"""
+
+{.experimental: "views".}
+
+block:
+  type
+    Foo = object
+      id: openArray[char]
+
+  proc foo(): Foo =
+    var source = "1245"
+    result = Foo(id: source.toOpenArray(0, 1))
+
+  doAssert foo().id == @['1', '2']
+
+block: # bug #15778
+  type
+    Reader = object
+      data: openArray[char]
+      current: int
+
+  var count = 0
+
+  proc read(data: var Reader, length: int): openArray[char] =
+    inc count
+    let start = data.current
+    data.current.inc length
+    return data.data.toOpenArray(start, data.current-1)
+
+  var data = "hello there"
+  var reader = Reader(data: data.toOpenArray(0, data.len-1), current: 0)
+  doAssert @(reader.read(2)) == @['h', 'e']
+  doAssert @(reader.read(3)) == @['l', 'l', 'o']
+  doAssert count == 2
+
+block: # bug #16671
+  block:
+    type X = ref object of RootObj
+    type Y = ref object of X
+      field: openArray[int]
+
+    var s: seq[X]
+    proc f() =
+      s.add(Y(field: [1]))
+
+    f()
+
+  block:
+    type X = ref object of RootObj
+    type Y = ref object of X
+      field: openArray[int]
+
+    var s: seq[X]
+    proc f() =
+      s.add(Y(field: toOpenArray([1, 2, 3], 0, 1)))
+
+    f()
+
+block: # bug #15746
+  type
+    Reader = object
+      data: openArray[char]
+      current: int
+
+  proc initReader(data: openArray[char], offset = 0): Reader =
+    result = Reader(data: data, current: offset)
+
+  let s = "\x01\x00\x00\x00"
+  doAssert initReader(s).data[0].int == 1
+
+block:
+  proc foo(x: openArray[char]) =
+    discard x
+
+  foo("12254")
+  foo(@['a', 'b'])
+
+  var a1 = "12254"
+  foo(a1)
+
+  var a2 = @['a', 'b']
+  foo(a2)
+
+  var s = "138443"
+  var ooo: openArray[char] = s
+  var xxx: openArray[char] = ooo
+  foo(ooo)
+  foo(xxx)
diff --git a/tests/vm/tevalffi.nim b/tests/vm/mevalffi.nim
index c2abdba5d..ad8f8b62b 100644
--- a/tests/vm/tevalffi.nim
+++ b/tests/vm/mevalffi.nim
@@ -1,43 +1,16 @@
-discard """
-  cmd: "nim c --experimental:compiletimeFFI $file"
-  nimout: '''
-foo
-foo:100
-foo:101
-foo:102:103
-foo:102:103:104
-foo:0.03:asdf:103:105
-ret={s1:foobar s2:foobar age:25 pi:3.14}
-hello world stderr
-hi stderr
-'''
-  output: '''
-foo
-foo:100
-foo:101
-foo:102:103
-foo:102:103:104
-foo:0.03:asdf:103:105
-ret={s1:foobar s2:foobar age:25 pi:3.14}
-hello world stderr
-hi stderr
-'''
-  disabled: "true"
-"""
-
 # re-enable for windows once libffi can be installed in koch.nim
 # With win32 (not yet win64), libffi on windows works and this test passes.
 
-when defined(linux):
+when defined(linux) or defined(bsd):
   {.passL: "-lm".} # for exp
 proc c_exp(a: float64): float64 {.importc: "exp", header: "<math.h>".}
 
 proc c_printf(frmt: cstring): cint {.importc: "printf", header: "<stdio.h>", varargs, discardable.}
 
 const snprintfName = when defined(windows): "_snprintf" else: "snprintf"
-proc c_snprintf*(buffer: pointer, buf_size: uint, format: cstring): cint {.importc: snprintfName, header: "<stdio.h>", varargs .}
+proc c_snprintf*(str: cstring, size: csize_t, format: cstring): cint {.importc: snprintfName, header: "<stdio.h>", varargs .}
 
-proc c_malloc(size:uint):pointer {.importc:"malloc", header: "<stdlib.h>".}
+proc c_malloc(size: csize_t): pointer {.importc:"malloc", header: "<stdlib.h>".}
 proc c_free(p: pointer) {.importc:"free", header: "<stdlib.h>".}
 
 proc fun() =
@@ -62,12 +35,15 @@ proc fun() =
 
   block: # c_snprintf, c_malloc, c_free
     let n: uint = 50
-    var buffer2: pointer = c_malloc(n)
+    var buffer2 = cstring(cast[ptr char](c_malloc(n)))
+
     var s: cstring = "foobar"
     var age: cint = 25
-    let j = c_snprintf(buffer2, n, "s1:%s s2:%s age:%d pi:%g", s, s, age, 3.14)
-    c_printf("ret={%s}\n", buffer2)
-    c_free(buffer2) # not sure it has an effect
+    let num = c_snprintf(buffer2, n, "s1:%s s2:%s age:%d pi:%g", s, s, age, 3.14)
+    let numExp = 34 
+    doAssert num == numExp
+    c_printf("ret=[%s]\n", buffer2)
+    c_free(buffer2)
 
   block: # c_printf bug
     var a = 123
@@ -85,10 +61,11 @@ static:
   fun()
 fun()
 
-when true:
+when not defined nimEvalffiStderrWorkaround:
   import system/ansi_c
-  proc fun2()=
-    c_fprintf(cstderr, "hello world stderr\n")
-    write(stderr, "hi stderr\n")
-  static: fun2()
-  fun2()
+  block:
+    proc fun2()=
+      c_fprintf(cstderr, "hello world stderr\n")
+      write(stderr, "hi stderr\n")
+    static: fun2()
+    fun2()
diff --git a/tests/vm/mscriptcompiletime.nim b/tests/vm/mscriptcompiletime.nim
new file mode 100644
index 000000000..ed7e7c029
--- /dev/null
+++ b/tests/vm/mscriptcompiletime.nim
@@ -0,0 +1,7 @@
+# bug.nim
+var bar* {.compileTime.} = 1
+
+proc dummy = discard
+
+static:
+  inc bar
\ No newline at end of file
diff --git a/tests/vm/t11637.nim b/tests/vm/t11637.nim
new file mode 100644
index 000000000..c061c6641
--- /dev/null
+++ b/tests/vm/t11637.nim
@@ -0,0 +1,52 @@
+type Foo = ref object
+  val: int
+
+proc `+`(a, b: Foo): Foo =
+  Foo(val: a.val + b.val)
+
+proc `*`(a: Foo, b: int): Foo =
+  Foo(val: a.val * b)
+
+proc `+=`(a: var Foo, b: Foo) =
+  a = Foo(
+    val: a.val + b.val
+  )
+
+proc foobar(a, b, c: Foo): tuple[bar, baz, buzz: Foo] =
+
+  let foo = a + b + c
+  result.bar = foo * 2
+
+  result.baz = foo * 3
+  result.buzz = result.baz
+
+  result.buzz += a * 10000
+  result.baz += b
+  result.buzz += b
+
+
+block: # Compile-Time
+  let
+    a {.compileTime.} = Foo(val: 1)
+    b {.compileTime.} = Foo(val: 2)
+    c {.compileTime.} = Foo(val: 3)
+    r {.compileTime.} = foobar(a, b, c)
+
+  static:
+    doAssert r.bar.val == 12
+    doAssert r.baz.val == 20
+    doAssert r.buzz.val == 10020
+
+####################################
+
+block: # Run-time
+  let
+    a = Foo(val: 1)
+    b = Foo(val: 2)
+    c = Foo(val: 3)
+    r = foobar(a, b, c)
+
+  # Expected values
+  doAssert r.bar.val == 12
+  doAssert r.baz.val == 20
+  doAssert r.buzz.val == 10020
diff --git a/tests/vm/t17039.nim b/tests/vm/t17039.nim
new file mode 100644
index 000000000..f92c93f30
--- /dev/null
+++ b/tests/vm/t17039.nim
@@ -0,0 +1,10 @@
+type
+  Obj1 = object
+    case kind: bool
+    of false:
+      field: seq[int]
+    else: discard
+
+static:
+  var obj1 = Obj1()
+  obj1.field.add(@[])
diff --git a/tests/vm/t17121.nim b/tests/vm/t17121.nim
new file mode 100644
index 000000000..bf2d6423f
--- /dev/null
+++ b/tests/vm/t17121.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "cannot 'importc' variable at compile time; c_printf"
+"""
+
+proc c_printf*(frmt: cstring): cint {.importc: "printf", header: "<stdio.h>", varargs, discardable.} =
+  ## foo bar
+  runnableExamples: discard
+static:
+  let a = c_printf("abc\n")
diff --git a/tests/vm/t18103.nim b/tests/vm/t18103.nim
new file mode 100644
index 000000000..8622ab290
--- /dev/null
+++ b/tests/vm/t18103.nim
@@ -0,0 +1,35 @@
+discard """
+  targets: "c cpp"
+  matrix: "--mm:refc; --mm:arc"
+"""
+
+import base64, complex, sequtils, math, sugar
+
+type
+
+  FP = float
+  T = object
+    index: int
+    arg: FP
+    val: Complex[FP]
+  M = object
+    alpha, beta: FP
+
+func a(s: openArray[T], model: M): seq[T] =
+  let f = (tn: int) => model.alpha + FP(tn) * model.beta;
+  return mapIt s:
+    block:
+      let s = it.val * rect(1.0, - f(it.index))
+      T(index: it.index, arg: phase(s), val: s)
+
+proc b(): float64 =
+  var s = toSeq(0..10).mapIt(T(index: it, arg: 1.0, val: complex.complex(1.0)))
+  discard a(s, M(alpha: 1, beta: 1))
+  return 1.0
+
+func cc(str: cstring, offset: ptr[cdouble]): cint {.exportc.} =
+  offset[] = b()
+  return 0
+
+static:
+  echo b()
diff --git a/tests/vm/t19075.nim b/tests/vm/t19075.nim
new file mode 100644
index 000000000..89ca9cb19
--- /dev/null
+++ b/tests/vm/t19075.nim
@@ -0,0 +1,19 @@
+discard """
+  timeout: 10
+  joinable: false
+"""
+
+# bug #19075
+const size = 50_000
+
+const stuff = block:
+    var a: array[size, int]
+    a
+
+const zeugs = block:
+    var zeugs: array[size, int]
+    for i in 0..<size:
+        zeugs[i] = stuff[i]
+    zeugs
+
+doAssert zeugs[0] == 0
\ No newline at end of file
diff --git a/tests/vm/t19199.nim b/tests/vm/t19199.nim
new file mode 100644
index 000000000..6ae48cb54
--- /dev/null
+++ b/tests/vm/t19199.nim
@@ -0,0 +1,6 @@
+# bug #19199
+proc mikasa(x: float) = doAssert x == 42
+
+static:
+  mikasa 42.uint.float
+mikasa 42.uint.float
diff --git a/tests/vm/t20746.nim b/tests/vm/t20746.nim
new file mode 100644
index 000000000..bfad269ef
--- /dev/null
+++ b/tests/vm/t20746.nim
@@ -0,0 +1,13 @@
+discard """
+  timeout: 10
+  joinable: false
+  output: "fine"
+"""
+
+func addString(): string =
+  let x = newString(1000000)
+  for i in 0..<1000000:
+    discard x[i]
+
+const translationTable = addString()
+echo "fine"
diff --git a/tests/vm/t21704.nim b/tests/vm/t21704.nim
new file mode 100644
index 000000000..27f4f5b06
--- /dev/null
+++ b/tests/vm/t21704.nim
@@ -0,0 +1,69 @@
+discard """
+matrix: "--hints:off"
+nimout: '''
+Found 2 tests to run.
+Found 3 benches to compile.
+ 
+  --passC:-Wno-stringop-overflow --passL:-Wno-stringop-overflow 
+ 
+  --passC:-Wno-stringop-overflow --passL:-Wno-stringop-overflow 
+ 
+  --passC:-Wno-stringop-overflow --passL:-Wno-stringop-overflow
+'''
+"""
+# bug #21704
+import std/strformat
+
+const testDesc: seq[string] = @[
+  "tests/t_hash_sha256_vs_openssl.nim",
+  "tests/t_cipher_chacha20.nim"
+]
+const benchDesc = [
+  "bench_sha256",
+  "bench_hash_to_curve",
+  "bench_ethereum_bls_signatures"
+]
+
+proc setupTestCommand(flags, path: string): string =
+  return "nim c -r " &
+    flags &
+    &" --nimcache:nimcache/{path} " & # Commenting this out also solves the issue
+    path
+
+proc testBatch(commands: var string, flags, path: string) =
+  commands &= setupTestCommand(flags, path) & '\n'
+
+proc setupBench(benchName: string): string =
+  var runFlags = if false: " -r "
+                 else: " " # taking this branch is needed to trigger the bug
+
+  echo runFlags # Somehow runflags isn't reset in corner cases
+  runFlags &= " --passC:-Wno-stringop-overflow --passL:-Wno-stringop-overflow "
+  echo runFlags
+
+  return "nim c " &
+       runFlags &
+       &" benchmarks/{benchName}.nim"
+
+proc buildBenchBatch(commands: var string, benchName: string) =
+  let command = setupBench(benchName)
+  commands &= command & '\n'
+
+proc addTestSet(cmdFile: var string) =
+  echo "Found " & $testDesc.len & " tests to run."
+
+  for path in testDesc:
+    var flags = "" # This is important
+    cmdFile.testBatch(flags, path)
+
+proc addBenchSet(cmdFile: var string) =
+  echo "Found " & $benchDesc.len & " benches to compile."
+  for bd in benchDesc:
+    cmdFile.buildBenchBatch(bd)
+
+proc task_bug() =
+  var cmdFile: string
+  cmdFile.addTestSet() # Comment this out and there is no bug
+  cmdFile.addBenchSet()
+
+static: task_bug()
diff --git a/tests/vm/t9622.nim b/tests/vm/t9622.nim
new file mode 100644
index 000000000..fada8fe59
--- /dev/null
+++ b/tests/vm/t9622.nim
@@ -0,0 +1,30 @@
+discard """
+  targets: "c cpp"
+  matrix: "--mm:refc; --mm:arc"
+"""
+
+type
+  GlobNodeKind = enum
+    LiteralIdent,
+    Group
+
+  GlobNode = object
+    case kind: GlobNodeKind
+    of LiteralIdent:
+      value: string
+    of Group:
+      values: seq[string]
+
+  PathSegment = object
+    children: seq[GlobNode]
+
+  GlobPattern = seq[PathSegment]
+
+proc parseImpl(): GlobPattern =
+  if result.len == 0:
+    result.add PathSegment()
+  result[^1].children.add GlobNode(kind: LiteralIdent)
+
+block:
+  const pattern = parseImpl()
+  doAssert $pattern == """@[(children: @[(kind: LiteralIdent, value: "")])]"""
diff --git a/tests/vm/tableinstatic.nim b/tests/vm/tableinstatic.nim
index 4080a5286..934c3a8dd 100644
--- a/tests/vm/tableinstatic.nim
+++ b/tests/vm/tableinstatic.nim
@@ -35,4 +35,4 @@ static:
   otherTable["hallo"] = "123"
   otherTable["welt"]  = "456"
 
-  assert otherTable == {"hallo": "123", "welt": "456"}.newTable
+  doAssert otherTable == {"hallo": "123", "welt": "456"}.newTable
diff --git a/tests/vm/tcastint.nim b/tests/vm/tcastint.nim
index acff0d2b1..c306e4a31 100644
--- a/tests/vm/tcastint.nim
+++ b/tests/vm/tcastint.nim
@@ -1,9 +1,5 @@
-discard """
-  output: "OK"
-"""
-
 import macros
-
+from stdtest/testutils import disableVM
 type
   Dollar = distinct int
   XCoord = distinct int32
@@ -15,6 +11,12 @@ proc `==`(x, y: XCoord): bool {.borrow.}
 
 proc dummy[T](x: T): T = x
 
+template roundTrip(a, T) =
+  let a2 = a # sideeffect safe
+  let b = cast[T](a2)
+  let c = cast[type(a2)](b)
+  doAssert c == a2
+
 proc test() =
   let U8 = 0b1011_0010'u8
   let I8 = 0b1011_0010'i8
@@ -102,17 +104,21 @@ proc test() =
     doAssert(cast[int](digit) == raw)
     doAssert(cast[Digit](raw) == digit)
 
-  when defined nimvm:
-    doAssert(not compiles(cast[float](I64A)))
-    doAssert(not compiles(cast[float32](I64A)))
-
-    doAssert(not compiles(cast[char](I64A)))
-    doAssert(not compiles(cast[uint16](I64A)))
-    doAssert(not compiles(cast[uint32](I64A)))
+  block:
+    roundTrip(I64A, float)
+    roundTrip(I8, uint16)
+    roundTrip(I8, uint32)
+    roundTrip(I8, uint64)
+    doAssert cast[uint16](I8) == 65458'u16
+    doAssert cast[uint32](I8) == 4294967218'u32
+    doAssert cast[uint64](I8) == 18446744073709551538'u64
+    doAssert cast[uint32](I64A) == 2571663889'u32
+    doAssert cast[uint16](I64A) == 31249
+    doAssert cast[char](I64A).ord == 17
+    doAssert compiles(cast[float32](I64A))
 
-    doAssert(not compiles(cast[uint16](I8)))
-    doAssert(not compiles(cast[uint32](I8)))
-    doAssert(not compiles(cast[uint64](I8)))
+  disableVM: # xxx Error: VM does not support 'cast' from tyInt64 to tyFloat32
+    doAssert cast[uint32](cast[float32](I64A)) == 2571663889'u32
 
 const prerecordedResults = [
   # cast to char
@@ -292,16 +298,12 @@ proc test_float32_castB() =
   # any surprising content.
   doAssert cast[uint64](c) == 3270918144'u64
 
-test()
-test_float_cast()
-test_float32_cast()
-free_integer_casting()
-test_float32_castB()
-static:
+template main() =
   test()
   test_float_cast()
   test_float32_cast()
   free_integer_casting()
   test_float32_castB()
 
-echo "OK"
+static: main()
+main()
diff --git a/tests/vm/tclosureiterator.nim b/tests/vm/tclosureiterator.nim
new file mode 100644
index 000000000..c909392d5
--- /dev/null
+++ b/tests/vm/tclosureiterator.nim
@@ -0,0 +1,9 @@
+discard """
+  errormsg: "Closure iterators are not supported by VM!"
+"""
+
+iterator iter*(): int {.closure.} =
+  yield 3
+
+static:
+  var x = iter
diff --git a/tests/cnstseq/tcnstseq.nim b/tests/vm/tcnstseq.nim
index 5679a6e37..5679a6e37 100644
--- a/tests/cnstseq/tcnstseq.nim
+++ b/tests/vm/tcnstseq.nim
diff --git a/tests/vm/tcompilesetting.nim b/tests/vm/tcompilesetting.nim
new file mode 100644
index 000000000..d6c08e70f
--- /dev/null
+++ b/tests/vm/tcompilesetting.nim
@@ -0,0 +1,18 @@
+discard """
+cmd: "nim c --nimcache:build/myNimCache --nimblePath:myNimblePath --gc:arc $file"
+joinable: false
+"""
+
+import std/[strutils,compilesettings]
+from std/os import fileExists, `/`
+
+template main =
+  doAssert querySetting(nimcacheDir) == nimcacheDir.querySetting
+  doAssert "myNimCache" in nimcacheDir.querySetting
+  doAssert "myNimblePath" in nimblePaths.querySettingSeq[0]
+  doAssert querySetting(backend) == "c"
+  doAssert fileExists(libPath.querySetting / "system.nim")
+  doAssert querySetting(mm) == "arc"
+
+static: main()
+main()
diff --git a/tests/vm/tcompiletimetable.nim b/tests/vm/tcompiletimetable.nim
index ece2ddfe9..1db490f1a 100644
--- a/tests/vm/tcompiletimetable.nim
+++ b/tests/vm/tcompiletimetable.nim
@@ -1,12 +1,16 @@
 discard """
-  nimout: '''2
+  nimout: '''
+2
 3
 4:2
 Got Hi
 Got Hey
+'''
+  output:'''
 a
 b
-c'''
+c
+'''
 """
 
 # bug #404
diff --git a/tests/vm/tconst.nim b/tests/vm/tconst.nim
new file mode 100644
index 000000000..5cfe7533e
--- /dev/null
+++ b/tests/vm/tconst.nim
@@ -0,0 +1,58 @@
+discard """
+  targets: "c cpp js"
+"""
+
+import std/strutils
+
+template forceConst(a: untyped): untyped =
+  ## Force evaluation at CT, but `static(a)` is simpler
+  const ret = a
+  ret
+
+proc isNimVm(): bool =
+  when nimvm: result = true
+  else: result = false
+
+block:
+  doAssert forceConst(isNimVm())
+  doAssert not isNimVm()
+  doAssert forceConst(isNimVm()) == static(isNimVm())
+  doAssert forceConst(isNimVm()) == isNimVm().static
+
+template main() =
+  # xxx merge more const related tests here
+  const ct = CompileTime
+    # refs https://github.com/timotheecour/Nim/issues/718, apparently `CompileTime`
+    # isn't cached, which seems surprising.
+  block:
+    const
+      a = """
+    Version $1|
+    Compiled at: $2, $3
+    """ % [NimVersion & spaces(44-len(NimVersion)), CompileDate, ct]
+    let b = $a
+    doAssert ct in b, $(b, ct)
+    doAssert NimVersion in b
+
+  block: # Test for fix on broken const unpacking
+    template mytemp() =
+      const
+        (x, increment) = (4, true)
+        a = 100
+      discard (x, increment, a)
+    mytemp()
+
+  block: # bug #12334
+    block:
+      const b: cstring = "foo"
+      var c = b
+      doAssert c == "foo"
+    block:
+      const a = "foo"
+      const b: cstring = a
+      var c = b
+      doAssert c == "foo"
+
+
+static: main()
+main()
diff --git a/tests/vm/tconstarrayresem.nim b/tests/vm/tconstarrayresem.nim
new file mode 100644
index 000000000..6701cfe4d
--- /dev/null
+++ b/tests/vm/tconstarrayresem.nim
@@ -0,0 +1,29 @@
+# issue #23010
+
+type
+  Result[T, E] = object
+    case oResult: bool
+    of false:
+      discard
+    of true:
+      vResult: T
+
+  Opt[T] = Result[T, void]
+
+template ok[T, E](R: type Result[T, E], x: untyped): R =
+  R(oResult: true, vResult: x)
+
+template c[T](v: T): Opt[T] = Opt[T].ok(v)
+
+type
+  FixedBytes[N: static[int]] = distinct array[N, byte]
+
+  H = object
+    d: FixedBytes[2]
+
+const b = default(H)
+template g(): untyped =
+  const t = default(H)
+  b
+
+discard c(g())
diff --git a/tests/vm/tconsteval.nim b/tests/vm/tconsteval.nim
deleted file mode 100644
index 2e0fcb888..000000000
--- a/tests/vm/tconsteval.nim
+++ /dev/null
@@ -1,31 +0,0 @@
-discard """
-action: compile
-"""
-
-import strutils
-
-const
-  HelpText = """
-+-----------------------------------------------------------------+
-|         Maintenance program for Nim                             |
-|             Version $1|
-|             (c) 2012 Andreas Rumpf                              |
-+-----------------------------------------------------------------+
-Compiled at: $2, $3
-
-Usage:
-  koch [options] command [options for command]
-Options:
-  --force, -f, -B, -b      forces rebuild
-  --help, -h               shows this help and quits
-Possible Commands:
-  boot [options]           bootstraps with given command line options
-  clean                    cleans Nim project; removes generated files
-  web                      generates the website
-  csource [options]        builds the C sources for installation
-  zip                      builds the installation ZIP package
-  inno                     builds the Inno Setup installer
-""" % [NimVersion & spaces(44-len(NimVersion)),
-       CompileDate, CompileTime]
-
-echo HelpText
diff --git a/tests/vm/tconstobj.nim b/tests/vm/tconstobj.nim
index ac7148b59..7dc20a0ba 100644
--- a/tests/vm/tconstobj.nim
+++ b/tests/vm/tconstobj.nim
@@ -3,6 +3,7 @@ discard """
 (name: "hello")
 (-1, 0)
 (FirstName: "James", LastName: "Franco")
+[1, 2, 3]
 '''
 """
 
@@ -70,3 +71,25 @@ static: # issue #11861
   var ifb2: InheritedFromBase
   initBase(ifb2)
   doAssert(ifb2.txt == "Initialized string from base")
+
+
+static: # issue #15662
+  proc a(T: typedesc) = echo T.type
+  a((int, int))
+
+# bug #16069
+type
+  E = enum
+    val1, val2
+  Obj = object
+    case k: E
+    of val1:
+      x: array[3, int]
+    of val2:
+      y: uint32
+
+const
+  foo = [1, 2, 3]
+  arr = Obj(k: val1, x: foo)
+
+echo arr.x
diff --git a/tests/vm/tconstresem.nim b/tests/vm/tconstresem.nim
new file mode 100644
index 000000000..4526cb891
--- /dev/null
+++ b/tests/vm/tconstresem.nim
@@ -0,0 +1,10 @@
+block: # issue #19849
+  type
+    Vec2[T] = object
+      x, y: T
+    Vec2i = Vec2[int]
+  template getX(p: Vec2i): int = p.x
+  let x = getX:
+    const t = Vec2i(x: 1, y: 2)
+    t
+  doAssert x == 1
diff --git a/tests/vm/tconstscope1.nim b/tests/vm/tconstscope1.nim
new file mode 100644
index 000000000..41c45a28f
--- /dev/null
+++ b/tests/vm/tconstscope1.nim
@@ -0,0 +1,5 @@
+# issue #5395
+
+const a = (var b = 3; b)
+echo b #[tt.Error
+     ^ undeclared identifier: 'b']#
diff --git a/tests/vm/tconstscope2.nim b/tests/vm/tconstscope2.nim
new file mode 100644
index 000000000..d858e96c2
--- /dev/null
+++ b/tests/vm/tconstscope2.nim
@@ -0,0 +1,5 @@
+const
+  a = (var x = 3; x)
+  # should we allow this?
+  b = x #[tt.Error
+      ^ undeclared identifier: 'x']#
diff --git a/tests/vm/tconsttable.nim b/tests/vm/tconsttable.nim
index 64a74a59d..152a33cba 100644
--- a/tests/vm/tconsttable.nim
+++ b/tests/vm/tconsttable.nim
@@ -17,3 +17,18 @@ x = "ah"
 echo foo[x]
 x = "possible."
 echo foo[x]
+
+block: # bug #19840
+  const testBytes = [byte 0xD8, 0x08, 0xDF, 0x45, 0x00, 0x3D, 0x00, 0x52, 0x00, 0x61]
+  var tempStr = "__________________"
+
+  tempStr.prepareMutation
+  copyMem(addr tempStr[0], addr testBytes[0], testBytes.len)
+
+block: # bug #22389
+  func foo(): ptr UncheckedArray[byte] =
+    const bar = [77.byte]
+    cast[ptr UncheckedArray[byte]](addr bar[0])
+
+  doAssert foo()[0] == 77
+
diff --git a/tests/vm/tconvaddr.nim b/tests/vm/tconvaddr.nim
new file mode 100644
index 000000000..9762a9e59
--- /dev/null
+++ b/tests/vm/tconvaddr.nim
@@ -0,0 +1,49 @@
+block: # issue #24097
+  type Foo = distinct int
+  proc foo(x: var Foo) =
+    int(x) += 1
+  proc bar(x: var int) =
+    x += 1
+  static:
+    var x = Foo(1)
+    int(x) = int(x) + 1
+    doAssert x.int == 2
+    int(x) += 1
+    doAssert x.int == 3
+    foo(x)
+    doAssert x.int == 4
+    bar(int(x)) # need vmgen flags propagated for this
+    doAssert x.int == 5
+  type Bar = object
+    x: Foo
+  static:
+    var obj = Bar(x: Foo(1))
+    int(obj.x) = int(obj.x) + 1
+    doAssert obj.x.int == 2
+    int(obj.x) += 1
+    doAssert obj.x.int == 3
+    foo(obj.x)
+    doAssert obj.x.int == 4
+    bar(int(obj.x)) # need vmgen flags propagated for this
+    doAssert obj.x.int == 5
+  static:
+    var arr = @[Foo(1)]
+    int(arr[0]) = int(arr[0]) + 1
+    doAssert arr[0].int == 2
+    int(arr[0]) += 1
+    doAssert arr[0].int == 3
+    foo(arr[0])
+    doAssert arr[0].int == 4
+    bar(int(arr[0])) # need vmgen flags propagated for this
+    doAssert arr[0].int == 5
+  proc testResult(): Foo =
+    result = Foo(1)
+    int(result) = int(result) + 1
+    doAssert result.int == 2
+    int(result) += 1
+    doAssert result.int == 3
+    foo(result)
+    doAssert result.int == 4
+    bar(int(result)) # need vmgen flags propagated for this
+    doAssert result.int == 5
+  doAssert testResult().int == 5
diff --git a/tests/vm/textensionmap.nim b/tests/vm/textensionmap.nim
index 5d4b25d01..7ada1880d 100644
--- a/tests/vm/textensionmap.nim
+++ b/tests/vm/textensionmap.nim
@@ -10,4 +10,4 @@ const EXTENSIONMAP = {
   "c": @["*.c", "*.h"],
 }.toTable()
 
-const EXTENSIONS = toSet(concat(toSeq(EXTENSIONMAP.values())))
+const EXTENSIONS = toHashSet(concat(toSeq(EXTENSIONMAP.values())))
diff --git a/tests/vm/tfibconst.nim b/tests/vm/tfibconst.nim
new file mode 100644
index 000000000..cca6dd84f
--- /dev/null
+++ b/tests/vm/tfibconst.nim
@@ -0,0 +1,43 @@
+discard """
+  nimout: '''
+Fibonacci sequence: 0, 1, 1, 2, 3
+Sequence continues: 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610
+'''
+"""
+
+
+import strformat
+
+var fib_n {.compileTime.}: int
+var fib_prev {.compileTime.}: int
+var fib_prev_prev {.compileTime.}: int
+
+proc next_fib(): int {.compileTime.} =
+  let fib = if fib_n < 2:
+    fib_n
+  else:
+    fib_prev_prev + fib_prev
+  inc(fib_n)
+  fib_prev_prev = fib_prev
+  fib_prev = fib
+  fib
+
+const f0 = next_fib()
+const f1 = next_fib()
+const f2 = next_fib()
+const f3 = next_fib()
+const f4 = next_fib()
+
+static:
+  echo fmt"Fibonacci sequence: {f0}, {f1}, {f2}, {f3}, {f4}"
+
+const fib_continues = block:
+  var result = fmt"Sequence continues: "
+  for i in 0..10:
+    if i > 0:
+      add(result, ", ")
+    add(result, $next_fib())
+  result
+
+static:
+  echo fib_continues
\ No newline at end of file
diff --git a/tests/vm/tfile_rw.nim b/tests/vm/tfile_rw.nim
index 8d7a2ca95..439886e49 100644
--- a/tests/vm/tfile_rw.nim
+++ b/tests/vm/tfile_rw.nim
@@ -1,7 +1,3 @@
-discard """
-  output: '''ok'''
-"""
-
 # test file read write in vm
 
 import os, strutils
@@ -24,4 +20,3 @@ static:
 
 
 removeFile(filename)
-echo "ok"
\ No newline at end of file
diff --git a/tests/vm/tgenericcompiletimeproc.nim b/tests/vm/tgenericcompiletimeproc.nim
new file mode 100644
index 000000000..08099ebbe
--- /dev/null
+++ b/tests/vm/tgenericcompiletimeproc.nim
@@ -0,0 +1,36 @@
+block: # issue #10753
+  proc foo(x: int): int {.compileTime.} = x
+  const a = foo(123)
+  doAssert foo(123) == a
+
+  proc bar[T](x: T): T {.compileTime.} = x
+  const b = bar(123)
+  doAssert bar(123) == b
+  const c = bar("abc")
+  doAssert bar("abc") == c
+
+block: # issue #22021
+  proc foo(x: static int): int {.compileTime.} = x + 1
+  doAssert foo(123) == 124
+
+block: # issue #19365
+  proc f[T](x: static T): T {.compileTime.} = x + x
+  doAssert f(123) == 246
+  doAssert f(1.0) == 2.0
+
+block:
+  # don't fold compile time procs in typeof
+  proc fail[T](x: T): T {.compileTime.} =
+    doAssert false
+    x
+  doAssert typeof(fail(123)) is typeof(123)
+  proc p(x: int): int = x
+
+  type Foo = typeof(p(fail(123)))
+
+block: # issue #24150, related regression
+  proc w(T: type): T {.compileTime.} = default(ptr T)[]
+  template y(v: auto): auto = typeof(v) is int
+  discard compiles(y(w int))
+  proc s(): int {.compileTime.} = discard
+  discard s()
diff --git a/tests/vm/tgloballetfrommacro.nim b/tests/vm/tgloballetfrommacro.nim
index 14dbff1e8..4be09b56e 100644
--- a/tests/vm/tgloballetfrommacro.nim
+++ b/tests/vm/tgloballetfrommacro.nim
@@ -5,7 +5,7 @@ line: 11
 
 import sets
 
-let BUILTIN_NAMES = toSet(["int8", "int16", "int32", "int64"])
+let BUILTIN_NAMES = toHashSet(["int8", "int16", "int32", "int64"])
 
 macro test*(): bool =
   echo "int64" notin BUILTIN_NAMES
diff --git a/tests/vm/tissues.nim b/tests/vm/tissues.nim
index 063559d2e..f0ae6c296 100644
--- a/tests/vm/tissues.nim
+++ b/tests/vm/tissues.nim
@@ -1,6 +1,6 @@
 import macros
 
-block t9043: # issue #9043
+block t9043: # bug #9043
   proc foo[N: static[int]](dims: array[N, int]): string =
     const N1 = N
     const N2 = dims.len
@@ -25,4 +25,52 @@ block t4952:
   static:
     let tree = newTree(nnkExprColonExpr)
     let t = (n: tree)
-    assert: t.n.kind == tree.kind
+    doAssert: t.n.kind == tree.kind
+
+
+# bug #19909
+type
+  SinglyLinkedList[T] = ref object
+  SinglyLinkedListObj[T] = ref object
+
+
+proc addMoved[T](a, b: var SinglyLinkedList[T]) =
+  if a.addr != b.addr: discard
+
+proc addMoved[T](a, b: var SinglyLinkedListObj[T]) =
+  if a.addr != b.addr: discard
+
+proc main =
+  var a: SinglyLinkedList[int]; new a
+  var b: SinglyLinkedList[int]; new b
+  a.addMoved b
+
+  var a0: SinglyLinkedListObj[int]
+  var b0: SinglyLinkedListObj[int]
+  a0.addMoved b0
+
+static: main()
+
+
+# bug #18641
+
+type A = object
+  ha1: int
+static:
+  var a = A()
+  var a2 = a.addr
+  a2.ha1 = 11
+  doAssert a2.ha1 == 11
+  a.ha1 = 12
+  doAssert a.ha1 == 12
+  doAssert a2.ha1 == 12 # ok
+static:
+  proc fn() =
+    var a = A()
+    var a2 = a.addr
+    a2.ha1 = 11
+    doAssert a2.ha1 == 11
+    a.ha1 = 12
+    doAssert a.ha1 == 12
+    doAssert a2.ha1 == 12 # fails
+  fn()
diff --git a/tests/vm/tmisc_vm.nim b/tests/vm/tmisc_vm.nim
index 6eeecb869..1ad830b5f 100644
--- a/tests/vm/tmisc_vm.nim
+++ b/tests/vm/tmisc_vm.nim
@@ -1,8 +1,12 @@
 discard """
-  output: '''[127, 127, 0, 255]
-[127, 127, 0, 255]
-
+  targets: "c js"
+  output: '''
+[127, 127, 0, 255][127, 127, 0, 255]
 (data: 1)
+(2, 1)
+(2, 1)
+(2, 1)
+(f0: 5)
 '''
 
   nimout: '''caught Exception
@@ -18,8 +22,22 @@ foo4
 (a: 0, b: 0)
 (a: 0, b: 0)
 (a: 0, b: 0)
+z1 m: (lo: 12)
+z2 a: (lo: 3)
+x1 a: (lo: 3)
+x2 a: (lo: 6)
+x3 a: (lo: 0)
+z3 a: (lo: 3)
+x1 a: (lo: 3)
+x2 a: (lo: 6)
+x3 a: (lo: 0)
+(2, 1)
+(2, 1)
+(2, 1)
+(f0: 5)
 '''
 """
+import std/sets
 
 #bug #1009
 type
@@ -96,8 +114,6 @@ static: simpleTryFinally()
 
 # bug #10981
 
-import sets
-
 proc main =
   for i in 0..<15:
     var someSets = @[initHashSet[int]()]
@@ -251,3 +267,193 @@ static:
   echo x2[]
   let x3 = new(ref MyObject) # cannot generate VM code for ref MyObject
   echo x3[]
+
+# bug #19464
+type
+  Wrapper = object
+    inner: int
+
+proc assign(r: var Wrapper, a: Wrapper) =
+  r = a
+
+proc myEcho(a: Wrapper) =
+  var tmp = a
+  assign(tmp, Wrapper(inner: 0)) # this shouldn't modify `a`
+  doAssert a.inner == 1
+
+static:
+  var result: Wrapper
+  assign(result, Wrapper(inner: 1))
+  myEcho(result)
+
+when true:
+  # bug #15974
+  type Foo = object
+    f0: int
+
+  proc fn(a: var Foo) =
+    var s: Foo
+    a = Foo(f0: 2)
+    s = a
+    doAssert s.f0 == 2
+    a = Foo(f0: 3)
+    doAssert s.f0 == 2
+
+  proc test2()=
+    var a = Foo(f0: 1)
+    fn(a)
+
+  static: test2()
+  test2()
+
+# bug #12551
+type
+  StUint = object
+    lo: uint64
+
+func `+=`(x: var Stuint, y: Stuint) =
+  x.lo += y.lo
+
+func `-`(x, y: Stuint): Stuint =
+  result.lo = x.lo - y.lo
+
+func `+`(x, y: Stuint): Stuint =
+  result.lo = x.lo + y.lo
+
+func `-=`(x: var Stuint, y: Stuint) =
+  x = x - y
+
+func `<`(x, y: Stuint): bool=
+  x.lo < y.lo
+
+func `==`(x, y: Stuint): bool =
+  x.lo == y.lo
+
+func `<=`(x, y: Stuint): bool =
+  x.lo <= y.lo
+
+proc div3n2n(r: var Stuint, b: Stuint) =
+  var d: Stuint
+  r = d
+  r += b
+
+func div2n1n(r: var Stuint, b: Stuint) =
+  div3n2n(r, b)
+
+func divmodBZ(x, y: Stuint, r: var Stuint)=
+  div2n1n(r, y)
+  r.lo = 3
+
+func `mod`(x, y: Stuint): Stuint =
+  divmodBZ(x, y, result)
+
+func doublemod_internal(a, m: Stuint): Stuint =
+  result = a
+  if a >= m - a:
+    result -= m
+  result += a
+
+func mulmod_internal(a, b, m: Stuint): Stuint =
+  var (a, b) = (a, b)
+  swap(a, b)
+  debugEcho "x1 a: ", a
+  a = doublemod_internal(a, m)
+  debugEcho "x2 a: ", a
+  a = doublemod_internal(a, m)
+  debugEcho "x3 a: ", a
+
+func powmod_internal(a, m: Stuint): Stuint =
+  var a = a
+  debugEcho "z1 m: ", m
+  debugEcho "z2 a: ", a
+  result = mulmod_internal(result, a, m)
+  debugEcho "z3 a: ", a
+  a = mulmod_internal(a, a, m)
+
+func powmod*(a, m: Stuint) =
+  discard powmod_internal(a mod m, m)
+
+static:
+  var x = Stuint(lo: high(uint64))
+  var y = Stuint(lo: 12)
+
+  powmod(x, y)
+
+# bug #16780
+when true:
+  template swap*[T](a, b: var T) =
+    var a2 = addr(a)
+    var b2 = addr(b)
+    var aOld = a2[]
+    a2[] = b2[]
+    b2[] = aOld
+
+  proc rather =
+    block:
+      var a = 1
+      var b = 2
+      swap(a, b)
+      echo (a,b)
+
+    block:
+      type Foo = ref object
+        x: int
+      var a = Foo(x:1)
+      var b = Foo(x:2)
+      swap(a, b)
+      echo (a.x, b.x)
+
+    block:
+      type Foo = object
+        x: int
+      var a = Foo(x:1)
+      var b = Foo(x:2)
+      swap(a, b)
+      echo (a.x,b.x)
+
+  static: rather()
+  rather()
+
+# bug #16020
+when true:
+  block:
+    type Foo = object
+      f0: int
+    proc main=
+      var f = Foo(f0: 3)
+      var f2 = f.addr
+      f2[].f0 += 1
+      f2.f0 += 1
+      echo f
+    static: main()
+    main()
+
+import tables, strutils
+
+# bug #14553
+const PpcPatterns = @[("aaaa", "bbbb"), ("aaaaa", "bbbbb"), ("aaaaaa", "bbbbbb"), ("aaaaaaa", "bbbbbbb"), ("aaaaaaaa", "bbbbb")]
+
+static:
+    var
+        needSecondIdentifier = initTable[uint32, seq[(string, string)]]()
+
+    for (name, pattern) in PpcPatterns:
+        let
+            firstPart = 0'u32
+            lastPart = "test"
+
+        needSecondIdentifier.mgetOrPut(firstPart, @[]).add((name, pattern))
+
+    doAssert needSecondIdentifier[0] == @[("aaaa", "bbbb"), ("aaaaa", "bbbbb"), ("aaaaaa", "bbbbbb"), ("aaaaaaa", "bbbbbbb"), ("aaaaaaaa", "bbbbb")]
+
+# bug #17864
+macro transform*(fn: typed) =
+  quote do:
+    `fn`
+
+var map: Table[string, HashSet[string]]
+proc publish*(): void {.transform.} =
+  map["k"] = init_hash_set[string]()
+  map["k"].incl "d"
+
+publish()
diff --git a/tests/vm/tnewseqofcap.nim b/tests/vm/tnewseqofcap.nim
new file mode 100644
index 000000000..a7dc07aa6
--- /dev/null
+++ b/tests/vm/tnewseqofcap.nim
@@ -0,0 +1,14 @@
+const
+  foo = @["aaa", "bbb", "ccc"]
+
+proc myTuple: tuple[n: int, bar: seq[string]] =
+  result.n = 42
+  result.bar = newSeqOfCap[string](foo.len)
+  for f in foo:
+    result.bar.add(f)
+
+# It works if you change the below `const` to `let`
+const
+  (n, bar) = myTuple()
+
+doAssert bar == @["aaa", "bbb", "ccc"]
\ No newline at end of file
diff --git a/tests/vm/tnilclosurecall.nim b/tests/vm/tnilclosurecall.nim
new file mode 100644
index 000000000..449865b9c
--- /dev/null
+++ b/tests/vm/tnilclosurecall.nim
@@ -0,0 +1,8 @@
+discard """
+  errormsg: "attempt to call nil closure"
+  line: 8
+"""
+
+static:
+  let x: proc () = nil
+  x()
diff --git a/tests/vm/tnilclosurecallstacktrace.nim b/tests/vm/tnilclosurecallstacktrace.nim
new file mode 100644
index 000000000..879060e8e
--- /dev/null
+++ b/tests/vm/tnilclosurecallstacktrace.nim
@@ -0,0 +1,23 @@
+discard """
+  action: reject
+  nimout: '''
+stack trace: (most recent call last)
+tnilclosurecallstacktrace.nim(23, 6) tnilclosurecallstacktrace
+tnilclosurecallstacktrace.nim(20, 6) baz
+tnilclosurecallstacktrace.nim(17, 6) bar
+tnilclosurecallstacktrace.nim(14, 4) foo
+tnilclosurecallstacktrace.nim(14, 4) Error: attempt to call nil closure
+'''
+"""
+
+proc foo(x: proc ()) =
+  x()
+
+proc bar(x: proc ()) =
+  foo(x)
+
+proc baz(x: proc ()) =
+  bar(x)
+
+static:
+  baz(nil)
diff --git a/tests/vm/tnocompiletimefunc.nim b/tests/vm/tnocompiletimefunc.nim
new file mode 100644
index 000000000..a95648c0f
--- /dev/null
+++ b/tests/vm/tnocompiletimefunc.nim
@@ -0,0 +1,14 @@
+discard """
+  errormsg: "request to generate code for .compileTime proc: foo"
+"""
+
+# ensure compileTime funcs can't be called from runtime
+
+func foo(a: int): int {.compileTime.} =
+  a * a
+
+proc doAThing(): int =
+  for i in 0..2:
+    result += foo(i)
+
+echo doAThing()
diff --git a/tests/vm/tnocompiletimefunclambda.nim b/tests/vm/tnocompiletimefunclambda.nim
new file mode 100644
index 000000000..d134eea40
--- /dev/null
+++ b/tests/vm/tnocompiletimefunclambda.nim
@@ -0,0 +1,6 @@
+discard """
+  errormsg: "request to generate code for .compileTime proc: :anonymous"
+"""
+
+let a = func(a: varargs[int]) {.compileTime, closure.} =
+  discard a[0]
\ No newline at end of file
diff --git a/tests/vm/tnoreturn.nim b/tests/vm/tnoreturn.nim
new file mode 100644
index 000000000..d4f8601a9
--- /dev/null
+++ b/tests/vm/tnoreturn.nim
@@ -0,0 +1,32 @@
+block: # issue #22216
+  type
+    Result[T, E] = object
+      case oVal: bool
+      of false:
+        eVal: E
+      of true:
+        vVal: T
+
+  func raiseResultDefect(m: string) {.noreturn, noinline.} =
+    raise (ref Defect)(msg: m)
+
+  template withAssertOk(self: Result, body: untyped): untyped =
+    case self.oVal
+    of false:
+      raiseResultDefect("Trying to access value with err Result")    
+    else:
+      body
+
+  func value[T, E](self: Result[T, E]): T {.inline.} =    
+    withAssertOk(self):  
+      self.vVal
+      
+  const
+    x = Result[int, string](oVal: true, vVal: 123)
+    z = x.value()
+    
+  let
+    xx = Result[int, string](oVal: true, vVal: 123)
+    zz = x.value()
+  
+  doAssert z == zz
diff --git a/tests/vm/topenarrays.nim b/tests/vm/topenarrays.nim
new file mode 100644
index 000000000..375d2523d
--- /dev/null
+++ b/tests/vm/topenarrays.nim
@@ -0,0 +1,89 @@
+proc mutate(a: var openarray[int]) =
+  var i = 0
+  for x in a.mitems:
+    x = i
+    inc i
+
+proc mutate(a: var openarray[char]) =
+  var i = 1
+  for ch in a.mitems:
+    ch = 'a'
+
+
+static:
+  var a = [10, 20, 30]
+  assert a.toOpenArray(1, 2).len == 2
+
+  mutate(a)
+  assert a.toOpenArray(0, 2) == [0, 1, 2]
+  assert a.toOpenArray(0, 0) == [0]
+  assert a.toOpenArray(1, 2) == [1, 2]
+  assert "Hello".toOpenArray(1, 4) == "ello"
+  var str = "Hello"
+  str.toOpenArray(2, 4).mutate()
+  assert str.toOpenArray(0, 4).len == 5
+  assert str.toOpenArray(0, 0).len == 1
+  assert str.toOpenArray(0, 0).high == 0
+  assert str == "Heaaa"
+  assert str.toOpenArray(0, 4) == "Heaaa"
+
+  var arr: array[3..4, int] = [1, 2]
+  assert arr.toOpenArray(3, 4) == [1, 2]
+  assert arr.toOpenArray(3, 4).len == 2
+  assert arr.toOpenArray(3, 3).high == 0
+
+  assert arr.toOpenArray(3, 4).toOpenArray(0, 0) == [1]
+
+
+proc doThing(s: static openArray[int]) = discard
+
+doThing([10, 20, 30].toOpenArray(0, 0))
+
+# bug #19969
+proc f(): array[1, byte] =
+  var a: array[1, byte]
+  result[0..0] = a.toOpenArray(0, 0)
+
+doAssert static(f()) == [byte(0)]
+
+
+# bug #15952
+proc main1[T](a: openArray[T]) = discard
+proc main2[T](a: var openArray[T]) = discard
+
+proc main =
+  var a = [1,2,3,4,5]
+  main1(a.toOpenArray(1,3))
+  main2(a.toOpenArray(1,3))
+static: main()
+main()
+
+# bug #16306
+{.experimental: "views".}
+proc test(x: openArray[int]): tuple[id: int] =
+  let y: openArray[int] = toOpenArray(x, 0, 2)
+  result = (y[0],)
+template fn=
+  doAssert test([0,1,2,3,4,5]).id == 0
+fn() # ok
+static: fn()
+
+
+block: # bug #22095
+  type
+    StUint = object
+      limbs: array[4, uint64]
+
+  func shlAddMod(a: var openArray[uint64]) =  
+    a[0] = 10
+
+  func divRem(r: var openArray[uint64]) =
+    shlAddMod(r.toOpenArray(0, 3))
+
+  func fn(): StUint =
+    divRem(result.limbs)
+
+  const
+    z = fn()
+
+  doAssert z.limbs[0] == 10
diff --git a/tests/vm/toverflowopcaddimmint.nim b/tests/vm/toverflowopcaddimmint.nim
index c36b9ed9b..4ff614e5b 100644
--- a/tests/vm/toverflowopcaddimmint.nim
+++ b/tests/vm/toverflowopcaddimmint.nim
@@ -7,5 +7,5 @@ static:
     var
       x = int64.high
     discard x + 1
-    assert false
+    doAssert false
   p()
diff --git a/tests/vm/toverflowopcaddint.nim b/tests/vm/toverflowopcaddint.nim
index 6d96afc78..d494245b1 100644
--- a/tests/vm/toverflowopcaddint.nim
+++ b/tests/vm/toverflowopcaddint.nim
@@ -8,5 +8,5 @@ static:
       x = int64.high
       y = 1
     discard x + y
-    assert false
+    doAssert false
   p()
diff --git a/tests/vm/toverflowopcmulint.nim b/tests/vm/toverflowopcmulint.nim
index 5607c59a7..936eea6c2 100644
--- a/tests/vm/toverflowopcmulint.nim
+++ b/tests/vm/toverflowopcmulint.nim
@@ -7,5 +7,5 @@ static:
     var
       x = 1'i64 shl 62
     discard x * 2
-    assert false
+    doAssert false
   p()
diff --git a/tests/vm/toverflowopcsubimmint.nim b/tests/vm/toverflowopcsubimmint.nim
index 09d6f745b..08356590c 100644
--- a/tests/vm/toverflowopcsubimmint.nim
+++ b/tests/vm/toverflowopcsubimmint.nim
@@ -6,5 +6,5 @@ static:
   proc p =
     var x = int64.low
     discard x - 1
-    assert false
+    doAssert false
   p()
diff --git a/tests/vm/toverflowopcsubint.nim b/tests/vm/toverflowopcsubint.nim
index 8d114f200..74e34c6a4 100644
--- a/tests/vm/toverflowopcsubint.nim
+++ b/tests/vm/toverflowopcsubint.nim
@@ -8,5 +8,5 @@ static:
       x = int64.low
       y = 1
     discard x - y
-    assert false
+    doAssert false
   p()
diff --git a/tests/vm/tquadplus.nim b/tests/vm/tquadplus.nim
index 552e8fef7..acf20cd96 100644
--- a/tests/vm/tquadplus.nim
+++ b/tests/vm/tquadplus.nim
@@ -1,8 +1,5 @@
 # bug #1023
 
-discard """
-  output: "1 == 1"
-"""
 
 type Quadruple = tuple[a, b, c, d: int]
 
@@ -14,4 +11,4 @@ const
   B = (a: 0, b: -2, c: 1, d: 0)
   C = A + B
 
-echo C.d, " == ", (A+B).d
+doAssert $C.d & " == " & $(A+B).d == "1 == 1"
diff --git a/tests/vm/tref.nim b/tests/vm/tref.nim
index f5cd23da5..e70305225 100644
--- a/tests/vm/tref.nim
+++ b/tests/vm/tref.nim
@@ -59,4 +59,13 @@ static:
 static: # bug #8402
   type R = ref object
   var empty: R
-  let otherEmpty = empty
\ No newline at end of file
+  let otherEmpty = empty
+
+block:
+  # fix https://github.com/timotheecour/Nim/issues/88
+  template fun() =
+    var s = @[10,11,12]
+    var a = s[0].addr
+    a[] += 100 # was giving SIGSEGV
+    doAssert a[] == 110
+  static: fun()
diff --git a/tests/vm/treset.nim b/tests/vm/treset.nim
index ff8bc5b83..32fbc7f04 100644
--- a/tests/vm/treset.nim
+++ b/tests/vm/treset.nim
@@ -1,6 +1,3 @@
-discard """
-  output: '''0'''
-"""
 static:
   type Obj = object
     field: int
@@ -48,6 +45,6 @@ proc main =
 
   var x = 4
   x = default(int)
-  echo x
+  doAssert x == 0
 
 main()
diff --git a/tests/vm/triangle_array.nim b/tests/vm/triangle_array.nim
index 054c66f22..0704239c6 100644
--- a/tests/vm/triangle_array.nim
+++ b/tests/vm/triangle_array.nim
@@ -1,7 +1,3 @@
-discard """
-  output: "56"
-"""
-
 # bug #1781
 
 proc initCombinations: array[11, array[11, int]] =
@@ -14,4 +10,4 @@ proc initCombinations: array[11, array[11, int]] =
   result[6][6 .. 10] =             [52,53,54,55,56]
 
 const combinations = initCombinations()
-echo combinations[6][10]
+doAssert combinations[6][10] == 56
diff --git a/tests/vm/tscriptcompiletime.nims b/tests/vm/tscriptcompiletime.nims
new file mode 100644
index 000000000..daec54bf7
--- /dev/null
+++ b/tests/vm/tscriptcompiletime.nims
@@ -0,0 +1,9 @@
+discard """
+  cmd: "nim e $file"
+"""
+
+import mscriptcompiletime
+
+macro foo =
+  doAssert bar == 2
+foo()
diff --git a/tests/vm/tsignaturehash.nim b/tests/vm/tsignaturehash.nim
index 42e0a1571..972ec6fb0 100644
--- a/tests/vm/tsignaturehash.nim
+++ b/tests/vm/tsignaturehash.nim
@@ -1,7 +1,7 @@
 # test sym digest is computable at compile time
 
 import macros, algorithm
-import md5
+import ../../dist/checksums/src/checksums/md5
 
 macro testmacro(s: typed{nkSym}): string =
   let s = getMD5(signaturehash(s) & " - " & symBodyHash(s))
diff --git a/tests/vm/tslow_tables.nim b/tests/vm/tslow_tables.nim
index f726c6323..e40187f18 100644
--- a/tests/vm/tslow_tables.nim
+++ b/tests/vm/tslow_tables.nim
@@ -1,5 +1,5 @@
 discard """
-  timeout: "4"
+  timeout: "7"
   action: "compile"
   nimout: '''create
 search
@@ -26,5 +26,5 @@ proc hop(): bool =
 
   echo "done"
 
-const r = hop()
+const r {.used.} = hop()
 
diff --git a/tests/vm/tstring_openarray.nim b/tests/vm/tstring_openarray.nim
index 1b8a1304c..9318344f8 100644
--- a/tests/vm/tstring_openarray.nim
+++ b/tests/vm/tstring_openarray.nim
@@ -12,16 +12,16 @@ proc set_all[T](s: var openArray[T]; val: T) =
   for i in 0..<s.len:
     s[i] = val
 
-proc test() =
-    var a0 = "hello_world"
-    var a1 = [1,2,3,4,5,6,7,8,9]
-    var a2 = @[1,2,3,4,5,6,7,8,9]
-    a0.set_all('i')
-    a1.set_all(4)
-    a2.set_all(4)
-    doAssert a0 == "iiiiiiiiiii"
-    doAssert a1 == [4,4,4,4,4,4,4,4,4]
-    doAssert a2 == @[4,4,4,4,4,4,4,4,4]
+proc main() =
+  var a0 = "hello_world"
+  var a1 = [1,2,3,4,5,6,7,8,9]
+  var a2 = @[1,2,3,4,5,6,7,8,9]
+  a0.set_all('i')
+  a1.set_all(4)
+  a2.set_all(4)
+  doAssert a0 == "iiiiiiiiiii"
+  doAssert a1 == [4,4,4,4,4,4,4,4,4]
+  doAssert a2 == @[4,4,4,4,4,4,4,4,4]
 
 const constval0 = "hello".map(proc(x: char): char = x)
 const constval1 = [1,2,3,4].map(proc(x: int): int = x)
@@ -29,6 +29,5 @@ const constval1 = [1,2,3,4].map(proc(x: int): int = x)
 doAssert("hello".map(proc(x: char): char = x) == constval0)
 doAssert([1,2,3,4].map(proc(x: int): int = x) == constval1)
 
-test()
-static:
-    test()
+static: main()
+main()
diff --git a/tests/vm/tstringnil.nim b/tests/vm/tstringnil.nim
index df408910e..d5dd4f4c9 100644
--- a/tests/vm/tstringnil.nim
+++ b/tests/vm/tstringnil.nim
@@ -47,4 +47,4 @@ macro suite(suiteName, suiteDesc, suiteBloc: untyped): typed =
 # Test above
 suite basics, "Description of such":
   test(t5, ""):
-    assert false
+    doAssert false
diff --git a/tests/vm/tswap.nim b/tests/vm/tswap.nim
index 4243b5a71..bdbe5528c 100644
--- a/tests/vm/tswap.nim
+++ b/tests/vm/tswap.nim
@@ -3,7 +3,9 @@ nimout: '''
 x.data = @[10]
 y = @[11]
 x.data = @[11]
-y = @[10]'''
+y = @[10]
+@[3, 2, 1]
+'''
 """
 
 # bug #2946
@@ -22,3 +24,11 @@ proc testSwap(): int {.compiletime.} =
   result = 99
 
 const something = testSwap()
+
+# bug #15463
+block:
+  static:
+    var s = @[1, 2, 3]
+    swap(s[0], s[2])
+
+    echo s
diff --git a/tests/vm/ttouintconv.nim b/tests/vm/ttouintconv.nim
index ff2187a36..8c43a3adb 100644
--- a/tests/vm/ttouintconv.nim
+++ b/tests/vm/ttouintconv.nim
@@ -75,3 +75,10 @@ macro foo2() =
 
 foo()
 foo2()
+
+block:
+  const neg5VM = block:
+    let x = -5'i8
+    uint64(x)
+  let y = -5'i8
+  doAssert uint64(y) == neg5VM
diff --git a/tests/vm/ttypedesc.nim b/tests/vm/ttypedesc.nim
new file mode 100644
index 000000000..d799e5adb
--- /dev/null
+++ b/tests/vm/ttypedesc.nim
@@ -0,0 +1,31 @@
+block: # issue #15760
+  type
+    Banana = object
+    SpecialBanana = object
+    
+  proc getName(_: type Banana): string = "Banana"
+  proc getName(_: type SpecialBanana): string = "SpecialBanana"
+
+  proc x[T](): string = 
+    const n = getName(T) # this one works
+    result = n
+    
+  proc y(T: type): string =
+    const n = getName(T) # this one failed to compile
+    result = n
+
+  doAssert x[SpecialBanana]() == "SpecialBanana"
+  doAssert y(SpecialBanana) == "SpecialBanana"
+
+import macros
+
+block: # issue #23112
+  type Container = object
+    foo: string
+
+  proc canBeImplicit(t: typedesc) {.compileTime.} =
+    let tDesc = getType(t)
+    doAssert tDesc.kind == nnkObjectTy
+
+  static:
+    canBeImplicit(Container)
diff --git a/tests/vm/tunsupportedintfloatcast.nim b/tests/vm/tunsupportedintfloatcast.nim
new file mode 100644
index 000000000..d65f10d86
--- /dev/null
+++ b/tests/vm/tunsupportedintfloatcast.nim
@@ -0,0 +1,3 @@
+static:
+  echo cast[int32](12.0) #[tt.Error
+       ^ VM does not support 'cast' from tyFloat with size 8 to tyInt32 with size 4 due to different sizes]#
diff --git a/tests/vm/tvarsection.nim b/tests/vm/tvarsection.nim
index d1c4926a0..cd34bd02e 100644
--- a/tests/vm/tvarsection.nim
+++ b/tests/vm/tvarsection.nim
@@ -1,7 +1,3 @@
-discard """
-  output: '''-1abc'''
-"""
-
 var
   a {.compileTime.} = 2
   b = -1
@@ -9,7 +5,7 @@ var
   d = "abc"
 
 static:
-  assert a == 2
-  assert c == 3
+  doAssert a == 2
+  doAssert c == 3
 
-echo b, d
+doAssert ($b & $d) == "-1abc"
diff --git a/tests/vm/tvmmisc.nim b/tests/vm/tvmmisc.nim
index 20adb5b8f..6aeac5529 100644
--- a/tests/vm/tvmmisc.nim
+++ b/tests/vm/tvmmisc.nim
@@ -1,8 +1,7 @@
-# bug #4462
 import macros
 import os
-import strutils
 
+# bug #4462
 block:
   proc foo(t: typedesc) {.compileTime.} =
     assert sameType(getType(t), getType(int))
@@ -10,26 +9,26 @@ block:
   static:
     foo(int)
 
-# #4412
+# bug #4412
 block:
   proc default[T](t: typedesc[T]): T {.inline.} = discard
 
   static:
     var x = default(type(0))
 
-# #6379
+# bug #6379
 import algorithm
 
 static:
   var numArray = [1, 2, 3, 4, -1]
   numArray.sort(cmp)
-  assert numArray == [-1, 1, 2, 3, 4]
+  doAssert numArray == [-1, 1, 2, 3, 4]
 
   var str = "cba"
   str.sort(cmp)
-  assert str == "abc"
+  doAssert str == "abc"
 
-# #6086
+# bug #6086
 import math, sequtils, sugar
 
 block:
@@ -43,7 +42,7 @@ block:
   var a = f()
   const b = f()
 
-  assert a == b
+  doAssert a == b
 
 block:
   proc f(): seq[char] =
@@ -51,7 +50,7 @@ block:
 
   var runTime = f()
   const compTime = f()
-  assert runTime == compTime
+  doAssert runTime == compTime
 
 # #6083
 block:
@@ -65,26 +64,28 @@ block:
       result[i] = tmp
 
   const fact1000 = abc()
-  assert fact1000 == @[1, 2]
+  doAssert fact1000 == @[1, 2]
 
 # Tests for VM ops
 block:
   static:
     # for joint test, the project path is different, so I disabled it:
     when false:
-      assert "vm" in getProjectPath()
+      doAssert "vm" in getProjectPath()
 
     let b = getEnv("UNSETENVVAR")
-    assert b == ""
-    assert existsEnv("UNSERENVVAR") == false
+    doAssert b == ""
+    doAssert existsEnv("UNSERENVVAR") == false
     putEnv("UNSETENVVAR", "VALUE")
-    assert getEnv("UNSETENVVAR") == "VALUE"
-    assert existsEnv("UNSETENVVAR") == true
+    doAssert getEnv("UNSETENVVAR") == "VALUE"
+    doAssert existsEnv("UNSETENVVAR") == true
 
-    assert fileExists("MISSINGFILE") == false
-    assert dirExists("MISSINGDIR") == false
+    doAssert fileExists("MISSINGFILE") == false
+    doAssert dirExists("MISSINGDIR") == false
+    doAssert fileExists(currentSourcePath())
+    doAssert dirExists(currentSourcePath().parentDir)
 
-# #7210
+# bug #7210
 block:
   static:
     proc f(size: int): int =
@@ -92,7 +93,7 @@ block:
       result = size
     doAssert f(4) == 4
 
-# #6689
+# bug #6689
 block:
   static:
     proc foo(): int = 0
@@ -107,7 +108,7 @@ block:
     new(x)
     doAssert(not x.isNil)
 
-# #7871
+# bug #7871
 static:
   type Obj = object
     field: int
@@ -117,11 +118,11 @@ static:
   o.field = 2
   doAssert s[0].field == 0
 
-# #8125
+# bug #8125
 static:
    let def_iter_var = ident("it")
 
-# #8142
+# bug #8142
 static:
   type Obj = object
     names: string
@@ -137,7 +138,7 @@ static:
   o.pushName()
   doAssert o.names == "FOOBARFOOBAR"
 
-# #8154
+# bug #8154
 import parseutils
 
 static:
@@ -150,7 +151,7 @@ static:
   static:
     doAssert foo().i == 1
 
-# #10333
+# bug #10333
 block:
   const
     encoding: auto = [
@@ -161,7 +162,7 @@ block:
     ]
   doAssert encoding.len == 4
 
-# #10886
+# bug #10886
 
 proc tor(): bool =
   result = true
@@ -178,3 +179,618 @@ const
 static:
   doAssert ctor
   doAssert ctand
+
+block: # bug #13081
+  type Kind = enum
+    k0, k1, k2, k3
+
+  type Foo = object
+    x0: float
+    case kind: Kind
+    of k0: discard
+    of k1: x1: int
+    of k2: x2: string
+    of k3: x3: string
+
+  const j1 = Foo(x0: 1.2, kind: k1, x1: 12)
+  const j2 = Foo(x0: 1.3, kind: k2, x2: "abc")
+  const j3 = Foo(x0: 1.3, kind: k3, x3: "abc2")
+  static:
+    doAssert $j1 == "(x0: 1.2, kind: k1, x1: 12)"
+    doAssert $j2 == """(x0: 1.3, kind: k2, x2: "abc")"""
+    doAssert $j3 == """(x0: 1.3, kind: k3, x3: "abc2")"""
+  doAssert $j1 == "(x0: 1.2, kind: k1, x1: 12)"
+  doAssert $j2 == """(x0: 1.3, kind: k2, x2: "abc")"""
+  doAssert $j3 == """(x0: 1.3, kind: k3, x3: "abc2")"""
+
+  doAssert j1.x1 == 12
+  static:
+    doAssert j1.x1 == 12
+
+block: # bug #15595
+  proc fn0()=echo 0
+  proc fn1()=discard
+  proc main=
+    var local = 0
+    proc fn2()=echo local
+    var a0 = fn0
+    var a1 = fn1
+    var a2 = fn2
+    var a3: proc()
+    var a4: proc()
+    doAssert a0 == fn0 # bugfix
+    doAssert a1 == fn1 # ditto
+    doAssert a2 == fn2 # ditto
+
+    doAssert fn0 != fn1
+
+    doAssert a2 != nil
+    doAssert a3 == nil # bugfix
+
+    doAssert a3 == a4 # bugfix
+  static: main()
+  main()
+
+block: # issue #20543
+  type F = proc()
+  const myArray = block:
+    var r: array[1, F]
+    r[0] = nil
+    r
+  doAssert isNil(myArray[0])
+
+# bug #15363
+import sequtils
+
+block:
+  func identity(a: bool): bool = a
+
+  var a: seq[bool] = static:
+      newSeq[bool](0).mapIt(it) # segfaults
+  var b: seq[bool] = static:
+      newSeq[bool](0).filterIt(it) # does not segfault
+  var c: seq[bool] = static:
+      newSeq[bool](0).map(identity) # does not segfault
+  var d: seq[bool] = static:
+      newSeq[bool](0).map(proc (a: bool): bool = false) # segfaults
+  var e: seq[bool] = static:
+      newSeq[bool](0).filter(identity) # does not segfault
+  var f: seq[bool] = static:
+      newSeq[bool](0).filter(proc (a: bool): bool = false) # segfaults
+
+  doAssert a == @[]
+  doAssert b == @[]
+  doAssert c == @[]
+  doAssert d == @[]
+  doAssert e == @[]
+  doAssert f == @[]
+
+
+block: # bug #18310
+  macro t() : untyped =
+    let
+      x = nnkTupleConstr.newTree(newLit(1))
+      y = nnkTupleConstr.newTree(newLit(2))
+    doAssert not (x == y) # not using != intentionally
+    doAssert not(cast[int](x) == cast[int](y))
+    doAssert not(system.`==`(x, y))
+    doAssert system.`==`(x, x)
+  t()
+
+block: # bug #10815
+  type
+    Opcode = enum
+      iChar, iSet
+
+    Inst = object
+      case code: Opcode
+        of iChar:
+          c: char
+        of iSet:
+          cs: set[char]
+
+    Patt = seq[Inst]
+
+
+  proc `$`(p: Patt): string =
+    discard
+
+  proc P(): Patt =
+    result.add Inst(code: iSet)
+
+  const a = P()
+  doAssert $a == ""
+
+import tables
+
+block: # bug #8007
+  type
+    CostKind = enum
+      Fixed,
+      Dynamic
+
+    Cost = object
+      case kind*: CostKind
+      of Fixed:
+        cost*: int
+      of Dynamic:
+        handler*: proc(value: int): int {.nimcall.}
+
+  proc foo(value: int): int {.nimcall.} =
+    sizeof(value)
+
+  const a: array[2, Cost] =[
+    Cost(kind: Fixed, cost: 999),
+    Cost(kind: Dynamic, handler: foo)
+  ]
+
+  # OK with arrays & object variants
+  doAssert $a == "[(kind: Fixed, cost: 999), (kind: Dynamic, handler: ...)]"
+
+  const b: Table[int, Cost] = {
+    0: Cost(kind: Fixed, cost: 999),
+    1: Cost(kind: Dynamic, handler: foo)
+  }.toTable
+
+  # KO with Tables & object variants
+  # echo b # {0: (kind: Fixed, cost: 0), 1: (kind: Dynamic, handler: ...)} # <----- wrong behaviour
+  doAssert $b == "{0: (kind: Fixed, cost: 999), 1: (kind: Dynamic, handler: ...)}"
+
+  const c: Table[int, int] = {
+    0: 100,
+    1: 999
+  }.toTable
+
+  # OK with Tables and primitive int
+  doAssert $c == "{0: 100, 1: 999}"
+
+  # For some reason the following gives
+  #    Error: invalid type for const: Cost
+  const d0 = Cost(kind: Fixed, cost: 999)
+
+  # OK with seq & object variants
+  const d = @[Cost(kind: Fixed, cost: 999), Cost(kind: Dynamic, handler: foo)]
+  doAssert $d == "@[(kind: Fixed, cost: 999), (kind: Dynamic, handler: ...)]"
+
+block: # bug #14340
+  block:
+    proc opl3EnvelopeCalcSin0() = discard
+    type EnvelopeSinfunc = proc() {.nimcall.} # todo: fixme 
+    # const EnvelopeCalcSin0 = opl3EnvelopeCalcSin0 # ok
+    const EnvelopeCalcSin0: EnvelopeSinfunc = opl3EnvelopeCalcSin0 # was bug
+    const envelopeSin = [EnvelopeCalcSin0]
+    var a = 0
+    envelopeSin[a]()
+
+  block:
+    type Mutator = proc() {.noSideEffect, gcsafe.}
+    proc mutator0() = discard
+    const mTable = [Mutator(mutator0)]
+    var i=0
+    mTable[i]()
+
+block: # VM wrong register free causes errors in unrelated code
+  block: # bug #15597
+    #[
+    Error: unhandled exception: 'sym' is not accessible using discriminant 'kind' of type 'TNode' [FieldDefect]
+    in /Users/timothee/git_clone/nim/Nim_prs/compiler/vm.nim(1176) rawExecute
+    in opcIndCall
+    in let prc = if not isClosure: bb.sym else: bb[0].sym
+    ]#
+    proc bar2(head: string): string = "asdf"
+    proc zook(u1: int) = discard
+
+    type PathEntry = object
+      kind: int
+      path: string
+
+    iterator globOpt(): int =
+      var u1: int
+
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+      zook(u1)
+
+      var entry = PathEntry()
+      entry.path = bar2("")
+      if false:
+        echo "here2"
+
+    proc processAux(a: float) = discard
+
+    template bar(iter: untyped): untyped =
+      var ret: float
+      for x in iter: break
+      ret
+
+    proc main() =
+      processAux(bar(globOpt()))
+    static: main()
+
+  block: # ditto
+    # D20201024T133245
+    type Deque = object
+    proc initDeque2(initialSize: int = 4): Deque = Deque()
+    proc len2(a: Deque): int = 2
+    proc baz(dir: string): bool = true
+    proc bar2(head: string): string = "asdf"
+    proc bar3(path: var string) = path = path
+
+    type PathEntry = object
+      kind: int
+      path: string
+
+    proc initGlobOpt(dir: string, a1=false,a2=false,a3=false,a4=false): string = dir
+
+    iterator globOpt(dir: string): int =
+      var stack = initDeque2()
+      doAssert baz("")
+      let z = stack.len2
+      if stack.len2 >= 0:
+        var entry = PathEntry()
+        let current = if true: stack.len2 else: stack.len2
+        entry.path = bar2("")
+        bar3(entry.path)
+      if false:
+        echo "here2" # comment here => you get same error as https://github.com/nim-lang/Nim/issues/15704
+
+    proc processAux(a: float) = discard
+
+    template bar(iter: untyped): untyped =
+      var ret: float
+      for x in iter: break
+      ret
+    proc main() =
+      processAux(bar(globOpt(initGlobOpt("."))))
+    static: main()
+
+  block: # bug #15704
+    #[
+    Error: attempt to access a nil address kind: rkFloat
+    ]#
+    type Deque = object
+    proc initDeque2(initialSize: int = 4): Deque = Deque()
+    proc len2(a: Deque): int = 2
+
+    proc baz(dir: string): bool = true
+    proc bar2(head: string): string = "asdf"
+    proc bar3(path: var string) = path = path
+
+    type PathEntry = object
+      kind: int
+      path: string
+      depth: int
+
+    proc initGlobOpt(dir: string, a1=false,a2=false,a3=false,a4=false): string =
+      dir
+
+    iterator globOpt(dir: string): int =
+      var stack = initDeque2()
+      doAssert baz("")
+      let z = stack.len2
+      var a5: int
+      if stack.len2 >= 0:
+        var entry = PathEntry()
+        if false:
+          echo "here"
+        let current = if true: stack.len2 else: stack.len2
+        entry.depth = 1
+        entry.path = bar2("")
+        bar3(entry.path)
+    proc processAux(a: float) = discard
+    template bar(iter: untyped): untyped =
+      var ret: float
+      for x in iter:
+        break
+      ret
+    const dir = "."
+    proc main() =
+      processAux(bar(globOpt(initGlobOpt(dir))))
+    static: main()
+
+block: # bug #8015
+  block:
+    type Foo = object
+      case b: bool
+      of false: v1: int
+      of true: v2: int
+    const t = [Foo(b: false, v1: 1), Foo(b: true, v2: 2)]
+    doAssert $t == "[(b: false, v1: 1), (b: true, v2: 2)]"
+    doAssert $t[0] == "(b: false, v1: 1)" # was failing
+
+  block:
+    type
+      CostKind = enum
+        Fixed,
+        Dynamic
+
+      Cost = object
+        case kind*: CostKind
+        of Fixed:
+          cost*: int
+        of Dynamic:
+          handler*: proc(): int {.nimcall.}
+
+    proc foo1(): int {.nimcall.} =
+      100
+
+    proc foo2(): int {.nimcall.} =
+      200
+
+    # Change to `let` and it doesn't crash
+    const costTable = [
+      0: Cost(kind: Fixed, cost: 999),
+      1: Cost(kind: Dynamic, handler: foo1),
+      2: Cost(kind: Dynamic, handler: foo2)
+    ]
+
+    doAssert $costTable[0] == "(kind: Fixed, cost: 999)"
+    doAssert costTable[1].handler() == 100
+    doAssert costTable[2].handler() == 200
+
+    # Now trying to carry the table as an object field
+    type
+      Wrapper = object
+        table: array[3, Cost]
+
+    proc procNewWrapper(): Wrapper =
+      result.table = costTable
+
+    # Alternatively, change to `const` and it doesn't crash
+    let viaProc = procNewWrapper()
+
+    doAssert viaProc.table[1].handler != nil
+    doAssert viaProc.table[2].handler != nil
+    doAssert $viaProc.table[0] == "(kind: Fixed, cost: 999)"
+    doAssert viaProc.table[1].handler() == 100
+    doAssert viaProc.table[2].handler() == 200
+
+
+# bug #19198
+
+block:
+  type
+    Foo[n: static int] = int
+
+block:
+  static:
+    let x = int 1
+    doAssert $(x.type) == "int"  # Foo
+
+block:
+  static:
+    let x = int 1
+    let y = x + 1
+    # Error: unhandled exception: value out of range: -8 notin 0 .. 65535 [RangeDefect]
+    doAssert y == 2
+
+
+type Atom* = object
+  bar: int
+
+proc main() = # bug #12994
+  var s: seq[Atom]
+  var atom: Atom
+  var checked = 0
+  for i in 0..<2:
+    atom.bar = 5
+    s.add atom
+    atom.reset
+    if i == 0:
+      checked += 1
+      doAssert $s == "@[(bar: 5)]"
+    else:
+      checked += 1
+      doAssert $s == "@[(bar: 5), (bar: 5)]"
+  doAssert checked == 2
+
+static: main()
+main()
+
+# bug #19201
+proc foo(s: sink string) = doAssert s.len == 3
+
+static:
+  foo("abc")
+
+
+static:
+  for i in '1' .. '2': # bug #10938
+    var s: set[char]
+    doAssert s == {}
+    incl(s, i)
+
+  for _ in 0 ..< 3: # bug #13312
+    var s: string
+    s.add("foo")
+    doAssert s == "foo"
+
+  for i in 1 .. 5: # bug #13918
+    var arr: array[3, int]
+    var val: int
+    doAssert arr == [0, 0, 0] and val == 0
+    for j in 0 ..< len(arr):
+      arr[j] = i
+      val = i
+
+# bug #20985
+let a = block:
+  var groups: seq[seq[int]]
+  for i in 0 ..< 3:
+    var group: seq[int]
+    for j in 0 ..< 3:
+      group.add j
+    groups.add group
+  groups
+
+const b = block:
+  var groups: seq[seq[int]]
+  for i in 0 ..< 3:
+    var group: seq[int]
+    for j in 0 ..< 3:
+      group.add j
+    groups.add group
+  groups
+
+doAssert a == @[@[0, 1, 2], @[0, 1, 2], @[0, 1, 2]]
+doAssert b == @[@[0, 1, 2], @[0, 1, 2], @[0, 1, 2]]
+
+macro m1(s: string): int =
+  var ProcID {.global, compileTime.}: int
+  inc(ProcID)
+  result = newLit(ProcID)
+
+proc macroGlobal =
+  doAssert m1("Macro argument") == 1
+  doAssert m1("Macro argument") == 2
+  doAssert m1("Macro argument") == 3
+
+static: macroGlobal()
+macroGlobal()
+
+block: # bug #10108
+  template reject(x) =
+    static: doAssert(not compiles(x))
+
+  static:
+    let x: int = 2
+    proc deliver_x(): int = x
+    var y2 = deliver_x()
+    discard y2
+    reject:
+      const c5 = deliver_x()
+
+block: # bug #7590
+  proc doInit[T]():auto=
+    var a: T
+    return a
+
+  proc fun2[T](tup1:T)=
+    const tup0=doInit[T]()
+
+    # var tup=tup0 #ok
+    const tup=tup0 #causes bug
+
+    doAssert tup is tuple
+    doAssert tup[0] is tuple
+    for ai in tup.fields:
+      doAssert ai is tuple, "BUG2"
+
+  # const c=(foo:(bar1: 0.0))
+  const c=(foo:(bar1:"foo1"))
+  fun2(c)
+
+block: # bug #21708
+  type
+    Tup = tuple[name: string]
+
+  const X: array[2, Tup] = [(name: "foo",), (name: "bar",)]
+
+  static:
+    let s = X[0]
+    doAssert s[0] == "foo"
+
+block:
+  proc swap[T](x: var T): T =
+    result = x
+    x = default(T)
+
+  proc merge[T](a, b: var openArray[T]) =
+    a[0] = swap b[0]
+
+  static:
+    var x = "abc"
+    var y = "356"
+    merge(x, y)
+    doAssert x == "3bc"
+
+block: # bug #22190
+  type
+    EVMFork = enum
+      Berlin
+      Istanbul
+      Shanghai
+
+  const
+    Vm2OpAllForks =
+      {EVMFork.low .. EVMFork.high}
+
+    vm2OpExecBlockData = [(forks: Vm2OpAllForks)]
+
+  proc mkOpTable(selected: EVMFork): bool =
+    selected notin vm2OpExecBlockData[0].forks
+
+  const
+    tab = mkOpTable(Berlin)
+
+  doAssert not tab
+
+block: # issue #22524
+  const cnst = cstring(nil)
+  doAssert cnst.isNil
+  doAssert cnst == nil
+  let b = cnst
+  doAssert b.isNil
+  doAssert b == nil
+
+  let a = static: cstring(nil)
+  doAssert a.isNil
+
+  static:
+    var x: cstring
+    doAssert x.isNil
+    doAssert x == nil
+    doAssert x != ""
+
+block: # issue #15730
+  const s: cstring = ""
+  doAssert s != nil
+
+  static:
+    let s: cstring = ""
+    doAssert not s.isNil
+    doAssert s != nil
+    doAssert s == ""
+
+static: # more nil cstring issues
+  let x = cstring(nil)
+  doAssert x.len == 0
+
+block: # bug #23925
+  type Foo = enum A = -1
+  proc foo =
+    doAssert cast[Foo](-1) == A
+    doAssert ord(A) == -1
+
+  static: foo()
+  foo()
+
+  type E = enum
+    e0 e1 e2 e3 e4 e5 e6 e7 e8 e9 e10 e11 e12 e13 e14 e15 e16 e17 e18 e19 e20
+    e21 e22 e23 e24 e25 e26 e27 e28 e29 e30 e31 e32 e33 e34 e35 e36 e37 e38
+    e39 e40 e41 e42 e43 e44 e45 e46 e47 e48 e49 e50 e51 e52 e53 e54 e55 e56
+    e57 e58 e59 e60 e61 e62 e63 e64 e65 e66 e67 e68 e69 e70 e71 e72 e73 e74
+    e75 e76 e77 e78 e79 e80 e81 e82 e83 e84 e85 e86 e87 e88 e89 e90 e91 e92
+    e93 e94 e95 e96 e97 e98 e99 e100 e101 e102 e103 e104 e105 e106 e107 e108
+    e109 e110 e111 e112 e113 e114 e115 e116 e117 e118 e119 e120 e121 e122
+    e123 e124 e125 e126 e127 e128
+  proc bar =
+    doAssert cast[E](int(e128)) == e128
+
+  static: bar()
+  bar()
+
+static: # bug #21353
+  var s: proc () = default(proc ())
+  doAssert s == nil
diff --git a/tests/vm/tvmops.nim b/tests/vm/tvmops.nim
index 6442c49d6..3d8d5a9ac 100644
--- a/tests/vm/tvmops.nim
+++ b/tests/vm/tvmops.nim
@@ -1,3 +1,7 @@
+discard """
+  targets: "c cpp js"
+"""
+
 #[
 test for vmops.nim
 ]#
@@ -5,16 +9,6 @@ import os
 import math
 import strutils
 
-template forceConst(a: untyped): untyped =
-  ## Force evaluation at CT, useful for example here:
-  ## `callFoo(forceConst(getBar1()), getBar2())`
-  ## instead of:
-  ##  block:
-  ##    const a = getBar1()
-  ##    `callFoo(a, getBar2())`
-  const ret = a
-  ret
-
 static:
   # TODO: add more tests
   block: #getAppFilename, gorgeEx, gorge
@@ -22,7 +16,7 @@ static:
     let ret = gorgeEx(nim & " --version")
     doAssert ret.exitCode == 0
     doAssert ret.output.contains "Nim Compiler"
-    let ret2 = gorgeEx(nim & " --unexistant")
+    let ret2 = gorgeEx(nim & " --nonxistent")
     doAssert ret2.exitCode != 0
     let output3 = gorge(nim & " --version")
     doAssert output3.contains "Nim Compiler"
@@ -47,6 +41,6 @@ static:
 
 block:
   # Check against bugs like #9176
-  doAssert getCurrentCompilerExe() == forceConst(getCurrentCompilerExe())
+  doAssert getCurrentCompilerExe() == getCurrentCompilerExe().static
   if false: #pending #9176
-    doAssert gorgeEx("unexistant") == forceConst(gorgeEx("unexistant"))
+    doAssert gorgeEx("nonxistent") == gorgeEx("nonxistent").static
diff --git a/tests/vm/tvmopsDanger.nim b/tests/vm/tvmopsDanger.nim
new file mode 100644
index 000000000..966feffe6
--- /dev/null
+++ b/tests/vm/tvmopsDanger.nim
@@ -0,0 +1,13 @@
+discard """
+  cmd: "nim c --experimental:vmopsDanger -r $file"
+"""
+when defined(nimPreviewSlimSystem):
+  import std/assertions
+import std/[times, os]
+
+const foo = getTime()
+let bar = foo
+doAssert bar > low(Time)
+
+static: # bug #23932
+  doAssert getCurrentDir().len > 0
diff --git a/tests/vm/twrong_concat.nim b/tests/vm/twrong_concat.nim
index 538ea2527..59a10bdb9 100644
--- a/tests/vm/twrong_concat.nim
+++ b/tests/vm/twrong_concat.nim
@@ -1,7 +1,3 @@
-discard """
-  output: '''success'''
-"""
-
 # bug #3804
 
 #import sequtils
@@ -23,6 +19,4 @@ static:
   sameBug(objs)
   # sameBug(objs)
   echo objs[0].field
-  assert(objs[0].field == "hello") # fails, because (objs[0].field == "hello bug") - mutated!
-
-echo "success"
+  doAssert(objs[0].field == "hello") # fails, because (objs[0].field == "hello bug") - mutated!
diff --git a/tests/vm/twrongarray.nim b/tests/vm/twrongarray.nim
index c1514d0e9..7f24290e2 100644
--- a/tests/vm/twrongarray.nim
+++ b/tests/vm/twrongarray.nim
@@ -14,4 +14,4 @@ when false:
 
 proc two(dummy: int, size: int) =
   var x: array[size * 1, int] # compiles, but shouldn't?
-  #assert(x.len == size) # just for fun
+  # doAssert(x.len == size) # just for fun
diff --git a/tests/vm/tyaytypedesc.nim b/tests/vm/tyaytypedesc.nim
index a3ad9b707..8cb402bff 100644
--- a/tests/vm/tyaytypedesc.nim
+++ b/tests/vm/tyaytypedesc.nim
@@ -1,7 +1,3 @@
-discard """
-  output: "ntWhitespace"
-"""
-
 # bug #3357
 
 type NodeType* = enum
@@ -10,7 +6,7 @@ type NodeType* = enum
 type TokenType* = enum
   ttWhitespace
 
-proc enumTable*[A, B, C](a: openarray[tuple[key: A, val: B]], ret: typedesc[C]): C =
+proc enumTable*[A, B, C](a: openArray[tuple[key: A, val: B]], ret: typedesc[C]): C =
   for item in a:
     result[item.key] = item.val
 
@@ -18,4 +14,4 @@ const tokenTypeToNodeType = {
   ttWhitespace: ntWhitespace,
 }.enumTable(array[ttWhitespace..ttWhitespace, NodeType])
 
-echo tokenTypeToNodeType[ttWhitespace]
+doAssert tokenTypeToNodeType[ttWhitespace] == ntWhitespace
diff --git a/tests/vm/tzero_extend.nim b/tests/vm/tzero_extend.nim
index 1fed5d419..418dbc486 100644
--- a/tests/vm/tzero_extend.nim
+++ b/tests/vm/tzero_extend.nim
@@ -5,10 +5,10 @@ proc get_values(): (seq[int8], seq[int16], seq[int32]) =
   let i8 = -3'i8
   let i16 = -3'i16
   let i32 = -3'i32
-  doAssert i8.ze == 0xFD
-  doAssert i8.ze64 == 0xFD
-  doAssert i16.ze == 0xFFFD
-  doAssert i16.ze64 == 0xFFFD
+  doAssert int(cast[uint8](i8)) == 0xFD
+  doAssert int64(cast[uint8](i8)) == 0xFD
+  doAssert int(cast[uint16](i16)) == 0xFFFD
+  doAssert int64(cast[uint16](i16)) == 0xFFFD
 
   result[0] = @[]; result[1] = @[]; result[2] = @[]
 
diff --git a/tests/whenstmt/t12517.nim b/tests/whenstmt/t12517.nim
new file mode 100644
index 000000000..8be0171e1
--- /dev/null
+++ b/tests/whenstmt/t12517.nim
@@ -0,0 +1,21 @@
+# Test based on issue #12517
+
+discard """
+  nimout: '''
+nimvm
+both
+'''
+  output: '''
+both
+'''
+"""
+
+proc test() =
+  when nimvm:
+    echo "nimvm"
+  echo "both"
+
+static:
+  test()
+test()
+
diff --git a/tests/whenstmt/t19426.nim b/tests/whenstmt/t19426.nim
new file mode 100644
index 000000000..95fb54a9e
--- /dev/null
+++ b/tests/whenstmt/t19426.nim
@@ -0,0 +1,16 @@
+type
+  MyInt = object
+    bitWidth: int
+
+template toRealType*(t: MyInt): typedesc =
+  when t.bitWidth == 32: int32
+  elif t.bitWidth == 64: int64
+  else: {.error.}
+
+proc doFail(T: typedesc): T = default(T)
+
+proc test =
+  const myInt = MyInt(bitWidth:32)
+  discard doFail(toRealType(myInt))
+
+test()
\ No newline at end of file
diff --git a/tests/whenstmt/twhen.nim b/tests/whenstmt/twhen.nim
new file mode 100644
index 000000000..b155ddcfb
--- /dev/null
+++ b/tests/whenstmt/twhen.nim
@@ -0,0 +1,47 @@
+discard """
+  nimout: '''
+nimvm - when
+nimvm - whenElif
+nimvm - whenElse
+'''
+  output: '''
+when
+whenElif
+whenElse
+'''
+"""
+
+# test both when and when nimvm to ensure proper evaluation
+
+proc compileOrRuntimeProc(s: string) =
+  when nimvm:
+    echo "nimvm - " & s
+  else:
+     echo s
+
+template output(s: string) =
+  static:
+    compileOrRuntimeProc(s)
+  compileOrRuntimeProc(s)
+
+when compiles(1):
+  output("when")
+elif compiles(2):
+  output("fail - whenElif")
+else:
+  output("fail - whenElse")
+
+when compiles(nonexistent):
+  output("fail - when")
+elif compiles(1):
+  output("whenElif")
+else:
+  output("fail - whenElse")
+
+when compiles(nonexistent):
+  output("fail - when")
+elif compiles(nonexistent):
+  output("fail - whenElif")
+else:
+  output("whenElse")
+
diff --git a/tests/whenstmt/twhen_macro.nim b/tests/whenstmt/twhen_macro.nim
new file mode 100644
index 000000000..deb1dddc9
--- /dev/null
+++ b/tests/whenstmt/twhen_macro.nim
@@ -0,0 +1,18 @@
+import macros
+
+# test that when stmt works from within a macro
+
+macro output(s: string, xs: varargs[untyped]): auto =
+  result = quote do:
+    when compiles(`s`):
+      "when - " & `s`
+    elif compiles(`s`):
+      "elif - " & `s`
+      # should never get here so this should not break
+      broken.xs
+    else:
+      "else - " & `s`
+      # should never get here so this should not break
+      more.broken.xs
+
+doAssert output("test") == "when - test"
\ No newline at end of file
diff --git a/tests/xml/ttree_add.nim b/tests/xml/ttree_add.nim
new file mode 100644
index 000000000..4c6ef6cf9
--- /dev/null
+++ b/tests/xml/ttree_add.nim
@@ -0,0 +1,51 @@
+discard """
+  output: '''
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+var baseDocHead = """
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+</xml>
+"""
+var baseDocHeadTree = parseXml(baseDocHead)
+var baseDocBody = """
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+"""
+var baseDocBodyTree = parseXml(baseDocBody)
+
+proc test_add() =
+  var testDoc = baseDocHeadTree
+  var newBody = newElement("body")
+  for item in baseDocBodyTree.items():
+    newBody.add(item)
+  
+  echo $newBody
+  
+  testDoc.add(newBody)
+  echo $testDoc
+
+test_add()
diff --git a/tests/xml/ttree_add1.nim b/tests/xml/ttree_add1.nim
new file mode 100644
index 000000000..30ec83c02
--- /dev/null
+++ b/tests/xml/ttree_add1.nim
@@ -0,0 +1,53 @@
+discard """
+  output: '''
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+var baseDocHead = """
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+</xml>
+"""
+var baseDocHeadTree = parseXml(baseDocHead)
+var baseDocBody = """
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+"""
+var baseDocBodyTree = parseXml(baseDocBody)
+
+proc test_add() =
+  var testDoc = baseDocHeadTree
+  var newBody = newElement("body")
+  var bodyItems: seq[XmlNode] = @[]
+  for item in baseDocBodyTree.items():
+    bodyItems.add(item)
+  newBody.add(bodyItems)
+  
+  echo $newBody
+  
+  testDoc.add(newBody)
+  echo $testDoc
+
+test_add()
diff --git a/tests/xml/ttree_delete.nim b/tests/xml/ttree_delete.nim
new file mode 100644
index 000000000..32b477839
--- /dev/null
+++ b/tests/xml/ttree_delete.nim
@@ -0,0 +1,47 @@
+discard """
+  output: '''
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+let initialDocBase = """
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <tag>
+    <div>MORE TEXT </div>
+    <div>MORE TEXT Some more text</div>
+  </tag>
+  <tag>
+    <div>MORE TEXT </div>
+    <div>MORE TEXT Some more text</div>
+  </tag>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+"""
+var initialDocBaseTree = parseXml(initialDocBase)
+
+proc test_delete() =
+  var testDoc = initialDocBaseTree
+  
+  testDoc.delete(1..2)
+  echo $testDoc
+
+test_delete()
diff --git a/tests/xml/ttree_delete1.nim b/tests/xml/ttree_delete1.nim
new file mode 100644
index 000000000..a8442a093
--- /dev/null
+++ b/tests/xml/ttree_delete1.nim
@@ -0,0 +1,48 @@
+discard """
+  output: '''
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+let initialDocBase = """
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <tag>
+    <div>MORE TEXT </div>
+    <div>MORE TEXT Some more text</div>
+  </tag>
+  <tag>
+    <div>MORE TEXT </div>
+    <div>MORE TEXT Some more text</div>
+  </tag>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+"""
+var initialDocBaseTree = parseXml(initialDocBase)
+
+proc test_delete() =
+  var testDoc = initialDocBaseTree
+  
+  testDoc.delete(1)
+  testDoc.delete(1)
+  echo $testDoc
+
+test_delete()
diff --git a/tests/xml/ttree_insert.nim b/tests/xml/ttree_insert.nim
new file mode 100644
index 000000000..b2941395b
--- /dev/null
+++ b/tests/xml/ttree_insert.nim
@@ -0,0 +1,53 @@
+discard """
+  output: '''
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+var baseDocHead = """
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+</xml>
+"""
+var baseDocHeadTree = parseXml(baseDocHead)
+var baseDocBody = """
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+"""
+var baseDocBodyTree = parseXml(baseDocBody)
+
+proc test_insert() =
+  var testDoc = baseDocHeadTree
+  var newBody = newElement("body")
+  var bodyItems: seq[XmlNode] = @[]
+  for item in baseDocBodyTree.items():
+    bodyItems.insert(item, len(bodyItems))
+  newBody.insert(bodyItems, 1)
+  
+  echo $newBody
+  
+  testDoc.insert(newBody, 1)
+  echo $testDoc
+
+test_insert()
diff --git a/tests/xml/ttree_insert1.nim b/tests/xml/ttree_insert1.nim
new file mode 100644
index 000000000..9aa3faf69
--- /dev/null
+++ b/tests/xml/ttree_insert1.nim
@@ -0,0 +1,51 @@
+discard """
+  output: '''
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+var baseDocHead = """
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+</xml>
+"""
+var baseDocHeadTree = parseXml(baseDocHead)
+var baseDocBody = """
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+"""
+var baseDocBodyTree = parseXml(baseDocBody)
+
+proc test_insert() =
+  var testDoc = baseDocHeadTree
+  var newBody = newElement("body")
+  for item in baseDocBodyTree.items():
+    newBody.insert(item, len(newBody))
+  
+  echo $newBody
+  
+  testDoc.insert(newBody, 1)
+  echo $testDoc
+
+test_insert()
diff --git a/tests/xml/ttree_replace.nim b/tests/xml/ttree_replace.nim
new file mode 100644
index 000000000..97d2db638
--- /dev/null
+++ b/tests/xml/ttree_replace.nim
@@ -0,0 +1,46 @@
+discard """
+  output: '''
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+var baseDocBody = """
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+"""
+var baseDocBodyTree = parseXml(baseDocBody)
+let initialDocBase = """
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body before replace </div>
+    <div>Some more text in body before replace </div>
+  </body>
+</xml>
+"""
+var initialDocBaseTree = parseXml(initialDocBase)
+
+proc test_replace() =
+  var testDoc = initialDocBaseTree
+  
+  testDoc.replace(1, @[baseDocBodyTree])
+  echo $testDoc
+
+test_replace()
diff --git a/tests/xml/ttree_replace1.nim b/tests/xml/ttree_replace1.nim
new file mode 100644
index 000000000..059ce2085
--- /dev/null
+++ b/tests/xml/ttree_replace1.nim
@@ -0,0 +1,53 @@
+discard """
+  output: '''
+<xml>
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+  <body>
+    <div>Some text in body</div>
+    <div>Some more text in body </div>
+  </body>
+</xml>
+'''
+"""
+
+# Test xmltree add/insert/delete/replace operations
+import xmlparser
+import xmltree
+var baseDocHead = """
+  <head>
+    <div>Some text</div>
+    <div>Some more text </div>
+  </head>
+"""
+var baseDocHeadTree = parseXml(baseDocHead)
+var baseDocBody = """
+<body>
+  <div>Some text in body</div>
+  <div>Some more text in body </div>
+</body>
+"""
+var baseDocBodyTree = parseXml(baseDocBody)
+let initialDocBase = """
+<xml>
+  <head>
+    <div>Some text before replace </div>
+    <div>Some more text before replace </div>
+  </head>
+  <body>
+    <div>Some text in body before replace </div>
+    <div>Some more text in body before replace </div>
+  </body>
+</xml>
+"""
+var initialDocBaseTree = parseXml(initialDocBase)
+
+proc test_replace() =
+  var testDoc = initialDocBaseTree
+  
+  testDoc.replace(0..1, @[baseDocHeadTree, baseDocBodyTree])
+  echo $testDoc
+
+test_replace()