summary refs log tree commit diff stats
path: root/rod/syntaxes.nim
blob: b8e4c1837adeaeef8cc340aae82fa96e53b7a88c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
#
#
#           The Nimrod Compiler
#        (c) Copyright 2009 Andreas Rumpf
#
#    See the file "copying.txt", included in this
#    distribution, for details about the copyright.
#

# Implements the dispatcher for the different parsers.

import 
  strutils, llstream, ast, astalgo, idents, scanner, options, msgs, pnimsyn, 
  pbraces, ptmplsyn, filters, rnimsyn

type 
  TFilterKind* = enum 
    filtNone, filtTemplate, filtReplace, filtStrip
  TParserKind* = enum 
    skinStandard, skinBraces, skinEndX

const 
  parserNames*: array[TParserKind, string] = ["standard", "braces", "endx"]
  filterNames*: array[TFilterKind, string] = ["none", "stdtmpl", "replace", 
    "strip"]

type 
  TParsers*{.final.} = object 
    skin*: TParserKind
    parser*: TParser


proc ParseFile*(filename: string): PNode{.procvar.}
proc openParsers*(p: var TParsers, filename: string, inputstream: PLLStream)
proc closeParsers*(p: var TParsers)
proc parseAll*(p: var TParsers): PNode
proc parseTopLevelStmt*(p: var TParsers): PNode
  # implements an iterator. Returns the next top-level statement or nil if end
  # of stream.
# implementation

proc ParseFile(filename: string): PNode = 
  var 
    p: TParsers
    f: tfile
  if not open(f, filename): 
    rawMessage(errCannotOpenFile, filename)
    return 
  OpenParsers(p, filename, LLStreamOpen(f))
  result = ParseAll(p)
  CloseParsers(p)

proc parseAll(p: var TParsers): PNode = 
  case p.skin
  of skinStandard: 
    result = pnimsyn.parseAll(p.parser)
  of skinBraces: 
    result = pbraces.parseAll(p.parser)
  of skinEndX: 
    InternalError("parser to implement") # skinEndX: result := pendx.parseAll(p.parser);
  
proc parseTopLevelStmt(p: var TParsers): PNode = 
  case p.skin
  of skinStandard: 
    result = pnimsyn.parseTopLevelStmt(p.parser)
  of skinBraces: 
    result = pbraces.parseTopLevelStmt(p.parser)
  of skinEndX: 
    InternalError("parser to implement") #skinEndX: result := pendx.parseTopLevelStmt(p.parser);
  
proc UTF8_BOM(s: string): int = 
  if (s[0] == '\xEF') and (s[0 + 1] == '\xBB') and (s[0 + 2] == '\xBF'): 
    result = 3
  else: 
    result = 0
  
proc containsShebang(s: string, i: int): bool = 
  var j: int
  result = false
  if (s[i] == '#') and (s[i + 1] == '!'): 
    j = i + 2
    while s[j] in WhiteSpace: inc(j)
    result = s[j] == '/'

proc parsePipe(filename: string, inputStream: PLLStream): PNode = 
  var 
    line: string
    s: PLLStream
    i: int
    q: TParser
  result = nil
  s = LLStreamOpen(filename, fmRead)
  if s != nil: 
    line = LLStreamReadLine(s)
    i = UTF8_Bom(line) + 0
    if containsShebang(line, i): 
      line = LLStreamReadLine(s)
      i = 0
    if (line[i] == '#') and (line[i + 1] == '!'): 
      inc(i, 2)
      while line[i] in WhiteSpace: inc(i)
      OpenParser(q, filename, LLStreamOpen(copy(line, i)))
      result = pnimsyn.parseAll(q)
      CloseParser(q)
    LLStreamClose(s)

proc getFilter(ident: PIdent): TFilterKind = 
  for i in countup(low(TFilterKind), high(TFilterKind)): 
    if IdentEq(ident, filterNames[i]): 
      return i
  result = filtNone

proc getParser(ident: PIdent): TParserKind = 
  for i in countup(low(TParserKind), high(TParserKind)): 
    if IdentEq(ident, parserNames[i]): 
      return i
  rawMessage(errInvalidDirectiveX, ident.s)

proc getCallee(n: PNode): PIdent = 
  if (n.kind == nkCall) and (n.sons[0].kind == nkIdent): 
    result = n.sons[0].ident
  elif n.kind == nkIdent: 
    result = n.ident
  else: 
    rawMessage(errXNotAllowedHere, renderTree(n))
  
proc applyFilter(p: var TParsers, n: PNode, filename: string, stdin: PLLStream): PLLStream = 
  var 
    ident: PIdent
    f: TFilterKind
  ident = getCallee(n)
  f = getFilter(ident)
  case f
  of filtNone: 
    p.skin = getParser(ident)
    result = stdin
  of filtTemplate: 
    result = filterTmpl(stdin, filename, n)
  of filtStrip: 
    result = filterStrip(stdin, filename, n)
  of filtReplace: 
    result = filterReplace(stdin, filename, n)
  if f != filtNone: 
    if gVerbosity >= 2: 
      rawMessage(hintCodeBegin)
      messageOut(result.s)
      rawMessage(hintCodeEnd)

proc evalPipe(p: var TParsers, n: PNode, filename: string, start: PLLStream): PLLStream = 
  result = start
  if n == nil: return 
  if (n.kind == nkInfix) and (n.sons[0].kind == nkIdent) and
      IdentEq(n.sons[0].ident, "|"): 
    for i in countup(1, 2): 
      if n.sons[i].kind == nkInfix: 
        result = evalPipe(p, n.sons[i], filename, result)
      else: 
        result = applyFilter(p, n.sons[i], filename, result)
  elif n.kind == nkStmtList: 
    result = evalPipe(p, n.sons[0], filename, result)
  else: 
    result = applyFilter(p, n, filename, result)
  
proc openParsers(p: var TParsers, filename: string, inputstream: PLLStream) = 
  var 
    pipe: PNode
    s: PLLStream
  p.skin = skinStandard
  pipe = parsePipe(filename, inputStream)
  if pipe != nil: s = evalPipe(p, pipe, filename, inputStream)
  else: s = inputStream
  case p.skin
  of skinStandard, skinBraces, skinEndX: pnimsyn.openParser(p.parser, filename, 
      s)
  
proc closeParsers(p: var TParsers) = 
  pnimsyn.closeParser(p.parser)
>:danger " & args) proc buildVccTool(args: string) = nimCompileFold("Compile Vcc", "tools/vccexe/vccexe.nim ", options = args) proc bundleWinTools(args: string) = nimCompile("tools/finish.nim", outputDir = "", options = args) buildVccTool(args) nimCompile("tools/nimgrab.nim", options = "-d:ssl " & args) nimCompile("tools/nimgrep.nim", options = args) bundleC2nim(args) nimCompile("testament/testament.nim", options = args) when false: # not yet a tool worth including nimCompile(r"tools\downloader.nim", options = r"--cc:vcc --app:gui -d:ssl --noNimblePath --path:..\ui " & args) proc zip(latest: bool; args: string) = bundleNimbleExe(latest, args) bundleNimsuggest(args) bundleWinTools(args) nimexec("cc -r $2 --var:version=$1 --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini" % [VersionAsString, compileNimInst]) exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim zip compiler/installer.ini" % ["tools/niminst/niminst".exe, VersionAsString]) proc ensureCleanGit() = let (outp, status) = osproc.execCmdEx("git diff") if outp.len != 0: quit "Not a clean git repository; 'git diff' not empty!" if status != 0: quit "Not a clean git repository; 'git diff' returned non-zero!" proc xz(latest: bool; args: string) = ensureCleanGit() nimexec("cc -r $2 --var:version=$1 --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini" % [VersionAsString, compileNimInst]) exec("$# --var:version=$# --var:mingw=none --main:compiler/nim.nim xz compiler/installer.ini" % ["tools" / "niminst" / "niminst".exe, VersionAsString]) proc buildTool(toolname, args: string) = nimexec("cc $# $#" % [args, toolname]) copyFile(dest="bin" / splitFile(toolname).name.exe, source=toolname.exe) proc buildTools(args: string = "") = bundleNimsuggest(args) nimCompileFold("Compile nimgrep", "tools/nimgrep.nim", options = "-d:release " & args) when defined(windows): buildVccTool(args) nimCompileFold("Compile nimpretty", "nimpretty/nimpretty.nim", options = "-d:release " & args) nimCompileFold("Compile nimfind", "tools/nimfind.nim", options = "-d:release " & args) nimCompileFold("Compile testament", "testament/testament.nim", options = "-d:release " & args) proc nsis(latest: bool; args: string) = bundleNimbleExe(latest, args) bundleNimsuggest(args) bundleWinTools(args) # make sure we have generated the niminst executables: buildTool("tools/niminst/niminst", args) #buildTool("tools/nimgrep", args) # produce 'nim_debug.exe': #exec "nim c compiler" / "nim.nim" #copyExe("compiler/nim".exe, "bin/nim_debug".exe) exec(("tools" / "niminst" / "niminst --var:version=$# --var:mingw=mingw$#" & " nsis compiler/installer.ini") % [VersionAsString, $(sizeof(pointer)*8)]) proc geninstall(args="") = nimexec("cc -r $# --var:version=$# --var:mingw=none --main:compiler/nim.nim scripts compiler/installer.ini $#" % [compileNimInst, VersionAsString, args]) proc install(args: string) = geninstall() exec("sh ./install.sh $#" % args) when false: proc web(args: string) = nimexec("js tools/dochack/dochack.nim") nimexec("cc -r tools/nimweb.nim $# web/website.ini --putenv:nimversion=$#" % [args, VersionAsString]) proc website(args: string) = nimexec("cc -r tools/nimweb.nim $# --website web/website.ini --putenv:nimversion=$#" % [args, VersionAsString]) proc pdf(args="") = exec("$# cc -r tools/nimweb.nim $# --pdf web/website.ini --putenv:nimversion=$#" % [findNim(), args, VersionAsString], additionalPATH=findNim().splitFile.dir) # -------------- boot --------------------------------------------------------- proc findStartNim: string = # we try several things before giving up: # * bin/nim # * $PATH/nim # If these fail, we try to build nim with the "build.(sh|bat)" script. var nim = "nim".exe result = "bin" / nim if existsFile(result): return for dir in split(getEnv("PATH"), PathSep): if existsFile(dir / nim): return dir / nim when defined(Posix): const buildScript = "build.sh" if existsFile(buildScript): if tryExec("./" & buildScript): return "bin" / nim else: const buildScript = "build.bat" if existsFile(buildScript): if tryExec(buildScript): return "bin" / nim echo("Found no nim compiler and every attempt to build one failed!") quit("FAILURE") proc thVersion(i: int): string = result = ("compiler" / "nim" & $i).exe proc boot(args: string) = var output = "compiler" / "nim".exe var finalDest = "bin" / "nim".exe # default to use the 'c' command: let useCpp = getEnv("NIM_COMPILE_TO_CPP", "false") == "true" let smartNimcache = (if "release" in args or "danger" in args: "nimcache/r_" else: "nimcache/d_") & hostOS & "_" & hostCPU let nimStart = findStartNim() for i in 0..2: let defaultCommand = if useCpp: "cpp" else: "c" let bootOptions = if args.len == 0 or args.startsWith("-"): defaultCommand else: "" echo "iteration: ", i+1 var extraOption = "" var nimi = i.thVersion if i == 0: nimi = nimStart extraOption.add " --skipUserCfg --skipParentCfg" # The configs are skipped for bootstrap # (1st iteration) to prevent newer flags from breaking bootstrap phase. let ret = execCmdEx(nimStart & " --version") doAssert ret.exitCode == 0 let version = ret.output.splitLines[0] if version.startsWith "Nim Compiler Version 0.19.0": extraOption.add " -d:nimBoostrapCsources0_19_0" # remove this when csources get updated # in order to use less memory, we split the build into two steps: # --compileOnly produces a $project.json file and does not run GCC/Clang. # jsonbuild then uses the $project.json file to build the Nim binary. exec "$# $# $# $# --nimcache:$# --compileOnly compiler" / "nim.nim" % [nimi, bootOptions, extraOption, args, smartNimcache] exec "$# jsonscript --nimcache:$# compiler" / "nim.nim" % [nimi, smartNimcache] if sameFileContent(output, i.thVersion): copyExe(output, finalDest) echo "executables are equal: SUCCESS!" return copyExe(output, (i+1).thVersion) copyExe(output, finalDest) when not defined(windows): echo "[Warning] executables are still not equal" # -------------- clean -------------------------------------------------------- const cleanExt = [ ".ppu", ".o", ".obj", ".dcu", ".~pas", ".~inc", ".~dsk", ".~dpr", ".map", ".tds", ".err", ".bak", ".pyc", ".exe", ".rod", ".pdb", ".idb", ".idx", ".ilk" ] ignore = [ ".bzrignore", "nim", "nim.exe", "koch", "koch.exe", ".gitignore" ] proc cleanAux(dir: string) = for kind, path in walkDir(dir): case kind of pcFile: var (_, name, ext) = splitFile(path) if ext == "" or cleanExt.contains(ext): if not ignore.contains(name): echo "removing: ", path removeFile(path) of pcDir: case splitPath(path).tail of "nimcache": echo "removing dir: ", path removeDir(path) of "dist", ".git", "icons": discard else: cleanAux(path) else: discard proc removePattern(pattern: string) = for f in walkFiles(pattern): echo "removing: ", f removeFile(f) proc clean(args: string) = removePattern("web/*.html") removePattern("doc/*.html") cleanAux(getCurrentDir()) for kind, path in walkDir(getCurrentDir() / "build"): if kind == pcDir: echo "removing dir: ", path removeDir(path) # -------------- builds a release --------------------------------------------- proc winReleaseArch(arch: string) = doAssert arch in ["32", "64"] let cpu = if arch == "32": "i386" else: "amd64" template withMingw(path, body) = let prevPath = getEnv("PATH") putEnv("PATH", (if path.len > 0: path & PathSep else: "") & prevPath) try: body finally: putEnv("PATH", prevPath) withMingw r"..\mingw" & arch & r"\bin": # Rebuilding koch is necessary because it uses its pointer size to # determine which mingw link to put in the NSIS installer. inFold "winrelease koch": nimexec "c --cpu:$# koch" % cpu kochExecFold("winrelease boot", "boot -d:release --cpu:$#" % cpu) kochExecFold("winrelease zip", "zip -d:release") overwriteFile r"build\nim-$#.zip" % VersionAsString, r"web\upload\download\nim-$#_x$#.zip" % [VersionAsString, arch] proc winRelease*() = # Now used from "tools/winrelease" and not directly supported by koch # anymore! # Build -docs file: when true: inFold "winrelease buildDocs": buildDocs(gaCode) withDir "web/upload/" & VersionAsString: inFold "winrelease zipdocs": exec "7z a -tzip docs-$#.zip *.html" % VersionAsString overwriteFile "web/upload/$1/docs-$1.zip" % VersionAsString, "web/upload/download/docs-$1.zip" % VersionAsString when true: inFold "winrelease csource": csource("-d:release") when sizeof(pointer) == 4: winReleaseArch "32" when sizeof(pointer) == 8: winReleaseArch "64" # -------------- tests -------------------------------------------------------- template `|`(a, b): string = (if a.len > 0: a else: b) proc tests(args: string) = nimexec "cc --opt:speed testament/testament" let tester = quoteShell(getCurrentDir() / "testament/testament".exe) let success = tryExec tester & " " & (args|"all") if not success: quit("tests failed", QuitFailure) proc temp(args: string) = proc splitArgs(a: string): (string, string) = # every --options before the command (indicated by starting # with not a dash) is part of the bootArgs, the rest is part # of the programArgs: let args = os.parseCmdLine a result = ("", "") var i = 0 while i < args.len and args[i][0] == '-': result[0].add " " & quoteShell(args[i]) inc i while i < args.len: result[1].add " " & quoteShell(args[i]) inc i let d = getAppDir() var output = d / "compiler" / "nim".exe var finalDest = d / "bin" / "nim_temp".exe # 125 is the magic number to tell git bisect to skip the current commit. var (bootArgs, programArgs) = splitArgs(args) if "doc" notin programArgs and "threads" notin programArgs and "js" notin programArgs: bootArgs.add " -d:leanCompiler" let nimexec = findNim() exec(nimexec & " c -d:debug --debugger:native -d:nimBetterRun " & bootArgs & " " & (d / "compiler" / "nim"), 125) copyExe(output, finalDest) setCurrentDir(origDir) if programArgs.len > 0: exec(finalDest & " " & programArgs) proc xtemp(cmd: string) = let d = getAppDir() copyExe(d / "bin" / "nim".exe, d / "bin" / "nim_backup".exe) try: withDir(d): temp"" copyExe(d / "bin" / "nim_temp".exe, d / "bin" / "nim".exe) exec(cmd) finally: copyExe(d / "bin" / "nim_backup".exe, d / "bin" / "nim".exe) proc runCI(cmd: string) = doAssert cmd.len == 0, cmd # avoid silently ignoring echo "runCI:", cmd # note(@araq): Do not replace these commands with direct calls (eg boot()) # as that would weaken our testing efforts. when defined(posix): # appveyor (on windows) didn't run this kochExecFold("Boot", "boot") # boot without -d:nimHasLibFFI to make sure this still works kochExecFold("Boot in release mode", "boot -d:release -d:danger") ## build nimble early on to enable remainder to depend on it if needed kochExecFold("Build Nimble", "nimble") when false: execFold("nimble install -y libffi", "nimble install -y libffi") kochExecFold("boot -d:release -d:nimHasLibFFI", "boot -d:release -d:nimHasLibFFI") if getEnv("NIM_TEST_PACKAGES", "false") == "true": execFold("Test selected Nimble packages", "nim c -r testament/testament cat nimble-packages") else: buildTools() # altenatively, kochExec "tools --toolsNoNimble" ## run tests execFold("Test nimscript", "nim e tests/test_nimscript.nims") when defined(windows): # note: will be over-written below execFold("Compile tester", "nim c -d:nimCoroutines --os:genode -d:posix --compileOnly testament/testament") # main bottleneck here execFold("Run tester", "nim c -r -d:nimCoroutines testament/testament --pedantic all -d:nimCoroutines") execFold("Run nimdoc tests", "nim c -r nimdoc/tester") execFold("Run nimpretty tests", "nim c -r nimpretty/tester.nim") when defined(posix): execFold("Run nimsuggest tests", "nim c -r nimsuggest/tester") ## remaining actions when defined(posix): kochExecFold("Docs", "docs --git.commit:devel") kochExecFold("C sources", "csource") elif defined(windows): when false: kochExec "csource" kochExec "zip" proc pushCsources() = if not dirExists("../csources/.git"): quit "[Error] no csources git repository found" csource("-d:release") let cwd = getCurrentDir() try: copyDir("build/c_code", "../csources/c_code") copyFile("build/build.sh", "../csources/build.sh") copyFile("build/build.bat", "../csources/build.bat") copyFile("build/build64.bat", "../csources/build64.bat") copyFile("build/makefile", "../csources/makefile") setCurrentDir("../csources") for kind, path in walkDir("c_code"): if kind == pcDir: exec("git add " & path / "*.c") exec("git commit -am \"updated csources to version " & NimVersion & "\"") exec("git push origin master") exec("git tag -am \"Version $1\" v$1" % NimVersion) exec("git push origin v$1" % NimVersion) finally: setCurrentDir(cwd) proc testUnixInstall(cmdLineRest: string) = csource("-d:release " & cmdLineRest) xz(false, cmdLineRest) let oldCurrentDir = getCurrentDir() try: let destDir = getTempDir() copyFile("build/nim-$1.tar.xz" % VersionAsString, destDir / "nim-$1.tar.xz" % VersionAsString) setCurrentDir(destDir) execCleanPath("tar -xJf nim-$1.tar.xz" % VersionAsString) setCurrentDir("nim-$1" % VersionAsString) execCleanPath("sh build.sh") # first test: try if './bin/nim --version' outputs something sane: let output = execProcess("./bin/nim --version").splitLines if output.len > 0 and output[0].contains(VersionAsString): echo "Version check: success" execCleanPath("./bin/nim c koch.nim") execCleanPath("./koch boot -d:release", destDir / "bin") # check the docs build: execCleanPath("./koch docs", destDir / "bin") # check nimble builds: execCleanPath("./koch tools") # check the tests work: putEnv("NIM_EXE_NOT_IN_PATH", "NOT_IN_PATH") execCleanPath("./koch tests --nim:./bin/nim cat megatest", destDir / "bin") else: echo "Version check: failure" finally: setCurrentDir oldCurrentDir proc valgrind(cmd: string) = # somewhat hacky: '=' sign means "pass to valgrind" else "pass to Nim" let args = parseCmdLine(cmd) var nimcmd = "" var valcmd = "" for i, a in args: if i == args.len-1: # last element is the filename: valcmd.add ' ' valcmd.add changeFileExt(a, ExeExt) nimcmd.add ' ' nimcmd.add a elif '=' in a: valcmd.add ' ' valcmd.add a else: nimcmd.add ' ' nimcmd.add a exec("nim c" & nimcmd) let supp = getAppDir() / "tools" / "nimgrind.supp" exec("valgrind --suppressions=" & supp & valcmd) proc showHelp() = quit(HelpText % [VersionAsString & spaces(44-len(VersionAsString)), CompileDate, CompileTime], QuitSuccess) when isMainModule: var op = initOptParser() var latest = false while true: op.next() case op.kind of cmdLongOption, cmdShortOption: case normalize(op.key) of "latest": latest = true of "stable": latest = false else: showHelp() of cmdArgument: case normalize(op.key) of "boot": boot(op.cmdLineRest) of "clean": clean(op.cmdLineRest) of "doc", "docs": buildDocs(op.cmdLineRest) of "doc0", "docs0": # undocumented command for Araq-the-merciful: buildDocs(op.cmdLineRest & gaCode) of "pdf": buildPdfDoc(op.cmdLineRest, "doc/pdf") of "csource", "csources": csource(op.cmdLineRest) of "zip": zip(latest, op.cmdLineRest) of "xz": xz(latest, op.cmdLineRest) of "nsis": nsis(latest, op.cmdLineRest) of "geninstall": geninstall(op.cmdLineRest) of "distrohelper": geninstall() of "install": install(op.cmdLineRest) of "testinstall": testUnixInstall(op.cmdLineRest) of "runci": runCI(op.cmdLineRest) of "test", "tests": tests(op.cmdLineRest) of "temp": temp(op.cmdLineRest) of "xtemp": xtemp(op.cmdLineRest) of "wintools": bundleWinTools(op.cmdLineRest) of "nimble": buildNimble(latest, op.cmdLineRest) of "nimsuggest": bundleNimsuggest(op.cmdLineRest) of "toolsnonimble": buildTools(op.cmdLineRest) of "tools": buildTools(op.cmdLineRest) buildNimble(latest, op.cmdLineRest) of "pushcsource", "pushcsources": pushCsources() of "valgrind": valgrind(op.cmdLineRest) of "c2nim": bundleC2nim(op.cmdLineRest) else: showHelp() break of cmdEnd: break