diff options
199 files changed, 8268 insertions, 4793 deletions
diff --git a/.gitignore b/.gitignore index 15272385f..462df4efc 100644 --- a/.gitignore +++ b/.gitignore @@ -1,36 +1,27 @@ +* +!**/ +!*.* +nimcache/ + *.o +!/icons/*.o *.exe *.so +*.dylib *.zip *.iss -nimcache -lib/nimcache -tools/nimcache -tools/nimweb -tests/nimcache -tests/accept/run/nimcache -tests/accept/compile/nimcache -tests/reject/nimcache -compiler/nimcache -compiler/c2nim/nimcache -compiler/pas2nim/nimcache -misc + +mapping.txt +tags +install.sh +deinstall.sh + doc/*.html doc/*.pdf doc/*.idx /web/upload -koch -compiler/nimrod* -build/[0-9]_[0-9] -bin/nimrod -examples/cross_calculator/nimrod_commandline/nimcalculator -examples/cross_todo/nimrod_backend/*.html -examples/cross_todo/nimrod_backend/backend -examples/cross_todo/nimrod_backend/testbackend -examples/cross_todo/nimrod_backend/todo.sqlite3 -examples/cross_todo/nimrod_commandline/nimtodo -install.sh -deinstall.sh +build/* +bin/* # iOS specific wildcards. *.mode1v3 @@ -42,534 +33,11 @@ deinstall.sh project.xcworkspace/ xcuserdata/ -# iOS specific absolute paths -examples/cross_calculator/ios/resources/ui/*.m -examples/cross_calculator/ios/tags - -# Android specific absolute paths. -examples/cross_calculator/android/bin/ -examples/cross_calculator/android/gen/ -examples/cross_calculator/android/jni/backend-jni.h -examples/cross_calculator/android/libs/ -examples/cross_calculator/android/local.properties -examples/cross_calculator/android/obj/ -examples/cross_calculator/android/tags - # Generated files. /compile.json -/compiler/c2nim/c2nim /compiler/nimrod.dot -/compiler/pas2nim/pas2nim -/compiler/service -/examples/allany -/examples/cairoex -/examples/cgiex -/examples/cgi/cgi_stacktrace -/examples/cgi/example -/examples/curlex -/examples/debugging -/examples/docstrings -/examples/filterex -/examples/fizzbuzz -/examples/gtk/ex1 -/examples/gtk/ex2 -/examples/gtk/ex3 -/examples/gtk/ex4 -/examples/gtk/ex5 -/examples/gtk/ex6 -/examples/gtk/ex7 -/examples/gtk/ex8 -/examples/gtk/ex9 -/examples/hallo -/examples/htmlrefs -/examples/htmltitle -/examples/httpserver2 -/examples/iupex1 -/examples/keyval -/examples/keyval2 -/examples/luaex -/examples/maximum -/examples/parsecfgex -/examples/pythonex -/examples/sdlex -/examples/statcsv -/examples/talk/dsl -/examples/talk/formatoptimizer -/examples/talk/hoisting -/examples/talk/lazyeval -/examples/talk/quasiquote -/examples/talk/tags -/examples/tclex -/examples/transff -/examples/tunit -/examples/wingui -/examples/x11ex -/lib/libnimrtl.dylib -/lib/libserver.dylib -/lib/packages/docutils/highlite -/lib/pure/actors -/lib/pure/algorithm -/lib/pure/asyncio -/lib/pure/base64 -/lib/pure/basic2d -/lib/pure/basic3d -/lib/pure/browsers -/lib/pure/cgi -/lib/pure/collections/sequtils -/lib/pure/collections/tables -/lib/pure/colors -/lib/pure/complex -/lib/pure/cookies -/lib/pure/dynlib -/lib/pure/encodings -/lib/pure/endians -/lib/pure/events -/lib/pure/fsmonitor -/lib/pure/ftpclient -/lib/pure/gentabs -/lib/pure/hashes -/lib/pure/htmlgen -/lib/pure/htmlparser -/lib/pure/httpclient -/lib/pure/httpserver -/lib/pure/irc -/lib/pure/json -/lib/pure/lexbase -/lib/pure/lib/ -/lib/pure/marshal -/lib/pure/matchers -/lib/pure/math -/lib/pure/md5 -/lib/pure/memfiles -/lib/pure/mersenne -/lib/pure/mimetypes -/lib/pure/nimprof -/lib/pure/numeric -/lib/pure/oids -/lib/pure/os -/lib/pure/osproc -/lib/pure/parsecfg -/lib/pure/parsecsv -/lib/pure/parseopt -/lib/pure/parseopt2 -/lib/pure/parsesql -/lib/pure/parseurl -/lib/pure/parseutils -/lib/pure/parsexml -/lib/pure/pegs -/lib/pure/poly -/lib/pure/redis -/lib/pure/romans -/lib/pure/ropes -/lib/pure/scgi -/lib/pure/smtp -/lib/pure/sockets -/lib/pure/streams -/lib/pure/strtabs -/lib/pure/strutils -/lib/pure/subexes -/lib/pure/terminal -/lib/pure/times -/lib/pure/typetraits -/lib/pure/unicode -/lib/pure/unittest -/lib/pure/uri -/lib/pure/xmldom -/lib/pure/xmldomparser -/lib/pure/xmlparser -/lib/pure/xmltree -/lib/system/sysio -/lib/weird -/lib/wrappers/gtk/gtk2 /reject.json /run.json /testresults.html /testresults.json -/tests/caas/absurd_nesting -/tests/caas/completion_dot_syntax_main -/tests/caasdriver -/tests/caas/forward_declarations -/tests/caas/idetools_api -/tests/caas/imported -/tests/caas/issue_416_template_shift -/tests/caas/issue_452_export_shift -/tests/caas/issue_477_dynamic_dispatch -/tests/caas/its_full_of_procs -/tests/caas/main -/tests/caas/SymbolProcRun.*/ -/tests/ccg/tmissingbracket -/tests/compile/talias -/tests/compile/tambsym2 -/tests/compile/tarrindx -/tests/compile/tassign -/tests/compile/tbindoverload -/tests/compile/tcan_alias_generic -/tests/compile/tcan_alias_specialised_generic -/tests/compile/tcan_inherit_generic -/tests/compile/tcan_specialise_generic -/tests/compile/tccgen1 -/tests/compile/tclosure4 -/tests/compile/tclosurebug2 -/tests/compile/tcmdline -/tests/compile/tcodegenbug1 -/tests/compile/tcolonisproc -/tests/compile/tcolors -/tests/compile/tcommontype -/tests/compile/tcompiles -/tests/compile/tcomputedgoto -/tests/compile/tconsteval -/tests/compile/tconstraints -/tests/compile/tconvcolors -/tests/compile/tcputime -/tests/compile/tdefaultprocparam -/tests/compile/tdictdestruct -/tests/compile/tdiscardable -/tests/compile/tdllvar -/tests/compile/tdumpast -/tests/compile/tdumpast2 -/tests/compile/techo -/tests/compile/teffects1 -/tests/compile/temptyecho -/tests/compile/tendian -/tests/compile/tenum -/tests/compile/tenum2 -/tests/compile/tenum3 -/tests/compile/teval1 -/tests/compile/texport -/tests/compile/tfib -/tests/compile/tforwardgeneric -/tests/compile/tforwty -/tests/compile/tforwty2 -/tests/compile/tgeneric -/tests/compile/tgeneric2 -/tests/compile/tgeneric3 -/tests/compile/tgeneric4 -/tests/compile/tgenericmatcher -/tests/compile/tgenericmatcher2 -/tests/compile/tgenericprocvar -/tests/compile/tgenericprop -/tests/compile/tgenericrefs -/tests/compile/tgenerictmpl -/tests/compile/tgenericvariant -/tests/compile/tgensymgeneric -/tests/compile/tgetstartmilsecs -/tests/compile/tglobalforvar -/tests/compile/thallo -/tests/compile/theaproots -/tests/compile/thexrange -/tests/compile/thygienictempl -/tests/compile/tident -/tests/compile/timplicititems -/tests/compile/timplictderef -/tests/compile/tinheritref -/tests/compile/tio -/tests/compile/tircbot -/tests/compile/titer -/tests/compile/titer2 -/tests/compile/titer_no_tuple_unpack -/tests/compile/titerovl -/tests/compile/tlastmod -/tests/compile/tlinearscanend -/tests/compile/tloops -/tests/compile/tmacro1 -/tests/compile/tmacro2 -/tests/compile/tmacroaspragma -/tests/compile/tmacrostmt -/tests/compile/tmandelbrot -/tests/compile/tmarshal -/tests/compile/tmath -/tests/compile/tmatrix1 -/tests/compile/tmatrix2 -/tests/compile/tmongo -/tests/compile/tnamedparamanonproc -/tests/compile/tnamedparams -/tests/compile/tnestedproc -/tests/compile/tnew -/tests/compile/tnewsets -/tests/compile/tnewuns -/tests/compile/tnoargopenarray -/tests/compile/tnoforward -/tests/compile/tobjconstr2 -/tests/compile/tobjcov -/tests/compile/tobject2 -/tests/compile/tobject3 -/tests/compile/tobjects -/tests/compile/toop -/tests/compile/toptions -/tests/compile/tos -/tests/compile/toverprc -/tests/compile/tparedef -/tests/compile/tparscfg -/tests/compile/tparsefloat -/tests/compile/tparsopt -/tests/compile/tposix -/tests/compile/tprep -/tests/compile/tprocvars -/tests/compile/tpush -/tests/compile/tquicksort -/tests/compile/tquit -/tests/compile/tradix -/tests/compile/treadln -/tests/compile/treadx -/tests/compile/trecmod -/tests/compile/trecmod2 -/tests/compile/trectuple -/tests/compile/trectuples -/tests/compile/tredef -/tests/compile/trepr -/tests/compile/tsecondarrayproperty -/tests/compile/tseq2 -/tests/compile/tseqcon2 -/tests/compile/tshadow_magic_type -/tests/compile/tsizeof -/tests/compile/tslurp -/tests/compile/tsockets -/tests/compile/tsortcall -/tests/compile/tspecialised_is_equivalent -/tests/compile/tstrace -/tests/compile/tstrdesc -/tests/compile/tstrdist -/tests/compile/tstreams -/tests/compile/tstrset -/tests/compile/tstrtabs -/tests/compile/ttableconstr -/tests/compile/ttempl -/tests/compile/ttempl3 -/tests/compile/ttempl4 -/tests/compile/ttempl5 -/tests/compile/ttemplreturntype -/tests/compile/tthread_generic -/tests/compile/ttime -/tests/compile/ttuple1 -/tests/compile/ttypeclasses -/tests/compile/ttypeconverter1 -/tests/compile/tuserpragma -/tests/compile/tvoid -/tests/compile/twalker -/tests/compile/typalias -/tests/dll/client -/tests/gc/closureleak -/tests/gc/cycleleak -/tests/gc/gcbench -/tests/gc/gcleak -/tests/gc/gcleak2 -/tests/gc/gcleak3 -/tests/gc/gctest -/tests/gc/weakrefs -/tests/manyloc/argument_parser/ex_wget -/tests/manyloc/nake/nakefile -/tests/manyloc/packages/noconflicts -/tests/manyloc/standalone/barebone -/tests/patterns/targlist -/tests/patterns/tcse -/tests/patterns/thoist -/tests/patterns/tmatrix -/tests/patterns/tnoalias -/tests/patterns/tnoendlessrec -/tests/patterns/tor -/tests/patterns/tpartial -/tests/patterns/tstar -/tests/patterns/tstmtlist -/tests/reject/t99bott -/tests/reject/tcheckedfield1 -/tests/reject/tdeprecated -/tests/reject/tdisallowif -/tests/reject/tuninit1 -/tests/rodfiles/aconv -/tests/rodfiles/bconv -/tests/rodfiles/bmethods -/tests/rodfiles/bmethods2 -/tests/rodfiles/deada -/tests/rodfiles/deada2 -/tests/rodfiles/hallo -/tests/rodfiles/hallo2 -/tests/rodfiles/tgeneric1 -/tests/rodfiles/tgeneric2 -/tests/run/tack -/tests/run/tactiontable -/tests/run/tambsym2 -/tests/run/tambsys -/tests/run/tanontuples -/tests/run/tarray -/tests/run/tarray2 -/tests/run/tarray3 -/tests/run/tarraycons -/tests/run/tassert -/tests/run/tastoverload1 -/tests/run/tasynciossl -/tests/run/tasyncudp -/tests/run/tbind1 -/tests/run/tbind3 -/tests/run/tbintre2 -/tests/run/tbintree -/tests/run/tborrow -/tests/run/tbug499771 -/tests/run/tbug511622 -/tests/run/tcase_setconstr -/tests/run/tcasestm -/tests/run/tcgbug -/tests/run/tclosure2 -/tests/run/tclosure3 -/tests/run/tcnstseq -/tests/run/tcnstseq2 -/tests/run/tcnstseq3 -/tests/run/tconcat -/tests/run/tconstr2 -/tests/run/tcontinue -/tests/run/tcontinuexc -/tests/run/tcopy -/tests/run/tcountup -/tests/run/tcritbits -/tests/run/tcurrncy -/tests/run/tdestructor -/tests/run/tdrdobbs_examples -/tests/run/temit -/tests/run/tenumhole -/tests/run/tenumitems -/tests/run/teventemitter -/tests/run/tevents -/tests/run/texceptions -/tests/run/texcpt1 -/tests/run/texcsub -/tests/run/texplicitgeneric1 -/tests/run/tfieldindex -/tests/run/tfielditerator -/tests/run/tfielditerator2 -/tests/run/tfilter -/tests/run/tfinally -/tests/run/tfinally2 -/tests/run/tfinally3 -/tests/run/tfinalobj -/tests/run/tfloat1 -/tests/run/tfloat2 -/tests/run/tfloat3 -/tests/run/tformat -/tests/run/tfriends -/tests/run/tgenericassign -/tests/run/tgenericassigntuples -/tests/run/tgenericconverter -/tests/run/tgenericprocvar -/tests/run/tgenerics1 -/tests/run/tgensym -/tests/run/tglobal -/tests/run/thashes -/tests/run/thexlit -/tests/run/thintoff -/tests/run/tidgen -/tests/run/tindent1 -/tests/run/tinit -/tests/run/tinterf -/tests/run/tints -/tests/run/tisopr -/tests/run/titer3 -/tests/run/titer5 -/tests/run/titer6 -/tests/run/titer7 -/tests/run/titer8 -/tests/run/titer9 -/tests/run/titerslice -/tests/run/titervaropenarray -/tests/run/tkoeniglookup -/tests/run/tlet -/tests/run/tlists -/tests/run/tlocals -/tests/run/tlowhigh -/tests/run/tmacro2 -/tests/run/tmacro3 -/tests/run/tmacro4 -/tests/run/tmacros1 -/tests/run/tmath -/tests/run/tmatrix -/tests/run/tmemoization -/tests/run/tmethods1 -/tests/run/tmixin -/tests/run/tmoditer -/tests/run/tmultim1 -/tests/run/tmultim2 -/tests/run/tmultim3 -/tests/run/tmultim4 -/tests/run/tmultim6 -/tests/run/tnamedenumfields -/tests/run/tnestif -/tests/run/tnestprc -/tests/run/tnewderef -/tests/run/tnodeadlocks -/tests/run/tobjasgn -/tests/run/tobjconstr -/tests/run/tobject -/tests/run/tofopr -/tests/run/tonraise -/tests/run/toop1 -/tests/run/topenarrayrepr -/tests/run/topenlen -/tests/run/toprprec -/tests/run/toverflw -/tests/run/toverflw2 -/tests/run/toverl2 -/tests/run/toverl3 -/tests/run/toverwr -/tests/run/tovfint -/tests/run/tpatterns -/tests/run/tpegs -/tests/run/tpos -/tests/run/tprecedence -/tests/run/tprintf -/tests/run/tprocvar -/tests/run/tquotewords -/tests/run/tregex -/tests/run/treguse -/tests/run/trepr -/tests/run/treraise -/tests/run/tromans -/tests/run/tseqcon -/tests/run/tseqtuple -/tests/run/tsequtils -/tests/run/tsets -/tests/run/tsets2 -/tests/run/tsidee2 -/tests/run/tsidee3 -/tests/run/tsimmeth -/tests/run/tsimplesort -/tests/run/tslices -/tests/run/tsortdev -/tests/run/tsplit -/tests/run/tstempl -/tests/run/tstmtexprs -/tests/run/tstrange -/tests/run/tstringinterp -/tests/run/tstrlits -/tests/run/tstrutil -/tests/run/tsubrange -/tests/run/tsubrange2 -/tests/run/ttables -/tests/run/ttables2 -/tests/run/ttoseq -/tests/run/ttypedesc1 -/tests/run/tunhandledexc -/tests/run/tunidecode -/tests/run/tunittests -/tests/run/tuserassert -/tests/run/tvarargs_vs_generic -/tests/run/tvardecl -/tests/run/tvariantasgn -/tests/run/tvariantstack -/tests/run/tvarious1 -/tests/run/tvarnums -/tests/run/tvarres1 -/tests/run/tvarres2 -/tests/run/tvartup -/tests/run/tvtable -/tests/run/twrongexc -/tests/run/txmlgen -/tests/run/txmltree -/tests/run/tzeroarray -/tests/system/helpers/readall_echo -/tests/system/io -/tests/system/params -/tests/tester -/tests/threads/tactors -/tests/threads/tactors2 -/tests/threads/tthreadanalysis2 -/tests/threads/tthreadanalysis3 -/tests/threads/tthreadheapviolation1 -/tools/nimgrep +testament.db diff --git a/compiler/ast.nim b/compiler/ast.nim index 97f48b253..516954b88 100644 --- a/compiler/ast.nim +++ b/compiler/ast.nim @@ -510,6 +510,7 @@ const tfUncheckedArray* = tfVarargs tfUnion* = tfNoSideEffect tfGcSafe* = tfThread + tfObjHasKids* = tfEnumHasHoles skError* = skUnknown # type flags that are essential for type equality: @@ -549,7 +550,7 @@ type mFields, mFieldPairs, mOmpParFor, mAppendStrCh, mAppendStrStr, mAppendSeqElem, mInRange, mInSet, mRepr, mExit, mSetLengthStr, mSetLengthSeq, - mIsPartOf, mAstToStr, mRand, + mIsPartOf, mAstToStr, mParallel, mSwap, mIsNil, mArrToSeq, mCopyStr, mCopyStrLast, mNewString, mNewStringOfCap, mReset, @@ -560,7 +561,7 @@ type mFloat, mFloat32, mFloat64, mFloat128, mBool, mChar, mString, mCstring, mPointer, mEmptySet, mIntSetBaseType, mNil, mExpr, mStmt, mTypeDesc, - mVoidType, mPNimrodNode, mShared, mGuarded, mLock, mSpawn, + mVoidType, mPNimrodNode, mShared, mGuarded, mLock, mSpawn, mDeepCopy, mIsMainModule, mCompileDate, mCompileTime, mNimrodVersion, mNimrodMajor, mNimrodMinor, mNimrodPatch, mCpuEndian, mHostOS, mHostCPU, mAppType, mNaN, mInf, mNegInf, @@ -597,18 +598,17 @@ const mIntToStr, mInt64ToStr, mFloatToStr, mCStrToStr, mStrToStr, mEnumToStr, mAnd, mOr, mEqStr, mLeStr, mLtStr, mEqSet, mLeSet, mLtSet, mMulSet, mPlusSet, mMinusSet, mSymDiffSet, mConStrStr, mConArrArr, mConArrT, - mConTArr, mConTT, mSlice, + mConTArr, mConTT, mAppendStrCh, mAppendStrStr, mAppendSeqElem, mInRange, mInSet, mRepr, - mRand, mCopyStr, mCopyStrLast} # magics that require special semantic checking and # thus cannot be overloaded (also documented in the spec!): SpecialSemMagics* = { mDefined, mDefinedInScope, mCompiles, mLow, mHigh, mSizeOf, mIs, mOf, - mEcho, mShallowCopy, mExpandToAst} + mEcho, mShallowCopy, mExpandToAst, mParallel, mSpawn} -type +type PNode* = ref TNode TNodeSeq* = seq[PNode] PType* = ref TType @@ -873,7 +873,7 @@ const skMacro, skTemplate, skConverter, skEnumField, skLet, skStub} PersistentNodeFlags*: TNodeFlags = {nfBase2, nfBase8, nfBase16, nfDotSetter, nfDotField, - nfAllConst,nfIsRef} + nfIsRef} namePos* = 0 patternPos* = 1 # empty except for term rewriting macros genericParamsPos* = 2 @@ -886,6 +886,8 @@ const nkCallKinds* = {nkCall, nkInfix, nkPrefix, nkPostfix, nkCommand, nkCallStrLit, nkHiddenCallConv} + nkIdentKinds* = {nkIdent, nkSym, nkAccQuoted, nkOpenSymChoice, + nkClosedSymChoice} nkLiterals* = {nkCharLit..nkTripleStrLit} nkLambdaKinds* = {nkLambda, nkDo} @@ -1046,7 +1048,7 @@ proc discardSons(father: PNode) = father.sons = nil when defined(useNodeIds): - const nodeIdToDebug* = 482228 # 612794 + const nodeIdToDebug* = 310841 # 612794 #612840 # 612905 # 614635 # 614637 # 614641 # 423408 #429107 # 430443 # 441048 # 441090 # 441153 diff --git a/compiler/c2nim/cparse.nim b/compiler/c2nim/cparse.nim index 52d50ca39..2e31af528 100644 --- a/compiler/c2nim/cparse.nim +++ b/compiler/c2nim/cparse.nim @@ -19,7 +19,7 @@ import os, llstream, renderer, clex, idents, strutils, pegs, ast, astalgo, msgs, - options, strtabs + options, strtabs, hashes, algorithm type TParserFlag = enum @@ -63,6 +63,15 @@ type ERetryParsing = object of ESynch + + +proc addTypeDef(section, name, t: PNode) +proc parseStruct(p: var TParser, stmtList: PNode, isUnion: bool): PNode +proc parseStructBody(p: var TParser, stmtList: PNode, isUnion: bool, + kind: TNodeKind = nkRecList): PNode + + + proc newParserOptions*(): PParserOptions = new(result) result.prefixes = @[] @@ -682,12 +691,75 @@ proc parseField(p: var TParser, kind: TNodeKind): PNode = else: result = mangledIdent(p.tok.s, p) getTok(p, result) -proc parseStructBody(p: var TParser, isUnion: bool, +proc structPragmas(p: TParser, name: PNode, origName: string): PNode = + assert name.kind == nkIdent + result = newNodeP(nkPragmaExpr, p) + addSon(result, exportSym(p, name, origName)) + var pragmas = newNodeP(nkPragma, p) + #addSon(pragmas, newIdentNodeP("pure", p), newIdentNodeP("final", p)) + if p.options.header.len > 0: + addSon(pragmas, newIdentStrLitPair("importc", origName, p), + newIdentStrLitPair("header", p.options.header, p)) + if pragmas.len > 0: addSon(result, pragmas) + else: addSon(result, ast.emptyNode) + +proc hashPosition(p: TParser): string = + let lineInfo = parLineInfo(p) + let fileInfo = fileInfos[lineInfo.fileIndex] + result = $hash(fileInfo.shortName & "_" & $lineInfo.line & "_" & $lineInfo.col).uint + +proc parseInnerStruct(p: var TParser, stmtList: PNode, isUnion: bool): PNode = + getTok(p, nil) + if p.tok.xkind != pxCurlyLe: + parMessage(p, errUser, "Expected '{' but found '" & $(p.tok[]) & "'") + + let structName = if isUnion: "INNER_C_UNION_" & p.hashPosition + else: "INNER_C_STRUCT_" & p.hashPosition + let typeSection = newNodeP(nkTypeSection, p) + let newStruct = newNodeP(nkObjectTy, p) + var pragmas = ast.emptyNode + if isUnion: + pragmas = newNodeP(nkPragma, p) + addSon(pragmas, newIdentNodeP("union", p)) + addSon(newStruct, pragmas, ast.emptyNode) # no inheritance + result = newNodeP(nkIdent, p) + result.ident = getIdent(structName) + let struct = parseStructBody(p, stmtList, isUnion) + let defName = newNodeP(nkIdent, p) + defName.ident = getIdent(structName) + addSon(newStruct, struct) + addTypeDef(typeSection, structPragmas(p, defName, "no_name"), newStruct) + addSon(stmtList, typeSection) + +proc parseStructBody(p: var TParser, stmtList: PNode, isUnion: bool, kind: TNodeKind = nkRecList): PNode = result = newNodeP(kind, p) eat(p, pxCurlyLe, result) while p.tok.xkind notin {pxEof, pxCurlyRi}: - var baseTyp = typeAtom(p) + skipConst(p) + var baseTyp: PNode + if p.tok.xkind == pxSymbol and (p.tok.s == "struct" or p.tok.s == "union"): + let gotUnion = if p.tok.s == "union": true else: false + saveContext(p) + getTok(p, nil) + if p.tok.xkind == pxSymbol: + backtrackContext(p) + baseTyp = typeAtom(p) + else: + backtrackContext(p) + baseTyp = parseInnerStruct(p, stmtList, gotUnion) + if p.tok.xkind == pxSemiColon: + let def = newNodeP(nkIdentDefs, p) + var t = pointer(p, baseTyp) + let i = fieldIdent("ano_" & p.hashPosition, p) + t = parseTypeSuffix(p, t) + addSon(def, i, t, ast.emptyNode) + addSon(result, def) + getTok(p, nil) + continue + else: + baseTyp = typeAtom(p) + while true: var def = newNodeP(nkIdentDefs, p) var t = pointer(p, baseTyp) @@ -700,18 +772,6 @@ proc parseStructBody(p: var TParser, isUnion: bool, eat(p, pxSemicolon, lastSon(result)) eat(p, pxCurlyRi, result) -proc structPragmas(p: TParser, name: PNode, origName: string): PNode = - assert name.kind == nkIdent - result = newNodeP(nkPragmaExpr, p) - addSon(result, exportSym(p, name, origName)) - var pragmas = newNodeP(nkPragma, p) - #addSon(pragmas, newIdentNodeP("pure", p), newIdentNodeP("final", p)) - if p.options.header.len > 0: - addSon(pragmas, newIdentStrLitPair("importc", origName, p), - newIdentStrLitPair("header", p.options.header, p)) - if pragmas.len > 0: addSon(result, pragmas) - else: addSon(result, ast.emptyNode) - proc enumPragmas(p: TParser, name: PNode): PNode = result = newNodeP(nkPragmaExpr, p) addSon(result, name) @@ -722,7 +782,7 @@ proc enumPragmas(p: TParser, name: PNode): PNode = addSon(pragmas, e) addSon(result, pragmas) -proc parseStruct(p: var TParser, isUnion: bool): PNode = +proc parseStruct(p: var TParser, stmtList: PNode, isUnion: bool): PNode = result = newNodeP(nkObjectTy, p) var pragmas = ast.emptyNode if isUnion: @@ -730,7 +790,7 @@ proc parseStruct(p: var TParser, isUnion: bool): PNode = addSon(pragmas, newIdentNodeP("union", p)) addSon(result, pragmas, ast.emptyNode) # no inheritance if p.tok.xkind == pxCurlyLe: - addSon(result, parseStructBody(p, isUnion)) + addSon(result, parseStructBody(p, stmtList, isUnion)) else: addSon(result, newNodeP(nkRecList, p)) @@ -855,9 +915,28 @@ proc parseTrailingDefinedTypes(p: var TParser, section, typ: PNode) = newTyp = parseTypeSuffix(p, newTyp) addTypeDef(section, newName, newTyp) -proc enumFields(p: var TParser): PNode = +proc createConst(name, typ, val: PNode, p: TParser): PNode = + result = newNodeP(nkConstDef, p) + addSon(result, name, typ, val) + +proc exprToNumber(n: PNode not nil): tuple[succ: bool, val: BiggestInt] = + result = (false, 0.BiggestInt) + case n.kind: + of nkPrefix: + # Check for negative/positive numbers -3 or +6 + if n.sons.len == 2 and n.sons[0].kind == nkIdent and n.sons[1].kind == nkIntLit: + let pre = n.sons[0] + let num = n.sons[1] + if pre.ident.s == "-": result = (true, - num.intVal) + elif pre.ident.s == "+": result = (true, num.intVal) + else: discard + +proc enumFields(p: var TParser, constList: PNode): PNode = result = newNodeP(nkEnumTy, p) addSon(result, ast.emptyNode) # enum does not inherit from anything + var i: BiggestInt = 0 + var field: tuple[id: BiggestInt, isNumber: bool, node: PNode] + var fields = newSeq[type(field)]() while true: var e = skipIdent(p) if p.tok.xkind == pxAsgn: @@ -867,17 +946,59 @@ proc enumFields(p: var TParser): PNode = e = newNodeP(nkEnumFieldDef, p) addSon(e, a, c) skipCom(p, e) - - addSon(result, e) + if c.kind == nkIntLit: + i = c.intVal + field.isNumber = true + else: + var (success, number) = exprToNumber(c) + if success: + i = number + field.isNumber = true + else: + field.isNumber = false + else: + inc(i) + field.isNumber = true + field.id = i + field.node = e + fields.add(field) if p.tok.xkind != pxComma: break getTok(p, e) # allow trailing comma: if p.tok.xkind == pxCurlyRi: break - -proc parseTypedefStruct(p: var TParser, result: PNode, isUnion: bool) = + fields.sort do (x, y: type(field)) -> int: + cmp(x.id, y.id) + var lastId: BiggestInt + var lastIdent: PNode + for count, f in fields: + if not f.isNumber: + addSon(result, f.node) + elif f.id == lastId and count > 0: + var currentIdent: PNode + case f.node.kind: + of nkEnumFieldDef: + if f.node.sons.len > 0 and f.node.sons[0].kind == nkIdent: + currentIdent = f.node.sons[0] + else: parMessage(p, errGenerated, "Warning: When sorting enum fields an expected nkIdent was not found. Check the fields!") + of nkIdent: currentIdent = f.node + else: parMessage(p, errGenerated, "Warning: When sorting enum fields an expected nkIdent was not found. Check the fields!") + var constant = createConst( currentIdent, ast.emptyNode, lastIdent, p) + constList.addSon(constant) + else: + addSon(result, f.node) + lastId = f.id + case f.node.kind: + of nkEnumFieldDef: + if f.node.sons.len > 0 and f.node.sons[0].kind == nkIdent: + lastIdent = f.node.sons[0] + else: parMessage(p, errGenerated, "Warning: When sorting enum fields an expected nkIdent was not found. Check the fields!") + of nkIdent: lastIdent = f.node + else: parMessage(p, errGenerated, "Warning: When sorting enum fields an expected nkIdent was not found. Check the fields!") + +proc parseTypedefStruct(p: var TParser, result: PNode, stmtList: PNode, isUnion: bool) = getTok(p, result) if p.tok.xkind == pxCurlyLe: - var t = parseStruct(p, isUnion) + var t = parseStruct(p, stmtList, isUnion) var origName = p.tok.s markTypeIdent(p, nil) var name = skipIdent(p) @@ -890,7 +1011,7 @@ proc parseTypedefStruct(p: var TParser, result: PNode, isUnion: bool) = var nameOrType = skipIdent(p) case p.tok.xkind of pxCurlyLe: - var t = parseStruct(p, isUnion) + var t = parseStruct(p, stmtList, isUnion) if p.tok.xkind == pxSymbol: # typedef struct tagABC {} abc, *pabc; # --> abc is a better type name than tagABC! @@ -914,11 +1035,11 @@ proc parseTypedefStruct(p: var TParser, result: PNode, isUnion: bool) = else: expectIdent(p) -proc parseTypedefEnum(p: var TParser, result: PNode) = +proc parseTypedefEnum(p: var TParser, result, constSection: PNode) = getTok(p, result) if p.tok.xkind == pxCurlyLe: getTok(p, result) - var t = enumFields(p) + var t = enumFields(p, constSection) eat(p, pxCurlyRi, t) var origName = p.tok.s markTypeIdent(p, nil) @@ -933,7 +1054,7 @@ proc parseTypedefEnum(p: var TParser, result: PNode) = case p.tok.xkind of pxCurlyLe: getTok(p, result) - var t = enumFields(p) + var t = enumFields(p, constSection) eat(p, pxCurlyRi, t) if p.tok.xkind == pxSymbol: # typedef enum tagABC {} abc, *pabc; @@ -960,27 +1081,36 @@ proc parseTypedefEnum(p: var TParser, result: PNode) = expectIdent(p) proc parseTypeDef(p: var TParser): PNode = - result = newNodeP(nkTypeSection, p) + result = newNodeP(nkStmtList, p) + var typeSection = newNodeP(nkTypeSection, p) + var afterStatements = newNodeP(nkStmtList, p) while p.tok.xkind == pxSymbol and p.tok.s == "typedef": - getTok(p, result) + getTok(p, typeSection) inc(p.inTypeDef) expectIdent(p) case p.tok.s - of "struct": parseTypedefStruct(p, result, isUnion=false) - of "union": parseTypedefStruct(p, result, isUnion=true) - of "enum": parseTypedefEnum(p, result) + of "struct": parseTypedefStruct(p, typeSection, result, isUnion=false) + of "union": parseTypedefStruct(p, typeSection, result, isUnion=true) + of "enum": + var constSection = newNodeP(nkConstSection, p) + parseTypedefEnum(p, typeSection, constSection) + addSon(afterStatements, constSection) of "class": if pfCpp in p.options.flags: - parseTypedefStruct(p, result, isUnion=false) + parseTypedefStruct(p, typeSection, result, isUnion=false) else: var t = typeAtom(p) - otherTypeDef(p, result, t) + otherTypeDef(p, typeSection, t) else: var t = typeAtom(p) - otherTypeDef(p, result, t) + otherTypeDef(p, typeSection, t) eat(p, pxSemicolon) dec(p.inTypeDef) - + + addSon(result, typeSection) + for s in afterStatements: + addSon(result, s) + proc skipDeclarationSpecifiers(p: var TParser) = while p.tok.xkind == pxSymbol: case p.tok.s @@ -1092,10 +1222,6 @@ proc declaration(p: var TParser): PNode = result = parseVarDecl(p, baseTyp, rettyp, origName) assert result != nil -proc createConst(name, typ, val: PNode, p: TParser): PNode = - result = newNodeP(nkConstDef, p) - addSon(result, name, typ, val) - proc enumSpecifier(p: var TParser): PNode = saveContext(p) getTok(p, nil) # skip "enum" @@ -1141,12 +1267,16 @@ proc enumSpecifier(p: var TParser): PNode = closeContext(p) var name = result # create a type section containing the enum - result = newNodeP(nkTypeSection, p) + result = newNodeP(nkStmtList, p) + var tSection = newNodeP(nkTypeSection, p) var t = newNodeP(nkTypeDef, p) getTok(p, t) - var e = enumFields(p) + var constSection = newNodeP(nkConstSection, p) + var e = enumFields(p, constSection) addSon(t, exportSym(p, name, origName), ast.emptyNode, e) - addSon(result, t) + addSon(tSection, t) + addSon(result, tSection) + addSon(result, constSection) eat(p, pxCurlyRi, result) eat(p, pxSemicolon) of pxSemicolon: @@ -1608,8 +1738,8 @@ proc declarationOrStatement(p: var TParser): PNode = result = expressionStatement(p) assert result != nil -proc parseTuple(p: var TParser, isUnion: bool): PNode = - result = parseStructBody(p, isUnion, nkTupleTy) +proc parseTuple(p: var TParser, statements: PNode, isUnion: bool): PNode = + parseStructBody(p, statements, isUnion, nkTupleTy) proc parseTrailingDefinedIdents(p: var TParser, result, baseTyp: PNode) = var varSection = newNodeP(nkVarSection, p) @@ -1640,13 +1770,13 @@ proc parseStandaloneStruct(p: var TParser, isUnion: bool): PNode = if p.tok.xkind in {pxCurlyLe, pxSemiColon}: if origName.len > 0: var name = mangledIdent(origName, p) - var t = parseStruct(p, isUnion) + var t = parseStruct(p, result, isUnion) var typeSection = newNodeP(nkTypeSection, p) addTypeDef(typeSection, structPragmas(p, name, origName), t) addSon(result, typeSection) parseTrailingDefinedIdents(p, result, name) else: - var t = parseTuple(p, isUnion) + var t = parseTuple(p, result, isUnion) parseTrailingDefinedIdents(p, result, t) else: backtrackContext(p) @@ -2034,7 +2164,7 @@ proc parseStandaloneClass(p: var TParser, isStruct: bool): PNode = addTypeDef(typeSection, structPragmas(p, name, origName), t) parseTrailingDefinedIdents(p, result, name) else: - var t = parseTuple(p, isUnion=false) + var t = parseTuple(p, result, isUnion=false) parseTrailingDefinedIdents(p, result, t) else: backtrackContext(p) diff --git a/compiler/c2nim/tests/enum.h b/compiler/c2nim/tests/enum.h new file mode 100644 index 000000000..16bc59058 --- /dev/null +++ b/compiler/c2nim/tests/enum.h @@ -0,0 +1,40 @@ + +enum vehicles +{ + car = 0x10, + truck, + boat = 0x01, + ship = 1, + speedboat = 1, + bicycle = 4, + bobycar +}; + +enum +{ + red = 4, + green = 2, + blue +}; + +typedef enum food +{ + bread = 4, + toast = 4, + bun = 0x04, + cucumber = 2, + chocolate = 6 +}; + +typedef enum numbers +{ + one = 1, + two, + nten = - 10, + nnine, + four = 4, + three = + 3, + positivenine = + 9, + nfour = - 4, + negativeten = -10 +}; \ No newline at end of file diff --git a/compiler/c2nim/tests/struct_anonym.h b/compiler/c2nim/tests/struct_anonym.h new file mode 100644 index 000000000..859bfc206 --- /dev/null +++ b/compiler/c2nim/tests/struct_anonym.h @@ -0,0 +1,27 @@ + +struct normal{ + int a; + int b; +}; + +typedef struct outerStruct { + struct normal a_nomal_one; + + int a; + + struct { + union { + int b; + } a_union_in_the_struct; + + int c; + }; + + union { + int d; + + struct { + int e; + } a_struct_in_the_union; + } a_union; +}; \ No newline at end of file diff --git a/compiler/ccgcalls.nim b/compiler/ccgcalls.nim index 84c5bf419..71e23aa1d 100644 --- a/compiler/ccgcalls.nim +++ b/compiler/ccgcalls.nim @@ -77,18 +77,38 @@ proc isInCurrentFrame(p: BProc, n: PNode): bool = proc openArrayLoc(p: BProc, n: PNode): PRope = var a: TLoc - initLocExpr(p, n, a) - case skipTypes(a.t, abstractVar).kind - of tyOpenArray, tyVarargs: - result = ropef("$1, $1Len0", [rdLoc(a)]) - of tyString, tySequence: - if skipTypes(n.typ, abstractInst).kind == tyVar: - result = ropef("(*$1)->data, (*$1)->$2", [a.rdLoc, lenField()]) - else: - result = ropef("$1->data, $1->$2", [a.rdLoc, lenField()]) - of tyArray, tyArrayConstr: - result = ropef("$1, $2", [rdLoc(a), toRope(lengthOrd(a.t))]) - else: internalError("openArrayLoc: " & typeToString(a.t)) + + let q = skipConv(n) + if getMagic(q) == mSlice: + # magic: pass slice to openArray: + var b, c: TLoc + initLocExpr(p, q[1], a) + initLocExpr(p, q[2], b) + initLocExpr(p, q[3], c) + let fmt = + case skipTypes(a.t, abstractVar+{tyPtr}).kind + of tyOpenArray, tyVarargs, tyArray, tyArrayConstr: + "($1)+($2), ($3)-($2)+1" + of tyString, tySequence: + if skipTypes(n.typ, abstractInst).kind == tyVar: + "(*$1)->data+($2), ($3)-($2)+1" + else: + "$1->data+($2), ($3)-($2)+1" + else: (internalError("openArrayLoc: " & typeToString(a.t)); "") + result = ropef(fmt, [rdLoc(a), rdLoc(b), rdLoc(c)]) + else: + initLocExpr(p, n, a) + case skipTypes(a.t, abstractVar).kind + of tyOpenArray, tyVarargs: + result = ropef("$1, $1Len0", [rdLoc(a)]) + of tyString, tySequence: + if skipTypes(n.typ, abstractInst).kind == tyVar: + result = ropef("(*$1)->data, (*$1)->$2", [a.rdLoc, lenField()]) + else: + result = ropef("$1->data, $1->$2", [a.rdLoc, lenField()]) + of tyArray, tyArrayConstr: + result = ropef("$1, $2", [rdLoc(a), toRope(lengthOrd(a.t))]) + else: internalError("openArrayLoc: " & typeToString(a.t)) proc genArgStringToCString(p: BProc, n: PNode): PRope {.inline.} = diff --git a/compiler/ccgexprs.nim b/compiler/ccgexprs.nim index 49350fa9c..4698082f1 100644 --- a/compiler/ccgexprs.nim +++ b/compiler/ccgexprs.nim @@ -484,7 +484,7 @@ proc unaryArithOverflow(p: BProc, e: PNode, d: var TLoc, m: TMagic) = opr: array[mUnaryMinusI..mAbsI64, string] = [ mUnaryMinusI: "((NI$2)-($1))", mUnaryMinusI64: "-($1)", - mAbsI: "(NI$2)abs($1)", + mAbsI: "($1 > 0? ($1) : -($1))", mAbsI64: "($1 > 0? ($1) : -($1))"] var a: TLoc @@ -714,11 +714,12 @@ proc genFieldCheck(p: BProc, e: PNode, obj: PRope, field: PSym) = assert(it.sons[0].kind == nkSym) let op = it.sons[0].sym if op.magic == mNot: it = it.sons[1] - assert(it.sons[2].kind == nkSym) + let disc = it.sons[2].skipConv + assert(disc.kind == nkSym) initLoc(test, locNone, it.typ, OnStack) initLocExpr(p, it.sons[1], u) - initLoc(v, locExpr, it.sons[2].typ, OnUnknown) - v.r = ropef("$1.$2", [obj, it.sons[2].sym.loc.r]) + initLoc(v, locExpr, disc.typ, OnUnknown) + v.r = ropef("$1.$2", [obj, disc.sym.loc.r]) genInExprAux(p, it, u, v, test) let id = nodeTableTestOrSet(p.module.dataCache, newStrNode(nkStrLit, field.name.s), gBackendId) @@ -1144,6 +1145,24 @@ proc genNewFinalize(p: BProc, e: PNode) = genObjectInit(p, cpsStmts, bt, a, false) gcUsage(e) +proc genOfHelper(p: BProc; dest: PType; a: PRope): PRope = + # unfortunately 'genTypeInfo' sets tfObjHasKids as a side effect, so we + # have to call it here first: + let ti = genTypeInfo(p.module, dest) + if tfFinal in dest.flags or (p.module.objHasKidsValid and + tfObjHasKids notin dest.flags): + result = ropef("$1.m_type == $2", a, ti) + else: + discard cgsym(p.module, "TNimType") + inc p.module.labels + let cache = con("Nim_OfCheck_CACHE", p.module.labels.toRope) + appf(p.module.s[cfsVars], "static TNimType* $#[2];$n", cache) + result = rfmt(p.module, "#isObjWithCache($#.m_type, $#, $#)", a, ti, cache) + when false: + # former version: + result = rfmt(p.module, "#isObj($1.m_type, $2)", + a, genTypeInfo(p.module, dest)) + proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) = var a: TLoc initLocExpr(p, x, a) @@ -1163,11 +1182,9 @@ proc genOf(p: BProc, x: PNode, typ: PType, d: var TLoc) = globalError(x.info, errGenerated, "no 'of' operator available for pure objects") if nilCheck != nil: - r = rfmt(p.module, "(($1) && #isObj($2.m_type, $3))", - nilCheck, r, genTypeInfo(p.module, dest)) + r = rfmt(p.module, "(($1) && ($2))", nilCheck, genOfHelper(p, dest, r)) else: - r = rfmt(p.module, "#isObj($1.m_type, $2)", - r, genTypeInfo(p.module, dest)) + r = rfmt(p.module, "($1)", genOfHelper(p, dest, r)) putIntoDest(p, d, getSysType(tyBool), r) proc genOf(p: BProc, n: PNode, d: var TLoc) = @@ -1382,10 +1399,10 @@ proc genSetOp(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of mIncl: var ts = "NI" & $(size * 8) binaryStmtInExcl(p, e, d, - "$1 |=((" & ts & ")(1)<<(($2)%(sizeof(" & ts & ")*8)));$n") + "$1 |= ((" & ts & ")1)<<(($2)%(sizeof(" & ts & ")*8));$n") of mExcl: var ts = "NI" & $(size * 8) - binaryStmtInExcl(p, e, d, "$1 &= ~((" & ts & ")(1) << (($2) % (sizeof(" & + binaryStmtInExcl(p, e, d, "$1 &= ~(((" & ts & ")1) << (($2) % (sizeof(" & ts & ")*8)));$n") of mCard: if size <= 4: unaryExprChar(p, e, d, "#countBits32($1)") @@ -1623,7 +1640,7 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of mIncl, mExcl, mCard, mLtSet, mLeSet, mEqSet, mMulSet, mPlusSet, mMinusSet, mInSet: genSetOp(p, e, d, op) - of mNewString, mNewStringOfCap, mCopyStr, mCopyStrLast, mExit, mRand: + of mNewString, mNewStringOfCap, mCopyStr, mCopyStrLast, mExit: var opr = e.sons[0].sym if lfNoDecl notin opr.loc.flags: discard cgsym(p.module, opr.loc.r.ropeToStr) @@ -1636,7 +1653,10 @@ proc genMagicExpr(p: BProc, e: PNode, d: var TLoc, op: TMagic) = of mSlurp..mQuoteAst: localError(e.info, errXMustBeCompileTime, e.sons[0].sym.name.s) of mSpawn: - let n = lowerings.wrapProcForSpawn(p.module.module, e.sons[1]) + let n = lowerings.wrapProcForSpawn(p.module.module, e, e.typ, nil, nil) + expr(p, n, d) + of mParallel: + let n = semparallel.liftParallel(p.module.module, e) expr(p, n, d) else: internalError(e.info, "genMagicExpr: " & $op) diff --git a/compiler/ccgstmts.nim b/compiler/ccgstmts.nim index 311149cb3..a8cfa57e4 100644 --- a/compiler/ccgstmts.nim +++ b/compiler/ccgstmts.nim @@ -593,6 +593,7 @@ proc genStringCase(p: BProc, t: PNode, d: var TLoc) = else: # else statement: nothing to do yet # but we reserved a label, which we use later + discard linefmt(p, cpsStmts, "switch (#hashString($1) & $2) {$n", rdLoc(a), toRope(bitMask)) for j in countup(0, high(branches)): diff --git a/compiler/ccgtypes.nim b/compiler/ccgtypes.nim index f51e66897..8e762ce27 100644 --- a/compiler/ccgtypes.nim +++ b/compiler/ccgtypes.nim @@ -11,49 +11,10 @@ # ------------------------- Name Mangling -------------------------------- -proc mangleField(name: string): string = - case name[0] - of 'a'..'z': - result = "" - add(result, chr(ord(name[0]) - ord('a') + ord('A'))) - of '0'..'9', 'A'..'Z': - result = "" - add(result, name[0]) - else: result = "HEX" & toHex(ord(name[0]), 2) - for i in countup(1, len(name) - 1): - case name[i] - of 'A'..'Z': - add(result, chr(ord(name[i]) - ord('A') + ord('a'))) - of '_': - discard - of 'a'..'z', '0'..'9': - add(result, name[i]) - else: - add(result, "HEX") - add(result, toHex(ord(name[i]), 2)) - -proc mangle(name: string): string = - when false: - case name[0] - of 'a'..'z': - result = "" - add(result, chr(ord(name[0]) - ord('a') + ord('A'))) - of '0'..'9', 'A'..'Z': - result = "" - add(result, name[0]) - else: result = "HEX" & toHex(ord(name[0]), 2) - result = "" - for i in countup(0, len(name) - 1): - case name[i] - of 'A'..'Z': - add(result, chr(ord(name[i]) - ord('A') + ord('a'))) - of '_': - discard - of 'a'..'z', '0'..'9': - add(result, name[i]) - else: - add(result, "HEX") - add(result, toHex(ord(name[i]), 2)) +proc mangleField(name: string): string = + result = mangle(name) + result[0] = result[0].toUpper # Mangling makes everything lowercase, + # but some identifiers are C keywords proc isKeyword(w: PIdent): bool = # nimrod and C++ share some keywords @@ -835,6 +796,11 @@ proc genObjectInfo(m: BModule, typ: PType, name: PRope) = var tmp = getNimNode(m) genObjectFields(m, typ, typ.n, tmp) appf(m.s[cfsTypeInit3], "$1.node = &$2;$n", [name, tmp]) + var t = typ.sons[0] + while t != nil: + t = t.skipTypes(abstractInst) + t.flags.incl tfObjHasKids + t = t.sons[0] proc genTupleInfo(m: BModule, typ: PType, name: PRope) = genTypeInfoAuxBase(m, typ, name, toRope("0")) diff --git a/compiler/ccgutils.nim b/compiler/ccgutils.nim index 1d8f0158b..04983d6a4 100644 --- a/compiler/ccgutils.nim +++ b/compiler/ccgutils.nim @@ -161,6 +161,30 @@ proc makeSingleLineCString*(s: string): string = result.add(c.toCChar) result.add('\"') +proc mangle*(name: string): string = + ## Lowercases the given name and manges any non-alphanumeric characters + ## so they are represented as `HEX____`. If the name starts with a number, + ## `N` is prepended + result = "" + case name[0] + of Letters: + result.add(name[0].toLower) + of Digits: + result.add("N" & name[0]) + else: + result = "HEX" & toHex(ord(name[0]), 2) + for i in 1..(name.len-1): + let c = name[i] + case c + of 'A'..'Z': + add(result, c.toLower) + of '_': + discard + of 'a'..'z', '0'..'9': + add(result, c) + else: + add(result, "HEX" & toHex(ord(c), 2)) + proc makeLLVMString*(s: string): PRope = const MaxLineLength = 64 result = nil diff --git a/compiler/cgen.nim b/compiler/cgen.nim index 8d66d7a3b..e2f3b5ab0 100644 --- a/compiler/cgen.nim +++ b/compiler/cgen.nim @@ -14,7 +14,8 @@ import options, intsets, nversion, nimsets, msgs, crc, bitsets, idents, lists, types, ccgutils, os, times, ropes, math, passes, rodread, wordrecg, treetab, cgmeth, - rodutils, renderer, idgen, cgendata, ccgmerge, semfold, aliases, lowerings + rodutils, renderer, idgen, cgendata, ccgmerge, semfold, aliases, lowerings, + semparallel when options.hasTinyCBackend: import tccgen @@ -503,7 +504,8 @@ proc assignLocalVar(p: BProc, s: PSym) = if sfRegister in s.flags: app(decl, " register") #elif skipTypes(s.typ, abstractInst).kind in GcTypeKinds: # app(decl, " GC_GUARD") - if sfVolatile in s.flags or p.nestedTryStmts.len > 0: + if sfVolatile in s.flags or (p.nestedTryStmts.len > 0 and + gCmd != cmdCompileToCpp): app(decl, " volatile") appf(decl, " $1;$n", [s.loc.r]) else: @@ -1048,6 +1050,7 @@ proc getSomeInitName(m: PSym, suffix: string): PRope = assert m.owner.kind == skPackage if {sfSystemModule, sfMainModule} * m.flags == {}: result = m.owner.name.s.mangle.toRope + result.app "_" result.app m.name.s result.app suffix @@ -1382,6 +1385,7 @@ proc myClose(b: PPassContext, n: PNode): PNode = registerModuleToMain(m.module) if sfMainModule in m.module.flags: + m.objHasKidsValid = true var disp = generateMethodDispatchers() for i in 0..sonsLen(disp)-1: genProcAux(m, disp.sons[i].sym) genMainProc(m) diff --git a/compiler/cgendata.nim b/compiler/cgendata.nim index e7d818556..12041c55b 100644 --- a/compiler/cgendata.nim +++ b/compiler/cgendata.nim @@ -96,6 +96,7 @@ type # a frame var twice in an init proc isHeaderFile*: bool # C source file is the header file includesStringh*: bool # C source file already includes ``<string.h>`` + objHasKidsValid*: bool # whether we can rely on tfObjHasKids cfilename*: string # filename of the module (including path, # without extension) typeCache*: TIdTable # cache the generated types diff --git a/compiler/commands.nim b/compiler/commands.nim index 8339219ed..38c8dd294 100644 --- a/compiler/commands.nim +++ b/compiler/commands.nim @@ -9,10 +9,34 @@ # This module handles the parsing of command line arguments. + +# We do this here before the 'import' statement so 'defined' does not get +# confused with 'TGCMode.gcGenerational' etc. +template bootSwitch(name, expr, userString: expr): expr = + # Helper to build boot constants, for debugging you can 'echo' the else part. + const name = if expr: " " & userString else: "" + +bootSwitch(usedRelease, defined(release), "-d:release") +bootSwitch(usedGnuReadline, defined(useGnuReadline), "-d:useGnuReadline") +bootSwitch(usedNoCaas, defined(noCaas), "-d:noCaas") +bootSwitch(usedBoehm, defined(boehmgc), "--gc:boehm") +bootSwitch(usedMarkAndSweep, defined(gcmarkandsweep), "--gc:markAndSweep") +bootSwitch(usedGenerational, defined(gcgenerational), "--gc:generational") +bootSwitch(usedNoGC, defined(nogc), "--gc:none") + import os, msgs, options, nversion, condsyms, strutils, extccomp, platform, lists, wordrecg, parseutils, babelcmd, idents +# but some have deps to imported modules. Yay. +bootSwitch(usedTinyC, hasTinyCBackend, "-d:tinyc") +bootSwitch(usedAvoidTimeMachine, noTimeMachine, "-d:avoidTimeMachine") +bootSwitch(usedNativeStacktrace, + defined(nativeStackTrace) and nativeStackTraceSupported, + "-d:nativeStackTrace") +bootSwitch(usedFFI, hasFFI, "-d:useFFI") + + proc writeCommandLineUsage*() type @@ -55,6 +79,14 @@ proc writeVersionInfo(pass: TCmdLinePass) = msgWriteln(`%`(HelpMessage, [VersionAsString, platform.OS[platform.hostOS].name, CPU[platform.hostCPU].name])) + + const gitHash = gorge("git log -n 1 --format=%H") + if gitHash.strip.len == 40: + msgWriteln("git hash: " & gitHash) + + msgWriteln("active boot switches:" & usedRelease & usedAvoidTimeMachine & + usedTinyC & usedGnuReadline & usedNativeStacktrace & usedNoCaas & + usedFFI & usedBoehm & usedMarkAndSweep & usedGenerational & usedNoGC) quit(0) var diff --git a/compiler/docgen.nim b/compiler/docgen.nim index 6948c4979..4c9803401 100644 --- a/compiler/docgen.nim +++ b/compiler/docgen.nim @@ -541,8 +541,14 @@ proc genOutFile(d: PDoc): PRope = if toc != nil: toc = ropeFormatNamedVars(getConfigVar("doc.toc"), ["content"], [toc]) for i in countup(low(TSymKind), high(TSymKind)): app(code, d.section[i]) - if d.meta[metaTitle].len != 0: title = d.meta[metaTitle] - else: title = "Module " & extractFilename(changeFileExt(d.filename, "")) + + # Extract the title. Non API modules generate an entry in the index table. + if d.meta[metaTitle].len != 0: + title = d.meta[metaTitle] + setIndexTerm(d[], "", title) + else: + # Modules get an automatic title for the HTML, but no entry in the index. + title = "Module " & extractFilename(changeFileExt(d.filename, "")) let bodyname = if d.hasToc: "doc.body_toc" else: "doc.body_no_toc" content = ropeFormatNamedVars(getConfigVar(bodyname), ["title", diff --git a/compiler/evals.nim b/compiler/evals.nim deleted file mode 100644 index 151adf690..000000000 --- a/compiler/evals.nim +++ /dev/null @@ -1,1502 +0,0 @@ -# -# -# The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf -# -# See the file "copying.txt", included in this -# distribution, for details about the copyright. -# - -# This file implements the evaluator for Nimrod code. -# The evaluator is very slow, but simple. Since this -# is used mainly for evaluating macros and some other -# stuff at compile time, performance is not that -# important. - -import - strutils, magicsys, lists, options, ast, astalgo, trees, treetab, nimsets, - msgs, os, condsyms, idents, renderer, types, passes, semfold, transf, - parser, ropes, rodread, idgen, osproc, streams, evaltempl - -when hasFFI: - import evalffi - -type - PStackFrame* = ref TStackFrame - TStackFrame* = object - prc: PSym # current prc; proc that is evaluated - slots: TNodeSeq # parameters passed to the proc + locals; - # parameters come first - call: PNode - next: PStackFrame # for stacking - - TEvalMode* = enum ## reason for evaluation - emRepl, ## evaluate because in REPL mode - emConst, ## evaluate for 'const' according to spec - emOptimize, ## evaluate for optimization purposes (same as - ## emConst?) - emStatic ## evaluate for enforced compile time eval - ## ('static' context) - - TSandboxFlag* = enum ## what the evaluation engine should allow - allowCast, ## allow unsafe language feature: 'cast' - allowFFI, ## allow the FFI - allowInfiniteLoops ## allow endless loops - TSandboxFlags* = set[TSandboxFlag] - - TEvalContext* = object of passes.TPassContext - module*: PSym - tos*: PStackFrame # top of stack - lastException*: PNode - callsite: PNode # for 'callsite' magic - mode*: TEvalMode - features: TSandboxFlags - globals*: TIdNodeTable # state of global vars - getType*: proc(n: PNode): PNode {.closure.} - handleIsOperator*: proc(n: PNode): PNode {.closure.} - - PEvalContext* = ref TEvalContext - - TEvalFlag = enum - efNone, efLValue - TEvalFlags = set[TEvalFlag] - -const - evalMaxIterations = 500_000 # max iterations of all loops - evalMaxRecDepth = 10_000 # max recursion depth for evaluation - -# other idea: use a timeout! -> Wether code compiles depends on the machine -# the compiler runs on then! Bad idea! - -proc newStackFrame*(): PStackFrame = - new(result) - result.slots = @[] - -proc newEvalContext*(module: PSym, mode: TEvalMode): PEvalContext = - new(result) - result.module = module - result.mode = mode - result.features = {allowFFI} - initIdNodeTable(result.globals) - -proc pushStackFrame*(c: PEvalContext, t: PStackFrame) {.inline.} = - t.next = c.tos - c.tos = t - -proc popStackFrame*(c: PEvalContext) {.inline.} = - if c.tos != nil: c.tos = c.tos.next - else: InternalError("popStackFrame") - -proc evalMacroCall*(c: PEvalContext, n, nOrig: PNode, sym: PSym): PNode -proc evalAux(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode - -proc raiseCannotEval(c: PEvalContext, info: TLineInfo): PNode = - if defined(debug) and gVerbosity >= 3: writeStackTrace() - result = newNodeI(nkExceptBranch, info) - # creating a nkExceptBranch without sons - # means that it could not be evaluated - -proc stackTraceAux(x: PStackFrame) = - if x != nil: - stackTraceAux(x.next) - var info = if x.call != nil: x.call.info else: UnknownLineInfo() - # we now use the same format as in system/except.nim - var s = toFilename(info) - var line = toLineNumber(info) - if line > 0: - add(s, '(') - add(s, $line) - add(s, ')') - if x.prc != nil: - for k in 1..max(1, 25-s.len): add(s, ' ') - add(s, x.prc.name.s) - MsgWriteln(s) - -proc stackTrace(c: PEvalContext, info: TLineInfo, msg: TMsgKind, arg = "") = - MsgWriteln("stack trace: (most recent call last)") - stackTraceAux(c.tos) - LocalError(info, msg, arg) - -template isSpecial(n: PNode): bool = n.kind == nkExceptBranch -template bailout() {.dirty.} = - if isSpecial(result): return - -template evalX(n, flags) {.dirty.} = - result = evalAux(c, n, flags) - bailout() - -proc myreset(n: PNode) = - when defined(system.reset): - var oldInfo = n.info - reset(n[]) - n.info = oldInfo - -proc evalIf(c: PEvalContext, n: PNode): PNode = - var i = 0 - var length = sonsLen(n) - while (i < length) and (sonsLen(n.sons[i]) >= 2): - evalX(n.sons[i].sons[0], {}) - if result.kind == nkIntLit and result.intVal != 0: - return evalAux(c, n.sons[i].sons[1], {}) - inc(i) - if (i < length) and (sonsLen(n.sons[i]) < 2): - result = evalAux(c, n.sons[i].sons[0], {}) - else: - result = emptyNode - -proc evalCase(c: PEvalContext, n: PNode): PNode = - evalX(n.sons[0], {}) - var res = result - result = emptyNode - for i in countup(1, sonsLen(n) - 1): - if n.sons[i].kind == nkOfBranch: - for j in countup(0, sonsLen(n.sons[i]) - 2): - if overlap(res, n.sons[i].sons[j]): - return evalAux(c, lastSon(n.sons[i]), {}) - else: - result = evalAux(c, lastSon(n.sons[i]), {}) - -var - gWhileCounter: int # Use a counter to prevent endless loops! - # We make this counter global, because otherwise - # nested loops could make the compiler extremely slow. - gNestedEvals: int # count the recursive calls to ``evalAux`` to prevent - # endless recursion - -proc evalWhile(c: PEvalContext, n: PNode): PNode = - while true: - evalX(n.sons[0], {}) - if getOrdValue(result) == 0: - result = emptyNode; break - result = evalAux(c, n.sons[1], {}) - case result.kind - of nkBreakStmt: - if result.sons[0].kind == nkEmpty: - result = emptyNode # consume ``break`` token - # Bugfix (see tmacro2): but break in any case! - break - of nkExceptBranch, nkReturnToken: break - else: nil - dec(gWhileCounter) - if gWhileCounter <= 0: - if allowInfiniteLoops in c.features: - gWhileCounter = 0 - else: - stackTrace(c, n.info, errTooManyIterations) - break - -proc evalBlock(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {}) - if result.kind == nkBreakStmt: - if result.sons[0] != nil: - assert(result.sons[0].kind == nkSym) - if n.sons[0].kind != nkEmpty: - assert(n.sons[0].kind == nkSym) - if result.sons[0].sym.id == n.sons[0].sym.id: result = emptyNode - # blocks can only be left with an explicit label now! - #else: - # result = emptyNode # consume ``break`` token - -proc evalFinally(c: PEvalContext, n, exc: PNode): PNode = - var finallyNode = lastSon(n) - if finallyNode.kind == nkFinally: - result = evalAux(c, finallyNode, {}) - if result.kind != nkExceptBranch: result = exc - else: - result = exc - -proc evalTry(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[0], {}) - case result.kind - of nkBreakStmt, nkReturnToken: - nil - of nkExceptBranch: - if sonsLen(result) >= 1: - # creating a nkExceptBranch without sons means that it could not be - # evaluated - var exc = result - var i = 1 - var length = sonsLen(n) - while (i < length) and (n.sons[i].kind == nkExceptBranch): - var blen = sonsLen(n.sons[i]) - if blen == 1: - # general except section: - result = evalAux(c, n.sons[i].sons[0], {}) - exc = result - break - else: - for j in countup(0, blen - 2): - assert(n.sons[i].sons[j].kind == nkType) - let a = exc.typ.skipTypes(abstractPtrs) - let b = n.sons[i].sons[j].typ.skipTypes(abstractPtrs) - if a == b: - result = evalAux(c, n.sons[i].sons[blen - 1], {}) - exc = result - break - inc(i) - result = evalFinally(c, n, exc) - else: result = evalFinally(c, n, emptyNode) - -proc getNullValue(typ: PType, info: TLineInfo): PNode -proc getNullValueAux(obj: PNode, result: PNode) = - case obj.kind - of nkRecList: - for i in countup(0, sonsLen(obj) - 1): getNullValueAux(obj.sons[i], result) - of nkRecCase: - getNullValueAux(obj.sons[0], result) - for i in countup(1, sonsLen(obj) - 1): - getNullValueAux(lastSon(obj.sons[i]), result) - of nkSym: - var s = obj.sym - var p = newNodeIT(nkExprColonExpr, result.info, s.typ) - addSon(p, newSymNode(s, result.info)) - addSon(p, getNullValue(s.typ, result.info)) - addSon(result, p) - else: InternalError(result.info, "getNullValueAux") - -proc getNullValue(typ: PType, info: TLineInfo): PNode = - var t = skipTypes(typ, abstractRange-{tyTypeDesc}) - result = emptyNode - case t.kind - of tyBool, tyEnum, tyChar, tyInt..tyInt64: - result = newNodeIT(nkIntLit, info, t) - of tyUInt..tyUInt64: - result = newNodeIT(nkUIntLit, info, t) - of tyFloat..tyFloat128: - result = newNodeIt(nkFloatLit, info, t) - of tyVar, tyPointer, tyPtr, tyRef, tyCString, tySequence, tyString, tyExpr, - tyStmt, tyTypeDesc, tyStatic, tyProc: - result = newNodeIT(nkNilLit, info, t) - of tyObject: - result = newNodeIT(nkPar, info, t) - getNullValueAux(t.n, result) - # initialize inherited fields: - var base = t.sons[0] - while base != nil: - getNullValueAux(skipTypes(base, skipPtrs).n, result) - base = base.sons[0] - of tyArray, tyArrayConstr: - result = newNodeIT(nkBracket, info, t) - for i in countup(0, int(lengthOrd(t)) - 1): - addSon(result, getNullValue(elemType(t), info)) - of tyTuple: - # XXX nkExprColonExpr is out of fashion ... - result = newNodeIT(nkPar, info, t) - for i in countup(0, sonsLen(t) - 1): - var p = newNodeIT(nkExprColonExpr, info, t.sons[i]) - var field = if t.n != nil: t.n.sons[i].sym else: newSym( - skField, getIdent(":tmp" & $i), t.owner, info) - addSon(p, newSymNode(field, info)) - addSon(p, getNullValue(t.sons[i], info)) - addSon(result, p) - of tySet: - result = newNodeIT(nkCurly, info, t) - else: InternalError("getNullValue: " & $t.kind) - -proc evalVarValue(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n, {}) - if result.kind in {nkType..nkNilLit}: result = result.copyNode - -proc allocSlot(c: PStackFrame; sym: PSym): int = - result = sym.position + ord(sym.kind == skParam) - if result == 0 and sym.kind != skResult: - result = c.slots.len - if result == 0: result = 1 - sym.position = result - setLen(c.slots, max(result+1, c.slots.len)) - -proc setSlot(c: PStackFrame, sym: PSym, val: PNode) = - assert sym.owner == c.prc or sfFromGeneric in sym.flags - let idx = allocSlot(c, sym) - c.slots[idx] = val - -proc setVar(c: PEvalContext, v: PSym, n: PNode) = - if sfGlobal notin v.flags: setSlot(c.tos, v, n) - else: IdNodeTablePut(c.globals, v, n) - -proc evalVar(c: PEvalContext, n: PNode): PNode = - for i in countup(0, sonsLen(n) - 1): - let a = n.sons[i] - if a.kind == nkCommentStmt: continue - #assert(a.sons[0].kind == nkSym) can happen for transformed vars - if a.kind == nkVarTuple: - result = evalVarValue(c, a.lastSon) - if result.kind in {nkType..nkNilLit}: - result = result.copyNode - bailout() - if result.kind != nkPar: - return raiseCannotEval(c, n.info) - for i in 0 .. a.len-3: - var v = a.sons[i].sym - setVar(c, v, result.sons[i]) - else: - if a.sons[2].kind != nkEmpty: - result = evalVarValue(c, a.sons[2]) - bailout() - else: - result = getNullValue(a.sons[0].typ, a.sons[0].info) - if a.sons[0].kind == nkSym: - var v = a.sons[0].sym - setVar(c, v, result) - else: - # assign to a.sons[0]: - var x = result - evalX(a.sons[0], {}) - myreset(x) - x.kind = result.kind - x.typ = result.typ - case x.kind - of nkCharLit..nkInt64Lit: x.intVal = result.intVal - of nkFloatLit..nkFloat64Lit: x.floatVal = result.floatVal - of nkStrLit..nkTripleStrLit: x.strVal = result.strVal - of nkIdent: x.ident = result.ident - of nkSym: x.sym = result.sym - else: - if x.kind notin {nkEmpty..nkNilLit}: - discardSons(x) - for j in countup(0, sonsLen(result) - 1): addSon(x, result.sons[j]) - result = emptyNode - -proc aliasNeeded(n: PNode, flags: TEvalFlags): bool = - result = efLValue in flags or n.typ == nil or - n.typ.kind in {tyExpr, tyStatic, tyStmt, tyTypeDesc} - -proc evalVariable(c: PStackFrame, sym: PSym, flags: TEvalFlags): PNode = - # We need to return a node to the actual value, - # which can be modified. - assert sym.position != 0 or skResult == sym.kind - var x = c - while x != nil: - if sym.owner == x.prc: - result = x.slots[sym.position] - assert result != nil - if not aliasNeeded(result, flags): - result = copyTree(result) - return - x = x.next - #internalError(sym.info, "cannot eval " & sym.name.s & " " & $sym.position) - result = raiseCannotEval(nil, sym.info) - #result = emptyNode - -proc evalGlobalVar(c: PEvalContext, s: PSym, flags: TEvalFlags): PNode = - if sfCompileTime in s.flags or c.mode == emRepl or s.kind == skForVar: - result = IdNodeTableGet(c.globals, s) - if result != nil: - if not aliasNeeded(result, flags): - result = copyTree(result) - else: - when hasFFI: - if sfImportc in s.flags and allowFFI in c.features: - result = importcSymbol(s) - IdNodeTablePut(c.globals, s, result) - return result - - result = s.ast - if result == nil or result.kind == nkEmpty: - result = getNullValue(s.typ, s.info) - else: - result = evalAux(c, result, {}) - if isSpecial(result): return - IdNodeTablePut(c.globals, s, result) - else: - result = raiseCannotEval(nil, s.info) - -proc optBody(c: PEvalContext, s: PSym): PNode = - result = s.getBody - -proc evalCall(c: PEvalContext, n: PNode): PNode = - var d = newStackFrame() - d.call = n - var prc = n.sons[0] - let isClosure = prc.kind == nkClosure - setlen(d.slots, sonsLen(n) + ord(isClosure)) - if isClosure: - #debug prc - evalX(prc.sons[1], {efLValue}) - d.slots[sonsLen(n)] = result - result = evalAux(c, prc.sons[0], {}) - else: - result = evalAux(c, prc, {}) - - if isSpecial(result): return - prc = result - # bind the actual params to the local parameter of a new binding - if prc.kind != nkSym: - InternalError(n.info, "evalCall " & n.renderTree) - return - d.prc = prc.sym - if prc.sym.kind notin {skProc, skConverter, skMacro}: - InternalError(n.info, "evalCall") - return - for i in countup(1, sonsLen(n) - 1): - evalX(n.sons[i], {}) - d.slots[i] = result - if n.typ != nil: d.slots[0] = getNullValue(n.typ, n.info) - - when hasFFI: - if sfImportc in prc.sym.flags and allowFFI in c.features: - var newCall = newNodeI(nkCall, n.info, n.len) - newCall.sons[0] = evalGlobalVar(c, prc.sym, {}) - for i in 1 .. <n.len: - newCall.sons[i] = d.slots[i] - return callForeignFunction(newCall) - - pushStackFrame(c, d) - evalX(optBody(c, prc.sym), {}) - if n.typ != nil: result = d.slots[0] - popStackFrame(c) - -proc evalArrayAccess(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - evalX(n.sons[0], flags) - var x = result - evalX(n.sons[1], {}) - var idx = getOrdValue(result) - result = emptyNode - case x.kind - of nkPar: - if (idx >= 0) and (idx < sonsLen(x)): - result = x.sons[int(idx)] - if result.kind == nkExprColonExpr: result = result.sons[1] - if not aliasNeeded(result, flags): result = copyTree(result) - else: - stackTrace(c, n.info, errIndexOutOfBounds) - of nkBracket, nkMetaNode: - if (idx >= 0) and (idx < sonsLen(x)): - result = x.sons[int(idx)] - if not aliasNeeded(result, flags): result = copyTree(result) - else: - stackTrace(c, n.info, errIndexOutOfBounds) - of nkStrLit..nkTripleStrLit: - if efLValue in flags: return raiseCannotEval(c, n.info) - result = newNodeIT(nkCharLit, x.info, getSysType(tyChar)) - if (idx >= 0) and (idx < len(x.strVal)): - result.intVal = ord(x.strVal[int(idx) + 0]) - elif idx == len(x.strVal): - nil - else: - stackTrace(c, n.info, errIndexOutOfBounds) - else: stackTrace(c, n.info, errNilAccess) - -proc evalFieldAccess(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - # a real field access; proc calls have already been transformed - # XXX: field checks! - evalX(n.sons[0], flags) - var x = result - if x.kind != nkPar: return raiseCannotEval(c, n.info) - # this is performance critical: - var field = n.sons[1].sym - result = x.sons[field.position] - if result.kind == nkExprColonExpr: result = result.sons[1] - if not aliasNeeded(result, flags): result = copyTree(result) - -proc evalAsgn(c: PEvalContext, n: PNode): PNode = - var a = n.sons[0] - if a.kind == nkBracketExpr and a.sons[0].typ.kind in {tyString, tyCString}: - evalX(a.sons[0], {efLValue}) - var x = result - evalX(a.sons[1], {}) - var idx = getOrdValue(result) - - evalX(n.sons[1], {}) - if result.kind notin {nkIntLit, nkCharLit}: return c.raiseCannotEval(n.info) - - if idx >= 0 and idx < len(x.strVal): - x.strVal[int(idx)] = chr(int(result.intVal)) - else: - stackTrace(c, n.info, errIndexOutOfBounds) - else: - evalX(n.sons[0], {efLValue}) - var x = result - evalX(n.sons[1], {}) - myreset(x) - x.kind = result.kind - x.typ = result.typ - case x.kind - of nkCharLit..nkInt64Lit: x.intVal = result.intVal - of nkFloatLit..nkFloat64Lit: x.floatVal = result.floatVal - of nkStrLit..nkTripleStrLit: x.strVal = result.strVal - of nkIdent: x.ident = result.ident - of nkSym: x.sym = result.sym - else: - if x.kind notin {nkEmpty..nkNilLit}: - discardSons(x) - for i in countup(0, sonsLen(result) - 1): addSon(x, result.sons[i]) - result = emptyNode - assert result.kind == nkEmpty - -proc evalSwap(c: PEvalContext, n: PNode): PNode = - evalX(n.sons[0], {efLValue}) - var x = result - evalX(n.sons[1], {efLValue}) - if x.kind != result.kind: - stackTrace(c, n.info, errCannotInterpretNodeX, $n.kind) - else: - case x.kind - of nkCharLit..nkInt64Lit: swap(x.intVal, result.intVal) - of nkFloatLit..nkFloat64Lit: swap(x.floatVal, result.floatVal) - of nkStrLit..nkTripleStrLit: swap(x.strVal, result.strVal) - of nkIdent: swap(x.ident, result.ident) - of nkSym: swap(x.sym, result.sym) - else: - var tmpn = copyTree(x) - discardSons(x) - for i in countup(0, sonsLen(result) - 1): addSon(x, result.sons[i]) - discardSons(result) - for i in countup(0, sonsLen(tmpn) - 1): addSon(result, tmpn.sons[i]) - result = emptyNode - -proc evalSym(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - var s = n.sym - case s.kind - of skProc, skConverter, skMacro, skType: - result = n - #result = s.getBody - of skVar, skLet, skForVar, skTemp, skResult: - if sfGlobal notin s.flags: - result = evalVariable(c.tos, s, flags) - else: - result = evalGlobalVar(c, s, flags) - of skParam: - # XXX what about LValue? - if s.position + 1 <% c.tos.slots.len: - result = c.tos.slots[s.position + 1] - of skConst: result = s.ast - of skEnumField: result = newIntNodeT(s.position, n) - else: result = nil - let mask = if hasFFI and allowFFI in c.features: {sfForward} - else: {sfImportc, sfForward} - if result == nil or mask * s.flags != {}: - result = raiseCannotEval(c, n.info) - -proc evalIncDec(c: PEvalContext, n: PNode, sign: biggestInt): PNode = - evalX(n.sons[1], {efLValue}) - var a = result - evalX(n.sons[2], {}) - var b = result - case a.kind - of nkCharLit..nkInt64Lit: a.intval = a.intVal + sign * getOrdValue(b) - else: return raiseCannotEval(c, n.info) - result = emptyNode - -proc getStrValue(n: PNode): string = - case n.kind - of nkStrLit..nkTripleStrLit: result = n.strVal - else: - InternalError(n.info, "getStrValue") - result = "" - -proc evalEcho(c: PEvalContext, n: PNode): PNode = - for i in countup(1, sonsLen(n) - 1): - evalX(n.sons[i], {}) - Write(stdout, getStrValue(result)) - writeln(stdout, "") - result = emptyNode - -proc evalExit(c: PEvalContext, n: PNode): PNode = - if c.mode in {emRepl, emStatic}: - evalX(n.sons[1], {}) - Message(n.info, hintQuitCalled) - quit(int(getOrdValue(result))) - else: - result = raiseCannotEval(c, n.info) - -proc evalOr(c: PEvalContext, n: PNode): PNode = - evalX(n.sons[1], {}) - if result.intVal == 0: result = evalAux(c, n.sons[2], {}) - -proc evalAnd(c: PEvalContext, n: PNode): PNode = - evalX(n.sons[1], {}) - if result.intVal != 0: result = evalAux(c, n.sons[2], {}) - -proc evalNew(c: PEvalContext, n: PNode): PNode = - #if c.mode == emOptimize: return raiseCannotEval(c, n.info) - - # we ignore the finalizer for now and most likely forever :-) - evalX(n.sons[1], {efLValue}) - var a = result - var t = skipTypes(n.sons[1].typ, abstractVar) - if a.kind == nkEmpty: InternalError(n.info, "first parameter is empty") - myreset(a) - let u = getNullValue(t.sons[0], n.info) - a.kind = u.kind - a.typ = t - shallowCopy(a.sons, u.sons) - result = emptyNode - when false: - a.kind = nkRefTy - a.info = n.info - a.typ = t - a.sons = nil - addSon(a, getNullValue(t.sons[0], n.info)) - result = emptyNode - -proc evalDeref(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - evalX(n.sons[0], {efLValue}) - case result.kind - of nkNilLit: stackTrace(c, n.info, errNilAccess) - of nkRefTy: - # XXX efLValue? - result = result.sons[0] - else: - if skipTypes(n.sons[0].typ, abstractInst).kind != tyRef: - result = raiseCannotEval(c, n.info) - -proc evalAddr(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - evalX(n.sons[0], {efLValue}) - var a = result - var t = newType(tyPtr, c.module) - addSonSkipIntLit(t, a.typ) - result = newNodeIT(nkRefTy, n.info, t) - addSon(result, a) - -proc evalConv(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - if result.typ != nil: - var a = result - result = foldConv(n, a) - if result == nil: - # foldConv() cannot deal with everything that we want to do here: - result = a - -proc evalCast(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - if allowCast in c.features: - when hasFFI: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - InternalAssert result.typ != nil - result = fficast(result, n.typ) - else: - result = evalConv(c, n) - else: - result = raiseCannotEval(c, n.info) - -proc evalCheckedFieldAccess(c: PEvalContext, n: PNode, - flags: TEvalFlags): PNode = - result = evalAux(c, n.sons[0], flags) - -proc evalUpConv(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - result = evalAux(c, n.sons[0], flags) - if isSpecial(result): return - var dest = skipTypes(n.typ, abstractPtrs) - var src = skipTypes(result.typ, abstractPtrs) - if inheritanceDiff(src, dest) > 0: - stackTrace(c, n.info, errInvalidConversionFromTypeX, typeToString(src)) - -proc evalRangeChck(c: PEvalContext, n: PNode): PNode = - evalX(n.sons[0], {}) - var x = result - evalX(n.sons[1], {}) - var a = result - evalX(n.sons[2], {}) - var b = result - if leValueConv(a, x) and leValueConv(x, b): - result = x # a <= x and x <= b - result.typ = n.typ - else: - stackTrace(c, n.info, errGenerated, - msgKindToString(errIllegalConvFromXtoY) % [ - typeToString(n.sons[0].typ), typeToString(n.typ)]) - -proc evalConvStrToCStr(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[0], {}) - if isSpecial(result): return - result.typ = n.typ - -proc evalConvCStrToStr(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[0], {}) - if isSpecial(result): return - result.typ = n.typ - -proc evalRaise(c: PEvalContext, n: PNode): PNode = - if c.mode in {emRepl, emStatic}: - if n.sons[0].kind != nkEmpty: - result = evalAux(c, n.sons[0], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkExceptBranch, n.info, a.typ) - addSon(result, a) - c.lastException = result - elif c.lastException != nil: - result = c.lastException - else: - stackTrace(c, n.info, errExceptionAlreadyHandled) - result = newNodeIT(nkExceptBranch, n.info, nil) - addSon(result, ast.emptyNode) - else: - result = raiseCannotEval(c, n.info) - -proc evalReturn(c: PEvalContext, n: PNode): PNode = - if n.sons[0].kind != nkEmpty: - result = evalAsgn(c, n.sons[0]) - if isSpecial(result): return - result = newNodeIT(nkReturnToken, n.info, nil) - -proc evalProc(c: PEvalContext, n: PNode): PNode = - if n.sons[genericParamsPos].kind == nkEmpty: - var s = n.sons[namePos].sym - if (resultPos < sonsLen(n)) and (n.sons[resultPos].kind != nkEmpty): - var v = n.sons[resultPos].sym - result = getNullValue(v.typ, n.info) - if c.tos.slots.len == 0: setLen(c.tos.slots, 1) - c.tos.slots[0] = result - #IdNodeTablePut(c.tos.mapping, v, result) - result = evalAux(c, s.getBody, {}) - if result.kind == nkReturnToken: - result = c.tos.slots[0] - else: - result = evalAux(c, s.getBody, {}) - if result.kind == nkReturnToken: - result = emptyNode - else: - result = emptyNode - -proc evalHigh(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - case skipTypes(n.sons[1].typ, abstractVar).kind - of tyOpenArray, tySequence, tyVarargs: - result = newIntNodeT(sonsLen(result)-1, n) - of tyString: result = newIntNodeT(len(result.strVal) - 1, n) - else: InternalError(n.info, "evalHigh") - -proc evalOf(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - result = newIntNodeT(ord(inheritanceDiff(result.typ, n.sons[2].typ) >= 0), n) - -proc evalSetLengthStr(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - case a.kind - of nkStrLit..nkTripleStrLit: - var newLen = int(getOrdValue(b)) - setlen(a.strVal, newLen) - else: InternalError(n.info, "evalSetLengthStr") - result = emptyNode - -proc evalSetLengthSeq(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - if a.kind != nkBracket: - InternalError(n.info, "evalSetLengthSeq") - return - var newLen = int(getOrdValue(b)) - var oldLen = sonsLen(a) - setlen(a.sons, newLen) - for i in countup(oldLen, newLen - 1): - a.sons[i] = getNullValue(skipTypes(n.sons[1].typ, abstractVar), n.info) - result = emptyNode - -proc evalNewSeq(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - var t = skipTypes(n.sons[1].typ, abstractVar) - if a.kind == nkEmpty: InternalError(n.info, "first parameter is empty") - myreset(a) - a.kind = nkBracket - a.info = n.info - a.typ = t - a.sons = nil - var L = int(getOrdValue(b)) - newSeq(a.sons, L) - for i in countup(0, L-1): - a.sons[i] = getNullValue(t.sons[0], n.info) - result = emptyNode - -proc evalIncl(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - if not inSet(a, b): addSon(a, copyTree(b)) - result = emptyNode - -proc evalExcl(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = newNodeIT(nkCurly, n.info, n.sons[1].typ) - addSon(b, result) - var r = diffSets(a, b) - discardSons(a) - for i in countup(0, sonsLen(r) - 1): addSon(a, r.sons[i]) - result = emptyNode - -proc evalAppendStrCh(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - case a.kind - of nkStrLit..nkTripleStrLit: add(a.strVal, chr(int(getOrdValue(b)))) - else: return raiseCannotEval(c, n.info) - result = emptyNode - -proc evalConStrStr(c: PEvalContext, n: PNode): PNode = - # we cannot use ``evalOp`` for this as we can here have more than 2 arguments - var a = newNodeIT(nkStrLit, n.info, n.typ) - a.strVal = "" - for i in countup(1, sonsLen(n) - 1): - result = evalAux(c, n.sons[i], {}) - if isSpecial(result): return - a.strVal.add(getStrOrChar(result)) - result = a - -proc evalAppendStrStr(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - case a.kind - of nkStrLit..nkTripleStrLit: a.strVal = a.strVal & getStrOrChar(b) - else: return raiseCannotEval(c, n.info) - result = emptyNode - -proc evalAppendSeqElem(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - if a.kind == nkBracket: addSon(a, copyTree(b)) - else: return raiseCannotEval(c, n.info) - result = emptyNode - -proc evalRepr(c: PEvalContext, n: PNode): PNode = - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - result = newStrNodeT(renderTree(result, {renderNoComments}), n) - -proc isEmpty(n: PNode): bool = - result = n != nil and n.kind == nkEmpty - -proc evalParseExpr(c: PEvalContext, n: PNode): PNode = - var code = evalAux(c, n.sons[1], {}) - var ast = parseString(code.getStrValue, code.info.toFilename, - code.info.line.int) - if sonsLen(ast) != 1: - GlobalError(code.info, errExprExpected, "multiple statements") - result = ast.sons[0] - #result.typ = newType(tyExpr, c.module) - -proc evalParseStmt(c: PEvalContext, n: PNode): PNode = - var code = evalAux(c, n.sons[1], {}) - result = parseString(code.getStrValue, code.info.toFilename, - code.info.line.int) - #result.typ = newType(tyStmt, c.module) - -proc evalTypeTrait*(trait, operand: PNode, context: PSym): PNode = - let typ = operand.typ.skipTypes({tyTypeDesc}) - case trait.sym.name.s.normalize - of "name": - result = newStrNode(nkStrLit, typ.typeToString(preferName)) - result.typ = newType(tyString, context) - result.info = trait.info - of "arity": - result = newIntNode(nkIntLit, typ.n.len-1) - result.typ = newType(tyInt, context) - result.info = trait.info - else: - internalAssert false - -proc expectString(n: PNode) = - if n.kind notin nkStrKinds: - GlobalError(n.info, errStringLiteralExpected) - -proc evalSlurp*(e: PNode, module: PSym): PNode = - expectString(e) - result = newNodeIT(nkStrLit, e.info, getSysType(tyString)) - try: - var filename = e.strVal.FindFile - result.strVal = readFile(filename) - # we produce a fake include statement for every slurped filename, so that - # the module dependencies are accurate: - appendToModule(module, newNode(nkIncludeStmt, e.info, @[ - newStrNode(nkStrLit, filename)])) - except EIO: - result.strVal = "" - LocalError(e.info, errCannotOpenFile, e.strVal) - -proc readOutput(p: PProcess): string = - result = "" - var output = p.outputStream - discard p.waitForExit - while not output.atEnd: - result.add(output.readLine) - -proc evalStaticExec*(cmd, input: PNode): PNode = - expectString(cmd) - var p = startCmd(cmd.strVal) - if input != nil: - expectString(input) - p.inputStream.write(input.strVal) - p.inputStream.close() - result = newStrNode(nkStrLit, p.readOutput) - result.typ = getSysType(tyString) - result.info = cmd.info - -proc evalExpandToAst(c: PEvalContext, original: PNode): PNode = - var - n = original.copyTree - macroCall = n.sons[1] - expandedSym = macroCall.sons[0].sym - - for i in countup(1, macroCall.sonsLen - 1): - macroCall.sons[i] = evalAux(c, macroCall.sons[i], {}) - - case expandedSym.kind - of skTemplate: - let genSymOwner = if c.tos != nil and c.tos.prc != nil: - c.tos.prc - else: - c.module - result = evalTemplate(macroCall, expandedSym, genSymOwner) - of skMacro: - # At this point macroCall.sons[0] is nkSym node. - # To be completely compatible with normal macro invocation, - # we want to replace it with nkIdent node featuring - # the original unmangled macro name. - macroCall.sons[0] = newIdentNode(expandedSym.name, expandedSym.info) - result = evalMacroCall(c, macroCall, original, expandedSym) - else: - InternalError(macroCall.info, - "ExpandToAst: expanded symbol is no macro or template") - result = emptyNode - -proc evalMagicOrCall(c: PEvalContext, n: PNode): PNode = - var m = getMagic(n) - case m - of mNone: result = evalCall(c, n) - of mOf: result = evalOf(c, n) - of mSizeOf: result = raiseCannotEval(c, n.info) - of mHigh: result = evalHigh(c, n) - of mExit: result = evalExit(c, n) - of mNew, mNewFinalize: result = evalNew(c, n) - of mNewSeq: result = evalNewSeq(c, n) - of mSwap: result = evalSwap(c, n) - of mInc: result = evalIncDec(c, n, 1) - of ast.mDec: result = evalIncDec(c, n, - 1) - of mEcho: result = evalEcho(c, n) - of mSetLengthStr: result = evalSetLengthStr(c, n) - of mSetLengthSeq: result = evalSetLengthSeq(c, n) - of mIncl: result = evalIncl(c, n) - of mExcl: result = evalExcl(c, n) - of mAnd: result = evalAnd(c, n) - of mOr: result = evalOr(c, n) - of mAppendStrCh: result = evalAppendStrCh(c, n) - of mAppendStrStr: result = evalAppendStrStr(c, n) - of mAppendSeqElem: result = evalAppendSeqElem(c, n) - of mParseExprToAst: result = evalParseExpr(c, n) - of mParseStmtToAst: result = evalParseStmt(c, n) - of mExpandToAst: result = evalExpandToAst(c, n) - of mTypeTrait: - let operand = evalAux(c, n.sons[1], {}) - result = evalTypeTrait(n[0], operand, c.module) - of mIs: - n.sons[1] = evalAux(c, n.sons[1], {}) - result = c.handleIsOperator(n) - of mSlurp: result = evalSlurp(evalAux(c, n.sons[1], {}), c.module) - of mStaticExec: - let cmd = evalAux(c, n.sons[1], {}) - let input = if n.sonsLen == 3: evalAux(c, n.sons[2], {}) else: nil - result = evalStaticExec(cmd, input) - of mNLen: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkIntLit, n.info, n.typ) - case a.kind - of nkEmpty..nkNilLit: nil - else: result.intVal = sonsLen(a) - of mNChild: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - var k = getOrdValue(result) - if not (a.kind in {nkEmpty..nkNilLit}) and (k >= 0) and (k < sonsLen(a)): - result = a.sons[int(k)] - if result == nil: result = newNode(nkEmpty) - else: - stackTrace(c, n.info, errIndexOutOfBounds) - result = emptyNode - of mNSetChild: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - var b = result - result = evalAux(c, n.sons[3], {efLValue}) - if isSpecial(result): return - var k = getOrdValue(b) - if (k >= 0) and (k < sonsLen(a)) and not (a.kind in {nkEmpty..nkNilLit}): - a.sons[int(k)] = result - else: - stackTrace(c, n.info, errIndexOutOfBounds) - result = emptyNode - of mNAdd: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - addSon(a, result) - result = a - of mNAddMultiple: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - for i in countup(0, sonsLen(result) - 1): addSon(a, result.sons[i]) - result = a - of mNDel: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - var b = result - result = evalAux(c, n.sons[3], {efLValue}) - if isSpecial(result): return - for i in countup(0, int(getOrdValue(result)) - 1): - delSon(a, int(getOrdValue(b))) - result = emptyNode - of mNKind: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkIntLit, n.info, n.typ) - result.intVal = ord(a.kind) - of mNIntVal: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkIntLit, n.info, n.typ) - case a.kind - of nkCharLit..nkInt64Lit: result.intVal = a.intVal - else: stackTrace(c, n.info, errFieldXNotFound, "intVal") - of mNFloatVal: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkFloatLit, n.info, n.typ) - case a.kind - of nkFloatLit..nkFloat64Lit: result.floatVal = a.floatVal - else: stackTrace(c, n.info, errFieldXNotFound, "floatVal") - of mNSymbol: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - if result.kind != nkSym: stackTrace(c, n.info, errFieldXNotFound, "symbol") - of mNIdent: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - if result.kind != nkIdent: stackTrace(c, n.info, errFieldXNotFound, "ident") - of mNGetType: - var ast = evalAux(c, n.sons[1], {}) - InternalAssert c.getType != nil - result = c.getType(ast) - of mNStrVal: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkStrLit, n.info, n.typ) - case a.kind - of nkStrLit..nkTripleStrLit: result.strVal = a.strVal - else: stackTrace(c, n.info, errFieldXNotFound, "strVal") - of mNSetIntVal: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - if a.kind in {nkCharLit..nkInt64Lit} and - result.kind in {nkCharLit..nkInt64Lit}: - a.intVal = result.intVal - else: - stackTrace(c, n.info, errFieldXNotFound, "intVal") - result = emptyNode - of mNSetFloatVal: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - if a.kind in {nkFloatLit..nkFloat64Lit} and - result.kind in {nkFloatLit..nkFloat64Lit}: - a.floatVal = result.floatVal - else: - stackTrace(c, n.info, errFieldXNotFound, "floatVal") - result = emptyNode - of mNSetSymbol: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - if a.kind == nkSym and result.kind == nkSym: - a.sym = result.sym - else: - stackTrace(c, n.info, errFieldXNotFound, "symbol") - result = emptyNode - of mNSetIdent: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - if a.kind == nkIdent and result.kind == nkIdent: - a.ident = result.ident - else: - stackTrace(c, n.info, errFieldXNotFound, "ident") - result = emptyNode - of mNSetType: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - InternalAssert result.kind == nkSym and result.sym.kind == skType - a.typ = result.sym.typ - result = emptyNode - of mNSetStrVal: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - - if a.kind in {nkStrLit..nkTripleStrLit} and - result.kind in {nkStrLit..nkTripleStrLit}: - a.strVal = result.strVal - else: stackTrace(c, n.info, errFieldXNotFound, "strVal") - result = emptyNode - of mNNewNimNode: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var k = getOrdValue(result) - result = evalAux(c, n.sons[2], {efLValue}) - if result.kind == nkExceptBranch: return - var a = result - if k < 0 or k > ord(high(TNodeKind)): - internalError(n.info, "request to create a NimNode with invalid kind") - result = newNodeI(TNodeKind(int(k)), - if a.kind == nkNilLit: n.info else: a.info) - of mNCopyNimNode: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - result = copyNode(result) - of mNCopyNimTree: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - result = copyTree(result) - of mNBindSym: - # trivial implementation: - result = n.sons[1] - of mNGenSym: - evalX(n.sons[1], {efLValue}) - let k = getOrdValue(result) - evalX(n.sons[2], {efLValue}) - let b = result - let name = if b.strVal.len == 0: ":tmp" else: b.strVal - if k < 0 or k > ord(high(TSymKind)): - internalError(n.info, "request to create a symbol with invalid kind") - result = newSymNode(newSym(k.TSymKind, name.getIdent, c.module, n.info)) - incl(result.sym.flags, sfGenSym) - of mStrToIdent: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - if not (result.kind in {nkStrLit..nkTripleStrLit}): - stackTrace(c, n.info, errFieldXNotFound, "strVal") - return - var a = result - result = newNodeIT(nkIdent, n.info, n.typ) - result.ident = getIdent(a.strVal) - of mIdentToStr: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkStrLit, n.info, n.typ) - if a.kind == nkSym: - result.strVal = a.sym.name.s - else: - if a.kind != nkIdent: InternalError(n.info, "no ident node") - result.strVal = a.ident.s - of mEqIdent: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - var b = result - result = newNodeIT(nkIntLit, n.info, n.typ) - if (a.kind == nkIdent) and (b.kind == nkIdent): - if a.ident.id == b.ident.id: result.intVal = 1 - of mEqNimrodNode: - result = evalAux(c, n.sons[1], {efLValue}) - if isSpecial(result): return - var a = result - result = evalAux(c, n.sons[2], {efLValue}) - if isSpecial(result): return - var b = result - result = newNodeIT(nkIntLit, n.info, n.typ) - if (a == b) or - (b.kind in {nkNilLit, nkEmpty}) and (a.kind in {nkNilLit, nkEmpty}): - result.intVal = 1 - of mNLineInfo: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - result = newStrNodeT(result.info.toFileLineCol, n) - of mNHint: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - Message(n.info, hintUser, getStrValue(result)) - result = emptyNode - of mNWarning: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - Message(n.info, warnUser, getStrValue(result)) - result = emptyNode - of mNError: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - stackTrace(c, n.info, errUser, getStrValue(result)) - result = emptyNode - of mConStrStr: - result = evalConStrStr(c, n) - of mRepr: - result = evalRepr(c, n) - of mNewString: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkStrLit, n.info, n.typ) - result.strVal = newString(int(getOrdValue(a))) - of mNewStringOfCap: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - result = newNodeIT(nkStrLit, n.info, n.typ) - result.strVal = newString(0) - of mNCallSite: - if c.callsite != nil: result = c.callsite - else: stackTrace(c, n.info, errFieldXNotFound, "callsite") - else: - result = evalAux(c, n.sons[1], {}) - if isSpecial(result): return - var a = result - var b: PNode = nil - var cc: PNode = nil - if sonsLen(n) > 2: - result = evalAux(c, n.sons[2], {}) - if isSpecial(result): return - b = result - if sonsLen(n) > 3: - result = evalAux(c, n.sons[3], {}) - if isSpecial(result): return - cc = result - if isEmpty(a) or isEmpty(b) or isEmpty(cc): result = emptyNode - else: result = evalOp(m, n, a, b, cc) - -proc evalAux(c: PEvalContext, n: PNode, flags: TEvalFlags): PNode = - result = emptyNode - dec(gNestedEvals) - if gNestedEvals <= 0: stackTrace(c, n.info, errTooManyIterations) - case n.kind - of nkSym: result = evalSym(c, n, flags) - of nkType..nkNilLit, nkTypeOfExpr: - # nkStrLit is VERY common in the traces, so we should avoid - # the 'copyNode' here. - result = n #.copyNode - of nkAsgn, nkFastAsgn: result = evalAsgn(c, n) - of nkCommand..nkHiddenCallConv: - result = evalMagicOrCall(c, n) - of nkDotExpr: result = evalFieldAccess(c, n, flags) - of nkBracketExpr: - result = evalArrayAccess(c, n, flags) - of nkDerefExpr, nkHiddenDeref: result = evalDeref(c, n, flags) - of nkAddr, nkHiddenAddr: result = evalAddr(c, n, flags) - of nkHiddenStdConv, nkHiddenSubConv, nkConv: result = evalConv(c, n) - of nkCurly, nkBracket, nkRange: - # flags need to be passed here for mNAddMultiple :-( - # XXX this is not correct in every case! - var a = copyNode(n) - for i in countup(0, sonsLen(n) - 1): - result = evalAux(c, n.sons[i], flags) - if isSpecial(result): return - addSon(a, result) - result = a - of nkPar, nkClosure: - var a = copyTree(n) - for i in countup(0, sonsLen(n) - 1): - var it = n.sons[i] - if it.kind == nkExprColonExpr: - result = evalAux(c, it.sons[1], flags) - if isSpecial(result): return - a.sons[i].sons[1] = result - else: - result = evalAux(c, it, flags) - if isSpecial(result): return - a.sons[i] = result - result = a - of nkObjConstr: - let t = skipTypes(n.typ, abstractInst) - var a: PNode - if t.kind == tyRef: - result = newNodeIT(nkRefTy, n.info, t) - a = getNullValue(t.sons[0], n.info) - addSon(result, a) - else: - a = getNullValue(t, n.info) - result = a - for i in countup(1, sonsLen(n) - 1): - let it = n.sons[i] - if it.kind == nkExprColonExpr: - let value = evalAux(c, it.sons[1], flags) - if isSpecial(value): return value - a.sons[it.sons[0].sym.position] = value - else: return raiseCannotEval(c, n.info) - of nkWhenStmt, nkIfStmt, nkIfExpr: result = evalIf(c, n) - of nkWhileStmt: result = evalWhile(c, n) - of nkCaseStmt: result = evalCase(c, n) - of nkVarSection, nkLetSection: result = evalVar(c, n) - of nkTryStmt: result = evalTry(c, n) - of nkRaiseStmt: result = evalRaise(c, n) - of nkReturnStmt: result = evalReturn(c, n) - of nkBreakStmt, nkReturnToken: result = n - of nkBlockExpr, nkBlockStmt: result = evalBlock(c, n) - of nkDiscardStmt: result = evalAux(c, n.sons[0], {}) - of nkCheckedFieldExpr: result = evalCheckedFieldAccess(c, n, flags) - of nkObjDownConv: result = evalAux(c, n.sons[0], flags) - of nkObjUpConv: result = evalUpConv(c, n, flags) - of nkChckRangeF, nkChckRange64, nkChckRange: result = evalRangeChck(c, n) - of nkStringToCString: result = evalConvStrToCStr(c, n) - of nkCStringToString: result = evalConvCStrToStr(c, n) - of nkStmtListExpr, nkStmtList: - for i in countup(0, sonsLen(n) - 1): - result = evalAux(c, n.sons[i], flags) - case result.kind - of nkExceptBranch, nkReturnToken, nkBreakStmt: break - else: nil - of nkProcDef, nkMethodDef, nkMacroDef, nkCommentStmt, nkPragma, - nkTypeSection, nkTemplateDef, nkConstSection, nkIteratorDef, - nkConverterDef, nkIncludeStmt, nkImportStmt, nkFromStmt: - nil - of nkMetaNode: - result = copyTree(n.sons[0]) - result.typ = n.typ - of nkPragmaBlock: - result = evalAux(c, n.sons[1], flags) - of nkCast: - result = evalCast(c, n, flags) - of nkIdentDefs, nkYieldStmt, nkAsmStmt, nkForStmt, nkPragmaExpr, - nkLambdaKinds, nkContinueStmt, nkIdent, nkParForStmt, nkBindStmt, - nkClosedSymChoice, nkOpenSymChoice: - result = raiseCannotEval(c, n.info) - of nkRefTy: - result = evalAux(c, n.sons[0], flags) - of nkEmpty: - # nkEmpty occurs once in each trace that I looked at - result = n - else: InternalError(n.info, "evalAux: " & $n.kind) - if result == nil: - InternalError(n.info, "evalAux: returned nil " & $n.kind) - inc(gNestedEvals) - -proc tryEval(c: PEvalContext, n: PNode): PNode = - #internalAssert nfTransf in n.flags - var n = transformExpr(c.module, n) - gWhileCounter = evalMaxIterations - gNestedEvals = evalMaxRecDepth - result = evalAux(c, n, {}) - -proc eval*(c: PEvalContext, n: PNode): PNode = - ## eval never returns nil! This simplifies the code a lot and - ## makes it faster too. - result = tryEval(c, n) - if result.kind == nkExceptBranch: - if sonsLen(result) >= 1: - stackTrace(c, n.info, errUnhandledExceptionX, typeToString(result.typ)) - else: - stackTrace(c, result.info, errCannotInterpretNodeX, renderTree(n)) - -proc evalConstExprAux*(p: PEvalContext, module, prc: PSym, e: PNode): PNode = - var s = newStackFrame() - s.call = e - s.prc = prc - pushStackFrame(p, s) - result = tryEval(p, e) - if result != nil and result.kind == nkExceptBranch: result = nil - popStackFrame(p) - -proc setupMacroParam(x: PNode): PNode = - result = x - if result.kind in {nkHiddenSubConv, nkHiddenStdConv}: result = result.sons[1] - -proc evalMacroCall(c: PEvalContext, n, nOrig: PNode, sym: PSym): PNode = - # XXX GlobalError() is ugly here, but I don't know a better solution for now - inc(evalTemplateCounter) - if evalTemplateCounter > 100: - GlobalError(n.info, errTemplateInstantiationTooNested) - - c.callsite = nOrig - var s = newStackFrame() - s.call = n - s.prc = sym - var L = n.safeLen - if L == 0: L = 1 - setlen(s.slots, L) - # return value: - s.slots[0] = newNodeIT(nkNilLit, n.info, sym.typ.sons[0]) - # setup parameters: - for i in 1 .. < L: s.slots[i] = setupMacroParam(n.sons[i]) - pushStackFrame(c, s) - discard eval(c, optBody(c, sym)) - result = s.slots[0] - popStackFrame(c) - if cyclicTree(result): GlobalError(n.info, errCyclicTree) - dec(evalTemplateCounter) - c.callsite = nil - -proc myOpen(module: PSym): PPassContext = - var c = newEvalContext(module, emRepl) - c.features = {allowCast, allowFFI, allowInfiniteLoops} - pushStackFrame(c, newStackFrame()) - result = c - -var oldErrorCount: int - -proc myProcess(c: PPassContext, n: PNode): PNode = - # don't eval errornous code: - if oldErrorCount == msgs.gErrorCounter: - result = eval(PEvalContext(c), n) - else: - result = n - oldErrorCount = msgs.gErrorCounter - -const evalPass* = makePass(myOpen, nil, myProcess, myProcess) - diff --git a/compiler/guards.nim b/compiler/guards.nim index f475f5068..4cf06fe02 100644 --- a/compiler/guards.nim +++ b/compiler/guards.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -9,7 +9,8 @@ ## This module implements the 'implies' relation for guards. -import ast, astalgo, msgs, magicsys, nimsets, trees, types, renderer, idents +import ast, astalgo, msgs, magicsys, nimsets, trees, types, renderer, idents, + saturate const someEq = {mEqI, mEqI64, mEqF64, mEqEnum, mEqCh, mEqB, mEqRef, mEqProc, @@ -25,6 +26,17 @@ const someIn = {mInRange, mInSet} + someHigh = {mHigh} + # we don't list unsigned here because wrap around semantics suck for + # proving anything: + someAdd = {mAddI, mAddI64, mAddF64, mSucc} + someSub = {mSubI, mSubI64, mSubF64, mPred} + someMul = {mMulI, mMulI64, mMulF64} + someDiv = {mDivI, mDivI64, mDivF64} + someMod = {mModI, mModI64} + someMax = {mMaxI, mMaxI64, mMaxF64} + someMin = {mMinI, mMinI64, mMinF64} + proc isValue(n: PNode): bool = n.kind in {nkCharLit..nkNilLit} proc isLocation(n: PNode): bool = not n.isValue @@ -69,19 +81,24 @@ proc isLetLocation(m: PNode, isApprox: bool): bool = proc interestingCaseExpr*(m: PNode): bool = isLetLocation(m, true) -proc getMagicOp(name: string, m: TMagic): PSym = +proc createMagic*(name: string, m: TMagic): PSym = result = newSym(skProc, getIdent(name), nil, unknownLineInfo()) result.magic = m let - opLe = getMagicOp("<=", mLeI) - opLt = getMagicOp("<", mLtI) - opAnd = getMagicOp("and", mAnd) - opOr = getMagicOp("or", mOr) - opNot = getMagicOp("not", mNot) - opIsNil = getMagicOp("isnil", mIsNil) - opContains = getMagicOp("contains", mInSet) - opEq = getMagicOp("==", mEqI) + opLe = createMagic("<=", mLeI) + opLt = createMagic("<", mLtI) + opAnd = createMagic("and", mAnd) + opOr = createMagic("or", mOr) + opNot = createMagic("not", mNot) + opIsNil = createMagic("isnil", mIsNil) + opContains = createMagic("contains", mInSet) + opEq = createMagic("==", mEqI) + opAdd = createMagic("+", mAddI) + opSub = createMagic("-", mSubI) + opMul = createMagic("*", mMulI) + opDiv = createMagic("div", mDivI) + opLen = createMagic("len", mLengthSeq) proc swapArgs(fact: PNode, newOp: PSym): PNode = result = newNodeI(nkCall, fact.info, 3) @@ -137,17 +154,141 @@ proc neg(n: PNode): PNode = result.sons[0] = newSymNode(opNot) result.sons[1] = n -proc buildIsNil(arg: PNode): PNode = - result = newNodeI(nkCall, arg.info, 2) - result.sons[0] = newSymNode(opIsNil) - result.sons[1] = arg +proc buildCall(op: PSym; a: PNode): PNode = + result = newNodeI(nkCall, a.info, 2) + result.sons[0] = newSymNode(op) + result.sons[1] = a + +proc buildCall(op: PSym; a, b: PNode): PNode = + result = newNodeI(nkInfix, a.info, 3) + result.sons[0] = newSymNode(op) + result.sons[1] = a + result.sons[2] = b + +proc `|+|`(a, b: PNode): PNode = + result = copyNode(a) + if a.kind in {nkCharLit..nkUInt64Lit}: result.intVal = a.intVal |+| b.intVal + else: result.floatVal = a.floatVal + b.floatVal + +proc `|*|`(a, b: PNode): PNode = + result = copyNode(a) + if a.kind in {nkCharLit..nkUInt64Lit}: result.intVal = a.intVal |*| b.intVal + else: result.floatVal = a.floatVal * b.floatVal + +proc negate(a, b, res: PNode): PNode = + if b.kind in {nkCharLit..nkUInt64Lit} and b.intVal != low(BiggestInt): + var b = copyNode(b) + b.intVal = -b.intVal + if a.kind in {nkCharLit..nkUInt64Lit}: + b.intVal = b.intVal |+| a.intVal + result = b + else: + result = buildCall(opAdd, a, b) + elif b.kind in {nkFloatLit..nkFloat64Lit}: + var b = copyNode(b) + b.floatVal = -b.floatVal + result = buildCall(opAdd, a, b) + else: + result = res + +proc zero(): PNode = nkIntLit.newIntNode(0) +proc one(): PNode = nkIntLit.newIntNode(1) +proc minusOne(): PNode = nkIntLit.newIntNode(-1) + +proc lowBound*(x: PNode): PNode = + result = nkIntLit.newIntNode(firstOrd(x.typ)) + result.info = x.info + +proc highBound*(x: PNode): PNode = + result = if x.typ.skipTypes(abstractInst).kind == tyArray: + nkIntLit.newIntNode(lastOrd(x.typ)) + else: + opAdd.buildCall(opLen.buildCall(x), minusOne()) + result.info = x.info + +proc reassociation(n: PNode): PNode = + result = n + # (foo+5)+5 --> foo+10; same for '*' + case result.getMagic + of someAdd: + if result[2].isValue and + result[1].getMagic in someAdd and result[1][2].isValue: + result = opAdd.buildCall(result[1][1], result[1][2] |+| result[2]) + of someMul: + if result[2].isValue and + result[1].getMagic in someMul and result[1][2].isValue: + result = opAdd.buildCall(result[1][1], result[1][2] |*| result[2]) + else: discard + +proc canon*(n: PNode): PNode = + # XXX for now only the new code in 'semparallel' uses this + if n.safeLen >= 1: + result = shallowCopy(n) + for i in 0 .. < n.len: + result.sons[i] = canon(n.sons[i]) + else: + result = n + case result.getMagic + of someEq, someAdd, someMul, someMin, someMax: + # these are symmetric; put value as last: + if result.sons[1].isValue and not result.sons[2].isValue: + result = swapArgs(result, result.sons[0].sym) + # (4 + foo) + 2 --> (foo + 4) + 2 + of someHigh: + # high == len+(-1) + result = opAdd.buildCall(opLen.buildCall(result[1]), minusOne()) + of mUnaryMinusI, mUnaryMinusI64: + result = buildCall(opAdd, result[1], newIntNode(nkIntLit, -1)) + of someSub: + # x - 4 --> x + (-4) + result = negate(result[1], result[2], result) + of someLen: + result.sons[0] = opLen.newSymNode + else: discard + + result = skipConv(result) + result = reassociation(result) + # most important rule: (x-4) < a.len --> x < a.len+4 + case result.getMagic + of someLe, someLt: + let x = result[1] + let y = result[2] + if x.kind in nkCallKinds and x.len == 3 and x[2].isValue and + isLetLocation(x[1], true): + case x.getMagic + of someSub: + result = buildCall(result[0].sym, x[1], + reassociation(opAdd.buildCall(y, x[2]))) + of someAdd: + # Rule A: + let plus = negate(y, x[2], nil).reassociation + if plus != nil: result = buildCall(result[0].sym, x[1], plus) + else: discard + elif y.kind in nkCallKinds and y.len == 3 and y[2].isValue and + isLetLocation(y[1], true): + # a.len < x-3 + case y.getMagic + of someSub: + result = buildCall(result[0].sym, y[1], + reassociation(opAdd.buildCall(x, y[2]))) + of someAdd: + let plus = negate(x, y[2], nil).reassociation + # ensure that Rule A will not trigger afterwards with the + # additional 'not isLetLocation' constraint: + if plus != nil and not isLetLocation(x, true): + result = buildCall(result[0].sym, plus, y[1]) + else: discard + else: discard + +proc `+@`*(a: PNode; b: BiggestInt): PNode = + canon(if b != 0: opAdd.buildCall(a, nkIntLit.newIntNode(b)) else: a) proc usefulFact(n: PNode): PNode = case n.getMagic of someEq: if skipConv(n.sons[2]).kind == nkNilLit and ( isLetLocation(n.sons[1], false) or isVar(n.sons[1])): - result = buildIsNil(n.sons[1]) + result = opIsNil.buildCall(n.sons[1]) else: if isLetLocation(n.sons[1], true) or isLetLocation(n.sons[2], true): # XXX algebraic simplifications! 'i-1 < a.len' --> 'i < a.len+1' @@ -217,7 +358,7 @@ proc addFactNeg*(m: var TModel, n: PNode) = let n = n.neg if n != nil: addFact(m, n) -proc sameTree(a, b: PNode): bool = +proc sameTree*(a, b: PNode): bool = result = false if a == b: result = true @@ -484,7 +625,7 @@ proc factImplies(fact, prop: PNode): TImplication = # == not a or not b == not (a and b) let arg = fact.sons[1] case arg.getMagic - of mIsNil: + of mIsNil, mEqRef: return ~factImplies(arg, prop) of mAnd: # not (a and b) means not a or not b: @@ -519,7 +660,144 @@ proc doesImply*(facts: TModel, prop: PNode): TImplication = if result != impUnknown: return proc impliesNotNil*(facts: TModel, arg: PNode): TImplication = - result = doesImply(facts, buildIsNil(arg).neg) + result = doesImply(facts, opIsNil.buildCall(arg).neg) + +proc simpleSlice*(a, b: PNode): BiggestInt = + # returns 'c' if a..b matches (i+c)..(i+c), -1 otherwise. (i)..(i) is matched + # as if it is (i+0)..(i+0). + if guards.sameTree(a, b): + if a.getMagic in someAdd and a[2].kind in {nkCharLit..nkUInt64Lit}: + result = a[2].intVal + else: + result = 0 + else: + result = -1 + +proc pleViaModel(model: TModel; aa, bb: PNode): TImplication + +proc ple(m: TModel; a, b: PNode): TImplication = + template `<=?`(a,b): expr = ple(m,a,b) == impYes + # 0 <= 3 + if a.isValue and b.isValue: + return if leValue(a, b): impYes else: impNo + + # use type information too: x <= 4 iff high(x) <= 4 + if b.isValue and a.typ != nil and a.typ.isOrdinalType: + if lastOrd(a.typ) <= b.intVal: return impYes + # 3 <= x iff low(x) <= 3 + if a.isValue and b.typ != nil and b.typ.isOrdinalType: + if firstOrd(b.typ) <= a.intVal: return impYes + + # x <= x + if sameTree(a, b): return impYes + + # 0 <= x.len + if b.getMagic in someLen and a.isValue: + if a.intVal <= 0: return impYes + + # x <= y+c if 0 <= c and x <= y + if b.getMagic in someAdd and zero() <=? b[2] and a <=? b[1]: return impYes + + # x+c <= y if c <= 0 and x <= y + if a.getMagic in someAdd and a[2] <=? zero() and a[1] <=? b: return impYes + + # x <= y*c if 1 <= c and x <= y and 0 <= y + if b.getMagic in someMul: + if a <=? b[1] and one() <=? b[2] and zero() <=? b[1]: return impYes + + # x div c <= y if 1 <= c and 0 <= y and x <= y: + if a.getMagic in someDiv: + if one() <=? a[2] and zero() <=? b and a[1] <=? b: return impYes + + # slightly subtle: + # x <= max(y, z) iff x <= y or x <= z + # note that 'x <= max(x, z)' is a special case of the above rule + if b.getMagic in someMax: + if a <=? b[1] or a <=? b[2]: return impYes + + # min(x, y) <= z iff x <= z or y <= z + if a.getMagic in someMin: + if a[1] <=? b or a[2] <=? b: return impYes + + # use the knowledge base: + return pleViaModel(m, a, b) + #return doesImply(m, opLe.buildCall(a, b)) + +type TReplacements = seq[tuple[a,b: PNode]] + +proc replaceSubTree(n, x, by: PNode): PNode = + if sameTree(n, x): + result = by + elif hasSubTree(n, x): + result = shallowCopy(n) + for i in 0 .. safeLen(n)-1: + result.sons[i] = replaceSubTree(n.sons[i], x, by) + else: + result = n + +proc applyReplacements(n: PNode; rep: TReplacements): PNode = + result = n + for x in rep: result = result.replaceSubTree(x.a, x.b) + +proc pleViaModelRec(m: var TModel; a, b: PNode): TImplication = + # now check for inferrable facts: a <= b and b <= c implies a <= c + for i in 0..m.high: + let fact = m[i] + if fact != nil and fact.getMagic in someLe: + # x <= y implies a <= b if a <= x and y <= b + let x = fact[1] + let y = fact[2] + # mark as used: + m[i] = nil + if ple(m, a, x) == impYes: + if ple(m, y, b) == impYes: return impYes + #if pleViaModelRec(m, y, b): return impYes + # fact: 16 <= i + # x y + # question: i <= 15? no! + result = impliesLe(fact, a, b) + if result != impUnknown: return result + if sameTree(y, a): + result = ple(m, x, b) + if result != impUnknown: return result + +proc pleViaModel(model: TModel; aa, bb: PNode): TImplication = + # compute replacements: + var replacements: TReplacements = @[] + for fact in model: + if fact != nil and fact.getMagic in someEq: + let a = fact[1] + let b = fact[2] + if a.kind == nkSym: replacements.add((a,b)) + else: replacements.add((b,a)) + var m: TModel + var a = aa + var b = bb + if replacements.len > 0: + m = @[] + # make the other facts consistent: + for fact in model: + if fact != nil and fact.getMagic notin someEq: + # XXX 'canon' should not be necessary here, but it is + m.add applyReplacements(fact, replacements).canon + a = applyReplacements(aa, replacements) + b = applyReplacements(bb, replacements) + else: + # we have to make a copy here, because the model will be modified: + m = model + result = pleViaModelRec(m, a, b) + +proc proveLe*(m: TModel; a, b: PNode): TImplication = + let x = canon(opLe.buildCall(a, b)) + #echo "ROOT ", renderTree(x[1]), " <=? ", renderTree(x[2]) + result = ple(m, x[1], x[2]) + if result == impUnknown: + # try an alternative: a <= b iff not (b < a) iff not (b+1 <= a): + let y = canon(opLe.buildCall(opAdd.buildCall(b, one()), a)) + result = ~ple(m, y[1], y[2]) + +proc addFactLe*(m: var TModel; a, b: PNode) = + m.add canon(opLe.buildCall(a, b)) proc settype(n: PNode): PType = result = newType(tySet, n.typ.owner) diff --git a/compiler/importer.nim b/compiler/importer.nim index 7a73f2bbf..b4cae017e 100644 --- a/compiler/importer.nim +++ b/compiler/importer.nim @@ -93,7 +93,7 @@ proc rawImportSymbol(c: PContext, s: PSym) = if hasPattern(s): addPattern(c, s) proc importSymbol(c: PContext, n: PNode, fromMod: PSym) = - let ident = lookups.considerAcc(n) + let ident = lookups.considerQuotedIdent(n) let s = strTableGet(fromMod.tab, ident) if s == nil: localError(n.info, errUndeclaredIdentifier, ident.s) @@ -193,7 +193,7 @@ proc evalImportExcept*(c: PContext, n: PNode): PNode = addDecl(c, m) # add symbol to symbol table of module var exceptSet = initIntSet() for i in countup(1, sonsLen(n) - 1): - let ident = lookups.considerAcc(n.sons[i]) + let ident = lookups.considerQuotedIdent(n.sons[i]) exceptSet.incl(ident.id) importAllSymbolsExcept(c, m, exceptSet) importForwarded(c, m.ast, exceptSet) diff --git a/compiler/jsgen.nim b/compiler/jsgen.nim index 373a11e9a..6687e2e8e 100644 --- a/compiler/jsgen.nim +++ b/compiler/jsgen.nim @@ -136,18 +136,6 @@ proc mapType(typ: PType): TJSTypeKind = of tyProc: result = etyProc of tyCString: result = etyString -proc mangle(name: string): string = - result = "" - for i in countup(0, len(name) - 1): - case name[i] - of 'A'..'Z': - add(result, chr(ord(name[i]) - ord('A') + ord('a'))) - of '_': - discard - of 'a'..'z', '0'..'9': - add(result, name[i]) - else: add(result, 'X' & toHex(ord(name[i]), 2)) - proc mangleName(s: PSym): PRope = result = s.loc.r if result == nil: diff --git a/compiler/lexer.nim b/compiler/lexer.nim index 2bfd8d1eb..0e4dfc2ac 100644 --- a/compiler/lexer.nim +++ b/compiler/lexer.nim @@ -347,7 +347,7 @@ proc getNumber(L: var TLexer): TToken = result.base = base2 while true: case L.buf[pos] - of 'A'..'Z', 'a'..'z', '2'..'9', '.': + of '2'..'9', '.': lexMessage(L, errInvalidNumber, result.literal) inc(pos) of '_': @@ -363,7 +363,7 @@ proc getNumber(L: var TLexer): TToken = result.base = base8 while true: case L.buf[pos] - of 'A'..'Z', 'a'..'z', '8'..'9', '.': + of '8'..'9', '.': lexMessage(L, errInvalidNumber, result.literal) inc(pos) of '_': @@ -377,25 +377,22 @@ proc getNumber(L: var TLexer): TToken = else: break of 'O': lexMessage(L, errInvalidNumber, result.literal) - of 'x', 'X': + of 'x', 'X': result.base = base16 - while true: + while true: case L.buf[pos] - of 'G'..'Z', 'g'..'z': - lexMessage(L, errInvalidNumber, result.literal) - inc(pos) - of '_': - if L.buf[pos+1] notin {'0'..'9', 'a'..'f', 'A'..'F'}: + of '_': + if L.buf[pos+1] notin {'0'..'9', 'a'..'f', 'A'..'F'}: lexMessage(L, errInvalidToken, "_") break inc(pos) - of '0'..'9': + of '0'..'9': xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('0')) inc(pos) - of 'a'..'f': + of 'a'..'f': xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('a') + 10) inc(pos) - of 'A'..'F': + of 'A'..'F': xi = `shl`(xi, 4) or (ord(L.buf[pos]) - ord('A') + 10) inc(pos) else: break @@ -424,8 +421,14 @@ proc getNumber(L: var TLexer): TToken = if (result.iNumber < low(int32)) or (result.iNumber > high(int32)): if result.tokType == tkIntLit: result.tokType = tkInt64Lit - elif result.tokType in {tkInt8Lit, tkInt16Lit}: - lexMessage(L, errInvalidNumber, result.literal) + elif result.tokType in {tkInt8Lit, tkInt16Lit, tkInt32Lit}: + lexMessage(L, errNumberOutOfRange, result.literal) + elif result.tokType == tkInt8Lit and + (result.iNumber < int8.low or result.iNumber > int8.high): + lexMessage(L, errNumberOutOfRange, result.literal) + elif result.tokType == tkInt16Lit and + (result.iNumber < int16.low or result.iNumber > int16.high): + lexMessage(L, errNumberOutOfRange, result.literal) except EInvalidValue: lexMessage(L, errInvalidNumber, result.literal) except EOverflow, EOutOfRange: @@ -537,6 +540,10 @@ proc getString(L: var TLexer, tok: var TToken, rawMode: bool) = tok.tokType = tkTripleStrLit # long string literal: inc(pos, 2) # skip "" # skip leading newline: + if buf[pos] in {' ', '\t'}: + var newpos = pos+1 + while buf[newpos] in {' ', '\t'}: inc newpos + if buf[newpos] in {CR, LF}: pos = newpos pos = handleCRLF(L, pos) buf = L.buf while true: diff --git a/compiler/llstream.nim b/compiler/llstream.nim index 510880ffd..86bfeaabd 100644 --- a/compiler/llstream.nim +++ b/compiler/llstream.nim @@ -82,6 +82,9 @@ when not defined(readLineFromStdin): proc readLineFromStdin(prompt: string, line: var string): bool = stdout.write(prompt) result = readLine(stdin, line) + if not result: + stdout.write("\n") + quit(0) proc endsWith*(x: string, s: set[char]): bool = var i = x.len-1 diff --git a/compiler/lookups.nim b/compiler/lookups.nim index 60125177c..aee64f52f 100644 --- a/compiler/lookups.nim +++ b/compiler/lookups.nim @@ -15,14 +15,15 @@ import proc ensureNoMissingOrUnusedSymbols(scope: PScope) -proc considerAcc*(n: PNode): PIdent = +proc considerQuotedIdent*(n: PNode): PIdent = + ## Retrieve a PIdent from a PNode, taking into account accent nodes. case n.kind of nkIdent: result = n.ident of nkSym: result = n.sym.name of nkAccQuoted: case n.len of 0: globalError(n.info, errIdentifierExpected, renderTree(n)) - of 1: result = considerAcc(n.sons[0]) + of 1: result = considerQuotedIdent(n.sons[0]) else: var id = "" for i in 0.. <n.len: @@ -82,10 +83,10 @@ proc searchInScopes*(c: PContext, s: PIdent, filter: TSymKinds): PSym = proc errorSym*(c: PContext, n: PNode): PSym = ## creates an error symbol to avoid cascading errors (for IDE support) var m = n - # ensure that 'considerAcc' can't fail: + # ensure that 'considerQuotedIdent' can't fail: if m.kind == nkDotExpr: m = m.sons[1] let ident = if m.kind in {nkIdent, nkSym, nkAccQuoted}: - considerAcc(m) + considerQuotedIdent(m) else: getIdent("err:" & renderTree(m)) result = newSym(skError, ident, getCurrOwner(), n.info) @@ -189,7 +190,7 @@ proc lookUp*(c: PContext, n: PNode): PSym = of nkSym: result = n.sym of nkAccQuoted: - var ident = considerAcc(n) + var ident = considerQuotedIdent(n) result = searchInScopes(c, ident) if result == nil: localError(n.info, errUndeclaredIdentifier, ident.s) @@ -208,7 +209,7 @@ type proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = case n.kind of nkIdent, nkAccQuoted: - var ident = considerAcc(n) + var ident = considerQuotedIdent(n) result = searchInScopes(c, ident) if result == nil and checkUndeclared in flags: localError(n.info, errUndeclaredIdentifier, ident.s) @@ -228,7 +229,7 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = if n.sons[1].kind == nkIdent: ident = n.sons[1].ident elif n.sons[1].kind == nkAccQuoted: - ident = considerAcc(n.sons[1]) + ident = considerQuotedIdent(n.sons[1]) if ident != nil: if m == c.module: result = strTableGet(c.topLevelScope.symbols, ident) @@ -251,7 +252,7 @@ proc qualifiedLookUp*(c: PContext, n: PNode, flags = {checkUndeclared}): PSym = proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = case n.kind of nkIdent, nkAccQuoted: - var ident = considerAcc(n) + var ident = considerQuotedIdent(n) o.scope = c.currentScope o.mode = oimNoQualifier while true: @@ -272,7 +273,7 @@ proc initOverloadIter*(o: var TOverloadIter, c: PContext, n: PNode): PSym = if n.sons[1].kind == nkIdent: ident = n.sons[1].ident elif n.sons[1].kind == nkAccQuoted: - ident = considerAcc(n.sons[1]) + ident = considerQuotedIdent(n.sons[1]) if ident != nil: if o.m == c.module: # a module may access its private members: @@ -354,5 +355,5 @@ when false: if sfImmediate in a.flags: return a a = nextOverloadIter(o, c, n) if result == nil and checkUndeclared in flags: - localError(n.info, errUndeclaredIdentifier, n.considerAcc.s) + localError(n.info, errUndeclaredIdentifier, n.considerQuotedIdent.s) result = errorSym(c, n) diff --git a/compiler/lowerings.nim b/compiler/lowerings.nim index 1b9e5fe0f..e2afa4362 100644 --- a/compiler/lowerings.nim +++ b/compiler/lowerings.nim @@ -13,6 +13,8 @@ const genPrefix* = ":tmp" # prefix for generated names import ast, astalgo, types, idents, magicsys, msgs, options +from guards import createMagic +from trees import getMagic proc newTupleAccess*(tup: PNode, i: int): PNode = result = newNodeIT(nkBracketExpr, tup.info, tup.typ.skipTypes( @@ -68,6 +70,7 @@ proc addField*(obj: PType; s: PSym) = var field = newSym(skField, getIdent(s.name.s & $s.id), s.owner, s.info) let t = skipIntLit(s.typ) field.typ = t + assert t.kind != tyStmt field.position = sonsLen(obj.n) addSon(obj.n, newSymNode(field)) @@ -79,19 +82,30 @@ proc newDotExpr(obj, b: PSym): PNode = addSon(result, newSymNode(field)) result.typ = field.typ -proc indirectAccess*(a: PNode, b: PSym, info: TLineInfo): PNode = +proc indirectAccess*(a: PNode, b: string, info: TLineInfo): PNode = # returns a[].b as a node var deref = newNodeI(nkHiddenDeref, info) - deref.typ = a.typ.sons[0] - assert deref.typ.kind == tyObject - let field = getSymFromList(deref.typ.n, getIdent(b.name.s & $b.id)) - assert field != nil, b.name.s + deref.typ = a.typ.skipTypes(abstractInst).sons[0] + var t = deref.typ.skipTypes(abstractInst) + var field: PSym + while true: + assert t.kind == tyObject + field = getSymFromList(t.n, getIdent(b)) + if field != nil: break + t = t.sons[0] + if t == nil: break + t = t.skipTypes(abstractInst) + assert field != nil, b addSon(deref, a) result = newNodeI(nkDotExpr, info) addSon(result, deref) addSon(result, newSymNode(field)) result.typ = field.typ +proc indirectAccess*(a: PNode, b: PSym, info: TLineInfo): PNode = + # returns a[].b as a node + result = indirectAccess(a, b.name.s & $b.id, info) + proc indirectAccess*(a, b: PSym, info: TLineInfo): PNode = result = indirectAccess(newSymNode(a), b, info) @@ -101,6 +115,11 @@ proc genAddrOf*(n: PNode): PNode = result.typ = newType(tyPtr, n.typ.owner) result.typ.rawAddSon(n.typ) +proc genDeref*(n: PNode): PNode = + result = newNodeIT(nkHiddenDeref, n.info, + n.typ.skipTypes(abstractInst).sons[0]) + result.add n + proc callCodegenProc*(name: string, arg1: PNode; arg2, arg3: PNode = nil): PNode = result = newNodeI(nkCall, arg1.info) @@ -112,13 +131,120 @@ proc callCodegenProc*(name: string, arg1: PNode; result.add arg1 if arg2 != nil: result.add arg2 if arg3 != nil: result.add arg3 + result.typ = sym.typ.sons[0] + +proc callProc(a: PNode): PNode = + result = newNodeI(nkCall, a.info) + result.add a + result.typ = a.typ.sons[0] + +# we have 4 cases to consider: +# - a void proc --> nothing to do +# - a proc returning GC'ed memory --> requires a flowVar +# - a proc returning non GC'ed memory --> pass as hidden 'var' parameter +# - not in a parallel environment --> requires a flowVar for memory safety +type + TSpawnResult = enum + srVoid, srFlowVar, srByVar + TFlowVarKind = enum + fvInvalid # invalid type T for 'FlowVar[T]' + fvGC # FlowVar of a GC'ed type + fvBlob # FlowVar of a blob type + +proc spawnResult(t: PType; inParallel: bool): TSpawnResult = + if t.isEmptyType: srVoid + elif inParallel and not containsGarbageCollectedRef(t): srByVar + else: srFlowVar + +proc flowVarKind(t: PType): TFlowVarKind = + if t.skipTypes(abstractInst).kind in {tyRef, tyString, tySequence}: fvGC + elif containsGarbageCollectedRef(t): fvInvalid + else: fvBlob + +proc addLocalVar(varSection: PNode; owner: PSym; typ: PType; v: PNode): PSym = + result = newSym(skTemp, getIdent(genPrefix), owner, varSection.info) + result.typ = typ + incl(result.flags, sfFromGeneric) + + var vpart = newNodeI(nkIdentDefs, varSection.info, 3) + vpart.sons[0] = newSymNode(result) + vpart.sons[1] = ast.emptyNode + vpart.sons[2] = v + varSection.add vpart + +discard """ +We generate roughly this: + +proc f_wrapper(thread, args) = + barrierEnter(args.barrier) # for parallel statement + var a = args.a # thread transfer; deepCopy or shallowCopy or no copy + # depending on whether we're in a 'parallel' statement + var b = args.b + var fv = args.fv + + fv.owner = thread # optional + nimArgsPassingDone() # signal parent that the work is done + # + args.fv.blob = f(a, b, ...) + nimFlowVarSignal(args.fv) + + # - or - + f(a, b, ...) + barrierLeave(args.barrier) # for parallel statement + +stmtList: + var scratchObj + scratchObj.a = a + scratchObj.b = b + + nimSpawn(f_wrapper, addr scratchObj) + scratchObj.fv # optional + +""" proc createWrapperProc(f: PNode; threadParam, argsParam: PSym; - varSection, call: PNode): PSym = + varSection, call, barrier, fv: PNode; + spawnKind: TSpawnResult): PSym = var body = newNodeI(nkStmtList, f.info) + var threadLocalBarrier: PSym + if barrier != nil: + var varSection = newNodeI(nkVarSection, barrier.info) + threadLocalBarrier = addLocalVar(varSection, argsParam.owner, + barrier.typ, barrier) + body.add varSection + body.add callCodeGenProc("barrierEnter", threadLocalBarrier.newSymNode) + var threadLocalProm: PSym + if spawnKind == srByVar: + threadLocalProm = addLocalVar(varSection, argsParam.owner, fv.typ, fv) + elif fv != nil: + internalAssert fv.typ.kind == tyGenericInst + threadLocalProm = addLocalVar(varSection, argsParam.owner, fv.typ, fv) + body.add varSection - body.add callCodeGenProc("nimArgsPassingDone", newSymNode(threadParam)) - body.add call + if fv != nil and spawnKind != srByVar: + # generate: + # fv.owner = threadParam + body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode, + "owner", fv.info), threadParam.newSymNode) + + body.add callCodeGenProc("nimArgsPassingDone", threadParam.newSymNode) + if spawnKind == srByVar: + body.add newAsgnStmt(genDeref(threadLocalProm.newSymNode), call) + elif fv != nil: + let fk = fv.typ.sons[1].flowVarKind + if fk == fvInvalid: + localError(f.info, "cannot create a flowVar of type: " & + typeToString(fv.typ.sons[1])) + body.add newAsgnStmt(indirectAccess(threadLocalProm.newSymNode, + if fk == fvGC: "data" else: "blob", fv.info), call) + if barrier == nil: + # by now 'fv' is shared and thus might have beeen overwritten! we need + # to use the thread-local view instead: + body.add callCodeGenProc("nimFlowVarSignal", threadLocalProm.newSymNode) + else: + body.add call + if barrier != nil: + body.add callCodeGenProc("barrierLeave", threadLocalBarrier.newSymNode) var params = newNodeI(nkFormalParams, f.info) params.add emptyNode @@ -146,10 +272,152 @@ proc createCastExpr(argsParam: PSym; objType: PType): PNode = result.typ = newType(tyPtr, objType.owner) result.typ.rawAddSon(objType) -proc wrapProcForSpawn*(owner: PSym; n: PNode): PNode = - result = newNodeI(nkStmtList, n.info) - if n.kind notin nkCallKinds or not n.typ.isEmptyType: - localError(n.info, "'spawn' takes a call expression of type void") +proc setupArgsForConcurrency(n: PNode; objType: PType; scratchObj: PSym, + castExpr, call, varSection, result: PNode) = + let formals = n[0].typ.n + let tmpName = getIdent(genPrefix) + for i in 1 .. <n.len: + # we pick n's type here, which hopefully is 'tyArray' and not + # 'tyOpenArray': + var argType = n[i].typ.skipTypes(abstractInst) + if i < formals.len and formals[i].typ.kind == tyVar: + localError(n[i].info, "'spawn'ed function cannot have a 'var' parameter") + elif containsTyRef(argType): + localError(n[i].info, "'spawn'ed function cannot refer to 'ref'/closure") + + let fieldname = if i < formals.len: formals[i].sym.name else: tmpName + var field = newSym(skField, fieldname, objType.owner, n.info) + field.typ = argType + objType.addField(field) + result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[i]) + + let temp = addLocalVar(varSection, objType.owner, argType, + indirectAccess(castExpr, field, n.info)) + call.add(newSymNode(temp)) + +proc getRoot*(n: PNode): PSym = + ## ``getRoot`` takes a *path* ``n``. A path is an lvalue expression + ## like ``obj.x[i].y``. The *root* of a path is the symbol that can be + ## determined as the owner; ``obj`` in the example. + case n.kind + of nkSym: + if n.sym.kind in {skVar, skResult, skTemp, skLet, skForVar}: + result = n.sym + of nkDotExpr, nkBracketExpr, nkHiddenDeref, nkDerefExpr, + nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr: + result = getRoot(n.sons[0]) + of nkHiddenStdConv, nkHiddenSubConv, nkConv: + result = getRoot(n.sons[1]) + of nkCallKinds: + if getMagic(n) == mSlice: result = getRoot(n.sons[1]) + else: discard + +proc newIntLit(value: BiggestInt): PNode = + result = nkIntLit.newIntNode(value) + result.typ = getSysType(tyInt) + +proc genHigh(n: PNode): PNode = + if skipTypes(n.typ, abstractVar).kind in {tyArrayConstr, tyArray}: + result = newIntLit(lastOrd(skipTypes(n.typ, abstractVar))) + else: + result = newNodeI(nkCall, n.info, 2) + result.typ = getSysType(tyInt) + result.sons[0] = newSymNode(createMagic("high", mHigh)) + result.sons[1] = n + +proc setupArgsForParallelism(n: PNode; objType: PType; scratchObj: PSym; + castExpr, call, varSection, result: PNode) = + let formals = n[0].typ.n + let tmpName = getIdent(genPrefix) + # we need to copy the foreign scratch object fields into local variables + # for correctness: These are called 'threadLocal' here. + for i in 1 .. <n.len: + let n = n[i] + let argType = skipTypes(if i < formals.len: formals[i].typ else: n.typ, + abstractInst) + if containsTyRef(argType): + localError(n.info, "'spawn'ed function cannot refer to 'ref'/closure") + + let fieldname = if i < formals.len: formals[i].sym.name else: tmpName + var field = newSym(skField, fieldname, objType.owner, n.info) + + if argType.kind in {tyVarargs, tyOpenArray}: + # important special case: we always create a zero-copy slice: + let slice = newNodeI(nkCall, n.info, 4) + slice.typ = n.typ + slice.sons[0] = newSymNode(createMagic("slice", mSlice)) + var fieldB = newSym(skField, tmpName, objType.owner, n.info) + fieldB.typ = getSysType(tyInt) + objType.addField(fieldB) + + if getMagic(n) == mSlice: + let a = genAddrOf(n[1]) + field.typ = a.typ + objType.addField(field) + result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a) + + var fieldA = newSym(skField, tmpName, objType.owner, n.info) + fieldA.typ = getSysType(tyInt) + objType.addField(fieldA) + result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldA), n[2]) + result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), n[3]) + + let threadLocal = addLocalVar(varSection, objType.owner, fieldA.typ, + indirectAccess(castExpr, fieldA, n.info)) + slice.sons[2] = threadLocal.newSymNode + else: + let a = genAddrOf(n) + field.typ = a.typ + objType.addField(field) + result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a) + result.add newFastAsgnStmt(newDotExpr(scratchObj, fieldB), genHigh(n)) + + slice.sons[2] = newIntLit(0) + # the array itself does not need to go through a thread local variable: + slice.sons[1] = genDeref(indirectAccess(castExpr, field, n.info)) + + let threadLocal = addLocalVar(varSection, objType.owner, fieldB.typ, + indirectAccess(castExpr, fieldB, n.info)) + slice.sons[3] = threadLocal.newSymNode + call.add slice + elif (let size = computeSize(argType); size < 0 or size > 16) and + n.getRoot != nil: + # it is more efficient to pass a pointer instead: + let a = genAddrOf(n) + field.typ = a.typ + objType.addField(field) + result.add newFastAsgnStmt(newDotExpr(scratchObj, field), a) + let threadLocal = addLocalVar(varSection, objType.owner, field.typ, + indirectAccess(castExpr, field, n.info)) + call.add(genDeref(threadLocal.newSymNode)) + else: + # boring case + field.typ = argType + objType.addField(field) + result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n) + let threadLocal = addLocalVar(varSection, objType.owner, field.typ, + indirectAccess(castExpr, field, n.info)) + call.add(threadLocal.newSymNode) + +proc wrapProcForSpawn*(owner: PSym; spawnExpr: PNode; retType: PType; + barrier, dest: PNode = nil): PNode = + # if 'barrier' != nil, then it is in a 'parallel' section and we + # generate quite different code + let n = spawnExpr[1] + let spawnKind = spawnResult(retType, barrier!=nil) + case spawnKind + of srVoid: + internalAssert dest == nil + result = newNodeI(nkStmtList, n.info) + of srFlowVar: + internalAssert dest == nil + result = newNodeIT(nkStmtListExpr, n.info, retType) + of srByVar: + if dest == nil: localError(n.info, "'spawn' must not be discarded") + result = newNodeI(nkStmtList, n.info) + + if n.kind notin nkCallKinds: + localError(n.info, "'spawn' takes a call expression") return if optThreadAnalysis in gGlobalOptions: if {tfThread, tfNoSideEffect} * n[0].typ.flags == {}: @@ -162,6 +430,7 @@ proc wrapProcForSpawn*(owner: PSym; n: PNode): PNode = threadParam.typ = ptrType argsParam.typ = ptrType argsParam.position = 1 + var objType = createObj(owner, n.info) incl(objType.flags, tfFinal) let castExpr = createCastExpr(argsParam, objType) @@ -174,7 +443,7 @@ proc wrapProcForSpawn*(owner: PSym; n: PNode): PNode = varSectionB.addVar(scratchObj.newSymNode) result.add varSectionB - var call = newNodeI(nkCall, n.info) + var call = newNodeIT(nkCall, n.info, n.typ) var fn = n.sons[0] # templates and macros are in fact valid here due to the nature of # the transformation: @@ -194,35 +463,44 @@ proc wrapProcForSpawn*(owner: PSym; n: PNode): PNode = call.add(fn) var varSection = newNodeI(nkVarSection, n.info) - let formals = n[0].typ.n - let tmpName = getIdent(genPrefix) - for i in 1 .. <n.len: - # we pick n's type here, which hopefully is 'tyArray' and not - # 'tyOpenArray': - var argType = n[i].typ.skipTypes(abstractInst) - if i < formals.len and formals[i].typ.kind == tyVar: - localError(n[i].info, "'spawn'ed function cannot have a 'var' parameter") - elif containsTyRef(argType): - localError(n[i].info, "'spawn'ed function cannot refer to 'ref'/closure") + if barrier.isNil: + setupArgsForConcurrency(n, objType, scratchObj, castExpr, call, varSection, result) + else: + setupArgsForParallelism(n, objType, scratchObj, castExpr, call, varSection, result) - let fieldname = if i < formals.len: formals[i].sym.name else: tmpName - var field = newSym(skField, fieldname, owner, n.info) - field.typ = argType + var barrierAsExpr: PNode = nil + if barrier != nil: + let typ = newType(tyPtr, owner) + typ.rawAddSon(magicsys.getCompilerProc("Barrier").typ) + var field = newSym(skField, getIdent"barrier", owner, n.info) + field.typ = typ objType.addField(field) - result.add newFastAsgnStmt(newDotExpr(scratchObj, field), n[i]) - - var temp = newSym(skTemp, tmpName, owner, n.info) - temp.typ = argType - incl(temp.flags, sfFromGeneric) + result.add newFastAsgnStmt(newDotExpr(scratchObj, field), barrier) + barrierAsExpr = indirectAccess(castExpr, field, n.info) - var vpart = newNodeI(nkIdentDefs, n.info, 3) - vpart.sons[0] = newSymNode(temp) - vpart.sons[1] = ast.emptyNode - vpart.sons[2] = indirectAccess(castExpr, field, n.info) - varSection.add vpart + var fvField, fvAsExpr: PNode = nil + if spawnKind == srFlowVar: + var field = newSym(skField, getIdent"fv", owner, n.info) + field.typ = retType + objType.addField(field) + fvField = newDotExpr(scratchObj, field) + fvAsExpr = indirectAccess(castExpr, field, n.info) + # create flowVar: + result.add newFastAsgnStmt(fvField, callProc(spawnExpr[2])) + if barrier == nil: + result.add callCodeGenProc("nimFlowVarCreateCondVar", fvField) - call.add(newSymNode(temp)) + elif spawnKind == srByVar: + var field = newSym(skField, getIdent"fv", owner, n.info) + field.typ = newType(tyPtr, objType.owner) + field.typ.rawAddSon(retType) + objType.addField(field) + fvAsExpr = indirectAccess(castExpr, field, n.info) + result.add newFastAsgnStmt(newDotExpr(scratchObj, field), genAddrOf(dest)) - let wrapper = createWrapperProc(fn, threadParam, argsParam, varSection, call) + let wrapper = createWrapperProc(fn, threadParam, argsParam, varSection, call, + barrierAsExpr, fvAsExpr, spawnKind) result.add callCodeGenProc("nimSpawn", wrapper.newSymNode, genAddrOf(scratchObj.newSymNode)) + + if spawnKind == srFlowVar: result.add fvField diff --git a/compiler/main.nim b/compiler/main.nim index f6d11d960..b4af49248 100644 --- a/compiler/main.nim +++ b/compiler/main.nim @@ -69,6 +69,7 @@ proc commandCompileToC = # echo "BEFORE CHECK DEP" # discard checkDepMem(gProjectMainIdx) # echo "CHECK DEP COMPLETE" + discard compileProject() cgenWriteModules() @@ -283,11 +284,11 @@ proc resetMemory = echo GC_getStatistics() const - SimiluateCaasMemReset = false + SimulateCaasMemReset = false PrintRopeCacheStats = false proc mainCommand* = - when SimiluateCaasMemReset: + when SimulateCaasMemReset: gGlobalOptions.incl(optCaasEnabled) # In "nimrod serve" scenario, each command must reset the registered passes @@ -309,7 +310,7 @@ proc mainCommand* = of "cpp", "compiletocpp": extccomp.cExt = ".cpp" gCmd = cmdCompileToCpp - if cCompiler == ccGcc: setCC("gpp") + if cCompiler == ccGcc: setCC("gcc") wantMainModule() defineSymbol("cpp") commandCompileToC() @@ -453,6 +454,6 @@ proc mainCommand* = echo " efficiency: ", formatFloat(1-(gCacheMisses.float/gCacheTries.float), ffDecimal, 3) - when SimiluateCaasMemReset: + when SimulateCaasMemReset: resetMemory() diff --git a/compiler/modules.nim b/compiler/modules.nim index fb1940741..b102224cd 100644 --- a/compiler/modules.nim +++ b/compiler/modules.nim @@ -115,7 +115,7 @@ proc newModule(fileIdx: int32): PSym = new(result) result.id = - 1 # for better error checking result.kind = skModule - let filename = fileIdx.toFilename + let filename = fileIdx.toFullPath result.name = getIdent(splitFile(filename).name) if not isNimrodIdentifier(result.name.s): rawMessage(errInvalidModuleName, result.name.s) diff --git a/compiler/msgs.nim b/compiler/msgs.nim index 8374c92a7..730cb9605 100644 --- a/compiler/msgs.nim +++ b/compiler/msgs.nim @@ -116,7 +116,7 @@ type warnSmallLshouldNotBeUsed, warnUnknownMagic, warnRedefinitionOfLabel, warnUnknownSubstitutionX, warnLanguageXNotSupported, warnCommentXIgnored, warnNilStatement, warnAnalysisLoophole, - warnDifferentHeaps, warnWriteToForeignHeap, warnImplicitClosure, + warnDifferentHeaps, warnWriteToForeignHeap, warnUnsafeCode, warnEachIdentIsTuple, warnShadowIdent, warnProveInit, warnProveField, warnProveIndex, warnGcUnsafe, warnGcUnsafe2, warnUninit, warnGcMem, warnUser, @@ -380,7 +380,7 @@ const warnAnalysisLoophole: "thread analysis incomplete due to unknown call '$1' [AnalysisLoophole]", warnDifferentHeaps: "possible inconsistency of thread local heaps [DifferentHeaps]", warnWriteToForeignHeap: "write to foreign heap [WriteToForeignHeap]", - warnImplicitClosure: "implicit closure convention: '$1' [ImplicitClosure]", + warnUnsafeCode: "unsafe code: '$1' [UnsafeCode]", warnEachIdentIsTuple: "each identifier is a tuple [EachIdentIsTuple]", warnShadowIdent: "shadowed identifier: '$1' [ShadowIdent]", warnProveInit: "Cannot prove that '$1' is initialized. This will become a compile time error in the future. [ProveInit]", @@ -416,7 +416,7 @@ const "RedefinitionOfLabel", "UnknownSubstitutionX", "LanguageXNotSupported", "CommentXIgnored", "NilStmt", "AnalysisLoophole", "DifferentHeaps", "WriteToForeignHeap", - "ImplicitClosure", "EachIdentIsTuple", "ShadowIdent", + "UnsafeCode", "EachIdentIsTuple", "ShadowIdent", "ProveInit", "ProveField", "ProveIndex", "GcUnsafe", "GcUnsafe2", "Uninit", "GcMem", "User"] diff --git a/compiler/nimrod.ini b/compiler/nimrod.ini index 0dc44a7c9..44e16cec8 100644 --- a/compiler/nimrod.ini +++ b/compiler/nimrod.ini @@ -3,7 +3,7 @@ Name: "Nimrod" Version: "$version" Platforms: """ windows: i386;amd64 - linux: i386;amd64;powerpc64;arm;sparc;mips + linux: i386;amd64;powerpc64;arm;sparc;mips;powerpc macosx: i386;amd64;powerpc64 solaris: i386;amd64;sparc freebsd: i386;amd64 @@ -79,6 +79,7 @@ Files: "lib/system/*.nim" Files: "lib/core/*.nim" Files: "lib/pure/*.nim" Files: "lib/pure/collections/*.nim" +Files: "lib/pure/concurrency/*.nim" Files: "lib/impure/*.nim" Files: "lib/wrappers/*.nim" diff --git a/compiler/nversion.nim b/compiler/nversion.nim index b996d0b9b..3c868ed2a 100644 --- a/compiler/nversion.nim +++ b/compiler/nversion.nim @@ -12,10 +12,9 @@ const MaxSetElements* = 1 shl 16 # (2^16) to support unicode character sets? - defaultAsmMarkerSymbol* = '!' VersionMajor* = 0 VersionMinor* = 9 - VersionPatch* = 4 + VersionPatch* = 5 VersionAsString* = $VersionMajor & "." & $VersionMinor & "." & $VersionPatch RodFileVersion* = "1215" # modify this if the rod-format changes! diff --git a/compiler/options.nim b/compiler/options.nim index 36d343d1b..58a340d21 100644 --- a/compiler/options.nim +++ b/compiler/options.nim @@ -16,7 +16,7 @@ const hasFFI* = defined(useFFI) newScopeForIf* = true useCaas* = not defined(noCaas) - noTimeMachine = defined(avoidTimeMachine) and defined(macosx) + noTimeMachine* = defined(avoidTimeMachine) and defined(macosx) type # please make sure we have under 32 options # (improves code efficiency a lot!) diff --git a/compiler/parampatterns.nim b/compiler/parampatterns.nim index e94068776..bbdba8c22 100644 --- a/compiler/parampatterns.nim +++ b/compiler/parampatterns.nim @@ -10,7 +10,7 @@ ## This module implements the pattern matching features for term rewriting ## macro support. -import strutils, ast, astalgo, types, msgs, idents, renderer, wordrecg +import strutils, ast, astalgo, types, msgs, idents, renderer, wordrecg, trees # we precompile the pattern here for efficiency into some internal # stack based VM :-) Why? Because it's fun; I did no benchmarks to see if that @@ -215,6 +215,9 @@ proc isAssignable*(owner: PSym, n: PNode): TAssignableResult = result = arLValue of nkObjUpConv, nkObjDownConv, nkCheckedFieldExpr: result = isAssignable(owner, n.sons[0]) + of nkCallKinds: + # builtin slice keeps lvalue-ness: + if getMagic(n) == mSlice: result = isAssignable(owner, n.sons[1]) else: discard diff --git a/compiler/parser.nim b/compiler/parser.nim index 5c7b86240..6ff0c2dfc 100644 --- a/compiler/parser.nim +++ b/compiler/parser.nim @@ -28,25 +28,20 @@ import llstream, lexer, idents, strutils, ast, astalgo, msgs type - TParser*{.final.} = object # a TParser object represents a module that + TParser*{.final.} = object # A TParser object represents a module that # is being parsed - currInd: int # current indentation - firstTok, strongSpaces: bool - lex*: TLexer # the lexer that is used for parsing - tok*: TToken # the current token - inPragma: int + currInd: int # current indentation level + firstTok, strongSpaces: bool # Has the first token been read? + # Is strongSpaces on? + lex*: TLexer # The lexer that is used for parsing + tok*: TToken # The current token + inPragma: int # Pragma level inSemiStmtList: int proc parseAll*(p: var TParser): PNode proc closeParser*(p: var TParser) proc parseTopLevelStmt*(p: var TParser): PNode - # implements an iterator. Returns the next top-level statement or - # emtyNode if end of stream. - proc parseString*(s: string, filename: string = "", line: int = 0): PNode - # filename and line could be set optionally, when the string originates - # from a certain source file. This way, the compiler could generate - # correct error messages referring to the original source. # helpers for the other parsers proc isOperator*(tok: TToken): bool @@ -68,15 +63,19 @@ proc optInd*(p: var TParser, n: PNode) proc indAndComment*(p: var TParser, n: PNode) proc setBaseFlags*(n: PNode, base: TNumericalBase) proc parseSymbol*(p: var TParser, allowNil = false): PNode -proc parseTry(p: var TParser): PNode +proc parseTry(p: var TParser; isExpr: bool): PNode proc parseCase(p: var TParser): PNode # implementation -proc getTok(p: var TParser) = +proc getTok(p: var TParser) = + ## Get the next token from the parser's lexer, and store it in the parser's + ## `tok` member. rawGetTok(p.lex, p.tok) proc openParser*(p: var TParser, fileIdx: int32, inputStream: PLLStream, strongSpaces=false) = + ## Open a parser, using the given arguments to set up its internal state. + ## initToken(p.tok) openLexer(p.lex, fileIdx, inputStream) getTok(p) # read the first token @@ -87,13 +86,16 @@ proc openParser*(p: var TParser, filename: string, inputStream: PLLStream, strongSpaces=false) = openParser(p, filename.fileInfoIdx, inputstream, strongSpaces) -proc closeParser(p: var TParser) = +proc closeParser(p: var TParser) = + ## Close a parser, freeing up its resources. closeLexer(p.lex) -proc parMessage(p: TParser, msg: TMsgKind, arg: string = "") = +proc parMessage(p: TParser, msg: TMsgKind, arg = "") = + ## Produce and emit the parser message `arg` to output. lexMessage(p.lex, msg, arg) -proc parMessage(p: TParser, msg: TMsgKind, tok: TToken) = +proc parMessage(p: TParser, msg: TMsgKind, tok: TToken) = + ## Produce and emit a parser message to output about the token `tok` lexMessage(p.lex, msg, prettyTok(tok)) template withInd(p: expr, body: stmt) {.immediate.} = @@ -143,10 +145,15 @@ proc expectIdent(p: TParser) = lexMessage(p.lex, errIdentifierExpected, prettyTok(p.tok)) proc eat(p: var TParser, tokType: TTokType) = - if p.tok.tokType == tokType: getTok(p) - else: lexMessage(p.lex, errTokenExpected, TokTypeToStr[tokType]) + ## Move the parser to the next token if the current token is of type + ## `tokType`, otherwise error. + if p.tok.tokType == tokType: + getTok(p) + else: + lexMessage(p.lex, errTokenExpected, TokTypeToStr[tokType]) proc parLineInfo(p: TParser): TLineInfo = + ## Retrieve the line information associated with the parser's current state. result = getLineInfo(p.lex, p.tok) proc indAndComment(p: var TParser, n: PNode) = @@ -192,9 +199,11 @@ proc isSigilLike(tok: TToken): bool {.inline.} = result = tok.tokType == tkOpr and relevantOprChar(tok.ident) == '@' proc isLeftAssociative(tok: TToken): bool {.inline.} = + ## Determines whether the token is left assocative. result = tok.tokType != tkOpr or relevantOprChar(tok.ident) != '^' proc getPrecedence(tok: TToken, strongSpaces: bool): int = + ## Calculates the precedence of the given token. template considerStrongSpaces(x): expr = x + (if strongSpaces: 100 - tok.strongSpaceA.int*10 else: 0) @@ -224,22 +233,26 @@ proc getPrecedence(tok: TToken, strongSpaces: bool): int = else: result = -10 proc isOperator(tok: TToken): bool = + ## Determines if the given token is an operator type token. tok.tokType in {tkOpr, tkDiv, tkMod, tkShl, tkShr, tkIn, tkNotin, tkIs, tkIsnot, tkNot, tkOf, tkAs, tkDotDot, tkAnd, tkOr, tkXor} proc isUnary(p: TParser): bool = + ## Check if the current parser token is a unary operator p.strongSpaces and p.tok.tokType in {tkOpr, tkDotDot} and p.tok.strongSpaceB == 0 and p.tok.strongSpaceA > 0 proc checkBinary(p: TParser) {.inline.} = + ## Check if the current parser token is a binary operator. # we don't check '..' here as that's too annoying if p.strongSpaces and p.tok.tokType == tkOpr: if p.tok.strongSpaceB > 0 and p.tok.strongSpaceA != p.tok.strongSpaceB: - parMessage(p, errGenerated, "number of spaces around '$#' not consistent"% - prettyTok(p.tok)) + parMessage(p, errGenerated, + "Number of spaces around '$#' not consistent" % + prettyTok(p.tok)) elif p.tok.strongSpaceA notin {0,1,2,4,8}: - parMessage(p, errGenerated, "number of spaces must be 0,1,2,4 or 8") + parMessage(p, errGenerated, "Number of spaces must be 0,1,2,4 or 8") #| module = stmt ^* (';' / IND{=}) #| @@ -274,7 +287,7 @@ proc colcom(p: var TParser, n: PNode) = skipComment(p, n) proc parseSymbol(p: var TParser, allowNil = false): PNode = - #| symbol = '`' (KEYW|IDENT|operator|'(' ')'|'[' ']'|'{' '}'|'='|literal)+ '`' + #| symbol = '`' (KEYW|IDENT|literal|(operator|'('|')'|'['|']'|'{'|'}'|'=')+)+ '`' #| | IDENT case p.tok.tokType of tkSymbol: @@ -285,31 +298,22 @@ proc parseSymbol(p: var TParser, allowNil = false): PNode = getTok(p) while true: case p.tok.tokType - of tkBracketLe: - add(result, newIdentNodeP(getIdent"[]", p)) - getTok(p) - eat(p, tkBracketRi) - of tkEquals: - add(result, newIdentNodeP(getIdent"=", p)) - getTok(p) - of tkParLe: - add(result, newIdentNodeP(getIdent"()", p)) - getTok(p) - eat(p, tkParRi) - of tkCurlyLe: - add(result, newIdentNodeP(getIdent"{}", p)) - getTok(p) - eat(p, tkCurlyRi) - of tokKeywordLow..tokKeywordHigh, tkSymbol, tkOpr, tkDot, tkDotDot: - add(result, newIdentNodeP(p.tok.ident, p)) - getTok(p) - of tkIntLit..tkCharLit: - add(result, newIdentNodeP(getIdent(tokToStr(p.tok)), p)) - getTok(p) - else: + of tkAccent: if result.len == 0: parMessage(p, errIdentifierExpected, p.tok) break + of tkOpr, tkDot, tkDotDot, tkEquals, tkParLe..tkParDotRi: + var accm = "" + while p.tok.tokType in {tkOpr, tkDot, tkDotDot, tkEquals, + tkParLe..tkParDotRi}: + accm.add(tokToStr(p.tok)) + getTok(p) + result.add(newIdentNodeP(getIdent(accm), p)) + of tokKeywordLow..tokKeywordHigh, tkSymbol, tkIntLit..tkCharLit: + result.add(newIdentNodeP(getIdent(tokToStr(p.tok)), p)) + getTok(p) + else: + parMessage(p, errIdentifierExpected, p.tok) eat(p, tkAccent) else: if allowNil and p.tok.tokType == tkNil: @@ -841,7 +845,7 @@ proc parseIdentColonEquals(p: var TParser, flags: TDeclaredIdentFlags): PNode = addSon(result, parseTypeDesc(p)) else: addSon(result, ast.emptyNode) - if (p.tok.tokType != tkEquals) and not (withBothOptional in flags): + if p.tok.tokType != tkEquals and withBothOptional notin flags: parMessage(p, errColonOrEqualsExpected, p.tok) if p.tok.tokType == tkEquals: getTok(p) @@ -982,6 +986,7 @@ proc parseSymbolList(p: var TParser, result: PNode, allowNil = false) = proc parseTypeDescKAux(p: var TParser, kind: TNodeKind, mode: TPrimaryMode): PNode = + #| distinct = 'distinct' optInd typeDesc result = newNodeP(kind, p) getTok(p) optInd(p, result) @@ -999,13 +1004,13 @@ proc parseExpr(p: var TParser): PNode = #| expr = (ifExpr #| | whenExpr #| | caseExpr - #| | tryStmt) + #| | tryExpr) #| / simpleExpr case p.tok.tokType: of tkIf: result = parseIfExpr(p, nkIfExpr) of tkWhen: result = parseIfExpr(p, nkWhenExpr) of tkCase: result = parseCase(p) - of tkTry: result = parseTry(p) + of tkTry: result = parseTry(p, isExpr=true) else: result = simpleExpr(p) proc parseEnum(p: var TParser): PNode @@ -1108,6 +1113,7 @@ proc parseTypeDefAux(p: var TParser): PNode = result = simpleExpr(p, pmTypeDef) proc makeCall(n: PNode): PNode = + ## Creates a call if the given node isn't already a call. if n.kind in nkCallKinds: result = n else: @@ -1357,22 +1363,25 @@ proc parseCase(p: var TParser): PNode = if wasIndented: p.currInd = oldInd -proc parseTry(p: var TParser): PNode = +proc parseTry(p: var TParser; isExpr: bool): PNode = #| tryStmt = 'try' colcom stmt &(IND{=}? 'except'|'finally') #| (IND{=}? 'except' exprList colcom stmt)* #| (IND{=}? 'finally' colcom stmt)? + #| tryExpr = 'try' colcom stmt &(optInd 'except'|'finally') + #| (optInd 'except' exprList colcom stmt)* + #| (optInd 'finally' colcom stmt)? result = newNodeP(nkTryStmt, p) getTok(p) eat(p, tkColon) skipComment(p, result) addSon(result, parseStmt(p)) var b: PNode = nil - while sameOrNoInd(p): + while sameOrNoInd(p) or isExpr: case p.tok.tokType - of tkExcept: + of tkExcept: b = newNodeP(nkExceptBranch, p) exprList(p, tkColon, b) - of tkFinally: + of tkFinally: b = newNodeP(nkFinally, p) getTokNoInd(p) eat(p, tkColon) @@ -1871,7 +1880,7 @@ proc complexOrSimpleStmt(p: var TParser): PNode = of tkIf: result = parseIfOrWhen(p, nkIfStmt) of tkWhile: result = parseWhile(p) of tkCase: result = parseCase(p) - of tkTry: result = parseTry(p) + of tkTry: result = parseTry(p, isExpr=false) of tkFinally: result = parseExceptBlock(p, nkFinally) of tkExcept: result = parseExceptBlock(p, nkExceptBranch) of tkFor: result = parseFor(p) @@ -1952,7 +1961,8 @@ proc parseStmt(p: var TParser): PNode = if p.tok.tokType != tkSemiColon: break getTok(p) -proc parseAll(p: var TParser): PNode = +proc parseAll(p: var TParser): PNode = + ## Parses the rest of the input stream held by the parser into a PNode. result = newNodeP(nkStmtList, p) while p.tok.tokType != tkEof: var a = complexOrSimpleStmt(p) @@ -1966,6 +1976,8 @@ proc parseAll(p: var TParser): PNode = parMessage(p, errInvalidIndentation) proc parseTopLevelStmt(p: var TParser): PNode = + ## Implements an iterator which, when called repeatedly, returns the next + ## top-level statement or emptyNode if end of stream. result = ast.emptyNode while true: if p.tok.indent != 0: @@ -1984,6 +1996,10 @@ proc parseTopLevelStmt(p: var TParser): PNode = break proc parseString(s: string, filename: string = "", line: int = 0): PNode = + ## Parses a string into an AST, returning the top node. + ## `filename` and `line`, although optional, provide info so that the + ## compiler can generate correct error messages referring to the original + ## source. var stream = llStreamOpen(s) stream.lineOffset = line diff --git a/compiler/patterns.nim b/compiler/patterns.nim index d262790ab..5e21289b5 100644 --- a/compiler/patterns.nim +++ b/compiler/patterns.nim @@ -287,7 +287,7 @@ proc applyRule*(c: PContext, s: PSym, n: PNode): PNode = # constraint not fullfilled: if not ok: return nil - markUsed(n, s) + markUsed(n.info, s) if ctx.subMatch: assert m.len == 3 m.sons[1] = result diff --git a/compiler/pragmas.nim b/compiler/pragmas.nim index db9fe7cbe..a17773aa4 100644 --- a/compiler/pragmas.nim +++ b/compiler/pragmas.nim @@ -517,7 +517,7 @@ proc pragmaUses(c: PContext, n: PNode) = proc processExc(c: PContext, x: PNode): PNode = if x.kind in {nkAccQuoted, nkIdent, nkSym, nkOpenSymChoice, nkClosedSymChoice}: - if considerAcc(x).s == "*": + if considerQuotedIdent(x).s == "*": return newSymNode(ast.anyGlobal) result = c.semExpr(c, x) if result.kind != nkSym or sfGlobal notin result.sym.flags: @@ -644,12 +644,13 @@ proc singlePragma(c: PContext, sym: PSym, n: PNode, i: int, incl(sym.flags, sfNoReturn) of wDynlib: processDynLib(c, it, sym) - of wCompilerproc: + of wCompilerproc: noVal(it) # compilerproc may not get a string! - makeExternExport(sym, "$1", it.info) - incl(sym.flags, sfCompilerProc) - incl(sym.flags, sfUsed) # suppress all those stupid warnings - registerCompilerProc(sym) + if sfFromGeneric notin sym.flags: + makeExternExport(sym, "$1", it.info) + incl(sym.flags, sfCompilerProc) + incl(sym.flags, sfUsed) # suppress all those stupid warnings + registerCompilerProc(sym) of wProcVar: noVal(it) incl(sym.flags, sfProcvar) diff --git a/compiler/pretty.nim b/compiler/pretty.nim index 3a5bfe197..17311f9e6 100644 --- a/compiler/pretty.nim +++ b/compiler/pretty.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -149,8 +149,8 @@ proc checkDef(c: PGen; n: PNode) = if n.kind != nkSym: return checkDef(n, n.sym) -proc checkUse*(n: PNode, s: PSym) = - if n.info.fileIndex < 0: return +proc checkUse*(info: TLineInfo; s: PSym) = + if info.fileIndex < 0: return # we simply convert it to what it looks like in the definition # for consistency @@ -159,10 +159,10 @@ proc checkUse*(n: PNode, s: PSym) = if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return let newName = s.name.s - loadFile(n.info) + loadFile(info) - let line = gSourceFiles[n.info.fileIndex].lines[n.info.line-1] - var first = min(n.info.col.int, line.len) + let line = gSourceFiles[info.fileIndex].lines[info.line-1] + var first = min(info.col.int, line.len) if first < 0: return #inc first, skipIgnoreCase(line, "proc ", first) while first > 0 and line[first-1] in Letters: dec first @@ -179,8 +179,8 @@ proc checkUse*(n: PNode, s: PSym) = if x.match(peg"\s* {\ident} \s* '=' \s* y$1 ('#' .*)?"): x = "" - system.shallowCopy(gSourceFiles[n.info.fileIndex].lines[n.info.line-1], x) - gSourceFiles[n.info.fileIndex].dirty = true + system.shallowCopy(gSourceFiles[info.fileIndex].lines[info.line-1], x) + gSourceFiles[info.fileIndex].dirty = true when false: var cannotRename = initIntSet() @@ -220,53 +220,9 @@ when false: result.add s[i] inc i - proc checkUse(c: PGen; n: PNode) = - if n.info.fileIndex < 0: return - let s = n.sym - # operators stay as they are: - if s.kind in {skResult, skTemp} or s.name.s[0] notin Letters: return - if s.kind in {skType, skGenericParam} and sfAnon in s.flags: return - - if s.id in cannotRename: return - - let newName = if rules.hasKey(s.name.s): rules[s.name.s] - else: beautifyName(s.name.s, n.sym.kind) - - loadFile(n.info) - - let line = gSourceFiles[n.info.fileIndex].lines[n.info.line-1] - var first = min(n.info.col.int, line.len) - if first < 0: return - #inc first, skipIgnoreCase(line, "proc ", first) - while first > 0 and line[first-1] in Letters: dec first - if first < 0: return - if line[first] == '`': inc first - - if {sfImportc, sfExportc} * s.flags != {}: - # careful, we must ensure the resulting name still matches the external - # name: - if newName != s.name.s and newName != s.loc.r.ropeToStr and - lfFullExternalName notin s.loc.flags: - #Message(n.info, errGenerated, - # "cannot rename $# to $# due to external name" % [s.name.s, newName]) - cannotRename.incl(s.id) - return - let last = first+identLen(line, first)-1 - if differ(line, first, last, newName): - # last-first+1 != newName.len or - var x = line.subStr(0, first-1) & newName & line.substr(last+1) - when removeTP: - # the WinAPI module is full of 'TX = X' which after the substitution - # becomes 'X = X'. We remove those lines: - if x.match(peg"\s* {\ident} \s* '=' \s* y$1 ('#' .*)?"): - x = "" - - system.shallowCopy(gSourceFiles[n.info.fileIndex].lines[n.info.line-1], x) - gSourceFiles[n.info.fileIndex].dirty = true - proc check(c: PGen, n: PNode) = case n.kind - of nkSym: checkUse(n, n.sym) + of nkSym: checkUse(n.info, n.sym) of nkBlockStmt, nkBlockExpr, nkBlockType: checkDef(c, n[0]) check(c, n.sons[1]) diff --git a/compiler/renderer.nim b/compiler/renderer.nim index 6b62c48c5..0b1312ccc 100644 --- a/compiler/renderer.nim +++ b/compiler/renderer.nim @@ -146,28 +146,29 @@ proc makeNimString(s: string): string = for i in countup(0, len(s)-1): add(result, toNimChar(s[i])) add(result, '\"') -proc putComment(g: var TSrcGen, s: string) = +proc putComment(g: var TSrcGen, s: string) = + if s.isNil: return var i = 0 var comIndent = 1 var isCode = (len(s) >= 2) and (s[1] != ' ') var ind = g.lineLen var com = "" - while true: + while true: case s[i] - of '\0': - break - of '\x0D': + of '\0': + break + of '\x0D': put(g, tkComment, com) com = "" inc(i) if s[i] == '\x0A': inc(i) optNL(g, ind) - of '\x0A': + of '\x0A': put(g, tkComment, com) com = "" inc(i) optNL(g, ind) - of '#': + of '#': add(com, s[i]) inc(i) comIndent = 0 @@ -175,10 +176,10 @@ proc putComment(g: var TSrcGen, s: string) = add(com, s[i]) inc(i) inc(comIndent) - of ' ', '\x09': + of ' ', '\x09': add(com, s[i]) inc(i) - else: + else: # we may break the comment into a multi-line comment if the line # gets too long: # compute length of the following word: @@ -195,10 +196,10 @@ proc putComment(g: var TSrcGen, s: string) = optNL(g) proc maxLineLength(s: string): int = - result = 0 + if s.isNil: return 0 var i = 0 var lineLen = 0 - while true: + while true: case s[i] of '\0': break @@ -459,7 +460,7 @@ proc lsub(n: PNode): int = of nkBreakStmt: result = lsub(n.sons[0]) + len("break_") of nkContinueStmt: result = lsub(n.sons[0]) + len("continue_") of nkPragma: result = lcomma(n) + 4 - of nkCommentStmt: result = len(n.comment) + of nkCommentStmt: result = if n.comment.isNil: 0 else: len(n.comment) of nkOfBranch: result = lcomma(n, 0, - 2) + lsub(lastSon(n)) + len("of_:_") of nkImportAs: result = lsub(n.sons[0]) + len("_as_") + lsub(n.sons[1]) of nkElifBranch: result = lsons(n) + len("elif_:_") diff --git a/compiler/rodutils.nim b/compiler/rodutils.nim index 4433ed4ab..09b92cd8a 100644 --- a/compiler/rodutils.nim +++ b/compiler/rodutils.nim @@ -10,7 +10,7 @@ ## Serialization utilities for the compiler. import strutils -proc c_sprintf(buf, frmt: cstring) {.importc: "sprintf", nodecl, varargs.} +proc c_sprintf(buf, frmt: cstring) {.importc: "sprintf", header: "<stdio.h>", nodecl, varargs.} proc toStrMaxPrecision*(f: BiggestFloat): string = if f != f: diff --git a/compiler/sem.nim b/compiler/sem.nim index 7d129caf4..8025ef70d 100644 --- a/compiler/sem.nim +++ b/compiler/sem.nim @@ -15,7 +15,8 @@ import magicsys, parser, nversion, nimsets, semfold, importer, procfind, lookups, rodread, pragmas, passes, semdata, semtypinst, sigmatch, intsets, transf, vmdef, vm, idgen, aliases, cgmeth, lambdalifting, - evaltempl, patterns, parampatterns, sempass2, pretty, semmacrosanity + evaltempl, patterns, parampatterns, sempass2, pretty, semmacrosanity, + semparallel # implementation @@ -134,7 +135,7 @@ proc isTopLevel(c: PContext): bool {.inline.} = result = c.currentScope.depthLevel <= 2 proc newSymS(kind: TSymKind, n: PNode, c: PContext): PSym = - result = newSym(kind, considerAcc(n), getCurrOwner(), n.info) + result = newSym(kind, considerQuotedIdent(n), getCurrOwner(), n.info) proc newSymG*(kind: TSymKind, n: PNode, c: PContext): PSym = # like newSymS, but considers gensym'ed symbols @@ -147,7 +148,7 @@ proc newSymG*(kind: TSymKind, n: PNode, c: PContext): PSym = # template; we must fix it here: see #909 result.owner = getCurrOwner() else: - result = newSym(kind, considerAcc(n), getCurrOwner(), n.info) + result = newSym(kind, considerQuotedIdent(n), getCurrOwner(), n.info) proc semIdentVis(c: PContext, kind: TSymKind, n: PNode, allowed: TSymFlags): PSym @@ -268,11 +269,15 @@ include hlo, seminst, semcall proc semAfterMacroCall(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = + ## Semantically check the output of a macro. + ## This involves processes such as re-checking the macro output for type + ## coherence, making sure that variables declared with 'let' aren't + ## reassigned, and binding the unbound identifiers that the macro output + ## contains. inc(evalTemplateCounter) if evalTemplateCounter > 100: globalError(s.info, errTemplateInstantiationTooNested) - let oldFriend = c.friendModule - c.friendModule = s.owner.getModule + c.friendModules.add(s.owner.getModule) result = n if s.typ.sons[0] == nil: @@ -296,11 +301,13 @@ proc semAfterMacroCall(c: PContext, n: PNode, s: PSym, result = fitNode(c, s.typ.sons[0], result) #GlobalError(s.info, errInvalidParamKindX, typeToString(s.typ.sons[0])) dec(evalTemplateCounter) - c.friendModule = oldFriend + discard c.friendModules.pop() proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym, flags: TExprFlags = {}): PNode = - markUsed(n, sym) + pushInfoContext(nOrig.info) + + markUsed(n.info, sym) if sym == c.p.owner: globalError(n.info, errRecursiveDependencyX, sym.name.s) @@ -310,6 +317,7 @@ proc semMacroExpr(c: PContext, n, nOrig: PNode, sym: PSym, result = evalMacroCall(c.module, n, nOrig, sym) if efNoSemCheck notin flags: result = semAfterMacroCall(c, result, sym, flags) + popInfoContext() proc forceBool(c: PContext, n: PNode): PNode = result = fitNode(c, getSysType(tyBool), n) diff --git a/compiler/semcall.nim b/compiler/semcall.nim index 04d280ce2..65a2d7ab8 100644 --- a/compiler/semcall.nim +++ b/compiler/semcall.nim @@ -168,7 +168,7 @@ proc resolveOverloads(c: PContext, n, orig: PNode, pickBest(callOp) if overloadsState == csEmpty and result.state == csEmpty: - localError(n.info, errUndeclaredIdentifier, considerAcc(f).s) + localError(n.info, errUndeclaredIdentifier, considerQuotedIdent(f).s) return elif result.state != csMatch: if nfExprCall in n.flags: @@ -251,7 +251,7 @@ proc inferWithMetatype(c: PContext, formal: PType, proc semResolvedCall(c: PContext, n: PNode, x: TCandidate): PNode = assert x.state == csMatch var finalCallee = x.calleeSym - markUsed(n.sons[0], finalCallee) + markUsed(n.sons[0].info, finalCallee) if finalCallee.ast == nil: internalError(n.info, "calleeSym.ast is nil") # XXX: remove this check! if finalCallee.ast.sons[genericParamsPos].kind != nkEmpty: @@ -283,7 +283,7 @@ proc explicitGenericSym(c: PContext, n: PNode, s: PSym): PNode = var m: TCandidate initCandidate(c, m, s, n) var newInst = generateInstance(c, s, m.bindings, n.info) - markUsed(n, s) + markUsed(n.info, s) result = newSymNode(newInst, n.info) proc explicitGenericInstantiation(c: PContext, n: PNode, s: PSym): PNode = diff --git a/compiler/semdata.nim b/compiler/semdata.nim index 987a70a41..abecc1b6d 100644 --- a/compiler/semdata.nim +++ b/compiler/semdata.nim @@ -52,7 +52,7 @@ type importTable*: PScope # scope for all imported symbols topLevelScope*: PScope # scope for all top-level symbols p*: PProcCon # procedure context - friendModule*: PSym # current friend module; may access private data; + friendModules*: seq[PSym] # friend modules; may access private data; # this is used so that generic instantiations # can access private object fields instCounter*: int # to prevent endless instantiations @@ -91,6 +91,7 @@ type generics*: seq[TInstantiationPair] # pending list of instantiated generics to compile lastGenericIdx*: int # used for the generics stack hloLoopDetector*: int # used to prevent endless loops in the HLO + inParallelStmt*: int proc makeInstPair*(s: PSym, inst: PInstantiation): TInstantiationPair = result.genericSym = s @@ -168,7 +169,7 @@ proc newContext(module: PSym): PContext = initLinkedList(result.libs) append(result.optionStack, newOptionEntry()) result.module = module - result.friendModule = module + result.friendModules = @[module] result.converters = @[] result.patterns = @[] result.includedFiles = initIntSet() diff --git a/compiler/semexprs.nim b/compiler/semexprs.nim index 652e1dd4b..7f97124e1 100644 --- a/compiler/semexprs.nim +++ b/compiler/semexprs.nim @@ -12,7 +12,7 @@ proc semTemplateExpr(c: PContext, n: PNode, s: PSym, flags: TExprFlags = {}): PNode = - markUsed(n, s) + markUsed(n.info, s) pushInfoContext(n.info) result = evalTemplate(n, s, getCurrOwner()) if efNoSemCheck notin flags: result = semAfterMacroCall(c, result, s, flags) @@ -78,7 +78,7 @@ proc inlineConst(n: PNode, s: PSym): PNode {.inline.} = proc semSym(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = case s.kind of skConst: - markUsed(n, s) + markUsed(n.info, s) case skipTypes(s.typ, abstractInst-{tyTypeDesc}).kind of tyNil, tyChar, tyInt..tyInt64, tyFloat..tyFloat128, tyTuple, tySet, tyUInt..tyUInt64: @@ -101,7 +101,7 @@ proc semSym(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = of skMacro: result = semMacroExpr(c, n, n, s, flags) of skTemplate: result = semTemplateExpr(c, n, s, flags) of skVar, skLet, skResult, skParam, skForVar: - markUsed(n, s) + markUsed(n.info, s) # if a proc accesses a global variable, it is not side effect free: if sfGlobal in s.flags: incl(c.p.owner.flags, sfSideEffect) @@ -123,13 +123,13 @@ proc semSym(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = n.typ = s.typ return n of skType: - markUsed(n, s) + markUsed(n.info, s) if s.typ.kind == tyStatic and s.typ.n != nil: return s.typ.n result = newSymNode(s, n.info) result.typ = makeTypeDesc(c, s.typ) else: - markUsed(n, s) + markUsed(n.info, s) result = newSymNode(s, n.info) type @@ -166,6 +166,7 @@ proc checkConvertible(c: PContext, castDest, src: PType): TConvStatus = elif (skipTypes(castDest, abstractVarRange).kind in IntegralTypes) and (skipTypes(src, abstractVarRange-{tyTypeDesc}).kind in IntegralTypes): # accept conversion between integral types + discard else: # we use d, s here to speed up that operation a bit: case cmpTypes(c, d, s) @@ -175,21 +176,26 @@ proc checkConvertible(c: PContext, castDest, src: PType): TConvStatus = else: discard -proc isCastable(dst, src: PType): bool = +proc isCastable(dst, src: PType): bool = + ## Checks whether the source type can be casted to the destination type. + ## Casting is very unrestrictive; casts are allowed as long as + ## castDest.size >= src.size, and typeAllowed(dst, skParam) #const # castableTypeKinds = {tyInt, tyPtr, tyRef, tyCstring, tyString, # tySequence, tyPointer, tyNil, tyOpenArray, # tyProc, tySet, tyEnum, tyBool, tyChar} - var ds, ss: BiggestInt - # this is very unrestrictive; cast is allowed if castDest.size >= src.size - ds = computeSize(dst) - ss = computeSize(src) - if ds < 0: + var dstSize, srcSize: BiggestInt + + dstSize = computeSize(dst) + srcSize = computeSize(src) + if dstSize < 0: result = false - elif ss < 0: + elif srcSize < 0: + result = false + elif not typeAllowed(dst, skParam): result = false else: - result = (ds >= ss) or + result = (dstSize >= srcSize) or (skipTypes(dst, abstractInst).kind in IntegralTypes) or (skipTypes(src, abstractInst-{tyTypeDesc}).kind in IntegralTypes) @@ -247,12 +253,13 @@ proc semConv(c: PContext, n: PNode): PNode = let it = op.sons[i] let status = checkConvertible(c, result.typ, it.typ) if status in {convOK, convNotNeedeed}: - markUsed(n, it.sym) + markUsed(n.info, it.sym) markIndirect(c, it.sym) return it localError(n.info, errUseQualifier, op.sons[0].sym.name.s) proc semCast(c: PContext, n: PNode): PNode = + ## Semantically analyze a casting ("cast[type](param)") if optSafeCode in gGlobalOptions: localError(n.info, errCastNotInSafeMode) #incl(c.p.owner.flags, sfSideEffect) checkSonsLen(n, 2) @@ -386,7 +393,7 @@ proc semOpAux(c: PContext, n: PNode) = var a = n.sons[i] if a.kind == nkExprEqExpr and sonsLen(a) == 2: var info = a.sons[0].info - a.sons[0] = newIdentNode(considerAcc(a.sons[0]), info) + a.sons[0] = newIdentNode(considerQuotedIdent(a.sons[0]), info) a.sons[1] = semExprWithType(c, a.sons[1], flags) a.typ = a.sons[1].typ else: @@ -785,6 +792,10 @@ proc semIndirectOp(c: PContext, n: PNode, flags: TExprFlags): PNode = n.flags.incl nfExprCall result = semOverloadedCallAnalyseEffects(c, n, nOrig, flags) if result == nil: return errorNode(c, n) + elif result.kind notin nkCallKinds: + # the semExpr() in overloadedCallOpr can even break this condition! + # See bug #904 of how to trigger it: + return result #result = afterCallActions(c, result, nOrig, flags) fixAbstractType(c, result) analyseIfAddressTakenInCall(c, result) @@ -964,12 +975,12 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = var s = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared}) if s != nil: - markUsed(n.sons[1], s) + markUsed(n.sons[1].info, s) return semSym(c, n, s, flags) n.sons[0] = semExprWithType(c, n.sons[0], flags+{efDetermineType}) #restoreOldStyleType(n.sons[0]) - var i = considerAcc(n.sons[1]) + var i = considerQuotedIdent(n.sons[1]) var ty = n.sons[0].typ var f: PSym = nil result = nil @@ -987,7 +998,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = result = newSymNode(f) result.info = n.info result.typ = ty - markUsed(n, f) + markUsed(n.info, f) return of tyTypeParamsHolders: return readTypeParameter(c, ty, i, n.info) @@ -1019,7 +1030,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = if f != nil: if fieldVisible(c, f): # is the access to a public field or in the same module or in a friend? - markUsed(n.sons[1], f) + markUsed(n.sons[1].info, f) n.sons[0] = makeDeref(n.sons[0]) n.sons[1] = newSymNode(f) # we now have the correct field n.typ = f.typ @@ -1032,7 +1043,7 @@ proc builtinFieldAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = elif ty.kind == tyTuple and ty.n != nil: f = getSymFromList(ty.n, i) if f != nil: - markUsed(n.sons[1], f) + markUsed(n.sons[1].info, f) n.sons[0] = makeDeref(n.sons[0]) n.sons[1] = newSymNode(f) n.typ = f.typ @@ -1050,7 +1061,7 @@ proc dotTransformation(c: PContext, n: PNode): PNode = addSon(result, n.sons[1]) addSon(result, copyTree(n[0])) else: - var i = considerAcc(n.sons[1]) + var i = considerQuotedIdent(n.sons[1]) result = newNodeI(nkDotCall, n.info) result.flags.incl nfDotField addSon(result, newIdentNode(i, n[1].info)) @@ -1134,7 +1145,7 @@ proc semArrayAccess(c: PContext, n: PNode, flags: TExprFlags): PNode = result = semExpr(c, buildOverloadedSubscripts(n, getIdent"[]")) proc propertyWriteAccess(c: PContext, n, nOrig, a: PNode): PNode = - var id = considerAcc(a[1]) + var id = considerQuotedIdent(a[1]) var setterId = newIdentNode(getIdent(id.s & '='), n.info) # a[0] is already checked for semantics, that does ``builtinFieldAccess`` # this is ugly. XXX Semantic checking should use the ``nfSem`` flag for @@ -1368,7 +1379,7 @@ proc lookUpForDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PSym = else: localError(n.sons[1].info, errIdentifierExpected, "") of nkAccQuoted: - result = lookUpForDefined(c, considerAcc(n), onlyCurrentScope) + result = lookUpForDefined(c, considerQuotedIdent(n), onlyCurrentScope) of nkSym: result = n.sym else: @@ -1387,11 +1398,6 @@ proc semDefined(c: PContext, n: PNode, onlyCurrentScope: bool): PNode = result.info = n.info result.typ = getSysType(tyBool) -proc setMs(n: PNode, s: PSym): PNode = - result = n - n.sons[0] = newSymNode(s) - n.sons[0].info = n.info - proc expectMacroOrTemplateCall(c: PContext, n: PNode): PSym = ## The argument to the proc should be nkCall(...) or similar ## Returns the macro/template symbol @@ -1448,7 +1454,7 @@ proc semExpandToAst(c: PContext, n: PNode): PNode = if expandedSym.kind == skError: return n macroCall.sons[0] = newSymNode(expandedSym, macroCall.info) - markUsed(n, expandedSym) + markUsed(n.info, expandedSym) for i in countup(1, macroCall.len-1): macroCall.sons[i] = semExprWithType(c, macroCall[i], {}) @@ -1583,6 +1589,27 @@ proc semShallowCopy(c: PContext, n: PNode, flags: TExprFlags): PNode = else: result = semDirectOp(c, n, flags) +proc createFlowVar(c: PContext; t: PType; info: TLineInfo): PType = + result = newType(tyGenericInvokation, c.module) + addSonSkipIntLit(result, magicsys.getCompilerProc("FlowVar").typ) + addSonSkipIntLit(result, t) + result = instGenericContainer(c, info, result, allowMetaTypes = false) + +proc instantiateCreateFlowVarCall(c: PContext; t: PType; + info: TLineInfo): PSym = + let sym = magicsys.getCompilerProc("nimCreateFlowVar") + if sym == nil: + localError(info, errSystemNeeds, "nimCreateFlowVar") + var bindings: TIdTable + initIdTable(bindings) + bindings.idTablePut(sym.ast[genericParamsPos].sons[0].typ, t) + result = c.semGenerateInstance(c, sym, bindings, info) + +proc setMs(n: PNode, s: PSym): PNode = + result = n + n.sons[0] = newSymNode(s) + n.sons[0].info = n.info + proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = # this is a hotspot in the compiler! # DON'T forget to update ast.SpecialSemMagics if you add a magic here! @@ -1604,6 +1631,22 @@ proc semMagic(c: PContext, n: PNode, s: PSym, flags: TExprFlags): PNode = checkSonsLen(n, 2) result = newStrNodeT(renderTree(n[1], {renderNoComments}), n) result.typ = getSysType(tyString) + of mParallel: + result = setMs(n, s) + var x = n.lastSon + if x.kind == nkDo: x = x.sons[bodyPos] + inc c.inParallelStmt + result.sons[1] = semStmt(c, x) + dec c.inParallelStmt + of mSpawn: + result = setMs(n, s) + result.sons[1] = semExpr(c, n.sons[1]) + if not result[1].typ.isEmptyType: + if c.inParallelStmt > 0: + result.typ = result[1].typ + else: + result.typ = createFlowVar(c, result[1].typ, n.info) + result.add instantiateCreateFlowVarCall(c, result[1].typ, n.info).newSymNode else: result = semDirectOp(c, n, flags) proc semWhen(c: PContext, n: PNode, semCheck = true): PNode = @@ -1842,7 +1885,7 @@ proc semBlock(c: PContext, n: PNode): PNode = if sfGenSym notin labl.flags: addDecl(c, labl) n.sons[0] = newSymNode(labl, n.sons[0].info) - suggestSym(n.sons[0], labl) + suggestSym(n.sons[0].info, labl) n.sons[1] = semExpr(c, n.sons[1]) n.typ = n.sons[1].typ if isEmptyType(n.typ): n.kind = nkBlockStmt @@ -1962,7 +2005,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = var s = qualifiedLookUp(c, n.sons[0], mode) if s != nil: if gCmd == cmdPretty and n.sons[0].kind == nkDotExpr: - pretty.checkUse(n.sons[0].sons[1], s) + pretty.checkUse(n.sons[0].sons[1].info, s) case s.kind of skMacro: if sfImmediate notin s.flags: @@ -2060,6 +2103,7 @@ proc semExpr(c: PContext, n: PNode, flags: TExprFlags = {}): PNode = of nkClosedSymChoice, nkOpenSymChoice: # handling of sym choices is context dependent # the node is left intact for now + discard of nkStaticExpr: result = semStaticExpr(c, n) of nkAsgn: result = semAsgn(c, n) diff --git a/compiler/semfold.nim b/compiler/semfold.nim index 79abfaf4d..30e02dcc9 100644 --- a/compiler/semfold.nim +++ b/compiler/semfold.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -380,6 +380,7 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = of mInSet: result = newIntNodeT(ord(inSet(a, b)), n) of mRepr: # BUGFIX: we cannot eval mRepr here for reasons that I forgot. + discard of mIntToStr, mInt64ToStr: result = newStrNodeT($(getOrdValue(a)), n) of mBoolToStr: if getOrdValue(a) == 0: result = newStrNodeT("false", n) @@ -404,10 +405,8 @@ proc evalOp(m: TMagic, n, a, b, c: PNode): PNode = mExit, mInc, ast.mDec, mEcho, mSwap, mAppendStrCh, mAppendStrStr, mAppendSeqElem, mSetLengthStr, mSetLengthSeq, mParseExprToAst, mParseStmtToAst, mExpandToAst, mTypeTrait, - mNLen..mNError, mEqRef, mSlurp, mStaticExec, mNGenSym, mSpawn: + mNLen..mNError, mEqRef, mSlurp, mStaticExec, mNGenSym, mSpawn, mParallel: discard - of mRand: - result = newIntNodeT(math.random(a.getInt.int), n) else: internalError(a.info, "evalOp(" & $m & ')') proc getConstIfExpr(c: PSym, n: PNode): PNode = @@ -538,17 +537,18 @@ proc foldArrayAccess(m: PSym, n: PNode): PNode = var idx = getOrdValue(y) case x.kind of nkPar: - if (idx >= 0) and (idx < sonsLen(x)): + if idx >= 0 and idx < sonsLen(x): result = x.sons[int(idx)] if result.kind == nkExprColonExpr: result = result.sons[1] else: localError(n.info, errIndexOutOfBounds) - of nkBracket: - if (idx >= 0) and (idx < sonsLen(x)): result = x.sons[int(idx)] + of nkBracket: + idx = idx - x.typ.firstOrd + if idx >= 0 and idx < x.len: result = x.sons[int(idx)] else: localError(n.info, errIndexOutOfBounds) - of nkStrLit..nkTripleStrLit: + of nkStrLit..nkTripleStrLit: result = newNodeIT(nkCharLit, x.info, n.typ) - if (idx >= 0) and (idx < len(x.strVal)): + if idx >= 0 and idx < len(x.strVal): result.intVal = ord(x.strVal[int(idx)]) elif idx == len(x.strVal): discard diff --git a/compiler/semgnrc.nim b/compiler/semgnrc.nim index da4a2a132..934434951 100644 --- a/compiler/semgnrc.nim +++ b/compiler/semgnrc.nim @@ -69,7 +69,7 @@ proc semGenericStmtSymbol(c: PContext, n: PNode, s: PSym): PNode = proc lookup(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var TIntSet): PNode = result = n - let ident = considerAcc(n) + let ident = considerQuotedIdent(n) var s = searchInScopes(c, ident) if s == nil: if ident.id notin ctx and withinMixin notin flags: @@ -82,7 +82,37 @@ proc lookup(c: PContext, n: PNode, flags: TSemGenericFlags, else: result = semGenericStmtSymbol(c, n, s) # else: leave as nkIdent + +proc newDot(n, b: PNode): PNode = + result = newNodeI(nkDotExpr, n.info) + result.add(n.sons[0]) + result.add(b) + +proc fuzzyLookup(c: PContext, n: PNode, flags: TSemGenericFlags, + ctx: var TIntSet): PNode = + assert n.kind == nkDotExpr + let luf = if withinMixin notin flags: {checkUndeclared} else: {} + var s = qualifiedLookUp(c, n, luf) + if s != nil: + result = semGenericStmtSymbol(c, n, s) + else: + result = n + let n = n[1] + let ident = considerQuotedIdent(n) + var s = searchInScopes(c, ident) + if s != nil and s.kind in routineKinds: + if withinBind in flags: + result = newDot(result, symChoice(c, n, s, scClosed)) + elif s.name.id in ctx: + result = newDot(result, symChoice(c, n, s, scForceOpen)) + else: + let sym = semGenericStmtSymbol(c, n, s) + if sym.kind == nkSym: + result = newDot(result, symChoice(c, n, s, scForceOpen)) + else: + result = newDot(result, sym) + proc semGenericStmt(c: PContext, n: PNode, flags: TSemGenericFlags, ctx: var TIntSet): PNode = result = n @@ -91,10 +121,11 @@ proc semGenericStmt(c: PContext, n: PNode, of nkIdent, nkAccQuoted: result = lookup(c, n, flags, ctx) of nkDotExpr: - let luf = if withinMixin notin flags: {checkUndeclared} else: {} - var s = qualifiedLookUp(c, n, luf) - if s != nil: result = semGenericStmtSymbol(c, n, s) + #let luf = if withinMixin notin flags: {checkUndeclared} else: {} + #var s = qualifiedLookUp(c, n, luf) + #if s != nil: result = semGenericStmtSymbol(c, n, s) # XXX for example: ``result.add`` -- ``add`` needs to be looked up here... + result = fuzzyLookup(c, n, flags, ctx) of nkEmpty, nkSym..nkNilLit: # see tests/compile/tgensymgeneric.nim: # We need to open the gensym'ed symbol again so that the instantiation @@ -114,7 +145,7 @@ proc semGenericStmt(c: PContext, n: PNode, let fn = n.sons[0] var s = qualifiedLookUp(c, fn, {}) if s == nil and withinMixin notin flags and - fn.kind in {nkIdent, nkAccQuoted} and considerAcc(fn).id notin ctx: + fn.kind in {nkIdent, nkAccQuoted} and considerQuotedIdent(fn).id notin ctx: localError(n.info, errUndeclaredIdentifier, fn.renderTree) var first = 0 @@ -141,6 +172,7 @@ proc semGenericStmt(c: PContext, n: PNode, # symbol lookup ... of skUnknown, skParam: # Leave it as an identifier. + discard of skProc, skMethod, skIterators, skConverter: result.sons[0] = symChoice(c, n.sons[0], s, scOption) first = 1 diff --git a/compiler/seminst.nim b/compiler/seminst.nim index f7d5fa6f8..b93d7ca15 100644 --- a/compiler/seminst.nim +++ b/compiler/seminst.nim @@ -190,6 +190,9 @@ proc instantiateProcType(c: PContext, pt: TIdTable, proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, info: TLineInfo): PSym = + ## Generates a new instance of a generic procedure. + ## The `pt` parameter is a type-unsafe mapping table used to link generic + ## parameters to their concrete types within the generic instance. # no need to instantiate generic templates/macros: if fn.kind in {skTemplate, skMacro}: return fn # generates an instantiated proc @@ -199,8 +202,7 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, var n = copyTree(fn.ast) # NOTE: for access of private fields within generics from a different module # we set the friend module: - var oldFriend = c.friendModule - c.friendModule = getModule(fn) + c.friendModules.add(getModule(fn)) #let oldScope = c.currentScope #c.currentScope = fn.scope result = copySym(fn, false) @@ -236,6 +238,6 @@ proc generateInstance(c: PContext, fn: PSym, pt: TIdTable, closeScope(c) # close scope for parameters popOwner() #c.currentScope = oldScope - c.friendModule = oldFriend + discard c.friendModules.pop() dec(c.instCounter) if result.kind == skMethod: finishMethod(c, result) diff --git a/compiler/semmagic.nim b/compiler/semmagic.nim index 4caf1fb8e..f943e7006 100644 --- a/compiler/semmagic.nim +++ b/compiler/semmagic.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -131,4 +131,3 @@ proc magicsAfterOverloadResolution(c: PContext, n: PNode, of mNBindSym: result = semBindSym(c, n) of mLocals: result = semLocals(c, n) else: result = n - diff --git a/compiler/semparallel.nim b/compiler/semparallel.nim new file mode 100644 index 000000000..c594a4788 --- /dev/null +++ b/compiler/semparallel.nim @@ -0,0 +1,465 @@ +# +# +# The Nimrod Compiler +# (c) Copyright 2014 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Semantic checking for 'parallel'. + +# - codegen needs to support mSlice (+) +# - lowerings must not perform unnecessary copies (+) +# - slices should become "nocopy" to openArray (+) +# - need to perform bound checks (+) +# +# - parallel needs to insert a barrier (+) +# - passed arguments need to be ensured to be "const" +# - what about 'f(a)'? --> f shouldn't have side effects anyway +# - passed arrays need to be ensured not to alias +# - passed slices need to be ensured to be disjoint (+) +# - output slices need special logic (+) + +import + ast, astalgo, idents, lowerings, magicsys, guards, sempass2, msgs, + renderer +from trees import getMagic +from strutils import `%` + +discard """ + +one major problem: + spawn f(a[i]) + inc i + spawn f(a[i]) +is valid, but + spawn f(a[i]) + spawn f(a[i]) + inc i +is not! However, + spawn f(a[i]) + if guard: inc i + spawn f(a[i]) +is not valid either! --> We need a flow dependent analysis here. + +However: + while foo: + spawn f(a[i]) + inc i + spawn f(a[i]) + +Is not valid either! --> We should really restrict 'inc' to loop endings? + +The heuristic that we implement here (that has no false positives) is: Usage +of 'i' in a slice *after* we determined the stride is invalid! +""" + +type + TDirection = enum + ascending, descending + MonotonicVar = object + v, alias: PSym # to support the ordinary 'countup' iterator + # we need to detect aliases + lower, upper, stride: PNode + dir: TDirection + blacklisted: bool # blacklisted variables that are not monotonic + AnalysisCtx = object + locals: seq[MonotonicVar] + slices: seq[tuple[x,a,b: PNode, spawnId: int, inLoop: bool]] + guards: TModel # nested guards + args: seq[PSym] # args must be deeply immutable + spawns: int # we can check that at last 1 spawn is used in + # the 'parallel' section + currentSpawnId: int + inLoop: int + +let opSlice = createMagic("slice", mSlice) + +proc initAnalysisCtx(): AnalysisCtx = + result.locals = @[] + result.slices = @[] + result.args = @[] + result.guards = @[] + +proc lookupSlot(c: AnalysisCtx; s: PSym): int = + for i in 0.. <c.locals.len: + if c.locals[i].v == s or c.locals[i].alias == s: return i + return -1 + +proc getSlot(c: var AnalysisCtx; v: PSym): ptr MonotonicVar = + let s = lookupSlot(c, v) + if s >= 0: return addr(c.locals[s]) + let L = c.locals.len + c.locals.setLen(L+1) + c.locals[L].v = v + return addr(c.locals[L]) + +proc gatherArgs(c: var AnalysisCtx; n: PNode) = + for i in 0.. <n.safeLen: + let root = getRoot n[i] + if root != nil: + block addRoot: + for r in items(c.args): + if r == root: break addRoot + c.args.add root + gatherArgs(c, n[i]) + +proc isSingleAssignable(n: PNode): bool = + n.kind == nkSym and (let s = n.sym; + s.kind in {skTemp, skForVar, skLet} and + {sfAddrTaken, sfGlobal} * s.flags == {}) + +proc isLocal(n: PNode): bool = + n.kind == nkSym and (let s = n.sym; + s.kind in {skResult, skTemp, skForVar, skVar, skLet} and + {sfAddrTaken, sfGlobal} * s.flags == {}) + +proc checkLocal(c: AnalysisCtx; n: PNode) = + if isLocal(n): + let s = c.lookupSlot(n.sym) + if s >= 0 and c.locals[s].stride != nil: + localError(n.info, "invalid usage of counter after increment") + else: + for i in 0 .. <n.safeLen: checkLocal(c, n.sons[i]) + +template `?`(x): expr = x.renderTree + +proc checkLe(c: AnalysisCtx; a, b: PNode) = + case proveLe(c.guards, a, b) + of impUnknown: + localError(a.info, "cannot prove: " & ?a & " <= " & ?b) + of impYes: discard + of impNo: + localError(a.info, "can prove: " & ?a & " > " & ?b) + +proc checkBounds(c: AnalysisCtx; arr, idx: PNode) = + checkLe(c, arr.lowBound, idx) + checkLe(c, idx, arr.highBound) + +proc addLowerBoundAsFacts(c: var AnalysisCtx) = + for v in c.locals: + if not v.blacklisted: + c.guards.addFactLe(v.lower, newSymNode(v.v)) + +proc addSlice(c: var AnalysisCtx; n: PNode; x, le, ri: PNode) = + checkLocal(c, n) + let le = le.canon + let ri = ri.canon + # perform static bounds checking here; and not later! + let oldState = c.guards.len + addLowerBoundAsFacts(c) + c.checkBounds(x, le) + c.checkBounds(x, ri) + c.guards.setLen(oldState) + c.slices.add((x, le, ri, c.currentSpawnId, c.inLoop > 0)) + +proc overlap(m: TModel; x,y,c,d: PNode) = + # X..Y and C..D overlap iff (X <= D and C <= Y) + case proveLe(m, x, d) + of impUnknown: + localError(x.info, + "cannot prove: $# > $#; required for ($#)..($#) disjoint from ($#)..($#)" % + [?x, ?d, ?x, ?y, ?c, ?d]) + of impYes: + case proveLe(m, c, y) + of impUnknown: + localError(x.info, + "cannot prove: $# > $#; required for ($#)..($#) disjoint from ($#)..($#)" % + [?c, ?y, ?x, ?y, ?c, ?d]) + of impYes: + localError(x.info, "($#)..($#) not disjoint from ($#)..($#)" % [?x, ?y, ?c, ?d]) + of impNo: discard + of impNo: discard + +proc stride(c: AnalysisCtx; n: PNode): BiggestInt = + if isLocal(n): + let s = c.lookupSlot(n.sym) + if s >= 0 and c.locals[s].stride != nil: + result = c.locals[s].stride.intVal + else: + for i in 0 .. <n.safeLen: result += stride(c, n.sons[i]) + +proc subStride(c: AnalysisCtx; n: PNode): PNode = + # substitute with stride: + if isLocal(n): + let s = c.lookupSlot(n.sym) + if s >= 0 and c.locals[s].stride != nil: + result = n +@ c.locals[s].stride.intVal + else: + result = n + elif n.safeLen > 0: + result = shallowCopy(n) + for i in 0 .. <n.len: result.sons[i] = subStride(c, n.sons[i]) + else: + result = n + +proc checkSlicesAreDisjoint(c: var AnalysisCtx) = + # this is the only thing that we need to perform after we have traversed + # the whole tree so that the strides are available. + # First we need to add all the computed lower bounds: + addLowerBoundAsFacts(c) + # Every slice used in a loop needs to be disjoint with itself: + for x,a,b,id,inLoop in items(c.slices): + if inLoop: overlap(c.guards, a,b, c.subStride(a), c.subStride(b)) + # Another tricky example is: + # while true: + # spawn f(a[i]) + # spawn f(a[i+1]) + # inc i # inc i, 2 would be correct here + # + # Or even worse: + # while true: + # spawn f(a[i+1 .. i+3]) + # spawn f(a[i+4 .. i+5]) + # inc i, 4 + # Prove that i*k*stride + 3 != i*k'*stride + 5 + # For the correct example this amounts to + # i*k*2 != i*k'*2 + 1 + # which is true. + # For now, we don't try to prove things like that at all, even though it'd + # be feasible for many useful examples. Instead we attach the slice to + # a spawn and if the attached spawns differ, we bail out: + for i in 0 .. high(c.slices): + for j in i+1 .. high(c.slices): + let x = c.slices[i] + let y = c.slices[j] + if x.spawnId != y.spawnId and guards.sameTree(x.x, y.x): + if not x.inLoop or not y.inLoop: + # XXX strictly speaking, 'or' is not correct here and it needs to + # be 'and'. However this prevents too many obviously correct programs + # like f(a[0..x]); for i in x+1 .. a.high: f(a[i]) + overlap(c.guards, x.a, x.b, y.a, y.b) + elif (let k = simpleSlice(x.a, x.b); let m = simpleSlice(y.a, y.b); + k >= 0 and m >= 0): + # ah I cannot resist the temptation and add another sweet heuristic: + # if both slices have the form (i+k)..(i+k) and (i+m)..(i+m) we + # check they are disjoint and k < stride and m < stride: + overlap(c.guards, x.a, x.b, y.a, y.b) + let stride = min(c.stride(x.a), c.stride(y.a)) + if k < stride and m < stride: + discard + else: + localError(x.x.info, "cannot prove ($#)..($#) disjoint from ($#)..($#)" % + [?x.a, ?x.b, ?y.a, ?y.b]) + else: + localError(x.x.info, "cannot prove ($#)..($#) disjoint from ($#)..($#)" % + [?x.a, ?x.b, ?y.a, ?y.b]) + +proc analyse(c: var AnalysisCtx; n: PNode) + +proc analyseSons(c: var AnalysisCtx; n: PNode) = + for i in 0 .. <safeLen(n): analyse(c, n[i]) + +proc min(a, b: PNode): PNode = + if a.isNil: result = b + elif a.intVal < b.intVal: result = a + else: result = b + +proc fromSystem(op: PSym): bool = sfSystemModule in getModule(op).flags + +proc analyseCall(c: var AnalysisCtx; n: PNode; op: PSym) = + if op.magic == mSpawn: + inc c.spawns + let oldSpawnId = c.currentSpawnId + c.currentSpawnId = c.spawns + gatherArgs(c, n[1]) + analyseSons(c, n) + c.currentSpawnId = oldSpawnId + elif op.magic == mInc or (op.name.s == "+=" and op.fromSystem): + if n[1].isLocal: + let incr = n[2].skipConv + if incr.kind in {nkCharLit..nkUInt32Lit} and incr.intVal > 0: + let slot = c.getSlot(n[1].sym) + slot.stride = min(slot.stride, incr) + analyseSons(c, n) + elif op.name.s == "[]" and op.fromSystem: + c.addSlice(n, n[1], n[2][1], n[2][2]) + analyseSons(c, n) + elif op.name.s == "[]=" and op.fromSystem: + c.addSlice(n, n[1], n[2][1], n[2][2]) + analyseSons(c, n) + else: + analyseSons(c, n) + +proc analyseCase(c: var AnalysisCtx; n: PNode) = + analyse(c, n.sons[0]) + let oldFacts = c.guards.len + for i in 1.. <n.len: + let branch = n.sons[i] + setLen(c.guards, oldFacts) + addCaseBranchFacts(c.guards, n, i) + for i in 0 .. <branch.len: + analyse(c, branch.sons[i]) + setLen(c.guards, oldFacts) + +proc analyseIf(c: var AnalysisCtx; n: PNode) = + analyse(c, n.sons[0].sons[0]) + let oldFacts = c.guards.len + addFact(c.guards, canon(n.sons[0].sons[0])) + + analyse(c, n.sons[0].sons[1]) + for i in 1.. <n.len: + let branch = n.sons[i] + setLen(c.guards, oldFacts) + for j in 0..i-1: + addFactNeg(c.guards, canon(n.sons[j].sons[0])) + if branch.len > 1: + addFact(c.guards, canon(branch.sons[0])) + for i in 0 .. <branch.len: + analyse(c, branch.sons[i]) + setLen(c.guards, oldFacts) + +proc analyse(c: var AnalysisCtx; n: PNode) = + case n.kind + of nkAsgn, nkFastAsgn: + if n[0].isSingleAssignable and n[1].isLocal: + let slot = c.getSlot(n[1].sym) + slot.alias = n[0].sym + elif n[0].isLocal: + # since we already ensure sfAddrTaken is not in s.flags, we only need to + # prevent direct assignments to the monotonic variable: + let slot = c.getSlot(n[0].sym) + slot.blackListed = true + invalidateFacts(c.guards, n[0]) + analyseSons(c, n) + addAsgnFact(c.guards, n[0], n[1]) + of nkCallKinds: + # direct call: + if n[0].kind == nkSym: analyseCall(c, n, n[0].sym) + else: analyseSons(c, n) + of nkBracketExpr: + c.addSlice(n, n[0], n[1], n[1]) + analyseSons(c, n) + of nkReturnStmt, nkRaiseStmt, nkTryStmt: + localError(n.info, "invalid control flow for 'parallel'") + # 'break' that leaves the 'parallel' section is not valid either + # or maybe we should generate a 'try' XXX + of nkVarSection: + for it in n: + let value = it.lastSon + if value.kind != nkEmpty: + for j in 0 .. it.len-3: + if it[j].isLocal: + let slot = c.getSlot(it[j].sym) + if slot.lower.isNil: slot.lower = value + else: internalError(it.info, "slot already has a lower bound") + analyse(c, value) + of nkCaseStmt: analyseCase(c, n) + of nkIfStmt, nkIfExpr: analyseIf(c, n) + of nkWhileStmt: + analyse(c, n.sons[0]) + # 'while true' loop? + inc c.inLoop + if isTrue(n.sons[0]): + analyseSons(c, n.sons[1]) + else: + # loop may never execute: + let oldState = c.locals.len + let oldFacts = c.guards.len + addFact(c.guards, canon(n.sons[0])) + analyse(c, n.sons[1]) + setLen(c.locals, oldState) + setLen(c.guards, oldFacts) + # we know after the loop the negation holds: + if not hasSubnodeWith(n.sons[1], nkBreakStmt): + addFactNeg(c.guards, canon(n.sons[0])) + dec c.inLoop + of nkTypeSection, nkProcDef, nkConverterDef, nkMethodDef, nkIteratorDef, + nkMacroDef, nkTemplateDef, nkConstSection, nkPragma: + discard + else: + analyseSons(c, n) + +proc transformSlices(n: PNode): PNode = + if n.kind in nkCallKinds and n[0].kind == nkSym: + let op = n[0].sym + if op.name.s == "[]" and op.fromSystem: + result = copyNode(n) + result.add opSlice.newSymNode + result.add n[1] + result.add n[2][1] + result.add n[2][2] + return result + if n.safeLen > 0: + result = shallowCopy(n) + for i in 0 .. < n.len: + result.sons[i] = transformSlices(n.sons[i]) + else: + result = n + +proc transformSpawn(owner: PSym; n, barrier: PNode): PNode +proc transformSpawnSons(owner: PSym; n, barrier: PNode): PNode = + result = shallowCopy(n) + for i in 0 .. < n.len: + result.sons[i] = transformSpawn(owner, n.sons[i], barrier) + +proc transformSpawn(owner: PSym; n, barrier: PNode): PNode = + case n.kind + of nkVarSection: + result = nil + for it in n: + let b = it.lastSon + if getMagic(b) == mSpawn: + if it.len != 3: localError(it.info, "invalid context for 'spawn'") + let m = transformSlices(b) + if result.isNil: + result = newNodeI(nkStmtList, n.info) + result.add n + result.add wrapProcForSpawn(owner, m, b.typ, barrier, it[0]) + it.sons[it.len-1] = emptyNode + if result.isNil: result = n + of nkAsgn, nkFastAsgn: + let b = n[1] + if getMagic(b) == mSpawn: + let m = transformSlices(b) + return wrapProcForSpawn(owner, m, b.typ, barrier, n[0]) + result = transformSpawnSons(owner, n, barrier) + of nkCallKinds: + if getMagic(n) == mSpawn: + result = transformSlices(n) + return wrapProcForSpawn(owner, result, n.typ, barrier, nil) + result = transformSpawnSons(owner, n, barrier) + elif n.safeLen > 0: + result = transformSpawnSons(owner, n, barrier) + else: + result = n + +proc checkArgs(a: var AnalysisCtx; n: PNode) = + discard "too implement" + +proc generateAliasChecks(a: AnalysisCtx; result: PNode) = + discard "too implement" + +proc liftParallel*(owner: PSym; n: PNode): PNode = + # this needs to be called after the 'for' loop elimination + + # first pass: + # - detect monotonic local integer variables + # - detect used slices + # - detect used arguments + #echo "PAR ", renderTree(n) + + var a = initAnalysisCtx() + let body = n.lastSon + analyse(a, body) + if a.spawns == 0: + localError(n.info, "'parallel' section without 'spawn'") + checkSlicesAreDisjoint(a) + checkArgs(a, body) + + var varSection = newNodeI(nkVarSection, n.info) + var temp = newSym(skTemp, getIdent"barrier", owner, n.info) + temp.typ = magicsys.getCompilerProc("Barrier").typ + incl(temp.flags, sfFromGeneric) + let tempNode = newSymNode(temp) + varSection.addVar tempNode + + let barrier = genAddrOf(tempNode) + result = newNodeI(nkStmtList, n.info) + generateAliasChecks(a, result) + result.add varSection + result.add callCodeGenProc("openBarrier", barrier) + result.add transformSpawn(owner, body, barrier) + result.add callCodeGenProc("closeBarrier", barrier) + diff --git a/compiler/sempass2.nim b/compiler/sempass2.nim index 6235fb76a..c8ce5e787 100644 --- a/compiler/sempass2.nim +++ b/compiler/sempass2.nim @@ -1,7 +1,7 @@ # # # The Nimrod Compiler -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -89,7 +89,7 @@ proc initVarViaNew(a: PEffects, n: PNode) = if n.kind != nkSym: return let s = n.sym if {tfNeedsInit, tfNotNil} * s.typ.flags <= {tfNotNil}: - # 'x' is not nil, but that doesn't mean it's not nil children + # 'x' is not nil, but that doesn't mean its "not nil" children # are initialized: initVar(a, n) @@ -478,13 +478,18 @@ proc trackBlock(tracked: PEffects, n: PNode) = else: track(tracked, n) -proc isTrue(n: PNode): bool = +proc isTrue*(n: PNode): bool = n.kind == nkSym and n.sym.kind == skEnumField and n.sym.position != 0 or n.kind == nkIntLit and n.intVal != 0 proc paramType(op: PType, i: int): PType = if op != nil and i < op.len: result = op.sons[i] +proc cstringCheck(tracked: PEffects; n: PNode) = + if n.sons[0].typ.kind == tyCString and (let a = skipConv(n[1]); + a.typ.kind == tyString and a.kind notin {nkStrLit..nkTripleStrLit}): + message(n.info, warnUnsafeCode, renderTree(n)) + proc track(tracked: PEffects, n: PNode) = case n.kind of nkSym: @@ -541,6 +546,7 @@ proc track(tracked: PEffects, n: PNode) = track(tracked, n.sons[0]) addAsgnFact(tracked.guards, n.sons[0], n.sons[1]) notNilCheck(tracked, n.sons[1], n.sons[0].typ) + when false: cstringCheck(tracked, n) of nkVarSection: for child in n: let last = lastSon(child) diff --git a/compiler/semstmts.nim b/compiler/semstmts.nim index 2429e4183..3cb9691eb 100644 --- a/compiler/semstmts.nim +++ b/compiler/semstmts.nim @@ -33,7 +33,7 @@ proc semBreakOrContinue(c: PContext, n: PNode): PNode = x.info = n.info incl(s.flags, sfUsed) n.sons[0] = x - suggestSym(x, s) + suggestSym(x.info, s) else: localError(n.info, errInvalidControlFlowX, s.name.s) elif (c.p.nestedLoopCounter <= 0) and (c.p.nestedBlockCounter <= 0): @@ -66,10 +66,16 @@ proc toCover(t: PType): BiggestInt = result = lengthOrd(skipTypes(t, abstractVar-{tyTypeDesc})) proc performProcvarCheck(c: PContext, n: PNode, s: PSym) = + ## Checks that the given symbol is a proper procedure variable, meaning + ## that it var smoduleId = getModule(s).id if sfProcvar notin s.flags and s.typ.callConv == ccDefault and - smoduleId != c.module.id and smoduleId != c.friendModule.id: - localError(n.info, errXCannotBePassedToProcVar, s.name.s) + smoduleId != c.module.id: + block outer: + for module in c.friendModules: + if smoduleId == module.id: + break outer + localError(n.info, errXCannotBePassedToProcVar, s.name.s) proc semProcvarCheck(c: PContext, n: PNode) = let n = n.skipConv @@ -190,7 +196,7 @@ proc semCase(c: PContext, n: PNode): PNode = var typ = commonTypeBegin var hasElse = false case skipTypes(n.sons[0].typ, abstractVarRange-{tyTypeDesc}).kind - of tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32: + of tyInt..tyInt64, tyChar, tyEnum, tyUInt..tyUInt32, tyBool: chckCovered = true of tyFloat..tyFloat128, tyString, tyError: discard @@ -313,7 +319,7 @@ proc semIdentDef(c: PContext, n: PNode, kind: TSymKind): PSym = incl(result.flags, sfGlobal) else: result = semIdentWithPragma(c, kind, n, {}) - suggestSym(n, result) + suggestSym(n.info, result) proc checkNilable(v: PSym) = if sfGlobal in v.flags and {tfNotNil, tfNeedsInit} * v.typ.flags != {}: @@ -655,7 +661,7 @@ proc semFor(c: PContext, n: PNode): PNode = n.sons[length-2] = semExprNoDeref(c, n.sons[length-2], {efWantIterator}) var call = n.sons[length-2] let isCallExpr = call.kind in nkCallKinds - if isCallExpr and call.sons[0].sym.magic != mNone: + if isCallExpr and call[0].kind == nkSym and call[0].sym.magic != mNone: if call.sons[0].sym.magic == mOmpParFor: result = semForVars(c, n) result.kind = nkParForStmt @@ -822,6 +828,9 @@ proc typeSectionFinalPass(c: PContext, n: PNode) = getCurrOwner(), s.info) proc semTypeSection(c: PContext, n: PNode): PNode = + ## Processes a type section. This must be done in separate passes, in order + ## to allow the type definitions in the section to reference each other + ## without regard for the order of their definitions. typeSectionLeftSidePass(c, n) typeSectionRightSidePass(c, n) typeSectionFinalPass(c, n) @@ -868,7 +877,7 @@ proc lookupMacro(c: PContext, n: PNode): PSym = result = n.sym if result.kind notin {skMacro, skTemplate}: result = nil else: - result = searchInScopes(c, considerAcc(n), {skMacro, skTemplate}) + result = searchInScopes(c, considerQuotedIdent(n), {skMacro, skTemplate}) proc semProcAnnotation(c: PContext, prc: PNode): PNode = var n = prc.sons[pragmasPos] @@ -879,7 +888,7 @@ proc semProcAnnotation(c: PContext, prc: PNode): PNode = let m = lookupMacro(c, key) if m == nil: if key.kind == nkIdent and key.ident.id == ord(wDelegator): - if considerAcc(prc.sons[namePos]).s == "()": + if considerQuotedIdent(prc.sons[namePos]).s == "()": prc.sons[namePos] = newIdentNode(idDelegator, prc.info) prc.sons[pragmasPos] = copyExcept(n, i) else: diff --git a/compiler/semtempl.nim b/compiler/semtempl.nim index ad34eea65..ee8b1ccb8 100644 --- a/compiler/semtempl.nim +++ b/compiler/semtempl.nim @@ -59,7 +59,7 @@ proc symChoice(c: PContext, n: PNode, s: PSym, r: TSymChoiceRule): PNode = # (s.kind notin routineKinds or s.magic != mNone): # for instance 'nextTry' is both in tables.nim and astalgo.nim ... result = newSymNode(s, n.info) - markUsed(n, s) + markUsed(n.info, s) else: # semantic checking requires a type; ``fitNode`` deals with it # appropriately @@ -93,7 +93,7 @@ proc semBindStmt(c: PContext, n: PNode, toBind: var TIntSet): PNode = proc semMixinStmt(c: PContext, n: PNode, toMixin: var TIntSet): PNode = for i in 0 .. < n.len: - toMixin.incl(considerAcc(n.sons[i]).id) + toMixin.incl(considerQuotedIdent(n.sons[i]).id) result = newNodeI(nkEmpty, n.info) proc replaceIdentBySym(n: var PNode, s: PNode) = @@ -151,7 +151,7 @@ proc onlyReplaceParams(c: var TemplCtx, n: PNode): PNode = result.sons[i] = onlyReplaceParams(c, n.sons[i]) proc newGenSym(kind: TSymKind, n: PNode, c: var TemplCtx): PSym = - result = newSym(kind, considerAcc(n), c.owner, n.info) + result = newSym(kind, considerQuotedIdent(n), c.owner, n.info) incl(result.flags, sfGenSym) incl(result.flags, sfShadowed) diff --git a/compiler/semtypes.nim b/compiler/semtypes.nim index 6289ecc85..53fe4e266 100644 --- a/compiler/semtypes.nim +++ b/compiler/semtypes.nim @@ -70,9 +70,10 @@ proc semEnum(c: PContext, n: PNode, prev: PType): PType = counter = x of nkSym: e = n.sons[i].sym - of nkIdent: + of nkIdent, nkAccQuoted: e = newSymS(skEnumField, n.sons[i], c) - else: illFormedAst(n) + else: + illFormedAst(n[i]) e.typ = result e.position = int(counter) if e.position == 0: hasNull = true @@ -116,7 +117,7 @@ proc semVarargs(c: PContext, n: PNode, prev: PType): PType = var base = semTypeNode(c, n.sons[1], nil) addSonSkipIntLit(result, base) if sonsLen(n) == 3: - result.n = newIdentNode(considerAcc(n.sons[2]), n.sons[2].info) + result.n = newIdentNode(considerQuotedIdent(n.sons[2]), n.sons[2].info) else: localError(n.info, errXExpectsOneTypeParam, "varargs") addSonSkipIntLit(result, errorType(c)) @@ -280,7 +281,7 @@ proc semTypeIdent(c: PContext, n: PNode): PSym = else: result = qualifiedLookUp(c, n, {checkAmbiguity, checkUndeclared}) if result != nil: - markUsed(n, result) + markUsed(n.info, result) if result.kind == skParam and result.typ.kind == tyTypeDesc: # This is a typedesc param. is it already bound? # it's not bound when it's used multiple times in the @@ -385,6 +386,7 @@ proc semIdentWithPragma(c: PContext, kind: TSymKind, n: PNode, case kind of skType: # process pragmas later, because result.typ has not been set yet + discard of skField: pragma(c, result, n.sons[1], fieldPragmas) of skVar: pragma(c, result, n.sons[1], varPragmas) of skLet: pragma(c, result, n.sons[1], letPragmas) @@ -441,14 +443,14 @@ proc semCaseBranch(c: PContext, t, branch: PNode, branchIndex: int, elif isRange(b): branch.sons[i] = semCaseBranchRange(c, t, b, covered) else: + # constant sets and arrays are allowed: var r = semConstExpr(c, b) # for ``{}`` we want to trigger the type mismatch in ``fitNode``: - if r.kind != nkCurly or len(r) == 0: + if r.kind notin {nkCurly, nkBracket} or len(r) == 0: checkMinSonsLen(t, 1) branch.sons[i] = skipConv(fitNode(c, t.sons[0].typ, r)) inc(covered) else: - # constant sets have special rules # first element is special and will overwrite: branch.sons[i]: branch.sons[i] = semCaseBranchSetElem(c, t, r[0], covered) # other elements have to be added to ``branch`` @@ -560,7 +562,7 @@ proc semRecordNodeAux(c: PContext, n: PNode, check: var TIntSet, pos: var int, let rec = rectype.sym for i in countup(0, sonsLen(n)-3): var f = semIdentWithPragma(c, skField, n.sons[i], {sfExported}) - suggestSym(n.sons[i], f) + suggestSym(n.sons[i].info, f) f.typ = typ f.position = pos if (rec != nil) and ({sfImportc, sfExportc} * rec.flags != {}) and @@ -825,7 +827,7 @@ proc liftParamType(c: PContext, procKind: TSymKind, genericParams: PNode, result = addImplicitGeneric(newTypeS(tyAnything, c)) of tyGenericParam: - markUsed(genericParams, paramType.sym) + markUsed(info, paramType.sym) if tfWildcard in paramType.flags: paramType.flags.excl tfWildcard paramType.sym.kind = skType @@ -862,7 +864,13 @@ proc semProcTypeNode(c: PContext, n, genericParams: PNode, var counter = 0 for i in countup(1, n.len - 1): var a = n.sons[i] - if a.kind != nkIdentDefs: illFormedAst(a) + if a.kind != nkIdentDefs: + # for some generic instantiations the passed ':env' parameter + # for closures has already been produced (see bug #898). We simply + # skip this parameter here. It'll then be re-generated in another LL + # pass over this instantiation: + if a.kind == nkSym and sfFromGeneric in a.sym.flags: continue + illFormedAst(a) checkMinSonsLen(a, 3) var typ: PType = nil @@ -1083,8 +1091,10 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = of nkCallKinds: if isRange(n): result = semRangeAux(c, n, prev) - elif n[0].kind == nkIdent: - let op = n.sons[0].ident + elif n[0].kind notin nkIdentKinds: + result = semTypeExpr(c, n) + else: + let op = considerQuotedIdent(n.sons[0]) if op.id in {ord(wAnd), ord(wOr)} or op.s == "|": checkSonsLen(n, 3) var @@ -1119,8 +1129,6 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = result = semAnyRef(c, n, tyRef, prev) else: result = semTypeExpr(c, n) - else: - result = semTypeExpr(c, n) of nkWhenStmt: var whenResult = semWhen(c, n, false) if whenResult.kind == nkStmtList: whenResult.kind = nkStmtListType @@ -1179,7 +1187,7 @@ proc semTypeNode(c: PContext, n: PNode, prev: PType): PType = else: assignType(prev, t) result = prev - markUsed(n, n.sym) + markUsed(n.info, n.sym) else: if n.sym.kind != skError: localError(n.info, errTypeExpected) result = newOrPrevType(tyError, prev, c) diff --git a/compiler/sigmatch.nim b/compiler/sigmatch.nim index 4b91a067e..e5bf08097 100644 --- a/compiler/sigmatch.nim +++ b/compiler/sigmatch.nim @@ -62,7 +62,7 @@ type const isNilConversion = isConvertible # maybe 'isIntConv' fits better? -proc markUsed*(n: PNode, s: PSym) +proc markUsed*(info: TLineInfo, s: PSym) proc initCandidateAux(ctx: PContext, c: var TCandidate, callee: PType) {.inline.} = @@ -497,11 +497,11 @@ proc matchUserTypeClass*(c: PContext, m: var TCandidate, proc shouldSkipDistinct(rules: PNode, callIdent: PIdent): bool = if rules.kind == nkWith: for r in rules: - if r.considerAcc == callIdent: return true + if r.considerQuotedIdent == callIdent: return true return false else: for r in rules: - if r.considerAcc == callIdent: return false + if r.considerQuotedIdent == callIdent: return false return true proc maybeSkipDistinct(t: PType, callee: PSym): PType = @@ -1058,7 +1058,7 @@ proc userConvMatch(c: PContext, m: var TCandidate, f, a: PType, dest = generateTypeInstance(c, m.bindings, arg, dest) let fdest = typeRel(m, f, dest) if fdest in {isEqual, isGeneric}: - markUsed(arg, c.converters[i]) + markUsed(arg.info, c.converters[i]) var s = newSymNode(c.converters[i]) s.typ = c.converters[i].typ s.info = arg.info @@ -1271,7 +1271,7 @@ proc paramTypesMatch*(m: var TCandidate, f, a: PType, result = nil else: # only one valid interpretation found: - markUsed(arg, arg.sons[best].sym) + markUsed(arg.info, arg.sons[best].sym) result = paramTypesMatchAux(m, f, arg.sons[best].typ, arg.sons[best], argOrig) @@ -1302,7 +1302,7 @@ proc prepareOperand(c: PContext; a: PNode): PNode = proc prepareNamedParam(a: PNode) = if a.sons[0].kind != nkIdent: var info = a.sons[0].info - a.sons[0] = newIdentNode(considerAcc(a.sons[0]), info) + a.sons[0] = newIdentNode(considerQuotedIdent(a.sons[0]), info) proc arrayConstr(c: PContext, n: PNode): PType = result = newTypeS(tyArrayConstr, c) diff --git a/compiler/suggest.nim b/compiler/suggest.nim index fc6ba2f77..c2bdfc5c3 100644 --- a/compiler/suggest.nim +++ b/compiler/suggest.nim @@ -63,8 +63,11 @@ proc filterSym(s: PSym): bool {.inline.} = proc fieldVisible*(c: PContext, f: PSym): bool {.inline.} = let fmoduleId = getModule(f).id - result = sfExported in f.flags or fmoduleId == c.module.id or - fmoduleId == c.friendModule.id + result = sfExported in f.flags or fmoduleId == c.module.id + for module in c.friendModules: + if fmoduleId == module.id: + result = true + break proc suggestField(c: PContext, s: PSym, outputs: var int) = if filterSym(s) and fieldVisible(c, s): @@ -243,18 +246,18 @@ var usageSym*: PSym lastLineInfo: TLineInfo -proc findUsages(node: PNode, s: PSym) = - if usageSym == nil and isTracked(node.info, s.name.s.len): +proc findUsages(info: TLineInfo; s: PSym) = + if usageSym == nil and isTracked(info, s.name.s.len): usageSym = s suggestWriteln(symToStr(s, isLocal=false, sectionUsage)) elif s == usageSym: - if lastLineInfo != node.info: - suggestWriteln(symToStr(s, isLocal=false, sectionUsage, node.info)) - lastLineInfo = node.info + if lastLineInfo != info: + suggestWriteln(symToStr(s, isLocal=false, sectionUsage, info)) + lastLineInfo = info -proc findDefinition(node: PNode, s: PSym) = - if node.isNil or s.isNil: return - if isTracked(node.info, s.name.s.len): +proc findDefinition(info: TLineInfo; s: PSym) = + if s.isNil: return + if isTracked(info, s.name.s.len): suggestWriteln(symToStr(s, isLocal=false, sectionDef)) suggestQuit() @@ -313,26 +316,26 @@ proc defFromSourceMap*(i: TLineInfo) = defFromLine(gSourceMaps[i.fileIndex].lines[i.line].entries, i.col) -proc suggestSym*(n: PNode, s: PSym) {.inline.} = +proc suggestSym*(info: TLineInfo; s: PSym) {.inline.} = ## misnamed: should be 'symDeclared' if optUsages in gGlobalOptions: - findUsages(n, s) + findUsages(info, s) if optDef in gGlobalOptions: - findDefinition(n, s) + findDefinition(info, s) if isServing: - addToSourceMap(s, n.info) + addToSourceMap(s, info) -proc markUsed(n: PNode, s: PSym) = +proc markUsed(info: TLineInfo; s: PSym) = incl(s.flags, sfUsed) if {sfDeprecated, sfError} * s.flags != {}: - if sfDeprecated in s.flags: message(n.info, warnDeprecated, s.name.s) - if sfError in s.flags: localError(n.info, errWrongSymbolX, s.name.s) - suggestSym(n, s) - if gCmd == cmdPretty: checkUse(n, s) + if sfDeprecated in s.flags: message(info, warnDeprecated, s.name.s) + if sfError in s.flags: localError(info, errWrongSymbolX, s.name.s) + suggestSym(info, s) + if gCmd == cmdPretty: checkUse(info, s) proc useSym*(sym: PSym): PNode = result = newSymNode(sym) - markUsed(result, sym) + markUsed(result.info, sym) proc suggestExpr*(c: PContext, node: PNode) = var cp = msgs.inCheckpoint(node.info) diff --git a/compiler/transf.nim b/compiler/transf.nim index fb5e321b6..dece1ac18 100644 --- a/compiler/transf.nim +++ b/compiler/transf.nim @@ -546,7 +546,7 @@ proc flattenTree(root: PNode): PNode = flattenTreeAux(result, root, op) else: result = root - + proc transformCall(c: PTransf, n: PNode): PTransNode = var n = flattenTree(n) var op = getMergeOp(n) @@ -565,6 +565,9 @@ proc transformCall(c: PTransf, n: PNode): PTransNode = inc(j) add(result, a.PTransNode) if len(result) == 2: result = result[1] + elif getMagic(n) == mNBindSym: + # for bindSym(myconst) we MUST NOT perform constant folding: + result = n.PTransNode else: let s = transformSons(c, n).PNode # bugfix: check after 'transformSons' if it's still a method call: diff --git a/compiler/types.nim b/compiler/types.nim index 1f266d64f..786eea14e 100644 --- a/compiler/types.nim +++ b/compiler/types.nim @@ -1118,6 +1118,11 @@ proc typeAllowed(t: PType, kind: TSymKind): bool = proc align(address, alignment: BiggestInt): BiggestInt = result = (address + (alignment - 1)) and not (alignment - 1) +const + szNonConcreteType* = -3 + szIllegalRecursion* = -2 + szUnknownSize* = -1 + proc computeSizeAux(typ: PType, a: var BiggestInt): BiggestInt proc computeRecSizeAux(n: PNode, a, currOffset: var BiggestInt): BiggestInt = var maxAlign, maxSize, b, res: BiggestInt @@ -1151,14 +1156,9 @@ proc computeRecSizeAux(n: PNode, a, currOffset: var BiggestInt): BiggestInt = of nkSym: result = computeSizeAux(n.sym.typ, a) n.sym.offset = int(currOffset) - else: - internalError("computeRecSizeAux()") + else: a = 1 - result = - 1 - -const - szIllegalRecursion* = -2 - szUnknownSize* = -1 + result = szNonConcreteType proc computeSizeAux(typ: PType, a: var BiggestInt): BiggestInt = var res, maxAlign, length, currOffset: BiggestInt diff --git a/compiler/typesrenderer.nim b/compiler/typesrenderer.nim index 790bd1047..f3121a0b4 100644 --- a/compiler/typesrenderer.nim +++ b/compiler/typesrenderer.nim @@ -1,4 +1,4 @@ -import renderer, strutils, ast, msgs, types +import renderer, strutils, ast, msgs, types, astalgo const defaultParamSeparator* = "," @@ -92,7 +92,7 @@ proc renderParamTypes(found: var seq[string], n: PNode) = if not typ.isNil: typeStr = typeToString(typ, preferExported) if typeStr.len < 1: return for i in 0 .. <typePos: - assert n[i].kind == nkIdent + assert ((n[i].kind == nkIdent) or (n[i].kind == nkAccQuoted)) found.add(typeStr) else: internalError(n.info, "renderParamTypes(found,n) with " & $n.kind) diff --git a/compiler/vm.nim b/compiler/vm.nim index 836f90967..66595856a 100644 --- a/compiler/vm.nim +++ b/compiler/vm.nim @@ -127,15 +127,20 @@ proc createStrKeepNode(x: var TFullReg) = elif x.node.kind == nkNilLit: system.reset(x.node[]) x.node.kind = nkStrLit - elif x.node.kind notin {nkStrLit..nkTripleStrLit}: + elif x.node.kind notin {nkStrLit..nkTripleStrLit} or + nfAllConst in x.node.flags: # XXX this is hacky; tests/txmlgen triggers it: x.node = newNode(nkStrLit) - # debug x.node - #assert x.node.kind in {nkStrLit..nkTripleStrLit} + # It not only hackey, it is also wrong for tgentemplate. The primary + # cause of bugs like these is that the VM does not properly distinguish + # between variable defintions (var foo = e) and variable updates (foo = e). template createStr(x) = x.node = newNode(nkStrLit) +template createSet(x) = + x.node = newNode(nkCurly) + proc moveConst(x: var TFullReg, y: TFullReg) = if x.kind != y.kind: myreset(x) @@ -433,7 +438,6 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = if regs[rc].intVal > high(int): stackTrace(c, tos, pc, errIndexOutOfBounds) let idx = regs[rc].intVal.int - # XXX what if the array is not 0-based? -> codegen should insert a sub let src = regs[rb].node if src.kind notin {nkEmpty..nkNilLit} and idx <% src.len: regs[ra].node = src.sons[idx] @@ -499,13 +503,13 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = else: stackTrace(c, tos, pc, errNilAccess) of opcWrDeref: - # a[] = b + # a[] = c; b unused let ra = instr.regA - let rb = instr.regB + let rc = instr.regC case regs[ra].kind - of rkNodeAddr: putIntoNode(regs[ra].nodeAddr[], regs[rb]) - of rkRegisterAddr: regs[ra].regAddr[] = regs[rb] - of rkNode: putIntoNode(regs[ra].node, regs[rb]) + of rkNodeAddr: putIntoNode(regs[ra].nodeAddr[], regs[rc]) + of rkRegisterAddr: regs[ra].regAddr[] = regs[rc] + of rkNode: putIntoNode(regs[ra].node, regs[rc]) else: stackTrace(c, tos, pc, errNilAccess) of opcAddInt: decodeBC(rkInt) @@ -667,14 +671,11 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = of opcLtu: decodeBC(rkInt) regs[ra].intVal = ord(regs[rb].intVal <% regs[rc].intVal) - of opcEqRef: + of opcEqRef, opcEqNimrodNode: decodeBC(rkInt) regs[ra].intVal = ord((regs[rb].node.kind == nkNilLit and regs[rc].node.kind == nkNilLit) or regs[rb].node == regs[rc].node) - of opcEqNimrodNode: - decodeBC(rkInt) - regs[ra].intVal = ord(regs[rb].node == regs[rc].node) of opcXor: decodeBC(rkInt) regs[ra].intVal = ord(regs[rb].intVal != regs[rc].intVal) @@ -720,18 +721,22 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = regs[ra].intVal = ord(containsSets(a, b) and not equalSets(a, b)) of opcMulSet: decodeBC(rkNode) + createSet(regs[ra]) move(regs[ra].node.sons, nimsets.intersectSets(regs[rb].node, regs[rc].node).sons) of opcPlusSet: decodeBC(rkNode) + createSet(regs[ra]) move(regs[ra].node.sons, nimsets.unionSets(regs[rb].node, regs[rc].node).sons) of opcMinusSet: decodeBC(rkNode) + createSet(regs[ra]) move(regs[ra].node.sons, nimsets.diffSets(regs[rb].node, regs[rc].node).sons) of opcSymdiffSet: decodeBC(rkNode) + createSet(regs[ra]) move(regs[ra].node.sons, nimsets.symdiffSets(regs[rb].node, regs[rc].node).sons) of opcConcatStr: @@ -742,11 +747,11 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = regs[ra].node.strVal.add getstr(regs[i]) of opcAddStrCh: decodeB(rkNode) - createStrKeepNode regs[ra] + #createStrKeepNode regs[ra] regs[ra].node.strVal.add(regs[rb].intVal.chr) of opcAddStrStr: decodeB(rkNode) - createStrKeepNode regs[ra] + #createStrKeepNode regs[ra] regs[ra].node.strVal.add(regs[rb].node.strVal) of opcAddSeqElem: decodeB(rkNode) @@ -897,10 +902,10 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = c.exceptionInstr = pc let (newPc, newTos) = cleanUpOnException(c, tos) # -1 because of the following 'inc' - if pc-1 < 0: + if newPc-1 < 0: bailOut(c, tos) return - pc = newPc -1 + pc = newPc-1 if tos != newTos: tos = newTos move(regs, tos.slots) @@ -983,7 +988,7 @@ proc rawExecute(c: PCtx, start: int, tos: PStackFrame): TFullReg = return TFullReg(kind: rkNone) of opcSetLenStr: decodeB(rkNode) - createStrKeepNode regs[ra] + #createStrKeepNode regs[ra] regs[ra].node.strVal.setLen(regs[rb].intVal.int) of opcOf: decodeBC(rkInt) diff --git a/compiler/vmdef.nim b/compiler/vmdef.nim index d0c38a2ad..c391d8415 100644 --- a/compiler/vmdef.nim +++ b/compiler/vmdef.nim @@ -207,7 +207,7 @@ const largeInstrs* = { # instructions which use 2 int32s instead of 1: opcSubStr, opcConv, opcCast, opcNewSeq, opcOf} slotSomeTemp* = slotTempUnknown - relativeJumps* = {opcTJmp, opcFJmp, opcJmp} + relativeJumps* = {opcTJmp, opcFJmp, opcJmp, opcJmpBack} template opcode*(x: TInstr): TOpcode {.immediate.} = TOpcode(x.uint32 and 0xff'u32) template regA*(x: TInstr): TRegister {.immediate.} = TRegister(x.uint32 shr 8'u32 and 0xff'u32) diff --git a/compiler/vmdeps.nim b/compiler/vmdeps.nim index 0e01f5031..9a213d813 100644 --- a/compiler/vmdeps.nim +++ b/compiler/vmdeps.nim @@ -15,6 +15,8 @@ proc readOutput(p: PProcess): string = discard p.waitForExit while not output.atEnd: result.add(output.readLine) + result.add("\n") + result.setLen(result.len - "\n".len) proc opGorge*(cmd, input: string): string = var p = startCmd(cmd) diff --git a/compiler/vmgen.nim b/compiler/vmgen.nim index 84577bb22..c1ec637dd 100644 --- a/compiler/vmgen.nim +++ b/compiler/vmgen.nim @@ -9,6 +9,24 @@ ## This module implements the code generator for the VM. +# Important things to remember: +# - The VM does not distinguish between definitions ('var x = y') and +# assignments ('x = y'). For simple data types that fit into a register +# this doesn't matter. However it matters for strings and other complex +# types that use the 'node' field; the reason is that slots are +# re-used in a register based VM. Example: +# +# .. code-block:: nimrod +# let s = a & b # no matter what, create fresh node +# s = a & b # no matter what, keep the node +# +# Also *stores* into non-temporary memory need to perform deep copies: +# a.b = x.y +# We used to generate opcAsgn for the *load* of 'x.y' but this is clearly +# wrong! We need to produce opcAsgn (the copy) for the *store*. This also +# solves the opcLdConst vs opcAsgnConst issue. Of course whether we need +# this copy depends on the involved types. + import unsigned, strutils, ast, astalgo, types, msgs, renderer, vmdef, trees, intsets, rodread, magicsys, options, lowerings @@ -84,21 +102,27 @@ proc gABI(c: PCtx; n: PNode; opc: TOpcode; a, b: TRegister; imm: BiggestInt) = # Takes the `b` register and the immediate `imm`, appies the operation `opc`, # and stores the output value into `a`. # `imm` is signed and must be within [-127, 128] - assert(imm >= -127 and imm <= 128) - let ins = (opc.uint32 or (a.uint32 shl 8'u32) or - (b.uint32 shl 16'u32) or - (imm+byteExcess).uint32 shl 24'u32).TInstr - c.code.add(ins) - c.debug.add(n.info) + if imm >= -127 and imm <= 128: + let ins = (opc.uint32 or (a.uint32 shl 8'u32) or + (b.uint32 shl 16'u32) or + (imm+byteExcess).uint32 shl 24'u32).TInstr + c.code.add(ins) + c.debug.add(n.info) + else: + localError(n.info, errGenerated, + "VM: immediate value does not fit into an int8") proc gABx(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0; bx: int) = # Applies `opc` to `bx` and stores it into register `a` # `bx` must be signed and in the range [-32767, 32768] - assert(bx >= -32767 and bx <= 32768) - let ins = (opc.uint32 or a.uint32 shl 8'u32 or - (bx+wordExcess).uint32 shl 16'u32).TInstr - c.code.add(ins) - c.debug.add(n.info) + if bx >= -32767 and bx <= 32768: + let ins = (opc.uint32 or a.uint32 shl 8'u32 or + (bx+wordExcess).uint32 shl 16'u32).TInstr + c.code.add(ins) + c.debug.add(n.info) + else: + localError(n.info, errGenerated, + "VM: immediate value does not fit into an int16") proc xjmp(c: PCtx; n: PNode; opc: TOpcode; a: TRegister = 0): TPosition = #assert opc in {opcJmp, opcFJmp, opcTJmp} @@ -331,6 +355,7 @@ proc canonValue*(n: PNode): PNode = proc rawGenLiteral(c: PCtx; n: PNode): int = result = c.constants.len assert(n.kind != nkCall) + n.flags.incl nfAllConst c.constants.add n.canonValue internalAssert result < 0x7fff @@ -484,11 +509,22 @@ proc genField(n: PNode): TRegister = "too large offset! cannot generate code for: " & s.name.s) result = s.position +proc genIndex(c: PCtx; n: PNode; arr: PType): TRegister = + if arr.skipTypes(abstractInst).kind == tyArray and (let x = firstOrd(arr); + x != 0): + let tmp = c.genx(n) + # freeing the temporary here means we can produce: regA = regA - Imm + c.freeTemp(tmp) + result = c.getTemp(n.typ) + c.gABI(n, opcSubImmInt, result, tmp, x.int) + else: + result = c.genx(n) + proc genAsgnPatch(c: PCtx; le: PNode, value: TRegister) = case le.kind of nkBracketExpr: let dest = c.genx(le.sons[0], {gfAddrOf}) - let idx = c.genx(le.sons[1]) + let idx = c.genIndex(le.sons[1], le.sons[0].typ) c.gABC(le, opcWrArr, dest, idx, value) c.freeTemp(dest) c.freeTemp(idx) @@ -501,12 +537,12 @@ proc genAsgnPatch(c: PCtx; le: PNode, value: TRegister) = c.freeTemp(dest) of nkDerefExpr, nkHiddenDeref: let dest = c.genx(le.sons[0], {gfAddrOf}) - c.gABC(le, opcWrDeref, dest, value) + c.gABC(le, opcWrDeref, dest, 0, value) c.freeTemp(dest) of nkSym: if le.sym.isGlobal: let dest = c.genx(le, {gfAddrOf}) - c.gABC(le, opcWrDeref, dest, value) + c.gABC(le, opcWrDeref, dest, 0, value) c.freeTemp(dest) else: discard @@ -786,10 +822,12 @@ proc genMagic(c: PCtx; n: PNode; dest: var TDest) = c.freeTemp(tmp) of mSwap: unused(n, dest) - var d = c.genx(n.sons[1]) - var tmp = c.genx(n.sons[2]) - c.gABC(n, opcSwap, d, tmp) - c.freeTemp(tmp) + var + d1 = c.genx(n.sons[1]) + d2 = c.genx(n.sons[2]) + c.gABC(n, opcSwap, d1, d2) + c.genAsgnPatch(n.sons[1], d1) + c.genAsgnPatch(n.sons[2], d2) of mIsNil: genUnaryABC(c, n, dest, opcIsNil) of mCopyStr: if dest < 0: dest = c.getTemp(n.typ) @@ -968,7 +1006,7 @@ const proc fitsRegister*(t: PType): bool = t.skipTypes(abstractInst-{tyTypeDesc}).kind in { - tyRange, tyEnum, tyBool, tyInt..tyUInt64} + tyRange, tyEnum, tyBool, tyInt..tyUInt64, tyChar} proc requiresCopy(n: PNode): bool = if n.typ.skipTypes(abstractInst-{tyTypeDesc}).kind in atomicTypes: @@ -1065,17 +1103,36 @@ proc checkCanEval(c: PCtx; n: PNode) = not s.isOwnedBy(c.prc.sym) and s.owner != c.module: cannotEval(n) +proc isTemp(c: PCtx; dest: TDest): bool = + result = dest >= 0 and c.prc.slots[dest].kind >= slotTempUnknown + +template needsAdditionalCopy(n): expr = + not c.isTemp(dest) and not fitsRegister(n.typ) + +proc preventFalseAlias(c: PCtx; n: PNode; opc: TOpcode; + dest, idx, value: TRegister) = + # opcLdObj et al really means "load address". We sometimes have to create a + # copy in order to not introduce false aliasing: + # mylocal = a.b # needs a copy of the data! + if needsAdditionalCopy(n): + var cc = c.getTemp(n.typ) + c.gABC(n, whichAsgnOpc(n), cc, value) + c.gABC(n, opc, dest, idx, cc) + c.freeTemp(cc) + else: + c.gABC(n, opc, dest, idx, value) + proc genAsgn(c: PCtx; le, ri: PNode; requiresCopy: bool) = case le.kind of nkBracketExpr: let dest = c.genx(le.sons[0], {gfAddrOf}) - let idx = c.genx(le.sons[1]) + let idx = c.genIndex(le.sons[1], le.sons[0].typ) let tmp = c.genx(ri) if le.sons[0].typ.skipTypes(abstractVarRange-{tyTypeDesc}).kind in { tyString, tyCString}: - c.gABC(le, opcWrStrIdx, dest, idx, tmp) + c.preventFalseAlias(le, opcWrStrIdx, dest, idx, tmp) else: - c.gABC(le, opcWrArr, dest, idx, tmp) + c.preventFalseAlias(le, opcWrArr, dest, idx, tmp) c.freeTemp(tmp) of nkDotExpr, nkCheckedFieldExpr: # XXX field checks here @@ -1083,12 +1140,12 @@ proc genAsgn(c: PCtx; le, ri: PNode; requiresCopy: bool) = let dest = c.genx(left.sons[0], {gfAddrOf}) let idx = genField(left.sons[1]) let tmp = c.genx(ri) - c.gABC(left, opcWrObj, dest, idx, tmp) + c.preventFalseAlias(left, opcWrObj, dest, idx, tmp) c.freeTemp(tmp) of nkDerefExpr, nkHiddenDeref: let dest = c.genx(le.sons[0], {gfAddrOf}) let tmp = c.genx(ri) - c.gABC(le, opcWrDeref, dest, tmp) + c.preventFalseAlias(le, opcWrDeref, dest, 0, tmp) c.freeTemp(tmp) of nkSym: let s = le.sym @@ -1097,24 +1154,32 @@ proc genAsgn(c: PCtx; le, ri: PNode; requiresCopy: bool) = withTemp(tmp, le.typ): c.gen(le, tmp, {gfAddrOf}) let val = c.genx(ri) - c.gABC(le, opcWrDeref, tmp, val) + c.preventFalseAlias(le, opcWrDeref, tmp, 0, val) c.freeTemp(val) else: if s.kind == skForVar: c.setSlot s internalAssert s.position > 0 or (s.position == 0 and s.kind in {skParam,skResult}) var dest: TRegister = s.position + ord(s.kind == skParam) - gen(c, ri, dest) + if needsAdditionalCopy(le) and s.kind in {skResult, skVar, skParam}: + var cc = c.getTemp(le.typ) + gen(c, ri, cc) + c.gABC(le, whichAsgnOpc(le), dest, cc) + c.freeTemp(cc) + else: + gen(c, ri, dest) else: let dest = c.genx(le, {gfAddrOf}) genAsgn(c, dest, ri, requiresCopy) proc genLit(c: PCtx; n: PNode; dest: var TDest) = - var opc = opcLdConst + # opcLdConst is now always valid. We produce the necessary copy in the + # assignments now: + #var opc = opcLdConst if dest < 0: dest = c.getTemp(n.typ) - elif c.prc.slots[dest].kind == slotFixedVar: opc = opcAsgnConst + #elif c.prc.slots[dest].kind == slotFixedVar: opc = opcAsgnConst let lit = genLiteral(c, n) - c.gABx(n, opc, dest, lit) + c.gABx(n, opcLdConst, dest, lit) proc genTypeLit(c: PCtx; t: PType; dest: var TDest) = var n = newNode(nkType) @@ -1143,7 +1208,7 @@ proc genGlobalInit(c: PCtx; n: PNode; s: PSym) = let dest = c.getTemp(s.typ) c.gABx(n, opcLdGlobal, dest, s.position) let tmp = c.genx(s.ast) - c.gABC(n, opcWrDeref, dest, tmp) + c.preventFalseAlias(n, opcWrDeref, dest, 0, tmp) c.freeTemp(dest) c.freeTemp(tmp) @@ -1179,17 +1244,22 @@ proc genRdVar(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) = # see tests/t99bott for an example that triggers it: cannotEval(n) +template needsRegLoad(): expr = + gfAddrOf notin flags and fitsRegister(n.typ.skipTypes({tyVar})) + proc genArrAccess2(c: PCtx; n: PNode; dest: var TDest; opc: TOpcode; flags: TGenFlags) = let a = c.genx(n.sons[0], flags) - let b = c.genx(n.sons[1], {}) + let b = c.genIndex(n.sons[1], n.sons[0].typ) if dest < 0: dest = c.getTemp(n.typ) - if gfAddrOf notin flags and fitsRegister(n.typ): + if needsRegLoad(): var cc = c.getTemp(n.typ) c.gABC(n, opc, cc, a, b) c.gABC(n, opcNodeToReg, dest, cc) c.freeTemp(cc) else: + #message(n.info, warnUser, "argh") + #echo "FLAGS ", flags, " ", fitsRegister(n.typ), " ", typeToString(n.typ) c.gABC(n, opc, dest, a, b) c.freeTemp(a) c.freeTemp(b) @@ -1198,7 +1268,7 @@ proc genObjAccess(c: PCtx; n: PNode; dest: var TDest; flags: TGenFlags) = let a = c.genx(n.sons[0], flags) let b = genField(n.sons[1]) if dest < 0: dest = c.getTemp(n.typ) - if gfAddrOf notin flags and fitsRegister(n.typ.skipTypes({tyVar})): + if needsRegLoad(): var cc = c.getTemp(n.typ) c.gABC(n, opcLdObj, cc, a, b) c.gABC(n, opcNodeToReg, dest, cc) @@ -1298,7 +1368,7 @@ proc genVarSection(c: PCtx; n: PNode) = if a.sons[2].kind != nkEmpty: let tmp = c.genx(a.sons[0], {gfAddrOf}) let val = c.genx(a.sons[2]) - c.gABC(a, opcWrDeref, tmp, val) + c.preventFalseAlias(a, opcWrDeref, tmp, 0, val) c.freeTemp(val) c.freeTemp(tmp) else: @@ -1306,7 +1376,16 @@ proc genVarSection(c: PCtx; n: PNode) = if a.sons[2].kind == nkEmpty: c.gABx(a, ldNullOpcode(s.typ), s.position, c.genType(s.typ)) else: - gen(c, a.sons[2], s.position.TRegister) + if not fitsRegister(s.typ): + c.gABx(a, ldNullOpcode(s.typ), s.position, c.genType(s.typ)) + let le = a.sons[0] + if not fitsRegister(le.typ) and s.kind in {skResult, skVar, skParam}: + var cc = c.getTemp(le.typ) + gen(c, a.sons[2], cc) + c.gABC(le, whichAsgnOpc(le), s.position.TRegister, cc) + c.freeTemp(cc) + else: + gen(c, a.sons[2], s.position.TRegister) else: # assign to a.sons[0]; happens for closures if a.sons[2].kind == nkEmpty: @@ -1334,7 +1413,7 @@ proc genArrayConstr(c: PCtx, n: PNode, dest: var TDest) = c.gABx(n, opcLdNullReg, tmp, c.genType(intType)) for x in n: let a = c.genx(x) - c.gABC(n, whichAsgnOpc(x, opcWrArr), dest, tmp, a) + c.preventFalseAlias(n, whichAsgnOpc(x, opcWrArr), dest, tmp, a) c.gABI(n, opcAddImmInt, tmp, tmp, 1) c.freeTemp(a) c.freeTemp(tmp) @@ -1366,7 +1445,8 @@ proc genObjConstr(c: PCtx, n: PNode, dest: var TDest) = if it.kind == nkExprColonExpr and it.sons[0].kind == nkSym: let idx = genField(it.sons[0]) let tmp = c.genx(it.sons[1]) - c.gABC(it, whichAsgnOpc(it.sons[1], opcWrObj), dest, idx, tmp) + c.preventFalseAlias(it.sons[1], whichAsgnOpc(it.sons[1], opcWrObj), + dest, idx, tmp) c.freeTemp(tmp) else: internalError(n.info, "invalid object constructor") @@ -1380,11 +1460,12 @@ proc genTupleConstr(c: PCtx, n: PNode, dest: var TDest) = if it.kind == nkExprColonExpr: let idx = genField(it.sons[0]) let tmp = c.genx(it.sons[1]) - c.gABC(it, whichAsgnOpc(it.sons[1], opcWrObj), dest, idx, tmp) + c.preventFalseAlias(it.sons[1], whichAsgnOpc(it.sons[1], opcWrObj), + dest, idx, tmp) c.freeTemp(tmp) else: let tmp = c.genx(it) - c.gABC(it, whichAsgnOpc(it, opcWrObj), dest, i.TRegister, tmp) + c.preventFalseAlias(it, whichAsgnOpc(it, opcWrObj), dest, i.TRegister, tmp) c.freeTemp(tmp) proc genProc*(c: PCtx; s: PSym): int @@ -1622,7 +1703,7 @@ proc genProc(c: PCtx; s: PSym): int = c.gABC(body, opcEof, eofInstr.regA) c.optimizeJumps(result) s.offset = c.prc.maxSlots - #if s.name.s == "addStuff": + #if s.name.s == "calc": # echo renderTree(body) # c.echoCode(result) c.prc = oldPrc diff --git a/config/nimrod.cfg b/config/nimrod.cfg index 2817eac55..df3835ace 100644 --- a/config/nimrod.cfg +++ b/config/nimrod.cfg @@ -16,6 +16,7 @@ arm.linux.gcc.linkerexe = "arm-linux-gcc" path="$lib/core" path="$lib/pure" path="$lib/pure/collections" +path="$lib/pure/concurrency" path="$lib/impure" path="$lib/wrappers" # path="$lib/wrappers/cairo" diff --git a/doc/abstypes.txt b/doc/abstypes.txt deleted file mode 100644 index c5827745a..000000000 --- a/doc/abstypes.txt +++ /dev/null @@ -1,152 +0,0 @@ -============== -Abstract types -============== - -.. contents:: - -Abstract types in Nimrod provide a means to model different `units`:idx: of -a `base type`:idx:. - - -Use case 1: SQL strings ------------------------ -An SQL statement that is passed from Nimrod to an SQL database might be -modelled as a string. However, using string templates and filling in the -values is vulnerable to the famous `SQL injection attack`:idx:\: - -.. code-block:: nimrod - proc query(db: TDbHandle, statement: TSQL) = ... - - var - username: string - - db.query("SELECT FROM users WHERE name = '$1'" % username) - # Horrible security hole, but the compiler does not mind! - -This can be avoided by distinguishing strings that contain SQL from strings -that don't. Abstract types provide a means to introduce a new string type -``TSQL`` that is incompatible with ``string``: - -.. code-block:: nimrod - type - TSQL = abstract string - - proc query(db: TDbHandle, statement: TSQL) = ... - - var - username: string - - db.query("SELECT FROM users WHERE name = '$1'" % username) - # Error at compile time: `query` expects an SQL string! - - -It is an essential property of abstract types that they **do not** imply a -subtype relation between the abtract type and its base type. Explict type -conversions from ``string`` to ``TSQL`` are allowed: - -.. code-block:: nimrod - proc properQuote(s: string): TSQL = - # quotes a string properly for an SQL statement - ... - - proc `%` (frmt: TSQL, values: openarray[string]): TSQL = - # quote each argument: - var v = values.each(properQuote) - # we need a temporary type for the type conversion :-( - type TStrSeq = seq[string] - # call strutils.`%`: - result = TSQL(string(frmt) % TStrSeq(v)) - - db.query("SELECT FROM users WHERE name = $1".TSQL % username) - -Now we have compile-time checking against SQL injection attacks. -Since ``"".TSQL`` is transformed to ``TSQL("")`` no new syntax is needed -for nice looking ``TSQL`` string literals. - - - -Use case 2: Money ------------------ -Different currencies should not be mixed in monetary calculations. Abstract -types are a perfect tool to model different currencies: - -.. code-block:: nimrod - type - TDollar = abstract int - TEuro = abstract int - - var - d: TDollar - e: TEuro - - echo d + 12 - # Error: cannot add a number with no unit with a ``TDollar`` - -Unfortunetaly, ``d + 12.TDollar`` is not allowed either, -because ``+`` is defined for ``int`` (among others), not for ``TDollar``. So -we define our own ``+`` for dollars: - -.. code-block:: - proc `+` (x, y: TDollar): TDollar = - result = TDollar(int(x) + int(y)) - -It does not make sense to multiply a dollar with a dollar, but with a -number without unit; and the same holds for division: - -.. code-block:: - proc `*` (x: TDollar, y: int): TDollar = - result = TDollar(int(x) * y) - - proc `*` (x: int, y: TDollar): TDollar = - result = TDollar(x * int(y)) - - proc `div` ... - -This quickly gets tedious. The implementations are trivial and the compiler -should not generate all this code only to optimize it away later - after all -``+`` for dollars should produce the same binary code as ``+`` for ints. -The pragma ``borrow`` has been designed to solve this problem; in principle -it generates the trivial implementation for us: - -.. code-block:: nimrod - proc `*` (x: TDollar, y: int): TDollar {.borrow.} - proc `*` (x: int, y: TDollar): TDollar {.borrow.} - proc `div` (x: TDollar, y: int): TDollar {.borrow.} - -The ``borrow`` pragma makes the compiler to use the same implementation as -the proc that deals with the abstract type's base type, so no code is -generated. - -But it seems we still have to repeat all this boilerplate code for -the ``TEuro`` currency. Fortunately, Nimrod has a template mechanism: - -.. code-block:: nimrod - template Additive(typ: typeDesc): stmt = - proc `+` *(x, y: typ): typ {.borrow.} - proc `-` *(x, y: typ): typ {.borrow.} - - # unary operators: - proc `+` *(x: typ): typ {.borrow.} - proc `-` *(x: typ): typ {.borrow.} - - template Multiplicative(typ, base: typeDesc): stmt = - proc `*` *(x: typ, y: base): typ {.borrow.} - proc `*` *(x: base, y: typ): typ {.borrow.} - proc `div` *(x: typ, y: base): typ {.borrow.} - proc `mod` *(x: typ, y: base): typ {.borrow.} - - template Comparable(typ: typeDesc): stmt = - proc `<` * (x, y: typ): bool {.borrow.} - proc `<=` * (x, y: typ): bool {.borrow.} - proc `==` * (x, y: typ): bool {.borrow.} - - template DefineCurrency(typ, base: expr): stmt = - type - typ* = abstract base - Additive(typ) - Multiplicative(typ, base) - Comparable(typ) - - DefineCurrency(TDollar, int) - DefineCurrency(TEuro, int) - diff --git a/doc/advopt.txt b/doc/advopt.txt index f5ff90791..08465e457 100644 --- a/doc/advopt.txt +++ b/doc/advopt.txt @@ -2,6 +2,7 @@ Advanced commands: //compileToC, cc compile project with C code generator //compileToCpp, cpp compile project to C++ code //compileToOC, objc compile project to Objective C code + //js compile project to Javascript //rst2html convert a reStructuredText file to HTML //rst2tex convert a reStructuredText file to TeX //jsondoc extract the documentation to a json file diff --git a/doc/apis.txt b/doc/apis.txt index d76bd721e..9906f6bbc 100644 --- a/doc/apis.txt +++ b/doc/apis.txt @@ -1,6 +1,6 @@ -========== -API design -========== +================= +API naming design +================= The API is designed to be **easy to use** and consistent. Ease of use is measured by the number of calls to achieve a concrete high level action. @@ -79,3 +79,10 @@ string str identifier ident indentation indent ------------------- ------------ -------------------------------------- + + +Coding Guidelines +================= + +For coding guidelines see the `Internals of the Nimrod Compiler +<intern.html#coding-guidelines>`_ documentation. diff --git a/doc/backends.txt b/doc/backends.txt new file mode 100644 index 000000000..26576e733 --- /dev/null +++ b/doc/backends.txt @@ -0,0 +1,409 @@ +================================ + Nimrod Backend Integration +================================ + +:Author: Puppet Master +:Version: |nimrodversion| + +.. contents:: + "Heresy grows from idleness." -- Unknown. + + +Introduction +============ + +The `Nimrod Compiler User Guide <nimrodc.html>`_ documents the typical +compiler invocation, using the ``compile`` or ``c`` command to transform a +``.nim`` file into one or more ``.c`` files which are then compiled with the +platform's C compiler into a static binary. However there are other commands +to compile to C++, Objective-C or JavaScript. This document tries to +concentrate in a single place all the backend and interfacing options. + +The Nimrod compiler supports mainly two backend families: the C, C++ and +Objective-C targets and the JavaScript target. `The C like targets`_ creates +source files which can be compiled into a library or a final executable. `The +JavaScript target`_ can generate a ``.js`` file which you reference from an +HTML file or create a `standalone nodejs program <http://nodejs.org>`_. + +On top of generating libraries or standalone applications, Nimrod offers +bidirectional interfacing with the backend targets through generic and +specific pragmas. + + +Backends +======== + +The C like targets +------------------ + +The commands to compile to either C, C++ or Objective-C are: + + //compileToC, cc compile project with C code generator + //compileToCpp, cpp compile project to C++ code + //compileToOC, objc compile project to Objective C code + +The most significant difference between these commands is that if you look +into the ``nimcache`` directory you will find ``.c``, ``.cpp`` or ``.m`` +files, other than that all of them will produce a native binary for your +project. This allows you to take the generated code and place it directly +into a project using any of these languages. Here are some typical command +line invocations:: + + $ nimrod c hallo.nim + $ nimrod cpp hallo.nim + $ nimrod objc hallo.nim + +The compiler commands select the target backend, but if needed you can +`specify additional switches for cross compilation +<nimrodc.html#cross-compilation>`_ to select the target CPU, operative system +or compiler/linker commands. + + +The JavaScript target +--------------------- + +Nimrod can also generate `JavaScript`:idx: code through the ``js`` command. +However, the JavaScript code generator is experimental! + +Nimrod targets JavaScript 1.5 which is supported by any widely used browser. +Since JavaScript does not have a portable means to include another module, +Nimrod just generates a long ``.js`` file. + +Features or modules that the JavaScript platform does not support are not +available. This includes: + +* manual memory management (``alloc``, etc.) +* casting and other unsafe operations (``cast`` operator, ``zeroMem``, etc.) +* file management +* most modules of the Standard library +* proper 64 bit integer arithmetic +* unsigned integer arithmetic + +However, the modules `strutils <strutils.html>`_, `math <math.html>`_, and +`times <times.html>`_ are available! To access the DOM, use the `dom +<dom.html>`_ module that is only available for the JavaScript platform. + +To compile a Nimrod module into a ``.js`` file use the ``js`` command; the +default is a ``.js`` file that is supposed to be referenced in an ``.html`` +file. However, you can also run the code with `nodejs`:idx:, a `software +platform for easily building fast, scalable network applications +<http://nodejs.org>`_:: + + nimrod js -d:nodejs -r examples/hallo.nim + + +Interfacing +=========== + +Nimrod offers bidirectional interfacing with the target backend. This means +that you can call backend code from Nimrod and Nimrod code can be called by +the backend code. Usually the direction of which calls which depends on your +software architecture (is Nimrod your main program or is Nimrod providing a +component?). + + +Nimrod code calling the backend +-------------------------------- + +Nimrod code can interface with the backend through the `Foreign function +interface <manual.html#foreign-function-interface>`_ mainly through the +`importc pragma <manual.html#importc-pragma>`_. The ``importc`` pragma is the +*generic* way of making backend symbols available in Nimrod and is available +in all the target backends (JavaScript too). The C++ or Objective-C backends +have their respective `ImportCpp <nimrodc.html#importcpp-pragma>`_ and +`ImportObjC <nimrodc.html#importobjc-pragma>`_ pragmas to call methods from +classes. + +Whenever you use any of these pragmas you need to integrate native code into +your final binary. In the case of JavaScript this is no problem at all, the +same html file which hosts the generated JavaScript will likely provide other +JavaScript functions which you are importing with ``importc``. + +However, for the C like targets you need to link external code either +statically or dynamically. The preferred way of integrating native code is to +use dynamic linking because it allows you to compile Nimrod programs without +the need for having the related development libraries installed. This is done +through the `dynlib pragma for import +<manual.html#dynlib-pragma-for-import>`_, though more specific control can be +gained using the `dynlib module <dynlib.html>`_. + +The `dynlibOverride <nimrodc.html#dynliboverride>`_ command line switch allows +to avoid dynamic linking if you need to statically link something instead. +Nimrod wrappers designed to statically link source files can use the `compile +pragma <nimrodc.html#compile-pragma>`_ if there are few sources or providing +them along the Nimrod code is easier than using a system library. Libraries +installed on the host system can be linked in with the `PassL pragma +<nimrodc.html#passl-pragma>`_. + +To wrap native code, take a look at the `c2nim tool <c2nim.html>`_ which helps +with the process of scanning and transforming header files into a Nimrod +interface. + +C invocation example +~~~~~~~~~~~~~~~~~~~~ + +Create a ``logic.c`` file with the following content: + +.. code-block:: c + int addTwoIntegers(int a, int b) + { + return a + b; + } + +Create a ``calculator.nim`` file with the following content: + +.. code-block:: nimrod + + {.compile: "logic.c".} + proc addTwoIntegers(a, b: cint): cint {.importc.} + + when isMainModule: + echo addTwoIntegers(3, 7) + +With these two files in place, you can run ``nimrod c -r calculator.nim`` and +the Nimrod compiler will compile the ``logic.c`` file in addition to +``calculator.nim`` and link both into an executable, which outputs ``10`` when +run. Another way to link the C file statically and get the same effect would +be remove the line with the ``compile`` pragma and run the following typical +Unix commands:: + + $ gcc -c logic.c + $ ar rvs mylib.a logic.o + $ nimrod c --passL:mylib.a -r calculator.nim + +Just like in this example we pass the path to the ``mylib.a`` library (and we +could as well pass ``logic.o``) we could be passing switches to link any other +static C library. + + +JavaScript invocation example +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Create a ``host.html`` file with the following content: + +.. code-block:: + + <html><body> + <script type="text/javascript"> + function addTwoIntegers(a, b) + { + return a + b; + } + </script> + <script type="text/javascript" src="calculator.js"></script> + </body></html> + +Create a ``calculator.nim`` file with the following content (or reuse the one +from the previous section): + +.. code-block:: nimrod + + proc addTwoIntegers(a, b: int): int {.importc.} + + when isMainModule: + echo addTwoIntegers(3, 7) + +Compile the Nimrod code to JavaScript with ``nimrod js -o:calculator.js +calculator.nim`` and open ``host.html`` in a browser. If the browser supports +javascript, you should see the value ``10``. In JavaScript the `echo proc +<system.html#echo>`_ will modify the HTML DOM and append the string. Use the +`dom module <dom.html>`_ for specific DOM querying and modification procs. + + +Backend code calling Nimrod +--------------------------- + +Backend code can interface with Nimrod code exposed through the `exportc +pragma <manual.html#exportc-pragma>`_. The ``exportc`` pragma is the *generic* +way of making Nimrod symbols available to the backends. By default the Nimrod +compiler will mangle all the Nimrod symbols to avoid any name collision, so +the most significant thing the ``exportc`` pragma does is maintain the Nimrod +symbol name, or if specified, use an alternative symbol for the backend in +case the symbol rules don't match. + +The JavaScript target doesn't have any further interfacing considerations +since it also has garbage collection, but the C targets require you to +initialize Nimrod's internals, which is done calling a ``NimMain`` function. +Also, C code requires you to specify a forward declaration for functions or +the compiler will asume certain types for the return value and parameters +which will likely make your program crash at runtime. + +The Nimrod compiler can generate a C interface header through the ``--header`` +command line switch. The generated header will contain all the exported +symbols and the ``NimMain`` proc which you need to call before any other +Nimrod code. + + +Nimrod invocation example from C +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Create a ``fib.nim`` file with the following content: + +.. code-block:: nimrod + + proc fib(a: cint): cint {.exportc.} = + if a <= 2: + result = 1 + else: + result = fib(a - 1) + fib(a - 2) + +Create a ``maths.c`` file with the following content: + +.. code-block:: c + + #include "fib.h" + #include <stdio.h> + + int main(void) + { + NimMain(); + for (int f = 0; f < 10; f++) + printf("Fib of %d is %d\n", f, fib(f)); + return 0; + } + +Now you can run the following Unix like commands to first generate C sources +form the Nimrod code, then link them into a static binary along your main C +program:: + + $ nimrod c --noMain --noLinking --header:fib.h fib.nim + $ gcc -o m -Inimcache -Ipath/to/nimrod/lib nimcache/*.c maths.c + +The first command runs the Nimrod compiler with three special options to avoid +generating a ``main()`` function in the generated files, avoid linking the +object files into a final binary, and explicitly generate a header file for C +integration. All the generated files are placed into the ``nimcache`` +directory. That's why the next command compiles the ``maths.c`` source plus +all the ``.c`` files form ``nimcache``. In addition to this path, you also +have to tell the C compiler where to find Nimrod's ``nimbase.h`` header file. + +Instead of depending on the generation of the individual ``.c`` files you can +also ask the Nimrod compiler to generate a statically linked library:: + + $ nimrod c --app:staticLib --noMain --header fib.nim + $ gcc -o m -Inimcache -Ipath/to/nimrod/lib libfib.nim.a maths.c + +The Nimrod compiler will handle linking the source files generated in the +``nimcache`` directory into the ``libfib.nim.a`` static library, which you can +then link into your C program. Note that these commands are generic and will +vary for each system. For instance, on Linux systems you will likely need to +use ``-ldl`` too to link in required dlopen functionality. + + +Nimrod invocation example from JavaScript +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Create a ``mhost.html`` file with the following content: + +.. code-block:: + + <html><body> + <script type="text/javascript" src="fib.js"></script> + <script type="text/javascript"> + alert("Fib for 9 is " + fib(9)); + </script> + </body></html> + +Create a ``fib.nim`` file with the following content (or reuse the one +from the previous section): + +.. code-block:: nimrod + + proc fib(a: cint): cint {.exportc.} = + if a <= 2: + result = 1 + else: + result = fib(a - 1) + fib(a - 2) + +Compile the Nimrod code to JavaScript with ``nimrod js -o:fib.js fib.nim`` and +open ``mhost.html`` in a browser. If the browser supports javascript, you +should see an alert box displaying the text ``Fib for 9 is 34``. As mentioned +earlier, JavaScript doesn't require an initialisation call to ``NimMain`` or +similar function and you can call the exported Nimrod proc directly. + + +Memory management +================= + +In the previous sections the ``NimMain()`` function reared its head. Since +JavaScript already provides automatic memory management, you can freely pass +objects between the two language without problems. In C and derivate languages +you need to be careful about what you do and how you share memory. The +previous examples only dealt with simple scalar values, but passing a Nimrod +string to C, or reading back a C string in Nimrod already requires you to be +aware of who controls what to avoid crashing. + + +Strings and C strings +--------------------- + +The manual mentions that `Nimrod strings are implicitly convertible to +cstrings <manual.html#cstring-type>`_ which makes interaction usually +painless. Most C functions accepting a Nimrod string converted to a +``cstring`` will likely not need to keep this string around and by the time +they return the string won't be needed any more. However, for the rare cases +where a Nimrod string has to be preserved and made available to the C backend +as a ``cstring``, you will need to manually prevent the string data from being +freed with `GC_ref <system.html#GC_ref>`_ and `GC_unref +<system.html#GC_unref>`_. + +A similar thing happens with C code invoking Nimrod code which returns a +``cstring``. Consider the following proc: + +.. code-block:: nimrod + + proc gimme(): cstring {.exportc.} = + result = "Hey there C code! " & $random(100) + +Since Nimrod's garbage collector is not aware of the C code, once the +``gimme`` proc has finished it can reclaim the memory of the ``cstring``. +However, from a practical standpoint, the C code invoking the ``gimme`` +function directly will be able to use it since Nimrod's garbage collector has +not had a chance to run *yet*. This gives you enough time to make a copy for +the C side of the program, as calling any further Nimrod procs *might* trigger +garbage collection making the previously returned string garbage. Or maybe you +are `triggering yourself the collection <gc.html>`_. + + +Custom data types +----------------- + +Just like strings, custom data types that are to be shared between Nimrod and +the backend will need careful consideration of who controlls who. If you want +to hand a Nimrod reference to C code, you will need to use `GC_ref +<system.html#GC_ref>`_ to mark the reference as used, so it does not get +freed. And for the C backend you will need to expose the `GC_unref +<system.html#GC_unref>`_ proc to clean up this memory when it is not required +any more. + +Again, if you are wrapping a library which *mallocs* and *frees* data +structures, you need to expose the appropriate *free* function to Nimrod so +you can clean it up. And of course, once cleaned you should avoid accessing it +from Nimrod (or C for that matter). Typically C data structures have their own +``malloc_structure`` and ``free_structure`` specific functions, so wrapping +these for the Nimrod side should be enough. + + +Thread coordination +------------------- + +When the ``NimMain()`` function is called Nimrod initializes the garbage +collector to the current thread, which is usually the main thread of your +application. If your C code later spawns a different thread and calls Nimrod +code, the garbage collector will fail to work properly and you will crash. + +As long as you don't use the threadvar emulation Nimrod uses native thread +variables, of which you get a fresh version whenever you create a thread. You +can then attach a GC to this thread via + +.. code-block:: nimrod + + setStackBottom(addr(someLocal)) + initGC() + +At the moment this support is still experimental so you need to expose these +functions yourself or submit patches to request a public API. + +It is **not** safe to disable the garbage collector and enable it after the +call from your background thread even if the code you are calling is short +lived. diff --git a/doc/c2nim.txt b/doc/c2nim.txt index 6788ef569..237af7fb2 100644 --- a/doc/c2nim.txt +++ b/doc/c2nim.txt @@ -1,6 +1,6 @@ -================================= - c2nim User's manual -================================= +======================= + c2nim User's manual +======================= :Author: Andreas Rumpf :Version: |nimrodversion| diff --git a/doc/docgen.txt b/doc/docgen.txt index 520d5e8a0..30d0c6ff2 100644 --- a/doc/docgen.txt +++ b/doc/docgen.txt @@ -164,20 +164,10 @@ Index switch nimrod doc2 --index:on filename.nim This will generate an index of all the exported symbols in the input Nimrod -module, and put it into a neighboring file with the extension of `.idx`. The -index file is line oriented (newlines have to be escaped). Each line represents -a tab separated record of several columns, the first two mandatory, the rest -optional: - -1. Mandatory term being indexed. Terms can include quoting according to - Nimrod's rules (eg. ```^```) -2. Base filename plus anchor hyper link (eg. - ``algorithm.html#*,int,TSortOrder``). -3. Optional human readable string to display as hyper link. If the value is not - present or is the empty string, the hyper link will be rendered using the - term. -4. Optional title or description of the hyper link. Browsers usually display - this as a tooltip after hovering a moment over the hyper link. +module, and put it into a neighboring file with the extension of ``.idx``. The +index file is line oriented (newlines have to be escaped). Each line +represents a tab separated record of several columns, the first two mandatory, +the rest optional. See the `Index (idx) file format`_ section for details. Once index files have been generated for one or more modules, the Nimrod compiler command ``buildIndex directory`` can be run to go over all the index @@ -295,6 +285,60 @@ symbols in the `system module <system.html>`_. <system.html#newException.t,typedesc,string>`_ +Index (idx) file format +======================= + +Files with the ``.idx`` extension are generated when you use the `Index +switch`_ along with commands to generate documentation from source or text +files. You can programatically generate indices with the `setIndexTerm() +<rstgen.html#setIndexTerm>`_ and `writeIndexFile() +<rstgen.html#writeIndexFile>`_ procs. The purpose of ``idx`` files is to hold +the interesting symbols and their HTML references so they can be later +concatenated into a big index file with `mergeIndexes() +<rstgen.html#mergeIndexes>`_. This section documents the file format in +detail. + +Index files are line oriented and tab separated (newline and tab characters +have to be escaped). Each line represents a record with at least two fields, +but can have up to four (additional columns are ignored). The content of these +columns is: + +1. Mandatory term being indexed. Terms can include quoting according to + Nimrod's rules (eg. \`^\` like in `the actors module + <actors.html#^,ptr.TChannel[T]>`_). +2. Base filename plus anchor hyper link (eg. + ``algorithm.html#*,int,TSortOrder``). +3. Optional human readable string to display as hyper link. If the value is not + present or is the empty string, the hyper link will be rendered + using the term. Prefix whitespace indicates that this entry is + not for an API symbol but for a TOC entry. +4. Optional title or description of the hyper link. Browsers usually display + this as a tooltip after hovering a moment over the hyper link. + +The index generation tools try to differentiate between documentation +generated from ``.nim`` files and documentation generated from ``.txt`` or +``.rst`` files. The former are always closely related to source code and +consist mainly of API entries. The latter are generic documents meant for +human reading. + +To differentiate both types (documents and APIs), the index generator will add +to the index of documents an entry with the title of the document. Since the +title is the topmost element, it will be added with a second field containing +just the filename without any HTML anchor. By convention this entry without +anchor is the *title entry*, and since entries in the index file are added as +they are scanned, the title entry will be the first line. The title for APIs +is not present because it can be generated concatenating the name of the file +to the word **Module**. + +Normal symbols are added to the index with surrounding whitespaces removed. An +exception to this are table of content (TOC) entries. TOC entries are added to +the index file with their third column having as much prefix spaces as their +level is in the TOC (at least 1 character). The prefix whitespace helps to +filter TOC entries from API or text symbols. This is important because the +amount of spaces is used to replicate the hiearchy for document TOCs in the +final index, and TOC entries found in ``.nim`` files are discarded. + + Additional resources ==================== diff --git a/doc/docs.txt b/doc/docs.txt index 2162d6564..8126da86c 100644 --- a/doc/docs.txt +++ b/doc/docs.txt @@ -6,19 +6,19 @@ The documentation consists of several documents: - | `Tutorial (part II) <tut2.html>`_ | The Nimrod tutorial part two deals with the advanced language constructs. +- | `Language Manual <manual.html>`_ + | The Nimrod manual is a draft that will evolve into a proper specification. + - | `Library documentation <lib.html>`_ | This document describes Nimrod's standard library. -- | `User guide <nimrodc.html>`_ +- | `Compiler user guide <nimrodc.html>`_ | The user guide lists command line arguments, special features of the compiler, etc. - | `Tools documentation <tools.html>`_ | Description of some tools that come with the standard distribution. -- | `Manual <manual.html>`_ - | The Nimrod manual is a draft that will evolve into a proper specification. - - | `GC <gc.html>`_ | Additional documentation about Nimrod's GC and how to operate it in a | realtime setting. diff --git a/doc/endb.txt b/doc/endb.txt index d4437e5d9..e9a01b583 100644 --- a/doc/endb.txt +++ b/doc/endb.txt @@ -1,6 +1,6 @@ -=========================================== - Embedded Nimrod Debugger User Guide -=========================================== +============================================== + Embedded Nimrod Debugger (ENDB) User Guide +============================================== :Author: Andreas Rumpf :Version: |nimrodversion| @@ -9,7 +9,7 @@ Nimrod comes with a platform independent debugger - -the `Embedded Nimrod Debugger`:idx: (`ENDB`:idx:). The debugger is +the Embedded Nimrod Debugger (ENDB). The debugger is *embedded* into your executable if it has been compiled with the ``--debugger:on`` command line option. This also defines the conditional symbol ``ENDB`` for you. @@ -102,7 +102,7 @@ necessary: A special pragma has been defined for this: The ``breakpoint`` pragma ------------------------- -The `breakpoint`:idx: pragma is syntactically a statement. It can be used +The ``breakpoint`` pragma is syntactically a statement. It can be used to mark the *following line* as a breakpoint: .. code-block:: Nimrod @@ -122,7 +122,7 @@ debugging. The ``watchpoint`` pragma ------------------------- -The `watchpoint`:idx: pragma is syntactically a statement. It can be used +The ``watchpoint`` pragma is syntactically a statement. It can be used to mark a location as a watchpoint: .. code-block:: Nimrod diff --git a/doc/estp.txt b/doc/estp.txt index 353e4576f..704bc33f2 100644 --- a/doc/estp.txt +++ b/doc/estp.txt @@ -1,13 +1,13 @@ -============================================ - Embedded Stack Trace Profiler User Guide -============================================ +=================================================== + Embedded Stack Trace Profiler (ESTP) User Guide +=================================================== :Author: Andreas Rumpf :Version: |nimrodversion| Nimrod comes with a platform independent profiler - -the `Embedded Stack Trace Profiler`:idx: (`ESTP`:idx:). The profiler +the Embedded Stack Trace Profiler (ESTP). The profiler is *embedded* into your executable. To activate the profiler you need to do: * compile your program with the ``--profiler:on --stackTrace:on`` command diff --git a/doc/filters.txt b/doc/filters.txt index 683599a03..961a0ea49 100644 --- a/doc/filters.txt +++ b/doc/filters.txt @@ -26,7 +26,7 @@ available parameters depend on the invoked filter. Pipe operator ============= -Filters can be combined with the ``|`` `pipe operator`:idx:\ :: +Filters can be combined with the ``|`` pipe operator:: #! strip(startswith="<") | stdtmpl #proc generateXML(name, age: string): string = @@ -46,7 +46,7 @@ after each filter application. Replace filter -------------- -The `replace`:idx: filter replaces substrings in each line. +The replace filter replaces substrings in each line. Parameters and their defaults: @@ -60,7 +60,7 @@ Parameters and their defaults: Strip filter ------------ -The `strip`:idx: filter simply removes leading and trailing whitespace from +The strip filter simply removes leading and trailing whitespace from each line. Parameters and their defaults: @@ -79,7 +79,7 @@ Parameters and their defaults: StdTmpl filter -------------- -The `stdtmpl`:idx: filter provides a simple templating engine for Nimrod. The +The stdtmpl filter provides a simple templating engine for Nimrod. The filter uses a line based parser: Lines prefixed with a *meta character* (default: ``#``) contain Nimrod code, other lines are verbatim. Because indentation-based parsing is not suited for a templating engine, control flow diff --git a/doc/grammar.txt b/doc/grammar.txt index 63e898e11..a54428678 100644 --- a/doc/grammar.txt +++ b/doc/grammar.txt @@ -24,7 +24,7 @@ ampExpr = plusExpr (OP6 optInd plusExpr)* plusExpr = mulExpr (OP7 optInd mulExpr)* mulExpr = dollarExpr (OP8 optInd dollarExpr)* dollarExpr = primary (OP9 optInd primary)* -symbol = '`' (KEYW|IDENT|operator|'(' ')'|'[' ']'|'{' '}'|'='|literal)+ '`' +symbol = '`' (KEYW|IDENT|literal|(operator|'('|')'|'['|']'|'{'|'}'|'=')+)+ '`' | IDENT indexExpr = expr indexExprList = indexExpr ^+ comma @@ -82,10 +82,11 @@ paramListColon = paramList? (':' optInd typeDesc)? doBlock = 'do' paramListArrow pragmas? colcom stmt doBlocks = doBlock ^* IND{=} procExpr = 'proc' paramListColon pragmas? ('=' COMMENT? stmt)? +distinct = 'distinct' optInd typeDesc expr = (ifExpr | whenExpr | caseExpr - | tryStmt) + | tryExpr) / simpleExpr typeKeyw = 'var' | 'ref' | 'ptr' | 'shared' | 'type' | 'tuple' | 'proc' | 'iterator' | 'distinct' | 'object' | 'enum' @@ -134,6 +135,9 @@ caseStmt = 'case' expr ':'? COMMENT? tryStmt = 'try' colcom stmt &(IND{=}? 'except'|'finally') (IND{=}? 'except' exprList colcom stmt)* (IND{=}? 'finally' colcom stmt)? +tryExpr = 'try' colcom stmt &(optInd 'except'|'finally') + (optInd 'except' exprList colcom stmt)* + (optInd 'finally' colcom stmt)? exceptBlock = 'except' colcom stmt forStmt = 'for' (identWithPragma ^+ comma) 'in' expr colcom stmt blockStmt = 'block' symbol? colcom stmt @@ -166,7 +170,6 @@ object = 'object' pragma? ('of' typeDesc)? COMMENT? objectPart typeClassParam = ('var')? symbol typeClass = typeClassParam ^* ',' (pragma)? ('of' typeDesc ^* ',')? &IND{>} stmt -distinct = 'distinct' optInd typeDesc typeDef = identWithPragma genericParamList? '=' optInd typeDefAux indAndComment? varTuple = '(' optInd identWithPragma ^+ comma optPar ')' '=' optInd expr diff --git a/doc/idetools.txt b/doc/idetools.txt index d4f0f077d..97e110b1d 100644 --- a/doc/idetools.txt +++ b/doc/idetools.txt @@ -16,7 +16,7 @@ Nimrod differs from many other compilers in that it is really fast, and being so fast makes it suited to provide external queries for text editors about the source code being written. Through the -`idetools`:idx: command of `the compiler <nimrodc.html>`_, any IDE +``idetools`` command of `the compiler <nimrodc.html>`_, any IDE can query a ``.nim`` source file and obtain useful information like definition of symbols or suggestions for completion. @@ -169,7 +169,7 @@ clicks it and after a second or two the IDE displays where that symbol is defined. Such latencies would be terrible for features like symbol suggestion, plus why wait at all if we can avoid it? -The idetools command can be run as a compiler service (`caas`:idx:), +The idetools command can be run as a compiler service (CAAS), where you first launch the compiler and it will stay online as a server, accepting queries in a telnet like fashion. The advantage of staying on is that for many queries the compiler can cache the @@ -528,7 +528,7 @@ suite is not integrated with the main test suite and you have to run it manually. First you have to compile the tester:: $ cd my/nimrod/checkout/tests - $ nimrod c caasdriver.nim + $ nimrod c testament/caasdriver.nim Running the ``caasdriver`` without parameters will attempt to process all the test cases in all three operation modes. If a test succeeds diff --git a/doc/intern.txt b/doc/intern.txt index c602e4933..1dcf27774 100644 --- a/doc/intern.txt +++ b/doc/intern.txt @@ -59,6 +59,8 @@ And for a debug version compatible with GDB:: The ``koch`` program is Nimrod's maintenance script. It is a replacement for make and shell scripting with the advantage that it is much more portable. +More information about its options can be found in the `koch <koch.html>`_ +documentation. Coding Guidelines @@ -69,8 +71,10 @@ Coding Guidelines * Max line length is 80 characters. * Provide spaces around binary operators if that enhances readability. * Use a space after a colon, but not before it. -* Start types with a capital ``T``, unless they are pointers/references which start - with ``P``. +* Start types with a capital ``T``, unless they are pointers/references which + start with ``P``. + +See also the `API naming design <apis.html>`_ document. Porting to new platforms @@ -156,7 +160,7 @@ generator. Compilation cache ================= -The implementation of the `compilation cache`:idx: is tricky: There are lots +The implementation of the compilation cache is tricky: There are lots of issues to be solved for the front- and backend. In the following sections *global* means *shared between modules* or *property of the whole program*. diff --git a/doc/koch.txt b/doc/koch.txt new file mode 100644 index 000000000..032151808 --- /dev/null +++ b/doc/koch.txt @@ -0,0 +1,144 @@ +=============================== + Nimrod maintenance script +=============================== + +:Version: |nimrodversion| + +.. contents:: + +.. raw:: html + <blockquote><p> + "A great chef is an artist that I truly respect" -- Robert Stack. + </p></blockquote> + + +Introduction +============ + +The `koch`:idx: program is Nimrod's maintenance script. It is a replacement +for make and shell scripting with the advantage that it is much more portable. +The word *koch* means *cook* in German. ``koch`` is used mainly to build the +Nimrod compiler, but it can also be used for other tasks. This document +describes the supported commands and their options. + + +Commands +======== + +boot command +------------ + +The `boot`:idx: command bootstraps the compiler, and it accepts different +options: + +-d:release + By default a debug version is created, passing this option will + force a release build, which is much faster and should be preferred + unless you are debugging the compiler. +-d:tinyc + Include the `Tiny C <http://bellard.org/tcc/>`_ backend. This + option is not supported on Windows. +-d:useGnuReadline + Includes the `rdstdin module <rdstdin.html>`_ for `interactive + mode <nimrodc.html#nimrod-interactive-mode>`_ (aka ``nimrod i``). + This is not needed on Windows. On other platforms this may + incorporate the GNU readline library. +-d:nativeStacktrace + Use native stack traces (only for Mac OS X or Linux). +-d:noCaas + Builds Nimrod without compiler as a service (CAAS) support. CAAS + support is required for functionality like Nimrod's `idetool + <idetools.html>`_ command used to integrate the compiler with + `external IDEs <https://github.com/Araq/Nimrod/wiki/Editor-Support>`_. +-d:avoidTimeMachine + Only for Mac OS X, activating this switch will force excluding + the generated ``nimcache`` directories from Time Machine backups. + By default ``nimcache`` directories will be included in backups, + and just for the Nimrod compiler itself it means backing up 20MB + of generated files each time you update the compiler. Using this + option will make the compiler invoke the `tmutil + <https://developer.apple.com/library/mac/documentation/Darwin/Reference/Manpages/man8/tmutil.8.html>`_ + command on all ``nimcache`` directories, setting their backup + exclusion bit. + + You can use the following command to locate all ``nimcache`` + directories and check their backup exclusion bit:: + + $ find . -type d -name nimcache -exec tmutil isexcluded \{\} \; +-d:useFFI + Nimrod code can use the `foreign function interface (FFI) + <manual.html#foreign-function-interface>`_ at runtime, but macros + are limited to pure Nimrod code at compilation time. Enabling + this switch will allow macros to execute non-nimrod code at + compilation time (eg. open a file and write to it). +--gc:refc|v2|markAndSweep|boehm|none + Selects which garbage collection strategy to use for the compiler + and generated code. See the `Nimrod's Garbage Collector <gc.html>`_ + documentation for more information. + +After compilation is finished you will hopefully end up with the nimrod +compiler in the ``bin`` directory. You can add Nimrod's ``bin`` directory to +your ``$PATH`` or use the `install command`_ to place it where it will be +found. + +clean command +------------- + +The `clean`:idx: command removes all generated files. + +csource command +--------------- + +The `csource`:idx: command builds the C sources for installation. It accepts +the same options as you would pass to the `boot command`_. + +inno command +------------ + +The `inno`:idx: command builds the `Inno Setup installer for Windows +<http://www.jrsoftware.org/isinfo.php>`_. + +install command +--------------- + +The `install`:idx: command installs Nimrod to the specified directory, which +is required as a parameter. For example, on Unix platforms you could run:: + + $ ./koch install /usr/local/bin + +temp command +------------ + +The temp command builds the Nimrod compiler but with a different final name +(``nimrod_temp``), so it doesn't overwrite your normal compiler. You can use +this command to test different options, the same you would issue for the `boot +command`_. + +test command +------------ + +The `test`:idx: command can also be invoked with the alias ``tests``. This +command will compile and run ``tests/testament/tester.nim``, which is the main +driver of Nimrod's test suite. You can pass options to the ``test`` command, +they will be forwarded to the tester. See its source code for available +options. + +update command +-------------- + +The `update`:idx: command updates nimrod to the latest version from github. +For this command to work you need to have compiled ``koch`` itself with the +``-d:withUpdate`` switch. + +web command +----------- + +The `web`:idx: command converts the documentation in the ``doc`` directory +from rst to HTML. It also repeats the same operation but places the result in +the ``web/upload`` which can be used to update the website at +http://nimrod-lang.org. + +zip command +----------- + +The `zip`:idx: command builds the installation ZIP package. diff --git a/doc/lib.txt b/doc/lib.txt index 3ca519c9e..2da753007 100644 --- a/doc/lib.txt +++ b/doc/lib.txt @@ -535,7 +535,7 @@ Database support * `odbcsql <odbcsql.html>`_ interface to the ODBC driver. * `sphinx <sphinx.html>`_ - Nimrod wrapper for ``shpinx``. + Nimrod wrapper for ``sphinx``. XML Processing diff --git a/doc/manual.txt b/doc/manual.txt index 98af5aebc..32b0541e9 100644 --- a/doc/manual.txt +++ b/doc/manual.txt @@ -123,7 +123,7 @@ This means that all the control structures are recognized by indentation. Indentation consists only of spaces; tabulators are not allowed. The indentation handling is implemented as follows: The lexer annotates the -following token with the preceeding number of spaces; indentation is not +following token with the preceding number of spaces; indentation is not a separate token. This trick allows parsing of Nimrod with only 1 token of lookahead. @@ -152,7 +152,7 @@ statements (simplified example):: Comments -------- -`Comments`:idx: start anywhere outside a string or character literal with the +Comments start anywhere outside a string or character literal with the hash character ``#``. Comments consist of a concatenation of `comment pieces`:idx:. A comment piece starts with ``#`` and runs until the end of the line. The end of line characters @@ -188,7 +188,7 @@ which code snippet the comment refers to. Identifiers & Keywords ---------------------- -`Identifiers`:idx: in Nimrod can be any string of letters, digits +Identifiers in Nimrod can be any string of letters, digits and underscores, beginning with a letter. Two immediate following underscores ``__`` are not allowed:: @@ -201,7 +201,7 @@ classified as a ``letter`` and may thus be part of an identifier but later versions of the language may assign some Unicode characters to belong to the operator characters instead. -The following `keywords`:idx: are reserved and cannot be used as identifiers: +The following keywords are reserved and cannot be used as identifiers: .. code-block:: nimrod :file: keywords.txt @@ -224,7 +224,7 @@ String literals Terminal symbol in the grammar: ``STR_LIT``. -`String literals`:idx: can be delimited by matching double quotes, and can +String literals can be delimited by matching double quotes, and can contain the following `escape sequences`:idx:\ : ================== =================================================== @@ -263,15 +263,16 @@ String literals can also be delimited by three double quotes ``"""`` ... ``"""``. Literals in this form may run for several lines, may contain ``"`` and do not interpret any escape sequences. -For convenience, when the opening ``"""`` is immediately followed by a newline, -the newline is not included in the string. The ending of the string literal is -defined by the pattern ``"""[^"]``, so this: - +For convenience, when the opening ``"""`` is followed by a newline (there may +be whitespace between the opening ``"""`` and the newline), +the newline (and the preceding whitespace) is not included in the string. The +ending of the string literal is defined by the pattern ``"""[^"]``, so this: + .. code-block:: nimrod """"long string within quotes"""" - + Produces:: - + "long string within quotes" @@ -280,7 +281,7 @@ Raw string literals Terminal symbol in the grammar: ``RSTR_LIT``. -There are also `raw string literals`:idx: that are preceded with the +There are also raw string literals that are preceded with the letter ``r`` (or ``R``) and are delimited by matching double quotes (just like ordinary string literals) and do not interpret the escape sequences. This is especially convenient for regular expressions or Windows paths: @@ -313,7 +314,7 @@ Terminal symbols in the grammar: ``GENERALIZED_STR_LIT``, The construct ``identifier"string literal"`` (without whitespace between the identifier and the opening quotation mark) is a -`generalized raw string literal`:idx:. It is a shortcut for the construct +generalized raw string literal. It is a shortcut for the construct ``identifier(r"string literal")``, so it denotes a procedure call with a raw string literal as its only argument. Generalized raw string literals are especially convenient for embedding mini languages directly into Nimrod @@ -365,7 +366,7 @@ type is used for Unicode characters, it can represent any Unicode character. Numerical constants ------------------- -`Numerical constants`:idx: are of a single type and have the form:: +Numerical constants are of a single type and have the form:: hexdigit = digit | 'A'..'F' | 'a'..'f' octdigit = '0'..'7' @@ -440,7 +441,7 @@ is approximately 1.72826e35 according to the IEEE floating point standard. Operators --------- -In Nimrod one can define his own operators. An `operator`:idx: is any +In Nimrod one can define his own operators. An operator is any combination of the following characters:: = + - * / < > @@ -587,7 +588,7 @@ The grammar's start symbol is ``module``. Types ===== -All expressions have a `type`:idx: which is known at compile time. Nimrod +All expressions have a type which is known at compile time. Nimrod is statically typed. One can declare new types, which is in essence defining an identifier that can be used to denote this custom type. @@ -605,7 +606,7 @@ These are the major type classes: Ordinal types ------------- -`Ordinal types`:idx: have the following characteristics: +Ordinal types have the following characteristics: - Ordinal types are countable and ordered. This property allows the operation of functions as ``Inc``, ``Ord``, ``Dec`` on ordinal types to @@ -617,7 +618,7 @@ Ordinal types Integers, bool, characters and enumeration types (and subranges of these types) belong to ordinal types. For reasons of simplicity of implementation -the types ``uint`` and ``uint64`` are no ordinal types. +the types ``uint`` and ``uint64`` are not ordinal types. Pre-defined integer types @@ -686,7 +687,7 @@ kinds of integer types are used: the smaller type is converted to the larger. A `narrowing type conversion`:idx: converts a larger to a smaller type (for example ``int32 -> int16``. A `widening type conversion`:idx: converts a smaller type to a larger type (for example ``int16 -> int32``). In Nimrod only -widening type conversion are *implicit*: +widening type conversions are *implicit*: .. code-block:: nimrod var myInt16 = 5i16 @@ -705,7 +706,7 @@ For further details, see `Convertible relation`_. Subrange types -------------- -A `subrange`:idx: type is a range of values from an ordinal type (the base +A subrange type is a range of values from an ordinal type (the base type). To define a subrange type, one must specify it's limiting values: the lowest and highest value of the type: @@ -806,7 +807,7 @@ the ``+``, ``-``, ``*``, ``/`` operators for floating point types. Boolean type ------------ -The `boolean`:idx: type is named `bool`:idx: in Nimrod and can be one of the two +The boolean type is named `bool`:idx: in Nimrod and can be one of the two pre-defined values ``true`` and ``false``. Conditions in while, if, elif, when statements need to be of type bool. @@ -830,7 +831,7 @@ The size of the bool type is one byte. Character type -------------- -The `character type`:idx: is named ``char`` in Nimrod. Its size is one byte. +The character type is named ``char`` in Nimrod. Its size is one byte. Thus it cannot represent an UTF-8 character, but a part of it. The reason for this is efficiency: for the overwhelming majority of use-cases, the resulting programs will still handle UTF-8 properly as UTF-8 was specially @@ -845,7 +846,7 @@ character. ``TRune`` is declared in the `unicode module <unicode.html>`_. Enumeration types ----------------- -`Enumeration`:idx: types define a new type whose values consist of the ones +Enumeration types define a new type whose values consist of the ones specified. The values are ordered. Example: .. code-block:: nimrod @@ -915,7 +916,7 @@ via ``TMyEnum.value``: String type ----------- -All string literals are of the type `string`:idx:. A string in Nimrod is very +All string literals are of the type ``string``. A string in Nimrod is very similar to a sequence of characters. However, strings in Nimrod are both zero-terminated and have a length field. One can retrieve the length with the builtin ``len`` procedure; the length never counts the terminating zero. @@ -942,7 +943,7 @@ i-th *unichar*. The iterator ``runes`` from the `unicode module CString type ------------ -The `cstring`:idx: type represents a pointer to a zero-terminated char array +The ``cstring`` type represents a pointer to a zero-terminated char array compatible to the type ``char*`` in Ansi C. Its primary purpose lies in easy interfacing with C. The index operation ``s[i]`` means the i-th *char* of ``s``; however no bounds checking for ``cstring`` is performed making the @@ -965,23 +966,31 @@ stack roots conservatively. One can use the builtin procs ``GC_ref`` and ``GC_unref`` to keep the string data alive for the rare cases where it does not work. +A `$` proc is defined for cstrings that returns a string. Thus to get a nimrod +string from a cstring: + +.. code-block:: nimrod + var str: string = "Hello!" + var cstr: cstring = s + var newstr: string = $cstr + Structured types ---------------- -A variable of a `structured type`:idx: can hold multiple values at the same +A variable of a structured type can hold multiple values at the same time. Structured types can be nested to unlimited levels. Arrays, sequences, tuples, objects and sets belong to the structured types. Array and sequence types ------------------------ -`Arrays`:idx: are a homogeneous type, meaning that each element in the array +Arrays are a homogeneous type, meaning that each element in the array has the same type. Arrays always have a fixed length which is specified at compile time (except for open arrays). They can be indexed by any ordinal type. A parameter ``A`` may be an *open array*, in which case it is indexed by integers from 0 to ``len(A)-1``. An array expression may be constructed by the array constructor ``[]``. -`Sequences`:idx: are similar to arrays but of dynamic length which may change +Sequences are similar to arrays but of dynamic length which may change during runtime (like strings). Sequences are implemented as growable arrays, allocating pieces of memory as items are added. A sequence ``S`` is always indexed by integers from 0 to ``len(S)-1`` and its bounds are checked. @@ -1038,7 +1047,7 @@ supported because this is seldom needed and cannot be done efficiently. Varargs ------- -A `varargs`:idx: parameter is an openarray parameter that additionally +A ``varargs`` parameter is an openarray parameter that additionally allows to pass a variable number of arguments to a procedure. The compiler converts the list of arguments to an array implicitly: @@ -1073,7 +1082,7 @@ parameter ``a``. (Note that ``$`` applied to strings is a nop.) Tuples and object types ----------------------- -A variable of a `tuple`:idx: or `object`:idx: type is a heterogeneous storage +A variable of a tuple or object type is a heterogeneous storage container. A tuple or object defines various named *fields* of a type. A tuple also defines an *order* of the fields. Tuples are meant for heterogeneous storage @@ -1081,7 +1090,8 @@ types with no overhead and few abstraction possibilities. The constructor ``()`` can be used to construct tuples. The order of the fields in the constructor must match the order of the tuple's definition. Different tuple-types are *equivalent* if they specify the same fields of the same type in the same -order. +order. The *names* of the fields also have to be identical but this might +change in a future version of the language. The assignment operator for tuples copies each component. The default assignment operator for objects copies each component. Overloading @@ -1153,7 +1163,7 @@ For a ``ref object`` type ``system.new`` is invoked implicitly. Object variants --------------- Often an object hierarchy is overkill in certain situations where simple -`variant`:idx: types are needed. +variant types are needed. An example: @@ -1211,7 +1221,7 @@ branch switch ``system.reset`` has to be used. Set type -------- -The `set type`:idx: models the mathematical notion of a set. The set's +The set type models the mathematical notion of a set. The set's basetype can only be an ordinal type. The reason is that sets are implemented as high performance bit vectors. @@ -1246,7 +1256,7 @@ operation meaning Reference and pointer types --------------------------- -References (similar to `pointers`:idx: in other programming languages) are a +References (similar to pointers in other programming languages) are a way to introduce many-to-one relationships. This means different references can point to and modify the same location in memory (also called `aliasing`:idx:). @@ -1344,7 +1354,7 @@ Not nil annotation ------------------ All types for that ``nil`` is a valid value can be annotated to -exclude ``nil`` as a valid value with the `not nil`:idx: annotation: +exclude ``nil`` as a valid value with the ``not nil`` annotation: .. code-block:: nimrod type @@ -1369,7 +1379,7 @@ here. Memory regions -------------- -The types ``ref`` and ``ptr`` can get an optional `region`:idx: annotation. +The types ``ref`` and ``ptr`` can get an optional ``region`` annotation. A region has to be an object type. Regions are very useful to separate user space and kernel memory in the @@ -1428,7 +1438,7 @@ Future directions: Procedural type --------------- -A `procedural type`:idx: is internally a pointer to a procedure. ``nil`` is +A procedural type is internally a pointer to a procedure. ``nil`` is an allowed value for variables of a procedural type. Nimrod uses procedural types to achieve `functional`:idx: programming techniques. @@ -1519,7 +1529,7 @@ Most calling conventions exist only for the Windows 32-bit platform. Assigning/passing a procedure to a procedural variable is only allowed if one of the following conditions hold: -1) The procedure that is accessed resists in the current module. +1) The procedure that is accessed resides in the current module. 2) The procedure is marked with the ``procvar`` pragma (see `procvar pragma`_). 3) The procedure has a calling convention that differs from ``nimcall``. 4) The procedure is anonymous. @@ -1527,8 +1537,8 @@ of the following conditions hold: The rules' purpose is to prevent the case that extending a non-``procvar`` procedure with default parameters breaks client code. -The default calling convention is ``nimcall``, unless it is an inner proc ( -a proc inside of a proc). For an inner proc an analysis is performed whether it +The default calling convention is ``nimcall``, unless it is an inner proc (a +proc inside of a proc). For an inner proc an analysis is performed whether it accesses its environment. If it does so, it has the calling convention ``closure``, otherwise it has the calling convention ``nimcall``. @@ -1536,12 +1546,16 @@ accesses its environment. If it does so, it has the calling convention Distinct type ------------- -A `distinct type`:idx: is new type derived from a `base type`:idx: that is +A ``distinct`` type is new type derived from a `base type`:idx: that is incompatible with its base type. In particular, it is an essential property of a distinct type that it **does not** imply a subtype relation between it and its base type. Explicit type conversions from a distinct type to its base type and vice versa are allowed. + +Modelling currencies +~~~~~~~~~~~~~~~~~~~~ + A distinct type can be used to model different physical `units`:idx: with a numerical base type, for example. The following example models currencies. @@ -1649,12 +1663,73 @@ certain builtin operations to be lifted: Currently only the dot accessor can be borrowed in this way. +Avoiding SQL injection attacks +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +An SQL statement that is passed from Nimrod to an SQL database might be +modelled as a string. However, using string templates and filling in the +values is vulnerable to the famous `SQL injection attack`:idx:\: + +.. code-block:: nimrod + import strutils + + proc query(db: TDbHandle, statement: string) = ... + + var + username: string + + db.query("SELECT FROM users WHERE name = '$1'" % username) + # Horrible security hole, but the compiler does not mind! + +This can be avoided by distinguishing strings that contain SQL from strings +that don't. Distinct types provide a means to introduce a new string type +``TSQL`` that is incompatible with ``string``: + +.. code-block:: nimrod + type + TSQL = distinct string + + proc query(db: TDbHandle, statement: TSQL) = ... + + var + username: string + + db.query("SELECT FROM users WHERE name = '$1'" % username) + # Error at compile time: `query` expects an SQL string! + + +It is an essential property of abstract types that they **do not** imply a +subtype relation between the abtract type and its base type. Explict type +conversions from ``string`` to ``TSQL`` are allowed: + +.. code-block:: nimrod + import strutils, sequtils + + proc properQuote(s: string): TSQL = + # quotes a string properly for an SQL statement + return TSQL(s) + + proc `%` (frmt: TSQL, values: openarray[string]): TSQL = + # quote each argument: + let v = values.mapIt(TSQL, properQuote(it)) + # we need a temporary type for the type conversion :-( + type TStrSeq = seq[string] + # call strutils.`%`: + result = TSQL(string(frmt) % TStrSeq(v)) + + db.query("SELECT FROM users WHERE name = '$1'".TSQL % [username]) + +Now we have compile-time checking against SQL injection attacks. Since +``"".TSQL`` is transformed to ``TSQL("")`` no new syntax is needed for nice +looking ``TSQL`` string literals. The hypothetical ``TSQL`` type actually +exists in the library as the `TSqlQuery type <db_sqlite.html#TSqlQuery>`_ of +modules like `db_sqlite <db_sqlite.html>`_. Void type --------- -The `void`:idx: type denotes the absense of any type. Parameters of +The ``void`` type denotes the absense of any type. Parameters of type ``void`` are treated as non-existent, ``void`` as a return type means that the procedure does not return a value: @@ -1887,7 +1962,7 @@ To be written. Statements and expressions ========================== -Nimrod uses the common statement/expression paradigm: `Statements`:idx: do not +Nimrod uses the common statement/expression paradigm: Statements do not produce a value in contrast to expressions. However, some expressions are statements. @@ -1904,7 +1979,7 @@ Statement list expression Statements can also occur in an expression context that looks like ``(stmt1; stmt2; ...; ex)``. This is called -an `statement list expression`:idx: or ``(;)``. The type +an statement list expression or ``(;)``. The type of ``(stmt1; stmt2; ...; ex)`` is the type of ``ex``. All the other statements must be of type ``void``. (One can use ``discard`` to produce a ``void`` type.) ``(;)`` does not introduce a new scope. @@ -1921,7 +1996,7 @@ Example: discard p(3, 4) # discard the return value of `p` -The `discard`:idx: statement evaluates its expression for side-effects and +The ``discard`` statement evaluates its expression for side-effects and throws the expression's resulting value away. Ignoring the return value of a procedure without using a discard statement is @@ -1949,7 +2024,7 @@ An empty ``discard`` statement is often used as a null statement: Var statement ------------- -`Var`:idx: statements declare new local and global variables and +Var statements declare new local and global variables and initialize them. A comma separated list of variables can be used to specify variables of the same type: @@ -2018,7 +2093,7 @@ initialized and does not rely on syntactic properties: let statement ------------- -A `Let`:idx: statement declares new local and global `single assignment`:idx: +A ``let`` statement declares new local and global `single assignment`:idx: variables and binds a value to them. The syntax is the of the ``var`` statement, except that the keyword ``var`` is replaced by the keyword ``let``. Let variables are not l-values and can thus not be passed to ``var`` parameters @@ -2060,7 +2135,7 @@ they contain such a type. Static statement/expression --------------------------- -A `static`:idx: statement/expression can be used to enforce compile +A static statement/expression can be used to enforce compile time evaluation explicitly. Enforced compile time evaluation can even evaluate code that has side effects: @@ -2094,7 +2169,7 @@ Example: else: echo("Boring name...") -The `if`:idx: statement is a simple way to make a branch in the control flow: +The ``if`` statement is a simple way to make a branch in the control flow: The expression after the keyword ``if`` is evaluated, if it is true the corresponding statements after the ``:`` are executed. Otherwise the expression after the ``elif`` is evaluated (if there is an @@ -2140,7 +2215,7 @@ Example: else: echo("unknown command") -The `case`:idx: statement is similar to the if statement, but it represents +The ``case`` statement is similar to the if statement, but it represents a multi-branch selection. The expression after the keyword ``case`` is evaluated and if its value is in a *slicelist* the corresponding statements (after the ``of`` keyword) are executed. If the value is not in any @@ -2153,12 +2228,12 @@ type. If the expression is not of an ordinal type, and no ``else`` part is given, control passes after the ``case`` statement. -To suppress the static error in the ordinal case an ``else`` part with a ``nil`` -statement can be used. +To suppress the static error in the ordinal case an ``else`` part with an +empty ``discard`` statement can be used. As a special semantic extension, an expression in an ``of`` branch of a case -statement may evaluate to a set constructor; the set is then expanded into -a list of its elements: +statement may evaluate to a set or array constructor; the set or array is then +expanded into a list of its elements: .. code-block:: nimrod const @@ -2194,7 +2269,7 @@ Example: else: echo("cannot happen!") -The `when`:idx: statement is almost identical to the ``if`` statement with some +The ``when`` statement is almost identical to the ``if`` statement with some exceptions: * Each condition (``expr``) has to be a constant expression (of type ``bool``). @@ -2216,7 +2291,7 @@ Example: .. code-block:: nimrod return 40+2 -The `return`:idx: statement ends the execution of the current procedure. +The ``return`` statement ends the execution of the current procedure. It is only allowed in procedures. If there is an ``expr``, this is syntactic sugar for: @@ -2243,7 +2318,7 @@ Example: .. code-block:: nimrod yield (1, 2, 3) -The `yield`:idx: statement is used instead of the ``return`` statement in +The ``yield`` statement is used instead of the ``return`` statement in iterators. It is only valid in iterators. Execution is returned to the body of the for loop that called the iterator. Yield does not end the iteration process, but execution is passed back to the iterator if the next iteration @@ -2266,7 +2341,7 @@ Example: break myblock # leave the block, in this case both for-loops echo(found) -The block statement is a means to group statements to a (named) `block`:idx:. +The block statement is a means to group statements to a (named) ``block``. Inside the block, the ``break`` statement is allowed to leave the block immediately. A ``break`` statement can contain a name of a surrounding block to specify which block is to leave. @@ -2280,7 +2355,7 @@ Example: .. code-block:: nimrod break -The `break`:idx: statement is used to leave a block immediately. If ``symbol`` +The ``break`` statement is used to leave a block immediately. If ``symbol`` is given, it is the name of the enclosing block that is to leave. If it is absent, the innermost block is left. @@ -2298,7 +2373,7 @@ Example: pw = readLine(stdin) -The `while`:idx: statement is executed until the ``expr`` evaluates to false. +The ``while`` statement is executed until the ``expr`` evaluates to false. Endless loops are no error. ``while`` statements open an `implicit block`, so that they can be left with a ``break`` statement. @@ -2306,7 +2381,7 @@ so that they can be left with a ``break`` statement. Continue statement ------------------ -A `continue`:idx: statement leads to the immediate next iteration of the +A ``continue`` statement leads to the immediate next iteration of the surrounding loop construct. It is only allowed within a loop. A continue statement is syntactic sugar for a nested block: @@ -2329,13 +2404,14 @@ Is equivalent to: Assembler statement ------------------- -The direct embedding of `assembler`:idx: code into Nimrod code is supported +The direct embedding of assembler code into Nimrod code is supported by the unsafe ``asm`` statement. Identifiers in the assembler code that refer to Nimrod identifiers shall be enclosed in a special character which can be specified in the statement's pragmas. The default special character is ``'`'``: .. code-block:: nimrod - proc addInt(a, b: int): int {.noStackFrame.} = + {.push stackTrace:off.} + proc addInt(a, b: int): int = # a in eax, and b in edx asm """ mov eax, `a` @@ -2344,6 +2420,7 @@ specified in the statement's pragmas. The default special character is ``'`'``: call `raiseOverflow` theEnd: """ + {.pop.} If the GNU assembler is used, quotes and newlines are inserted automatically: @@ -2376,7 +2453,7 @@ Using statement **Warning**: The ``using`` statement is highly experimental! -The `using statement`:idx: provides syntactic convenience for procs that +The using statement provides syntactic convenience for procs that heavily use a single contextual parameter. When applied to a variable or a constant, it will instruct Nimrod to automatically consider the used symbol as a hidden leading parameter for any procedure calls, following the using @@ -2461,7 +2538,7 @@ the last expression as the result value, much like in an `expr` template. Table constructor ----------------- -A `table constructor`:idx: is syntactic sugar for an array constructor: +A table constructor is syntactic sugar for an array constructor: .. code-block:: nimrod {"key1": "value1", "key2", "key3": "value2"} @@ -2508,7 +2585,7 @@ only needed for low-level programming and are inherently unsafe. The addr operator ----------------- -The `addr`:idx: operator returns the address of an l-value. If the type of the +The ``addr`` operator returns the address of an l-value. If the type of the location is ``T``, the `addr` operator result is of the type ``ptr T``. An address is always an untraced reference. Taking the address of an object that resides on the stack is **unsafe**, as the pointer may live longer than the @@ -2609,7 +2686,7 @@ For object oriented programming, the syntax ``obj.method(args)`` can be used instead of ``method(obj, args)``. The parentheses can be omitted if there are no remaining arguments: ``obj.len`` (instead of ``len(obj)``). -This `method call syntax`:idx: is not restricted to objects, it can be used +This method call syntax is not restricted to objects, it can be used to supply any type of first argument for procedures: .. code-block:: nimrod @@ -2654,7 +2731,7 @@ Command invocation syntax ------------------------- Routines can be invoked without the ``()`` if the call is syntatically -a statement. This `command invocation syntax`:idx: also works for +a statement. This command invocation syntax also works for expressions, but then only a single argument may follow. This restriction means ``echo f 1, f 2`` is parsed as ``echo(f(1), f(2))`` and not as ``echo(f(1, f(2)))``. The method call syntax may be used to provide one @@ -2748,7 +2825,7 @@ The following builtin procs cannot be overloaded for reasons of implementation simplicity (they require specialized semantic checking):: defined, definedInScope, compiles, low, high, sizeOf, - is, of, echo, shallowCopy, getAst + is, of, echo, shallowCopy, getAst, spawn Thus they act more like keywords than like ordinary identifiers; unlike a keyword however, a redefinition may `shadow`:idx: the definition in @@ -2851,7 +2928,7 @@ The ``[]`` subscript operator for arrays/openarrays/sequences can be overloaded. Multi-methods ============= -Procedures always use static dispatch. `Multi-methods`:idx: use dynamic +Procedures always use static dispatch. Multi-methods use dynamic dispatch. .. code-block:: nimrod @@ -3104,7 +3181,7 @@ Example: line: int # the line the symbol was declared in code: PNode # the symbol's abstract syntax tree -A `type`:idx: section begins with the ``type`` keyword. It contains multiple +A type section begins with the ``type`` keyword. It contains multiple type definitions. A type definition binds a type to a name. Type definitions can be recursive or even mutually recursive. Mutually recursive types are only possible within a single ``type`` section. Nominal types like ``objects`` @@ -3141,7 +3218,7 @@ Example: close(f) -The statements after the `try`:idx: are executed in sequential order unless +The statements after the ``try`` are executed in sequential order unless an exception ``e`` is raised. If the exception type of ``e`` matches any listed in an ``except`` clause the corresponding statements are executed. The statements following the ``except`` clauses are called @@ -3163,7 +3240,7 @@ is not executed (if an exception occurs). Except and finally statements ----------------------------- -`except`:idx: and `finally`:idx: can also be used as a stand-alone statements. +``except`` and ``finally`` can also be used as a stand-alone statements. Any statements following them in the current block will be considered to be in an implicit try block: @@ -3212,9 +3289,9 @@ exception (unless a raise hook has been provided). OnRaise builtin --------------- -``system.onRaise`` can be used to override the behaviour of ``raise`` for a -single ``try`` statement. `onRaise`:idx: has to be called within the ``try`` -statement that should be affected. +`system.onRaise() <system.html#onRaise>`_ can be used to override the +behaviour of ``raise`` for a single ``try`` statement. ``onRaise`` has to be +called within the ``try`` statement that should be affected. This allows for a Lisp-like `condition system`:idx:\: @@ -3243,7 +3320,7 @@ Effect system Exception tracking ------------------ -Nimrod supports `exception tracking`:idx:. The `raises`:idx: pragma can be used +Nimrod supports exception tracking. The `raises`:idx: pragma can be used to explicitly define which exceptions a proc/iterator/method/converter is allowed to raise. The compiler verifies this: @@ -3351,7 +3428,7 @@ exception tracking. Effects pragma -------------- -The `effects`:idx: pragma has been designed to assist the programmer with the +The ``effects`` pragma has been designed to assist the programmer with the effects analysis. It is a statement that makes the compiler output all inferred effects up to the ``effects``'s position: @@ -3420,7 +3497,7 @@ Example: for str in inorder(root): writeln(stdout, str) -`Generics`:idx: are Nimrod's means to parametrize procs, iterators or types with +Generics are Nimrod's means to parametrize procs, iterators or types with `type parameters`:idx:. Depending on context, the brackets are used either to introduce type parameters or to instantiate a generic proc, iterator or type. @@ -3428,7 +3505,7 @@ introduce type parameters or to instantiate a generic proc, iterator or type. Is operator ----------- -The `is`:idx: operator checks for type equivalence at compile time. It is +The ``is`` operator checks for type equivalence at compile time. It is therefore very useful for type specialization within generic code: .. code-block:: nimrod @@ -3443,7 +3520,7 @@ therefore very useful for type specialization within generic code: Type operator ------------- -The `type`:idx: (in many other languages called `typeof`:idx:) operator can +The ``type`` (in many other languages called `typeof`:idx:) operator can be used to get the type of an expression: .. code-block:: nimrod @@ -3466,7 +3543,7 @@ other interpretations: Type Classes ------------ -A `type class`:idx: is a special pseudo-type that can be used to match against +A type class is a special pseudo-type that can be used to match against types in the context of overload resolution or the ``is`` operator. Nimrod supports the following built-in type classes: @@ -3684,7 +3761,7 @@ A symbol can be forced to be open by a `mixin`:idx: declaration: Bind statement -------------- -The `bind`:idx: statement is the counterpart to the ``mixin`` statement. It +The ``bind`` statement is the counterpart to the ``mixin`` statement. It can be used to explicitly declare identifiers that should be bound early (i.e. the identifiers should be looked up in the scope of the template/generic definition): @@ -3712,7 +3789,7 @@ scope is the default. Templates ========= -A `template`:idx: is a simple form of a macro: It is a simple substitution +A template is a simple form of a macro: It is a simple substitution mechanism that operates on Nimrod's abstract syntax trees. It is processed in the semantic pass of the compiler. @@ -3744,7 +3821,7 @@ expected. Ordinary vs immediate templates ------------------------------- -There are two different kinds of templates: `immediate`:idx: templates and +There are two different kinds of templates: immediate templates and ordinary templates. Ordinary templates take part in overloading resolution. As such their arguments need to be type checked before the template is invoked. So ordinary templates cannot receive undeclared identifiers: @@ -3939,7 +4016,7 @@ a template. ``inject`` and ``gensym`` have no effect in ``dirty`` templates. Macros ====== -A `macro`:idx: is a special kind of low level template. Macros can be used +A macro is a special kind of low level template. Macros can be used to implement `domain specific languages`:idx:. Like templates, macros come in the 2 flavors *immediate* and *ordinary*. @@ -4317,7 +4394,7 @@ This operator will be matched against assignments to missing fields. Term rewriting macros ===================== -`Term rewriting macros`:idx: are macros or templates that have not only +Term rewriting macros are macros or templates that have not only a *name* but also a *pattern* that is searched for after the semantic checking phase of the compiler: This means they provide an easy way to enhance the compilation pipeline with user defined optimizations: @@ -4653,7 +4730,7 @@ ordinary routines. Move optimization ----------------- -The ``call`` constraint is particularly useful to implement a `move`:idx: +The ``call`` constraint is particularly useful to implement a move optimization for types that have copying semantics: .. code-block:: nimrod @@ -4679,7 +4756,7 @@ optimization for types that have copying semantics: Modules ======= -Nimrod supports splitting a program into pieces by a `module`:idx: concept. +Nimrod supports splitting a program into pieces by a module concept. Each module needs to be in its own file and has its own `namespace`:idx:. Modules enable `information hiding`:idx: and `separate compilation`:idx:. A module may gain access to symbols of another module by the `import`:idx: @@ -4722,7 +4799,7 @@ This is best illustrated by an example: Import statement ~~~~~~~~~~~~~~~~ -After the `import`:idx: statement a list of module names can follow or a single +After the ``import`` statement a list of module names can follow or a single module name followed by an ``except`` to prevent some symbols to be imported: .. code-block:: nimrod @@ -4765,7 +4842,7 @@ Likewise the following does not make sense as the name is ``strutils`` already: From import statement ~~~~~~~~~~~~~~~~~~~~~ -After the `from`:idx: statement a module name follows followed by +After the ``from`` statement a module name follows followed by an ``import`` to list the symbols one likes to use without explict full qualification: @@ -4784,7 +4861,7 @@ in ``module``. Export statement ~~~~~~~~~~~~~~~~ -An `export`:idx: statement can be used for symbol fowarding so that client +An ``export`` statement can be used for symbol fowarding so that client modules don't need to import a module's dependencies: .. code-block:: nimrod @@ -4812,7 +4889,7 @@ Scope rules ----------- Identifiers are valid from the point of their declaration until the end of the block in which the declaration occurred. The range where the identifier -is known is the `scope`:idx: of the identifier. The exact scope of an +is known is the scope of the identifier. The exact scope of an identifier depends on the way it was declared. Block scope @@ -4885,7 +4962,7 @@ to access the feature becomes available. noSideEffect pragma ------------------- -The `noSideEffect`:idx: pragma is used to mark a proc/iterator to have no side +The ``noSideEffect`` pragma is used to mark a proc/iterator to have no side effects. This means that the proc/iterator only changes locations that are reachable from its parameters and the return value only depends on the arguments. If none of its parameters have the type ``var T`` @@ -4907,7 +4984,7 @@ proc with no side effects: destructor pragma ----------------- -The `destructor`:idx: pragma is used to mark a proc to act as a type destructor. +The ``destructor`` pragma is used to mark a proc to act as a type destructor. The proc must have a single parameter with a concrete type (the name of a generic type is allowed too). @@ -4967,25 +5044,25 @@ the ``finalizer`` parameter to ``new``. procvar pragma -------------- -The `procvar`:idx: pragma is used to mark a proc that it can be passed to a +The ``procvar`` pragma is used to mark a proc that it can be passed to a procedural variable. compileTime pragma ------------------ -The `compileTime`:idx: pragma is used to mark a proc to be used at compile +The ``compileTime`` pragma is used to mark a proc to be used at compile time only. No code will be generated for it. Compile time procs are useful as helpers for macros. noReturn pragma --------------- -The `noreturn`:idx: pragma is used to mark a proc that never returns. +The ``noreturn`` pragma is used to mark a proc that never returns. Acyclic pragma -------------- -The `acyclic`:idx: pragma can be used for object types to mark them as acyclic +The ``acyclic`` pragma can be used for object types to mark them as acyclic even though they seem to be cyclic. This is an **optimization** for the garbage collector to not consider objects of this type as part of a cycle: @@ -5016,13 +5093,13 @@ memory, but nothing worse happens. Final pragma ------------ -The `final`:idx: pragma can be used for an object type to specify that it +The ``final`` pragma can be used for an object type to specify that it cannot be inherited from. shallow pragma -------------- -The `shallow`:idx: pragma affects the semantics of a type: The compiler is +The ``shallow`` pragma affects the semantics of a type: The compiler is allowed to make a shallow copy. This can cause serious semantic issues and break memory safety! However, it can speed up assignments considerably, because the semantics of Nimrod require deep copying of sequences and strings. @@ -5042,14 +5119,14 @@ structure: Pure pragma ----------- -An object type can be marked with the `pure`:idx: pragma so that its type +An object type can be marked with the ``pure`` pragma so that its type field which is used for runtime type identification is omitted. This is necessary for binary compatibility with other compiled languages. AsmNoStackFrame pragma ---------------------- -A proc can be marked with the `AsmNoStackFrame`:idx: pragma to tell the compiler +A proc can be marked with the ``AsmNoStackFrame`` pragma to tell the compiler it should not generate a stack frame for the proc. There are also no exit statements like ``return result;`` generated and the generated C function is declared as ``__declspec(naked)`` or ``__attribute__((naked))`` (depending on @@ -5060,7 +5137,7 @@ assembler statements. error pragma ------------ -The `error`:idx: pragma is used to make the compiler output an error message +The ``error`` pragma is used to make the compiler output an error message with the given content. Compilation does not necessarily abort after an error though. @@ -5076,7 +5153,7 @@ operation is valid due to overloading and type conversions: fatal pragma ------------ -The `fatal`:idx: pragma is used to make the compiler output an error message +The ``fatal`` pragma is used to make the compiler output an error message with the given content. In contrast to the ``error`` pragma, compilation is guaranteed to be aborted by this pragma. Example: @@ -5086,17 +5163,17 @@ is guaranteed to be aborted by this pragma. Example: warning pragma -------------- -The `warning`:idx: pragma is used to make the compiler output a warning message +The ``warning`` pragma is used to make the compiler output a warning message with the given content. Compilation continues after the warning. hint pragma ----------- -The `hint`:idx: pragma is used to make the compiler output a hint message with +The ``hint`` pragma is used to make the compiler output a hint message with the given content. Compilation continues after the hint. line pragma ----------- -The `line`:idx: pragma can be used to affect line information of the annotated +The ``line`` pragma can be used to affect line information of the annotated statement as seen in stack backtraces: .. code-block:: nimrod @@ -5114,7 +5191,7 @@ If the ``line`` pragma is used with a parameter, the parameter needs be a linearScanEnd pragma -------------------- -The `linearScanEnd`:idx: pragma can be used to tell the compiler how to +The ``linearScanEnd`` pragma can be used to tell the compiler how to compile a Nimrod `case`:idx: statement. Syntactically it has to be used as a statement: @@ -5142,7 +5219,7 @@ whole ``case`` statement, the whole ``case`` statement uses linear scanning. computedGoto pragma ------------------- -The `computedGoto`:idx: pragma can be used to tell the compiler how to +The ``computedGoto`` pragma can be used to tell the compiler how to compile a Nimrod `case`:idx: in a ``while true`` statement. Syntactically it has to be used as a statement inside the loop: @@ -5187,7 +5264,7 @@ extension the pragma is simply ignored. unroll pragma ------------- -The `unroll`:idx: pragma can be used to tell the compiler that it should unroll +The ``unroll`` pragma can be used to tell the compiler that it should unroll a `for`:idx: or `while`:idx: loop for runtime efficiency: .. code-block:: nimrod @@ -5266,7 +5343,7 @@ but are used to override the settings temporarily. Example: register pragma --------------- -The `register`:idx: pragma is for variables only. It declares the variable as +The ``register`` pragma is for variables only. It declares the variable as ``register``, giving the compiler a hint that the variable should be placed in a hardware register for faster access. C compilers usually ignore this though and for good reasons: Often they do a better job without it anyway. @@ -5277,7 +5354,7 @@ example) it may provide benefits, though. global pragma ------------- -The `global`:idx: pragma can be applied to a variable within a proc to instruct +The ``global`` pragma can be applied to a variable within a proc to instruct the compiler to store it in a global location and initialize it once at program startup. @@ -5294,7 +5371,7 @@ and before any variable in a module that imports it. DeadCodeElim pragma ------------------- -The `deadCodeElim`:idx: pragma only applies to whole modules: It tells the +The ``deadCodeElim`` pragma only applies to whole modules: It tells the compiler to activate (or deactivate) dead code elimination for the module the pragma appears in. @@ -5312,7 +5389,7 @@ Example: .. NoForward pragma ---------------- - The `noforward`:idx: pragma can be used to turn on and off a special compilation + The ``noforward`` pragma can be used to turn on and off a special compilation mode that to large extent eliminates the need for forward declarations. In this mode, the proc definitions may appear out of order and the compiler will postpone their semantic analysis and compilation until it actually needs to generate code @@ -5360,7 +5437,7 @@ Example: Pragma pragma ------------- -The `pragma`:idx: pragma can be used to declare user defined pragmas. This is +The ``pragma`` pragma can be used to declare user defined pragmas. This is useful because Nimrod's templates and macros do not affect pragmas. User defined pragmas are in a different module-wide scope than all other symbols. They cannot be imported from a module. @@ -5389,7 +5466,7 @@ and warning message contains a symbol in brackets. This is the message's identifier that can be used to enable or disable it: .. code-block:: Nimrod - {.warning[LineTooLong]: off.} # turn off warning about too long lines + {.hint[LineTooLong]: off.} # turn off the hint about too long lines This is often better than disabling all warnings at once. @@ -5404,21 +5481,24 @@ are documented here. Importc pragma -------------- -The `importc`:idx: pragma provides a means to import a proc or a variable +The ``importc`` pragma provides a means to import a proc or a variable from C. The optional argument is a string containing the C identifier. If the argument is missing, the C name is the Nimrod identifier *exactly as spelled*: .. code-block:: - proc printf(formatstr: cstring) {.importc: "printf", varargs.} + proc printf(formatstr: cstring) {.header: "<stdio.h>", importc: "printf", varargs.} Note that this pragma is somewhat of a misnomer: Other backends will provide -the same feature under the same name. +the same feature under the same name. Also, if you are interfacing with C++ +you can use the `ImportCpp pragma <nimrodc.html#importcpp-pragma>`_ and +interfacing with Objective-C the `ImportObjC pragma +<nimrodc.html#importobjc-pragma>`_. Exportc pragma -------------- -The `exportc`:idx: pragma provides a means to export a type, a variable, or a +The ``exportc`` pragma provides a means to export a type, a variable, or a procedure to C. Enums and constants can't be exported. The optional argument is a string containing the C identifier. If the argument is missing, the C name is the Nimrod identifier *exactly as spelled*: @@ -5432,7 +5512,7 @@ the same feature under the same name. Extern pragma ------------- -Like ``exportc`` or ``importc`` the `extern`:idx: pragma affects name +Like ``exportc`` or ``importc``, the ``extern`` pragma affects name mangling. The string literal passed to ``extern`` can be a format string: .. code-block:: Nimrod @@ -5445,7 +5525,7 @@ In the example the external name of ``p`` is set to ``prefixp``. Bycopy pragma ------------- -The `bycopy`:idx: pragma can be applied to an object or tuple type and +The ``bycopy`` pragma can be applied to an object or tuple type and instructs the compiler to pass the type by value to procs: .. code-block:: nimrod @@ -5457,13 +5537,13 @@ instructs the compiler to pass the type by value to procs: Byref pragma ------------ -The `byref`:idx: pragma can be applied to an object or tuple type and instructs +The ``byref`` pragma can be applied to an object or tuple type and instructs the compiler to pass the type by reference (hidden pointer) to procs. Varargs pragma -------------- -The `varargs`:idx: pragma can be applied to procedures only (and procedure +The ``varargs`` pragma can be applied to procedures only (and procedure types). It tells Nimrod that the proc can take a variable number of parameters after the last specified parameter. Nimrod string values will be converted to C strings automatically: @@ -5476,7 +5556,7 @@ strings automatically: Union pragma ------------ -The `union`:idx: pragma can be applied to any ``object`` type. It means all +The ``union`` pragma can be applied to any ``object`` type. It means all of the object's fields are overlaid in memory. This produces a ``union`` instead of a ``struct`` in the generated C/C++ code. The object declaration then must not use inheritance or any GC'ed memory but this is currently not @@ -5487,7 +5567,7 @@ should scan unions conservatively. Packed pragma ------------- -The `packed`:idx: pragma can be applied to any ``object`` type. It ensures +The ``packed`` pragma can be applied to any ``object`` type. It ensures that the fields of an object are packed back-to-back in memory. It is useful to store packets or messages from/to network or hardware drivers, and for interoperability with C. Combining packed pragma with inheritance is not @@ -5498,7 +5578,7 @@ compile-time error. Usage with inheritance should be defined and documented. Unchecked pragma ---------------- -The `unchecked`:idx: pragma can be used to mark a named array as ``unchecked`` +The ``unchecked`` pragma can be used to mark a named array as ``unchecked`` meaning its bounds are not checked. This is often useful when one wishes to implement his own flexibly sized arrays. Additionally an unchecked array is translated into a C array of undetermined size: @@ -5533,7 +5613,7 @@ runtime size of the array. Dynlib pragma for import ------------------------ -With the `dynlib`:idx: pragma a procedure or a variable can be imported from +With the ``dynlib`` pragma a procedure or a variable can be imported from a dynamic library (``.dll`` files for Windows, ``lib*.so`` files for UNIX). The non-optional argument has to be the name of the dynamic library: @@ -5623,7 +5703,7 @@ Thread pragma ------------- A proc that is executed as a new thread of execution should be marked by the -`thread pragma`:idx:. The compiler checks procedures marked as ``thread`` for +``thread`` pragma. The compiler checks procedures marked as ``thread`` for violations of the `no heap sharing restriction`:idx:\: This restriction implies that it is invalid to construct a data structure that consists of memory allocated from different (thread local) heaps. @@ -5664,7 +5744,7 @@ Future directions: Threadvar pragma ---------------- -A global variable can be marked with the `threadvar`:idx: pragma; it is +A global variable can be marked with the ``threadvar`` pragma; it is a `thread-local`:idx: variable then: .. code-block:: nimrod @@ -5688,7 +5768,7 @@ Spawn Nimrod has a builtin thread pool that can be used for CPU intensive tasks. For IO intensive tasks the upcoming ``async`` and ``await`` features should be -used. `spawn`:idx: is used to pass a task to the thread pool: +used instead. `spawn`:idx: is used to pass a task to the thread pool: .. code-block:: nimrod proc processLine(line: string) = @@ -5716,7 +5796,7 @@ Taint mode ========== The Nimrod compiler and most parts of the standard library support -a `taint mode`:idx:. Input strings are declared with the `TaintedString`:idx: +a taint mode. Input strings are declared with the `TaintedString`:idx: string type declared in the ``system`` module. If the taint mode is turned on (via the ``--taintMode:on`` command line diff --git a/doc/nimgrep.txt b/doc/nimgrep.txt index c231bf31b..67aaa427e 100644 --- a/doc/nimgrep.txt +++ b/doc/nimgrep.txt @@ -1,6 +1,6 @@ -================================= - nimgrep User's manual -================================= +========================= + nimgrep User's manual +========================= :Author: Andreas Rumpf :Version: 0.9 diff --git a/doc/niminst.txt b/doc/niminst.txt index ebed396e4..8d95d01c9 100644 --- a/doc/niminst.txt +++ b/doc/niminst.txt @@ -1,6 +1,6 @@ -================================= - niminst User's manual -================================= +========================= + niminst User's manual +========================= :Author: Andreas Rumpf :Version: |nimrodversion| diff --git a/doc/nimrodc.txt b/doc/nimrodc.txt index 52e0a6eaf..428c42f39 100644 --- a/doc/nimrodc.txt +++ b/doc/nimrodc.txt @@ -87,6 +87,18 @@ Level Description for compiler developers. ===== ============================================ + +Compile time symbols +-------------------- + +Through the ``-d:x`` or ``--define:x`` switch you can define compile time +symbols for conditional compilation. The defined switches can be checked in +source code with the `when statement <manual.html#when-statement>`_ and +`defined proc <system.html#defined>`_. The typical use of this switch is to +enable builds in release mode (``-d:release``) where certain safety checks are +omitted for better performance. Another common use is the ``-d:ssl`` switch to +activate `SSL sockets <sockets.html>`_. + Configuration files ------------------- @@ -116,7 +128,7 @@ The default build of a project is a `debug build`:idx:. To compile a Search path handling -------------------- -Nimrod has the concept of a global `search path`:idx: (PATH) that is queried to +Nimrod has the concept of a global search path (PATH) that is queried to determine where to find imported modules or include files. If multiple files are found an ambiguity error is produced. @@ -167,14 +179,14 @@ might contain some cruft even when dead code elimination is turned on. So the final release build should be done with ``--symbolFiles:off``. Due to the aggregation of C code it is also recommended that each project -resists in its own directory so that the generated ``nimcache`` directory +resides in its own directory so that the generated ``nimcache`` directory is not shared between different projects. Cross compilation ================= -To `cross compile`:idx:, use for example:: +To cross compile, use for example:: nimrod c --cpu:i386 --os:linux --compile_only --gen_script myproject.nim @@ -200,7 +212,7 @@ DLL generation Nimrod supports the generation of DLLs. However, there must be only one instance of the GC per process/address space. This instance is contained in -``nimrtl.dll``. This means that every generated Nimrod `DLL`:idx: depends +``nimrtl.dll``. This means that every generated Nimrod DLL depends on ``nimrtl.dll``. To generate the "nimrtl.dll" file, use the command:: nimrod c -d:release lib/nimrtl.nim @@ -251,7 +263,7 @@ generator and are subject to change. NoDecl pragma ------------- -The `noDecl`:idx: pragma can be applied to almost any symbol (variable, proc, +The ``noDecl`` pragma can be applied to almost any symbol (variable, proc, type, etc.) and is sometimes useful for interoperability with C: It tells Nimrod that it should not generate a declaration for the symbol in the C code. For example: @@ -268,7 +280,7 @@ However, the ``header`` pragma is often the better alternative. Header pragma ------------- -The `header`:idx: pragma is very similar to the ``noDecl`` pragma: It can be +The ``header`` pragma is very similar to the ``noDecl`` pragma: It can be applied to almost any symbol and specifies that it should not be declared and instead the generated code should contain an ``#include``: @@ -287,7 +299,7 @@ encloses the header file in ``""`` in the generated C code. IncompleteStruct pragma ----------------------- -The `incompleteStruct`:idx: pragma tells the compiler to not use the +The ``incompleteStruct`` pragma tells the compiler to not use the underlying C ``struct`` in a ``sizeof`` expression: .. code-block:: Nimrod @@ -298,7 +310,7 @@ underlying C ``struct`` in a ``sizeof`` expression: Compile pragma -------------- -The `compile`:idx: pragma can be used to compile and link a C/C++ source file +The ``compile`` pragma can be used to compile and link a C/C++ source file with the project: .. code-block:: Nimrod @@ -311,7 +323,7 @@ of the file. Link pragma ----------- -The `link`:idx: pragma can be used to link an additional file with the project: +The ``link`` pragma can be used to link an additional file with the project: .. code-block:: Nimrod {.link: "myfile.o".} @@ -319,7 +331,7 @@ The `link`:idx: pragma can be used to link an additional file with the project: PassC pragma ------------ -The `passC`:idx: pragma can be used to pass additional parameters to the C +The ``passC`` pragma can be used to pass additional parameters to the C compiler like you would using the commandline switch ``--passC``: .. code-block:: Nimrod @@ -333,7 +345,7 @@ embed parameters from an external command at compile time: PassL pragma ------------ -The `passL`:idx: pragma can be used to pass additional parameters to the linker +The ``passL`` pragma can be used to pass additional parameters to the linker like you would using the commandline switch ``--passL``: .. code-block:: Nimrod @@ -348,7 +360,7 @@ embed parameters from an external command at compile time: Emit pragma ----------- -The `emit`:idx: pragma can be used to directly affect the output of the +The ``emit`` pragma can be used to directly affect the output of the compiler's code generator. So it makes your code unportable to other code generators/backends. Its usage is highly discouraged! However, it can be extremely useful for interfacing with `C++`:idx: or `Objective C`:idx: code. @@ -360,20 +372,23 @@ Example: static int cvariable = 420; """.} - proc embedsC() {.noStackFrame.} = + {.push stackTrace:off.} + proc embedsC() = var nimrodVar = 89 # use backticks to access Nimrod symbols within an emit section: {.emit: """fprintf(stdout, "%d\n", cvariable + (int)`nimrodVar`);""".} + {.pop.} embedsC() ImportCpp pragma ---------------- -The `importcpp`:idx: pragma can be used to import `C++`:idx: methods. The -generated code then uses the C++ method calling syntax: ``obj->method(arg)``. -In addition with the ``header`` and ``emit`` pragmas this allows *sloppy* -interfacing with libraries written in C++: +Similar to the `importc pragma for C <manual.html#importc-pragma>`_, the +``importcpp`` pragma can be used to import `C++`:idx: methods. The generated +code then uses the C++ method calling syntax: ``obj->method(arg)``. In +addition with the ``header`` and ``emit`` pragmas this allows *sloppy* +interfacing with libraries written in C++: .. code-block:: Nimrod # Horrible example of how to interface with a C++ engine ... ;-) @@ -408,11 +423,11 @@ emits C++ code. ImportObjC pragma ----------------- -The `importobjc`:idx: pragma can be used to import `Objective C`:idx: methods. -The generated code then uses the Objective C method calling -syntax: ``[obj method param1: arg]``. -In addition with the ``header`` and ``emit`` pragmas this allows *sloppy* -interfacing with libraries written in Objective C: +Similar to the `importc pragma for C <manual.html#importc-pragma>`_, the +``importobjc`` pragma can be used to import `Objective C`:idx: methods. The +generated code then uses the Objective C method calling syntax: ``[obj method +param1: arg]``. In addition with the ``header`` and ``emit`` pragmas this +allows *sloppy* interfacing with libraries written in Objective C: .. code-block:: Nimrod # horrible example of how to interface with GNUStep ... @@ -458,7 +473,7 @@ emits Objective C code. CodegenDecl pragma ------------------ -The `codegenDecl`:idx: pragma can be used to directly influence Nimrod's code +The ``codegenDecl`` pragma can be used to directly influence Nimrod's code generator. It receives a format string that determines how the variable or proc is declared in the generated code: @@ -473,7 +488,7 @@ proc is declared in the generated code: InjectStmt pragma ----------------- -The `injectStmt`:idx: pragma can be used to inject a statement before every +The ``injectStmt`` pragma can be used to inject a statement before every other statement in the current module. It is only supposed to be used for debugging: @@ -485,28 +500,28 @@ debugging: LineDir option -------------- -The `lineDir`:idx: option can be turned on or off. If turned on the +The ``lineDir`` option can be turned on or off. If turned on the generated C code contains ``#line`` directives. This may be helpful for debugging with GDB. StackTrace option ----------------- -If the `stackTrace`:idx: option is turned on, the generated C contains code to +If the ``stackTrace`` option is turned on, the generated C contains code to ensure that proper stack traces are given if the program crashes or an uncaught exception is raised. LineTrace option ---------------- -The `lineTrace`:idx: option implies the ``stackTrace`` option. If turned on, +The ``lineTrace`` option implies the ``stackTrace`` option. If turned on, the generated C contains code to ensure that proper stack traces with line number information are given if the program crashes or an uncaught exception is raised. Debugger option --------------- -The `debugger`:idx: option enables or disables the *Embedded Nimrod Debugger*. +The ``debugger`` option enables or disables the *Embedded Nimrod Debugger*. See the documentation of endb_ for further information. @@ -518,7 +533,7 @@ ENDB. See the documentation of `endb <endb.html>`_ for further information. Volatile pragma --------------- -The `volatile`:idx: pragma is for variables only. It declares the variable as +The ``volatile`` pragma is for variables only. It declares the variable as ``volatile``, whatever that means in C/C++ (its semantics are not well defined in C/C++). @@ -530,14 +545,24 @@ DynlibOverride By default Nimrod's ``dynlib`` pragma causes the compiler to generate ``GetProcAddress`` (or their Unix counterparts) -calls to bind to a DLL. With the `dynlibOverride`:idx: command line switch this +calls to bind to a DLL. With the ``dynlibOverride`` command line switch this can be prevented and then via ``--passL`` the static library can be linked against. For instance, to link statically against Lua this command might work on Linux:: nimrod c --dynlibOverride:lua --passL:liblua.lib program.nim - - + + +Backend language options +======================== + +The typical compiler usage involves using the ``compile`` or ``c`` command to +transform a ``.nim`` file into one or more ``.c`` files which are then +compiled with the platform's C compiler into a static binary. However there +are other commands to compile to C++, Objective-C or Javascript. More details +can be read in the `Nimrod Backend Integration document <backends.html>`_. + + Nimrod documentation tools ========================== @@ -556,7 +581,7 @@ for further information. Nimrod interactive mode ======================= -The Nimrod compiler supports an `interactive mode`:idx:. This is also known as +The Nimrod compiler supports an interactive mode. This is also known as a `REPL`:idx: (*read eval print loop*). If Nimrod has been built with the ``-d:useGnuReadline`` switch, it uses the GNU readline library for terminal input management. To start Nimrod in interactive mode use the command @@ -681,35 +706,3 @@ efficient: else: quit(errorStr(p, "expected: console or gui")) of "license": c.license = UnixToNativePath(k.value) else: quit(errorStr(p, "unknown variable: " & k.key)) - - -The JavaScript target -===================== - -Nimrod can also generate `JavaScript`:idx: code. However, the -JavaScript code generator is experimental! - -Nimrod targets JavaScript 1.5 which is supported by any widely used browser. -Since JavaScript does not have a portable means to include another module, -Nimrod just generates a long ``.js`` file. - -Features or modules that the JavaScript platform does not support are not -available. This includes: - -* manual memory management (``alloc``, etc.) -* casting and other unsafe operations (``cast`` operator, ``zeroMem``, etc.) -* file management -* most modules of the Standard library -* proper 64 bit integer arithmetic -* unsigned integer arithmetic - -However, the modules `strutils`:idx:, `math`:idx:, and `times`:idx: are -available! To access the DOM, use the `dom`:idx: module that is only -available for the JavaScript platform. - -To compile a Nimrod module into a ``.js`` file use the ``js`` command; the -default is a ``.js`` file that is supposed to be referenced in an ``.html`` -file. However, you can also run the code with `nodejs`:idx:\: - - nimrod js -d:nodejs -r examples/hallo.nim - diff --git a/doc/spawn.txt b/doc/spawn.txt new file mode 100644 index 000000000..ed500f3a5 --- /dev/null +++ b/doc/spawn.txt @@ -0,0 +1,98 @@ +========================================================== + Parallel & Spawn +========================================================== + +Nimrod has two flavors of parallelism: +1) `Structured`:idx parallelism via the ``parallel`` statement. +2) `Unstructured`:idx: parallelism via the standalone ``spawn`` statement. + +Both need the `threadpool <threadpool.html>`_ module to work. + +Somewhat confusingly, ``spawn`` is also used in the ``parallel`` statement +with slightly different semantics. ``spawn`` always takes a call expression of +the form ``f(a, ...)``. Let ``T`` be ``f``'s return type. If ``T`` is ``void`` +then ``spawn``'s return type is also ``void``. Within a ``parallel`` section +``spawn``'s return type is ``T``, otherwise it is ``FlowVar[T]``. + +The compiler can ensure the location in ``location = spawn f(...)`` is not +read prematurely within a ``parallel`` section and so there is no need for +the overhead of an indirection via ``FlowVar[T]`` to ensure correctness. + + +Parallel statement +================== + +Example: + +.. code-block:: nimrod + # Compute PI in an inefficient way + import strutils, math, threadpool + + proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1) + + proc pi(n: int): float = + var ch = newSeq[float](n+1) + parallel: + for k in 0..ch.high: + ch[k] = spawn term(float(k)) + for k in 0..ch.high: + result += ch[k] + + echo formatFloat(pi(5000)) + + +The parallel statement is the preferred mechanism to introduce parallelism +in a Nimrod program. A subset of the Nimrod language is valid within a +``parallel`` section. This subset is checked to be free of data races at +compile time. A sophisticated `disjoint checker`:idx: ensures that no data +races are possible even though shared memory is extensively supported! + +The subset is in fact the full language with the following +restrictions / changes: + +* ``spawn`` within a ``parallel`` section has special semantics. +* Every location of the form ``a[i]`` and ``a[i..j]`` and ``dest`` where + ``dest`` is part of the pattern ``dest = spawn f(...)`` has to be + provable disjoint. This is called the *disjoint check*. +* Every other complex location ``loc`` that is used in a spawned + proc (``spawn f(loc)``) has to be immutable for the duration of + the ``parallel`` section. This is called the *immutability check*. Currently + it is not specified what exactly "complex location" means. We need to make + this an optimization! +* Every array access has to be provable within bounds. This is called + the *bounds check*. +* Slices are optimized so that no copy is performed. This optimization is not + yet performed for ordinary slices outside of a ``parallel`` section. Slices + are also special in that they currently do not support negative indexes! + + + + +Spawn statement +=============== + +A standalone ``spawn`` statement is a simple construct. It executes +the passed expression on the thread pool and returns a `data flow variable`:idx: +``FlowVar[T]`` that can be read from. The reading with the ``^`` operator is +**blocking**. However, one can use ``awaitAny`` to wait on multiple flow +variables at the same time: + +.. code-block:: nimrod + import threadpool, ... + + # wait until 2 out of 3 servers received the update: + proc main = + var responses = newSeq[RawFlowVar](3) + for i in 0..2: + responses[i] = spawn tellServer(Update, "key", "value") + var index = awaitAny(responses) + assert index >= 0 + responses.del(index) + discard awaitAny(responses) + +Like the ``parallel`` statement data flow variables ensure that no data races +are possible. Due to technical limitations not every type ``T`` is possible in +a data flow variable: ``T`` has to be of the type ``ref``, ``string``, ``seq`` +or of a type that doesn't contain a type that is garbage collected. This +restriction will be removed in the future. + diff --git a/doc/subexes.txt b/doc/subexes.txt index 10e0f4cc1..3b688fd0a 100644 --- a/doc/subexes.txt +++ b/doc/subexes.txt @@ -1,4 +1,3 @@ -================================ Substitution Expressions (subex) ================================ diff --git a/doc/tools.txt b/doc/tools.txt index ae739e778..0127bc4a8 100644 --- a/doc/tools.txt +++ b/doc/tools.txt @@ -1,6 +1,6 @@ -===== -Tools -===== +=========================== +Tools available with Nimrod +=========================== The standard distribution ships with the following tools: diff --git a/doc/trmacros.txt b/doc/trmacros.txt deleted file mode 100644 index d5ad74e6e..000000000 --- a/doc/trmacros.txt +++ /dev/null @@ -1,275 +0,0 @@ -========================================================= - Term rewriting macros for Nimrod -========================================================= - -:Author: Andreas Rumpf - -Term rewriting macros are macros or templates that have not only a *name* but -also a *pattern* that is searched for after the semantic checking phase of -the compiler: This means they provide an easy way to enhance the compilation -pipeline with user defined optimizations: - -.. code-block:: nimrod - template optMul{`*`(a, 2)}(a: int): int = a+a - - let x = 3 - echo x * 2 - -The compiler now rewrites ``x * 2`` as ``x + x``. The code inside the -curlies is the pattern to match against. The operators ``*``, ``**``, -``|``, ``~`` have a special meaning in patterns if they are written in infix -notation, so to match verbatim against ``*`` the ordinary function call syntax -needs to be used. - - -Unfortunately optimizations are hard to get right and even the tiny example -is **wrong**: - -.. code-block:: nimrod - template optMul{`*`(a, 2)}(a: int): int = a+a - - proc f(): int = - echo "side effect!" - result = 55 - - echo f() * 2 - -We cannot duplicate 'a' if it denotes an expression that has a side effect! -Fortunately Nimrod supports side effect analysis: - -.. code-block:: nimrod - template optMul{`*`(a, 2)}(a: int{noSideEffect}): int = a+a - - proc f(): int = - echo "side effect!" - result = 55 - - echo f() * 2 # not optimized ;-) - -So what about ``2 * a``? We should tell the compiler ``*`` is commutative. We -cannot really do that however as the following code only swaps arguments -blindly: - -.. code-block:: nimrod - template mulIsCommutative{`*`(a, b)}(a, b: int): int = b*a - -What optimizers really need to do is a *canonicalization*: - -.. code-block:: nimrod - template canonMul{`*`(a, b)}(a: int{lit}, b: int): int = b*a - -The ``int{lit}`` parameter pattern matches against an expression of -type ``int``, but only if it's a literal. - - - -Parameter constraints -===================== - -The parameter constraint expression can use the operators ``|`` (or), -``&`` (and) and ``~`` (not) and the following predicates: - -=================== ===================================================== -Predicate Meaning -=================== ===================================================== -``atom`` The matching node has no children. -``lit`` The matching node is a literal like "abc", 12. -``sym`` The matching node must be a symbol (a bound - identifier). -``ident`` The matching node must be an identifier (an unbound - identifier). -``call`` The matching AST must be a call/apply expression. -``lvalue`` The matching AST must be an lvalue. -``sideeffect`` The matching AST must have a side effect. -``nosideeffect`` The matching AST must have no side effect. -``param`` A symbol which is a parameter. -``genericparam`` A symbol which is a generic parameter. -``module`` A symbol which is a module. -``type`` A symbol which is a type. -``var`` A symbol which is a variable. -``let`` A symbol which is a ``let`` variable. -``const`` A symbol which is a constant. -``result`` The special ``result`` variable. -``proc`` A symbol which is a proc. -``method`` A symbol which is a method. -``iterator`` A symbol which is an iterator. -``converter`` A symbol which is a converter. -``macro`` A symbol which is a macro. -``template`` A symbol which is a template. -``field`` A symbol which is a field in a tuple or an object. -``enumfield`` A symbol which is a field in an enumeration. -``forvar`` A for loop variable. -``label`` A label (used in ``block`` statements). -``nk*`` The matching AST must have the specified kind. - (Example: ``nkIfStmt`` denotes an ``if`` statement.) -``alias`` States that the marked parameter needs to alias - with *some* other parameter. -``noalias`` States that *every* other parameter must not alias - with the marked parameter. -=================== ===================================================== - -The ``alias`` and ``noalias`` predicates refer not only to the matching AST, -but also to every other bound parameter; syntactially they need to occur after -the ordinary AST predicates: - -.. code-block:: nimrod - template ex{a = b + c}(a: int{noalias}, b, c: int) = - # this transformation is only valid if 'b' and 'c' do not alias 'a': - a = b - inc a, b - - -Pattern operators -================= - -The operators ``*``, ``**``, ``|``, ``~`` have a special meaning in patterns -if they are written in infix notation. - - -The ``|`` operator ------------------- - -The ``|`` operator if used as infix operator creates an ordered choice: - -.. code-block:: nimrod - template t{0|1}(): expr = 3 - let a = 1 - # outputs 3: - echo a - -The matching is performed after the compiler performed some optimizations like -constant folding, so the following does not work: - -.. code-block:: nimrod - template t{0|1}(): expr = 3 - # outputs 1: - echo 1 - -The reason is that the compiler already transformed the 1 into "1" for -the ``echo`` statement. However, a term rewriting macro should not change the -semantics anyway. In fact they can be deactived with the ``--patterns:off`` -command line option or temporarily with the ``patterns`` pragma. - - -The ``{}`` operator -------------------- - -A pattern expression can be bound to a pattern parameter via the ``expr{param}`` -notation: - -.. code-block:: nimrod - template t{(0|1|2){x}}(x: expr): expr = x+1 - let a = 1 - # outputs 2: - echo a - - -The ``~`` operator ------------------- - -The ``~`` operator is the **not** operator in patterns: - -.. code-block:: nimrod - template t{x = (~x){y} and (~x){z}}(x, y, z: bool): stmt = - x = y - if x: x = z - - var - a = false - b = true - c = false - a = b and c - echo a - - -The ``*`` operator ------------------- - -The ``*`` operator can *flatten* a nested binary expression like ``a & b & c`` -to ``&(a, b, c)``: - -.. code-block:: nimrod - var - calls = 0 - - proc `&&`(s: varargs[string]): string = - result = s[0] - for i in 1..len(s)-1: result.add s[i] - inc calls - - template optConc{ `&&` * a }(a: string): expr = &&a - - let space = " " - echo "my" && (space & "awe" && "some " ) && "concat" - - # check that it's been optimized properly: - doAssert calls == 1 - - -The second operator of `*` must be a parameter; it is used to gather all the -arguments. The expression ``"my" && (space & "awe" && "some " ) && "concat"`` -is passed to ``optConc`` in ``a`` as a special list (of kind ``nkArgList``) -which is flattened into a call expression; thus the invocation of ``optConc`` -produces: - -.. code-block:: nimrod - `&&`("my", space & "awe", "some ", "concat") - - -The ``**`` operator -------------------- - -The ``**`` is much like the ``*`` operator, except that it gathers not only -all the arguments, but also the matched operators in reverse polish notation: - -.. code-block:: nimrod - import macros - - type - TMatrix = object - dummy: int - - proc `*`(a, b: TMatrix): TMatrix = nil - proc `+`(a, b: TMatrix): TMatrix = nil - proc `-`(a, b: TMatrix): TMatrix = nil - proc `$`(a: TMatrix): string = result = $a.dummy - proc mat21(): TMatrix = - result.dummy = 21 - - macro optM{ (`+`|`-`|`*`) ** a }(a: TMatrix): expr = - echo treeRepr(a) - result = newCall(bindSym"mat21") - - var x, y, z: TMatrix - - echo x + y * z - x - -This passes the expression ``x + y * z - x`` to the ``optM`` macro as -an ``nnkArgList`` node containing:: - - Arglist - Sym "x" - Sym "y" - Sym "z" - Sym "*" - Sym "+" - Sym "x" - Sym "-" - -(Which is the reverse polish notation of ``x + y * z - x``.) - - -Parameters -========== - -Parameters in a pattern are type checked in the matching process. If a -parameter is of the type ``varargs`` it is treated specially and it can match -0 or more arguments in the AST to be matched against: - -.. code-block:: nimrod - template optWrite{ - write(f, x) - ((write|writeln){w})(f, y) - }(x, y: varargs[expr], f: TFile, w: expr) = - w(f, x, y) - diff --git a/doc/tut1.txt b/doc/tut1.txt index 46eda7ae3..a2aa835ee 100644 --- a/doc/tut1.txt +++ b/doc/tut1.txt @@ -1,4 +1,4 @@ -======================== +======================== Nimrod Tutorial (Part I) ======================== @@ -110,7 +110,7 @@ useful for embedding HTML code templates for example. Comments -------- -`Comments`:idx: start anywhere outside a string or character literal with the +Comments start anywhere outside a string or character literal with the hash character ``#``. Documentation comments start with ``##``. Multiline comments need to be aligned at the same column: @@ -224,7 +224,7 @@ different values! For safety use only constant values. Constants ========= -`Constants`:idx: are symbols which are bound to a value. The constant's value +Constants are symbols which are bound to a value. The constant's value cannot change. The compiler must be able to evaluate the expression in a constant declaration at compile time: @@ -369,7 +369,7 @@ he types in nothing (only presses RETURN). For statement ------------- -The `for`:idx: statement is a construct to loop over any element an *iterator* +The ``for`` statement is a construct to loop over any element an *iterator* provides. The example uses the built-in ``countup`` iterator: .. code-block:: nimrod @@ -481,7 +481,7 @@ Example: else: echo("unknown operating system") -The `when`:idx: statement is almost identical to the ``if`` statement with some +The ``when`` statement is almost identical to the ``if`` statement with some differences: * Each condition has to be a constant expression since it is evaluated by the @@ -791,7 +791,7 @@ However, this cannot be done for mutually recursive procedures: Here ``odd`` depends on ``even`` and vice versa. Thus ``even`` needs to be introduced to the compiler before it is completely defined. The syntax for -such a `forward declaration`:idx: is simple: just omit the ``=`` and the +such a forward declaration is simple: just omit the ``=`` and the procedure's body. Later versions of the language may get rid of the need for forward @@ -863,7 +863,7 @@ that are available for them in detail. Booleans -------- -The `boolean`:idx: type is named ``bool`` in Nimrod and consists of the two +The boolean type is named ``bool`` in Nimrod and consists of the two pre-defined values ``true`` and ``false``. Conditions in while, if, elif, when statements need to be of type bool. @@ -1030,7 +1030,7 @@ Enumeration and object types cannot be defined on the fly, but only within a Enumerations ------------ -A variable of an `enumeration`:idx: type can only be assigned a value of a +A variable of an enumeration type can only be assigned a value of a limited set. This set consists of ordered symbols. Each symbol is mapped to an integer value internally. The first symbol is represented at runtime by 0, the second by 1 and so on. Example: @@ -1069,7 +1069,7 @@ An explicit ordered enum can have *holes*: Ordinal types ------------- Enumerations without holes, integer types, ``char`` and ``bool`` (and -subranges) are called `ordinal`:idx: types. Ordinal types have quite +subranges) are called ordinal types. Ordinal types have quite a few special operations: ----------------- -------------------------------------------------------- @@ -1094,7 +1094,7 @@ checks turned on.) Subranges --------- -A `subrange`:idx: type is a range of values from an integer or enumeration type +A subrange type is a range of values from an integer or enumeration type (the base type). Example: .. code-block:: nimrod @@ -1117,7 +1117,7 @@ avoid this common programming error. Sets ---- -The `set type`:idx: models the mathematical notion of a set. The set's +The set type models the mathematical notion of a set. The set's basetype can only be an ordinal type. The reason is that sets are implemented as high performance bit vectors. @@ -1161,7 +1161,7 @@ constants that should be ``or``'ed together. Arrays ------ -An `array`:idx: is a simple fixed length container. Each element in +An array is a simple fixed length container. Each element in the array has the same type. The array's index type can be any ordinal type. Arrays can be constructed via ``[]``: @@ -1253,7 +1253,7 @@ to specify a range from zero to the specified index minus one: Sequences --------- -`Sequences`:idx: are similar to arrays but of dynamic length which may change +Sequences are similar to arrays but of dynamic length which may change during runtime (like strings). Since sequences are resizable they are always allocated on the heap and garbage collected. @@ -1385,8 +1385,8 @@ Tuples A tuple type defines various named *fields* and an *order* of the fields. The constructor ``()`` can be used to construct tuples. The order of the fields in the constructor must match the order in the tuple's definition. -Different tuple-types are *equivalent* if they specify the same fields of -the same type in the same order. +Different tuple-types are *equivalent* if they specify fields of +the same type and of the same name in the same order. The assignment operator for tuples copies each component. The notation ``t.field`` is used to access a tuple's field. Another notation is @@ -1471,7 +1471,7 @@ won't compile: Reference and pointer types --------------------------- -References (similar to `pointers`:idx: in other programming languages) are a +References (similar to pointers in other programming languages) are a way to introduce many-to-one relationships. This means different references can point to and modify the same location in memory. @@ -1513,7 +1513,7 @@ If a reference points to *nothing*, it has the value ``nil``. Procedural type --------------- -A `procedural type`:idx: is a (somewhat abstract) pointer to a procedure. +A procedural type is a (somewhat abstract) pointer to a procedure. ``nil`` is an allowed value for a variable of a procedural type. Nimrod uses procedural types to achieve `functional`:idx: programming techniques. @@ -1521,17 +1521,13 @@ techniques. Example: .. code-block:: nimrod + proc echoItem(x: int) = echo(x) - type - TCallback = proc (x: int) - - proc echoItem(x: Int) = echo(x) - - proc forEach(callback: TCallback) = + proc forEach(action: proc (x: int)) = const data = [2, 3, 5, 7, 11] for d in items(data): - callback(d) + action(d) forEach(echoItem) @@ -1543,7 +1539,7 @@ listed in the `manual <manual.html>`_. Modules ======= -Nimrod supports splitting a program into pieces with a `module`:idx: concept. +Nimrod supports splitting a program into pieces with a module concept. Each module is in its own file. Modules enable `information hiding`:idx: and `separate compilation`:idx:. A module may gain access to symbols of another module by the `import`:idx: statement. Only top-level symbols that are marked @@ -1698,7 +1694,7 @@ define a shorter alias to use when qualifying symbols. Include statement ----------------- -The `include`:idx: statement does something fundamentally different than +The ``include`` statement does something fundamentally different than importing a module: it merely includes the contents of a file. The ``include`` statement is useful to split up a large module into several files: diff --git a/doc/tut2.txt b/doc/tut2.txt index ea6733c07..1e23618e0 100644 --- a/doc/tut2.txt +++ b/doc/tut2.txt @@ -135,7 +135,7 @@ The ``EInvalidObjectConversion`` exception is raised if ``x`` is not a Object variants --------------- Often an object hierarchy is overkill in certain situations where simple -`variant`:idx: types are needed. +variant types are needed. An example: @@ -182,7 +182,7 @@ bound to a class. This has disadvantages: ``join`` a string method or an array method? Nimrod avoids these problems by not assigning methods to a class. All methods -in Nimrod are `multi-methods`:idx:. As we will see later, multi-methods are +in Nimrod are multi-methods. As we will see later, multi-methods are distinguished from procs only for dynamic binding purposes. @@ -194,7 +194,7 @@ The syntax ``obj.method(args)`` can be used instead of ``method(obj, args)``. If there are no remaining arguments, the parentheses can be omitted: ``obj.len`` (instead of ``len(obj)``). -This `method call syntax`:idx: is not restricted to objects, it can be used +This method call syntax is not restricted to objects, it can be used for any type: .. code-block:: nimrod @@ -343,7 +343,7 @@ evaluation or dead code elimination do not work with methods. Exceptions ========== -In Nimrod `exceptions`:idx: are objects. By convention, exception types are +In Nimrod exceptions are objects. By convention, exception types are prefixed with an 'E', not 'T'. The `system <system.html>`_ module defines an exception hierarchy that you might want to stick to. Exceptions derive from E_Base, which provides the common interface. @@ -380,7 +380,7 @@ the template ``newException`` in the ``system`` module can be used: Try statement ------------- -The `try`:idx: statement handles exceptions: +The ``try`` statement handles exceptions: .. code-block:: nimrod # read the first two lines of a text file that should contain numbers @@ -501,7 +501,7 @@ with the file and line where the uncaught exception is being raised, which may help you locate the offending code which has changed. If you want to add the ``{.raises.}`` pragma to existing code, the compiler can -also help you. You can add the ``{.effect.}`` pragma statement to your proc and +also help you. You can add the ``{.effects.}`` pragma statement to your proc and the compiler will output all inferred effects up to that point (exception tracking is part of Nimrod's effect system). Another more roundabout way to find out the list of exceptions raised by a proc is to use the Nimrod ``doc2`` @@ -513,7 +513,7 @@ procs with the list of raised exceptions. You can read more about Nimrod's Generics ======== -`Generics`:idx: are Nimrod's means to parametrize procs, iterators or types +Generics are Nimrod's means to parametrize procs, iterators or types with `type parameters`:idx:. They are most useful for efficient type safe containers: @@ -714,9 +714,9 @@ know how the Nimrod concrete syntax is converted to an abstract syntax tree (AST). The AST is documented in the `macros <macros.html>`_ module. Once your macro is finished, there are two ways to invoke it: -(1) invoking a macro like a procedure call (`expression macros`:idx:) +(1) invoking a macro like a procedure call (expression macros) (2) invoking a macro with the special ``macrostmt`` - syntax (`statement macros`:idx:) + syntax (statement macros) Expression Macros diff --git a/examples/cross_calculator/.gitignore b/examples/cross_calculator/.gitignore new file mode 100644 index 000000000..e521bf338 --- /dev/null +++ b/examples/cross_calculator/.gitignore @@ -0,0 +1,12 @@ +# Android specific absolute paths. +android/bin/ +android/gen/ +android/jni/backend-jni.h +android/libs/ +android/local.properties +android/obj/ +android/tags +# iOS specific absolute paths +ios/resources/ui/*.m +ios/tags + diff --git a/examples/cross_calculator/android/scripts/jnibuild.sh b/examples/cross_calculator/android/scripts/jnibuild.sh index 8b61f20f7..8b61f20f7 100755..100644 --- a/examples/cross_calculator/android/scripts/jnibuild.sh +++ b/examples/cross_calculator/android/scripts/jnibuild.sh diff --git a/examples/cross_calculator/android/scripts/nimbuild.sh b/examples/cross_calculator/android/scripts/nimbuild.sh index 97130b8dd..97130b8dd 100755..100644 --- a/examples/cross_calculator/android/scripts/nimbuild.sh +++ b/examples/cross_calculator/android/scripts/nimbuild.sh diff --git a/examples/cross_calculator/android/scripts/tags.sh b/examples/cross_calculator/android/scripts/tags.sh index 95507064f..95507064f 100755..100644 --- a/examples/cross_calculator/android/scripts/tags.sh +++ b/examples/cross_calculator/android/scripts/tags.sh diff --git a/examples/cross_calculator/ios/scripts/tags.sh b/examples/cross_calculator/ios/scripts/tags.sh index 111e7a1c0..111e7a1c0 100755..100644 --- a/examples/cross_calculator/ios/scripts/tags.sh +++ b/examples/cross_calculator/ios/scripts/tags.sh diff --git a/examples/cross_calculator/ios/scripts/xcode_prebuild.sh b/examples/cross_calculator/ios/scripts/xcode_prebuild.sh index c6d38f164..c6d38f164 100755..100644 --- a/examples/cross_calculator/ios/scripts/xcode_prebuild.sh +++ b/examples/cross_calculator/ios/scripts/xcode_prebuild.sh diff --git a/koch.nim b/koch.nim index 9d59344f2..15ee3732d 100644 --- a/koch.nim +++ b/koch.nim @@ -6,6 +6,8 @@ # See the file "copying.txt", included in this # distribution, for details about the copyright. # +# See doc/koch.txt for documentation. +# when defined(gcc) and defined(windows): when defined(x86): @@ -152,7 +154,7 @@ proc boot(args: string) = copyExe(findStartNimrod(), 0.thVersion) for i in 0..2: echo "iteration: ", i+1 - exec i.thVersion & " cc $# $# compiler" / "nimrod.nim" % [bootOptions, args] + exec i.thVersion & " c $# $# compiler" / "nimrod.nim" % [bootOptions, args] if sameFileContent(output, i.thVersion): copyExe(output, finalDest) echo "executables are equal: SUCCESS!" @@ -167,7 +169,7 @@ const cleanExt = [ ".ppu", ".o", ".obj", ".dcu", ".~pas", ".~inc", ".~dsk", ".~dpr", ".map", ".tds", ".err", ".bak", ".pyc", ".exe", ".rod", ".pdb", ".idb", - ".idx" + ".idx", ".ilk" ] ignore = [ ".bzrignore", "nimrod", "nimrod.exe", "koch", "koch.exe", ".gitignore" @@ -299,7 +301,7 @@ of cmdArgument: of "boot": boot(op.cmdLineRest) of "clean": clean(op.cmdLineRest) of "web": web(op.cmdLineRest) - of "csource": csource(op.cmdLineRest) + of "csource", "csources": csource(op.cmdLineRest) of "zip": zip(op.cmdLineRest) of "inno": inno(op.cmdLineRest) of "install": install(op.cmdLineRest) diff --git a/lib/impure/db_mysql.nim b/lib/impure/db_mysql.nim index 32cda3e4d..eec4daf00 100644 --- a/lib/impure/db_mysql.nim +++ b/lib/impure/db_mysql.nim @@ -24,6 +24,15 @@ type FReadDb* = object of FDb ## effect that denotes a read operation FWriteDb* = object of FDb ## effect that denotes a write operation +proc sql*(query: string): TSqlQuery {.noSideEffect, inline.} = + ## constructs a TSqlQuery from the string `query`. This is supposed to be + ## used as a raw-string-literal modifier: + ## ``sql"update user set counter = counter + 1"`` + ## + ## If assertions are turned off, it does nothing. If assertions are turned + ## on, later versions will check the string for valid syntax. + result = TSqlQuery(query) + proc dbError(db: TDbConn) {.noreturn.} = ## raises an EDb exception. var e: ref EDb diff --git a/lib/js/dom.nim b/lib/js/dom.nim index d90067176..951d8e835 100644 --- a/lib/js/dom.nim +++ b/lib/js/dom.nim @@ -7,7 +7,8 @@ # distribution, for details about the copyright. # -## Declaration of the Document Object Model for the JavaScript backend. +## Declaration of the Document Object Model for the `JavaScript backend +## <backends.html#the-javascript-target>`_. when not defined(js) and not defined(Nimdoc): {.error: "This module only works on the JavaScript platform".} diff --git a/lib/packages/docutils/rstgen.nim b/lib/packages/docutils/rstgen.nim index cead17f2b..fdbca4ca8 100644 --- a/lib/packages/docutils/rstgen.nim +++ b/lib/packages/docutils/rstgen.nim @@ -23,7 +23,8 @@ ## many options and tweaking, but you are not limited to snippets and can ## generate `LaTeX documents <https://en.wikipedia.org/wiki/LaTeX>`_ too. -import strutils, os, hashes, strtabs, rstast, rst, highlite +import strutils, os, hashes, strtabs, rstast, rst, highlite, tables, sequtils, + algorithm const HtmlExt = "html" @@ -56,6 +57,9 @@ type currentSection: string ## \ ## Stores the empty string or the last headline/overline found in the rst ## document, so it can be used as a prettier name for term index generation. + seenIndexTerms: TTable[string, int] ## \ + ## Keeps count of same text index terms to generate different identifiers + ## for hyperlinks. See renderIndexTerm proc for details. PDoc = var TRstGenerator ## Alias to type less. @@ -68,10 +72,16 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, ## ## You need to call this before using a ``TRstGenerator`` with any other ## procs in this module. Pass a non ``nil`` ``PStringTable`` value as - ## ``config`` with parameters used by the HTML output generator. If you - ## don't know what to use, pass the results of the ``defaultConfig()`` proc. - ## The ``filename`` is symbolic and used only for error reporting, you can - ## pass any non ``nil`` string here. + ## `config` with parameters used by the HTML output generator. If you don't + ## know what to use, pass the results of the `defaultConfig() + ## <#defaultConfig>_` proc. + ## + ## The `filename` parameter will be used for error reporting and creating + ## index hyperlinks to the file, but you can pass an empty string here if you + ## are parsing a stream in memory. If `filename` ends with the ``.nim`` + ## extension, the title for the document will be set by default to ``Module + ## filename``. This default title can be overriden by the embedded rst, but + ## it helps to prettify the generated index if no title is found. ## ## The ``TRstParseOptions``, ``TFindFileHandler`` and ``TMsgHandler`` types ## are defined in the the `packages/docutils/rst module <rst.html>`_. @@ -111,6 +121,10 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, g.options = options g.findFile = findFile g.currentSection = "" + let fileParts = filename.splitFile + if fileParts.ext == ".nim": + g.currentSection = "Module " & fileParts.name + g.seenIndexTerms = initTable[string, int]() g.msgHandler = msgHandler let s = config["split.item.toc"] @@ -120,8 +134,8 @@ proc initRstGenerator*(g: var TRstGenerator, target: TOutputTarget, proc writeIndexFile*(g: var TRstGenerator, outfile: string) = ## Writes the current index buffer to the specified output file. ## - ## You previously need to add entries to the index with the ``setIndexTerm`` - ## proc. If the index is empty the file won't be created. + ## You previously need to add entries to the index with the `setIndexTerm() + ## <#setIndexTerm>`_ proc. If the index is empty the file won't be created. if g.theIndex.len > 0: writeFile(outfile, g.theIndex) proc addXmlChar(dest: var string, c: char) = @@ -207,6 +221,9 @@ proc dispA(target: TOutputTarget, dest: var string, if target != outLatex: addf(dest, xml, args) else: addf(dest, tex, args) +proc `or`(x, y: string): string {.inline.} = + result = if x.isNil: y else: x + proc renderRstToOut*(d: var TRstGenerator, n: PRstNode, result: var string) ## Writes into ``result`` the rst ast ``n`` using the ``d`` configuration. ## @@ -224,7 +241,7 @@ proc renderRstToOut*(d: var TRstGenerator, n: PRstNode, result: var string) proc renderAux(d: PDoc, n: PRstNode, result: var string) = for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], result) -proc renderAux(d: PDoc, n: PRstNode, frmtA, frmtB: string, result: var string) = +proc renderAux(d: PDoc, n: PRstNode, frmtA, frmtB: string, result: var string) = var tmp = "" for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], tmp) if d.target != outLatex: @@ -254,25 +271,45 @@ proc setIndexTerm*(d: var TRstGenerator, id, term: string, linkTitle, linkDesc = "") = ## Adds a `term` to the index using the specified hyperlink identifier. ## - ## The ``d.theIndex`` string will be used to append the term in the format - ## ``term<tab>file#id``. The anchor will be the based on the name of the file - ## currently being parsed plus the `id`, which will be appended after a hash. + ## A new entry will be added to the index using the format + ## ``term<tab>file#id``. The file part will come from the `filename` + ## parameter used in a previous call to the `initRstGenerator() + ## <#initRstGenerator>`_ proc. + ## + ## The `id` will be appended with a hash character only if its length is not + ## zero, otherwise no specific anchor will be generated. In general you + ## should only pass an empty `id` value for the title of standalone rst + ## documents (they are special for the `mergeIndexes() <#mergeIndexes>`_ + ## proc, see `Index (idx) file format <docgen.html#index-idx-file-format>`_ + ## for more information). Unlike other index terms, title entries are + ## inserted at the beginning of the accumulated buffer to maintain a logical + ## order of entries. + ## ## If `linkTitle` or `linkDesc` are not the empty string, two additional ## columns with their contents will be added. ## - ## The index won't be written to disk unless you call ``writeIndexFile``. The - ## purpose of the index is documented in the `docgen tools guide - ## <docgen.html#index-switch>`_. - d.theIndex.add(term) - d.theIndex.add('\t') + ## The index won't be written to disk unless you call `writeIndexFile() + ## <#writeIndexFile>`_. The purpose of the index is documented in the `docgen + ## tools guide <docgen.html#index-switch>`_. + assert(not d.theIndex.isNil) + var + entry = term + isTitle = false + entry.add('\t') let htmlFile = changeFileExt(extractFilename(d.filename), HtmlExt) - d.theIndex.add(htmlFile) - d.theIndex.add('#') - d.theIndex.add(id) + entry.add(htmlFile) + if id.len > 0: + entry.add('#') + entry.add(id) + else: + isTitle = true if linkTitle.len > 0 or linkDesc.len > 0: - d.theIndex.add('\t' & linkTitle.quoteIndexColumn) - d.theIndex.add('\t' & linkDesc.quoteIndexColumn) - d.theIndex.add("\n") + entry.add('\t' & linkTitle.quoteIndexColumn) + entry.add('\t' & linkDesc.quoteIndexColumn) + entry.add("\n") + + if isTitle: d.theIndex.insert(entry) + else: d.theIndex.add(entry) proc hash(n: PRstNode): int = if n.kind == rnLeaf: @@ -283,8 +320,20 @@ proc hash(n: PRstNode): int = result = result !& hash(n.sons[i]) result = !$result -proc renderIndexTerm(d: PDoc, n: PRstNode, result: var string) = - let id = rstnodeToRefname(n) & '_' & $abs(hash(n)) +proc renderIndexTerm*(d: PDoc, n: PRstNode, result: var string) = + ## Renders the string decorated within \`foobar\`\:idx\: markers. + ## + ## Additionally adds the encosed text to the index as a term. Since we are + ## interested in different instances of the same term to have different + ## entries, a table is used to keep track of the amount of times a term has + ## previously appeared to give a different identifier value for each. + let refname = n.rstnodeToRefname + if d.seenIndexTerms.hasKey(refname): + d.seenIndexTerms[refname] = d.seenIndexTerms[refname] + 1 + else: + d.seenIndexTerms[refname] = 1 + let id = refname & '_' & $d.seenIndexTerms[refname] + var term = "" renderAux(d, n, term) setIndexTerm(d, id, term, d.currentSection) @@ -298,12 +347,34 @@ type linkTitle: string ## If not nil, contains a prettier text for the href linkDesc: string ## If not nil, the title attribute of the final href + TIndexedDocs {.pure, final.} = TTable[TIndexEntry, seq[TIndexEntry]] ## \ + ## Contains the index sequences for doc types. + ## + ## The key is a *fake* TIndexEntry which will contain the title of the + ## document in the `keyword` field and `link` will contain the html + ## filename for the document. `linkTitle` and `linkDesc` will be nil. + ## + ## The value indexed by this TIndexEntry is a sequence with the real index + ## entries found in the ``.idx`` file. + + proc cmp(a, b: TIndexEntry): int = ## Sorts two ``TIndexEntry`` first by `keyword` field, then by `link`. result = cmpIgnoreStyle(a.keyword, b.keyword) if result == 0: result = cmpIgnoreStyle(a.link, b.link) +proc hash(x: TIndexEntry): THash = + ## Returns the hash for the combined fields of the type. + ## + ## The hash is computed as the chained hash of the individual string hashes. + assert(not x.keyword.isNil) + assert(not x.link.isNil) + result = x.keyword.hash !& x.link.hash + result = result !& (x.linkTitle or "").hash + result = result !& (x.linkDesc or "").hash + result = !$result + proc `<-`(a: var TIndexEntry, b: TIndexEntry) = shallowCopy a.keyword, b.keyword shallowCopy a.link, b.link @@ -332,43 +403,18 @@ proc sortIndex(a: var openArray[TIndexEntry]) = a[j] <- v if h == 1: break -proc mergeIndexes*(dir: string): string = - ## merges all index files in `dir` and returns the generated index as HTML. - ## The result is no full HTML for flexibility. - var a: seq[TIndexEntry] - newSeq(a, 15_000) - setLen(a, 0) - var L = 0 - for kind, path in walkDir(dir): - if kind == pcFile and path.endsWith(IndexExt): - for line in lines(path): - let s = line.find('\t') - if s < 0: continue - setLen(a, L+1) - a[L].keyword = line.substr(0, s-1) - a[L].link = line.substr(s+1) - if a[L].link.find('\t') > 0: - let extraCols = a[L].link.split('\t') - a[L].link = extraCols[0] - assert extraCols.len == 3 - a[L].linkTitle = extraCols[1].unquoteIndexColumn - a[L].linkDesc = extraCols[2].unquoteIndexColumn - else: - a[L].linkTitle = nil - a[L].linkDesc = nil - inc L - sortIndex(a) +proc generateSymbolIndex(symbols: seq[TIndexEntry]): string = result = "" var i = 0 - while i < L: - result.addf("<dt><span>$1</span></dt><ul class=\"simple\"><dd>\n", - [a[i].keyword]) + while i < symbols.len: + result.addf("<dt><span>$1:</span></dt><ul class=\"simple\"><dd>\n", + [symbols[i].keyword]) var j = i - while j < L and a[i].keyword == a[j].keyword: + while j < symbols.len and symbols[i].keyword == symbols[j].keyword: let - url = a[j].link - text = if not a[j].linkTitle.isNil: a[j].linkTitle else: url - desc = if not a[j].linkDesc.isNil: a[j].linkDesc else: "" + url = symbols[j].link + text = if not symbols[j].linkTitle.isNil: symbols[j].linkTitle else: url + desc = if not symbols[j].linkDesc.isNil: symbols[j].linkDesc else: "" if desc.len > 0: result.addf("""<li><a class="reference external" title="$3" href="$1">$2</a></li> @@ -379,9 +425,246 @@ proc mergeIndexes*(dir: string): string = inc j result.add("</ul></dd>\n") i = j + +proc isDocumentationTitle(hyperlink: string): bool = + ## Returns true if the hyperlink is actually a documentation title. + ## + ## Documentation titles lack the hash. See `mergeIndexes() <#mergeIndexes>`_ + ## for a more detailed explanation. + result = hyperlink.find('#') < 0 + +proc stripTOCLevel(s: string): tuple[level: int, text: string] = + ## Returns the *level* of the toc along with the text without it. + for c in 0 .. <s.len: + result.level = c + if s[c] != ' ': break + result.text = s[result.level .. <s.len] + +proc indentToLevel(level: var int, newLevel: int): string = + ## Returns the sequence of <ul>|</ul> characters to switch to `newLevel`. + ## + ## The amount of lists added/removed will be based on the `level` variable, + ## which will be reset to `newLevel` at the end of the proc. + result = "" + if level == newLevel: + return + if newLevel > level: + result = repeatStr(newLevel - level, "<ul>") + else: + result = repeatStr(level - newLevel, "</ul>") + level = newLevel + +proc generateDocumentationTOC(entries: seq[TIndexEntry]): string = + ## Returns the sequence of index entries in an HTML hierarchical list. + result = "" + # Build a list of levels and extracted titles to make processing easier. + var + titleRef: string + levels: seq[tuple[level: int, text: string]] + L = 0 + level = 1 + levels.newSeq(entries.len) + for entry in entries: + let (rawLevel, rawText) = stripTOCLevel(entry.linkTitle or entry.keyword) + if rawLevel < 1: + # This is a normal symbol, push it *inside* one level from the last one. + levels[L].level = level + 1 + # Also, ignore the linkTitle and use directly the keyword. + levels[L].text = entry.keyword + else: + # The level did change, update the level indicator. + level = rawLevel + levels[L].level = rawLevel + levels[L].text = rawText + inc L + + # Now generate hierarchical lists based on the precalculated levels. + result = "<ul>\n" + level = 1 + L = 0 + while L < entries.len: + let link = entries[L].link + if link.isDocumentationTitle: + titleRef = link + else: + result.add(level.indentToLevel(levels[L].level)) + result.add("<li><a href=\"" & link & "\">" & + levels[L].text & "</a>\n") + inc L + result.add(level.indentToLevel(1) & "</ul>\n") + assert(not titleRef.isNil, + "Can't use this proc on an API index, docs always have a title entry") + +proc generateDocumentationIndex(docs: TIndexedDocs): string = + ## Returns all the documentation TOCs in an HTML hierarchical list. + result = "" + + # Sort the titles to generate their toc in alphabetical order. + var titles = toSeq(keys[TIndexEntry, seq[TIndexEntry]](docs)) + sort(titles, cmp) + + for title in titles: + let tocList = generateDocumentationTOC(docs[title]) + result.add("<ul><li><a href=\"" & + title.link & "\">" & title.keyword & "</a>\n" & tocList & "</ul>\n") + +proc generateDocumentationJumps(docs: TIndexedDocs): string = + ## Returns a plain list of hyperlinks to documentation TOCs in HTML. + result = "Documents: " + + # Sort the titles to generate their toc in alphabetical order. + var titles = toSeq(keys[TIndexEntry, seq[TIndexEntry]](docs)) + sort(titles, cmp) + + var chunks: seq[string] = @[] + for title in titles: + chunks.add("<a href=\"" & title.link & "\">" & title.keyword & "</a>") + + result.add(chunks.join(", ") & ".<br>") + +proc generateModuleJumps(modules: seq[string]): string = + ## Returns a plain list of hyperlinks to the list of modules. + result = "Modules: " + + var chunks: seq[string] = @[] + for name in modules: + chunks.add("<a href=\"" & name & ".html\">" & name & "</a>") + + result.add(chunks.join(", ") & ".<br>") + +proc readIndexDir(dir: string): + tuple[modules: seq[string], symbols: seq[TIndexEntry], docs: TIndexedDocs] = + ## Walks `dir` reading ``.idx`` files converting them in TIndexEntry items. + ## + ## Returns the list of found module names, the list of free symbol entries + ## and the different documentation indexes. The list of modules is sorted. + ## See the documentation of ``mergeIndexes`` for details. + result.modules = @[] + result.docs = initTable[TIndexEntry, seq[TIndexEntry]](32) + newSeq(result.symbols, 15_000) + setLen(result.symbols, 0) + var L = 0 + # Scan index files and build the list of symbols. + for kind, path in walkDir(dir): + if kind == pcFile and path.endsWith(IndexExt): + var + fileEntries: seq[TIndexEntry] + title: TIndexEntry + F = 0 + newSeq(fileEntries, 500) + setLen(fileEntries, 0) + for line in lines(path): + let s = line.find('\t') + if s < 0: continue + setLen(fileEntries, F+1) + fileEntries[F].keyword = line.substr(0, s-1) + fileEntries[F].link = line.substr(s+1) + # See if we detect a title, a link without a `#foobar` trailing part. + if title.keyword.isNil and fileEntries[F].link.isDocumentationTitle: + title.keyword = fileEntries[F].keyword + title.link = fileEntries[F].link + + if fileEntries[F].link.find('\t') > 0: + let extraCols = fileEntries[F].link.split('\t') + fileEntries[F].link = extraCols[0] + assert extraCols.len == 3 + fileEntries[F].linkTitle = extraCols[1].unquoteIndexColumn + fileEntries[F].linkDesc = extraCols[2].unquoteIndexColumn + else: + fileEntries[F].linkTitle = nil + fileEntries[F].linkDesc = nil + inc F + # Depending on type add this to the list of symbols or table of APIs. + if title.keyword.isNil: + for i in 0 .. <F: + # Don't add to symbols TOC entries (they start with a whitespace). + let toc = fileEntries[i].linkTitle + if not toc.isNil and toc.len > 0 and toc[0] == ' ': + continue + # Ok, non TOC entry, add it. + setLen(result.symbols, L + 1) + result.symbols[L] = fileEntries[i] + inc L + result.modules.add(path.splitFile.name) + else: + # Generate the symbolic anchor for index quickjumps. + title.linkTitle = "doc_toc_" & $result.docs.len + result.docs[title] = fileEntries + + sort(result.modules, system.cmp) + +proc mergeIndexes*(dir: string): string = + ## Merges all index files in `dir` and returns the generated index as HTML. + ## + ## This proc will first scan `dir` for index files with the ``.idx`` + ## extension previously created by commands like ``nimrod doc|rst2html`` + ## which use the ``--index:on`` switch. These index files are the result of + ## calls to `setIndexTerm() <#setIndexTerm>`_ and `writeIndexFile() + ## <#writeIndexFile>`_, so they are simple tab separated files. + ## + ## As convention this proc will split index files into two categories: + ## documentation and API. API indices will be all joined together into a + ## single big sorted index, making the bulk of the final index. This is good + ## for API documentation because many symbols are repated in different + ## modules. On the other hand, documentation indices are essentially table of + ## contents plus a few special markers. These documents will be rendered in a + ## separate section which tries to maintain the order and hierarchy of the + ## symbols in the index file. + ## + ## To differentiate between a documentation and API file a convention is + ## used: indices which contain one entry without the HTML hash character (#) + ## will be considered `documentation`, since this hash-less entry is the + ## explicit title of the document. Indices without this explicit entry will + ## be considered `generated API` extracted out of a source ``.nim`` file. + ## + ## Returns the merged and sorted indices into a single HTML block which can + ## be further embedded into nimdoc templates. + var (modules, symbols, docs) = readIndexDir(dir) + assert(not symbols.isNil) + + result = "" + # Generate a quick jump list of documents. + if docs.len > 0: + result.add(generateDocumentationJumps(docs)) + result.add("<p />") + + # Generate hyperlinks to all the linked modules. + if modules.len > 0: + result.add(generateModuleJumps(modules)) + result.add("<p />") + + # Generate the HTML block with API documents. + if docs.len > 0: + result.add("<h2>Documentation files</h2>\n") + result.add(generateDocumentationIndex(docs)) + + # Generate the HTML block with symbols. + if symbols.len > 0: + sortIndex(symbols) + result.add("<h2>API symbols</h2>\n") + result.add(generateSymbolIndex(symbols)) + -# ---------------------------------------------------------------------------- - +# ---------------------------------------------------------------------------- + +proc stripTOCHTML(s: string): string = + ## Ugly quick hack to remove HTML tags from TOC titles. + ## + ## A TTocEntry.header field already contains rendered HTML tags. Instead of + ## implementing a proper version of renderRstToOut() which recursively + ## renders an rst tree to plain text, we simply remove text found between + ## angled brackets. Given the limited possibilities of rst inside TOC titles + ## this should be enough. + result = s + var first = result.find('<') + while first >= 0: + let last = result.find('>', first) + if last < 0: + # Abort, since we didn't found a closing angled bracket. + return + result.delete(first, last) + first = result.find('<', first) + proc renderHeadline(d: PDoc, n: PRstNode, result: var string) = var tmp = "" for i in countup(0, len(n) - 1): renderRstToOut(d, n.sons[i], tmp) @@ -393,27 +676,30 @@ proc renderHeadline(d: PDoc, n: PRstNode, result: var string) = d.tocPart[length].refname = refname d.tocPart[length].n = n d.tocPart[length].header = tmp - - dispA(d.target, result, - "\n<h$1><a class=\"toc-backref\" id=\"$2\" href=\"#$2_toc\">$3</a></h$1>", - "\\rsth$4{$3}\\label{$2}\n", [$n.level, - d.tocPart[length].refname, tmp, - $chr(n.level - 1 + ord('A'))]) + + dispA(d.target, result, "\n<h$1><a class=\"toc-backref\" " & + "id=\"$2\" href=\"#$2_toc\">$3</a></h$1>", "\\rsth$4{$3}\\label{$2}\n", + [$n.level, d.tocPart[length].refname, tmp, $chr(n.level - 1 + ord('A'))]) else: dispA(d.target, result, "\n<h$1 id=\"$2\">$3</h$1>", "\\rsth$4{$3}\\label{$2}\n", [ $n.level, refname, tmp, $chr(n.level - 1 + ord('A'))]) - + + # Generate index entry using spaces to indicate TOC level for the output HTML. + assert n.level >= 0 + setIndexTerm(d, refname, tmp.stripTOCHTML, + repeatChar(max(0, n.level), ' ') & tmp) + proc renderOverline(d: PDoc, n: PRstNode, result: var string) = if d.meta[metaTitle].len == 0: - d.currentSection = d.meta[metaTitle] for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], d.meta[metaTitle]) + d.currentSection = d.meta[metaTitle] elif d.meta[metaSubtitle].len == 0: - d.currentSection = d.meta[metaSubtitle] for i in countup(0, len(n)-1): renderRstToOut(d, n.sons[i], d.meta[metaSubtitle]) + d.currentSection = d.meta[metaSubtitle] else: var tmp = "" for i in countup(0, len(n) - 1): renderRstToOut(d, n.sons[i], tmp) @@ -428,7 +714,8 @@ proc renderTocEntry(d: PDoc, e: TTocEntry, result: var string) = "<li><a class=\"reference\" id=\"$1_toc\" href=\"#$1\">$2</a></li>\n", "\\item\\label{$1_toc} $2\\ref{$1}\n", [e.refname, e.header]) -proc renderTocEntries*(d: var TRstGenerator, j: var int, lvl: int, result: var string) = +proc renderTocEntries*(d: var TRstGenerator, j: var int, lvl: int, + result: var string) = var tmp = "" while j <= high(d.tocPart): var a = abs(d.tocPart[j].n.level) @@ -572,7 +859,8 @@ proc renderRstToOut(d: PDoc, n: PRstNode, result: var string) = [tmp]) of rnField: renderField(d, n, result) of rnFieldName: - renderAux(d, n, "<th class=\"docinfo-name\">$1:</th>", "\\item[$1:]", result) + renderAux(d, n, "<th class=\"docinfo-name\">$1:</th>", + "\\item[$1:]", result) of rnFieldBody: renderAux(d, n, "<td>$1</td>", " $1\n", result) of rnIndex: @@ -631,8 +919,9 @@ proc renderRstToOut(d: PDoc, n: PRstNode, result: var string) = of rnRef: var tmp = "" renderAux(d, n, tmp) - dispA(d.target, result, "<a class=\"reference external\" href=\"#$2\">$1</a>", - "$1\\ref{$2}", [tmp, rstnodeToRefname(n)]) + dispA(d.target, result, + "<a class=\"reference external\" href=\"#$2\">$1</a>", + "$1\\ref{$2}", [tmp, rstnodeToRefname(n)]) of rnStandaloneHyperlink: renderAux(d, n, "<a class=\"reference external\" href=\"$1\">$1</a>", @@ -642,9 +931,9 @@ proc renderRstToOut(d: PDoc, n: PRstNode, result: var string) = var tmp1 = "" renderRstToOut(d, n.sons[0], tmp0) renderRstToOut(d, n.sons[1], tmp1) - dispA(d.target, result, "<a class=\"reference external\" href=\"$2\">$1</a>", - "\\href{$2}{$1}", - [tmp0, tmp1]) + dispA(d.target, result, + "<a class=\"reference external\" href=\"$2\">$1</a>", + "\\href{$2}{$1}", [tmp0, tmp1]) of rnDirArg, rnRaw: renderAux(d, n, result) of rnRawHtml: if d.target != outLatex: diff --git a/lib/posix/posix.nim b/lib/posix/posix.nim index e206447cc..8e66336c2 100644 --- a/lib/posix/posix.nim +++ b/lib/posix/posix.nim @@ -846,7 +846,7 @@ var FE_UPWARD* {.importc, header: "<fenv.h>".}: cint FE_DFL_ENV* {.importc, header: "<fenv.h>".}: cint -when not defined(haiku): +when not defined(haiku) and not defined(OpenBSD): var MM_HARD* {.importc, header: "<fmtmsg.h>".}: cint ## Source of the condition is hardware. @@ -1578,8 +1578,17 @@ var ## Terminates a record (if supported by the protocol). MSG_OOB* {.importc, header: "<sys/socket.h>".}: cint ## Out-of-band data. - MSG_NOSIGNAL* {.importc, header: "<sys/socket.h>".}: cint - ## No SIGPIPE generated when an attempt to send is made on a stream-oriented socket that is no longer connected. + +when defined(macosx): + var + MSG_HAVEMORE* {.importc, header: "<sys/socket.h>".}: cint + MSG_NOSIGNAL* = MSG_HAVEMORE +else: + var + MSG_NOSIGNAL* {.importc, header: "<sys/socket.h>".}: cint + ## No SIGPIPE generated when an attempt to send is made on a stream-oriented socket that is no longer connected. + +var MSG_PEEK* {.importc, header: "<sys/socket.h>".}: cint ## Leave received data in queue. MSG_TRUNC* {.importc, header: "<sys/socket.h>".}: cint @@ -1816,7 +1825,7 @@ proc feholdexcept*(a1: ptr Tfenv): cint {.importc, header: "<fenv.h>".} proc fesetenv*(a1: ptr Tfenv): cint {.importc, header: "<fenv.h>".} proc feupdateenv*(a1: ptr Tfenv): cint {.importc, header: "<fenv.h>".} -when not defined(haiku): +when not defined(haiku) and not defined(OpenBSD): proc fmtmsg*(a1: int, a2: cstring, a3: cint, a4, a5, a6: cstring): cint {.importc, header: "<fmtmsg.h>".} diff --git a/lib/pure/algorithm.nim b/lib/pure/algorithm.nim index 37fbc948c..86d329763 100644 --- a/lib/pure/algorithm.nim +++ b/lib/pure/algorithm.nim @@ -150,6 +150,15 @@ proc sort*[T](a: var openArray[T], ## # overload: ## sort(myStrArray, system.cmp) ## + ## You can inline adhoc comparison procs with the `do notation + ## <manual.html#do-notation>`_. Example: + ## + ## .. code-block:: nimrod + ## + ## people.sort do (x, y: Person) -> int: + ## result = cmp(x.surname, y.surname) + ## if result == 0: + ## result = cmp(x.name, y.name) var n = a.len var b: seq[T] newSeq(b, n div 2) diff --git a/lib/pure/asyncdispatch.nim b/lib/pure/asyncdispatch.nim index f50383038..d410f8ce1 100644 --- a/lib/pure/asyncdispatch.nim +++ b/lib/pure/asyncdispatch.nim @@ -11,8 +11,11 @@ include "system/inclrtl" import os, oids, tables, strutils, macros -import rawsockets -export TPort +import rawsockets, net + +export TPort, TSocketFlags + +#{.injectStmt: newGcInvariant().} ## AsyncDispatch ## ------------- @@ -24,10 +27,12 @@ export TPort ## **Note:** This module is still largely experimental. -# TODO: Discarded void PFutures need to checked for exception. -# TODO: Exceptions are currently uncatchable due to the limitation that -# you cannot have yield in a try stmt. Perhaps I can get the macro to put -# a user's try except around ``future.read``. +# TODO: Discarded void PFutures need to be checked for exception. +# TODO: ``except`` statement (without `try`) does not work. +# TODO: Multiple exception names in a ``except`` don't work. +# TODO: The effect system (raises: []) has trouble with my try transformation. +# TODO: Can't await in a 'except' body +# TODO: getCurrentException(Msg) don't work # -- Futures @@ -35,19 +40,33 @@ type PFutureBase* = ref object of PObject cb: proc () {.closure,gcsafe.} finished: bool + error*: ref EBase + stackTrace: string ## For debugging purposes only. PFuture*[T] = ref object of PFutureBase value: T - error*: ref EBase # TODO: This shouldn't be necessary, generics bug? proc newFuture*[T](): PFuture[T] = ## Creates a new future. new(result) result.finished = false + result.stackTrace = getStackTrace() + +proc checkFinished[T](future: PFuture[T]) = + if future.finished: + echo("<----->") + echo(future.stackTrace) + echo("-----") + when T is string: + echo("Contents: ", future.value.repr) + echo("<----->") + echo("Future already finished, cannot finish twice.") + assert false proc complete*[T](future: PFuture[T], val: T) = ## Completes ``future`` with value ``val``. - assert(not future.finished, "Future already finished, cannot finish twice.") + #assert(not future.finished, "Future already finished, cannot finish twice.") + checkFinished(future) assert(future.error == nil) future.value = val future.finished = true @@ -56,7 +75,8 @@ proc complete*[T](future: PFuture[T], val: T) = proc complete*(future: PFuture[void]) = ## Completes a void ``future``. - assert(not future.finished, "Future already finished, cannot finish twice.") + #assert(not future.finished, "Future already finished, cannot finish twice.") + checkFinished(future) assert(future.error == nil) future.finished = true if future.cb != nil: @@ -64,11 +84,18 @@ proc complete*(future: PFuture[void]) = proc fail*[T](future: PFuture[T], error: ref EBase) = ## Completes ``future`` with ``error``. - assert(not future.finished, "Future already finished, cannot finish twice.") + #assert(not future.finished, "Future already finished, cannot finish twice.") + checkFinished(future) future.finished = true future.error = error if future.cb != nil: future.cb() + else: + # This is to prevent exceptions from being silently ignored when a future + # is discarded. + # TODO: This may turn out to be a bad idea. + # Turns out this is a bad idea. + #raise error proc `callback=`*(future: PFutureBase, cb: proc () {.closure,gcsafe.}) = ## Sets the callback proc to be called when the future completes. @@ -112,10 +139,19 @@ proc finished*[T](future: PFuture[T]): bool = ## ``True`` may indicate an error or a value. Use ``failed`` to distinguish. future.finished -proc failed*[T](future: PFuture[T]): bool = +proc failed*(future: PFutureBase): bool = ## Determines whether ``future`` completed with an error. future.error != nil +proc asyncCheck*[T](future: PFuture[T]) = + ## Sets a callback on ``future`` which raises an exception if the future + ## finished with an error. + ## + ## This should be used instead of ``discard`` to discard void futures. + future.callback = + proc () = + if future.failed: raise future.error + when defined(windows) or defined(nimdoc): import winlean, sets, hashes type @@ -130,15 +166,10 @@ when defined(windows) or defined(nimdoc): ioPort: THandle handles: TSet[TAsyncFD] - TCustomOverlapped = object - Internal*: DWORD - InternalHigh*: DWORD - Offset*: DWORD - OffsetHigh*: DWORD - hEvent*: THANDLE + TCustomOverlapped = object of TOVERLAPPED data*: TCompletionData - PCustomOverlapped = ptr TCustomOverlapped + PCustomOverlapped = ref TCustomOverlapped TAsyncFD* = distinct int @@ -184,27 +215,27 @@ when defined(windows) or defined(nimdoc): else: timeout.int32 var lpNumberOfBytesTransferred: DWORD var lpCompletionKey: ULONG - var lpOverlapped: POverlapped - let res = GetQueuedCompletionStatus(p.ioPort, addr lpNumberOfBytesTransferred, - addr lpCompletionKey, addr lpOverlapped, llTimeout).bool + var customOverlapped: PCustomOverlapped + let res = GetQueuedCompletionStatus(p.ioPort, + addr lpNumberOfBytesTransferred, addr lpCompletionKey, + cast[ptr POverlapped](addr customOverlapped), llTimeout).bool # http://stackoverflow.com/a/12277264/492186 # TODO: http://www.serverframework.com/handling-multiple-pending-socket-read-and-write-operations.html - var customOverlapped = cast[PCustomOverlapped](lpOverlapped) if res: # This is useful for ensuring the reliability of the overlapped struct. assert customOverlapped.data.sock == lpCompletionKey.TAsyncFD customOverlapped.data.cb(customOverlapped.data.sock, lpNumberOfBytesTransferred, TOSErrorCode(-1)) - dealloc(customOverlapped) + GC_unref(customOverlapped) else: let errCode = osLastError() - if lpOverlapped != nil: + if customOverlapped != nil: assert customOverlapped.data.sock == lpCompletionKey.TAsyncFD customOverlapped.data.cb(customOverlapped.data.sock, lpNumberOfBytesTransferred, errCode) - dealloc(customOverlapped) + GC_unref(customOverlapped) else: if errCode.int32 == WAIT_TIMEOUT: # Timed out @@ -300,7 +331,8 @@ when defined(windows) or defined(nimdoc): while it != nil: # "the OVERLAPPED structure must remain valid until the I/O completes" # http://blogs.msdn.com/b/oldnewthing/archive/2011/02/02/10123392.aspx - var ol = cast[PCustomOverlapped](alloc0(sizeof(TCustomOverlapped))) + var ol = PCustomOverlapped() + GC_ref(ol) ol.data = TCompletionData(sock: socket, cb: proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) = if not retFuture.finished: @@ -328,7 +360,7 @@ when defined(windows) or defined(nimdoc): success = true break else: - dealloc(ol) + GC_unref(ol) success = false it = it.ai_next @@ -338,7 +370,7 @@ when defined(windows) or defined(nimdoc): return retFuture proc recv*(socket: TAsyncFD, size: int, - flags: int = 0): PFuture[string] = + flags = {TSocketFlags.SafeDisconn}): PFuture[string] = ## Reads **up to** ``size`` bytes from ``socket``. Returned future will ## complete once all the data requested is read, a part of the data has been ## read, or the socket has disconnected in which case the future will @@ -352,15 +384,15 @@ when defined(windows) or defined(nimdoc): # '\0' in the message currently signifies a socket disconnect. Who # knows what will happen when someone sends that to our socket. verifyPresence(socket) - var retFuture = newFuture[string]() - + var retFuture = newFuture[string]() var dataBuf: TWSABuf dataBuf.buf = cast[cstring](alloc0(size)) dataBuf.len = size var bytesReceived: DWord - var flagsio = flags.DWord - var ol = cast[PCustomOverlapped](alloc0(sizeof(TCustomOverlapped))) + var flagsio = flags.toOSFlags().DWord + var ol = PCustomOverlapped() + GC_ref(ol) ol.data = TCompletionData(sock: socket, cb: proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) = if not retFuture.finished: @@ -374,7 +406,9 @@ when defined(windows) or defined(nimdoc): retFuture.complete($data) else: retFuture.fail(newException(EOS, osErrorMsg(errcode))) - dealloc dataBuf.buf + if dataBuf.buf != nil: + dealloc dataBuf.buf + dataBuf.buf = nil ) let ret = WSARecv(socket.TSocketHandle, addr dataBuf, 1, addr bytesReceived, @@ -382,9 +416,14 @@ when defined(windows) or defined(nimdoc): if ret == -1: let err = osLastError() if err.int32 != ERROR_IO_PENDING: - dealloc dataBuf.buf - dealloc(ol) - retFuture.fail(newException(EOS, osErrorMsg(err))) + if dataBuf.buf != nil: + dealloc dataBuf.buf + dataBuf.buf = nil + GC_unref(ol) + if flags.isDisconnectionError(err): + retFuture.complete("") + else: + retFuture.fail(newException(EOS, osErrorMsg(err))) elif ret == 0 and bytesReceived == 0 and dataBuf.buf[0] == '\0': # We have to ensure that the buffer is empty because WSARecv will tell # us immediatelly when it was disconnected, even when there is still @@ -415,7 +454,8 @@ when defined(windows) or defined(nimdoc): # free ``ol``. return retFuture - proc send*(socket: TAsyncFD, data: string): PFuture[void] = + proc send*(socket: TAsyncFD, data: string, + flags = {TSocketFlags.SafeDisconn}): PFuture[void] = ## Sends ``data`` to ``socket``. The returned future will complete once all ## data has been sent. verifyPresence(socket) @@ -425,8 +465,9 @@ when defined(windows) or defined(nimdoc): dataBuf.buf = data # since this is not used in a callback, this is fine dataBuf.len = data.len - var bytesReceived, flags: DWord - var ol = cast[PCustomOverlapped](alloc0(sizeof(TCustomOverlapped))) + var bytesReceived, lowFlags: DWord + var ol = PCustomOverlapped() + GC_ref(ol) ol.data = TCompletionData(sock: socket, cb: proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) = if not retFuture.finished: @@ -437,12 +478,15 @@ when defined(windows) or defined(nimdoc): ) let ret = WSASend(socket.TSocketHandle, addr dataBuf, 1, addr bytesReceived, - flags, cast[POverlapped](ol), nil) + lowFlags, cast[POverlapped](ol), nil) if ret == -1: let err = osLastError() if err.int32 != ERROR_IO_PENDING: - retFuture.fail(newException(EOS, osErrorMsg(err))) - dealloc(ol) + GC_unref(ol) + if flags.isDisconnectionError(err): + retFuture.complete() + else: + retFuture.fail(newException(EOS, osErrorMsg(err))) else: retFuture.complete() # We don't deallocate ``ol`` here because even though this completed @@ -490,7 +534,8 @@ when defined(windows) or defined(nimdoc): client: clientSock.TAsyncFD) ) - var ol = cast[PCustomOverlapped](alloc0(sizeof(TCustomOverlapped))) + var ol = PCustomOverlapped() + GC_ref(ol) ol.data = TCompletionData(sock: socket, cb: proc (sock: TAsyncFD, bytesCount: DWord, errcode: TOSErrorCode) = if not retFuture.finished: @@ -511,7 +556,7 @@ when defined(windows) or defined(nimdoc): let err = osLastError() if err.int32 != ERROR_IO_PENDING: retFuture.fail(newException(EOS, osErrorMsg(err))) - dealloc(ol) + GC_unref(ol) else: completeAccept() # We don't deallocate ``ol`` here because even though this completed @@ -528,15 +573,30 @@ when defined(windows) or defined(nimdoc): result.TSocketHandle.setBlocking(false) register(result) - proc close*(socket: TAsyncFD) = + proc closeSocket*(socket: TAsyncFD) = ## Closes a socket and ensures that it is unregistered. socket.TSocketHandle.close() getGlobalDispatcher().handles.excl(socket) + proc unregister*(fd: TAsyncFD) = + ## Unregisters ``fd``. + getGlobalDispatcher().handles.excl(fd) + initAll() else: import selectors - from posix import EINTR, EAGAIN, EINPROGRESS, EWOULDBLOCK, MSG_PEEK + when defined(windows): + import winlean + const + EINTR = WSAEINPROGRESS + EINPROGRESS = WSAEINPROGRESS + EWOULDBLOCK = WSAEWOULDBLOCK + EAGAIN = EINPROGRESS + MSG_NOSIGNAL = 0 + else: + from posix import EINTR, EAGAIN, EINPROGRESS, EWOULDBLOCK, MSG_PEEK, + MSG_NOSIGNAL + type TAsyncFD* = distinct cint TCallback = proc (sock: TAsyncFD): bool {.closure,gcsafe.} @@ -577,11 +637,14 @@ else: result.TSocketHandle.setBlocking(false) register(result) - proc close*(sock: TAsyncFD) = + proc closeSocket*(sock: TAsyncFD) = let disp = getGlobalDispatcher() sock.TSocketHandle.close() disp.selector.unregister(sock.TSocketHandle) + proc unregister*(fd: TAsyncFD) = + getGlobalDispatcher().selector.unregister(fd.TSocketHandle) + proc addRead(sock: TAsyncFD, cb: TCallback) = let p = getGlobalDispatcher() if sock.TSocketHandle notin p.selector: @@ -667,20 +730,23 @@ else: return retFuture proc recv*(socket: TAsyncFD, size: int, - flags: int = 0): PFuture[string] = + flags = {TSocketFlags.SafeDisconn}): PFuture[string] = var retFuture = newFuture[string]() var readBuffer = newString(size) proc cb(sock: TAsyncFD): bool = result = true - let res = recv(sock.TSocketHandle, addr readBuffer[0], size, - flags.cint) + let res = recv(sock.TSocketHandle, addr readBuffer[0], size.cint, + flags.toOSFlags()) #echo("recv cb res: ", res) if res < 0: let lastError = osLastError() - if lastError.int32 notin {EINTR, EWOULDBLOCK, EAGAIN}: - retFuture.fail(newException(EOS, osErrorMsg(lastError))) + if lastError.int32 notin {EINTR, EWOULDBLOCK, EAGAIN}: + if flags.isDisconnectionError(lastError): + retFuture.complete("") + else: + retFuture.fail(newException(EOS, osErrorMsg(lastError))) else: result = false # We still want this callback to be called. elif res == 0: @@ -689,11 +755,13 @@ else: else: readBuffer.setLen(res) retFuture.complete(readBuffer) - + # TODO: The following causes a massive slowdown. + #if not cb(socket): addRead(socket, cb) return retFuture - proc send*(socket: TAsyncFD, data: string): PFuture[void] = + proc send*(socket: TAsyncFD, data: string, + flags = {TSocketFlags.SafeDisconn}): PFuture[void] = var retFuture = newFuture[void]() var written = 0 @@ -702,11 +770,15 @@ else: result = true let netSize = data.len-written var d = data.cstring - let res = send(sock.TSocketHandle, addr d[written], netSize, 0.cint) + let res = send(sock.TSocketHandle, addr d[written], netSize.cint, + MSG_NOSIGNAL) if res < 0: let lastError = osLastError() if lastError.int32 notin {EINTR, EWOULDBLOCK, EAGAIN}: - retFuture.fail(newException(EOS, osErrorMsg(lastError))) + if flags.isDisconnectionError(lastError): + retFuture.complete() + else: + retFuture.fail(newException(EOS, osErrorMsg(lastError))) else: result = false # We still want this callback to be called. else: @@ -715,6 +787,8 @@ else: result = false # We still have data to send. else: retFuture.complete() + # TODO: The following causes crashes. + #if not cb(socket): addWrite(socket, cb) return retFuture @@ -757,41 +831,76 @@ proc accept*(socket: TAsyncFD): PFuture[TAsyncFD] = # -- Await Macro -template createCb*(retFutureSym, iteratorNameSym: expr): stmt {.immediate.} = +template createCb*(retFutureSym, iteratorNameSym, + name: expr): stmt {.immediate.} = var nameIterVar = iteratorNameSym + #{.push stackTrace: off.} proc cb {.closure,gcsafe.} = - if not nameIterVar.finished: - var next = nameIterVar() - if next == nil: - assert retFutureSym.finished, "Async procedure's return Future was not finished." - else: - next.callback = cb + try: + if not nameIterVar.finished: + var next = nameIterVar() + if next == nil: + assert retFutureSym.finished, "Async procedure's (" & + name & ") return Future was not finished." + else: + next.callback = cb + except: + retFutureSym.fail(getCurrentException()) cb() - -template createVar(futSymName: string, asyncProc: PNimrodNode, - valueReceiver: expr) {.immediate, dirty.} = - # TODO: Used template here due to bug #926 + #{.pop.} +proc generateExceptionCheck(futSym, + exceptBranch, rootReceiver: PNimrodNode): PNimrodNode {.compileTime.} = + if exceptBranch == nil: + result = rootReceiver + else: + if exceptBranch[0].kind == nnkStmtList: + result = newIfStmt( + (newDotExpr(futSym, newIdentNode("failed")), + exceptBranch[0] + ) + ) + else: + expectKind(exceptBranch[1], nnkStmtList) + result = newIfStmt( + (newDotExpr(futSym, newIdentNode("failed")), + newIfStmt( + (infix(newDotExpr(futSym, newIdentNode("error")), "of", exceptBranch[0]), + exceptBranch[1]) + ) + ) + ) + let elseNode = newNimNode(nnkElse) + elseNode.add newNimNode(nnkStmtList) + elseNode[0].add rootReceiver + result.add elseNode + +template createVar(result: var PNimrodNode, futSymName: string, + asyncProc: PNimrodNode, + valueReceiver, rootReceiver: expr) = result = newNimNode(nnkStmtList) var futSym = genSym(nskVar, "future") result.add newVarStmt(futSym, asyncProc) # -> var future<x> = y result.add newNimNode(nnkYieldStmt).add(futSym) # -> yield future<x> valueReceiver = newDotExpr(futSym, newIdentNode("read")) # -> future<x>.read + result.add generateExceptionCheck(futSym, exceptBranch, rootReceiver) proc processBody(node, retFutureSym: PNimrodNode, - subtypeName: string): PNimrodNode {.compileTime.} = + subTypeIsVoid: bool, + exceptBranch: PNimrodNode): PNimrodNode {.compileTime.} = + #echo(node.treeRepr) result = node case node.kind of nnkReturnStmt: result = newNimNode(nnkStmtList) if node[0].kind == nnkEmpty: - if subtypeName != "void": + if not subtypeIsVoid: result.add newCall(newIdentNode("complete"), retFutureSym, newIdentNode("result")) else: result.add newCall(newIdentNode("complete"), retFutureSym) else: result.add newCall(newIdentNode("complete"), retFutureSym, - node[0].processBody(retFutureSym, subtypeName)) + node[0].processBody(retFutureSym, subtypeIsVoid, exceptBranch)) result.add newNimNode(nnkReturnStmt).add(newNilLit()) return # Don't process the children of this return stmt @@ -804,16 +913,16 @@ proc processBody(node, retFutureSym: PNimrodNode, of nnkCall: # await foo(p, x) var futureValue: PNimrodNode - createVar("future" & $node[1][0].toStrLit, node[1], futureValue) - result.add futureValue + result.createVar("future" & $node[1][0].toStrLit, node[1], futureValue, + futureValue) else: error("Invalid node kind in 'await', got: " & $node[1].kind) elif node[1].kind == nnkCommand and node[1][0].kind == nnkIdent and node[1][0].ident == !"await": # foo await x var newCommand = node - createVar("future" & $node[0].toStrLit, node[1][1], newCommand[1]) - result.add newCommand + result.createVar("future" & $node[0].toStrLit, node[1][1], newCommand[1], + newCommand) of nnkVarSection, nnkLetSection: case node[0][2].kind @@ -821,9 +930,8 @@ proc processBody(node, retFutureSym: PNimrodNode, if node[0][2][0].ident == !"await": # var x = await y var newVarSection = node # TODO: Should this use copyNimNode? - createVar("future" & $node[0][0].ident, node[0][2][1], - newVarSection[0][2]) - result.add newVarSection + result.createVar("future" & $node[0][0].ident, node[0][2][1], + newVarSection[0][2], newVarSection) else: discard of nnkAsgn: case node[1].kind @@ -831,19 +939,43 @@ proc processBody(node, retFutureSym: PNimrodNode, if node[1][0].ident == !"await": # x = await y var newAsgn = node - createVar("future" & $node[0].toStrLit, node[1][1], newAsgn[1]) - result.add newAsgn + result.createVar("future" & $node[0].toStrLit, node[1][1], newAsgn[1], newAsgn) else: discard of nnkDiscardStmt: # discard await x - if node[0][0].kind == nnkIdent and node[0][0].ident == !"await": - var dummy = newNimNode(nnkStmtList) - createVar("futureDiscard_" & $toStrLit(node[0][1]), node[0][1], dummy) + if node[0].kind != nnkEmpty and node[0][0].kind == nnkIdent and + node[0][0].ident == !"await": + var newDiscard = node + result.createVar("futureDiscard_" & $toStrLit(node[0][1]), node[0][1], + newDiscard[0], newDiscard) + of nnkTryStmt: + # try: await x; except: ... + result = newNimNode(nnkStmtList) + proc processForTry(n: PNimrodNode, i: var int, + res: PNimrodNode): bool {.compileTime.} = + result = false + while i < n[0].len: + var processed = processBody(n[0][i], retFutureSym, subtypeIsVoid, n[1]) + if processed.kind != n[0][i].kind or processed.len != n[0][i].len: + expectKind(processed, nnkStmtList) + expectKind(processed[2][1], nnkElse) + i.inc + discard processForTry(n, i, processed[2][1][0]) + res.add processed + result = true + else: + res.add n[0][i] + i.inc + var i = 0 + if not processForTry(node, i, result): + var temp = node + temp[0] = result + result = temp + return else: discard - + for i in 0 .. <result.len: - result[i] = processBody(result[i], retFutureSym, subtypeName) - #echo(treeRepr(result)) + result[i] = processBody(result[i], retFutureSym, subtypeIsVoid, exceptBranch) proc getName(node: PNimrodNode): string {.compileTime.} = case node.kind @@ -851,47 +983,53 @@ proc getName(node: PNimrodNode): string {.compileTime.} = return $node[1].ident of nnkIdent: return $node.ident + of nnkEmpty: + return "anonymous" else: - assert false + error("Unknown name.") macro async*(prc: stmt): stmt {.immediate.} = ## Macro which processes async procedures into the appropriate ## iterators and yield statements. - - expectKind(prc, nnkProcDef) + if prc.kind notin {nnkProcDef, nnkLambda}: + error("Cannot transform this node kind into an async proc." & + " Proc definition or lambda node expected.") hint("Processing " & prc[0].getName & " as an async proc.") let returnType = prc[3][0] - var subtypeName = "" # Verify that the return type is a PFuture[T] if returnType.kind == nnkIdent: error("Expected return type of 'PFuture' got '" & $returnType & "'") elif returnType.kind == nnkBracketExpr: if $returnType[0] != "PFuture": error("Expected return type of 'PFuture' got '" & $returnType[0] & "'") - subtypeName = $returnType[1].ident - elif returnType.kind == nnkEmpty: - subtypeName = "void" + + let subtypeIsVoid = returnType.kind == nnkEmpty or + (returnType.kind == nnkBracketExpr and + returnType[1].kind == nnkIdent and returnType[1].ident == !"void") var outerProcBody = newNimNode(nnkStmtList) # -> var retFuture = newFuture[T]() var retFutureSym = genSym(nskVar, "retFuture") + var subRetType = + if returnType.kind == nnkEmpty: newIdentNode("void") + else: returnType[1] outerProcBody.add( newVarStmt(retFutureSym, newCall( newNimNode(nnkBracketExpr).add( newIdentNode(!"newFuture"), # TODO: Strange bug here? Remove the `!`. - newIdentNode(subtypeName))))) # Get type from return type of this proc + subRetType)))) # Get type from return type of this proc # -> iterator nameIter(): PFutureBase {.closure.} = # -> var result: T # -> <proc_body> # -> complete(retFuture, result) var iteratorNameSym = genSym(nskIterator, $prc[0].getName & "Iter") - var procBody = prc[6].processBody(retFutureSym, subtypeName) - if subtypeName != "void": + var procBody = prc[6].processBody(retFutureSym, subtypeIsVoid, nil) + if not subtypeIsVoid: procBody.insert(0, newNimNode(nnkVarSection).add( newIdentDefs(newIdentNode("result"), returnType[1]))) # -> var result: T procBody.add( @@ -908,7 +1046,8 @@ macro async*(prc: stmt): stmt {.immediate.} = # -> createCb(retFuture) var cbName = newIdentNode("cb") - var procCb = newCall("createCb", retFutureSym, iteratorNameSym) + var procCb = newCall("createCb", retFutureSym, iteratorNameSym, + newStrLitNode(prc[0].getName)) outerProcBody.add procCb # -> return retFuture @@ -918,17 +1057,18 @@ macro async*(prc: stmt): stmt {.immediate.} = # Remove the 'async' pragma. for i in 0 .. <result[4].len: - if result[4][i].ident == !"async": + if result[4][i].kind == nnkIdent and result[4][i].ident == !"async": result[4].del(i) - if subtypeName == "void": + if subtypeIsVoid: # Add discardable pragma. - result[4].add(newIdentNode("discardable")) if returnType.kind == nnkEmpty: # Add PFuture[void] result[3][0] = parseExpr("PFuture[void]") result[6] = outerProcBody + #echo(treeRepr(result)) + #if prc[0].getName == "routeReq": #echo(toStrLit(result)) proc recvLine*(socket: TAsyncFD): PFuture[string] {.async.} = @@ -956,7 +1096,7 @@ proc recvLine*(socket: TAsyncFD): PFuture[string] {.async.} = if c.len == 0: return "" if c == "\r": - c = await recv(socket, 1, MSG_PEEK) + c = await recv(socket, 1, {TSocketFlags.SafeDisconn, TSocketFlags.Peek}) if c.len > 0 and c == "\L": discard await recv(socket, 1) addNLIfEmpty() diff --git a/lib/pure/asynchttpserver.nim b/lib/pure/asynchttpserver.nim index 2ebd7036d..ee6658fd1 100644 --- a/lib/pure/asynchttpserver.nim +++ b/lib/pure/asynchttpserver.nim @@ -14,12 +14,13 @@ import strtabs, asyncnet, asyncdispatch, parseutils, parseurl, strutils type TRequest* = object - client: PAsyncSocket # TODO: Separate this into a Response object? + client*: PAsyncSocket # TODO: Separate this into a Response object? reqMethod*: string headers*: PStringTable protocol*: tuple[orig: string, major, minor: int] url*: TURL hostname*: string ## The hostname of the client that made the request. + body*: string PAsyncHttpServer* = ref object socket: PAsyncSocket @@ -50,10 +51,15 @@ proc `==`*(protocol: tuple[orig: string, major, minor: int], proc newAsyncHttpServer*(): PAsyncHttpServer = new result -proc sendHeaders*(req: TRequest, headers: PStringTable) {.async.} = - ## Sends the specified headers to the requesting client. +proc addHeaders(msg: var string, headers: PStringTable) = for k, v in headers: - await req.client.send(k & ": " & v & "\c\L") + msg.add(k & ": " & v & "\c\L") + +proc sendHeaders*(req: TRequest, headers: PStringTable): PFuture[void] = + ## Sends the specified headers to the requesting client. + var msg = "" + addHeaders(msg, headers) + return req.client.send(msg) proc respond*(req: TRequest, code: THttpCode, content: string, headers: PStringTable = newStringTable()) {.async.} = @@ -63,9 +69,9 @@ proc respond*(req: TRequest, code: THttpCode, ## This procedure will **not** close the client socket. var customHeaders = headers customHeaders["Content-Length"] = $content.len - await req.client.send("HTTP/1.1 " & $code & "\c\L") - await sendHeaders(req, headers) - await req.client.send("\c\L" & content) + var msg = "HTTP/1.1 " & $code & "\c\L" + msg.addHeaders(customHeaders) + await req.client.send(msg & "\c\L" & content) proc newRequest(): TRequest = result.headers = newStringTable(modeCaseInsensitive) @@ -77,7 +83,7 @@ proc parseHeader(line: string): tuple[key, value: string] = i += line.skipWhiteSpace(i) i += line.parseUntil(result.value, {'\c', '\L'}, i) -proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] = +proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] = var i = protocol.skipIgnoreCase("HTTP/") if i != 5: raise newException(EInvalidValue, "Invalid request protocol. Got: " & @@ -87,70 +93,95 @@ proc parseProtocol(protocol: string): tuple[orig: string, major, minor: int] = i.inc # Skip . i.inc protocol.parseInt(result.minor, i) +proc sendStatus(client: PAsyncSocket, status: string): PFuture[void] = + client.send("HTTP/1.1 " & status & "\c\L") + proc processClient(client: PAsyncSocket, address: string, callback: proc (request: TRequest): PFuture[void]) {.async.} = - # GET /path HTTP/1.1 - # Header: val - # \n - var request = newRequest() - request.hostname = address - assert client != nil - request.client = client - - # First line - GET /path HTTP/1.1 - let line = await client.recvLine() # TODO: Timeouts. - if line == "": - client.close() - return - let lineParts = line.split(' ') - if lineParts.len != 3: - request.respond(Http400, "Invalid request. Got: " & line) - client.close() - return - - let reqMethod = lineParts[0] - let path = lineParts[1] - let protocol = lineParts[2] - - # Headers - var i = 0 while true: - i = 0 - let headerLine = await client.recvLine() - if headerLine == "": - client.close(); return - if headerLine == "\c\L": break - # TODO: Compiler crash - #let (key, value) = parseHeader(headerLine) - let kv = parseHeader(headerLine) - request.headers[kv.key] = kv.value - - request.reqMethod = reqMethod - request.url = parseUrl(path) - try: - request.protocol = protocol.parseProtocol() - except EInvalidValue: - request.respond(Http400, "Invalid request protocol. Got: " & protocol) - return - - case reqMethod.normalize - of "get", "post", "head", "put", "delete", "trace", "options", "connect", "patch": - await callback(request) - else: - request.respond(Http400, "Invalid request method. Got: " & reqMethod) - - # Persistent connections - if (request.protocol == HttpVer11 and - request.headers["connection"].normalize != "close") or - (request.protocol == HttpVer10 and - request.headers["connection"].normalize == "keep-alive"): - # In HTTP 1.1 we assume that connection is persistent. Unless connection - # header states otherwise. - # In HTTP 1.0 we assume that the connection should not be persistent. - # Unless the connection header states otherwise. - await processClient(client, address, callback) - else: - request.client.close() + # GET /path HTTP/1.1 + # Header: val + # \n + var request = newRequest() + request.hostname = address + assert client != nil + request.client = client + + # First line - GET /path HTTP/1.1 + let line = await client.recvLine() # TODO: Timeouts. + if line == "": + client.close() + return + let lineParts = line.split(' ') + if lineParts.len != 3: + await request.respond(Http400, "Invalid request. Got: " & line) + continue + + let reqMethod = lineParts[0] + let path = lineParts[1] + let protocol = lineParts[2] + + # Headers + var i = 0 + while true: + i = 0 + let headerLine = await client.recvLine() + if headerLine == "": + client.close(); return + if headerLine == "\c\L": break + # TODO: Compiler crash + #let (key, value) = parseHeader(headerLine) + let kv = parseHeader(headerLine) + request.headers[kv.key] = kv.value + + request.reqMethod = reqMethod + request.url = parseUrl(path) + try: + request.protocol = protocol.parseProtocol() + except EInvalidValue: + asyncCheck request.respond(Http400, "Invalid request protocol. Got: " & + protocol) + continue + + if reqMethod.normalize == "post": + # Check for Expect header + if request.headers.hasKey("Expect"): + if request.headers["Expect"].toLower == "100-continue": + await client.sendStatus("100 Continue") + else: + await client.sendStatus("417 Expectation Failed") + + # Read the body + # - Check for Content-length header + if request.headers.hasKey("Content-Length"): + var contentLength = 0 + if parseInt(request.headers["Content-Length"], contentLength) == 0: + await request.respond(Http400, "Bad Request. Invalid Content-Length.") + else: + request.body = await client.recv(contentLength) + assert request.body.len == contentLength + else: + await request.respond(Http400, "Bad Request. No Content-Length.") + continue + + case reqMethod.normalize + of "get", "post", "head", "put", "delete", "trace", "options", "connect", "patch": + await callback(request) + else: + await request.respond(Http400, "Invalid request method. Got: " & reqMethod) + + # Persistent connections + if (request.protocol == HttpVer11 and + request.headers["connection"].normalize != "close") or + (request.protocol == HttpVer10 and + request.headers["connection"].normalize == "keep-alive"): + # In HTTP 1.1 we assume that connection is persistent. Unless connection + # header states otherwise. + # In HTTP 1.0 we assume that the connection should not be persistent. + # Unless the connection header states otherwise. + else: + request.client.close() + break proc serve*(server: PAsyncHttpServer, port: TPort, callback: proc (request: TRequest): PFuture[void], @@ -167,14 +198,20 @@ proc serve*(server: PAsyncHttpServer, port: TPort, # TODO: Causes compiler crash. #var (address, client) = await server.socket.acceptAddr() var fut = await server.socket.acceptAddr() - processClient(fut.client, fut.address, callback) + asyncCheck processClient(fut.client, fut.address, callback) + +proc close*(server: PAsyncHttpServer) = + ## Terminates the async http server instance. + server.socket.close() when isMainModule: var server = newAsyncHttpServer() proc cb(req: TRequest) {.async.} = #echo(req.reqMethod, " ", req.url) #echo(req.headers) - await req.respond(Http200, "Hello World") + let headers = {"Date": "Tue, 29 Apr 2014 23:40:08 GMT", + "Content-type": "text/plain; charset=utf-8"} + await req.respond(Http200, "Hello World", headers.newStringTable()) - server.serve(TPort(5555), cb) + asyncCheck server.serve(TPort(5555), cb) runForever() diff --git a/lib/pure/asyncnet.nim b/lib/pure/asyncnet.nim index b1abf627b..374ac77e3 100644 --- a/lib/pure/asyncnet.nim +++ b/lib/pure/asyncnet.nim @@ -80,7 +80,8 @@ proc connect*(socket: PAsyncSocket, address: string, port: TPort, ## or an error occurs. result = connect(socket.fd.TAsyncFD, address, port, af) -proc readIntoBuf(socket: PAsyncSocket, flags: int): PFuture[int] {.async.} = +proc readIntoBuf(socket: PAsyncSocket, + flags: set[TSocketFlags]): PFuture[int] {.async.} = var data = await recv(socket.fd.TAsyncFD, BufferSize, flags) if data.len != 0: copyMem(addr socket.buffer[0], addr data[0], data.len) @@ -89,7 +90,7 @@ proc readIntoBuf(socket: PAsyncSocket, flags: int): PFuture[int] {.async.} = result = data.len proc recv*(socket: PAsyncSocket, size: int, - flags: int = 0): PFuture[string] {.async.} = + flags = {TSocketFlags.SafeDisconn}): PFuture[string] {.async.} = ## Reads ``size`` bytes from ``socket``. Returned future will complete once ## all of the requested data is read. If socket is disconnected during the ## recv operation then the future may complete with only a part of the @@ -97,37 +98,42 @@ proc recv*(socket: PAsyncSocket, size: int, ## to be read then the future will complete with a value of ``""``. if socket.isBuffered: result = newString(size) - - template returnNow(readBytes: int) = - result.setLen(readBytes) - # Only increase buffer position when not peeking. - if (flags and MSG_PEEK) != MSG_PEEK: - socket.currPos.inc(readBytes) - return + let originalBufPos = socket.currPos if socket.bufLen == 0: - let res = await socket.readIntoBuf(flags and (not MSG_PEEK)) - if res == 0: returnNow(0) + let res = await socket.readIntoBuf(flags - {TSocketFlags.Peek}) + if res == 0: + result.setLen(0) + return var read = 0 while read < size: if socket.currPos >= socket.bufLen: - let res = await socket.readIntoBuf(flags and (not MSG_PEEK)) - if res == 0: returnNow(read) + if TSocketFlags.Peek in flags: + # We don't want to get another buffer if we're peeking. + break + let res = await socket.readIntoBuf(flags - {TSocketFlags.Peek}) + if res == 0: + break let chunk = min(socket.bufLen-socket.currPos, size-read) - copyMem(addr(result[read]), addr(socket.buffer[socket.currPos+read]), chunk) + copyMem(addr(result[read]), addr(socket.buffer[socket.currPos]), chunk) read.inc(chunk) + socket.currPos.inc(chunk) - returnNow(read) + if TSocketFlags.Peek in flags: + # Restore old buffer cursor position. + socket.currPos = originalBufPos + result.setLen(read) else: result = await recv(socket.fd.TAsyncFD, size, flags) -proc send*(socket: PAsyncSocket, data: string): PFuture[void] = +proc send*(socket: PAsyncSocket, data: string, + flags = {TSocketFlags.SafeDisconn}): PFuture[void] = ## Sends ``data`` to ``socket``. The returned future will complete once all ## data has been sent. assert socket != nil - result = send(socket.fd.TAsyncFD, data) + result = send(socket.fd.TAsyncFD, data, flags) proc acceptAddr*(socket: PAsyncSocket): PFuture[tuple[address: string, client: PAsyncSocket]] = @@ -162,7 +168,8 @@ proc accept*(socket: PAsyncSocket): PFuture[PAsyncSocket] = retFut.complete(future.read.client) return retFut -proc recvLine*(socket: PAsyncSocket): PFuture[string] {.async.} = +proc recvLine*(socket: PAsyncSocket, + flags = {TSocketFlags.SafeDisconn}): PFuture[string] {.async.} = ## Reads a line of data from ``socket``. Returned future will complete once ## a full line is read or an error occurs. ## @@ -175,28 +182,60 @@ proc recvLine*(socket: PAsyncSocket): PFuture[string] {.async.} = ## If the socket is disconnected in the middle of a line (before ``\r\L`` ## is read) then line will be set to ``""``. ## The partial line **will be lost**. - + ## + ## **Warning**: The ``Peek`` flag is not yet implemented. template addNLIfEmpty(): stmt = if result.len == 0: result.add("\c\L") + assert TSocketFlags.Peek notin flags ## TODO: + if socket.isBuffered: + result = "" + if socket.bufLen == 0: + let res = await socket.readIntoBuf(flags) + if res == 0: + return - result = "" - var c = "" - while true: - c = await recv(socket, 1) - if c.len == 0: - return "" - if c == "\r": - c = await recv(socket, 1, MSG_PEEK) - if c.len > 0 and c == "\L": - let dummy = await recv(socket, 1) - assert dummy == "\L" - addNLIfEmpty() - return - elif c == "\L": - addNLIfEmpty() - return - add(result.string, c) + var lastR = false + while true: + if socket.currPos >= socket.bufLen: + let res = await socket.readIntoBuf(flags) + if res == 0: + result = "" + break + + case socket.buffer[socket.currPos] + of '\r': + lastR = true + addNLIfEmpty() + of '\L': + addNLIfEmpty() + socket.currPos.inc() + return + else: + if lastR: + socket.currPos.inc() + return + else: + result.add socket.buffer[socket.currPos] + socket.currPos.inc() + else: + result = "" + var c = "" + while true: + c = await recv(socket, 1, flags) + if c.len == 0: + return "" + if c == "\r": + c = await recv(socket, 1, flags + {TSocketFlags.Peek}) + if c.len > 0 and c == "\L": + let dummy = await recv(socket, 1, flags) + assert dummy == "\L" + addNLIfEmpty() + return + elif c == "\L": + addNLIfEmpty() + return + add(result.string, c) proc bindAddr*(socket: PAsyncSocket, port = TPort(0), address = "") = ## Binds ``address``:``port`` to the socket. @@ -214,7 +253,7 @@ proc listen*(socket: PAsyncSocket, backlog = SOMAXCONN) = proc close*(socket: PAsyncSocket) = ## Closes the socket. - socket.fd.TAsyncFD.close() + socket.fd.TAsyncFD.closeSocket() # TODO SSL when isMainModule: @@ -235,7 +274,7 @@ when isMainModule: break else: echo("Got line: ", line) - main() + asyncCheck main() elif test == LowClient: var sock = newAsyncSocket() var f = connect(sock, "irc.freenode.net", TPort(6667)) diff --git a/lib/pure/collections/sequtils.nim b/lib/pure/collections/sequtils.nim index f5db9d3fa..e760c5e02 100644 --- a/lib/pure/collections/sequtils.nim +++ b/lib/pure/collections/sequtils.nim @@ -47,19 +47,15 @@ proc concat*[T](seqs: varargs[seq[T]]): seq[T] = result[i] = itm inc(i) -proc distnct*[T](seq1: seq[T]): seq[T] = +proc deduplicate*[T](seq1: seq[T]): seq[T] = ## Returns a new sequence without duplicates. ## - ## This proc is `misspelled` on purpose to avoid a clash with the keyword - ## ``distinct`` used to `define a derived type incompatible with its base - ## type <manual.html#distinct-type>`_. Example: - ## ## .. code-block:: nimrod ## let ## dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4] ## dup2 = @["a", "a", "c", "d", "d"] - ## unique1 = distnct(dup1) - ## unique2 = distnct(dup2) + ## unique1 = deduplicate(dup1) + ## unique2 = deduplicate(dup2) ## assert unique1 == @[1, 3, 4, 2, 8] ## assert unique2 == @["a", "c", "d"] result = @[] @@ -182,6 +178,24 @@ proc filter*[T](seq1: seq[T], pred: proc(item: T): bool {.closure.}): seq[T] = ## assert f2 == @["yellow"] accumulateResult(filter(seq1, pred)) +proc keepIf*[T](seq1: var seq[T], pred: proc(item: T): bool {.closure.}) = + ## Keeps the items in the passed sequence if they fulfilled the predicate. + ## Same as the ``filter`` proc, but modifies the sequence directly. + ## + ## Example: + ## + ## .. code-block:: nimrod + ## var floats = @[13.0, 12.5, 5.8, 2.0, 6.1, 9.9, 10.1] + ## filter(floats, proc(x: float): bool = x > 10) + ## assert floats == @[13.0, 12.5, 10.1] + var pos = 0 + for i in 0 .. <len(seq1): + if pred(seq1[i]): + if pos != i: + seq1[pos] = seq1[i] + inc(pos) + setLen(seq1, pos) + proc delete*[T](s: var seq[T], first=0, last=0) = ## Deletes in `s` the items at position `first` .. `last`. This modifies ## `s` itself, it does not return a copy. @@ -252,6 +266,27 @@ template filterIt*(seq1, pred: expr): expr {.immediate.} = if pred: result.add(it) result +template keepItIf*(varSeq, pred: expr) = + ## Convenience template around the ``keepIf`` proc to reduce typing. + ## + ## Unlike the `proc` version, the predicate needs to be an expression using + ## the ``it`` variable for testing, like: ``keepItIf("abcxyz", it == 'x')``. + ## Example: + ## + ## .. code-block:: nimrod + ## var candidates = @["foo", "bar", "baz", "foobar"] + ## keepItIf(candidates, it.len == 3 and it[0] == 'b') + ## assert candidates == @["bar", "baz"] + var pos = 0 + for i in 0 .. <len(varSeq): + let it {.inject.} = varSeq[i] + if pred: + if pos != i: + varSeq[pos] = varSeq[i] + inc(pos) + setLen(varSeq, pos) + + template toSeq*(iter: expr): expr {.immediate.} = ## Transforms any iterator into a sequence. ## @@ -387,8 +422,8 @@ when isMainModule: let dup1 = @[1, 1, 3, 4, 2, 2, 8, 1, 4] dup2 = @["a", "a", "c", "d", "d"] - unique1 = distnct(dup1) - unique2 = distnct(dup2) + unique1 = deduplicate(dup1) + unique2 = deduplicate(dup2) assert unique1 == @[1, 3, 4, 2, 8] assert unique2 == @["a", "c", "d"] @@ -418,6 +453,11 @@ when isMainModule: echo($n) # echoes 4, 8, 4 in separate lines + 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) + assert floats == @[13.0, 12.5, 10.1] + block: # filterIt test let temperatures = @[-272.15, -2.0, 24.5, 44.31, 99.9, -113.44] @@ -426,6 +466,11 @@ when isMainModule: assert acceptable == @[-2.0, 24.5, 44.31] assert 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') + assert candidates == @["bar", "baz"] + block: # toSeq test let numeric = @[1, 2, 3, 4, 5, 6, 7, 8, 9] diff --git a/lib/pure/collections/sets.nim b/lib/pure/collections/sets.nim index bc249ed63..4ba67cb2e 100644 --- a/lib/pure/collections/sets.nim +++ b/lib/pure/collections/sets.nim @@ -112,6 +112,10 @@ proc incl*[A](s: var TSet[A], key: A) = ## includes an element `key` in `s`. inclImpl() +proc incl*[A](s: var TSet[A], other: TSet[A]) = + ## includes everything in `other` in `s` + for item in other: incl(s, item) + proc excl*[A](s: var TSet[A], key: A) = ## excludes `key` from the set `s`. var index = rawGet(s, key) @@ -119,6 +123,10 @@ proc excl*[A](s: var TSet[A], key: A) = s.data[index].slot = seDeleted dec(s.counter) +proc excl*[A](s: var TSet[A], other: TSet[A]) = + ## excludes everything in `other` from `s`. + for item in other: excl(s, item) + proc containsOrIncl*[A](s: var TSet[A], key: A): bool = ## returns true if `s` contains `key`, otherwise `key` is included in `s` ## and false is returned. @@ -147,6 +155,43 @@ proc `$`*[A](s: TSet[A]): string = ## The `$` operator for hash sets. dollarImpl() +proc union*[A](s1, s2: TSet[A]): TSet[A] = + ## returns a new set of all items that are contained in at + ## least one of `s1` and `s2` + result = s1 + incl(result, s2) + +proc intersection*[A](s1, s2: TSet[A]): TSet[A] = + ## returns a new set of all items that are contained in both `s1` and `s2` + result = initSet[A](min(s1.data.len, s2.data.len)) + for item in s1: + if item in s2: incl(result, item) + +proc symmetricDifference*[A](s1, s2: TSet[A]): TSet[A] = + ## returns a new set of all items that are contained in either + ## `s1` or `s2`, but not both + result = s1 + for item in s2: + if containsOrIncl(result, item): excl(result, item) + +proc `+`*[A](s1, s2: TSet[A]): TSet[A] {.inline.} = + ## alias for `union` + result = union(s1, s2) + +proc `*`*[A](s1, s2: TSet[A]): TSet[A] {.inline.} = + ## alias for `intersection` + result = intersection(s1, s2) + +proc `-+-`*[A](s1, s2: TSet[A]): TSet[A] {.inline.} = + ## alias for `symmetricDifference` + result = symmetricDifference(s1, s2) + +proc disjoint*[A](s1, s2: TSet[A]): bool = + ## returns true iff `s1` and `s2` have no items in common + for item in s1: + if item in s2: return false + return true + # ------------------------------ ordered set ------------------------------ type @@ -211,6 +256,10 @@ proc incl*[A](s: var TOrderedSet[A], key: A) = ## includes an element `key` in `s`. inclImpl() +proc incl*[A](s: var TSet[A], other: TOrderedSet[A]) = + ## includes everything in `other` in `s` + for item in other: incl(s, item) + proc containsOrIncl*[A](s: var TOrderedSet[A], key: A): bool = ## returns true if `s` contains `key`, otherwise `key` is included in `s` ## and false is returned. diff --git a/lib/pure/collections/tables.nim b/lib/pure/collections/tables.nim index cd28f9af0..ce9df09e1 100644 --- a/lib/pure/collections/tables.nim +++ b/lib/pure/collections/tables.nim @@ -10,6 +10,48 @@ ## The ``tables`` module implements an efficient hash table that is ## a mapping from keys to values. ## +## If you are using simple standard types like ``int`` or ``string`` for the +## keys of the table you won't have any problems, but as soon as you try to use +## a more complex object as a key you will be greeted by a strange compiler +## error:: +## +## Error: type mismatch: got (Person) +## but expected one of: +## hashes.hash(x: openarray[A]): THash +## hashes.hash(x: int): THash +## hashes.hash(x: float): THash +## … +## +## What is happening here is that the types used for table keys require to have +## a ``hash()`` proc which will convert them to a `THash <hashes.html#THash>`_ +## value, and the compiler is listing all the hash functions it knows. After +## you add such a proc for your custom type everything will work. See this +## example: +## +## .. code-block:: nimrod +## type +## Person = object +## firstName, lastName: string +## +## proc hash(x: Person): THash = +## ## 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 +## ## **Note:** The data types declared here have *value semantics*: This means ## that ``=`` performs a copy of the hash table. @@ -25,6 +67,7 @@ type TTable* {.final, myShallow.}[A, B] = object ## generic hash table data: TKeyValuePairSeq[A, B] counter: int + PTable*[A,B] = ref TTable[A, B] when not defined(nimhygiene): {.pragma: dirty.} @@ -103,6 +146,14 @@ proc mget*[A, B](t: var TTable[A, B], key: A): var B = if index >= 0: result = t.data[index].val else: raise newException(EInvalidKey, "key not found: " & $key) +iterator allValues*[A, B](t: TTable[A, B]; key: A): B = + ## iterates over any value in the table `t` that belongs to the given `key`. + var h: THash = hash(key) and high(t.data) + while t.data[h].slot != seEmpty: + if t.data[h].key == key and t.data[h].slot == seFilled: + yield t.data[h].val + h = nextTry(h, high(t.data)) + proc hasKey*[A, B](t: TTable[A, B], key: A): bool = ## returns true iff `key` is in the table `t`. result = rawGet(t, key) >= 0 @@ -190,7 +241,7 @@ proc `$`*[A, B](t: TTable[A, B]): string = ## The `$` operator for hash tables. dollarImpl() -proc `==`*[A, B](s, t: TTable[A, B]): bool = +template equalsImpl() = if s.counter == t.counter: # different insertion orders mean different 'data' seqs, so we have # to use the slow route here: @@ -199,6 +250,9 @@ proc `==`*[A, B](s, t: TTable[A, B]): bool = if t[key] != val: return false return true +proc `==`*[A, B](s, t: TTable[A, B]): bool = + equalsImpl() + proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): TTable[C, B] = ## Index the collection with the proc provided. # TODO: As soon as supported, change collection: A to collection: A[B] @@ -206,6 +260,87 @@ proc indexBy*[A, B, C](collection: A, index: proc(x: B): C): TTable[C, B] = for item in collection: result[index(item)] = item +proc len*[A, B](t: PTable[A, B]): int = + ## returns the number of keys in `t`. + result = t.counter + +iterator pairs*[A, B](t: PTable[A, B]): tuple[key: A, val: B] = + ## iterates over any (key, value) pair in the table `t`. + for h in 0..high(t.data): + if t.data[h].slot == seFilled: yield (t.data[h].key, t.data[h].val) + +iterator mpairs*[A, B](t: PTable[A, B]): tuple[key: A, val: var B] = + ## iterates over any (key, value) pair in the table `t`. The values + ## can be modified. + for h in 0..high(t.data): + if t.data[h].slot == seFilled: yield (t.data[h].key, t.data[h].val) + +iterator keys*[A, B](t: PTable[A, B]): A = + ## iterates over any key in the table `t`. + for h in 0..high(t.data): + if t.data[h].slot == seFilled: yield t.data[h].key + +iterator values*[A, B](t: PTable[A, B]): B = + ## iterates over any value in the table `t`. + for h in 0..high(t.data): + if t.data[h].slot == seFilled: yield t.data[h].val + +iterator mvalues*[A, B](t: PTable[A, B]): var B = + ## iterates over any value in the table `t`. The values can be modified. + for h in 0..high(t.data): + if t.data[h].slot == seFilled: yield t.data[h].val + +proc `[]`*[A, B](t: PTable[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. + result = t[][key] + +proc mget*[A, B](t: PTable[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. + t[].mget(key) + +proc hasKey*[A, B](t: PTable[A, B], key: A): bool = + ## returns true iff `key` is in the table `t`. + result = t[].hasKey(key) + +proc `[]=`*[A, B](t: PTable[A, B], key: A, val: B) = + ## puts a (key, value)-pair into `t`. + t[][key] = val + +proc add*[A, B](t: PTable[A, B], key: A, val: B) = + ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists. + t[].add(key, val) + +proc del*[A, B](t: PTable[A, B], key: A) = + ## deletes `key` from hash table `t`. + t[].del(key) + +proc newTable*[A, B](initialSize=64): PTable[A, B] = + new(result) + result[] = initTable[A, B](initialSize) + +proc newTable*[A, B](pairs: openArray[tuple[key: A, val: B]]): PTable[A, B] = + ## creates a new hash table that contains the given `pairs`. + new(result) + result[] = toTable[A, B](pairs) + +proc `$`*[A, B](t: PTable[A, B]): string = + ## The `$` operator for hash tables. + dollarImpl() + +proc `==`*[A, B](s, t: PTable[A, B]): bool = + equalsImpl() + +proc newTableFrom*[A, B, C](collection: A, index: proc(x: B): C): PTable[C, B] = + ## Index the collection with the proc provided. + # TODO: As soon as supported, change collection: A to collection: A[B] + result = newTable[C, B]() + for item in collection: + result[index(item)] = item + # ------------------------------ ordered table ------------------------------ type @@ -216,6 +351,7 @@ type final, myShallow.}[A, B] = object ## table that remembers insertion order data: TOrderedKeyValuePairSeq[A, B] counter, first, last: int + POrderedTable*[A, B] = ref TOrderedTable[A, B] proc len*[A, B](t: TOrderedTable[A, B]): int {.inline.} = ## returns the number of keys in `t`. @@ -376,6 +512,96 @@ proc sort*[A, B](t: var TOrderedTable[A, B], t.first = list t.last = tail +proc len*[A, B](t: POrderedTable[A, B]): int {.inline.} = + ## returns the number of keys in `t`. + result = t.counter + +template forAllOrderedPairs(yieldStmt: stmt) {.dirty, immediate.} = + 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: POrderedTable[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: POrderedTable[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: POrderedTable[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: POrderedTable[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: POrderedTable[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 `[]`*[A, B](t: POrderedTable[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. + result = t[][key] + +proc mget*[A, B](t: POrderedTable[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. + result = t[].mget(key) + +proc hasKey*[A, B](t: POrderedTable[A, B], key: A): bool = + ## returns true iff `key` is in the table `t`. + result = t[].hasKey(key) + +proc `[]=`*[A, B](t: POrderedTable[A, B], key: A, val: B) = + ## puts a (key, value)-pair into `t`. + t[][key] = val + +proc add*[A, B](t: POrderedTable[A, B], key: A, val: B) = + ## puts a new (key, value)-pair into `t` even if ``t[key]`` already exists. + t[].add(key, val) + +proc newOrderedTable*[A, B](initialSize=64): POrderedTable[A, B] = + ## creates a new ordered hash table that is empty. + ## + ## `initialSize` needs to be a power of two. If you need to accept runtime + ## values for this you could use the ``nextPowerOfTwo`` proc from the + ## `math <math.html>`_ module. + new(result) + result[] = initOrderedTable[A, B]() + +proc newOrderedTable*[A, B](pairs: openArray[tuple[key: A, + val: B]]): POrderedTable[A, B] = + ## creates a new ordered hash table that contains the given `pairs`. + result = newOrderedTable[A, B](nextPowerOfTwo(pairs.len+10)) + for key, val in items(pairs): result[key] = val + +proc `$`*[A, B](t: POrderedTable[A, B]): string = + ## The `$` operator for ordered hash tables. + dollarImpl() + +proc sort*[A, B](t: POrderedTable[A, B], + cmp: proc (x,y: tuple[key: A, val: B]): int) = + ## sorts `t` according to `cmp`. This modifies the internal list + ## that kept the insertion order, so insertion order is lost after this + ## call but key lookup and insertions remain possible after `sort` (in + ## contrast to the `sort` for count tables). + t[].sort(cmp) + # ------------------------------ count tables ------------------------------- type @@ -383,6 +609,7 @@ type A] = object ## table that counts the number of each key data: seq[tuple[key: A, val: int]] counter: int + PCountTable*[A] = ref TCountTable[A] proc len*[A](t: TCountTable[A]): int = ## returns the number of keys in `t`. @@ -526,3 +753,118 @@ proc sort*[A](t: var TCountTable[A]) = if j < h: break if h == 1: break +proc len*[A](t: PCountTable[A]): int = + ## returns the number of keys in `t`. + result = t.counter + +iterator pairs*[A](t: PCountTable[A]): tuple[key: A, val: int] = + ## iterates over any (key, value) pair in the table `t`. + for h in 0..high(t.data): + if t.data[h].val != 0: yield (t.data[h].key, t.data[h].val) + +iterator mpairs*[A](t: PCountTable[A]): tuple[key: A, val: var int] = + ## iterates over any (key, value) pair in the table `t`. The values can + ## be modified. + for h in 0..high(t.data): + if t.data[h].val != 0: yield (t.data[h].key, t.data[h].val) + +iterator keys*[A](t: PCountTable[A]): A = + ## iterates over any key in the table `t`. + for h in 0..high(t.data): + if t.data[h].val != 0: yield t.data[h].key + +iterator values*[A](t: PCountTable[A]): int = + ## iterates over any value in the table `t`. + for h in 0..high(t.data): + if t.data[h].val != 0: yield t.data[h].val + +iterator mvalues*[A](t: PCountTable[A]): var int = + ## iterates over any value in the table `t`. The values can be modified. + for h in 0..high(t.data): + if t.data[h].val != 0: yield t.data[h].val + +proc `[]`*[A](t: PCountTable[A], key: A): int = + ## retrieves the value at ``t[key]``. If `key` is not in `t`, + ## 0 is returned. One can check with ``hasKey`` whether the key + ## exists. + result = t[][key] + +proc mget*[A](t: PCountTable[A], key: A): var int = + ## retrieves the value at ``t[key]``. The value can be modified. + ## If `key` is not in `t`, the ``EInvalidKey`` exception is raised. + result = t[].mget(key) + +proc hasKey*[A](t: PCountTable[A], key: A): bool = + ## returns true iff `key` is in the table `t`. + result = t[].hasKey(key) + +proc `[]=`*[A](t: PCountTable[A], key: A, val: int) = + ## puts a (key, value)-pair into `t`. `val` has to be positive. + assert val > 0 + t[][key] = val + +proc newCountTable*[A](initialSize=64): PCountTable[A] = + ## creates a new count table that is empty. + ## + ## `initialSize` needs to be a power of two. If you need to accept runtime + ## values for this you could use the ``nextPowerOfTwo`` proc from the + ## `math <math.html>`_ module. + new(result) + result[] = initCountTable[A](initialSize) + +proc newCountTable*[A](keys: openArray[A]): PCountTable[A] = + ## creates a new count table with every key in `keys` having a count of 1. + result = newCountTable[A](nextPowerOfTwo(keys.len+10)) + for key in items(keys): result[key] = 1 + +proc `$`*[A](t: PCountTable[A]): string = + ## The `$` operator for count tables. + dollarImpl() + +proc inc*[A](t: PCountTable[A], key: A, val = 1) = + ## increments `t[key]` by `val`. + t[].inc(key, val) + +proc smallest*[A](t: PCountTable[A]): tuple[key: A, val: int] = + ## returns the largest (key,val)-pair. Efficiency: O(n) + t[].smallest + +proc largest*[A](t: PCountTable[A]): tuple[key: A, val: int] = + ## returns the (key,val)-pair with the largest `val`. Efficiency: O(n) + t[].largest + +proc sort*[A](t: PCountTable[A]) = + ## sorts the count table so that the entry with the highest counter comes + ## first. This is destructive! You must not modify `t` afterwards! + ## You can use the iterators `pairs`, `keys`, and `values` to iterate over + ## `t` in the sorted order. + t[].sort + +when isMainModule: + type + Person = object + firstName, lastName: string + + proc hash(x: Person): THash = + ## 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 diff --git a/lib/pure/concurrency/cpuinfo.nim b/lib/pure/concurrency/cpuinfo.nim new file mode 100644 index 000000000..dfa819f64 --- /dev/null +++ b/lib/pure/concurrency/cpuinfo.nim @@ -0,0 +1,58 @@ +# +# +# Nimrod's Runtime Library +# (c) Copyright 2014 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module implements procs to determine the number of CPUs / cores. + +include "system/inclrtl" + +import strutils, os + +when not defined(windows): + import posix + +when defined(linux): + import linux + +when defined(macosx) or defined(bsd): + const + CTL_HW = 6 + HW_AVAILCPU = 25 + HW_NCPU = 3 + proc sysctl(x: ptr array[0..3, cint], y: cint, z: pointer, + a: var csize, b: pointer, c: int): cint {. + importc: "sysctl", header: "<sys/sysctl.h>".} + +proc countProcessors*(): int {.rtl, extern: "ncpi$1".} = + ## returns the numer of the processors/cores the machine has. + ## Returns 0 if it cannot be detected. + when defined(windows): + var x = getEnv("NUMBER_OF_PROCESSORS") + if x.len > 0: result = parseInt(x.string) + elif defined(macosx) or defined(bsd): + var + mib: array[0..3, cint] + numCPU: int + len: csize + mib[0] = CTL_HW + mib[1] = HW_AVAILCPU + len = sizeof(numCPU) + discard sysctl(addr(mib), 2, addr(numCPU), len, nil, 0) + if numCPU < 1: + mib[1] = HW_NCPU + discard sysctl(addr(mib), 2, addr(numCPU), len, nil, 0) + result = numCPU + elif defined(hpux): + result = mpctl(MPC_GETNUMSPUS, nil, nil) + elif defined(irix): + var SC_NPROC_ONLN {.importc: "_SC_NPROC_ONLN", header: "<unistd.h>".}: cint + result = sysconf(SC_NPROC_ONLN) + else: + result = sysconf(SC_NPROCESSORS_ONLN) + if result <= 0: result = 1 + diff --git a/lib/pure/concurrency/cpuload.nim b/lib/pure/concurrency/cpuload.nim new file mode 100644 index 000000000..3cf6a7392 --- /dev/null +++ b/lib/pure/concurrency/cpuload.nim @@ -0,0 +1,96 @@ +# +# +# Nimrod's Runtime Library +# (c) Copyright 2014 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## This module implements a helper for a thread pool to determine whether +## creating a thread is a good idea. + +when defined(windows): + import winlean, os, strutils, math + + proc `-`(a, b: TFILETIME): int64 = a.rdFileTime - b.rdFileTime +elif defined(linux): + from cpuinfo import countProcessors + +type + ThreadPoolAdvice* = enum + doNothing, + doCreateThread, # create additional thread for throughput + doShutdownThread # too many threads are busy, shutdown one + + ThreadPoolState* = object + when defined(windows): + prevSysKernel, prevSysUser, prevProcKernel, prevProcUser: TFILETIME + calls*: int + +proc advice*(s: var ThreadPoolState): ThreadPoolAdvice = + when defined(windows): + var + sysIdle, sysKernel, sysUser, + procCreation, procExit, procKernel, procUser: TFILETIME + if getSystemTimes(sysIdle, sysKernel, sysUser) == 0 or + getProcessTimes(THandle(-1), procCreation, procExit, + procKernel, procUser) == 0: + return doNothing + if s.calls > 0: + let + sysKernelDiff = sysKernel - s.prevSysKernel + sysUserDiff = sysUser - s.prevSysUser + + procKernelDiff = procKernel - s.prevProcKernel + procUserDiff = procUser - s.prevProcUser + + sysTotal = int(sysKernelDiff + sysUserDiff) + procTotal = int(procKernelDiff + procUserDiff) + # total CPU usage < 85% --> create a new worker thread. + # Measurements show that 100% and often even 90% is not reached even + # if all my cores are busy. + if sysTotal == 0 or procTotal / sysTotal < 0.85: + result = doCreateThread + s.prevSysKernel = sysKernel + s.prevSysUser = sysUser + s.prevProcKernel = procKernel + s.prevProcUser = procUser + elif defined(linux): + proc fscanf(c: TFile, frmt: cstring) {.varargs, importc, + header: "<stdio.h>".} + + var f = open("/proc/loadavg") + var b: float + var busy, total: int + fscanf(f,"%lf %lf %lf %ld/%ld", + addr b, addr b, addr b, addr busy, addr total) + f.close() + let cpus = countProcessors() + if busy-1 < cpus: + result = doCreateThread + elif busy-1 >= cpus*2: + result = doShutdownThread + else: + result = doNothing + else: + # XXX implement this for other OSes + result = doNothing + inc s.calls + +when isMainModule: + proc busyLoop() = + while true: + discard random(80) + os.sleep(100) + + spawn busyLoop() + spawn busyLoop() + spawn busyLoop() + spawn busyLoop() + + var s: ThreadPoolState + + for i in 1 .. 70: + echo advice(s) + os.sleep(1000) diff --git a/lib/pure/concurrency/threadpool.nim b/lib/pure/concurrency/threadpool.nim new file mode 100644 index 000000000..fd1041918 --- /dev/null +++ b/lib/pure/concurrency/threadpool.nim @@ -0,0 +1,378 @@ +# +# +# Nimrod's Runtime Library +# (c) Copyright 2014 Andreas Rumpf +# +# See the file "copying.txt", included in this +# distribution, for details about the copyright. +# + +## Implements Nimrod's 'spawn'. + +import cpuinfo, cpuload, locks + +{.push stackTrace:off.} + +type + CondVar = object + c: TCond + L: TLock + counter: int + +proc createCondVar(): CondVar = + initCond(result.c) + initLock(result.L) + +proc destroyCondVar(cv: var CondVar) {.inline.} = + deinitCond(cv.c) + deinitLock(cv.L) + +proc await(cv: var CondVar) = + acquire(cv.L) + while cv.counter <= 0: + wait(cv.c, cv.L) + dec cv.counter + release(cv.L) + +proc signal(cv: var CondVar) = + acquire(cv.L) + inc cv.counter + release(cv.L) + signal(cv.c) + +const CacheLineSize = 32 # true for most archs + +type + Barrier {.compilerProc.} = object + entered: int + cv: CondVar # condvar takes 3 words at least + when sizeof(int) < 8: + cacheAlign: array[CacheLineSize-4*sizeof(int), byte] + left: int + cacheAlign2: array[CacheLineSize-sizeof(int), byte] + interest: bool ## wether the master is interested in the "all done" event + +proc barrierEnter(b: ptr Barrier) {.compilerProc, inline.} = + # due to the signaling between threads, it is ensured we are the only + # one with access to 'entered' so we don't need 'atomicInc' here: + inc b.entered + # also we need no 'fence' instructions here as soon 'nimArgsPassingDone' + # will be called which already will perform a fence for us. + +proc barrierLeave(b: ptr Barrier) {.compilerProc, inline.} = + atomicInc b.left + when not defined(x86): fence() + if b.interest and b.left == b.entered: signal(b.cv) + +proc openBarrier(b: ptr Barrier) {.compilerProc, inline.} = + b.entered = 0 + b.left = 0 + b.interest = false + +proc closeBarrier(b: ptr Barrier) {.compilerProc.} = + fence() + if b.left != b.entered: + b.cv = createCondVar() + fence() + b.interest = true + fence() + while b.left != b.entered: await(b.cv) + destroyCondVar(b.cv) + +{.pop.} + +# ---------------------------------------------------------------------------- + +type + foreign* = object ## a region that indicates the pointer comes from a + ## foreign thread heap. + AwaitInfo = object + cv: CondVar + idx: int + + FlowVarBase* = ref FlowVarBaseObj ## untyped base class for 'FlowVar[T]' + FlowVarBaseObj = object of TObject + ready, usesCondVar: bool + cv: CondVar #\ + # for 'awaitAny' support + ai: ptr AwaitInfo + idx: int + data: pointer # we incRef and unref it to keep it alive + owner: pointer # ptr Worker + + FlowVarObj[T] = object of FlowVarBaseObj + blob: T + + FlowVar*{.compilerProc.}[T] = ref FlowVarObj[T] ## a data flow variable + + ToFreeQueue = object + len: int + lock: TLock + empty: TCond + data: array[512, pointer] + + WorkerProc = proc (thread, args: pointer) {.nimcall, gcsafe.} + Worker = object + taskArrived: CondVar + taskStarted: CondVar #\ + # task data: + f: WorkerProc + data: pointer + ready: bool # put it here for correct alignment! + initialized: bool # whether it has even been initialized + shutdown: bool # the pool requests to shut down this worker thread + q: ToFreeQueue + +proc await*(fv: FlowVarBase) = + ## waits until the value for the flowVar arrives. Usually it is not necessary + ## to call this explicitly. + if fv.usesCondVar: + fv.usesCondVar = false + await(fv.cv) + destroyCondVar(fv.cv) + +proc finished(fv: FlowVarBase) = + doAssert fv.ai.isNil, "flowVar is still attached to an 'awaitAny'" + # we have to protect against the rare cases where the owner of the flowVar + # simply disregards the flowVar and yet the "flowVarr" has not yet written + # anything to it: + await(fv) + if fv.data.isNil: return + let owner = cast[ptr Worker](fv.owner) + let q = addr(owner.q) + var waited = false + while true: + acquire(q.lock) + if q.len < q.data.len: + q.data[q.len] = fv.data + inc q.len + release(q.lock) + break + else: + # the queue is exhausted! We block until it has been cleaned: + release(q.lock) + wait(q.empty, q.lock) + waited = true + fv.data = nil + # wakeup other potentially waiting threads: + if waited: signal(q.empty) + +proc cleanFlowVars(w: ptr Worker) = + let q = addr(w.q) + acquire(q.lock) + for i in 0 .. <q.len: + GC_unref(cast[PObject](q.data[i])) + q.len = 0 + release(q.lock) + signal(q.empty) + +proc fvFinalizer[T](fv: FlowVar[T]) = finished(fv) + +proc nimCreateFlowVar[T](): FlowVar[T] {.compilerProc.} = + new(result, fvFinalizer) + +proc nimFlowVarCreateCondVar(fv: FlowVarBase) {.compilerProc.} = + fv.cv = createCondVar() + fv.usesCondVar = true + +proc nimFlowVarSignal(fv: FlowVarBase) {.compilerProc.} = + if fv.ai != nil: + acquire(fv.ai.cv.L) + fv.ai.idx = fv.idx + inc fv.ai.cv.counter + release(fv.ai.cv.L) + signal(fv.ai.cv.c) + if fv.usesCondVar: signal(fv.cv) + +proc awaitAndThen*[T](fv: FlowVar[T]; action: proc (x: T) {.closure.}) = + ## blocks until the ``fv`` is available and then passes its value + ## to ``action``. Note that due to Nimrod's parameter passing semantics this + ## means that ``T`` doesn't need to be copied and so ``awaitAndThen`` can + ## sometimes be more efficient than ``^``. + await(fv) + when T is string or T is seq: + action(cast[T](fv.data)) + elif T is ref: + {.error: "'awaitAndThen' not available for FlowVar[ref]".} + else: + action(fv.blob) + finished(fv) + +proc `^`*[T](fv: FlowVar[ref T]): foreign ptr T = + ## blocks until the value is available and then returns this value. + await(fv) + result = cast[foreign ptr T](fv.data) + +proc `^`*[T](fv: FlowVar[T]): T = + ## blocks until the value is available and then returns this value. + await(fv) + when T is string or T is seq: + result = cast[T](fv.data) + else: + result = fv.blob + +proc awaitAny*(flowVars: openArray[FlowVarBase]): int = + ## awaits any of the given flowVars. Returns the index of one flowVar for + ## which a value arrived. A flowVar only supports one call to 'awaitAny' at + ## the same time. That means if you await([a,b]) and await([b,c]) the second + ## call will only await 'c'. If there is no flowVar left to be able to wait + ## on, -1 is returned. + ## **Note**: This results in non-deterministic behaviour and so should be + ## avoided. + var ai: AwaitInfo + ai.cv = createCondVar() + var conflicts = 0 + for i in 0 .. flowVars.high: + if cas(addr flowVars[i].ai, nil, addr ai): + flowVars[i].idx = i + else: + inc conflicts + if conflicts < flowVars.len: + await(ai.cv) + result = ai.idx + for i in 0 .. flowVars.high: + discard cas(addr flowVars[i].ai, addr ai, nil) + else: + result = -1 + destroyCondVar(ai.cv) + +proc nimArgsPassingDone(p: pointer) {.compilerProc.} = + let w = cast[ptr Worker](p) + signal(w.taskStarted) + +const + MaxThreadPoolSize* = 256 ## maximal size of the thread pool. 256 threads + ## should be good enough for anybody ;-) + +var + currentPoolSize: int + maxPoolSize = MaxThreadPoolSize + minPoolSize = 4 + gSomeReady = createCondVar() + readyWorker: ptr Worker + +proc slave(w: ptr Worker) {.thread.} = + while true: + w.ready = true + readyWorker = w + signal(gSomeReady) + await(w.taskArrived) + assert(not w.ready) + w.f(w, w.data) + if w.q.len != 0: w.cleanFlowVars + if w.shutdown: + w.shutdown = false + atomicDec currentPoolSize + +proc setMinPoolSize*(size: range[1..MaxThreadPoolSize]) = + ## sets the minimal thread pool size. The default value of this is 4. + minPoolSize = size + +proc setMaxPoolSize*(size: range[1..MaxThreadPoolSize]) = + ## sets the minimal thread pool size. The default value of this + ## is ``MaxThreadPoolSize``. + maxPoolSize = size + +var + workers: array[MaxThreadPoolSize, TThread[ptr Worker]] + workersData: array[MaxThreadPoolSize, Worker] + +proc activateThread(i: int) {.noinline.} = + workersData[i].taskArrived = createCondVar() + workersData[i].taskStarted = createCondVar() + workersData[i].initialized = true + initCond(workersData[i].q.empty) + initLock(workersData[i].q.lock) + createThread(workers[i], slave, addr(workersData[i])) + +proc setup() = + currentPoolSize = min(countProcessors(), MaxThreadPoolSize) + readyWorker = addr(workersData[0]) + for i in 0.. <currentPoolSize: activateThread(i) + +proc preferSpawn*(): bool = + ## Use this proc to determine quickly if a 'spawn' or a direct call is + ## preferable. If it returns 'true' a 'spawn' may make sense. In general + ## it is not necessary to call this directly; use 'spawnX' instead. + result = gSomeReady.counter > 0 + +proc spawn*(call: expr): expr {.magic: "Spawn".} + ## always spawns a new task, so that the 'call' is never executed on + ## the calling thread. 'call' has to be proc call 'p(...)' where 'p' + ## is gcsafe and has a return type that is either 'void' or compatible + ## with ``FlowVar[T]``. + +template spawnX*(call: expr): expr = + ## spawns a new task if a CPU core is ready, otherwise executes the + ## call in the calling thread. Usually it is advised to + ## use 'spawn' in order to not block the producer for an unknown + ## amount of time. 'call' has to be proc call 'p(...)' where 'p' + ## is gcsafe and has a return type that is either 'void' or compatible + ## with ``FlowVar[T]``. + (if preferSpawn(): spawn call else: call) + +proc parallel*(body: stmt) {.magic: "Parallel".} + ## a parallel section can be used to execute a block in parallel. ``body`` + ## has to be in a DSL that is a particular subset of the language. Please + ## refer to the manual for further information. + +var + state: ThreadPoolState + stateLock: TLock + +initLock stateLock + +proc selectWorker(w: ptr Worker; fn: WorkerProc; data: pointer): bool = + if cas(addr w.ready, true, false): + w.data = data + w.f = fn + signal(w.taskArrived) + await(w.taskStarted) + result = true + +proc nimSpawn(fn: WorkerProc; data: pointer) {.compilerProc.} = + # implementation of 'spawn' that is used by the code generator. + while true: + if selectWorker(readyWorker, fn, data): return + for i in 0.. <currentPoolSize: + if selectWorker(addr(workersData[i]), fn, data): return + # determine what to do, but keep in mind this is expensive too: + # state.calls < maxPoolSize: warmup phase + # (state.calls and 127) == 0: periodic check + if state.calls < maxPoolSize or (state.calls and 127) == 0: + # ensure the call to 'advice' is atomic: + if tryAcquire(stateLock): + case advice(state) + of doNothing: discard + of doCreateThread: + if currentPoolSize < maxPoolSize: + if not workersData[currentPoolSize].initialized: + activateThread(currentPoolSize) + let w = addr(workersData[currentPoolSize]) + atomicInc currentPoolSize + if selectWorker(w, fn, data): + release(stateLock) + return + # else we didn't succeed but some other thread, so do nothing. + of doShutdownThread: + if currentPoolSize > minPoolSize: + let w = addr(workersData[currentPoolSize-1]) + w.shutdown = true + # we don't free anything here. Too dangerous. + release(stateLock) + # else the acquire failed, but this means some + # other thread succeeded, so we don't need to do anything here. + await(gSomeReady) + +proc sync*() = + ## a simple barrier to wait for all spawn'ed tasks. If you need more elaborate + ## waiting, you have to use an explicit barrier. + while true: + var allReady = true + for i in 0 .. <currentPoolSize: + if not allReady: break + allReady = allReady and workersData[i].ready + if allReady: break + await(gSomeReady) + +setup() diff --git a/lib/pure/fsmonitor.nim b/lib/pure/fsmonitor.nim index d6584c1a0..b35466771 100644 --- a/lib/pure/fsmonitor.nim +++ b/lib/pure/fsmonitor.nim @@ -119,8 +119,8 @@ proc getEvent(m: PFSMonitor, fd: cint): seq[TMonitorEvent] = var mev: TMonitorEvent mev.wd = event.wd if event.len.int != 0: - mev.name = newString(event.len.int) - copyMem(addr(mev.name[0]), addr event.name, event.len.int-1) + let cstr = event.name.addr.cstring + mev.name = $cstr else: mev.name = "" @@ -211,4 +211,4 @@ when isMainModule: while true: if not disp.poll(): break - \ No newline at end of file + diff --git a/lib/pure/future.nim b/lib/pure/future.nim index e0e4c4176..b7df05207 100644 --- a/lib/pure/future.nim +++ b/lib/pure/future.nim @@ -18,7 +18,6 @@ proc createProcType(p, b: PNimrodNode): PNimrodNode {.compileTime.} = result = newNimNode(nnkProcTy) var formalParams = newNimNode(nnkFormalParams) - expectKind(b, nnkIdent) formalParams.add b case p.kind diff --git a/lib/pure/hashes.nim b/lib/pure/hashes.nim index 5784a96c1..740355e55 100644 --- a/lib/pure/hashes.nim +++ b/lib/pure/hashes.nim @@ -8,7 +8,34 @@ # ## This module implements efficient computations of hash values for diverse -## Nimrod types. +## Nimrod types. All the procs are based on these two building blocks: the `!& +## proc <#!&>`_ used to start or mix a hash value, and the `!$ proc <#!$>`_ +## used to *finish* the hash value. If you want to implement hash procs for +## your custom types you will end up writing the following kind of skeleton of +## code: +## +## .. code-block:: nimrod +## proc hash(x: Something): THash = +## ## Computes a THash from `x`. +## var h: THash = 0 +## # Iterate over parts of `x`. +## for xAtom in x: +## # Mix the atom with the partial hash. +## h = h !& xAtom +## # Finish the hash. +## result = !$h +## +## If your custom types contain fields for which there already is a hash proc, +## like for example objects made up of ``strings``, you can simply hash +## together the hash value of the individual fields: +## +## .. code-block:: nimrod +## proc hash(x: Something): THash = +## ## Computes a THash from `x`. +## var h: THash = 0 +## h = h &! hash(x.foo) +## h = h &! hash(x.bar) +## result = !$h import strutils diff --git a/lib/pure/httpclient.nim b/lib/pure/httpclient.nim index be06a7b8e..9bacc80d6 100644 --- a/lib/pure/httpclient.nim +++ b/lib/pure/httpclient.nim @@ -654,7 +654,7 @@ when isMainModule: resp = await client.request("http://nimrod-lang.org/download.html") echo("Got response: ", resp.status) - main() + asyncCheck main() runForever() else: diff --git a/lib/pure/httpserver.nim b/lib/pure/httpserver.nim index 8de708c5d..885742b64 100644 --- a/lib/pure/httpserver.nim +++ b/lib/pure/httpserver.nim @@ -192,7 +192,7 @@ when false: if path[path.len-1] == '/' or existsDir(path): path = path / "index.html" - if not ExistsFile(path): + if not existsFile(path): discardHeaders(client) notFound(client) else: diff --git a/lib/pure/json.nim b/lib/pure/json.nim index 4250847e5..508e564c5 100644 --- a/lib/pure/json.nim +++ b/lib/pure/json.nim @@ -619,6 +619,44 @@ proc `%`*(elements: openArray[PJsonNode]): PJsonNode = newSeq(result.elems, elements.len) for i, p in pairs(elements): result.elems[i] = p +proc `==`* (a,b: PJsonNode): bool = + ## Check two nodes for equality + if a.kind != b.kind: false + else: + case a.kind + of JString: + a.str == b.str + of JInt: + a.num == b.num + of JFloat: + a.fnum == b.fnum + of JBool: + a.bval == b.bval + of JNull: + true + of JArray: + a.elems == b.elems + of JObject: + a.fields == b.fields + +proc hash* (n:PJsonNode): THash = + ## Compute the hash for a JSON node + case n.kind + of JArray: + result = hash(n.elems) + of JObject: + result = hash(n.fields) + of JInt: + result = hash(n.num) + of JFloat: + result = hash(n.fnum) + of JBool: + result = hash(n.bval.int) + of JString: + result = hash(n.str) + of JNull: + result = hash(0) + proc len*(n: PJsonNode): int = ## If `n` is a `JArray`, it returns the number of elements. ## If `n` is a `JObject`, it returns the number of pairs. @@ -629,7 +667,9 @@ proc len*(n: PJsonNode): int = else: discard proc `[]`*(node: PJsonNode, name: string): PJsonNode = - ## Gets a field from a `JObject`. Returns nil if the key is not found. + ## Gets a field from a `JObject`, which must not be nil. + ## If the value at `name` does not exist, returns nil + assert(not isNil(node)) assert(node.kind == JObject) for key, item in items(node.fields): if key == name: @@ -637,7 +677,9 @@ proc `[]`*(node: PJsonNode, name: string): PJsonNode = return nil proc `[]`*(node: PJsonNode, index: int): PJsonNode = - ## Gets the node at `index` in an Array. + ## Gets the node at `index` in an Array. Result is undefined if `index` + ## is out of bounds + assert(not isNil(node)) assert(node.kind == JArray) return node.elems[index] @@ -671,6 +713,23 @@ proc `[]=`*(obj: PJsonNode, key: string, val: PJsonNode) = return obj.fields.add((key, val)) +proc `{}`*(node: PJsonNode, key: string): PJsonNode = + ## Transverses the node and gets the given value. If any of the + ## names does not exist, returns nil + result = node + if isNil(node): return nil + result = result[key] + +proc `{}=`*(node: PJsonNode, names: varargs[string], value: PJsonNode) = + ## Transverses the node and tries to set the value at the given location + ## to `value` If any of the names are missing, they are added + var node = node + for i in 0..(names.len-2): + if isNil(node[names[i]]): + node[names[i]] = newJObject() + node = node[names[i]] + node[names[names.len-1]] = value + proc delete*(obj: PJsonNode, key: string) = ## Deletes ``obj[key]`` preserving the order of the other (key, value)-pairs. assert(obj.kind == JObject) @@ -996,6 +1055,28 @@ when isMainModule: raise newException(EInvalidValue, "That line was expected to fail") except EInvalidIndex: echo() + let testJson = parseJson"""{ "a": [1, 2, 3, 4], "b": "asd" }""" + # nil passthrough + assert(testJson{"doesnt_exist"}{"anything"}.isNil) + testJson{["c", "d"]} = %true + assert(testJson["c"]["d"].bval) + + # Bounds checking + try: + let a = testJson["a"][9] + assert(false, "EInvalidIndex not thrown") + except EInvalidIndex: + discard + try: + let a = testJson["a"][-1] + assert(false, "EInvalidIndex not thrown") + except EInvalidIndex: + discard + try: + assert(testJson["a"][0].num == 1, "Index doesn't correspond to its value") + except: + assert(false, "EInvalidIndex thrown for valid index") + discard """ while true: var json = stdin.readLine() diff --git a/lib/pure/math.nim b/lib/pure/math.nim index e4aecd272..2f7a696b9 100644 --- a/lib/pure/math.nim +++ b/lib/pure/math.nim @@ -10,7 +10,8 @@ ## Constructive mathematics is naturally typed. -- Simon Thompson ## ## Basic math routines for Nimrod. -## This module is available for the JavaScript target. +## This module is available for the `JavaScript target +## <backends.html#the-javascript-target>`_. include "system/inclrtl" @@ -135,12 +136,12 @@ proc random*(max: int): int {.gcsafe.} ## which initializes the random number generator with a "random" ## number, i.e. a tickcount. -when not defined(windows): - proc random*(max: float): float {.gcsafe.} - ## returns a random number in the range 0..<max. The sequence of - ## random number is always the same, unless `randomize` is called - ## which initializes the random number generator with a "random" - ## number, i.e. a tickcount. This is currently not supported for windows. +proc random*(max: float): float {.gcsafe.} + ## returns a random number in the range 0..<max. The sequence of + ## random number is always the same, unless `randomize` is called + ## which initializes the random number generator with a "random" + ## number, i.e. a tickcount. This has a 16-bit resolution on windows + ## and a 48-bit resolution on other platforms. proc randomize*() {.gcsafe.} ## initializes the random number generator with a "random" @@ -205,7 +206,14 @@ when not defined(JS): proc drand48(): float {.importc: "drand48", header: "<stdlib.h>".} proc random(max: float): float = result = drand48() * max - + when defined(windows): + proc random(max: float): float = + # we are hardcodeing this because + # importcing macros is extremely problematic + # and because the value is publicly documented + # on MSDN and very unlikely to change + const rand_max = 32767 + result = (float(rand()) / float(rand_max)) * max proc randomize() = randomize(cast[int](epochTime())) diff --git a/lib/pure/memfiles.nim b/lib/pure/memfiles.nim index 807f3da43..31fefc6c8 100644 --- a/lib/pure/memfiles.nim +++ b/lib/pure/memfiles.nim @@ -74,9 +74,22 @@ proc unmapMem*(f: var TMemFile, p: pointer, size: int) = proc open*(filename: string, mode: TFileMode = fmRead, mappedSize = -1, offset = 0, newFileSize = -1): TMemFile = ## opens a memory mapped file. If this fails, ``EOS`` is raised. - ## `newFileSize` can only be set if the file is not opened with ``fmRead`` - ## access. `mappedSize` and `offset` can be used to map only a slice of - ## the file. + ## `newFileSize` can only be set if the file does not exist and is opened + ## with write access (e.g., with fmReadWrite). `mappedSize` and `offset` + ## can be used to map only a slice of the file. Example: + ## + ## .. code-block:: nimrod + ## var + ## mm, mm_full, mm_half: TMemFile + ## + ## mm = memfiles.open("/tmp/test.mmap", mode = fmWrite, newFileSize = 1024) # Create a new file + ## mm.close() + ## + ## # Read the whole file, would fail if newFileSize was set + ## mm_full = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = -1) + ## + ## # Read the first 512 bytes + ## mm_half = memfiles.open("/tmp/test.mmap", mode = fmReadWrite, mappedSize = 512) # The file can be resized only when write mode is used: assert newFileSize == -1 or mode != fmRead @@ -165,8 +178,11 @@ proc open*(filename: string, mode: TFileMode = fmRead, if newFileSize != -1: flags = flags or O_CREAT or O_TRUNC + var permissions_mode = S_IRUSR or S_IWUSR + result.handle = open(filename, flags, permissions_mode) + else: + result.handle = open(filename, flags) - result.handle = open(filename, flags) if result.handle == -1: # XXX: errno is supposed to be set here # Is there an exception that wraps it? diff --git a/lib/pure/net.nim b/lib/pure/net.nim index 74739630b..ddc2bbe2d 100644 --- a/lib/pure/net.nim +++ b/lib/pure/net.nim @@ -11,7 +11,7 @@ {.deadCodeElim: on.} import rawsockets, os, strutils, unsigned, parseutils, times -export TPort +export TPort, `$` const useWinVersion = defined(Windows) or defined(nimdoc) @@ -350,6 +350,30 @@ type ETimeout* = object of ESynch + TSocketFlags* {.pure.} = enum + Peek, + SafeDisconn ## Ensures disconnection exceptions (ECONNRESET, EPIPE etc) are not thrown. + +proc isDisconnectionError*(flags: set[TSocketFlags], + lastError: TOSErrorCode): bool = + ## Determines whether ``lastError`` is a disconnection error. Only does this + ## if flags contains ``SafeDisconn``. + when useWinVersion: + TSocketFlags.SafeDisconn in flags and + lastError.int32 in {WSAECONNRESET, WSAECONNABORTED, WSAENETRESET, + WSAEDISCON} + else: + TSocketFlags.SafeDisconn in flags and + lastError.int32 in {ECONNRESET, EPIPE, ENETRESET} + +proc toOSFlags*(socketFlags: set[TSocketFlags]): cint = + ## Converts the flags into the underlying OS representation. + for f in socketFlags: + case f + of TSocketFlags.Peek: + result = result or MSG_PEEK + of TSocketFlags.SafeDisconn: continue + proc createSocket(fd: TSocketHandle, isBuff: bool): PSocket = assert fd != osInvalidSocket new(result) @@ -470,7 +494,8 @@ when defined(ssl): if SSLSetFd(socket.sslHandle, socket.fd) != 1: SSLError() -proc socketError*(socket: PSocket, err: int = -1, async = false) = +proc socketError*(socket: PSocket, err: int = -1, async = false, + lastError = (-1).TOSErrorCode) = ## Raises an EOS error based on the error code returned by ``SSLGetError`` ## (for SSL sockets) and ``osLastError`` otherwise. ## @@ -500,17 +525,17 @@ proc socketError*(socket: PSocket, err: int = -1, async = false) = else: SSLError("Unknown Error") if err == -1 and not (when defined(ssl): socket.isSSL else: false): - let lastError = osLastError() + let lastE = if lastError.int == -1: osLastError() else: lastError if async: when useWinVersion: - if lastError.int32 == WSAEWOULDBLOCK: + if lastE.int32 == WSAEWOULDBLOCK: return - else: osError(lastError) + else: osError(lastE) else: - if lastError.int32 == EAGAIN or lastError.int32 == EWOULDBLOCK: + if lastE.int32 == EAGAIN or lastE.int32 == EWOULDBLOCK: return - else: osError(lastError) - else: osError(lastError) + else: osError(lastE) + else: osError(lastE) proc listen*(socket: PSocket, backlog = SOMAXCONN) {.tags: [FReadIO].} = ## Marks ``socket`` as accepting connections. @@ -805,6 +830,7 @@ proc recv*(socket: PSocket, data: pointer, size: int): int {.tags: [FReadIO].} = let chunk = min(socket.bufLen-socket.currPos, size-read) var d = cast[cstring](data) + assert size-read >= chunk copyMem(addr(d[read]), addr(socket.buffer[socket.currPos]), chunk) read.inc(chunk) socket.currPos.inc(chunk) @@ -871,6 +897,7 @@ proc recv*(socket: PSocket, data: pointer, size: int, timeout: int): int {. while read < size: let avail = waitFor(socket, waited, timeout, size-read, "recv") var d = cast[cstring](data) + assert avail <= size-read result = recv(socket, addr(d[read]), avail) if result == 0: break if result < 0: @@ -879,7 +906,8 @@ proc recv*(socket: PSocket, data: pointer, size: int, timeout: int): int {. result = read -proc recv*(socket: PSocket, data: var string, size: int, timeout = -1): int = +proc recv*(socket: PSocket, data: var string, size: int, timeout = -1, + flags = {TSocketFlags.SafeDisconn}): int = ## Higher-level version of ``recv``. ## ## When 0 is returned the socket's connection has been closed. @@ -891,11 +919,15 @@ proc recv*(socket: PSocket, data: var string, size: int, timeout = -1): int = ## within the time specified an ETimeout exception will be raised. ## ## **Note**: ``data`` must be initialised. + ## + ## **Warning**: Only the ``SafeDisconn`` flag is currently supported. data.setLen(size) result = recv(socket, cstring(data), size, timeout) if result < 0: data.setLen(0) - socket.socketError(result) + let lastError = osLastError() + if flags.isDisconnectionError(lastError): return + socket.socketError(result, lastError = lastError) data.setLen(result) proc peekChar(socket: PSocket, c: var char): int {.tags: [FReadIO].} = @@ -918,7 +950,8 @@ proc peekChar(socket: PSocket, c: var char): int {.tags: [FReadIO].} = return result = recv(socket.fd, addr(c), 1, MSG_PEEK) -proc readLine*(socket: PSocket, line: var TaintedString, timeout = -1) {. +proc readLine*(socket: PSocket, line: var TaintedString, timeout = -1, + flags = {TSocketFlags.SafeDisconn}) {. tags: [FReadIO, FTime].} = ## Reads a line of data from ``socket``. ## @@ -932,11 +965,18 @@ proc readLine*(socket: PSocket, line: var TaintedString, timeout = -1) {. ## ## A timeout can be specified in miliseconds, if data is not received within ## the specified time an ETimeout exception will be raised. + ## + ## **Warning**: Only the ``SafeDisconn`` flag is currently supported. template addNLIfEmpty(): stmt = if line.len == 0: line.add("\c\L") + template raiseSockError(): stmt {.dirty, immediate.} = + let lastError = osLastError() + if flags.isDisconnectionError(lastError): setLen(line.string, 0); return + socket.socketError(n, lastError = lastError) + var waited = 0.0 setLen(line.string, 0) @@ -944,14 +984,14 @@ proc readLine*(socket: PSocket, line: var TaintedString, timeout = -1) {. var c: char discard waitFor(socket, waited, timeout, 1, "readLine") var n = recv(socket, addr(c), 1) - if n < 0: socket.socketError() - elif n == 0: return + if n < 0: raiseSockError() + elif n == 0: setLen(line.string, 0); return if c == '\r': discard waitFor(socket, waited, timeout, 1, "readLine") n = peekChar(socket, c) if n > 0 and c == '\L': discard recv(socket, addr(c), 1) - elif n <= 0: socket.socketError() + elif n <= 0: raiseSockError() addNLIfEmpty() return elif c == '\L': @@ -1019,11 +1059,14 @@ proc send*(socket: PSocket, data: pointer, size: int): int {. const MSG_NOSIGNAL = 0 result = send(socket.fd, data, size, int32(MSG_NOSIGNAL)) -proc send*(socket: PSocket, data: string) {.tags: [FWriteIO].} = +proc send*(socket: PSocket, data: string, + flags = {TSocketFlags.SafeDisconn}) {.tags: [FWriteIO].} = ## sends data to a socket. let sent = send(socket, cstring(data), data.len) if sent < 0: - socketError(socket) + let lastError = osLastError() + if flags.isDisconnectionError(lastError): return + socketError(socket, lastError = lastError) if sent != data.len: raise newException(EOS, "Could not send all data.") diff --git a/lib/pure/nimprof.nim b/lib/pure/nimprof.nim index 3d0cc2154..ab7cd1944 100644 --- a/lib/pure/nimprof.nim +++ b/lib/pure/nimprof.nim @@ -58,8 +58,9 @@ when not defined(memProfiler): ## instruction count measure instead then. if intervalInUs <= 0: interval = 0 else: interval = intervalInUs * 1000 - tickCountCorrection - + when withThreads: + import locks var profilingLock: TLock @@ -72,7 +73,7 @@ proc hookAux(st: TStackTrace, costs: int) = var last = high(st) while last > 0 and isNil(st[last]): dec last var h = hash(pointer(st[last])) and high(profileData) - + # we use probing for maxChainLen entries and replace the encountered entry # with the minimal 'total' value: if emptySlots == 0: @@ -133,7 +134,7 @@ else: hookAux(st, 1) elif getticks() - t0 > interval: hookAux(st, 1) - t0 = getticks() + t0 = getticks() proc getTotal(x: ptr TProfileEntry): int = result = if isNil(x): 0 else: x.total @@ -145,7 +146,7 @@ proc `//`(a, b: int): string = result = format("$1/$2 = $3%", a, b, formatFloat(a / b * 100.0, ffDefault, 2)) proc writeProfile() {.noconv.} = - when defined(system.TStackTrace): + when defined(system.TStackTrace): system.profilerHook = nil const filename = "profile_results.txt" echo "writing " & filename & "..." @@ -156,7 +157,7 @@ proc writeProfile() {.noconv.} = var entries = 0 for i in 0..high(profileData): if profileData[i] != nil: inc entries - + var perProc = initCountTable[string]() for i in 0..entries-1: var dups = initSet[string]() @@ -166,7 +167,7 @@ proc writeProfile() {.noconv.} = let p = $procname if not containsOrIncl(dups, p): perProc.inc(p, profileData[i].total) - + var sum = 0 # only write the first 100 entries: for i in 0..min(100, entries-1): diff --git a/lib/pure/oids.nim b/lib/pure/oids.nim index b3e74d2a1..2843e6c65 100644 --- a/lib/pure/oids.nim +++ b/lib/pure/oids.nim @@ -62,9 +62,9 @@ var proc genOid*(): TOid = ## generates a new OID. - proc rand(): cint {.importc: "rand", nodecl.} + proc rand(): cint {.importc: "rand", header: "<stdlib.h>", nodecl.} proc gettime(dummy: ptr cint): cint {.importc: "time", header: "<time.h>".} - proc srand(seed: cint) {.importc: "srand", nodecl.} + proc srand(seed: cint) {.importc: "srand", header: "<stdlib.h>", nodecl.} var t = gettime(nil) diff --git a/lib/pure/os.nim b/lib/pure/os.nim index 00a33db75..0b4538abc 100644 --- a/lib/pure/os.nim +++ b/lib/pure/os.nim @@ -1,7 +1,7 @@ # # # Nimrod's Runtime Library -# (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -1612,6 +1612,20 @@ when defined(linux) or defined(solaris) or defined(bsd) or defined(aix): len = readlink(procPath, result, len) setLen(result, len) +when not (defined(windows) or defined(macosx)): + proc getApplHeuristic(): string = + when defined(paramStr): + result = string(paramStr(0)) + # POSIX guaranties that this contains the executable + # as it has been executed by the calling process + if len(result) > 0 and result[0] != DirSep: # not an absolute path? + # iterate over any path in the $PATH environment variable + for p in split(string(getEnv("PATH")), {PathSep}): + var x = joinPath(p, result) + if existsFile(x): return x + else: + result = "" + when defined(macosx): type cuint32* {.importc: "unsigned int", nodecl.} = int @@ -1648,10 +1662,13 @@ proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} = setlen(result, int(len)) elif defined(linux) or defined(aix): result = getApplAux("/proc/self/exe") + if result.len == 0: result = getApplHeuristic() elif defined(solaris): result = getApplAux("/proc/" & $getpid() & "/path/a.out") + if result.len == 0: result = getApplHeuristic() elif defined(freebsd): result = getApplAux("/proc/" & $getpid() & "/file") + if result.len == 0: result = getApplHeuristic() elif defined(macosx): var size: cuint32 getExecPath1(nil, size) @@ -1663,15 +1680,7 @@ proc getAppFilename*(): string {.rtl, extern: "nos$1", tags: [FReadIO].} = else: # little heuristic that may work on other POSIX-like systems: result = string(getEnv("_")) - if len(result) == 0: - result = string(paramStr(0)) - # POSIX guaranties that this contains the executable - # as it has been executed by the calling process - if len(result) > 0 and result[0] != DirSep: # not an absolute path? - # iterate over any path in the $PATH environment variable - for p in split(string(getEnv("PATH")), {PathSep}): - var x = joinPath(p, result) - if existsFile(x): return x + if result.len == 0: result = getApplHeuristic() proc getApplicationFilename*(): string {.rtl, extern: "nos$1", deprecated.} = ## Returns the filename of the application's executable. @@ -1760,16 +1769,16 @@ else: FileId = TIno type - FileInfo = object + FileInfo* = object ## Contains information associated with a file object. - id: tuple[device: DeviceId, file: FileId] # Device and file id. - kind: TPathComponent # Kind of file object - directory, symlink, etc. - size: BiggestInt # Size of file. - permissions: set[TFilePermission] # File permissions - linkCount: BiggestInt # Number of hard links the file object has. - lastAccessTime: TTime # Time file was last accessed. - lastWriteTime: TTime # Time file was last modified/written to. - creationTime: TTime # Time file was created. Not supported on all systems! + id*: tuple[device: DeviceId, file: FileId] # Device and file id. + kind*: TPathComponent # Kind of file object - directory, symlink, etc. + size*: BiggestInt # Size of file. + permissions*: set[TFilePermission] # File permissions + linkCount*: BiggestInt # Number of hard links the file object has. + lastAccessTime*: TTime # Time file was last accessed. + lastWriteTime*: TTime # Time file was last modified/written to. + creationTime*: TTime # Time file was created. Not supported on all systems! template rawToFormalFileInfo(rawInfo, formalInfo): expr = ## Transforms the native file info structure into the one nimrod uses. diff --git a/lib/pure/osproc.nim b/lib/pure/osproc.nim index 6e250f9d5..04a0c2403 100644 --- a/lib/pure/osproc.nim +++ b/lib/pure/osproc.nim @@ -1,7 +1,7 @@ # # # Nimrod's Runtime Library -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. @@ -13,7 +13,7 @@ include "system/inclrtl" import - strutils, os, strtabs, streams + strutils, os, strtabs, streams, cpuinfo when defined(windows): import winlean @@ -225,42 +225,10 @@ proc errorHandle*(p: PProcess): TFileHandle {.rtl, extern: "nosp$1", ## it is closed when closing the PProcess ``p``. result = p.errHandle -when defined(macosx) or defined(bsd): - const - CTL_HW = 6 - HW_AVAILCPU = 25 - HW_NCPU = 3 - proc sysctl(x: ptr array[0..3, cint], y: cint, z: pointer, - a: var csize, b: pointer, c: int): cint {. - importc: "sysctl", header: "<sys/sysctl.h>".} - proc countProcessors*(): int {.rtl, extern: "nosp$1".} = ## returns the numer of the processors/cores the machine has. ## Returns 0 if it cannot be detected. - when defined(windows): - var x = getEnv("NUMBER_OF_PROCESSORS") - if x.len > 0: result = parseInt(x.string) - elif defined(macosx) or defined(bsd): - var - mib: array[0..3, cint] - numCPU: int - len: csize - mib[0] = CTL_HW - mib[1] = HW_AVAILCPU - len = sizeof(numCPU) - discard sysctl(addr(mib), 2, addr(numCPU), len, nil, 0) - if numCPU < 1: - mib[1] = HW_NCPU - discard sysctl(addr(mib), 2, addr(numCPU), len, nil, 0) - result = numCPU - elif defined(hpux): - result = mpctl(MPC_GETNUMSPUS, nil, nil) - elif defined(irix): - var SC_NPROC_ONLN {.importc: "_SC_NPROC_ONLN", header: "<unistd.h>".}: cint - result = sysconf(SC_NPROC_ONLN) - else: - result = sysconf(SC_NPROCESSORS_ONLN) - if result <= 0: result = 1 + result = cpuinfo.countProcessors() proc execProcesses*(cmds: openArray[string], options = {poStdErrToStdOut, poParentStreams}, @@ -800,8 +768,8 @@ elif not defined(useNimRtl): proc startProcessAfterFork(data: ptr TStartProcessData) = # Warning: no GC here! - # Or anythink that touches global structures - all called nimrod procs - # must be marked with noStackFrame. Inspect C code after making changes. + # Or anything that touches global structures - all called nimrod procs + # must be marked with stackTrace:off. Inspect C code after making changes. if not data.optionPoParentStreams: discard close(data.pStdin[writeIdx]) if dup2(data.pStdin[readIdx], readIdx) < 0: @@ -903,7 +871,7 @@ elif not defined(useNimRtl): createStream(p.errStream, p.errHandle, fmRead) return p.errStream - proc csystem(cmd: cstring): cint {.nodecl, importc: "system".} + proc csystem(cmd: cstring): cint {.nodecl, importc: "system", header: "<stdlib.h>".} proc execCmd(command: string): int = when defined(linux): diff --git a/lib/pure/rawsockets.nim b/lib/pure/rawsockets.nim index 07b647b68..d96741846 100644 --- a/lib/pure/rawsockets.nim +++ b/lib/pure/rawsockets.nim @@ -21,11 +21,12 @@ const useWinVersion = defined(Windows) or defined(nimdoc) when useWinVersion: import winlean - export WSAEWOULDBLOCK + export WSAEWOULDBLOCK, WSAECONNRESET, WSAECONNABORTED, WSAENETRESET, + WSAEDISCON else: import posix export fcntl, F_GETFL, O_NONBLOCK, F_SETFL, EAGAIN, EWOULDBLOCK, MSG_NOSIGNAL, - EINTR, EINPROGRESS + EINTR, EINPROGRESS, ECONNRESET, EPIPE, ENETRESET export TSocketHandle, TSockaddr_in, TAddrinfo, INADDR_ANY, TSockAddr, TSockLen, inet_ntoa, recv, `==`, connect, send, accept, recvfrom, sendto @@ -39,7 +40,6 @@ export MSG_PEEK type - TPort* = distinct uint16 ## port type TDomain* = enum ## domain, which specifies the protocol family of the diff --git a/lib/pure/selectors.nim b/lib/pure/selectors.nim index f630ba235..bd53c2dbf 100644 --- a/lib/pure/selectors.nim +++ b/lib/pure/selectors.nim @@ -11,9 +11,12 @@ import tables, os, unsigned, hashes -when defined(linux): import posix, epoll -elif defined(windows): import winlean -else: import posix +when defined(linux): + import posix, epoll +elif defined(windows): + import winlean +else: + import posix proc hash*(x: TSocketHandle): THash {.borrow.} proc `$`*(x: TSocketHandle): string {.borrow.} @@ -29,7 +32,36 @@ type TReadyInfo* = tuple[key: PSelectorKey, events: set[TEvent]] -when defined(linux) or defined(nimdoc): +when defined(nimdoc): + type + PSelector* = ref object + ## An object which holds file descripters to be checked for read/write + ## status. + fds: TTable[TSocketHandle, PSelectorKey] + + proc register*(s: PSelector, fd: TSocketHandle, events: set[TEvent], + data: PObject): PSelectorKey {.discardable.} = + ## Registers file descriptor ``fd`` to selector ``s`` with a set of TEvent + ## ``events``. + + proc update*(s: PSelector, fd: TSocketHandle, + events: set[TEvent]): PSelectorKey {.discardable.} = + ## Updates the events which ``fd`` wants notifications for. + + proc select*(s: PSelector, timeout: int): seq[TReadyInfo] = + ## The ``events`` field of the returned ``key`` contains the original events + ## for which the ``fd`` was bound. This is contrary to the ``events`` field + ## of the ``TReadyInfo`` tuple which determines which events are ready + ## on the ``fd``. + + proc contains*(s: PSelector, fd: TSocketHandle): bool = + ## Determines whether selector contains a file descriptor. + + proc `[]`*(s: PSelector, fd: TSocketHandle): PSelectorKey = + ## Retrieves the selector key for ``fd``. + + +elif defined(linux): type PSelector* = ref object epollFD: cint @@ -49,9 +81,10 @@ when defined(linux) or defined(nimdoc): ## Registers file descriptor ``fd`` to selector ``s`` with a set of TEvent ## ``events``. var event = createEventStruct(events, fd) - if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fd, addr(event)) != 0: - OSError(OSLastError()) - + if events != {}: + if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fd, addr(event)) != 0: + OSError(OSLastError()) + var key = PSelectorKey(fd: fd, events: events, data: data) s.fds[fd] = key @@ -61,11 +94,27 @@ when defined(linux) or defined(nimdoc): events: set[TEvent]): PSelectorKey {.discardable.} = ## Updates the events which ``fd`` wants notifications for. if s.fds[fd].events != events: - var event = createEventStruct(events, fd) + if events == {}: + # This fd is idle -- it should not be registered to epoll. + # But it should remain a part of this selector instance. + # This is to prevent epoll_wait from returning immediately + # because its got fds which are waiting for no events and + # are therefore constantly ready. (leading to 100% CPU usage). + if epoll_ctl(s.epollFD, EPOLL_CTL_DEL, fd, nil) != 0: + OSError(OSLastError()) + s.fds[fd].events = events + else: + var event = createEventStruct(events, fd) + if s.fds[fd].events == {}: + # This fd is idle. It's not a member of this epoll instance and must + # be re-registered. + if epoll_ctl(s.epollFD, EPOLL_CTL_ADD, fd, addr(event)) != 0: + OSError(OSLastError()) + else: + if epoll_ctl(s.epollFD, EPOLL_CTL_MOD, fd, addr(event)) != 0: + OSError(OSLastError()) + s.fds[fd].events = events - s.fds[fd].events = events - if epoll_ctl(s.epollFD, EPOLL_CTL_MOD, fd, addr(event)) != 0: - OSError(OSLastError()) result = s.fds[fd] proc unregister*(s: PSelector, fd: TSocketHandle): PSelectorKey {.discardable.} = @@ -114,7 +163,7 @@ when defined(linux) or defined(nimdoc): proc newSelector*(): PSelector = new result result.epollFD = epoll_create(64) - result.events = cast[array[64, epoll_event]](alloc0(sizeof(epoll_event)*64)) + #result.events = cast[array[64, epoll_event]](alloc0(sizeof(epoll_event)*64)) result.fds = initTable[TSocketHandle, PSelectorKey]() if result.epollFD < 0: OSError(OSLastError()) @@ -123,7 +172,10 @@ when defined(linux) or defined(nimdoc): ## Determines whether selector contains a file descriptor. if s.fds.hasKey(fd): # Ensure the underlying epoll instance still contains this fd. - result = epollHasFd(s, fd) + if s.fds[fd].events != {}: + result = epollHasFd(s, fd) + else: + result = true else: return false @@ -131,7 +183,7 @@ when defined(linux) or defined(nimdoc): ## Retrieves the selector key for ``fd``. return s.fds[fd] -else: +elif not defined(nimdoc): # TODO: kqueue for bsd/mac os x. type PSelector* = ref object @@ -230,7 +282,7 @@ proc contains*(s: PSelector, key: PSelectorKey): bool = ## the new one may have the same value. return key.fd in s and s.fds[key.fd] == key -when isMainModule: +when isMainModule and not defined(nimdoc): # Select() import sockets type diff --git a/lib/pure/sockets.nim b/lib/pure/sockets.nim index 8d96cbaaf..7b8b3d557 100644 --- a/lib/pure/sockets.nim +++ b/lib/pure/sockets.nim @@ -295,7 +295,7 @@ when defined(ssl): of protSSLv23: newCTX = SSL_CTX_new(SSLv23_method()) # SSlv2,3 and TLS1 support. of protSSLv2: - when not defined(linux): + when not defined(linux) and not defined(OpenBSD): newCTX = SSL_CTX_new(SSLv2_method()) else: SSLError() diff --git a/lib/pure/strutils.nim b/lib/pure/strutils.nim index bd6814dcc..e642f6a99 100644 --- a/lib/pure/strutils.nim +++ b/lib/pure/strutils.nim @@ -10,6 +10,8 @@ ## This module contains various string utility routines. ## See the module `re <re.html>`_ for regular expression support. ## See the module `pegs <pegs.html>`_ for PEG support. +## This module is available for the `JavaScript target +## <backends.html#the-javascript-target>`_. import parseutils diff --git a/lib/pure/times.nim b/lib/pure/times.nim index fdff06b2a..498511899 100644 --- a/lib/pure/times.nim +++ b/lib/pure/times.nim @@ -9,7 +9,8 @@ ## This module contains routines and types for dealing with time. -## This module is available for the JavaScript target. +## This module is available for the `JavaScript target +## <backends.html#the-javascript-target>`_. {.push debugger:off.} # the user does not want to trace a part # of the standard library! diff --git a/lib/pure/unidecode/gen.py b/lib/pure/unidecode/gen.py index 8da0136ff..8da0136ff 100755..100644 --- a/lib/pure/unidecode/gen.py +++ b/lib/pure/unidecode/gen.py diff --git a/lib/system.nim b/lib/system.nim index 4a5d46a7f..3bb632536 100644 --- a/lib/system.nim +++ b/lib/system.nim @@ -42,15 +42,18 @@ type cstring* {.magic: Cstring.} ## built-in cstring (*compatible string*) type pointer* {.magic: Pointer.} ## built-in pointer type, use the ``addr`` ## operator to get a pointer to a variable - const on* = true ## alias for ``true`` off* = false ## alias for ``false`` +{.push warning[GcMem]: off.} {.push hints: off.} type Ordinal* {.magic: Ordinal.}[T] + `ptr`* {.magic: Pointer.}[T] ## built-in generic untraced pointer type + `ref`* {.magic: Pointer.}[T] ## built-in generic traced pointer type + `nil` {.magic: "Nil".} expr* {.magic: Expr.} ## meta type to denote an expression (for templates) stmt* {.magic: Stmt.} ## meta type to denote a statement (for templates) @@ -88,6 +91,15 @@ proc defined*(x: expr): bool {.magic: "Defined", noSideEffect.} ## when not defined(strutils.toUpper): ## # provide our own toUpper proc here, because strutils is ## # missing it. + ## + ## You can also check external symbols introduced through the compiler's + ## `-d:x switch <nimrodc.html#compile-time-symbols>`_ to enable build time + ## conditionals: + ## + ## .. code-block:: Nimrod + ## when not defined(release): + ## # Do here programmer friendly expensive sanity checks. + ## # Put here the normal code when defined(useNimRtl): {.deadCodeElim: on.} @@ -234,6 +246,11 @@ template `>` * (x, y: expr): expr {.immediate.} = ## "is greater" operator. This is the same as ``y < x``. y < x +const + appType* {.magic: "AppType"}: string = "" + ## a string that describes the application type. Possible values: + ## "console", "gui", "lib". + include "system/inclrtl" const NoFakeVars* = defined(NimrodVM) ## true if the backend doesn't support \ @@ -415,12 +432,12 @@ proc pred*[T](x: Ordinal[T], y = 1): T {.magic: "Pred", noSideEffect.} ## an ordinal type. If such a value does not exist, ``EOutOfRange`` is raised ## or a compile time error occurs. -proc inc*[T](x: var Ordinal[T], y = 1) {.magic: "Inc", noSideEffect.} +proc inc*[T: Ordinal|uint|uint64](x: var T, y = 1) {.magic: "Inc", noSideEffect.} ## increments the ordinal ``x`` by ``y``. If such a value does not ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a ## short notation for: ``x = succ(x, y)``. -proc dec*[T](x: var Ordinal[T], y = 1) {.magic: "Dec", noSideEffect.} +proc dec*[T: Ordinal|uint|uint64](x: var T, y = 1) {.magic: "Dec", noSideEffect.} ## decrements the ordinal ``x`` by ``y``. If such a value does not ## exist, ``EOutOfRange`` is raised or a compile time error occurs. This is a ## short notation for: ``x = pred(x, y)``. @@ -940,10 +957,6 @@ const ## a string that describes the host CPU. Possible values: ## "i386", "alpha", "powerpc", "sparc", "amd64", "mips", "arm". - appType* {.magic: "AppType"}: string = "" - ## a string that describes the application type. Possible values: - ## "console", "gui", "lib". - seqShallowFlag = low(int) proc compileOption*(option: string): bool {. @@ -1433,6 +1446,20 @@ when not defined(nimrodVM) and hostOS != "standalone": proc getTotalMem*(): int {.rtl.} ## returns the number of bytes that are owned by the process. + when hasThreadSupport: + proc getOccupiedSharedMem*(): int {.rtl.} + ## returns the number of bytes that are owned by the process + ## on the shared heap and hold data. This is only available when + ## threads are enabled. + + proc getFreeSharedMem*(): int {.rtl.} + ## returns the number of bytes that are owned by the + ## process on the shared heap, but do not hold any meaningful data. + ## This is only available when threads are enabled. + + proc getTotalSharedMem*(): int {.rtl.} + ## returns the number of bytes on the shared heap that are owned by the + ## process. This is only available when threads are enabled. iterator countdown*[T](a, b: T, step = 1): T {.inline.} = ## Counts from ordinal value `a` down to `b` with the given @@ -1752,9 +1779,38 @@ iterator fields*[S:tuple|object, T:tuple|object](x: S, y: T): tuple[a,b: expr] { ## in the loop body. iterator fieldPairs*[T: tuple|object](x: T): TObject {. magic: "FieldPairs", noSideEffect.} - ## iterates over every field of `x`. Warning: This really transforms - ## the 'for' and unrolls the loop. The current implementation also has a bug - ## that affects symbol binding in the loop body. + ## Iterates over every field of `x` returning their name and value. + ## + ## When you iterate over objects with different field types you have to use + ## the compile time ``when`` instead of a runtime ``if`` to select the code + ## you want to run for each type. To perform the comparison use the `is + ## operator <manual.html#is-operator>`_. Example: + ## + ## .. code-block:: Nimrod + ## + ## type + ## Custom = object + ## foo: string + ## bar: bool + ## + ## proc `$`(x: Custom): string = + ## result = "Custom:" + ## for name, value in x.fieldPairs: + ## when value is bool: + ## result.add("\n\t" & name & " is " & $value) + ## else: + ## if value.isNil: + ## result.add("\n\t" & name & " (nil)") + ## else: + ## result.add("\n\t" & name & " '" & value & "'") + ## + ## Another way to do the same without ``when`` is to leave the task of + ## picking the appropriate code to a secondary proc which you overload for + ## each field type and pass the `value` to. + ## + ## Warning: This really transforms the 'for' and unrolls the loop. The + ## current implementation also has a bug that affects symbol binding in the + ## loop body. iterator fieldPairs*[S: tuple|object, T: tuple|object](x: S, y: T): tuple[ a, b: expr] {. magic: "FieldPairs", noSideEffect.} @@ -2412,7 +2468,7 @@ when not defined(JS): #and not defined(NimrodVM): ## for line in filename.lines: ## buffer.add(line.replace("a", "0") & '\x0A') ## writeFile(filename, buffer) - var f = open(filename) + var f = open(filename, bufSize=8000) var res = TaintedString(newStringOfCap(80)) while f.readLine(res): yield res close(f) @@ -2608,6 +2664,8 @@ when hostOS != "standalone": proc `[]`*[Idx, T](a: array[Idx, T], x: TSlice[int]): seq[T] = ## slice operation for arrays. Negative indexes are **not** supported ## because the array might have negative bounds. + when low(a) < 0: + {.error: "Slicing for arrays with negative indices is unsupported.".} var L = x.b - x.a + 1 newSeq(result, L) for i in 0.. <L: result[i] = a[i + x.a] @@ -2615,11 +2673,13 @@ proc `[]`*[Idx, T](a: array[Idx, T], x: TSlice[int]): seq[T] = proc `[]=`*[Idx, T](a: var array[Idx, T], x: TSlice[int], b: openArray[T]) = ## slice assignment for arrays. Negative indexes are **not** supported ## because the array might have negative bounds. + when low(a) < 0: + {.error: "Slicing for arrays with negative indices is unsupported.".} var L = x.b - x.a + 1 if L == b.len: for i in 0 .. <L: a[i+x.a] = b[i] else: - sysFatal(EOutOfRange, "differing lengths for slice assignment") + sysFatal(EOutOfRange, "different lengths for slice assignment") proc `[]`*[Idx, T](a: array[Idx, T], x: TSlice[Idx]): seq[T] = ## slice operation for arrays. Negative indexes are **not** supported @@ -2641,7 +2701,7 @@ proc `[]=`*[Idx, T](a: var array[Idx, T], x: TSlice[Idx], b: openArray[T]) = a[j] = b[i] inc(j) else: - sysFatal(EOutOfRange, "differing lengths for slice assignment") + sysFatal(EOutOfRange, "different lengths for slice assignment") proc `[]`*[T](s: seq[T], x: TSlice[int]): seq[T] = ## slice operation for sequences. Negative indexes are supported. @@ -2690,13 +2750,13 @@ proc staticExec*(command: string, input = ""): string {. ## inside a pragma like `passC <nimrodc.html#passc-pragma>`_ or `passL ## <nimrodc.html#passl-pragma>`_. -proc `+=`*[T: TOrdinal](x: var T, y: T) {.magic: "Inc", noSideEffect.} +proc `+=`*[T: TOrdinal|uint|uint64](x: var T, y: T) {.magic: "Inc", noSideEffect.} ## Increments an ordinal -proc `-=`*[T: TOrdinal](x: var T, y: T) {.magic: "Dec", noSideEffect.} +proc `-=`*[T: TOrdinal|uint|uint64](x: var T, y: T) {.magic: "Dec", noSideEffect.} ## Decrements an ordinal -proc `*=`*[T: TOrdinal](x: var T, y: T) {.inline, noSideEffect.} = +proc `*=`*[T: TOrdinal|uint|uint64](x: var T, y: T) {.inline, noSideEffect.} = ## Binary `*=` operator for ordinals x = x * y @@ -2718,9 +2778,6 @@ proc `/=`*[T: float|float32|float64] (x: var T, y: T) {.inline, noSideEffect.} = proc `&=`* (x: var string, y: string) {.magic: "AppendStrStr", noSideEffect.} -proc rand*(max: int): int {.magic: "Rand", sideEffect.} - ## compile-time `random` function. Useful for debugging. - proc astToStr*[T](x: T): string {.magic: "AstToStr", noSideEffect.} ## converts the AST of `x` into a string representation. This is very useful ## for debugging. @@ -2771,10 +2828,15 @@ when true: THide(raiseAssert)(msg) template assert*(cond: bool, msg = "") = - ## provides a means to implement `programming by contracts`:idx: in Nimrod. + ## Raises ``EAssertionFailure`` with `msg` if `cond` is false. + ## + ## Provides a means to implement `programming by contracts`:idx: in Nimrod. ## ``assert`` evaluates expression ``cond`` and if ``cond`` is false, it - ## raises an ``EAssertionFailure`` exception. However, the compiler may - ## not generate any code at all for ``assert`` if it is advised to do so. + ## raises an ``EAssertionFailure`` exception. However, the compiler may not + ## generate any code at all for ``assert`` if it is advised to do so through + ## the ``-d:release`` or ``--assertions:off`` `command line switches + ## <nimrodc.html#command-line-switches>`_. + ## ## Use ``assert`` for debugging purposes only. bind instantiationInfo mixin failedAssertImpl @@ -2928,6 +2990,12 @@ proc locals*(): TObject {.magic: "Locals", noSideEffect.} = ## # -> B is 1 discard +proc deepCopy*[T](x: T): T {.magic: "DeepCopy", noSideEffect.} = discard + ## performs a deep copy of `x`. This is also used by the code generator + ## for the implementation of ``spawn``. + +{.pop.} #{.push warning[GcMem]: off.} + when not defined(booting): type semistatic*[T] = static[T] | T @@ -2936,6 +3004,3 @@ when not defined(booting): template isStatic*(x): expr = compiles(static(x)) # checks whether `x` is a value known at compile-time - -when hasThreadSupport: - when hostOS != "standalone": include "system/sysspawn" diff --git a/lib/system/alloc.nim b/lib/system/alloc.nim index eaef6cd95..602e5c7fa 100644 --- a/lib/system/alloc.nim +++ b/lib/system/alloc.nim @@ -835,4 +835,20 @@ template instantiateForRegion(allocator: expr) = else: result = realloc(p, newsize) + when hasThreadSupport: + + template sharedMemStatsShared(v: int) {.immediate.} = + acquireSys(heapLock) + result = v + releaseSys(heapLock) + + proc getFreeSharedMem(): int = + sharedMemStatsShared(sharedHeap.freeMem) + + proc getTotalSharedMem(): int = + sharedMemStatsShared(sharedHeap.currMem) + + proc getOccupiedSharedMem(): int = + sharedMemStatsShared(sharedHeap.currMem - sharedHeap.freeMem) + {.pop.} diff --git a/lib/system/ansi_c.nim b/lib/system/ansi_c.nim index 2d33965e3..5111bc3cf 100644 --- a/lib/system/ansi_c.nim +++ b/lib/system/ansi_c.nim @@ -57,6 +57,7 @@ when not defined(SIGINT): SIGINT = cint(2) SIGSEGV = cint(11) SIGTERM = cint(15) + SIGPIPE = cint(13) else: {.error: "SIGABRT not ported to your platform".} else: @@ -66,6 +67,8 @@ when not defined(SIGINT): SIGABRT {.importc: "SIGABRT", nodecl.}: cint SIGFPE {.importc: "SIGFPE", nodecl.}: cint SIGILL {.importc: "SIGILL", nodecl.}: cint + when defined(macosx) or defined(linux): + var SIGPIPE {.importc: "SIGPIPE", nodecl.}: cint when defined(macosx): when NoFakeVars: diff --git a/lib/system/assign.nim b/lib/system/assign.nim index 75c749633..2ae945fb1 100644 --- a/lib/system/assign.nim +++ b/lib/system/assign.nim @@ -179,7 +179,8 @@ when not defined(nimmixin): # internal proc used for destroying sequences and arrays for i in countup(0, r.len - 1): destroy(r[i]) else: - # XXX Why is this exported and no compilerproc? + # XXX Why is this exported and no compilerproc? -> compilerprocs cannot be + # generic for now proc nimDestroyRange*[T](r: T) = # internal proc used for destroying sequences and arrays mixin destroy diff --git a/lib/system/atomics.nim b/lib/system/atomics.nim index b1a96b209..43b3f0438 100644 --- a/lib/system/atomics.nim +++ b/lib/system/atomics.nim @@ -1,15 +1,18 @@ # # # Nimrod's Runtime Library -# (c) Copyright 2012 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. # ## Atomic operations for Nimrod. +{.push stackTrace:off.} -when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: +const someGcc = defined(gcc) or defined(llvm_gcc) or defined(clang) + +when someGcc and hasThreadSupport: type AtomMemModel* = enum ATOMIC_RELAXED, ## No barriers or synchronization. @@ -152,41 +155,16 @@ when (defined(gcc) or defined(llvm_gcc)) and hasThreadSupport: ## A value of 0 indicates typical alignment should be used. The compiler may also ## ignore this parameter. + template fence*() = atomicThreadFence(ATOMIC_SEQ_CST) elif defined(vcc) and hasThreadSupport: proc addAndFetch*(p: ptr int, val: int): int {. importc: "NimXadd", nodecl.} + else: proc addAndFetch*(p: ptr int, val: int): int {.inline.} = inc(p[], val) result = p[] -# atomic compare and swap (CAS) funcitons to implement lock-free algorithms - -#if defined(windows) and not defined(gcc) and hasThreadSupport: -# proc InterlockedCompareExchangePointer(mem: ptr pointer, -# newValue: pointer, comparand: pointer) : pointer {.nodecl, -# importc: "InterlockedCompareExchangePointer", header:"windows.h".} - -# proc compareAndSwap*[T](mem: ptr T, -# expected: T, newValue: T): bool {.inline.}= -# ## Returns true if successfully set value at mem to newValue when value -# ## at mem == expected -# return InterlockedCompareExchangePointer(addr(mem), -# addr(newValue), addr(expected))[] == expected - -#elif not hasThreadSupport: -# proc compareAndSwap*[T](mem: ptr T, -# expected: T, newValue: T): bool {.inline.} = -# ## Returns true if successfully set value at mem to newValue when value -# ## at mem == expected -# var oldval = mem[] -# if oldval == expected: -# mem[] = newValue -# return true -# return false - - -# Some convenient functions proc atomicInc*(memLoc: var int, x: int = 1): int = when defined(gcc) and hasThreadSupport: result = atomic_add_fetch(memLoc.addr, x, ATOMIC_RELAXED) @@ -203,3 +181,37 @@ proc atomicDec*(memLoc: var int, x: int = 1): int = else: dec(memLoc, x) result = memLoc + +when defined(windows) and not someGcc: + proc interlockedCompareExchange(p: pointer; exchange, comparand: int32): int32 + {.importc: "InterlockedCompareExchange", header: "<windows.h>", cdecl.} + + proc cas*[T: bool|int|ptr](p: ptr T; oldValue, newValue: T): bool = + interlockedCompareExchange(p, newValue.int32, oldValue.int32) != 0 + # XXX fix for 64 bit build +else: + # this is valid for GCC and Intel C++ + proc cas*[T: bool|int|ptr](p: ptr T; oldValue, newValue: T): bool + {.importc: "__sync_bool_compare_and_swap", nodecl.} + # XXX is this valid for 'int'? + + +when (defined(x86) or defined(amd64)) and (defined(gcc) or defined(llvm_gcc)): + proc cpuRelax {.inline.} = + {.emit: """asm volatile("pause" ::: "memory");""".} +elif (defined(x86) or defined(amd64)) and defined(vcc): + proc cpuRelax {.importc: "YieldProcessor", header: "<windows.h>".} +elif defined(intelc): + proc cpuRelax {.importc: "_mm_pause", header: "xmmintrin.h".} +elif false: + from os import sleep + + proc cpuRelax {.inline.} = os.sleep(1) + +when not defined(fence) and hasThreadSupport: + # XXX fixme + proc fence*() {.inline.} = + var dummy: bool + discard cas(addr dummy, false, true) + +{.pop.} diff --git a/lib/system/chcks.nim b/lib/system/chcks.nim index f29e222e8..387b54ef1 100644 --- a/lib/system/chcks.nim +++ b/lib/system/chcks.nim @@ -67,6 +67,28 @@ proc chckObjAsgn(a, b: PNimType) {.compilerproc, inline.} = if a != b: sysFatal(EInvalidObjectAssignment, "invalid object assignment") +type ObjCheckCache = array[0..1, PNimType] + +proc isObjSlowPath(obj, subclass: PNimType; + cache: var ObjCheckCache): bool {.noinline.} = + # checks if obj is of type subclass: + var x = obj.base + while x != subclass: + if x == nil: + cache[0] = obj + return false + x = x.base + cache[1] = obj + return true + +proc isObjWithCache(obj, subclass: PNimType; + cache: var ObjCheckCache): bool {.compilerProc, inline.} = + if obj == subclass: return true + if obj.base == subclass: return true + if cache[0] == obj: return false + if cache[1] == obj: return true + return isObjSlowPath(obj, subclass, cache) + proc isObj(obj, subclass: PNimType): bool {.compilerproc.} = # checks if obj is of type subclass: var x = obj diff --git a/lib/system/excpt.nim b/lib/system/excpt.nim index 2f7c5ed51..63a61183f 100644 --- a/lib/system/excpt.nim +++ b/lib/system/excpt.nim @@ -77,7 +77,7 @@ proc popCurrentException {.compilerRtl, inl.} = # some platforms have native support for stack traces: const - nativeStackTraceSupported = (defined(macosx) or defined(linux)) and + nativeStackTraceSupported* = (defined(macosx) or defined(linux)) and not nimrodStackTrace hasSomeStackTrace = nimrodStackTrace or defined(nativeStackTrace) and nativeStackTraceSupported @@ -298,7 +298,13 @@ when not defined(noSignalHandler): elif s == SIGILL: action("SIGILL: Illegal operation.\n") elif s == SIGBUS: action("SIGBUS: Illegal storage access. (Attempt to read from nil?)\n") - else: action("unknown signal\n") + else: + block platformSpecificSignal: + when defined(SIGPIPE): + if s == SIGPIPE: + action("SIGPIPE: Pipe closed.\n") + break platformSpecificSignal + action("unknown signal\n") # print stack trace and quit when hasSomeStackTrace: @@ -323,6 +329,8 @@ when not defined(noSignalHandler): c_signal(SIGFPE, signalHandler) c_signal(SIGILL, signalHandler) c_signal(SIGBUS, signalHandler) + when defined(SIGPIPE): + c_signal(SIGPIPE, signalHandler) registerSignalHandler() # call it in initialization section diff --git a/lib/system/gc_ms.nim b/lib/system/gc_ms.nim index 3c99a57e1..05bcdcc82 100644 --- a/lib/system/gc_ms.nim +++ b/lib/system/gc_ms.nim @@ -48,12 +48,15 @@ type # non-zero count table stackBottom: pointer cycleThreshold: int + when useCellIds: + idGenerator: int when withBitvectors: allocated, marked: TCellSet tempStack: TCellSeq # temporary stack for recursion elimination recGcLock: int # prevent recursion via finalizers; no thread lock region: TMemRegion # garbage collected region stat: TGcStat + additionalRoots: TCellSeq # dummy roots for GC_ref/unref var gch {.rtlThreadVar.}: TGcHeap @@ -131,13 +134,27 @@ proc prepareDealloc(cell: PCell) = (cast[TFinalizer](cell.typ.finalizer))(cellToUsr(cell)) dec(gch.recGcLock) -proc nimGCref(p: pointer) {.compilerProc, inline.} = +proc nimGCref(p: pointer) {.compilerProc.} = # we keep it from being collected by pretending it's not even allocated: - when withBitvectors: excl(gch.allocated, usrToCell(p)) - else: usrToCell(p).refcount = rcBlack -proc nimGCunref(p: pointer) {.compilerProc, inline.} = - when withBitvectors: incl(gch.allocated, usrToCell(p)) - else: usrToCell(p).refcount = rcWhite + when false: + when withBitvectors: excl(gch.allocated, usrToCell(p)) + else: usrToCell(p).refcount = rcBlack + add(gch.additionalRoots, usrToCell(p)) + +proc nimGCunref(p: pointer) {.compilerProc.} = + let cell = usrToCell(p) + var L = gch.additionalRoots.len-1 + var i = L + let d = gch.additionalRoots.d + while i >= 0: + if d[i] == cell: + d[i] = d[L] + dec gch.additionalRoots.len + break + dec(i) + when false: + when withBitvectors: incl(gch.allocated, usrToCell(p)) + else: usrToCell(p).refcount = rcWhite proc initGC() = when not defined(useNimRtl): @@ -146,6 +163,7 @@ proc initGC() = gch.stat.maxThreshold = 0 gch.stat.maxStackSize = 0 init(gch.tempStack) + init(gch.additionalRoots) when withBitvectors: Init(gch.allocated) init(gch.marked) @@ -212,8 +230,16 @@ proc rawNewObj(typ: PNimType, size: int, gch: var TGcHeap): pointer = res.refcount = 0 release(gch) when withBitvectors: incl(gch.allocated, res) + when useCellIds: + inc gch.idGenerator + res.id = gch.idGenerator result = cellToUsr(res) +when useCellIds: + proc getCellId*[T](x: ref T): int = + let p = usrToCell(cast[pointer](x)) + result = p.id + {.pop.} proc newObj(typ: PNimType, size: int): pointer {.compilerRtl.} = @@ -262,6 +288,9 @@ proc growObj(old: pointer, newsize: int, gch: var TGcHeap): pointer = else: zeroMem(ol, sizeof(TCell)) when withBitvectors: incl(gch.allocated, res) + when useCellIds: + inc gch.idGenerator + res.id = gch.idGenerator release(gch) result = cellToUsr(res) when defined(memProfiler): nimProfile(newsize-oldsize) @@ -284,6 +313,7 @@ proc mark(gch: var TGcHeap, c: PCell) = if not containsOrIncl(gch.marked, d): forAllChildren(d, waMarkPrecise) else: + # XXX no 'if c.refCount != rcBlack' here? c.refCount = rcBlack gcAssert gch.tempStack.len == 0, "stack not empty!" forAllChildren(c, waMarkPrecise) @@ -332,8 +362,19 @@ proc sweep(gch: var TGcHeap) = if c.refcount == rcBlack: c.refcount = rcWhite else: freeCyclicCell(gch, c) +when false: + proc newGcInvariant*() = + for x in allObjects(gch.region): + if isCell(x): + var c = cast[PCell](x) + if c.typ == nil: + writeStackTrace() + quit 1 + proc markGlobals(gch: var TGcHeap) = for i in 0 .. < globalMarkersLen: globalMarkers[i]() + let d = gch.additionalRoots.d + for i in 0 .. < gch.additionalRoots.len: mark(gch, d[i]) proc gcMark(gch: var TGcHeap, p: pointer) {.inline.} = # the addresses are not as cells on the stack, so turn them to cells: diff --git a/lib/system/inclrtl.nim b/lib/system/inclrtl.nim index 12eb90162..5c82db4da 100644 --- a/lib/system/inclrtl.nim +++ b/lib/system/inclrtl.nim @@ -1,7 +1,7 @@ # # # Nimrod's Runtime Library -# (c) Copyright 2013 Andreas Rumpf +# (c) Copyright 2014 Andreas Rumpf # # See the file "copying.txt", included in this # distribution, for details about the copyright. diff --git a/lib/system/sets.nim b/lib/system/sets.nim index 043d37533..794c65cb8 100644 --- a/lib/system/sets.nim +++ b/lib/system/sets.nim @@ -10,7 +10,7 @@ # set handling type - TNimSet = array [0..4*2048-1, int8] + TNimSet = array [0..4*2048-1, uint8] proc countBits32(n: int32): int {.compilerproc.} = var v = n @@ -25,4 +25,4 @@ proc countBits64(n: int64): int {.compilerproc.} = proc cardSet(s: TNimSet, len: int): int {.compilerproc.} = result = 0 for i in countup(0, len-1): - inc(result, countBits32(int32(ze(s[i])))) + inc(result, countBits32(int32(s[i]))) diff --git a/lib/system/sysio.nim b/lib/system/sysio.nim index 02c17b92b..32d4c3e91 100644 --- a/lib/system/sysio.nim +++ b/lib/system/sysio.nim @@ -115,10 +115,14 @@ proc readAllBuffer(file: TFile): string = # bytes we need to read before the buffer is empty. result = "" var buffer = newString(BufSize) - var bytesRead = BufSize - while bytesRead == BufSize: - bytesRead = readBuffer(file, addr(buffer[0]), BufSize) - result.add(buffer) + while true: + var bytesRead = readBuffer(file, addr(buffer[0]), BufSize) + if bytesRead == BufSize: + result.add(buffer) + else: + buffer.setLen(bytesRead) + result.add(buffer) + break proc rawFileSize(file: TFile): int = # this does not raise an error opposed to `getFileSize` diff --git a/lib/system/sysspawn.nim b/lib/system/sysspawn.nim index dabf35a3e..95cdba65d 100644 --- a/lib/system/sysspawn.nim +++ b/lib/system/sysspawn.nim @@ -14,30 +14,6 @@ when not defined(NimString): {.push stackTrace:off.} -when (defined(x86) or defined(amd64)) and defined(gcc): - proc cpuRelax {.inline.} = - {.emit: """asm volatile("pause" ::: "memory");""".} -elif (defined(x86) or defined(amd64)) and defined(vcc): - proc cpuRelax {.importc: "YieldProcessor", header: "<windows.h>".} -elif defined(intelc): - proc cpuRelax {.importc: "_mm_pause", header: "xmmintrin.h".} -elif false: - from os import sleep - - proc cpuRelax {.inline.} = os.sleep(1) - -when defined(windows) and not defined(gcc): - proc interlockedCompareExchange(p: pointer; exchange, comparand: int32): int32 - {.importc: "InterlockedCompareExchange", header: "<windows.h>", cdecl.} - - proc cas(p: ptr bool; oldValue, newValue: bool): bool = - interlockedCompareExchange(p, newValue.int32, oldValue.int32) != 0 - -else: - # this is valid for GCC and Intel C++ - proc cas(p: ptr bool; oldValue, newValue: bool): bool - {.importc: "__sync_bool_compare_and_swap", nodecl.} - # We declare our own condition variables here to get rid of the dummy lock # on Windows: @@ -54,6 +30,9 @@ proc createCondVar(): CondVar = initSysLock(result.stupidLock) #acquireSys(result.stupidLock) +proc destroyCondVar(c: var CondVar) {.inline.} = + deinitSysCond(c.c) + proc await(cv: var CondVar) = when defined(posix): acquireSys(cv.stupidLock) @@ -100,6 +79,26 @@ proc signal(cv: var FastCondVar) = #if cas(addr cv.slowPath, true, false): signal(cv.slow) +type + Barrier* {.compilerProc.} = object + counter: int + cv: CondVar + +proc barrierEnter*(b: ptr Barrier) {.compilerProc.} = + atomicInc b.counter + +proc barrierLeave*(b: ptr Barrier) {.compilerProc.} = + atomicDec b.counter + if b.counter <= 0: signal(b.cv) + +proc openBarrier*(b: ptr Barrier) {.compilerProc.} = + b.counter = 0 + b.cv = createCondVar() + +proc closeBarrier*(b: ptr Barrier) {.compilerProc.} = + await(b.cv) + destroyCondVar(b.cv) + {.pop.} # ---------------------------------------------------------------------------- diff --git a/lib/system/threads.nim b/lib/system/threads.nim index 0d52e4d09..d3b3aa457 100644 --- a/lib/system/threads.nim +++ b/lib/system/threads.nim @@ -243,7 +243,7 @@ when not defined(useNimRtl): # on UNIX, the GC uses ``SIGFREEZE`` to tell every thread to stop so that # the GC can examine the stacks? - proc stopTheWord() = nil + proc stopTheWord() = discard # We jump through some hops here to ensure that Nimrod thread procs can have # the Nimrod calling convention. This is needed because thread procs are diff --git a/lib/windows/windows.nim b/lib/windows/windows.nim index dd743ffa4..5fd9127b3 100644 --- a/lib/windows/windows.nim +++ b/lib/windows/windows.nim @@ -62,7 +62,7 @@ type # BaseTsd.h -- Type definitions for the basic sized types type # WinDef.h -- Basic Windows Type Definitions # BaseTypes - UINT = int32 + WINUINT* = int32 ULONG* = int PULONG* = ptr int USHORT* = int16 @@ -137,7 +137,7 @@ type # WinDef.h -- Basic Windows Type Definitions HFILE* = HANDLE HCURSOR* = HANDLE # = HICON - COLORREF* = int + COLORREF* = DWORD LPCOLORREF* = ptr COLORREF POINT* {.final, pure.} = object @@ -238,7 +238,7 @@ type CALTYPE* = int CALID* = int CCHAR* = char - TCOLORREF* = int + TCOLORREF* = COLORREF WINT* = int32 PINTEGER* = ptr int32 PBOOL* = ptr WINBOOL @@ -377,32 +377,32 @@ type # Definitions for callback procedures # type - BFFCALLBACK* = proc (para1: HWND, para2: UINT, para3: LPARAM, para4: LPARAM): int32{. + BFFCALLBACK* = proc (para1: HWND, para2: WINUINT, para3: LPARAM, para4: LPARAM): int32{. stdcall.} - LPCCHOOKPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, para4: LPARAM): UINT{. + LPCCHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. stdcall.} - LPCFHOOKPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, para4: LPARAM): UINT{. + LPCFHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. stdcall.} PTHREAD_START_ROUTINE* = Pointer LPTHREAD_START_ROUTINE* = PTHREAD_START_ROUTINE EDITSTREAMCALLBACK* = proc (para1: DWORD, para2: LPBYTE, para3: LONG, para4: LONG): DWORD{.stdcall.} - LPFRHOOKPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, para4: LPARAM): UINT{. + LPFRHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. stdcall.} - LPOFNHOOKPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, para4: LPARAM): UINT{. + LPOFNHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): WINUINT{. stdcall.} - LPPRINTHOOKPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, - para4: LPARAM): UINT{.stdcall.} - LPSETUPHOOKPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, - para4: LPARAM): UINT{.stdcall.} - DLGPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, para4: LPARAM): LRESULT{. + LPPRINTHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, + para4: LPARAM): WINUINT{.stdcall.} + LPSETUPHOOKPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, + para4: LPARAM): WINUINT{.stdcall.} + DLGPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): LRESULT{. stdcall.} - PFNPROPSHEETCALLBACK* = proc (para1: HWND, para2: UINT, para3: LPARAM): int32{. + PFNPROPSHEETCALLBACK* = proc (para1: HWND, para2: WINUINT, para3: LPARAM): int32{. stdcall.} LPSERVICE_MAIN_FUNCTION* = proc (para1: DWORD, para2: LPTSTR){.stdcall.} PFNTVCOMPARE* = proc (para1: LPARAM, para2: LPARAM, para3: LPARAM): int32{. stdcall.} - WNDPROC* = proc (para1: HWND, para2: UINT, para3: WPARAM, para4: LPARAM): LRESULT{. + WNDPROC* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, para4: LPARAM): LRESULT{. stdcall.} FARPROC* = pointer TFarProc* = FARPROC @@ -416,9 +416,9 @@ type DESKTOPENUMPROC* = FARPROC ENUMWINDOWSPROC* = proc (para1: HWND, para2: LPARAM): WINBOOL{.stdcall.} ENUMWINDOWSTATIONPROC* = proc (para1: LPTSTR, para2: LPARAM): WINBOOL{.stdcall.} - SENDASYNCPROC* = proc (para1: HWND, para2: UINT, para3: DWORD, para4: LRESULT){. + SENDASYNCPROC* = proc (para1: HWND, para2: WINUINT, para3: DWORD, para4: LRESULT){. stdcall.} - TIMERPROC* = proc (para1: HWND, para2: UINT, para3: UINT, para4: DWORD){. + TIMERPROC* = proc (para1: HWND, para2: WINUINT, para3: WINUINT, para4: DWORD){. stdcall.} GRAYSTRINGPROC* = FARPROC DRAWSTATEPROC* = proc (para1: HDC, para2: LPARAM, para3: WPARAM, para4: int32, @@ -432,10 +432,10 @@ type ENUMOBJECTSPROC* = proc (para1: LPVOID, para2: LPARAM){.stdcall.} LINEDDAPROC* = proc (para1: int32, para2: int32, para3: LPARAM){.stdcall.} TABORTPROC* = proc (para1: HDC, para2: int32): WINBOOL{.stdcall.} - LPPAGEPAINTHOOK* = proc (para1: HWND, para2: UINT, para3: WPARAM, - para4: LPARAM): UINT{.stdcall.} - LPPAGESETUPHOOK* = proc (para1: HWND, para2: UINT, para3: WPARAM, - para4: LPARAM): UINT{.stdcall.} + LPPAGEPAINTHOOK* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, + para4: LPARAM): WINUINT{.stdcall.} + LPPAGESETUPHOOK* = proc (para1: HWND, para2: WINUINT, para3: WPARAM, + para4: LPARAM): WINUINT{.stdcall.} ICMENUMPROC* = proc (para1: LPTSTR, para2: LPARAM): int32{.stdcall.} EDITWORDBREAKPROCEX* = proc (para1: cstring, para2: LONG, para3: int8, para4: WINT): LONG{.stdcall.} @@ -448,9 +448,9 @@ type CALINFO_ENUMPROC* = proc (para1: LPTSTR): WINBOOL{.stdcall.} PHANDLER_ROUTINE* = proc (para1: DWORD): WINBOOL{.stdcall.} LPHANDLER_FUNCTION* = proc (para1: DWORD): WINBOOL{.stdcall.} - PFNGETPROFILEPATH* = proc (para1: LPCTSTR, para2: LPSTR, para3: UINT): UINT{. + PFNGETPROFILEPATH* = proc (para1: LPCTSTR, para2: LPSTR, para3: WINUINT): WINUINT{. stdcall.} - PFNRECONCILEPROFILE* = proc (para1: LPCTSTR, para2: LPCTSTR, para3: DWORD): UINT{. + PFNRECONCILEPROFILE* = proc (para1: LPCTSTR, para2: LPCTSTR, para3: DWORD): WINUINT{. stdcall.} PFNPROCESSPOLICIES* = proc (para1: HWND, para2: LPCTSTR, para3: LPCTSTR, para4: LPCTSTR, para5: DWORD): WINBOOL{.stdcall.} @@ -498,7 +498,7 @@ else: SERVICES_FAILED_DATABASE* = SERVICES_FAILED_DATABASEA SC_GROUP_IDENTIFIER* = SC_GROUP_IDENTIFIERA type - PFNCALLBACK* = proc (para1, para2: UINT, para3: HCONV, para4, para5: HSZ, + PFNCALLBACK* = proc (para1, para2: WINUINT, para3: HCONV, para4, para5: HSZ, para6: HDDEDATA, para7, para8: DWORD): HDDEData{.stdcall.} CALLB* = PFNCALLBACK SECURITY_CONTEXT_TRACKING_MODE* = WINBOOL @@ -6872,7 +6872,7 @@ type va_list* = cstring TABC* {.final, pure.} = object abcA*: int32 - abcB*: UINT + abcB*: WINUINT abcC*: int32 LPABC* = ptr TABC @@ -6913,7 +6913,7 @@ type TACCESS_DENIED_ACE* = ACCESS_DENIED_ACE ACCESSTIMEOUT* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT dwFlags*: DWORD iTimeOutMSec*: DWORD @@ -6982,7 +6982,7 @@ type TADDJOB_INFO_1* = ADDJOB_INFO_1 PADDJOB_INFO_1* = ptr ADDJOB_INFO_1 ANIMATIONINFO* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT iMinAnimate*: int32 LPANIMATIONINFO* = ptr ANIMATIONINFO @@ -6992,8 +6992,8 @@ type APPBARDATA* {.final, pure.} = object cbSize*: DWORD hWnd*: HWND - uCallbackMessage*: UINT - uEdge*: UINT + uCallbackMessage*: WINUINT + uEdge*: WINUINT rc*: RECT lParam*: LPARAM @@ -7147,7 +7147,7 @@ type pidlRoot*: LPCITEMIDLIST pszDisplayName*: LPSTR lpszTitle*: LPCSTR - ulFlags*: UINT + ulFlags*: WINUINT lpfn*: BFFCALLBACK lParam*: LPARAM iImage*: int32 @@ -7244,7 +7244,7 @@ type TCHAR_INFO* = CHAR_INFO PCHAR_INFO* = ptr CHAR_INFO CHARFORMAT* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT dwMask*: DWORD dwEffects*: DWORD yHeight*: LONG @@ -7276,8 +7276,8 @@ type TFONTSIGNATURE* = FONTSIGNATURE PFONTSIGNATURE* = ptr FONTSIGNATURE CHARSETINFO* {.final, pure.} = object - ciCharset*: UINT - ciACP*: UINT + ciCharset*: WINUINT + ciACP*: WINUINT fs*: FONTSIGNATURE LPCHARSETINFO* = ptr CHARSETINFO @@ -7359,15 +7359,15 @@ type LPCHOOSEFONT* = ptr TCHOOSEFONT PCHOOSEFONT* = ptr TCHOOSEFONT CIDA* {.final, pure.} = object - cidl*: UINT - aoffset*: array[0..0, UINT] + cidl*: WINUINT + aoffset*: array[0..0, WINUINT] LPIDA* = ptr CIDA TIDA* = CIDA PIDA* = ptr CIDA CLIENTCREATESTRUCT* {.final, pure.} = object hWindowMenu*: HANDLE - idFirstChild*: UINT + idFirstChild*: WINUINT LPCLIENTCREATESTRUCT* = ptr CLIENTCREATESTRUCT TCLIENTCREATESTRUCT* = CLIENTCREATESTRUCT @@ -7537,12 +7537,12 @@ type TCOMMTIMEOUTS* = COMMTIMEOUTS PCOMMTIMEOUTS* = ptr COMMTIMEOUTS COMPAREITEMSTRUCT* {.final, pure.} = object - CtlType*: UINT - CtlID*: UINT + CtlType*: WINUINT + CtlID*: WINUINT hwndItem*: HWND - itemID1*: UINT + itemID1*: WINUINT itemData1*: ULONG_PTR - itemID2*: UINT + itemID2*: WINUINT itemData2*: ULONG_PTR TCOMPAREITEMSTRUCT* = COMPAREITEMSTRUCT @@ -7936,9 +7936,9 @@ type PSECURITY_QUALITY_OF_SERVICE* = ptr SECURITY_QUALITY_OF_SERVICE TSECURITYQUALITYOFSERVICE* = SECURITY_QUALITY_OF_SERVICE CONVCONTEXT* {.final, pure.} = object - cb*: UINT - wFlags*: UINT - wCountryID*: UINT + cb*: WINUINT + wFlags*: WINUINT + wCountryID*: WINUINT iCodePage*: int32 dwLangID*: DWORD dwSecurity*: DWORD @@ -7954,11 +7954,11 @@ type hszServiceReq*: HSZ hszTopic*: HSZ hszItem*: HSZ - wFmt*: UINT - wType*: UINT - wStatus*: UINT - wConvst*: UINT - wLastError*: UINT + wFmt*: WINUINT + wType*: WINUINT + wStatus*: WINUINT + wConvst*: WINUINT + wLastError*: WINUINT hConvList*: HCONVLIST ConvCtxt*: CONVCONTEXT hwnd*: HWND @@ -7974,7 +7974,7 @@ type TCOPYDATASTRUCT* = COPYDATASTRUCT PCOPYDATASTRUCT* = ptr COPYDATASTRUCT CPINFO* {.final, pure.} = object - MaxCharSize*: UINT + MaxCharSize*: WINUINT DefaultChar*: array[0..(MAX_DEFAULTCHAR) - 1, int8] LeadByte*: array[0..(MAX_LEADBYTES) - 1, int8] @@ -8012,13 +8012,13 @@ type PCREATETHREADDEBUGINFO* = ptr CREATE_THREAD_DEBUG_INFO CURRENCYFMT* {.final, pure.} = object - NumDigits*: UINT - LeadingZero*: UINT - Grouping*: UINT + NumDigits*: WINUINT + LeadingZero*: WINUINT + Grouping*: WINUINT lpDecimalSep*: LPTSTR lpThousandSep*: LPTSTR - NegativeOrder*: UINT - PositiveOrder*: UINT + NegativeOrder*: WINUINT + PositiveOrder*: WINUINT lpCurrencySymbol*: LPTSTR Tcurrencyfmt* = CURRENCYFMT @@ -8047,7 +8047,7 @@ type CWPSTRUCT* {.final, pure.} = object lParam*: LPARAM wParam*: WPARAM - message*: UINT + message*: WINUINT hwnd*: HWND TCWPSTRUCT* = CWPSTRUCT @@ -8161,8 +8161,8 @@ proc fAckReq*(a: var DDELN): int16 proc set_fAckReq*(a: var DDELN, fAckReq: int16) type DDEML_MSG_HOOK_DATA* {.final, pure.} = object - uiLo*: UINT - uiHi*: UINT + uiLo*: WINUINT + uiHi*: WINUINT cbData*: DWORD Data*: array[0..7, DWORD] @@ -8329,9 +8329,9 @@ type TDEBUGHOOKINFO* = DEBUGHOOKINFO PDEBUGHOOKINFO* = ptr DEBUGHOOKINFO DELETEITEMSTRUCT* {.final, pure.} = object - CtlType*: UINT - CtlID*: UINT - itemID*: UINT + CtlType*: WINUINT + CtlID*: WINUINT + itemID*: WINUINT hwndItem*: HWND itemData*: ULONG_PTR @@ -8572,7 +8572,7 @@ type TDOCINFOA* = DOCINFO PDOCINFO* = ptr DOCINFO DRAGLISTINFO* {.final, pure.} = object - uNotification*: UINT + uNotification*: WINUINT hWnd*: HWND ptCursor*: POINT @@ -8580,11 +8580,11 @@ type TDRAGLISTINFO* = DRAGLISTINFO PDRAGLISTINFO* = ptr DRAGLISTINFO DRAWITEMSTRUCT* {.final, pure.} = object - CtlType*: UINT - CtlID*: UINT - itemID*: UINT - itemAction*: UINT - itemState*: UINT + CtlType*: WINUINT + CtlID*: WINUINT + itemID*: WINUINT + itemAction*: WINUINT + itemState*: WINUINT hwndItem*: HWND hDC*: HDC rcItem*: RECT @@ -8594,11 +8594,11 @@ type TDRAWITEMSTRUCT* = DRAWITEMSTRUCT PDRAWITEMSTRUCT* = ptr DRAWITEMSTRUCT DRAWTEXTPARAMS* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT iTabLength*: int32 iLeftMargin*: int32 iRightMargin*: int32 - uiLengthDrawn*: UINT + uiLengthDrawn*: WINUINT LPDRAWTEXTPARAMS* = ptr DRAWTEXTPARAMS TDRAWTEXTPARAMS* = DRAWTEXTPARAMS @@ -8720,7 +8720,7 @@ type TEMRBITBLT* = EMRBITBLT PEMRBITBLT* = ptr EMRBITBLT LOGBRUSH* {.final, pure.} = object - lbStyle*: UINT + lbStyle*: WINUINT lbColor*: COLORREF lbHatch*: LONG @@ -8806,7 +8806,7 @@ type TEMRCREATEPALETTE* = EMRCREATEPALETTE PEMRCREATEPALETTE* = ptr EMRCREATEPALETTE LOGPEN* {.final, pure.} = object - lopnStyle*: UINT + lopnStyle*: WINUINT lopnWidth*: POINT lopnColor*: COLORREF @@ -8881,9 +8881,9 @@ type TEMREXTCREATEFONTINDIRECTW* = EMREXTCREATEFONTINDIRECTW PEMREXTCREATEFONTINDIRECTW* = ptr EMREXTCREATEFONTINDIRECTW EXTLOGPEN* {.final, pure.} = object - elpPenStyle*: UINT - elpWidth*: UINT - elpBrushStyle*: UINT + elpPenStyle*: WINUINT + elpWidth*: WINUINT + elpBrushStyle*: WINUINT elpColor*: COLORREF elpHatch*: LONG elpNumEntries*: DWORD @@ -9424,8 +9424,8 @@ type PEMRENABLEICM* = ptr EMRSELECTCLIPPATH NMHDR* {.final, pure.} = object hwndFrom*: HWND - idFrom*: UINT - code*: UINT + idFrom*: WINUINT + code*: WINUINT TNMHDR* = NMHDR PNMHDR* = ptr NMHDR @@ -9483,7 +9483,7 @@ type PENHMETARECORD* = ptr TENHMETARECORD TENPROTECTED* {.final, pure.} = object nmhdr*: NMHDR - msg*: UINT + msg*: WINUINT wParam*: WPARAM lParam*: LPARAM chrg*: CHARRANGE @@ -9546,9 +9546,9 @@ type TEVENTLOGRECORD* = EVENTLOGRECORD PEVENTLOGRECORD* = ptr EVENTLOGRECORD EVENTMSG* {.final, pure.} = object - message*: UINT - paramL*: UINT - paramH*: UINT + message*: WINUINT + paramL*: WINUINT + paramH*: WINUINT time*: DWORD hwnd*: HWND @@ -9570,7 +9570,7 @@ type TEXTBUTTON* = EXT_BUTTON PEXTBUTTON* = ptr EXT_BUTTON FILTERKEYS* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT dwFlags*: DWORD iWaitMSec*: DWORD iDelayMSec*: DWORD @@ -9646,7 +9646,7 @@ type dwSize*: DWORD szMenuName*: array[0..(MENU_TEXT_LEN) - 1, TCHAR] hMenu*: HMENU - wMenuDelta*: UINT + wMenuDelta*: WINUINT TFMSLOAD* = FMS_LOAD PFMSLOAD* = ptr FMS_LOAD @@ -9694,13 +9694,13 @@ type GCP_RESULTS* {.final, pure.} = object lStructSize*: DWORD lpOutString*: LPTSTR - lpOrder*: ptr UINT + lpOrder*: ptr WINUINT lpDx*: ptr WINT lpCaretPos*: ptr WINT lpClass*: LPTSTR - lpGlyphs*: ptr UINT - nGlyphs*: UINT - nMaxFit*: UINT + lpGlyphs*: ptr WINUINT + nGlyphs*: WINUINT + nMaxFit*: WINUINT LPGCP_RESULTS* = ptr GCP_RESULTS TGCPRESULTS* = GCP_RESULTS @@ -9714,8 +9714,8 @@ type PGENERIC_MAPPING* = ptr GENERIC_MAPPING TGENERICMAPPING* = GENERIC_MAPPING GLYPHMETRICS* {.final, pure.} = object - gmBlackBoxX*: UINT - gmBlackBoxY*: UINT + gmBlackBoxX*: WINUINT + gmBlackBoxY*: WINUINT gmptGlyphOrigin*: POINT gmCellIncX*: SHORT gmCellIncY*: SHORT @@ -9730,13 +9730,13 @@ type LPHANDLETABLE* = ptr HANDLETABLE HD_HITTESTINFO* {.final, pure.} = object pt*: POINT - flags*: UINT + flags*: WINUINT iItem*: int32 THDHITTESTINFO* = HD_HITTESTINFO PHDHITTESTINFO* = ptr HD_HITTESTINFO HD_ITEM* {.final, pure.} = object - mask*: UINT + mask*: WINUINT cxy*: int32 pszText*: LPTSTR hbm*: HBITMAP @@ -9753,7 +9753,7 @@ type y*: int32 cx*: int32 cy*: int32 - flags*: UINT + flags*: WINUINT LPWINDOWPOS* = ptr WINDOWPOS TWINDOWPOS* = WINDOWPOS @@ -9773,7 +9773,7 @@ type THDNOTIFY* = HD_NOTIFY PHDNOTIFY* = ptr HD_NOTIFY HELPINFO* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT iContextType*: int32 iCtrlId*: int32 hItemHandle*: HANDLE @@ -9795,7 +9795,7 @@ type THELPWININFO* = HELPWININFO PHELPWININFO* = ptr HELPWININFO HIGHCONTRAST* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT dwFlags*: DWORD lpszDefaultScheme*: LPTSTR @@ -9818,7 +9818,7 @@ type TICONINFO* = ICONINFO PICONINFO* = ptr ICONINFO ICONMETRICS* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT iHorzSpacing*: int32 iVertSpacing*: int32 iTitleWrap*: int32 @@ -9860,7 +9860,7 @@ type TWINDOWBUFFERSIZERECORD* = WINDOW_BUFFER_SIZE_RECORD PWINDOWBUFFERSIZERECORD* = ptr WINDOW_BUFFER_SIZE_RECORD MENU_EVENT_RECORD* {.final, pure.} = object - dwCommandId*: UINT + dwCommandId*: WINUINT PMENU_EVENT_RECORD* = ptr MENU_EVENT_RECORD TMENUEVENTRECORD* = MENU_EVENT_RECORD @@ -10039,7 +10039,7 @@ type PLUID_AND_ATTRIBUTES_ARRAY* = ptr LUID_AND_ATTRIBUTES_ARRAY TLUIDANDATTRIBUTESARRAY* = LUID_AND_ATTRIBUTES_ARRAY LV_COLUMN* {.final, pure.} = object - mask*: UINT + mask*: WINUINT fmt*: int32 cx*: int32 pszText*: LPTSTR @@ -10049,11 +10049,11 @@ type TLVCOLUMN* = LV_COLUMN PLVCOLUMN* = ptr LV_COLUMN LV_ITEM* {.final, pure.} = object - mask*: UINT + mask*: WINUINT iItem*: int32 iSubItem*: int32 - state*: UINT - stateMask*: UINT + state*: WINUINT + stateMask*: WINUINT pszText*: LPTSTR cchTextMax*: int32 iImage*: int32 @@ -10068,17 +10068,17 @@ type TLVDISPINFO* = LV_DISPINFO PLVDISPINFO* = ptr LV_DISPINFO LV_FINDINFO* {.final, pure.} = object - flags*: UINT + flags*: WINUINT psz*: LPCTSTR lParam*: LPARAM pt*: POINT - vkDirection*: UINT + vkDirection*: WINUINT TLVFINDINFO* = LV_FINDINFO PLVFINDINFO* = ptr LV_FINDINFO LV_HITTESTINFO* {.final, pure.} = object pt*: POINT - flags*: UINT + flags*: WINUINT iItem*: int32 TLVHITTESTINFO* = LV_HITTESTINFO @@ -10086,7 +10086,7 @@ type LV_KEYDOWN* {.final, pure.} = object hdr*: NMHDR wVKey*: int16 - flags*: UINT + flags*: WINUINT TLVKEYDOWN* = LV_KEYDOWN PLVKEYDOWN* = ptr LV_KEYDOWN @@ -10113,11 +10113,11 @@ type TMDICREATESTRUCT* = MDICREATESTRUCT PMDICREATESTRUCT* = ptr MDICREATESTRUCT MEASUREITEMSTRUCT* {.final, pure.} = object - CtlType*: UINT - CtlID*: UINT - itemID*: UINT - itemWidth*: UINT - itemHeight*: UINT + CtlType*: WINUINT + CtlID*: WINUINT + itemID*: WINUINT + itemWidth*: WINUINT + itemHeight*: WINUINT itemData*: ULONG_PTR LPMEASUREITEMSTRUCT* = ptr MEASUREITEMSTRUCT @@ -10163,7 +10163,7 @@ type MENUEX_TEMPLATE_ITEM* {.final, pure.} = object dwType*: DWORD dwState*: DWORD - uId*: UINT + uId*: WINUINT bResInfo*: int8 szText*: array[0..0, WCHAR] dwHelpId*: DWORD @@ -10174,7 +10174,7 @@ type cbSize*: DWORD fMask*: DWORD dwStyle*: DWORD - cyMax*: UINT + cyMax*: WINUINT hbrBack*: HBRUSH dwContextHelpID*: DWORD dwMenuData*: ULONG_PTR @@ -10184,17 +10184,17 @@ type TMENUINFO* = MENUINFO PMENUINFO* = ptr MENUINFO MENUITEMINFO* {.final, pure.} = object - cbSize*: UINT - fMask*: UINT - fType*: UINT - fState*: UINT - wID*: UINT + cbSize*: WINUINT + fMask*: WINUINT + fType*: WINUINT + fState*: WINUINT + wID*: WINUINT hSubMenu*: HMENU hbmpChecked*: HBITMAP hbmpUnchecked*: HBITMAP dwItemData*: ULONG_PTR dwTypeData*: LPTSTR - cch*: UINT + cch*: WINUINT hbmpItem*: HBITMAP LPMENUITEMINFO* = ptr MENUITEMINFO @@ -10248,7 +10248,7 @@ type TMETARECORD* = METARECORD PMETARECORD* = ptr METARECORD MINIMIZEDMETRICS* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT iWidth*: int32 iHorzGap*: int32 iVertGap*: int32 @@ -10309,12 +10309,12 @@ type TMODEMSETTINGS* = MODEMSETTINGS PMODEMSETTINGS* = ptr MODEMSETTINGS MONCBSTRUCT* {.final, pure.} = object - cb*: UINT + cb*: WINUINT dwTime*: DWORD hTask*: HANDLE dwRet*: DWORD - wType*: UINT - wFmt*: UINT + wType*: WINUINT + wFmt*: WINUINT hConv*: HCONV hsz1*: HSZ hsz2*: HSZ @@ -10328,7 +10328,7 @@ type TMONCBSTRUCT* = MONCBSTRUCT PMONCBSTRUCT* = ptr MONCBSTRUCT MONCONVSTRUCT* {.final, pure.} = object - cb*: UINT + cb*: WINUINT fConnect*: WINBOOL dwTime*: DWORD hTask*: HANDLE @@ -10340,15 +10340,15 @@ type TMONCONVSTRUCT* = MONCONVSTRUCT PMONCONVSTRUCT* = ptr MONCONVSTRUCT MONERRSTRUCT* {.final, pure.} = object - cb*: UINT - wLastError*: UINT + cb*: WINUINT + wLastError*: WINUINT dwTime*: DWORD hTask*: HANDLE TMONERRSTRUCT* = MONERRSTRUCT PMONERRSTRUCT* = ptr MONERRSTRUCT MONHSZSTRUCT* {.final, pure.} = object - cb*: UINT + cb*: WINUINT fsAction*: WINBOOL dwTime*: DWORD hsz*: HSZ @@ -10370,7 +10370,7 @@ type TMONITORINFO2* = MONITOR_INFO_2 PMONITORINFO2* = ptr MONITOR_INFO_2 MONLINKSTRUCT* {.final, pure.} = object - cb*: UINT + cb*: WINUINT dwTime*: DWORD hTask*: HANDLE fEstablished*: WINBOOL @@ -10378,7 +10378,7 @@ type hszSvc*: HSZ hszTopic*: HSZ hszItem*: HSZ - wFmt*: UINT + wFmt*: WINUINT fServer*: WINBOOL hConvServer*: HCONV hConvClient*: HCONV @@ -10386,11 +10386,11 @@ type TMONLINKSTRUCT* = MONLINKSTRUCT PMONLINKSTRUCT* = ptr MONLINKSTRUCT MONMSGSTRUCT* {.final, pure.} = object - cb*: UINT + cb*: WINUINT hwndTo*: HWND dwTime*: DWORD hTask*: HANDLE - wMsg*: UINT + wMsg*: WINUINT wParam*: WPARAM lParam*: LPARAM dmhd*: DDEML_MSG_HOOK_DATA @@ -10400,7 +10400,7 @@ type MOUSEHOOKSTRUCT* {.final, pure.} = object pt*: POINT hwnd*: HWND - wHitTestCode*: UINT + wHitTestCode*: WINUINT dwExtraInfo*: DWORD LPMOUSEHOOKSTRUCT* = ptr MOUSEHOOKSTRUCT @@ -10420,7 +10420,7 @@ type MSGBOXCALLBACK* = proc (lpHelpInfo: LPHELPINFO){.stdcall.} TMSGBOXCALLBACK* = MSGBOXCALLBACK MSGBOXPARAMS* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT hwndOwner*: HWND hInstance*: HINST lpszText*: LPCSTR @@ -10437,7 +10437,7 @@ type PMSGBOXPARAMS* = ptr MSGBOXPARAMS MSGFILTER* {.final, pure.} = object nmhdr*: NMHDR - msg*: UINT + msg*: WINUINT wParam*: WPARAM lParam*: LPARAM @@ -10546,9 +10546,9 @@ type tmPitchAndFamily*: int8 tmCharSet*: int8 ntmFlags*: DWORD - ntmSizeEM*: UINT - ntmCellHeight*: UINT - ntmAvgWidth*: UINT + ntmSizeEM*: WINUINT + ntmCellHeight*: WINUINT + ntmAvgWidth*: WINUINT TNEWTEXTMETRIC* = NEWTEXTMETRIC PNEWTEXTMETRIC* = ptr NEWTEXTMETRIC @@ -10562,19 +10562,19 @@ type hdr*: NMHDR iItem*: int32 iSubItem*: int32 - uNewState*: UINT - uOldState*: UINT - uChanged*: UINT + uNewState*: WINUINT + uOldState*: WINUINT + uChanged*: WINUINT ptAction*: POINT lParam*: LPARAM TNMLISTVIEW* = NM_LISTVIEW PNMLISTVIEW* = ptr NM_LISTVIEW TV_ITEM* {.final, pure.} = object - mask*: UINT + mask*: WINUINT hItem*: HTREEITEM - state*: UINT - stateMask*: UINT + state*: WINUINT + stateMask*: WINUINT pszText*: LPTSTR cchTextMax*: int32 iImage*: int32 @@ -10587,7 +10587,7 @@ type PTVITEM* = ptr TV_ITEM NM_TREEVIEW* {.final, pure.} = object hdr*: NMHDR - action*: UINT + action*: WINUINT itemOld*: TV_ITEM itemNew*: TV_ITEM ptDrag*: POINT @@ -10603,7 +10603,7 @@ type TNMUPDOWN* = NM_UPDOWNW PNMUPDOWN* = ptr NM_UPDOWNW NONCLIENTMETRICS* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT iBorderWidth*: int32 iScrollWidth*: int32 iScrollHeight*: int32 @@ -10666,12 +10666,12 @@ type TNSSERVICEINFO* = NS_SERVICE_INFO PNSSERVICEINFO* = ptr NS_SERVICE_INFO NUMBERFMT* {.final, pure.} = object - NumDigits*: UINT - LeadingZero*: UINT - Grouping*: UINT + NumDigits*: WINUINT + LeadingZero*: WINUINT + Grouping*: WINUINT lpDecimalSep*: LPTSTR lpThousandSep*: LPTSTR - NegativeOrder*: UINT + NegativeOrder*: WINUINT Tnumberfmt* = NUMBERFMT Pnumberfmt* = ptr NUMBERFMT @@ -10821,31 +10821,31 @@ type TTEXTMETRICW* = TEXTMETRICW PTEXTMETRICW* = ptr TEXTMETRICW OUTLINETEXTMETRIC* {.final, pure.} = object - otmSize*: UINT + otmSize*: WINUINT otmTextMetrics*: TEXTMETRIC otmFiller*: int8 otmPanoseNumber*: PANOSE - otmfsSelection*: UINT - otmfsType*: UINT + otmfsSelection*: WINUINT + otmfsType*: WINUINT otmsCharSlopeRise*: int32 otmsCharSlopeRun*: int32 otmItalicAngle*: int32 - otmEMSquare*: UINT + otmEMSquare*: WINUINT otmAscent*: int32 otmDescent*: int32 - otmLineGap*: UINT - otmsCapEmHeight*: UINT - otmsXHeight*: UINT + otmLineGap*: WINUINT + otmsCapEmHeight*: WINUINT + otmsXHeight*: WINUINT otmrcFontBox*: RECT otmMacAscent*: int32 otmMacDescent*: int32 - otmMacLineGap*: UINT - otmusMinimumPPEM*: UINT + otmMacLineGap*: WINUINT + otmusMinimumPPEM*: WINUINT otmptSubscriptSize*: POINT otmptSubscriptOffset*: POINT otmptSuperscriptSize*: POINT otmptSuperscriptOffset*: POINT - otmsStrikeoutSize*: UINT + otmsStrikeoutSize*: WINUINT otmsStrikeoutPosition*: int32 otmsUnderscoreSize*: int32 otmsUnderscorePosition*: int32 @@ -10900,7 +10900,7 @@ type TPAINTSTRUCT* = PAINTSTRUCT PPAINTSTRUCT* = ptr PAINTSTRUCT PARAFORMAT* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT dwMask*: DWORD wNumbering*: int16 wReserved*: int16 @@ -10981,9 +10981,9 @@ type POLYTEXT* {.final, pure.} = object x*: int32 y*: int32 - n*: UINT + n*: WINUINT lpstr*: LPCTSTR - uiFlags*: UINT + uiFlags*: WINUINT rcl*: RECT pdx*: ptr int32 @@ -11169,7 +11169,7 @@ type LPPROCESS_INFORMATION* = ptr PROCESS_INFORMATION TPROCESSINFORMATION* = PROCESS_INFORMATION PPROCESSINFORMATION* = ptr PROCESS_INFORMATION - LPFNPSPCALLBACK* = proc (para1: HWND, para2: UINT, para3: LPVOID): UINT{. + LPFNPSPCALLBACK* = proc (para1: HWND, para2: WINUINT, para3: LPVOID): WINUINT{. stdcall.} TFNPSPCALLBACK* = LPFNPSPCALLBACK PROPSHEETPAGE* {.final, pure.} = object @@ -11181,7 +11181,7 @@ type pfnDlgProc*: DLGPROC lParam*: LPARAM pfnCallback*: LPFNPSPCALLBACK - pcRefParent*: ptr UINT + pcRefParent*: ptr WINUINT LPPROPSHEETPAGE* = ptr PROPSHEETPAGE LPCPROPSHEETPAGE* = ptr PROPSHEETPAGE @@ -11197,7 +11197,7 @@ type hInstance*: HINST pszIcon*: LPCTSTR pszCaption*: LPCTSTR - nPages*: UINT + nPages*: WINUINT pStartPage*: LPCTSTR phpage*: ptr HPROPSHEETPAGE pfnCallback*: PFNPROPSHEETCALLBACK @@ -11243,7 +11243,7 @@ type TPSHNOTIFY* = PSHNOTIFY PPSHNOTIFY* = ptr PSHNOTIFY PUNCTUATION* {.final, pure.} = object - iSize*: UINT + iSize*: WINUINT szPunctuation*: LPSTR Tpunctuation* = PUNCTUATION @@ -11395,11 +11395,11 @@ type TRGNDATA* = RGNDATA PRGNDATA* = ptr RGNDATA SCROLLINFO* {.final, pure.} = object - cbSize*: UINT - fMask*: UINT + cbSize*: WINUINT + fMask*: WINUINT nMin*: int32 nMax*: int32 - nPage*: UINT + nPage*: WINUINT nPos*: int32 nTrackPos*: int32 @@ -11499,7 +11499,7 @@ type PFILEOPFLAGS* = ptr FILEOP_FLAGS SHFILEOPSTRUCT* {.final, pure.} = object hwnd*: HWND - wFunc*: UINT + wFunc*: WINUINT pFrom*: LPCSTR pTo*: LPCSTR fFlags*: FILEOP_FLAGS @@ -11537,7 +11537,7 @@ type TSINGLELISTENTRY* = SINGLE_LIST_ENTRY PSINGLELISTENTRY* = ptr SINGLE_LIST_ENTRY SOUNDSENTRY* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT dwFlags*: DWORD iFSTextEffect*: DWORD iFSTextEffectMSec*: DWORD @@ -11584,7 +11584,7 @@ type TSTICKYKEYS* = STICKYKEYS PSTICKYKEYS* = ptr STICKYKEYS STRRET* {.final, pure.} = object - uType*: UINT + uType*: WINUINT cStr*: array[0..(MAX_PATH) - 1, char] LPSTRRET* = ptr STRRET @@ -11709,7 +11709,7 @@ type PTAPEWRITEMARKS* = ptr TAPE_WRITE_MARKS TTBADDBITMAP* {.final, pure.} = object hInst*: HINST - nID*: UINT + nID*: WINUINT LPTBADDBITMAP* = ptr TTBADDBITMAP PTBADDBITMAP* = ptr TTBADDBITMAP @@ -11744,14 +11744,14 @@ type PTBSAVEPARAMS* = ptr TBSAVEPARAMS TC_HITTESTINFO* {.final, pure.} = object pt*: POINT - flags*: UINT + flags*: WINUINT TTCHITTESTINFO* = TC_HITTESTINFO PTCHITTESTINFO* = ptr TC_HITTESTINFO TC_ITEM* {.final, pure.} = object - mask*: UINT - lpReserved1*: UINT - lpReserved2*: UINT + mask*: WINUINT + lpReserved1*: WINUINT + lpReserved2*: WINUINT pszText*: LPTSTR cchTextMax*: int32 iImage*: int32 @@ -11760,9 +11760,9 @@ type TTCITEM* = TC_ITEM PTCITEM* = ptr TC_ITEM TC_ITEMHEADER* {.final, pure.} = object - mask*: UINT - lpReserved1*: UINT - lpReserved2*: UINT + mask*: WINUINT + lpReserved1*: WINUINT + lpReserved2*: WINUINT pszText*: LPTSTR cchTextMax*: int32 iImage*: int32 @@ -11772,7 +11772,7 @@ type TC_KEYDOWN* {.final, pure.} = object hdr*: NMHDR wVKey*: int16 - flags*: UINT + flags*: WINUINT TTCKEYDOWN* = TC_KEYDOWN PTCKEYDOWN* = ptr TC_KEYDOWN @@ -11855,10 +11855,10 @@ type PTOKENUSER* = ptr TTOKEN_USER TOOLINFO* {.final, pure.} = object - cbSize*: UINT - uFlags*: UINT + cbSize*: WINUINT + uFlags*: WINUINT hwnd*: HWND - uId*: UINT + uId*: WINUINT rect*: RECT hinst*: HINST lpszText*: LPTSTR @@ -11871,13 +11871,13 @@ type lpszText*: LPTSTR szText*: array[0..79, char] hinst*: HINST - uFlags*: UINT + uFlags*: WINUINT LPTOOLTIPTEXT* = ptr TOOLTIPTEXT TTOOLTIPTEXT* = TOOLTIPTEXT PTOOLTIPTEXT* = ptr TOOLTIPTEXT TPMPARAMS* {.final, pure.} = object - cbSize*: UINT + cbSize*: WINUINT rcExclude*: RECT LPTPMPARAMS* = ptr TPMPARAMS @@ -11923,7 +11923,7 @@ type PTVDISPINFO* = ptr TV_DISPINFO TV_HITTESTINFO* {.final, pure.} = object pt*: POINT - flags*: UINT + flags*: WINUINT hItem*: HTREEITEM LPTV_HITTESTINFO* = ptr TV_HITTESTINFO @@ -11940,7 +11940,7 @@ type TV_KEYDOWN* {.final, pure.} = object hdr*: NMHDR wVKey*: int16 - flags*: UINT + flags*: WINUINT TTVKEYDOWN* = TV_KEYDOWN PTVKEYDOWN* = ptr TV_KEYDOWN @@ -11953,8 +11953,8 @@ type TTVSORTCB* = TV_SORTCB PTVSORTCB* = ptr TV_SORTCB UDACCEL* {.final, pure.} = object - nSec*: UINT - nInc*: UINT + nSec*: WINUINT + nInc*: WINUINT TUDACCEL* = UDACCEL PUDACCEL* = ptr UDACCEL @@ -12045,9 +12045,9 @@ type TWIN32STREAMID* = WIN32_STREAM_ID PWIN32STREAMID* = ptr WIN32_STREAM_ID WINDOWPLACEMENT* {.final, pure.} = object - len*: UINT - flags*: UINT - showCmd*: UINT + len*: WINUINT + flags*: WINUINT + showCmd*: WINUINT ptMinPosition*: POINT ptMaxPosition*: POINT rcNormalPosition*: RECT @@ -12055,7 +12055,7 @@ type TWINDOWPLACEMENT* = WINDOWPLACEMENT PWINDOWPLACEMENT* = ptr WINDOWPLACEMENT WNDCLASS* {.final, pure.} = object - style*: UINT + style*: WINUINT lpfnWndProc*: WNDPROC cbClsExtra*: int32 cbWndExtra*: int32 @@ -12071,7 +12071,7 @@ type TWNDCLASSA* = WNDCLASS PWNDCLASS* = ptr WNDCLASS WNDCLASSW* {.final, pure.} = object - style*: UINT + style*: WINUINT lpfnWndProc*: WNDPROC cbClsExtra*: int32 cbWndExtra*: int32 @@ -12086,8 +12086,8 @@ type TWNDCLASSW* = WNDCLASSW PWNDCLASSW* = ptr WNDCLASSW WNDCLASSEX* {.final, pure.} = object - cbSize*: UINT - style*: UINT + cbSize*: WINUINT + style*: WINUINT lpfnWndProc*: WNDPROC cbClsExtra*: int32 cbWndExtra*: int32 @@ -12104,8 +12104,8 @@ type TWNDCLASSEXA* = WNDCLASSEX PWNDCLASSEX* = ptr WNDCLASSEX WNDCLASSEXW* {.final, pure.} = object - cbSize*: UINT - style*: UINT + cbSize*: WINUINT + style*: WINUINT lpfnWndProc*: WNDPROC cbClsExtra*: int32 cbWndExtra*: int32 @@ -12362,9 +12362,9 @@ type NOTIFYICONDATAA* {.final, pure.} = object cbSize*: DWORD Wnd*: HWND - uID*: UINT - uFlags*: UINT - uCallbackMessage*: UINT + uID*: WINUINT + uFlags*: WINUINT + uCallbackMessage*: WINUINT hIcon*: HICON szTip*: array[0..63, Char] @@ -12372,9 +12372,9 @@ type NOTIFYICONDATAW* {.final, pure.} = object cbSize*: DWORD Wnd*: HWND - uID*: UINT - uFlags*: UINT - uCallbackMessage*: UINT + uID*: WINUINT + uFlags*: WINUINT + uCallbackMessage*: WINUINT hIcon*: HICON szTip*: array[0..63, int16] @@ -13519,7 +13519,7 @@ else: type MSG* {.final, pure.} = object hwnd*: HWND - message*: UINT + message*: WINUINT wParam*: WPARAM lParam*: LPARAM time*: DWORD @@ -13530,20 +13530,20 @@ type PMSG* = ptr MSG PMessage* = ptr TMessage TMessage* {.final, pure.} = object #fields according to ICS - msg*: UINT + msg*: WINUINT wParam*: WPARAM lParam*: LPARAM Result*: LRESULT TWMSize* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT SizeType*: WPARAM Width*: HALFPARAM Height*: HALFPARAM Result*: LRESULT TWMNoParams* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: array[0..3, HALFPARAM] Result*: LRESULT @@ -13553,7 +13553,7 @@ type TWMClose* = TWMNoParams TWMQueryUIState* = TWMNoParams TWMUIState* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Action*: int16 Flags*: int16 Unused*: HRESULT @@ -13561,7 +13561,7 @@ type TWMChangeUIState* = TWMUIState TWMUpdateUIState* = TWMUIState TWMKey* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT CharCode*: int16 Unused*: int16 KeyData*: int32 @@ -13574,7 +13574,7 @@ type TWMSysKeyDown* = TWMKey TWMSysKeyUp* = TWMKey TWMMenuChar* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT User*: Char MenuFlag*: int16 Menu*: HMENU @@ -13586,7 +13586,7 @@ type TWMSysColorChange* = TWMNoParams TWMQueryDragIcon* = TWMNoParams TWMScroll* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT ScrollCode*: HALFPARAM Pos*: HALFPARAM ScrollBar*: HWND @@ -13595,59 +13595,59 @@ type TWMHScroll* = TWMScroll TWMVScroll* = TWMScroll TWMGetText* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT TextMax*: LPARAM Text*: cstring Result*: LRESULT TWMGetTextLength* = TWMNoParams TWMKillFocus* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT FocusedWnd*: HWND UnUsed*: WPARAM Result*: LRESULT TWMSetCursor* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT CursorWnd*: HWND HitTest*: HALFPARAM MouseMsg*: HALFPARAM Result*: LRESULT TWMSetFocus* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT FocusedWnd*: HWND Unused*: WPARAM Result*: LRESULT TWMSetFont* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Font*: HFONT Redraw*: HALFPARAMBOOL Unused*: HALFPARAM Result*: LRESULT TWMShowWindow* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Show*: HALFPARAMBOOL Unused*: HALFPARAM Status*: WPARAM Result*: LRESULT TWMEraseBkgnd* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT DC*: HDC Unused*: LPARAM Result*: LRESULT TWMNCHitTest* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int32 Pos*: TSmallPoint Result*: LRESULT TWMMouse* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Keys*: int32 Pos*: TSmallPoint Result*: LRESULT @@ -13659,14 +13659,14 @@ type TWMMButtonDown* = TWMMouse TWMMButtonUp* = TWMMouse TWMMouseWheel* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Keys*: int16 WheelDelta*: int16 Pos*: TSmallPoint Result*: LRESULT TWMNCHitMessage* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT HitTest*: int32 XCursor*: int16 YCursor*: int16 @@ -13684,51 +13684,51 @@ type TWMRButtonUp* = TWMMouse TWMMouseMove* = TWMMouse TWMPaint* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT DC*: HDC Unused*: int32 Result*: LRESULT TWMCommand* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT ItemID*: int16 NotifyCode*: int16 Ctl*: HWND Result*: LRESULT TWMNotify* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT IDCtrl*: int32 NMHdr*: PNMHdr Result*: LRESULT TWMPrint* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT DC*: HDC Flags*: int Result*: LRESULT TWMPrintClient* = TWMPrint TWMWinIniChange* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int Section*: cstring Result*: LRESULT TWMContextMenu* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT hWnd*: HWND Pos*: TSmallPoint Result*: LRESULT TWMNCCalcSize* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT CalcValidRects*: WINBOOL CalcSize_Params*: PNCCalcSizeParams Result*: LRESULT TWMCharToItem* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Key*: int16 CaretPos*: int16 ListBox*: HWND @@ -13737,7 +13737,7 @@ type TWMVKeyToItem* = TWMCharToItem TMyEventRange = range[0'i16..16000'i16] TWMParentNotify* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT case Event*: TMyEventRange of TMyEventRange(WM_CREATE), TMyEventRange(WM_DESTROY): ChildID*: int16 @@ -13756,7 +13756,7 @@ type Result*: LRESULT TWMSysCommand* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT CmdType*: int32 XPos*: int16 YPos*: int16 @@ -13774,13 +13774,13 @@ type # Key*: int16 TWMMove* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int Pos*: TSmallPoint Result*: LRESULT TWMWindowPosMsg* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int WindowPos*: PWindowPos Result*: LRESULT @@ -13788,101 +13788,101 @@ type TWMWindowPosChanged* = TWMWindowPosMsg TWMWindowPosChanging* = TWMWindowPosMsg TWMCompareItem* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Ctl*: HWnd CompareItemStruct*: PCompareItemStruct Result*: LRESULT TWMDeleteItem* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Ctl*: HWND DeleteItemStruct*: PDeleteItemStruct Result*: LRESULT TWMDrawItem* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Ctl*: HWND DrawItemStruct*: PDrawItemStruct Result*: LRESULT TWMMeasureItem* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT IDCtl*: HWnd MeasureItemStruct*: PMeasureItemStruct Result*: LRESULT TWMNCCreate* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int CreateStruct*: PCreateStruct Result*: LRESULT TWMInitMenuPopup* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT MenuPopup*: HMENU Pos*: int16 SystemMenu*: WordBool Result*: LRESULT TWMMenuSelect* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT IDItem*: int16 MenuFlag*: int16 Menu*: HMENU Result*: LRESULT TWMActivate* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Active*: int16 Minimized*: WordBool ActiveWindow*: HWND Result*: LRESULT TWMQueryEndSession* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Source*: int32 Unused*: int32 Result*: LRESULT TWMMDIActivate* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT DeactiveWnd*: HWND ActiveWnd*: HWND Result*: LRESULT TWMNextDlgCtl* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT CtlFocus*: int32 Handle*: WordBool Unused*: int16 Result*: LRESULT TWMHelp* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int HelpInfo*: PHelpInfo Result*: LRESULT TWMGetMinMaxInfo* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int MinMaxInfo*: PMinMaxInfo Result*: LRESULT TWMSettingChange* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Flag*: int Section*: cstring Result*: LRESULT TWMCreate* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int CreateStruct*: PCreateStruct Result*: LRESULT TWMCtlColor* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT ChildDC*: HDC ChildWnd*: HWND Result*: LRESULT @@ -13895,38 +13895,38 @@ type TWMCtlColorDlg* = TWMCtlColor TWMCtlColorEdit* = TWMCtlColor TWMInitDialog* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Focus*: HWND InitParam*: int32 Result*: LRESULT TWMNCPaint* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT RGN*: HRGN Unused*: int32 Result*: LRESULT TWMSetText* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Unused*: int32 Text*: cstring Result*: LRESULT TWMSizeClipboard* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Viewer*: HWND RC*: THandle Result*: LRESULT TWMSpoolerStatus* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT JobStatus*: LPARAM JobsLeft*: WPARAM Unused*: WPARAM Result*: LRESULT TWMStyleChange* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT StyleType*: LPARAM StyleStruct*: PStyleStruct Result*: LRESULT @@ -13934,42 +13934,42 @@ type TWMStyleChanged* = TWMStyleChange TWMStyleChanging* = TWMStyleChange TWMSysDeadChar* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT CharCode*: WPARAM Unused*: WPARAM KeyData*: LPARAM Result*: LRESULT TWMSystemError* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT ErrSpec*: WPARAM Unused*: LPARAM Result*: LRESULT TWMTimeChange* = TWMNoParams TWMTimer* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT TimerID*: LPARAM TimerProc*: TFarProc Result*: LRESULT TWMUndo* = TWMNoParams TWMVScrollClipboard* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Viewer*: HWND ScollCode*: WPARAM ThumbPos*: WPARAM Result*: LRESULT TWMDisplayChange* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT BitsPerPixel*: int Width*: WPARAM Height*: WPARAM Result*: LRESULT TWMDropFiles* {.final, pure.} = object - Msg*: UINT + Msg*: WINUINT Drop*: THANDLE Unused*: LPARAM Result*: LRESULT @@ -14042,7 +14042,7 @@ proc GetModuleFileNameA*(hModule: HINST, lpFilename: LPSTR, nSize: DWORD): DWORD stdcall, dynlib: "kernel32", importc.} proc GetModuleHandleA*(lpModuleName: LPCSTR): HMODULE{.stdcall, dynlib: "kernel32", importc.} -proc FatalAppExitA*(uAction: UINT, lpMessageText: LPCSTR){.stdcall, +proc FatalAppExitA*(uAction: WINUINT, lpMessageText: LPCSTR){.stdcall, dynlib: "kernel32", importc.} proc GetCommandLineA*(): LPSTR{.stdcall, dynlib: "kernel32", importc.} proc GetEnvironmentVariableA*(lpName: LPCSTR, lpBuffer: LPSTR, nSize: DWORD): DWORD{. @@ -14080,15 +14080,15 @@ proc GlobalAddAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "GlobalAddAtomA".} proc GlobalFindAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "GlobalFindAtomA".} -proc GlobalGetAtomNameA*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): UINT{. +proc GlobalGetAtomNameA*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{. stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameA".} proc AddAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "AddAtomA".} proc FindAtomA*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "FindAtomA".} -proc GetAtomNameA*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): UINT{.stdcall, +proc GetAtomNameA*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetAtomNameA".} -proc GetProfileIntA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: WINT): UINT{. +proc GetProfileIntA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: WINT): WINUINT{. stdcall, dynlib: "kernel32", importc: "GetProfileIntA".} proc GetProfileStringA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, lpDefault: LPCSTR, lpReturnedString: LPSTR, nSize: DWORD): DWORD{.stdcall, @@ -14101,7 +14101,7 @@ proc GetProfileSectionA*(lpAppName: LPCSTR, lpReturnedString: LPSTR, proc WriteProfileSectionA*(lpAppName: LPCSTR, lpString: LPCSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteProfileSectionA".} proc GetPrivateProfileIntA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - nDefault: WINT, lpFileName: LPCSTR): UINT{.stdcall, + nDefault: WINT, lpFileName: LPCSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetPrivateProfileIntA".} proc GetPrivateProfileStringA*(lpAppName: LPCSTR, lpKeyName: LPCSTR, lpDefault: LPCSTR, lpReturnedString: LPSTR, @@ -14117,16 +14117,16 @@ proc GetPrivateProfileSectionA*(lpAppName: LPCSTR, lpReturnedString: LPSTR, proc WritePrivateProfileSectionA*(lpAppName: LPCSTR, lpString: LPCSTR, lpFileName: LPCSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WritePrivateProfileSectionA".} -proc GetDriveTypeA*(lpRootPathName: LPCSTR): UINT{.stdcall, dynlib: "kernel32", +proc GetDriveTypeA*(lpRootPathName: LPCSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetDriveTypeA".} -proc GetSystemDirectoryA*(lpBuffer: LPSTR, uSize: UINT): UINT{.stdcall, +proc GetSystemDirectoryA*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetSystemDirectoryA".} proc GetTempPathA*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{.stdcall, dynlib: "kernel32", importc: "GetTempPathA".} proc GetTempFileNameA*(lpPathName: LPCSTR, lpPrefixString: LPCSTR, - uUnique: UINT, lpTempFileName: LPSTR): UINT{.stdcall, + uUnique: WINUINT, lpTempFileName: LPSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetTempFileNameA".} -proc GetWindowsDirectoryA*(lpBuffer: LPSTR, uSize: UINT): UINT{.stdcall, +proc GetWindowsDirectoryA*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetWindowsDirectoryA".} proc SetCurrentDirectoryA*(lpPathName: LPCSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetCurrentDirectoryA".} @@ -14267,7 +14267,7 @@ proc GetFileSecurityA*(lpFileName: LPCSTR, proc FindFirstChangeNotificationA*(lpPathName: LPCSTR, bWatchSubtree: WINBOOL, dwNotifyFilter: DWORD): HANDLE{.stdcall, dynlib: "kernel32", importc: "FindFirstChangeNotificationA".} -proc IsBadStringPtrA*(lpsz: LPCSTR, ucchMax: UINT): WINBOOL{.stdcall, +proc IsBadStringPtrA*(lpsz: LPCSTR, ucchMax: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadStringPtrA".} proc LookupAccountSidA*(lpSystemName: LPCSTR, Sid: PSID, Name: LPSTR, cbName: LPDWORD, ReferencedDomainName: LPSTR, @@ -14304,7 +14304,7 @@ proc SetComputerNameA*(lpComputerName: LPCSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetComputerNameA".} proc GetUserNameA*(lpBuffer: LPSTR, nSize: LPDWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "GetUserNameA".} -proc LoadKeyboardLayoutA*(pwszKLID: LPCSTR, Flags: UINT): HKL{.stdcall, +proc LoadKeyboardLayoutA*(pwszKLID: LPCSTR, Flags: WINUINT): HKL{.stdcall, dynlib: "user32", importc: "LoadKeyboardLayoutA".} proc GetKeyboardLayoutNameA*(pwszKLID: LPSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "GetKeyboardLayoutNameA".} @@ -14332,35 +14332,35 @@ proc GetUserObjectInformationA*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, proc SetUserObjectInformationA*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, nLength: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SetUserObjectInformationA".} -proc RegisterWindowMessageA*(lpString: LPCSTR): UINT{.stdcall, dynlib: "user32", +proc RegisterWindowMessageA*(lpString: LPCSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterWindowMessageA".} -proc GetMessageA*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc GetMessageA*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMessageA".} proc DispatchMessageA*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", importc: "DispatchMessageA".} -proc PeekMessageA*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT, wRemoveMsg: UINT): WINBOOL{.stdcall, +proc PeekMessageA*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "PeekMessageA".} -proc SendMessageA*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc SendMessageA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageA".} -proc SendMessageTimeoutA*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM, - fuFlags: UINT, uTimeout: UINT, lpdwResult: LPDWORD): LRESULT{. +proc SendMessageTimeoutA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, + fuFlags: WINUINT, uTimeout: WINUINT, lpdwResult: LPDWORD): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageTimeoutA".} -proc SendNotifyMessageA*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. +proc SendNotifyMessageA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "SendNotifyMessageA".} -proc SendMessageCallbackA*(wnd: HWND, Msg: UINT, wp: WPARAM, +proc SendMessageCallbackA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, lpResultCallBack: SENDASYNCPROC, dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SendMessageCallbackA".} -proc PostMessageA*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. +proc PostMessageA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "PostMessageA".} -proc PostThreadMessageA*(idThread: DWORD, Msg: UINT, wp: WPARAM, +proc PostThreadMessageA*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", importc: "PostThreadMessageA".} -proc DefWindowProcA*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc DefWindowProcA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefWindowProcA".} -proc CallWindowProcA*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: UINT, +proc CallWindowProcA*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "CallWindowProcA".} proc RegisterClassA*(lpWndClass: LPWNDCLASS): ATOM{.stdcall, dynlib: "user32", @@ -14398,18 +14398,18 @@ proc DialogBoxIndirectParamA*(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, proc SetDlgItemTextA*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCSTR): WINBOOL{. stdcall, dynlib: "user32", importc: "SetDlgItemTextA".} proc GetDlgItemTextA*(hDlg: HWND, nIDDlgItem: int32, lpString: LPSTR, - nMaxCount: int32): UINT{.stdcall, dynlib: "user32", + nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", importc: "GetDlgItemTextA".} -proc SendDlgItemMessageA*(hDlg: HWND, nIDDlgItem: int32, Msg: UINT, +proc SendDlgItemMessageA*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LONG{.stdcall, dynlib: "user32", importc: "SendDlgItemMessageA".} -proc DefDlgProcA*(hDlg: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc DefDlgProcA*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefDlgProcA".} proc CallMsgFilterA*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "CallMsgFilterA".} -proc RegisterClipboardFormatA*(lpszFormat: LPCSTR): UINT{.stdcall, +proc RegisterClipboardFormatA*(lpszFormat: LPCSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterClipboardFormatA".} -proc GetClipboardFormatNameA*(format: UINT, lpszFormatName: LPSTR, +proc GetClipboardFormatNameA*(format: WINUINT, lpszFormatName: LPSTR, cchMaxCount: int32): int32{.stdcall, dynlib: "user32", importc: "GetClipboardFormatNameA".} proc CharToOemA*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, @@ -14446,9 +14446,9 @@ proc VkKeyScanA*(ch: CHAR): SHORT{.stdcall, dynlib: "user32", importc: "VkKeyScanA".} proc VkKeyScanExA*(ch: CHAR, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", importc: "VkKeyScanExA".} -proc MapVirtualKeyA*(uCode: UINT, uMapType: UINT): UINT{.stdcall, +proc MapVirtualKeyA*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyA".} -proc MapVirtualKeyExA*(uCode: UINT, uMapType: UINT, dwhkl: HKL): UINT{.stdcall, +proc MapVirtualKeyExA*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyExA".} proc LoadAcceleratorsA*(hInstance: HINST, lpTableName: LPCSTR): HACCEL{.stdcall, dynlib: "user32", importc: "LoadAcceleratorsA".} @@ -14463,35 +14463,35 @@ proc LoadMenuA*(hInstance: HINST, lpMenuName: LPCSTR): HMENU{.stdcall, dynlib: "user32", importc: "LoadMenuA".} proc LoadMenuIndirectA*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, dynlib: "user32", importc: "LoadMenuIndirectA".} -proc ChangeMenuA*(menu: HMENU, cmd: UINT, lpszNewItem: LPCSTR, cmdInsert: UINT, - flags: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc ChangeMenuA*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCSTR, cmdInsert: WINUINT, + flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "ChangeMenuA".} -proc GetMenuStringA*(menu: HMENU, uIDItem: UINT, lpString: LPSTR, - nMaxCount: int32, uFlag: UINT): int32{.stdcall, +proc GetMenuStringA*(menu: HMENU, uIDItem: WINUINT, lpString: LPSTR, + nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, dynlib: "user32", importc: "GetMenuStringA".} -proc InsertMenuA*(menu: HMENU, uPosition: UINT, uFlags: UINT, uIDNewItem: UINT, +proc InsertMenuA*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuA".} -proc AppendMenuA*(menu: HMENU, uFlags: UINT, uIDNewItem: UINT, +proc AppendMenuA*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "AppendMenuA".} -proc ModifyMenuA*(hMnu: HMENU, uPosition: UINT, uFlags: UINT, uIDNewItem: UINT, +proc ModifyMenuA*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "ModifyMenuA".} -proc InsertMenuItemA*(para1: HMENU, para2: UINT, para3: WINBOOL, +proc InsertMenuItemA*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuItemA".} -proc GetMenuItemInfoA*(para1: HMENU, para2: UINT, para3: WINBOOL, +proc GetMenuItemInfoA*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} -proc SetMenuItemInfoA*(para1: HMENU, para2: UINT, para3: WINBOOL, +proc SetMenuItemInfoA*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} proc DrawTextA*(hDC: HDC, lpString: LPCSTR, nCount: int32, lpRect: LPRECT, - uFormat: UINT): int32{.stdcall, dynlib: "user32", + uFormat: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DrawTextA".} proc DrawTextExA*(para1: HDC, para2: LPSTR, para3: int32, para4: LPRECT, - para5: UINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, + para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, dynlib: "user32", importc: "DrawTextExA".} proc GrayStringA*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, lpData: LPARAM, nCount: int32, X: int32, Y: int32, @@ -14499,7 +14499,7 @@ proc GrayStringA*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, dynlib: "user32", importc: "GrayStringA".} proc DrawStateA*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, para4: LPARAM, para5: WPARAM, para6: int32, para7: int32, para8: int32, - para9: int32, para10: UINT): WINBOOL{.stdcall, + para9: int32, para10: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawStateA".} proc TabbedTextOutA*(hDC: HDC, X: int32, Y: int32, lpString: LPCSTR, nCount: int32, nTabPositions: int32, @@ -14526,7 +14526,7 @@ proc GetWindowTextLengthA*(wnd: HWND): int32{.stdcall, dynlib: "user32", importc: "GetWindowTextLengthA".} proc MessageBoxA*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: int): int32{. stdcall, dynlib: "user32", importc: "MessageBoxA".} -proc MessageBoxExA*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT, +proc MessageBoxExA*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: WINUINT, wLanguageId: int16): int32{.stdcall, dynlib: "user32", importc: "MessageBoxExA".} proc MessageBoxIndirectA*(para1: LPMSGBOXPARAMS): int32{.stdcall, @@ -14574,44 +14574,44 @@ proc LoadCursorFromFileA*(lpFileName: LPCSTR): HCURSOR{.stdcall, dynlib: "user32", importc: "LoadCursorFromFileA".} proc LoadIconA*(hInstance: HINST, lpIconName: LPCSTR): HICON{.stdcall, dynlib: "user32", importc: "LoadIconA".} -proc LoadImageA*(para1: HINST, para2: LPCSTR, para3: UINT, para4: int32, - para5: int32, para6: UINT): HANDLE{.stdcall, dynlib: "user32", +proc LoadImageA*(para1: HINST, para2: LPCSTR, para3: WINUINT, para4: int32, + para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", importc: "LoadImageA".} -proc LoadStringA*(hInstance: HINST, uID: UINT, lpBuffer: LPSTR, +proc LoadStringA*(hInstance: HINST, uID: WINUINT, lpBuffer: LPSTR, nBufferMax: int32): int32{.stdcall, dynlib: "user32", importc: "LoadStringA".} proc IsDialogMessageA*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, dynlib: "user32", importc: "IsDialogMessageA".} proc DlgDirListA*(hDlg: HWND, lpPathSpec: LPSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: UINT): int32{.stdcall, + nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DlgDirListA".} proc DlgDirSelectExA*(hDlg: HWND, lpString: LPSTR, nCount: int32, nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectExA".} proc DlgDirListComboBoxA*(hDlg: HWND, lpPathSpec: LPSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: UINT): int32{. + nIDStaticPath: int32, uFiletype: WINUINT): int32{. stdcall, dynlib: "user32", importc: "DlgDirListComboBoxA".} proc DlgDirSelectComboBoxExA*(hDlg: HWND, lpString: LPSTR, nCount: int32, nIDComboBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectComboBoxExA".} -proc DefFrameProcA*(wnd: HWND, hWndMDIClient: HWND, uMsg: UINT, wp: WPARAM, +proc DefFrameProcA*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "DefFrameProcA".} -proc DefMDIChildProcA*(wnd: HWND, uMsg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc DefMDIChildProcA*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefMDIChildProcA".} proc CreateMDIWindowA*(lpClassName: LPSTR, lpWindowName: LPSTR, dwStyle: DWORD, X: int32, Y: int32, nWidth: int32, nHeight: int32, hWndParent: HWND, hInstance: HINST, lp: LPARAM): HWND{. stdcall, dynlib: "user32", importc: "CreateMDIWindowA".} -proc WinHelpA*(hWndMain: HWND, lpszHelp: LPCSTR, uCommand: UINT, dwData: DWORD): WINBOOL{. +proc WinHelpA*(hWndMain: HWND, lpszHelp: LPCSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. stdcall, dynlib: "user32", importc: "WinHelpA".} proc ChangeDisplaySettingsA*(lpDevMode: LPDEVMODE, dwFlags: DWORD): LONG{. stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} proc EnumDisplaySettingsA*(lpszDeviceName: LPCSTR, iModeNum: DWORD, lpDevMode: LPDEVMODE): WINBOOL{.stdcall, dynlib: "user32", importc: "EnumDisplaySettingsA".} -proc SystemParametersInfoA*(uiAction: UINT, uiParam: UINT, pvParam: PVOID, - fWinIni: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc SystemParametersInfoA*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, + fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "SystemParametersInfoA".} proc AddFontResourceA*(para1: LPCSTR): int32{.stdcall, dynlib: "gdi32", importc: "AddFontResourceA".} @@ -14643,24 +14643,24 @@ proc EnumFontsA*(para1: HDC, para2: LPCSTR, para3: ENUMFONTSPROC, para4: LPARAM) stdcall, dynlib: "gdi32", importc: "EnumFontsA".} proc EnumFontsA*(para1: HDC, para2: LPCSTR, para3: ENUMFONTSPROC, para4: pointer): int32{. stdcall, dynlib: "gdi32", importc: "EnumFontsA".} -proc GetCharWidthA*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. +proc GetCharWidthA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthA".} -proc GetCharWidth32A*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. +proc GetCharWidth32A*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidth32A".} -proc GetCharWidthFloatA*(para1: HDC, para2: UINT, para3: UINT, para4: ptr float32): WINBOOL{. +proc GetCharWidthFloatA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} -proc GetCharABCWidthsA*(para1: HDC, para2: UINT, para3: UINT, para4: LPABC): WINBOOL{. +proc GetCharABCWidthsA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} -proc GetCharABCWidthsFloatA*(para1: HDC, para2: UINT, para3: UINT, +proc GetCharABCWidthsFloatA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABCFLOAT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} -proc GetGlyphOutlineA*(para1: HDC, para2: UINT, para3: UINT, +proc GetGlyphOutlineA*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineA".} proc GetMetaFileA*(para1: LPCSTR): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetMetaFileA".} -proc GetOutlineTextMetricsA*(para1: HDC, para2: UINT, para3: LPOUTLINETEXTMETRIC): UINT{. +proc GetOutlineTextMetricsA*(para1: HDC, para2: WINUINT, para3: LPOUTLINETEXTMETRIC): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetOutlineTextMetricsA".} proc GetTextExtentPointA*(para1: HDC, para2: LPCSTR, para3: int32, para4: LPSIZE): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetTextExtentPointA".} @@ -14684,7 +14684,7 @@ proc CreateEnhMetaFileA*(para1: HDC, para2: LPCSTR, para3: LPRECT, para4: LPCSTR stdcall, dynlib: "gdi32", importc: "CreateEnhMetaFileA".} proc GetEnhMetaFileA*(para1: LPCSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileA".} -proc GetEnhMetaFileDescriptionA*(para1: HENHMETAFILE, para2: UINT, para3: LPSTR): UINT{. +proc GetEnhMetaFileDescriptionA*(para1: HENHMETAFILE, para2: WINUINT, para3: LPSTR): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionA".} proc GetTextMetricsA*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextMetricsA".} @@ -14695,8 +14695,8 @@ proc GetObjectA*(para1: HGDIOBJ, para2: int32, para3: LPVOID): int32{.stdcall, proc TextOutA*(para1: HDC, para2: int32, para3: int32, para4: LPCSTR, para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "TextOutA".} -proc ExtTextOutA*(para1: HDC, para2: int32, para3: int32, para4: UINT, - para5: LPRECT, para6: LPCSTR, para7: UINT, para8: LPINT): WINBOOL{. +proc ExtTextOutA*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, + para5: LPRECT, para6: LPCSTR, para7: WINUINT, para8: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "ExtTextOutA".} proc PolyTextOutA*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PolyTextOutA".} @@ -14712,19 +14712,19 @@ proc GetICMProfileA*(para1: HDC, para2: DWORD, para3: LPSTR): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetICMProfileA".} proc SetICMProfileA*(para1: HDC, para2: LPSTR): WINBOOL{.stdcall, dynlib: "gdi32", importc: "SetICMProfileA".} -proc UpdateICMRegKeyA*(para1: DWORD, para2: DWORD, para3: LPSTR, para4: UINT): WINBOOL{. +proc UpdateICMRegKeyA*(para1: DWORD, para2: DWORD, para3: LPSTR, para4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyA".} proc EnumICMProfilesA*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. stdcall, dynlib: "gdi32", importc: "EnumICMProfilesA".} proc PropertySheetA*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, dynlib: "comctl32", importc: "PropertySheetA".} proc ImageList_LoadImageA*(hi: HINST, lpbmp: LPCSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: UINT, uFlags: UINT): HIMAGELIST{. + crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageA".} proc CreateStatusWindowA*(style: LONG, lpszText: LPCSTR, hwndParent: HWND, - wID: UINT): HWND{.stdcall, dynlib: "comctl32", + wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", importc: "CreateStatusWindowA".} -proc DrawStatusTextA*(hDC: HDC, lprc: LPRECT, pszText: LPCSTR, uFlags: UINT){. +proc DrawStatusTextA*(hDC: HDC, lprc: LPRECT, pszText: LPCSTR, uFlags: WINUINT){. stdcall, dynlib: "comctl32", importc: "DrawStatusTextA".} proc GetOpenFileNameA*(para1: LPOPENFILENAME): WINBOOL{.stdcall, dynlib: "comdlg32", importc: "GetOpenFileNameA".} @@ -15077,7 +15077,7 @@ proc Shell_NotifyIconA*(dwMessage: DWORD, lpData: PNotifyIconDataA): WINBOOL{. proc DdeCreateStringHandleA*(para1: DWORD, para2: cstring, para3: int32): HSZ{. stdcall, dynlib: "user32", importc: "DdeCreateStringHandleA".} proc DdeInitializeA*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): UINT{.stdcall, dynlib: "user32", + para4: DWORD): WINUINT{.stdcall, dynlib: "user32", importc: "DdeInitializeA".} proc DdeQueryStringA*(para1: DWORD, para2: HSZ, para3: cstring, para4: DWORD, para5: int32): DWORD{.stdcall, dynlib: "user32", @@ -15157,7 +15157,7 @@ proc GetModuleFileNameW*(hModule: HINST, lpFilename: LPWSTR, nSize: DWORD): DWOR stdcall, dynlib: "kernel32", importc: "GetModuleFileNameW".} proc GetModuleHandleW*(lpModuleName: LPCWSTR): HMODULE{.stdcall, dynlib: "kernel32", importc: "GetModuleHandleW".} -proc FatalAppExitW*(uAction: UINT, lpMessageText: LPCWSTR){.stdcall, +proc FatalAppExitW*(uAction: WINUINT, lpMessageText: LPCWSTR){.stdcall, dynlib: "kernel32", importc: "FatalAppExitW".} proc GetCommandLineW*(): LPWSTR{.stdcall, dynlib: "kernel32", importc: "GetCommandLineW".} @@ -15194,15 +15194,15 @@ proc GlobalAddAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "GlobalAddAtomW".} proc GlobalFindAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "GlobalFindAtomW".} -proc GlobalGetAtomNameW*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): UINT{. +proc GlobalGetAtomNameW*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{. stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameW".} proc AddAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "AddAtomW".} proc FindAtomW*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "FindAtomW".} -proc GetAtomNameW*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): UINT{.stdcall, +proc GetAtomNameW*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetAtomNameW".} -proc GetProfileIntW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: WINT): UINT{. +proc GetProfileIntW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: WINT): WINUINT{. stdcall, dynlib: "kernel32", importc: "GetProfileIntW".} proc GetProfileStringW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpDefault: LPCWSTR, lpReturnedString: LPWSTR, @@ -15217,7 +15217,7 @@ proc GetProfileSectionW*(lpAppName: LPCWSTR, lpReturnedString: LPWSTR, proc WriteProfileSectionW*(lpAppName: LPCWSTR, lpString: LPCWSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteProfileSectionW".} proc GetPrivateProfileIntW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - nDefault: WINT, lpFileName: LPCWSTR): UINT{.stdcall, + nDefault: WINT, lpFileName: LPCWSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetPrivateProfileIntW".} proc GetPrivateProfileStringW*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpDefault: LPCWSTR, lpReturnedString: LPWSTR, @@ -15232,16 +15232,16 @@ proc GetPrivateProfileSectionW*(lpAppName: LPCWSTR, lpReturnedString: LPWSTR, proc WritePrivateProfileSectionW*(lpAppName: LPCWSTR, lpString: LPCWSTR, lpFileName: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WritePrivateProfileSectionW".} -proc GetDriveTypeW*(lpRootPathName: LPCWSTR): UINT{.stdcall, dynlib: "kernel32", +proc GetDriveTypeW*(lpRootPathName: LPCWSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetDriveTypeW".} -proc GetSystemDirectoryW*(lpBuffer: LPWSTR, uSize: UINT): UINT{.stdcall, +proc GetSystemDirectoryW*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetSystemDirectoryW".} proc GetTempPathW*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{.stdcall, dynlib: "kernel32", importc: "GetTempPathW".} proc GetTempFileNameW*(lpPathName: LPCWSTR, lpPrefixString: LPCWSTR, - uUnique: UINT, lpTempFileName: LPWSTR): UINT{.stdcall, + uUnique: WINUINT, lpTempFileName: LPWSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetTempFileNameW".} -proc GetWindowsDirectoryW*(lpBuffer: LPWSTR, uSize: UINT): UINT{.stdcall, +proc GetWindowsDirectoryW*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetWindowsDirectoryW".} proc SetCurrentDirectoryW*(lpPathName: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetCurrentDirectoryW".} @@ -15382,7 +15382,7 @@ proc GetFileSecurityW*(lpFileName: LPCWSTR, proc FindFirstChangeNotificationW*(lpPathName: LPCWSTR, bWatchSubtree: WINBOOL, dwNotifyFilter: DWORD): HANDLE{.stdcall, dynlib: "kernel32", importc: "FindFirstChangeNotificationW".} -proc IsBadStringPtrW*(lpsz: LPCWSTR, ucchMax: UINT): WINBOOL{.stdcall, +proc IsBadStringPtrW*(lpsz: LPCWSTR, ucchMax: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadStringPtrW".} proc LookupAccountSidW*(lpSystemName: LPCWSTR, Sid: PSID, Name: LPWSTR, cbName: LPDWORD, ReferencedDomainName: LPWSTR, @@ -15421,7 +15421,7 @@ proc SetComputerNameW*(lpComputerName: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetComputerNameW".} proc GetUserNameW*(lpBuffer: LPWSTR, nSize: LPDWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "GetUserNameW".} -proc LoadKeyboardLayoutW*(pwszKLID: LPCWSTR, Flags: UINT): HKL{.stdcall, +proc LoadKeyboardLayoutW*(pwszKLID: LPCWSTR, Flags: WINUINT): HKL{.stdcall, dynlib: "user32", importc: "LoadKeyboardLayoutW".} proc GetKeyboardLayoutNameW*(pwszKLID: LPWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "GetKeyboardLayoutNameW".} @@ -15449,35 +15449,35 @@ proc GetUserObjectInformationW*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, proc SetUserObjectInformationW*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, nLength: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SetUserObjectInformationW".} -proc RegisterWindowMessageW*(lpString: LPCWSTR): UINT{.stdcall, +proc RegisterWindowMessageW*(lpString: LPCWSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterWindowMessageW".} -proc GetMessageW*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc GetMessageW*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMessageW".} proc DispatchMessageW*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", importc: "DispatchMessageW".} -proc PeekMessageW*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT, wRemoveMsg: UINT): WINBOOL{.stdcall, +proc PeekMessageW*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "PeekMessageW".} -proc SendMessageW*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc SendMessageW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageW".} -proc SendMessageTimeoutW*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM, - fuFlags: UINT, uTimeout: UINT, lpdwResult: LPDWORD): LRESULT{. +proc SendMessageTimeoutW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, + fuFlags: WINUINT, uTimeout: WINUINT, lpdwResult: LPDWORD): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageTimeoutW".} -proc SendNotifyMessageW*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. +proc SendNotifyMessageW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "SendNotifyMessageW".} -proc SendMessageCallbackW*(wnd: HWND, Msg: UINT, wp: WPARAM, +proc SendMessageCallbackW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, lpResultCallBack: SENDASYNCPROC, dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SendMessageCallbackW".} -proc PostMessageW*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. +proc PostMessageW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "PostMessageW".} -proc PostThreadMessageW*(idThread: DWORD, Msg: UINT, wp: WPARAM, +proc PostThreadMessageW*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", importc: "PostThreadMessageW".} -proc DefWindowProcW*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc DefWindowProcW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefWindowProcW".} -proc CallWindowProcW*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: UINT, +proc CallWindowProcW*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "CallWindowProcW".} proc RegisterClassW*(lpWndClass: LPWNDCLASSW): ATOM{.stdcall, dynlib: "user32", @@ -15515,18 +15515,18 @@ proc DialogBoxIndirectParamW*(hInstance: HINST, hDialogTemplate: LPCDLGTEMPLATE, proc SetDlgItemTextW*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCWSTR): WINBOOL{. stdcall, dynlib: "user32", importc: "SetDlgItemTextW".} proc GetDlgItemTextW*(hDlg: HWND, nIDDlgItem: int32, lpString: LPWSTR, - nMaxCount: int32): UINT{.stdcall, dynlib: "user32", + nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", importc: "GetDlgItemTextW".} -proc SendDlgItemMessageW*(hDlg: HWND, nIDDlgItem: int32, Msg: UINT, +proc SendDlgItemMessageW*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LONG{.stdcall, dynlib: "user32", importc: "SendDlgItemMessageW".} -proc DefDlgProcW*(hDlg: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc DefDlgProcW*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefDlgProcW".} proc CallMsgFilterW*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "CallMsgFilterW".} -proc RegisterClipboardFormatW*(lpszFormat: LPCWSTR): UINT{.stdcall, +proc RegisterClipboardFormatW*(lpszFormat: LPCWSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterClipboardFormatW".} -proc GetClipboardFormatNameW*(format: UINT, lpszFormatName: LPWSTR, +proc GetClipboardFormatNameW*(format: WINUINT, lpszFormatName: LPWSTR, cchMaxCount: int32): int32{.stdcall, dynlib: "user32", importc: "GetClipboardFormatNameW".} proc CharToOemW*(lpszSrc: LPCWSTR, lpszDst: LPSTR): WINBOOL{.stdcall, @@ -15563,9 +15563,9 @@ proc VkKeyScanW*(ch: WCHAR): SHORT{.stdcall, dynlib: "user32", importc: "VkKeyScanW".} proc VkKeyScanExW*(ch: WCHAR, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", importc: "VkKeyScanExW".} -proc MapVirtualKeyW*(uCode: UINT, uMapType: UINT): UINT{.stdcall, +proc MapVirtualKeyW*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyW".} -proc MapVirtualKeyExW*(uCode: UINT, uMapType: UINT, dwhkl: HKL): UINT{.stdcall, +proc MapVirtualKeyExW*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyExW".} proc LoadAcceleratorsW*(hInstance: HINST, lpTableName: LPCWSTR): HACCEL{. stdcall, dynlib: "user32", importc: "LoadAcceleratorsW".} @@ -15580,35 +15580,35 @@ proc LoadMenuW*(hInstance: HINST, lpMenuName: LPCWSTR): HMENU{.stdcall, dynlib: "user32", importc: "LoadMenuW".} proc LoadMenuIndirectW*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, dynlib: "user32", importc: "LoadMenuIndirectW".} -proc ChangeMenuW*(menu: HMENU, cmd: UINT, lpszNewItem: LPCWSTR, - cmdInsert: UINT, flags: UINT): WINBOOL{.stdcall, +proc ChangeMenuW*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCWSTR, + cmdInsert: WINUINT, flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "ChangeMenuW".} -proc GetMenuStringW*(menu: HMENU, uIDItem: UINT, lpString: LPWSTR, - nMaxCount: int32, uFlag: UINT): int32{.stdcall, +proc GetMenuStringW*(menu: HMENU, uIDItem: WINUINT, lpString: LPWSTR, + nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, dynlib: "user32", importc: "GetMenuStringW".} -proc InsertMenuW*(menu: HMENU, uPosition: UINT, uFlags: UINT, uIDNewItem: UINT, +proc InsertMenuW*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuW".} -proc AppendMenuW*(menu: HMENU, uFlags: UINT, uIDNewItem: UINT, +proc AppendMenuW*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "AppendMenuW".} -proc ModifyMenuW*(hMnu: HMENU, uPosition: UINT, uFlags: UINT, uIDNewItem: UINT, +proc ModifyMenuW*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "ModifyMenuW".} -proc InsertMenuItemW*(para1: HMENU, para2: UINT, para3: WINBOOL, +proc InsertMenuItemW*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuItemW".} -proc GetMenuItemInfoW*(para1: HMENU, para2: UINT, para3: WINBOOL, +proc GetMenuItemInfoW*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMenuItemInfoW".} -proc SetMenuItemInfoW*(para1: HMENU, para2: UINT, para3: WINBOOL, +proc SetMenuItemInfoW*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "SetMenuItemInfoW".} proc DrawTextW*(hDC: HDC, lpString: LPCWSTR, nCount: int32, lpRect: LPRECT, - uFormat: UINT): int32{.stdcall, dynlib: "user32", + uFormat: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DrawTextW".} proc DrawTextExW*(para1: HDC, para2: LPWSTR, para3: int32, para4: LPRECT, - para5: UINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, + para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, dynlib: "user32", importc: "DrawTextExW".} proc GrayStringW*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, lpData: LPARAM, nCount: int32, X: int32, Y: int32, @@ -15616,7 +15616,7 @@ proc GrayStringW*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, dynlib: "user32", importc: "GrayStringW".} proc DrawStateW*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, para4: LPARAM, para5: WPARAM, para6: int32, para7: int32, para8: int32, - para9: int32, para10: UINT): WINBOOL{.stdcall, + para9: int32, para10: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawStateW".} proc TabbedTextOutW*(hDC: HDC, X: int32, Y: int32, lpString: LPCWSTR, nCount: int32, nTabPositions: int32, @@ -15641,10 +15641,10 @@ proc GetWindowTextW*(wnd: HWND, lpString: LPWSTR, nMaxCount: int32): int32{. stdcall, dynlib: "user32", importc: "GetWindowTextW".} proc GetWindowTextLengthW*(wnd: HWND): int32{.stdcall, dynlib: "user32", importc: "GetWindowTextLengthW".} -proc MessageBoxW*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: UINT): int32{. +proc MessageBoxW*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: WINUINT): int32{. stdcall, dynlib: "user32", importc: "MessageBoxW".} proc MessageBoxExW*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, - uType: UINT, wLanguageId: int16): int32{.stdcall, + uType: WINUINT, wLanguageId: int16): int32{.stdcall, dynlib: "user32", importc: "MessageBoxExW".} proc MessageBoxIndirectW*(para1: LPMSGBOXPARAMS): int32{.stdcall, dynlib: "user32", importc: "MessageBoxIndirectW".} @@ -15691,45 +15691,45 @@ proc LoadCursorFromFileW*(lpFileName: LPCWSTR): HCURSOR{.stdcall, dynlib: "user32", importc: "LoadCursorFromFileW".} proc LoadIconW*(hInstance: HINST, lpIconName: LPCWSTR): HICON{.stdcall, dynlib: "user32", importc: "LoadIconW".} -proc LoadImageW*(para1: HINST, para2: LPCWSTR, para3: UINT, para4: int32, - para5: int32, para6: UINT): HANDLE{.stdcall, dynlib: "user32", +proc LoadImageW*(para1: HINST, para2: LPCWSTR, para3: WINUINT, para4: int32, + para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", importc: "LoadImageW".} -proc LoadStringW*(hInstance: HINST, uID: UINT, lpBuffer: LPWSTR, +proc LoadStringW*(hInstance: HINST, uID: WINUINT, lpBuffer: LPWSTR, nBufferMax: int32): int32{.stdcall, dynlib: "user32", importc: "LoadStringW".} proc IsDialogMessageW*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, dynlib: "user32", importc: "IsDialogMessageW".} proc DlgDirListW*(hDlg: HWND, lpPathSpec: LPWSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: UINT): int32{.stdcall, + nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DlgDirListW".} proc DlgDirSelectExW*(hDlg: HWND, lpString: LPWSTR, nCount: int32, nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectExW".} proc DlgDirListComboBoxW*(hDlg: HWND, lpPathSpec: LPWSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: UINT): int32{. + nIDStaticPath: int32, uFiletype: WINUINT): int32{. stdcall, dynlib: "user32", importc: "DlgDirListComboBoxW".} proc DlgDirSelectComboBoxExW*(hDlg: HWND, lpString: LPWSTR, nCount: int32, nIDComboBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectComboBoxExW".} -proc DefFrameProcW*(wnd: HWND, hWndMDIClient: HWND, uMsg: UINT, w: WPARAM, +proc DefFrameProcW*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, w: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "DefFrameProcW".} -proc DefMDIChildProcW*(wnd: HWND, uMsg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. +proc DefMDIChildProcW*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefMDIChildProcW".} proc CreateMDIWindowW*(lpClassName: LPWSTR, lpWindowName: LPWSTR, dwStyle: DWORD, X: int32, Y: int32, nWidth: int32, nHeight: int32, hWndParent: HWND, hInstance: HINST, lp: LPARAM): HWND{.stdcall, dynlib: "user32", importc: "CreateMDIWindowW".} -proc WinHelpW*(hWndMain: HWND, lpszHelp: LPCWSTR, uCommand: UINT, dwData: DWORD): WINBOOL{. +proc WinHelpW*(hWndMain: HWND, lpszHelp: LPCWSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. stdcall, dynlib: "user32", importc: "WinHelpW".} proc ChangeDisplaySettingsW*(lpDevMode: LPDEVMODEW, dwFlags: DWORD): LONG{. stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsW".} proc EnumDisplaySettingsW*(lpszDeviceName: LPCWSTR, iModeNum: DWORD, lpDevMode: LPDEVMODEW): WINBOOL{.stdcall, dynlib: "user32", importc: "EnumDisplaySettingsW".} -proc SystemParametersInfoW*(uiAction: UINT, uiParam: UINT, pvParam: PVOID, - fWinIni: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc SystemParametersInfoW*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, + fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "SystemParametersInfoW".} proc AddFontResourceW*(para1: LPCWSTR): int32{.stdcall, dynlib: "gdi32", importc: "AddFontResourceW".} @@ -15763,24 +15763,24 @@ proc EnumFontsW*(para1: HDC, para2: LPCWSTR, para3: ENUMFONTSPROC, para4: LPARAM proc EnumFontsW*(para1: HDC, para2: LPCWSTR, para3: ENUMFONTSPROC, para4: pointer): int32{.stdcall, dynlib: "gdi32", importc: "EnumFontsW".} -proc GetCharWidthW*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. +proc GetCharWidthW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthW".} -proc GetCharWidth32W*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. +proc GetCharWidth32W*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidth32W".} -proc GetCharWidthFloatW*(para1: HDC, para2: UINT, para3: UINT, para4: ptr float32): WINBOOL{. +proc GetCharWidthFloatW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatW".} -proc GetCharABCWidthsW*(para1: HDC, para2: UINT, para3: UINT, para4: LPABC): WINBOOL{. +proc GetCharABCWidthsW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsW".} -proc GetCharABCWidthsFloatW*(para1: HDC, para2: UINT, para3: UINT, +proc GetCharABCWidthsFloatW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABCFLOAT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatW".} -proc GetGlyphOutlineW*(para1: HDC, para2: UINT, para3: UINT, +proc GetGlyphOutlineW*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineW".} proc GetMetaFileW*(para1: LPCWSTR): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetMetaFileW".} -proc GetOutlineTextMetricsW*(para1: HDC, para2: UINT, para3: LPOUTLINETEXTMETRIC): UINT{. +proc GetOutlineTextMetricsW*(para1: HDC, para2: WINUINT, para3: LPOUTLINETEXTMETRIC): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetOutlineTextMetricsW".} proc GetTextExtentPointW*(para1: HDC, para2: LPCWSTR, para3: int32, para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", @@ -15806,7 +15806,7 @@ proc CreateEnhMetaFileW*(para1: HDC, para2: LPCWSTR, para3: LPRECT, importc: "CreateEnhMetaFileW".} proc GetEnhMetaFileW*(para1: LPCWSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileW".} -proc GetEnhMetaFileDescriptionW*(para1: HENHMETAFILE, para2: UINT, para3: LPWSTR): UINT{. +proc GetEnhMetaFileDescriptionW*(para1: HENHMETAFILE, para2: WINUINT, para3: LPWSTR): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionW".} proc GetTextMetricsW*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextMetricsW".} @@ -15817,8 +15817,8 @@ proc GetObjectW*(para1: HGDIOBJ, para2: int32, para3: LPVOID): int32{.stdcall, proc TextOutW*(para1: HDC, para2: int32, para3: int32, para4: LPCWSTR, para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "TextOutW".} -proc ExtTextOutW*(para1: HDC, para2: int32, para3: int32, para4: UINT, - para5: LPRECT, para6: LPCWSTR, para7: UINT, para8: LPINT): WINBOOL{. +proc ExtTextOutW*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, + para5: LPRECT, para6: LPCWSTR, para7: WINUINT, para8: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "ExtTextOutW".} proc PolyTextOutW*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PolyTextOutW".} @@ -15834,7 +15834,7 @@ proc GetICMProfileW*(para1: HDC, para2: DWORD, para3: LPWSTR): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetICMProfileW".} proc SetICMProfileW*(para1: HDC, para2: LPWSTR): WINBOOL{.stdcall, dynlib: "gdi32", importc: "SetICMProfileW".} -proc UpdateICMRegKeyW*(para1: DWORD, para2: DWORD, para3: LPWSTR, para4: UINT): WINBOOL{. +proc UpdateICMRegKeyW*(para1: DWORD, para2: DWORD, para3: LPWSTR, para4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyW".} proc EnumICMProfilesW*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. stdcall, dynlib: "gdi32", importc: "EnumICMProfilesW".} @@ -15843,12 +15843,12 @@ proc CreatePropertySheetPageW*(lppsp: LPCPROPSHEETPAGE): HPROPSHEETPAGE{. proc PropertySheetW*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, dynlib: "comctl32", importc: "PropertySheetW".} proc ImageList_LoadImageW*(hi: HINST, lpbmp: LPCWSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: UINT, uFlags: UINT): HIMAGELIST{. + crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageW".} proc CreateStatusWindowW*(style: LONG, lpszText: LPCWSTR, hwndParent: HWND, - wID: UINT): HWND{.stdcall, dynlib: "comctl32", + wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", importc: "CreateStatusWindowW".} -proc DrawStatusTextW*(hDC: HDC, lprc: LPRECT, pszText: LPCWSTR, uFlags: UINT){. +proc DrawStatusTextW*(hDC: HDC, lprc: LPRECT, pszText: LPCWSTR, uFlags: WINUINT){. stdcall, dynlib: "comctl32", importc: "DrawStatusTextW".} proc GetOpenFileNameW*(para1: LPOPENFILENAME): WINBOOL{.stdcall, dynlib: "comdlg32", importc: "GetOpenFileNameW".} @@ -16203,7 +16203,7 @@ proc Shell_NotifyIconW*(dwMessage: DWORD, lpData: PNotifyIconDataA): WINBOOL{. proc DdeCreateStringHandleW*(para1: DWORD, para2: LPCWSTR, para3: int32): HSZ{. stdcall, dynlib: "user32", importc: "DdeCreateStringHandleW".} proc DdeInitializeW*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): UINT{.stdcall, dynlib: "user32", + para4: DWORD): WINUINT{.stdcall, dynlib: "user32", importc: "DdeInitializeW".} proc DdeQueryStringW*(para1: DWORD, para2: HSZ, para3: LPCWSTR, para4: DWORD, para5: int32): DWORD{.stdcall, dynlib: "user32", @@ -16286,7 +16286,7 @@ when defined(winUnicode): stdcall, dynlib: "kernel32", importc: "GetModuleFileNameW".} proc GetModuleHandle*(lpModuleName: LPCWSTR): HMODULE{.stdcall, dynlib: "kernel32", importc: "GetModuleHandleW".} - proc FatalAppExit*(uAction: UINT, lpMessageText: LPCWSTR){.stdcall, + proc FatalAppExit*(uAction: WINUINT, lpMessageText: LPCWSTR){.stdcall, dynlib: "kernel32", importc: "FatalAppExitW".} proc GetCommandLine*(): LPWSTR{.stdcall, dynlib: "kernel32", importc: "GetCommandLineW".} @@ -16324,15 +16324,15 @@ when defined(winUnicode): importc: "GlobalAddAtomW".} proc GlobalFindAtom*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "GlobalFindAtomW".} - proc GlobalGetAtomName*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): UINT{. + proc GlobalGetAtomName*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{. stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameW".} proc AddAtom*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "AddAtomW".} proc FindAtom*(lpString: LPCWSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "FindAtomW".} - proc GetAtomName*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): UINT{.stdcall, + proc GetAtomName*(nAtom: ATOM, lpBuffer: LPWSTR, nSize: int32): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetAtomNameW".} - proc GetProfileInt*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: WINT): UINT{. + proc GetProfileInt*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, nDefault: WINT): WINUINT{. stdcall, dynlib: "kernel32", importc: "GetProfileIntW".} proc GetProfileString*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpDefault: LPCWSTR, lpReturnedString: LPWSTR, @@ -16347,7 +16347,7 @@ when defined(winUnicode): proc WriteProfileSection*(lpAppName: LPCWSTR, lpString: LPCWSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteProfileSectionW".} proc GetPrivateProfileInt*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, - nDefault: WINT, lpFileName: LPCWSTR): UINT{. + nDefault: WINT, lpFileName: LPCWSTR): WINUINT{. stdcall, dynlib: "kernel32", importc: "GetPrivateProfileIntW".} proc GetPrivateProfileString*(lpAppName: LPCWSTR, lpKeyName: LPCWSTR, lpDefault: LPCWSTR, lpReturnedString: LPWSTR, @@ -16362,16 +16362,16 @@ when defined(winUnicode): proc WritePrivateProfileSection*(lpAppName: LPCWSTR, lpString: LPCWSTR, lpFileName: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WritePrivateProfileSectionW".} - proc GetDriveType*(lpRootPathName: LPCWSTR): UINT{.stdcall, + proc GetDriveType*(lpRootPathName: LPCWSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetDriveTypeW".} - proc GetSystemDirectory*(lpBuffer: LPWSTR, uSize: UINT): UINT{.stdcall, + proc GetSystemDirectory*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetSystemDirectoryW".} proc GetTempPath*(nBufferLength: DWORD, lpBuffer: LPWSTR): DWORD{.stdcall, dynlib: "kernel32", importc: "GetTempPathW".} proc GetTempFileName*(lpPathName: LPCWSTR, lpPrefixString: LPCWSTR, - uUnique: UINT, lpTempFileName: LPWSTR): UINT{.stdcall, + uUnique: WINUINT, lpTempFileName: LPWSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetTempFileNameW".} - proc GetWindowsDirectory*(lpBuffer: LPWSTR, uSize: UINT): UINT{.stdcall, + proc GetWindowsDirectory*(lpBuffer: LPWSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetWindowsDirectoryW".} proc SetCurrentDirectory*(lpPathName: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetCurrentDirectoryW".} @@ -16513,7 +16513,7 @@ when defined(winUnicode): proc FindFirstChangeNotification*(lpPathName: LPCWSTR, bWatchSubtree: WINBOOL, dwNotifyFilter: DWORD): HANDLE{.stdcall, dynlib: "kernel32", importc: "FindFirstChangeNotificationW".} - proc IsBadStringPtr*(lpsz: LPCWSTR, ucchMax: UINT): WINBOOL{.stdcall, + proc IsBadStringPtr*(lpsz: LPCWSTR, ucchMax: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadStringPtrW".} proc LookupAccountSid*(lpSystemName: LPCWSTR, Sid: PSID, Name: LPWSTR, cbName: LPDWORD, ReferencedDomainName: LPWSTR, @@ -16553,7 +16553,7 @@ when defined(winUnicode): dynlib: "kernel32", importc: "SetComputerNameW".} proc GetUserName*(lpBuffer: LPWSTR, nSize: LPDWORD): WINBOOL{.stdcall, dynlib: "advapi32", importc: "GetUserNameW".} - proc LoadKeyboardLayout*(pwszKLID: LPCWSTR, Flags: UINT): HKL{.stdcall, + proc LoadKeyboardLayout*(pwszKLID: LPCWSTR, Flags: WINUINT): HKL{.stdcall, dynlib: "user32", importc: "LoadKeyboardLayoutW".} proc GetKeyboardLayoutName*(pwszKLID: LPWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "GetKeyboardLayoutNameW".} @@ -16581,36 +16581,36 @@ when defined(winUnicode): proc SetUserObjectInformation*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, nLength: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SetUserObjectInformationW".} - proc RegisterWindowMessage*(lpString: LPCWSTR): UINT{.stdcall, + proc RegisterWindowMessage*(lpString: LPCWSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterWindowMessageW".} - proc GetMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT): WINBOOL{.stdcall, dynlib: "user32", + proc GetMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMessageW".} proc DispatchMessage*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", importc: "DispatchMessageW".} - proc PeekMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT, wRemoveMsg: UINT): WINBOOL{.stdcall, + proc PeekMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "PeekMessageW".} - proc SendMessage*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc SendMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageW".} - proc SendMessageTimeout*(wnd: HWND, Msg: UINT, wp: WPARAM, - lp: LPARAM, fuFlags: UINT, uTimeout: UINT, + proc SendMessageTimeout*(wnd: HWND, Msg: WINUINT, wp: WPARAM, + lp: LPARAM, fuFlags: WINUINT, uTimeout: WINUINT, lpdwResult: LPDWORD): LRESULT{.stdcall, dynlib: "user32", importc: "SendMessageTimeoutW".} - proc SendNotifyMessage*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. + proc SendNotifyMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "SendNotifyMessageW".} - proc SendMessageCallback*(wnd: HWND, Msg: UINT, wp: WPARAM, + proc SendMessageCallback*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, lpResultCallBack: SENDASYNCPROC, dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SendMessageCallbackW".} - proc PostMessage*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. + proc PostMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "PostMessageW".} - proc PostThreadMessage*(idThread: DWORD, Msg: UINT, wp: WPARAM, + proc PostThreadMessage*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", importc: "PostThreadMessageW".} - proc DefWindowProc*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc DefWindowProc*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefWindowProcW".} - proc CallWindowProc*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: UINT, + proc CallWindowProc*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "CallWindowProcW".} proc RegisterClass*(lpWndClass: LPWNDCLASS): ATOM{.stdcall, dynlib: "user32", @@ -16650,18 +16650,18 @@ when defined(winUnicode): proc SetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCWSTR): WINBOOL{. stdcall, dynlib: "user32", importc: "SetDlgItemTextW".} proc GetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPWSTR, - nMaxCount: int32): UINT{.stdcall, dynlib: "user32", + nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", importc: "GetDlgItemTextW".} - proc SendDlgItemMessage*(hDlg: HWND, nIDDlgItem: int32, Msg: UINT, + proc SendDlgItemMessage*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LONG{.stdcall, dynlib: "user32", importc: "SendDlgItemMessageW".} - proc DefDlgProc*(hDlg: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc DefDlgProc*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefDlgProcW".} proc CallMsgFilter*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "CallMsgFilterW".} - proc RegisterClipboardFormat*(lpszFormat: LPCWSTR): UINT{.stdcall, + proc RegisterClipboardFormat*(lpszFormat: LPCWSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterClipboardFormatW".} - proc GetClipboardFormatName*(format: UINT, lpszFormatName: LPWSTR, + proc GetClipboardFormatName*(format: WINUINT, lpszFormatName: LPWSTR, cchMaxCount: int32): int32{.stdcall, dynlib: "user32", importc: "GetClipboardFormatNameW".} proc CharToOem*(lpszSrc: LPCWSTR, lpszDst: LPSTR): WINBOOL{.stdcall, @@ -16698,9 +16698,9 @@ when defined(winUnicode): importc: "VkKeyScanW".} proc VkKeyScanEx*(ch: WCHAR, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", importc: "VkKeyScanExW".} - proc MapVirtualKey*(uCode: UINT, uMapType: UINT): UINT{.stdcall, + proc MapVirtualKey*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyW".} - proc MapVirtualKeyEx*(uCode: UINT, uMapType: UINT, dwhkl: HKL): UINT{.stdcall, + proc MapVirtualKeyEx*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyExW".} proc LoadAccelerators*(hInstance: HINST, lpTableName: LPCWSTR): HACCEL{. stdcall, dynlib: "user32", importc: "LoadAcceleratorsW".} @@ -16715,35 +16715,35 @@ when defined(winUnicode): dynlib: "user32", importc: "LoadMenuW".} proc LoadMenuIndirect*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, dynlib: "user32", importc: "LoadMenuIndirectW".} - proc ChangeMenu*(menu: HMENU, cmd: UINT, lpszNewItem: LPCWSTR, - cmdInsert: UINT, flags: UINT): WINBOOL{.stdcall, + proc ChangeMenu*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCWSTR, + cmdInsert: WINUINT, flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "ChangeMenuW".} - proc GetMenuString*(menu: HMENU, uIDItem: UINT, lpString: LPWSTR, - nMaxCount: int32, uFlag: UINT): int32{.stdcall, + proc GetMenuString*(menu: HMENU, uIDItem: WINUINT, lpString: LPWSTR, + nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, dynlib: "user32", importc: "GetMenuStringW".} - proc InsertMenu*(menu: HMENU, uPosition: UINT, uFlags: UINT, - uIDNewItem: UINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, + proc InsertMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, + uIDNewItem: WINUINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuW".} - proc AppendMenu*(menu: HMENU, uFlags: UINT, uIDNewItem: UINT, + proc AppendMenu*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "AppendMenuW".} - proc ModifyMenu*(hMnu: HMENU, uPosition: UINT, uFlags: UINT, uIDNewItem: UINT, + proc ModifyMenu*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCWSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "ModifyMenuW".} - proc InsertMenuItem*(para1: HMENU, para2: UINT, para3: WINBOOL, + proc InsertMenuItem*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuItemW".} - proc GetMenuItemInfo*(para1: HMENU, para2: UINT, para3: WINBOOL, + proc GetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMenuItemInfoW".} - proc SetMenuItemInfo*(para1: HMENU, para2: UINT, para3: WINBOOL, + proc SetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "SetMenuItemInfoW".} proc DrawText*(hDC: HDC, lpString: LPCWSTR, nCount: int32, lpRect: LPRECT, - uFormat: UINT): int32{.stdcall, dynlib: "user32", + uFormat: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DrawTextW".} proc DrawTextEx*(para1: HDC, para2: LPWSTR, para3: int32, para4: LPRECT, - para5: UINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, + para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, dynlib: "user32", importc: "DrawTextExW".} proc GrayString*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, lpData: LPARAM, nCount: int32, X: int32, Y: int32, @@ -16751,7 +16751,7 @@ when defined(winUnicode): dynlib: "user32", importc: "GrayStringW".} proc DrawState*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, para4: LPARAM, para5: WPARAM, para6: int32, para7: int32, - para8: int32, para9: int32, para10: UINT): WINBOOL{.stdcall, + para8: int32, para9: int32, para10: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawStateW".} proc TabbedTextOut*(hDC: HDC, X: int32, Y: int32, lpString: LPCWSTR, nCount: int32, nTabPositions: int32, @@ -16776,10 +16776,10 @@ when defined(winUnicode): stdcall, dynlib: "user32", importc: "GetWindowTextW".} proc GetWindowTextLength*(wnd: HWND): int32{.stdcall, dynlib: "user32", importc: "GetWindowTextLengthW".} - proc MessageBox*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: UINT): int32{. + proc MessageBox*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, uType: WINUINT): int32{. stdcall, dynlib: "user32", importc: "MessageBoxW".} proc MessageBoxEx*(wnd: HWND, lpText: LPCWSTR, lpCaption: LPCWSTR, - uType: UINT, wLanguageId: int16): int32{.stdcall, + uType: WINUINT, wLanguageId: int16): int32{.stdcall, dynlib: "user32", importc: "MessageBoxExW".} proc MessageBoxIndirect*(para1: LPMSGBOXPARAMS): int32{.stdcall, dynlib: "user32", importc: "MessageBoxIndirectW".} @@ -16826,45 +16826,45 @@ when defined(winUnicode): dynlib: "user32", importc: "LoadCursorFromFileW".} proc LoadIcon*(hInstance: HINST, lpIconName: LPCWSTR): HICON{.stdcall, dynlib: "user32", importc: "LoadIconW".} - proc LoadImage*(para1: HINST, para2: LPCWSTR, para3: UINT, para4: int32, - para5: int32, para6: UINT): HANDLE{.stdcall, dynlib: "user32", + proc LoadImage*(para1: HINST, para2: LPCWSTR, para3: WINUINT, para4: int32, + para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", importc: "LoadImageW".} - proc LoadString*(hInstance: HINST, uID: UINT, lpBuffer: LPWSTR, + proc LoadString*(hInstance: HINST, uID: WINUINT, lpBuffer: LPWSTR, nBufferMax: int32): int32{.stdcall, dynlib: "user32", importc: "LoadStringW".} proc IsDialogMessage*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, dynlib: "user32", importc: "IsDialogMessageW".} proc DlgDirList*(hDlg: HWND, lpPathSpec: LPWSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: UINT): int32{.stdcall, + nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DlgDirListW".} proc DlgDirSelectEx*(hDlg: HWND, lpString: LPWSTR, nCount: int32, nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectExW".} proc DlgDirListComboBox*(hDlg: HWND, lpPathSpec: LPWSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: UINT): int32{. + nIDStaticPath: int32, uFiletype: WINUINT): int32{. stdcall, dynlib: "user32", importc: "DlgDirListComboBoxW".} proc DlgDirSelectComboBoxEx*(hDlg: HWND, lpString: LPWSTR, nCount: int32, nIDComboBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectComboBoxExW".} - proc DefFrameProc*(wnd: HWND, hWndMDIClient: HWND, uMsg: UINT, + proc DefFrameProc*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "DefFrameProcW".} - proc DefMDIChildProc*(wnd: HWND, uMsg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc DefMDIChildProc*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefMDIChildProcW".} proc CreateMDIWindow*(lpClassName: LPWSTR, lpWindowName: LPWSTR, dwStyle: DWORD, X: int32, Y: int32, nWidth: int32, nHeight: int32, hWndParent: HWND, hInstance: HINST, lp: LPARAM): HWND{.stdcall, dynlib: "user32", importc: "CreateMDIWindowW".} - proc WinHelp*(hWndMain: HWND, lpszHelp: LPCWSTR, uCommand: UINT, dwData: DWORD): WINBOOL{. + proc WinHelp*(hWndMain: HWND, lpszHelp: LPCWSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. stdcall, dynlib: "user32", importc: "WinHelpW".} proc ChangeDisplaySettings*(lpDevMode: LPDEVMODE, dwFlags: DWORD): LONG{. stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsW".} proc EnumDisplaySettings*(lpszDeviceName: LPCWSTR, iModeNum: DWORD, lpDevMode: LPDEVMODEW): WINBOOL{.stdcall, dynlib: "user32", importc: "EnumDisplaySettingsW".} - proc SystemParametersInfo*(uiAction: UINT, uiParam: UINT, pvParam: PVOID, - fWinIni: UINT): WINBOOL{.stdcall, dynlib: "user32", + proc SystemParametersInfo*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, + fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "SystemParametersInfoW".} proc AddFontResource*(para1: LPCWSTR): int32{.stdcall, dynlib: "gdi32", importc: "AddFontResourceW".} @@ -16899,25 +16899,25 @@ when defined(winUnicode): proc EnumFonts*(para1: HDC, para2: LPCWSTR, para3: ENUMFONTSPROC, para4: pointer): int32{.stdcall, dynlib: "gdi32", importc: "EnumFontsW".} - proc GetCharWidth*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. + proc GetCharWidth*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthW".} - proc GetCharWidth32*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. + proc GetCharWidth32*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidth32W".} - proc GetCharWidthFloat*(para1: HDC, para2: UINT, para3: UINT, para4: ptr float32): WINBOOL{. + proc GetCharWidthFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatW".} - proc GetCharABCWidths*(para1: HDC, para2: UINT, para3: UINT, para4: LPABC): WINBOOL{. + proc GetCharABCWidths*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsW".} - proc GetCharABCWidthsFloat*(para1: HDC, para2: UINT, para3: UINT, + proc GetCharABCWidthsFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABCFLOAT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatW".} - proc GetGlyphOutline*(para1: HDC, para2: UINT, para3: UINT, + proc GetGlyphOutline*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineW".} proc GetMetaFile*(para1: LPCWSTR): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetMetaFileW".} - proc GetOutlineTextMetrics*(para1: HDC, para2: UINT, - para3: LPOUTLINETEXTMETRIC): UINT{.stdcall, + proc GetOutlineTextMetrics*(para1: HDC, para2: WINUINT, + para3: LPOUTLINETEXTMETRIC): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetOutlineTextMetricsW".} proc GetTextExtentPoint*(para1: HDC, para2: LPCWSTR, para3: int32, para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", @@ -16943,8 +16943,8 @@ when defined(winUnicode): importc: "CreateEnhMetaFileW".} proc GetEnhMetaFile*(para1: LPCWSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileW".} - proc GetEnhMetaFileDescription*(para1: HENHMETAFILE, para2: UINT, - para3: LPWSTR): UINT{.stdcall, + proc GetEnhMetaFileDescription*(para1: HENHMETAFILE, para2: WINUINT, + para3: LPWSTR): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionW".} proc GetTextMetrics*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextMetricsW".} @@ -16955,8 +16955,8 @@ when defined(winUnicode): proc TextOut*(para1: HDC, para2: int32, para3: int32, para4: LPCWSTR, para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "TextOutW".} - proc ExtTextOut*(para1: HDC, para2: int32, para3: int32, para4: UINT, - para5: LPRECT, para6: LPCWSTR, para7: UINT, para8: LPINT): WINBOOL{. + proc ExtTextOut*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, + para5: LPRECT, para6: LPCWSTR, para7: WINUINT, para8: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "ExtTextOutW".} proc PolyTextOut*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PolyTextOutW".} @@ -16974,7 +16974,7 @@ when defined(winUnicode): proc SetICMProfile*(para1: HDC, para2: LPWSTR): WINBOOL{.stdcall, dynlib: "gdi32", importc: "SetICMProfileW".} - proc UpdateICMRegKey*(para1: DWORD, para2: DWORD, para3: LPWSTR, para4: UINT): WINBOOL{. + proc UpdateICMRegKey*(para1: DWORD, para2: DWORD, para3: LPWSTR, para4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyW".} proc EnumICMProfiles*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. stdcall, dynlib: "gdi32", importc: "EnumICMProfilesW".} @@ -16983,12 +16983,12 @@ when defined(winUnicode): proc PropertySheet*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, dynlib: "comctl32", importc: "PropertySheetW".} proc ImageList_LoadImage*(hi: HINST, lpbmp: LPCWSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: UINT, uFlags: UINT): HIMAGELIST{. + crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageW".} proc CreateStatusWindow*(style: LONG, lpszText: LPCWSTR, hwndParent: HWND, - wID: UINT): HWND{.stdcall, dynlib: "comctl32", + wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", importc: "CreateStatusWindowW".} - proc DrawStatusText*(hDC: HDC, lprc: LPRECT, pszText: LPCWSTR, uFlags: UINT){. + proc DrawStatusText*(hDC: HDC, lprc: LPRECT, pszText: LPCWSTR, uFlags: WINUINT){. stdcall, dynlib: "comctl32", importc: "DrawStatusTextW".} proc GetOpenFileName*(para1: LPOPENFILENAME): WINBOOL{.stdcall, dynlib: "comdlg32", importc: "GetOpenFileNameW".} @@ -17348,7 +17348,7 @@ when defined(winUnicode): proc DdeCreateStringHandle*(para1: DWORD, para2: LPCWSTR, para3: int32): HSZ{. stdcall, dynlib: "user32", importc: "DdeCreateStringHandleW".} proc DdeInitialize*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): UINT{.stdcall, dynlib: "user32", + para4: DWORD): WINUINT{.stdcall, dynlib: "user32", importc: "DdeInitializeW".} proc DdeQueryString*(para1: DWORD, para2: HSZ, para3: LPCWSTR, para4: DWORD, para5: int32): DWORD{.stdcall, dynlib: "user32", @@ -17429,7 +17429,7 @@ else: stdcall, dynlib: "kernel32", importc: "GetModuleFileNameA".} proc GetModuleHandle*(lpModuleName: LPCSTR): HMODULE{.stdcall, dynlib: "kernel32", importc: "GetModuleHandleA".} - proc FatalAppExit*(uAction: UINT, lpMessageText: LPCSTR){.stdcall, + proc FatalAppExit*(uAction: WINUINT, lpMessageText: LPCSTR){.stdcall, dynlib: "kernel32", importc: "FatalAppExitA".} proc GetCommandLine*(): LPSTR{.stdcall, dynlib: "kernel32", importc: "GetCommandLineA".} @@ -17466,15 +17466,15 @@ else: importc: "GlobalAddAtomA".} proc GlobalFindAtom*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "GlobalFindAtomA".} - proc GlobalGetAtomName*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): UINT{. + proc GlobalGetAtomName*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{. stdcall, dynlib: "kernel32", importc: "GlobalGetAtomNameA".} proc AddAtom*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "AddAtomA".} proc FindAtom*(lpString: LPCSTR): ATOM{.stdcall, dynlib: "kernel32", importc: "FindAtomA".} - proc GetAtomName*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): UINT{.stdcall, + proc GetAtomName*(nAtom: ATOM, lpBuffer: LPSTR, nSize: int32): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetAtomNameA".} - proc GetProfileInt*(lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: WINT): UINT{. + proc GetProfileInt*(lpAppName: LPCSTR, lpKeyName: LPCSTR, nDefault: WINT): WINUINT{. stdcall, dynlib: "kernel32", importc: "GetProfileIntA".} proc GetProfileString*(lpAppName: LPCSTR, lpKeyName: LPCSTR, lpDefault: LPCSTR, lpReturnedString: LPSTR, @@ -17489,7 +17489,7 @@ else: proc WriteProfileSection*(lpAppName: LPCSTR, lpString: LPCSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WriteProfileSectionA".} proc GetPrivateProfileInt*(lpAppName: LPCSTR, lpKeyName: LPCSTR, - nDefault: WINT, lpFileName: LPCSTR): UINT{.stdcall, + nDefault: WINT, lpFileName: LPCSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetPrivateProfileIntA".} proc GetPrivateProfileString*(lpAppName: LPCSTR, lpKeyName: LPCSTR, lpDefault: LPCSTR, lpReturnedString: LPSTR, @@ -17504,16 +17504,16 @@ else: proc WritePrivateProfileSection*(lpAppName: LPCSTR, lpString: LPCSTR, lpFileName: LPCSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WritePrivateProfileSectionA".} - proc GetDriveType*(lpRootPathName: LPCSTR): UINT{.stdcall, dynlib: "kernel32", + proc GetDriveType*(lpRootPathName: LPCSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetDriveTypeA".} - proc GetSystemDirectory*(lpBuffer: LPSTR, uSize: UINT): UINT{.stdcall, + proc GetSystemDirectory*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetSystemDirectoryA".} proc GetTempPath*(nBufferLength: DWORD, lpBuffer: LPSTR): DWORD{.stdcall, dynlib: "kernel32", importc: "GetTempPathA".} proc GetTempFileName*(lpPathName: LPCSTR, lpPrefixString: LPCSTR, - uUnique: UINT, lpTempFileName: LPSTR): UINT{.stdcall, + uUnique: WINUINT, lpTempFileName: LPSTR): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetTempFileNameA".} - proc GetWindowsDirectory*(lpBuffer: LPSTR, uSize: UINT): UINT{.stdcall, + proc GetWindowsDirectory*(lpBuffer: LPSTR, uSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetWindowsDirectoryA".} proc SetCurrentDirectory*(lpPathName: LPCSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetCurrentDirectoryA".} @@ -17654,7 +17654,7 @@ else: proc FindFirstChangeNotification*(lpPathName: LPCSTR, bWatchSubtree: WINBOOL, dwNotifyFilter: DWORD): HANDLE{.stdcall, dynlib: "kernel32", importc: "FindFirstChangeNotificationA".} - proc IsBadStringPtr*(lpsz: LPCSTR, ucchMax: UINT): WINBOOL{.stdcall, + proc IsBadStringPtr*(lpsz: LPCSTR, ucchMax: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadStringPtrA".} proc LookupAccountSid*(lpSystemName: LPCSTR, Sid: PSID, Name: LPSTR, cbName: LPDWORD, ReferencedDomainName: LPSTR, @@ -17694,7 +17694,7 @@ else: dynlib: "advapi32", importc: "GetUserNameA".} proc wvsprintf*(para1: LPSTR, para2: LPCSTR, arglist: va_list): int32{. stdcall, dynlib: "user32", importc: "wvsprintfA".} - proc LoadKeyboardLayout*(pwszKLID: LPCSTR, Flags: UINT): HKL{.stdcall, + proc LoadKeyboardLayout*(pwszKLID: LPCSTR, Flags: WINUINT): HKL{.stdcall, dynlib: "user32", importc: "LoadKeyboardLayoutA".} proc GetKeyboardLayoutName*(pwszKLID: LPSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "GetKeyboardLayoutNameA".} @@ -17722,36 +17722,36 @@ else: proc SetUserObjectInformation*(hObj: HANDLE, nIndex: int32, pvInfo: PVOID, nLength: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SetUserObjectInformationA".} - proc RegisterWindowMessage*(lpString: LPCSTR): UINT{.stdcall, + proc RegisterWindowMessage*(lpString: LPCSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterWindowMessageA".} - proc GetMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT): WINBOOL{.stdcall, dynlib: "user32", + proc GetMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMessageA".} proc DispatchMessage*(lpMsg: LPMSG): LONG{.stdcall, dynlib: "user32", importc: "DispatchMessageA".} - proc PeekMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: UINT, - wMsgFilterMax: UINT, wRemoveMsg: UINT): WINBOOL{.stdcall, + proc PeekMessage*(lpMsg: LPMSG, wnd: HWND, wMsgFilterMin: WINUINT, + wMsgFilterMax: WINUINT, wRemoveMsg: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "PeekMessageA".} - proc SendMessage*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc SendMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageA".} - proc SendMessageTimeout*(wnd: HWND, Msg: UINT, wp: WPARAM, - lp: LPARAM, fuFlags: UINT, uTimeout: UINT, + proc SendMessageTimeout*(wnd: HWND, Msg: WINUINT, wp: WPARAM, + lp: LPARAM, fuFlags: WINUINT, uTimeout: WINUINT, lpdwResult: LPDWORD): LRESULT{.stdcall, dynlib: "user32", importc: "SendMessageTimeoutA".} - proc SendNotifyMessage*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. + proc SendNotifyMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "SendNotifyMessageA".} - proc SendMessageCallback*(wnd: HWND, Msg: UINT, wp: WPARAM, + proc SendMessageCallback*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, lpResultCallBack: SENDASYNCPROC, dwData: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SendMessageCallbackA".} - proc PostMessage*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): WINBOOL{. + proc PostMessage*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{. stdcall, dynlib: "user32", importc: "PostMessageA".} - proc PostThreadMessage*(idThread: DWORD, Msg: UINT, wp: WPARAM, + proc PostThreadMessage*(idThread: DWORD, Msg: WINUINT, wp: WPARAM, lp: LPARAM): WINBOOL{.stdcall, dynlib: "user32", importc: "PostThreadMessageA".} - proc DefWindowProc*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc DefWindowProc*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefWindowProcA".} - proc CallWindowProc*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: UINT, + proc CallWindowProc*(lpPrevWndFunc: WNDPROC, wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "CallWindowProcA".} proc RegisterClass*(lpWndClass: LPWNDCLASS): ATOM{.stdcall, dynlib: "user32", @@ -17791,18 +17791,18 @@ else: proc SetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPCSTR): WINBOOL{. stdcall, dynlib: "user32", importc: "SetDlgItemTextA".} proc GetDlgItemText*(hDlg: HWND, nIDDlgItem: int32, lpString: LPSTR, - nMaxCount: int32): UINT{.stdcall, dynlib: "user32", + nMaxCount: int32): WINUINT{.stdcall, dynlib: "user32", importc: "GetDlgItemTextA".} - proc SendDlgItemMessage*(hDlg: HWND, nIDDlgItem: int32, Msg: UINT, + proc SendDlgItemMessage*(hDlg: HWND, nIDDlgItem: int32, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LONG{.stdcall, dynlib: "user32", importc: "SendDlgItemMessageA".} - proc DefDlgProc*(hDlg: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc DefDlgProc*(hDlg: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefDlgProcA".} proc CallMsgFilter*(lpMsg: LPMSG, nCode: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "CallMsgFilterA".} - proc RegisterClipboardFormat*(lpszFormat: LPCSTR): UINT{.stdcall, + proc RegisterClipboardFormat*(lpszFormat: LPCSTR): WINUINT{.stdcall, dynlib: "user32", importc: "RegisterClipboardFormatA".} - proc GetClipboardFormatName*(format: UINT, lpszFormatName: LPSTR, + proc GetClipboardFormatName*(format: WINUINT, lpszFormatName: LPSTR, cchMaxCount: int32): int32{.stdcall, dynlib: "user32", importc: "GetClipboardFormatNameA".} proc CharToOem*(lpszSrc: LPCSTR, lpszDst: LPSTR): WINBOOL{.stdcall, @@ -17839,9 +17839,9 @@ else: importc: "VkKeyScanA".} proc VkKeyScanEx*(ch: CHAR, dwhkl: HKL): SHORT{.stdcall, dynlib: "user32", importc: "VkKeyScanExA".} - proc MapVirtualKey*(uCode: UINT, uMapType: UINT): UINT{.stdcall, + proc MapVirtualKey*(uCode: WINUINT, uMapType: WINUINT): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyA".} - proc MapVirtualKeyEx*(uCode: UINT, uMapType: UINT, dwhkl: HKL): UINT{.stdcall, + proc MapVirtualKeyEx*(uCode: WINUINT, uMapType: WINUINT, dwhkl: HKL): WINUINT{.stdcall, dynlib: "user32", importc: "MapVirtualKeyExA".} proc LoadAccelerators*(hInstance: HINST, lpTableName: LPCSTR): HACCEL{. stdcall, dynlib: "user32", importc: "LoadAcceleratorsA".} @@ -17856,35 +17856,35 @@ else: dynlib: "user32", importc: "LoadMenuA".} proc LoadMenuIndirect*(lpMenuTemplate: LPMENUTEMPLATE): HMENU{.stdcall, dynlib: "user32", importc: "LoadMenuIndirectA".} - proc ChangeMenu*(menu: HMENU, cmd: UINT, lpszNewItem: LPCSTR, - cmdInsert: UINT, flags: UINT): WINBOOL{.stdcall, + proc ChangeMenu*(menu: HMENU, cmd: WINUINT, lpszNewItem: LPCSTR, + cmdInsert: WINUINT, flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "ChangeMenuA".} - proc GetMenuString*(menu: HMENU, uIDItem: UINT, lpString: LPSTR, - nMaxCount: int32, uFlag: UINT): int32{.stdcall, + proc GetMenuString*(menu: HMENU, uIDItem: WINUINT, lpString: LPSTR, + nMaxCount: int32, uFlag: WINUINT): int32{.stdcall, dynlib: "user32", importc: "GetMenuStringA".} - proc InsertMenu*(menu: HMENU, uPosition: UINT, uFlags: UINT, - uIDNewItem: UINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, + proc InsertMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, + uIDNewItem: WINUINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuA".} - proc AppendMenu*(menu: HMENU, uFlags: UINT, uIDNewItem: UINT, + proc AppendMenu*(menu: HMENU, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "AppendMenuA".} - proc ModifyMenu*(hMnu: HMENU, uPosition: UINT, uFlags: UINT, uIDNewItem: UINT, + proc ModifyMenu*(hMnu: HMENU, uPosition: WINUINT, uFlags: WINUINT, uIDNewItem: WINUINT, lpNewItem: LPCSTR): WINBOOL{.stdcall, dynlib: "user32", importc: "ModifyMenuA".} - proc InsertMenuItem*(para1: HMENU, para2: UINT, para3: WINBOOL, + proc InsertMenuItem*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "InsertMenuItemA".} - proc GetMenuItemInfo*(para1: HMENU, para2: UINT, para3: WINBOOL, + proc GetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} - proc SetMenuItemInfo*(para1: HMENU, para2: UINT, para3: WINBOOL, + proc SetMenuItemInfo*(para1: HMENU, para2: WINUINT, para3: WINBOOL, para4: LPCMENUITEMINFO): WINBOOL{.stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} proc DrawText*(hDC: HDC, lpString: LPCSTR, nCount: int32, lpRect: LPRECT, - uFormat: UINT): int32{.stdcall, dynlib: "user32", + uFormat: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DrawTextA".} proc DrawTextEx*(para1: HDC, para2: LPSTR, para3: int32, para4: LPRECT, - para5: UINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, + para5: WINUINT, para6: LPDRAWTEXTPARAMS): int32{.stdcall, dynlib: "user32", importc: "DrawTextExA".} proc GrayString*(hDC: HDC, hBrush: HBRUSH, lpOutputFunc: GRAYSTRINGPROC, lpData: LPARAM, nCount: int32, X: int32, Y: int32, @@ -17892,7 +17892,7 @@ else: dynlib: "user32", importc: "GrayStringA".} proc DrawState*(para1: HDC, para2: HBRUSH, para3: DRAWSTATEPROC, para4: LPARAM, para5: WPARAM, para6: int32, para7: int32, - para8: int32, para9: int32, para10: UINT): WINBOOL{.stdcall, + para8: int32, para9: int32, para10: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawStateA".} proc TabbedTextOut*(dc: HDC, X: int32, Y: int32, lpString: LPCSTR, nCount: int32, nTabPositions: int32, @@ -17917,9 +17917,9 @@ else: stdcall, dynlib: "user32", importc: "GetWindowTextA".} proc GetWindowTextLength*(wnd: HWND): int32{.stdcall, dynlib: "user32", importc: "GetWindowTextLengthA".} - proc MessageBox*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT): int32{. + proc MessageBox*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: WINUINT): int32{. stdcall, dynlib: "user32", importc: "MessageBoxA".} - proc MessageBoxEx*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: UINT, + proc MessageBoxEx*(wnd: HWND, lpText: LPCSTR, lpCaption: LPCSTR, uType: WINUINT, wLanguageId: int16): int32{.stdcall, dynlib: "user32", importc: "MessageBoxExA".} proc MessageBoxIndirect*(para1: LPMSGBOXPARAMS): int32{.stdcall, @@ -17967,44 +17967,44 @@ else: dynlib: "user32", importc: "LoadCursorFromFileA".} proc LoadIcon*(hInstance: HINST, lpIconName: LPCSTR): HICON{.stdcall, dynlib: "user32", importc: "LoadIconA".} - proc LoadImage*(para1: HINST, para2: LPCSTR, para3: UINT, para4: int32, - para5: int32, para6: UINT): HANDLE{.stdcall, dynlib: "user32", + proc LoadImage*(para1: HINST, para2: LPCSTR, para3: WINUINT, para4: int32, + para5: int32, para6: WINUINT): HANDLE{.stdcall, dynlib: "user32", importc: "LoadImageA".} - proc LoadString*(hInstance: HINST, uID: UINT, lpBuffer: LPSTR, + proc LoadString*(hInstance: HINST, uID: WINUINT, lpBuffer: LPSTR, nBufferMax: int32): int32{.stdcall, dynlib: "user32", importc: "LoadStringA".} proc IsDialogMessage*(hDlg: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, dynlib: "user32", importc: "IsDialogMessageA".} proc DlgDirList*(hDlg: HWND, lpPathSpec: LPSTR, nIDListBox: int32, - nIDStaticPath: int32, uFileType: UINT): int32{.stdcall, + nIDStaticPath: int32, uFileType: WINUINT): int32{.stdcall, dynlib: "user32", importc: "DlgDirListA".} proc DlgDirSelectEx*(hDlg: HWND, lpString: LPSTR, nCount: int32, nIDListBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectExA".} proc DlgDirListComboBox*(hDlg: HWND, lpPathSpec: LPSTR, nIDComboBox: int32, - nIDStaticPath: int32, uFiletype: UINT): int32{. + nIDStaticPath: int32, uFiletype: WINUINT): int32{. stdcall, dynlib: "user32", importc: "DlgDirListComboBoxA".} proc DlgDirSelectComboBoxEx*(hDlg: HWND, lpString: LPSTR, nCount: int32, nIDComboBox: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "DlgDirSelectComboBoxExA".} - proc DefFrameProc*(wnd: HWND, hWndMDIClient: HWND, uMsg: UINT, + proc DefFrameProc*(wnd: HWND, hWndMDIClient: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{.stdcall, dynlib: "user32", importc: "DefFrameProcA".} - proc DefMDIChildProc*(wnd: HWND, uMsg: UINT, wp: WPARAM, lp: LPARAM): LRESULT{. + proc DefMDIChildProc*(wnd: HWND, uMsg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "DefMDIChildProcA".} proc CreateMDIWindow*(lpClassName: LPSTR, lpWindowName: LPSTR, dwStyle: DWORD, X: int32, Y: int32, nWidth: int32, nHeight: int32, hWndParent: HWND, hInstance: HINST, lp: LPARAM): HWND{. stdcall, dynlib: "user32", importc: "CreateMDIWindowA".} - proc WinHelp*(hWndMain: HWND, lpszHelp: LPCSTR, uCommand: UINT, dwData: DWORD): WINBOOL{. + proc WinHelp*(hWndMain: HWND, lpszHelp: LPCSTR, uCommand: WINUINT, dwData: DWORD): WINBOOL{. stdcall, dynlib: "user32", importc: "WinHelpA".} proc ChangeDisplaySettings*(lpDevMode: LPDEVMODE, dwFlags: DWORD): LONG{. stdcall, dynlib: "user32", importc: "ChangeDisplaySettingsA".} proc EnumDisplaySettings*(lpszDeviceName: LPCSTR, iModeNum: DWORD, lpDevMode: LPDEVMODE): WINBOOL{.stdcall, dynlib: "user32", importc: "EnumDisplaySettingsA".} - proc SystemParametersInfo*(uiAction: UINT, uiParam: UINT, pvParam: PVOID, - fWinIni: UINT): WINBOOL{.stdcall, dynlib: "user32", + proc SystemParametersInfo*(uiAction: WINUINT, uiParam: WINUINT, pvParam: PVOID, + fWinIni: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "SystemParametersInfoA".} proc AddFontResource*(para1: LPCSTR): int32{.stdcall, dynlib: "gdi32", importc: "AddFontResourceA".} @@ -18037,25 +18037,25 @@ else: proc EnumFonts*(para1: HDC, para2: LPCSTR, para3: ENUMFONTSPROC, para4: pointer): int32{.stdcall, dynlib: "gdi32", importc: "EnumFontsA".} - proc GetCharWidth*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. + proc GetCharWidth*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthA".} - proc GetCharWidth32*(para1: HDC, para2: UINT, para3: UINT, para4: LPINT): WINBOOL{. + proc GetCharWidth32*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidth32A".} - proc GetCharWidthFloat*(para1: HDC, para2: UINT, para3: UINT, para4: ptr float32): WINBOOL{. + proc GetCharWidthFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: ptr float32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} - proc GetCharABCWidths*(para1: HDC, para2: UINT, para3: UINT, para4: LPABC): WINBOOL{. + proc GetCharABCWidths*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABC): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} - proc GetCharABCWidthsFloat*(para1: HDC, para2: UINT, para3: UINT, + proc GetCharABCWidthsFloat*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPABCFLOAT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} - proc GetGlyphOutline*(para1: HDC, para2: UINT, para3: UINT, + proc GetGlyphOutline*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: LPGLYPHMETRICS, para5: DWORD, para6: LPVOID, para7: PMAT2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineA".} proc GetMetaFile*(para1: LPCSTR): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetMetaFileA".} - proc GetOutlineTextMetrics*(para1: HDC, para2: UINT, - para3: LPOUTLINETEXTMETRIC): UINT{.stdcall, + proc GetOutlineTextMetrics*(para1: HDC, para2: WINUINT, + para3: LPOUTLINETEXTMETRIC): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetOutlineTextMetricsA".} proc GetTextExtentPoint*(para1: HDC, para2: LPCSTR, para3: int32, para4: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", @@ -18081,7 +18081,7 @@ else: importc: "CreateEnhMetaFileA".} proc GetEnhMetaFile*(para1: LPCSTR): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileA".} - proc GetEnhMetaFileDescription*(para1: HENHMETAFILE, para2: UINT, para3: LPSTR): UINT{. + proc GetEnhMetaFileDescription*(para1: HENHMETAFILE, para2: WINUINT, para3: LPSTR): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileDescriptionA".} proc GetTextMetrics*(para1: HDC, para2: LPTEXTMETRIC): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetTextMetricsA".} @@ -18092,8 +18092,8 @@ else: proc TextOut*(para1: HDC, para2: int32, para3: int32, para4: LPCSTR, para5: int32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "TextOutA".} - proc ExtTextOut*(para1: HDC, para2: int32, para3: int32, para4: UINT, - para5: LPRECT, para6: LPCSTR, para7: UINT, para8: LPINT): WINBOOL{. + proc ExtTextOut*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, + para5: LPRECT, para6: LPCSTR, para7: WINUINT, para8: LPINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "ExtTextOutA".} proc PolyTextOut*(para1: HDC, para2: PPOLYTEXT, para3: int32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PolyTextOutA".} @@ -18110,19 +18110,19 @@ else: dynlib: "gdi32", importc: "GetICMProfileA".} proc SetICMProfile*(para1: HDC, para2: LPSTR): WINBOOL{.stdcall, dynlib: "gdi32", importc: "SetICMProfileA".} - proc UpdateICMRegKey*(para1: DWORD, para2: DWORD, para3: LPSTR, para4: UINT): WINBOOL{. + proc UpdateICMRegKey*(para1: DWORD, para2: DWORD, para3: LPSTR, para4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "UpdateICMRegKeyA".} proc EnumICMProfiles*(para1: HDC, para2: ICMENUMPROC, para3: LPARAM): int32{. stdcall, dynlib: "gdi32", importc: "EnumICMProfilesA".} proc PropertySheet*(lppsph: LPCPROPSHEETHEADER): int32{.stdcall, dynlib: "comctl32", importc: "PropertySheetA".} proc ImageList_LoadImage*(hi: HINST, lpbmp: LPCSTR, cx: int32, cGrow: int32, - crMask: COLORREF, uType: UINT, uFlags: UINT): HIMAGELIST{. + crMask: COLORREF, uType: WINUINT, uFlags: WINUINT): HIMAGELIST{. stdcall, dynlib: "comctl32", importc: "ImageList_LoadImageA".} proc CreateStatusWindow*(style: LONG, lpszText: LPCSTR, hwndParent: HWND, - wID: UINT): HWND{.stdcall, dynlib: "comctl32", + wID: WINUINT): HWND{.stdcall, dynlib: "comctl32", importc: "CreateStatusWindowA".} - proc DrawStatusText*(hDC: HDC, lprc: LPRECT, pszText: LPCSTR, uFlags: UINT){. + proc DrawStatusText*(hDC: HDC, lprc: LPRECT, pszText: LPCSTR, uFlags: WINUINT){. stdcall, dynlib: "comctl32", importc: "DrawStatusTextA".} proc GetOpenFileName*(para1: LPOPENFILENAME): WINBOOL{.stdcall, dynlib: "comdlg32", importc: "GetOpenFileNameA".} @@ -18477,7 +18477,7 @@ else: proc DdeCreateStringHandle*(para1: DWORD, para2: cstring, para3: int32): HSZ{. stdcall, dynlib: "user32", importc: "DdeCreateStringHandleA".} proc DdeInitialize*(para1: LPDWORD, para2: PFNCALLBACK, para3: DWORD, - para4: DWORD): UINT{.stdcall, dynlib: "user32", + para4: DWORD): WINUINT{.stdcall, dynlib: "user32", importc: "DdeInitializeA".} proc DdeQueryString*(para1: DWORD, para2: HSZ, para3: cstring, para4: DWORD, para5: int32): DWORD{.stdcall, dynlib: "user32", @@ -18519,7 +18519,7 @@ proc GlobalReAlloc*(hMem: HGLOBAL, dwBytes: DWORD, uFlags: INT): HGLOBAL{. stdcall, dynlib: "kernel32", importc: "GlobalReAlloc".} proc GlobalSize*(hMem: HGLOBAL): DWORD{.stdcall, dynlib: "kernel32", importc: "GlobalSize".} -proc GlobalFlags*(hMem: HGLOBAL): UINT{.stdcall, dynlib: "kernel32", +proc GlobalFlags*(hMem: HGLOBAL): WINUINT{.stdcall, dynlib: "kernel32", importc: "GlobalFlags".} proc GlobalLock*(hMem: HGLOBAL): LPVOID{.stdcall, dynlib: "kernel32", importc: "GlobalLock".} @@ -18529,7 +18529,7 @@ proc GlobalUnlock*(hMem: HGLOBAL): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GlobalUnlock".} proc GlobalFree*(hMem: HGLOBAL): HGLOBAL{.stdcall, dynlib: "kernel32", importc: "GlobalFree".} -proc GlobalCompact*(dwMinFree: DWORD): UINT{.stdcall, dynlib: "kernel32", +proc GlobalCompact*(dwMinFree: DWORD): WINUINT{.stdcall, dynlib: "kernel32", importc: "GlobalCompact".} proc GlobalFix*(hMem: HGLOBAL){.stdcall, dynlib: "kernel32", importc: "GlobalFix".} @@ -18541,9 +18541,9 @@ proc GlobalUnWire*(hMem: HGLOBAL): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GlobalUnWire".} proc GlobalMemoryStatus*(lpBuffer: LPMEMORYSTATUS){.stdcall, dynlib: "kernel32", importc: "GlobalMemoryStatus".} -proc LocalAlloc*(uFlags: UINT, uBytes: UINT): HLOCAL{.stdcall, +proc LocalAlloc*(uFlags: WINUINT, uBytes: WINUINT): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalAlloc".} -proc LocalReAlloc*(hMem: HLOCAL, uBytes: UINT, uFlags: UINT): HLOCAL{.stdcall, +proc LocalReAlloc*(hMem: HLOCAL, uBytes: WINUINT, uFlags: WINUINT): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalReAlloc".} proc LocalLock*(hMem: HLOCAL): LPVOID{.stdcall, dynlib: "kernel32", importc: "LocalLock".} @@ -18551,15 +18551,15 @@ proc LocalHandle*(pMem: LPCVOID): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalHandle".} proc LocalUnlock*(hMem: HLOCAL): WINBOOL{.stdcall, dynlib: "kernel32", importc: "LocalUnlock".} -proc LocalSize*(hMem: HLOCAL): UINT{.stdcall, dynlib: "kernel32", +proc LocalSize*(hMem: HLOCAL): WINUINT{.stdcall, dynlib: "kernel32", importc: "LocalSize".} -proc LocalFlags*(hMem: HLOCAL): UINT{.stdcall, dynlib: "kernel32", +proc LocalFlags*(hMem: HLOCAL): WINUINT{.stdcall, dynlib: "kernel32", importc: "LocalFlags".} proc LocalFree*(hMem: HLOCAL): HLOCAL{.stdcall, dynlib: "kernel32", importc: "LocalFree".} -proc LocalShrink*(hMem: HLOCAL, cbNewSize: UINT): UINT{.stdcall, +proc LocalShrink*(hMem: HLOCAL, cbNewSize: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "LocalShrink".} -proc LocalCompact*(uMinFree: UINT): UINT{.stdcall, dynlib: "kernel32", +proc LocalCompact*(uMinFree: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "LocalCompact".} proc FlushInstructionCache*(hProcess: HANDLE, lpBaseAddress: LPCVOID, dwSize: DWORD): WINBOOL{.stdcall, @@ -18595,7 +18595,7 @@ proc HeapSize*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): DWORD{.stdcall, dynlib: "kernel32", importc: "HeapSize".} proc HeapValidate*(hHeap: HANDLE, dwFlags: DWORD, lpMem: LPCVOID): WINBOOL{. stdcall, dynlib: "kernel32", importc: "HeapValidate".} -proc HeapCompact*(hHeap: HANDLE, dwFlags: DWORD): UINT{.stdcall, +proc HeapCompact*(hHeap: HANDLE, dwFlags: DWORD): WINUINT{.stdcall, dynlib: "kernel32", importc: "HeapCompact".} proc GetProcessHeap*(): HANDLE{.stdcall, dynlib: "kernel32", importc: "GetProcessHeap".} @@ -18628,9 +18628,9 @@ proc GetCurrentProcess*(): HANDLE{.stdcall, dynlib: "kernel32", importc: "GetCurrentProcess".} proc GetCurrentProcessId*(): DWORD{.stdcall, dynlib: "kernel32", importc: "GetCurrentProcessId".} -proc ExitProcess*(uExitCode: UINT){.stdcall, dynlib: "kernel32", +proc ExitProcess*(uExitCode: WINUINT){.stdcall, dynlib: "kernel32", importc: "ExitProcess".} -proc TerminateProcess*(hProcess: HANDLE, uExitCode: UINT): WINBOOL{.stdcall, +proc TerminateProcess*(hProcess: HANDLE, uExitCode: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "TerminateProcess".} proc SetProcessAffinityMask*(hProcess: THandle, dwProcessAffinityMask: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetProcessAffinityMask".} @@ -18681,7 +18681,7 @@ proc CreateIoCompletionPort*(FileHandle: HANDLE, ExistingCompletionPort: HANDLE, CompletionKey: DWORD, NumberOfConcurrentThreads: DWORD): HANDLE{.stdcall, dynlib: "kernel32", importc: "CreateIoCompletionPort".} -proc SetErrorMode*(uMode: UINT): UINT{.stdcall, dynlib: "kernel32", +proc SetErrorMode*(uMode: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "SetErrorMode".} proc ReadProcessMemory*(hProcess: HANDLE, lpBaseAddress: LPCVOID, lpBuffer: LPVOID, nSize: DWORD, @@ -18741,7 +18741,7 @@ proc InitAtomTable*(nSize: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "InitAtomTable".} proc DeleteAtom*(nAtom: ATOM): ATOM{.stdcall, dynlib: "kernel32", importc: "DeleteAtom".} -proc SetHandleCount*(uNumber: UINT): UINT{.stdcall, dynlib: "kernel32", +proc SetHandleCount*(uNumber: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "SetHandleCount".} proc GetLogicalDrives*(): DWORD{.stdcall, dynlib: "kernel32", importc: "GetLogicalDrives".} @@ -18803,7 +18803,7 @@ proc SetHandleInformation*(hObject: HANDLE, dwMask: DWORD, dwFlags: DWORD): WINB stdcall, dynlib: "kernel32", importc: "SetHandleInformation".} proc LoadModule*(lpModuleName: LPCSTR, lpParameterBlock: LPVOID): DWORD{. stdcall, dynlib: "kernel32", importc: "LoadModule".} -proc WinExec*(lpCmdLine: LPCSTR, uCmdShow: UINT): UINT{.stdcall, +proc WinExec*(lpCmdLine: LPCSTR, uCmdShow: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "WinExec".} proc ClearCommBreak*(hFile: HANDLE): WINBOOL{.stdcall, dynlib: "kernel32", importc: "ClearCommBreak".} @@ -18954,15 +18954,15 @@ proc FlushViewOfFile*(lpBaseAddress: LPCVOID, dwNumberOfBytesToFlush: DWORD): WI stdcall, dynlib: "kernel32", importc: "FlushViewOfFile".} proc UnmapViewOfFile*(lpBaseAddress: LPVOID): WINBOOL{.stdcall, dynlib: "kernel32", importc: "UnmapViewOfFile".} -proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: LPOFSTRUCT, uStyle: UINT): HFILE{. +proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: LPOFSTRUCT, uStyle: WINUINT): HFILE{. stdcall, dynlib: "kernel32", importc: "OpenFile".} proc lopen*(lpPathName: LPCSTR, iReadWrite: int32): HFILE{.stdcall, dynlib: "kernel32", importc: "_lopen".} proc lcreat*(lpPathName: LPCSTR, iAttribute: int32): HFILE{.stdcall, dynlib: "kernel32", importc: "_lcreat".} -proc lread*(hFile: HFILE, lpBuffer: LPVOID, uBytes: UINT): UINT{.stdcall, +proc lread*(hFile: HFILE, lpBuffer: LPVOID, uBytes: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "_lread".} -proc lwrite*(hFile: HFILE, lpBuffer: LPCSTR, uBytes: UINT): UINT{.stdcall, +proc lwrite*(hFile: HFILE, lpBuffer: LPCSTR, uBytes: WINUINT): WINUINT{.stdcall, dynlib: "kernel32", importc: "_lwrite".} proc hread*(hFile: HFILE, lpBuffer: LPVOID, lBytes: int32): int32{.stdcall, dynlib: "kernel32", importc: "_hread".} @@ -19233,13 +19233,13 @@ proc SetPriorityClass*(hProcess: HANDLE, dwPriorityClass: DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetPriorityClass".} proc GetPriorityClass*(hProcess: HANDLE): DWORD{.stdcall, dynlib: "kernel32", importc: "GetPriorityClass".} -proc IsBadReadPtr*(lp: pointer, ucb: UINT): WINBOOL{.stdcall, +proc IsBadReadPtr*(lp: pointer, ucb: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadReadPtr".} -proc IsBadWritePtr*(lp: LPVOID, ucb: UINT): WINBOOL{.stdcall, +proc IsBadWritePtr*(lp: LPVOID, ucb: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadWritePtr".} -proc IsBadHugeReadPtr*(lp: pointer, ucb: UINT): WINBOOL{.stdcall, +proc IsBadHugeReadPtr*(lp: pointer, ucb: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadHugeReadPtr".} -proc IsBadHugeWritePtr*(lp: LPVOID, ucb: UINT): WINBOOL{.stdcall, +proc IsBadHugeWritePtr*(lp: LPVOID, ucb: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadHugeWritePtr".} proc IsBadCodePtr*(lpfn: FARPROC): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsBadCodePtr".} @@ -19249,7 +19249,7 @@ proc QueryPerformanceCounter*(lpPerformanceCount: PLARGE_INTEGER): WINBOOL{. stdcall, dynlib: "kernel32", importc: "QueryPerformanceCounter".} proc QueryPerformanceFrequency*(lpFrequency: PLARGE_INTEGER): WINBOOL{.stdcall, dynlib: "kernel32", importc: "QueryPerformanceFrequency".} -proc ActivateKeyboardLayout*(hkl: HKL, Flags: UINT): WINBOOL{.stdcall, +proc ActivateKeyboardLayout*(hkl: HKL, Flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "ActivateKeyboardLayout".} proc UnloadKeyboardLayout*(hkl: HKL): WINBOOL{.stdcall, dynlib: "user32", importc: "UnloadKeyboardLayout".} @@ -19286,11 +19286,11 @@ proc TranslateMessage*(lpMsg: LPMSG): WINBOOL{.stdcall, dynlib: "user32", importc: "TranslateMessage".} proc SetMessageQueue*(cMessagesMax: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "SetMessageQueue".} -proc RegisterHotKey*(wnd: HWND, anID: int32, fsModifiers: UINT, vk: UINT): WINBOOL{. +proc RegisterHotKey*(wnd: HWND, anID: int32, fsModifiers: WINUINT, vk: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "RegisterHotKey".} proc UnregisterHotKey*(wnd: HWND, anID: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "UnregisterHotKey".} -proc ExitWindowsEx*(uFlags: UINT, dwReserved: DWORD): WINBOOL{.stdcall, +proc ExitWindowsEx*(uFlags: WINUINT, dwReserved: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "ExitWindowsEx".} proc SwapMouseButton*(fSwap: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", importc: "SwapMouseButton".} @@ -19302,7 +19302,7 @@ proc GetMessageExtraInfo*(): LONG{.stdcall, dynlib: "user32", importc: "GetMessageExtraInfo".} proc SetMessageExtraInfo*(lp: LPARAM): LPARAM{.stdcall, dynlib: "user32", importc: "SetMessageExtraInfo".} -proc BroadcastSystemMessage*(para1: DWORD, para2: LPDWORD, para3: UINT, +proc BroadcastSystemMessage*(para1: DWORD, para2: LPDWORD, para3: WINUINT, para4: WPARAM, para5: LPARAM): int32{.stdcall, dynlib: "user32", importc: "BroadcastSystemMessage".} proc AttachThreadInput*(idAttach: DWORD, idAttachTo: DWORD, fAttach: WINBOOL): WINBOOL{. @@ -19316,9 +19316,9 @@ proc PostQuitMessage*(nExitCode: int32){.stdcall, dynlib: "user32", importc: "PostQuitMessage".} proc InSendMessage*(): WINBOOL{.stdcall, dynlib: "user32", importc: "InSendMessage".} -proc GetDoubleClickTime*(): UINT{.stdcall, dynlib: "user32", +proc GetDoubleClickTime*(): WINUINT{.stdcall, dynlib: "user32", importc: "GetDoubleClickTime".} -proc SetDoubleClickTime*(para1: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc SetDoubleClickTime*(para1: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "SetDoubleClickTime".} proc IsWindow*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", importc: "IsWindow".} @@ -19344,7 +19344,7 @@ proc MoveWindow*(wnd: HWND, X: int32, Y: int32, nWidth: int32, nHeight: int32, bRepaint: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", importc: "MoveWindow".} proc SetWindowPos*(wnd: HWND, hWndInsertAfter: HWND, X: int32, Y: int32, - cx: int32, cy: int32, uFlags: UINT): WINBOOL{.stdcall, + cx: int32, cy: int32, uFlags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "SetWindowPos".} proc GetWindowPlacement*(wnd: HWND, lpwndpl: var WINDOWPLACEMENT): WINBOOL{. stdcall, dynlib: "user32", importc: "GetWindowPlacement".} @@ -19357,7 +19357,7 @@ proc SetWindowPlacement*(wnd: HWND, lpwndpl: PWINDOWPLACEMENT): WINBOOL{. proc BeginDeferWindowPos*(nNumWindows: int32): HDWP{.stdcall, dynlib: "user32", importc: "BeginDeferWindowPos".} proc DeferWindowPos*(hWinPosInfo: HDWP, wnd: HWND, hWndInsertAfter: HWND, - x: int32, y: int32, cx: int32, cy: int32, uFlags: UINT): HDWP{. + x: int32, y: int32, cx: int32, cy: int32, uFlags: WINUINT): HDWP{. stdcall, dynlib: "user32", importc: "DeferWindowPos".} proc EndDeferWindowPos*(hWinPosInfo: HDWP): WINBOOL{.stdcall, dynlib: "user32", importc: "EndDeferWindowPos".} @@ -19374,18 +19374,18 @@ proc EndDialog*(hDlg: HWND, nResult: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "EndDialog".} proc GetDlgItem*(hDlg: HWND, nIDDlgItem: int32): HWND{.stdcall, dynlib: "user32", importc: "GetDlgItem".} -proc SetDlgItemInt*(hDlg: HWND, nIDDlgItem: int32, uValue: UINT, +proc SetDlgItemInt*(hDlg: HWND, nIDDlgItem: int32, uValue: WINUINT, bSigned: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", importc: "SetDlgItemInt".} proc GetDlgItemInt*(hDlg: HWND, nIDDlgItem: int32, lpTranslated: var WINBOOL, - bSigned: WINBOOL): UINT{.stdcall, dynlib: "user32", + bSigned: WINBOOL): WINUINT{.stdcall, dynlib: "user32", importc: "GetDlgItemInt".} -proc CheckDlgButton*(hDlg: HWND, nIDButton: int32, uCheck: UINT): WINBOOL{. +proc CheckDlgButton*(hDlg: HWND, nIDButton: int32, uCheck: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "CheckDlgButton".} proc CheckRadioButton*(hDlg: HWND, nIDFirstButton: int32, nIDLastButton: int32, nIDCheckButton: int32): WINBOOL{.stdcall, dynlib: "user32", importc: "CheckRadioButton".} -proc IsDlgButtonChecked*(hDlg: HWND, nIDButton: int32): UINT{.stdcall, +proc IsDlgButtonChecked*(hDlg: HWND, nIDButton: int32): WINUINT{.stdcall, dynlib: "user32", importc: "IsDlgButtonChecked".} proc GetNextDlgGroupItem*(hDlg: HWND, hCtl: HWND, bPrevious: WINBOOL): HWND{. stdcall, dynlib: "user32", importc: "GetNextDlgGroupItem".} @@ -19407,19 +19407,19 @@ proc GetClipboardViewer*(): HWND{.stdcall, dynlib: "user32", importc: "GetClipboardViewer".} proc ChangeClipboardChain*(hWndRemove: HWND, hWndNewNext: HWND): WINBOOL{. stdcall, dynlib: "user32", importc: "ChangeClipboardChain".} -proc SetClipboardData*(uFormat: UINT, hMem: HANDLE): HANDLE{.stdcall, +proc SetClipboardData*(uFormat: WINUINT, hMem: HANDLE): HANDLE{.stdcall, dynlib: "user32", importc: "SetClipboardData".} -proc GetClipboardData*(uFormat: UINT): HANDLE{.stdcall, dynlib: "user32", +proc GetClipboardData*(uFormat: WINUINT): HANDLE{.stdcall, dynlib: "user32", importc: "GetClipboardData".} proc CountClipboardFormats*(): int32{.stdcall, dynlib: "user32", importc: "CountClipboardFormats".} -proc EnumClipboardFormats*(format: UINT): UINT{.stdcall, dynlib: "user32", +proc EnumClipboardFormats*(format: WINUINT): WINUINT{.stdcall, dynlib: "user32", importc: "EnumClipboardFormats".} proc EmptyClipboard*(): WINBOOL{.stdcall, dynlib: "user32", importc: "EmptyClipboard".} -proc IsClipboardFormatAvailable*(format: UINT): WINBOOL{.stdcall, +proc IsClipboardFormatAvailable*(format: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "IsClipboardFormatAvailable".} -proc GetPriorityClipboardFormat*(paFormatPriorityList: var UINT, cFormats: int32): int32{. +proc GetPriorityClipboardFormat*(paFormatPriorityList: var WINUINT, cFormats: int32): int32{. stdcall, dynlib: "user32", importc: "GetPriorityClipboardFormat".} proc GetOpenClipboardWindow*(): HWND{.stdcall, dynlib: "user32", importc: "GetOpenClipboardWindow".} @@ -19432,7 +19432,7 @@ proc SetFocus*(wnd: HWND): HWND{.stdcall, dynlib: "user32", importc: "SetFocus". proc GetActiveWindow*(): HWND{.stdcall, dynlib: "user32", importc: "GetActiveWindow".} proc GetFocus*(): HWND{.stdcall, dynlib: "user32", importc: "GetFocus".} -proc GetKBCodePage*(): UINT{.stdcall, dynlib: "user32", importc: "GetKBCodePage".} +proc GetKBCodePage*(): WINUINT{.stdcall, dynlib: "user32", importc: "GetKBCodePage".} proc GetKeyState*(nVirtKey: int32): SHORT{.stdcall, dynlib: "user32", importc: "GetKeyState".} proc GetAsyncKeyState*(vKey: int32): SHORT{.stdcall, dynlib: "user32", @@ -19443,14 +19443,14 @@ proc SetKeyboardState*(lpKeyState: LPBYTE): WINBOOL{.stdcall, dynlib: "user32", importc: "SetKeyboardState".} proc GetKeyboardType*(nTypeFlag: int32): int32{.stdcall, dynlib: "user32", importc: "GetKeyboardType".} -proc ToAscii*(uVirtKey: UINT, uScanCode: UINT, lpKeyState: PBYTE, - lpChar: LPWORD, uFlags: UINT): int32{.stdcall, dynlib: "user32", +proc ToAscii*(uVirtKey: WINUINT, uScanCode: WINUINT, lpKeyState: PBYTE, + lpChar: LPWORD, uFlags: WINUINT): int32{.stdcall, dynlib: "user32", importc: "ToAscii".} -proc ToAsciiEx*(uVirtKey: UINT, uScanCode: UINT, lpKeyState: PBYTE, - lpChar: LPWORD, uFlags: UINT, dwhkl: HKL): int32{.stdcall, +proc ToAsciiEx*(uVirtKey: WINUINT, uScanCode: WINUINT, lpKeyState: PBYTE, + lpChar: LPWORD, uFlags: WINUINT, dwhkl: HKL): int32{.stdcall, dynlib: "user32", importc: "ToAsciiEx".} -proc ToUnicode*(wVirtKey: UINT, wScanCode: UINT, lpKeyState: PBYTE, - pwszBuff: LPWSTR, cchBuff: int32, wFlags: UINT): int32{.stdcall, +proc ToUnicode*(wVirtKey: WINUINT, wScanCode: WINUINT, lpKeyState: PBYTE, + pwszBuff: LPWSTR, cchBuff: int32, wFlags: WINUINT): int32{.stdcall, dynlib: "user32", importc: "ToUnicode".} proc OemKeyScan*(wOemChar: int16): DWORD{.stdcall, dynlib: "user32", importc: "OemKeyScan".} @@ -19461,7 +19461,7 @@ proc mouse_event*(dwFlags: DWORD, dx: DWORD, dy: DWORD, cButtons: DWORD, importc: "mouse_event".} proc GetInputState*(): WINBOOL{.stdcall, dynlib: "user32", importc: "GetInputState".} -proc GetQueueStatus*(flags: UINT): DWORD{.stdcall, dynlib: "user32", +proc GetQueueStatus*(flags: WINUINT): DWORD{.stdcall, dynlib: "user32", importc: "GetQueueStatus".} proc GetCapture*(): HWND{.stdcall, dynlib: "user32", importc: "GetCapture".} proc SetCapture*(wnd: HWND): HWND{.stdcall, dynlib: "user32", @@ -19472,9 +19472,9 @@ proc MsgWaitForMultipleObjects*(nCount: DWORD, pHandles: LPHANDLE, fWaitAll: WINBOOL, dwMilliseconds: DWORD, dwWakeMask: DWORD): DWORD{.stdcall, dynlib: "user32", importc: "MsgWaitForMultipleObjects".} -proc SetTimer*(wnd: HWND, nIDEvent: UINT, uElapse: UINT, lpTimerFunc: TIMERPROC): UINT{. +proc SetTimer*(wnd: HWND, nIDEvent: WINUINT, uElapse: WINUINT, lpTimerFunc: TIMERPROC): WINUINT{. stdcall, dynlib: "user32", importc: "SetTimer".} -proc KillTimer*(wnd: HWND, uIDEvent: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc KillTimer*(wnd: HWND, uIDEvent: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "KillTimer".} proc IsWindowUnicode*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", importc: "IsWindowUnicode".} @@ -19489,10 +19489,10 @@ proc GetSystemMetrics*(nIndex: int32): int32{.stdcall, dynlib: "user32", proc GetMenu*(wnd: HWND): HMENU{.stdcall, dynlib: "user32", importc: "GetMenu".} proc SetMenu*(wnd: HWND, menu: HMENU): WINBOOL{.stdcall, dynlib: "user32", importc: "SetMenu".} -proc HiliteMenuItem*(wnd: HWND, menu: HMENU, uIDHiliteItem: UINT, - uHilite: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc HiliteMenuItem*(wnd: HWND, menu: HMENU, uIDHiliteItem: WINUINT, + uHilite: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "HiliteMenuItem".} -proc GetMenuState*(menu: HMENU, uId: UINT, uFlags: UINT): UINT{.stdcall, +proc GetMenuState*(menu: HMENU, uId: WINUINT, uFlags: WINUINT): WINUINT{.stdcall, dynlib: "user32", importc: "GetMenuState".} proc DrawMenuBar*(wnd: HWND): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawMenuBar".} @@ -19503,37 +19503,37 @@ proc CreatePopupMenu*(): HMENU{.stdcall, dynlib: "user32", importc: "CreatePopupMenu".} proc DestroyMenu*(menu: HMENU): WINBOOL{.stdcall, dynlib: "user32", importc: "DestroyMenu".} -proc CheckMenuItem*(menu: HMENU, uIDCheckItem: UINT, uCheck: UINT): DWORD{. +proc CheckMenuItem*(menu: HMENU, uIDCheckItem: WINUINT, uCheck: WINUINT): DWORD{. stdcall, dynlib: "user32", importc: "CheckMenuItem".} -proc EnableMenuItem*(menu: HMENU, uIDEnableItem: UINT, uEnable: UINT): WINBOOL{. +proc EnableMenuItem*(menu: HMENU, uIDEnableItem: WINUINT, uEnable: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "EnableMenuItem".} proc GetSubMenu*(menu: HMENU, nPos: int32): HMENU{.stdcall, dynlib: "user32", importc: "GetSubMenu".} -proc GetMenuItemID*(menu: HMENU, nPos: int32): UINT{.stdcall, dynlib: "user32", +proc GetMenuItemID*(menu: HMENU, nPos: int32): WINUINT{.stdcall, dynlib: "user32", importc: "GetMenuItemID".} proc GetMenuItemCount*(menu: HMENU): int32{.stdcall, dynlib: "user32", importc: "GetMenuItemCount".} -proc RemoveMenu*(menu: HMENU, uPosition: UINT, uFlags: UINT): WINBOOL{.stdcall, +proc RemoveMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "RemoveMenu".} -proc DeleteMenu*(menu: HMENU, uPosition: UINT, uFlags: UINT): WINBOOL{.stdcall, +proc DeleteMenu*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "DeleteMenu".} -proc SetMenuItemBitmaps*(menu: HMENU, uPosition: UINT, uFlags: UINT, +proc SetMenuItemBitmaps*(menu: HMENU, uPosition: WINUINT, uFlags: WINUINT, hBitmapUnchecked: HBITMAP, hBitmapChecked: HBITMAP): WINBOOL{. stdcall, dynlib: "user32", importc: "SetMenuItemBitmaps".} proc GetMenuCheckMarkDimensions*(): LONG{.stdcall, dynlib: "user32", importc: "GetMenuCheckMarkDimensions".} -proc TrackPopupMenu*(menu: HMENU, uFlags: UINT, x: int32, y: int32, +proc TrackPopupMenu*(menu: HMENU, uFlags: WINUINT, x: int32, y: int32, nReserved: int32, wnd: HWND, prcRect: var RECT): WINBOOL{. stdcall, dynlib: "user32", importc: "TrackPopupMenu".} -proc GetMenuDefaultItem*(menu: HMENU, fByPos: UINT, gmdiFlags: UINT): UINT{. +proc GetMenuDefaultItem*(menu: HMENU, fByPos: WINUINT, gmdiFlags: WINUINT): WINUINT{. stdcall, dynlib: "user32", importc: "GetMenuDefaultItem".} -proc SetMenuDefaultItem*(menu: HMENU, uItem: UINT, fByPos: UINT): WINBOOL{. +proc SetMenuDefaultItem*(menu: HMENU, uItem: WINUINT, fByPos: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "SetMenuDefaultItem".} -proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: UINT, lprcItem: LPRECT): WINBOOL{. +proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: WINUINT, lprcItem: LPRECT): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMenuItemRect".} proc MenuItemFromPoint*(wnd: HWND, menu: HMENU, ptScreen: POINT): int32{. stdcall, dynlib: "user32", importc: "MenuItemFromPoint".} -proc DragObject*(para1: HWND, para2: HWND, para3: UINT, para4: DWORD, +proc DragObject*(para1: HWND, para2: HWND, para3: WINUINT, para4: DWORD, para5: HCURSOR): DWORD{.stdcall, dynlib: "user32", importc: "DragObject".} proc DragDetect*(wnd: HWND, pt: POINT): WINBOOL{.stdcall, dynlib: "user32", @@ -19586,9 +19586,9 @@ proc InvalidateRgn*(wnd: HWND, hRgn: HRGN, bErase: WINBOOL): WINBOOL{.stdcall, proc ValidateRgn*(wnd: HWND, hRgn: HRGN): WINBOOL{.stdcall, dynlib: "user32", importc: "ValidateRgn".} proc RedrawWindow*(wnd: HWND, lprcUpdate: var RECT, hrgnUpdate: HRGN, - flags: UINT): WINBOOL{.stdcall, dynlib: "user32", + flags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "RedrawWindow".} -proc RedrawWindow*(wnd: HWND, lprcUpdate: LPRECT, hrgnUpdate: HRGN, flags: UINT): WINBOOL{. +proc RedrawWindow*(wnd: HWND, lprcUpdate: LPRECT, hrgnUpdate: HRGN, flags: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "RedrawWindow".} proc LockWindowUpdate*(hWndLock: HWND): WINBOOL{.stdcall, dynlib: "user32", importc: "LockWindowUpdate".} @@ -19600,7 +19600,7 @@ proc ScrollDC*(hDC: HDC, dx: int32, dy: int32, lprcScroll: var RECT, stdcall, dynlib: "user32", importc: "ScrollDC".} proc ScrollWindowEx*(wnd: HWND, dx: int32, dy: int32, prcScroll: var RECT, prcClip: var RECT, hrgnUpdate: HRGN, prcUpdate: LPRECT, - flags: UINT): int32{.stdcall, dynlib: "user32", + flags: WINUINT): int32{.stdcall, dynlib: "user32", importc: "ScrollWindowEx".} proc SetScrollPos*(wnd: HWND, nBar: int32, nPos: int32, bRedraw: WINBOOL): int32{. stdcall, dynlib: "user32", importc: "SetScrollPos".} @@ -19613,7 +19613,7 @@ proc GetScrollRange*(wnd: HWND, nBar: int32, lpMinPos: LPINT, lpMaxPos: LPINT): stdcall, dynlib: "user32", importc: "GetScrollRange".} proc ShowScrollBar*(wnd: HWND, wBar: int32, bShow: WINBOOL): WINBOOL{.stdcall, dynlib: "user32", importc: "ShowScrollBar".} -proc EnableScrollBar*(wnd: HWND, wSBflags: UINT, wArrows: UINT): WINBOOL{. +proc EnableScrollBar*(wnd: HWND, wSBflags: WINUINT, wArrows: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "EnableScrollBar".} proc GetClientRect*(wnd: HWND, lpRect: LPRECT): WINBOOL{.stdcall, dynlib: "user32", importc: "GetClientRect".} @@ -19632,7 +19632,7 @@ proc SetMenuContextHelpId*(para1: HMENU, para2: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "SetMenuContextHelpId".} proc GetMenuContextHelpId*(para1: HMENU): DWORD{.stdcall, dynlib: "user32", importc: "GetMenuContextHelpId".} -proc MessageBeep*(uType: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc MessageBeep*(uType: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "MessageBeep".} proc ShowCursor*(bShow: WINBOOL): int32{.stdcall, dynlib: "user32", importc: "ShowCursor".} @@ -19649,9 +19649,9 @@ proc GetClipCursor*(lpRect: LPRECT): WINBOOL{.stdcall, dynlib: "user32", proc GetCursor*(): HCURSOR{.stdcall, dynlib: "user32", importc: "GetCursor".} proc CreateCaret*(wnd: HWND, hBitmap: HBITMAP, nWidth: int32, nHeight: int32): WINBOOL{. stdcall, dynlib: "user32", importc: "CreateCaret".} -proc GetCaretBlinkTime*(): UINT{.stdcall, dynlib: "user32", +proc GetCaretBlinkTime*(): WINUINT{.stdcall, dynlib: "user32", importc: "GetCaretBlinkTime".} -proc SetCaretBlinkTime*(uMSeconds: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc SetCaretBlinkTime*(uMSeconds: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "SetCaretBlinkTime".} proc DestroyCaret*(): WINBOOL{.stdcall, dynlib: "user32", importc: "DestroyCaret".} @@ -19668,7 +19668,7 @@ proc ClientToScreen*(wnd: HWND, lpPoint: LPPOINT): WINBOOL{.stdcall, proc ScreenToClient*(wnd: HWND, lpPoint: LPPOINT): WINBOOL{.stdcall, dynlib: "user32", importc: "ScreenToClient".} proc MapWindowPoints*(hWndFrom: HWND, hWndTo: HWND, lpPoints: LPPOINT, - cPoints: UINT): int32{.stdcall, dynlib: "user32", + cPoints: WINUINT): int32{.stdcall, dynlib: "user32", importc: "MapWindowPoints".} proc WindowFromPoint*(Point: POINT): HWND{.stdcall, dynlib: "user32", importc: "WindowFromPoint".} @@ -19683,7 +19683,7 @@ proc SetSysColors*(cElements: int32, lpaElements: var wINT, dynlib: "user32", importc: "SetSysColors".} proc DrawFocusRect*(hDC: HDC, lprc: var RECT): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawFocusRect".} -proc FillRect*(hDC: HDC, lprc: RECT, hbr: HBRUSH): int32{.stdcall, +proc FillRect*(hDC: HDC, lprc: var RECT, hbr: HBRUSH): int32{.stdcall, dynlib: "user32", importc: "FillRect".} proc FrameRect*(hDC: HDC, lprc: var RECT, hbr: HBRUSH): int32{.stdcall, dynlib: "user32", importc: "FrameRect".} @@ -19743,7 +19743,7 @@ proc GetWindowThreadProcessId*(wnd: HWND, lpdwProcessId: LPDWORD): DWORD{. stdcall, dynlib: "user32", importc: "GetWindowThreadProcessId".} proc GetLastActivePopup*(wnd: HWND): HWND{.stdcall, dynlib: "user32", importc: "GetLastActivePopup".} -proc GetWindow*(wnd: HWND, uCmd: UINT): HWND{.stdcall, dynlib: "user32", +proc GetWindow*(wnd: HWND, uCmd: WINUINT): HWND{.stdcall, dynlib: "user32", importc: "GetWindow".} proc UnhookWindowsHook*(nCode: int32, pfnFilterProc: HOOKPROC): WINBOOL{. stdcall, dynlib: "user32", importc: "UnhookWindowsHook".} @@ -19751,8 +19751,8 @@ proc UnhookWindowsHookEx*(hhk: HHOOK): WINBOOL{.stdcall, dynlib: "user32", importc: "UnhookWindowsHookEx".} proc CallNextHookEx*(hhk: HHOOK, nCode: int32, wp: WPARAM, lp: LPARAM): LRESULT{. stdcall, dynlib: "user32", importc: "CallNextHookEx".} -proc CheckMenuRadioItem*(para1: HMENU, para2: UINT, para3: UINT, para4: UINT, - para5: UINT): WINBOOL{.stdcall, dynlib: "user32", +proc CheckMenuRadioItem*(para1: HMENU, para2: WINUINT, para3: WINUINT, para4: WINUINT, + para5: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "CheckMenuRadioItem".} proc CreateCursor*(hInst: HINST, xHotSpot: int32, yHotSpot: int32, nWidth: int32, nHeight: int32, pvANDPlane: pointer, @@ -19771,17 +19771,17 @@ proc LookupIconIdFromDirectory*(presbits: PBYTE, fIcon: WINBOOL): int32{. stdcall, dynlib: "user32", importc: "LookupIconIdFromDirectory".} proc LookupIconIdFromDirectoryEx*(presbits: PBYTE, fIcon: WINBOOL, cxDesired: int32, cyDesired: int32, - Flags: UINT): int32{.stdcall, + Flags: WINUINT): int32{.stdcall, dynlib: "user32", importc: "LookupIconIdFromDirectoryEx".} proc CreateIconFromResource*(presbits: PBYTE, dwResSize: DWORD, fIcon: WINBOOL, dwVer: DWORD): HICON{.stdcall, dynlib: "user32", importc: "CreateIconFromResource".} proc CreateIconFromResourceEx*(presbits: PBYTE, dwResSize: DWORD, fIcon: WINBOOL, dwVer: DWORD, cxDesired: int32, - cyDesired: int32, Flags: UINT): HICON{.stdcall, + cyDesired: int32, Flags: WINUINT): HICON{.stdcall, dynlib: "user32", importc: "CreateIconFromResourceEx".} -proc CopyImage*(para1: HANDLE, para2: UINT, para3: int32, para4: int32, - para5: UINT): HICON{.stdcall, dynlib: "user32", +proc CopyImage*(para1: HANDLE, para2: WINUINT, para3: int32, para4: int32, + para5: WINUINT): HICON{.stdcall, dynlib: "user32", importc: "CopyImage".} proc CreateIconIndirect*(piconinfo: PICONINFO): HICON{.stdcall, dynlib: "user32", importc: "CreateIconIndirect".} @@ -19798,37 +19798,37 @@ proc GetScrollInfo*(para1: HWND, para2: int32, para3: LPSCROLLINFO): WINBOOL{. stdcall, dynlib: "user32", importc: "GetScrollInfo".} proc TranslateMDISysAccel*(hWndClient: HWND, lpMsg: LPMSG): WINBOOL{.stdcall, dynlib: "user32", importc: "TranslateMDISysAccel".} -proc ArrangeIconicWindows*(wnd: HWND): UINT{.stdcall, dynlib: "user32", +proc ArrangeIconicWindows*(wnd: HWND): WINUINT{.stdcall, dynlib: "user32", importc: "ArrangeIconicWindows".} -proc TileWindows*(hwndParent: HWND, wHow: UINT, lpRect: var RECT, cKids: UINT, +proc TileWindows*(hwndParent: HWND, wHow: WINUINT, lpRect: var RECT, cKids: WINUINT, lpKids: var HWND): int16{.stdcall, dynlib: "user32", importc: "TileWindows".} -proc CascadeWindows*(hwndParent: HWND, wHow: UINT, lpRect: var RECT, - cKids: UINT, lpKids: var HWND): int16{.stdcall, +proc CascadeWindows*(hwndParent: HWND, wHow: WINUINT, lpRect: var RECT, + cKids: WINUINT, lpKids: var HWND): int16{.stdcall, dynlib: "user32", importc: "CascadeWindows".} proc SetLastErrorEx*(dwErrCode: DWORD, dwType: DWORD){.stdcall, dynlib: "user32", importc: "SetLastErrorEx".} proc SetDebugErrorLevel*(dwLevel: DWORD){.stdcall, dynlib: "user32", importc: "SetDebugErrorLevel".} -proc DrawEdge*(hdc: HDC, qrc: LPRECT, edge: UINT, grfFlags: UINT): WINBOOL{. +proc DrawEdge*(hdc: HDC, qrc: LPRECT, edge: WINUINT, grfFlags: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DrawEdge".} -proc DrawFrameControl*(para1: HDC, para2: LPRECT, para3: UINT, para4: UINT): WINBOOL{. +proc DrawFrameControl*(para1: HDC, para2: LPRECT, para3: WINUINT, para4: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DrawFrameControl".} -proc DrawCaption*(para1: HWND, para2: HDC, para3: var RECT, para4: UINT): WINBOOL{. +proc DrawCaption*(para1: HWND, para2: HDC, para3: var RECT, para4: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DrawCaption".} proc DrawAnimatedRects*(wnd: HWND, idAni: int32, lprcFrom: var RECT, lprcTo: var RECT): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawAnimatedRects".} -proc TrackPopupMenuEx*(para1: HMENU, para2: UINT, para3: int32, para4: int32, +proc TrackPopupMenuEx*(para1: HMENU, para2: WINUINT, para3: int32, para4: int32, para5: HWND, para6: LPTPMPARAMS): WINBOOL{.stdcall, dynlib: "user32", importc: "TrackPopupMenuEx".} -proc ChildWindowFromPointEx*(para1: HWND, para2: POINT, para3: UINT): HWND{. +proc ChildWindowFromPointEx*(para1: HWND, para2: POINT, para3: WINUINT): HWND{. stdcall, dynlib: "user32", importc: "ChildWindowFromPointEx".} proc DrawIconEx*(hdc: HDC, xLeft: int32, yTop: int32, icon: HICON, - cxWidth: int32, cyWidth: int32, istepIfAniCur: UINT, - hbrFlickerFreeDraw: HBRUSH, diFlags: UINT): WINBOOL{.stdcall, + cxWidth: int32, cyWidth: int32, istepIfAniCur: WINUINT, + hbrFlickerFreeDraw: HBRUSH, diFlags: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "DrawIconEx".} -proc AnimatePalette*(para1: HPALETTE, para2: UINT, para3: UINT, +proc AnimatePalette*(para1: HPALETTE, para2: WINUINT, para3: WINUINT, para4: var PALETTEENTRY): WINBOOL{.stdcall, dynlib: "gdi32", importc: "AnimatePalette".} proc Arc*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, @@ -19846,7 +19846,7 @@ proc CloseMetaFile*(para1: HDC): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "CloseMetaFile".} proc CombineRgn*(para1: HRGN, para2: HRGN, para3: HRGN, para4: int32): int32{. stdcall, dynlib: "gdi32", importc: "CombineRgn".} -proc CreateBitmap*(para1: int32, para2: int32, para3: UINT, para4: UINT, +proc CreateBitmap*(para1: int32, para2: int32, para3: WINUINT, para4: WINUINT, para5: pointer): HBITMAP{.stdcall, dynlib: "gdi32", importc: "CreateBitmap".} proc CreateBitmapIndirect*(para1: var BITMAP): HBITMAP{.stdcall, @@ -19860,11 +19860,11 @@ proc CreateDiscardableBitmap*(para1: HDC, para2: int32, para3: int32): HBITMAP{. proc CreateCompatibleDC*(para1: HDC): HDC{.stdcall, dynlib: "gdi32", importc: "CreateCompatibleDC".} proc CreateDIBitmap*(para1: HDC, para2: var BITMAPINFOHEADER, para3: DWORD, - para4: pointer, para5: var BITMAPINFO, para6: UINT): HBITMAP{. + para4: pointer, para5: var BITMAPINFO, para6: WINUINT): HBITMAP{. stdcall, dynlib: "gdi32", importc: "CreateDIBitmap".} -proc CreateDIBPatternBrush*(para1: HGLOBAL, para2: UINT): HBRUSH{.stdcall, +proc CreateDIBPatternBrush*(para1: HGLOBAL, para2: WINUINT): HBRUSH{.stdcall, dynlib: "gdi32", importc: "CreateDIBPatternBrush".} -proc CreateDIBPatternBrushPt*(para1: pointer, para2: UINT): HBRUSH{.stdcall, +proc CreateDIBPatternBrushPt*(para1: pointer, para2: WINUINT): HBRUSH{.stdcall, dynlib: "gdi32", importc: "CreateDIBPatternBrushPt".} proc CreateEllipticRgn*(para1: int32, para2: int32, para3: int32, para4: int32): HRGN{. stdcall, dynlib: "gdi32", importc: "CreateEllipticRgn".} @@ -19918,7 +19918,7 @@ proc ExcludeClipRect*(para1: HDC, para2: int32, para3: int32, para4: int32, proc ExtCreateRegion*(para1: var XFORM, para2: DWORD, para3: var RGNDATA): HRGN{. stdcall, dynlib: "gdi32", importc: "ExtCreateRegion".} proc ExtFloodFill*(para1: HDC, para2: int32, para3: int32, para4: COLORREF, - para5: UINT): WINBOOL{.stdcall, dynlib: "gdi32", + para5: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "ExtFloodFill".} proc FillRgn*(para1: HDC, para2: HRGN, para3: HBRUSH): WINBOOL{.stdcall, dynlib: "gdi32", importc: "FillRgn".} @@ -19938,7 +19938,7 @@ proc GetBitmapBits*(para1: HBITMAP, para2: LONG, para3: LPVOID): LONG{.stdcall, dynlib: "gdi32", importc: "GetBitmapBits".} proc GetBitmapDimensionEx*(para1: HBITMAP, para2: LPSIZE): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetBitmapDimensionEx".} -proc GetBoundsRect*(para1: HDC, para2: LPRECT, para3: UINT): UINT{.stdcall, +proc GetBoundsRect*(para1: HDC, para2: LPRECT, para3: WINUINT): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetBoundsRect".} proc GetBrushOrgEx*(para1: HDC, para2: LPPOINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetBrushOrgEx".} @@ -19948,14 +19948,14 @@ proc GetClipRgn*(para1: HDC, para2: HRGN): int32{.stdcall, dynlib: "gdi32", importc: "GetClipRgn".} proc GetMetaRgn*(para1: HDC, para2: HRGN): int32{.stdcall, dynlib: "gdi32", importc: "GetMetaRgn".} -proc GetCurrentObject*(para1: HDC, para2: UINT): HGDIOBJ{.stdcall, +proc GetCurrentObject*(para1: HDC, para2: WINUINT): HGDIOBJ{.stdcall, dynlib: "gdi32", importc: "GetCurrentObject".} proc GetCurrentPositionEx*(para1: HDC, para2: LPPOINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCurrentPositionEx".} proc GetDeviceCaps*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", importc: "GetDeviceCaps".} -proc GetDIBits*(para1: HDC, para2: HBITMAP, para3: UINT, para4: UINT, - para5: LPVOID, para6: LPBITMAPINFO, para7: UINT): int32{. +proc GetDIBits*(para1: HDC, para2: HBITMAP, para3: WINUINT, para4: WINUINT, + para5: LPVOID, para6: LPBITMAPINFO, para7: WINUINT): int32{. stdcall, dynlib: "gdi32", importc: "GetDIBits".} proc GetFontData*(para1: HDC, para2: DWORD, para3: DWORD, para4: LPVOID, para5: DWORD): DWORD{.stdcall, dynlib: "gdi32", @@ -19964,16 +19964,16 @@ proc GetGraphicsMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "GetGraphicsMode".} proc GetMapMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "GetMapMode".} -proc GetMetaFileBitsEx*(para1: HMETAFILE, para2: UINT, para3: LPVOID): UINT{. +proc GetMetaFileBitsEx*(para1: HMETAFILE, para2: WINUINT, para3: LPVOID): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetMetaFileBitsEx".} proc GetNearestColor*(para1: HDC, para2: COLORREF): COLORREF{.stdcall, dynlib: "gdi32", importc: "GetNearestColor".} -proc GetNearestPaletteIndex*(para1: HPALETTE, para2: COLORREF): UINT{.stdcall, +proc GetNearestPaletteIndex*(para1: HPALETTE, para2: COLORREF): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetNearestPaletteIndex".} proc GetObjectType*(h: HGDIOBJ): DWORD{.stdcall, dynlib: "gdi32", importc: "GetObjectType".} -proc GetPaletteEntries*(para1: HPALETTE, para2: UINT, para3: UINT, - para4: LPPALETTEENTRY): UINT{.stdcall, dynlib: "gdi32", +proc GetPaletteEntries*(para1: HPALETTE, para2: WINUINT, para3: WINUINT, + para4: LPPALETTEENTRY): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetPaletteEntries".} proc GetPixel*(para1: HDC, para2: int32, para3: int32): COLORREF{.stdcall, dynlib: "gdi32", importc: "GetPixel".} @@ -19981,7 +19981,7 @@ proc GetPixelFormat*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "GetPixelFormat".} proc GetPolyFillMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "GetPolyFillMode".} -proc GetRasterizerCaps*(para1: LPRASTERIZER_STATUS, para2: UINT): WINBOOL{. +proc GetRasterizerCaps*(para1: LPRASTERIZER_STATUS, para2: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetRasterizerCaps".} proc GetRegionData*(para1: HRGN, para2: DWORD, para3: LPRGNDATA): DWORD{. stdcall, dynlib: "gdi32", importc: "GetRegionData".} @@ -19991,14 +19991,14 @@ proc GetStockObject*(para1: int32): HGDIOBJ{.stdcall, dynlib: "gdi32", importc: "GetStockObject".} proc GetStretchBltMode*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "GetStretchBltMode".} -proc GetSystemPaletteEntries*(para1: HDC, para2: UINT, para3: UINT, - para4: LPPALETTEENTRY): UINT{.stdcall, +proc GetSystemPaletteEntries*(para1: HDC, para2: WINUINT, para3: WINUINT, + para4: LPPALETTEENTRY): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetSystemPaletteEntries".} -proc GetSystemPaletteUse*(para1: HDC): UINT{.stdcall, dynlib: "gdi32", +proc GetSystemPaletteUse*(para1: HDC): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetSystemPaletteUse".} proc GetTextCharacterExtra*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "GetTextCharacterExtra".} -proc GetTextAlign*(para1: HDC): UINT{.stdcall, dynlib: "gdi32", +proc GetTextAlign*(para1: HDC): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetTextAlign".} proc GetTextColor*(para1: HDC): COLORREF{.stdcall, dynlib: "gdi32", importc: "GetTextColor".} @@ -20064,12 +20064,12 @@ proc Rectangle*(para1: HDC, para2: int32, para3: int32, para4: int32, importc: "Rectangle".} proc RestoreDC*(para1: HDC, para2: int32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "RestoreDC".} -proc RealizePalette*(para1: HDC): UINT{.stdcall, dynlib: "gdi32", +proc RealizePalette*(para1: HDC): WINUINT{.stdcall, dynlib: "gdi32", importc: "RealizePalette".} proc RoundRect*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, para6: int32, para7: int32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "RoundRect".} -proc ResizePalette*(para1: HPALETTE, para2: UINT): WINBOOL{.stdcall, +proc ResizePalette*(para1: HPALETTE, para2: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "ResizePalette".} proc SaveDC*(para1: HDC): int32{.stdcall, dynlib: "gdi32", importc: "SaveDC".} proc SelectClipRgn*(para1: HDC, para2: HRGN): int32{.stdcall, dynlib: "gdi32", @@ -20088,15 +20088,15 @@ proc SetBkMode*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", importc: "SetBkMode".} proc SetBitmapBits*(para1: HBITMAP, para2: DWORD, para3: pointer): LONG{. stdcall, dynlib: "gdi32", importc: "SetBitmapBits".} -proc SetBoundsRect*(para1: HDC, para2: var RECT, para3: UINT): UINT{.stdcall, +proc SetBoundsRect*(para1: HDC, para2: var RECT, para3: WINUINT): WINUINT{.stdcall, dynlib: "gdi32", importc: "SetBoundsRect".} -proc SetDIBits*(para1: HDC, para2: HBITMAP, para3: UINT, para4: UINT, - para5: pointer, para6: PBITMAPINFO, para7: UINT): int32{. +proc SetDIBits*(para1: HDC, para2: HBITMAP, para3: WINUINT, para4: WINUINT, + para5: pointer, para6: PBITMAPINFO, para7: WINUINT): int32{. stdcall, dynlib: "gdi32", importc: "SetDIBits".} proc SetDIBitsToDevice*(para1: HDC, para2: int32, para3: int32, para4: DWORD, - para5: DWORD, para6: int32, para7: int32, para8: UINT, - para9: UINT, para10: pointer, para11: var BITMAPINFO, - para12: UINT): int32{.stdcall, dynlib: "gdi32", + para5: DWORD, para6: int32, para7: int32, para8: WINUINT, + para9: WINUINT, para10: pointer, para11: var BITMAPINFO, + para12: WINUINT): int32{.stdcall, dynlib: "gdi32", importc: "SetDIBitsToDevice".} proc SetMapperFlags*(para1: HDC, para2: DWORD): DWORD{.stdcall, dynlib: "gdi32", importc: "SetMapperFlags".} @@ -20104,10 +20104,10 @@ proc SetGraphicsMode*(hdc: HDC, iMode: int32): int32{.stdcall, dynlib: "gdi32", importc: "SetGraphicsMode".} proc SetMapMode*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", importc: "SetMapMode".} -proc SetMetaFileBitsEx*(para1: UINT, para2: var int8): HMETAFILE{.stdcall, +proc SetMetaFileBitsEx*(para1: WINUINT, para2: var int8): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetMetaFileBitsEx".} -proc SetPaletteEntries*(para1: HPALETTE, para2: UINT, para3: UINT, - para4: var PALETTEENTRY): UINT{.stdcall, +proc SetPaletteEntries*(para1: HPALETTE, para2: WINUINT, para3: WINUINT, + para4: var PALETTEENTRY): WINUINT{.stdcall, dynlib: "gdi32", importc: "SetPaletteEntries".} proc SetPixel*(para1: HDC, para2: int32, para3: int32, para4: COLORREF): COLORREF{. stdcall, dynlib: "gdi32", importc: "SetPixel".} @@ -20125,26 +20125,26 @@ proc SetRectRgn*(para1: HRGN, para2: int32, para3: int32, para4: int32, proc StretchDIBits*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: int32, para6: int32, para7: int32, para8: int32, para9: int32, para10: pointer, para11: var BITMAPINFO, - para12: UINT, para13: DWORD): int32{.stdcall, + para12: WINUINT, para13: DWORD): int32{.stdcall, dynlib: "gdi32", importc: "StretchDIBits".} proc SetROP2*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", importc: "SetROP2".} proc SetStretchBltMode*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", importc: "SetStretchBltMode".} -proc SetSystemPaletteUse*(para1: HDC, para2: UINT): UINT{.stdcall, +proc SetSystemPaletteUse*(para1: HDC, para2: WINUINT): WINUINT{.stdcall, dynlib: "gdi32", importc: "SetSystemPaletteUse".} proc SetTextCharacterExtra*(para1: HDC, para2: int32): int32{.stdcall, dynlib: "gdi32", importc: "SetTextCharacterExtra".} proc SetTextColor*(para1: HDC, para2: COLORREF): COLORREF{.stdcall, dynlib: "gdi32", importc: "SetTextColor".} -proc SetTextAlign*(para1: HDC, para2: UINT): UINT{.stdcall, dynlib: "gdi32", +proc SetTextAlign*(para1: HDC, para2: WINUINT): WINUINT{.stdcall, dynlib: "gdi32", importc: "SetTextAlign".} proc SetTextJustification*(para1: HDC, para2: int32, para3: int32): WINBOOL{. stdcall, dynlib: "gdi32", importc: "SetTextJustification".} proc UpdateColors*(para1: HDC): WINBOOL{.stdcall, dynlib: "gdi32", importc: "UpdateColors".} proc PlayMetaFileRecord*(para1: HDC, para2: LPHANDLETABLE, para3: LPMETARECORD, - para4: UINT): WINBOOL{.stdcall, dynlib: "gdi32", + para4: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "PlayMetaFileRecord".} proc EnumMetaFile*(para1: HDC, para2: HMETAFILE, para3: ENUMMETAFILEPROC, para4: LPARAM): WINBOOL{.stdcall, dynlib: "gdi32", @@ -20156,28 +20156,28 @@ proc DeleteEnhMetaFile*(para1: HENHMETAFILE): WINBOOL{.stdcall, dynlib: "gdi32", proc EnumEnhMetaFile*(para1: HDC, para2: HENHMETAFILE, para3: ENHMETAFILEPROC, para4: LPVOID, para5: var RECT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "EnumEnhMetaFile".} -proc GetEnhMetaFileHeader*(para1: HENHMETAFILE, para2: UINT, - para3: LPENHMETAHEADER): UINT{.stdcall, +proc GetEnhMetaFileHeader*(para1: HENHMETAFILE, para2: WINUINT, + para3: LPENHMETAHEADER): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileHeader".} -proc GetEnhMetaFilePaletteEntries*(para1: HENHMETAFILE, para2: UINT, - para3: LPPALETTEENTRY): UINT{.stdcall, +proc GetEnhMetaFilePaletteEntries*(para1: HENHMETAFILE, para2: WINUINT, + para3: LPPALETTEENTRY): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetEnhMetaFilePaletteEntries".} -proc GetEnhMetaFileBits*(para1: HENHMETAFILE, para2: UINT, para3: LPBYTE): UINT{. +proc GetEnhMetaFileBits*(para1: HENHMETAFILE, para2: WINUINT, para3: LPBYTE): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetEnhMetaFileBits".} -proc GetWinMetaFileBits*(para1: HENHMETAFILE, para2: UINT, para3: LPBYTE, - para4: wINT, para5: HDC): UINT{.stdcall, +proc GetWinMetaFileBits*(para1: HENHMETAFILE, para2: WINUINT, para3: LPBYTE, + para4: wINT, para5: HDC): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetWinMetaFileBits".} proc PlayEnhMetaFile*(para1: HDC, para2: HENHMETAFILE, para3: RECT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFile".} proc PlayEnhMetaFileRecord*(para1: HDC, para2: LPHANDLETABLE, - para3: var TENHMETARECORD, para4: UINT): WINBOOL{. + para3: var TENHMETARECORD, para4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFileRecord".} -proc SetEnhMetaFileBits*(para1: UINT, para2: var int8): HENHMETAFILE{.stdcall, +proc SetEnhMetaFileBits*(para1: WINUINT, para2: var int8): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetEnhMetaFileBits".} -proc SetWinMetaFileBits*(para1: UINT, para2: var int8, para3: HDC, +proc SetWinMetaFileBits*(para1: WINUINT, para2: var int8, para3: HDC, para4: var METAFILEPICT): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetWinMetaFileBits".} -proc GdiComment*(para1: HDC, para2: UINT, para3: var int8): WINBOOL{.stdcall, +proc GdiComment*(para1: HDC, para2: WINUINT, para3: var int8): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GdiComment".} proc AngleArc*(para1: HDC, para2: int32, para3: int32, para4: DWORD, para5: float32, para6: float32): WINBOOL{.stdcall, @@ -20192,12 +20192,12 @@ proc ModifyWorldTransform*(para1: HDC, para2: var XFORM, para3: DWORD): WINBOOL{ stdcall, dynlib: "gdi32", importc: "ModifyWorldTransform".} proc CombineTransform*(para1: LPXFORM, para2: var XFORM, para3: var XFORM): WINBOOL{. stdcall, dynlib: "gdi32", importc: "CombineTransform".} -proc CreateDIBSection*(para1: HDC, para2: var BITMAPINFO, para3: UINT, +proc CreateDIBSection*(para1: HDC, para2: var BITMAPINFO, para3: WINUINT, para4: var pointer, para5: HANDLE, para6: DWORD): HBITMAP{. stdcall, dynlib: "gdi32", importc: "CreateDIBSection".} -proc GetDIBColorTable*(para1: HDC, para2: UINT, para3: UINT, para4: var RGBQUAD): UINT{. +proc GetDIBColorTable*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: var RGBQUAD): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetDIBColorTable".} -proc SetDIBColorTable*(para1: HDC, para2: UINT, para3: UINT, para4: var RGBQUAD): UINT{. +proc SetDIBColorTable*(para1: HDC, para2: WINUINT, para3: WINUINT, para4: var RGBQUAD): WINUINT{. stdcall, dynlib: "gdi32", importc: "SetDIBColorTable".} proc SetColorAdjustment*(para1: HDC, para2: var COLORADJUSTMENT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "SetColorAdjustment".} @@ -20324,7 +20324,7 @@ proc DestroyPropertySheetPage*(hPSPage: HPROPSHEETPAGE): WINBOOL{.stdcall, proc InitCommonControls*(){.stdcall, dynlib: "comctl32", importc: "InitCommonControls".} proc ImageList_AddIcon*(himl: HIMAGELIST, hicon: HICON): int32 -proc ImageList_Create*(cx: int32, cy: int32, flags: UINT, cInitial: int32, +proc ImageList_Create*(cx: int32, cy: int32, flags: WINUINT, cInitial: int32, cGrow: int32): HIMAGELIST{.stdcall, dynlib: "comctl32", importc: "ImageList_Create".} proc ImageList_Destroy*(himl: HIMAGELIST): WINBOOL{.stdcall, dynlib: "comctl32", @@ -20342,7 +20342,7 @@ proc ImageList_GetBkColor*(himl: HIMAGELIST): COLORREF{.stdcall, proc ImageList_SetOverlayImage*(himl: HIMAGELIST, iImage: int32, iOverlay: int32): WINBOOL{. stdcall, dynlib: "comctl32", importc: "ImageList_SetOverlayImage".} proc ImageList_Draw*(himl: HIMAGELIST, i: int32, hdcDst: HDC, x: int32, - y: int32, fStyle: UINT): WINBOOL{.stdcall, + y: int32, fStyle: WINUINT): WINBOOL{.stdcall, dynlib: "comctl32", importc: "ImageList_Draw".} proc ImageList_Replace*(himl: HIMAGELIST, i: int32, hbmImage: HBITMAP, hbmMask: HBITMAP): WINBOOL{.stdcall, dynlib: "comctl32", @@ -20351,11 +20351,11 @@ proc ImageList_AddMasked*(himl: HIMAGELIST, hbmImage: HBITMAP, crMask: COLORREF) stdcall, dynlib: "comctl32", importc: "ImageList_AddMasked".} proc ImageList_DrawEx*(himl: HIMAGELIST, i: int32, hdcDst: HDC, x: int32, y: int32, dx: int32, dy: int32, rgbBk: COLORREF, - rgbFg: COLORREF, fStyle: UINT): WINBOOL{.stdcall, + rgbFg: COLORREF, fStyle: WINUINT): WINBOOL{.stdcall, dynlib: "comctl32", importc: "ImageList_DrawEx".} proc ImageList_Remove*(himl: HIMAGELIST, i: int32): WINBOOL{.stdcall, dynlib: "comctl32", importc: "ImageList_Remove".} -proc ImageList_GetIcon*(himl: HIMAGELIST, i: int32, flags: UINT): HICON{. +proc ImageList_GetIcon*(himl: HIMAGELIST, i: int32, flags: WINUINT): HICON{. stdcall, dynlib: "comctl32", importc: "ImageList_GetIcon".} proc ImageList_BeginDrag*(himlTrack: HIMAGELIST, iTrack: int32, dxHotspot: int32, dyHotspot: int32): WINBOOL{.stdcall, @@ -20385,20 +20385,20 @@ proc ImageList_GetImageInfo*(himl: HIMAGELIST, i: int32, proc ImageList_Merge*(himl1: HIMAGELIST, i1: int32, himl2: HIMAGELIST, i2: int32, dx: int32, dy: int32): HIMAGELIST{.stdcall, dynlib: "comctl32", importc: "ImageList_Merge".} -proc ImageList_SetImageCount*(himl: HIMAGELIST, uNewCount: UINT): int{.stdcall, +proc ImageList_SetImageCount*(himl: HIMAGELIST, uNewCount: WINUINT): int{.stdcall, dynlib: "comctl32.dll", importc: "ImageList_SetImageCount".} -proc CreateToolbarEx*(wnd: HWND, ws: DWORD, wID: UINT, nBitmaps: int32, - hBMInst: HINST, wBMID: UINT, lpButtons: LPCTBBUTTON, +proc CreateToolbarEx*(wnd: HWND, ws: DWORD, wID: WINUINT, nBitmaps: int32, + hBMInst: HINST, wBMID: WINUINT, lpButtons: LPCTBBUTTON, iNumButtons: int32, dxButton: int32, dyButton: int32, - dxBitmap: int32, dyBitmap: int32, uStructSize: UINT): HWND{. + dxBitmap: int32, dyBitmap: int32, uStructSize: WINUINT): HWND{. stdcall, dynlib: "comctl32", importc: "CreateToolbarEx".} -proc CreateMappedBitmap*(hInstance: HINST, idBitmap: int32, wFlags: UINT, +proc CreateMappedBitmap*(hInstance: HINST, idBitmap: int32, wFlags: WINUINT, lpColorMap: LPCOLORMAP, iNumMaps: int32): HBITMAP{. stdcall, dynlib: "comctl32", importc: "CreateMappedBitmap".} -proc MenuHelp*(uMsg: UINT, wp: WPARAM, lp: LPARAM, hMainMenu: HMENU, - hInst: HINST, hwndStatus: HWND, lpwIDs: var UINT){.stdcall, +proc MenuHelp*(uMsg: WINUINT, wp: WPARAM, lp: LPARAM, hMainMenu: HMENU, + hInst: HINST, hwndStatus: HWND, lpwIDs: var WINUINT){.stdcall, dynlib: "comctl32", importc: "MenuHelp".} -proc ShowHideMenuCtl*(wnd: HWND, uFlags: UINT, lpInfo: LPINT): WINBOOL{. +proc ShowHideMenuCtl*(wnd: HWND, uFlags: WINUINT, lpInfo: LPINT): WINBOOL{. stdcall, dynlib: "comctl32", importc: "ShowHideMenuCtl".} proc GetEffectiveClientRect*(wnd: HWND, lprc: LPRECT, lpInfo: LPINT){.stdcall, dynlib: "comctl32", importc: "GetEffectiveClientRect".} @@ -20428,21 +20428,21 @@ proc RegNotifyChangeKeyValue*(key: HKEY, bWatchSubtree: WINBOOL, dwNotifyFilter: DWORD, hEvent: HANDLE, fAsynchronus: WINBOOL): LONG{.stdcall, dynlib: "advapi32", importc: "RegNotifyChangeKeyValue".} -proc IsValidCodePage*(CodePage: UINT): WINBOOL{.stdcall, dynlib: "kernel32", +proc IsValidCodePage*(CodePage: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsValidCodePage".} -proc GetACP*(): UINT{.stdcall, dynlib: "kernel32", importc: "GetACP".} -proc GetOEMCP*(): UINT{.stdcall, dynlib: "kernel32", importc: "GetOEMCP".} -proc GetCPInfo*(para1: UINT, para2: LPCPINFO): WINBOOL{.stdcall, +proc GetACP*(): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetACP".} +proc GetOEMCP*(): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetOEMCP".} +proc GetCPInfo*(para1: WINUINT, para2: LPCPINFO): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetCPInfo".} proc IsDBCSLeadByte*(TestChar: int8): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsDBCSLeadByte".} -proc IsDBCSLeadByteEx*(CodePage: UINT, TestChar: int8): WINBOOL{.stdcall, +proc IsDBCSLeadByteEx*(CodePage: WINUINT, TestChar: int8): WINBOOL{.stdcall, dynlib: "kernel32", importc: "IsDBCSLeadByteEx".} -proc MultiByteToWideChar*(CodePage: UINT, dwFlags: DWORD, +proc MultiByteToWideChar*(CodePage: WINUINT, dwFlags: DWORD, lpMultiByteStr: LPCSTR, cchMultiByte: int32, lpWideCharStr: LPWSTR, cchWideChar: int32): int32{. stdcall, dynlib: "kernel32", importc: "MultiByteToWideChar".} -proc WideCharToMultiByte*(CodePage: UINT, dwFlags: DWORD, +proc WideCharToMultiByte*(CodePage: WINUINT, dwFlags: DWORD, lpWideCharStr: LPCWSTR, cchWideChar: int32, lpMultiByteStr: LPSTR, cchMultiByte: int32, lpDefaultChar: LPCSTR, lpUsedDefaultChar: LPBOOL): int32{. @@ -20520,12 +20520,12 @@ proc CreateConsoleScreenBuffer*(dwDesiredAccess: DWORD, dwShareMode: DWORD, lpSecurityAttributes: var SECURITY_ATTRIBUTES, dwFlags: DWORD, lpScreenBufferData: LPVOID): HANDLE{. stdcall, dynlib: "kernel32", importc: "CreateConsoleScreenBuffer".} -proc GetConsoleCP*(): UINT{.stdcall, dynlib: "kernel32", importc: "GetConsoleCP".} -proc SetConsoleCP*(wCodePageID: UINT): WINBOOL{.stdcall, dynlib: "kernel32", +proc GetConsoleCP*(): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetConsoleCP".} +proc SetConsoleCP*(wCodePageID: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetConsoleCP".} -proc GetConsoleOutputCP*(): UINT{.stdcall, dynlib: "kernel32", +proc GetConsoleOutputCP*(): WINUINT{.stdcall, dynlib: "kernel32", importc: "GetConsoleOutputCP".} -proc SetConsoleOutputCP*(wCodePageID: UINT): WINBOOL{.stdcall, +proc SetConsoleOutputCP*(wCodePageID: WINUINT): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetConsoleOutputCP".} proc WNetConnectionDialog*(wnd: HWND, dwType: DWORD): DWORD{.stdcall, dynlib: "mpr", importc: "WNetConnectionDialog".} @@ -20562,7 +20562,7 @@ proc UnlockServiceDatabase*(ScLock: SC_LOCK): WINBOOL{.stdcall, dynlib: "advapi32", importc: "UnlockServiceDatabase".} proc ChoosePixelFormat*(para1: HDC, para2: PPIXELFORMATDESCRIPTOR): int32{. stdcall, dynlib: "gdi32", importc: "ChoosePixelFormat".} -proc DescribePixelFormat*(para1: HDC, para2: int32, para3: UINT, +proc DescribePixelFormat*(para1: HDC, para2: int32, para3: WINUINT, para4: LPPIXELFORMATDESCRIPTOR): int32{.stdcall, dynlib: "gdi32", importc: "DescribePixelFormat".} proc SetPixelFormat*(para1: HDC, para2: int32, para3: PPIXELFORMATDESCRIPTOR): WINBOOL{. @@ -20584,7 +20584,7 @@ proc DdeAccessData*(para1: HDDEDATA, para2: PDWORD): PBYTE{.stdcall, proc DdeAddData*(para1: HDDEDATA, para2: PBYTE, para3: DWORD, para4: DWORD): HDDEDATA{. stdcall, dynlib: "user32", importc: "DdeAddData".} proc DdeClientTransaction*(para1: PBYTE, para2: DWORD, para3: HCONV, para4: HSZ, - para5: UINT, para6: UINT, para7: DWORD, para8: PDWORD): HDDEDATA{. + para5: WINUINT, para6: WINUINT, para7: DWORD, para8: PDWORD): HDDEDATA{. stdcall, dynlib: "user32", importc: "DdeClientTransaction".} proc DdeCmpStringHandles*(para1: HSZ, para2: HSZ): int32{.stdcall, dynlib: "user32", importc: "DdeCmpStringHandles".} @@ -20594,13 +20594,13 @@ proc DdeConnectList*(para1: DWORD, para2: HSZ, para3: HSZ, para4: HCONVLIST, para5: PCONVCONTEXT): HCONVLIST{.stdcall, dynlib: "user32", importc: "DdeConnectList".} proc DdeCreateDataHandle*(para1: DWORD, para2: LPBYTE, para3: DWORD, - para4: DWORD, para5: HSZ, para6: UINT, para7: UINT): HDDEDATA{. + para4: DWORD, para5: HSZ, para6: WINUINT, para7: WINUINT): HDDEDATA{. stdcall, dynlib: "user32", importc: "DdeCreateDataHandle".} proc DdeDisconnect*(para1: HCONV): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeDisconnect".} proc DdeDisconnectList*(para1: HCONVLIST): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeDisconnectList".} -proc DdeEnableCallback*(para1: DWORD, para2: HCONV, para3: UINT): WINBOOL{. +proc DdeEnableCallback*(para1: DWORD, para2: HCONV, para3: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DdeEnableCallback".} proc DdeFreeDataHandle*(para1: HDDEDATA): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeFreeDataHandle".} @@ -20608,17 +20608,17 @@ proc DdeFreeStringHandle*(para1: DWORD, para2: HSZ): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeFreeStringHandle".} proc DdeGetData*(para1: HDDEDATA, para2: LPBYTE, para3: DWORD, para4: DWORD): DWORD{. stdcall, dynlib: "user32", importc: "DdeGetData".} -proc DdeGetLastError*(para1: DWORD): UINT{.stdcall, dynlib: "user32", +proc DdeGetLastError*(para1: DWORD): WINUINT{.stdcall, dynlib: "user32", importc: "DdeGetLastError".} proc DdeImpersonateClient*(para1: HCONV): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeImpersonateClient".} proc DdeKeepStringHandle*(para1: DWORD, para2: HSZ): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeKeepStringHandle".} -proc DdeNameService*(para1: DWORD, para2: HSZ, para3: HSZ, para4: UINT): HDDEDATA{. +proc DdeNameService*(para1: DWORD, para2: HSZ, para3: HSZ, para4: WINUINT): HDDEDATA{. stdcall, dynlib: "user32", importc: "DdeNameService".} proc DdePostAdvise*(para1: DWORD, para2: HSZ, para3: HSZ): WINBOOL{.stdcall, dynlib: "user32", importc: "DdePostAdvise".} -proc DdeQueryConvInfo*(para1: HCONV, para2: DWORD, para3: PCONVINFO): UINT{. +proc DdeQueryConvInfo*(para1: HCONV, para2: DWORD, para3: PCONVINFO): WINUINT{. stdcall, dynlib: "user32", importc: "DdeQueryConvInfo".} proc DdeQueryNextServer*(para1: HCONVLIST, para2: HCONV): HCONV{.stdcall, dynlib: "user32", importc: "DdeQueryNextServer".} @@ -20630,18 +20630,18 @@ proc DdeUnaccessData*(para1: HDDEDATA): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeUnaccessData".} proc DdeUninitialize*(para1: DWORD): WINBOOL{.stdcall, dynlib: "user32", importc: "DdeUninitialize".} -proc SHAddToRecentDocs*(para1: UINT, para2: LPCVOID){.stdcall, +proc SHAddToRecentDocs*(para1: WINUINT, para2: LPCVOID){.stdcall, dynlib: "shell32", importc: "SHAddToRecentDocs".} proc SHBrowseForFolder*(para1: LPBROWSEINFO): LPITEMIDLIST{.stdcall, dynlib: "shell32", importc: "SHBrowseForFolder".} -proc SHChangeNotify*(para1: LONG, para2: UINT, para3: LPCVOID, para4: LPCVOID){. +proc SHChangeNotify*(para1: LONG, para2: WINUINT, para3: LPCVOID, para4: LPCVOID){. stdcall, dynlib: "shell32", importc: "SHChangeNotify".} proc SHFileOperation*(para1: LPSHFILEOPSTRUCT): int32{.stdcall, dynlib: "shell32", importc: "SHFileOperation".} proc SHFreeNameMappings*(para1: HANDLE){.stdcall, dynlib: "shell32", importc: "SHFreeNameMappings".} proc SHGetFileInfo*(para1: LPCTSTR, para2: DWORD, para3: var SHFILEINFO, - para4: UINT, para5: UINT): DWORD{.stdcall, + para4: WINUINT, para5: WINUINT): DWORD{.stdcall, dynlib: "shell32", importc: "SHGetFileInfo".} proc SHGetPathFromIDList*(para1: LPCITEMIDLIST, para2: LPTSTR): WINBOOL{. stdcall, dynlib: "shell32", importc: "SHGetPathFromIDList".} @@ -20657,7 +20657,7 @@ proc wglCreateContext*(para1: HDC): HGLRC{.stdcall, dynlib: "opengl32", importc: "wglCreateContext".} proc wglCreateLayerContext*(para1: HDC, para2: int32): HGLRC{.stdcall, dynlib: "opengl32", importc: "wglCreateLayerContext".} -proc wglCopyContext*(para1: HGLRC, para2: HGLRC, para3: UINT): WINBOOL{.stdcall, +proc wglCopyContext*(para1: HGLRC, para2: HGLRC, para3: WINUINT): WINBOOL{.stdcall, dynlib: "opengl32", importc: "wglCopyContext".} proc wglDeleteContext*(para1: HGLRC): WINBOOL{.stdcall, dynlib: "opengl32", importc: "wglDeleteContext".} @@ -20681,7 +20681,7 @@ proc wglUseFontOutlinesA*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD, para5: float32, para6: float32, para7: int32, para8: LPGLYPHMETRICSFLOAT): WINBOOL{.stdcall, dynlib: "opengl32", importc: "wglUseFontOutlinesA".} -proc wglDescribeLayerPlane*(para1: HDC, para2: int32, para3: int32, para4: UINT, +proc wglDescribeLayerPlane*(para1: HDC, para2: int32, para3: int32, para4: WINUINT, para5: LPLAYERPLANEDESCRIPTOR): WINBOOL{.stdcall, dynlib: "opengl32", importc: "wglDescribeLayerPlane".} proc wglGetLayerPaletteEntries*(para1: HDC, para2: int32, para3: int32, @@ -20694,7 +20694,7 @@ proc wglRealizeLayerPalette*(para1: HDC, para2: int32, para3: WINBOOL): WINBOOL{ proc wglSetLayerPaletteEntries*(para1: HDC, para2: int32, para3: int32, para4: int32, para5: var COLORREF): int32{. stdcall, dynlib: "opengl32", importc: "wglSetLayerPaletteEntries".} -proc wglSwapLayerBuffers*(para1: HDC, para2: UINT): WINBOOL{.stdcall, +proc wglSwapLayerBuffers*(para1: HDC, para2: WINUINT): WINBOOL{.stdcall, dynlib: "opengl32", importc: "wglSwapLayerBuffers".} proc wglUseFontOutlinesW*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD, para5: float32, para6: float32, para7: int32, @@ -20703,7 +20703,7 @@ proc wglUseFontOutlinesW*(para1: HDC, para2: DWORD, para3: DWORD, para4: DWORD, # translated macros proc Animate_Create*(hWndP: HWND, id: HMENU, dwStyle: DWORD, hInstance: HINST): HWND proc Animate_Open*(wnd: HWND, szName: LPTSTR): LRESULT -proc Animate_Play*(wnd: HWND, `from`, `to`: int32, rep: UINT): LRESULT +proc Animate_Play*(wnd: HWND, `from`, `to`: int32, rep: WINUINT): LRESULT proc Animate_Stop*(wnd: HWND): LRESULT proc Animate_Close*(wnd: HWND): LRESULT @@ -20734,7 +20734,7 @@ proc Header_GetItemCount*(hwndHD: HWND): int32 proc Header_InsertItem*(hwndHD: HWND, index: int32, hdi: var HD_ITEM): int32 proc Header_Layout*(hwndHD: HWND, layout: var HD_LAYOUT): WINBOOL proc Header_SetItem*(hwndHD: HWND, index: int32, hdi: var HD_ITEM): WINBOOL -proc ListView_Arrange*(hwndLV: HWND, code: UINT): LRESULT +proc ListView_Arrange*(hwndLV: HWND, code: WINUINT): LRESULT proc ListView_CreateDragImage*(wnd: HWND, i: int32, lpptUpLeft: LPPOINT): LRESULT proc ListView_DeleteAllItems*(wnd: HWND): LRESULT proc ListView_DeleteColumn*(wnd: HWND, iCol: int32): LRESULT @@ -20769,7 +20769,7 @@ proc ListView_InsertItem*(wnd: HWND, item: var LV_ITEM): LRESULT proc ListView_RedrawItems*(hwndLV: HWND, iFirst, iLast: int32): LRESULT proc ListView_Scroll*(hwndLV: HWND, dx, dy: int32): LRESULT proc ListView_SetBkColor*(wnd: HWND, clrBk: COLORREF): LRESULT -proc ListView_SetCallbackMask*(wnd: HWND, mask: UINT): LRESULT +proc ListView_SetCallbackMask*(wnd: HWND, mask: WINUINT): LRESULT proc ListView_SetColumn*(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT proc ListView_SetColumnWidth*(wnd: HWND, iCol, cx: int32): LRESULT proc ListView_SetImageList*(wnd: HWND, himl: int32, iImageList: HIMAGELIST): LRESULT @@ -20842,7 +20842,7 @@ proc TabCtrl_GetToolTips*(wnd: HWND): LRESULT proc TabCtrl_SetToolTips*(wnd: HWND, hwndTT: int32): LRESULT proc TabCtrl_GetCurFocus*(wnd: HWND): LRESULT proc TabCtrl_SetCurFocus*(wnd: HWND, i: int32): LRESULT -proc SNDMSG*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT +proc SNDMSG*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT proc CommDlg_OpenSave_GetSpecA*(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT proc CommDlg_OpenSave_GetSpecW*(hdlg: HWND, psz: LPWSTR, cbmax: int32): LRESULT when defined(winUnicode): @@ -20865,7 +20865,7 @@ proc CommDlg_OpenSave_GetFolderIDList*(hdlg: HWND, pidl: LPVOID, cbmax: int32): proc CommDlg_OpenSave_SetControlText*(hdlg: HWND, id: int32, text: LPSTR): LRESULT proc CommDlg_OpenSave_HideControl*(hdlg: HWND, id: int32): LRESULT proc CommDlg_OpenSave_SetDefExt*(hdlg: HWND, pszext: LPSTR): LRESULT -proc GetNextWindow*(wnd: HWND, uCmd: UINT): HWND{.stdcall, dynlib: "user32", +proc GetNextWindow*(wnd: HWND, uCmd: WINUINT): HWND{.stdcall, dynlib: "user32", importc: "GetWindow".} proc GlobalAllocPtr*(flags, cb: DWord): Pointer proc GlobalFreePtr*(lp: Pointer): Pointer @@ -21183,9 +21183,9 @@ proc CreateDialogIndirectParam*(hInstance: HINST, lpTemplate: TDlgTemplate, dynlib: "user32", importc: "CreateDialogIndirectParamA".} #function CreateDialogIndirectParamA(hInstance: HINST; const lpTemplate: TDlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamA'; #function CreateDialogIndirectParamW(hInstance: HINST; const lpTemplate: TDlgTemplate; hWndParent: HWND; lpDialogFunc: TFNDlgProc; dwInitParam: LPARAM): HWND; stdcall; external 'user32' name 'CreateDialogIndirectParamW'; - #function CreateDIBitmap(DC: HDC; var InfoHeader: TBitmapInfoHeader; dwUsage: DWORD; InitBits: PChar; var InitInfo: TBitmapInfo; wUsage: UINT): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBitmap'; - #function CreateDIBPatternBrushPt(const p1: Pointer; p2: UINT): HBRUSH; stdcall; external 'gdi32' name 'CreateDIBPatternBrushPt'; - #function CreateDIBSection(DC: HDC; const p2: TBitmapInfo; p3: UINT; var p4: Pointer; p5: THandle; p6: DWORD): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBSection'; + #function CreateDIBitmap(DC: HDC; var InfoHeader: TBitmapInfoHeader; dwUsage: DWORD; InitBits: PChar; var InitInfo: TBitmapInfo; wUsage: WINUINT): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBitmap'; + #function CreateDIBPatternBrushPt(const p1: Pointer; p2: WINUINT): HBRUSH; stdcall; external 'gdi32' name 'CreateDIBPatternBrushPt'; + #function CreateDIBSection(DC: HDC; const p2: TBitmapInfo; p3: WINUINT; var p4: Pointer; p5: THandle; p6: DWORD): HBITMAP; stdcall; external 'gdi32' name 'CreateDIBSection'; #function CreateEllipticRgnIndirect(const p1: TRect): HRGN; stdcall; external 'gdi32' name 'CreateEllipticRgnIndirect'; #function CreateFontIndirect(const p1: TLogFont): HFONT;stdcall; external 'gdi32' name 'CreateFontIndirectA'; #function CreateFontIndirectA(const p1: TLogFontA): HFONT; stdcall; external 'gdi32' name 'CreateFontIndirectA'; @@ -21251,7 +21251,7 @@ proc DdeSetQualityOfService*(hWndClient: HWnd, pqosPrev: PSecurityQualityOfService): WINBOOL{. stdcall, dynlib: "user32", importc: "DdeSetQualityOfService".} #function DeleteAce(var pAcl: TACL; dwAceIndex: DWORD): WINBOOL; stdcall; external 'advapi32' name 'DeleteAce'; -proc DescribePixelFormat*(DC: HDC, p2: int, p3: UINT, +proc DescribePixelFormat*(DC: HDC, p2: int, p3: WINUINT, p4: var TPixelFormatDescriptor): WINBOOL{.stdcall, dynlib: "gdi32", importc: "DescribePixelFormat".} #function DestroyPrivateObjectSecurity(var ObjectDescriptor: PSecurityDescriptor): WINBOOL; stdcall; external 'advapi32' name 'DestroyPrivateObjectSecurity'; @@ -21283,29 +21283,29 @@ proc DosDateTimeToFileTime*(wFatDate, wFatTime: int16, lpFileTime: var TFileTime proc DPtoLP*(DC: HDC, Points: pointer, Count: int): WINBOOL{.stdcall, dynlib: "gdi32", importc: "DPtoLP".} # function DrawAnimatedRects(wnd: HWND; idAni: Integer; const lprcFrom, lprcTo: TRect): WINBOOL; stdcall; external 'user32' name 'DrawAnimatedRects'; - #function DrawCaption(p1: HWND; p2: HDC; const p3: TRect; p4: UINT): WINBOOL; stdcall; external 'user32' name 'DrawCaption'; -proc DrawEdge*(hdc: HDC, qrc: var TRect, edge: UINT, grfFlags: UINT): WINBOOL{. + #function DrawCaption(p1: HWND; p2: HDC; const p3: TRect; p4: WINUINT): WINBOOL; stdcall; external 'user32' name 'DrawCaption'; +proc DrawEdge*(hdc: HDC, qrc: var TRect, edge: WINUINT, grfFlags: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DrawEdge".} #function DrawFocusRect(hDC: HDC; const lprc: TRect): WINBOOL; stdcall; external 'user32' name 'DrawFocusRect'; -proc DrawFrameControl*(DC: HDC, Rect: TRect, uType, uState: UINT): WINBOOL{. +proc DrawFrameControl*(DC: HDC, Rect: TRect, uType, uState: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "DrawFrameControl".} proc DrawText*(hDC: HDC, lpString: cstring, nCount: int, lpRect: var TRect, - uFormat: UINT): int{.stdcall, dynlib: "user32", + uFormat: WINUINT): int{.stdcall, dynlib: "user32", importc: "DrawTextA".} proc DrawTextA*(hDC: HDC, lpString: LPCSTR, nCount: int, lpRect: var TRect, - uFormat: UINT): int{.stdcall, dynlib: "user32", + uFormat: WINUINT): int{.stdcall, dynlib: "user32", importc: "DrawTextA".} proc DrawTextEx*(DC: HDC, lpchText: cstring, cchText: int, p4: var TRect, - dwDTFormat: UINT, DTParams: PDrawTextParams): int{.stdcall, + dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, dynlib: "user32", importc: "DrawTextExA".} proc DrawTextExA*(DC: HDC, lpchText: LPCSTR, cchText: int, p4: var TRect, - dwDTFormat: UINT, DTParams: PDrawTextParams): int{.stdcall, + dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, dynlib: "user32", importc: "DrawTextExA".} proc DrawTextExW*(DC: HDC, lpchText: LPWSTR, cchText: int, p4: var TRect, - dwDTFormat: UINT, DTParams: PDrawTextParams): int{.stdcall, + dwDTFormat: WINUINT, DTParams: PDrawTextParams): int{.stdcall, dynlib: "user32", importc: "DrawTextExW".} proc DrawTextW*(hDC: HDC, lpString: LPWSTR, nCount: int, lpRect: var TRect, - uFormat: UINT): int{.stdcall, dynlib: "user32", + uFormat: WINUINT): int{.stdcall, dynlib: "user32", importc: "DrawTextW".} #function DuplicateTokenEx(hExistingToken: THandle; dwDesiredAccess: DWORD; lpTokenAttributes: PSecurityAttributes; ImpersonationLevel: TSecurityImpersonationLevel; TokenType: TTokenType; var phNewToken: THandle): WINBOOL; # stdcall; external 'advapi32' name 'DuplicateTokenEx'; @@ -21377,9 +21377,9 @@ proc FindNextFileW*(hFindFile: THandle, lpFindFileData: var TWIN32FindDataW): WI #function FrameRect(hDC: HDC; const lprc: TRect; hbr: HBRUSH): Integer; stdcall; external 'user32' name 'FrameRect'; #function GetAce(const pAcl: TACL; dwAceIndex: DWORD; var pAce: Pointer): WINBOOL; stdcall; external 'advapi32' name 'GetAce'; #function GetAclInformation(const pAcl: TACL; pAclInformation: Pointer; nAclInformationLength: DWORD; dwAclInformationClass: TAclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'GetAclInformation'; - #function GetAltTabInfo(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: PChar; cchItemText: UINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; - #function GetAltTabInfoA(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPCSTR; cchItemText: UINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; - #function GetAltTabInfoW(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPWSTR; cchItemText: UINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoW'; + #function GetAltTabInfo(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: PChar; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; + #function GetAltTabInfoA(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPCSTR; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoA'; + #function GetAltTabInfoW(wnd: HWND; iItem: Integer; var pati: TAltTabInfo; pszItemText: LPWSTR; cchItemText: WINUINT): WINBOOL;stdcall; external 'user32' name 'GetAltTabInfoW'; proc GetAspectRatioFilterEx*(DC: HDC, p2: var TSize): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetAspectRatioFilterEx".} proc GetBinaryType*(lpApplicationName: cstring, lpBinaryType: var DWORD): WINBOOL{. @@ -21390,24 +21390,24 @@ proc GetBinaryTypeW*(lpApplicationName: LPWSTR, lpBinaryType: var DWORD): WINBOO stdcall, dynlib: "kernel32", importc: "GetBinaryTypeW".} proc GetBitmapDimensionEx*(p1: HBITMAP, p2: var TSize): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetBitmapDimensionEx".} -proc GetBoundsRect*(DC: HDC, p2: var TRect, p3: UINT): UINT{.stdcall, +proc GetBoundsRect*(DC: HDC, p2: var TRect, p3: WINUINT): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetBoundsRect".} proc GetBrushOrgEx*(DC: HDC, p2: var TPoint): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetBrushOrgEx".} proc GetCaretPos*(lpPoint: var TPoint): WINBOOL{.stdcall, dynlib: "user32", importc: "GetCaretPos".} -proc GetCharABCWidths*(DC: HDC, p2, p3: UINT, ABCStructs: pointer): WINBOOL{. +proc GetCharABCWidths*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} -proc GetCharABCWidthsA*(DC: HDC, p2, p3: UINT, ABCStructs: pointer): WINBOOL{. +proc GetCharABCWidthsA*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsA".} -proc GetCharABCWidthsFloat*(DC: HDC, p2, p3: UINT, ABCFloatSturcts: pointer): WINBOOL{. +proc GetCharABCWidthsFloat*(DC: HDC, p2, p3: WINUINT, ABCFloatSturcts: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} -proc GetCharABCWidthsFloatA*(DC: HDC, p2, p3: UINT, ABCFloatSturcts: pointer): WINBOOL{. +proc GetCharABCWidthsFloatA*(DC: HDC, p2, p3: WINUINT, ABCFloatSturcts: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatA".} -proc GetCharABCWidthsFloatW*(DC: HDC, p2, p3: UINT, ABCFloatSturcts: pointer): WINBOOL{. +proc GetCharABCWidthsFloatW*(DC: HDC, p2, p3: WINUINT, ABCFloatSturcts: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsFloatW".} - #function GetCharABCWidthsI(DC: HDC; p2, p3: UINT; p4: PWORD; const Widths): WINBOOL;stdcall; external 'gdi32' name 'GetCharABCWidthsI'; -proc GetCharABCWidthsW*(DC: HDC, p2, p3: UINT, ABCStructs: pointer): WINBOOL{. + #function GetCharABCWidthsI(DC: HDC; p2, p3: WINUINT; p4: PWORD; const Widths): WINBOOL;stdcall; external 'gdi32' name 'GetCharABCWidthsI'; +proc GetCharABCWidthsW*(DC: HDC, p2, p3: WINUINT, ABCStructs: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharABCWidthsW".} proc GetCharacterPlacement*(DC: HDC, p2: cstring, p3, p4: WINBOOL, p5: var TGCPResults, p6: DWORD): DWORD{.stdcall, @@ -21418,24 +21418,24 @@ proc GetCharacterPlacementA*(DC: HDC, p2: LPCSTR, p3, p4: WINBOOL, proc GetCharacterPlacementW*(DC: HDC, p2: LPWSTR, p3, p4: WINBOOL, p5: var TGCPResults, p6: DWORD): DWORD{.stdcall, dynlib: "gdi32", importc: "GetCharacterPlacementW".} -proc GetCharWidth*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{.stdcall, +proc GetCharWidth*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidthA".} -proc GetCharWidth32*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{.stdcall, +proc GetCharWidth32*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidth32A".} -proc GetCharWidth32A*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{.stdcall, +proc GetCharWidth32A*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidth32A".} -proc GetCharWidth32W*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{.stdcall, +proc GetCharWidth32W*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidth32W".} -proc GetCharWidthA*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{.stdcall, +proc GetCharWidthA*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidthA".} -proc GetCharWidthFloat*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{. +proc GetCharWidthFloat*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} -proc GetCharWidthFloatA*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{. +proc GetCharWidthFloatA*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatA".} -proc GetCharWidthFloatW*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{. +proc GetCharWidthFloatW*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "GetCharWidthFloatW".} - #function GetCharWidthI(DC: HDC; p2, p3: UINT; p4: PWORD; const Widths:pointer): WINBOOL;stdcall; external 'gdi32' name 'GetCharWidthI'; -proc GetCharWidthW*(DC: HDC, p2, p3: UINT, Widths: pointer): WINBOOL{.stdcall, + #function GetCharWidthI(DC: HDC; p2, p3: WINUINT; p4: PWORD; const Widths:pointer): WINBOOL;stdcall; external 'gdi32' name 'GetCharWidthI'; +proc GetCharWidthW*(DC: HDC, p2, p3: WINUINT, Widths: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetCharWidthW".} proc GetClassInfo*(hInstance: HINST, lpClassName: cstring, lpWndClass: var TWndClass): WINBOOL{.stdcall, @@ -21484,7 +21484,7 @@ proc GetConsoleMode*(hConsoleHandle: THandle, lpMode: var DWORD): WINBOOL{. proc GetConsoleScreenBufferInfo*(hConsoleOutput: THandle, lpConsoleScreenBufferInfo: var TConsoleScreenBufferInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetConsoleScreenBufferInfo".} -proc GetCPInfo*(CodePage: UINT, lpCPInfo: var TCPInfo): WINBOOL{.stdcall, +proc GetCPInfo*(CodePage: WINUINT, lpCPInfo: var TCPInfo): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetCPInfo".} #function GetCurrentHwProfile(var lpHwProfileInfo: THWProfileInfo): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileA'; #function GetCurrentHwProfileA(var lpHwProfileInfo: THWProfileInfoA): WINBOOL;stdcall; external 'advapi32' name 'GetCurrentHwProfileA'; @@ -21504,10 +21504,10 @@ proc GetDefaultCommConfigA*(lpszName: LPCSTR, lpCC: var TCommConfig, proc GetDefaultCommConfigW*(lpszName: LPWSTR, lpCC: var TCommConfig, lpdwSize: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetDefaultCommConfigW".} -proc GetDIBColorTable*(DC: HDC, p2, p3: UINT, RGBQuadStructs: pointer): UINT{. +proc GetDIBColorTable*(DC: HDC, p2, p3: WINUINT, RGBQuadStructs: pointer): WINUINT{. stdcall, dynlib: "gdi32", importc: "GetDIBColorTable".} -proc GetDIBits*(DC: HDC, Bitmap: HBitmap, StartScan, NumScans: UINT, - Bits: Pointer, BitInfo: var TBitmapInfo, Usage: UINT): int{. +proc GetDIBits*(DC: HDC, Bitmap: HBitmap, StartScan, NumScans: WINUINT, + Bits: Pointer, BitInfo: var TBitmapInfo, Usage: WINUINT): int{. stdcall, dynlib: "gdi32", importc: "GetDIBits".} proc GetDiskFreeSpace*(lpRootPathName: cstring, lpSectorsPerCluster, lpBytesPerSector, lpNumberOfFreeClusters, lpTotalNumberOfClusters: var DWORD): WINBOOL{. @@ -21539,7 +21539,7 @@ proc GetDiskFreeSpaceExA*(lpDirectoryName: LPCSTR, lpFreeBytesAvailableToCaller, proc GetDiskFreeSpaceExW*(lpDirectoryName: LPWSTR, lpFreeBytesAvailableToCaller, lpTotalNumberOfBytes: pLargeInteger, lpTotalNumberOfFreeBytes: PLargeInteger): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetDiskFreeSpaceExW".} - #function GetEnhMetaFilePixelFormat(p1: HENHMETAFILE; p2: Cardinal; var p3: TPixelFormatDescriptor): UINT;stdcall; external 'gdi32' name 'GetEnhMetaFilePixelFormat'; + #function GetEnhMetaFilePixelFormat(p1: HENHMETAFILE; p2: Cardinal; var p3: TPixelFormatDescriptor): WINUINT;stdcall; external 'gdi32' name 'GetEnhMetaFilePixelFormat'; proc GetExitCodeProcess*(hProcess: THandle, lpExitCode: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetExitCodeProcess".} proc GetExitCodeThread*(hThread: THandle, lpExitCode: var DWORD): WINBOOL{. @@ -21559,13 +21559,13 @@ proc GetFileVersionInfoSizeW*(lptstrFilename: LPWSTR, lpdwHandle: var DWORD): DW # function GetFullPathName(lpFileName: PChar; nBufferLength: DWORD; lpBuffer: PChar; var lpFilePart: PChar): DWORD;stdcall; external 'kernel32' name 'GetFullPathNameA'; # function GetFullPathNameA(lpFileName: LPCSTR; nBufferLength: DWORD; lpBuffer: LPCSTR; var lpFilePart: LPCSTR): DWORD; stdcall; external 'kernel32' name 'GetFullPathNameA'; # function GetFullPathNameW(lpFileName: LPWSTR; nBufferLength: DWORD; lpBuffer: LPWSTR; var lpFilePart: LPWSTR): DWORD; stdcall; external 'kernel32' name 'GetFullPathNameW'; -proc GetGlyphOutline*(DC: HDC, p2, p3: UINT, p4: TGlyphMetrics, p5: DWORD, +proc GetGlyphOutline*(DC: HDC, p2, p3: WINUINT, p4: TGlyphMetrics, p5: DWORD, p6: Pointer, p7: TMat2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineA".} -proc GetGlyphOutlineA*(DC: HDC, p2, p3: UINT, p4: TGlyphMetrics, p5: DWORD, +proc GetGlyphOutlineA*(DC: HDC, p2, p3: WINUINT, p4: TGlyphMetrics, p5: DWORD, p6: Pointer, p7: TMat2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineA".} -proc GetGlyphOutlineW*(DC: HDC, p2, p3: UINT, p4: TGlyphMetrics, p5: DWORD, +proc GetGlyphOutlineW*(DC: HDC, p2, p3: WINUINT, p4: TGlyphMetrics, p5: DWORD, p6: Pointer, p7: TMat2): DWORD{.stdcall, dynlib: "gdi32", importc: "GetGlyphOutlineW".} #function GetGUIThreadInfo(idThread: DWORD; var pgui: TGUIThreadinfo): WINBOOL;stdcall; external 'user32' name 'GetGUIThreadInfo'; @@ -21579,7 +21579,7 @@ proc GetIconInfo*(icon: HICON, piconinfo: var TIconInfo): WINBOOL{.stdcall, #function GetKernelObjectSecurity(Handle: THandle; RequestedInformation: SECURITY_INFORMATION; pSecurityDescriptor: PSecurityDescriptor; nLength: DWORD; var lpnLengthNeeded: DWORD): WINBOOL; stdcall; external 'advapi32' name 'GetKernelObjectSecurity'; proc GetKerningPairs*(DC: HDC, Count: DWORD, KerningPairs: pointer): DWORD{. stdcall, dynlib: "gdi32", importc: "GetKerningPairs".} -proc GetKeyboardLayoutList*(nBuff: int, List: pointer): UINT{.stdcall, +proc GetKeyboardLayoutList*(nBuff: int, List: pointer): WINUINT{.stdcall, dynlib: "user32", importc: "GetKeyboardLayoutList".} #function GetKeyboardState(var KeyState: TKeyboardState): WINBOOL; stdcall; external 'user32' name 'GetKeyboardState'; #function GetLastInputInfo(var plii: TLastInputInfo): WINBOOL;stdcall; external 'user32' name 'GetLastInputInfo'; @@ -21606,24 +21606,24 @@ proc GetMailslotInfo*(hMailslot: THandle, lpMaxMessageSize: Pointer, dynlib: "kernel32", importc: "GetMailslotInfo".} #function GetMenuBarInfo(hend: HWND; idObject, idItem: Longint; var pmbi: TMenuBarInfo): WINBOOL;stdcall; external 'user32' name 'GetMenuBarInfo'; #function GetMenuInfo(menu: HMENU; var lpmi: TMenuInfo): WINBOOL;stdcall; external 'user32' name 'GetMenuInfo'; -proc GetMenuItemInfo*(p1: HMENU, p2: UINT, p3: WINBOOL, p4: var TMenuItemInfo): WINBOOL{. +proc GetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var TMenuItemInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} -proc GetMenuItemInfoA*(p1: HMENU, p2: UINT, p3: WINBOOL, p4: var TMenuItemInfoA): WINBOOL{. +proc GetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: var TMenuItemInfoA): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMenuItemInfoA".} - #function GetMenuItemInfoW(p1: HMENU; p2: UINT; p3: WINBOOL; var p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'GetMenuItemInfoW'; -proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: UINT, lprcItem: var TRect): WINBOOL{. + #function GetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; var p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'GetMenuItemInfoW'; +proc GetMenuItemRect*(wnd: HWND, menu: HMENU, uItem: WINUINT, lprcItem: var TRect): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMenuItemRect".} -proc GetMessage*(lpMsg: var TMsg, wnd: HWND, wMsgFilterMin, wMsgFilterMax: UINT): WINBOOL{. +proc GetMessage*(lpMsg: var TMsg, wnd: HWND, wMsgFilterMin, wMsgFilterMax: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "GetMessageA".} proc GetMessageA*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax: UINT): WINBOOL{.stdcall, + wMsgFilterMin, wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMessageA".} proc GetMessageW*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax: UINT): WINBOOL{.stdcall, + wMsgFilterMin, wMsgFilterMax: WINUINT): WINBOOL{.stdcall, dynlib: "user32", importc: "GetMessageW".} proc GetMiterLimit*(DC: HDC, Limit: var float32): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetMiterLimit".} - #function GetMouseMovePoints(cbSize: UINT; var lppt, lpptBuf: TMouseMovePoint; nBufPoints: Integer; resolution: DWORD): Integer;stdcall; external 'user32' name 'GetMouseMovePoints'; + #function GetMouseMovePoints(cbSize: WINUINT; var lppt, lpptBuf: TMouseMovePoint; nBufPoints: Integer; resolution: DWORD): Integer;stdcall; external 'user32' name 'GetMouseMovePoints'; proc GetNamedPipeInfo*(hNamedPipe: THandle, lpFlags: var DWORD, lpOutBufferSize, lpInBufferSize, lpMaxInstances: Pointer): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetNamedPipeInfo".} @@ -21637,8 +21637,8 @@ proc GetNumberOfConsoleMouseButtons*(lpNumberOfMouseButtons: var DWORD): WINBOOL proc GetOverlappedResult*(hFile: THandle, lpOverlapped: TOverlapped, lpNumberOfBytesTransferred: var DWORD, bWait: WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetOverlappedResult".} -proc GetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: UINT, - PaletteEntries: pointer): UINT{.stdcall, +proc GetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: WINUINT, + PaletteEntries: pointer): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetPaletteEntries".} proc GetPath*(DC: HDC, Points, Types: pointer, nSize: int): int{.stdcall, dynlib: "gdi32", importc: "GetPath".} @@ -21656,13 +21656,13 @@ proc GetPrivateProfileSectionNames*(lpszReturnBuffer: LPTSTR, nSize: DWORD, lpFileName: LPCTSTR): DWORD{.stdcall, dynlib: "kernel32", importc: "GetPrivateProfileSectionNamesA".} proc GetPrivateProfileStructA*(lpszSection, lpszKey: LPCSTR, lpStruct: LPVOID, - uSizeStruct: UINT, szFile: LPCSTR): WINBOOL{. + uSizeStruct: WINUINT, szFile: LPCSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStructA".} proc GetPrivateProfileStructW*(lpszSection, lpszKey: LPCWSTR, lpStruct: LPVOID, - uSizeStruct: UINT, szFile: LPCWSTR): WINBOOL{. + uSizeStruct: WINUINT, szFile: LPCWSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStructW".} proc GetPrivateProfileStruct*(lpszSection, lpszKey: LPCTSTR, lpStruct: LPVOID, - uSizeStruct: UINT, szFile: LPCTSTR): WINBOOL{. + uSizeStruct: WINUINT, szFile: LPCTSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetPrivateProfileStructA".} proc GetProcessAffinityMask*(hProcess: THandle, lpProcessAffinityMask, lpSystemAffinityMask: var DWORD): WINBOOL{.stdcall, dynlib: "kernel32", @@ -21685,7 +21685,7 @@ proc GetQueuedCompletionStatus*(CompletionPort: THandle, lpOverlapped: var POverlapped, dwMilliseconds: DWORD): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetQueuedCompletionStatus".} -proc GetRasterizerCaps*(p1: var TRasterizerStatus, p2: UINT): WINBOOL{.stdcall, +proc GetRasterizerCaps*(p1: var TRasterizerStatus, p2: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "GetRasterizerCaps".} proc GetRgnBox*(RGN: HRGN, p2: var TRect): int{.stdcall, dynlib: "gdi32", importc: "GetRgnBox".} @@ -21715,8 +21715,8 @@ proc GetStringTypeExW*(Locale: LCID, dwInfoType: DWORD, lpSrcStr: LPWSTR, proc GetStringTypeW*(dwInfoType: DWORD, lpSrcStr: WCHAR, cchSrc: WINBOOL, lpCharType: var int16): WINBOOL{.stdcall, dynlib: "kernel32", importc: "GetStringTypeW".} -proc GetSystemPaletteEntries*(DC: HDC, StartIndex, NumEntries: UINT, - PaletteEntries: pointer): UINT{.stdcall, +proc GetSystemPaletteEntries*(DC: HDC, StartIndex, NumEntries: WINUINT, + PaletteEntries: pointer): WINUINT{.stdcall, dynlib: "gdi32", importc: "GetSystemPaletteEntries".} proc GetSystemPowerStatus*(lpSystemPowerStatus: var TSystemPowerStatus): WINBOOL{. stdcall, dynlib: "kernel32", importc: "GetSystemPowerStatus".} @@ -21859,9 +21859,9 @@ proc InitializeAcl*(pAcl: var TACL, nAclLength, dwAclRevision: DWORD): WINBOOL{. proc InitializeSid*(Sid: Pointer, pIdentifierAuthority: TSIDIdentifierAuthority, nSubAuthorityCount: int8): WINBOOL{.stdcall, dynlib: "advapi32", importc: "InitializeSid".} -proc InsertMenuItemA*(p1: HMENU, p2: UINT, p3: WINBOOL, p4: TMenuItemInfoA): WINBOOL{. +proc InsertMenuItemA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: TMenuItemInfoA): WINBOOL{. stdcall, dynlib: "user32", importc: "InsertMenuItemA".} - #function InsertMenuItemW(p1: HMENU; p2: UINT; p3: WINBOOL; const p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'InsertMenuItemW'; + #function InsertMenuItemW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'InsertMenuItemW'; proc IntersectRect*(lprcDst: var TRect, lprcSrc1, lprcSrc2: TRect): WINBOOL{. stdcall, dynlib: "user32", importc: "IntersectRect".} #function InvertRect(hDC: HDC; const lprc: TRect): WINBOOL; stdcall; external 'user32' name 'InvertRect'; @@ -21967,7 +21967,7 @@ proc MakeSelfRelativeSD*(pAbsoluteSecurityDescriptor: PSecurityDescriptor, dynlib: "advapi32", importc: "MakeSelfRelativeSD".} proc MapDialogRect*(hDlg: HWND, lpRect: var TRect): WINBOOL{.stdcall, dynlib: "user32", importc: "MapDialogRect".} -proc MapWindowPoints*(hWndFrom, hWndTo: HWND, lpPoints: pointer, cPoints: UINT): int{. +proc MapWindowPoints*(hWndFrom, hWndTo: HWND, lpPoints: pointer, cPoints: WINUINT): int{. stdcall, dynlib: "user32", importc: "MapWindowPoints".} proc MessageBoxIndirect*(MsgBoxParams: TMsgBoxParams): WINBOOL{.stdcall, dynlib: "user32", importc: "MessageBoxIndirectA".} @@ -21982,7 +21982,7 @@ proc MsgWaitForMultipleObjects*(nCount: DWORD, pHandles: pointer, proc MsgWaitForMultipleObjectsEx*(nCount: DWORD, pHandles: pointer, dwMilliseconds, dwWakeMask, dwFlags: DWORD): DWORD{. stdcall, dynlib: "user32", importc: "MsgWaitForMultipleObjectsEx".} - # function MultiByteToWideChar(CodePage: UINT; dwFlags: DWORD; const lpMultiByteStr: LPCSTR; cchMultiByte: Integer; lLPWSTRStr: LPWSTR; cchWideChar: Integer): Integer; stdcall; external 'kernel32' name 'MultiByteToWideChar'; + # function MultiByteToWideChar(CodePage: WINUINT; dwFlags: DWORD; const lpMultiByteStr: LPCSTR; cchMultiByte: Integer; lLPWSTRStr: LPWSTR; cchWideChar: Integer): Integer; stdcall; external 'kernel32' name 'MultiByteToWideChar'; proc ObjectOpenAuditAlarm*(SubsystemName: cstring, HandleId: Pointer, ObjectTypeName: cstring, ObjectName: cstring, pSecurityDescriptor: PSecurityDescriptor, @@ -22031,7 +22031,7 @@ proc OffsetViewportOrgEx*(DC: HDC, X, Y: int, Points: pointer): WINBOOL{. stdcall, dynlib: "gdi32", importc: "OffsetViewportOrgEx".} proc OffsetWindowOrgEx*(DC: HDC, X, Y: int, Points: pointer): WINBOOL{.stdcall, dynlib: "gdi32", importc: "OffsetWindowOrgEx".} -proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: var TOFStruct, uStyle: UINT): HFILE{. +proc OpenFile*(lpFileName: LPCSTR, lpReOpenBuff: var TOFStruct, uStyle: WINUINT): HFILE{. stdcall, dynlib: "kernel32", importc: "OpenFile".} proc OpenProcessToken*(ProcessHandle: THandle, DesiredAccess: DWORD, TokenHandle: var THandle): WINBOOL{.stdcall, @@ -22049,19 +22049,19 @@ proc PeekConsoleInputW*(hConsoleInput: THandle, lpBuffer: var TInputRecord, nLength: DWORD, lpNumberOfEventsRead: var DWORD): WINBOOL{. stdcall, dynlib: "kernel32", importc: "PeekConsoleInputW".} proc PeekMessage*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): WINBOOL{. + wMsgFilterMin, wMsgFilterMax, wRemoveMsg: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "PeekMessageA".} proc PeekMessageA*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): WINBOOL{. + wMsgFilterMin, wMsgFilterMax, wRemoveMsg: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "PeekMessageA".} proc PeekMessageW*(lpMsg: var TMsg, wnd: HWND, - wMsgFilterMin, wMsgFilterMax, wRemoveMsg: UINT): WINBOOL{. + wMsgFilterMin, wMsgFilterMax, wRemoveMsg: WINUINT): WINBOOL{. stdcall, dynlib: "user32", importc: "PeekMessageW".} #function PlayEnhMetaFile(DC: HDC; p2: HENHMETAFILE; const p3: TRect): WINBOOL; stdcall; external 'gdi32' name 'PlayEnhMetaFile'; proc PlayEnhMetaFileRecord*(DC: HDC, p2: var THandleTable, p3: TEnhMetaRecord, - p4: UINT): WINBOOL{.stdcall, dynlib: "gdi32", + p4: WINUINT): WINBOOL{.stdcall, dynlib: "gdi32", importc: "PlayEnhMetaFileRecord".} -proc PlayMetaFileRecord*(DC: HDC, p2: THandleTable, p3: TMetaRecord, p4: UINT): WINBOOL{. +proc PlayMetaFileRecord*(DC: HDC, p2: THandleTable, p3: TMetaRecord, p4: WINUINT): WINBOOL{. stdcall, dynlib: "gdi32", importc: "PlayMetaFileRecord".} proc PlgBlt*(DC: HDC, PointsArray: pointer, p3: HDC, p4, p5, p6, p7: int, p8: HBITMAP, p9, p10: int): WINBOOL{.stdcall, dynlib: "gdi32", @@ -22328,21 +22328,21 @@ proc ScrollWindow*(wnd: HWND, XAmount: int32, YAmount: int32, rect: LPRECT, importc: "ScrollWindow".} proc ScrollWindowEx*(wnd: HWND, dx: int32, dy: int32, prcScroll: lpRECT, prcClip: lpRECT, hrgnUpdate: HRGN, prcUpdate: LPRECT, - flags: UINT): int32{.stdcall, dynlib: "user32", + flags: WINUINT): int32{.stdcall, dynlib: "user32", importc: "ScrollWindowEx".} #function ScrollDC(DC: HDC; DX, DY: Integer; var Scroll, Clip: TRect; Rgn: HRGN; Update: PRect): WINBOOL; stdcall; external 'user32' name 'ScrollDC'; #function SearchPath(lpPath, lpFileName, lpExtension: PChar; nBufferLength: DWORD; lpBuffer: PChar; var lpFilePart: PChar): DWORD;stdcall; external 'kernel32' name 'SearchPathA'; #function SearchPathA(lpPath, lpFileName, lpExtension: LPCSTR; nBufferLength: DWORD; lpBuffer: LPCSTR; var lpFilePart: LPCSTR): DWORD; stdcall; external 'kernel32' name 'SearchPathA'; #function SearchPathW(lpPath, lpFileName, lpExtension: LPWSTR; nBufferLength: DWORD; lpBuffer: LPWSTR; var lpFilePart: LPWSTR): DWORD; stdcall; external 'kernel32' name 'SearchPathW'; - #function SendInput(cInputs: UINT; var pInputs: TInput; cbSize: Integer): UINT;stdcall; external 'user32' name 'SendInput'; -proc SendMessageTimeout*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM, - fuFlags, uTimeout: UINT, lpdwResult: var DWORD): LRESULT{. + #function SendInput(cInputs: WINUINT; var pInputs: TInput; cbSize: Integer): WINUINT;stdcall; external 'user32' name 'SendInput'; +proc SendMessageTimeout*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, + fuFlags, uTimeout: WINUINT, lpdwResult: var DWORD): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageTimeoutA".} -proc SendMessageTimeoutA*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM, - fuFlags, uTimeout: UINT, lpdwResult: var DWORD): LRESULT{. +proc SendMessageTimeoutA*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, + fuFlags, uTimeout: WINUINT, lpdwResult: var DWORD): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageTimeoutA".} -proc SendMessageTimeoutW*(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM, - fuFlags, uTimeout: UINT, lpdwResult: var DWORD): LRESULT{. +proc SendMessageTimeoutW*(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM, + fuFlags, uTimeout: WINUINT, lpdwResult: var DWORD): LRESULT{. stdcall, dynlib: "user32", importc: "SendMessageTimeoutW".} #function SetAclInformation(var pAcl: TACL; pAclInformation: Pointer; nAclInformationLength: DWORD; dwAclInformationClass: TAclInformationClass): WINBOOL; stdcall; external 'advapi32' name 'SetAclInformation'; #function SetColorAdjustment(DC: HDC; const p2: TColorAdjustment): WINBOOL; stdcall; external 'gdi32' name 'SetColorAdjustment'; @@ -22356,13 +22356,13 @@ proc SetConsoleCursorInfo*(hConsoleOutput: THandle, lpConsoleCursorInfo: TConsoleCursorInfo): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetConsoleCursorInfo".} #function SetConsoleWindowInfo(hConsoleOutput: THandle; bAbsolute: WINBOOL; const lpConsoleWindow: TSmallRect): WINBOOL; stdcall; external 'kernel32' name 'SetConsoleWindowInfo'; -proc SetDIBColorTable*(DC: HDC, p2, p3: UINT, RGBQuadSTructs: pointer): UINT{. +proc SetDIBColorTable*(DC: HDC, p2, p3: WINUINT, RGBQuadSTructs: pointer): WINUINT{. stdcall, dynlib: "gdi32", importc: "SetDIBColorTable".} -proc SetDIBits*(DC: HDC, Bitmap: HBITMAP, StartScan, NumScans: UINT, - Bits: Pointer, BitsInfo: var TBitmapInfo, Usage: UINT): int{. +proc SetDIBits*(DC: HDC, Bitmap: HBITMAP, StartScan, NumScans: WINUINT, + Bits: Pointer, BitsInfo: var TBitmapInfo, Usage: WINUINT): int{. stdcall, dynlib: "gdi32", importc: "SetDIBits".} - #function SetDIBitsToDevice(DC: HDC; DestX, DestY: Integer; Width, Height: DWORD; SrcX, SrcY: Integer; nStartScan, NumScans: UINT; Bits: Pointer; var BitsInfo: TBitmapInfo; Usage: UINT): Integer; stdcall; external 'gdi32' name 'SetDIBitsToDevice'; -proc SetEnhMetaFileBits*(para1: UINT, para2: pointer): HENHMETAFILE{.stdcall, + #function SetDIBitsToDevice(DC: HDC; DestX, DestY: Integer; Width, Height: DWORD; SrcX, SrcY: Integer; nStartScan, NumScans: WINUINT; Bits: Pointer; var BitsInfo: TBitmapInfo; Usage: WINUINT): Integer; stdcall; external 'gdi32' name 'SetDIBitsToDevice'; +proc SetEnhMetaFileBits*(para1: WINUINT, para2: pointer): HENHMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetEnhMetaFileBits".} proc SetFileTime*(hFile: HANDLE, lpCreationTime: var FILETIME, lpLastAccessTime: var FILETIME, lpLastWriteTime: var FILETIME): WINBOOL{. @@ -22370,18 +22370,18 @@ proc SetFileTime*(hFile: HANDLE, lpCreationTime: var FILETIME, #function SetKeyboardState(var KeyState: TKeyboardState): WINBOOL; stdcall; external 'user32' name 'SetKeyboardState'; #function SetLocalTime(const lpSystemTime: TSystemTime): WINBOOL; stdcall; external 'kernel32' name 'SetLocalTime'; #function SetMenuInfo(menu: HMENU; const lpcmi: TMenuInfo): WINBOOL;stdcall; external 'user32' name 'SetMenuInfo'; -proc SetMenuItemInfo*(p1: HMENU, p2: UINT, p3: WINBOOL, p4: TMenuItemInfo): WINBOOL{. +proc SetMenuItemInfo*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: TMenuItemInfo): WINBOOL{. stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} -proc SetMenuItemInfoA*(p1: HMENU, p2: UINT, p3: WINBOOL, p4: TMenuItemInfoA): WINBOOL{. +proc SetMenuItemInfoA*(p1: HMENU, p2: WINUINT, p3: WINBOOL, p4: TMenuItemInfoA): WINBOOL{. stdcall, dynlib: "user32", importc: "SetMenuItemInfoA".} - #function SetMenuItemInfoW(p1: HMENU; p2: UINT; p3: WINBOOL; const p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'SetMenuItemInfoW'; -proc SetMetaFileBitsEx*(p1: UINT, p2: cstring): HMETAFILE{.stdcall, + #function SetMenuItemInfoW(p1: HMENU; p2: WINUINT; p3: WINBOOL; const p4: TMenuItemInfoW): WINBOOL; stdcall; external 'user32' name 'SetMenuItemInfoW'; +proc SetMetaFileBitsEx*(p1: WINUINT, p2: cstring): HMETAFILE{.stdcall, dynlib: "gdi32", importc: "SetMetaFileBitsEx".} proc SetNamedPipeHandleState*(hNamedPipe: THandle, lpMode: var DWORD, lpMaxCollectionCount, lpCollectDataTimeout: Pointer): WINBOOL{.stdcall, dynlib: "kernel32", importc: "SetNamedPipeHandleState".} -proc SetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: UINT, - PaletteEntries: pointer): UINT{.stdcall, +proc SetPaletteEntries*(Palette: HPALETTE, StartIndex, NumEntries: WINUINT, + PaletteEntries: pointer): WINUINT{.stdcall, dynlib: "gdi32", importc: "SetPaletteEntries".} #function SetPrivateObjectSecurity(SecurityInformation: SECURITY_INFORMATION; ModificationDescriptor: PSecurityDescriptor; var ObjectsSecurityDescriptor: PSecurityDescriptor; const GenericMapping: TGenericMapping; Token: THandle): WINBOOL; # stdcall; external 'advapi32' name 'SetPrivateObjectSecurity'; @@ -22407,7 +22407,7 @@ proc SetWaitableTimer*(hTimer: THandle, lpDueTime: var TLargeInteger, lPeriod: int32, pfnCompletionRoutine: TFNTimerAPCRoutine, lpArgToCompletionRoutine: Pointer, fResume: WINBOOL): WINBOOL{. stdcall, dynlib: "kernel32", importc: "SetWaitableTimer".} -proc SetWinMetaFileBits*(p1: UINT, p2: cstring, p3: HDC, p4: TMetaFilePict): HENHMETAFILE{. +proc SetWinMetaFileBits*(p1: WINUINT, p2: cstring, p3: HDC, p4: TMetaFilePict): HENHMETAFILE{. stdcall, dynlib: "gdi32", importc: "SetWinMetaFileBits".} #function SetWorldTransform(DC: HDC; const p2: TXForm): WINBOOL; stdcall; external 'gdi32' name 'SetWorldTransform'; proc StartDoc*(DC: HDC, p2: TDocInfo): int{.stdcall, dynlib: "gdi32", @@ -22415,7 +22415,7 @@ proc StartDoc*(DC: HDC, p2: TDocInfo): int{.stdcall, dynlib: "gdi32", proc StartDocA*(DC: HDC, p2: TDocInfoA): int{.stdcall, dynlib: "gdi32", importc: "StartDocA".} #function StartDocW(DC: HDC; const p2: TDocInfoW): Integer; stdcall; external 'gdi32' name 'StartDocW'; - #function StretchDIBits(DC: HDC; DestX, DestY, DestWidth, DestHegiht, SrcX, SrcY, SrcWidth, SrcHeight: Integer; Bits: Pointer; var BitsInfo: TBitmapInfo; Usage: UINT; Rop: DWORD): Integer; stdcall; external 'gdi32' name 'StretchDIBits'; + #function StretchDIBits(DC: HDC; DestX, DestY, DestWidth, DestHegiht, SrcX, SrcY, SrcWidth, SrcHeight: Integer; Bits: Pointer; var BitsInfo: TBitmapInfo; Usage: WINUINT; Rop: DWORD): Integer; stdcall; external 'gdi32' name 'StretchDIBits'; proc SubtractRect*(lprcDst: var TRect, lprcSrc1, lprcSrc2: TRect): WINBOOL{. stdcall, dynlib: "user32", importc: "SubtractRect".} proc SystemTimeToFileTime*(lpSystemTime: TSystemTime, lpFileTime: var TFileTime): WINBOOL{. @@ -22435,15 +22435,15 @@ proc TabbedTextOutW*(hDC: HDC, X, Y: int, lpString: LPWSTR, nCount, nTabPositions: int, lpnTabStopPositions: pointer, nTabOrigin: int): int32{.stdcall, dynlib: "user32", importc: "TabbedTextOutW".} - #function ToAscii(uVirtKey, uScanCode: UINT; const KeyState: TKeyboardState; lpChar: PChar; uFlags: UINT): Integer; stdcall; external 'user32' name 'ToAscii'; - #function ToAsciiEx(uVirtKey: UINT; uScanCode: UINT; const KeyState: TKeyboardState; lpChar: PChar; uFlags: UINT; dwhkl: HKL): Integer; stdcall; external 'user32' name 'ToAsciiEx'; - #function ToUnicode(wVirtKey, wScanCode: UINT; const KeyState: TKeyboardState; var pwszBuff; cchBuff: Integer; wFlags: UINT): Integer; stdcall; external 'user32' name 'ToUnicode'; + #function ToAscii(uVirtKey, uScanCode: WINUINT; const KeyState: TKeyboardState; lpChar: PChar; uFlags: WINUINT): Integer; stdcall; external 'user32' name 'ToAscii'; + #function ToAsciiEx(uVirtKey: WINUINT; uScanCode: WINUINT; const KeyState: TKeyboardState; lpChar: PChar; uFlags: WINUINT; dwhkl: HKL): Integer; stdcall; external 'user32' name 'ToAsciiEx'; + #function ToUnicode(wVirtKey, wScanCode: WINUINT; const KeyState: TKeyboardState; var pwszBuff; cchBuff: Integer; wFlags: WINUINT): Integer; stdcall; external 'user32' name 'ToUnicode'; # Careful, NT and higher only. proc TrackMouseEvent*(EventTrack: var TTrackMouseEvent): WINBOOL{.stdcall, dynlib: "user32", importc: "TrackMouseEvent".} proc TrackMouseEvent*(lpEventTrack: PTrackMouseEvent): WINBOOL{.stdcall, dynlib: "user32", importc: "TrackMouseEvent".} -proc TrackPopupMenu*(menu: HMENU, uFlags: UINT, x: int32, y: int32, +proc TrackPopupMenu*(menu: HMENU, uFlags: WINUINT, x: int32, y: int32, nReserved: int32, wnd: HWND, prcRect: PRect): WINBOOL{. stdcall, dynlib: "user32", importc: "TrackPopupMenu".} proc TransactNamedPipe*(hNamedPipe: THandle, lpInBuffer: Pointer, @@ -22464,7 +22464,7 @@ proc TranslateMDISysAccel*(hWndClient: HWND, lpMsg: TMsg): WINBOOL{.stdcall, dynlib: "user32", importc: "TranslateMDISysAccel".} proc TranslateMessage*(lpMsg: TMsg): WINBOOL{.stdcall, dynlib: "user32", importc: "TranslateMessage".} - #function TransparentDIBits(DC: HDC; p2, p3, p4, p5: Integer; const p6: Pointer; const p7: PBitmapInfo; p8: UINT; p9, p10, p11, p12: Integer; p13: UINT): WINBOOL;stdcall; external 'gdi32' name 'TransparentDIBits'; + #function TransparentDIBits(DC: HDC; p2, p3, p4, p5: Integer; const p6: Pointer; const p7: PBitmapInfo; p8: WINUINT; p9, p10, p11, p12: Integer; p13: WINUINT): WINBOOL;stdcall; external 'gdi32' name 'TransparentDIBits'; proc UnhandledExceptionFilter*(ExceptionInfo: TExceptionPointers): int32{. stdcall, dynlib: "kernel32", importc: "UnhandledExceptionFilter".} proc UnionRect*(lprcDst: var TRect, lprcSrc1, lprcSrc2: TRect): WINBOOL{. @@ -22474,39 +22474,39 @@ proc UnlockFileEx*(hFile: THandle, dwReserved, nNumberOfBytesToUnlockLow: DWORD, stdcall, dynlib: "kernel32", importc: "UnlockFileEx".} proc VerFindFile*(uFlags: DWORD, szFileName, szWinDir, szAppDir, szCurDir: cstring, - lpuCurDirLen: var UINT, szDestDir: cstring, - lpuDestDirLen: var UINT): DWORD{.stdcall, dynlib: "version", + lpuCurDirLen: var WINUINT, szDestDir: cstring, + lpuDestDirLen: var WINUINT): DWORD{.stdcall, dynlib: "version", importc: "VerFindFileA".} proc VerFindFileA*(uFlags: DWORD, szFileName, szWinDir, szAppDir, szCurDir: LPCSTR, - lpuCurDirLen: var UINT, szDestDir: LPCSTR, - lpuDestDirLen: var UINT): DWORD{.stdcall, dynlib: "version", + lpuCurDirLen: var WINUINT, szDestDir: LPCSTR, + lpuDestDirLen: var WINUINT): DWORD{.stdcall, dynlib: "version", importc: "VerFindFileA".} proc VerFindFileW*(uFlags: DWORD, szFileName, szWinDir, szAppDir, szCurDir: LPWSTR, - lpuCurDirLen: var UINT, szDestDir: LPWSTR, - lpuDestDirLen: var UINT): DWORD{.stdcall, dynlib: "version", + lpuCurDirLen: var WINUINT, szDestDir: LPWSTR, + lpuDestDirLen: var WINUINT): DWORD{.stdcall, dynlib: "version", importc: "VerFindFileW".} proc VerInstallFile*(uFlags: DWORD, szSrcFileName, szDestFileName, szSrcDir, szDestDir, szCurDir, szTmpFile: cstring, - lpuTmpFileLen: var UINT): DWORD{.stdcall, + lpuTmpFileLen: var WINUINT): DWORD{.stdcall, dynlib: "version", importc: "VerInstallFileA".} proc VerInstallFileA*(uFlags: DWORD, szSrcFileName, szDestFileName, szSrcDir, szDestDir, szCurDir, szTmpFile: LPCSTR, - lpuTmpFileLen: var UINT): DWORD{.stdcall, + lpuTmpFileLen: var WINUINT): DWORD{.stdcall, dynlib: "version", importc: "VerInstallFileA".} proc VerInstallFileW*(uFlags: DWORD, szSrcFileName, szDestFileName, szSrcDir, szDestDir, szCurDir, szTmpFile: LPWSTR, - lpuTmpFileLen: var UINT): DWORD{.stdcall, + lpuTmpFileLen: var WINUINT): DWORD{.stdcall, dynlib: "version", importc: "VerInstallFileW".} proc VerQueryValue*(pBlock: Pointer, lpSubBlock: cstring, - lplpBuffer: var Pointer, puLen: var UINT): WINBOOL{.stdcall, + lplpBuffer: var Pointer, puLen: var WINUINT): WINBOOL{.stdcall, dynlib: "version", importc: "VerQueryValueA".} proc VerQueryValueA*(pBlock: Pointer, lpSubBlock: LPCSTR, - lplpBuffer: var Pointer, puLen: var UINT): WINBOOL{. + lplpBuffer: var Pointer, puLen: var WINUINT): WINBOOL{. stdcall, dynlib: "version", importc: "VerQueryValueA".} proc VerQueryValueW*(pBlock: Pointer, lpSubBlock: LPWSTR, - lplpBuffer: var Pointer, puLen: var UINT): WINBOOL{. + lplpBuffer: var Pointer, puLen: var WINUINT): WINBOOL{. stdcall, dynlib: "version", importc: "VerQueryValueW".} proc VirtualQuery*(lpAddress: Pointer, lpBuffer: var TMemoryBasicInformation, dwLength: DWORD): DWORD{.stdcall, dynlib: "kernel32", @@ -22526,7 +22526,7 @@ proc wglGetLayerPaletteEntries*(p1: HDC, p2, p3, p4: int, pcr: pointer): int{. stdcall, dynlib: "opengl32", importc: "wglGetLayerPaletteEntries".} proc wglSetLayerPaletteEntries*(p1: HDC, p2, p3, p4: int, pcr: pointer): int{. stdcall, dynlib: "opengl32", importc: "wglSetLayerPaletteEntries".} - #function wglSwapMultipleBuffers(p1: UINT; const p2: PWGLSwap): DWORD;stdcall; external 'opengl32' name 'wglSwapMultipleBuffers'; + #function wglSwapMultipleBuffers(p1: WINUINT; const p2: PWGLSwap): DWORD;stdcall; external 'opengl32' name 'wglSwapMultipleBuffers'; #function WinSubmitCertificate(var lpCertificate: TWinCertificate): WINBOOL;stdcall; external 'imaghlp' name 'WinSubmitCertificate'; #function WinVerifyTrust(wnd: HWND; const ActionID: TGUID; ActionData: Pointer): Longint;stdcall; external 'imaghlp' name 'WinVerifyTrust'; proc WNetAddConnection2*(lpNetResource: var TNetResource, @@ -22698,14 +22698,14 @@ proc WriteFileEx*(hFile: THandle, lpBuffer: Pointer, lpCompletionRoutine: FARPROC): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WriteFileEx".} proc WritePrivateProfileStructA*(lpszSection, lpszKey: LPCSTR, lpStruct: LPVOID, - uSizeStruct: UINT, szFile: LPCSTR): WINBOOL{. + uSizeStruct: WINUINT, szFile: LPCSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStructA".} proc WritePrivateProfileStructW*(lpszSection, lpszKey: LPCWSTR, - lpStruct: LPVOID, uSizeStruct: UINT, + lpStruct: LPVOID, uSizeStruct: WINUINT, szFile: LPCWSTR): WINBOOL{.stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStructW".} proc WritePrivateProfileStruct*(lpszSection, lpszKey: LPCTSTR, lpStruct: LPVOID, - uSizeStruct: UINT, szFile: LPCTSTR): WINBOOL{. + uSizeStruct: WINUINT, szFile: LPCTSTR): WINBOOL{. stdcall, dynlib: "kernel32", importc: "WritePrivateProfileStructA".} proc WriteProcessMemory*(hProcess: THandle, lpBaseAddress: Pointer, lpBuffer: Pointer, nSize: DWORD, @@ -22758,12 +22758,12 @@ proc LocalDiscard*(hlocMem: HLOCAL): HLOCAL = # WinGDI.h -proc GetGValue*(rgb: int32): int8 = - result = toU8(rgb shr 8'i32) +discard """proc GetGValue*(rgb: int32): int8 = + result = toU8(rgb shr 8'i32)""" proc RGB*(r, g, b: int): COLORREF = result = toU32(r) or (toU32(g) shl 8) or (toU32(b) shl 16) proc RGB*(r, g, b: range[0 .. 255]): COLORREF = - result = r or g shl 8 or b shl 16 + result = toU32(r) or (toU32(g) shl 8) or (toU32(b) shl 16) proc PALETTERGB*(r, g, b: range[0..255]): COLORREF = result = 0x02000000 or RGB(r, g, b) @@ -23363,7 +23363,7 @@ proc Animate_Create(hWndP: HWND, id: HMENU, dwStyle: DWORD, hInstance: HINST): H proc Animate_Open(wnd: HWND, szName: LPTSTR): LRESULT = result = SendMessage(wnd, ACM_OPEN, 0, cast[LPARAM](szName)) -proc Animate_Play(wnd: HWND, `from`, `to`: int32, rep: UINT): LRESULT = +proc Animate_Play(wnd: HWND, `from`, `to`: int32, rep: WINUINT): LRESULT = result = SendMessage(wnd, ACM_PLAY, WPARAM(rep), LPARAM(MAKELONG(`from`, `to`))) @@ -23458,7 +23458,7 @@ proc Header_SetItem(hwndHD: HWND, index: int32, hdi: var HD_ITEM): WINBOOL = result = WINBOOL(SendMessage(hwndHD, HDM_SETITEM, WPARAM(index), cast[LPARAM](addr(hdi)))) -proc ListView_Arrange(hwndLV: HWND, code: UINT): LRESULT = +proc ListView_Arrange(hwndLV: HWND, code: WINUINT): LRESULT = result = SendMessage(hwndLV, LVM_ARRANGE, WPARAM(code), 0) proc ListView_CreateDragImage(wnd: HWND, i: int32, lpptUpLeft: LPPOINT): LRESULT = @@ -23481,7 +23481,7 @@ proc ListView_EnsureVisible(hwndLV: HWND, i, fPartialOK: int32): LRESULT = MAKELPARAM(fPartialOK, 0)) proc ListView_FindItem(wnd: HWND, iStart: int32, lvfi: var LV_FINDINFO): int32 = - result = SendMessage(wnd, LVM_FINDITEM, WPARAM(iStart), + result = SendMessage(wnd, LVM_FINDITEM, WPARAM(iStart), cast[LPARAM](addr(lvfi))).int32 proc ListView_GetBkColor(wnd: HWND): LRESULT = @@ -23566,7 +23566,7 @@ proc ListView_Scroll(hwndLV: HWND, dx, dy: int32): LRESULT = proc ListView_SetBkColor(wnd: HWND, clrBk: COLORREF): LRESULT = result = SendMessage(wnd, LVM_SETBKCOLOR, 0, LPARAM(clrBk)) -proc ListView_SetCallbackMask(wnd: HWND, mask: UINT): LRESULT = +proc ListView_SetCallbackMask(wnd: HWND, mask: WINUINT): LRESULT = result = SendMessage(wnd, LVM_SETCALLBACKMASK, WPARAM(mask), 0) proc ListView_SetColumn(wnd: HWND, iCol: int32, col: var LV_COLUMN): LRESULT = @@ -23577,7 +23577,7 @@ proc ListView_SetColumnWidth(wnd: HWND, iCol, cx: int32): LRESULT = proc ListView_SetImageList(wnd: HWND, himl: int32, iImageList: HIMAGELIST): LRESULT = result = SendMessage(wnd, LVM_SETIMAGELIST, WPARAM(iImageList), - LPARAM(UINT(himl))) + LPARAM(WINUINT(himl))) proc ListView_SetItem(wnd: HWND, item: var LV_ITEM): LRESULT = result = SendMessage(wnd, LVM_SETITEM, 0, cast[LPARAM](addr(item))) @@ -23597,8 +23597,8 @@ proc ListView_SetItemPosition32(hwndLV: HWND, i, x, y: int32): LRESULT = proc ListView_SetItemState(hwndLV: HWND, i, data, mask: int32): LRESULT = var gnu_lvi: LV_ITEM - gnu_lvi.stateMask = uint(mask) - gnu_lvi.state = uint(data) + gnu_lvi.stateMask = WINUINT(mask) + gnu_lvi.state = WINUINT(data) result = SendMessage(hwndLV, LVM_SETITEMSTATE, WPARAM(i), cast[LPARAM](addr(gnu_lvi))) @@ -23648,7 +23648,7 @@ proc TreeView_GetImageList(wnd: HWND, iImage: WPARAM): LRESULT = result = SendMessage(wnd, TVM_GETIMAGELIST, iImage, 0) proc TreeView_SetImageList(wnd: HWND, himl: HIMAGELIST, iImage: WPARAM): LRESULT = - result = SendMessage(wnd, TVM_SETIMAGELIST, iImage, LPARAM(UINT(himl))) + result = SendMessage(wnd, TVM_SETIMAGELIST, iImage, LPARAM(WINUINT(himl))) proc TreeView_GetNextItem(wnd: HWND, hitem: HTREEITEM, code: int32): LRESULT = result = SendMessage(wnd, TVM_GETNEXTITEM, WPARAM(code), cast[LPARAM](hitem)) @@ -23735,7 +23735,7 @@ proc TabCtrl_GetImageList(wnd: HWND): LRESULT = result = SendMessage(wnd, TCM_GETIMAGELIST, 0, 0) proc TabCtrl_SetImageList(wnd: HWND, himl: HIMAGELIST): LRESULT = - result = SendMessage(wnd, TCM_SETIMAGELIST, 0, LPARAM(UINT(himl))) + result = SendMessage(wnd, TCM_SETIMAGELIST, 0, LPARAM(WINUINT(himl))) proc TabCtrl_GetItemCount(wnd: HWND): LRESULT = result = SendMessage(wnd, TCM_GETITEMCOUNT, 0, 0) @@ -23797,7 +23797,7 @@ proc TabCtrl_GetCurFocus(wnd: HWND): LRESULT = proc TabCtrl_SetCurFocus(wnd: HWND, i: int32): LRESULT = result = SendMessage(wnd, TCM_SETCURFOCUS, i, 0) -proc SNDMSG(wnd: HWND, Msg: UINT, wp: WPARAM, lp: LPARAM): LRESULT = +proc SNDMSG(wnd: HWND, Msg: WINUINT, wp: WPARAM, lp: LPARAM): LRESULT = result = SendMessage(wnd, Msg, wp, lp) proc CommDlg_OpenSave_GetSpecA(hdlg: HWND, psz: LPSTR, cbmax: int32): LRESULT = diff --git a/lib/windows/winlean.nim b/lib/windows/winlean.nim index 4ce2f11b4..dcae6ffaf 100644 --- a/lib/windows/winlean.nim +++ b/lib/windows/winlean.nim @@ -639,9 +639,9 @@ proc unmapViewOfFile*(lpBaseAddress: pointer): WINBOOL {.stdcall, dynlib: "kernel32", importc: "UnmapViewOfFile".} type - TOVERLAPPED* {.final, pure.} = object - Internal*: DWORD - InternalHigh*: DWORD + TOVERLAPPED* {.pure, inheritable.} = object + Internal*: PULONG + InternalHigh*: PULONG Offset*: DWORD OffsetHigh*: DWORD hEvent*: THANDLE @@ -718,4 +718,12 @@ proc WSASend*(s: TSocketHandle, buf: ptr TWSABuf, bufCount: DWORD, stdcall, importc: "WSASend", dynlib: "Ws2_32.dll".} proc get_osfhandle*(fd:TFileHandle): THandle {. - importc:"_get_osfhandle", header:"<io.h>".} + importc: "_get_osfhandle", header:"<io.h>".} + +proc getSystemTimes*(lpIdleTime, lpKernelTime, + lpUserTime: var TFILETIME): WINBOOL {.stdcall, + dynlib: "kernel32", importc: "GetSystemTimes".} + +proc getProcessTimes*(hProcess: THandle; lpCreationTime, lpExitTime, + lpKernelTime, lpUserTime: var TFILETIME): WINBOOL {.stdcall, + dynlib: "kernel32", importc: "GetProcessTimes".} diff --git a/lib/wrappers/openssl.nim b/lib/wrappers/openssl.nim index 90c398dce..4dc71bffd 100644 --- a/lib/wrappers/openssl.nim +++ b/lib/wrappers/openssl.nim @@ -270,7 +270,7 @@ proc OPENSSL_config*(configName: cstring){.cdecl, dynlib: DLLSSLName, importc.} when not defined(windows): proc CRYPTO_set_mem_functions(a,b,c: pointer){.cdecl, - dynlib: DLLSSLName, importc.} + dynlib: DLLUtilName, importc.} proc CRYPTO_malloc_init*() = when not defined(windows): @@ -433,3 +433,70 @@ else: proc SSLGetMode(s: PSSL): int = result = SSLctrl(s, SSL_CTRL_MODE, 0, nil) +# <openssl/md5.h> +type + MD5_LONG* = cuint +const + MD5_CBLOCK* = 64 + MD5_LBLOCK* = int(MD5_CBLOCK div 4) + MD5_DIGEST_LENGTH* = 16 +type + MD5_CTX* = object + A,B,C,D,Nl,Nh: MD5_LONG + data: array[MD5_LBLOCK, MD5_LONG] + num: cuint + +{.pragma: ic, importc: "$1".} +{.push callconv:cdecl, dynlib:DLLUtilName.} +proc MD5_Init*(c: var MD5_CTX): cint{.ic.} +proc MD5_Update*(c: var MD5_CTX; data: pointer; len: csize): cint{.ic.} +proc MD5_Final*(md: cstring; c: var MD5_CTX): cint{.ic.} +proc MD5*(d: ptr cuchar; n: csize; md: ptr cuchar): ptr cuchar{.ic.} +proc MD5_Transform*(c: var MD5_CTX; b: ptr cuchar){.ic.} +{.pop.} + +from strutils import toHex,toLower + +proc hexStr (buf:cstring): string = + # turn md5s output into a nice hex str + result = newStringOfCap(32) + for i in 0 .. <16: + result.add toHex(buf[i].ord, 2).toLower + +proc MD5_File* (file: string): string {.raises:[EIO,Ebase].} = + ## Generate MD5 hash for a file. Result is a 32 character + # hex string with lowercase characters (like the output + # of `md5sum` + const + sz = 512 + let f = open(file,fmRead) + var + buf: array[sz,char] + ctx: MD5_CTX + + discard md5_init(ctx) + while(let bytes = f.readChars(buf, 0, sz); bytes > 0): + discard md5_update(ctx, buf[0].addr, bytes) + + discard md5_final( buf[0].addr, ctx ) + f.close + + result = hexStr(buf) + +proc MD5_Str* (str:string): string {.raises:[EIO].} = + ##Generate MD5 hash for a string. Result is a 32 character + #hex string with lowercase characters + var + ctx: MD5_CTX + res: array[MD5_DIGEST_LENGTH,char] + input = str.cstring + discard md5_init(ctx) + + var i = 0 + while i < str.len: + let L = min(str.len - i, 512) + discard md5_update(ctx, input[i].addr, L) + i += L + + discard md5_final(res,ctx) + result = hexStr(res) diff --git a/lib/wrappers/pdcurses.nim b/lib/wrappers/pdcurses.nim index f014c5e9c..a53289bce 100644 --- a/lib/wrappers/pdcurses.nim +++ b/lib/wrappers/pdcurses.nim @@ -554,14 +554,12 @@ template BUTTON_CHANGED*(x: expr): expr = template BUTTON_STATUS*(x: expr): expr = (Mouse_status.button[(x) - 1]) -template ACS_PICK*(w, n: expr): expr = - (cast[int32](w) or A_ALTCHARSET) +template ACS_PICK*(w, n: expr): expr = int32(w) or A_ALTCHARSET -template KEY_F*(n: expr): expr = - (KEY_F0 + (n)) +template KEY_F*(n: expr): expr = KEY_F0 + n template COLOR_PAIR*(n: expr): expr = - ((cast[cunsignedlong]((n)) shl COLOR_SHIFT) and A_COLOR) + ((cunsignedlong(n) shl COLOR_SHIFT) and A_COLOR) template PAIR_NUMBER*(n: expr): expr = (((n) and A_COLOR) shr COLOR_SHIFT) diff --git a/lib/wrappers/readline/readline.nim b/lib/wrappers/readline/readline.nim index 1f0dd564f..bbe416534 100644 --- a/lib/wrappers/readline/readline.nim +++ b/lib/wrappers/readline/readline.nim @@ -29,8 +29,8 @@ elif defined(macosx): else: const readlineDll* = "libreadline.so.6(|.0)" -## mangle "'TCommandFunc'" TCommandFunc -## mangle TvcpFunc TvcpFunc +# mangle "'TCommandFunc'" TCommandFunc +# mangle TvcpFunc TvcpFunc import rltypedefs diff --git a/lib/wrappers/sqlite3.nim b/lib/wrappers/sqlite3.nim index 586f763ae..7b7f0874e 100644 --- a/lib/wrappers/sqlite3.nim +++ b/lib/wrappers/sqlite3.nim @@ -106,15 +106,15 @@ type Pstmt* = ptr Tstmt Tvalue{.pure, final.} = object Pvalue* = ptr Tvalue - PPValue* = ptr Pvalue + PValueArg* = array[0..127, Pvalue] Tcallback* = proc (para1: pointer, para2: int32, para3, para4: cstringArray): int32{.cdecl.} Tbind_destructor_func* = proc (para1: pointer){.cdecl.} Tcreate_function_step_func* = proc (para1: Pcontext, para2: int32, - para3: PPValue){.cdecl.} + para3: PValueArg){.cdecl.} Tcreate_function_func_func* = proc (para1: Pcontext, para2: int32, - para3: PPValue){.cdecl.} + para3: PValueArg){.cdecl.} Tcreate_function_final_func* = proc (para1: Pcontext){.cdecl.} Tresult_func* = proc (para1: pointer){.cdecl.} Tcreate_collation_func* = proc (para1: pointer, para2: int32, para3: pointer, diff --git a/readme.md b/readme.md index 38e04233f..e8c081d4e 100644 --- a/readme.md +++ b/readme.md @@ -39,8 +39,9 @@ $ bin/nimrod c koch $ ./koch boot -d:release ``` -``koch install [dir]`` may then be used to install Nimrod, or you -can simply add it to your PATH. +``koch install [dir]`` may then be used to install Nimrod, or you can simply +add it to your PATH. More ``koch`` related options are documented in +[doc/koch.txt](doc/koch.txt). The above steps can be performed on Windows in a similar fashion, the ``build.bat`` and ``build64.bat`` (for x86_64 systems) are provided to be used diff --git a/readme.txt b/readme.txt index 3eaef0b35..3f6aef05c 100644 --- a/readme.txt +++ b/readme.txt @@ -39,8 +39,9 @@ $ bin/nimrod c koch $ ./koch boot -d:release ``` -``koch install [dir]`` may then be used to install Nimrod, or you -can simply add it to your PATH. +``koch install [dir]`` may then be used to install Nimrod, or you can simply +add it to your PATH. More ``koch`` related options are documented in +[doc/koch.txt](doc/koch.txt). The above steps can be performed on Windows in a similar fashion, the ``build.bat`` and ``build64.bat`` (for x86_64 systems) are provided to be used diff --git a/tests/async/tasyncawait.nim b/tests/async/tasyncawait.nim index ffceeaee6..2d65db4bd 100644 --- a/tests/async/tasyncawait.nim +++ b/tests/async/tasyncawait.nim @@ -23,19 +23,19 @@ proc launchSwarm(port: TPort) {.async.} = await connect(sock, "localhost", port) when true: await sendMessages(sock) - close(sock) + closeSocket(sock) else: # Issue #932: https://github.com/Araq/Nimrod/issues/932 var msgFut = sendMessages(sock) msgFut.callback = proc () = - close(sock) + closeSocket(sock) proc readMessages(client: TAsyncFD) {.async.} = while true: var line = await recvLine(client) if line == "": - close(client) + closeSocket(client) clientCount.inc break else: @@ -61,11 +61,11 @@ proc createServer(port: TPort) {.async.} = discard server.TSocketHandle.listen() while true: var client = await accept(server) - readMessages(client) + asyncCheck readMessages(client) # TODO: Test: readMessages(disp, await disp.accept(server)) -createServer(TPort(10335)) -launchSwarm(TPort(10335)) +asyncCheck createServer(TPort(10335)) +asyncCheck launchSwarm(TPort(10335)) while true: poll() if clientCount == swarmSize: break diff --git a/tests/async/tasyncdiscard.nim b/tests/async/tasyncdiscard.nim new file mode 100644 index 000000000..966851acc --- /dev/null +++ b/tests/async/tasyncdiscard.nim @@ -0,0 +1,39 @@ +discard """ + output: ''' +1 +2 +3 +4 +1 +2 +1 +6 +''' +""" +import asyncio, asyncdispatch, asyncnet + +proc main {.async.} = + proc f: PFuture[int] {.async.} = + discard + echo 1 + discard + result = 2 + discard + + let x = await f() + echo x + echo 3 + + proc g: PFuture[int] {.async.} = + discard + echo 4 + discard + result = 6 + discard + echo await f() + discard await f() + + discard await g() + echo 6 + +asyncCheck main() diff --git a/tests/async/tnestedpfuturetypeparam.nim b/tests/async/tnestedpfuturetypeparam.nim new file mode 100644 index 000000000..1db442170 --- /dev/null +++ b/tests/async/tnestedpfuturetypeparam.nim @@ -0,0 +1,8 @@ +import asyncdispatch, asyncnet + +proc main {.async.} = + proc f: PFuture[seq[int]] {.async.} = + await newAsyncSocket().connect("www.google.com", TPort(80)) + let x = await f() + +asyncCheck main() diff --git a/tests/casestmt/tcase_arrayconstr.nim b/tests/casestmt/tcase_arrayconstr.nim new file mode 100644 index 000000000..cd7156600 --- /dev/null +++ b/tests/casestmt/tcase_arrayconstr.nim @@ -0,0 +1,19 @@ +discard """ + output: '''Not found! +Found!''' +""" + +const + md_extension = [".md", ".markdown"] + +proc test(ext: string) = + case ext + of ".txt", md_extension: + echo "Found!" + else: + echo "Not found!" + +test(".something") +# ensure it's not evaluated at compile-time: +var foo = ".markdown" +test(foo) diff --git a/tests/ccgbugs/tbug1081.nim b/tests/ccgbugs/tbug1081.nim new file mode 100644 index 000000000..71628feec --- /dev/null +++ b/tests/ccgbugs/tbug1081.nim @@ -0,0 +1,17 @@ +discard """ + output: '''1 +0 +0 +0''' +""" + +proc `1/1`() = echo(1 div 1) +template `1/2`() = echo(1 div 2) +var `1/3` = 1 div 4 +`1/3` = 1 div 3 # oops, 1/3!=1/4 +let `1/4` = 1 div 4 + +`1/1`() +`1/2`() +echo `1/3` +echo `1/4` diff --git a/tests/exprs/tstmtexprs.nim b/tests/exprs/tstmtexprs.nim index ed0066287..d6b827b6d 100644 --- a/tests/exprs/tstmtexprs.nim +++ b/tests/exprs/tstmtexprs.nim @@ -4,7 +4,8 @@ discard """ 1244 6 abcdefghijklmnopqrstuvwxyz -145 23''' +145 23 +3''' """ import strutils @@ -92,3 +93,32 @@ proc parseResponse(): PJsonNode = #bug #992 var se = @[1,2] let b = (se[1] = 1; 1) + + +# bug #1161 + +type + PFooBase = ref object of PObject + field: int + + PFoo[T] = ref object of PFooBase + field2: T + +var testIf = + if true: + 2 + else: + 3 + +var testCase = + case 8 + of 8: 9 + else: 10 + +var testTry = + try: + PFoo[string](field: 3, field2: "asfasf") + except: + PFooBase(field: 5) + +echo(testTry.field) diff --git a/tests/generics/mdotlookup.nim b/tests/generics/mdotlookup.nim new file mode 100644 index 000000000..7a5e0ccbf --- /dev/null +++ b/tests/generics/mdotlookup.nim @@ -0,0 +1,8 @@ +proc baz(o: any): int = 5 # if bar is exported, it works + +type MyObj = object + x: int + +proc foo*(b: any) = + var o: MyObj + echo b.baz, " ", o.x.baz, " ", b.baz() diff --git a/tests/generics/tdotlookup.nim b/tests/generics/tdotlookup.nim new file mode 100644 index 000000000..b886cd8c9 --- /dev/null +++ b/tests/generics/tdotlookup.nim @@ -0,0 +1,7 @@ +discard """ + output: '''5 5 5''' +""" + +import mdotlookup + +foo(7) diff --git a/tests/macros/tbindsym.nim b/tests/macros/tbindsym.nim new file mode 100644 index 000000000..e1e3b5112 --- /dev/null +++ b/tests/macros/tbindsym.nim @@ -0,0 +1,25 @@ +discard """ + output: '''TFoo +TBar''' +""" + +# bug #1319 + +import macros + +type + TTextKind = enum + TFoo, TBar + +macro test: stmt = + var x = @[TFoo, TBar] + result = newStmtList() + for i in x: + result.add newCall(newIdentNode("echo"), + case i + of TFoo: + bindSym("TFoo") + of TBar: + bindSym("TBar")) + +test() diff --git a/tests/macros/tbugs.nim b/tests/macros/tbugs.nim new file mode 100644 index 000000000..3db851dd1 --- /dev/null +++ b/tests/macros/tbugs.nim @@ -0,0 +1,90 @@ +discard """ +msg: '''a +s +d +f +TTaa +TTaa +TTaa +TTaa +true +true +nil''' + +output: '''test +2''' +""" + +type + Foo = object + s: char + +iterator test2(f: string): Foo = + for i in f: + yield Foo(s: i) + +macro test(): stmt = + for i in test2("asdf"): + echo i.s + +test() + + +# bug 1297 + +import macros + +type TType = tuple[s: string] + +macro echotest(): stmt = + var t: TType + t.s = "" + t.s.add("test") + result = newCall(newIdentNode("echo"), newStrLitNode(t.s)) + +echotest() + +# bug #1103 + +type + Td = tuple + a:string + b:int + +proc get_data(d: Td) : string {.compileTime.} = + result = d.a # Works if a literal string is used here. + # Bugs if line A or B is active. Works with C + result &= "aa" # A + #result.add("aa") # B + #result = result & "aa" # C + +macro m(s:static[Td]) : stmt = + echo get_data(s) + echo get_data(s) + result = newEmptyNode() + +const s=("TT", 3) +m(s) +m(s) + +# bug #933 + +proc nilcheck(): PNimrodNode {.compileTime.} = + echo(result == nil) # true + echo(result.isNil) # true + echo(repr(result)) # nil + +macro testnilcheck(): stmt = + result = newNimNode(nnkStmtList) + discard nilcheck() + +testnilcheck() + +# bug #1323 + +proc calc(): array[1, int] = + result[0].inc() + result[0].inc() + +const c = calc() +echo c[0] diff --git a/tests/macros/tdumptree.nim b/tests/macros/tdumptree.nim index 5299a94e3..e5160b7ba 100644 --- a/tests/macros/tdumptree.nim +++ b/tests/macros/tdumptree.nim @@ -1,6 +1,5 @@ discard """ -disabled: true -output: '''StmtList +msg: '''StmtList VarSection IdentDefs Ident !"x" diff --git a/tests/macros/tgentemplates.nim b/tests/macros/tgentemplates.nim new file mode 100644 index 000000000..a7727c597 --- /dev/null +++ b/tests/macros/tgentemplates.nim @@ -0,0 +1,35 @@ +# bug #1140 + +import parseutils, macros + +proc parse_until_symbol(node: PNimrodNode, value: string, index: var int): bool {.compiletime.} = + var splitValue: string + var read = value.parseUntil(splitValue, '$', index) + + # when false: + if false: + var identifier: string + read = value.parseWhile(identifier, {}, index) + node.add newCall("add", ident("result"), newCall("$", ident(identifier))) + + if splitValue.len > 0: + node.insert node.len, newCall("add", ident("result"), newStrLitNode(splitValue)) + +proc parse_template(node: PNimrodNode, value: string) {.compiletime.} = + var index = 0 + while index < value.len and + parse_until_symbol(node, value, index): discard + +macro tmpli*(body: expr): stmt = + result = newStmtList() + result.add parseExpr("result = \"\"") + result.parse_template body[1].strVal + + +proc actual: string = tmpli html""" + <p>Test!</p> + """ + +proc another: string = tmpli html""" + <p>what</p> + """ diff --git a/tests/metatype/tautoproc.nim b/tests/metatype/tautoproc.nim new file mode 100644 index 000000000..9e8ff0bcb --- /dev/null +++ b/tests/metatype/tautoproc.nim @@ -0,0 +1,16 @@ +# bug #898 + +proc measureTime(e: auto) = + discard + +proc generate(a: int): void = + discard + +proc runExample = + var builder: int = 0 + + measureTime: + builder.generate() + +measureTime: + discard diff --git a/tests/misc/tbug1217bracketquotes.nim b/tests/misc/tbug1217bracketquotes.nim new file mode 100644 index 000000000..90e67d45b --- /dev/null +++ b/tests/misc/tbug1217bracketquotes.nim @@ -0,0 +1,14 @@ +discard """ + output: "13{(.{}}{*4&*$**()&*@1235" +""" + +type + Test = enum + `1`, `3`, `{`, `(.`, `{}}{`, `*4&*$**()&*@` + +let `.}` = 1 +let `(}` = 2 +let `[` = 3 +let `]` = 5 + +echo `1`, `3`, `{`, `(.`, `{}}{`, `*4&*$**()&*@`, `.}`, `(}`, `[`, `]` diff --git a/tests/notnil/tnotnil4.nim b/tests/notnil/tnotnil4.nim new file mode 100644 index 000000000..23968ee48 --- /dev/null +++ b/tests/notnil/tnotnil4.nim @@ -0,0 +1,14 @@ +discard "" +type + TObj = ref object + +proc check(a: TObj not nil) = + echo repr(a) + +proc doit() = + var x : array[0..1, TObj] + + if x[0] != nil: + check(x[0]) + +doit() \ No newline at end of file diff --git a/tests/objects/tobjconstr2.nim b/tests/objects/tobjconstr2.nim index cb47e146d..8ef7004e4 100644 --- a/tests/objects/tobjconstr2.nim +++ b/tests/objects/tobjconstr2.nim @@ -20,3 +20,15 @@ type var a = Bar(y: 100, x: 200) # works var b = Bar(x: 100, y: 200) # used to fail + +# bug 1275 + +type + Graphic = object of TObject + case kind: range[0..1] + of 0: + radius: float + of 1: + size: tuple[w, h: float] + +var d = Graphic(kind: 1, size: (12.9, 6.9)) diff --git a/tests/osproc/ta.nim b/tests/osproc/ta.nim new file mode 100644 index 000000000..6c1495590 --- /dev/null +++ b/tests/osproc/ta.nim @@ -0,0 +1,3 @@ +import strutils +let x = stdin.readLine() +echo x.parseInt + 5 \ No newline at end of file diff --git a/tests/osproc/tstdin.nim b/tests/osproc/tstdin.nim new file mode 100644 index 000000000..2ea939992 --- /dev/null +++ b/tests/osproc/tstdin.nim @@ -0,0 +1,16 @@ +discard """ + file: "tstdin.nim" + output: "10" +""" +import osproc, os, streams + +doAssert fileExists(getCurrentDir() / "tests" / "osproc" / "ta.exe") + +var p = startProcess("ta.exe", getCurrentDir() / "tests" / "osproc") +p.inputStream.write("5\n") +while true: + let line = p.outputStream.readLine() + if line != "": + echo line + else: + break \ No newline at end of file diff --git a/tests/parallel/nimrod.cfg b/tests/parallel/nimrod.cfg new file mode 100644 index 000000000..b81c89721 --- /dev/null +++ b/tests/parallel/nimrod.cfg @@ -0,0 +1 @@ +threads:on diff --git a/tests/parallel/tdisjoint_slice1.nim b/tests/parallel/tdisjoint_slice1.nim new file mode 100644 index 000000000..c1d0e52f8 --- /dev/null +++ b/tests/parallel/tdisjoint_slice1.nim @@ -0,0 +1,21 @@ +discard """ + outputsub: "EVEN 28" +""" + +import threadpool + +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 + +main() diff --git a/tests/parallel/tdisjoint_slice2.nim b/tests/parallel/tdisjoint_slice2.nim new file mode 100644 index 000000000..1e86ea644 --- /dev/null +++ b/tests/parallel/tdisjoint_slice2.nim @@ -0,0 +1,33 @@ +discard """ + output: '''0 +1 +2 +3 +4 +5 +6 +7 +8''' + sortoutput: true +""" + +import threadpool + +proc f(a: openArray[int]) = + for x in a: echo x + +proc f(a: int) = 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 new file mode 100644 index 000000000..77fab14b5 --- /dev/null +++ b/tests/parallel/tflowvar.nim @@ -0,0 +1,17 @@ +discard """ + output: '''foobarfoobarbazbearbazbear''' + cmd: "nimrod $target --threads:on $options $file" +""" + +import threadpool + +proc computeSomething(a, b: string): string = a & b & a & b + +proc main = + let fvA = spawn computeSomething("foo", "bar") + let fvB = spawn computeSomething("baz", "bear") + + echo(^fvA, ^fvB) + +main() +sync() diff --git a/tests/parallel/tforstmt.nim b/tests/parallel/tforstmt.nim new file mode 100644 index 000000000..58de833f3 --- /dev/null +++ b/tests/parallel/tforstmt.nim @@ -0,0 +1,25 @@ +discard """ + output: '''3 +4 +5 +6 +7''' + sortoutput: true +""" + +import threadpool, os + +proc p(x: int) = + os.sleep(100 - x*10) + echo x + +proc testFor(a, b: int; foo: var openArray[int]) = + parallel: + for i in max(a, 0) .. min(b, foo.high): + spawn p(foo[i]) + +var arr = [0, 1, 2, 3, 4, 5, 6, 7] + +testFor(3, 10, arr) + + diff --git a/tests/parallel/tinvalid_array_bounds.nim b/tests/parallel/tinvalid_array_bounds.nim new file mode 100644 index 000000000..4c6065fd6 --- /dev/null +++ b/tests/parallel/tinvalid_array_bounds.nim @@ -0,0 +1,25 @@ +discard """ + errormsg: "can prove: i + 1 > 30" + line: 21 +""" + +import threadpool + +proc f(a: openArray[int]) = + for x in a: echo x + +proc f(a: int) = echo a + +proc main() = + var a: array[0..30, int] + parallel: + spawn f(a[0..15]) + spawn f(a[16..30]) + var i = 0 + while i <= 30: + spawn f(a[i]) + spawn f(a[i+1]) + inc i + #inc i # inc i, 2 would be correct here + +main() diff --git a/tests/parallel/tinvalid_counter_usage.nim b/tests/parallel/tinvalid_counter_usage.nim new file mode 100644 index 000000000..c6303c651 --- /dev/null +++ b/tests/parallel/tinvalid_counter_usage.nim @@ -0,0 +1,26 @@ +discard """ + errormsg: "invalid usage of counter after increment" + line: 21 +""" + +import threadpool + +proc f(a: openArray[int]) = + for x in a: echo x + +proc f(a: int) = echo a + +proc main() = + var a: array[0..30, int] + parallel: + spawn f(a[0..15]) + spawn f(a[16..30]) + var i = 0 + while i <= 30: + inc i + spawn f(a[i]) + inc i + #spawn f(a[i+1]) + #inc i # inc i, 2 would be correct here + +main() diff --git a/tests/parallel/tnon_disjoint_slice1.nim b/tests/parallel/tnon_disjoint_slice1.nim new file mode 100644 index 000000000..72d008bbd --- /dev/null +++ b/tests/parallel/tnon_disjoint_slice1.nim @@ -0,0 +1,25 @@ +discard """ + errormsg: "cannot prove (i)..(i) disjoint from (i + 1)..(i + 1)" + line: 20 +""" + +import threadpool + +proc f(a: openArray[int]) = + for x in a: echo x + +proc f(a: int) = echo a + +proc main() = + var a: array[0..30, int] + parallel: + #spawn f(a[0..15]) + #spawn f(a[16..30]) + var i = 0 + while i <= 29: + spawn f(a[i]) + spawn f(a[i+1]) + inc i + #inc i # inc i, 2 would be correct here + +main() diff --git a/tests/parallel/tpi.nim b/tests/parallel/tpi.nim new file mode 100644 index 000000000..dcb9b8fc5 --- /dev/null +++ b/tests/parallel/tpi.nim @@ -0,0 +1,26 @@ +discard """ + output: '''3.141792613595791 +3.141792613595791''' +""" + +import strutils, math, threadpool + +proc term(k: float): float = 4 * math.pow(-1, k) / (2*k + 1) + +proc piU(n: int): float = + var ch = newSeq[FlowVar[float]](n+1) + for k in 0..n: + ch[k] = spawn term(float(k)) + for k in 0..n: + result += ^ch[k] + +proc piS(n: int): float = + var ch = newSeq[float](n+1) + parallel: + for k in 0..ch.high: + ch[k] = spawn term(float(k)) + for k in 0..ch.high: + result += ch[k] + +echo formatFloat(piU(5000)) +echo formatFloat(piS(5000)) diff --git a/tests/parallel/tsysspawn.nim b/tests/parallel/tsysspawn.nim new file mode 100644 index 000000000..fc7921b0e --- /dev/null +++ b/tests/parallel/tsysspawn.nim @@ -0,0 +1,31 @@ +discard """ + output: '''4 +8''' + cmd: "nimrod $target --threads:on $options $file" +""" + +import threadpool + +var + x, y = 0 + +proc p1 = + for i in 0 .. 10_000: + discard + + atomicInc x + +proc p2 = + for i in 0 .. 10_000: + discard + + atomicInc y, 2 + +for i in 0.. 3: + spawn(p1()) + spawn(p2()) + +sync() + +echo x +echo y diff --git a/tests/parallel/tsysspawnbadarg.nim b/tests/parallel/tsysspawnbadarg.nim new file mode 100644 index 000000000..ad798a7d3 --- /dev/null +++ b/tests/parallel/tsysspawnbadarg.nim @@ -0,0 +1,9 @@ +discard """ + line: 9 + errormsg: "'spawn' takes a call expression" + cmd: "nimrod $target --threads:on $options $file" +""" + +import threadpool + +let foo = spawn(1) diff --git a/tests/seq/tsequtils.nim b/tests/seq/tsequtils.nim index 7bc15ef9c..3a7eeeffa 100644 --- a/tests/seq/tsequtils.nim +++ b/tests/seq/tsequtils.nim @@ -50,6 +50,6 @@ var concatseq = concat(seq1,seq2) echo "Concat: ", $$(concatseq) var seq3 = @[1,2,3,4,5,5,5,7] -var discntseq = distnct(seq3) -echo "Distnct: ", $$(discntseq) +var dedupseq = deduplicate(seq3) +echo "Deduplicate: ", $$(dedupseq) diff --git a/tests/sets/tsets3.nim b/tests/sets/tsets3.nim new file mode 100644 index 000000000..d2b15d72d --- /dev/null +++ b/tests/sets/tsets3.nim @@ -0,0 +1,81 @@ +include sets + +let + s1: TSet[int] = toSet([1, 2, 4, 8, 16]) + s2: TSet[int] = toSet([1, 2, 3, 5, 8]) + s3: TSet[int] = toSet([3, 5, 7]) + +block union: + let + s1_s2 = union(s1, s2) + s1_s3 = s1 + s3 + s2_s3 = s2 + s3 + + assert s1_s2.len == 7 + assert s1_s3.len == 8 + assert s2_s3.len == 6 + + for i in s1: + assert i in s1_s2 + assert i in s1_s3 + for i in s2: + assert i in s1_s2 + assert i in s2_s3 + for i in s3: + assert i in s1_s3 + assert i in s2_s3 + + assert((s1 + s1) == s1) + assert((s2 + s1) == s1_s2) + +block intersection: + let + s1_s2 = intersection(s1, s2) + s1_s3 = intersection(s1, s3) + s2_s3 = s2 * s3 + + assert s1_s2.len == 3 + assert s1_s3.len == 0 + assert s2_s3.len == 2 + + for i in s1_s2: + assert i in s1 + assert i in s2 + for i in s1_s3: + assert i in s1 + assert i in s3 + for i in s2_s3: + assert i in s2 + assert i in s3 + + assert((s2 * s2) == s2) + assert((s3 * s2) == s2_s3) + +block symmetricDifference: + let + s1_s2 = symmetricDifference(s1, s2) + s1_s3 = s1 -+- s3 + s2_s3 = s2 -+- s3 + + assert s1_s2.len == 4 + assert s1_s3.len == 8 + assert 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 + for i in s2: + assert i in s1_s2 xor i in s1 + assert 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 + + assert((s3 -+- s3) == initSet[int]()) + assert((s3 -+- s1) == s1_s3) + +block disjoint: + assert(not disjoint(s1, s2)) + assert disjoint(s1, s3) + assert(not disjoint(s2, s3)) + assert(not disjoint(s2, s2)) \ No newline at end of file diff --git a/tests/system/tsysspawnbadarg.nim b/tests/system/tsysspawnbadarg.nim deleted file mode 100644 index ace074602..000000000 --- a/tests/system/tsysspawnbadarg.nim +++ /dev/null @@ -1,7 +0,0 @@ -discard """ - line: 7 - errormsg: "'spawn' takes a call expression of type void" - cmd: "nimrod $target --threads:on $options $file" -""" - -spawn(1) diff --git a/tests/table/ptables.nim b/tests/table/ptables.nim new file mode 100644 index 000000000..ec52d08c3 --- /dev/null +++ b/tests/table/ptables.nim @@ -0,0 +1,128 @@ +discard """ + output: '''true''' +""" + +import hashes, tables + +const + data = { + "34": 123456, "12": 789, + "90": 343, "0": 34404, + "1": 344004, "2": 344774, + "3": 342244, "4": 3412344, + "5": 341232144, "6": 34214544, + "7": 3434544, "8": 344544, + "9": 34435644, "---00": 346677844, + "10": 34484, "11": 34474, "19": 34464, + "20": 34454, "30": 34141244, "40": 344114, + "50": 344490, "60": 344491, "70": 344492, + "80": 344497} + + sorteddata = { + "---00": 346677844, + "0": 34404, + "1": 344004, + "10": 34484, + "11": 34474, + "12": 789, + "19": 34464, + "2": 344774, "20": 34454, + "3": 342244, "30": 34141244, + "34": 123456, + "4": 3412344, "40": 344114, + "5": 341232144, "50": 344490, + "6": 34214544, "60": 344491, + "7": 3434544, "70": 344492, + "8": 344544, "80": 344497, + "9": 34435644, + "90": 343} + +block tableTest1: + var t = newTable[tuple[x, y: int], string]() + t[(0,0)] = "00" + t[(1,0)] = "10" + t[(0,1)] = "01" + t[(1,1)] = "11" + for x in 0..1: + for y in 0..1: + assert t[(x,y)] == $x & $y + assert($t == + "{(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]() + t["test"] = 1.2345 + t["111"] = 1.000043 + t["123"] = 1.23 + t.del("111") + + t["012"] = 67.9 + t["123"] = 1.5 # test overwriting + + assert t["123"] == 1.5 + assert t["111"] == 0.0 # deleted + assert(not hasKey(t, "111")) + + for key, val in items(data): t[key] = val.toFloat + for key, val in items(data): assert 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 + 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] + inc(i) + + for key, val in mpairs(t): val = 99 + for val in mvalues(t): assert val == 99 + +block countTableTest1: + var s = data.toTable + var t = newCountTable[string]() + for k in s.Keys: t.inc(k) + for k in t.keys: assert t[k] == 1 + t.inc("90", 3) + t.inc("12", 2) + t.inc("34", 1) + assert 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 + else: break + inc i + +block SyntaxTest: + var x = newTable[int, string]({:}) + +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 + 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: + for key, val in pairs(t): + doAssert key == sorteddata[i][0] + doAssert val == sorteddata[i][1] + inc(i) + + # check that lookup still works: + for key, val in pairs(t): + doAssert val == t[key] + # check that insert still works: + t["newKeyHere"] = 80 + + +orderedTableSortTest() +echo "true" + diff --git a/tests/table/ptables2.nim b/tests/table/ptables2.nim new file mode 100644 index 000000000..939de2b84 --- /dev/null +++ b/tests/table/ptables2.nim @@ -0,0 +1,20 @@ +discard """ + output: '''true''' +""" + +import tables + +proc TestHashIntInt() = + var tab = newTable[int,int]() + for i in 1..1_000_000: + tab[i] = i + for i in 1..1_000_000: + 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() + +run1() +echo "true" diff --git a/tests/template/annotate.nim b/tests/template/annotate.nim new file mode 100644 index 000000000..fa58030dc --- /dev/null +++ b/tests/template/annotate.nim @@ -0,0 +1,113 @@ +import macros, parseutils + +# Generate tags +macro make(names: openarray[expr]): stmt {.immediate.} = + result = newStmtList() + + for i in 0 .. names.len-1: + result.add newProc( + name = ident($names[i]).postfix("*"), + params = [ + ident("string"), + newIdentDefs( + ident("content"), + ident("string") + ) + ], + body = newStmtList( + parseStmt("reindent(content)") + ) + ) + + +iterator lines(value: string): string = + var i = 0 + while i < value.len: + var line: string + inc(i, value.parseUntil(line, 0x0A.char, i) + 1) + yield line + + +proc reindent*(value: string, preset_indent = 0): string = + var indent = -1 + + # Detect indentation! + for ln in lines(value): + var read = ln.skipWhitespace() + + # If the line is empty, ignore it for indentation + if read == ln.len: continue + + indent = if indent < 0: read + else: min(indent, read) + + # Create a precursor indent as-needed + var precursor = newString(0) + for i in 1 .. preset_indent: + precursor.add(' ') + + # Re-indent + result = newString(0) + + for ln in lines(value): + var value = ln.substr(indent) + + result.add(precursor) + + if value.len > 0: + result.add(value) + result.add(0x0A.char) + + return result + + +#Define tags +make([ html, xml, glsl, js, css, rst ]) + + +when isMainModule: + ## Test tags + + const script = js""" + var x = 5; + console.log(x.toString()); + """ + + const styles = css""" + .someRule { + width: 500px; + } + """ + + const body = html""" + <ul> + <li>1</li> + <li>2</li> + <li> + <a hef="#google">google</a> + </li> + </ul> + """ + + const info = xml""" + <item> + <i>1</i> + <i>2</i> + </item> + """ + + const shader = glsl""" + void main() + { + gl_Position = gl_ProjectionMatrix + * gl_ModelViewMatrix + * gl_Vertex; + } + """ + + + echo script + echo styles + echo body + echo info + echo shader \ No newline at end of file diff --git a/tests/template/otests.nim b/tests/template/otests.nim new file mode 100644 index 000000000..c885e23df --- /dev/null +++ b/tests/template/otests.nim @@ -0,0 +1,219 @@ +# Fields +const x = 5 + + +# Test substring +static: + assert "test".substring(3) == "t" + assert "test".substring(2,1) == "s" + assert "test".substring(3,2) == "t" + assert "test".substring(1,2) == "es" + + +# Various parsing tests +when true: + + block: #no_substitution + proc actual: string = tmpli html""" + <p>Test!</p> + """ + const expected = html""" + <p>Test!</p> + """ + doAssert actual() == expected + + block: #basic + proc actual: string = tmpli html""" + <p>Test $$x</p> + $x + """ + const expected = html""" + <p>Test $x</p> + 5 + """ + doAssert actual() == expected + + block: #expression + proc actual: string = tmpli html""" + <p>Test $$(x * 5)</p> + $(x * 5) + """ + const expected = html""" + <p>Test $(x * 5)</p> + 25 + """ + doAssert actual() == expected + + block: #escape + proc actual: string = tmpli js""" + [{ + "hello world" + }] + """ + const expected = js""" + [{ + "hello world" + }] + """ + doAssert actual() == expected + + block: #forIn + proc actual: string = tmpli html""" + <p>Test for</p> + <ul> + $for y in 0..2 { + <li>$y</li> + } + </ul> + """ + const expected = html""" + <p>Test for</p> + <ul> + <li>0</li> + <li>1</li> + <li>2</li> + </ul> + """ + doAssert actual() == expected + + block: #while + proc actual: string = tmpli html""" + <p>Test while/stmt</p> + <ul> + ${ var y = 0 } + $while y < 4 { + <li>$y</li> + ${ inc(y) } + } + </ul> + """ + const expected = html""" + <p>Test while/stmt</p> + <ul> + <li>0</li> + <li>1</li> + <li>2</li> + <li>3</li> + </ul> + """ + doAssert actual() == expected + + block: #ifElifElse + proc actual: string = tmpli html""" + <p>Test if/elif/else</p> + $if x == 8 { + <div>x is 8!</div> + } + $elif x == 7 { + <div>x is 7!</div> + } + $else { + <div>x is neither!</div> + } + """ + const expected = html""" + <p>Test if/elif/else</p> + <div>x is neither!</div> + """ + doAssert actual() == expected + + block: #multiLineStatements + proc actual: string = tmpli html""" + <p>Test multiline statements</p> + ${ + var x = 5 + var y = 7 + } + <span>$x</span><span>$y</span> + """ + const expected = html""" + <p>Test multiline statements</p> + <span>5</span><span>7</span> + """ + doAssert actual() == expected + + block: #caseOfElse + proc actual: string = tmpli html""" + <p>Test case</p> + $case x + $of 5 { + <div>x == 5</div> + } + $of 6 { + <div>x == 6</div> + } + $else {} + """ + const expected = html""" + <p>Test case</p> + <div>x == 5</div> + """ + doAssert actual() == expected + + + +when true: #embeddingTest + proc no_substitution: string = tmpli html""" + <h1>Template test!</h1> + """ + + # # Single variable substitution + proc substitution(who = "nobody"): string = tmpli html""" + <div id="greeting">hello $who!</div> + """ + + # Expression template + proc test_expression(nums: openarray[int] = []): string = + var i = 2 + tmpli html""" + $(no_substitution()) + $(substitution("Billy")) + <div id="age">Age: $($nums[i] & "!!")</div> + """ + + proc test_statements(nums: openarray[int] = []): string = + tmpli html""" + $(test_expression(nums)) + $if true { + <ul> + $for i in nums { + <li>$(i * 2)</li> + } + </ul> + } + """ + + var actual = test_statements([0,1,2]) + const expected = html""" + <h1>Template test!</h1> + <div id="greeting">hello Billy!</div> + <div id="age">Age: 2!!</div> + <ul> + <li>0</li> + <li>2</li> + <li>4</li> + </ul> + """ + doAssert actual == expected + + +when defined(future): + block: #tryCatch + proc actual: string = tmpli html""" + <p>Test try/catch</p> + <div> + $try { + <div>Lets try this!</div> + } + $except { + <div>Uh oh!</div> + } + </div> + """ + const expected = html""" + <p>Test try/catch</p> + <div> + <div>Lets try this!</div> + </div> + """ + doAssert actual() == expected \ No newline at end of file diff --git a/tests/template/t_otemplates.nim b/tests/template/t_otemplates.nim new file mode 100644 index 000000000..7de728ab2 --- /dev/null +++ b/tests/template/t_otemplates.nim @@ -0,0 +1,345 @@ +discard """ + output: "Success" +""" + +# Ref: +# http://nimrod-lang.org/macros.html +# http://nimrod-lang.org/parseutils.html + + +# Imports +import tables, parseutils, macros, strutils +import annotate +export annotate + + +# Fields +const identChars = {'a'..'z', 'A'..'Z', '0'..'9', '_'} + + +# Procedure Declarations +proc parse_template(node: PNimrodNode, value: string) {.compiletime.} + + +# Procedure Definitions +proc substring(value: string, index: int, length = -1): string {.compiletime.} = + ## Returns a string at most `length` characters long, starting at `index`. + return if length < 0: value.substr(index) + elif length == 0: "" + else: value.substr(index, index + length-1) + + +proc parse_thru_eol(value: string, index: int): int {.compiletime.} = + ## Reads until and past the end of the current line, unless + ## a non-whitespace character is encountered first + var remainder: string + var read = value.parseUntil(remainder, {0x0A.char}, index) + if remainder.skipWhitespace() == read: + return read + 1 + + +proc trim_after_eol(value: var string) {.compiletime.} = + ## Trims any whitespace at end after \n + var toTrim = 0 + for i in countdown(value.len-1, 0): + # If \n, return + if value[i] in [' ', '\t']: inc(toTrim) + else: break + + if toTrim > 0: + value = value.substring(0, value.len - toTrim) + + +proc trim_eol(value: var string) {.compiletime.} = + ## Removes everything after the last line if it contains nothing but whitespace + for i in countdown(value.len - 1, 0): + # If \n, trim and return + if value[i] == 0x0A.char: + value = value.substr(0, i) + break + + # This is the first character + if i == 0: + value = "" + break + + # Skip change + if not (value[i] in [' ', '\t']): break + + +proc detect_indent(value: string, index: int): int {.compiletime.} = + ## Detects how indented the line at `index` is. + # Seek to the beginning of the line. + var lastChar = index + for i in countdown(index, 0): + if value[i] == 0x0A.char: + # if \n, return the indentation level + return lastChar - i + elif not (value[i] in [' ', '\t']): + # if non-whitespace char, decrement lastChar + dec(lastChar) + + +proc parse_thru_string(value: string, i: var int, strType = '"') {.compiletime.} = + ## Parses until ending " or ' is reached. + inc(i) + if i < value.len-1: + inc(i, value.skipUntil({'\\', strType}, i)) + + +proc parse_to_close(value: string, index: int, open='(', close=')', opened=0): int {.compiletime.} = + ## Reads until all opened braces are closed + ## ignoring any strings "" or '' + var remainder = value.substring(index) + var open_braces = opened + result = 0 + + while result < remainder.len: + var c = remainder[result] + + if c == open: inc(open_braces) + elif c == close: dec(open_braces) + elif c == '"': remainder.parse_thru_string(result) + elif c == '\'': remainder.parse_thru_string(result, '\'') + + if open_braces == 0: break + else: inc(result) + + +iterator parse_stmt_list(value: string, index: var int): string = + ## Parses unguided ${..} block + var read = value.parse_to_close(index, open='{', close='}') + var expressions = value.substring(index + 1, read - 1).split({ ';', 0x0A.char }) + + for expression in expressions: + let value = expression.strip + if value.len > 0: + yield value + + #Increment index & parse thru EOL + inc(index, read + 1) + inc(index, value.parse_thru_eol(index)) + + +iterator parse_compound_statements(value, identifier: string, index: int): string = + ## Parses through several statements, i.e. if {} elif {} else {} + ## and returns the initialization of each as an empty statement + ## i.e. if x == 5 { ... } becomes if x == 5: nil. + + template get_next_ident(expected): stmt = + var nextIdent: string + discard value.parseWhile(nextIdent, {'$'} + identChars, i) + + var next: string + var read: int + + if nextIdent == "case": + # We have to handle case a bit differently + read = value.parseUntil(next, '$', i) + inc(i, read) + yield next.strip(leading=false) & "\n" + + else: + read = value.parseUntil(next, '{', i) + + if nextIdent in expected: + inc(i, read) + # Parse until closing }, then skip whitespace afterwards + read = value.parse_to_close(i, open='{', close='}') + inc(i, read + 1) + inc(i, value.skipWhitespace(i)) + yield next & ": nil\n" + + else: break + + + var i = index + while true: + # Check if next statement would be valid, given the identifier + if identifier in ["if", "when"]: + get_next_ident([identifier, "$elif", "$else"]) + + elif identifier == "case": + get_next_ident(["case", "$of", "$elif", "$else"]) + + elif identifier == "try": + get_next_ident(["try", "$except", "$finally"]) + + +proc parse_complex_stmt(value, identifier: string, index: var int): PNimrodNode {.compiletime.} = + ## Parses if/when/try /elif /else /except /finally statements + + # Build up complex statement string + var stmtString = newString(0) + var numStatements = 0 + for statement in value.parse_compound_statements(identifier, index): + if statement[0] == '$': stmtString.add(statement.substr(1)) + else: stmtString.add(statement) + inc(numStatements) + + # Parse stmt string + result = parseExpr(stmtString) + + var resultIndex = 0 + + # Fast forward a bit if this is a case statement + if identifier == "case": + inc(resultIndex) + + while resultIndex < numStatements: + + # Detect indentation + let indent = detect_indent(value, index) + + # Parse until an open brace `{` + var read = value.skipUntil('{', index) + inc(index, read + 1) + + # Parse through EOL + inc(index, value.parse_thru_eol(index)) + + # Parse through { .. } + read = value.parse_to_close(index, open='{', close='}', opened=1) + + # Add parsed sub-expression into body + var body = newStmtList() + var stmtString = value.substring(index, read) + trim_after_eol(stmtString) + stmtString = reindent(stmtString, indent) + parse_template(body, stmtString) + inc(index, read + 1) + + # Insert body into result + var stmtIndex = macros.high(result[resultIndex]) + result[resultIndex][stmtIndex] = body + + # Parse through EOL again & increment result index + inc(index, value.parse_thru_eol(index)) + inc(resultIndex) + + +proc parse_simple_statement(value: string, index: var int): PNimrodNode {.compiletime.} = + ## Parses for/while + + # Detect indentation + let indent = detect_indent(value, index) + + # Parse until an open brace `{` + var splitValue: string + var read = value.parseUntil(splitValue, '{', index) + result = parseExpr(splitValue & ":nil") + inc(index, read + 1) + + # Parse through EOL + inc(index, value.parse_thru_eol(index)) + + # Parse through { .. } + read = value.parse_to_close(index, open='{', close='}', opened=1) + + # Add parsed sub-expression into body + var body = newStmtList() + var stmtString = value.substring(index, read) + trim_after_eol(stmtString) + stmtString = reindent(stmtString, indent) + parse_template(body, stmtString) + inc(index, read + 1) + + # Insert body into result + var stmtIndex = macros.high(result) + result[stmtIndex] = body + + # Parse through EOL again + inc(index, value.parse_thru_eol(index)) + + +proc parse_until_symbol(node: PNimrodNode, value: string, index: var int): bool {.compiletime.} = + ## Parses a string until a $ symbol is encountered, if + ## two $$'s are encountered in a row, a split will happen + ## removing one of the $'s from the resulting output + var splitValue: string + var read = value.parseUntil(splitValue, '$', index) + var insertionPoint = node.len + + inc(index, read + 1) + if index < value.len: + + case value[index] + of '$': + # Check for duplicate `$`, meaning this is an escaped $ + node.add newCall("add", ident("result"), newStrLitNode("$")) + inc(index) + + of '(': + # Check for open `(`, which means parse as simple single-line expression. + trim_eol(splitValue) + read = value.parse_to_close(index) + 1 + node.add newCall("add", ident("result"), + newCall(bindSym"strip", parseExpr("$" & value.substring(index, read))) + ) + inc(index, read) + + of '{': + # Check for open `{`, which means open statement list + trim_eol(splitValue) + for s in value.parse_stmt_list(index): + node.add parseExpr(s) + + else: + # Otherwise parse while valid `identChars` and make expression w/ $ + var identifier: string + read = value.parseWhile(identifier, identChars, index) + + if identifier in ["for", "while"]: + ## for/while means open simple statement + trim_eol(splitValue) + node.add value.parse_simple_statement(index) + + elif identifier in ["if", "when", "case", "try"]: + ## if/when/case/try means complex statement + trim_eol(splitValue) + node.add value.parse_complex_stmt(identifier, index) + + elif identifier.len > 0: + ## Treat as simple variable + node.add newCall("add", ident("result"), newCall("$", ident(identifier))) + inc(index, read) + + result = true + + # Insert + if splitValue.len > 0: + node.insert insertionPoint, newCall("add", ident("result"), newStrLitNode(splitValue)) + + +proc parse_template(node: PNimrodNode, value: string) = + ## Parses through entire template, outputing valid + ## Nimrod code into the input `node` AST. + var index = 0 + while index < value.len and + parse_until_symbol(node, value, index): nil + + +macro tmpli*(body: expr): stmt = + result = newStmtList() + + result.add parseExpr("result = \"\"") + + var value = if body.kind in nnkStrLit..nnkTripleStrLit: body.strVal + else: body[1].strVal + + parse_template(result, reindent(value)) + + +macro tmpl*(body: expr): stmt = + result = newStmtList() + + var value = if body.kind in nnkStrLit..nnkTripleStrLit: body.strVal + else: body[1].strVal + + parse_template(result, reindent(value)) + + +# Run tests +when isMainModule: + include otests + echo "Success" diff --git a/tests/testament/caasdriver.nim b/tests/testament/caasdriver.nim index 28f0bae9b..ddfe88273 100644 --- a/tests/testament/caasdriver.nim +++ b/tests/testament/caasdriver.nim @@ -25,7 +25,7 @@ const silentReplaceText = "--verbosity:0 --hints:off" var - TesterDir = getAppDir() + TesterDir = getAppDir() / ".." NimrodBin = TesterDir / "../bin/nimrod" proc replaceVars(session: var TNimrodSession, text: string): string = @@ -86,6 +86,10 @@ proc doProcCommand(session: var TNimrodSession, command: string): string = proc doCommand(session: var TNimrodSession, command: string) = if session.mode == CaasRun: + if not session.nim.running: + session.lastOutput = "FAILED TO EXECUTE: " & command & "\n" & + "Exit code " & $session.nim.peekExitCode + return session.lastOutput = doCaasCommand(session, command & " " & session.filename) else: @@ -102,7 +106,7 @@ proc close(session: var TNimrodSession) {.destructor.} = if session.mode == CaasRun: session.nim.close -proc doScenario(script: string, output: PStream, mode: TRunMode): bool = +proc doScenario(script: string, output: PStream, mode: TRunMode, verbose: bool): bool = result = true var f = open(script) @@ -134,7 +138,7 @@ proc doScenario(script: string, output: PStream, mode: TRunMode): bool = continue elif line.startsWith(">"): s.doCommand(line.substr(1).strip) - output.writeln line, "\n", s.lastOutput + output.writeln line, "\n", if verbose: s.lastOutput else: "" else: var expectMatch = true var pattern = s.replaceVars(line) @@ -151,13 +155,14 @@ proc doScenario(script: string, output: PStream, mode: TRunMode): bool = output.writeln "FAILURE ", line result = false -iterator caasTestsRunner*(filter = ""): tuple[test, output: string, - status: bool, mode: TRunMode] = +iterator caasTestsRunner*(filter = "", verbose = false): tuple[test, + output: string, status: bool, + mode: TRunMode] = for scenario in os.walkFiles(TesterDir / "caas/*.txt"): if filter.len > 0 and find(scenario, filter) == -1: continue for mode in modes: var outStream = newStringStream() - let r = doScenario(scenario, outStream, mode) + let r = doScenario(scenario, outStream, mode, verbose) yield (scenario, outStream.data, r, mode) when isMainModule: @@ -175,9 +180,12 @@ when isMainModule: if verbose and len(filter) > 0: echo "Running only test cases matching filter '$1'" % [filter] - for test, output, result, mode in caasTestsRunner(filter): + for test, output, result, mode in caasTestsRunner(filter, verbose): if not result or verbose: - echo test, "\n", output, "-> ", $mode, ":", $result, "\n-----" + echo "Mode ", $mode, " (", if result: "succeeded)" else: "failed)" + echo test + echo output + echo "---------\n" if not result: failures += 1 diff --git a/tests/testament/categories.nim b/tests/testament/categories.nim index bb9c90d2a..841eb8159 100644 --- a/tests/testament/categories.nim +++ b/tests/testament/categories.nim @@ -282,26 +282,33 @@ proc testBabelPackages(r: var TResults, cat: Category, filter: PackageFilter) = echo("[Warning] - Cannot run babel tests: Babel update failed.") return - for name, url in listPackages(filter): - var test = makeTest(name, "", cat) - echo(url) - let - installProcess = startProcess(babelExe, "", ["install", "-y", name]) - installStatus = waitForExitEx(installProcess) - installProcess.close - if installStatus != quitSuccess: - r.addResult(test, "", "", reInstallFailed) - continue + let packageFileTest = makeTest("PackageFileParsed", "", cat) + try: + for name, url in listPackages(filter): + var test = makeTest(name, "", cat) + echo(url) + let + installProcess = startProcess(babelExe, "", ["install", "-y", name]) + installStatus = waitForExitEx(installProcess) + installProcess.close + if installStatus != quitSuccess: + r.addResult(test, "", "", reInstallFailed) + continue + + let + buildPath = getPackageDir(name)[0.. -3] + let + buildProcess = startProcess(babelExe, buildPath, ["build"]) + buildStatus = waitForExitEx(buildProcess) + buildProcess.close + if buildStatus != quitSuccess: + r.addResult(test, "", "", reBuildFailed) + r.addResult(test, "", "", reSuccess) + r.addResult(packageFileTest, "", "", reSuccess) + except EJsonParsingError: + echo("[Warning] - Cannot run babel tests: Invalid package file.") + r.addResult(packageFileTest, "", "", reBuildFailed) - let - buildPath = getPackageDir(name)[0.. -3] - let - buildProcess = startProcess(babelExe, buildPath, ["build"]) - buildStatus = waitForExitEx(buildProcess) - buildProcess.close - if buildStatus != quitSuccess: - r.addResult(test, "", "", reBuildFailed) - r.addResult(test, "", "", reSuccess) # ---------------------------------------------------------------------------- diff --git a/tests/testament/specs.nim b/tests/testament/specs.nim index 225ea1891..6e72f4b5e 100644 --- a/tests/testament/specs.nim +++ b/tests/testament/specs.nim @@ -46,7 +46,7 @@ type msg*: string ccodeCheck*: string err*: TResultEnum - substr*: bool + substr*, sortoutput*: bool targets*: set[TTarget] const @@ -113,6 +113,8 @@ proc parseSpec*(filename: string): TSpec = result.action = actionRun result.outp = e.value result.substr = true + of "sortoutput": + result.sortoutput = parseCfgBool(e.value) of "exitcode": discard parseInt(e.value, result.exitCode) of "msg": diff --git a/tests/testament/tester.nim b/tests/testament/tester.nim index 50d0e6eac..fc6b4ff95 100644 --- a/tests/testament/tester.nim +++ b/tests/testament/tester.nim @@ -11,7 +11,8 @@ import parseutils, strutils, pegs, os, osproc, streams, parsecfg, json, - marshal, backend, parseopt, specs, htmlgen, browsers, terminal + marshal, backend, parseopt, specs, htmlgen, browsers, terminal, + algorithm const resultsFile = "testresults.html" @@ -150,6 +151,11 @@ proc codegenCheck(test: TTest, check: string, given: var TSpec) = except EIO: given.err = reCodeNotFound +proc makeDeterministic(s: string): string = + var x = splitLines(s) + sort(x, system.cmp) + result = join(x, "\n") + proc testSpec(r: var TResults, test: TTest) = # major entry point for a single test let tname = test.name.addFileExt(".nim") @@ -191,8 +197,10 @@ proc testSpec(r: var TResults, test: TTest) = r.addResult(test, "exitcode: " & $expected.exitCode, "exitcode: " & $exitCode, reExitCodesDiffer) else: - if strip(buf.string) != strip(expected.outp): - if not (expected.substr and expected.outp in buf.string): + var bufB = strip(buf.string) + if expected.sortoutput: bufB = makeDeterministic(bufB) + if bufB != strip(expected.outp): + if not (expected.substr and expected.outp in bufB): given.err = reOutputsDiffer if given.err == reSuccess: codeGenCheck(test, expected.ccodeCheck, given) diff --git a/tests/vm/tarrayboundeval.nim b/tests/vm/tarrayboundeval.nim index 9b33a2415..07aac4c4e 100644 --- a/tests/vm/tarrayboundeval.nim +++ b/tests/vm/tarrayboundeval.nim @@ -1,6 +1,7 @@ discard """ output: '''7 -8 8''' +8 8 +-2''' """ #bug 1063 @@ -21,3 +22,10 @@ type internal: array[int((KeyMax + 31)/32), cuint] echo myconst, " ", int((KeyMax + 31) / 32) + +#bug 1304 or something: + +const constArray: array [-3..2, int] = [-3, -2, -1, 0, 1, 2] + +echo constArray[-2] + diff --git a/tests/vm/teval1.nim b/tests/vm/teval1.nim index a02f26592..cdb4ad8e2 100644 --- a/tests/vm/teval1.nim +++ b/tests/vm/teval1.nim @@ -16,4 +16,9 @@ const echo "##", x, "##" +# bug #1310 +static: + var i, j: set[int8] = {} + var k = i + j + diff --git a/tinyc/tests/gcctestsuite.sh b/tinyc/tests/gcctestsuite.sh index bd9204b2b..bd9204b2b 100755..100644 --- a/tinyc/tests/gcctestsuite.sh +++ b/tinyc/tests/gcctestsuite.sh diff --git a/tinyc/texi2pod.pl b/tinyc/texi2pod.pl index d86e176f1..d86e176f1 100755..100644 --- a/tinyc/texi2pod.pl +++ b/tinyc/texi2pod.pl diff --git a/todo.txt b/todo.txt index bc7c7979a..d1387669d 100644 --- a/todo.txt +++ b/todo.txt @@ -1,6 +1,40 @@ -version 0.9.4 +version 0.9.6 ============= +- scopes are still broken for generic instantiation! +- integrate the new LL into the devel branch +- start experimental branch + +Concurrency +----------- + +- 'gcsafe' inferrence needs to be fixed +- the disjoint checker needs to deal with 'a = spawn f(); g = spawn f()' +- implement 'deepCopy' builtin +- implement 'foo[1..4] = spawn(f[4..7])' +- support for exception propagation +- Minor: The copying of the 'ref Promise' into the thead local storage only + happens to work due to the write barrier's implementation +- implement lock levels --> first without the more complex race avoidance +- document the new 'spawn' and 'parallel' statements + + +Misc +---- + +- fix the bug that keeps 'defer' template from working +- make '--implicitStatic:on' the default +- fix the tuple unpacking in lambda bug +- make tuple unpacking work in a non-var/let context +- special rule for ``[]=`` +- ``=`` should be overloadable; requires specialization for ``=``; general + lift mechanism in the compiler is already implemented for 'fields' +- built-in 'getImpl' +- type API for macros; make 'spawn' a macro +- markAndSweepGC should expose an API for fibers +- prevent 'alloc(TypeWithGCedMemory)' +- some table related tests are wrong (memory usage checks) + Bugs ==== @@ -16,7 +50,6 @@ Bugs version 0.9.x ============= -- fix the bug that keeps 'defer' template from working - pragmas need 'bindSym' support - pragmas need re-work: 'push' is dangerous, 'hasPragma' does not work reliably with user-defined pragmas @@ -28,18 +61,10 @@ version 0.9.x - ensure (ref T)(a, b) works as a type conversion and type constructor - optimize 'genericReset'; 'newException' leads to code bloat - stack-less GC -- make '--implicitStatic:on' the default - implicit deref for parameter matching -- special rule for ``[]=`` -- ``=`` should be overloadable; requires specialization for ``=``; general - lift mechanism in the compiler is already implemented for 'fields' -- built-in 'getImpl' - VM: optimize opcAsgnStr -- change comment handling in the AST; that's lots of work as c2nim and pas2nim - make use of the fact every node can have a comment! - version 0.9.X ============= @@ -111,10 +136,6 @@ GC - precise stack marking; embrace C++ code generation for that - marker procs for Boehm GC - hybrid GC -- GC: implement simple generational GC - * first version: mark black in write barrier - * second version: introduce fake roots instead of marking black - * third version: find some clever heuristic which is preferable - acyclic vs prunable; introduce GC hints - use big blocks in the allocator - object pooling support for *hard* realtime systems @@ -139,7 +160,6 @@ Not essential for 1.0.0 - implement the "snoopResult" pragma; no, make a strutils with string append semantics instead ... - implement "closure tuple consists of a single 'ref'" optimization -- optimize method dispatchers - new feature: ``distinct T with operations`` - arglist as a type (iterator chaining); variable length type lists for generics - implement marker procs for message passing diff --git a/tools/trimcc.nim b/tools/trimcc.nim index fd15726a5..6271d2b9a 100644 --- a/tools/trimcc.nim +++ b/tools/trimcc.nim @@ -21,7 +21,7 @@ proc walker(dir: string) = moveFile(dest=path, sourc=newName(path)) of pcDir: walker(path) - else: nil + else: discard if paramCount() == 1: walker(paramStr(1)) diff --git a/tools/website.tmpl b/tools/website.tmpl index bd68bdb06..1d6242736 100644 --- a/tools/website.tmpl +++ b/tools/website.tmpl @@ -71,7 +71,7 @@ </div> <!-- site_foot --> <div id="site_foot"> - <div id="legal">Copyright © 2013 - Andreas Rumpf & Contributors - All rights reserved - <a href="http://reign-studios.com/philipwitte/">Design by Philip Witte</a></div> + <div id="legal">Copyright © 2014 - Andreas Rumpf & Contributors - All rights reserved - <a href="http://reign-studios.com/philipwitte/">Design by Philip Witte</a></div> </div> </div> <script> diff --git a/web/assets/style.css b/web/assets/style.css index 5cee279fc..91bb4bd8a 100644 --- a/web/assets/style.css +++ b/web/assets/style.css @@ -93,7 +93,7 @@ html, body { border-left:10px solid #8f9698; background:#f3f6f8; font-size:15px; - font-family:courier; + font-family:courier, monospace; letter-spacing:0; line-height:17px; } diff --git a/web/babelpkglist.nim b/web/babelpkglist.nim index 378d4ce30..8745c9f99 100644 --- a/web/babelpkglist.nim +++ b/web/babelpkglist.nim @@ -28,13 +28,19 @@ proc processContent(content: string) = officialCount = 0 unofficialList = "" unofficialCount = 0 + let + endings = {'.', '!'} for pkg in jsonArr: assert pkg.kind == JObject let pkgWeb = if pkg.hasKey("web"): pkg["web"].str else: pkg["url"].str - let listItem = li(a(href=pkgWeb, pkg["name"].str), " ", pkg["description"].str) + let + desc = pkg["description"].str + # Review array index access when #1291 is solved. + dot = if desc.high > 0 and desc[<desc.high] in endings: "" else: "." + listItem = li(a(href=pkgWeb, pkg["name"].str), " ", desc & dot) if pkg["url"].str.startsWith("git://github.com/nimrod-code") or "official" in pkg["tags"].elems: officialCount.inc diff --git a/web/download.txt b/web/download.txt index a306e516c..557788217 100644 --- a/web/download.txt +++ b/web/download.txt @@ -1,7 +1,130 @@ +You can download the latest version of the Nimrod compiler here. You can +use the binaries provided or build from source. + +Binaries +======== + +All installers and archives contain the html documentation and tools +(nimgrep, c2nim and babel). + +**Note:** The Nimrod compiler requires a C compiler to compile software. On +Windows we recommend that you use +`Mingw-w64 <http://mingw-w64.sourceforge.net/>`_. GCC is recommended on Linux +and clang on Mac OS X. + +Installers +---------- + +The "full" version includes a full mingw distribution which includes a C +compiler. The "slim" version lacks this. + +* Full (i386, 32bit): `<download/nimrod_0.9.4_windows_i386_full.exe>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: dca7c63d0c1861d2d7c51b2e7a29fa98371750a10ab282d5df9de22a07719c24 + </p> + +* Slim (i386, 32bit): `<download/nimrod_0.9.4_windows_i386_slim.exe>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: c0fcd1201bd20fad1e14b9d2cc2529494057068de1dd01f871cf129f088a8242 + </p> + +* Full (amd64, 64bit): `<download/nimrod_0.9.4_windows_amd64_full.exe>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: af9d478c2f3361e0f238fcb07fa8e7ae5821938c0f9063c6670e925c9ae9d16e + </p> + +* Slim (amd64, 64bit): `<download/nimrod_0.9.4_windows_amd64_slim.exe>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: 90c380721a46be2b9b8d5437187f701940aefc2e1fb9722dbc543f5c5a3bb85e + </p> + +Archives +-------- + +Windows +~~~~~~~ + +The "full" version includes a full mingw distribution which includes a C +compiler. The "slim" version lacks this. + +* Full (i386, 32bit): `<download/nimrod_0.9.4_windows_i386_full.zip>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: 8ee18faaa3a3d5df482c7abd6aa7ea87a350d7328b80ce1e2d486b59a7a93956 + </p> + +* Slim (i386, 32bit): `<download/nimrod_0.9.4_windows_i386_slim.zip>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: 7024fb8ad8f98c0bd4949ae36ed11b52b4e401754bbd62a11199d6dc8628d857 + </p> + +* Full (amd64, 64bit): `<download/nimrod_0.9.4_windows_amd64_full.zip>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: cb33cacc1a84fec771323d24cb6d9795f4803882466a9f417b424990aa49e18a + </p> + +* Slim (amd64, 64bit): `<download/nimrod_0.9.4_windows_amd64_slim.zip>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: fcf877e4bd1ebfa214749af6e4811cd8539af19f1d7b23017e4bd7f6cbfb3eba + </p> + +Linux +~~~~~ + +* Linux (i386, 32bit): `<download/nimrod_0.9.4_linux_i386.tar.gz>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: 79DD337A77AC4313A75F2C5EED8252F00BBBDEB1E0C3504660D4A52EA63DBA92 + </p> +* Linux (amd64, 64bit): `<download/nimrod_0.9.4_linux_amd64.tar.gz>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: 6F6CB3C727BA8059B7605C02942AE7910C20C2A3DC6A8A600D90D50FE61F0D8C + </p> +* Linux (ppc64, 64bit): `<download/nimrod_0.9.4_linux_ppc64.tar.gz>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: 5DAC2D9F7F545929E04540E6E2594C68FC3126A3B2F7B1FA7DBA5E295B4A7D31 + </p> + +Mac OS X +~~~~~~~~ + +* Mac OS X (amd64, 64bit): `<download/nimrod_0.9.4_macosx_amd64.zip>`_ + + .. raw:: html + <p style="font-size: 8pt; margin-top: 0;"> + SHA256: E6F3A8E434DF3E89686F043954C6DFC09ABEBC0FC09D3B9A6B35C2B3102F7C3C + </p> + +If a binary for your platform is not available then you must build from source. +Bleeding edge binaries are available from the `Nimrod build farm <http://build.nimrod-lang.org/>`_. + +Source +====== + Starting with 0.9.4 we now advise people to build directly from the github `master <https://github.com/Araq/Nimrod#compiling>`_ branch:: - git clone git://github.com/Araq/Nimrod.git + git clone -b master git://github.com/Araq/Nimrod.git cd Nimrod git clone --depth 1 git://github.com/nimrod-code/csources cd csources && sh build.sh @@ -9,4 +132,7 @@ github `master <https://github.com/Araq/Nimrod#compiling>`_ branch:: bin/nimrod c koch ./koch boot -d:release -Prebuilt binaries will be available soon. +The ``master`` branch always contains the latest stable version of the compiler. +If you want bleeding edge then switch to the ``devel`` branch and follow +the same instructions outlined above. + diff --git a/web/index.txt b/web/index.txt index e504b65c4..c3459d56b 100644 --- a/web/index.txt +++ b/web/index.txt @@ -90,7 +90,9 @@ Nimrod plays nice with others interfacing.** * There are lots of bindings: for example, bindings to GTK2, the Windows API, the POSIX API, OpenGL, SDL, Cairo, Python, Lua, TCL, X11, libzip, PCRE, - libcurl, mySQL and SQLite are included in the standard distribution. + libcurl, mySQL and SQLite are included in the standard distribution or + can easily be obtained via the + `Babel package manager <https://github.com/nimrod-code/babel>`_. * A C to Nimrod conversion utility: New bindings to C libraries are easily generated by ``c2nim``. @@ -98,6 +100,6 @@ Nimrod plays nice with others Roadmap to 1.0 ============== -Version 0.9.x - * the symbol binding rules for templates will change - * a shared memory garbage collected heap will be provided +Please have a look at +this `wiki page <https://github.com/Araq/Nimrod/wiki/Feature-Matrix>`_ for +an up-to-date overview. diff --git a/web/news.txt b/web/news.txt index fa1c532e8..a3019df51 100644 --- a/web/news.txt +++ b/web/news.txt @@ -2,6 +2,26 @@ News ==== +.. + 2014-06-29 Version 0.9.6 released + ================================= + + Changes affecting backwards compatibility + ----------------------------------------- + + - ``spawn`` now uses an elaborate self-adapting thread pool and as such + has been moved into its own module. So to use it, you now have to import + ``threadpool``. + - The symbol binding rules in generics changed: ``bar`` in ``foo.bar`` is + now considered for implicit early binding. + + + Library Additions + ----------------- + + - Added module ``cpuinfo``. + - Added module ``threadpool``. + - ``sequtils.distnct`` has been renamed to ``sequtils.deduplicate``. 2014-04-21 Version 0.9.4 released @@ -9,13 +29,15 @@ News The Nimrod development community is proud to announce the release of version 0.9.4 of the Nimrod compiler and tools. **Note: This release has to be -considered beta quality! Lots of new features have been implemented but most -do not fullfill our quality standards.** +considered beta quality! Lots of new features have been implemented but +unfortunately some do not fullfill our quality standards yet.** -This release can be downloaded from `github <https://github.com/Araq/Nimrod>`_. -Prebuilt binaries will be available soon. +Prebuilt binaries and instructions for building from source are available +on the `download page <download.html>`_. -This release includes about 1300 changes in total including various bug +This release includes about +`1400 changes <https://github.com/Araq/Nimrod/compare/v0.9.2...v0.9.4>`_ +in total including various bug fixes, new languages features and standard library additions and improvements. This release brings with it support for user-defined type classes, a brand new VM for executing Nimrod code at compile-time and new symbol binding @@ -79,6 +101,8 @@ syntax: var s = @[1, 2, 3, 4, 5] echo(s.map((x: int) => x * 5)) +A list of changes follows, for a comprehensive list of changes take a look +`here <https://github.com/Araq/Nimrod/compare/v0.9.2...v0.9.4>`_. Library Additions ----------------- @@ -93,7 +117,7 @@ Library Additions - Added module ``selectors``. - Added module ``asynchttpserver``. - Added support for the new asynchronous IO in the ``httpclient`` module. -- Added a Python-inspired ``future`` module that feature upcoming additions +- Added a Python-inspired ``future`` module that features upcoming additions to the ``system`` module. diff --git a/web/nimrod.ini b/web/nimrod.ini index 14701ecea..af9ac0cd9 100644 --- a/web/nimrod.ini +++ b/web/nimrod.ini @@ -36,8 +36,8 @@ UNIX. We don't believe this to be a coincidence. - Jeremy S. Anderson.""" [Documentation] -doc: "endb;intern;apis;lib;manual;tut1;tut2;nimrodc;overview;filters;trmacros" -doc: "tools;c2nim;niminst;nimgrep;gc;estp;idetools;docgen" +doc: "endb;intern;apis;lib;manual;tut1;tut2;nimrodc;overview;filters" +doc: "tools;c2nim;niminst;nimgrep;gc;estp;idetools;docgen;koch;backends.txt" pdf: "manual;lib;tut1;tut2;nimrodc;c2nim;niminst;gc" srcdoc2: "system.nim;impure/graphics;wrappers/sdl" srcdoc2: "core/macros;pure/marshal;core/typeinfo;core/unsigned" @@ -64,6 +64,15 @@ srcdoc2: "pure/nimprof;pure/unittest;packages/docutils/highlite" srcdoc2: "packages/docutils/rst;packages/docutils/rstast" srcdoc2: "packages/docutils/rstgen;pure/logging;pure/asyncdispatch;pure/asyncnet" srcdoc2: "pure/rawsockets;pure/asynchttpserver;pure/net;pure/selectors;pure/future" +srcdoc2: "wrappers/expat;wrappers/readline/history" +srcdoc2: "wrappers/libsvm.nim;wrappers/libuv" +srcdoc2: "wrappers/zip/zlib;wrappers/zip/libzip" +srcdoc2: "wrappers/libcurl;pure/md5;wrappers/mysql;wrappers/iup" +srcdoc2: "posix/posix;wrappers/odbcsql" +srcdoc2: "wrappers/tre;wrappers/openssl;wrappers/pcre" +srcdoc2: "wrappers/sqlite3;wrappers/postgres;wrappers/tinyc" +srcdoc2: "wrappers/readline/readline;wrappers/readline/rltypedefs" +srcdoc2: "wrappers/joyent_http_parser" webdoc: "wrappers/libcurl;pure/md5;wrappers/mysql;wrappers/iup" webdoc: "wrappers/sqlite3;wrappers/postgres;wrappers/tinyc" diff --git a/web/ticker.txt b/web/ticker.txt index 691a14575..f06b00572 100644 --- a/web/ticker.txt +++ b/web/ticker.txt @@ -1,4 +1,4 @@ -<a class="news" href="news.html#Z2014-XX-XX-version-0-9-4-released"> +<a class="news" href="news.html#Z2014-04-21-version-0-9-4-released"> <h3>Apr 21, 2014</h3> <p>Nimrod version 0.9.4 has been released!</p> </a> @@ -46,4 +46,4 @@ <a class="news" href="news.html#Z2010-03-14-version-0-8-8-released"> <h3>Mar 14, 2010</h3> <p>Nimrod version 0.8.8 has been released!</p> -</a> \ No newline at end of file +</a> |