summaryrefslogtreecommitdiff
path: root/tests
diff options
context:
space:
mode:
authorGeorg Brandl <georg@python.org>2014-10-08 08:50:24 +0200
committerGeorg Brandl <georg@python.org>2014-10-08 08:50:24 +0200
commitab509e4ea2a8bd3c7e8e355b0e83b3e2de9f7a01 (patch)
treedb1c94d9d2ba3fc0c664b71ba798007eb0da5a65 /tests
parent7f5c98a36c3a8e1b9877e1d4cfe41fd00f08833a (diff)
parente07ba8bf31d7a9ee2cfd4832608a9453a9f81fbe (diff)
downloadpygments-ab509e4ea2a8bd3c7e8e355b0e83b3e2de9f7a01.tar.gz
Merged in __russ__/pygments-main (pull request #165)
Diffstat (limited to 'tests')
-rw-r--r--tests/examplefiles/99_bottles_of_beer.chpl161
-rwxr-xr-xtests/examplefiles/Deflate.fs578
-rw-r--r--tests/examplefiles/Error.pmod38
-rw-r--r--tests/examplefiles/Errors.scala5
-rw-r--r--tests/examplefiles/FakeFile.pike360
-rw-r--r--tests/examplefiles/Get-CommandDefinitionHtml.ps166
-rw-r--r--tests/examplefiles/IPDispatchC.nc104
-rw-r--r--tests/examplefiles/IPDispatchP.nc671
-rw-r--r--tests/examplefiles/RoleQ.pm623
-rw-r--r--tests/examplefiles/all.nit1986
-rw-r--r--tests/examplefiles/antlr_ANTLRv3.g (renamed from tests/examplefiles/ANTLRv3.g)0
-rw-r--r--tests/examplefiles/clojure-weird-keywords.clj5
-rw-r--r--tests/examplefiles/core.cljs52
-rw-r--r--tests/examplefiles/demo.cfm14
-rw-r--r--tests/examplefiles/demo.hbs12
-rw-r--r--tests/examplefiles/docker.docker5
-rw-r--r--tests/examplefiles/ember.handlebars33
-rw-r--r--tests/examplefiles/example.als217
-rw-r--r--tests/examplefiles/example.c2
-rw-r--r--tests/examplefiles/example.ceylon39
-rw-r--r--tests/examplefiles/example.chai6
-rw-r--r--tests/examplefiles/example.clay33
-rw-r--r--tests/examplefiles/example.cob936
-rw-r--r--tests/examplefiles/example.coffee27
-rw-r--r--tests/examplefiles/example.e124
-rw-r--r--tests/examplefiles/example.f908
-rw-r--r--tests/examplefiles/example.feature16
-rw-r--r--tests/examplefiles/example.gd23
-rw-r--r--tests/examplefiles/example.gi64
-rw-r--r--tests/examplefiles/example.golo113
-rwxr-xr-xtests/examplefiles/example.groovy2
-rw-r--r--tests/examplefiles/example.hs31
-rw-r--r--tests/examplefiles/example.hx192
-rw-r--r--tests/examplefiles/example.i6t32
-rw-r--r--tests/examplefiles/example.i7x45
-rw-r--r--tests/examplefiles/example.inf374
-rw-r--r--tests/examplefiles/example.j564
-rw-r--r--tests/examplefiles/example.java16
-rw-r--r--tests/examplefiles/example.kal75
-rw-r--r--tests/examplefiles/example.lagda19
-rw-r--r--tests/examplefiles/example.liquid42
-rw-r--r--tests/examplefiles/example.ma8
-rw-r--r--tests/examplefiles/example.mq4187
-rw-r--r--tests/examplefiles/example.mqh123
-rw-r--r--tests/examplefiles/example.ni57
-rw-r--r--tests/examplefiles/example.nix80
-rw-r--r--tests/examplefiles/example.pp8
-rw-r--r--tests/examplefiles/example.red257
-rw-r--r--tests/examplefiles/example.reds150
-rw-r--r--tests/examplefiles/example.rexx50
-rw-r--r--tests/examplefiles/example.rkt706
-rw-r--r--tests/examplefiles/example.sh22
-rw-r--r--tests/examplefiles/example.slim31
-rw-r--r--tests/examplefiles/example.sls51
-rw-r--r--tests/examplefiles/example.stan174
-rw-r--r--tests/examplefiles/example.thy751
-rw-r--r--tests/examplefiles/example.todotxt9
-rw-r--r--tests/examplefiles/example.weechatlog4
-rw-r--r--tests/examplefiles/exampleScript.cfc241
-rw-r--r--tests/examplefiles/exampleTag.cfc18
-rw-r--r--tests/examplefiles/example_coq.v4
-rw-r--r--tests/examplefiles/example_elixir.ex570
-rw-r--r--tests/examplefiles/garcia-wachs.kk70
-rw-r--r--tests/examplefiles/grammar-test.p622
-rw-r--r--tests/examplefiles/hash_syntax.rb5
-rw-r--r--tests/examplefiles/hello.at6
-rw-r--r--tests/examplefiles/hello.golo5
-rw-r--r--tests/examplefiles/hello.lsl12
-rw-r--r--tests/examplefiles/hybris_File.hy (renamed from tests/examplefiles/File.hy)0
-rw-r--r--tests/examplefiles/idl_sample.pro (renamed from tests/examplefiles/mg_sample.pro)0
-rw-r--r--tests/examplefiles/iex_example23
-rw-r--r--tests/examplefiles/import.hs4
-rw-r--r--tests/examplefiles/inet_pton6.dg48
-rw-r--r--tests/examplefiles/interp.scala10
-rw-r--r--tests/examplefiles/language.hy165
-rw-r--r--tests/examplefiles/limbo.b456
-rw-r--r--tests/examplefiles/livescript-demo.ls4
-rw-r--r--tests/examplefiles/main.cmake2
-rw-r--r--tests/examplefiles/matlab_sample4
-rw-r--r--tests/examplefiles/objc_example.m176
-rw-r--r--tests/examplefiles/objc_example2.m24
-rw-r--r--tests/examplefiles/openedge_example (renamed from tests/examplefiles/example.p)0
-rw-r--r--tests/examplefiles/pawn_example25
-rw-r--r--tests/examplefiles/py3tb_test.py3tb4
-rw-r--r--tests/examplefiles/pycon_test.pycon5
-rw-r--r--tests/examplefiles/qbasic_example2
-rw-r--r--tests/examplefiles/r6rs-comments.scm23
-rw-r--r--tests/examplefiles/robotframework_test.txt (renamed from tests/examplefiles/robotframework.txt)0
-rw-r--r--tests/examplefiles/rql-queries.rql34
-rw-r--r--tests/examplefiles/rust_example.rs4
-rw-r--r--tests/examplefiles/scope.cirru43
-rw-r--r--tests/examplefiles/sparql.rq23
-rw-r--r--tests/examplefiles/swig_java.swg1329
-rw-r--r--tests/examplefiles/swig_std_vector.i225
-rw-r--r--tests/examplefiles/test.R42
-rw-r--r--tests/examplefiles/test.agda109
-rw-r--r--tests/examplefiles/test.apl26
-rw-r--r--tests/examplefiles/test.bb95
-rw-r--r--tests/examplefiles/test.cyp123
-rw-r--r--tests/examplefiles/test.ebnf31
-rw-r--r--tests/examplefiles/test.idr101
-rw-r--r--tests/examplefiles/test.mask41
-rw-r--r--tests/examplefiles/test.p6252
-rw-r--r--tests/examplefiles/test.pan54
-rw-r--r--tests/examplefiles/test.php12
-rw-r--r--tests/examplefiles/test.pig148
-rw-r--r--tests/examplefiles/test.pwn253
-rw-r--r--tests/examplefiles/test.pypylog839
-rw-r--r--tests/examplefiles/test.r334
-rw-r--r--tests/examplefiles/test.rsl111
-rw-r--r--tests/examplefiles/test.swift65
-rw-r--r--tests/examplefiles/test.zep33
-rw-r--r--tests/examplefiles/type.lisp16
-rw-r--r--tests/examplefiles/unicode.go10
-rw-r--r--tests/examplefiles/unicode.js5
-rw-r--r--tests/examplefiles/vbnet_test.bas (renamed from tests/examplefiles/test.bas)0
-rw-r--r--tests/examplefiles/vctreestatus_hg4
-rw-r--r--tests/examplefiles/vimrc21
-rw-r--r--tests/examplefiles/vpath.mk16
-rw-r--r--tests/old_run.py138
-rw-r--r--tests/run.py38
-rw-r--r--tests/string_asserts.py22
-rw-r--r--tests/support.py2
-rw-r--r--tests/test_basic_api.py147
-rw-r--r--tests/test_cfm.py46
-rw-r--r--tests/test_clexer.py211
-rw-r--r--tests/test_cmdline.py32
-rw-r--r--tests/test_examplefiles.py101
-rw-r--r--tests/test_html_formatter.py31
-rw-r--r--tests/test_java.py42
-rw-r--r--tests/test_latex_formatter.py11
-rw-r--r--tests/test_lexers_other.py65
-rw-r--r--tests/test_objectiveclexer.py81
-rw-r--r--tests/test_perllexer.py4
-rw-r--r--tests/test_qbasiclexer.py43
-rw-r--r--tests/test_regexlexer.py9
-rw-r--r--tests/test_regexopt.py52
-rw-r--r--tests/test_rtf_formatter.py109
-rw-r--r--tests/test_ruby.py145
-rw-r--r--tests/test_shell.py63
-rw-r--r--tests/test_smarty.py40
-rw-r--r--tests/test_string_asserts.py35
-rw-r--r--tests/test_token.py6
-rw-r--r--tests/test_using_api.py2
-rw-r--r--tests/test_util.py14
145 files changed, 14641 insertions, 2656 deletions
diff --git a/tests/examplefiles/99_bottles_of_beer.chpl b/tests/examplefiles/99_bottles_of_beer.chpl
new file mode 100644
index 00000000..47fcaaf6
--- /dev/null
+++ b/tests/examplefiles/99_bottles_of_beer.chpl
@@ -0,0 +1,161 @@
+/***********************************************************************
+ * Chapel implementation of "99 bottles of beer"
+ *
+ * by Brad Chamberlain and Steve Deitz
+ * 07/13/2006 in Knoxville airport while waiting for flight home from
+ * HPLS workshop
+ * compiles and runs with chpl compiler version 1.7.0
+ * for more information, contact: chapel_info@cray.com
+ *
+ *
+ * Notes:
+ * o as in all good parallel computations, boundary conditions
+ * constitute the vast bulk of complexity in this code (invite Brad to
+ * tell you about his zany boundary condition simplification scheme)
+ * o uses type inference for variables, arguments
+ * o relies on integer->string coercions
+ * o uses named argument passing (for documentation purposes only)
+ ***********************************************************************/
+
+// allow executable command-line specification of number of bottles
+// (e.g., ./a.out -snumBottles=999999)
+config const numBottles = 99;
+const numVerses = numBottles+1;
+
+// a domain to describe the space of lyrics
+var LyricsSpace: domain(1) = {1..numVerses};
+
+// array of lyrics
+var Lyrics: [LyricsSpace] string;
+
+// parallel computation of lyrics array
+[verse in LyricsSpace] Lyrics(verse) = computeLyric(verse);
+
+// as in any good parallel language, I/O to stdout is serialized.
+// (Note that I/O to a file could be parallelized using a parallel
+// prefix computation on the verse strings' lengths with file seeking)
+writeln(Lyrics);
+
+
+// HELPER FUNCTIONS:
+
+proc computeLyric(verseNum) {
+ var bottleNum = numBottles - (verseNum - 1);
+ var nextBottle = (bottleNum + numVerses - 1)%numVerses;
+ return "\n" // disguise space used to separate elements in array I/O
+ + describeBottles(bottleNum, startOfVerse=true) + " on the wall, "
+ + describeBottles(bottleNum) + ".\n"
+ + computeAction(bottleNum)
+ + describeBottles(nextBottle) + " on the wall.\n";
+}
+
+
+proc describeBottles(bottleNum, startOfVerse:bool = false) {
+ // NOTE: bool should not be necessary here (^^^^); working around bug
+ var bottleDescription = if (bottleNum) then bottleNum:string
+ else (if startOfVerse then "N"
+ else "n")
+ + "o more";
+ return bottleDescription
+ + " bottle" + (if (bottleNum == 1) then "" else "s")
+ + " of beer";
+}
+
+
+proc computeAction(bottleNum) {
+ return if (bottleNum == 0) then "Go to the store and buy some more, "
+ else "Take one down and pass it around, ";
+}
+
+
+// Modules...
+module M1 {
+ var x = 10;
+}
+
+module M2 {
+ use M1;
+ proc main() {
+ writeln("M2 -> M1 -> x " + x);
+ }
+}
+
+
+// Classes, records, unions...
+const PI: real = 3.14159;
+
+record Point {
+ var x, y: real;
+}
+var p: Point;
+writeln("Distance from origin: " + sqrt(p.x ** 2 + p.y ** 2));
+p = new Point(1.0, 2.0);
+writeln("Distance from origin: " + sqrt(p.x ** 2 + p.y ** 2));
+
+class Circle {
+ var p: Point;
+ var r: real;
+}
+var c = new Circle(r=2.0);
+proc Circle.area()
+ return PI * r ** 2;
+writeln("Area of circle: " + c.area());
+
+class Oval: Circle {
+ var r2: real;
+}
+proc Oval.area()
+ return PI * r * r2;
+
+delete c;
+c = nil;
+c = new Oval(r=1.0, r2=2.0);
+writeln("Area of oval: " + c.area());
+
+// This is a valid decimal integer:
+var x = 0000000000012;
+
+union U {
+ var i: int;
+ var r: real;
+}
+
+// chapel ranges are awesome.
+var r1 = 1..10, // 1 2 3 4 5 6 7 8 9 10
+ r2 = 10..1, // no values in this range
+ r3 = 1..10 by -1, // 10 9 8 7 6 5 4 3 2 1
+ r4 = 1..10 by 2, // 1 3 5 7 9
+ r5 = 1..10 by 2 align 0, // 2 4 6 8 10
+ r6 = 1..10 by 2 align 2, // 2 4 6 8 10
+ r7 = 1..10 # 3, // 1 2 3
+ r8 = 1..10 # -2, // 9 10
+ r9 = 1..100 # 10 by 2, // 1 3 5 7 9
+ ra = 1..100 by 2 # 10, // 1 3 5 7 9 11 13 15 17 19
+ rb = 1.. # 100 by 10; // 1 11 21 31 41 51 61 71 81 91
+
+// create a variable with default initialization
+var myVarWithoutInit: real = noinit;
+myVarWithoutInit = 1.0;
+
+// Chapel has <~> operator for read and write I/O operations.
+class IntPair {
+ var x: int;
+ var y: int;
+ proc readWriteThis(f) {
+ f <~> x <~> new ioLiteral(",") <~> y <~> new ioNewline();
+ }
+}
+var ip = new IntPair(17,2);
+write(ip);
+
+var targetDom: {1..10},
+ target: [targetDom] int;
+coforall i in targetDom with (ref target) {
+ targetDom[i] = i ** 3;
+}
+
+var wideOpen = 0o777,
+ mememe = 0o600,
+ clique_y = 0O660,
+ zeroOct = 0o0,
+ minPosOct = 0O1;
diff --git a/tests/examplefiles/Deflate.fs b/tests/examplefiles/Deflate.fs
new file mode 100755
index 00000000..7d3680ec
--- /dev/null
+++ b/tests/examplefiles/Deflate.fs
@@ -0,0 +1,578 @@
+// public domain
+
+module Deflate
+
+open System
+open System.Collections.Generic
+open System.IO
+open System.Linq
+open Crc
+
+let maxbuf = 32768
+let maxlen = 258
+
+let getBit (b:byte) (bit:int) =
+ if b &&& (1uy <<< bit) = 0uy then 0 else 1
+
+type BitReader(sin:Stream) =
+ let mutable bit = 8
+ let mutable cur = 0uy
+
+ member x.Skip() =
+ bit <- 8
+
+ member x.ReadBit() =
+ if bit = 8 then
+ bit <- 0
+ let b = sin.ReadByte()
+ if b = -1 then
+ failwith "バッファを超過しました"
+ cur <- byte b
+ let ret = if cur &&& (1uy <<< bit) = 0uy then 0 else 1
+ bit <- bit + 1
+ ret
+
+ member x.ReadLE n =
+ let mutable ret = 0
+ for i = 0 to n - 1 do
+ if x.ReadBit() = 1 then ret <- ret ||| (1 <<< i)
+ ret
+
+ member x.ReadBE n =
+ let mutable ret = 0
+ for i = 0 to n - 1 do
+ ret <- (ret <<< 1) ||| x.ReadBit()
+ ret
+
+ member x.ReadBytes len =
+ if bit <> 8 then bit <- 8
+ let buf = Array.zeroCreate<byte> len
+ ignore <| sin.Read(buf, 0, len)
+ buf
+
+type WriteBuffer(sout:Stream) =
+ let mutable prev:byte[] = null
+ let mutable buf = Array.zeroCreate<byte> maxbuf
+ let mutable p = 0
+
+ let next newbuf =
+ prev <- buf
+ buf <- if newbuf then Array.zeroCreate<byte> maxbuf else null
+ p <- 0
+
+ member x.Close() =
+ next false
+ next false
+
+ interface IDisposable with
+ member x.Dispose() = x.Close()
+
+ member x.WriteByte (b:byte) =
+ buf.[p] <- b
+ sout.WriteByte b
+ p <- p + 1
+ if p = maxbuf then next true
+
+ member x.Write (src:byte[]) start len =
+ let maxlen = maxbuf - p
+ if len <= maxlen then
+ Array.Copy(src, start, buf, p, len)
+ sout.Write(src, start, len)
+ p <- p + len
+ if p = maxbuf then next true
+ else
+ x.Write src start maxlen
+ x.Write src (start + maxlen) (len - maxlen)
+
+ member x.Copy len dist =
+ if dist < 1 then
+ failwith <| sprintf "dist too small: %d < 1" dist
+ elif dist > maxbuf then
+ failwith <| sprintf "dist too big: %d > %d" dist maxbuf
+ let pp = p - dist
+ if pp < 0 then
+ if prev = null then
+ failwith <| sprintf "dist too big: %d > %d" dist p
+ let pp = pp + maxbuf
+ let maxlen = maxbuf - pp
+ if len <= maxlen then
+ x.Write prev pp len
+ else
+ x.Write prev pp maxlen
+ x.Copy (len - maxlen) dist
+ else
+ let maxlen = p - pp
+ if len <= maxlen then
+ x.Write buf pp len
+ else
+ if dist = 1 then
+ let b = buf.[pp]
+ for i = 1 to len do
+ x.WriteByte b
+ else
+ let buf' = buf
+ let mutable len' = len
+ while len' > 0 do
+ let len'' = Math.Min(len', maxlen)
+ x.Write buf' pp len''
+ len' <- len' - len''
+
+type Huffman(lens:int[]) =
+ let vals = Array.zeroCreate<int> lens.Length
+ let min = lens.Where(fun x -> x > 0).Min()
+ let max = lens.Max()
+ let counts = Array.zeroCreate<int> (max + 1)
+ let firsts = Array.zeroCreate<int> (max + 1)
+ let nexts = Array.zeroCreate<int> (max + 1)
+ let tables = Array.zeroCreate<int[]>(max + 1)
+
+ do
+ for len in lens do
+ if len > 0 then counts.[len] <- counts.[len] + 1
+ for i = 1 to max do
+ firsts.[i] <- (firsts.[i - 1] + counts.[i - 1]) <<< 1
+ Array.Copy(firsts, 0, nexts, 0, max + 1)
+ for i = 0 to vals.Length - 1 do
+ let len = lens.[i]
+ if len > 0 then
+ vals.[i] <- nexts.[len]
+ nexts.[len] <- nexts.[len] + 1
+
+ for i = 0 to vals.Length - 1 do
+ let len = lens.[i]
+ if len > 0 then
+ let start = firsts.[len]
+ if tables.[len] = null then
+ let count = nexts.[len] - start
+ tables.[len] <- Array.zeroCreate<int> count
+ tables.[len].[vals.[i] - start] <- i
+
+ member x.GetValue h =
+ let rec getv i =
+ if i > max then -1 else
+ if h < nexts.[i] then
+ tables.[i].[h - firsts.[i]]
+ else
+ getv (i + 1)
+ getv min
+
+ member x.Read(br:BitReader) =
+ let rec read h i =
+ if h < nexts.[i] then
+ tables.[i].[h - firsts.[i]]
+ else
+ read ((h <<< 1) ||| br.ReadBit()) (i + 1)
+ read (br.ReadBE min) min
+
+type [<AbstractClass>] HuffmanDecoder() =
+ abstract GetValue: unit->int
+ abstract GetDistance: unit->int
+
+type FixedHuffman(br:BitReader) =
+ inherit HuffmanDecoder()
+
+ override x.GetValue() =
+ let v = br.ReadBE 7
+ if v < 24 then v + 256 else
+ let v = (v <<< 1) ||| br.ReadBit()
+ if v < 192 then v - 48
+ elif v < 200 then v + 88
+ else ((v <<< 1) ||| br.ReadBit()) - 256
+
+ override x.GetDistance() = br.ReadBE 5
+
+type DynamicHuffman(br:BitReader) =
+ inherit HuffmanDecoder()
+
+ let lit, dist =
+ let hlit =
+ let hlit = (br.ReadLE 5) + 257
+ if hlit > 286 then failwith <| sprintf "hlit: %d > 286" hlit
+ hlit
+
+ let hdist =
+ let hdist = (br.ReadLE 5) + 1
+ if hdist > 32 then failwith <| sprintf "hdist: %d > 32" hdist
+ hdist
+
+ let hclen =
+ let hclen = (br.ReadLE 4) + 4
+ if hclen > 19 then failwith <| sprintf "hclen: %d > 19" hclen
+ hclen
+
+ let clen =
+ let hclens = Array.zeroCreate<int> 19
+ let order = [| 16; 17; 18; 0; 8; 7; 9; 6; 10; 5;
+ 11; 4; 12; 3; 13; 2; 14; 1; 15 |]
+ for i = 0 to hclen - 1 do
+ hclens.[order.[i]] <- br.ReadLE 3
+ new Huffman(hclens)
+
+ let ld = Array.zeroCreate<int>(hlit + hdist)
+ let mutable i = 0
+ while i < ld.Length do
+ let v = clen.Read(br)
+ if v < 16 then
+ ld.[i] <- v
+ i <- i + 1
+ else
+ let r, v =
+ match v with
+ | 16 -> (br.ReadLE 2) + 3, ld.[i - 1]
+ | 17 -> (br.ReadLE 3) + 3, 0
+ | 18 -> (br.ReadLE 7) + 11, 0
+ | _ -> failwith "不正な値です。"
+ for j = 0 to r - 1 do
+ ld.[i + j] <- v
+ i <- i + r
+
+ new Huffman(ld.[0 .. hlit - 1]),
+ new Huffman(ld.[hlit .. hlit + hdist - 1])
+
+ override x.GetValue() = lit.Read br
+ override x.GetDistance() = dist.Read br
+
+let getLitExLen v = if v < 265 || v = 285 then 0 else (v - 261) >>> 2
+let getDistExLen d = if d < 4 then 0 else (d - 2) >>> 1
+
+let litlens =
+ let litlens = Array.zeroCreate<int> 286
+ let mutable v = 3
+ for i = 257 to 284 do
+ litlens.[i] <- v
+ v <- v + (1 <<< (getLitExLen i))
+ litlens.[285] <- maxlen
+ litlens.[257..285]
+
+let distlens =
+ let distlens = Array.zeroCreate<int> 30
+ let mutable v = 1
+ for i = 0 to 29 do
+ distlens.[i] <- v
+ v <- v + (1 <<< (getDistExLen i))
+ distlens
+
+type Reader(sin:Stream) =
+ inherit Stream()
+
+ let br = new BitReader(sin)
+ let fh = new FixedHuffman(br)
+
+ let sout = new MemoryStream()
+ let dbuf = new WriteBuffer(sout)
+
+ let mutable cache:byte[] = null
+ let mutable canRead = true
+
+ let rec read (h:HuffmanDecoder) =
+ let v = h.GetValue()
+ if v > 285 then failwith <| sprintf "不正な値: %d" v
+ if v < 256 then
+ dbuf.WriteByte(byte v)
+ elif v > 256 then
+ let len =
+ if v < 265 then v - 254 else
+ litlens.[v - 257] + (br.ReadLE (getLitExLen v))
+ let dist =
+ let d = h.GetDistance()
+ if d > 29 then failwith <| sprintf "不正な距離: %d" d
+ if d < 4 then d + 1 else
+ distlens.[d] + (br.ReadLE (getDistExLen d))
+ dbuf.Copy len dist
+ if v <> 256 then read h
+
+ override x.CanRead = canRead
+ override x.CanWrite = false
+ override x.CanSeek = false
+ override x.Flush() = ()
+
+ override x.Close() =
+ dbuf.Close()
+ canRead <- false
+
+ override x.Read(buffer, offset, count) =
+ let offset =
+ if cache = null then 0 else
+ let clen = cache.Length
+ let len = Math.Min(clen, count)
+ Array.Copy(cache, 0, buffer, offset, len)
+ cache <- if len = clen then null
+ else cache.[len .. clen - 1]
+ len
+ let req = int64 <| count - offset
+ while canRead && sout.Length < req do
+ x.readBlock()
+ let len =
+ if sout.Length = 0L then 0 else
+ let data = sout.ToArray()
+ sout.SetLength(0L)
+ let dlen = data.Length
+ let len = Math.Min(int req, dlen)
+ Array.Copy(data, 0, buffer, offset, len)
+ if dlen > len then
+ cache <- data.[len..]
+ len
+ offset + len
+
+ override x.Position
+ with get() = raise <| new NotImplementedException()
+ and set(v) = raise <| new NotImplementedException()
+
+ override x.Length = raise <| new NotImplementedException()
+ override x.Seek(_, _) = raise <| new NotImplementedException()
+ override x.Write(_, _, _) = raise <| new NotImplementedException()
+ override x.SetLength(_) = raise <| new NotImplementedException()
+
+ member private x.readBlock() =
+ let bfinal = br.ReadBit()
+ match br.ReadLE 2 with
+ | 0 -> br.Skip()
+ let len = br.ReadLE 16
+ let nlen = br.ReadLE 16
+ if len + nlen <> 0x10000 then
+ failwith "不正な非圧縮長"
+ dbuf.Write (br.ReadBytes len) 0 len
+ | 1 -> read fh
+ | 2 -> read (new DynamicHuffman(br))
+ | _ -> failwith "不正なブロックタイプ"
+ if bfinal = 1 then
+ canRead <- false
+ x.Close()
+
+type BitWriter(sout:Stream) =
+ let mutable bit = 0
+ let mutable cur = 0uy
+
+ member x.Skip() =
+ if bit > 0 then
+ sout.WriteByte(cur)
+ bit <- 0
+ cur <- 0uy
+
+ interface IDisposable with
+ member x.Dispose() =
+ x.Skip()
+ sout.Flush()
+
+ member x.WriteBit(b:int) =
+ cur <- cur ||| ((byte b) <<< bit)
+ bit <- bit + 1
+ if bit = 8 then
+ sout.WriteByte(cur)
+ bit <- 0
+ cur <- 0uy
+
+ member x.WriteLE (len:int) (b:int) =
+ for i = 0 to len - 1 do
+ x.WriteBit <| if (b &&& (1 <<< i)) = 0 then 0 else 1
+
+ member x.WriteBE (len:int) (b:int) =
+ for i = len - 1 downto 0 do
+ x.WriteBit <| if (b &&& (1 <<< i)) = 0 then 0 else 1
+
+ member x.WriteBytes(data:byte[]) =
+ x.Skip()
+ sout.Write(data, 0, data.Length)
+
+type FixedHuffmanWriter(bw:BitWriter) =
+ member x.Write (b:int) =
+ if b < 144 then
+ bw.WriteBE 8 (b + 0b110000)
+ elif b < 256 then
+ bw.WriteBE 9 (b - 144 + 0b110010000)
+ elif b < 280 then
+ bw.WriteBE 7 (b - 256)
+ elif b < 288 then
+ bw.WriteBE 8 (b - 280 + 0b11000000)
+
+ member x.WriteLen (len:int) =
+ if len < 3 || len > maxlen then
+ failwith <| sprintf "不正な長さ: %d" len
+ let mutable ll = 285
+ while len < litlens.[ll - 257] do
+ ll <- ll - 1
+ x.Write ll
+ bw.WriteLE (getLitExLen ll) (len - litlens.[ll - 257])
+
+ member x.WriteDist (d:int) =
+ if d < 1 || d > maxbuf then
+ failwith <| sprintf "不正な距離: %d" d
+ let mutable dl = 29
+ while d < distlens.[dl] do
+ dl <- dl - 1
+ bw.WriteBE 5 dl
+ bw.WriteLE (getDistExLen dl) (d - distlens.[dl])
+
+let maxbuf2 = maxbuf * 2
+let buflen = maxbuf2 + maxlen
+
+let inline getHash (buf:byte[]) pos =
+ ((int buf.[pos]) <<< 4) ^^^ ((int buf.[pos + 1]) <<< 2) ^^^ (int buf.[pos + 2])
+
+let inline addHash (hash:List<int>[]) (buf:byte[]) pos =
+ if buf.[pos] <> buf.[pos + 1] then
+ hash.[getHash buf pos].Add pos
+
+let inline addHash2 (tables:int[,]) (counts:int[]) (buf:byte[]) pos =
+ if buf.[pos] <> buf.[pos + 1] then
+ let h = getHash buf pos
+ let c = counts.[h]
+ tables.[h, c &&& 15] <- pos
+ counts.[h] <- c + 1
+
+type Writer(t:int, sin:Stream) =
+ let mutable length = buflen
+ let buf = Array.zeroCreate<byte> buflen
+ let tables, counts =
+ if t = 2 then Array2D.zeroCreate<int> 4096 16, Array.create 4096 0 else null, null
+ let hash = if tables = null then [| for _ in 0..4095 -> new List<int>() |] else null
+ let mutable crc = ~~~0u
+
+ let read pos len =
+ let rlen = sin.Read(buf, pos, len)
+ if rlen < len then length <- pos + rlen
+ for i = pos to pos + rlen - 1 do
+ let b = int(crc ^^^ (uint32 buf.[i])) &&& 0xff
+ crc <- (crc >>> 8) ^^^ crc32_table.[b]
+ if hash <> null then
+ for list in hash do list.Clear()
+ else
+ Array.fill counts 0 counts.Length 0
+
+ do
+ read 0 buflen
+
+ let search (pos:int) =
+ let mutable maxp = -1
+ let mutable maxl = 2
+ let mlen = Math.Min(maxlen, length - pos)
+ let last = Math.Max(0, pos - maxbuf)
+ let h = getHash buf pos
+ if hash <> null then
+ let list = hash.[h]
+ let mutable i = list.Count - 1
+ while i >= 0 do
+ let p = list.[i]
+ if p < last then i <- 0 else
+ let mutable len = 0
+ while len < mlen && buf.[p + len] = buf.[pos + len] do
+ len <- len + 1
+ if len > maxl then
+ maxp <- p
+ maxl <- len
+ i <- i - 1
+ else
+ let c = counts.[h]
+ let p1, p2 = if c < 16 then 0, c - 1 else c + 1, c + 16
+ let mutable i = p2
+ while i >= p1 do
+ let p = tables.[h, i &&& 15]
+ if p < last then i <- 0 else
+ let mutable len = 0
+ while len < mlen && buf.[p + len] = buf.[pos + len] do
+ len <- len + 1
+ if len > maxl then
+ maxp <- p
+ maxl <- len
+ i <- i - 1
+ maxp, maxl
+
+ member x.Crc = ~~~crc
+
+ member x.Compress (sout:Stream) =
+ use bw = new BitWriter(sout)
+ bw.WriteBit 1
+ bw.WriteLE 2 1
+ let hw = new FixedHuffmanWriter(bw)
+ let mutable p = 0
+ match t with
+ | 2 ->
+ while p < length do
+ let b = buf.[p]
+ if p < length - 4 && b = buf.[p + 1] && b = buf.[p + 2] && b = buf.[p + 3] then
+ let mutable len = 4
+ let mlen = Math.Min(maxlen + 1, length - p)
+ while len < mlen && b = buf.[p + len] do
+ len <- len + 1
+ hw.Write(int b)
+ hw.WriteLen(len - 1)
+ hw.WriteDist 1
+ p <- p + len
+ else
+ let maxp, maxl = search p
+ if maxp < 0 then
+ hw.Write(int b)
+ addHash2 tables counts buf p
+ p <- p + 1
+ else
+ hw.WriteLen maxl
+ hw.WriteDist (p - maxp)
+ for i = p to p + maxl - 1 do
+ addHash2 tables counts buf i
+ p <- p + maxl
+ if p > maxbuf2 then
+ Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen)
+ if length < buflen then length <- length - maxbuf else
+ read (maxbuf + maxlen) maxbuf
+ p <- p - maxbuf
+ for i = 0 to p - 1 do
+ addHash2 tables counts buf i
+ | 1 ->
+ while p < length do
+ let b = buf.[p]
+ if p < length - 4 && b = buf.[p + 1] && b = buf.[p + 2] && b = buf.[p + 3] then
+ let mutable len = 4
+ let mlen = Math.Min(maxlen + 1, length - p)
+ while len < mlen && b = buf.[p + len] do
+ len <- len + 1
+ hw.Write(int b)
+ hw.WriteLen(len - 1)
+ hw.WriteDist 1
+ p <- p + len
+ else
+ let maxp, maxl = search p
+ if maxp < 0 then
+ hw.Write(int b)
+ addHash hash buf p
+ p <- p + 1
+ else
+ hw.WriteLen maxl
+ hw.WriteDist (p - maxp)
+ for i = p to p + maxl - 1 do
+ addHash hash buf i
+ p <- p + maxl
+ if p > maxbuf2 then
+ Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen)
+ if length < buflen then length <- length - maxbuf else
+ read (maxbuf + maxlen) maxbuf
+ p <- p - maxbuf
+ for i = 0 to p - 1 do
+ addHash hash buf i
+ | _ ->
+ while p < length do
+ let maxp, maxl = search p
+ if maxp < 0 then
+ hw.Write(int buf.[p])
+ hash.[getHash buf p].Add p
+ p <- p + 1
+ else
+ hw.WriteLen maxl
+ hw.WriteDist (p - maxp)
+ for i = p to p + maxl - 1 do
+ hash.[getHash buf i].Add i
+ p <- p + maxl
+ if p > maxbuf2 then
+ Array.Copy(buf, maxbuf, buf, 0, maxbuf + maxlen)
+ if length < buflen then length <- length - maxbuf else
+ read (maxbuf + maxlen) maxbuf
+ p <- p - maxbuf
+ for i = 0 to p - 1 do
+ hash.[getHash buf i].Add i
+ hw.Write 256
+
+let GetCompressBytes (sin:Stream) =
+ let now = DateTime.Now
+ let ms = new MemoryStream()
+ let w = new Writer(1, sin)
+ w.Compress ms
+ ms.ToArray(), w.Crc
diff --git a/tests/examplefiles/Error.pmod b/tests/examplefiles/Error.pmod
new file mode 100644
index 00000000..808ecb0e
--- /dev/null
+++ b/tests/examplefiles/Error.pmod
@@ -0,0 +1,38 @@
+#pike __REAL_VERSION__
+
+constant Generic = __builtin.GenericError;
+
+constant Index = __builtin.IndexError;
+
+constant BadArgument = __builtin.BadArgumentError;
+
+constant Math = __builtin.MathError;
+
+constant Resource = __builtin.ResourceError;
+
+constant Permission = __builtin.PermissionError;
+
+constant Decode = __builtin.DecodeError;
+
+constant Cpp = __builtin.CppError;
+
+constant Compilation = __builtin.CompilationError;
+
+constant MasterLoad = __builtin.MasterLoadError;
+
+constant ModuleLoad = __builtin.ModuleLoadError;
+
+//! Returns an Error object for any argument it receives. If the
+//! argument already is an Error object or is empty, it does nothing.
+object mkerror(mixed error)
+{
+ if (error == UNDEFINED)
+ return error;
+ if (objectp(error) && error->is_generic_error)
+ return error;
+ if (arrayp(error))
+ return Error.Generic(@error);
+ if (stringp(error))
+ return Error.Generic(error);
+ return Error.Generic(sprintf("%O", error));
+} \ No newline at end of file
diff --git a/tests/examplefiles/Errors.scala b/tests/examplefiles/Errors.scala
index 67198c05..7af70280 100644
--- a/tests/examplefiles/Errors.scala
+++ b/tests/examplefiles/Errors.scala
@@ -11,6 +11,11 @@ String
val foo_+ = "foo plus"
val foo_⌬⌬ = "double benzene"
+ // Test some interpolated strings
+ val mu = s"${if (true) "a:b" else "c" {with "braces"}}"
+ val mu2 = f"${if (true) "a:b" else "c" {with "braces"}}"
+ val raw = raw"a raw\nstring\"with escaped quotes"
+
def main(argv: Array[String]) {
println(⌘.interface + " " + foo_+ + " " + foo_⌬⌬ )
}
diff --git a/tests/examplefiles/FakeFile.pike b/tests/examplefiles/FakeFile.pike
new file mode 100644
index 00000000..48f3ea64
--- /dev/null
+++ b/tests/examplefiles/FakeFile.pike
@@ -0,0 +1,360 @@
+#pike __REAL_VERSION__
+
+//! A string wrapper that pretends to be a @[Stdio.File] object
+//! in addition to some features of a @[Stdio.FILE] object.
+
+
+//! This constant can be used to distinguish a FakeFile object
+//! from a real @[Stdio.File] object.
+constant is_fake_file = 1;
+
+protected string data;
+protected int ptr;
+protected int(0..1) r;
+protected int(0..1) w;
+protected int mtime;
+
+protected function read_cb;
+protected function read_oob_cb;
+protected function write_cb;
+protected function write_oob_cb;
+protected function close_cb;
+
+//! @seealso
+//! @[Stdio.File()->close()]
+int close(void|string direction) {
+ direction = lower_case(direction||"rw");
+ int cr = has_value(direction, "r");
+ int cw = has_value(direction, "w");
+
+ if(cr) {
+ r = 0;
+ }
+
+ if(cw) {
+ w = 0;
+ }
+
+ // FIXME: Close callback
+ return 1;
+}
+
+//! @decl void create(string data, void|string type, void|int pointer)
+//! @seealso
+//! @[Stdio.File()->create()]
+void create(string _data, void|string type, int|void _ptr) {
+ if(!_data) error("No data string given to FakeFile.\n");
+ data = _data;
+ ptr = _ptr;
+ mtime = time();
+ if(type) {
+ type = lower_case(type);
+ if(has_value(type, "r"))
+ r = 1;
+ if(has_value(type, "w"))
+ w = 1;
+ }
+ else
+ r = w = 1;
+}
+
+protected string make_type_str() {
+ string type = "";
+ if(r) type += "r";
+ if(w) type += "w";
+ return type;
+}
+
+//! @seealso
+//! @[Stdio.File()->dup()]
+this_program dup() {
+ return this_program(data, make_type_str(), ptr);
+}
+
+//! Always returns 0.
+//! @seealso
+//! @[Stdio.File()->errno()]
+int errno() { return 0; }
+
+//! Returns size and the creation time of the string.
+Stdio.Stat stat() {
+ Stdio.Stat st = Stdio.Stat();
+ st->size = sizeof(data);
+ st->mtime=st->ctime=mtime;
+ st->atime=time();
+ return st;
+}
+
+//! @seealso
+//! @[Stdio.File()->line_iterator()]
+String.SplitIterator line_iterator(int|void trim) {
+ if(trim)
+ return String.SplitIterator( data-"\r", '\n' );
+ return String.SplitIterator( data, '\n' );
+}
+
+protected mixed id;
+
+//! @seealso
+//! @[Stdio.File()->query_id()]
+mixed query_id() { return id; }
+
+//! @seealso
+//! @[Stdio.File()->set_id()]
+void set_id(mixed _id) { id = _id; }
+
+//! @seealso
+//! @[Stdio.File()->read_function()]
+function(:string) read_function(int nbytes) {
+ return lambda() { return read(nbytes); };
+}
+
+//! @seealso
+//! @[Stdio.File()->peek()]
+int(-1..1) peek(int|float|void timeout) {
+ if(!r) return -1;
+ if(ptr >= sizeof(data)) return 0;
+ return 1;
+}
+
+//! Always returns 0.
+//! @seealso
+//! @[Stdio.File()->query_address()]
+string query_address(void|int(0..1) is_local) { return 0; }
+
+//! @seealso
+//! @[Stdio.File()->read()]
+string read(void|int(0..) len, void|int(0..1) not_all) {
+ if(!r) return 0;
+ if (len < 0) error("Cannot read negative number of characters.\n");
+ int start=ptr;
+ ptr += len;
+ if(zero_type(len) || ptr>sizeof(data))
+ ptr = sizeof(data);
+
+ // FIXME: read callback
+ return data[start..ptr-1];
+}
+
+//! @seealso
+//! @[Stdio.FILE()->gets()]
+string gets() {
+ if(!r) return 0;
+ string ret;
+ sscanf(data,"%*"+(string)ptr+"s%[^\n]",ret);
+ if(ret)
+ {
+ ptr+=sizeof(ret)+1;
+ if(ptr>sizeof(data))
+ {
+ ptr=sizeof(data);
+ if(!sizeof(ret))
+ ret = 0;
+ }
+ }
+
+ // FIXME: read callback
+ return ret;
+}
+
+//! @seealso
+//! @[Stdio.FILE()->getchar()]
+int getchar() {
+ if(!r) return 0;
+ int c;
+ if(catch(c=data[ptr]))
+ c=-1;
+ else
+ ptr++;
+
+ // FIXME: read callback
+ return c;
+}
+
+//! @seealso
+//! @[Stdio.FILE()->unread()]
+void unread(string s) {
+ if(!r) return;
+ if(data[ptr-sizeof(s)..ptr-1]==s)
+ ptr-=sizeof(s);
+ else
+ {
+ data=s+data[ptr..];
+ ptr=0;
+ }
+}
+
+//! @seealso
+//! @[Stdio.File()->seek()]
+int seek(int pos, void|int mult, void|int add) {
+ if(mult)
+ pos = pos*mult+add;
+ if(pos<0)
+ {
+ pos = sizeof(data)+pos;
+ if( pos < 0 )
+ pos = 0;
+ }
+ ptr = pos;
+ if( ptr > strlen( data ) )
+ ptr = strlen(data);
+ return ptr;
+}
+
+//! Always returns 1.
+//! @seealso
+//! @[Stdio.File()->sync()]
+int(1..1) sync() { return 1; }
+
+//! @seealso
+//! @[Stdio.File()->tell()]
+int tell() { return ptr; }
+
+//! @seealso
+//! @[Stdio.File()->truncate()]
+int(0..1) truncate(int length) {
+ data = data[..length-1];
+ return sizeof(data)==length;
+}
+
+//! @seealso
+//! @[Stdio.File()->write()]
+int(-1..) write(string|array(string) str, mixed ... extra) {
+ if(!w) return -1;
+ if(arrayp(str)) str=str*"";
+ if(sizeof(extra)) str=sprintf(str, @extra);
+
+ if(ptr==sizeof(data)) {
+ data += str;
+ ptr = sizeof(data);
+ }
+ else if(sizeof(str)==1)
+ data[ptr++] = str[0];
+ else {
+ data = data[..ptr-1] + str + data[ptr+sizeof(str)..];
+ ptr += sizeof(str);
+ }
+
+ // FIXME: write callback
+ return sizeof(str);
+}
+
+//! @seealso
+//! @[Stdio.File()->set_blocking]
+void set_blocking() {
+ close_cb = 0;
+ read_cb = 0;
+ read_oob_cb = 0;
+ write_cb = 0;
+ write_oob_cb = 0;
+}
+
+//! @seealso
+//! @[Stdio.File()->set_blocking_keep_callbacks]
+void set_blocking_keep_callbacks() { }
+
+//! @seealso
+//! @[Stdio.File()->set_blocking]
+void set_nonblocking(function rcb, function wcb, function ccb,
+ function rocb, function wocb) {
+ read_cb = rcb;
+ write_cb = wcb;
+ close_cb = ccb;
+ read_oob_cb = rocb;
+ write_oob_cb = wocb;
+}
+
+//! @seealso
+//! @[Stdio.File()->set_blocking_keep_callbacks]
+void set_nonblocking_keep_callbacks() { }
+
+
+//! @seealso
+//! @[Stdio.File()->set_close_callback]
+void set_close_callback(function cb) { close_cb = cb; }
+
+//! @seealso
+//! @[Stdio.File()->set_read_callback]
+void set_read_callback(function cb) { read_cb = cb; }
+
+//! @seealso
+//! @[Stdio.File()->set_read_oob_callback]
+void set_read_oob_callback(function cb) { read_oob_cb = cb; }
+
+//! @seealso
+//! @[Stdio.File()->set_write_callback]
+void set_write_callback(function cb) { write_cb = cb; }
+
+//! @seealso
+//! @[Stdio.File()->set_write_oob_callback]
+void set_write_oob_callback(function cb) { write_oob_cb = cb; }
+
+
+//! @seealso
+//! @[Stdio.File()->query_close_callback]
+function query_close_callback() { return close_cb; }
+
+//! @seealso
+//! @[Stdio.File()->query_read_callback]
+function query_read_callback() { return read_cb; }
+
+//! @seealso
+//! @[Stdio.File()->query_read_oob_callback]
+function query_read_oob_callback() { return read_oob_cb; }
+
+//! @seealso
+//! @[Stdio.File()->query_write_callback]
+function query_write_callback() { return write_cb; }
+
+//! @seealso
+//! @[Stdio.File()->query_write_oob_callback]
+function query_write_oob_callback() { return write_oob_cb; }
+
+string _sprintf(int t) {
+ return t=='O' && sprintf("%O(%d,%O)", this_program, sizeof(data),
+ make_type_str());
+}
+
+
+// FakeFile specials.
+
+//! A FakeFile can be casted to a string.
+mixed cast(string to) {
+ switch(to) {
+ case "string": return data;
+ case "object": return this;
+ }
+ error("Can not cast object to %O.\n", to);
+}
+
+//! Sizeof on a FakeFile returns the size of its contents.
+int(0..) _sizeof() {
+ return sizeof(data);
+}
+
+//! @ignore
+
+#define NOPE(X) mixed X (mixed ... args) { error("This is a FakeFile. %s is not available.\n", #X); }
+NOPE(assign);
+NOPE(async_connect);
+NOPE(connect);
+NOPE(connect_unix);
+NOPE(open);
+NOPE(open_socket);
+NOPE(pipe);
+NOPE(tcgetattr);
+NOPE(tcsetattr);
+
+// Stdio.Fd
+NOPE(dup2);
+NOPE(lock); // We could implement this
+NOPE(mode); // We could implement this
+NOPE(proxy); // We could implement this
+NOPE(query_fd);
+NOPE(read_oob);
+NOPE(set_close_on_exec);
+NOPE(set_keepalive);
+NOPE(trylock); // We could implement this
+NOPE(write_oob);
+
+//! @endignore \ No newline at end of file
diff --git a/tests/examplefiles/Get-CommandDefinitionHtml.ps1 b/tests/examplefiles/Get-CommandDefinitionHtml.ps1
new file mode 100644
index 00000000..b181955f
--- /dev/null
+++ b/tests/examplefiles/Get-CommandDefinitionHtml.ps1
@@ -0,0 +1,66 @@
+
+function Get-CommandDefinitionHtml {
+
+ # this tells powershell to allow advanced features,
+ # like the [validatenotnullorempty()] attribute below.
+ [CmdletBinding()]
+ param(
+ [ValidateNotNullOrEmpty()]
+ [string]$name
+ )
+
+ $command = get-command $name
+
+ # Look mom! I'm a cmdlet!
+ $PSCmdlet.WriteVerbose("Dumping HTML for " + $command)
+
+@"
+ <html>
+ <head>
+ <title>$($command.name)</title>
+ </head>
+ <body>
+ <table border="1">
+$(
+ $command.parametersets | % {
+@"
+
+ <tr>
+ <td>$($_.name)</td>
+ <td>
+ <table border="1">
+ <tr>
+ <th colspan="8">Parameters</th>
+
+$(
+ $count = 0
+ $_.parameters | % {
+ if (0 -eq ($count % 8)) {
+@'
+ </tr>
+ <tr>
+'@
+ }
+@"
+ <td>$($_.name)</td>
+"@
+ $count++
+ }
+)
+ </tr>
+ </table>
+ </td>
+ </tr>
+"@
+ }
+)
+ </table>
+ </body>
+ </html>
+"@
+}
+
+Get-CommandDefinitionHtml get-item > out.html
+
+# show in browser
+invoke-item out.html
diff --git a/tests/examplefiles/IPDispatchC.nc b/tests/examplefiles/IPDispatchC.nc
new file mode 100644
index 00000000..95a61a2c
--- /dev/null
+++ b/tests/examplefiles/IPDispatchC.nc
@@ -0,0 +1,104 @@
+/*
+ * "Copyright (c) 2008-2011 The Regents of the University of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+/**
+ *
+ *
+ */
+#include "IPDispatch.h"
+#include "BlipStatistics.h"
+
+configuration IPDispatchC {
+ provides {
+ interface SplitControl;
+ interface IPLower;
+ interface BlipStatistics<ip_statistics_t>;
+ }
+} implementation {
+
+ components MainC;
+ components NoLedsC as LedsC;
+
+ /* IPDispatchP wiring -- fragment rassembly and lib6lowpan bindings */
+ components IPDispatchP;
+ components CC2420RadioC as MessageC;
+ components ReadLqiC;
+ components new TimerMilliC();
+
+ SplitControl = IPDispatchP.SplitControl;
+ IPLower = IPDispatchP;
+ BlipStatistics = IPDispatchP;
+
+ IPDispatchP.Boot -> MainC;
+/* #else */
+/* components ResourceSendP; */
+/* ResourceSendP.SubSend -> MessageC; */
+/* ResourceSendP.Resource -> MessageC.SendResource[unique("RADIO_SEND_RESOURCE")]; */
+/* IPDispatchP.Ieee154Send -> ResourceSendP.Ieee154Send; */
+/* #endif */
+ IPDispatchP.RadioControl -> MessageC;
+
+ IPDispatchP.BarePacket -> MessageC.BarePacket;
+ IPDispatchP.Ieee154Send -> MessageC.BareSend;
+ IPDispatchP.Ieee154Receive -> MessageC.BareReceive;
+
+#ifdef LOW_POWER_LISTENING
+ IPDispatchP.LowPowerListening -> MessageC;
+#endif
+ MainC.SoftwareInit -> IPDispatchP.Init;
+
+ IPDispatchP.PacketLink -> MessageC;
+ IPDispatchP.ReadLqi -> ReadLqiC;
+ IPDispatchP.Leds -> LedsC;
+ IPDispatchP.ExpireTimer -> TimerMilliC;
+
+ components new PoolC(message_t, N_FRAGMENTS) as FragPool;
+ components new PoolC(struct send_entry, N_FRAGMENTS) as SendEntryPool;
+ components new QueueC(struct send_entry *, N_FRAGMENTS);
+ components new PoolC(struct send_info, N_CONCURRENT_SENDS) as SendInfoPool;
+
+ IPDispatchP.FragPool -> FragPool;
+ IPDispatchP.SendEntryPool -> SendEntryPool;
+ IPDispatchP.SendInfoPool -> SendInfoPool;
+ IPDispatchP.SendQueue -> QueueC;
+
+ components IPNeighborDiscoveryP;
+ IPDispatchP.NeighborDiscovery -> IPNeighborDiscoveryP;
+
+/* components ICMPResponderC; */
+/* #ifdef BLIP_MULTICAST */
+/* components MulticastP; */
+/* components new TrickleTimerMilliC(2, 30, 2, 1); */
+/* IP = MulticastP.IP; */
+
+/* MainC.SoftwareInit -> MulticastP.Init; */
+/* MulticastP.MulticastRx -> IPDispatchP.Multicast; */
+/* MulticastP.HopHeader -> IPExtensionP.HopByHopExt[0]; */
+/* MulticastP.TrickleTimer -> TrickleTimerMilliC.TrickleTimer[0]; */
+/* MulticastP.IPExtensions -> IPDispatchP; */
+/* #endif */
+
+#ifdef DELUGE
+ components NWProgC;
+#endif
+
+}
diff --git a/tests/examplefiles/IPDispatchP.nc b/tests/examplefiles/IPDispatchP.nc
new file mode 100644
index 00000000..628f39a0
--- /dev/null
+++ b/tests/examplefiles/IPDispatchP.nc
@@ -0,0 +1,671 @@
+/*
+ * "Copyright (c) 2008 The Regents of the University of California.
+ * All rights reserved."
+ *
+ * Permission to use, copy, modify, and distribute this software and its
+ * documentation for any purpose, without fee, and without written agreement is
+ * hereby granted, provided that the above copyright notice, the following
+ * two paragraphs and the author appear in all copies of this software.
+ *
+ * IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
+ * DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT
+ * OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF THE UNIVERSITY OF
+ * CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ *
+ * THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
+ * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
+ * AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS
+ * ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATION TO
+ * PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS."
+ *
+ */
+
+#include <lib6lowpan/blip-tinyos-includes.h>
+#include <lib6lowpan/6lowpan.h>
+#include <lib6lowpan/lib6lowpan.h>
+#include <lib6lowpan/ip.h>
+#include <lib6lowpan/in_cksum.h>
+#include <lib6lowpan/ip_malloc.h>
+
+#include "blip_printf.h"
+#include "IPDispatch.h"
+#include "BlipStatistics.h"
+#include "table.h"
+
+/*
+ * Provides IP layer reception to applications on motes.
+ *
+ * @author Stephen Dawson-Haggerty <stevedh@cs.berkeley.edu>
+ */
+
+module IPDispatchP {
+ provides {
+ interface SplitControl;
+ // interface for protocols not requiring special hand-holding
+ interface IPLower;
+
+ interface BlipStatistics<ip_statistics_t>;
+
+ }
+ uses {
+ interface Boot;
+
+
+ /* link-layer wiring */
+ interface SplitControl as RadioControl;
+
+ interface Packet as BarePacket;
+ interface Send as Ieee154Send;
+ interface Receive as Ieee154Receive;
+
+ /* context lookup */
+ interface NeighborDiscovery;
+
+ interface ReadLqi;
+ interface PacketLink;
+ interface LowPowerListening;
+
+ /* buffers for outgoing fragments */
+ interface Pool<message_t> as FragPool;
+ interface Pool<struct send_info> as SendInfoPool;
+ interface Pool<struct send_entry> as SendEntryPool;
+ interface Queue<struct send_entry *> as SendQueue;
+
+ /* expire reconstruction */
+ interface Timer<TMilli> as ExpireTimer;
+
+ interface Leds;
+
+ }
+ provides interface Init;
+} implementation {
+
+#define HAVE_LOWPAN_EXTERN_MATCH_CONTEXT
+int lowpan_extern_read_context(struct in6_addr *addr, int context) {
+ return call NeighborDiscovery.getContext(context, addr);
+}
+
+int lowpan_extern_match_context(struct in6_addr *addr, uint8_t *ctx_id) {
+ return call NeighborDiscovery.matchContext(addr, ctx_id);
+}
+
+ // generally including source files like this is a no-no. I'm doing
+ // this in the hope that the optimizer will do a better job when
+ // they're part of a component.
+#include <lib6lowpan/ieee154_header.c>
+#include <lib6lowpan/lib6lowpan.c>
+#include <lib6lowpan/lib6lowpan_4944.c>
+#include <lib6lowpan/lib6lowpan_frag.c>
+
+ enum {
+ S_RUNNING,
+ S_STOPPED,
+ S_STOPPING,
+ };
+ uint8_t state = S_STOPPED;
+ bool radioBusy;
+ uint8_t current_local_label = 0;
+ ip_statistics_t stats;
+
+ // this in theory could be arbitrarily large; however, it needs to
+ // be large enough to hold all active reconstructions, and any tags
+ // which we are dropping. It's important to keep dropped tags
+ // around for a while, or else there are pathological situations
+ // where you continually allocate buffers for packets which will
+ // never complete.
+
+ ////////////////////////////////////////
+ //
+ //
+
+ table_t recon_cache;
+
+ // table of packets we are currently receiving fragments from, that
+ // are destined to us
+ struct lowpan_reconstruct recon_data[N_RECONSTRUCTIONS];
+
+ //
+ //
+ ////////////////////////////////////////
+
+ // task void sendTask();
+
+ void reconstruct_clear(void *ent) {
+ struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)ent;
+ memclr((uint8_t *)&recon->r_meta, sizeof(struct ip6_metadata));
+ recon->r_timeout = T_UNUSED;
+ recon->r_buf = NULL;
+ }
+
+ struct send_info *getSendInfo() {
+ struct send_info *ret = call SendInfoPool.get();
+ if (ret == NULL) return ret;
+ ret->_refcount = 1;
+ ret->upper_data = NULL;
+ ret->failed = FALSE;
+ ret->link_transmissions = 0;
+ ret->link_fragments = 0;
+ ret->link_fragment_attempts = 0;
+ return ret;
+ }
+#define SENDINFO_INCR(X) ((X)->_refcount)++
+void SENDINFO_DECR(struct send_info *si) {
+ if (--(si->_refcount) == 0) {
+ call SendInfoPool.put(si);
+ }
+}
+
+ command error_t SplitControl.start() {
+ return call RadioControl.start();
+ }
+
+ command error_t SplitControl.stop() {
+ if (!radioBusy) {
+ state = S_STOPPED;
+ return call RadioControl.stop();
+ } else {
+ // if there's a packet in the radio, wait for it to exit before
+ // stopping
+ state = S_STOPPING;
+ return SUCCESS;
+ }
+ }
+
+ event void RadioControl.startDone(error_t error) {
+#ifdef LPL_SLEEP_INTERVAL
+ call LowPowerListening.setLocalWakeupInterval(LPL_SLEEP_INTERVAL);
+#endif
+
+ if (error == SUCCESS) {
+ call Leds.led2Toggle();
+ call ExpireTimer.startPeriodic(FRAG_EXPIRE_TIME);
+ state = S_RUNNING;
+ radioBusy = FALSE;
+ }
+
+ signal SplitControl.startDone(error);
+ }
+
+ event void RadioControl.stopDone(error_t error) {
+ signal SplitControl.stopDone(error);
+ }
+
+ command error_t Init.init() {
+ // ip_malloc_init needs to be in init, not booted, because
+ // context for coap is initialised in init
+ ip_malloc_init();
+ return SUCCESS;
+ }
+
+ event void Boot.booted() {
+ call BlipStatistics.clear();
+
+ /* set up our reconstruction cache */
+ table_init(&recon_cache, recon_data, sizeof(struct lowpan_reconstruct), N_RECONSTRUCTIONS);
+ table_map(&recon_cache, reconstruct_clear);
+
+ call SplitControl.start();
+ }
+
+ /*
+ * Receive-side code.
+ */
+ void deliver(struct lowpan_reconstruct *recon) {
+ struct ip6_hdr *iph = (struct ip6_hdr *)recon->r_buf;
+
+ // printf("deliver [%i]: ", recon->r_bytes_rcvd);
+ // printf_buf(recon->r_buf, recon->r_bytes_rcvd);
+
+ /* the payload length field is always compressed, have to put it back here */
+ iph->ip6_plen = htons(recon->r_bytes_rcvd - sizeof(struct ip6_hdr));
+ signal IPLower.recv(iph, (void *)(iph + 1), &recon->r_meta);
+
+ // printf("ip_free(%p)\n", recon->r_buf);
+ ip_free(recon->r_buf);
+ recon->r_timeout = T_UNUSED;
+ recon->r_buf = NULL;
+ }
+
+ /*
+ * Bulletproof recovery logic is very important to make sure we
+ * don't get wedged with no free buffers.
+ *
+ * The table is managed as follows:
+ * - unused entries are marked T_UNUSED
+ * - entries which
+ * o have a buffer allocated
+ * o have had a fragment reception before we fired
+ * are marked T_ACTIVE
+ * - entries which have not had a fragment reception during the last timer period
+ * and were active are marked T_ZOMBIE
+ * - zombie receptions are deleted: their buffer is freed and table entry marked unused.
+ * - when a fragment is dropped, it is entered into the table as T_FAILED1.
+ * no buffer is allocated
+ * - when the timer fires, T_FAILED1 entries are aged to T_FAILED2.
+ * - T_FAILED2 entries are deleted. Incomming fragments with tags
+ * that are marked either FAILED1 or FAILED2 are dropped; this
+ * prevents us from allocating a buffer for a packet which we
+ * have already dropped fragments from.
+ *
+ */
+ void reconstruct_age(void *elt) {
+ struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)elt;
+ if (recon->r_timeout != T_UNUSED)
+ printf("recon src: 0x%x tag: 0x%x buf: %p recvd: %i/%i\n",
+ recon->r_source_key, recon->r_tag, recon->r_buf,
+ recon->r_bytes_rcvd, recon->r_size);
+ switch (recon->r_timeout) {
+ case T_ACTIVE:
+ recon->r_timeout = T_ZOMBIE; break; // age existing receptions
+ case T_FAILED1:
+ recon->r_timeout = T_FAILED2; break; // age existing receptions
+ case T_ZOMBIE:
+ case T_FAILED2:
+ // deallocate the space for reconstruction
+ printf("timing out buffer: src: %i tag: %i\n", recon->r_source_key, recon->r_tag);
+ if (recon->r_buf != NULL) {
+ printf("ip_free(%p)\n", recon->r_buf);
+ ip_free(recon->r_buf);
+ }
+ recon->r_timeout = T_UNUSED;
+ recon->r_buf = NULL;
+ break;
+ }
+ }
+
+ void ip_print_heap() {
+#ifdef PRINTFUART_ENABLED
+ bndrt_t *cur = (bndrt_t *)heap;
+ while (((uint8_t *)cur) - heap < IP_MALLOC_HEAP_SIZE) {
+ printf ("heap region start: %p length: %u used: %u\n",
+ cur, (*cur & IP_MALLOC_LEN), (*cur & IP_MALLOC_INUSE) >> 15);
+ cur = (bndrt_t *)(((uint8_t *)cur) + ((*cur) & IP_MALLOC_LEN));
+ }
+#endif
+ }
+
+ event void ExpireTimer.fired() {
+ table_map(&recon_cache, reconstruct_age);
+
+
+ printf("Frag pool size: %i\n", call FragPool.size());
+ printf("SendInfo pool size: %i\n", call SendInfoPool.size());
+ printf("SendEntry pool size: %i\n", call SendEntryPool.size());
+ printf("Forward queue length: %i\n", call SendQueue.size());
+ ip_print_heap();
+ printfflush();
+ }
+
+ /*
+ * allocate a structure for recording information about incomming fragments.
+ */
+
+ struct lowpan_reconstruct *get_reconstruct(uint16_t key, uint16_t tag) {
+ struct lowpan_reconstruct *ret = NULL;
+ int i;
+
+ // printf("get_reconstruct: %x %i\n", key, tag);
+
+ for (i = 0; i < N_RECONSTRUCTIONS; i++) {
+ struct lowpan_reconstruct *recon = (struct lowpan_reconstruct *)&recon_data[i];
+
+ if (recon->r_tag == tag &&
+ recon->r_source_key == key) {
+
+ if (recon->r_timeout > T_UNUSED) {
+ recon->r_timeout = T_ACTIVE;
+ ret = recon;
+ goto done;
+
+ } else if (recon->r_timeout < T_UNUSED) {
+ // if we have already tried and failed to get a buffer, we
+ // need to drop remaining fragments.
+ ret = NULL;
+ goto done;
+ }
+ }
+ if (recon->r_timeout == T_UNUSED)
+ ret = recon;
+ }
+ done:
+ // printf("got%p\n", ret);
+ return ret;
+ }
+
+ event message_t *Ieee154Receive.receive(message_t *msg, void *msg_payload, uint8_t len) {
+ struct packed_lowmsg lowmsg;
+ struct ieee154_frame_addr frame_address;
+ uint8_t *buf = msg_payload;
+
+ // printf(" -- RECEIVE -- len : %i\n", len);
+
+ BLIP_STATS_INCR(stats.rx_total);
+
+ /* unpack the 802.15.4 address fields */
+ buf = unpack_ieee154_hdr(msg_payload, &frame_address);
+ len -= buf - (uint8_t *)msg_payload;
+
+ /* unpack and 6lowpan headers */
+ lowmsg.data = buf;
+ lowmsg.len = len;
+ lowmsg.headers = getHeaderBitmap(&lowmsg);
+ if (lowmsg.headers == LOWMSG_NALP) {
+ goto fail;
+ }
+
+ if (hasFrag1Header(&lowmsg) || hasFragNHeader(&lowmsg)) {
+ // start reassembly
+ int rv;
+ struct lowpan_reconstruct *recon;
+ uint16_t tag, source_key;
+
+ source_key = ieee154_hashaddr(&frame_address.ieee_src);
+ getFragDgramTag(&lowmsg, &tag);
+ recon = get_reconstruct(source_key, tag);
+ if (!recon) {
+ goto fail;
+ }
+
+ /* fill in metadata: on fragmented packets, it applies to the
+ first fragment only */
+ memcpy(&recon->r_meta.sender, &frame_address.ieee_src,
+ sizeof(ieee154_addr_t));
+ recon->r_meta.lqi = call ReadLqi.readLqi(msg);
+ recon->r_meta.rssi = call ReadLqi.readRssi(msg);
+
+ if (hasFrag1Header(&lowmsg)) {
+ if (recon->r_buf != NULL) goto fail;
+ rv = lowpan_recon_start(&frame_address, recon, buf, len);
+ } else {
+ rv = lowpan_recon_add(recon, buf, len);
+ }
+
+ if (rv < 0) {
+ recon->r_timeout = T_FAILED1;
+ goto fail;
+ } else {
+ // printf("start recon buf: %p\n", recon->r_buf);
+ recon->r_timeout = T_ACTIVE;
+ recon->r_source_key = source_key;
+ recon->r_tag = tag;
+ }
+
+ if (recon->r_size == recon->r_bytes_rcvd) {
+ deliver(recon);
+ }
+
+ } else {
+ /* no fragmentation, just deliver it */
+ int rv;
+ struct lowpan_reconstruct recon;
+
+ /* fill in metadata */
+ memcpy(&recon.r_meta.sender, &frame_address.ieee_src,
+ sizeof(ieee154_addr_t));
+ recon.r_meta.lqi = call ReadLqi.readLqi(msg);
+ recon.r_meta.rssi = call ReadLqi.readRssi(msg);
+
+ buf = getLowpanPayload(&lowmsg);
+ if ((rv = lowpan_recon_start(&frame_address, &recon, buf, len)) < 0) {
+ goto fail;
+ }
+
+ if (recon.r_size == recon.r_bytes_rcvd) {
+ deliver(&recon);
+ } else {
+ // printf("ip_free(%p)\n", recon.r_buf);
+ ip_free(recon.r_buf);
+ }
+ }
+ goto done;
+ fail:
+ BLIP_STATS_INCR(stats.rx_drop);
+ done:
+ return msg;
+ }
+
+
+ /*
+ * Send-side functionality
+ */
+ task void sendTask() {
+ struct send_entry *s_entry;
+
+ // printf("sendTask() - sending\n");
+
+ if (radioBusy || state != S_RUNNING) return;
+ if (call SendQueue.empty()) return;
+ // this does not dequeue
+ s_entry = call SendQueue.head();
+
+#ifdef LPL_SLEEP_INTERVAL
+ call LowPowerListening.setRemoteWakeupInterval(s_entry->msg,
+ call LowPowerListening.getLocalWakeupInterval());
+#endif
+
+ if (s_entry->info->failed) {
+ dbg("Drops", "drops: sendTask: dropping failed fragment\n");
+ goto fail;
+ }
+
+ if ((call Ieee154Send.send(s_entry->msg,
+ call BarePacket.payloadLength(s_entry->msg))) != SUCCESS) {
+ dbg("Drops", "drops: sendTask: send failed\n");
+ goto fail;
+ } else {
+ radioBusy = TRUE;
+ }
+
+ return;
+ fail:
+ printf("SEND FAIL\n");
+ post sendTask();
+ BLIP_STATS_INCR(stats.tx_drop);
+
+ // deallocate the memory associated with this request.
+ // other fragments associated with this packet will get dropped.
+ s_entry->info->failed = TRUE;
+ SENDINFO_DECR(s_entry->info);
+ call FragPool.put(s_entry->msg);
+ call SendEntryPool.put(s_entry);
+ call SendQueue.dequeue();
+ }
+
+
+ /*
+ * it will pack the message into the fragment pool and enqueue
+ * those fragments for sending
+ *
+ * it will set
+ * - payload length
+ * - version, traffic class and flow label
+ *
+ * the source and destination IP addresses must be set by higher
+ * layers.
+ */
+ command error_t IPLower.send(struct ieee154_frame_addr *frame_addr,
+ struct ip6_packet *msg,
+ void *data) {
+ struct lowpan_ctx ctx;
+ struct send_info *s_info;
+ struct send_entry *s_entry;
+ message_t *outgoing;
+
+ int frag_len = 1;
+ error_t rc = SUCCESS;
+
+ if (state != S_RUNNING) {
+ return EOFF;
+ }
+
+ /* set version to 6 in case upper layers forgot */
+ msg->ip6_hdr.ip6_vfc &= ~IPV6_VERSION_MASK;
+ msg->ip6_hdr.ip6_vfc |= IPV6_VERSION;
+
+ ctx.tag = current_local_label++;
+ ctx.offset = 0;
+
+ s_info = getSendInfo();
+ if (s_info == NULL) {
+ rc = ERETRY;
+ goto cleanup_outer;
+ }
+ s_info->upper_data = data;
+
+ while (frag_len > 0) {
+ s_entry = call SendEntryPool.get();
+ outgoing = call FragPool.get();
+
+ if (s_entry == NULL || outgoing == NULL) {
+ if (s_entry != NULL)
+ call SendEntryPool.put(s_entry);
+ if (outgoing != NULL)
+ call FragPool.put(outgoing);
+ // this will cause any fragments we have already enqueued to
+ // be dropped by the send task.
+ s_info->failed = TRUE;
+ printf("drops: IP send: no fragments\n");
+ rc = ERETRY;
+ goto done;
+ }
+
+ call BarePacket.clear(outgoing);
+ frag_len = lowpan_frag_get(call Ieee154Send.getPayload(outgoing, 0),
+ call BarePacket.maxPayloadLength(),
+ msg,
+ frame_addr,
+ &ctx);
+ if (frag_len < 0) {
+ printf(" get frag error: %i\n", frag_len);
+ }
+
+ printf("fragment length: %i offset: %i\n", frag_len, ctx.offset);
+ call BarePacket.setPayloadLength(outgoing, frag_len);
+
+ if (frag_len <= 0) {
+ call FragPool.put(outgoing);
+ call SendEntryPool.put(s_entry);
+ goto done;
+ }
+
+ if (call SendQueue.enqueue(s_entry) != SUCCESS) {
+ BLIP_STATS_INCR(stats.encfail);
+ s_info->failed = TRUE;
+ printf("drops: IP send: enqueue failed\n");
+ goto done;
+ }
+
+ s_info->link_fragments++;
+ s_entry->msg = outgoing;
+ s_entry->info = s_info;
+
+ /* configure the L2 */
+ if (frame_addr->ieee_dst.ieee_mode == IEEE154_ADDR_SHORT &&
+ frame_addr->ieee_dst.i_saddr == IEEE154_BROADCAST_ADDR) {
+ call PacketLink.setRetries(s_entry->msg, 0);
+ } else {
+ call PacketLink.setRetries(s_entry->msg, BLIP_L2_RETRIES);
+ }
+ call PacketLink.setRetryDelay(s_entry->msg, BLIP_L2_DELAY);
+
+ SENDINFO_INCR(s_info);}
+
+ // printf("got %i frags\n", s_info->link_fragments);
+ done:
+ BLIP_STATS_INCR(stats.sent);
+ SENDINFO_DECR(s_info);
+ post sendTask();
+ cleanup_outer:
+ return rc;
+ }
+
+ event void Ieee154Send.sendDone(message_t *msg, error_t error) {
+ struct send_entry *s_entry = call SendQueue.head();
+
+ radioBusy = FALSE;
+
+ // printf("sendDone: %p %i\n", msg, error);
+
+ if (state == S_STOPPING) {
+ call RadioControl.stop();
+ state = S_STOPPED;
+ goto done;
+ }
+
+ s_entry->info->link_transmissions += (call PacketLink.getRetries(msg));
+ s_entry->info->link_fragment_attempts++;
+
+ if (!call PacketLink.wasDelivered(msg)) {
+ printf("sendDone: was not delivered! (%i tries)\n",
+ call PacketLink.getRetries(msg));
+ s_entry->info->failed = TRUE;
+ signal IPLower.sendDone(s_entry->info);
+/* if (s_entry->info->policy.dest[0] != 0xffff) */
+/* dbg("Drops", "drops: sendDone: frag was not delivered\n"); */
+ // need to check for broadcast frames
+ // BLIP_STATS_INCR(stats.tx_drop);
+ } else if (s_entry->info->link_fragment_attempts ==
+ s_entry->info->link_fragments) {
+ signal IPLower.sendDone(s_entry->info);
+ }
+
+ done:
+ // kill off any pending fragments
+ SENDINFO_DECR(s_entry->info);
+ call FragPool.put(s_entry->msg);
+ call SendEntryPool.put(s_entry);
+ call SendQueue.dequeue();
+
+ post sendTask();
+ }
+
+#if 0
+ command struct tlv_hdr *IPExtensions.findTlv(struct ip6_ext *ext, uint8_t tlv_val) {
+ int len = ext->len - sizeof(struct ip6_ext);
+ struct tlv_hdr *tlv = (struct tlv_hdr *)(ext + 1);
+ while (len > 0) {
+ if (tlv->type == tlv_val) return tlv;
+ if (tlv->len == 0) return NULL;
+ tlv = (struct tlv_hdr *)(((uint8_t *)tlv) + tlv->len);
+ len -= tlv->len;
+ }
+ return NULL;
+ }
+#endif
+
+
+ /*
+ * BlipStatistics interface
+ */
+ command void BlipStatistics.get(ip_statistics_t *statistics) {
+#ifdef BLIP_STATS_IP_MEM
+ stats.fragpool = call FragPool.size();
+ stats.sendinfo = call SendInfoPool.size();
+ stats.sendentry= call SendEntryPool.size();
+ stats.sndqueue = call SendQueue.size();
+ stats.heapfree = ip_malloc_freespace();
+ printf("frag: %i sendinfo: %i sendentry: %i sendqueue: %i heap: %i\n",
+ stats.fragpool,
+ stats.sendinfo,
+ stats.sendentry,
+ stats.sndqueue,
+ stats.heapfree);
+#endif
+ memcpy(statistics, &stats, sizeof(ip_statistics_t));
+
+ }
+
+ command void BlipStatistics.clear() {
+ memclr((uint8_t *)&stats, sizeof(ip_statistics_t));
+ }
+
+/* default event void IP.recv[uint8_t nxt_hdr](struct ip6_hdr *iph, */
+/* void *payload, */
+/* struct ip_metadata *meta) { */
+/* } */
+
+/* default event void Multicast.recv[uint8_t scope](struct ip6_hdr *iph, */
+/* void *payload, */
+/* struct ip_metadata *meta) { */
+/* } */
+}
diff --git a/tests/examplefiles/RoleQ.pm6 b/tests/examplefiles/RoleQ.pm6
new file mode 100644
index 00000000..9b66bde4
--- /dev/null
+++ b/tests/examplefiles/RoleQ.pm6
@@ -0,0 +1,23 @@
+role q {
+ token stopper { \' }
+
+ token escape:sym<\\> { <sym> <item=.backslash> }
+
+ token backslash:sym<qq> { <?before 'q'> <quote=.LANG('MAIN','quote')> }
+ token backslash:sym<\\> { <text=.sym> }
+ token backslash:sym<stopper> { <text=.stopper> }
+
+ token backslash:sym<miscq> { {} . }
+
+ method tweak_q($v) { self.panic("Too late for :q") }
+ method tweak_qq($v) { self.panic("Too late for :qq") }
+}
+
+role qq does b1 does c1 does s1 does a1 does h1 does f1 {
+ token stopper { \" }
+ token backslash:sym<unrec> { {} (\w) { self.throw_unrecog_backslash_seq: $/[0].Str } }
+ token backslash:sym<misc> { \W }
+
+ method tweak_q($v) { self.panic("Too late for :q") }
+ method tweak_qq($v) { self.panic("Too late for :qq") }
+}
diff --git a/tests/examplefiles/all.nit b/tests/examplefiles/all.nit
new file mode 100644
index 00000000..d4e1ddfa
--- /dev/null
+++ b/tests/examplefiles/all.nit
@@ -0,0 +1,1986 @@
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import gtk
+
+class CalculatorContext
+ var result : nullable Float = null
+
+ var last_op : nullable Char = null
+
+ var current : nullable Float = null
+ var after_point : nullable Int = null
+
+ fun push_op( op : Char )
+ do
+ apply_last_op_if_any
+ if op == 'C' then
+ self.result = 0.0
+ last_op = null
+ else
+ last_op = op # store for next push_op
+ end
+
+ # prepare next current
+ after_point = null
+ current = null
+ end
+
+ fun push_digit( digit : Int )
+ do
+ var current = current
+ if current == null then current = 0.0
+
+ var after_point = after_point
+ if after_point == null then
+ current = current * 10.0 + digit.to_f
+ else
+ current = current + digit.to_f * 10.0.pow(after_point.to_f)
+ self.after_point -= 1
+ end
+
+ self.current = current
+ end
+
+ fun switch_to_decimals
+ do
+ if self.current == null then current = 0.0
+ if after_point != null then return
+
+ after_point = -1
+ end
+
+ fun apply_last_op_if_any
+ do
+ var op = last_op
+
+ var result = result
+ if result == null then result = 0.0
+
+ var current = current
+ if current == null then current = 0.0
+
+ if op == null then
+ result = current
+ else if op == '+' then
+ result = result + current
+ else if op == '-' then
+ result = result - current
+ else if op == '/' then
+ result = result / current
+ else if op == '*' then
+ result = result * current
+ end
+ self.result = result
+ self.current = null
+ end
+end
+
+class CalculatorGui
+ super GtkCallable
+
+ var win : GtkWindow
+ var container : GtkGrid
+
+ var lbl_disp : GtkLabel
+ var but_eq : GtkButton
+ var but_dot : GtkButton
+
+ var context = new CalculatorContext
+
+ redef fun signal( sender, user_data )
+ do
+ var after_point = context.after_point
+ if after_point == null then
+ after_point = 0
+ else
+ after_point = (after_point.abs)
+ end
+
+ if user_data isa Char then # is an operation
+ var c = user_data
+ if c == '.' then
+ but_dot.sensitive= false
+ context.switch_to_decimals
+ lbl_disp.text = "{context.current.to_i}."
+ else
+ but_dot.sensitive= true
+ context.push_op( c )
+
+ var s = context.result.to_precision_native(6)
+ var index : nullable Int = null
+ for i in s.length.times do
+ var chiffre = s.chars[i]
+ if chiffre == '0' and index == null then
+ index = i
+ else if chiffre != '0' then
+ index = null
+ end
+ end
+ if index != null then
+ s = s.substring(0, index)
+ if s.chars[s.length-1] == ',' then s = s.substring(0, s.length-1)
+ end
+ lbl_disp.text = s
+ end
+ else if user_data isa Int then # is a number
+ var n = user_data
+ context.push_digit( n )
+ lbl_disp.text = context.current.to_precision_native(after_point)
+ end
+ end
+
+ init
+ do
+ init_gtk
+
+ win = new GtkWindow( 0 )
+
+ container = new GtkGrid(5,5,true)
+ win.add( container )
+
+ lbl_disp = new GtkLabel( "_" )
+ container.attach( lbl_disp, 0, 0, 5, 1 )
+
+ # digits
+ for n in [0..9] do
+ var but = new GtkButton.with_label( n.to_s )
+ but.request_size( 64, 64 )
+ but.signal_connect( "clicked", self, n )
+ if n == 0 then
+ container.attach( but, 0, 4, 1, 1 )
+ else container.attach( but, (n-1)%3, 3-(n-1)/3, 1, 1 )
+ end
+
+ # operators
+ var r = 1
+ for op in ['+', '-', '*', '/' ] do
+ var but = new GtkButton.with_label( op.to_s )
+ but.request_size( 64, 64 )
+ but.signal_connect( "clicked", self, op )
+ container.attach( but, 3, r, 1, 1 )
+ r+=1
+ end
+
+ # =
+ but_eq = new GtkButton.with_label( "=" )
+ but_eq.request_size( 64, 64 )
+ but_eq.signal_connect( "clicked", self, '=' )
+ container.attach( but_eq, 4, 3, 1, 2 )
+
+ # .
+ but_dot = new GtkButton.with_label( "." )
+ but_dot.request_size( 64, 64 )
+ but_dot.signal_connect( "clicked", self, '.' )
+ container.attach( but_dot, 1, 4, 1, 1 )
+
+ #C
+ var but_c = new GtkButton.with_label( "C" )
+ but_c.request_size( 64, 64 )
+ but_c.signal_connect("clicked", self, 'C')
+ container.attach( but_c, 2, 4, 1, 1 )
+
+ win.show_all
+ end
+end
+
+# context tests
+var context = new CalculatorContext
+context.push_digit( 1 )
+context.push_digit( 2 )
+context.push_op( '+' )
+context.push_digit( 3 )
+context.push_op( '*' )
+context.push_digit( 2 )
+context.push_op( '=' )
+var r = context.result.to_precision( 2 )
+assert r == "30.00" else print r
+
+context = new CalculatorContext
+context.push_digit( 1 )
+context.push_digit( 4 )
+context.switch_to_decimals
+context.push_digit( 1 )
+context.push_op( '*' )
+context.push_digit( 3 )
+context.push_op( '=' )
+r = context.result.to_precision( 2 )
+assert r == "42.30" else print r
+
+context.push_op( '+' )
+context.push_digit( 1 )
+context.push_digit( 1 )
+context.push_op( '=' )
+r = context.result.to_precision( 2 )
+assert r == "53.30" else print r
+
+context = new CalculatorContext
+context.push_digit( 4 )
+context.push_digit( 2 )
+context.switch_to_decimals
+context.push_digit( 3 )
+context.push_op( '/' )
+context.push_digit( 3 )
+context.push_op( '=' )
+r = context.result.to_precision( 2 )
+assert r == "14.10" else print r
+
+#test multiple decimals
+context = new CalculatorContext
+context.push_digit( 5 )
+context.push_digit( 0 )
+context.switch_to_decimals
+context.push_digit( 1 )
+context.push_digit( 2 )
+context.push_digit( 3 )
+context.push_op( '+' )
+context.push_digit( 1 )
+context.push_op( '=' )
+r = context.result.to_precision( 3 )
+assert r == "51.123" else print r
+
+#test 'C' button
+context = new CalculatorContext
+context.push_digit( 1 )
+context.push_digit( 0 )
+context.push_op( '+' )
+context.push_digit( 1 )
+context.push_digit( 0 )
+context.push_op( '=' )
+context.push_op( 'C' )
+r = context.result.to_precision( 1 )
+assert r == "0.0" else print r
+
+# graphical application
+
+if "NIT_TESTING".environ != "true" then
+ var app = new CalculatorGui
+ run_gtk
+end
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This sample has been implemented to show you how simple is it to play
+# with native callbacks (C) through an high level with NIT program.
+
+module callback_chimpanze
+import callback_monkey
+
+class Chimpanze
+ super MonkeyActionCallable
+
+ fun create
+ do
+ var monkey = new Monkey
+ print "Hum, I'm sleeping ..."
+ # Invoking method which will take some time to compute, and
+ # will be back in wokeUp method with information.
+ # - Callback method defined in MonkeyActionCallable Interface
+ monkey.wokeUpAction(self, "Hey, I'm awake.")
+ end
+
+ # Inherit callback method, defined by MonkeyActionCallable interface
+ # - Back of wokeUpAction method
+ redef fun wokeUp( sender:Monkey, message:Object )
+ do
+ print message
+ end
+end
+
+var m = new Chimpanze
+m.create
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This sample has been implemented to show you how simple is it to play
+# with native callbacks (C) through an high level with NIT program.
+
+module callback_monkey
+
+in "C header" `{
+ #include <stdio.h>
+ #include <stdlib.h>
+
+ typedef struct {
+ int id;
+ int age;
+ } CMonkey;
+
+ typedef struct {
+ MonkeyActionCallable toCall;
+ Object message;
+ } MonkeyAction;
+`}
+
+in "C body" `{
+ // Method which reproduce a callback answer
+ // Please note that a function pointer is only used to reproduce the callback
+ void cbMonkey(CMonkey *mkey, void callbackFunc(CMonkey*, MonkeyAction*), MonkeyAction *data)
+ {
+ sleep(2);
+ callbackFunc( mkey, data );
+ }
+
+ // Back of background treatment, will be redirected to callback function
+ void nit_monkey_callback_func( CMonkey *mkey, MonkeyAction *data )
+ {
+ // To call a your method, the signature must be written like this :
+ // <Interface Name>_<Method>...
+ MonkeyActionCallable_wokeUp( data->toCall, mkey, data->message );
+ }
+`}
+
+# Implementable interface to get callback in defined methods
+interface MonkeyActionCallable
+ fun wokeUp( sender:Monkey, message: Object) is abstract
+end
+
+# Defining my object type Monkey, which is, in a low level, a pointer to a C struct (CMonkey)
+extern class Monkey `{ CMonkey * `}
+
+ new `{
+ CMonkey *monkey = malloc( sizeof(CMonkey) );
+ monkey->age = 10;
+ monkey->id = 1;
+ return monkey;
+ `}
+
+ # Object method which will get a callback in wokeUp method, defined in MonkeyActionCallable interface
+ # Must be defined as Nit/C method because of C call inside
+ fun wokeUpAction( toCall: MonkeyActionCallable, message: Object ) is extern import MonkeyActionCallable.wokeUp `{
+
+ // Allocating memory to keep reference of received parameters :
+ // - Object receiver
+ // - Message
+ MonkeyAction *data = malloc( sizeof(MonkeyAction) );
+
+ // Incrementing reference counter to prevent from releasing
+ MonkeyActionCallable_incr_ref( toCall );
+ Object_incr_ref( message );
+
+ data->toCall = toCall;
+ data->message = message;
+
+ // Calling method which reproduce a callback by passing :
+ // - Receiver
+ // - Function pointer to object return method
+ // - Datas
+ cbMonkey( recv, &nit_monkey_callback_func, data );
+ `}
+end
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Implementation of circular lists
+# This example shows the usage of generics and somewhat a specialisation of collections.
+module circular_list
+
+# Sequences of elements implemented with a double-linked circular list
+class CircularList[E]
+ # Like standard Array or LinkedList, CircularList is a Sequence.
+ super Sequence[E]
+
+ # The first node of the list if any
+ # The special case of an empty list is handled by a null node
+ private var node: nullable CLNode[E] = null
+
+ redef fun iterator do return new CircularListIterator[E](self)
+
+ redef fun first do return self.node.item
+
+ redef fun push(e)
+ do
+ var new_node = new CLNode[E](e)
+ var n = self.node
+ if n == null then
+ # the first node
+ self.node = new_node
+ else
+ # not the first one, so attach nodes correctly.
+ var old_last_node = n.prev
+ new_node.next = n
+ new_node.prev = old_last_node
+ old_last_node.next = new_node
+ n.prev = new_node
+ end
+ end
+
+ redef fun pop
+ do
+ var n = self.node
+ assert n != null
+ var prev = n.prev
+ if prev == n then
+ # the only node
+ self.node = null
+ return n.item
+ end
+ # not the only one do detach nodes correctly.
+ var prev_prev = prev.prev
+ n.prev = prev_prev
+ prev_prev.next = n
+ return prev.item
+ end
+
+ redef fun unshift(e)
+ do
+ # Circularity has benefits.
+ push(e)
+ self.node = self.node.prev
+ end
+
+ redef fun shift
+ do
+ # Circularity has benefits.
+ self.node = self.node.next
+ return self.pop
+ end
+
+ # Move the first at the last position, the second at the first, etc.
+ fun rotate
+ do
+ var n = self.node
+ if n == null then return
+ self.node = n.next
+ end
+
+ # Sort the list using the Josephus algorithm.
+ fun josephus(step: Int)
+ do
+ var res = new CircularList[E]
+ while not self.is_empty do
+ # count 'step'
+ for i in [1..step[ do self.rotate
+ # kill
+ var x = self.shift
+ res.add(x)
+ end
+ self.node = res.node
+ end
+end
+
+# Nodes of a CircularList
+private class CLNode[E]
+ # The current item
+ var item: E
+
+ # The next item in the circular list.
+ # Because of circularity, there is always a next;
+ # so by default let it be self
+ var next: CLNode[E] = self
+
+ # The previous item in the circular list.
+ # Coherence between next and previous nodes has to be maintained by the
+ # circular list.
+ var prev: CLNode[E] = self
+end
+
+# An iterator of a CircularList.
+private class CircularListIterator[E]
+ super IndexedIterator[E]
+
+ redef var index: Int
+
+ # The current node pointed.
+ # Is null if the list is empty.
+ var node: nullable CLNode[E]
+
+ # The list iterated.
+ var list: CircularList[E]
+
+ redef fun is_ok
+ do
+ # Empty lists are not OK.
+ # Pointing again the first node is not OK.
+ return self.node != null and (self.index == 0 or self.node != self.list.node)
+ end
+
+ redef fun next
+ do
+ self.node = self.node.next
+ self.index += 1
+ end
+
+ redef fun item do return self.node.item
+
+ init(list: CircularList[E])
+ do
+ self.node = list.node
+ self.list = list
+ self.index = 0
+ end
+end
+
+var i = new CircularList[Int]
+i.add_all([1, 2, 3, 4, 5, 6, 7])
+print i.first
+print i.join(":")
+
+i.push(8)
+print i.shift
+print i.pop
+i.unshift(0)
+print i.join(":")
+
+i.josephus(3)
+print i.join(":")
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This module beef up the clock module by allowing a clock to be comparable.
+# It show the usage of class refinement
+module clock_more
+
+import clock
+
+redef class Clock
+ # Clock are now comparable
+ super Comparable
+
+ # Comparaison of a clock make only sense with an other clock
+ redef type OTHER: Clock
+
+ redef fun <(o)
+ do
+ # Note: < is the only abstract method of Comparable.
+ # All other operators and methods rely on < and ==.
+ return self.total_minutes < o.total_minutes
+ end
+end
+
+var c1 = new Clock(8, 12)
+var c2 = new Clock(8, 13)
+var c3 = new Clock(9, 13)
+
+print "{c1}<{c2}? {c1<c2}"
+print "{c1}<={c2}? {c1<=c2}"
+print "{c1}>{c2}? {c1>c2}"
+print "{c1}>={c2}? {c1>=c2}"
+print "{c1}<=>{c2}? {c1<=>c2}"
+print "{c1},{c2}? max={c1.max(c2)} min={c1.min(c2)}"
+print "{c1}.is_between({c2}, {c3})? {c1.is_between(c2, c3)}"
+print "{c2}.is_between({c1}, {c3})? {c2.is_between(c1, c3)}"
+
+print "-"
+
+c1.minutes += 1
+
+print "{c1}<{c2}? {c1<c2}"
+print "{c1}<={c2}? {c1<=c2}"
+print "{c1}>{c2}? {c1>c2}"
+print "{c1}>={c2}? {c1>=c2}"
+print "{c1}<=>{c2}? {c1<=>c2}"
+print "{c1},{c2}? max={c1.max(c2)} min={c1.min(c2)}"
+print "{c1}.is_between({c2}, {c3})? {c1.is_between(c2, c3)}"
+print "{c2}.is_between({c1}, {c3})? {c2.is_between(c1, c3)}"
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This module provide a simple wall clock.
+# It is an example of getters and setters.
+# A beefed-up module is available in clock_more
+module clock
+
+# A simple wall clock with 60 minutes and 12 hours.
+class Clock
+ # total number of minutes from 0 to 719
+ var total_minutes: Int
+ # Note: only the read acces is public, the write access is private.
+
+ # number of minutes in the current hour (from 0 to 59)
+ fun minutes: Int do return self.total_minutes % 60
+
+ # set the number of minutes in the current hour.
+ # if m < 0 or m >= 60, the hour will be changed accordinlgy
+ fun minutes=(m: Int) do self.total_minutes = self.hours * 60 + m
+
+ # number of hours (from 0 to 11)
+ fun hours: Int do return self.total_minutes / 60
+
+ # set the number of hours
+ # the minutes will not be updated
+ fun hours=(h: Int) do self.total_minutes = h * 60 + minutes
+
+ # the position of the hour arrow in the [0..60[ interval
+ fun hour_pos: Int do return total_minutes / 12
+
+ # replace the arrow of hours (from 0 to 59).
+ # the hours and the minutes will be updated.
+ fun hour_pos=(h: Int) do self.total_minutes = h * 12
+
+ redef fun to_s do return "{hours}:{minutes}"
+
+ fun reset(hours, minutes: Int) do self.total_minutes = hours*60 + minutes
+
+ init(hours, minutes: Int) do self.reset(hours, minutes)
+
+ redef fun ==(o)
+ do
+ # Note: o is a nullable Object, a type test is required
+ # Thanks to adaptive typing, there is no downcast
+ # i.e. the code is safe!
+ return o isa Clock and self.total_minutes == o.total_minutes
+ end
+end
+
+var c = new Clock(10,50)
+print "It's {c} o'clock."
+
+c.minutes += 22
+print "Now it's {c} o'clock."
+
+print "The short arrow in on the {c.hour_pos/5} and the long arrow in on the {c.minutes/5}."
+
+c.hours -= 2
+print "Now it's {c} o'clock."
+
+var c2 = new Clock(9, 11)
+print "It's {c2} on the second clock."
+print "The two clocks are synchronized: {c == c2}."
+c2.minutes += 1
+print "It's now {c2} on the second clock."
+print "The two clocks are synchronized: {c == c2}."
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Sample of the Curl module.
+module curl_http
+
+import curl
+
+# Small class to represent an Http Fetcher
+class MyHttpFetcher
+ super CurlCallbacks
+
+ var curl: Curl
+ var our_body: String = ""
+
+ init(curl: Curl) do self.curl = curl
+
+ # Release curl object
+ fun destroy do self.curl.destroy
+
+ # Header callback
+ redef fun header_callback(line: String) do
+ # We keep this callback silent for testing purposes
+ #if not line.has_prefix("Date:") then print "Header_callback : {line}"
+ end
+
+ # Body callback
+ redef fun body_callback(line: String) do self.our_body = "{self.our_body}{line}"
+
+ # Stream callback - Cf : No one is registered
+ redef fun stream_callback(buffer: String, size: Int, count: Int) do print "Stream_callback : {buffer} - {size} - {count}"
+end
+
+
+# Program
+if args.length < 2 then
+ print "Usage: curl_http <method wished [POST, GET, GET_FILE]> <target url>"
+else
+ var curl = new Curl
+ var url = args[1]
+ var request = new CurlHTTPRequest(url, curl)
+
+ # HTTP Get Request
+ if args[0] == "GET" then
+ request.verbose = false
+ var getResponse = request.execute
+
+ if getResponse isa CurlResponseSuccess then
+ print "Status code : {getResponse.status_code}"
+ print "Body : {getResponse.body_str}"
+ else if getResponse isa CurlResponseFailed then
+ print "Error code : {getResponse.error_code}"
+ print "Error msg : {getResponse.error_msg}"
+ end
+
+ # HTTP Post Request
+ else if args[0] == "POST" then
+ var myHttpFetcher = new MyHttpFetcher(curl)
+ request.delegate = myHttpFetcher
+
+ var postDatas = new HeaderMap
+ postDatas["Bugs Bunny"] = "Daffy Duck"
+ postDatas["Batman"] = "Robin likes special characters @#ùà!è§'(\"é&://,;<>∞~*"
+ postDatas["Batman"] = "Yes you can set multiple identical keys, but APACHE will consider only once, the last one"
+ request.datas = postDatas
+ request.verbose = false
+ var postResponse = request.execute
+
+ print "Our body from the callback : {myHttpFetcher.our_body}"
+
+ if postResponse isa CurlResponseSuccess then
+ print "*** Answer ***"
+ print "Status code : {postResponse.status_code}"
+ print "Body should be empty, because we decided to manage callbacks : {postResponse.body_str.length}"
+ else if postResponse isa CurlResponseFailed then
+ print "Error code : {postResponse.error_code}"
+ print "Error msg : {postResponse.error_msg}"
+ end
+
+ # HTTP Get to file Request
+ else if args[0] == "GET_FILE" then
+ var headers = new HeaderMap
+ headers["Accept"] = "Moo"
+ request.headers = headers
+ request.verbose = false
+ var downloadResponse = request.download_to_file(null)
+
+ if downloadResponse isa CurlFileResponseSuccess then
+ print "*** Answer ***"
+ print "Status code : {downloadResponse.status_code}"
+ print "Size downloaded : {downloadResponse.size_download}"
+ else if downloadResponse isa CurlResponseFailed then
+ print "Error code : {downloadResponse.error_code}"
+ print "Error msg : {downloadResponse.error_msg}"
+ end
+ # Program logic
+ else
+ print "Usage : Method[POST, GET, GET_FILE]"
+ end
+end
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Mail sender sample using the Curl module
+module curl_mail
+
+import curl
+
+var curl = new Curl
+var mail_request = new CurlMailRequest(curl)
+
+# Networks
+var response = mail_request.set_outgoing_server("smtps://smtp.example.org:465", "user@example.org", "mypassword")
+if response isa CurlResponseFailed then
+ print "Error code : {response.error_code}"
+ print "Error msg : {response.error_msg}"
+end
+
+# Headers
+mail_request.from = "Billy Bob"
+mail_request.to = ["user@example.org"]
+mail_request.cc = ["bob@example.org"]
+mail_request.bcc = null
+
+var headers_body = new HeaderMap
+headers_body["Content-Type:"] = "text/html; charset=\"UTF-8\""
+headers_body["Content-Transfer-Encoding:"] = "quoted-printable"
+mail_request.headers_body = headers_body
+
+# Content
+mail_request.body = "<h1>Here you can write HTML stuff.</h1>"
+mail_request.subject = "Hello From My Nit Program"
+
+# Others
+mail_request.verbose = false
+
+# Send mail
+response = mail_request.execute
+if response isa CurlResponseFailed then
+ print "Error code : {response.error_code}"
+ print "Error msg : {response.error_msg}"
+else if response isa CurlMailResponseSuccess then
+ print "Mail Sent"
+else
+ print "Unknown Curl Response type"
+end
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2012-2013 Alexis Laferrière <alexis.laf@xymus.net>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Draws an arithmetic operation to the terminal
+module draw_operation
+
+redef enum Int
+ fun n_chars: Int `{
+ int c;
+ if ( abs(recv) >= 10 )
+ c = 1+(int)log10f( (float)abs(recv) );
+ else
+ c = 1;
+ if ( recv < 0 ) c ++;
+ return c;
+ `}
+end
+
+redef enum Char
+ fun as_operator(a, b: Int): Int
+ do
+ if self == '+' then return a + b
+ if self == '-' then return a - b
+ if self == '*' then return a * b
+ if self == '/' then return a / b
+ if self == '%' then return a % b
+ abort
+ end
+
+ fun override_dispc: Bool
+ do
+ return self == '+' or self == '-' or self == '*' or self == '/' or self == '%'
+ end
+
+ fun lines(s: Int): Array[Line]
+ do
+ if self == '+' then
+ return [new Line(new P(0,s/2),1,0,s), new Line(new P(s/2,1),0,1,s-2)]
+ else if self == '-' then
+ return [new Line(new P(0,s/2),1,0,s)]
+ else if self == '*' then
+ var lines = new Array[Line]
+ for y in [1..s-1[ do
+ lines.add( new Line(new P(1,y), 1,0,s-2) )
+ end
+ return lines
+ else if self == '/' then
+ return [new Line(new P(s-1,0), -1,1, s )]
+ else if self == '%' then
+ var q4 = s/4
+ var lines = [new Line(new P(s-1,0),-1,1,s)]
+ for l in [0..q4[ do
+ lines.append([ new Line( new P(0,l), 1,0,q4), new Line( new P(s-1,s-1-l), -1,0,q4) ])
+ end
+ return lines
+ else if self == '1' then
+ return [new Line(new P(s/2,0), 0,1,s),new Line(new P(0,s-1),1,0,s),
+ new Line( new P(s/2,0),-1,1,s/2)]
+ else if self == '2' then
+ return [new Line(new P(0,0), 1,0,s),new Line(new P(s-1,0),0,1,s/2),
+ new Line( new P(0,s-1),1,0,s), new Line( new P(0,s/2), 0,1,s/2),
+ new Line( new P(0,s/2), 1,0,s)]
+ else if self == '3' then
+ return [new Line(new P(0,0), 1,0,s),new Line(new P(s-1,0),0,1,s),
+ new Line( new P(0,s-1),1,0,s), new Line( new P(0,s/2), 1,0,s)]
+ else if self == '4' then
+ return [new Line(new P(s-1,0),0,1,s), new Line( new P(0,0), 0,1,s/2),
+ new Line( new P(0,s/2), 1,0,s)]
+ else if self == '5' then
+ return [new Line(new P(0,0), 1,0,s),new Line(new P(s-1,s/2),0,1,s/2),
+ new Line( new P(0,s-1),1,0,s), new Line( new P(0,0), 0,1,s/2),
+ new Line( new P(0,s/2), 1,0,s)]
+ else if self == '6' then
+ return [new Line(new P(0,0), 1,0,s),new Line(new P(s-1,s/2),0,1,s/2),
+ new Line( new P(0,s-1),1,0,s), new Line( new P(0,0), 0,1,s),
+ new Line( new P(0,s/2), 1,0,s)]
+ else if self == '7' then
+ var tl = new P(0,0)
+ var tr = new P(s-1,0)
+ return [new Line(tl, 1,0,s), new Line(tr,-1,1,s)]
+ else if self == '8' then
+ return [new Line(new P(0,0), 1,0,s),new Line(new P(s-1,0),0,1,s),
+ new Line( new P(0,s-1),1,0,s), new Line( new P(0,0), 0,1,s),
+ new Line( new P(0,s/2), 1,0,s)]
+ else if self == '9' then
+ return [new Line(new P(0,0), 1,0,s),new Line(new P(s-1,0),0,1,s),
+ new Line( new P(0,s-1),1,0,s), new Line( new P(0,0), 0,1,s/2),
+ new Line( new P(0,s/2), 1,0,s)]
+ else if self == '0' then
+ return [new Line(new P(0,0), 1,0,s),new Line(new P(s-1,0),0,1,s),
+ new Line( new P(0,s-1),1,0,s), new Line( new P(0,0), 0,1,s)]
+ end
+ return new Array[Line]
+ end
+end
+
+class P
+ var x : Int
+ var y : Int
+end
+
+redef class String
+ # hack is to support a bug in the evaluation software
+ fun draw(dispc: Char, size, gap: Int, hack: Bool)
+ do
+ var w = size * length +(length-1)*gap
+ var h = size
+ var map = new Array[Array[Char]]
+ for x in [0..w[ do
+ map[x] = new Array[Char].filled_with( ' ', h )
+ end
+
+ var ci = 0
+ for c in self.chars do
+ var local_dispc
+ if c.override_dispc then
+ local_dispc = c
+ else
+ local_dispc = dispc
+ end
+
+ var lines = c.lines( size )
+ for line in lines do
+ var x = line.o.x+ci*size
+ x += ci*gap
+ var y = line.o.y
+ for s in [0..line.len[ do
+ assert map.length > x and map[x].length > y else print "setting {x},{y} as {local_dispc}"
+ map[x][y] = local_dispc
+ x += line.step_x
+ y += line.step_y
+ end
+ end
+
+ ci += 1
+ end
+
+ if hack then
+ for c in [0..size[ do
+ map[c][0] = map[map.length-size+c][0]
+ map[map.length-size+c][0] = ' '
+ end
+ end
+
+ for y in [0..h[ do
+ for x in [0..w[ do
+ printn map[x][y]
+ end
+ print ""
+ end
+ end
+end
+
+class Line
+ var o : P
+ var step_x : Int
+ var step_y : Int
+ var len : Int
+end
+
+var a
+var b
+var op_char
+var disp_char
+var disp_size
+var disp_gap
+
+if "NIT_TESTING".environ == "true" then
+ a = 567
+ b = 13
+ op_char = '*'
+ disp_char = 'O'
+ disp_size = 8
+ disp_gap = 1
+else
+ printn "Left operand: "
+ a = gets.to_i
+
+ printn "Right operand: "
+ b = gets.to_i
+
+ printn "Operator (+, -, *, /, %): "
+ op_char = gets.chars[0]
+
+ printn "Char to display: "
+ disp_char = gets.chars[0]
+
+ printn "Size of text: "
+ disp_size = gets.to_i
+
+ printn "Space between digits: "
+ disp_gap = gets.to_i
+end
+
+var result = op_char.as_operator( a, b )
+
+var len_a = a.n_chars
+var len_b = b.n_chars
+var len_res = result.n_chars
+var max_len = len_a.max( len_b.max( len_res ) ) + 1
+
+# draw first line
+var d = max_len - len_a
+var line_a = ""
+for i in [0..d[ do line_a += " "
+line_a += a.to_s
+line_a.draw( disp_char, disp_size, disp_gap, false )
+
+print ""
+# draw second line
+d = max_len - len_b-1
+var line_b = op_char.to_s
+for i in [0..d[ do line_b += " "
+line_b += b.to_s
+line_b.draw( disp_char, disp_size, disp_gap, false )
+
+# draw -----
+print ""
+for i in [0..disp_size*max_len+(max_len-1)*disp_gap] do
+ printn "_"
+end
+print ""
+print ""
+
+# draw result
+d = max_len - len_res
+var line_res = ""
+for i in [0..d[ do line_res += " "
+line_res += result.to_s
+line_res.draw( disp_char, disp_size, disp_gap, false )
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Alexis Laferrière <alexis.laf@xymus.net>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Example using the privileges module to drop privileges from root
+module drop_privileges
+
+import privileges
+
+# basic command line options
+var opts = new OptionContext
+var opt_ug = new OptionUserAndGroup.for_dropping_privileges
+opt_ug.mandatory = true
+opts.add_option(opt_ug)
+
+# parse and check command line options
+opts.parse(args)
+if not opts.errors.is_empty then
+ print opts.errors
+ print "Usage: drop_privileges [options]"
+ opts.usage
+ exit 1
+end
+
+# original user
+print "before {sys.uid}:{sys.gid}"
+
+# make the switch
+var user_group = opt_ug.value
+assert user_group != null
+user_group.drop_privileges
+
+# final user
+print "after {sys.uid}:{sys.egid}"
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2012-2013 Alexis Laferrière <alexis.laf@xymus.net>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# This module illustrates some uses of the FFI, specifically
+# how to use extern methods. Which means to implement a Nit method in C.
+module extern_methods
+
+redef enum Int
+ # Returns self'th fibonnaci number
+ # implemented here in C for optimization purposes
+ fun fib : Int import fib `{
+ if ( recv < 2 )
+ return recv;
+ else
+ return Int_fib( recv-1 ) + Int_fib( recv-2 );
+ `}
+
+ # System call to sleep for "self" seconds
+ fun sleep `{
+ sleep( recv );
+ `}
+
+ # Return atan2l( self, x ) from libmath
+ fun atan_with( x : Int ) : Float `{
+ return atan2( recv, x );
+ `}
+
+ # This method callback to Nit methods from C code
+ # It will use from C code:
+ # * the local fib method
+ # * the + operator, a method of Int
+ # * to_s, a method of all objects
+ # * String.to_cstring, a method of String to return an equivalent char*
+ fun foo import fib, +, to_s, String.to_cstring `{
+ long recv_fib = Int_fib( recv );
+ long recv_plus_fib = Int__plus( recv, recv_fib );
+
+ String nit_string = Int_to_s( recv_plus_fib );
+ char *c_string = String_to_cstring( nit_string );
+
+ printf( "from C: self + fib(self) = %s\n", c_string );
+ `}
+
+ # Equivalent to foo but written in pure Nit
+ fun bar do print "from Nit: self + fib(self) = {self+self.fib}"
+end
+
+print 12.fib
+
+print "sleeping 1 second..."
+1.sleep
+
+print 100.atan_with( 200 )
+8.foo
+8.bar
+
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2004-2008 Jean Privat <jean@pryen.org>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# A simple exemple of refinement where a method is added to the integer class.
+module fibonacci
+
+redef class Int
+ # Calculate the self-th element of the fibonacci sequence.
+ fun fibonacci: Int
+ do
+ if self < 2 then
+ return 1
+ else
+ return (self-2).fibonacci + (self-1).fibonacci
+ end
+ end
+end
+
+# Print usage and exit.
+fun usage
+do
+ print "Usage: fibonnaci <integer>"
+ exit 0
+end
+
+# Main part
+if args.length != 1 then
+ usage
+end
+print args.first.to_i.fibonacci
+print "hello world"
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import html
+
+class NitHomepage
+ super HTMLPage
+
+ redef fun head do
+ add("meta").attr("charset", "utf-8")
+ add("title").text("Nit")
+ add("link").attr("rel", "icon").attr("href", "http://nitlanguage.org/favicon.ico").attr("type", "image/x-icon")
+ add("link").attr("rel", "stylesheet").attr("href", "http://nitlanguage.org/style.css").attr("type", "text/css")
+ add("link").attr("rel", "stylesheet").attr("href", "http://nitlanguage.org/local.css").attr("type", "text/css")
+ end
+
+ redef fun body do
+ open("article").add_class("page")
+ open("section").add_class("pageheader")
+ add_html("<a id='toptitle_first' class='toptitle'>the</a><a id='toptitle_second' class='toptitle' href=''>Nit</a><a id='toptitle_third' class='toptitle' href=''>Programming Language</a>")
+ open("header").add_class("header")
+ open("div").add_class("topsubtitle")
+ add("p").text("A Fun Language for Serious Programming")
+ close("div")
+ close("header")
+ close("section")
+
+ open("div").attr("id", "pagebody")
+ open("section").attr("id", "content")
+ add("h1").text("# What is Nit?")
+ add("p").text("Nit is an object-oriented programming language. The goal of Nit is to propose a robust statically typed programming language where structure is not a pain.")
+ add("p").text("So, what does the famous hello world program look like, in Nit?")
+ add_html("<pre><tt><span class='normal'>print </span><span class='string'>'Hello, World!'</span></tt></pre>")
+
+ add("h1").text("# Feature Highlights")
+ add("h2").text("Usability")
+ add("p").text("Nit's goal is to be usable by real programmers for real projects")
+
+ open("ul")
+ open("li")
+ add("a").attr("href", "http://en.wikipedia.org/wiki/KISS_principle").text("KISS principle")
+ close("li")
+ add("li").text("Script-like language without verbosity nor cryptic statements")
+ add("li").text("Painless static types: static typing should help programmers")
+ add("li").text("Efficient development, efficient execution, efficient evolution.")
+ close("ul")
+
+ add("h2").text("Robustness")
+ add("p").text("Nit will help you to write bug-free programs")
+
+ open("ul")
+ add("li").text("Strong static typing")
+ add("li").text("No more NullPointerException")
+ close("ul")
+
+ add("h2").text("Object-Oriented")
+ add("p").text("Nit's guideline is to follow the most powerful OO principles")
+
+ open("ul")
+ open("li")
+ add("a").attr("href", "./everything_is_an_object/").text("Everything is an object")
+ close("li")
+ open("li")
+ add("a").attr("href", "./multiple_inheritance/").text("Multiple inheritance")
+ close("li")
+ open("li")
+ add("a").attr("href", "./refinement/").text("Open classes")
+ close("li")
+ open("li")
+ add("a").attr("href", "./virtual_types/").text("Virtual types")
+ close("li")
+ close("ul")
+
+
+ add("h1").text("# Getting Started")
+ add("p").text("Get Nit from its Git repository:")
+
+ add_html("<pre><code>$ git clone http://nitlanguage.org/nit.git</code></pre>")
+ add("p").text("Build the compiler (may be long):")
+ add_html("<pre><code>$ cd nit\n")
+ add_html("$ make</code></pre>")
+ add("p").text("Compile a program:")
+ add_html("<pre><code>$ bin/nitc examples/hello_world.nit</code></pre>")
+ add("p").text("Execute the program:")
+ add_html("<pre><code>$ ./hello_world</code></pre>")
+ close("section")
+ close("div")
+ close("article")
+ end
+end
+
+var page = new NitHomepage
+page.write_to stdout
+page.write_to_file("nit.html")
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# An example that defines and uses stacks of integers.
+# The implementation is done with a simple linked list.
+# It features: free constructors, nullable types and some adaptive typing.
+module int_stack
+
+# A stack of integer implemented by a simple linked list.
+# Note that this is only a toy class since a real linked list will gain to use
+# generics and extends interfaces, like Collection, from the standard library.
+class IntStack
+ # The head node of the list.
+ # Null means that the stack is empty.
+ private var head: nullable ISNode = null
+
+ # Add a new integer in the stack.
+ fun push(val: Int)
+ do
+ self.head = new ISNode(val, self.head)
+ end
+
+ # Remove and return the last pushed integer.
+ # Return null if the stack is empty.
+ fun pop: nullable Int
+ do
+ var head = self.head
+ if head == null then return null
+ # Note: the followings are statically safe because of the
+ # previous 'if'.
+ var val = head.val
+ self.head = head.next
+ return val
+ end
+
+ # Return the sum of all integers of the stack.
+ # Return 0 if the stack is empty.
+ fun sumall: Int
+ do
+ var sum = 0
+ var cur = self.head
+ while cur != null do
+ # Note: the followings are statically safe because of
+ # the condition of the 'while'.
+ sum += cur.val
+ cur = cur.next
+ end
+ return sum
+ end
+
+ # Note: Because all attributes have a default value, a free constructor
+ # "init()" is implicitly defined.
+end
+
+# A node of a IntStack
+private class ISNode
+ # The integer value stored in the node.
+ var val: Int
+
+ # The next node, if any.
+ var next: nullable ISNode
+
+ # Note: A free constructor "init(val: Int, next: nullable ISNode)" is
+ # implicitly defined.
+end
+
+var l = new IntStack
+l.push(1)
+l.push(2)
+l.push(3)
+
+print l.sumall
+
+# Note: the 'for' control structure cannot be used on IntStack in its current state.
+# It requires a more advanced topic.
+# However, why not using the 'loop' control structure?
+loop
+ var i = l.pop
+ if i == null then break
+ # The following is statically safe because of the previous 'if'.
+ print i * 10
+end
+
+# Note: 'or else' is used to give an alternative of a null expression.
+l.push(5)
+print l.pop or else 0 # l.pop gives 5, so print 5
+print l.pop or else 0 # l.pop gives null, so print the alternative: 0
+
+
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2014 Alexis Laferrière <alexis.laf@xymus.net>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Basic example of OpenGL ES 2.0 usage from the book OpenGL ES 2.0 Programming Guide.
+#
+# Code reference:
+# https://code.google.com/p/opengles-book-samples/source/browse/trunk/LinuxX11/Chapter_2/Hello_Triangle/Hello_Triangle.c
+module opengles2_hello_triangle
+
+import glesv2
+import egl
+import mnit_linux # for sdl
+import x11
+
+if "NIT_TESTING".environ == "true" then exit(0)
+
+var window_width = 800
+var window_height = 600
+
+#
+## SDL
+#
+var sdl_display = new SDLDisplay(window_width, window_height)
+var sdl_wm_info = new SDLSystemWindowManagerInfo
+var x11_window_handle = sdl_wm_info.x11_window_handle
+
+#
+## X11
+#
+var x_display = x_open_default_display
+assert x_display != 0 else print "x11 fail"
+
+#
+## EGL
+#
+var egl_display = new EGLDisplay(x_display)
+assert egl_display.is_valid else print "EGL display is not valid"
+egl_display.initialize
+
+print "EGL version: {egl_display.version}"
+print "EGL vendor: {egl_display.vendor}"
+print "EGL extensions: {egl_display.extensions.join(", ")}"
+print "EGL client APIs: {egl_display.client_apis.join(", ")}"
+
+assert egl_display.is_valid else print egl_display.error
+
+var config_chooser = new EGLConfigChooser
+#config_chooser.surface_type_egl
+config_chooser.blue_size = 8
+config_chooser.green_size = 8
+config_chooser.red_size = 8
+#config_chooser.alpha_size = 8
+#config_chooser.depth_size = 8
+#config_chooser.stencil_size = 8
+#config_chooser.sample_buffers = 1
+config_chooser.close
+
+var configs = config_chooser.choose(egl_display)
+assert configs != null else print "choosing config failed: {egl_display.error}"
+assert not configs.is_empty else print "no EGL config"
+
+print "{configs.length} EGL configs available"
+for config in configs do
+ var attribs = config.attribs(egl_display)
+ print "* caveats: {attribs.caveat}"
+ print " conformant to: {attribs.conformant}"
+ print " size of RGBA: {attribs.red_size} {attribs.green_size} {attribs.blue_size} {attribs.alpha_size}"
+ print " buffer, depth, stencil: {attribs.buffer_size} {attribs.depth_size} {attribs.stencil_size}"
+end
+
+var config = configs.first
+
+var format = config.attribs(egl_display).native_visual_id
+
+# TODO android part
+# Opengles1Display_midway_init(recv, format);
+
+var surface = egl_display.create_window_surface(config, x11_window_handle, [0])
+assert surface.is_ok else print egl_display.error
+
+var context = egl_display.create_context(config)
+assert context.is_ok else print egl_display.error
+
+var make_current_res = egl_display.make_current(surface, surface, context)
+assert make_current_res
+
+var width = surface.attribs(egl_display).width
+var height = surface.attribs(egl_display).height
+print "Width: {width}"
+print "Height: {height}"
+
+assert egl_bind_opengl_es_api else print "eglBingAPI failed: {egl_display.error}"
+
+#
+## GLESv2
+#
+
+print "Can compile shaders? {gl_shader_compiler}"
+assert_no_gl_error
+
+assert gl_shader_compiler else print "Cannot compile shaders"
+
+# gl program
+print gl_error.to_s
+var program = new GLProgram
+if not program.is_ok then
+ print "Program is not ok: {gl_error.to_s}\nLog:"
+ print program.info_log
+ abort
+end
+assert_no_gl_error
+
+# vertex shader
+var vertex_shader = new GLVertexShader
+assert vertex_shader.is_ok else print "Vertex shader is not ok: {gl_error}"
+vertex_shader.source = """
+attribute vec4 vPosition;
+void main()
+{
+ gl_Position = vPosition;
+} """
+vertex_shader.compile
+assert vertex_shader.is_compiled else print "Vertex shader compilation failed with: {vertex_shader.info_log} {program.info_log}"
+assert_no_gl_error
+
+# fragment shader
+var fragment_shader = new GLFragmentShader
+assert fragment_shader.is_ok else print "Fragment shader is not ok: {gl_error}"
+fragment_shader.source = """
+precision mediump float;
+void main()
+{
+ gl_FragColor = vec4(1.0, 0.0, 0.0, 1.0);
+}
+"""
+fragment_shader.compile
+assert fragment_shader.is_compiled else print "Fragment shader compilation failed with: {fragment_shader.info_log}"
+assert_no_gl_error
+
+program.attach_shader vertex_shader
+program.attach_shader fragment_shader
+program.bind_attrib_location(0, "vPosition")
+program.link
+assert program.is_linked else print "Linking failed: {program.info_log}"
+assert_no_gl_error
+
+# draw!
+var vertices = [0.0, 0.5, 0.0, -0.5, -0.5, 0.0, 0.5, -0.5, 0.0]
+var vertex_array = new VertexArray(0, 3, vertices)
+vertex_array.attrib_pointer
+gl_clear_color(0.5, 0.0, 0.5, 1.0)
+for i in [0..10000[ do
+ printn "."
+ assert_no_gl_error
+ gl_viewport(0, 0, width, height)
+ gl_clear_color_buffer
+ program.use
+ vertex_array.enable
+ vertex_array.draw_arrays_triangles
+ egl_display.swap_buffers(surface)
+end
+
+# delete
+program.delete
+vertex_shader.delete
+fragment_shader.delete
+
+#
+## EGL
+#
+# close
+egl_display.make_current(new EGLSurface.none, new EGLSurface.none, new EGLContext.none)
+egl_display.destroy_context(context)
+egl_display.destroy_surface(surface)
+
+#
+## SDL
+#
+# close
+sdl_display.destroy
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2004-2008 Jean Privat <jean@pryen.org>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# How to print arguments of the command line.
+module print_arguments
+
+for a in args do
+ print a
+end
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2004-2008 Jean Privat <jean@pryen.org>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# A procedural program (without explicit class definition).
+# This program manipulates arrays of integers.
+module procedural_array
+
+# The sum of the elements of `a'.
+# Uses a 'for' control structure.
+fun array_sum(a: Array[Int]): Int
+do
+ var sum = 0
+ for i in a do
+ sum = sum + i
+ end
+ return sum
+end
+
+# The sum of the elements of `a' (alternative version).
+# Uses a 'while' control structure.
+fun array_sum_alt(a: Array[Int]): Int
+do
+ var sum = 0
+ var i = 0
+ while i < a.length do
+ sum = sum + a[i]
+ i = i + 1
+ end
+ return sum
+end
+
+# The main part of the program.
+var a = [10, 5, 8, 9]
+print(array_sum(a))
+print(array_sum_alt(a))
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Client sample using the Socket module which connect to the server sample.
+module socket_client
+
+import socket
+
+if args.length < 2 then
+ print "Usage : socket_client <host> <port>"
+ return
+end
+
+var s = new Socket.client(args[0], args[1].to_i)
+print "[HOST ADDRESS] : {s.address}"
+print "[HOST] : {s.host}"
+print "[PORT] : {s.port}"
+print "Connecting ... {s.connected}"
+if s.connected then
+ print "Writing ... Hello server !"
+ s.write("Hello server !")
+ print "[Response from server] : {s.read(100)}"
+ print "Closing ..."
+ s.close
+end
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Server sample using the Socket module which allow client to connect
+module socket_server
+
+import socket
+
+if args.is_empty then
+ print "Usage : socket_server <port>"
+ return
+end
+
+var socket = new Socket.server(args[0].to_i, 1)
+print "[PORT] : {socket.port.to_s}"
+
+var clients = new Array[Socket]
+var max = socket
+loop
+ var fs = new SocketObserver(true, true, true)
+ fs.readset.set(socket)
+
+ for c in clients do fs.readset.set(c)
+
+ if fs.select(max, 4, 0) == 0 then
+ print "Error occured in select {sys.errno.strerror}"
+ break
+ end
+
+ if fs.readset.is_set(socket) then
+ var ns = socket.accept
+ print "Accepting {ns.address} ... "
+ print "[Message from {ns.address}] : {ns.read(100)}"
+ ns.write("Goodbye client.")
+ print "Closing {ns.address} ..."
+ ns.close
+ end
+end
+
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+import template
+
+### Here, definition of the specific templates
+
+# The root template for composers
+class TmplComposers
+ super Template
+
+ # Short list of composers
+ var composers = new Array[TmplComposer]
+
+ # Detailled list of composers
+ var composer_details = new Array[TmplComposerDetail]
+
+ # Add a composer in both lists
+ fun add_composer(firstname, lastname: String, birth, death: Int)
+ do
+ composers.add(new TmplComposer(lastname))
+ composer_details.add(new TmplComposerDetail(firstname, lastname, birth, death))
+ end
+
+ redef fun rendering do
+ add """
+COMPOSERS
+=========
+"""
+ add_all composers
+ add """
+
+DETAILS
+=======
+"""
+ add_all composer_details
+ end
+end
+
+# A composer in the short list of composers
+class TmplComposer
+ super Template
+
+ # Short name
+ var name: String
+
+ init(name: String) do self.name = name
+
+ redef fun rendering do add "- {name}\n"
+end
+
+# A composer in the detailled list of composers
+class TmplComposerDetail
+ super Template
+
+ var firstname: String
+ var lastname: String
+ var birth: Int
+ var death: Int
+
+ init(firstname, lastname: String, birth, death: Int) do
+ self.firstname = firstname
+ self.lastname = lastname
+ self.birth = birth
+ self.death = death
+ end
+
+ redef fun rendering do add """
+
+COMPOSER: {{{firstname}}} {{{lastname}}}
+BIRTH...: {{{birth}}}
+DEATH...: {{{death}}}
+"""
+
+end
+
+### Here a simple usage of the templates
+
+var f = new TmplComposers
+f.add_composer("Johann Sebastian", "Bach", 1685, 1750)
+f.add_composer("George Frideric", "Handel", 1685, 1759)
+f.add_composer("Wolfgang Amadeus", "Mozart", 1756, 1791)
+f.write_to(stdout)
+# This file is part of NIT ( http://www.nitlanguage.org ).
+#
+# Copyright 2014 Lucas Bajolet <r4pass@hotmail.com>
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+
+# Sample module for a minimal chat server using Websockets on port 8088
+module websocket_server
+
+import websocket
+
+var sock = new WebSocket(8088, 1)
+
+var msg: String
+
+if sock.listener.eof then
+ print sys.errno.strerror
+end
+
+sock.accept
+
+while not sock.listener.eof do
+ if not sock.connected then sock.accept
+ if sys.stdin.poll_in then
+ msg = gets
+ printn "Received message : {msg}"
+ if msg == "exit" then sock.close
+ if msg == "disconnect" then sock.disconnect_client
+ sock.write(msg)
+ end
+ if sock.can_read(10) then
+ msg = sock.read_line
+ if msg != "" then print msg
+ end
+end
+
diff --git a/tests/examplefiles/ANTLRv3.g b/tests/examplefiles/antlr_ANTLRv3.g
index fbe6d654..fbe6d654 100644
--- a/tests/examplefiles/ANTLRv3.g
+++ b/tests/examplefiles/antlr_ANTLRv3.g
diff --git a/tests/examplefiles/clojure-weird-keywords.clj b/tests/examplefiles/clojure-weird-keywords.clj
new file mode 100644
index 00000000..2d914c59
--- /dev/null
+++ b/tests/examplefiles/clojure-weird-keywords.clj
@@ -0,0 +1,5 @@
+; Note, clojure lexer is here (and is a good deal more liberal than the language spec:
+; https://github.com/clojure/clojure/blob/master/src/jvm/clojure/lang/LispReader.java#L62
+
+(defn valid [#^java.lang.reflect.Method meth]
+ [:keyword :#initial-hash :h#sh-in-middle :hash-at-end# #js {:keyword "value"}])
diff --git a/tests/examplefiles/core.cljs b/tests/examplefiles/core.cljs
new file mode 100644
index 00000000..f135b832
--- /dev/null
+++ b/tests/examplefiles/core.cljs
@@ -0,0 +1,52 @@
+
+(ns bounder.core
+ (:require [bounder.html :as html]
+ [domina :refer [value set-value! single-node]]
+ [domina.css :refer [sel]]
+ [lowline.functions :refer [debounce]]
+ [enfocus.core :refer [at]]
+ [cljs.reader :as reader]
+ [clojure.string :as s])
+ (:require-macros [enfocus.macros :as em]))
+
+(def filter-input
+ (single-node
+ (sel ".search input")))
+
+(defn project-matches [query project]
+ (let [words (cons (:name project)
+ (map name (:categories project)))
+ to-match (->> words
+ (s/join "")
+ (s/lower-case))]
+ (<= 0 (.indexOf to-match (s/lower-case query)))))
+
+(defn apply-filter-for [projects]
+ (let [query (value filter-input)]
+ (html/render-projects
+ (filter (partial project-matches query)
+ projects))))
+
+(defn filter-category [projects evt]
+ (let [target (.-currentTarget evt)]
+ (set-value! filter-input
+ (.-innerHTML target))
+ (apply-filter-for projects)))
+
+(defn init-listeners [projects]
+ (at js/document
+ ["input"] (em/listen
+ :keyup
+ (debounce
+ (partial apply-filter-for projects)
+ 500))
+ [".category-links li"] (em/listen
+ :click
+ (partial filter-category projects))))
+
+(defn init [projects-edn]
+ (let [projects (reader/read-string projects-edn)]
+ (init-listeners projects)
+ (html/render-projects projects)
+ (html/loaded)))
+
diff --git a/tests/examplefiles/demo.cfm b/tests/examplefiles/demo.cfm
index d94a06a0..78098c05 100644
--- a/tests/examplefiles/demo.cfm
+++ b/tests/examplefiles/demo.cfm
@@ -1,4 +1,11 @@
<!--- cfcomment --->
+<!--- nested <!--- cfcomment ---> --->
+<!--- multi-line
+nested
+<!---
+cfcomment
+--->
+--->
<!-- html comment -->
<html>
<head>
@@ -17,6 +24,9 @@
#IsDate("foo")#<br />
#DaysInMonth(RightNow)#
</cfoutput>
+<cfset x="x">
+<cfset y="y">
+<cfset z="z">
<cfoutput group="x">
#x#
<cfoutput>#y#</cfoutput>
@@ -29,10 +39,12 @@
<cfset greeting = "Hello #person#">
<cfset greeting = "Hello" & " world!">
+<cfset a = 5>
+<cfset b = 10>
<cfset c = a^b>
<cfset c = a MOD b>
<cfset c = a / b>
<cfset c = a * b>
<cfset c = a + b>
<cfset c = a - b>
-
+<!--- <!-- another <!--- nested --> ---> comment --->
diff --git a/tests/examplefiles/demo.hbs b/tests/examplefiles/demo.hbs
new file mode 100644
index 00000000..1b9ed5a7
--- /dev/null
+++ b/tests/examplefiles/demo.hbs
@@ -0,0 +1,12 @@
+<!-- post.handlebars -->
+
+<div class='intro'>
+ {{intro}}
+</div>
+
+{{#if isExpanded}}
+ <div class='body'>{{body}}</div>
+ <button {{action contract}}>Contract</button>
+{{else}}
+ <button {{action expand}}>Show More...</button>
+{{/if}}
diff --git a/tests/examplefiles/docker.docker b/tests/examplefiles/docker.docker
new file mode 100644
index 00000000..d65385b6
--- /dev/null
+++ b/tests/examplefiles/docker.docker
@@ -0,0 +1,5 @@
+maintainer First O'Last
+
+run echo \
+ 123 $bar
+# comment
diff --git a/tests/examplefiles/ember.handlebars b/tests/examplefiles/ember.handlebars
new file mode 100644
index 00000000..515dffbd
--- /dev/null
+++ b/tests/examplefiles/ember.handlebars
@@ -0,0 +1,33 @@
+{{#view EmberFirebaseChat.ChatView class="chat-container"}}
+ <div class="chat-messages-container">
+ <ul class="chat-messages">
+ {{#each message in content}}
+ <li>
+ [{{formatTimestamp "message.timestamp" fmtString="h:mm:ss A"}}]
+ <strong>{{message.sender}}</strong>: {{message.content}}
+ </li>
+ {{/each}}
+ </ul>
+ </div>
+
+ {{! Comment }}
+ {{{unescaped value}}}
+
+ {{#view EmberFirebaseChat.InputView class="chat-input-container"}}
+ <form class="form-inline">
+ {{#if "auth.authed"}}
+ {{#if "auth.hasName"}}
+ <input type="text" id="message" placeholder="Message">
+ <button {{action "postMessage" target="view"}} class="btn">Send</button>
+ {{else}}
+ <input type="text" id="username" placeholder="Enter your username...">
+ <button {{action "pickName" target="view"}} class="btn">Send</button>
+ {{/if}}
+ {{else}}
+ <input type="text" placeholder="Log in with Persona to chat!" disabled="disabled">
+ <button {{action "login"}} class="btn">Login</button>
+ {{/if}}
+ </form>
+ {{/view}}
+{{/view}}
+
diff --git a/tests/examplefiles/example.als b/tests/examplefiles/example.als
new file mode 100644
index 00000000..3a5ab82b
--- /dev/null
+++ b/tests/examplefiles/example.als
@@ -0,0 +1,217 @@
+module examples/systems/views
+
+/*
+ * Model of views in object-oriented programming.
+ *
+ * Two object references, called the view and the backing,
+ * are related by a view mechanism when changes to the
+ * backing are automatically propagated to the view. Note
+ * that the state of a view need not be a projection of the
+ * state of the backing; the keySet method of Map, for
+ * example, produces two view relationships, and for the
+ * one in which the map is modified by changes to the key
+ * set, the value of the new map cannot be determined from
+ * the key set. Note that in the iterator view mechanism,
+ * the iterator is by this definition the backing object,
+ * since changes are propagated from iterator to collection
+ * and not vice versa. Oddly, a reference may be a view of
+ * more than one backing: there can be two iterators on the
+ * same collection, eg. A reference cannot be a view under
+ * more than one view type.
+ *
+ * A reference is made dirty when it is a backing for a view
+ * with which it is no longer related by the view invariant.
+ * This usually happens when a view is modified, either
+ * directly or via another backing. For example, changing a
+ * collection directly when it has an iterator invalidates
+ * it, as does changing the collection through one iterator
+ * when there are others.
+ *
+ * More work is needed if we want to model more closely the
+ * failure of an iterator when its collection is invalidated.
+ *
+ * As a terminological convention, when there are two
+ * complementary view relationships, we will give them types
+ * t and t'. For example, KeySetView propagates from map to
+ * set, and KeySetView' propagates from set to map.
+ *
+ * author: Daniel Jackson
+ */
+
+open util/ordering[State] as so
+open util/relation as rel
+
+sig Ref {}
+sig Object {}
+
+-- t->b->v in views when v is view of type t of backing b
+-- dirty contains refs that have been invalidated
+sig State {
+ refs: set Ref,
+ obj: refs -> one Object,
+ views: ViewType -> refs -> refs,
+ dirty: set refs
+-- , anyviews: Ref -> Ref -- for visualization
+ }
+-- {anyviews = ViewType.views}
+
+sig Map extends Object {
+ keys: set Ref,
+ map: keys -> one Ref
+ }{all s: State | keys + Ref.map in s.refs}
+sig MapRef extends Ref {}
+fact {State.obj[MapRef] in Map}
+
+sig Iterator extends Object {
+ left, done: set Ref,
+ lastRef: lone done
+ }{all s: State | done + left + lastRef in s.refs}
+sig IteratorRef extends Ref {}
+fact {State.obj[IteratorRef] in Iterator}
+
+sig Set extends Object {
+ elts: set Ref
+ }{all s: State | elts in s.refs}
+sig SetRef extends Ref {}
+fact {State.obj[SetRef] in Set}
+
+abstract sig ViewType {}
+one sig KeySetView, KeySetView', IteratorView extends ViewType {}
+fact ViewTypes {
+ State.views[KeySetView] in MapRef -> SetRef
+ State.views[KeySetView'] in SetRef -> MapRef
+ State.views[IteratorView] in IteratorRef -> SetRef
+ all s: State | s.views[KeySetView] = ~(s.views[KeySetView'])
+ }
+
+/**
+ * mods is refs modified directly or by view mechanism
+ * doesn't handle possibility of modifying an object and its view at once?
+ * should we limit frame conds to non-dirty refs?
+ */
+pred modifies [pre, post: State, rs: set Ref] {
+ let vr = pre.views[ViewType], mods = rs.*vr {
+ all r: pre.refs - mods | pre.obj[r] = post.obj[r]
+ all b: mods, v: pre.refs, t: ViewType |
+ b->v in pre.views[t] => viewFrame [t, pre.obj[v], post.obj[v], post.obj[b]]
+ post.dirty = pre.dirty +
+ {b: pre.refs | some v: Ref, t: ViewType |
+ b->v in pre.views[t] && !viewFrame [t, pre.obj[v], post.obj[v], post.obj[b]]
+ }
+ }
+ }
+
+pred allocates [pre, post: State, rs: set Ref] {
+ no rs & pre.refs
+ post.refs = pre.refs + rs
+ }
+
+/**
+ * models frame condition that limits change to view object from v to v' when backing object changes to b'
+ */
+pred viewFrame [t: ViewType, v, v', b': Object] {
+ t in KeySetView => v'.elts = dom [b'.map]
+ t in KeySetView' => b'.elts = dom [v'.map]
+ t in KeySetView' => (b'.elts) <: (v.map) = (b'.elts) <: (v'.map)
+ t in IteratorView => v'.elts = b'.left + b'.done
+ }
+
+pred MapRef.keySet [pre, post: State, setRefs: SetRef] {
+ post.obj[setRefs].elts = dom [pre.obj[this].map]
+ modifies [pre, post, none]
+ allocates [pre, post, setRefs]
+ post.views = pre.views + KeySetView->this->setRefs + KeySetView'->setRefs->this
+ }
+
+pred MapRef.put [pre, post: State, k, v: Ref] {
+ post.obj[this].map = pre.obj[this].map ++ k->v
+ modifies [pre, post, this]
+ allocates [pre, post, none]
+ post.views = pre.views
+ }
+
+pred SetRef.iterator [pre, post: State, iterRef: IteratorRef] {
+ let i = post.obj[iterRef] {
+ i.left = pre.obj[this].elts
+ no i.done + i.lastRef
+ }
+ modifies [pre,post,none]
+ allocates [pre, post, iterRef]
+ post.views = pre.views + IteratorView->iterRef->this
+ }
+
+pred IteratorRef.remove [pre, post: State] {
+ let i = pre.obj[this], i' = post.obj[this] {
+ i'.left = i.left
+ i'.done = i.done - i.lastRef
+ no i'.lastRef
+ }
+ modifies [pre,post,this]
+ allocates [pre, post, none]
+ pre.views = post.views
+ }
+
+pred IteratorRef.next [pre, post: State, ref: Ref] {
+ let i = pre.obj[this], i' = post.obj[this] {
+ ref in i.left
+ i'.left = i.left - ref
+ i'.done = i.done + ref
+ i'.lastRef = ref
+ }
+ modifies [pre, post, this]
+ allocates [pre, post, none]
+ pre.views = post.views
+ }
+
+pred IteratorRef.hasNext [s: State] {
+ some s.obj[this].left
+ }
+
+assert zippishOK {
+ all
+ ks, vs: SetRef,
+ m: MapRef,
+ ki, vi: IteratorRef,
+ k, v: Ref |
+ let s0=so/first,
+ s1=so/next[s0],
+ s2=so/next[s1],
+ s3=so/next[s2],
+ s4=so/next[s3],
+ s5=so/next[s4],
+ s6=so/next[s5],
+ s7=so/next[s6] |
+ ({
+ precondition [s0, ks, vs, m]
+ no s0.dirty
+ ks.iterator [s0, s1, ki]
+ vs.iterator [s1, s2, vi]
+ ki.hasNext [s2]
+ vi.hasNext [s2]
+ ki.this/next [s2, s3, k]
+ vi.this/next [s3, s4, v]
+ m.put [s4, s5, k, v]
+ ki.remove [s5, s6]
+ vi.remove [s6, s7]
+ } => no State.dirty)
+ }
+
+pred precondition [pre: State, ks, vs, m: Ref] {
+ // all these conditions and other errors discovered in scope of 6 but 8,3
+ // in initial state, must have view invariants hold
+ (all t: ViewType, b, v: pre.refs |
+ b->v in pre.views[t] => viewFrame [t, pre.obj[v], pre.obj[v], pre.obj[b]])
+ // sets are not aliases
+-- ks != vs
+ // sets are not views of map
+-- no (ks+vs)->m & ViewType.pre.views
+ // no iterator currently on either set
+-- no Ref->(ks+vs) & ViewType.pre.views
+ }
+
+check zippishOK for 6 but 8 State, 3 ViewType expect 1
+
+/**
+ * experiment with controlling heap size
+ */
+fact {all s: State | #s.obj < 5}
diff --git a/tests/examplefiles/example.c b/tests/examplefiles/example.c
index a7f546d1..7bf70149 100644
--- a/tests/examplefiles/example.c
+++ b/tests/examplefiles/example.c
@@ -195,7 +195,7 @@ char convertType(int type) {
case TYPE_INT: return 'I';
case TYPE_FLOAT: return 'F';
case TYPE_BOOLEAN: return 'Z';
- default: yyerror("compiler-intern error in convertType().\n");
+ default : yyerror("compiler-intern error in convertType().\n");
}
return 0; /* to avoid compiler-warning */
}
diff --git a/tests/examplefiles/example.ceylon b/tests/examplefiles/example.ceylon
index b136b995..04223c56 100644
--- a/tests/examplefiles/example.ceylon
+++ b/tests/examplefiles/example.ceylon
@@ -1,33 +1,52 @@
+import ceylon.language { parseInteger }
+
doc "A top-level function,
with multi-line documentation."
-void topLevel(String? a, Integer b=5, String... seqs) {
+void topLevel(String? a, Integer b=5, String* seqs) {
function nested(String s) {
print(s[1..2]);
return true;
}
- for (s in seqs.filter((String x) x.size > 2)) {
+ for (s in seqs.filter((String x) => x.size > 2)) {
nested(s);
}
- value uppers = seqs.sequence[].uppercased;
- String|Nothing z = a;
- Sequence<Integer> ints = { 1, 2, 3, 4, 5 };
+ value uppers = seqs.map((String x) {
+ return x.uppercased;
+ });
+ String|Null z = a;
+ {Integer+} ints = { 1, 2, 3, 4, 5 };
+ value numbers = [ 1, #ffff, #ffff_ffff, $10101010, $1010_1010_1010_1010,
+ 123_456_789 ];
+ value chars = ['a', '\{#ffff}' ];
}
-shared class Example<Element>(name, element) satisfies Comparable<Example<Element>>
+shared class Example_1<Element>(name, element) satisfies Comparable<Example_1<Element>>
given Element satisfies Comparable<Element> {
shared String name;
shared Element element;
+ shared [Integer,String] tuple = [1, "2"];
+ shared late String lastName;
+ variable Integer cnt = 0;
+
+ shared Integer count => cnt;
+ assign count {
+ assert(count >= cnt);
+ cnt = count;
+ }
- shared actual Comparison compare(Example<Element> other) {
+ shared actual Comparison compare(Example_1<Element> other) {
return element <=> other.element;
}
shared actual String string {
- return "Example with " + element.string;
+ return "Example with ``element.string``";
}
}
-Example<Integer> instance = Example {
- name = "Named args call";
+Example_1<Integer> instance = Example_1 {
element = 5;
+ name = "Named args call \{#0060}";
};
+
+object example1 extends Example_1<Integer>("object", 5) {
+} \ No newline at end of file
diff --git a/tests/examplefiles/example.chai b/tests/examplefiles/example.chai
new file mode 100644
index 00000000..85f53c38
--- /dev/null
+++ b/tests/examplefiles/example.chai
@@ -0,0 +1,6 @@
+var f = fun(x) { x + 2; }
+// comment
+puts(someFunc(2 + 2 - 1 * 5 / 4));
+var x = "str";
+def dosomething(lhs, rhs) { print("lhs: ${lhs}, rhs: ${rhs}"); }
+callfunc(`+`, 1, 4);
diff --git a/tests/examplefiles/example.clay b/tests/examplefiles/example.clay
new file mode 100644
index 00000000..784752c6
--- /dev/null
+++ b/tests/examplefiles/example.clay
@@ -0,0 +1,33 @@
+
+/// @section StringLiteralRef
+
+record StringLiteralRef (
+ sizep : Pointer[SizeT],
+);
+
+
+/// @section predicates
+
+overload ContiguousSequence?(#StringLiteralRef) : Bool = true;
+[s when StringLiteral?(s)]
+overload ContiguousSequence?(#Static[s]) : Bool = true;
+
+
+
+/// @section size, begin, end, index
+
+forceinline overload size(a:StringLiteralRef) = a.sizep^;
+
+forceinline overload begin(a:StringLiteralRef) : Pointer[Char] = Pointer[Char](a.sizep + 1);
+forceinline overload end(a:StringLiteralRef) = begin(a) + size(a);
+
+[I when Integer?(I)]
+forceinline overload index(a:StringLiteralRef, i:I) : ByRef[Char] {
+ assert["boundsChecks"](i >= 0 and i < size(a), "StringLiteralRef index out of bounds");
+ return ref (begin(a) + i)^;
+}
+
+foo() = """
+long\tlong
+story
+"""
diff --git a/tests/examplefiles/example.cob b/tests/examplefiles/example.cob
index 3f65e498..92d2e300 100644
--- a/tests/examplefiles/example.cob
+++ b/tests/examplefiles/example.cob
@@ -2617,940 +2617,4 @@ GC0710 88 Token-Is-Reserved-Word VALUE " ".
*****************************************************************
** Perform all program-wide initialization operations **
*****************************************************************
- 101-Establish-Working-Env.
- MOVE TRIM(Src-Filename,Leading) TO Src-Filename
- ACCEPT Env-TEMP
- FROM ENVIRONMENT "TEMP"
- END-ACCEPT
- ACCEPT Lines-Per-Page-ENV
- FROM ENVIRONMENT "OCXREF_LINES"
- END-ACCEPT
- INSPECT Src-Filename REPLACING ALL "\" BY "/"
- INSPECT Env-TEMP REPLACING ALL "\" BY "/"
- MOVE Src-Filename TO Program-Path
- MOVE Program-Path TO Heading-2
- CALL "C$JUSTIFY"
- USING Heading-2, "Right"
- END-CALL
- MOVE LENGTH(TRIM(Src-Filename,Trailing)) TO I
- MOVE 0 TO J
- PERFORM UNTIL Src-Filename(I:1) = '/'
- OR I = 0
- SUBTRACT 1 FROM I
- ADD 1 TO J
- END-PERFORM
- UNSTRING Src-Filename((I + 1):J) DELIMITED BY "."
- INTO Filename, Dummy
- END-UNSTRING
- STRING TRIM(Env-TEMP,Trailing)
- "/"
- TRIM(Filename,Trailing)
- ".i"
- DELIMITED SIZE
- INTO Expanded-Src-Filename
- END-STRING
- STRING Program-Path(1:I)
- TRIM(Filename,Trailing)
- ".lst"
- DELIMITED SIZE
- INTO Report-Filename
- END-STRING
- IF Lines-Per-Page-ENV NOT = SPACES
- MOVE NUMVAL(Lines-Per-Page-ENV) TO Lines-Per-Page
- ELSE
- MOVE 60 TO Lines-Per-Page
- END-IF
- ACCEPT Todays-Date
- FROM DATE YYYYMMDD
- END-ACCEPT
- MOVE Todays-Date TO H1X-Date
- H1S-Date
- MOVE "????????????..." TO SPI-Current-Program-ID
- MOVE SPACES TO SPI-Current-Verb
- Held-Reference
- MOVE "Y" TO F-First-Record
- .
- /
- 200-Execute-cobc SECTION.
- 201-Build-Cmd.
- STRING "cobc -E "
- TRIM(Program-Path, Trailing)
- " > "
- TRIM(Expanded-Src-Filename,Trailing)
- DELIMITED SIZE
- INTO Cmd
- END-STRING
- CALL "SYSTEM"
- USING Cmd
- END-CALL
- IF RETURN-CODE NOT = 0
- DISPLAY
- "Cross-reference terminated by previous errors"
- UPON SYSERR
- END-DISPLAY
- GOBACK
- END-IF
- .
-
- 209-Exit.
- EXIT
- .
- /
- 300-Tokenize-Source SECTION.
- 301-Driver.
- OPEN INPUT Expand-Code
- MOVE SPACES TO Expand-Code-Rec
- MOVE 256 TO Src-Ptr
- MOVE 0 TO Num-UserNames
- SPI-Current-Line-No
- MOVE "?" TO SPI-Current-Division
-GC0710 MOVE "N" TO F-Verb-Has-Been-Found.
- PERFORM FOREVER
- PERFORM 310-Get-Token
- IF Token-Is-EOF
- EXIT PERFORM
- END-IF
- MOVE UPPER-CASE(SPI-Current-Token)
- TO SPI-Current-Token-UC
- IF Token-Is-Verb
- MOVE SPI-Current-Token-UC TO SPI-Current-Verb
- SPI-Prior-Token
- IF Held-Reference NOT = SPACES
- MOVE Held-Reference TO Sort-Rec
- MOVE SPACES TO Held-Reference
- RELEASE Sort-Rec
- END-IF
- END-IF
- EVALUATE TRUE
- WHEN In-IDENTIFICATION-DIVISION
- PERFORM 320-IDENTIFICATION-DIVISION
- WHEN In-ENVIRONMENT-DIVISION
- PERFORM 330-ENVIRONMENT-DIVISION
- WHEN In-DATA-DIVISION
- PERFORM 340-DATA-DIVISION
- WHEN In-PROCEDURE-DIVISION
- PERFORM 350-PROCEDURE-DIVISION
- END-EVALUATE
- IF Token-Is-Key-Word
- MOVE SPI-Current-Token-UC TO SPI-Prior-Token
- END-IF
- IF F-Token-Ended-Sentence = "Y"
- AND SPI-Current-Division NOT = "I"
- MOVE SPACES TO SPI-Prior-Token
- SPI-Current-Verb
- END-IF
-
- END-PERFORM
- CLOSE Expand-Code
- EXIT SECTION
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 310-Get-Token.
- *>-- Position to 1st non-blank character
- MOVE F-Token-Ended-Sentence TO F-Last-Token-Ended-Sent
- MOVE "N" TO F-Token-Ended-Sentence
- PERFORM UNTIL Expand-Code-Rec(Src-Ptr : 1) NOT = SPACE
- IF Src-Ptr > 255
- READ Expand-Code AT END
- IF Held-Reference NOT = SPACES
- MOVE Held-Reference TO Sort-Rec
- MOVE SPACES TO Held-Reference
- RELEASE Sort-Rec
- END-IF
- SET Token-Is-EOF TO TRUE
- MOVE 0 TO SPI-Current-Line-No
- EXIT PARAGRAPH
- END-READ
- IF ECR-1 = "#"
- PERFORM 311-Control-Record
- ELSE
- PERFORM 312-Expand-Code-Record
- END-IF
- ELSE
- ADD 1 TO Src-Ptr
- END-IF
- END-PERFORM
- *>-- Extract token string
- MOVE Expand-Code-Rec(Src-Ptr : 1) TO SPI-Current-Char
- MOVE Expand-Code-Rec(Src-Ptr + 1: 1) TO SPI-Next-Char
- IF SPI-Current-Char = "."
- ADD 1 TO Src-Ptr
- MOVE SPI-Current-Char TO SPI-Current-Token
- MOVE SPACE TO SPI-Token-Type
- MOVE "Y" TO F-Token-Ended-Sentence
- EXIT PARAGRAPH
- END-IF
- IF Current-Char-Is-Punct
- AND SPI-Current-Char = "="
- AND SPI-Current-Division = "P"
- ADD 1 TO Src-Ptr
- MOVE "EQUALS" TO SPI-Current-Token
- MOVE "K" TO SPI-Token-Type
- EXIT PARAGRAPH
- END-IF
- IF Current-Char-Is-Punct *> So subscripts don't get flagged w/ "*"
- AND SPI-Current-Char = "("
- AND SPI-Current-Division = "P"
- MOVE SPACES TO SPI-Prior-Token
- END-IF
- IF Current-Char-Is-Punct
- ADD 1 TO Src-Ptr
- MOVE SPI-Current-Char TO SPI-Current-Token
- MOVE SPACE TO SPI-Token-Type
- EXIT PARAGRAPH
- END-IF
- IF Current-Char-Is-Quote
- ADD 1 TO Src-Ptr
- UNSTRING Expand-Code-Rec
- DELIMITED BY SPI-Current-Char
- INTO SPI-Current-Token
- WITH POINTER Src-Ptr
- END-UNSTRING
- IF Expand-Code-Rec(Src-Ptr : 1) = "."
- MOVE "Y" TO F-Token-Ended-Sentence
- ADD 1 TO Src-Ptr
- END-IF
- SET Token-Is-Literal-Alpha TO TRUE
- EXIT PARAGRAPH
- END-IF
- IF Current-Char-Is-X AND Next-Char-Is-Quote
- ADD 2 TO Src-Ptr
- UNSTRING Expand-Code-Rec
- DELIMITED BY SPI-Next-Char
- INTO SPI-Current-Token
- WITH POINTER Src-Ptr
- END-UNSTRING
- IF Expand-Code-Rec(Src-Ptr : 1) = "."
- MOVE "Y" TO F-Token-Ended-Sentence
- ADD 1 TO Src-Ptr
- END-IF
- SET Token-Is-Literal-Number TO TRUE
- EXIT PARAGRAPH
- END-IF
- IF Current-Char-Is-Z AND Next-Char-Is-Quote
- ADD 2 TO Src-Ptr
- UNSTRING Expand-Code-Rec
- DELIMITED BY SPI-Next-Char
- INTO SPI-Current-Token
- WITH POINTER Src-Ptr
- END-UNSTRING
- IF Expand-Code-Rec(Src-Ptr : 1) = "."
- MOVE "Y" TO F-Token-Ended-Sentence
- ADD 1 TO Src-Ptr
- END-IF
- SET Token-Is-Literal-Alpha TO TRUE
- EXIT PARAGRAPH
- END-IF
- IF F-Processing-PICTURE = "Y"
- UNSTRING Expand-Code-Rec
- DELIMITED BY ". " OR " "
- INTO SPI-Current-Token
- DELIMITER IN Delim
- WITH POINTER Src-Ptr
- END-UNSTRING
- IF Delim = ". "
- MOVE "Y" TO F-Token-Ended-Sentence
- ADD 1 TO Src-Ptr
- END-IF
- IF UPPER-CASE(SPI-Current-Token) = "IS"
- MOVE SPACE TO SPI-Token-Type
- EXIT PARAGRAPH
- ELSE
- MOVE "N" TO F-Processing-PICTURE
- MOVE SPACE TO SPI-Token-Type
- EXIT PARAGRAPH
- END-IF
- END-IF
- UNSTRING Expand-Code-Rec
- DELIMITED BY ". " OR " " OR "=" OR "(" OR ")" OR "*"
- OR "/" OR "&" OR ";" OR "," OR "<"
- OR ">" OR ":"
- INTO SPI-Current-Token
- DELIMITER IN Delim
- WITH POINTER Src-Ptr
- END-UNSTRING
- IF Delim = ". "
- MOVE "Y" TO F-Token-Ended-Sentence
- END-IF
- IF Delim NOT = ". " AND " "
- SUBTRACT 1 FROM Src-Ptr
- END-IF
- *>-- Classify Token
- MOVE UPPER-CASE(SPI-Current-Token) TO Search-Token
- IF Search-Token = "EQUAL" OR "EQUALS"
- MOVE "EQUALS" TO SPI-Current-Token
- MOVE "K" TO SPI-Token-Type
- EXIT PARAGRAPH
- END-IF
- SEARCH ALL Reserved-Word
- WHEN RW-Word (RW-Idx) = Search-Token
- MOVE RW-Type (RW-Idx) TO SPI-Token-Type
-GC0710 IF Token-Is-Verb
-GC0710 MOVE "Y" TO F-Verb-Has-Been-Found
-GC0710 END-IF
- EXIT PARAGRAPH
- END-SEARCH
- *>-- Not a reserved word, must be a user name
- SET Token-Is-Identifier TO TRUE *> NEEDS EXPANSION!!!!
- PERFORM 313-Check-For-Numeric-Token
- IF Token-Is-Literal-Number
- IF (F-Last-Token-Ended-Sent = "Y")
- AND (SPI-Current-Division = "D")
- MOVE "LEVEL #" TO SPI-Current-Token
- MOVE "K" TO SPI-Token-Type
- EXIT PARAGRAPH
- ELSE
- EXIT PARAGRAPH
- END-IF
- END-IF
- EXIT PARAGRAPH
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 311-Control-Record.
- UNSTRING ECR-2-256
- DELIMITED BY '"'
- INTO PIC-X10, PIC-X256, Dummy
- END-UNSTRING
- INSPECT PIC-X10 REPLACING ALL '"' BY SPACE
- COMPUTE I = NUMVAL(PIC-X10) - 1
- IF TRIM(PIC-X256,Trailing) = TRIM(Program-Path,Trailing)
- MOVE I TO SPI-Current-Line-No
- SET In-Main-Module TO TRUE
- IF Saved-Section NOT = SPACES
- MOVE Saved-Section TO SPI-Current-Section
- END-IF
- ELSE
- SET In-Copybook TO TRUE
- IF Saved-Section = SPACES
- MOVE SPI-Current-Section TO Saved-Section
- END-IF
- MOVE LENGTH(TRIM(PIC-X256,Trailing)) TO I
- MOVE 0 TO J
- PERFORM UNTIL PIC-X256(I:1) = '/'
- OR I = 0
- SUBTRACT 1 FROM I
- ADD 1 TO J
- END-PERFORM
- UNSTRING PIC-X256((I + 1):J) DELIMITED BY "."
- INTO Filename, Dummy
- END-UNSTRING
- MOVE "[" TO SPI-CS-1
- MOVE Filename TO SPI-CS-2-14
- IF SPI-CS-11-14 NOT = SPACES
- MOVE "..." TO SPI-CS-11-14
- END-IF
- MOVE "]" TO SPI-CS-15
- END-IF
- MOVE SPACES TO Expand-Code-Rec *> Force another READ
- MOVE 256 TO Src-Ptr
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 312-Expand-Code-Record.
- MOVE 1 TO Src-Ptr
- IF In-Main-Module
- ADD 1 To SPI-Current-Line-No
- END-IF
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 313-Check-For-Numeric-Token.
- MOVE SPI-Current-Token TO PIC-X32
- INSPECT PIC-X32
- REPLACING TRAILING SPACES BY "0"
- IF PIC-X32 IS NUMERIC *> Simple Unsigned Integer
- SET Token-Is-Literal-Number TO TRUE
- EXIT PARAGRAPH
- END-IF
- IF PIC-X32(1:1) = "+" OR "-"
- MOVE "0" TO PIC-X32(1:1)
- END-IF
- MOVE 0 TO Tally
- INSPECT PIC-X32
- TALLYING Tally FOR ALL "."
- IF Tally = 1
- INSPECT PIC-X32 REPLACING ALL "." BY "0"
- END-IF
- IF PIC-X32 IS NUMERIC
- SET Token-Is-Literal-Number TO TRUE
- EXIT PARAGRAPH
- END-IF
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 320-IDENTIFICATION-DIVISION.
-GC0710 MOVE "N" TO F-Verb-Has-Been-Found
- IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
- MOVE SPI-Prior-Token TO SPI-Current-Division
- EXIT PARAGRAPH
- END-IF
- IF SPI-Prior-Token = "PROGRAM-ID"
- MOVE SPACES TO SPI-Prior-Token
- MOVE SPI-Current-Token TO SPI-Current-Program-ID
- IF SPI-CP-13-15 NOT = SPACES
- MOVE "..." TO SPI-CP-13-15
- END-IF
- EXIT PARAGRAPH
- END-IF
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 330-ENVIRONMENT-DIVISION.
- IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
- MOVE SPI-Prior-Token TO SPI-Current-Division
- EXIT PARAGRAPH
- END-IF
- IF Token-Is-Key-Word AND SPI-Current-Token = "SECTION"
- MOVE SPI-Prior-Token TO SPI-Current-Section
- EXIT PARAGRAPH
- END-IF
- IF Token-Is-Identifier
- PERFORM 361-Release-Ref
- END-IF
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 340-DATA-DIVISION.
- IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
- MOVE SPI-Prior-Token TO SPI-Current-Division
- EXIT PARAGRAPH
- END-IF
- IF Token-Is-Key-Word AND SPI-Current-Token = "SECTION"
- MOVE SPI-Prior-Token TO SPI-Current-Section
- EXIT PARAGRAPH
- END-IF
- IF (SPI-Current-Token = "PIC" OR "PICTURE")
- AND (Token-Is-Key-Word)
- MOVE "Y" TO F-Processing-PICTURE
- EXIT PARAGRAPH
- END-IF
-GC0710 IF Token-Is-Reserved-Word
-GC0710 AND SPI-Prior-Token = "LEVEL #"
-GC0710 MOVE SPACES TO SPI-Prior-Token
-GC0710 EXIT PARAGRAPH
-GC0710 END-IF
- IF Token-Is-Identifier
- EVALUATE SPI-Prior-Token
- WHEN "FD"
- PERFORM 360-Release-Def
- MOVE SPACES TO SPI-Prior-Token
- WHEN "SD"
- PERFORM 360-Release-Def
- MOVE SPACES TO SPI-Prior-Token
- WHEN "LEVEL #"
- PERFORM 360-Release-Def
- MOVE SPACES TO SPI-Prior-Token
- WHEN "INDEXED"
- PERFORM 360-Release-Def
- MOVE SPACES TO SPI-Prior-Token
- WHEN "USING"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN "INTO"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- EXIT PARAGRAPH
- END-IF
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 350-PROCEDURE-DIVISION.
- IF SPI-Current-Section NOT = "PROCEDURE"
- MOVE "PROCEDURE" TO SPI-Current-Section
- END-IF
-GC0710 IF SPI-Current-Token-UC = "PROGRAM"
-GC0710 AND SPI-Prior-Token = "END"
-GC0710 MOVE "?" TO SPI-Current-Division
-GC0710 EXIT PARAGRAPH
-GC0710 END-IF
- IF Token-Is-Key-Word AND SPI-Current-Token = "DIVISION"
- MOVE SPI-Prior-Token TO SPI-Current-Division
- EXIT PARAGRAPH
- END-IF
- IF SPI-Current-Verb = SPACES
-GC0710 AND F-Verb-Has-Been-Found = "Y"
- IF Token-Is-Identifier
- PERFORM 360-Release-Def
- MOVE SPACES TO SPI-Prior-Token
- END-IF
- EXIT PARAGRAPH
- END-IF
- IF NOT Token-Is-Identifier
- EXIT PARAGRAPH
- END-IF
- EVALUATE SPI-Current-Verb
- WHEN "ACCEPT"
- PERFORM 351-ACCEPT
- WHEN "ADD"
- PERFORM 351-ADD
- WHEN "ALLOCATE"
- PERFORM 351-ALLOCATE
- WHEN "CALL"
- PERFORM 351-CALL
- WHEN "COMPUTE"
- PERFORM 351-COMPUTE
- WHEN "DIVIDE"
- PERFORM 351-DIVIDE
- WHEN "FREE"
- PERFORM 351-FREE
- WHEN "INITIALIZE"
- PERFORM 351-INITIALIZE
- WHEN "INSPECT"
- PERFORM 351-INSPECT
- WHEN "MOVE"
- PERFORM 351-MOVE
- WHEN "MULTIPLY"
- PERFORM 351-MULTIPLY
- WHEN "PERFORM"
- PERFORM 351-PERFORM
- WHEN "SET"
- PERFORM 351-SET
- WHEN "STRING"
- PERFORM 351-STRING
- WHEN "SUBTRACT"
- PERFORM 351-SUBTRACT
- WHEN "TRANSFORM"
- PERFORM 351-TRANSFORM
- WHEN "UNSTRING"
- PERFORM 351-UNSTRING
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-ACCEPT.
- EVALUATE SPI-Prior-Token
- WHEN "ACCEPT"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-ADD.
- EVALUATE SPI-Prior-Token
- WHEN "GIVING"
- PERFORM 362-Release-Upd
- WHEN "TO"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-ALLOCATE.
- EVALUATE SPI-Prior-Token
- WHEN "ALLOCATE"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN "RETURNING"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-CALL.
- EVALUATE SPI-Prior-Token
- WHEN "RETURNING"
- PERFORM 362-Release-Upd
- WHEN "GIVING"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-COMPUTE.
- EVALUATE SPI-Prior-Token
- WHEN "COMPUTE"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-DIVIDE.
- EVALUATE SPI-Prior-Token
- WHEN "INTO"
- PERFORM 363-Set-Upd
- MOVE Sort-Rec TO Held-Reference
- WHEN "GIVING"
- IF Held-Reference NOT = SPACES
- MOVE Held-Reference To Sort-Rec
- MOVE SPACES To Held-Reference
- SR-Ref-Flag
- RELEASE Sort-Rec
- END-IF
- PERFORM 362-Release-Upd
- WHEN "REMAINDER"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-FREE.
- PERFORM 362-Release-Upd
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-INITIALIZE.
- EVALUATE SPI-Prior-Token
- WHEN "INITIALIZE"
- PERFORM 362-Release-Upd
- WHEN "REPLACING"
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-INSPECT.
- EVALUATE SPI-Prior-Token
- WHEN "INSPECT"
- PERFORM 364-Set-Ref
- MOVE SPACES TO Held-Reference
- MOVE SPACES TO SPI-Prior-Token
- WHEN "TALLYING"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN "REPLACING"
- IF Held-Reference NOT = SPACES
- MOVE Held-Reference TO Sort-Rec
- MOVE SPACES TO Held-Reference
- MOVE "*" TO SR-Ref-Flag
- RELEASE Sort-Rec
- END-IF
- MOVE SPACES TO SPI-Prior-Token
- WHEN "CONVERTING"
- IF Held-Reference NOT = SPACES
- MOVE Held-Reference TO Sort-Rec
- MOVE SPACES TO Held-Reference
- MOVE "*" TO SR-Ref-Flag
- RELEASE Sort-Rec
- END-IF
- MOVE SPACES TO SPI-Prior-Token
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-MOVE.
- EVALUATE SPI-Prior-Token
- WHEN "TO"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-MULTIPLY.
- EVALUATE SPI-Prior-Token
- WHEN "BY"
- PERFORM 363-Set-Upd
- MOVE Sort-Rec TO Held-Reference
- WHEN "GIVING"
- MOVE Held-Reference TO Sort-Rec
- MOVE SPACES TO Held-Reference
- SR-Ref-Flag
- RELEASE Sort-Rec
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-PERFORM.
- EVALUATE SPI-Prior-Token
- WHEN "VARYING"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN "AFTER"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-SET.
- EVALUATE SPI-Prior-Token
- WHEN "SET"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-STRING.
- EVALUATE SPI-Prior-Token
- WHEN "INTO"
- PERFORM 362-Release-Upd
- WHEN "POINTER"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-SUBTRACT.
- EVALUATE SPI-Prior-Token
- WHEN "GIVING"
- PERFORM 362-Release-Upd
- WHEN "FROM"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-TRANSFORM.
- EVALUATE SPI-Prior-Token
- WHEN "TRANSFORM"
- PERFORM 362-Release-Upd
- MOVE SPACES TO SPI-Prior-Token
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 351-UNSTRING.
- EVALUATE SPI-Prior-Token
- WHEN "INTO"
- PERFORM 362-Release-Upd
- WHEN "DELIMITER"
- PERFORM 362-Release-Upd
- WHEN "COUNT"
- PERFORM 362-Release-Upd
- WHEN "POINTER"
- PERFORM 362-Release-Upd
- WHEN "TALLYING"
- PERFORM 362-Release-Upd
- WHEN OTHER
- PERFORM 361-Release-Ref
- END-EVALUATE
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 360-Release-Def.
- MOVE SPACES TO Sort-Rec
- MOVE SPI-Current-Program-ID TO SR-Prog-ID
- MOVE SPI-Current-Token-UC TO SR-Token-UC
- MOVE SPI-Current-Token TO SR-Token
- MOVE SPI-Current-Section TO SR-Section
- MOVE SPI-Current-Line-No TO SR-Line-No-Def
- MOVE 0 TO SR-Line-No-Ref
- RELEASE Sort-Rec
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 361-Release-Ref.
- PERFORM 364-Set-Ref
- RELEASE Sort-Rec
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 362-Release-Upd.
- PERFORM 363-Set-Upd
- RELEASE Sort-Rec
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 363-Set-Upd.
- MOVE SPACES TO Sort-Rec
- MOVE SPI-Current-Program-ID TO SR-Prog-ID
- MOVE SPI-Current-Token-UC TO SR-Token-UC
- MOVE SPI-Current-Token TO SR-Token
- MOVE SPI-Current-Section TO SR-Section
- MOVE SPI-Current-Line-No TO SR-Line-No-Ref
- MOVE "*" TO SR-Ref-Flag
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 364-Set-Ref.
- MOVE SPACES TO Sort-Rec
- MOVE SPI-Current-Program-ID TO SR-Prog-ID
- MOVE SPI-Current-Token-UC TO SR-Token-UC
- MOVE SPI-Current-Token TO SR-Token
- MOVE SPI-Current-Section TO SR-Section
- MOVE SPI-Current-Line-No TO SR-Line-No-Ref
- .
- /
- 400-Produce-Xref-Listing SECTION.
- 401-Init.
- MOVE SPACES TO Detail-Line-X
- Group-Indicators
- MOVE 0 TO I
- Lines-Left
-GC0710 MOVE 'N' TO F-Duplicate
- .
-
- 402-Process-Sorted-Recs.
- PERFORM FOREVER
- RETURN Sort-File AT END
- EXIT PERFORM
- END-RETURN
- IF SR-Prog-ID NOT = GI-Prog-ID
- OR SR-Token-UC NOT = GI-Token
-GC0710 MOVE 'N' TO F-Duplicate
- IF Detail-Line-X NOT = SPACES
- PERFORM 410-Generate-Report-Line
- END-IF
- IF SR-Prog-ID NOT = GI-Prog-ID
- MOVE 0 TO Lines-Left
- END-IF
- MOVE SR-Prog-ID TO GI-Prog-ID
- MOVE SR-Token-UC TO GI-Token
- END-IF
-GC0710 IF SR-Token-UC = GI-Token
-GC0710 AND SR-Line-No-Def NOT = SPACES
-GC0710 AND Detail-Line-X NOT = SPACES
-GC0710 MOVE 'Y' TO F-Duplicate
-GC0710 PERFORM 410-Generate-Report-Line
-GC0710 MOVE 0 TO I
-GC0710 MOVE SR-Prog-ID TO DLX-Prog-ID
-GC0710 MOVE ' (Duplicate Definition)' TO DLX-Token
-GC0710 MOVE SR-Section TO DLX-Section
-GC0710 MOVE SR-Line-No-Def TO DLX-Line-No-Def
-GC0710 EXIT PERFORM CYCLE
-GC0710 END-IF
-GC0710 IF SR-Token-UC = GI-Token
-GC0710 AND SR-Line-No-Def = SPACES
-GC0710 AND F-Duplicate = 'Y'
-GC0710 MOVE 'N' TO F-Duplicate
-GC0710 PERFORM 410-Generate-Report-Line
-GC0710 MOVE 0 TO I
-GC0710 MOVE SR-Prog-ID TO DLX-Prog-ID
-GC0710 MOVE ' (Duplicate References)' TO DLX-Token
-GC0710 END-IF
- IF Detail-Line-X = SPACES
- MOVE SR-Prog-ID TO DLX-Prog-ID
- MOVE SR-Token TO DLX-Token
- MOVE SR-Section TO DLX-Section
- IF SR-Line-No-Def NOT = SPACES
- MOVE SR-Line-No-Def TO DLX-Line-No-Def
- END-IF
- END-IF
- IF SR-Reference > '000000'
- ADD 1 TO I
- IF I > Line-Nos-Per-Rec
- PERFORM 410-Generate-Report-Line
- MOVE 1 TO I
- END-IF
- MOVE SR-Line-No-Ref TO DLX-Line-No-Ref (I)
- MOVE SR-Ref-Flag TO DLX-Ref-Flag (I)
- END-IF
- END-PERFORM
- IF Detail-Line-X NOT = SPACES
- PERFORM 410-Generate-Report-Line
- END-IF
- EXIT SECTION
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 410-Generate-Report-Line.
- IF Lines-Left < 1
- IF F-First-Record = "Y"
- MOVE "N" TO F-First-Record
- WRITE Report-Rec FROM Heading-1X BEFORE 1
- ELSE
- MOVE SPACES TO Report-Rec
- WRITE Report-Rec BEFORE PAGE
- MOVE SPACES TO Report-Rec
- WRITE Report-Rec BEFORE 1
- WRITE Report-Rec FROM Heading-1X BEFORE 1
- END-IF
- WRITE Report-Rec FROM Heading-2 BEFORE 1
- WRITE Report-Rec FROM Heading-4X BEFORE 1
- WRITE Report-Rec FROM Heading-5X BEFORE 1
- COMPUTE
- Lines-Left = Lines-Per-Page - 4
- END-COMPUTE
- END-IF
- WRITE Report-Rec FROM Detail-Line-X BEFORE 1
- MOVE SPACES TO Detail-Line-X
- MOVE 0 TO I
- SUBTRACT 1 FROM Lines-Left
- .
- /
- 500-Produce-Source-Listing SECTION.
- 501-Generate-Source-Listing.
- OPEN INPUT Source-Code
- Expand-Code
- MOVE 0 TO Source-Line-No
- PERFORM FOREVER
- READ Expand-Code AT END
- EXIT PERFORM
- END-READ
- IF ECR-1 = "#"
- PERFORM 510-Control-Record
- ELSE
- PERFORM 520-Expand-Code-Record
- END-IF
- END-PERFORM
- CLOSE Source-Code
- Expand-Code
- EXIT SECTION
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 510-Control-Record.
- UNSTRING ECR-2-256
- DELIMITED BY '"'
- INTO PIC-X10, PIC-X256, Dummy
- END-UNSTRING
- IF TRIM(PIC-X256,Trailing) = TRIM(Program-Path,Trailing) *> Main Pgm
- SET In-Main-Module TO TRUE
- IF Source-Line-No > 0
- READ Expand-Code END-READ
- END-IF
- ELSE *> COPY
- SET In-Copybook TO TRUE
- END-IF
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 520-Expand-Code-Record.
- IF In-Main-Module
- ADD 1 To SPI-Current-Line-No
- READ Source-Code AT END NEXT SENTENCE END-READ
- ADD 1 TO Source-Line-No
- MOVE SPACES TO Detail-Line-S
- MOVE Source-Line-No TO DLS-Line-No
- MOVE SCR-1-128 TO DLS-Statement
-GC0410 IF SCR-7 = "/"
-GC0410 MOVE 0 TO Lines-Left
-GC0410 END-IF
- PERFORM 530-Generate-Source-Line
- IF SCR-129-256 NOT = SPACES
- MOVE SPACES TO Detail-Line-S
- MOVE SCR-129-256 TO DLS-Statement
- PERFORM 530-Generate-Source-Line
- END-IF
- ELSE
- IF Expand-Code-Rec NOT = SPACES
- MOVE SPACES TO Detail-Line-S
- MOVE ECR-1-128 TO DLS-Statement
- PERFORM 530-Generate-Source-Line
- IF ECR-129-256 NOT = SPACES
- MOVE SPACES TO Detail-Line-S
- MOVE ECR-129-256 TO DLS-Statement
- PERFORM 530-Generate-Source-Line
- END-IF
- END-IF
- END-IF
- .
- *>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
- 530-Generate-Source-Line.
- IF Lines-Left < 1
- IF F-First-Record = "Y"
- MOVE "N" TO F-First-Record
- WRITE Report-Rec FROM Heading-1S BEFORE 1
- ELSE
- MOVE SPACES TO Report-Rec
- WRITE Report-Rec BEFORE PAGE
- MOVE SPACES TO Report-Rec
- WRITE Report-Rec BEFORE 1
- WRITE Report-Rec FROM Heading-1S BEFORE 1
- END-IF
- WRITE Report-Rec FROM Heading-2 BEFORE 1
- WRITE Report-Rec FROM Heading-4S BEFORE 1
- WRITE Report-Rec FROM Heading-5S BEFORE 1
- COMPUTE
- Lines-Left = Lines-Per-Page - 4
- END-COMPUTE
- END-IF
- WRITE Report-Rec FROM Detail-Line-S BEFORE 1
- MOVE SPACES TO Detail-Line-S
- SUBTRACT 1 FROM Lines-Left
- .
-
END PROGRAM LISTING.
diff --git a/tests/examplefiles/example.coffee b/tests/examplefiles/example.coffee
new file mode 100644
index 00000000..2cbd1df3
--- /dev/null
+++ b/tests/examplefiles/example.coffee
@@ -0,0 +1,27 @@
+# function arrows
+
+methodA:-> 'A'
+methodB:=> 'B'
+methodC:()=> 'C'
+methodD:()-> 'D'
+methodE:(a,b)-> 'E'
+methodF:(c,d)-> 'F'
+-> 'G'
+=> 'H'
+
+(-> 'I')
+(=> 'J')
+
+# strings
+
+"#{wow}"
+"w#{wow}w"
+"#wow"
+"wow#"
+"w#ow"
+
+'#{wow}'
+'w#{wow}w'
+'#wow'
+'wow#'
+'w#ow'
diff --git a/tests/examplefiles/example.e b/tests/examplefiles/example.e
new file mode 100644
index 00000000..2e43954b
--- /dev/null
+++ b/tests/examplefiles/example.e
@@ -0,0 +1,124 @@
+note
+ description : "[
+ This is use to have almost every language element."
+
+ That way, I can correctly test the lexer. %]"
+
+ Don't try to understand what it does. It's not even compilling.
+ ]"
+ date : "August 6, 2013"
+ revision : "0.1"
+
+class
+ SAMPLE
+
+inherit
+ ARGUMENTS
+ rename
+ Command_line as Caller_command,
+ command_name as Application_name
+ undefine
+ out
+ end
+ ANY
+ export
+ {ANY} out
+ redefine
+ out
+ end
+
+
+
+create
+ make
+
+convert
+ as_boolean: {BOOLEAN}
+
+feature {NONE} -- Initialization
+
+ make
+ -- Run application.
+ local
+ i1_:expanded INTEGER
+ f_1:REAL_64
+ l_char:CHARACTER_8
+ do
+ l_char:='!'
+ l_char:='%''
+ l_char:='%%'
+ i1_:=80 - 0x2F0C // 0C70 \\ 0b10110 * 1;
+ f_1:=0.1 / .567
+ f_1:=34.
+ f_1:=12345.67890
+ inspect i1_
+ when 1 then
+ io.output.put_integer (i1_) -- Comment
+ else
+ io.output.put_real (f_1.truncated_to_real)
+ end
+ io.output.put_string (CuRrEnt.out) -- Comment
+ (agent funct_1).call([1,2,"Coucou"])
+ end
+
+feature -- Access
+
+ funct_1(x,y:separate INTEGER;a_text:READABLE_STRING_GENERAL):detachable BOOLEAN
+ obsolete "This function is obsolete"
+ require
+ Is_Attached: AttAched a_text
+ local
+ l_list:LIST[like x]
+ do
+ if (NOT a_text.is_empty=TrUe or elSe ((x<0 aNd x>10) oR (y>0 and then y<10))) xor True thEn
+ ResuLT := FalSe
+ elseif (acROss l_list as la_list SoMe la_list.item<0 end) implies a_text.is_boolean then
+ ResuLT := FalSe
+ else
+ Result := TruE
+ eND
+ from
+ l_list.start
+ until
+ l_list.exhausted
+ loop
+ l_list.forth
+ variant
+ l_list.count - l_list.index
+ end
+ check Current /= Void end
+ debug print("%"Here%"%N") end
+ ensure
+ Is_Cool_Not_Change: is_cool = old is_cool
+ end
+
+ is_cool:BOOLEAN
+ attribute
+ Result:=False
+ end
+
+ froZen c_malloc: POINTER is
+ exTErnal
+ "C inline use <stdlib.h>"
+ alIAs
+ "malloc (1)"
+ end
+
+ as_boolean:BOOLEAN
+ do
+ Result:=True
+ rescue
+ retry
+ end
+
+feature {ANY} -- The redefine feature
+
+ out:STRING_8
+ once
+ reSUlt:=PrecursOr {ANY}
+ Result := "Hello Worl"+('d').out
+ end
+
+invariant
+ Always_Cool: is_cool
+end
diff --git a/tests/examplefiles/example.f90 b/tests/examplefiles/example.f90
new file mode 100644
index 00000000..40462189
--- /dev/null
+++ b/tests/examplefiles/example.f90
@@ -0,0 +1,8 @@
+program main
+ integer, parameter :: mykind = selected_real_kind()
+ print *, 1
+ print *, 1_mykind
+ print *, 1.
+ print *, 1._mykind
+ print *, (1., 1._mykind)
+end program main
diff --git a/tests/examplefiles/example.feature b/tests/examplefiles/example.feature
new file mode 100644
index 00000000..a26268da
--- /dev/null
+++ b/tests/examplefiles/example.feature
@@ -0,0 +1,16 @@
+# First comment
+Feature: My amazing feature
+ Feature description line 1
+ Feature description line 2
+
+#comment
+Scenario Outline: My detailed scenario #string
+ Given That <x> is set
+ When When I <subtract>
+ Then I should get the <remain#der>
+
+ # indented comment
+ Examples:
+ | x | subtract | remain#der |
+ | 12 | 5\|3 | #73 |
+ | #the | 10 | 15 |
diff --git a/tests/examplefiles/example.gd b/tests/examplefiles/example.gd
new file mode 100644
index 00000000..c285ea32
--- /dev/null
+++ b/tests/examplefiles/example.gd
@@ -0,0 +1,23 @@
+#############################################################################
+##
+#W example.gd
+##
+## This file contains a sample of a GAP declaration file.
+##
+DeclareProperty( "SomeProperty", IsLeftModule );
+DeclareGlobalFunction( "SomeGlobalFunction" );
+
+
+#############################################################################
+##
+#C IsQuuxFrobnicator(<R>)
+##
+## <ManSection>
+## <Filt Name="IsQuuxFrobnicator" Arg='R' Type='Category'/>
+##
+## <Description>
+## Tests whether R is a quux frobnicator.
+## </Description>
+## </ManSection>
+##
+DeclareSynonym( "IsQuuxFrobnicator", IsField and IsGroup );
diff --git a/tests/examplefiles/example.gi b/tests/examplefiles/example.gi
new file mode 100644
index 00000000..c9c5e55d
--- /dev/null
+++ b/tests/examplefiles/example.gi
@@ -0,0 +1,64 @@
+#############################################################################
+##
+#W example.gd
+##
+## This file contains a sample of a GAP implementation file.
+##
+
+
+#############################################################################
+##
+#M SomeOperation( <val> )
+##
+## performs some operation on <val>
+##
+InstallMethod( SomeProperty,
+ "for left modules",
+ [ IsLeftModule ], 0,
+ function( M )
+ if IsFreeLeftModule( M ) and not IsTrivial( M ) then
+ return true;
+ fi;
+ TryNextMethod();
+ end );
+
+
+
+#############################################################################
+##
+#F SomeGlobalFunction( )
+##
+## A global variadic funfion.
+##
+InstallGlobalFunction( SomeGlobalFunction, function( arg )
+ if Length( arg ) = 3 then
+ return arg[1] + arg[2] * arg[3];
+ elif Length( arg ) = 2 then
+ return arg[1] - arg[2]
+ else
+ Error( "usage: SomeGlobalFunction( <x>, <y>[, <z>] )" );
+ fi;
+ end );
+
+
+#
+# A plain function.
+#
+SomeFunc := function(x, y)
+ local z, func, tmp, j;
+ z := x * 1.0;
+ y := 17^17 - y;
+ func := a -> a mod 5;
+ tmp := List( [1..50], func );
+ while y > 0 do
+ for j in tmp do
+ Print(j, "\n");
+ od;
+ repeat
+ y := y - 1;
+ until 0 < 1;
+ y := y -1;
+ od;
+ return z;
+end;
+ \ No newline at end of file
diff --git a/tests/examplefiles/example.golo b/tests/examplefiles/example.golo
new file mode 100644
index 00000000..92ff78b5
--- /dev/null
+++ b/tests/examplefiles/example.golo
@@ -0,0 +1,113 @@
+#
+# Comments
+#
+
+module pygments.Example
+
+import some.Module
+
+local function foo = |a, b| -> a + b
+
+----
+golodoc string
+----
+augment java.util.Collection {
+
+ ----
+ sub doc
+ ----
+ function plop = |this, v| {
+ return this: length() + v
+ }
+}
+
+function bar = |a, b| {
+ let msg = "a string"
+ var tmp = ""
+ tmp = tmp + a: toString()
+ println(tmp + b)
+}
+
+function baz = {
+ foreach i in range(0, 5) {
+ if i % 2 == 0 and true or false {
+ print("e")
+ } else {
+ print("o")
+ }
+ }
+}
+
+function userMatch = |v| ->
+ match {
+ when v % 2 == 0 then "e"
+ otherwise "o"
+ }
+}
+
+function add = |x| -> |y| -> x + y
+
+let aChar = 'a'
+
+let multiline =
+"""
+foo
+bar
+baz
+"""
+
+local function myObj = -> DynamicObject():
+ name("foo"):
+ age(25):
+ define("meth", |this| -> this: name() + this: age()
+
+----
+Golo doc string
+----
+function nullTest = {
+ let m = map[
+ ["a", 1],
+ ["b", 2]
+ ]
+
+ println(map: get("a") orIfNull 0)
+ println(map: get("b")?: toString() orIfNull "0")
+
+}
+
+struct Point = { x, y }
+
+function deco1 = |fun| {
+ return |args...| {
+ return "deco1 + " + fun: invokeWithArguments(args)
+ }
+}
+
+@deco1
+function decofoo = |a| {
+ return "foo: " + a
+}
+
+@deco1
+function decobar = |a| -> "bar: " + a
+
+function deco2 = |fun| {
+ return |args...| {
+ return "deco2 + " + fun: invokeWithArguments(args)
+ }
+}
+
+@deco2
+@deco1
+function decobaz = |a| -> "baz: " + a
+
+let deco3 = ^deco1: andThen(^deco2)
+
+@deco3
+function decospam = |a| -> "spam: " + a
+
+@another.Module.deco
+function ping = -> "pong"
+
+@deco("with", params)
+function gnop = -> "gnip"
diff --git a/tests/examplefiles/example.groovy b/tests/examplefiles/example.groovy
new file mode 100755
index 00000000..25ef2eab
--- /dev/null
+++ b/tests/examplefiles/example.groovy
@@ -0,0 +1,2 @@
+#!/usr/bin/env groovy
+println "Hello World"
diff --git a/tests/examplefiles/example.hs b/tests/examplefiles/example.hs
new file mode 100644
index 00000000..f5e2b555
--- /dev/null
+++ b/tests/examplefiles/example.hs
@@ -0,0 +1,31 @@
+module ĈrazyThings where
+
+import "base" Data.Char
+import "base" Data.Char (isControl, isSpace)
+import "base" Data.Char (isControl, --isSpace)
+ isSpace)
+import "base" Data.Char (isControl, -- isSpace)
+ isSpace)
+
+(-->) :: Num a => a -- signature
+(-->) = 2 -- >implementation
+
+--test comment
+-- test comment
+
+main :: IO ()
+main = putStrLn "hello world"
+
+gádd x y = x + y
+ádd x y = x + y
+
+
+data ĈrazyThings =
+ Ĉar |
+ House |
+ Peár
+ deriving (Show, Eq)
+
+-- some char literals:
+
+charl = ['"', 'a', '\ESC', '\'', ' ']
diff --git a/tests/examplefiles/example.hx b/tests/examplefiles/example.hx
new file mode 100644
index 00000000..7584fc81
--- /dev/null
+++ b/tests/examplefiles/example.hx
@@ -0,0 +1,192 @@
+/**
+ * This is not really a valid Haxe file, but just an demo...
+ */
+
+package;
+package net.onthewings;
+
+import net.onthewings.Test;
+import net.onthewings.*;
+
+using Lambda;
+using net.onthewings.Test;
+
+#if flash8
+// Haxe code specific for flash player 8
+#elseif flash
+// Haxe code specific for flash platform (any version)
+#elseif js
+// Haxe code specific for javascript plaform
+#elseif neko
+// Haxe code specific for neko plaform
+#else
+// do something else
+ #error // will display an error "Not implemented on this platform"
+ #error "Custom error message" // will display an error "Custom error message"
+#end
+
+0; // Int
+-134; // Int
+0xFF00; // Int
+
+123.0; // Float
+.14179; // Float
+13e50; // Float
+-1e-99; // Float
+
+"hello"; // String
+"hello \"world\" !"; // String
+'hello "world" !'; // String
+
+true; // Bool
+false; // Bool
+
+null; // Unknown<0>
+
+~/[a-z]+/i; // EReg : regular expression
+
+var point = { "x" : 1, "y" : -5 };
+
+{
+ var x;
+ var y = 3;
+ var z : String;
+ var w : String = "";
+ var a, b : Bool, c : Int = 0;
+}
+
+//haxe3 pattern matching
+switch(e.expr) {
+ case EConst(CString(s)) if (StringTools.startsWith(s, "foo")):
+ "1";
+ case EConst(CString(s)) if (StringTools.startsWith(s, "bar")):
+ "2";
+ case EConst(CInt(i)) if (switch(Std.parseInt(i) * 2) { case 4: true; case _: false; }):
+ "3";
+ case EConst(_):
+ "4";
+ case _:
+ "5";
+}
+
+switch [true, 1, "foo"] {
+ case [true, 1, "foo"]: "0";
+ case [true, 1, _]: "1";
+ case _: "_";
+}
+
+
+class Test <T:Void->Void> {
+ private function new():Void {
+ inline function innerFun(a:Int, b:Int):Int {
+ return readOnlyField = a + b;
+ }
+
+ _innerFun(1, 2.3);
+ }
+
+ static public var instance(get,null):Test;
+ static function get_instance():Test {
+ return instance != null ? instance : instance = new Test();
+ }
+}
+
+@:native("Test") private class Test2 {}
+
+extern class Ext {}
+
+@:macro class M {
+ @:macro static function test(e:Array<Expr>):ExprOf<String> {
+ return macro "ok";
+ }
+}
+
+enum Color {
+ Red;
+ Green;
+ Blue;
+ Grey( v : Int );
+ Rgb( r : Int, g : Int, b : Int );
+ Alpha( a : Int, col : Color );
+}
+
+class Colors {
+ static function toInt( c : Color ) : Int {
+ return switch( c ) {
+ case Red: 0xFF0000;
+ case Green: 0x00FF00;
+ case Blue: 0x0000FF;
+ case Grey(v): (v << 16) | (v << 8) | v;
+ case Rgb(r,g,b): (r << 16) | (g << 8) | b;
+ case Alpha(a,c): (a << 24) | (toInt(c) & 0xFFFFFF);
+ }
+ }
+}
+
+class EvtQueue<T : (Event, EventDispatcher)> {
+ var evt : T;
+}
+
+typedef DS = Dynamic<String>;
+typedef Pt = {
+ var x:Float;
+ var y:Float;
+ @:optional var z:Float; /* optional z */
+ function add(pt:Pt):Void;
+}
+typedef Pt2 = {
+ x:Float,
+ y:Float,
+ ?z:Float, //optional z
+ add : Point -> Void,
+}
+
+
+//top-level class members
+public function test();
+private var attr(get, set) = 1;
+
+
+//pre-proc number
+public static inline function indexOf<T>(arr:Array<T>, v:T) : Int
+{
+ #if (haxe_ver >= 3.1)
+ return arr.indexOf(v);
+ #else
+ #if (flash || js)
+ return untyped arr.indexOf(v);
+ #else
+ return std.Lambda.indexOf(arr, v);
+ #end
+ #end
+}
+
+//macro reification
+var e = macro var $myVar = 0;
+var e = macro ${v}.toLowerCase();
+var e = macro o.$myField;
+var e = macro { $myField : 0 };
+var e = macro $i{varName}++;
+var e = macro $v{myStr};
+var args = [macro "sub", macro 3];
+var e = macro "Hello".toLowerCase($a{args});
+(macro $i{tmp}.addAtom($v{name}, $atom)).finalize(op.pos);
+
+var c = macro class MyClass {
+ public function new() { }
+ public function $funcName() {
+ trace($v{funcName} + " was called");
+ }
+}
+
+var c = macro interface IClass {};
+
+//macro class could have no name...
+var def = macro class {
+ private inline function new(loader) this = loader;
+ private var loader(get,never) : $loaderType;
+ inline private function get_loader() : $loaderType return this;
+};
+
+//ECheckType
+var f = (123:Float); \ No newline at end of file
diff --git a/tests/examplefiles/example.i6t b/tests/examplefiles/example.i6t
new file mode 100644
index 00000000..0f41b425
--- /dev/null
+++ b/tests/examplefiles/example.i6t
@@ -0,0 +1,32 @@
+B/examt: Example Template.
+
+@Purpose: To show the syntax of I6T, specifically the parts relating to the
+inclusion of I7 and at signs in the first column.
+
+@-------------------------------------------------------------------------------
+
+@p Lines.
+
+@c
+{-lines:type}
+! This is a comment.
+{-endlines}
+
+@-This line begins with @-, so it is ignored.
+
+@p Paragraph.
+This is a paragraph.
+@p Another paragraph.
+So
+
+is
+
+this.
+
+@Purpose: This purpose line is ignored.
+
+@c At signs and (+ +).
+[ Foo i;
+print (+score [an I7 value]+), "^";
+@add sp 1 -> i; ! Assembly works even in the first column.
+];
diff --git a/tests/examplefiles/example.i7x b/tests/examplefiles/example.i7x
new file mode 100644
index 00000000..ab94ac69
--- /dev/null
+++ b/tests/examplefiles/example.i7x
@@ -0,0 +1,45 @@
+example by David Corbett begins here.
+
+"Implements testable examples."
+
+An example is a kind of thing. An example can be tested. An example is seldom tested.
+
+example ends here.
+
+----
+[The] documentation [starts here.]
+----
+
+This extension adds examples, which may be tested.
+
+Chapter: Usage
+
+To add an example to the story, we write:
+
+ The foobar is an example.
+
+To interact with it in Inform 6, we write something like:
+
+ To say (E - example): (-
+ print (object) {E};
+ -).
+ [The IDE's documentation viewer does not display the closing -). I don't know how to fix that.]
+
+Section: Testing
+
+We can make an example be tested using:
+
+ now the foobar is tested;
+
+Example: * Exempli Gratia - A simple example.
+
+ *: "Exempli Gratia"
+
+ Include example by David Corbett.
+
+ The Kitchen is a room. The egg is an example, here.
+
+ Before dropping the egg:
+ now the egg is tested.
+
+ Test me with "get egg / drop egg".
diff --git a/tests/examplefiles/example.inf b/tests/examplefiles/example.inf
new file mode 100644
index 00000000..73cdd087
--- /dev/null
+++ b/tests/examplefiles/example.inf
@@ -0,0 +1,374 @@
+!% $SMALL ! This is ICL, not a comment.
+!% -w
+
+!% A comprehensive test of Inform6Lexer.
+
+Switches d2SDq;
+
+Constant Story "Informal Testing";
+Constant Headline "^Not a game.^";!% This is a comment, not ICL.
+
+Release 2;
+Serial "140308";
+Version 5;
+
+Ifndef TARGET_ZCODE;
+Ifndef TARGET_GLULX;
+Ifndef WORDSIZE;
+Default WORDSIZE 2;
+Constant TARGET_ZCODE;
+Endif;
+Endif;
+Endif;
+
+Ifv3; Message "Compiling to version 3"; Endif;
+Ifv5; Message "Not compiling to version 3"; endif;
+ifdef TARGET_ZCODE;
+#IFTRUE (#version_number == 5);
+Message "Compiling to version 5";
+#ENDIF;
+endif ;
+
+Replace CreatureTest;
+
+Include "Parser";
+Include "VerbLib";
+
+# ! A hash is optional at the top level.
+Object kitchen "Kitchen"
+ with description "You are in a kitchen.",
+ arr 1 2 3 4,
+ has light;
+
+#[ Initialise;
+ location = kitchen;
+ print "v"; inversion; "^";
+];
+
+Ifdef VN_1633;
+Replace IsSeeThrough IsSeeThroughOrig;
+[ IsSeeThrough * o;
+ return o hasnt opaque || IsSeeThroughOrig(o);
+];
+Endif;
+
+Abbreviate "test";
+
+Array table buffer 260;
+
+Attribute reversed;
+Attribute opaque alias locked;
+Constant to reversed;
+
+Property long additive additive long alias;
+Property long long long wingspan alias alias;
+
+Class Flier with wingspan 5;
+Class Bird(10) has animate class Flier with wingspan 2;
+
+Constant Constant1;
+Constant Constant2 Constant1;
+Constant Constant3 = Constant2;
+Ifdef VN_1633; Undef Constant; Endif;
+
+Ifdef VN_1633;
+Dictionary 'word' 1 2;
+Ifnot;
+Dictionary dict_word "word";
+Endif;
+
+Fake_action NotReal;
+
+Global global1;
+Global global2 = 69105;
+
+Lowstring low_string "low string";
+
+Iftrue false;
+Message error "Uh-oh!^~false~ shouldn't be ~true~.";
+Endif;
+Iffalse true;
+Message fatalerror "Uh-oh!^~true~ shouldn't be ~false~.";
+Endif;
+
+Nearby person "person"
+ with name 'person',
+ description "This person is barely implemented.",
+ life [ * x y z;
+ Ask: print_ret (The) self, " says nothing.";
+ Answer: print (The) self, " didn't say anything.^"; rfalse;
+ ]
+ has has animate transparent;
+
+Object -> -> test_tube "test tube"
+ with name 'test' "tube" 'testtube',
+ has ~openable ~opaque container;
+
+Bird -> pigeon
+ with name 'pigeon',
+ description [;
+ "The pigeon has a wingspan of ", self.&wingspan-->0, " wing units.";
+ ];
+
+Object -> "thimble" with name 'thimble';
+
+Object -> pebble "pebble" with name 'pebble';
+
+Ifdef TARGET_ZCODE; Trace objects; Endif;
+
+Statusline score;
+
+Stub StubR 3;
+
+Ifdef TARGET_ZCODE;
+Zcharacter "abcdefghijklmnopqrstuvwxyz"
+ "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "123456789.,!?_#'0/@{005C}-:()";
+Zcharacter table '@!!' '@<<' '@'A';
+Zcharacter table + '@AE' '@{dc}' '@et' '@:y';
+Ifnot;
+Ifdef TARGET_GLULX;
+Message "Glulx doesn't use ~Zcharacter~.^Oh well."; ! '~' and '^' work here.
+Ifnot;
+Message warning "Uh-oh! ^~^"; ! They don't work in other Messages.
+Endif;
+Endif;
+
+Include "Grammar";
+
+Verb"acquire"'collect'='take';
+
+[ NounFilter; return noun ofclass Bird; ];
+
+[ ScopeFilter obj;
+ switch (scope_stage) {
+ 1: rtrue;
+ 2: objectloop (obj in compass) PlaceInScope(obj);
+ 3: "Nothing is in scope.";
+ }
+];
+
+Verb meta "t" 'test'
+ * 'held' held -> TestHeld
+ * number -> TestNumber
+ * reversed -> TestAttribute
+ * 'creature' creature -> TestCreature
+ * 'multiheld' multiheld -> TestMultiheld
+ * 'm' multiexcept 'into'/"in" noun -> TestMultiexcept
+ * 'm' multiinside 'from' noun -> TestMultiinside
+ * multi -> TestMulti
+ * 'filter'/'f' noun=NounFilter -> TestNounFilter
+ * 'filter'/'f' scope=ScopeFilter -> TestScopeFilter
+ * 'special' special -> TestSpecial
+ * topic -> TestTopic;
+
+Verb 'reverse' 'swap' 'exchange'
+ * held 'for' noun -> reverse
+ * noun 'with' noun -> reverse reverse;
+
+Extend "t" last * noun -> TestNoun;
+
+Extend 't' first * -> Test;
+
+Extend 'wave' replace * -> NewWave;
+
+Extend only 'feel' 'touch' replace * noun -> Feel;
+
+[ TestSub a b o;
+ string 25 low_string;
+ print "Test what?> ";
+ table->0 = 260;
+ parse->0 = 61;
+ #Ifdef TARGET_ZCODE;
+ read buffer parse;
+ #Ifnot; ! TARGET_GLULX
+ KeyboardPrimitive(buffer, parse);
+ #Endif; ! TARGET_
+ switch (parse-->1) {
+ 'save':
+ #Ifdef TARGET_ZCODE;
+ #Ifv3;
+ @save ?saved;
+ #Ifnot;
+ save saved;
+ #Endif;
+ #Endif;
+ print "Saving failed.^";
+ 'restore':
+ #Ifdef TARGET_ZCODE;
+ restore saved;
+ #Endif;
+ print "Restoring failed.^";
+ 'restart':
+ @restart;
+ 'quit', 'q//':
+ quit;
+ return 2; rtrue; rfalse; return;
+ 'print', 'p//':
+ print "Print:^",
+ " (string): ", (string) "xyzzy^",
+ " (number): ", (number) 123, "^",
+ " (char): ", (char) 'x', "^",
+ " (address): ", (address) 'plugh//p', "^",
+ " (The): ", (The) person, "^",
+ " (the): ", (the) person, "^",
+ " (A): ", (A) person, "^",
+ " (a): ", (a) person, "^",
+ " (an): ", (an) person, "^",
+ " (name): ", (name) person, "^",
+ " (object): ", (object) person, "^",
+ " (property): ", (property) alias, "^",
+ " (<routine>): ", (LanguageNumber) 123, "^",
+ " <expression>: ", a * 2 - 1, "^",
+ " (<expression>): ", (a + person), "^";
+ print "Escapes:^",
+ " by mnemonic: @!! @<< @'A @AE @et @:y^",
+ " by decimal value: @@64 @@126^",
+ " by Unicode value: @{DC}@{002b}^",
+ " by string variable: @25^";
+ 'font', 'style':
+ font off; print "font off^";
+ font on; print "font on^";
+ style reverse; print "style reverse^"; style roman;
+ style bold; print "style bold^";
+ style underline; print "style underline^";
+ style fixed; print "style fixed^";
+ style roman; print "style roman^";
+ 'statements':
+ spaces 8;
+ objectloop (o) {
+ print "objectloop (o): ", (the) o, "^";
+ }
+ objectloop (o in compass) { ! 'in' is a keyword
+ print "objectloop (o in compass): ", (the) o, "^";
+ }
+ objectloop (o in compass && true) { ! 'in' is an operator
+ print "objectloop (o in compass && true): ", (the) o, "^";
+ }
+ objectloop (o from se_obj) {
+ print "objectloop (o from se_obj): ", (the) o, "^";
+ }
+ objectloop (o near person) {
+ print "objectloop (o near person): ", (the) o, "^";
+ }
+ #Ifdef TARGET_ZCODE;
+ #Trace assembly on;
+@ ! This is assembly.
+ add -4 ($$1+$3)*2 -> b;
+ @get_sibling test_tube -> b ?saved;
+ @inc [b];
+ @je sp (1+3*0) ? equal;
+ @je 1 ((sp)) ?~ different;
+ .! This is a label:
+ equal;
+ print "sp == 1^";
+ jump label;
+ .different;
+ print "sp @@126= 1^";
+ .label;
+ #Trace off; #Endif; ! TARGET_ZCODE
+ a = random(10);
+ switch (a) {
+ 1, 9:
+ box "Testing oneself is best when done alone."
+ " -- Jimmy Carter";
+ 2, 6, to, 3 to 5, to to to:
+ <Take pigeon>;
+ #Ifdef VN_1633;
+ <Jump, person>;
+ #Endif;
+ a = ##Drop;
+ < ! The angle brackets may be separated by whitespace.
+ < (a) pigeon > >;
+ default:
+ do {
+ give person general ~general;
+ } until (person provides life && ~~false);
+ if (a == 7) a = 4;
+ else a = 5;
+ }
+ 'expressions':
+ a = 1+1-1*1/1%1&1|1&&1||1==(1~=(1>(1<(1>=(1<=1)))));
+ a++; ++a; a--; --a;
+ a = person.life;
+ a = kitchen.&arr;
+ a = kitchen.#arr;
+ a = Bird::wingspan;
+ a = kitchen has general;
+ a = kitchen hasnt general;
+ a = kitchen provides arr;
+ a = person in kitchen;
+ a = person notin kitchen;
+ a = person ofclass Bird;
+ a = a == 0 or 1;
+ a = StubR();
+ a = StubR(a);
+ a = StubR(, a);
+ a = "string";
+ a = 'word';
+ a = '''; ! character
+ a = $09afAF;
+ a = $$01;
+ a = ##Eat; a = #a$Eat;
+ a = #g$self;
+ a = #n$!word;
+ a = #r$StubR;
+ a = #dict_par1;
+ default:
+ for (a = 2, b = a; (a < buffer->1 + 2) && (Bird::wingspan): ++a, b--) {
+ print (char) buffer->a;
+ }
+ new_line;
+ for (::) break;
+ }
+ .saved;;
+];
+
+[ TestNumberSub;
+ print_ret parsed_number, " is ", (number) parsed_number, ".";
+];
+
+[ TestAttributeSub; print_ret (The) noun, " has been reversed."; ];
+
+[ CreatureTest obj; return obj has animate; ];
+
+[ TestCreatureSub; print_ret (The) noun, " is a creature."; ];
+
+[ TestMultiheldSub; print_ret "You are holding ", (the) noun, "."; ];
+
+[ TestMultiexceptSub; "You test ", (the) noun, " with ", (the) second, "."; ];
+
+[ TestMultiinsideSub; "You test ", (the) noun, " from ", (the) second, "."; ];
+
+[ TestMultiSub; print_ret (The) noun, " is a thing."; ];
+
+[ TestNounFilterSub; print_ret (The) noun, " is a bird."; ];
+
+[ TestScopeFilterSub; print_ret (The) noun, " is a direction."; ];
+
+[ TestSpecialSub; "Your lucky number is ", parsed_number, "."; ];
+
+[ TestTopicSub; "You discuss a topic."; ];
+
+[ TestNounSub; "That is ", (a) noun, "."; ];
+
+[ TestHeldSub; "You are holding ", (a) noun, "."; ];
+
+[ NewWaveSub; "That would be foolish."; ];
+
+[ FeelSub; print_ret (The) noun, " feels normal."; ];
+
+[ ReverseSub from;
+ from = parent(noun);
+ move noun to parent(second);
+ if (from == to)
+ move second to to;
+ else
+ move second to from;
+ give noun to;
+ from = to;
+ give second from;
+ "You swap ", (the) noun, " and ", (the) second, ".";
+];
+
+End: The End directive ends the source code.
diff --git a/tests/examplefiles/example.j b/tests/examplefiles/example.j
new file mode 100644
index 00000000..16cdde86
--- /dev/null
+++ b/tests/examplefiles/example.j
@@ -0,0 +1,564 @@
+; Example JVM assembly
+; Tested with JasminXT 2.4
+
+.bytecode 49.0
+.source HelloWorld.java
+.class public final enum HelloWorld
+.super java/lang/Object
+.implements java/io/Serializable
+.signature "Ljava/lang/Object;Ljava/io/Serializable;"
+.enclosing method hw/jasmin.HelloWorldRunner.run()V
+.deprecated
+.annotation visible HelloWorld
+ I I = 0
+.end annotation
+.debug "Happy debugging!"
+
+.inner interface public InnerInterface inner 'HelloWorld$InnerInterface' outer HelloWorld
+.inner class public InnerClass inner HelloWorld$InnerClass outer 'HelloWorld'
+
+.field public volatile transient I I
+.field static protected final serialVersionUID 'J' signature "TJ;" = 2147483648
+.field annotation protected 'protected' [[[Lcom/oracle/util/Checksums;
+ .deprecated
+ .signature "[[[Lcom/oracle/util/Checksums;"
+ .attribute foo "foo.txt"
+ .attribute 'foo' "foo.txt"
+.end field
+.field public newline I
+.field public static defaultString 'Ljava/lang/String;'
+
+.method public <init>()V
+ .limit stack 3
+.line 7
+ .var 0 is self LHelloWorld; from 0 to 1
+ aload_0
+ invokenonvirtual java/lang/Object/<init>()V
+ return
+.end method
+
+.method static public main([Ljava/lang/String;)V
+ .limit locals 7
+ .limit stack 10
+ .throws java.lang/RuntimeException
+ .catch java/lang.ClassCastException from cast to 'extra_l' using /extra
+ .signature "([Ljava/lang/String;)V"
+ .stack
+ offset /Input
+ locals Object java/lang/String
+ locals Uninitialized 'End'
+ locals Uninitialized 0
+ locals Top
+ locals Integer
+ locals Float
+ locals Long
+ locals Double
+ locals Null
+ locals UninitializedThis
+ stack Object java/lang/String
+ stack Uninitialized End
+ stack 'Uninitialized' 0
+ stack 'Top'
+ stack Integer
+ stack Float
+ stack Long
+ stack Double
+ stack Null
+ stack UninitializedThis
+ .end stack
+ .stack use 1 locals
+ offset 'extra'
+ .end stack
+ .stack use locals
+ .end stack
+.line 0xd
+ .var 0 is args [Ljava/lang/String;
+ aload_w 0
+ arraylength
+ ifne /Input
+ iconst_1
+ anewarray java/lang/String
+ checkcast [Ljava/lang/String;
+ astore_0
+ aload_0
+ iconst_0
+ ldc "World"
+ dup
+ putstatic HelloWorld.defaultString Ljava/lang/String;
+ aastore
+/Input:
+ iconst_2
+ iconst_3
+ multianewarray [[C 2
+ astore_1
+ aload_1
+ iconst_0
+ aaload
+ astore_2
+ aload_1
+ iconst_1
+ aaload
+ astore_3
+
+<<o:
+ aload_3
+ iconst_0
+ invokestatic HelloWorld/int()I
+ castore
+
+<<\u0020:
+ aload_3
+ dconst_1
+ dconst_0
+ dsub
+ d2i
+ invokestatic HelloWorld/double()D
+ d2i
+ castore
+
+<<!:
+ aload_3
+ lconst_0
+ dup2
+ lxor
+ lconst_1
+ dup2
+ ladd
+ lsub
+ lneg
+ l2i
+ invokestatic HelloWorld/long()J
+ l2i
+ castore
+
+<<H:
+ aload_2
+ fconst_0
+ fconst_1
+ fconst_2
+ dup_x2
+ fdiv
+ fmul
+ f2l
+ l2i
+ swap
+ invokestatic HelloWorld/float(F)F
+ f2i
+ castore
+
+<<e :
+ aload_2
+ iconst_1
+ i2s
+ i2c
+ i2b
+ iconst_1
+ newarray short
+ dup
+ iconst_0
+ iconst_1
+ newarray byte
+ dup
+ iconst_0
+ sipush 0x65
+ bastore
+ iconst_0
+ baload
+ sastore
+ iconst_0
+ saload
+ int2short
+ int2char
+ int2byte
+ castore
+
+ <<l :
+ aload_2
+ iconst_2
+ bipush 0x1b
+*2:
+ iconst_1
+ ishl
+ dup
+ lookupswitch
+ 0: '/lookupswitch'
+ 0x6c: /lookupswitch
+ default: *2
+/lookupswitch:
+ castore
+
+ ldc2_w 2
+ dup2
+ lcmp
+ .set i 4
+ .set 'j' 5
+ .var 4 is i I from 'i++' to End
+ .var 5 is j I signature "I" from i++ to End
+ istore 4
+ goto 1
+i++:
+ iinc 4 1
+1: iconst_0
+ istore_w 5
+ goto_w 2
+j++:
+ iinc_w 5 1
+2: getstatic java/lang/System/out Ljava/io/PrintStream;
+ aload_1
+ iload 4
+ aaload
+ iload_w 5
+ caload
+ invokevirtual java/io/PrintStream/print(C)V
+ iload 5
+ iconst_1
+ if_icmpne $+6
+ jsr extra
+ iload 5
+ iconst_2
+ if_icmplt j++
+ iconst_1
+ iload 4
+ if_icmpgt i++
+
+<<\u00a0:
+ getstatic java/lang/System/out Ljava/io/PrintStream;
+ invokestatic HelloWorld/get"example()LHelloWorld;
+ getfield HelloWorld/newline I
+ invokevirtual java/io/PrintStream/print(C)V
+End:
+ return
+
+extra:
+ astore 6
+ iload 4
+ tableswitch 0 1
+ extra_l
+ extra_string
+ default: 'End'
+ nop
+extra_string:
+ getstatic java/lang/System/out Ljava/io/PrintStream;
+ aload 0
+ iconst_0
+ aaload
+ invokevirtual java/io/PrintStream/print(Ljava/lang/String;)V
+cast:
+ ldc java/lang/String
+ checkcast java/lang/Class
+ pop
+ ldc Ljava/lang/String;
+ checkcast Ljava/lang/Class;
+ pop
+ iconst_1
+ dup
+ newarray boolean
+ checkcast [Z
+ pop
+ newarray 'int'
+ checkcast HelloWorld
+ checkcast LHelloWorld;
+ pop
+extra_l:
+ getstatic java/lang/System/out Ljava/io/PrintStream;
+ dup
+ ldc "\123.\456.\u006c.\n.\r.\t.\f.\b.\".\'.\\"
+ iconst_5
+ invokeinterface java/lang/CharSequence/charAt(I)C 2
+ invokevirtual java/io/PrintStream/print(C)V
+/extra:
+ pop
+ ret 6
+.end method
+
+.method private static get"example()LHelloWorld;
+ .limit locals 3
+ .limit stack 4
+ .catch all from 7 to 53 using 59
+ aconst_null
+ dup
+ dup
+ astore_w 0
+try:
+ goto $+0x11
+finally:
+ astore_w 2
+ putfield HelloWorld/newline I
+ ret_w 2
+ nop
+ aload_0
+ areturn
+ ifnonnull $-2
+ ifnull $+3
+ new HelloWorld
+ dup
+ dup
+ invokespecial HelloWorld/<init>()V
+ astore 0
+ aload 0
+ monitorenter
+ monitorexit
+ new java/lang/RuntimeException
+ dup
+ invokespecial java/lang/RuntimeException/<init>()V
+ athrow
+ aconst_null
+/try:
+ dup
+ aconst_null
+ if_acmpeq $+3
+ areturn
+catch:
+ jsr $+10
+ aload_0
+ dup
+ aconst_null
+ if_acmpne /try
+ areturn
+ astore_1
+ aload_0
+ ldc 10
+ jsr_w finally
+ ret 1
+'single\u0020quoted\u0020label': ; Messes up [@ below if lexed sloppily
+.end method
+
+.method varargs private static int()I
+ .annotation invisible HelloWorld
+ [@ [@ WhatIsThis??? = .annotation ; name, type, exttype
+ I I = 1 ; name, type
+ another-I I = 2
+ Enum e Ljava/util/logging/Level; = FINE
+ .end annotation
+ .annotation
+ s s = "foo"
+ another-s s = "bar"
+ Enum [e Ljava/util/logging/Level; = FINE FINE 'FINE' FINE
+ .end annotation
+ float F = 123.456
+ .end annotation
+ .annotation visibleparam 1 LHelloWorld;
+ x [I = 0x01 0x02 0x03
+ y I = 2
+ .end annotation
+ .annotation invisibleparam 255 HelloWorld
+ a F = 1.2
+ b D = 3.4
+ .end annotation
+ .annotation default
+ I = 0
+ .end annotation
+ .limit locals 4
+ .limit stack 20
+ iconst_1
+ newarray int
+ dup
+ dup
+ instanceof [Z
+ bipush 0x9
+ bipush 0xB
+ iand
+ iconst_5
+ iconst_4
+ dup_x1
+ iconst_m1
+ iadd
+ bipush +-111
+ ineg
+ swap
+ idiv
+ dup_x2
+ dup
+ ishr
+ ishl
+ imul
+ ior
+ bipush -73
+ ixor
+ isub
+ dup
+ iconst_1
+ iadd
+ irem
+ iastore
+ iconst_0
+ iaload
+ istore_0
+ iload_0
+ istore_1
+ iload_1
+ istore_2
+ iload_2
+ istore_3
+ iload_3
+ dup
+ dup
+ dup2_x1
+ if_icmpeq $+33
+ dup
+ dup
+ if_icmpge $+28
+ dup
+ dup
+ if_icmple $+23
+ dup
+ ifle $+19
+ dup
+ ifeq $+15
+ dup
+ iflt $+11
+ dup
+ ifgt $+7
+ dup
+ ifge $+3
+ ireturn
+.end method
+
+.method static private fpstrict double()D
+ .limit locals 7
+ .limit stack 11
+ dconst_1
+ dconst_0
+ dcmpg
+ newarray double
+ dup
+ dconst_0
+ dup2
+ dcmpl
+ ldc2_w 128.
+ ldc2_w -240.221d
+ dneg
+ ldc2_w 158.d
+ dup2
+ dadd
+ dup2_x2
+ drem
+ ddiv
+ pop2
+ dconst_1
+ dmul
+ d2f
+ f2d
+ d2l
+ l2i
+ iconst_2
+ iushr
+ i2d
+ dastore
+ iconst_0
+ daload
+ dstore_0
+ dload_0
+ dstore_1
+ dload_1
+ dstore_2
+ dload_2
+ dstore_3
+ dload_3
+ dstore 4
+ dload 4
+ dstore_w 5
+ dload_w 5
+ dreturn
+.end method
+
+.method static long()J
+ .limit locals 7
+ .limit stack 11
+ iconst_1
+ newarray long
+ dup
+ iconst_0
+ ldc2_w 5718613688
+ ldc2_w 3143486100
+ ldc2_w 0x3
+ ldiv
+ lmul
+ ldc2_w -10000000000
+ lrem
+ ldc_w 0x60
+ i2l
+ lor
+ ldc 0x33
+ i2l
+ land
+ dup2
+ iconst_1
+ lshl
+ iconst_3
+ lshr
+ iconst_3
+ lushr
+ ladd
+ l2d
+ d2l
+ l2f
+ f2l
+ lastore
+ iconst_0
+ laload
+ lstore_0
+ lload_0
+ lstore_1
+ lload_1
+ lstore_2
+ lload_2
+ lstore_3
+ lload_3
+ lstore 4
+ lload 4
+ lstore_w 5
+ lload_w 5
+ lreturn
+.end method
+
+.method private static float(F)F
+ .limit locals 6
+ .limit stack 9
+ iconst_1
+ newarray float
+ dup
+ fload_0
+ dup
+ fcmpg
+ fload_0
+ dup
+ dup
+ dup
+ dup2_x2
+ fadd
+ fsub
+ fneg
+ frem
+ ldc 70
+ i2f
+ fadd
+ fadd
+ swap
+ pop
+ fastore
+ fload_0
+ dup
+ fcmpl
+ faload
+ fstore_0
+ fload_0
+ fstore_1
+ fload_1
+ fstore_2
+ fload_2
+ fstore_3
+ fload_3
+ fstore 4
+ fload 4
+ fstore_w 5
+ fload_w 5
+ freturn
+.end method
+
+.method abstract bridge synthetic 'acc1()V'
+ breakpoint
+.end method
+
+.method native synchronized acc2()V
+.end method
diff --git a/tests/examplefiles/example.java b/tests/examplefiles/example.java
new file mode 100644
index 00000000..f2e94322
--- /dev/null
+++ b/tests/examplefiles/example.java
@@ -0,0 +1,16 @@
+class _PostUnico$deClassá
+{void fo$o() {}
+
+ void PostUnicodeFunctioná() {
+ láb$el:
+ break láb$el;
+
+ }
+}
+
+class áPreUnicode$Class
+{
+ public int $foo;
+ public int á$foo;
+ _PostUnico$deClassá áPreUnicodeFunction() { return null; }
+}
diff --git a/tests/examplefiles/example.kal b/tests/examplefiles/example.kal
new file mode 100644
index 00000000..c05c14ca
--- /dev/null
+++ b/tests/examplefiles/example.kal
@@ -0,0 +1,75 @@
+#!/usr/bin/env kal
+
+# This demo executes GET requests in parallel and in series
+# using `for` loops and `wait for` statements.
+
+# Notice how the serial GET requests always return in order
+# and take longer in total. Parallel requests come back in
+# order of receipt.
+
+http = require 'http'
+
+urls = ['http://www.google.com'
+ 'http://www.apple.com'
+ 'http://www.microsoft.com'
+ 'http://www.nodejs.org'
+ 'http://www.yahoo.com']
+
+# This function does a GET request for each URL in series
+# It will wait for a response from each request before moving on
+# to the next request. Notice the output will be in the same order as the
+# urls variable every time regardless of response time.
+# It is a task rather than a function because it is called asynchronously
+# This allows us to use `return` to implicitly call back
+task series_demo()
+ # The `series` keyword is optional here (for loops are serial by default)
+ total_time = 0
+
+ for series url in urls
+ timer = new Date
+
+ # we use the `safe` keyword because get is a "nonstandard" task
+ # that does not call back with an error argument
+ safe wait for response from http.get url
+
+ delay = new Date() - timer
+ total_time += delay
+
+ print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay} ms"
+
+ # because we are in a task rather than a function, this actually exectutes a callback
+ return total_time
+
+# This function does a GET request for each URL in parallel
+# It will NOT wait for a response from each request before moving on
+# to the next request. Notice the output will be determined by the order in which
+# the requests complete!
+task parallel_demo()
+ total_time = 0
+
+ # The `parallel` keyword is only meaningful here because the loop contains
+ # a `wait for` statement (meaning callbacks are used)
+ for parallel url in urls
+ timer = new Date
+
+ # we use the `safe` keyword because get is a "nonstandard" task
+ # that does not call back with an error argument
+ safe wait for response from http.get url
+
+ delay = new Date() - timer
+ total_time += delay
+
+ print "GET #{url} - #{response.statusCode} - #{response.connection.bytesRead} bytes - #{delay}ms"
+
+ # because we are in a task rather than a function, this actually exectutes a callback
+ return total_time
+
+print 'Series Requests...'
+wait for time1 from series_demo()
+print "Total duration #{time1}ms"
+
+print ''
+
+print 'Parallel Requests...'
+wait for time2 from parallel_demo()
+print "Total duration #{time2}ms"
diff --git a/tests/examplefiles/example.lagda b/tests/examplefiles/example.lagda
new file mode 100644
index 00000000..b5476fa0
--- /dev/null
+++ b/tests/examplefiles/example.lagda
@@ -0,0 +1,19 @@
+\documentclass{article}
+% this is a LaTeX comment
+\usepackage{agda}
+
+\begin{document}
+
+Here's how you can define \emph{RGB} colors in Agda:
+
+\begin{code}
+module example where
+
+open import Data.Fin
+open import Data.Nat
+
+data Color : Set where
+ RGB : Fin 256 → Fin 256 → Fin 256 → Color
+\end{code}
+
+\end{document} \ No newline at end of file
diff --git a/tests/examplefiles/example.liquid b/tests/examplefiles/example.liquid
new file mode 100644
index 00000000..8f3ea9e9
--- /dev/null
+++ b/tests/examplefiles/example.liquid
@@ -0,0 +1,42 @@
+# This is an example file. Process it with `./pygmentize -O full -f html -o /liquid-example.html example.liquid`.
+
+{% raw %}
+some {{raw}} liquid syntax
+
+{% raw %}
+{% endraw %}
+
+Just regular text - what happens?
+
+{% comment %}My lovely {{comment}} {% comment %}{% endcomment %}
+
+{% custom_tag params: true %}
+{% custom_block my="abc" c = false %}
+ Just usual {{liquid}}.
+{% endcustom_block %}
+
+{% another_tag "my string param" %}
+
+{{ variable | upcase }}
+{{ var.field | textilize | markdownify }}
+{{ var.field.property | textilize | markdownify }}
+{{ 'string' | truncate: 100 param='df"g' }}
+
+{% cycle '1', 2, var %}
+{% cycle 'group1': '1', var, 2 %}
+{% cycle group2: '1', var, 2 %}
+
+{% if a == 'B' %}
+{% elsif a == 'C%}' %}
+{% else %}
+{% endif %}
+
+{% unless not a %}
+{% else %}
+{% endunless %}
+
+{% case a %}
+{% when 'B' %}
+{% when 'C' %}
+{% else %}
+{% endcase %} \ No newline at end of file
diff --git a/tests/examplefiles/example.ma b/tests/examplefiles/example.ma
new file mode 100644
index 00000000..a8119ea5
--- /dev/null
+++ b/tests/examplefiles/example.ma
@@ -0,0 +1,8 @@
+1 + 1 (* This is a comment *)
+Global`
+SomeNamespace`Foo
+f[x_, y__, 3, z___] := tsneirsnteintie "fosrt" neisnrteiasrn
+E + 3
+Plus[1,Times[2,3]]
+Map[#1 + #2&, SomePairList]
+Plus[1.,-1,-1.,-1.0,] \ No newline at end of file
diff --git a/tests/examplefiles/example.mq4 b/tests/examplefiles/example.mq4
new file mode 100644
index 00000000..54a5fa60
--- /dev/null
+++ b/tests/examplefiles/example.mq4
@@ -0,0 +1,187 @@
+//+------------------------------------------------------------------+
+//| PeriodConverter.mq4 |
+//| Copyright 2006-2014, MetaQuotes Software Corp. |
+//| http://www.metaquotes.net |
+//+------------------------------------------------------------------+
+#property copyright "2006-2014, MetaQuotes Software Corp."
+#property link "http://www.mql4.com"
+#property description "Period Converter to updated format of history base"
+#property strict
+#property show_inputs
+#include <WinUser32.mqh>
+
+input int InpPeriodMultiplier=3; // Period multiplier factor
+int ExtHandle=-1;
+//+------------------------------------------------------------------+
+//| script program start function |
+//+------------------------------------------------------------------+
+void OnStart()
+ {
+ datetime time0;
+ ulong last_fpos=0;
+ long last_volume=0;
+ int i,start_pos,periodseconds;
+ int hwnd=0,cnt=0;
+//---- History header
+ int file_version=401;
+ string c_copyright;
+ string c_symbol=Symbol();
+ int i_period=Period()*InpPeriodMultiplier;
+ int i_digits=Digits;
+ int i_unused[13];
+ MqlRates rate;
+//---
+ ExtHandle=FileOpenHistory(c_symbol+(string)i_period+".hst",FILE_BIN|FILE_WRITE|FILE_SHARE_WRITE|FILE_SHARE_READ|FILE_ANSI);
+ if(ExtHandle<0)
+ return;
+ c_copyright="(C)opyright 2003, MetaQuotes Software Corp.";
+ ArrayInitialize(i_unused,0);
+//--- write history file header
+ FileWriteInteger(ExtHandle,file_version,LONG_VALUE);
+ FileWriteString(ExtHandle,c_copyright,64);
+ FileWriteString(ExtHandle,c_symbol,12);
+ FileWriteInteger(ExtHandle,i_period,LONG_VALUE);
+ FileWriteInteger(ExtHandle,i_digits,LONG_VALUE);
+ FileWriteInteger(ExtHandle,0,LONG_VALUE);
+ FileWriteInteger(ExtHandle,0,LONG_VALUE);
+ FileWriteArray(ExtHandle,i_unused,0,13);
+//--- write history file
+ periodseconds=i_period*60;
+ start_pos=Bars-1;
+ rate.open=Open[start_pos];
+ rate.low=Low[start_pos];
+ rate.high=High[start_pos];
+ rate.tick_volume=(long)Volume[start_pos];
+ rate.spread=0;
+ rate.real_volume=0;
+ //--- normalize open time
+ rate.time=Time[start_pos]/periodseconds;
+ rate.time*=periodseconds;
+ for(i=start_pos-1; i>=0; i--)
+ {
+ if(IsStopped())
+ break;
+ time0=Time[i];
+ //--- history may be updated
+ if(i==0)
+ {
+ //--- modify index if history was updated
+ if(RefreshRates())
+ i=iBarShift(NULL,0,time0);
+ }
+ //---
+ if(time0>=rate.time+periodseconds || i==0)
+ {
+ if(i==0 && time0<rate.time+periodseconds)
+ {
+ rate.tick_volume+=(long)Volume[0];
+ if(rate.low>Low[0])
+ rate.low=Low[0];
+ if(rate.high<High[0])
+ rate.high=High[0];
+ rate.close=Close[0];
+ }
+ last_fpos=FileTell(ExtHandle);
+ last_volume=(long)Volume[i];
+ FileWriteStruct(ExtHandle,rate);
+ cnt++;
+ if(time0>=rate.time+periodseconds)
+ {
+ rate.time=time0/periodseconds;
+ rate.time*=periodseconds;
+ rate.open=Open[i];
+ rate.low=Low[i];
+ rate.high=High[i];
+ rate.close=Close[i];
+ rate.tick_volume=last_volume;
+ }
+ }
+ else
+ {
+ rate.tick_volume+=(long)Volume[i];
+ if(rate.low>Low[i])
+ rate.low=Low[i];
+ if(rate.high<High[i])
+ rate.high=High[i];
+ rate.close=Close[i];
+ }
+ }
+ FileFlush(ExtHandle);
+ Print(cnt," record(s) written");
+//--- collect incoming ticks
+ datetime last_time=LocalTime()-5;
+ while(!IsStopped())
+ {
+ datetime cur_time=LocalTime();
+ //--- check for new rates
+ if(RefreshRates())
+ {
+ time0=Time[0];
+ FileSeek(ExtHandle,last_fpos,SEEK_SET);
+ //--- is there current bar?
+ if(time0<rate.time+periodseconds)
+ {
+ rate.tick_volume+=(long)Volume[0]-last_volume;
+ last_volume=(long)Volume[0];
+ if(rate.low>Low[0])
+ rate.low=Low[0];
+ if(rate.high<High[0])
+ rate.high=High[0];
+ rate.close=Close[0];
+ }
+ else
+ {
+ //--- no, there is new bar
+ rate.tick_volume+=(long)Volume[1]-last_volume;
+ if(rate.low>Low[1])
+ rate.low=Low[1];
+ if(rate.high<High[1])
+ rate.high=High[1];
+ //--- write previous bar remains
+ FileWriteStruct(ExtHandle,rate);
+ last_fpos=FileTell(ExtHandle);
+ //----
+ rate.time=time0/periodseconds;
+ rate.time*=periodseconds;
+ rate.open=Open[0];
+ rate.low=Low[0];
+ rate.high=High[0];
+ rate.close=Close[0];
+ rate.tick_volume=(long)Volume[0];
+ last_volume=rate.tick_volume;
+ }
+ //----
+ FileWriteStruct(ExtHandle,rate);
+ FileFlush(ExtHandle);
+ //---
+ if(hwnd==0)
+ {
+ hwnd=WindowHandle(Symbol(),i_period);
+ if(hwnd!=0)
+ Print("Chart window detected");
+ }
+ //--- refresh window not frequently than 1 time in 2 seconds
+ if(hwnd!=0 && cur_time-last_time>=2)
+ {
+ PostMessageA(hwnd,WM_COMMAND,33324,0);
+ last_time=cur_time;
+ }
+ }
+ Sleep(50);
+ }
+//---
+ }
+//+------------------------------------------------------------------+
+//| |
+//+------------------------------------------------------------------+
+void OnDeinit(const int reason)
+ {
+//---
+ if(ExtHandle>=0)
+ {
+ FileClose(ExtHandle);
+ ExtHandle=-1;
+ }
+//---
+ }
+//+------------------------------------------------------------------+ \ No newline at end of file
diff --git a/tests/examplefiles/example.mqh b/tests/examplefiles/example.mqh
new file mode 100644
index 00000000..ee80ed52
--- /dev/null
+++ b/tests/examplefiles/example.mqh
@@ -0,0 +1,123 @@
+//+------------------------------------------------------------------+
+//| Array.mqh |
+//| Copyright 2009-2013, MetaQuotes Software Corp. |
+//| http://www.mql4.com |
+//+------------------------------------------------------------------+
+#include <Object.mqh>
+//+------------------------------------------------------------------+
+//| Class CArray |
+//| Purpose: Base class of dynamic arrays. |
+//| Derives from class CObject. |
+//+------------------------------------------------------------------+
+class CArray : public CObject
+ {
+protected:
+ int m_step_resize; // increment size of the array
+ int m_data_total; // number of elements
+ int m_data_max; // maximmum size of the array without memory reallocation
+ int m_sort_mode; // mode of array sorting
+
+public:
+ CArray(void);
+ ~CArray(void);
+ //--- methods of access to protected data
+ int Step(void) const { return(m_step_resize); }
+ bool Step(const int step);
+ int Total(void) const { return(m_data_total); }
+ int Available(void) const { return(m_data_max-m_data_total); }
+ int Max(void) const { return(m_data_max); }
+ bool IsSorted(const int mode=0) const { return(m_sort_mode==mode); }
+ int SortMode(void) const { return(m_sort_mode); }
+ //--- cleaning method
+ void Clear(void) { m_data_total=0; }
+ //--- methods for working with files
+ virtual bool Save(const int file_handle);
+ virtual bool Load(const int file_handle);
+ //--- sorting method
+ void Sort(const int mode=0);
+
+protected:
+ virtual void QuickSort(int beg,int end,const int mode=0) { }
+ };
+//+------------------------------------------------------------------+
+//| Constructor |
+//+------------------------------------------------------------------+
+CArray::CArray(void) : m_step_resize(16),
+ m_data_total(0),
+ m_data_max(0),
+ m_sort_mode(-1)
+ {
+ }
+//+------------------------------------------------------------------+
+//| Destructor |
+//+------------------------------------------------------------------+
+CArray::~CArray(void)
+ {
+ }
+//+------------------------------------------------------------------+
+//| Method Set for variable m_step_resize |
+//+------------------------------------------------------------------+
+bool CArray::Step(const int step)
+ {
+//--- check
+ if(step>0)
+ {
+ m_step_resize=step;
+ return(true);
+ }
+//--- failure
+ return(false);
+ }
+//+------------------------------------------------------------------+
+//| Sorting an array in ascending order |
+//+------------------------------------------------------------------+
+void CArray::Sort(const int mode)
+ {
+//--- check
+ if(IsSorted(mode))
+ return;
+ m_sort_mode=mode;
+ if(m_data_total<=1)
+ return;
+//--- sort
+ QuickSort(0,m_data_total-1,mode);
+ }
+//+------------------------------------------------------------------+
+//| Writing header of array to file |
+//+------------------------------------------------------------------+
+bool CArray::Save(const int file_handle)
+ {
+//--- check handle
+ if(file_handle!=INVALID_HANDLE)
+ {
+ //--- write start marker - 0xFFFFFFFFFFFFFFFF
+ if(FileWriteLong(file_handle,-1)==sizeof(long))
+ {
+ //--- write array type
+ if(FileWriteInteger(file_handle,Type(),INT_VALUE)==INT_VALUE)
+ return(true);
+ }
+ }
+//--- failure
+ return(false);
+ }
+//+------------------------------------------------------------------+
+//| Reading header of array from file |
+//+------------------------------------------------------------------+
+bool CArray::Load(const int file_handle)
+ {
+//--- check handle
+ if(file_handle!=INVALID_HANDLE)
+ {
+ //--- read and check start marker - 0xFFFFFFFFFFFFFFFF
+ if(FileReadLong(file_handle)==-1)
+ {
+ //--- read and check array type
+ if(FileReadInteger(file_handle,INT_VALUE)==Type())
+ return(true);
+ }
+ }
+//--- failure
+ return(false);
+ }
+//+------------------------------------------------------------------+
diff --git a/tests/examplefiles/example.ni b/tests/examplefiles/example.ni
new file mode 100644
index 00000000..32279e80
--- /dev/null
+++ b/tests/examplefiles/example.ni
@@ -0,0 +1,57 @@
+ | | |
+"Informal by Nature"
+[ * * * ]
+by
+[ * * * ]
+David Corbett
+
+[This is a [nested] comment.]
+
+Section 1 - Use option translation
+
+Use maximum tests of at least 100 translates as (-
+@c
+Constant MAX_TESTS = {N}; —). | Section 2
+
+A room has a number called size.
+
+The Kitchen is a room. "A nondescript kitchen.“ The Kitchen has size 2.
+
+When play begins:
+ say "Testing:[line break]";
+ test 0.
+
+To test (N — number): (—
+ if (Test({N}) == (+size of the Kitchen [this should succeed]+)) {-open—brace}
+ print ”Success.^”;
+ {-close-brace} else {
+ print “Failure.^";
+ }
+]; ! You shouldn't end a routine within a phrase definition, but it works.
+[ Unused;
+ #Include "\
+@p \
+"; ! At signs hold no power here.
+! Of course, the file "@p .h" must exist.
+-).
+
+Include (-!% This is not ICL.
+
+[ Test x;
+ if (x) {x++;}
+ {–! Single line comment.}
+@inc x;
+@p At signs.
+...
+@Purpose: ...
+...
+@-...
+@c ...
+@inc x;
+@c
+@c
+ return x;
+];
+@Purpose: ...
+@-------------------------------------------------------------------------------
+-).
diff --git a/tests/examplefiles/example.nix b/tests/examplefiles/example.nix
new file mode 100644
index 00000000..515b686f
--- /dev/null
+++ b/tests/examplefiles/example.nix
@@ -0,0 +1,80 @@
+{ stdenv, fetchurl, fetchgit, openssl, zlib, pcre, libxml2, libxslt, expat
+, rtmp ? false
+, fullWebDAV ? false
+, syslog ? false
+, moreheaders ? false, ...}:
+
+let
+ version = "1.4.4";
+ mainSrc = fetchurl {
+ url = "http://nginx.org/download/nginx-${version}.tar.gz";
+ sha256 = "1f82845mpgmhvm151fhn2cnqjggw9w7cvsqbva9rb320wmc9m63w";
+ };
+
+ rtmp-ext = fetchgit {
+ url = git://github.com/arut/nginx-rtmp-module.git;
+ rev = "1cfb7aeb582789f3b15a03da5b662d1811e2a3f1";
+ sha256 = "03ikfd2l8mzsjwx896l07rdrw5jn7jjfdiyl572yb9jfrnk48fwi";
+ };
+
+ dav-ext = fetchgit {
+ url = git://github.com/arut/nginx-dav-ext-module.git;
+ rev = "54cebc1f21fc13391aae692c6cce672fa7986f9d";
+ sha256 = "1dvpq1fg5rslnl05z8jc39sgnvh3akam9qxfl033akpczq1bh8nq";
+ };
+
+ syslog-ext = fetchgit {
+ url = https://github.com/yaoweibin/nginx_syslog_patch.git;
+ rev = "165affd9741f0e30c4c8225da5e487d33832aca3";
+ sha256 = "14dkkafjnbapp6jnvrjg9ip46j00cr8pqc2g7374z9aj7hrvdvhs";
+ };
+
+ moreheaders-ext = fetchgit {
+ url = https://github.com/agentzh/headers-more-nginx-module.git;
+ rev = "refs/tags/v0.23";
+ sha256 = "12pbjgsxnvcf2ff2i2qdn39q4cm5czlgrng96j8ml4cgxvnbdh39";
+ };
+in
+
+stdenv.mkDerivation rec {
+ name = "nginx-${version}";
+ src = mainSrc;
+
+ buildInputs = [ openssl zlib pcre libxml2 libxslt
+ ] ++ stdenv.lib.optional fullWebDAV expat;
+
+ patches = if syslog then [ "${syslog-ext}/syslog_1.4.0.patch" ] else [];
+
+ configureFlags = [
+ "--with-http_ssl_module"
+ "--with-http_spdy_module"
+ "--with-http_xslt_module"
+ "--with-http_sub_module"
+ "--with-http_dav_module"
+ "--with-http_gzip_static_module"
+ "--with-http_secure_link_module"
+ "--with-ipv6"
+ # Install destination problems
+ # "--with-http_perl_module"
+ ] ++ stdenv.lib.optional rtmp "--add-module=${rtmp-ext}"
+ ++ stdenv.lib.optional fullWebDAV "--add-module=${dav-ext}"
+ ++ stdenv.lib.optional syslog "--add-module=${syslog-ext}"
+ ++ stdenv.lib.optional moreheaders "--add-module=${moreheaders-ext}";
+
+ preConfigure = ''
+ export NIX_CFLAGS_COMPILE="$NIX_CFLAGS_COMPILE -I${libxml2 }/include/libxml2"
+ '';
+
+ # escape example
+ postInstall = ''
+ mv $out/sbin $out/bin ''' ''${
+ ${ if true then ${ "" } else false }
+ '';
+
+ meta = {
+ description = "A reverse proxy and lightweight webserver";
+ maintainers = [ stdenv.lib.maintainers.raskin];
+ platforms = stdenv.lib.platforms.all;
+ inherit version;
+ };
+}
diff --git a/tests/examplefiles/example.pp b/tests/examplefiles/example.pp
new file mode 100644
index 00000000..ea697be2
--- /dev/null
+++ b/tests/examplefiles/example.pp
@@ -0,0 +1,8 @@
+exec { 'grep':
+ command => 'grep "\'" -rI *',
+ path => '/bin:/usr/bin',
+}
+
+node default {
+ notify {"Hello World":;}
+}
diff --git a/tests/examplefiles/example.red b/tests/examplefiles/example.red
new file mode 100644
index 00000000..37c17ef8
--- /dev/null
+++ b/tests/examplefiles/example.red
@@ -0,0 +1,257 @@
+Red [
+ Title: "Red console"
+ Author: ["Nenad Rakocevic" "Kaj de Vos"]
+ File: %console.red
+ Tabs: 4
+ Rights: "Copyright (C) 2012-2013 Nenad Rakocevic. All rights reserved."
+ License: {
+ Distributed under the Boost Software License, Version 1.0.
+ See https://github.com/dockimbel/Red/blob/master/BSL-License.txt
+ }
+ Purpose: "Just some code for testing Pygments colorizer"
+ Language: http://www.red-lang.org/
+]
+
+#system-global [
+ #either OS = 'Windows [
+ #import [
+ "kernel32.dll" stdcall [
+ AttachConsole: "AttachConsole" [
+ processID [integer!]
+ return: [integer!]
+ ]
+ SetConsoleTitle: "SetConsoleTitleA" [
+ title [c-string!]
+ return: [integer!]
+ ]
+ ReadConsole: "ReadConsoleA" [
+ consoleInput [integer!]
+ buffer [byte-ptr!]
+ charsToRead [integer!]
+ numberOfChars [int-ptr!]
+ inputControl [int-ptr!]
+ return: [integer!]
+ ]
+ ]
+ ]
+ line-buffer-size: 16 * 1024
+ line-buffer: allocate line-buffer-size
+ ][
+ #switch OS [
+ MacOSX [
+ #define ReadLine-library "libreadline.dylib"
+ ]
+ #default [
+ #define ReadLine-library "libreadline.so.6"
+ #define History-library "libhistory.so.6"
+ ]
+ ]
+ #import [
+ ReadLine-library cdecl [
+ read-line: "readline" [ ; Read a line from the console.
+ prompt [c-string!]
+ return: [c-string!]
+ ]
+ rl-bind-key: "rl_bind_key" [
+ key [integer!]
+ command [integer!]
+ return: [integer!]
+ ]
+ rl-insert: "rl_insert" [
+ count [integer!]
+ key [integer!]
+ return: [integer!]
+ ]
+ ]
+ #if OS <> 'MacOSX [
+ History-library cdecl [
+ add-history: "add_history" [ ; Add line to the history.
+ line [c-string!]
+ ]
+ ]
+ ]
+ ]
+
+ rl-insert-wrapper: func [
+ [cdecl]
+ count [integer!]
+ key [integer!]
+ return: [integer!]
+ ][
+ rl-insert count key
+ ]
+
+ ]
+]
+
+Windows?: system/platform = 'Windows
+
+read-argument: routine [
+ /local
+ args [str-array!]
+ str [red-string!]
+][
+ if system/args-count <> 2 [
+ SET_RETURN(none-value)
+ exit
+ ]
+ args: system/args-list + 1 ;-- skip binary filename
+ str: simple-io/read-txt args/item
+ SET_RETURN(str)
+]
+
+init-console: routine [
+ str [string!]
+ /local
+ ret
+][
+ #either OS = 'Windows [
+ ;ret: AttachConsole -1
+ ;if zero? ret [print-line "ReadConsole failed!" halt]
+
+ ret: SetConsoleTitle as c-string! string/rs-head str
+ if zero? ret [print-line "SetConsoleTitle failed!" halt]
+ ][
+ rl-bind-key as-integer tab as-integer :rl-insert-wrapper
+ ]
+]
+
+input: routine [
+ prompt [string!]
+ /local
+ len ret str buffer line
+][
+ #either OS = 'Windows [
+ len: 0
+ print as c-string! string/rs-head prompt
+ ret: ReadConsole stdin line-buffer line-buffer-size :len null
+ if zero? ret [print-line "ReadConsole failed!" halt]
+ len: len + 1
+ line-buffer/len: null-byte
+ str: string/load as c-string! line-buffer len
+ ][
+ line: read-line as c-string! string/rs-head prompt
+ if line = null [halt] ; EOF
+
+ #if OS <> 'MacOSX [add-history line]
+
+ str: string/load line 1 + length? line
+; free as byte-ptr! line
+ ]
+ SET_RETURN(str)
+]
+
+count-delimiters: function [
+ buffer [string!]
+ return: [block!]
+][
+ list: copy [0 0]
+ c: none
+
+ foreach c buffer [
+ case [
+ escaped? [
+ escaped?: no
+ ]
+ in-comment? [
+ switch c [
+ #"^/" [in-comment?: no]
+ ]
+ ]
+ 'else [
+ switch c [
+ #"^^" [escaped?: yes]
+ #";" [if zero? list/2 [in-comment?: yes]]
+ #"[" [list/1: list/1 + 1]
+ #"]" [list/1: list/1 - 1]
+ #"{" [list/2: list/2 + 1]
+ #"}" [list/2: list/2 - 1]
+ ]
+ ]
+ ]
+ ]
+ list
+]
+
+do-console: function [][
+ buffer: make string! 10000
+ prompt: red-prompt: "red>> "
+ mode: 'mono
+
+ switch-mode: [
+ mode: case [
+ cnt/1 > 0 ['block]
+ cnt/2 > 0 ['string]
+ 'else [
+ prompt: red-prompt
+ do eval
+ 'mono
+ ]
+ ]
+ prompt: switch mode [
+ block ["[^-"]
+ string ["{^-"]
+ mono [red-prompt]
+ ]
+ ]
+
+ eval: [
+ code: load/all buffer
+
+ unless tail? code [
+ set/any 'result do code
+
+ unless unset? :result [
+ if 67 = length? result: mold/part :result 67 [ ;-- optimized for width = 72
+ clear back tail result
+ append result "..."
+ ]
+ print ["==" result]
+ ]
+ ]
+ clear buffer
+ ]
+
+ while [true][
+ unless tail? line: input prompt [
+ append buffer line
+ cnt: count-delimiters buffer
+
+ either Windows? [
+ remove skip tail buffer -2 ;-- clear extra CR (Windows)
+ ][
+ append buffer lf ;-- Unix
+ ]
+
+ switch mode [
+ block [if cnt/1 <= 0 [do switch-mode]]
+ string [if cnt/2 <= 0 [do switch-mode]]
+ mono [do either any [cnt/1 > 0 cnt/2 > 0][switch-mode][eval]]
+ ]
+ ]
+ ]
+]
+
+q: :quit
+
+if script: read-argument [
+ script: load script
+ either any [
+ script/1 <> 'Red
+ not block? script/2
+ ][
+ print "*** Error: not a Red program!"
+ ][
+ do skip script 2
+ ]
+ quit
+]
+
+init-console "Red Console"
+
+print {
+-=== Red Console alpha version ===-
+(only ASCII input supported)
+}
+
+do-console \ No newline at end of file
diff --git a/tests/examplefiles/example.reds b/tests/examplefiles/example.reds
new file mode 100644
index 00000000..eb92310d
--- /dev/null
+++ b/tests/examplefiles/example.reds
@@ -0,0 +1,150 @@
+Red/System [
+ Title: "Red/System example file"
+ Purpose: "Just some code for testing Pygments colorizer"
+ Language: http://www.red-lang.org/
+]
+
+#include %../common/FPU-configuration.reds
+
+; C types
+
+#define time! long!
+#define clock! long!
+
+date!: alias struct! [
+ second [integer!] ; 0-61 (60?)
+ minute [integer!] ; 0-59
+ hour [integer!] ; 0-23
+
+ day [integer!] ; 1-31
+ month [integer!] ; 0-11
+ year [integer!] ; Since 1900
+
+ weekday [integer!] ; 0-6 since Sunday
+ yearday [integer!] ; 0-365
+ daylight-saving-time? [integer!] ; Negative: unknown
+]
+
+#either OS = 'Windows [
+ #define clocks-per-second 1000
+][
+ ; CLOCKS_PER_SEC value for Syllable, Linux (XSI-conformant systems)
+ ; TODO: check for other systems
+ #define clocks-per-second 1000'000
+]
+
+#import [LIBC-file cdecl [
+
+ ; Error handling
+
+ form-error: "strerror" [ ; Return error description.
+ code [integer!]
+ return: [c-string!]
+ ]
+ print-error: "perror" [ ; Print error to standard error output.
+ string [c-string!]
+ ]
+
+
+ ; Memory management
+
+ make: "calloc" [ ; Allocate zero-filled memory.
+ chunks [size!]
+ size [size!]
+ return: [binary!]
+ ]
+ resize: "realloc" [ ; Resize memory allocation.
+ memory [binary!]
+ size [size!]
+ return: [binary!]
+ ]
+ ]
+
+ JVM!: alias struct! [
+ reserved0 [int-ptr!]
+ reserved1 [int-ptr!]
+ reserved2 [int-ptr!]
+
+ DestroyJavaVM [function! [[JNICALL] vm [JVM-ptr!] return: [jint!]]]
+ AttachCurrentThread [function! [[JNICALL] vm [JVM-ptr!] penv [struct! [p [int-ptr!]]] args [byte-ptr!] return: [jint!]]]
+ DetachCurrentThread [function! [[JNICALL] vm [JVM-ptr!] return: [jint!]]]
+ GetEnv [function! [[JNICALL] vm [JVM-ptr!] penv [struct! [p [int-ptr!]]] version [integer!] return: [jint!]]]
+ AttachCurrentThreadAsDaemon [function! [[JNICALL] vm [JVM-ptr!] penv [struct! [p [int-ptr!]]] args [byte-ptr!] return: [jint!]]]
+]
+
+ ;just some datatypes for testing:
+
+ #some-hash
+ 10-1-2013
+ quit
+
+ ;binary:
+ #{00FF0000}
+ #{00FF0000 FF000000}
+ #{00FF0000 FF000000} ;with tab instead of space
+ 2#{00001111}
+ 64#{/wAAAA==}
+ 64#{/wAAA A==} ;with space inside
+ 64#{/wAAA A==} ;with tab inside
+
+
+ ;string with char
+ {bla ^(ff) foo}
+ {bla ^(( foo}
+ ;some numbers:
+ 12
+ 1'000
+ 1.2
+ FF00FF00h
+
+ ;some tests of hexa number notation with not common ending
+ [ff00h ff00h] ff00h{} FFh"foo" 00h(1 + 2) (AEh)
+
+;normal words:
+foo char
+
+;get-word
+:foo
+
+;lit-word:
+'foo 'foo
+
+;multiple comment tests...
+1 + 1
+comment "aa"
+2 + 2
+comment {aa}
+3 + 3
+comment {a^{}
+4 + 4
+comment {{}}
+5 + 5
+comment {
+ foo: 6
+}
+6 + 6
+comment [foo: 6]
+7 + 7
+comment [foo: "[" ]
+8 + 8
+comment [foo: {^{} ]
+9 + 9
+comment [foo: {boo} ]
+10 + 10
+comment 5-May-2014/11:17:34+2:00
+11 + 11
+
+
+to-integer foo
+foo/(a + 1)/b
+
+call/output reform ['which interpreter] path: copy ""
+
+ version-1.1: 00010001h
+
+ #if type = 'exe [
+ push system/stack/frame ;-- save previous frame pointer
+ system/stack/frame: system/stack/top ;-- @@ reposition frame pointer just after the catch flag
+]
+push CATCH_ALL ;-- exceptions root barrier
+push 0 ;-- keep stack aligned on 64-bit \ No newline at end of file
diff --git a/tests/examplefiles/example.rexx b/tests/examplefiles/example.rexx
new file mode 100644
index 00000000..ec4da5ad
--- /dev/null
+++ b/tests/examplefiles/example.rexx
@@ -0,0 +1,50 @@
+/* REXX example. */
+
+/* Some basic constructs. */
+almost_pi = 0.1415 + 3
+if almost_pi < 3 then
+ say 'huh?'
+else do
+ say 'almost_pi=' almost_pi || " - ok"
+end
+x = '"' || "'" || '''' || """" /* quotes */
+
+/* A comment
+ * spawning multiple
+ lines. /* / */
+
+/* Built-in functions. */
+line = 'line containing some short text'
+say WordPos(line, 'some')
+say Word(line, 4)
+
+/* Labels and procedures. */
+some_label :
+
+divide: procedure
+ parse arg some other
+ return some / other
+
+call divide(5, 2)
+
+/* Loops */
+do i = 1 to 5
+ do j = -3 to -9 by -3
+ say i '+' j '=' i + j
+ end j
+end i
+
+do forever
+ leave
+end
+
+/* Print a text file on MVS. */
+ADDRESS TSO
+"ALLOC F(TEXTFILE) DSN('some.text.dsn') SHR REU"
+"EXECIO * DISKR TEXTFILE ( FINIS STEM LINES."
+"FREE F(TEXTFILE)"
+I = 1
+DO WHILE I <= LINES.0
+ SAY ' LINE ' I ' : ' LINES.I
+ I = I + 1
+END
diff --git a/tests/examplefiles/example.rkt b/tests/examplefiles/example.rkt
index a3e4a29e..acc0328e 100644
--- a/tests/examplefiles/example.rkt
+++ b/tests/examplefiles/example.rkt
@@ -1,5 +1,7 @@
#lang racket
+(require (only-in srfi/13 string-contains))
+
; Single-line comment style.
;; Single-line comment style.
@@ -8,45 +10,259 @@
#|
Multi-line comment style ...
+#|### #| nested |#||| |#
... on multiple lines
|#
-(define (a-function x #:keyword [y 0])
+#;(s-expression comment (one line))
+
+#;
+(s-expression comment
+ (multiple lines))
+
+#! shebang comment
+
+#!/shebang comment
+
+#! shebang \
+comment
+
+#!/shebang \
+comment
+
+;; Uncommented numbers after single-line comments
+;; NEL…133
+;; LS
8232
+;; PS
8233
+
+#reader racket
+(define(a-function x #:keyword [y 0])
(define foo0 'symbol) ; ()
[define foo1 'symbol] ; []
{define foo2 'symbol} ; {}
- (and (append (car '(1 2 3))))
+ (define 100-Continue 'symbol)
+ (and (append (car'(1 2 3))))
(regexp-match? #rx"foobar" "foobar")
- (regexp-match? #px"foobar" "foobar")
- (define a 1))
- (let ([b "foo"])
- (displayln b))
+ (regexp-match? #px"\"foo\\(bar\\)?\"" "foobar")
+ (regexp-match? #rx#"foobar" "foobar")
+ (regexp-match? #px#"foobar" "foobar")
+ (define #csa 1)
+ #Ci (let ([#%A|||b #true C
+\|d "foo"])
+ (displayln #cS #%\ab\ #true\ C\
+\\d||))
(for/list ([x (in-list (list 1 2 (list 3 4)))])
- (cond
- [(pair? x) (car x)]
- [else x])))
+ (cond
+ [(pair? x) (car x)]
+ [else x])))
-;; Literal number examples
+;; Literals
(values
;; #b
- #b1.1
- #b-1.1
- #b1e1
- #b0/1
- #b1/1
- #b1e-1
- #b101
-
+ #b1
+ #b+1
+ #b-1
+ #b.1
+ #b1.
+ #b0.1
+ #b+0.1
+ #b-0.1
+ #b1/10
+ #b+1/10
+ #b-1/10
+ #b1e11
+ #b+1e11
+ #b-1e11
+ #b.1e11
+ #b1.e11
+ #b0.1e11
+ #b+0.1e11
+ #b-0.1e11
+ #b1/10e11
+ #b+1/10e11
+ #b-1/10e11
+ #b+i
+ #b1+i
+ #b+1+i
+ #b-1+i
+ #b.1+i
+ #b1.+i
+ #b0.1+i
+ #b+0.1+i
+ #b-0.1+i
+ #b1/10+i
+ #b+1/10+i
+ #b-1/10+i
+ #b1e11+i
+ #b+1e11+i
+ #b-1e11+i
+ #b1.e11+i
+ #b.1e11+i
+ #b0.1e11+i
+ #b+0.1e11+i
+ #b-0.1e11+i
+ #b1/10e11+i
+ #b+1/10e11+i
+ #b-1/10e11+i
+ #b+1i
+ #b1+1i
+ #b+1+1i
+ #b-1+1i
+ #b1.+1i
+ #b.1+1i
+ #b0.1+1i
+ #b+0.1+1i
+ #b-0.1+1i
+ #b1/10+1i
+ #b+1/10+1i
+ #b-1/10+1i
+ #b1e11+1i
+ #b+1e11+1i
+ #b-1e11+1i
+ #b.1e11+1i
+ #b0.1e11+1i
+ #b+0.1e11+1i
+ #b-0.1e11+1i
+ #b1/10e11+1i
+ #b+1/10e11+1i
+ #b-1/10e11+1i
+ #b+1/10e11i
+ #b1+1/10e11i
+ #b+1+1/10e11i
+ #b-1+1/10e11i
+ #b.1+1/10e11i
+ #b0.1+1/10e11i
+ #b+0.1+1/10e11i
+ #b-0.1+1/10e11i
+ #b1/10+1/10e11i
+ #b+1/10+1/10e11i
+ #b-1/10+1/10e11i
+ #b1e11+1/10e11i
+ #b+1e11+1/10e11i
+ #b-1e11+1/10e11i
+ #b.1e11+1/10e11i
+ #b0.1e11+1/10e11i
+ #b+0.1e11+1/10e11i
+ #b-0.1e11+1/10e11i
+ #b1/10e11+1/10e11i
+ #b+1/10e11+1/10e11i
+ #b-1/10e11+1/10e11i
;; #d
- #d-1.23
- #d1.123
- #d1e3
- #d1e-22
- #d1/2
- #d-1/2
#d1
+ #d+1
#d-1
-
+ #d.1
+ #d1.
+ #d1.2
+ #d+1.2
+ #d-1.2
+ #d1/2
+ #d+1/2
+ #d-1/2
+ #d1e3
+ #d+1e3
+ #d-1e3
+ #d.1e3
+ #d1.e3
+ #d1.2e3
+ #d+1.2e3
+ #d-1.2e3
+ #d1/2e3
+ #d+1/2e3
+ #d-1/2e3
+ #d+i
+ #d1+i
+ #d+1+i
+ #d-1+i
+ #d.1+i
+ #d1.+i
+ #d1.2+i
+ #d+1.2+i
+ #d-1.2+i
+ #d1/2+i
+ #d+1/2+i
+ #d-1/2+i
+ #d1e3+i
+ #d+1e3+i
+ #d-1e3+i
+ #d1.e3+i
+ #d.1e3+i
+ #d1.2e3+i
+ #d+1.2e3+i
+ #d-1.2e3+i
+ #d1/2e3+i
+ #d+1/2e3+i
+ #d-1/2e3+i
+ #d+1i
+ #d1+1i
+ #d+1+1i
+ #d-1+1i
+ #d1.+1i
+ #d.1+1i
+ #d1.2+1i
+ #d+1.2+1i
+ #d-1.2+1i
+ #d1/2+1i
+ #d+1/2+1i
+ #d-1/2+1i
+ #d1e3+1i
+ #d+1e3+1i
+ #d-1e3+1i
+ #d.1e3+1i
+ #d1.2e3+1i
+ #d+1.2e3+1i
+ #d-1.2e3+1i
+ #d1/2e3+1i
+ #d+1/2e3+1i
+ #d-1/2e3+1i
+ #d+1/2e3i
+ #d1+1/2e3i
+ #d+1+1/2e3i
+ #d-1+1/2e3i
+ #d.1+1/2e3i
+ #d1.2+1/2e3i
+ #d+1.2+1/2e3i
+ #d-1.2+1/2e3i
+ #d1/2+1/2e3i
+ #d+1/2+1/2e3i
+ #d-1/2+1/2e3i
+ #d1e3+1/2e3i
+ #d+1e3+1/2e3i
+ #d-1e3+1/2e3i
+ #d.1e3+1/2e3i
+ #d1.2e3+1/2e3i
+ #d+1.2e3+1/2e3i
+ #d-1.2e3+1/2e3i
+ #d1/2e3+1/2e3i
+ #d+1/2e3+1/2e3i
+ #d-1/2e3+1/2e3i
+ ;; Extflonums
+ +nan.t
+ 1t3
+ +1t3
+ -1t3
+ .1t3
+ 1.t3
+ 1.2t3
+ +1.2t3
+ -1.2t3
+ 1/2t3
+ +1/2t3
+ -1/2t3
+ 1#t0
+ 1.#t0
+ .2#t0
+ 1.2#t0
+ 1#/2t0
+ 1/2#t0
+ 1#/2#t0
+ 1#t3
+ 1.#t3
+ .2#t3
+ 1.2#t3
+ 1#/2t3
+ 1/2#t3
+ 1#/2#t3
;; No # reader prefix -- same as #d
-1.23
1.123
@@ -56,7 +272,6 @@ Multi-line comment style ...
-1/2
1
-1
-
;; #e
#e-1.23
#e1.123
@@ -66,7 +281,24 @@ Multi-line comment style ...
#e-1
#e1/2
#e-1/2
-
+ ;; #d#e
+ #d#e-1.23
+ #d#e1.123
+ #d#e1e3
+ #d#e1e-22
+ #d#e1
+ #d#e-1
+ #d#e1/2
+ #d#e-1/2
+ ;; #e#d
+ #e#d-1.23
+ #e#d1.123
+ #e#d1e3
+ #e#d1e-22
+ #e#d1
+ #e#d-1
+ #e#d1/2
+ #e#d-1/2
;; #i always float
#i-1.23
#i1.123
@@ -76,7 +308,126 @@ Multi-line comment style ...
#i-1/2
#i1
#i-1
-
+ ;; Implicitly inexact numbers
+ +nan.0
+ 1#
+ 1.#
+ .2#
+ 1.2#
+ 1#/2
+ 1/2#
+ 1#/2#
+ 1#e3
+ 1.#e3
+ .2#e3
+ 1.2#e3
+ 1#/2e3
+ 1/2#e3
+ 1#/2#e3
+ +nan.0+i
+ 1#+i
+ 1.#+i
+ .2#+i
+ 1.2#+i
+ 1#/2+i
+ 1/2#+i
+ 1#/2#+i
+ 1#e3+i
+ 1.#e3+i
+ .2#e3+i
+ 1.2#e3+i
+ 1#/2e3+i
+ 1/2#e3+i
+ 1#/2#e3+i
+ +nan.0i
+ +1#i
+ +1.#i
+ +.2#i
+ +1.2#i
+ +1#/2i
+ +1/2#i
+ +1#/2#i
+ +1#e3i
+ +1.#e3i
+ +.2#e3i
+ +1.2#e3i
+ +1#/2e3i
+ +1/2#e3i
+ +1#/2#e3i
+ 0+nan.0i
+ 0+1#i
+ 0+1.#i
+ 0+.2#i
+ 0+1.2#i
+ 0+1#/2i
+ 0+1/2#i
+ 0+1#/2#i
+ 0+1#e3i
+ 0+1.#e3i
+ 0+.2#e3i
+ 0+1.2#e3i
+ 0+1#/2e3i
+ 0+1/2#e3i
+ 0+1#/2#e3i
+ 1#/2#e3+nan.0i
+ 1#/2#e3+1#i
+ 1#/2#e3+1.#i
+ 1#/2#e3+.2#i
+ 1#/2#e3+1.2#i
+ 1#/2#e3+1#/2i
+ 1#/2#e3+1/2#i
+ 1#/2#e3+1#/2#i
+ 1#/2#e3+1#e3i
+ 1#/2#e3+1.#e3i
+ 1#/2#e3+.2#e3i
+ 1#/2#e3+1.2#e3i
+ 1#/2#e3+1#/2e3i
+ 1#/2#e3+1/2#e3i
+ 1#/2#e3+1#/2#e3i
+ +nan.0@1
+ 1#@1
+ 1.#@1
+ .2#@1
+ 1.2#@1
+ 1#/2@1
+ 1/2#@1
+ 1#/2#@1
+ 1#e3@1
+ 1.#e3@1
+ .2#e3@1
+ 1.2#e3@1
+ 1#/2e3@1
+ 1/2#e3@1
+ 1#/2#e3@1
+ 1@+nan.0
+ 1@1#
+ 1@1.#
+ 1@.2#
+ 1@1.2#
+ 1@1#/2
+ 1@1/2#
+ 1@1#/2#
+ 1@1#e3
+ 1@1.#e3
+ 1@.2#e3
+ 1@1.2#e3
+ 1@1#/2e3
+ 1@1/2#e3
+ 1@1#/2#e3
+ 1#/2#e3@1#
+ 1#/2#e3@1.#
+ 1#/2#e3@.2#
+ 1#/2#e3@1.2#
+ 1#/2#e3@1#/2
+ 1#/2#e3@1/2#
+ 1#/2#e3@1#/2#
+ 1#/2#e3@1#e3
+ 1#/2#e3@1.#e3
+ 1#/2#e3@.2#e3
+ 1#/2#e3@1.2#e3
+ 1#/2#e3@1#/2e3
+ 1#/2#e3@1/2#e3
+ 1#/2#e3@1#/2#e3
;; #o
#o777.777
#o-777.777
@@ -86,10 +437,307 @@ Multi-line comment style ...
#o-3/7
#o777
#o-777
-
+ #e#o777.777
+ #e#o-777.777
+ #e#o777e777
+ #e#o777e-777
+ #e#o3/7
+ #e#o-3/7
+ #e#o777
+ #e#o-777
+ #i#o777.777
+ #i#o-777.777
+ #i#o777e777
+ #i#o777e-777
+ #i#o3/7
+ #i#o-3/7
+ #i#o777
+ #i#o-777
;; #x
#x-f.f
#xf.f
+ #xfsf
+ #xfs-f
+ #x7/f
+ #x-7/f
#x-f
#xf
+ #e#x-f.f
+ #e#xf.f
+ #e#xfsf
+ #e#xfs-f
+ #e#x7/f
+ #e#x-7/f
+ #e#x-f
+ #e#xf
+ #i#x-f.f
+ #i#xf.f
+ #i#xfsf
+ #i#xfs-f
+ #i#x7/f
+ #i#x-7/f
+ #i#x-f
+ #i#xf
+ ;; Not numbers
+ '-1.23x
+ '1.123x
+ '1e3x
+ '1e-22x
+ '1/2x
+ '-1/2x
+ '1x
+ '-1x
+ '/
+ '1/
+ '/2
+ '1//2
+ '1e3.
+ '1e
+ 'e3
+ '.i
+ '1.2.3
+ '1..2
+ '.1.
+ '@
+ '1@
+ '@2
+ '1@@2
+ '1@2@3
+ '1@2i
+ '1+-2i
+ '1i+2
+ '1i+2i
+ '1+2i+3i
+ '-
+ '--1
+ '+
+ '++1
+ '1/2.3
+ '1#2
+ '1#.2
+ '1.#2
+ '.#2
+ '+nan.t+nan.ti
+ '+nan.t@nan.t
+ ;; Booleans
+ #t
+ #T
+ #true
+ #f
+ #F
+ #false
+ ;; Characters, strings, and byte strings
+ #\
+ #\Null9
+ #\n9
+ #\99
+ #\0009
+ #\u3BB
+ #\u03BB9
+ #\U3BB
+ #\U000003BB9
+ #\λ9
+ "string\
+ \a.\b.\t.\n.\v.\f.\r.\e.\".\'.\\.\1.\123.\1234.\x9.\x30.\x303"
+ "\u9.\u1234.\u12345.\U9.\U00100000.\U001000000"
+ #"byte-string\7\xff\t"
+ #<<HERE STRING
+lorem ipsum
+dolor sit amet
+consectetur HERE STRING
+HERE STRING adipisicing elit
+HERE STRING
+ #|
+HERE STRING
+|#
+ ;; Other literals
+ #(vector)
+ #20()
+ #s[prefab-structure 1 2 3]
+ #&{box}
+ #hash(("a" . 5))
+ #hasheq((a . 5) (b . 7))
+ #hasheqv((a . 5) (b . 7))
+ #'(define x 1)
+ #`(define x #,pi)
+ ;; quote, quasiquote, and unquote
+ 'pi
+ ' pi
+ ''pi
+ '`pi
+ '`,pi
+ ',pi
+ `pi
+ ` pi
+ `'pi
+ ``pi
+ `,pi
+ ` , pi
+ `,'pi
+ `,`pi
+ `,`,pi
+ '(+)
+ ' (+)
+ ''(+)
+ '`(+)
+ ',(+)
+ `(+)
+ ` (+)
+ `'(+)
+ ``(+)
+ `,(+)
+ ` , (+)
+ `,'(+)
+ `,`(+)
+ `,`,(+)
+ #readerracket/base'pi.f
+ '#readerracket/base pi.f
+ #readerracket/base`pi.f
+ `#readerracket/base pi.f
+ #readerracket/base`,pi.f
+ `#readerracket/base,pi.f
+ `,#readerracket/base pi.f
+ #readerracket/base'`,pi.f
+ '#readerracket/base`,pi.f
+ '`#readerracket/base,pi.f
+ '`,#readerracket/base pi.f
+ #readerracket/base'(*)
+ '#readerracket/base(*)
+ #readerracket/base`(*)
+ `#readerracket/base(*)
+ #readerracket/base`,(*)
+ `#readerracket/base,(*)
+ `,#readerracket/base(*)
+ #readerracket/base'`,(*)
+ '#readerracket/base`,(*)
+ '`#readerracket/base,(*)
+ '`,#readerracket/base(*)
+ (quote pi)
+ (quote (quote pi))
+ (quote (quasiquote pi))
+ (quote (quasiquote (unquote pi)))
+ (quote (unquote pi))
+ (quasiquote pi)
+ (quasiquote (quote pi))
+ (quasiquote (quasiquote pi))
+ (quasiquote (unquote pi))
+ (quasiquote (unquote (quote pi)))
+ (quasiquote (unquote (quasiquote pi)))
+ (quasiquote (unquote (quasiquote (unquote pi))))
+ (quote (+))
+ (quote (quote (+)))
+ (quote (quasiquote (+)))
+ (quote (unquote (+)))
+ (quasiquote (+))
+ (quasiquote (quote (+)))
+ (quasiquote (quasiquote (+)))
+ (quasiquote (unquote (+)))
+ (quasiquote (unquote (quote (+))))
+ (quasiquote (unquote (quasiquote (+))))
+ (quasiquote (unquote (quasiquote (unquote (+)))))
+ #reader racket/base (quote pi.f)
+ (quote #reader racket/base pi.f)
+ #reader racket/base (quasiquote pi.f)
+ (quasiquote #reader racket/base pi.f)
+ #reader racket/base (quasiquote (unquote pi.f))
+ (quasiquote #reader racket/base (unquote pi.f))
+ (quasiquote (unquote #reader racket/base pi.f))
+ #reader racket/base (quote (quasiquote (unquote pi.f)))
+ (quote #reader racket/base (quasiquote (unquote pi.f)))
+ (quote (quasiquote #reader racket/base (unquote pi.f)))
+ (quote (quasiquote (unquote #reader racket/base pi.f)))
+ #reader racket/base (quote (*))
+ (quote #reader racket/base (*))
+ #reader racket/base (quasiquote (*))
+ (quasiquote #reader racket/base (*))
+ #reader racket/base (quasiquote (unquote (*)))
+ (quasiquote #reader racket/base (unquote (*)))
+ (quasiquote (unquote #reader racket/base (*)))
+ #reader racket/base (quote (quasiquote (unquote (*))))
+ (quote #reader racket/base (quasiquote (unquote (*))))
+ (quote (quasiquote #reader racket/base (unquote (*))))
+ (quote (quasiquote (unquote #reader racket/base (*))))
+ ;; Make sure non-identifiers work with quotes
+ ' "" pi
+ ' #t pi
+ ' #() pi
+ ' #s(s) pi
+ ' #\u3BB pi
+ ' #\U000003BB pi
+ ' #\space pi
+ ' #\. pi
+ ' #"" pi
+ ' #:kw pi
+ ' #&b pi
+ ' #'(define x 1) pi
+ ' #`(define x #,pi) pi
+ ' #I0 pi
+ ' #E0 pi
+ ' #X0 pi
+ ' #O0 pi
+ ' #D0 pi
+ ' #B0 pi
+ ' #<<EOF
+EOF
+ pi
+ ' #rx"" pi
+ ' #rx#"" pi
+ ' #px"" pi
+ ' #px#"" pi
+ ' #hash() pi
+ ' #hasheq[] pi
+ ' #hasheqv{} pi
+ ' #1(v) pi
)
+
+;; Use the following to generate lists of built-ins and keywords.
+;; Run
+;; (displayln (wrap-lines KEYWORDS))
+;; (displayln (wrap-lines BUILTINS))
+;; and copy the results into RacketLexer._keywords and RacketLexer._builtins.
+
+;; (-> (listof string?) string?)
+;; Appends all the strings together, quoting them as appropriate for Python,
+;; with commas and spaces between them, wrapping at 80 characters, with an
+;; indentation of 8 spaces.
+(define (wrap-lines lst)
+ (define INDENTATION '" ")
+ (define WIDTH '80)
+ (define (wrap-lines* lst done-lines current-line)
+ (if (null? lst)
+ (string-append (foldr string-append "" done-lines) current-line)
+ (let* ([str (first lst)]
+ [wrapped-str (if (regexp-match-exact? '#px"[[:ascii:]]+" str)
+ (string-append "'" str "',")
+ (string-append "u'" str "',"))]
+ [new-line (string-append current-line " " wrapped-str)])
+ (if ((string-length new-line) . >= . WIDTH)
+ (wrap-lines* (rest lst)
+ (append done-lines
+ `(,(string-append current-line "\n")))
+ (string-append INDENTATION wrapped-str))
+ (wrap-lines* (rest lst)
+ done-lines
+ new-line)))))
+ (wrap-lines* lst '() INDENTATION))
+
+;; (-> string? boolean?)
+;; Returns #t if str represents a syntax identifier in the current namespace,
+;; otherwise #f.
+(define (syntax-identifier? str)
+ (with-handlers ([exn? exn?])
+ (not (eval (call-with-input-string str read)))))
+
+(define RACKET-NAMESPACE
+ (parameterize ([current-namespace (make-base-namespace)])
+ (namespace-require 'racket)
+ (current-namespace)))
+
+(define BOUND-IDENTIFIERS
+ (parameterize ([current-namespace RACKET-NAMESPACE])
+ (sort (map symbol->string (namespace-mapped-symbols))
+ string<=?)))
+
+(define-values (KEYWORDS BUILTINS)
+ (parameterize ([current-namespace RACKET-NAMESPACE])
+ (partition syntax-identifier? BOUND-IDENTIFIERS)))
diff --git a/tests/examplefiles/example.sh b/tests/examplefiles/example.sh
new file mode 100644
index 00000000..2112cdd1
--- /dev/null
+++ b/tests/examplefiles/example.sh
@@ -0,0 +1,22 @@
+#!/bin/bash
+
+printf "%d %s\n" 10 "foo"
+printf "%d %s\n" $((10#1)) "bar"
+
+let "m = 10#${1:1:2}"
+echo $m
+
+m=$((10#${1:4:3} + 10#${1:1:3}))
+echo $m
+
+m=$((10#${1:4:3}))
+echo $m
+
+m=$((10#$1))
+echo $m
+
+m=$((10#1))
+echo $m
+
+m=$((10))
+echo $m
diff --git a/tests/examplefiles/example.slim b/tests/examplefiles/example.slim
new file mode 100644
index 00000000..0e209200
--- /dev/null
+++ b/tests/examplefiles/example.slim
@@ -0,0 +1,31 @@
+doctype html
+html
+ head
+ title Slim Examples
+ meta name="keywords" content="template language"
+ meta name="author" content=author
+ javascript:
+ alert('Slim supports embedded javascript!')
+
+ body
+ h1 Markup examples
+
+ #content
+ p This example shows you how a basic Slim file looks like.
+
+ == yield
+
+ - unless items.empty?
+ table
+ - for item in items do
+ tr
+ td.name = item.name
+ td.price = item.price
+ - else
+ p
+ | No items found. Please add some inventory.
+ Thank you!
+
+ div id="footer"
+ = render 'footer'
+ | Copyright (C) #{year} #{author}
diff --git a/tests/examplefiles/example.sls b/tests/examplefiles/example.sls
new file mode 100644
index 00000000..824700e7
--- /dev/null
+++ b/tests/examplefiles/example.sls
@@ -0,0 +1,51 @@
+include:
+ - moosefs
+
+{% for mnt in salt['cmd.run']('ls /dev/data/moose*').split() %}
+/mnt/moose{{ mnt[-1] }}:
+ mount.mounted:
+ - device: {{ mnt }}
+ - fstype: xfs
+ - mkmnt: True
+ file.directory:
+ - user: mfs
+ - group: mfs
+ - require:
+ - user: mfs
+ - group: mfs
+{% endfor %}
+
+/etc/mfshdd.cfg:
+ file.managed:
+ - source: salt://moosefs/mfshdd.cfg
+ - user: root
+ - group: root
+ - mode: 644
+ - template: jinja
+ - require:
+ - pkg: mfs-chunkserver
+
+/etc/mfschunkserver.cfg:
+ file.managed:
+ - source: salt://moosefs/mfschunkserver.cfg
+ - user: root
+ - group: root
+ - mode: 644
+ - template: jinja
+ - require:
+ - pkg: mfs-chunkserver
+
+mfs-chunkserver:
+ pkg:
+ - installed
+mfschunkserver:
+ service:
+ - running
+ - require:
+{% for mnt in salt['cmd.run']('ls /dev/data/moose*') %}
+ - mount: /mnt/moose{{ mnt[-1] }}
+ - file: /mnt/moose{{ mnt[-1] }}
+{% endfor %}
+ - file: /etc/mfschunkserver.cfg
+ - file: /etc/mfshdd.cfg
+ - file: /var/lib/mfs
diff --git a/tests/examplefiles/example.stan b/tests/examplefiles/example.stan
index 5723403c..716b4d12 100644
--- a/tests/examplefiles/example.stan
+++ b/tests/examplefiles/example.stan
@@ -5,93 +5,115 @@ It is not a real model and will not compile
*/
# also a comment
// also a comment
+functions {
+ void f1(void a, real b) {
+ return 1 / a;
+ }
+ real f2(int a, vector b, real c) {
+ return a + b + c;
+ }
+}
data {
- // valid name
- int abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_abc;
- // all types should be highlighed
- int a3;
- real foo[2];
- vector[3] bar;
- row_vector[3] baz;
- matrix[3,3] qux;
- simplex[3] quux;
- ordered[3] corge;
- positive_ordered[3] wibble;
- corr_matrix[3] grault;
- cov_matrix[3] garply;
-
- real<lower=-1,upper=1> foo1;
- real<lower=0> foo2;
- real<upper=0> foo3;
-
- // bad names
- // includes .
- // real foo.;
- // beings with number
- //real 0foo;
- // begins with _
- //real _foo;
+ // valid name
+ int abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_abc;
+ // all types should be highlighed
+ int a3;
+ real foo[2];
+ vector[3] bar;
+ row_vector[3] baz;
+ matrix[3,3] qux;
+ simplex[3] quux;
+ ordered[3] corge;
+ positive_ordered[3] wibble;
+ corr_matrix[3] grault;
+ cov_matrix[3] garply;
+ cholesky_factor_cov[3] waldo;
+ cholesky_factor_corr[3] waldo2;
+
+ real<lower=-1,upper=1> foo1;
+ real<lower=0> foo2;
+ real<upper=0> foo3;
}
transformed data {
- real xyzzy;
- int thud;
- row_vector grault2;
- matrix qux2;
-
- // all floating point literals should be recognized
- // all operators should be recognized
- // paren should be recognized;
- xyzzy <- 1234.5687 + .123 - (2.7e3 / 2E-5 * 135e-5);
- // integer literal
- thud <- -12309865;
- // ./ and .* should be recognized as operators
- grault2 <- grault .* garply ./ garply;
- // ' and \ should be regognized as operators
- qux2 <- qux' \ bar;
-
+ real xyzzy;
+ int thud;
+ row_vector grault2;
+ matrix qux2;
+
+ // all floating point literals should be recognized
+ // all operators should be recognized
+ // paren should be recognized;
+ xyzzy <- 1234.5687 + .123 - (2.7e3 / 2E-5 * 135e-5);
+ // integer literal
+ thud <- -12309865;
+ // ./ and .* should be recognized as operators
+ grault2 <- grault .* garply ./ garply;
+ // ' and \ should be regognized as operators
+ qux2 <- qux' \ bar;
+
}
parameters {
- real fred;
- real plugh;
-
+ real fred;
+ real plugh;
}
transformed parameters {
}
model {
- // ~, <- are operators,
- // T may be be recognized
- // normal is a function
- fred ~ normal(0, 1) T(-0.5, 0.5);
- // interior block
- {
- real tmp;
- // for, in should be highlighted
- for (i in 1:10) {
- tmp <- tmp + 0.1;
- }
- }
- // lp__ should be highlighted
- // normal_log as a function
- lp__ <- lp__ + normal_log(plugh, 0, 1);
+ // ~, <- are operators,
+ // T may be be recognized
+ // normal is a function
+ fred ~ normal(0, 1) T(-0.5, 0.5);
+ real tmp;
+ // C++ reserved
+ real public;
+
+ // control structures
+ for (i in 1:10) {
+ tmp <- tmp + 0.1;
+ }
+ tmp <- 0.0;
+ while (tmp < 5.0) {
+ tmp <- tmp + 1;
+ }
+ if (tmp > 0.0) {
+ print(tmp);
+ } else {
+ print(tmp);
+ }
- // print statement and string literal
- print("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_~@#$%^&*`'-+={}[].,;: ");
- print("Hello, world!");
- print("");
+ // operators
+ tmp || tmp;
+ tmp && tmp;
+ tmp == tmp;
+ tmp != tmp;
+ tmp < tmp;
+ tmp <= tmp;
+ tmp > tmp;
+ tmp >= tmp;
+ tmp + tmp;
+ tmp - tmp;
+ tmp * tmp;
+ tmp / tmp;
+ tmp .* tmp;
+ tmp ./ tmp;
+ tmp ^ tmp;
+ ! tmp;
+ - tmp;
+ + tmp;
+ tmp ';
+ // lp__ should be highlighted
+ // normal_log as a function
+ lp__ <- lp__ + normal_log(plugh, 0, 1);
+ increment_log_prob(normal_log(plugh, 0, 1));
+
+ // print statement and string literal
+ print("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_~@#$%^&*`'-+={}[].,;: ");
+ print("Hello, world!");
+ print("");
+
}
generated quantities {
- real bar1;
- bar1 <- foo + 1;
+ real bar1;
+ bar1 <- foo + 1;
}
-
-## Baddness
-//foo <- 2.0;
-//foo ~ normal(0, 1);
-//not_a_block {
-//}
-
-/*
-what happens with this?
-*/
-// */
diff --git a/tests/examplefiles/example.thy b/tests/examplefiles/example.thy
new file mode 100644
index 00000000..abaa1af8
--- /dev/null
+++ b/tests/examplefiles/example.thy
@@ -0,0 +1,751 @@
+(* from Isabelle2013-2 src/HOL/Power.thy; BSD license *)
+
+(* Title: HOL/Power.thy
+ Author: Lawrence C Paulson, Cambridge University Computer Laboratory
+ Copyright 1997 University of Cambridge
+*)
+
+header {* Exponentiation *}
+
+theory Power
+imports Num
+begin
+
+subsection {* Powers for Arbitrary Monoids *}
+
+class power = one + times
+begin
+
+primrec power :: "'a \<Rightarrow> nat \<Rightarrow> 'a" (infixr "^" 80) where
+ power_0: "a ^ 0 = 1"
+ | power_Suc: "a ^ Suc n = a * a ^ n"
+
+notation (latex output)
+ power ("(_\<^bsup>_\<^esup>)" [1000] 1000)
+
+notation (HTML output)
+ power ("(_\<^bsup>_\<^esup>)" [1000] 1000)
+
+text {* Special syntax for squares. *}
+
+abbreviation (xsymbols)
+ power2 :: "'a \<Rightarrow> 'a" ("(_\<^sup>2)" [1000] 999) where
+ "x\<^sup>2 \<equiv> x ^ 2"
+
+notation (latex output)
+ power2 ("(_\<^sup>2)" [1000] 999)
+
+notation (HTML output)
+ power2 ("(_\<^sup>2)" [1000] 999)
+
+end
+
+context monoid_mult
+begin
+
+subclass power .
+
+lemma power_one [simp]:
+ "1 ^ n = 1"
+ by (induct n) simp_all
+
+lemma power_one_right [simp]:
+ "a ^ 1 = a"
+ by simp
+
+lemma power_commutes:
+ "a ^ n * a = a * a ^ n"
+ by (induct n) (simp_all add: mult_assoc)
+
+lemma power_Suc2:
+ "a ^ Suc n = a ^ n * a"
+ by (simp add: power_commutes)
+
+lemma power_add:
+ "a ^ (m + n) = a ^ m * a ^ n"
+ by (induct m) (simp_all add: algebra_simps)
+
+lemma power_mult:
+ "a ^ (m * n) = (a ^ m) ^ n"
+ by (induct n) (simp_all add: power_add)
+
+lemma power2_eq_square: "a\<^sup>2 = a * a"
+ by (simp add: numeral_2_eq_2)
+
+lemma power3_eq_cube: "a ^ 3 = a * a * a"
+ by (simp add: numeral_3_eq_3 mult_assoc)
+
+lemma power_even_eq:
+ "a ^ (2 * n) = (a ^ n)\<^sup>2"
+ by (subst mult_commute) (simp add: power_mult)
+
+lemma power_odd_eq:
+ "a ^ Suc (2*n) = a * (a ^ n)\<^sup>2"
+ by (simp add: power_even_eq)
+
+lemma power_numeral_even:
+ "z ^ numeral (Num.Bit0 w) = (let w = z ^ (numeral w) in w * w)"
+ unfolding numeral_Bit0 power_add Let_def ..
+
+lemma power_numeral_odd:
+ "z ^ numeral (Num.Bit1 w) = (let w = z ^ (numeral w) in z * w * w)"
+ unfolding numeral_Bit1 One_nat_def add_Suc_right add_0_right
+ unfolding power_Suc power_add Let_def mult_assoc ..
+
+lemma funpow_times_power:
+ "(times x ^^ f x) = times (x ^ f x)"
+proof (induct "f x" arbitrary: f)
+ case 0 then show ?case by (simp add: fun_eq_iff)
+next
+ case (Suc n)
+ def g \<equiv> "\<lambda>x. f x - 1"
+ with Suc have "n = g x" by simp
+ with Suc have "times x ^^ g x = times (x ^ g x)" by simp
+ moreover from Suc g_def have "f x = g x + 1" by simp
+ ultimately show ?case by (simp add: power_add funpow_add fun_eq_iff mult_assoc)
+qed
+
+end
+
+context comm_monoid_mult
+begin
+
+lemma power_mult_distrib:
+ "(a * b) ^ n = (a ^ n) * (b ^ n)"
+ by (induct n) (simp_all add: mult_ac)
+
+end
+
+context semiring_numeral
+begin
+
+lemma numeral_sqr: "numeral (Num.sqr k) = numeral k * numeral k"
+ by (simp only: sqr_conv_mult numeral_mult)
+
+lemma numeral_pow: "numeral (Num.pow k l) = numeral k ^ numeral l"
+ by (induct l, simp_all only: numeral_class.numeral.simps pow.simps
+ numeral_sqr numeral_mult power_add power_one_right)
+
+lemma power_numeral [simp]: "numeral k ^ numeral l = numeral (Num.pow k l)"
+ by (rule numeral_pow [symmetric])
+
+end
+
+context semiring_1
+begin
+
+lemma of_nat_power:
+ "of_nat (m ^ n) = of_nat m ^ n"
+ by (induct n) (simp_all add: of_nat_mult)
+
+lemma power_zero_numeral [simp]: "(0::'a) ^ numeral k = 0"
+ by (simp add: numeral_eq_Suc)
+
+lemma zero_power2: "0\<^sup>2 = 0" (* delete? *)
+ by (rule power_zero_numeral)
+
+lemma one_power2: "1\<^sup>2 = 1" (* delete? *)
+ by (rule power_one)
+
+end
+
+context comm_semiring_1
+begin
+
+text {* The divides relation *}
+
+lemma le_imp_power_dvd:
+ assumes "m \<le> n" shows "a ^ m dvd a ^ n"
+proof
+ have "a ^ n = a ^ (m + (n - m))"
+ using `m \<le> n` by simp
+ also have "\<dots> = a ^ m * a ^ (n - m)"
+ by (rule power_add)
+ finally show "a ^ n = a ^ m * a ^ (n - m)" .
+qed
+
+lemma power_le_dvd:
+ "a ^ n dvd b \<Longrightarrow> m \<le> n \<Longrightarrow> a ^ m dvd b"
+ by (rule dvd_trans [OF le_imp_power_dvd])
+
+lemma dvd_power_same:
+ "x dvd y \<Longrightarrow> x ^ n dvd y ^ n"
+ by (induct n) (auto simp add: mult_dvd_mono)
+
+lemma dvd_power_le:
+ "x dvd y \<Longrightarrow> m \<ge> n \<Longrightarrow> x ^ n dvd y ^ m"
+ by (rule power_le_dvd [OF dvd_power_same])
+
+lemma dvd_power [simp]:
+ assumes "n > (0::nat) \<or> x = 1"
+ shows "x dvd (x ^ n)"
+using assms proof
+ assume "0 < n"
+ then have "x ^ n = x ^ Suc (n - 1)" by simp
+ then show "x dvd (x ^ n)" by simp
+next
+ assume "x = 1"
+ then show "x dvd (x ^ n)" by simp
+qed
+
+end
+
+context ring_1
+begin
+
+lemma power_minus:
+ "(- a) ^ n = (- 1) ^ n * a ^ n"
+proof (induct n)
+ case 0 show ?case by simp
+next
+ case (Suc n) then show ?case
+ by (simp del: power_Suc add: power_Suc2 mult_assoc)
+qed
+
+lemma power_minus_Bit0:
+ "(- x) ^ numeral (Num.Bit0 k) = x ^ numeral (Num.Bit0 k)"
+ by (induct k, simp_all only: numeral_class.numeral.simps power_add
+ power_one_right mult_minus_left mult_minus_right minus_minus)
+
+lemma power_minus_Bit1:
+ "(- x) ^ numeral (Num.Bit1 k) = - (x ^ numeral (Num.Bit1 k))"
+ by (simp only: eval_nat_numeral(3) power_Suc power_minus_Bit0 mult_minus_left)
+
+lemma power_neg_numeral_Bit0 [simp]:
+ "neg_numeral k ^ numeral (Num.Bit0 l) = numeral (Num.pow k (Num.Bit0 l))"
+ by (simp only: neg_numeral_def power_minus_Bit0 power_numeral)
+
+lemma power_neg_numeral_Bit1 [simp]:
+ "neg_numeral k ^ numeral (Num.Bit1 l) = neg_numeral (Num.pow k (Num.Bit1 l))"
+ by (simp only: neg_numeral_def power_minus_Bit1 power_numeral pow.simps)
+
+lemma power2_minus [simp]:
+ "(- a)\<^sup>2 = a\<^sup>2"
+ by (rule power_minus_Bit0)
+
+lemma power_minus1_even [simp]:
+ "-1 ^ (2*n) = 1"
+proof (induct n)
+ case 0 show ?case by simp
+next
+ case (Suc n) then show ?case by (simp add: power_add power2_eq_square)
+qed
+
+lemma power_minus1_odd:
+ "-1 ^ Suc (2*n) = -1"
+ by simp
+
+lemma power_minus_even [simp]:
+ "(-a) ^ (2*n) = a ^ (2*n)"
+ by (simp add: power_minus [of a])
+
+end
+
+context ring_1_no_zero_divisors
+begin
+
+lemma field_power_not_zero:
+ "a \<noteq> 0 \<Longrightarrow> a ^ n \<noteq> 0"
+ by (induct n) auto
+
+lemma zero_eq_power2 [simp]:
+ "a\<^sup>2 = 0 \<longleftrightarrow> a = 0"
+ unfolding power2_eq_square by simp
+
+lemma power2_eq_1_iff:
+ "a\<^sup>2 = 1 \<longleftrightarrow> a = 1 \<or> a = - 1"
+ unfolding power2_eq_square by (rule square_eq_1_iff)
+
+end
+
+context idom
+begin
+
+lemma power2_eq_iff: "x\<^sup>2 = y\<^sup>2 \<longleftrightarrow> x = y \<or> x = - y"
+ unfolding power2_eq_square by (rule square_eq_iff)
+
+end
+
+context division_ring
+begin
+
+text {* FIXME reorient or rename to @{text nonzero_inverse_power} *}
+lemma nonzero_power_inverse:
+ "a \<noteq> 0 \<Longrightarrow> inverse (a ^ n) = (inverse a) ^ n"
+ by (induct n)
+ (simp_all add: nonzero_inverse_mult_distrib power_commutes field_power_not_zero)
+
+end
+
+context field
+begin
+
+lemma nonzero_power_divide:
+ "b \<noteq> 0 \<Longrightarrow> (a / b) ^ n = a ^ n / b ^ n"
+ by (simp add: divide_inverse power_mult_distrib nonzero_power_inverse)
+
+end
+
+
+subsection {* Exponentiation on ordered types *}
+
+context linordered_ring (* TODO: move *)
+begin
+
+lemma sum_squares_ge_zero:
+ "0 \<le> x * x + y * y"
+ by (intro add_nonneg_nonneg zero_le_square)
+
+lemma not_sum_squares_lt_zero:
+ "\<not> x * x + y * y < 0"
+ by (simp add: not_less sum_squares_ge_zero)
+
+end
+
+context linordered_semidom
+begin
+
+lemma zero_less_power [simp]:
+ "0 < a \<Longrightarrow> 0 < a ^ n"
+ by (induct n) (simp_all add: mult_pos_pos)
+
+lemma zero_le_power [simp]:
+ "0 \<le> a \<Longrightarrow> 0 \<le> a ^ n"
+ by (induct n) (simp_all add: mult_nonneg_nonneg)
+
+lemma power_mono:
+ "a \<le> b \<Longrightarrow> 0 \<le> a \<Longrightarrow> a ^ n \<le> b ^ n"
+ by (induct n) (auto intro: mult_mono order_trans [of 0 a b])
+
+lemma one_le_power [simp]: "1 \<le> a \<Longrightarrow> 1 \<le> a ^ n"
+ using power_mono [of 1 a n] by simp
+
+lemma power_le_one: "\<lbrakk>0 \<le> a; a \<le> 1\<rbrakk> \<Longrightarrow> a ^ n \<le> 1"
+ using power_mono [of a 1 n] by simp
+
+lemma power_gt1_lemma:
+ assumes gt1: "1 < a"
+ shows "1 < a * a ^ n"
+proof -
+ from gt1 have "0 \<le> a"
+ by (fact order_trans [OF zero_le_one less_imp_le])
+ have "1 * 1 < a * 1" using gt1 by simp
+ also have "\<dots> \<le> a * a ^ n" using gt1
+ by (simp only: mult_mono `0 \<le> a` one_le_power order_less_imp_le
+ zero_le_one order_refl)
+ finally show ?thesis by simp
+qed
+
+lemma power_gt1:
+ "1 < a \<Longrightarrow> 1 < a ^ Suc n"
+ by (simp add: power_gt1_lemma)
+
+lemma one_less_power [simp]:
+ "1 < a \<Longrightarrow> 0 < n \<Longrightarrow> 1 < a ^ n"
+ by (cases n) (simp_all add: power_gt1_lemma)
+
+lemma power_le_imp_le_exp:
+ assumes gt1: "1 < a"
+ shows "a ^ m \<le> a ^ n \<Longrightarrow> m \<le> n"
+proof (induct m arbitrary: n)
+ case 0
+ show ?case by simp
+next
+ case (Suc m)
+ show ?case
+ proof (cases n)
+ case 0
+ with Suc.prems Suc.hyps have "a * a ^ m \<le> 1" by simp
+ with gt1 show ?thesis
+ by (force simp only: power_gt1_lemma
+ not_less [symmetric])
+ next
+ case (Suc n)
+ with Suc.prems Suc.hyps show ?thesis
+ by (force dest: mult_left_le_imp_le
+ simp add: less_trans [OF zero_less_one gt1])
+ qed
+qed
+
+text{*Surely we can strengthen this? It holds for @{text "0<a<1"} too.*}
+lemma power_inject_exp [simp]:
+ "1 < a \<Longrightarrow> a ^ m = a ^ n \<longleftrightarrow> m = n"
+ by (force simp add: order_antisym power_le_imp_le_exp)
+
+text{*Can relax the first premise to @{term "0<a"} in the case of the
+natural numbers.*}
+lemma power_less_imp_less_exp:
+ "1 < a \<Longrightarrow> a ^ m < a ^ n \<Longrightarrow> m < n"
+ by (simp add: order_less_le [of m n] less_le [of "a^m" "a^n"]
+ power_le_imp_le_exp)
+
+lemma power_strict_mono [rule_format]:
+ "a < b \<Longrightarrow> 0 \<le> a \<Longrightarrow> 0 < n \<longrightarrow> a ^ n < b ^ n"
+ by (induct n)
+ (auto simp add: mult_strict_mono le_less_trans [of 0 a b])
+
+text{*Lemma for @{text power_strict_decreasing}*}
+lemma power_Suc_less:
+ "0 < a \<Longrightarrow> a < 1 \<Longrightarrow> a * a ^ n < a ^ n"
+ by (induct n)
+ (auto simp add: mult_strict_left_mono)
+
+lemma power_strict_decreasing [rule_format]:
+ "n < N \<Longrightarrow> 0 < a \<Longrightarrow> a < 1 \<longrightarrow> a ^ N < a ^ n"
+proof (induct N)
+ case 0 then show ?case by simp
+next
+ case (Suc N) then show ?case
+ apply (auto simp add: power_Suc_less less_Suc_eq)
+ apply (subgoal_tac "a * a^N < 1 * a^n")
+ apply simp
+ apply (rule mult_strict_mono) apply auto
+ done
+qed
+
+text{*Proof resembles that of @{text power_strict_decreasing}*}
+lemma power_decreasing [rule_format]:
+ "n \<le> N \<Longrightarrow> 0 \<le> a \<Longrightarrow> a \<le> 1 \<longrightarrow> a ^ N \<le> a ^ n"
+proof (induct N)
+ case 0 then show ?case by simp
+next
+ case (Suc N) then show ?case
+ apply (auto simp add: le_Suc_eq)
+ apply (subgoal_tac "a * a^N \<le> 1 * a^n", simp)
+ apply (rule mult_mono) apply auto
+ done
+qed
+
+lemma power_Suc_less_one:
+ "0 < a \<Longrightarrow> a < 1 \<Longrightarrow> a ^ Suc n < 1"
+ using power_strict_decreasing [of 0 "Suc n" a] by simp
+
+text{*Proof again resembles that of @{text power_strict_decreasing}*}
+lemma power_increasing [rule_format]:
+ "n \<le> N \<Longrightarrow> 1 \<le> a \<Longrightarrow> a ^ n \<le> a ^ N"
+proof (induct N)
+ case 0 then show ?case by simp
+next
+ case (Suc N) then show ?case
+ apply (auto simp add: le_Suc_eq)
+ apply (subgoal_tac "1 * a^n \<le> a * a^N", simp)
+ apply (rule mult_mono) apply (auto simp add: order_trans [OF zero_le_one])
+ done
+qed
+
+text{*Lemma for @{text power_strict_increasing}*}
+lemma power_less_power_Suc:
+ "1 < a \<Longrightarrow> a ^ n < a * a ^ n"
+ by (induct n) (auto simp add: mult_strict_left_mono less_trans [OF zero_less_one])
+
+lemma power_strict_increasing [rule_format]:
+ "n < N \<Longrightarrow> 1 < a \<longrightarrow> a ^ n < a ^ N"
+proof (induct N)
+ case 0 then show ?case by simp
+next
+ case (Suc N) then show ?case
+ apply (auto simp add: power_less_power_Suc less_Suc_eq)
+ apply (subgoal_tac "1 * a^n < a * a^N", simp)
+ apply (rule mult_strict_mono) apply (auto simp add: less_trans [OF zero_less_one] less_imp_le)
+ done
+qed
+
+lemma power_increasing_iff [simp]:
+ "1 < b \<Longrightarrow> b ^ x \<le> b ^ y \<longleftrightarrow> x \<le> y"
+ by (blast intro: power_le_imp_le_exp power_increasing less_imp_le)
+
+lemma power_strict_increasing_iff [simp]:
+ "1 < b \<Longrightarrow> b ^ x < b ^ y \<longleftrightarrow> x < y"
+by (blast intro: power_less_imp_less_exp power_strict_increasing)
+
+lemma power_le_imp_le_base:
+ assumes le: "a ^ Suc n \<le> b ^ Suc n"
+ and ynonneg: "0 \<le> b"
+ shows "a \<le> b"
+proof (rule ccontr)
+ assume "~ a \<le> b"
+ then have "b < a" by (simp only: linorder_not_le)
+ then have "b ^ Suc n < a ^ Suc n"
+ by (simp only: assms power_strict_mono)
+ from le and this show False
+ by (simp add: linorder_not_less [symmetric])
+qed
+
+lemma power_less_imp_less_base:
+ assumes less: "a ^ n < b ^ n"
+ assumes nonneg: "0 \<le> b"
+ shows "a < b"
+proof (rule contrapos_pp [OF less])
+ assume "~ a < b"
+ hence "b \<le> a" by (simp only: linorder_not_less)
+ hence "b ^ n \<le> a ^ n" using nonneg by (rule power_mono)
+ thus "\<not> a ^ n < b ^ n" by (simp only: linorder_not_less)
+qed
+
+lemma power_inject_base:
+ "a ^ Suc n = b ^ Suc n \<Longrightarrow> 0 \<le> a \<Longrightarrow> 0 \<le> b \<Longrightarrow> a = b"
+by (blast intro: power_le_imp_le_base antisym eq_refl sym)
+
+lemma power_eq_imp_eq_base:
+ "a ^ n = b ^ n \<Longrightarrow> 0 \<le> a \<Longrightarrow> 0 \<le> b \<Longrightarrow> 0 < n \<Longrightarrow> a = b"
+ by (cases n) (simp_all del: power_Suc, rule power_inject_base)
+
+lemma power2_le_imp_le:
+ "x\<^sup>2 \<le> y\<^sup>2 \<Longrightarrow> 0 \<le> y \<Longrightarrow> x \<le> y"
+ unfolding numeral_2_eq_2 by (rule power_le_imp_le_base)
+
+lemma power2_less_imp_less:
+ "x\<^sup>2 < y\<^sup>2 \<Longrightarrow> 0 \<le> y \<Longrightarrow> x < y"
+ by (rule power_less_imp_less_base)
+
+lemma power2_eq_imp_eq:
+ "x\<^sup>2 = y\<^sup>2 \<Longrightarrow> 0 \<le> x \<Longrightarrow> 0 \<le> y \<Longrightarrow> x = y"
+ unfolding numeral_2_eq_2 by (erule (2) power_eq_imp_eq_base) simp
+
+end
+
+context linordered_ring_strict
+begin
+
+lemma sum_squares_eq_zero_iff:
+ "x * x + y * y = 0 \<longleftrightarrow> x = 0 \<and> y = 0"
+ by (simp add: add_nonneg_eq_0_iff)
+
+lemma sum_squares_le_zero_iff:
+ "x * x + y * y \<le> 0 \<longleftrightarrow> x = 0 \<and> y = 0"
+ by (simp add: le_less not_sum_squares_lt_zero sum_squares_eq_zero_iff)
+
+lemma sum_squares_gt_zero_iff:
+ "0 < x * x + y * y \<longleftrightarrow> x \<noteq> 0 \<or> y \<noteq> 0"
+ by (simp add: not_le [symmetric] sum_squares_le_zero_iff)
+
+end
+
+context linordered_idom
+begin
+
+lemma power_abs:
+ "abs (a ^ n) = abs a ^ n"
+ by (induct n) (auto simp add: abs_mult)
+
+lemma abs_power_minus [simp]:
+ "abs ((-a) ^ n) = abs (a ^ n)"
+ by (simp add: power_abs)
+
+lemma zero_less_power_abs_iff [simp, no_atp]:
+ "0 < abs a ^ n \<longleftrightarrow> a \<noteq> 0 \<or> n = 0"
+proof (induct n)
+ case 0 show ?case by simp
+next
+ case (Suc n) show ?case by (auto simp add: Suc zero_less_mult_iff)
+qed
+
+lemma zero_le_power_abs [simp]:
+ "0 \<le> abs a ^ n"
+ by (rule zero_le_power [OF abs_ge_zero])
+
+lemma zero_le_power2 [simp]:
+ "0 \<le> a\<^sup>2"
+ by (simp add: power2_eq_square)
+
+lemma zero_less_power2 [simp]:
+ "0 < a\<^sup>2 \<longleftrightarrow> a \<noteq> 0"
+ by (force simp add: power2_eq_square zero_less_mult_iff linorder_neq_iff)
+
+lemma power2_less_0 [simp]:
+ "\<not> a\<^sup>2 < 0"
+ by (force simp add: power2_eq_square mult_less_0_iff)
+
+lemma abs_power2 [simp]:
+ "abs (a\<^sup>2) = a\<^sup>2"
+ by (simp add: power2_eq_square abs_mult abs_mult_self)
+
+lemma power2_abs [simp]:
+ "(abs a)\<^sup>2 = a\<^sup>2"
+ by (simp add: power2_eq_square abs_mult_self)
+
+lemma odd_power_less_zero:
+ "a < 0 \<Longrightarrow> a ^ Suc (2*n) < 0"
+proof (induct n)
+ case 0
+ then show ?case by simp
+next
+ case (Suc n)
+ have "a ^ Suc (2 * Suc n) = (a*a) * a ^ Suc(2*n)"
+ by (simp add: mult_ac power_add power2_eq_square)
+ thus ?case
+ by (simp del: power_Suc add: Suc mult_less_0_iff mult_neg_neg)
+qed
+
+lemma odd_0_le_power_imp_0_le:
+ "0 \<le> a ^ Suc (2*n) \<Longrightarrow> 0 \<le> a"
+ using odd_power_less_zero [of a n]
+ by (force simp add: linorder_not_less [symmetric])
+
+lemma zero_le_even_power'[simp]:
+ "0 \<le> a ^ (2*n)"
+proof (induct n)
+ case 0
+ show ?case by simp
+next
+ case (Suc n)
+ have "a ^ (2 * Suc n) = (a*a) * a ^ (2*n)"
+ by (simp add: mult_ac power_add power2_eq_square)
+ thus ?case
+ by (simp add: Suc zero_le_mult_iff)
+qed
+
+lemma sum_power2_ge_zero:
+ "0 \<le> x\<^sup>2 + y\<^sup>2"
+ by (intro add_nonneg_nonneg zero_le_power2)
+
+lemma not_sum_power2_lt_zero:
+ "\<not> x\<^sup>2 + y\<^sup>2 < 0"
+ unfolding not_less by (rule sum_power2_ge_zero)
+
+lemma sum_power2_eq_zero_iff:
+ "x\<^sup>2 + y\<^sup>2 = 0 \<longleftrightarrow> x = 0 \<and> y = 0"
+ unfolding power2_eq_square by (simp add: add_nonneg_eq_0_iff)
+
+lemma sum_power2_le_zero_iff:
+ "x\<^sup>2 + y\<^sup>2 \<le> 0 \<longleftrightarrow> x = 0 \<and> y = 0"
+ by (simp add: le_less sum_power2_eq_zero_iff not_sum_power2_lt_zero)
+
+lemma sum_power2_gt_zero_iff:
+ "0 < x\<^sup>2 + y\<^sup>2 \<longleftrightarrow> x \<noteq> 0 \<or> y \<noteq> 0"
+ unfolding not_le [symmetric] by (simp add: sum_power2_le_zero_iff)
+
+end
+
+
+subsection {* Miscellaneous rules *}
+
+lemma power_eq_if: "p ^ m = (if m=0 then 1 else p * (p ^ (m - 1)))"
+ unfolding One_nat_def by (cases m) simp_all
+
+lemma power2_sum:
+ fixes x y :: "'a::comm_semiring_1"
+ shows "(x + y)\<^sup>2 = x\<^sup>2 + y\<^sup>2 + 2 * x * y"
+ by (simp add: algebra_simps power2_eq_square mult_2_right)
+
+lemma power2_diff:
+ fixes x y :: "'a::comm_ring_1"
+ shows "(x - y)\<^sup>2 = x\<^sup>2 + y\<^sup>2 - 2 * x * y"
+ by (simp add: ring_distribs power2_eq_square mult_2) (rule mult_commute)
+
+lemma power_0_Suc [simp]:
+ "(0::'a::{power, semiring_0}) ^ Suc n = 0"
+ by simp
+
+text{*It looks plausible as a simprule, but its effect can be strange.*}
+lemma power_0_left:
+ "0 ^ n = (if n = 0 then 1 else (0::'a::{power, semiring_0}))"
+ by (induct n) simp_all
+
+lemma power_eq_0_iff [simp]:
+ "a ^ n = 0 \<longleftrightarrow>
+ a = (0::'a::{mult_zero,zero_neq_one,no_zero_divisors,power}) \<and> n \<noteq> 0"
+ by (induct n)
+ (auto simp add: no_zero_divisors elim: contrapos_pp)
+
+lemma (in field) power_diff:
+ assumes nz: "a \<noteq> 0"
+ shows "n \<le> m \<Longrightarrow> a ^ (m - n) = a ^ m / a ^ n"
+ by (induct m n rule: diff_induct) (simp_all add: nz field_power_not_zero)
+
+text{*Perhaps these should be simprules.*}
+lemma power_inverse:
+ fixes a :: "'a::division_ring_inverse_zero"
+ shows "inverse (a ^ n) = inverse a ^ n"
+apply (cases "a = 0")
+apply (simp add: power_0_left)
+apply (simp add: nonzero_power_inverse)
+done (* TODO: reorient or rename to inverse_power *)
+
+lemma power_one_over:
+ "1 / (a::'a::{field_inverse_zero, power}) ^ n = (1 / a) ^ n"
+ by (simp add: divide_inverse) (rule power_inverse)
+
+lemma power_divide:
+ "(a / b) ^ n = (a::'a::field_inverse_zero) ^ n / b ^ n"
+apply (cases "b = 0")
+apply (simp add: power_0_left)
+apply (rule nonzero_power_divide)
+apply assumption
+done
+
+text {* Simprules for comparisons where common factors can be cancelled. *}
+
+lemmas zero_compare_simps =
+ add_strict_increasing add_strict_increasing2 add_increasing
+ zero_le_mult_iff zero_le_divide_iff
+ zero_less_mult_iff zero_less_divide_iff
+ mult_le_0_iff divide_le_0_iff
+ mult_less_0_iff divide_less_0_iff
+ zero_le_power2 power2_less_0
+
+
+subsection {* Exponentiation for the Natural Numbers *}
+
+lemma nat_one_le_power [simp]:
+ "Suc 0 \<le> i \<Longrightarrow> Suc 0 \<le> i ^ n"
+ by (rule one_le_power [of i n, unfolded One_nat_def])
+
+lemma nat_zero_less_power_iff [simp]:
+ "x ^ n > 0 \<longleftrightarrow> x > (0::nat) \<or> n = 0"
+ by (induct n) auto
+
+lemma nat_power_eq_Suc_0_iff [simp]:
+ "x ^ m = Suc 0 \<longleftrightarrow> m = 0 \<or> x = Suc 0"
+ by (induct m) auto
+
+lemma power_Suc_0 [simp]:
+ "Suc 0 ^ n = Suc 0"
+ by simp
+
+text{*Valid for the naturals, but what if @{text"0<i<1"}?
+Premises cannot be weakened: consider the case where @{term "i=0"},
+@{term "m=1"} and @{term "n=0"}.*}
+lemma nat_power_less_imp_less:
+ assumes nonneg: "0 < (i\<Colon>nat)"
+ assumes less: "i ^ m < i ^ n"
+ shows "m < n"
+proof (cases "i = 1")
+ case True with less power_one [where 'a = nat] show ?thesis by simp
+next
+ case False with nonneg have "1 < i" by auto
+ from power_strict_increasing_iff [OF this] less show ?thesis ..
+qed
+
+lemma power_dvd_imp_le:
+ "i ^ m dvd i ^ n \<Longrightarrow> (1::nat) < i \<Longrightarrow> m \<le> n"
+ apply (rule power_le_imp_le_exp, assumption)
+ apply (erule dvd_imp_le, simp)
+ done
+
+lemma power2_nat_le_eq_le:
+ fixes m n :: nat
+ shows "m\<^sup>2 \<le> n\<^sup>2 \<longleftrightarrow> m \<le> n"
+ by (auto intro: power2_le_imp_le power_mono)
+
+lemma power2_nat_le_imp_le:
+ fixes m n :: nat
+ assumes "m\<^sup>2 \<le> n"
+ shows "m \<le> n"
+ using assms by (cases m) (simp_all add: power2_eq_square)
+
+
+
+subsection {* Code generator tweak *}
+
+lemma power_power_power [code]:
+ "power = power.power (1::'a::{power}) (op *)"
+ unfolding power_def power.power_def ..
+
+declare power.power.simps [code]
+
+code_identifier
+ code_module Power \<rightharpoonup> (SML) Arith and (OCaml) Arith and (Haskell) Arith
+
+end
+
diff --git a/tests/examplefiles/example.todotxt b/tests/examplefiles/example.todotxt
new file mode 100644
index 00000000..55ee5286
--- /dev/null
+++ b/tests/examplefiles/example.todotxt
@@ -0,0 +1,9 @@
+(A) Call Mom @Phone +Family
+(A) 2014-01-08 Schedule annual checkup +Health
+(B) Outline chapter 5 +Novel @Computer
+(C) Add cover sheets @Office +TPSReports
+Plan backyard herb garden @Home
+Pick up milk @GroceryStore
+Research self-publishing services +Novel @Computer
+x 2014-01-10 Download Todo.txt mobile app @Phone
+x 2014-01-10 2014-01-07 Download Todo.txt CLI @Computer
diff --git a/tests/examplefiles/example.weechatlog b/tests/examplefiles/example.weechatlog
index 9f036166..15e8130f 100644
--- a/tests/examplefiles/example.weechatlog
+++ b/tests/examplefiles/example.weechatlog
@@ -6,4 +6,6 @@
2007 Sep 01 00:23:55 -=- Das Topic von &bitlbee lautet: "Welcome to the control channel. Type help for help information."
2007 Sep 01 00:23:55 <root> Welcome to the BitlBee gateway!
2007 Sep 01 00:23:55 <root>
-2007 Sep 01 00:23:55 <root> If you've never used BitlBee before, please do read the help information using the help command. Lots of FAQ's are answered there. \ No newline at end of file
+2007 Sep 01 00:23:55 <root> If you've never used BitlBee before, please do read the help information using the help command. Lots of FAQ's are answered there.
+# check for fixed pathological matching behavior
+1111111111111111111111111111111
diff --git a/tests/examplefiles/exampleScript.cfc b/tests/examplefiles/exampleScript.cfc
new file mode 100644
index 00000000..002acbcd
--- /dev/null
+++ b/tests/examplefiles/exampleScript.cfc
@@ -0,0 +1,241 @@
+<cfscript>
+/**
+********************************************************************************
+ContentBox - A Modular Content Platform
+Copyright 2012 by Luis Majano and Ortus Solutions, Corp
+www.gocontentbox.org | www.luismajano.com | www.ortussolutions.com
+********************************************************************************
+Apache License, Version 2.0
+
+Copyright Since [2012] [Luis Majano and Ortus Solutions,Corp]
+
+Licensed under the Apache License, Version 2.0 (the "License");
+you may not use this file except in compliance with the License.
+You may obtain a copy of the License at
+
+http://www.apache.org/licenses/LICENSE-2.0
+
+Unless required by applicable law or agreed to in writing, software
+distributed under the License is distributed on an "AS IS" BASIS,
+WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+See the License for the specific language governing permissions and
+limitations under the License.
+********************************************************************************
+* A generic content service for content objects
+*/
+component extends="coldbox.system.orm.hibernate.VirtualEntityService" singleton{
+
+ // DI
+ property name="settingService" inject="id:settingService@cb";
+ property name="cacheBox" inject="cachebox";
+ property name="log" inject="logbox:logger:{this}";
+ property name="customFieldService" inject="customFieldService@cb";
+ property name="categoryService" inject="categoryService@cb";
+ property name="commentService" inject="commentService@cb";
+ property name="contentVersionService" inject="contentVersionService@cb";
+ property name="authorService" inject="authorService@cb";
+ property name="populator" inject="wirebox:populator";
+ property name="systemUtil" inject="SystemUtil@cb";
+
+ /*
+ * Constructor
+ * @entityName.hint The content entity name to bind this service to.
+ */
+ ContentService function init(entityName="cbContent"){
+ // init it
+ super.init(entityName=arguments.entityName, useQueryCaching=true);
+
+ // Test scope coloring in pygments
+ this.colorTestVar = "Just for testing pygments!";
+ cookie.colorTestVar = "";
+ client.colorTestVar = ""
+ session.colorTestVar = "";
+ application.colorTestVar = "";
+
+ return this;
+ }
+
+ /**
+ * Clear all content caches
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearAllCaches(boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clearByKeySnippet(keySnippet="cb-content",async=arguments.async);
+ return this;
+ }
+
+ /**
+ * Clear all page wrapper caches
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearAllPageWrapperCaches(boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper",async=arguments.async);
+ return this;
+ }
+
+ /**
+ * Clear all page wrapper caches
+ * @slug.hint The slug partial to clean on
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearPageWrapperCaches(required any slug, boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clearByKeySnippet(keySnippet="cb-content-pagewrapper-#arguments.slug#",async=arguments.async);
+ return this;
+ }
+
+ /**
+ * Clear a page wrapper cache
+ * @slug.hint The slug to clean
+ * @async.hint Run it asynchronously or not, defaults to false
+ */
+ function clearPageWrapper(required any slug, boolean async=false){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clear("cb-content-pagewrapper-#arguments.slug#/");
+ return this;
+ }
+
+ /**
+ * Searches published content with cool paramters, remember published content only
+ * @searchTerm.hint The search term to search
+ * @max.hint The maximum number of records to paginate
+ * @offset.hint The offset in the pagination
+ * @asQuery.hint Return as query or array of objects, defaults to array of objects
+ * @sortOrder.hint The sorting of the search results, defaults to publishedDate DESC
+ * @isPublished.hint Search for published, non-published or both content objects [true, false, 'all']
+ * @searchActiveContent.hint Search only content titles or both title and active content. Defaults to both.
+ */
+ function searchContent(
+ any searchTerm="",
+ numeric max=0,
+ numeric offset=0,
+ boolean asQuery=false,
+ any sortOrder="publishedDate DESC",
+ any isPublished=true,
+ boolean searchActiveContent=true){
+
+ var results = {};
+ var c = newCriteria();
+
+ // only published content
+ if( isBoolean( arguments.isPublished ) ){
+ // Published bit
+ c.isEq( "isPublished", javaCast( "Boolean", arguments.isPublished ) );
+ // Published eq true evaluate other params
+ if( arguments.isPublished ){
+ c.isLt("publishedDate", now() )
+ .$or( c.restrictions.isNull("expireDate"), c.restrictions.isGT("expireDate", now() ) )
+ .isEq("passwordProtection","");
+ }
+ }
+
+ // Search Criteria
+ if( len( arguments.searchTerm ) ){
+ // like disjunctions
+ c.createAlias("activeContent","ac");
+ // Do we search title and active content or just title?
+ if( arguments.searchActiveContent ){
+ c.$or( c.restrictions.like("title","%#arguments.searchTerm#%"),
+ c.restrictions.like("ac.content", "%#arguments.searchTerm#%") );
+ }
+ else{
+ c.like( "title", "%#arguments.searchTerm#%" );
+ }
+ }
+
+ // run criteria query and projections count
+ results.count = c.count( "contentID" );
+ results.content = c.resultTransformer( c.DISTINCT_ROOT_ENTITY )
+ .list(offset=arguments.offset, max=arguments.max, sortOrder=arguments.sortOrder, asQuery=arguments.asQuery);
+
+ return results;
+ }
+
+/********************************************* PRIVATE *********************************************/
+
+
+ /**
+ * Update the content hits
+ * @contentID.hint The content id to update
+ */
+ private function syncUpdateHits(required contentID){
+ var q = new Query(sql="UPDATE cb_content SET hits = hits + 1 WHERE contentID = #arguments.contentID#").execute();
+ return this;
+ }
+
+
+ private function closureTest(){
+ methodCall(
+ param1,
+ function( arg1, required arg2 ){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clear("cb-content-pagewrapper-#arguments.slug#/");
+ return this;
+ },
+ param1
+ );
+ }
+
+ private function StructliteralTest(){
+ return {
+ foo = bar,
+ brad = 'Wood',
+ func = function( arg1, required arg2 ){
+ var settings = settingService.getAllSettings(asStruct=true);
+ // Get appropriate cache provider
+ var cache = cacheBox.getCache( settings.cb_content_cacheName );
+ cache.clear("cb-content-pagewrapper-#arguments.slug#/");
+ return this;
+ },
+ array = [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 'test',
+ 'testing',
+ 'testerton',
+ {
+ foo = true,
+ brad = false,
+ wood = null
+ }
+ ],
+ last = "final"
+ };
+ }
+
+ private function arrayliteralTest(){
+ return [
+ 1,
+ 2,
+ 3,
+ 4,
+ 5,
+ 'test',
+ 'testing',
+ 'testerton',
+ {
+ foo = true,
+ brad = false,
+ wood = null
+ },
+ 'testy-von-testavich'
+ ];
+ }
+
+}
+</cfscript> \ No newline at end of file
diff --git a/tests/examplefiles/exampleTag.cfc b/tests/examplefiles/exampleTag.cfc
new file mode 100644
index 00000000..753bb826
--- /dev/null
+++ b/tests/examplefiles/exampleTag.cfc
@@ -0,0 +1,18 @@
+<cfcomponent>
+
+ <cffunction name="init" access="public" returntype="any">
+ <cfargument name="arg1" type="any" required="true">
+ <cfset this.myVariable = arguments.arg1>
+
+ <cfreturn this>
+ </cffunction>
+
+ <cffunction name="testFunc" access="private" returntype="void">
+ <cfargument name="arg1" type="any" required="false">
+
+ <cfif structKeyExists(arguments, "arg1")>
+ <cfset writeoutput("Argument exists")>
+ </cfif>
+ </cffunction>
+
+</cfcomponent> \ No newline at end of file
diff --git a/tests/examplefiles/example_coq.v b/tests/examplefiles/example_coq.v
new file mode 100644
index 00000000..fd1a7bc8
--- /dev/null
+++ b/tests/examplefiles/example_coq.v
@@ -0,0 +1,4 @@
+Lemma FalseLemma : False <-> False.
+tauto.
+Qed.
+Check FalseLemma.
diff --git a/tests/examplefiles/example_elixir.ex b/tests/examplefiles/example_elixir.ex
index 2e92163d..ddca7f60 100644
--- a/tests/examplefiles/example_elixir.ex
+++ b/tests/examplefiles/example_elixir.ex
@@ -1,363 +1,233 @@
-# We cannot use to_char_list because it depends on inspect,
-# which depends on protocol, which depends on this module.
-import Elixir::Builtin, except: [to_char_list: 1]
-
-defmodule Module do
- require Erlang.ets, as: ETS
-
- @moduledoc """
- This module provides many functions to deal with modules during
- compilation time. It allows a developer to dynamically attach
- documentation, merge data, register attributes and so forth.
-
- After the module is compiled, using many of the functions in
- this module will raise errors, since it is out of their purpose
- to inspect runtime data. Most of the runtime data can be inspected
- via the `__info__(attr)` function attached to each compiled module.
- """
-
- @doc """
- Evalutes the quotes contents in the given module context.
- Raises an error if the module was already compiled.
-
- ## Examples
-
- defmodule Foo do
- contents = quote do: (def sum(a, b), do: a + b)
- Module.eval_quoted __MODULE__, contents, [], __FILE__, __LINE__
- end
-
- Foo.sum(1, 2) #=> 3
- """
- def eval_quoted(module, quoted, binding, filename, line) do
- assert_not_compiled!(:eval_quoted, module)
- { binding, scope } = Erlang.elixir_module.binding_and_scope_for_eval(line, to_char_list(filename), module, binding)
- Erlang.elixir_def.reset_last(module)
- Erlang.elixir.eval_quoted([quoted], binding, line, scope)
- end
-
- @doc """
- Checks if the module is compiled or not.
-
- ## Examples
-
- defmodule Foo do
- Module.compiled?(__MODULE__) #=> false
- end
-
- Module.compiled?(Foo) #=> true
-
- """
- def compiled?(module) do
- table = data_table_for(module)
- table == ETS.info(table, :name)
- end
-
- @doc """
- Reads the data for the given module. This is used
- to read data of uncompiled modules. If the module
- was already compiled, you shoul access the data
- directly by invoking `__info__(:data)` in that module.
-
- ## Examples
-
- defmodule Foo do
- Module.merge_data __MODULE__, value: 1
- Module.read_data __MODULE__ #=> [value: 1]
- end
-
- """
- def read_data(module) do
- assert_not_compiled!(:read_data, module)
- ETS.lookup_element(data_table_for(module), :data, 2)
- end
-
- @doc """
- Reads the data from `module` at the given key `at`.
-
- ## Examples
-
- defmodule Foo do
- Module.merge_data __MODULE__, value: 1
- Module.read_data __MODULE__, :value #=> 1
- end
-
- """
- def read_data(module, at) do
- Orddict.get read_data(module), at
- end
-
- @doc """
- Merge the given data into the module, overriding any
- previous one.
-
- If any of the given data is a registered attribute, it is
- automatically added to the attribute set, instead of marking
- it as data. See register_attribute/2 and add_attribute/3 for
- more info.
-
- ## Examples
-
- defmodule Foo do
- Module.merge_data __MODULE__, value: 1
- end
-
- Foo.__info__(:data) #=> [value: 1]
-
- """
- def merge_data(module, data) do
- assert_not_compiled!(:merge_data, module)
-
- table = data_table_for(module)
- old = ETS.lookup_element(table, :data, 2)
- registered = ETS.lookup_element(table, :registered_attributes, 2)
-
- { attrs, new } = Enum.partition data, fn({k,_}) -> List.member?(registered, k) end
- Enum.each attrs, fn({k,v}) -> add_attribute(module, k, v) end
- ETS.insert(table, { :data, Orddict.merge(old, new) })
- end
-
- @doc """
- Attaches documentation to a given function. It expects
- the module the function belongs to, the line (a non negative
- integer), the kind (def or defmacro), a tuple representing
- the function and its arity and the documentation, which should
- be either a binary or a boolean.
-
- ## Examples
-
- defmodule MyModule do
- Module.add_doc(__MODULE__, __LINE__ + 1, :def, { :version, 0 }, "Manually added docs")
- def version, do: 1
- end
-
- """
- def add_doc(module, line, kind, tuple, doc) when
- is_binary(doc) or is_boolean(doc) do
- assert_not_compiled!(:add_doc, module)
- case kind do
- match: :defp
- :warn
- else:
- table = docs_table_for(module)
- ETS.insert(table, { tuple, line, kind, doc })
- :ok
- end
- end
+# Numbers
+0b0101011
+1234 ; 0x1A ; 0xbeef ; 0763 ; 0o123
+3.14 ; 5.0e21 ; 0.5e-12
+100_000_000
+
+# these are not valid numbers
+0b012 ; 0xboar ; 0o888
+0B01 ; 0XAF ; 0O123
+
+# Characters
+?a ; ?1 ; ?\n ; ?\s ; ?\c ; ? ; ?,
+?\x{12} ; ?\x{abcd}
+?\x34 ; ?\xF
+
+# these show that only the first digit is part of the character
+?\123 ; ?\12 ; ?\7
+
+# Atoms
+:this ; :that
+:'complex atom'
+:"with' \"\" 'quotes"
+:" multi
+ line ' \s \123 \xff
+atom"
+:... ; :<<>> ; :%{} ; :% ; :{}
+:++; :--; :*; :~~~; :::
+:% ; :. ; :<-
+
+# Strings
+"Hello world"
+"Interspersed \x{ff} codes \7 \8 \65 \016 and \t\s\\s\z\+ \\ escapes"
+"Quotes ' inside \" \123 the \"\" \xF \\xF string \\\" end"
+"Multiline
+ string"
+
+# Char lists
+'this is a list'
+'escapes \' \t \\\''
+'Multiline
+ char
+ list
+'
+
+# Binaries
+<<1, 2, 3>>
+<<"hello"::binary, c :: utf8, x::[4, unit(2)]>> = "hello™1"
+
+# Sigils
+~r/this + i\s "a" regex/
+~R'this + i\s "a" regex too'
+~w(hello #{ ["has" <> "123", '\c\d', "\123 interpol" | []] } world)s
+~W(hello #{no "123" \c\d \123 interpol} world)s
+
+~s{Escapes terminators \{ and \}, but no {balancing} # outside of sigil here }
+
+~S"No escapes \s\t\n and no #{interpolation}"
+
+:"atoms work #{"to" <> "o"}"
+
+# Operators
+x = 1 + 2.0 * 3
+y = true and false; z = false or true
+... = 144
+... == !x && y || z
+"hello" |> String.upcase |> String.downcase()
+{^z, a} = {true, x}
+
+# Free operators (added in 1.0.0)
+p ~>> f = bind(p, f)
+p1 ~> p2 = pair_right(p1, p2)
+p1 <~ p2 = pair_left(p1, p2)
+p1 <~> p2 = pair_both(p1, p2)
+p |~> f = map(p, f)
+p1 <|> p2 = either(p1, p2)
+
+# Lists, tuples, maps, keywords
+[1, :a, 'hello'] ++ [2, 3]
+[:head | [?t, ?a, ?i, ?l]]
+
+{:one, 2.0, "three"}
+
+[...: "this", <<>>: "is", %{}: "a keyword", %: "list", {}: "too"]
+["this is an atom too": 1, "so is this": 2]
+[option: "value", key: :word]
+[++: "operator", ~~~: :&&&]
+
+map = %{shortcut: "syntax"}
+%{map | "update" => "me"}
+%{ 12 => 13, :weird => ['thing'] }
+
+# Comprehensions
+for x <- 1..10, x < 5, do: {x, x}
+pixels = "12345678"
+for << <<r::4, g::4, b::4, a::size(4)>> <- pixels >> do
+ [r, {g, %{"b" => a}}]
+end
+
+# String interpolation
+"String #{inspect "interpolation"} is quite #{1+4+7} difficult"
+
+# Identifiers
+abc_123 = 1
+_018OP = 2
+A__0 == 3
+
+# Modules
+defmodule Long.Module.Name do
+ @moduledoc "Simple module docstring"
@doc """
- Checks if a function was defined, regardless if it is
- a macro or a private function. Use function_defined?/3
- to assert for an specific type.
-
- ## Examples
-
- defmodule Example do
- Module.function_defined? __MODULE__, { :version, 0 } #=> false
- def version, do: 1
- Module.function_defined? __MODULE__, { :version, 0 } #=> true
- end
-
+ Multiline docstring
+ "with quotes"
+ and #{ inspect %{"interpolation" => "in" <> "action"} }
+ now with #{ {:a, 'tuple'} }
+ and #{ inspect {
+ :tuple,
+ %{ with: "nested #{ inspect %{ :interpolation => %{} } }" }
+ } }
"""
- def function_defined?(module, tuple) when is_tuple(tuple) do
- assert_not_compiled!(:function_defined?, module)
- table = function_table_for(module)
- ETS.lookup(table, tuple) != []
- end
+ defstruct [:a, :name, :height]
- @doc """
- Checks if a function was defined and also for its `kind`.
- `kind` can be either :def, :defp or :defmacro.
+ @doc ~S'''
+ No #{interpolation} of any kind.
+ \000 \x{ff}
- ## Examples
-
- defmodule Example do
- Module.function_defined? __MODULE__, { :version, 0 }, :defp #=> false
- def version, do: 1
- Module.function_defined? __MODULE__, { :version, 0 }, :defp #=> false
- end
-
- """
- def function_defined?(module, tuple, kind) do
- List.member? defined_functions(module, kind), tuple
- end
-
- @doc """
- Return all functions defined in the given module.
-
- ## Examples
-
- defmodule Example do
- def version, do: 1
- Module.defined_functions __MODULE__ #=> [{:version,1}]
- end
-
- """
- def defined_functions(module) do
- assert_not_compiled!(:defined_functions, module)
- table = function_table_for(module)
- lc { tuple, _, _ } in ETS.tab2list(table), do: tuple
- end
-
- @doc """
- Returns all functions defined in te given module according
- to its kind.
-
- ## Examples
-
- defmodule Example do
- def version, do: 1
- Module.defined_functions __MODULE__, :def #=> [{:version,1}]
- Module.defined_functions __MODULE__, :defp #=> []
- end
-
- """
- def defined_functions(module, kind) do
- assert_not_compiled!(:defined_functions, module)
- table = function_table_for(module)
- entry = kind_to_entry(kind)
- ETS.lookup_element(table, entry, 2)
- end
-
- @doc """
- Adds a compilation callback hook that is invoked
- exactly before the module is compiled.
-
- This callback is useful when used with `use` as a mechanism
- to clean up any internal data in the module before it is compiled.
-
- ## Examples
-
- Imagine you are creating a module/library that is meant for
- external usage called `MyLib`. It could be defined as:
-
- defmodule MyLib do
- def __using__(target) do
- Module.merge_data target, some_data: true
- Module.add_compile_callback(target, __MODULE__, :__callback__)
- end
-
- defmacro __callback__(target) do
- value = Orddict.get(Module.read_data(target), :some_data, [])
- quote do: (def my_lib_value, do: unquote(value))
- end
- end
-
- And a module could use `MyLib` with:
-
- defmodule App do
- use ModuleTest::ToBeUsed
- end
-
- In the example above, `MyLib` defines a data to the target. This data
- can be updated throughout the module definition and therefore, the final
- value of the data can only be compiled using a compiation callback,
- which will read the final value of :some_data and compile to a function.
- """
- def add_compile_callback(module, target, fun // :__compiling__) do
- assert_not_compiled!(:add_compile_callback, module)
- new = { target, fun }
- table = data_table_for(module)
- old = ETS.lookup_element(table, :compile_callbacks, 2)
- ETS.insert(table, { :compile_callbacks, [new|old] })
- end
-
- @doc """
- Adds an Erlang attribute to the given module with the given
- key and value. The same attribute can be added more than once.
-
- ## Examples
-
- defmodule MyModule do
- Module.add_attribute __MODULE__, :custom_threshold_for_lib, 10
- end
-
- """
- def add_attribute(module, key, value) when is_atom(key) do
- assert_not_compiled!(:add_attribute, module)
- table = data_table_for(module)
- attrs = ETS.lookup_element(table, :attributes, 2)
- ETS.insert(table, { :attributes, [{key, value}|attrs] })
- end
-
- @doc """
- Deletes all attributes that matches the given key.
-
- ## Examples
-
- defmodule MyModule do
- Module.add_attribute __MODULE__, :custom_threshold_for_lib, 10
- Module.delete_attribute __MODULE__, :custom_threshold_for_lib
- end
-
- """
- def delete_attribute(module, key) when is_atom(key) do
- assert_not_compiled!(:delete_attribute, module)
- table = data_table_for(module)
- attrs = ETS.lookup_element(table, :attributes, 2)
- final = lc {k,v} in attrs, k != key, do: {k,v}
- ETS.insert(table, { :attributes, final })
- end
-
- @doc """
- Registers an attribute. This allows a developer to use the data API
- but Elixir will register the data as an attribute automatically.
- By default, `vsn`, `behavior` and other Erlang attributes are
- automatically registered.
-
- ## Examples
-
- defmodule MyModule do
- Module.register_attribute __MODULE__, :custom_threshold_for_lib
- @custom_threshold_for_lib 10
- end
-
- """
- def register_attribute(module, new) do
- assert_not_compiled!(:register_attribute, module)
- table = data_table_for(module)
- old = ETS.lookup_element(table, :registered_attributes, 2)
- ETS.insert(table, { :registered_attributes, [new|old] })
- end
+ \n #{\x{ff}}
+ '''
+ def func(a, b \\ []), do: :ok
@doc false
- # Used internally to compile documentation. This function
- # is private and must be used only internally.
- def compile_doc(module, line, kind, pair) do
- case read_data(module, :doc) do
- match: nil
- # We simply discard nil
- match: doc
- result = add_doc(module, line, kind, pair, doc)
- merge_data(module, doc: nil)
- result
- end
+ def __before_compile__(_) do
+ :ok
end
+end
- ## Helpers
+# Structs
+defmodule Second.Module do
+ s = %Long.Module.Name{name: "Silly"}
+ %Long.Module.Name{s | height: {192, :cm}}
+ ".. #{%Long.Module.Name{s | height: {192, :cm}}} .."
+end
- defp kind_to_entry(:def), do: :public
- defp kind_to_entry(:defp), do: :private
- defp kind_to_entry(:defmacro), do: :macros
+# Types, pseudo-vars, attributes
+defmodule M do
+ @custom_attr :some_constant
- defp to_char_list(list) when is_list(list), do: list
- defp to_char_list(bin) when is_binary(bin), do: binary_to_list(bin)
+ @before_compile Long.Module.Name
- defp data_table_for(module) do
- list_to_atom Erlang.lists.concat([:d, module])
- end
+ @typedoc "This is a type"
+ @type typ :: integer
- defp function_table_for(module) do
- list_to_atom Erlang.lists.concat([:f, module])
- end
-
- defp docs_table_for(module) do
- list_to_atom Erlang.lists.concat([:o, module])
- end
-
- defp assert_not_compiled!(fun, module) do
- compiled?(module) ||
- raise ArgumentError, message:
- "could not call #{fun} on module #{module} because it was already compiled"
- end
-end \ No newline at end of file
+ @typedoc """
+ Another type
+ """
+ @opaque typtyp :: 1..10
+
+ @spec func(typ, typtyp) :: :ok | :fail
+ def func(a, b) do
+ a || b || :ok || :fail
+ Path.expand("..", __DIR__)
+ IO.inspect __ENV__
+ __NOTAPSEUDOVAR__ = 11
+ __MODULE__.func(b, a)
+ end
+
+ defmacro m() do
+ __CALLER__
+ end
+end
+
+# Functions
+anon = fn x, y, z ->
+ fn(a, b, c) ->
+ &(x + y - z * a / &1 + b + div(&2, c))
+ end
+end
+
+&Set.put(&1, &2) ; & Set.put(&1, &2) ; &( Set.put(&1, &1) )
+
+# Function calls
+anon.(1, 2, 3); self; hd([1,2,3])
+Kernel.spawn(fn -> :ok end)
+IO.ANSI.black
+
+# Control flow
+if :this do
+ :that
+else
+ :otherwise
+end
+
+pid = self
+receive do
+ {:EXIT, _} -> :done
+ {^pid, :_} -> nil
+ after 100 -> :no_luck
+end
+
+case __ENV__.line do
+ x when is_integer(x) -> x
+ x when x in 1..12 -> -x
+end
+
+cond do
+ false -> "too bad"
+ 4 > 5 -> "oops"
+ true -> nil
+end
+
+# Lexical scope modifiers
+import Kernel, except: [spawn: 1, +: 2, /: 2, Unless: 2]
+alias Long.Module.Name, as: N0men123_and4
+use Bitwise
+
+4 &&& 5
+2 <<< 3
+
+# Protocols
+defprotocol Useless do
+ def func1(this)
+ def func2(that)
+end
+
+defimpl Useless, for: Atom do
+end
+
+# Exceptions
+defmodule NotAnError do
+ defexception [:message]
+end
+
+raise NotAnError, message: "This is not an error"
diff --git a/tests/examplefiles/garcia-wachs.kk b/tests/examplefiles/garcia-wachs.kk
index f766e051..91a01fbe 100644
--- a/tests/examplefiles/garcia-wachs.kk
+++ b/tests/examplefiles/garcia-wachs.kk
@@ -1,9 +1,25 @@
-/* This is an example in the Koka Language of the Garcia-Wachs algorithm */
-module garcia-wachs
+// Koka language test module
-public fun main()
-{
- test().print
+// This module implements the GarsiaWachs algorithm.
+// It is an adaptation of the algorithm in ML as described by JeanChristophe Filli�tre:
+// in ''A functional implementation of the GarsiaWachs algorithm. (functional pearl). ML workshop 2008, pages 91--96''.
+// See: http://www.lri.fr/~filliatr/publis/gwWml08.pdf
+//
+// The algorithm is interesting since it uses mutable references shared between a list and tree but the
+// side effects are not observable from outside. Koka automatically infers that the final algorithm is pure.
+// Note: due to a current limitation in the divergence analysis, koka cannot yet infer that mutually recursive
+// definitions in "insert" and "extract" are terminating and the final algorithm still has a divergence effect.
+// However, koka does infer that no other effect (i.e. an exception due to a partial match) can occur.
+module garcsiaWachs
+
+import test = qualified std/flags
+
+# pre processor test
+
+public function main() {
+ wlist = Cons1(('a',3), [('b',2),('c',1),('d',4),('e',5)])
+ tree = wlist.garsiaWachs()
+ tree.show.println()
}
//----------------------------------------------------
@@ -14,10 +30,9 @@ public type tree<a> {
con Node(left :tree<a>, right :tree<a>)
}
-fun show( t : tree<char> ) : string
-{
+function show( t : tree<char> ) : string {
match(t) {
- Leaf(c) -> Core.show(c)
+ Leaf(c) -> core/show(c)
Node(l,r) -> "Node(" + show(l) + "," + show(r) + ")"
}
}
@@ -30,23 +45,21 @@ public type list1<a> {
Cons1( head : a, tail : list<a> )
}
-
-fun map( xs, f ) {
+function map( xs, f ) {
val Cons1(y,ys) = xs
- return Cons1(f(y), Core.map(ys,f))
+ return Cons1(f(y), core/map(ys,f))
}
-fun zip( xs :list1<a>, ys :list1<b> ) : list1<(a,b)> {
+function zip( xs :list1<a>, ys :list1<b> ) : list1<(a,b)> {
Cons1( (xs.head, ys.head), zip(xs.tail, ys.tail))
}
-
//----------------------------------------------------
// Phase 1
//----------------------------------------------------
-fun insert( after : list<(tree<a>,int)>, t : (tree<a>,int), before : list<(tree<a>,int)> ) : div tree<a>
+function insert( after : list<(tree<a>,int)>, t : (tree<a>,int), before : list<(tree<a>,int)> ) : div tree<a>
{
match(before) {
Nil -> extract( [], Cons1(t,after) )
@@ -60,7 +73,7 @@ fun insert( after : list<(tree<a>,int)>, t : (tree<a>,int), before : list<(tree<
}
}
-fun extract( before : list<(tree<a>,int)>, after : list1<(tree<a>,int)> ) : div tree<a>
+function extract( before : list<(tree<a>,int)>, after : list1<(tree<a>,int)> ) : div tree<a>
{
val Cons1((t1,w1) as x, xs ) = after
match(xs) {
@@ -75,25 +88,24 @@ fun extract( before : list<(tree<a>,int)>, after : list1<(tree<a>,int)> ) : div
}
}
-
-
-fun balance( xs : list1<(tree<a>,int)> ) : div tree<a>
-{
+function balance( xs : list1<(tree<a>,int)> ) : div tree<a> {
extract( [], xs )
}
-fun mark( depth :int, t :tree<(a,ref<h,int>)> ) : <write<h>> ()
-{
+//----------------------------------------------------
+// Phase 2
+//----------------------------------------------------
+
+function mark( depth :int, t :tree<(a,ref<h,int>)> ) : <write<h>> () {
match(t) {
Leaf((_,d)) -> d := depth
Node(l,r) -> { mark(depth+1,l); mark(depth+1,r) }
}
}
-
-fun build( depth :int, xs :list1<(a,ref<h,int>)> ) : <read<h>,div> (tree<a>,list<(a,ref<h,int>)>)
+function build( depth :int, xs :list1<(a,ref<h,int>)> ) : <read<h>,div> (tree<a>,list<(a,ref<h,int>)>)
{
- if (!xs.head.snd == depth) return (Leaf(xs.head.fst), xs.tail)
+ if (!(xs.head.snd) == depth) return (Leaf(xs.head.fst), xs.tail)
l = build(depth+1, xs)
match(l.snd) {
@@ -105,13 +117,11 @@ fun build( depth :int, xs :list1<(a,ref<h,int>)> ) : <read<h>,div> (tree<a>,list
}
}
-public fun test() {
- wlist = Cons1(('a',3), [('b',2),('c',1),('d',4),('e',5)])
- tree = wlist.garciawachs()
- tree.show()
-}
+//----------------------------------------------------
+// Main
+//----------------------------------------------------
-public fun garciawachs( xs : list1<(a,int)> ) : div tree<a>
+public function garsiaWachs( xs : list1<(a,int)> ) : div tree<a>
{
refs = xs.map(fst).map( fun(x) { (x, ref(0)) } )
wleafs = zip( refs.map(Leaf), xs.map(snd) )
diff --git a/tests/examplefiles/grammar-test.p6 b/tests/examplefiles/grammar-test.p6
new file mode 100644
index 00000000..28107f3e
--- /dev/null
+++ b/tests/examplefiles/grammar-test.p6
@@ -0,0 +1,22 @@
+token pod_formatting_code {
+ $<code>=<[A..Z]>
+ '<' { $*POD_IN_FORMATTINGCODE := 1 }
+ $<content>=[ <!before '>'> <pod_string_character> ]+
+ '>' { $*POD_IN_FORMATTINGCODE := 0 }
+}
+
+token pod_string {
+ <pod_string_character>+
+}
+
+token something:sym«<» {
+ <!>
+}
+
+token name {
+ <!>
+}
+
+token comment:sym<#> {
+ '#' {} \N*
+}
diff --git a/tests/examplefiles/hash_syntax.rb b/tests/examplefiles/hash_syntax.rb
new file mode 100644
index 00000000..35b27723
--- /dev/null
+++ b/tests/examplefiles/hash_syntax.rb
@@ -0,0 +1,5 @@
+{ :old_syntax => 'ok' }
+{ 'stings as key' => 'should be ok' }
+{ new_syntax: 'broken until now' }
+{ withoutunderscore: 'should be ok' }
+{ _underscoreinfront: 'might be ok, if I understand the pygments code correct' }
diff --git a/tests/examplefiles/hello.at b/tests/examplefiles/hello.at
new file mode 100644
index 00000000..23af2f2d
--- /dev/null
+++ b/tests/examplefiles/hello.at
@@ -0,0 +1,6 @@
+def me := object: {
+ def name := "Kevin";
+ def sayHello(peerName) {
+ system.println(peerName + " says hello!");
+ };
+};
diff --git a/tests/examplefiles/hello.golo b/tests/examplefiles/hello.golo
new file mode 100644
index 00000000..7e8ca214
--- /dev/null
+++ b/tests/examplefiles/hello.golo
@@ -0,0 +1,5 @@
+module hello.World
+
+function main = |args| {
+ println("Hello world!")
+}
diff --git a/tests/examplefiles/hello.lsl b/tests/examplefiles/hello.lsl
new file mode 100644
index 00000000..61697e7f
--- /dev/null
+++ b/tests/examplefiles/hello.lsl
@@ -0,0 +1,12 @@
+default
+{
+ state_entry()
+ {
+ llSay(0, "Hello, Avatar!");
+ }
+
+ touch_start(integer total_number)
+ {
+ llSay(0, "Touched.");
+ }
+}
diff --git a/tests/examplefiles/File.hy b/tests/examplefiles/hybris_File.hy
index 9c86c641..9c86c641 100644
--- a/tests/examplefiles/File.hy
+++ b/tests/examplefiles/hybris_File.hy
diff --git a/tests/examplefiles/mg_sample.pro b/tests/examplefiles/idl_sample.pro
index 814d510d..814d510d 100644
--- a/tests/examplefiles/mg_sample.pro
+++ b/tests/examplefiles/idl_sample.pro
diff --git a/tests/examplefiles/iex_example b/tests/examplefiles/iex_example
new file mode 100644
index 00000000..22407e4e
--- /dev/null
+++ b/tests/examplefiles/iex_example
@@ -0,0 +1,23 @@
+iex> :" multi
+...> line ' \s \123 \x20
+...> atom"
+:" multi\n line ' S \natom"
+
+iex(1)> <<"hello"::binary, c :: utf8, x::[4, unit(2)]>> = "hello™1"
+"hello™1"
+
+iex(2)> c
+8482
+
+iex> 1 + :atom
+** (ArithmeticError) bad argument in arithmetic expression
+ :erlang.+(1, :atom)
+
+iex(3)> 1 +
+...(3)> 2 +
+...(3)> 3
+6
+
+iex> IO.puts "Hello world"
+Hello world
+:ok
diff --git a/tests/examplefiles/import.hs b/tests/examplefiles/import.hs
deleted file mode 100644
index 09058ae6..00000000
--- a/tests/examplefiles/import.hs
+++ /dev/null
@@ -1,4 +0,0 @@
-import "mtl" Control.Monad.Trans
-
-main :: IO ()
-main = putStrLn "hello world"
diff --git a/tests/examplefiles/inet_pton6.dg b/tests/examplefiles/inet_pton6.dg
index 4104b3e7..3813d5b8 100644
--- a/tests/examplefiles/inet_pton6.dg
+++ b/tests/examplefiles/inet_pton6.dg
@@ -1,5 +1,5 @@
-re = import!
-sys = import!
+import '/re'
+import '/sys'
# IPv6address = hexpart [ ":" IPv4address ]
@@ -20,7 +20,7 @@ addrv6 = re.compile $ r'(?i)(?:{})(?::{})?$'.format hexpart addrv4
#
# :return: a decimal integer
#
-base_n = (q digits) -> foldl (x y) -> (x * q + y) 0 digits
+base_n = q digits -> foldl (x y -> x * q + y) 0 digits
# Parse a sequence of hexadecimal numbers
@@ -29,7 +29,7 @@ base_n = (q digits) -> foldl (x y) -> (x * q + y) 0 digits
#
# :return: an iterable of Python ints
#
-unhex = q -> q and map p -> (int p 16) (q.split ':')
+unhex = q -> q and map (p -> int p 16) (q.split ':')
# Parse an IPv6 address as specified in RFC 4291.
@@ -39,33 +39,33 @@ unhex = q -> q and map p -> (int p 16) (q.split ':')
# :return: an integer which, written in binary form, points to the same node.
#
inet_pton6 = address ->
- raise $ ValueError 'not a valid IPv6 address' if not (match = addrv6.match address)
+ not (match = addrv6.match address) => raise $ ValueError 'not a valid IPv6 address'
start, end, *ipv4 = match.groups!
is_ipv4 = not $ None in ipv4
shift = (7 - start.count ':' - 2 * is_ipv4) * 16
- raise $ ValueError 'not a valid IPv6 address' if (end is None and shift) or shift < 0
+ (end is None and shift) or shift < 0 => raise $ ValueError 'not a valid IPv6 address'
hexaddr = (base_n 0x10000 (unhex start) << shift) + base_n 0x10000 (unhex $ end or '')
- (hexaddr << 32) + base_n 0x100 (map int ipv4) if is_ipv4 else hexaddr
+ if (is_ipv4 => (hexaddr << 32) + base_n 0x100 (map int ipv4)) (otherwise => hexaddr)
-inet6_type = q -> switch
- not q = 'unspecified'
- q == 1 = 'loopback'
- (q >> 32) == 0x000000000000ffff = 'IPv4-mapped'
- (q >> 64) == 0xfe80000000000000 = 'link-local'
- (q >> 120) != 0x00000000000000ff = 'general unicast'
- (q >> 112) % (1 << 4) == 0x0000000000000000 = 'multicast w/ reserved scope value'
- (q >> 112) % (1 << 4) == 0x000000000000000f = 'multicast w/ reserved scope value'
- (q >> 112) % (1 << 4) == 0x0000000000000001 = 'interface-local multicast'
- (q >> 112) % (1 << 4) == 0x0000000000000004 = 'admin-local multicast'
- (q >> 112) % (1 << 4) == 0x0000000000000005 = 'site-local multicast'
- (q >> 112) % (1 << 4) == 0x0000000000000008 = 'organization-local multicast'
- (q >> 112) % (1 << 4) == 0x000000000000000e = 'global multicast'
- (q >> 112) % (1 << 4) != 0x0000000000000002 = 'multicast w/ unknown scope value'
- (q >> 24) % (1 << 112) == 0x00000000000001ff = 'solicited-node multicast'
- True = 'link-local multicast'
+inet6_type = q -> if
+ q == 0 => 'unspecified'
+ q == 1 => 'loopback'
+ (q >> 32) == 0x000000000000ffff => 'IPv4-mapped'
+ (q >> 64) == 0xfe80000000000000 => 'link-local'
+ (q >> 120) != 0x00000000000000ff => 'general unicast'
+ (q >> 112) % (1 << 4) == 0x0000000000000000 => 'multicast w/ reserved scope value'
+ (q >> 112) % (1 << 4) == 0x000000000000000f => 'multicast w/ reserved scope value'
+ (q >> 112) % (1 << 4) == 0x0000000000000001 => 'interface-local multicast'
+ (q >> 112) % (1 << 4) == 0x0000000000000004 => 'admin-local multicast'
+ (q >> 112) % (1 << 4) == 0x0000000000000005 => 'site-local multicast'
+ (q >> 112) % (1 << 4) == 0x0000000000000008 => 'organization-local multicast'
+ (q >> 112) % (1 << 4) == 0x000000000000000e => 'global multicast'
+ (q >> 112) % (1 << 4) != 0x0000000000000002 => 'multicast w/ unknown scope value'
+ (q >> 24) % (1 << 112) == 0x00000000000001ff => 'solicited-node multicast'
+ otherwise => 'link-local multicast'
-print $ (x -> (inet6_type x, hex x)) $ inet_pton6 $ sys.stdin.read!.strip!
+print $ (x -> inet6_type x, hex x) $ inet_pton6 $ sys.stdin.read!.strip!
diff --git a/tests/examplefiles/interp.scala b/tests/examplefiles/interp.scala
new file mode 100644
index 00000000..4131b75e
--- /dev/null
+++ b/tests/examplefiles/interp.scala
@@ -0,0 +1,10 @@
+val n = 123;
+val a = s"n=$n";
+val a2 = s"n=$n''";
+val b = s"""n=$n""";
+val c = f"n=$n%f";
+val d = f"""n=$n%f""";
+val d2 = s"""a"""";
+val e = s"abc\u00e9";
+val f = s"a${n}b";
+val g = s"a${n + 1}b";
diff --git a/tests/examplefiles/language.hy b/tests/examplefiles/language.hy
new file mode 100644
index 00000000..9768c39c
--- /dev/null
+++ b/tests/examplefiles/language.hy
@@ -0,0 +1,165 @@
+;;;; This contains some of the core Hy functions used
+;;;; to make functional programming slightly easier.
+;;;;
+
+
+(defn _numeric-check [x]
+ (if (not (numeric? x))
+ (raise (TypeError (.format "{0!r} is not a number" x)))))
+
+(defn cycle [coll]
+ "Yield an infinite repetition of the items in coll"
+ (setv seen [])
+ (for [x coll]
+ (yield x)
+ (.append seen x))
+ (while seen
+ (for [x seen]
+ (yield x))))
+
+(defn dec [n]
+ "Decrement n by 1"
+ (_numeric-check n)
+ (- n 1))
+
+(defn distinct [coll]
+ "Return a generator from the original collection with duplicates
+ removed"
+ (let [[seen []] [citer (iter coll)]]
+ (for [val citer]
+ (if (not_in val seen)
+ (do
+ (yield val)
+ (.append seen val))))))
+
+(defn drop [count coll]
+ "Drop `count` elements from `coll` and yield back the rest"
+ (let [[citer (iter coll)]]
+ (try (for [i (range count)]
+ (next citer))
+ (catch [StopIteration]))
+ citer))
+
+(defn even? [n]
+ "Return true if n is an even number"
+ (_numeric-check n)
+ (= (% n 2) 0))
+
+(defn filter [pred coll]
+ "Return all elements from `coll` that pass `pred`"
+ (let [[citer (iter coll)]]
+ (for [val citer]
+ (if (pred val)
+ (yield val)))))
+
+(defn inc [n]
+ "Increment n by 1"
+ (_numeric-check n)
+ (+ n 1))
+
+(defn instance? [klass x]
+ (isinstance x klass))
+
+(defn iterable? [x]
+ "Return true if x is iterable"
+ (try (do (iter x) true)
+ (catch [Exception] false)))
+
+(defn iterate [f x]
+ (setv val x)
+ (while true
+ (yield val)
+ (setv val (f val))))
+
+(defn iterator? [x]
+ "Return true if x is an iterator"
+ (try (= x (iter x))
+ (catch [TypeError] false)))
+
+(defn neg? [n]
+ "Return true if n is < 0"
+ (_numeric-check n)
+ (< n 0))
+
+(defn none? [x]
+ "Return true if x is None"
+ (is x None))
+
+(defn numeric? [x]
+ (import numbers)
+ (instance? numbers.Number x))
+
+(defn nth [coll index]
+ "Return nth item in collection or sequence, counting from 0"
+ (if (not (neg? index))
+ (if (iterable? coll)
+ (try (first (list (take 1 (drop index coll))))
+ (catch [IndexError] None))
+ (try (get coll index)
+ (catch [IndexError] None)))
+ None))
+
+(defn odd? [n]
+ "Return true if n is an odd number"
+ (_numeric-check n)
+ (= (% n 2) 1))
+
+(defn pos? [n]
+ "Return true if n is > 0"
+ (_numeric_check n)
+ (> n 0))
+
+(defn remove [pred coll]
+ "Return coll with elements removed that pass `pred`"
+ (let [[citer (iter coll)]]
+ (for [val citer]
+ (if (not (pred val))
+ (yield val)))))
+
+(defn repeat [x &optional n]
+ "Yield x forever or optionally n times"
+ (if (none? n)
+ (setv dispatch (fn [] (while true (yield x))))
+ (setv dispatch (fn [] (for [_ (range n)] (yield x)))))
+ (dispatch))
+
+(defn repeatedly [func]
+ "Yield result of running func repeatedly"
+ (while true
+ (yield (func))))
+
+(defn take [count coll]
+ "Take `count` elements from `coll`, or the whole set if the total
+ number of entries in `coll` is less than `count`."
+ (let [[citer (iter coll)]]
+ (for [_ (range count)]
+ (yield (next citer)))))
+
+(defn take-nth [n coll]
+ "Return every nth member of coll
+ raises ValueError for (not (pos? n))"
+ (if (pos? n)
+ (let [[citer (iter coll)] [skip (dec n)]]
+ (for [val citer]
+ (yield val)
+ (for [_ (range skip)]
+ (next citer))))
+ (raise (ValueError "n must be positive"))))
+
+(defn take-while [pred coll]
+ "Take all elements while `pred` is true"
+ (let [[citer (iter coll)]]
+ (for [val citer]
+ (if (pred val)
+ (yield val)
+ (break)))))
+
+(defn zero? [n]
+ "Return true if n is 0"
+ (_numeric_check n)
+ (= n 0))
+
+(def *exports* ["cycle" "dec" "distinct" "drop" "even?" "filter" "inc"
+ "instance?" "iterable?" "iterate" "iterator?" "neg?"
+ "none?" "nth" "numeric?" "odd?" "pos?" "remove" "repeat"
+ "repeatedly" "take" "take_nth" "take_while" "zero?"])
diff --git a/tests/examplefiles/limbo.b b/tests/examplefiles/limbo.b
new file mode 100644
index 00000000..e55a0a62
--- /dev/null
+++ b/tests/examplefiles/limbo.b
@@ -0,0 +1,456 @@
+implement Ninewin;
+include "sys.m";
+ sys: Sys;
+include "draw.m";
+ draw: Draw;
+ Image, Display, Pointer: import draw;
+include "arg.m";
+include "keyboard.m";
+include "tk.m";
+include "wmclient.m";
+ wmclient: Wmclient;
+ Window: import wmclient;
+include "sh.m";
+ sh: Sh;
+
+# run a p9 graphics program (default rio) under inferno wm,
+# making available to it:
+# /dev/winname - naming the current inferno window (changing on resize)
+# /dev/mouse - pointer file + resize events; write to change position
+# /dev/cursor - change appearance of cursor.
+# /dev/draw - inferno draw device
+# /dev/cons - read keyboard events, write to 9win stdout.
+
+Ninewin: module {
+ init: fn(ctxt: ref Draw->Context, argv: list of string);
+};
+winname: string;
+
+init(ctxt: ref Draw->Context, argv: list of string)
+{
+ size := Draw->Point(500, 500);
+ sys = load Sys Sys->PATH;
+ draw = load Draw Draw->PATH;
+ wmclient = load Wmclient Wmclient->PATH;
+ wmclient->init();
+ sh = load Sh Sh->PATH;
+
+ buts := Wmclient->Resize;
+ if(ctxt == nil){
+ ctxt = wmclient->makedrawcontext();
+ buts = Wmclient->Plain;
+ }
+ arg := load Arg Arg->PATH;
+ arg->init(argv);
+ arg->setusage("9win [-s] [-x width] [-y height]");
+ exportonly := 0;
+ while(((opt := arg->opt())) != 0){
+ case opt {
+ 's' =>
+ exportonly = 1;
+ 'x' =>
+ size.x = int arg->earg();
+ 'y' =>
+ size.y = int arg->earg();
+ * =>
+ arg->usage();
+ }
+ }
+ if(size.x < 1 || size.y < 1)
+ arg->usage();
+ argv = arg->argv();
+ if(argv != nil && hd argv == "-s"){
+ exportonly = 1;
+ argv = tl argv;
+ }
+ if(argv == nil && !exportonly)
+ argv = "rio" :: nil;
+ if(argv != nil && exportonly){
+ sys->fprint(sys->fildes(2), "9win: no command allowed with -s flag\n");
+ raise "fail:usage";
+ }
+ title := "9win";
+ if(!exportonly)
+ title += " " + hd argv;
+ w := wmclient->window(ctxt, title, buts);
+ w.reshape(((0, 0), size));
+ w.onscreen(nil);
+ if(w.image == nil){
+ sys->fprint(sys->fildes(2), "9win: cannot get image to draw on\n");
+ raise "fail:no window";
+ }
+
+ sys->pctl(Sys->FORKNS|Sys->NEWPGRP, nil);
+ ld := "/n/9win";
+ if(sys->bind("#s", ld, Sys->MREPL) == -1 &&
+ sys->bind("#s", ld = "/n/local", Sys->MREPL) == -1){
+ sys->fprint(sys->fildes(2), "9win: cannot bind files: %r\n");
+ raise "fail:error";
+ }
+ w.startinput("kbd" :: "ptr" :: nil);
+ spawn ptrproc(rq := chan of Sys->Rread, ptr := chan[10] of ref Pointer, reshape := chan[1] of int);
+
+
+ fwinname := sys->file2chan(ld, "winname");
+ fconsctl := sys->file2chan(ld, "consctl");
+ fcons := sys->file2chan(ld, "cons");
+ fmouse := sys->file2chan(ld, "mouse");
+ fcursor := sys->file2chan(ld, "cursor");
+ if(!exportonly){
+ spawn run(sync := chan of string, w.ctl, ld, argv);
+ if((e := <-sync) != nil){
+ sys->fprint(sys->fildes(2), "9win: %s", e);
+ raise "fail:error";
+ }
+ }
+ spawn serveproc(w, rq, fwinname, fconsctl, fcons, fmouse, fcursor);
+ if(!exportonly){
+ # handle events synchronously so that we don't get a "killed" message
+ # from the shell.
+ handleevents(w, ptr, reshape);
+ }else{
+ spawn handleevents(w, ptr, reshape);
+ sys->bind(ld, "/dev", Sys->MBEFORE);
+ export(sys->fildes(0), w.ctl);
+ }
+}
+
+handleevents(w: ref Window, ptr: chan of ref Pointer, reshape: chan of int)
+{
+ for(;;)alt{
+ c := <-w.ctxt.ctl or
+ c = <-w.ctl =>
+ e := w.wmctl(c);
+ if(e != nil)
+ sys->fprint(sys->fildes(2), "9win: ctl error: %s\n", e);
+ if(e == nil && c != nil && c[0] == '!'){
+ alt{
+ reshape <-= 1 =>
+ ;
+ * =>
+ ;
+ }
+ winname = nil;
+ }
+ p := <-w.ctxt.ptr =>
+ if(w.pointer(*p) == 0){
+ # XXX would block here if client isn't reading mouse... but we do want to
+ # extert back-pressure, which conflicts.
+ alt{
+ ptr <-= p =>
+ ;
+ * =>
+ ; # sys->fprint(sys->fildes(2), "9win: discarding mouse event\n");
+ }
+ }
+ }
+}
+
+serveproc(w: ref Window, mouserq: chan of Sys->Rread, fwinname, fconsctl, fcons, fmouse, fcursor: ref Sys->FileIO)
+{
+ winid := 0;
+ krc: list of Sys->Rread;
+ ks: string;
+
+ for(;;)alt {
+ c := <-w.ctxt.kbd =>
+ ks[len ks] = inf2p9key(c);
+ if(krc != nil){
+ hd krc <-= (array of byte ks, nil);
+ ks = nil;
+ krc = tl krc;
+ }
+ (nil, d, nil, wc) := <-fcons.write =>
+ if(wc != nil){
+ sys->write(sys->fildes(1), d, len d);
+ wc <-= (len d, nil);
+ }
+ (nil, nil, nil, rc) := <-fcons.read =>
+ if(rc != nil){
+ if(ks != nil){
+ rc <-= (array of byte ks, nil);
+ ks = nil;
+ }else
+ krc = rc :: krc;
+ }
+ (offset, nil, nil, rc) := <-fwinname.read =>
+ if(rc != nil){
+ if(winname == nil){
+ winname = sys->sprint("noborder.9win.%d", winid++);
+ if(w.image.name(winname, 1) == -1){
+ sys->fprint(sys->fildes(2), "9win: namewin %q failed: %r", winname);
+ rc <-= (nil, "namewin failure");
+ break;
+ }
+ }
+ d := array of byte winname;
+ if(offset < len d)
+ d = d[offset:];
+ else
+ d = nil;
+ rc <-= (d, nil);
+ }
+ (nil, nil, nil, wc) := <-fwinname.write =>
+ if(wc != nil)
+ wc <-= (-1, "permission denied");
+ (nil, nil, nil, rc) := <-fconsctl.read =>
+ if(rc != nil)
+ rc <-= (nil, "permission denied");
+ (nil, d, nil, wc) := <-fconsctl.write =>
+ if(wc != nil){
+ if(string d != "rawon")
+ wc <-= (-1, "cannot change console mode");
+ else
+ wc <-= (len d, nil);
+ }
+ (nil, nil, nil, rc) := <-fmouse.read =>
+ if(rc != nil)
+ mouserq <-= rc;
+ (nil, d, nil, wc) := <-fmouse.write =>
+ if(wc != nil){
+ e := cursorset(w, string d);
+ if(e == nil)
+ wc <-= (len d, nil);
+ else
+ wc <-= (-1, e);
+ }
+ (nil, nil, nil, rc) := <-fcursor.read =>
+ if(rc != nil)
+ rc <-= (nil, "permission denied");
+ (nil, d, nil, wc) := <-fcursor.write =>
+ if(wc != nil){
+ e := cursorswitch(w, d);
+ if(e == nil)
+ wc <-= (len d, nil);
+ else
+ wc <-= (-1, e);
+ }
+ }
+}
+
+ptrproc(rq: chan of Sys->Rread, ptr: chan of ref Pointer, reshape: chan of int)
+{
+ rl: list of Sys->Rread;
+ c := ref Pointer(0, (0, 0), 0);
+ for(;;){
+ ch: int;
+ alt{
+ p := <-ptr =>
+ ch = 'm';
+ c = p;
+ <-reshape =>
+ ch = 'r';
+ rc := <-rq =>
+ rl = rc :: rl;
+ continue;
+ }
+ if(rl == nil)
+ rl = <-rq :: rl;
+ hd rl <-= (sys->aprint("%c%11d %11d %11d %11d ", ch, c.xy.x, c.xy.y, c.buttons, c.msec), nil);
+ rl = tl rl;
+ }
+}
+
+cursorset(w: ref Window, m: string): string
+{
+ if(m == nil || m[0] != 'm')
+ return "invalid mouse message";
+ x := int m[1:];
+ for(i := 1; i < len m; i++)
+ if(m[i] == ' '){
+ while(m[i] == ' ')
+ i++;
+ break;
+ }
+ if(i == len m)
+ return "invalid mouse message";
+ y := int m[i:];
+ return w.wmctl(sys->sprint("ptr %d %d", x, y));
+}
+
+cursorswitch(w: ref Window, d: array of byte): string
+{
+ Hex: con "0123456789abcdef";
+ if(len d != 2*4+64)
+ return w.wmctl("cursor");
+ hot := Draw->Point(bglong(d, 0*4), bglong(d, 1*4));
+ s := sys->sprint("cursor %d %d 16 32 ", hot.x, hot.y);
+ for(i := 2*4; i < len d; i++){
+ c := int d[i];
+ s[len s] = Hex[c >> 4];
+ s[len s] = Hex[c & 16rf];
+ }
+ return w.wmctl(s);
+}
+
+run(sync, ctl: chan of string, ld: string, argv: list of string)
+{
+ Rcmeta: con "|<>&^*[]?();";
+ sys->pctl(Sys->FORKNS, nil);
+ if(sys->bind("#₪", "/srv", Sys->MCREATE) == -1){
+ sync <-= sys->sprint("cannot bind srv device: %r");
+ exit;
+ }
+ srvname := "/srv/9win."+string sys->pctl(0, nil); # XXX do better.
+ fd := sys->create(srvname, Sys->ORDWR, 8r600);
+ if(fd == nil){
+ sync <-= sys->sprint("cannot create %s: %r", srvname);
+ exit;
+ }
+ sync <-= nil;
+ spawn export(fd, ctl);
+ sh->run(nil, "os" ::
+ "rc" :: "-c" ::
+ "mount "+srvname+" /mnt/term;"+
+ "rm "+srvname+";"+
+ "bind -b /mnt/term"+ld+" /dev;"+
+ "bind /mnt/term/dev/draw /dev/draw ||"+
+ "bind -a /mnt/term/dev /dev;"+
+ quotedc("cd"::"/mnt/term"+cwd()::nil, Rcmeta)+";"+
+ quotedc(argv, Rcmeta)+";"::
+ nil
+ );
+}
+
+export(fd: ref Sys->FD, ctl: chan of string)
+{
+ sys->export(fd, "/", Sys->EXPWAIT);
+ ctl <-= "exit";
+}
+
+inf2p9key(c: int): int
+{
+ KF: import Keyboard;
+
+ P9KF: con 16rF000;
+ Spec: con 16rF800;
+ Khome: con P9KF|16r0D;
+ Kup: con P9KF|16r0E;
+ Kpgup: con P9KF|16r0F;
+ Kprint: con P9KF|16r10;
+ Kleft: con P9KF|16r11;
+ Kright: con P9KF|16r12;
+ Kdown: con Spec|16r00;
+ Kview: con Spec|16r00;
+ Kpgdown: con P9KF|16r13;
+ Kins: con P9KF|16r14;
+ Kend: con P9KF|16r18;
+ Kalt: con P9KF|16r15;
+ Kshift: con P9KF|16r16;
+ Kctl: con P9KF|16r17;
+
+ case c {
+ Keyboard->LShift =>
+ return Kshift;
+ Keyboard->LCtrl =>
+ return Kctl;
+ Keyboard->LAlt =>
+ return Kalt;
+ Keyboard->Home =>
+ return Khome;
+ Keyboard->End =>
+ return Kend;
+ Keyboard->Up =>
+ return Kup;
+ Keyboard->Down =>
+ return Kdown;
+ Keyboard->Left =>
+ return Kleft;
+ Keyboard->Right =>
+ return Kright;
+ Keyboard->Pgup =>
+ return Kpgup;
+ Keyboard->Pgdown =>
+ return Kpgdown;
+ Keyboard->Ins =>
+ return Kins;
+
+ # function keys
+ KF|1 or
+ KF|2 or
+ KF|3 or
+ KF|4 or
+ KF|5 or
+ KF|6 or
+ KF|7 or
+ KF|8 or
+ KF|9 or
+ KF|10 or
+ KF|11 or
+ KF|12 =>
+ return (c - KF) + P9KF;
+ }
+ return c;
+}
+
+cwd(): string
+{
+ return sys->fd2path(sys->open(".", Sys->OREAD));
+}
+
+# from string.b, waiting for declaration to be uncommented.
+quotedc(argv: list of string, cl: string): string
+{
+ s := "";
+ while (argv != nil) {
+ arg := hd argv;
+ for (i := 0; i < len arg; i++) {
+ c := arg[i];
+ if (c == ' ' || c == '\t' || c == '\n' || c == '\'' || in(c, cl))
+ break;
+ }
+ if (i < len arg || arg == nil) {
+ s += "'" + arg[0:i];
+ for (; i < len arg; i++) {
+ if (arg[i] == '\'')
+ s[len s] = '\'';
+ s[len s] = arg[i];
+ }
+ s[len s] = '\'';
+ } else
+ s += arg;
+ if (tl argv != nil)
+ s[len s] = ' ';
+ argv = tl argv;
+ }
+ return s;
+}
+
+in(c: int, s: string): int
+{
+ n := len s;
+ if(n == 0)
+ return 0;
+ ans := 0;
+ negate := 0;
+ if(s[0] == '^') {
+ negate = 1;
+ s = s[1:];
+ n--;
+ }
+ for(i := 0; i < n; i++) {
+ if(s[i] == '-' && i > 0 && i < n-1) {
+ if(c >= s[i-1] && c <= s[i+1]) {
+ ans = 1;
+ break;
+ }
+ i++;
+ }
+ else
+ if(c == s[i]) {
+ ans = 1;
+ break;
+ }
+ }
+ if(negate)
+ ans = !ans;
+
+ # just to showcase labels
+skip:
+ return ans;
+}
+
+bglong(d: array of byte, i: int): int
+{
+ return int d[i] | (int d[i+1]<<8) | (int d[i+2]<<16) | (int d[i+3]<<24);
+}
diff --git a/tests/examplefiles/livescript-demo.ls b/tests/examplefiles/livescript-demo.ls
index 2ff68c63..03cbcc99 100644
--- a/tests/examplefiles/livescript-demo.ls
+++ b/tests/examplefiles/livescript-demo.ls
@@ -7,7 +7,9 @@ dashes-identifiers = ->
underscores_i$d = ->
/regexp1/
//regexp2//g
- 'strings' and "strings" and \strings
+ 'strings' and "strings" and \strings and \#$-"\'strings
+
+another-word-list = <[ more words ]>
[2 til 10]
|> map (* 2)
diff --git a/tests/examplefiles/main.cmake b/tests/examplefiles/main.cmake
index dac3da43..71dc3ce7 100644
--- a/tests/examplefiles/main.cmake
+++ b/tests/examplefiles/main.cmake
@@ -1,3 +1,5 @@
+CMAKE_MINIMUM_REQUIRED(VERSION 2.6 FATAL_ERROR)
+
SET( SOURCES back.c io.c main.c )
MESSAGE( ${SOURCES} ) # three arguments, prints "back.cio.cmain.c"
MESSAGE( "${SOURCES}" ) # one argument, prints "back.c;io.c;main.c"
diff --git a/tests/examplefiles/matlab_sample b/tests/examplefiles/matlab_sample
index 4f61afe8..bb00b517 100644
--- a/tests/examplefiles/matlab_sample
+++ b/tests/examplefiles/matlab_sample
@@ -28,3 +28,7 @@ y = exp(x);
{%
a block comment
%}
+
+function no_arg_func
+fprintf('%s\n', 'function with no args')
+end
diff --git a/tests/examplefiles/objc_example.m b/tests/examplefiles/objc_example.m
index cb5c0975..f3f85f65 100644
--- a/tests/examplefiles/objc_example.m
+++ b/tests/examplefiles/objc_example.m
@@ -1,25 +1,179 @@
-#import "Somefile.h"
+// Test various types of includes
+#import <Foundation/Foundation.h>
+# import <AppKit/AppKit.h>
+#import "stdio.h"
+#\
+ import \
+ "stdlib.h"
+# /*line1*/ \
+import /* line 2 */ \
+"stdlib.h" // line 3
-@implementation ABC
+// Commented out code with preprocessor
+#if 0
+#define MY_NUMBER 3
+#endif
-- (id)a:(B)b {
- return 1;
+ #\
+ if 1
+#define TEST_NUMBER 3
+#endif
+
+// Empty preprocessor
+#
+
+// Class forward declaration
+@class MyClass;
+
+// Empty classes
+@interface EmptyClass
+@end
+@interface EmptyClass2
+{
+}
+@end
+@interface EmptyClass3 : EmptyClass2
+{
+}
+@end
+
+// Custom class inheriting from built-in
+@interface MyClass : NSObject
+{
+@public
+ NSString *myString;
+ __weak NSString *_weakString;
+@protected
+ NSTextField *_textField;
+@private
+ NSDate *privateDate;
}
+// Various property aatributes
+@property(copy, readwrite, nonatomic) NSString *myString;
+@property(weak) NSString *weakString;
+@property(retain, strong, atomic) IBOutlet NSTextField *textField;
+
+// Class methods
++ (void)classMethod1:(NSString *)arg;
++ (void)classMethod2:(NSString *) arg; // Test space before arg
+
@end
-@implementation ABC
+typedef id B;
+
+#pragma mark MyMarker
-- (void)xyz;
+// MyClass.m
+// Class extension to declare private property
+@interface MyClass ()
+@property(retain) NSDate *privateDate;
+- (void)hiddenMethod;
+@end
+// Special category
+@interface MyClass (Special)
+@property(retain) NSDate *specialDate;
@end
-NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
- @"quattuor", @"four", @"quinque", @"five", @"sex", @"six", nil];
+@implementation MyClass
+@synthesize myString;
+@synthesize privateDate;
+
+- (id)a:(B)b {
+ /**
+ * C-style comment
+ */
+
+ // Selector keywords/types
+ SEL someMethod = @selector(hiddenMethod);
+
+ // Boolean types
+ Boolean b1 = FALSE;
+ BOOL b2 = NO;
+ bool b3 = true;
+
+ /**
+ * Number literals
+ */
+ // Int Literal
+ NSNumber *n1 = @( 1 );
+ // Method call
+ NSNumber *n2 = @( [b length] );
+ // Define variable
+ NSNumber *n3 = @( TEST_NUMBER );
+ // Arthimetic expression
+ NSNumber *n4 = @(1 + 2);
+ // From variable
+ int myInt = 5;
+ NSNumber *n5 = @(myInt);
+ // Nest expression
+ NSNumber *n6 = @(1 + (2 + 6.0));
+ // Bool literal
+ NSNumber *n7 = @NO;
+ // Bool expression
+ NSNumber *n8 = @(YES);
+ // Character
+ NSNumber *n9 = @'a';
+ // int
+ NSNumber *n10 = @123;
+ // unsigned
+ NSNumber *n11 = @1234U;
+ // long
+ NSNumber *n12 = @1234567890L;
+ // float
+ NSNumber *n13 = @3.14F;
+ // double
+ NSNumber *n14 = @3.14F;
+
+ // Array literals
+ NSArray *arr = @[ @"1", @"2" ];
+ arr = @[ @[ @"1", @"2" ], [arr lastObject] ];
+ [arr lastObject];
+ [@[ @"1", @"2" ] lastObject];
+
+ // Dictionary literals
+ NSDictionary *d = @{ @"key": @"value" };
+ [[d allKeys] lastObject];
+ [[@{ @"key": @"value" } allKeys] lastObject];
+ d = @{ @"key": @{ @"key": @"value" } };
+
+ [self hiddenMethod];
+ [b length];
+ [privateDate class];
+ NSDictionary *dictionary = [NSDictionary dictionaryWithObjectsAndKeys:
+ @"1", @"one", @"2", @"two", @"3", @"three", nil];
+
+ NSString *key;
+ for (key in dictionary) {
+ NSLog(@"Number: %@, Word: %@", key, [dictionary valueForKey:key]);
+ }
-NSString *key;
-for (key in dictionary) {
- NSLog(@"English: %@, Latin: %@", key, [dictionary valueForKey:key]);
+ // Blocks
+ int (^myBlock)(int arg1, int arg2);
+ NSString *(^myName)(NSString *) = ^(NSString *value) {
+ return value;
+ };
+
+ return nil;
+}
+
+- (void)hiddenMethod {
+ // Synchronized block
+ @synchronized(self) {
+ [myString retain];
+ [myString release];
+ }
}
++ (void)classMethod1:(NSString *)arg {}
++ (void)classMethod2:(NSString *) arg
+{
+ // Autorelease pool block
+ @autoreleasepool {
+ NSLog(@"Hello, World!");
+ }
+}
+
+@end
diff --git a/tests/examplefiles/objc_example2.m b/tests/examplefiles/objc_example2.m
deleted file mode 100644
index 8cd9b060..00000000
--- a/tests/examplefiles/objc_example2.m
+++ /dev/null
@@ -1,24 +0,0 @@
-// MyClass.h
-@interface MyClass : NSObject
-{
- NSString *value;
- NSTextField *textField;
-@private
- NSDate *lastModifiedDate;
-}
-@property(copy, readwrite) NSString *value;
-@property(retain) IBOutlet NSTextField *textField;
-@end
-
-// MyClass.m
-// Class extension to declare private property
-@interface MyClass ()
-@property(retain) NSDate *lastModifiedDate;
-@end
-
-@implementation MyClass
-@synthesize value;
-@synthesize textField;
-@synthesize lastModifiedDate;
-// implementation continues
-@end
diff --git a/tests/examplefiles/example.p b/tests/examplefiles/openedge_example
index e8c17e33..e8c17e33 100644
--- a/tests/examplefiles/example.p
+++ b/tests/examplefiles/openedge_example
diff --git a/tests/examplefiles/pawn_example b/tests/examplefiles/pawn_example
new file mode 100644
index 00000000..ee2ecca2
--- /dev/null
+++ b/tests/examplefiles/pawn_example
@@ -0,0 +1,25 @@
+{include.i}
+{nested.i {include.i}}
+
+&SCOPED-DEFINE MY_NAME "Abe"
+
+DEF VAR i AS INT NO-UNDO.
+i = 0xABE + 1337 / (1 * 1.00)
+
+def var clowercasetest as char no-undo.
+DEF VAR vardashtest AS DATETIME-TZ NO-UNDO.
+
+DEFINE TEMP-TABLE ttNames NO-UNDO
+ FIELD cName AS CHAR
+ INDEX IXPK_ttNames IS PRIMARY UNIQUE cName.
+
+/* One-line comment */
+/* Two-line
+ Comment */
+
+CREATE ttNames.
+ASSIGN ttNames.cName = {&MY_NAME}.
+
+FOR EACH ttNames:
+ MESSAGE "Hello, " + ttNames.cName + '!' VIEW-AS ALERT-BOX.
+END.
diff --git a/tests/examplefiles/py3tb_test.py3tb b/tests/examplefiles/py3tb_test.py3tb
new file mode 100644
index 00000000..706a540f
--- /dev/null
+++ b/tests/examplefiles/py3tb_test.py3tb
@@ -0,0 +1,4 @@
+ File "<stdin>", line 1
+ 1+
+ ^
+SyntaxError: invalid syntax
diff --git a/tests/examplefiles/pycon_test.pycon b/tests/examplefiles/pycon_test.pycon
index ff702864..9c4fc3d3 100644
--- a/tests/examplefiles/pycon_test.pycon
+++ b/tests/examplefiles/pycon_test.pycon
@@ -9,6 +9,9 @@ KeyboardInterrupt
>>> 1/0
Traceback (most recent call last):
-...
+ ...
ZeroDivisionError
+>>> 1/0 # this used to swallow the traceback
+Traceback (most recent call last):
+ ...
diff --git a/tests/examplefiles/qbasic_example b/tests/examplefiles/qbasic_example
new file mode 100644
index 00000000..27041af6
--- /dev/null
+++ b/tests/examplefiles/qbasic_example
@@ -0,0 +1,2 @@
+10 print RIGHT$("hi there", 5)
+20 goto 10
diff --git a/tests/examplefiles/r6rs-comments.scm b/tests/examplefiles/r6rs-comments.scm
new file mode 100644
index 00000000..cd5c3636
--- /dev/null
+++ b/tests/examplefiles/r6rs-comments.scm
@@ -0,0 +1,23 @@
+#!r6rs
+
+#|
+
+ The FACT procedure computes the factorial
+
+ of a non-negative integer.
+
+|#
+
+(define fact
+
+ (lambda (n)
+
+ ;; base case
+
+ (if (= n 0)
+
+ #;(= n 1)
+
+ 1 ; identity of *
+
+ (* n (fact (- n 1))))))
diff --git a/tests/examplefiles/robotframework.txt b/tests/examplefiles/robotframework_test.txt
index 63ba63e6..63ba63e6 100644
--- a/tests/examplefiles/robotframework.txt
+++ b/tests/examplefiles/robotframework_test.txt
diff --git a/tests/examplefiles/rql-queries.rql b/tests/examplefiles/rql-queries.rql
new file mode 100644
index 00000000..1d86df3c
--- /dev/null
+++ b/tests/examplefiles/rql-queries.rql
@@ -0,0 +1,34 @@
+Any N, N2 where N is Note, N2 is Note, N a_faire_par P1, P1 nom 'john', N2 a_faire_par P2, P2 nom 'jane' ;
+DISTINCT Any N, D, C, T, A ORDERBY D DESC LIMIT 40 where N is Note, N diem D, W is Workcase, W concerned_by N, N cost C, N text T, N author A, N diem <= today
+Bookmark B WHERE B owned_by G, G eid 5;
+Any X WHERE E eid 22762, NOT E is_in X, X modification_date D ORDERBY D DESC LIMIT 41;
+Any A, R, SUB ORDERBY R WHERE A is "Workcase", S is Division, S concerned_by A, A subject SUB, S eid 85, A ref R;
+Any D, T, L WHERE D is Document, A concerned_by D,A eid 14533, D title T, D location L;
+Any N,A,B,C,D ORDERBY A DESC WHERE N is Note, W concerned_by N, W eid 14533, N diem A,N author B,N text C,N cost D;
+Any X ORDERBY D DESC LIMIT 41 WHERE E eid 18134, NOT E concerned_by X, X modification_date D
+DISTINCT Any N, D, C, T, A ORDERBY D ASC LIMIT 40 WHERE N is Note, N diem D, P is Person, N to_be_contacted_by G, N cost C, N text T, N author A, G login "john";
+INSERT Person X: X surname "Doe", X firstname "John";
+Workcase W where W ref "ABCD12";
+Workcase W where W ref LIKE "AB%";
+Any X WHERE X X eid 53
+Any X WHERE X Document X occurence_of F, F class C, C name 'Comics' X owned_by U, U login 'syt' X available true
+Person P WHERE P work_for P, S name 'Acme', P interested_by T, T name 'training'
+Note N WHERE N written_on D, D day> (today -10), N written_by P, P name 'joe' or P name 'jack'
+Person P WHERE (P interested_by T, T name 'training') or (P city 'Paris')
+Any N, P WHERE X is Person, X name N, X first_name P
+String N, P WHERE X is Person, X name N, X first_name P
+INSERT Person X: X name 'widget'
+INSERT Person X, Person Y: X name 'foo', Y name 'nice', X friend Y
+INSERT Person X: X name 'foo', X friend Y WHERE name 'nice'
+SET X name 'bar', X first_name 'original' where X is Person X name 'foo'
+SET X know Y WHERE X friend Y
+DELETE Person X WHERE X name 'foo'
+DELETE X friend Y WHERE X is Person, X name 'foo'
+Any X WHERE X name LIKE '%lt'
+Any X WHERE X name IN ( 'joe', 'jack', 'william', 'averell')
+Any X, V WHERE X concerns P, P eid 42, X corrected_in V?
+Any C, P WHERE C is Card, P? documented_by C
+Point P where P abs X, P ord Y, P value X+Y
+Document X where X class C, C name 'Cartoon', X owned_by U, U login 'joe', X available true
+(Any X WHERE X is Document) UNION (Any X WHERE X is File)
+Any A,B WHERE A creation_date B WITH A BEING (Any X WHERE X is Document) UNION (Any X WHERE X is File)
diff --git a/tests/examplefiles/rust_example.rs b/tests/examplefiles/rust_example.rs
index 1c0a70c3..8c44af1d 100644
--- a/tests/examplefiles/rust_example.rs
+++ b/tests/examplefiles/rust_example.rs
@@ -11,6 +11,8 @@
// based on:
// http://shootout.alioth.debian.org/u32/benchmark.php?test=nbody&lang=java
+/* nest some /* comments */ */
+
extern mod std;
use core::os;
@@ -22,7 +24,7 @@ use core::os;
// an llvm intrinsic.
#[nolink]
extern mod libc {
- #[legacy_exports];
+ #![legacy_exports];
fn sqrt(n: float) -> float;
}
diff --git a/tests/examplefiles/scope.cirru b/tests/examplefiles/scope.cirru
new file mode 100644
index 00000000..728bcabf
--- /dev/null
+++ b/tests/examplefiles/scope.cirru
@@ -0,0 +1,43 @@
+
+-- https://github.com/Cirru/cirru-gopher/blob/master/code/scope.cr
+
+set a (int 2)
+
+print (self)
+
+set c (child)
+
+under c
+ under parent
+ print a
+
+print $ get c a
+
+set c x (int 3)
+print $ get c x
+
+set just-print $ code
+ print a
+
+print just-print
+
+eval (self) just-print
+eval just-print
+
+print (string "string with space")
+print (string "escapes \n \"\\")
+
+brackets ((((()))))
+
+"eval" $ string "eval"
+
+print (add $ (int 1) (int 2))
+
+print $ unwrap $
+ map (a $ int 1) (b $ int 2)
+
+print a
+ int 1
+ , b c
+ int 2
+ , d \ No newline at end of file
diff --git a/tests/examplefiles/sparql.rq b/tests/examplefiles/sparql.rq
new file mode 100644
index 00000000..caedfd14
--- /dev/null
+++ b/tests/examplefiles/sparql.rq
@@ -0,0 +1,23 @@
+# This is a test SPARQL query
+
+PREFIX foaf: <http://xmlns.com/foaf/0.1/>
+PREFIX ex: <http://example.org/>
+PREFIX xsd: <http://www.w3.org/2001/XMLSchema#>
+PREFIX dcterms: <http://purl.org/dc/terms/>
+
+SELECT ?person (COUNT(?nick) AS ?nickCount) {
+ ?person foaf:nick ?nick ;
+ foaf:lastName "Smith" ;
+ foaf:age "21"^^xsd:int ;
+ ex:title 'Mr' ; # single-quoted string
+ ex:height 1.80 ; # float
+ ex:distanceToSun +1.4e8 ; # float with exponent
+ ex:ownsACat true ;
+ dcterms:description "Someone with a cat called \"cat\"."@en .
+ OPTIONAL { ?person foaf:isPrimaryTopicOf ?page }
+ OPTIONAL { ?person foaf:name ?name
+ { ?person foaf:depiction ?img }
+ UNION
+ { ?person foaf:firstName ?firstN } }
+ FILTER ( bound(?page) || bound(?img) || bound(?firstN) )
+} GROUP BY ?person ORDER BY ?img
diff --git a/tests/examplefiles/swig_java.swg b/tests/examplefiles/swig_java.swg
new file mode 100644
index 00000000..6126a55e
--- /dev/null
+++ b/tests/examplefiles/swig_java.swg
@@ -0,0 +1,1329 @@
+/* -----------------------------------------------------------------------------
+ * java.swg
+ *
+ * Java typemaps
+ * ----------------------------------------------------------------------------- */
+
+%include <javahead.swg>
+
+/* The jni, jtype and jstype typemaps work together and so there should be one of each.
+ * The jni typemap contains the JNI type used in the JNI (C/C++) code.
+ * The jtype typemap contains the Java type used in the JNI intermediary class.
+ * The jstype typemap contains the Java type used in the Java proxy classes, type wrapper classes and module class. */
+
+/* Fragments */
+%fragment("SWIG_PackData", "header") {
+/* Pack binary data into a string */
+SWIGINTERN char * SWIG_PackData(char *c, void *ptr, size_t sz) {
+ static const char hex[17] = "0123456789abcdef";
+ register const unsigned char *u = (unsigned char *) ptr;
+ register const unsigned char *eu = u + sz;
+ for (; u != eu; ++u) {
+ register unsigned char uu = *u;
+ *(c++) = hex[(uu & 0xf0) >> 4];
+ *(c++) = hex[uu & 0xf];
+ }
+ return c;
+}
+}
+
+%fragment("SWIG_UnPackData", "header") {
+/* Unpack binary data from a string */
+SWIGINTERN const char * SWIG_UnpackData(const char *c, void *ptr, size_t sz) {
+ register unsigned char *u = (unsigned char *) ptr;
+ register const unsigned char *eu = u + sz;
+ for (; u != eu; ++u) {
+ register char d = *(c++);
+ register unsigned char uu;
+ if ((d >= '0') && (d <= '9'))
+ uu = ((d - '0') << 4);
+ else if ((d >= 'a') && (d <= 'f'))
+ uu = ((d - ('a'-10)) << 4);
+ else
+ return (char *) 0;
+ d = *(c++);
+ if ((d >= '0') && (d <= '9'))
+ uu |= (d - '0');
+ else if ((d >= 'a') && (d <= 'f'))
+ uu |= (d - ('a'-10));
+ else
+ return (char *) 0;
+ *u = uu;
+ }
+ return c;
+}
+}
+
+/* Primitive types */
+%typemap(jni) bool, const bool & "jboolean"
+%typemap(jni) char, const char & "jchar"
+%typemap(jni) signed char, const signed char & "jbyte"
+%typemap(jni) unsigned char, const unsigned char & "jshort"
+%typemap(jni) short, const short & "jshort"
+%typemap(jni) unsigned short, const unsigned short & "jint"
+%typemap(jni) int, const int & "jint"
+%typemap(jni) unsigned int, const unsigned int & "jlong"
+%typemap(jni) long, const long & "jint"
+%typemap(jni) unsigned long, const unsigned long & "jlong"
+%typemap(jni) long long, const long long & "jlong"
+%typemap(jni) unsigned long long, const unsigned long long & "jobject"
+%typemap(jni) float, const float & "jfloat"
+%typemap(jni) double, const double & "jdouble"
+%typemap(jni) void "void"
+
+%typemap(jtype) bool, const bool & "boolean"
+%typemap(jtype) char, const char & "char"
+%typemap(jtype) signed char, const signed char & "byte"
+%typemap(jtype) unsigned char, const unsigned char & "short"
+%typemap(jtype) short, const short & "short"
+%typemap(jtype) unsigned short, const unsigned short & "int"
+%typemap(jtype) int, const int & "int"
+%typemap(jtype) unsigned int, const unsigned int & "long"
+%typemap(jtype) long, const long & "int"
+%typemap(jtype) unsigned long, const unsigned long & "long"
+%typemap(jtype) long long, const long long & "long"
+%typemap(jtype) unsigned long long, const unsigned long long & "java.math.BigInteger"
+%typemap(jtype) float, const float & "float"
+%typemap(jtype) double, const double & "double"
+%typemap(jtype) void "void"
+
+%typemap(jstype) bool, const bool & "boolean"
+%typemap(jstype) char, const char & "char"
+%typemap(jstype) signed char, const signed char & "byte"
+%typemap(jstype) unsigned char, const unsigned char & "short"
+%typemap(jstype) short, const short & "short"
+%typemap(jstype) unsigned short, const unsigned short & "int"
+%typemap(jstype) int, const int & "int"
+%typemap(jstype) unsigned int, const unsigned int & "long"
+%typemap(jstype) long, const long & "int"
+%typemap(jstype) unsigned long, const unsigned long & "long"
+%typemap(jstype) long long, const long long & "long"
+%typemap(jstype) unsigned long long, const unsigned long long & "java.math.BigInteger"
+%typemap(jstype) float, const float & "float"
+%typemap(jstype) double, const double & "double"
+%typemap(jstype) void "void"
+
+%typemap(jni) char *, char *&, char[ANY], char[] "jstring"
+%typemap(jtype) char *, char *&, char[ANY], char[] "String"
+%typemap(jstype) char *, char *&, char[ANY], char[] "String"
+
+/* JNI types */
+%typemap(jni) jboolean "jboolean"
+%typemap(jni) jchar "jchar"
+%typemap(jni) jbyte "jbyte"
+%typemap(jni) jshort "jshort"
+%typemap(jni) jint "jint"
+%typemap(jni) jlong "jlong"
+%typemap(jni) jfloat "jfloat"
+%typemap(jni) jdouble "jdouble"
+%typemap(jni) jstring "jstring"
+%typemap(jni) jobject "jobject"
+%typemap(jni) jbooleanArray "jbooleanArray"
+%typemap(jni) jcharArray "jcharArray"
+%typemap(jni) jbyteArray "jbyteArray"
+%typemap(jni) jshortArray "jshortArray"
+%typemap(jni) jintArray "jintArray"
+%typemap(jni) jlongArray "jlongArray"
+%typemap(jni) jfloatArray "jfloatArray"
+%typemap(jni) jdoubleArray "jdoubleArray"
+%typemap(jni) jobjectArray "jobjectArray"
+
+%typemap(jtype) jboolean "boolean"
+%typemap(jtype) jchar "char"
+%typemap(jtype) jbyte "byte"
+%typemap(jtype) jshort "short"
+%typemap(jtype) jint "int"
+%typemap(jtype) jlong "long"
+%typemap(jtype) jfloat "float"
+%typemap(jtype) jdouble "double"
+%typemap(jtype) jstring "String"
+%typemap(jtype) jobject "Object"
+%typemap(jtype) jbooleanArray "boolean[]"
+%typemap(jtype) jcharArray "char[]"
+%typemap(jtype) jbyteArray "byte[]"
+%typemap(jtype) jshortArray "short[]"
+%typemap(jtype) jintArray "int[]"
+%typemap(jtype) jlongArray "long[]"
+%typemap(jtype) jfloatArray "float[]"
+%typemap(jtype) jdoubleArray "double[]"
+%typemap(jtype) jobjectArray "Object[]"
+
+%typemap(jstype) jboolean "boolean"
+%typemap(jstype) jchar "char"
+%typemap(jstype) jbyte "byte"
+%typemap(jstype) jshort "short"
+%typemap(jstype) jint "int"
+%typemap(jstype) jlong "long"
+%typemap(jstype) jfloat "float"
+%typemap(jstype) jdouble "double"
+%typemap(jstype) jstring "String"
+%typemap(jstype) jobject "Object"
+%typemap(jstype) jbooleanArray "boolean[]"
+%typemap(jstype) jcharArray "char[]"
+%typemap(jstype) jbyteArray "byte[]"
+%typemap(jstype) jshortArray "short[]"
+%typemap(jstype) jintArray "int[]"
+%typemap(jstype) jlongArray "long[]"
+%typemap(jstype) jfloatArray "float[]"
+%typemap(jstype) jdoubleArray "double[]"
+%typemap(jstype) jobjectArray "Object[]"
+
+/* Non primitive types */
+%typemap(jni) SWIGTYPE "jlong"
+%typemap(jtype) SWIGTYPE "long"
+%typemap(jstype) SWIGTYPE "$&javaclassname"
+
+%typemap(jni) SWIGTYPE [] "jlong"
+%typemap(jtype) SWIGTYPE [] "long"
+%typemap(jstype) SWIGTYPE [] "$javaclassname"
+
+%typemap(jni) SWIGTYPE * "jlong"
+%typemap(jtype) SWIGTYPE * "long"
+%typemap(jstype) SWIGTYPE * "$javaclassname"
+
+%typemap(jni) SWIGTYPE & "jlong"
+%typemap(jtype) SWIGTYPE & "long"
+%typemap(jstype) SWIGTYPE & "$javaclassname"
+
+/* pointer to a class member */
+%typemap(jni) SWIGTYPE (CLASS::*) "jstring"
+%typemap(jtype) SWIGTYPE (CLASS::*) "String"
+%typemap(jstype) SWIGTYPE (CLASS::*) "$javaclassname"
+
+/* The following are the in, out, freearg, argout typemaps. These are the JNI code generating typemaps for converting from Java to C and visa versa. */
+
+/* primitive types */
+%typemap(in) bool
+%{ $1 = $input ? true : false; %}
+
+%typemap(directorout) bool
+%{ $result = $input ? true : false; %}
+
+%typemap(javadirectorin) bool "$jniinput"
+%typemap(javadirectorout) bool "$javacall"
+
+%typemap(in) char,
+ signed char,
+ unsigned char,
+ short,
+ unsigned short,
+ int,
+ unsigned int,
+ long,
+ unsigned long,
+ long long,
+ float,
+ double
+%{ $1 = ($1_ltype)$input; %}
+
+%typemap(directorout) char,
+ signed char,
+ unsigned char,
+ short,
+ unsigned short,
+ int,
+ unsigned int,
+ long,
+ unsigned long,
+ long long,
+ float,
+ double
+%{ $result = ($1_ltype)$input; %}
+
+%typemap(directorin, descriptor="Z") bool "$input = (jboolean) $1;"
+%typemap(directorin, descriptor="C") char "$input = (jint) $1;"
+%typemap(directorin, descriptor="B") signed char "$input = (jbyte) $1;"
+%typemap(directorin, descriptor="S") unsigned char "$input = (jshort) $1;"
+%typemap(directorin, descriptor="S") short "$input = (jshort) $1;"
+%typemap(directorin, descriptor="I") unsigned short "$input = (jint) $1;"
+%typemap(directorin, descriptor="I") int "$input = (jint) $1;"
+%typemap(directorin, descriptor="J") unsigned int "$input = (jlong) $1;"
+%typemap(directorin, descriptor="I") long "$input = (jint) $1;"
+%typemap(directorin, descriptor="J") unsigned long "$input = (jlong) $1;"
+%typemap(directorin, descriptor="J") long long "$input = (jlong) $1;"
+%typemap(directorin, descriptor="F") float "$input = (jfloat) $1;"
+%typemap(directorin, descriptor="D") double "$input = (jdouble) $1;"
+
+%typemap(javadirectorin) char,
+ signed char,
+ unsigned char,
+ short,
+ unsigned short,
+ int,
+ unsigned int,
+ long,
+ unsigned long,
+ long long,
+ float,
+ double
+ "$jniinput"
+
+%typemap(javadirectorout) char,
+ signed char,
+ unsigned char,
+ short,
+ unsigned short,
+ int,
+ unsigned int,
+ long,
+ unsigned long,
+ long long,
+ float,
+ double
+ "$javacall"
+
+%typemap(out) bool %{ $result = (jboolean)$1; %}
+%typemap(out) char %{ $result = (jchar)$1; %}
+%typemap(out) signed char %{ $result = (jbyte)$1; %}
+%typemap(out) unsigned char %{ $result = (jshort)$1; %}
+%typemap(out) short %{ $result = (jshort)$1; %}
+%typemap(out) unsigned short %{ $result = (jint)$1; %}
+%typemap(out) int %{ $result = (jint)$1; %}
+%typemap(out) unsigned int %{ $result = (jlong)$1; %}
+%typemap(out) long %{ $result = (jint)$1; %}
+%typemap(out) unsigned long %{ $result = (jlong)$1; %}
+%typemap(out) long long %{ $result = (jlong)$1; %}
+%typemap(out) float %{ $result = (jfloat)$1; %}
+%typemap(out) double %{ $result = (jdouble)$1; %}
+
+/* unsigned long long */
+/* Convert from BigInteger using the toByteArray member function */
+%typemap(in) unsigned long long {
+ jclass clazz;
+ jmethodID mid;
+ jbyteArray ba;
+ jbyte* bae;
+ jsize sz;
+ int i;
+
+ if (!$input) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+ return $null;
+ }
+ clazz = JCALL1(GetObjectClass, jenv, $input);
+ mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+ ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+ bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+ sz = JCALL1(GetArrayLength, jenv, ba);
+ $1 = 0;
+ for(i=0; i<sz; i++) {
+ $1 = ($1 << 8) | ($1_type)(unsigned char)bae[i];
+ }
+ JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+%typemap(directorout) unsigned long long {
+ jclass clazz;
+ jmethodID mid;
+ jbyteArray ba;
+ jbyte* bae;
+ jsize sz;
+ int i;
+
+ if (!$input) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+ return $null;
+ }
+ clazz = JCALL1(GetObjectClass, jenv, $input);
+ mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+ ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+ bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+ sz = JCALL1(GetArrayLength, jenv, ba);
+ $result = 0;
+ for(i=0; i<sz; i++) {
+ $result = ($result << 8) | ($1_type)(unsigned char)bae[i];
+ }
+ JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+
+/* Convert to BigInteger - byte array holds number in 2's complement big endian format */
+%typemap(out) unsigned long long {
+ jbyteArray ba = JCALL1(NewByteArray, jenv, 9);
+ jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+ jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger");
+ jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V");
+ jobject bigint;
+ int i;
+
+ bae[0] = 0;
+ for(i=1; i<9; i++ ) {
+ bae[i] = (jbyte)($1>>8*(8-i));
+ }
+
+ JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+ bigint = JCALL3(NewObject, jenv, clazz, mid, ba);
+ $result = bigint;
+}
+
+/* Convert to BigInteger (see out typemap) */
+%typemap(directorin, descriptor="Ljava/math/BigInteger;") unsigned long long, const unsigned long long & {
+ jbyteArray ba = JCALL1(NewByteArray, jenv, 9);
+ jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+ jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger");
+ jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V");
+ jobject bigint;
+ int swig_i;
+
+ bae[0] = 0;
+ for(swig_i=1; swig_i<9; swig_i++ ) {
+ bae[swig_i] = (jbyte)($1>>8*(8-swig_i));
+ }
+
+ JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+ bigint = JCALL3(NewObject, jenv, clazz, mid, ba);
+ $input = bigint;
+}
+
+%typemap(javadirectorin) unsigned long long "$jniinput"
+%typemap(javadirectorout) unsigned long long "$javacall"
+
+/* char * - treat as String */
+%typemap(in, noblock=1) char * {
+ $1 = 0;
+ if ($input) {
+ $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+ if (!$1) return $null;
+ }
+}
+
+%typemap(directorout, noblock=1, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) char * {
+ $1 = 0;
+ if ($input) {
+ $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+ if (!$result) return $null;
+ }
+}
+
+%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char * {
+ $input = 0;
+ if ($1) {
+ $input = JCALL1(NewStringUTF, jenv, (const char *)$1);
+ if (!$input) return $null;
+ }
+}
+
+%typemap(freearg, noblock=1) char * { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); }
+%typemap(out, noblock=1) char * { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); }
+%typemap(javadirectorin) char * "$jniinput"
+%typemap(javadirectorout) char * "$javacall"
+
+/* char *& - treat as String */
+%typemap(in, noblock=1) char *& ($*1_ltype temp = 0) {
+ $1 = 0;
+ if ($input) {
+ temp = ($*1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+ if (!temp) return $null;
+ }
+ $1 = &temp;
+}
+%typemap(freearg, noblock=1) char *& { if ($1 && *$1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)*$1); }
+%typemap(out, noblock=1) char *& { if (*$1) $result = JCALL1(NewStringUTF, jenv, (const char *)*$1); }
+
+%typemap(out) void ""
+%typemap(javadirectorin) void "$jniinput"
+%typemap(javadirectorout) void "$javacall"
+%typemap(directorin, descriptor="V") void ""
+
+/* primitive types by reference */
+%typemap(in) const bool & ($*1_ltype temp)
+%{ temp = $input ? true : false;
+ $1 = &temp; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const bool &
+%{ static $*1_ltype temp;
+ temp = $input ? true : false;
+ $result = &temp; %}
+
+%typemap(javadirectorin) const bool & "$jniinput"
+%typemap(javadirectorout) const bool & "$javacall"
+
+%typemap(in) const char & ($*1_ltype temp),
+ const signed char & ($*1_ltype temp),
+ const unsigned char & ($*1_ltype temp),
+ const short & ($*1_ltype temp),
+ const unsigned short & ($*1_ltype temp),
+ const int & ($*1_ltype temp),
+ const unsigned int & ($*1_ltype temp),
+ const long & ($*1_ltype temp),
+ const unsigned long & ($*1_ltype temp),
+ const long long & ($*1_ltype temp),
+ const float & ($*1_ltype temp),
+ const double & ($*1_ltype temp)
+%{ temp = ($*1_ltype)$input;
+ $1 = &temp; %}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const char &,
+ const signed char &,
+ const unsigned char &,
+ const short &,
+ const unsigned short &,
+ const int &,
+ const unsigned int &,
+ const long &,
+ const unsigned long &,
+ const long long &,
+ const float &,
+ const double &
+%{ static $*1_ltype temp;
+ temp = ($*1_ltype)$input;
+ $result = &temp; %}
+
+%typemap(directorin, descriptor="Z") const bool & "$input = (jboolean)$1;"
+%typemap(directorin, descriptor="C") const char & "$input = (jchar)$1;"
+%typemap(directorin, descriptor="B") const signed char & "$input = (jbyte)$1;"
+%typemap(directorin, descriptor="S") const unsigned char & "$input = (jshort)$1;"
+%typemap(directorin, descriptor="S") const short & "$input = (jshort)$1;"
+%typemap(directorin, descriptor="I") const unsigned short & "$input = (jint)$1;"
+%typemap(directorin, descriptor="I") const int & "$input = (jint)$1;"
+%typemap(directorin, descriptor="J") const unsigned int & "$input = (jlong)$1;"
+%typemap(directorin, descriptor="I") const long & "$input = (jint)$1;"
+%typemap(directorin, descriptor="J") const unsigned long & "$input = (jlong)$1;"
+%typemap(directorin, descriptor="J") const long long & "$input = (jlong)$1;"
+%typemap(directorin, descriptor="F") const float & "$input = (jfloat)$1;"
+%typemap(directorin, descriptor="D") const double & "$input = (jdouble)$1;"
+
+%typemap(javadirectorin) const char & ($*1_ltype temp),
+ const signed char & ($*1_ltype temp),
+ const unsigned char & ($*1_ltype temp),
+ const short & ($*1_ltype temp),
+ const unsigned short & ($*1_ltype temp),
+ const int & ($*1_ltype temp),
+ const unsigned int & ($*1_ltype temp),
+ const long & ($*1_ltype temp),
+ const unsigned long & ($*1_ltype temp),
+ const long long & ($*1_ltype temp),
+ const float & ($*1_ltype temp),
+ const double & ($*1_ltype temp)
+ "$jniinput"
+
+%typemap(javadirectorout) const char & ($*1_ltype temp),
+ const signed char & ($*1_ltype temp),
+ const unsigned char & ($*1_ltype temp),
+ const short & ($*1_ltype temp),
+ const unsigned short & ($*1_ltype temp),
+ const int & ($*1_ltype temp),
+ const unsigned int & ($*1_ltype temp),
+ const long & ($*1_ltype temp),
+ const unsigned long & ($*1_ltype temp),
+ const long long & ($*1_ltype temp),
+ const float & ($*1_ltype temp),
+ const double & ($*1_ltype temp)
+ "$javacall"
+
+
+%typemap(out) const bool & %{ $result = (jboolean)*$1; %}
+%typemap(out) const char & %{ $result = (jchar)*$1; %}
+%typemap(out) const signed char & %{ $result = (jbyte)*$1; %}
+%typemap(out) const unsigned char & %{ $result = (jshort)*$1; %}
+%typemap(out) const short & %{ $result = (jshort)*$1; %}
+%typemap(out) const unsigned short & %{ $result = (jint)*$1; %}
+%typemap(out) const int & %{ $result = (jint)*$1; %}
+%typemap(out) const unsigned int & %{ $result = (jlong)*$1; %}
+%typemap(out) const long & %{ $result = (jint)*$1; %}
+%typemap(out) const unsigned long & %{ $result = (jlong)*$1; %}
+%typemap(out) const long long & %{ $result = (jlong)*$1; %}
+%typemap(out) const float & %{ $result = (jfloat)*$1; %}
+%typemap(out) const double & %{ $result = (jdouble)*$1; %}
+
+/* const unsigned long long & */
+/* Similar to unsigned long long */
+%typemap(in) const unsigned long long & ($*1_ltype temp) {
+ jclass clazz;
+ jmethodID mid;
+ jbyteArray ba;
+ jbyte* bae;
+ jsize sz;
+ int i;
+
+ if (!$input) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+ return $null;
+ }
+ clazz = JCALL1(GetObjectClass, jenv, $input);
+ mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+ ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+ bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+ sz = JCALL1(GetArrayLength, jenv, ba);
+ $1 = &temp;
+ temp = 0;
+ for(i=0; i<sz; i++) {
+ temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i];
+ }
+ JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+%typemap(directorout,warning=SWIGWARN_TYPEMAP_THREAD_UNSAFE_MSG) const unsigned long long & {
+ static $*1_ltype temp;
+ jclass clazz;
+ jmethodID mid;
+ jbyteArray ba;
+ jbyte* bae;
+ jsize sz;
+ int i;
+
+ if (!$input) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "BigInteger null");
+ return $null;
+ }
+ clazz = JCALL1(GetObjectClass, jenv, $input);
+ mid = JCALL3(GetMethodID, jenv, clazz, "toByteArray", "()[B");
+ ba = (jbyteArray)JCALL2(CallObjectMethod, jenv, $input, mid);
+ bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+ sz = JCALL1(GetArrayLength, jenv, ba);
+ $result = &temp;
+ temp = 0;
+ for(i=0; i<sz; i++) {
+ temp = (temp << 8) | ($*1_ltype)(unsigned char)bae[i];
+ }
+ JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+}
+
+%typemap(out) const unsigned long long & {
+ jbyteArray ba = JCALL1(NewByteArray, jenv, 9);
+ jbyte* bae = JCALL2(GetByteArrayElements, jenv, ba, 0);
+ jclass clazz = JCALL1(FindClass, jenv, "java/math/BigInteger");
+ jmethodID mid = JCALL3(GetMethodID, jenv, clazz, "<init>", "([B)V");
+ jobject bigint;
+ int i;
+
+ bae[0] = 0;
+ for(i=1; i<9; i++ ) {
+ bae[i] = (jbyte)(*$1>>8*(8-i));
+ }
+
+ JCALL3(ReleaseByteArrayElements, jenv, ba, bae, 0);
+ bigint = JCALL3(NewObject, jenv, clazz, mid, ba);
+ $result = bigint;
+}
+
+%typemap(javadirectorin) const unsigned long long & "$jniinput"
+%typemap(javadirectorout) const unsigned long long & "$javacall"
+
+/* Default handling. Object passed by value. Convert to a pointer */
+%typemap(in) SWIGTYPE ($&1_type argp)
+%{ argp = *($&1_ltype*)&$input;
+ if (!argp) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Attempt to dereference null $1_type");
+ return $null;
+ }
+ $1 = *argp; %}
+
+%typemap(directorout) SWIGTYPE ($&1_type argp)
+%{ argp = *($&1_ltype*)&$input;
+ if (!argp) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type");
+ return $null;
+ }
+ $result = *argp; %}
+
+%typemap(out) SWIGTYPE
+#ifdef __cplusplus
+%{ *($&1_ltype*)&$result = new $1_ltype((const $1_ltype &)$1); %}
+#else
+{
+ $&1_ltype $1ptr = ($&1_ltype) malloc(sizeof($1_ltype));
+ memmove($1ptr, &$1, sizeof($1_type));
+ *($&1_ltype*)&$result = $1ptr;
+}
+#endif
+
+%typemap(directorin,descriptor="L$packagepath/$&javaclassname;") SWIGTYPE
+%{ $input = 0;
+ *(($&1_ltype*)&$input) = &$1; %}
+%typemap(javadirectorin) SWIGTYPE "new $&javaclassname($jniinput, false)"
+%typemap(javadirectorout) SWIGTYPE "$&javaclassname.getCPtr($javacall)"
+
+/* Generic pointers and references */
+%typemap(in) SWIGTYPE * %{ $1 = *($&1_ltype)&$input; %}
+%typemap(in, fragment="SWIG_UnPackData") SWIGTYPE (CLASS::*) {
+ const char *temp = 0;
+ if ($input) {
+ temp = JCALL2(GetStringUTFChars, jenv, $input, 0);
+ if (!temp) return $null;
+ }
+ SWIG_UnpackData(temp, (void *)&$1, sizeof($1));
+}
+%typemap(in) SWIGTYPE & %{ $1 = *($&1_ltype)&$input;
+ if (!$1) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "$1_type reference is null");
+ return $null;
+ } %}
+%typemap(out) SWIGTYPE *
+%{ *($&1_ltype)&$result = $1; %}
+%typemap(out, fragment="SWIG_PackData", noblock=1) SWIGTYPE (CLASS::*) {
+ char buf[128];
+ char *data = SWIG_PackData(buf, (void *)&$1, sizeof($1));
+ *data = '\0';
+ $result = JCALL1(NewStringUTF, jenv, buf);
+}
+%typemap(out) SWIGTYPE &
+%{ *($&1_ltype)&$result = $1; %}
+
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE *
+%{ $result = *($&1_ltype)&$input; %}
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE (CLASS::*)
+%{ $result = *($&1_ltype)&$input; %}
+
+%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE *
+%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %}
+%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE (CLASS::*)
+%{ *(($&1_ltype)&$input) = ($1_ltype) $1; %}
+
+%typemap(directorout, warning=SWIGWARN_TYPEMAP_DIRECTOROUT_PTR_MSG) SWIGTYPE &
+%{ if (!$input) {
+ SWIG_JavaThrowException(jenv, SWIG_JavaNullPointerException, "Unexpected null return for type $1_type");
+ return $null;
+ }
+ $result = *($&1_ltype)&$input; %}
+%typemap(directorin,descriptor="L$packagepath/$javaclassname;") SWIGTYPE &
+%{ *($&1_ltype)&$input = ($1_ltype) &$1; %}
+
+%typemap(javadirectorin) SWIGTYPE *, SWIGTYPE (CLASS::*) "($jniinput == 0) ? null : new $javaclassname($jniinput, false)"
+%typemap(javadirectorin) SWIGTYPE & "new $javaclassname($jniinput, false)"
+%typemap(javadirectorout) SWIGTYPE *, SWIGTYPE (CLASS::*), SWIGTYPE & "$javaclassname.getCPtr($javacall)"
+
+/* Default array handling */
+%typemap(in) SWIGTYPE [] %{ $1 = *($&1_ltype)&$input; %}
+%typemap(out) SWIGTYPE [] %{ *($&1_ltype)&$result = $1; %}
+%typemap(freearg) SWIGTYPE [ANY], SWIGTYPE [] ""
+
+/* char arrays - treat as String */
+%typemap(in, noblock=1) char[ANY], char[] {
+ $1 = 0;
+ if ($input) {
+ $1 = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+ if (!$1) return $null;
+ }
+}
+
+%typemap(directorout, noblock=1) char[ANY], char[] {
+ $1 = 0;
+ if ($input) {
+ $result = ($1_ltype)JCALL2(GetStringUTFChars, jenv, $input, 0);
+ if (!$result) return $null;
+ }
+}
+
+%typemap(directorin, descriptor="Ljava/lang/String;", noblock=1) char[ANY], char[] {
+ $input = 0;
+ if ($1) {
+ $input = JCALL1(NewStringUTF, jenv, (const char *)$1);
+ if (!$input) return $null;
+ }
+}
+
+%typemap(argout) char[ANY], char[] ""
+%typemap(freearg, noblock=1) char[ANY], char[] { if ($1) JCALL2(ReleaseStringUTFChars, jenv, $input, (const char *)$1); }
+%typemap(out, noblock=1) char[ANY], char[] { if ($1) $result = JCALL1(NewStringUTF, jenv, (const char *)$1); }
+%typemap(javadirectorin) char[ANY], char[] "$jniinput"
+%typemap(javadirectorout) char[ANY], char[] "$javacall"
+
+/* JNI types */
+%typemap(in) jboolean,
+ jchar,
+ jbyte,
+ jshort,
+ jint,
+ jlong,
+ jfloat,
+ jdouble,
+ jstring,
+ jobject,
+ jbooleanArray,
+ jcharArray,
+ jbyteArray,
+ jshortArray,
+ jintArray,
+ jlongArray,
+ jfloatArray,
+ jdoubleArray,
+ jobjectArray
+%{ $1 = $input; %}
+
+%typemap(directorout) jboolean,
+ jchar,
+ jbyte,
+ jshort,
+ jint,
+ jlong,
+ jfloat,
+ jdouble,
+ jstring,
+ jobject,
+ jbooleanArray,
+ jcharArray,
+ jbyteArray,
+ jshortArray,
+ jintArray,
+ jlongArray,
+ jfloatArray,
+ jdoubleArray,
+ jobjectArray
+%{ $result = $input; %}
+
+%typemap(out) jboolean,
+ jchar,
+ jbyte,
+ jshort,
+ jint,
+ jlong,
+ jfloat,
+ jdouble,
+ jstring,
+ jobject,
+ jbooleanArray,
+ jcharArray,
+ jbyteArray,
+ jshortArray,
+ jintArray,
+ jlongArray,
+ jfloatArray,
+ jdoubleArray,
+ jobjectArray
+%{ $result = $1; %}
+
+%typemap(directorin,descriptor="Z") jboolean "$input = $1;"
+%typemap(directorin,descriptor="C") jchar "$input = $1;"
+%typemap(directorin,descriptor="B") jbyte "$input = $1;"
+%typemap(directorin,descriptor="S") jshort "$input = $1;"
+%typemap(directorin,descriptor="I") jint "$input = $1;"
+%typemap(directorin,descriptor="J") jlong "$input = $1;"
+%typemap(directorin,descriptor="F") jfloat "$input = $1;"
+%typemap(directorin,descriptor="D") jdouble "$input = $1;"
+%typemap(directorin,descriptor="Ljava/lang/String;") jstring "$input = $1;"
+%typemap(directorin,descriptor="Ljava/lang/Object;",nouse="1") jobject "$input = $1;"
+%typemap(directorin,descriptor="[Z") jbooleanArray "$input = $1;"
+%typemap(directorin,descriptor="[C") jcharArray "$input = $1;"
+%typemap(directorin,descriptor="[B") jbyteArray "$input = $1;"
+%typemap(directorin,descriptor="[S") jshortArray "$input = $1;"
+%typemap(directorin,descriptor="[I") jintArray "$input = $1;"
+%typemap(directorin,descriptor="[J") jlongArray "$input = $1;"
+%typemap(directorin,descriptor="[F") jfloatArray "$input = $1;"
+%typemap(directorin,descriptor="[D") jdoubleArray "$input = $1;"
+%typemap(directorin,descriptor="[Ljava/lang/Object;",nouse="1") jobjectArray "$input = $1;"
+
+%typemap(javadirectorin) jboolean,
+ jchar,
+ jbyte,
+ jshort,
+ jint,
+ jlong,
+ jfloat,
+ jdouble,
+ jstring,
+ jobject,
+ jbooleanArray,
+ jcharArray,
+ jbyteArray,
+ jshortArray,
+ jintArray,
+ jlongArray,
+ jfloatArray,
+ jdoubleArray,
+ jobjectArray
+ "$jniinput"
+
+%typemap(javadirectorout) jboolean,
+ jchar,
+ jbyte,
+ jshort,
+ jint,
+ jlong,
+ jfloat,
+ jdouble,
+ jstring,
+ jobject,
+ jbooleanArray,
+ jcharArray,
+ jbyteArray,
+ jshortArray,
+ jintArray,
+ jlongArray,
+ jfloatArray,
+ jdoubleArray,
+ jobjectArray
+ "$javacall"
+
+/* Typecheck typemaps - The purpose of these is merely to issue a warning for overloaded C++ functions
+ * that cannot be overloaded in Java as more than one C++ type maps to a single Java type */
+
+%typecheck(SWIG_TYPECHECK_BOOL) /* Java boolean */
+ jboolean,
+ bool,
+ const bool &
+ ""
+
+%typecheck(SWIG_TYPECHECK_CHAR) /* Java char */
+ jchar,
+ char,
+ const char &
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT8) /* Java byte */
+ jbyte,
+ signed char,
+ const signed char &
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT16) /* Java short */
+ jshort,
+ unsigned char,
+ short,
+ const unsigned char &,
+ const short &
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT32) /* Java int */
+ jint,
+ unsigned short,
+ int,
+ long,
+ const unsigned short &,
+ const int &,
+ const long &
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT64) /* Java long */
+ jlong,
+ unsigned int,
+ unsigned long,
+ long long,
+ const unsigned int &,
+ const unsigned long &,
+ const long long &
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT128) /* Java BigInteger */
+ unsigned long long,
+ const unsigned long long &
+ ""
+
+%typecheck(SWIG_TYPECHECK_FLOAT) /* Java float */
+ jfloat,
+ float,
+ const float &
+ ""
+
+%typecheck(SWIG_TYPECHECK_DOUBLE) /* Java double */
+ jdouble,
+ double,
+ const double &
+ ""
+
+%typecheck(SWIG_TYPECHECK_STRING) /* Java String */
+ jstring,
+ char *,
+ char *&,
+ char[ANY],
+ char []
+ ""
+
+%typecheck(SWIG_TYPECHECK_BOOL_ARRAY) /* Java boolean[] */
+ jbooleanArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_CHAR_ARRAY) /* Java char[] */
+ jcharArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT8_ARRAY) /* Java byte[] */
+ jbyteArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT16_ARRAY) /* Java short[] */
+ jshortArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT32_ARRAY) /* Java int[] */
+ jintArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_INT64_ARRAY) /* Java long[] */
+ jlongArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_FLOAT_ARRAY) /* Java float[] */
+ jfloatArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_DOUBLE_ARRAY) /* Java double[] */
+ jdoubleArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_OBJECT_ARRAY) /* Java jobject[] */
+ jobjectArray
+ ""
+
+%typecheck(SWIG_TYPECHECK_POINTER) /* Default */
+ SWIGTYPE,
+ SWIGTYPE *,
+ SWIGTYPE &,
+ SWIGTYPE *const&,
+ SWIGTYPE [],
+ SWIGTYPE (CLASS::*)
+ ""
+
+
+/* Exception handling */
+
+%typemap(throws) int,
+ long,
+ short,
+ unsigned int,
+ unsigned long,
+ unsigned short
+%{ char error_msg[256];
+ sprintf(error_msg, "C++ $1_type exception thrown, value: %d", $1);
+ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, error_msg);
+ return $null; %}
+
+%typemap(throws) SWIGTYPE, SWIGTYPE &, SWIGTYPE *, SWIGTYPE [], SWIGTYPE [ANY]
+%{ (void)$1;
+ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, "C++ $1_type exception thrown");
+ return $null; %}
+
+%typemap(throws) char *
+%{ SWIG_JavaThrowException(jenv, SWIG_JavaRuntimeException, $1);
+ return $null; %}
+
+
+/* Typemaps for code generation in proxy classes and Java type wrapper classes */
+
+/* The javain typemap is used for converting function parameter types from the type
+ * used in the proxy, module or type wrapper class to the type used in the JNI class. */
+%typemap(javain) bool, const bool &,
+ char, const char &,
+ signed char, const signed char &,
+ unsigned char, const unsigned char &,
+ short, const short &,
+ unsigned short, const unsigned short &,
+ int, const int &,
+ unsigned int, const unsigned int &,
+ long, const long &,
+ unsigned long, const unsigned long &,
+ long long, const long long &,
+ unsigned long long, const unsigned long long &,
+ float, const float &,
+ double, const double &
+ "$javainput"
+%typemap(javain) char *, char *&, char[ANY], char[] "$javainput"
+%typemap(javain) jboolean,
+ jchar,
+ jbyte,
+ jshort,
+ jint,
+ jlong,
+ jfloat,
+ jdouble,
+ jstring,
+ jobject,
+ jbooleanArray,
+ jcharArray,
+ jbyteArray,
+ jshortArray,
+ jintArray,
+ jlongArray,
+ jfloatArray,
+ jdoubleArray,
+ jobjectArray
+ "$javainput"
+%typemap(javain) SWIGTYPE "$&javaclassname.getCPtr($javainput)"
+%typemap(javain) SWIGTYPE *, SWIGTYPE &, SWIGTYPE [] "$javaclassname.getCPtr($javainput)"
+%typemap(javain) SWIGTYPE (CLASS::*) "$javaclassname.getCMemberPtr($javainput)"
+
+/* The javaout typemap is used for converting function return types from the return type
+ * used in the JNI class to the type returned by the proxy, module or type wrapper class. */
+%typemap(javaout) bool, const bool &,
+ char, const char &,
+ signed char, const signed char &,
+ unsigned char, const unsigned char &,
+ short, const short &,
+ unsigned short, const unsigned short &,
+ int, const int &,
+ unsigned int, const unsigned int &,
+ long, const long &,
+ unsigned long, const unsigned long &,
+ long long, const long long &,
+ unsigned long long, const unsigned long long &,
+ float, const float &,
+ double, const double & {
+ return $jnicall;
+ }
+%typemap(javaout) char *, char *&, char[ANY], char[] {
+ return $jnicall;
+ }
+%typemap(javaout) jboolean,
+ jchar,
+ jbyte,
+ jshort,
+ jint,
+ jlong,
+ jfloat,
+ jdouble,
+ jstring,
+ jobject,
+ jbooleanArray,
+ jcharArray,
+ jbyteArray,
+ jshortArray,
+ jintArray,
+ jlongArray,
+ jfloatArray,
+ jdoubleArray,
+ jobjectArray {
+ return $jnicall;
+ }
+%typemap(javaout) void {
+ $jnicall;
+ }
+%typemap(javaout) SWIGTYPE {
+ return new $&javaclassname($jnicall, true);
+ }
+%typemap(javaout) SWIGTYPE & {
+ return new $javaclassname($jnicall, $owner);
+ }
+%typemap(javaout) SWIGTYPE *, SWIGTYPE [] {
+ long cPtr = $jnicall;
+ return (cPtr == 0) ? null : new $javaclassname(cPtr, $owner);
+ }
+%typemap(javaout) SWIGTYPE (CLASS::*) {
+ String cMemberPtr = $jnicall;
+ return (cMemberPtr == null) ? null : new $javaclassname(cMemberPtr, $owner);
+ }
+
+/* Pointer reference typemaps */
+%typemap(jni) SWIGTYPE *const& "jlong"
+%typemap(jtype) SWIGTYPE *const& "long"
+%typemap(jstype) SWIGTYPE *const& "$*javaclassname"
+%typemap(javain) SWIGTYPE *const& "$*javaclassname.getCPtr($javainput)"
+%typemap(javaout) SWIGTYPE *const& {
+ long cPtr = $jnicall;
+ return (cPtr == 0) ? null : new $*javaclassname(cPtr, $owner);
+ }
+%typemap(in) SWIGTYPE *const& ($*1_ltype temp = 0)
+%{ temp = *($1_ltype)&$input;
+ $1 = ($1_ltype)&temp; %}
+%typemap(out) SWIGTYPE *const&
+%{ *($1_ltype)&$result = *$1; %}
+
+/* Typemaps used for the generation of proxy and type wrapper class code */
+%typemap(javabase) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(javaclassmodifiers) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) "public class"
+%typemap(javacode) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(javaimports) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+%typemap(javainterfaces) SWIGTYPE, SWIGTYPE *, SWIGTYPE &, SWIGTYPE [], SWIGTYPE (CLASS::*) ""
+
+/* javabody typemaps */
+
+%define SWIG_JAVABODY_METHODS(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...) SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE) %enddef // legacy name
+
+%define SWIG_JAVABODY_PROXY(PTRCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...)
+// Base proxy classes
+%typemap(javabody) TYPE %{
+ private long swigCPtr;
+ protected boolean swigCMemOwn;
+
+ PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) {
+ swigCMemOwn = cMemoryOwn;
+ swigCPtr = cPtr;
+ }
+
+ CPTR_VISIBILITY static long getCPtr($javaclassname obj) {
+ return (obj == null) ? 0 : obj.swigCPtr;
+ }
+%}
+
+// Derived proxy classes
+%typemap(javabody_derived) TYPE %{
+ private long swigCPtr;
+
+ PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean cMemoryOwn) {
+ super($imclassname.$javaclazznameSWIGUpcast(cPtr), cMemoryOwn);
+ swigCPtr = cPtr;
+ }
+
+ CPTR_VISIBILITY static long getCPtr($javaclassname obj) {
+ return (obj == null) ? 0 : obj.swigCPtr;
+ }
+%}
+%enddef
+
+%define SWIG_JAVABODY_TYPEWRAPPER(PTRCTOR_VISIBILITY, DEFAULTCTOR_VISIBILITY, CPTR_VISIBILITY, TYPE...)
+// Typewrapper classes
+%typemap(javabody) TYPE *, TYPE &, TYPE [] %{
+ private long swigCPtr;
+
+ PTRCTOR_VISIBILITY $javaclassname(long cPtr, boolean futureUse) {
+ swigCPtr = cPtr;
+ }
+
+ DEFAULTCTOR_VISIBILITY $javaclassname() {
+ swigCPtr = 0;
+ }
+
+ CPTR_VISIBILITY static long getCPtr($javaclassname obj) {
+ return (obj == null) ? 0 : obj.swigCPtr;
+ }
+%}
+
+%typemap(javabody) TYPE (CLASS::*) %{
+ private String swigCMemberPtr;
+
+ PTRCTOR_VISIBILITY $javaclassname(String cMemberPtr, boolean futureUse) {
+ swigCMemberPtr = cMemberPtr;
+ }
+
+ DEFAULTCTOR_VISIBILITY $javaclassname() {
+ swigCMemberPtr = null;
+ }
+
+ CPTR_VISIBILITY static String getCMemberPtr($javaclassname obj) {
+ return obj.swigCMemberPtr;
+ }
+%}
+%enddef
+
+/* Set the default javabody typemaps to use protected visibility.
+ Use the macros to change to public if using multiple modules. */
+SWIG_JAVABODY_PROXY(protected, protected, SWIGTYPE)
+SWIG_JAVABODY_TYPEWRAPPER(protected, protected, protected, SWIGTYPE)
+
+%typemap(javafinalize) SWIGTYPE %{
+ protected void finalize() {
+ delete();
+ }
+%}
+
+/*
+ * Java constructor typemaps:
+ *
+ * The javaconstruct typemap is inserted when a proxy class's constructor is generated.
+ * This typemap allows control over what code is executed in the constructor as
+ * well as specifying who owns the underlying C/C++ object. Normally, Java has
+ * ownership and the underlying C/C++ object is deallocated when the Java object
+ * is finalized (swigCMemOwn is true.) If swigCMemOwn is false, C/C++ is
+ * ultimately responsible for deallocating the underlying object's memory.
+ *
+ * The SWIG_PROXY_CONSTRUCTOR macro defines the javaconstruct typemap for a proxy
+ * class for a particular TYPENAME. OWNERSHIP is passed as the value of
+ * swigCMemOwn to the pointer constructor method. WEAKREF determines which kind
+ * of Java object reference will be used by the C++ director class (WeakGlobalRef
+ * vs. GlobalRef.)
+ *
+ * The SWIG_DIRECTOR_OWNED macro sets the ownership of director-based proxy
+ * classes and the weak reference flag to false, meaning that the underlying C++
+ * object will be reclaimed by C++.
+ */
+
+%define SWIG_PROXY_CONSTRUCTOR(OWNERSHIP, WEAKREF, TYPENAME...)
+%typemap(javaconstruct,directorconnect="\n $imclassname.$javaclazznamedirector_connect(this, swigCPtr, swigCMemOwn, WEAKREF);") TYPENAME {
+ this($imcall, OWNERSHIP);$directorconnect
+ }
+%enddef
+
+%define SWIG_DIRECTOR_OWNED(TYPENAME...)
+SWIG_PROXY_CONSTRUCTOR(true, false, TYPENAME)
+%enddef
+
+// Set the default for SWIGTYPE: Java owns the C/C++ object.
+SWIG_PROXY_CONSTRUCTOR(true, true, SWIGTYPE)
+
+%typemap(javadestruct, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE {
+ if (swigCPtr != 0) {
+ if (swigCMemOwn) {
+ swigCMemOwn = false;
+ $jnicall;
+ }
+ swigCPtr = 0;
+ }
+ }
+
+%typemap(javadestruct_derived, methodname="delete", methodmodifiers="public synchronized") SWIGTYPE {
+ if (swigCPtr != 0) {
+ if (swigCMemOwn) {
+ swigCMemOwn = false;
+ $jnicall;
+ }
+ swigCPtr = 0;
+ }
+ super.delete();
+ }
+
+%typemap(directordisconnect, methodname="swigDirectorDisconnect") SWIGTYPE %{
+ protected void $methodname() {
+ swigCMemOwn = false;
+ $jnicall;
+ }
+%}
+
+%typemap(directorowner_release, methodname="swigReleaseOwnership") SWIGTYPE %{
+ public void $methodname() {
+ swigCMemOwn = false;
+ $jnicall;
+ }
+%}
+
+%typemap(directorowner_take, methodname="swigTakeOwnership") SWIGTYPE %{
+ public void $methodname() {
+ swigCMemOwn = true;
+ $jnicall;
+ }
+%}
+
+/* Java specific directives */
+#define %javaconst(flag) %feature("java:const","flag")
+#define %javaconstvalue(value) %feature("java:constvalue",value)
+#define %javaenum(wrapapproach) %feature("java:enum","wrapapproach")
+#define %javamethodmodifiers %feature("java:methodmodifiers")
+#define %javaexception(exceptionclasses) %feature("except",throws=exceptionclasses)
+#define %nojavaexception %feature("except","0",throws="")
+#define %clearjavaexception %feature("except","",throws="")
+
+%pragma(java) jniclassclassmodifiers="public class"
+%pragma(java) moduleclassmodifiers="public class"
+
+/* Some ANSI C typemaps */
+
+%apply unsigned long { size_t };
+%apply const unsigned long & { const size_t & };
+
+/* Array reference typemaps */
+%apply SWIGTYPE & { SWIGTYPE ((&)[ANY]) }
+
+/* const pointers */
+%apply SWIGTYPE * { SWIGTYPE *const }
+
+/* String & length */
+%typemap(jni) (char *STRING, size_t LENGTH) "jbyteArray"
+%typemap(jtype) (char *STRING, size_t LENGTH) "byte[]"
+%typemap(jstype) (char *STRING, size_t LENGTH) "byte[]"
+%typemap(javain) (char *STRING, size_t LENGTH) "$javainput"
+%typemap(freearg) (char *STRING, size_t LENGTH) ""
+%typemap(in) (char *STRING, size_t LENGTH) {
+ if ($input) {
+ $1 = (char *) JCALL2(GetByteArrayElements, jenv, $input, 0);
+ $2 = (size_t) JCALL1(GetArrayLength, jenv, $input);
+ } else {
+ $1 = 0;
+ $2 = 0;
+ }
+}
+%typemap(argout) (char *STRING, size_t LENGTH) {
+ if ($input) JCALL3(ReleaseByteArrayElements, jenv, $input, (jbyte *)$1, 0);
+}
+%typemap(directorin, descriptor="[B") (char *STRING, size_t LENGTH) {
+ jbyteArray jb = (jenv)->NewByteArray($2);
+ (jenv)->SetByteArrayRegion(jb, 0, $2, (jbyte *)$1);
+ $input = jb;
+}
+%typemap(directorargout) (char *STRING, size_t LENGTH)
+%{(jenv)->GetByteArrayRegion($input, 0, $2, (jbyte *)$1); %}
+%apply (char *STRING, size_t LENGTH) { (char *STRING, int LENGTH) }
+
+/* java keywords */
+%include <javakw.swg>
+
+// Default enum handling
+%include <enumtypesafe.swg>
+
diff --git a/tests/examplefiles/swig_std_vector.i b/tests/examplefiles/swig_std_vector.i
new file mode 100644
index 00000000..baecf850
--- /dev/null
+++ b/tests/examplefiles/swig_std_vector.i
@@ -0,0 +1,225 @@
+//
+// std::vector
+//
+
+%include <std_container.i>
+
+// Vector
+
+%define %std_vector_methods(vector...)
+ %std_sequence_methods(vector)
+
+ void reserve(size_type n);
+ size_type capacity() const;
+%enddef
+
+
+%define %std_vector_methods_val(vector...)
+ %std_sequence_methods_val(vector)
+
+ void reserve(size_type n);
+ size_type capacity() const;
+%enddef
+
+
+// ------------------------------------------------------------------------
+// std::vector
+//
+// The aim of all that follows would be to integrate std::vector with
+// as much as possible, namely, to allow the user to pass and
+// be returned tuples or lists.
+// const declarations are used to guess the intent of the function being
+// exported; therefore, the following rationale is applied:
+//
+// -- f(std::vector<T>), f(const std::vector<T>&):
+// the parameter being read-only, either a sequence or a
+// previously wrapped std::vector<T> can be passed.
+// -- f(std::vector<T>&), f(std::vector<T>*):
+// the parameter may be modified; therefore, only a wrapped std::vector
+// can be passed.
+// -- std::vector<T> f(), const std::vector<T>& f():
+// the vector is returned by copy; therefore, a sequence of T:s
+// is returned which is most easily used in other functions
+// -- std::vector<T>& f(), std::vector<T>* f():
+// the vector is returned by reference; therefore, a wrapped std::vector
+// is returned
+// -- const std::vector<T>* f(), f(const std::vector<T>*):
+// for consistency, they expect and return a plain vector pointer.
+// ------------------------------------------------------------------------
+
+%{
+#include <vector>
+%}
+
+// exported classes
+
+
+namespace std {
+
+ template<class _Tp, class _Alloc = allocator< _Tp > >
+ class vector {
+ public:
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+ typedef _Tp value_type;
+ typedef value_type* pointer;
+ typedef const value_type* const_pointer;
+ typedef _Tp& reference;
+ typedef const _Tp& const_reference;
+ typedef _Alloc allocator_type;
+
+ %traits_swigtype(_Tp);
+ %traits_enum(_Tp);
+
+ %fragment(SWIG_Traits_frag(std::vector<_Tp, _Alloc >), "header",
+ fragment=SWIG_Traits_frag(_Tp),
+ fragment="StdVectorTraits") {
+ namespace swig {
+ template <> struct traits<std::vector<_Tp, _Alloc > > {
+ typedef pointer_category category;
+ static const char* type_name() {
+ return "std::vector<" #_Tp "," #_Alloc " >";
+ }
+ };
+ }
+ }
+
+ %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp, _Alloc >);
+
+#ifdef %swig_vector_methods
+ // Add swig/language extra methods
+ %swig_vector_methods(std::vector<_Tp, _Alloc >);
+#endif
+
+ %std_vector_methods(vector);
+ };
+
+ // ***
+ // This specialization should disappear or get simplified when
+ // a 'const SWIGTYPE*&' can be defined
+ // ***
+ template<class _Tp, class _Alloc >
+ class vector<_Tp*, _Alloc > {
+ public:
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+ typedef _Tp* value_type;
+ typedef value_type* pointer;
+ typedef const value_type* const_pointer;
+ typedef value_type reference;
+ typedef value_type const_reference;
+ typedef _Alloc allocator_type;
+
+ %traits_swigtype(_Tp);
+
+ %fragment(SWIG_Traits_frag(std::vector<_Tp*, _Alloc >), "header",
+ fragment=SWIG_Traits_frag(_Tp),
+ fragment="StdVectorTraits") {
+ namespace swig {
+ template <> struct traits<std::vector<_Tp*, _Alloc > > {
+ typedef value_category category;
+ static const char* type_name() {
+ return "std::vector<" #_Tp " *," #_Alloc " >";
+ }
+ };
+ }
+ }
+
+ %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp*, _Alloc >);
+
+#ifdef %swig_vector_methods_val
+ // Add swig/language extra methods
+ %swig_vector_methods_val(std::vector<_Tp*, _Alloc >);
+#endif
+
+ %std_vector_methods_val(vector);
+ };
+
+ // ***
+ // const pointer specialization
+ // ***
+ template<class _Tp, class _Alloc >
+ class vector<_Tp const *, _Alloc > {
+ public:
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+ typedef _Tp const * value_type;
+ typedef value_type* pointer;
+ typedef const value_type* const_pointer;
+ typedef value_type reference;
+ typedef value_type const_reference;
+ typedef _Alloc allocator_type;
+
+ %traits_swigtype(_Tp);
+
+ %fragment(SWIG_Traits_frag(std::vector<_Tp const*, _Alloc >), "header",
+ fragment=SWIG_Traits_frag(_Tp),
+ fragment="StdVectorTraits") {
+ namespace swig {
+ template <> struct traits<std::vector<_Tp const*, _Alloc > > {
+ typedef value_category category;
+ static const char* type_name() {
+ return "std::vector<" #_Tp " const*," #_Alloc " >";
+ }
+ };
+ }
+ }
+
+ %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<_Tp const*, _Alloc >);
+
+#ifdef %swig_vector_methods_val
+ // Add swig/language extra methods
+ %swig_vector_methods_val(std::vector<_Tp const*, _Alloc >);
+#endif
+
+ %std_vector_methods_val(vector);
+ };
+
+ // ***
+ // bool specialization
+ // ***
+
+ template<class _Alloc >
+ class vector<bool,_Alloc > {
+ public:
+ typedef size_t size_type;
+ typedef ptrdiff_t difference_type;
+ typedef bool value_type;
+ typedef value_type* pointer;
+ typedef const value_type* const_pointer;
+ typedef value_type reference;
+ typedef value_type const_reference;
+ typedef _Alloc allocator_type;
+
+ %traits_swigtype(bool);
+
+ %fragment(SWIG_Traits_frag(std::vector<bool, _Alloc >), "header",
+ fragment=SWIG_Traits_frag(bool),
+ fragment="StdVectorTraits") {
+ namespace swig {
+ template <> struct traits<std::vector<bool, _Alloc > > {
+ typedef value_category category;
+ static const char* type_name() {
+ return "std::vector<bool, _Alloc >";
+ }
+ };
+ }
+ }
+
+ %typemap_traits_ptr(SWIG_TYPECHECK_VECTOR, std::vector<bool, _Alloc >);
+
+
+#ifdef %swig_vector_methods_val
+ // Add swig/language extra methods
+ %swig_vector_methods_val(std::vector<bool, _Alloc >);
+#endif
+
+ %std_vector_methods_val(vector);
+
+#if defined(SWIG_STD_MODERN_STL) && !defined(SWIG_STD_NOMODERN_STL)
+ void flip();
+#endif
+
+ };
+
+}
diff --git a/tests/examplefiles/test.R b/tests/examplefiles/test.R
index 54325339..1dd8f64b 100644
--- a/tests/examplefiles/test.R
+++ b/tests/examplefiles/test.R
@@ -33,10 +33,11 @@ NA_foo_ <- NULL
123456.78901
123e3
123E3
-1.23e-3
-1.23e3
-1.23e-3
-## integer constants
+6.02e23
+1.6e-35
+1.E12
+.1234
+## integers
123L
1.23L
## imaginary numbers
@@ -80,7 +81,7 @@ repeat {1+1}
## Switch
x <- 3
switch(x, 2+2, mean(1:10), rnorm(5))
-## Function, dot-dot-dot, return
+## Function, dot-dot-dot, return, sum
foo <- function(...) {
return(sum(...))
}
@@ -151,3 +152,34 @@ world!'
## Backtick strings
`foo123 +!"bar'baz` <- 2 + 2
+
+## Builtin funcitons
+file.create()
+gamma()
+grep()
+paste()
+rbind()
+rownames()
+R.Version()
+R.version.string()
+sample()
+sapply()
+save.image()
+seq()
+setwd()
+sin()
+
+## Data structures
+servo <- matrix(1:25, nrow = 5)
+numeric()
+vector(servo)
+data.frame()
+list1 <- list(time = 1:40)
+# multidimensional array
+array(c(c(c(2,300,4),c(8,9,0)),c(c(5,60,0),c(66,7,847))), dim=c(3,2,2))
+
+## Namespace
+library(ggplot2)
+require(plyr)
+attach(cars)
+source("test.R")
diff --git a/tests/examplefiles/test.agda b/tests/examplefiles/test.agda
new file mode 100644
index 00000000..f6cea91c
--- /dev/null
+++ b/tests/examplefiles/test.agda
@@ -0,0 +1,109 @@
+-- An Agda example file
+
+module test where
+
+open import Coinduction
+open import Data.Bool
+open import {- pointless comment between import and module name -} Data.Char
+open import Data.Nat
+open import Data.Nat.Properties
+open import Data.String
+open import Data.List hiding ([_])
+open import Data.Vec hiding ([_])
+open import Relation.Nullary.Core
+open import Relation.Binary.PropositionalEquality using (_≡_; refl; cong; trans; inspect; [_])
+ renaming (setoid to setiod)
+
+open SemiringSolver
+
+{- this is a {- nested -} comment -}
+
+postulate pierce : {A B : Set} → ((A → B) → A) → A
+
+instance
+ someBool : Bool
+ someBool = true
+
+-- Factorial
+_! : ℕ → ℕ
+0 ! = 1
+(suc n) ! = (suc n) * n !
+
+-- The binomial coefficient
+_choose_ : ℕ → ℕ → ℕ
+_ choose 0 = 1
+0 choose _ = 0
+(suc n) choose (suc m) = (n choose m) + (n choose (suc m)) -- Pascal's rule
+
+choose-too-many : ∀ n m → n ≤ m → n choose (suc m) ≡ 0
+choose-too-many .0 m z≤n = refl
+choose-too-many (suc n) (suc m) (s≤s le) with n choose (suc m) | choose-too-many n m le | n choose (suc (suc m)) | choose-too-many n (suc m) (≤-step le)
+... | .0 | refl | .0 | refl = refl
+
+_++'_ : ∀ {a n m} {A : Set a} → Vec A n → Vec A m → Vec A (m + n)
+_++'_ {_} {n} {m} v₁ v₂ rewrite solve 2 (λ a b → b :+ a := a :+ b) refl n m = v₁ Data.Vec.++ v₂
+
+++'-test : (1 ∷ 2 ∷ 3 ∷ []) ++' (4 ∷ 5 ∷ []) ≡ (1 ∷ 2 ∷ 3 ∷ 4 ∷ 5 ∷ [])
+++'-test = refl
+
+data Coℕ : Set where
+ co0 : Coℕ
+ cosuc : ∞ Coℕ → Coℕ
+
+nanana : Coℕ
+nanana = let two = ♯ cosuc (♯ (cosuc (♯ co0))) in cosuc two
+
+abstract
+ data VacuumCleaner : Set where
+ Roomba : VacuumCleaner
+
+pointlessLemmaAboutBoolFunctions : (f : Bool → Bool) → f (f (f true)) ≡ f true
+pointlessLemmaAboutBoolFunctions f with f true | inspect f true
+... | true | [ eq₁ ] = trans (cong f eq₁) eq₁
+... | false | [ eq₁ ] with f false | inspect f false
+... | true | _ = eq₁
+... | false | [ eq₂ ] = eq₂
+
+mutual
+ isEven : ℕ → Bool
+ isEven 0 = true
+ isEven (suc n) = not (isOdd n)
+
+ isOdd : ℕ → Bool
+ isOdd 0 = false
+ isOdd (suc n) = not (isEven n)
+
+foo : String
+foo = "Hello World!"
+
+nl : Char
+nl = '\n'
+
+private
+ intersperseString : Char → List String → String
+ intersperseString c [] = ""
+ intersperseString c (x ∷ xs) = Data.List.foldl (λ a b → a Data.String.++ Data.String.fromList (c ∷ []) Data.String.++ b) x xs
+
+baz : String
+baz = intersperseString nl (Data.List.replicate 5 foo)
+
+postulate
+ Float : Set
+
+{-# BUILTIN FLOAT Float #-}
+
+pi : Float
+pi = 3.141593
+
+-- Astronomical unit
+au : Float
+au = 1.496e11 -- m
+
+plusFloat : Float → Float → Float
+plusFloat a b = {! !}
+
+record Subset (A : Set) (P : A → Set) : Set where
+ constructor _#_
+ field
+ elem : A
+ .proof : P elem
diff --git a/tests/examplefiles/test.apl b/tests/examplefiles/test.apl
new file mode 100644
index 00000000..26ecf971
--- /dev/null
+++ b/tests/examplefiles/test.apl
@@ -0,0 +1,26 @@
+∇ R←M COMBIN N;D;E;F;G;P
+ ⍝ Returns a matrix of every possible
+ ⍝ combination of M elements from the
+ ⍝ vector ⍳N. That is, returns a
+ ⍝ matrix with M!N rows and N columns.
+ ⍝
+ E←(⍳P←N-R←M-1)-⎕IO
+ D←R+⍳P
+ R←(P,1)⍴D
+ P←P⍴1
+ L1:→(⎕IO>1↑D←D-1)⍴0
+ P←+\P
+ G←+\¯1↓0,F←⌽P
+ E←F/E-G
+ R←(F/D),R[E+⍳⍴E;]
+ E←G
+ →L1
+∇
+
+∇ R←M QUICKEXP N
+ ⍝ Matrix exponentiation
+ B ← ⌊ 1 + 2 ⍟ N
+ V ← (B ⍴ 2) ⊤ N
+ L ← ⊂ M
+ R ← ⊃ +.× / V / L ⊣ { L ← (⊂ A +.× A ← ↑L) , L }¨ ⍳ B-1
+∇
diff --git a/tests/examplefiles/test.bb b/tests/examplefiles/test.bb
new file mode 100644
index 00000000..026ef22a
--- /dev/null
+++ b/tests/examplefiles/test.bb
@@ -0,0 +1,95 @@
+
+;foobar!
+
+;Include "blurg/blurg.bb"
+
+Const ca = $10000000 ; Hex
+Const cb = %10101010 ; Binary
+Global ga$ = "blargh"
+Local a = 124, b$ = "abcdef"
+
+Function name_123#(zorp$, ll = False, blah#, waffles% = 100)
+ Return 235.7804 ; comment
+End Function
+Function TestString$()
+End Function
+
+Function hub(blah$, abc = Pi)
+End Function
+Function Blar%()
+ Local aa %, ab # ,ac #, ad# ,ae$,af% ; Intentional mangling
+ Local ba#, bb.TBlarf , bc%,bd#,be. TFooBar,ff = True
+End Function
+
+abc()
+
+Function abc()
+ Print "abc" ; I cannot find a way to parse these as function calls without messing something up
+ Print ; Anyhow, they're generally not used in this way
+ Goto Eww_Goto
+ .Eww_Goto
+End Function
+
+Type TBlarf
+End Type
+
+Type TFooBar
+End Type
+
+Local myinst.MyClass = New MyClass
+TestMethod(myinst)
+
+Type MyClass
+
+ Field m_foo.MyClass
+ Field m_bar.MyClass
+
+; abc
+; def
+End Type
+
+Function TestMethod(self.MyClass) ; foobar
+ self\m_foo = self
+ self\m_bar = Object.MyClass(Handle self\m_foo)
+ Yell self\m_foo\m_bar\m_foo\m_bar
+End Function
+
+Function Yell(self.MyClass)
+ Print("huzzah!")
+End Function
+
+Function Wakka$(foo$)
+ Return foo + "bar"
+End Function
+
+
+Print("blah " + "blah " + "blah.")
+
+Local i : For i = 0 To 10 Step 1
+ Print("Index: " + i)
+Next
+Local array$[5]
+array[0] = "foo": array[1] = "bar":array[2] = "11":array[3] = "22":array[4] = "33"
+For i = 0 To 4
+ Local value$ = array[i]
+ Print("Value: " + value)
+Next
+
+Local foobar = Not (1 Or (2 And (4 Shl 5 Shr 6)) Sar 7) Mod (8+2)
+Local az = 1234567890
+az = az + 1
+az = az - 2
+az = az* 3
+az = az/ 4
+az = az And 5
+az = az Or 6
+az= ~ 7
+az = az Shl 8
+az= az Shr 9
+az = az Sar 10
+az = az Mod 11
+az = ((10-5+2/4*2)>(((8^2)) < 2)) And 12 Or 2
+
+
+;~IDEal Editor Parameters:
+;~C#Blitz3D \ No newline at end of file
diff --git a/tests/examplefiles/test.cyp b/tests/examplefiles/test.cyp
new file mode 100644
index 00000000..37465a4d
--- /dev/null
+++ b/tests/examplefiles/test.cyp
@@ -0,0 +1,123 @@
+//test comment
+START a = node(*)
+MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
+RETURN a.name, m.title, d.name;
+
+START a = node(*)
+MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
+WITH d,m,count(a) as Actors
+WHERE Actors > 4
+RETURN d.name as Director,m.title as Movie, Actors ORDER BY Actors;
+
+START a=node(*)
+MATCH p=(a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
+return p;
+
+START a = node(*)
+MATCH p1=(a)-[:ACTED_IN]->(m), p2=d-[:DIRECTED]->(m)
+WHERE m.title="The Matrix"
+RETURN p1, p2;
+
+START a = node(*)
+MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
+WHERE a=d
+RETURN a.name;
+
+START a = node(*)
+MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
+WHERE a=d
+RETURN a.name;
+
+START a=node(*)
+MATCH (a)-[:ACTED_IN]->(m)<-[:DIRECTED]-(d)
+RETURN a.name, d.name, count(*) as Movies,collect(m.title) as Titles
+ORDER BY (Movies) DESC
+LIMIT 5;
+
+START keanu=node:node_auto_index(name="Keanu Reeves")
+RETURN keanu;
+
+START keanu=node:node_auto_index(name="Keanu Reeves")
+MATCH (keanu)-[:ACTED_IN]->(movie)
+RETURN movie.title;
+
+START keanu=node:node_auto_index(name="Keanu Reeves")
+MATCH (keanu)-[r:ACTED_IN]->(movie)
+WHERE "Neo" in r.roles
+RETURN DISTINCT movie.title;
+
+START keanu=node:node_auto_index(name="Keanu Reeves")
+MATCH (keanu)-[:ACTED_IN]->()<-[:DIRECTED]-(director)
+RETURN director.name;
+
+START keanu=node:node_auto_index(name="Keanu Reeves")
+MATCH (keanu)-[:ACTED_IN]->(movie)<-[:ACTED_IN]-(n)
+WHERE n.born < keanu.born
+RETURN DISTINCT n.name, keanu.born ,n.born;
+
+START keanu=node:node_auto_index(name="Keanu Reeves"),
+ hugo=node:node_auto_index(name="Hugo Weaving")
+MATCH (keanu)-[:ACTED_IN]->(movie)
+WHERE NOT((hugo)-[:ACTED_IN]->(movie))
+RETURN DISTINCT movie.title;
+
+START a = node(*)
+MATCH (a)-[:ACTED_IN]->(m)
+WITH a,count(m) as Movies
+RETURN a.name as Actor, Movies ORDER BY Movies;
+
+START keanu=node:node_auto_index(name="Keanu Reeves"),actor
+MATCH past=(keanu)-[:ACTED_IN]->()<-[:ACTED_IN]-(),
+ actors=(actor)-[:ACTED_IN]->()
+WHERE hasnt=actors NOT IN past
+RETURN hasnt;
+
+START keanu=node:node_auto_index(name="Keanu Reeves")
+MATCH (keanu)-[:ACTED_IN]->()<-[:ACTED_IN]-(c),
+ (c)-[:ACTED_IN]->()<-[:ACTED_IN]-(coc)
+WHERE NOT((keanu)-[:ACTED_IN]->()<-[:ACTED_IN]-(coc))
+AND coc > keanu
+RETURN coc.name, count(coc)
+ORDER BY count(coc) DESC
+LIMIT 3;
+
+START kevin=node:node_auto_index(name="Kevin Bacon"),
+ movie=node:node_auto_index(name="Mystic River")
+MATCH (kevin)-[:ACTED_IN]->(movie)
+RETURN DISTINCT movie.title;
+
+CREATE (n
+ {
+ title:"Mystic River",
+ released:1993,
+ tagline:"We bury our sins here, Dave. We wash them clean."
+ }
+ ) RETURN n;
+
+
+START movie=node:node_auto_index(title="Mystic River")
+SET movie.released = 2003
+RETURN movie;
+
+start emil=node:node_auto_index(name="Emil Eifrem") MATCH emil-[r]->(n) DELETE r, emil;
+
+START a=node(*)
+MATCH (a)-[:ACTED_IN]->()<-[:ACTED_IN]-(b)
+CREATE UNIQUE (a)-[:KNOWS]->(b);
+
+START keanu=node:node_auto_index(name="Keanu Reeves")
+MATCH (keanu)-[:KNOWS*2]->(fof)
+WHERE keanu <> fof
+RETURN distinct fof.name;
+
+START charlize=node:node_auto_index(name="Charlize Theron"),
+ bacon=node:node_auto_index(name="Kevin Bacon")
+MATCH p=shortestPath((charlize)-[:KNOWS*]->(bacon))
+RETURN extract(n in nodes(p) | n.name)[1];
+
+START actors=node:
+
+MATCH (alice)-[:`REALLY LIKES`]->(bob)
+MATCH (alice)-[:`REALLY ``LIKES```]->(bob)
+myFancyIdentifier.`(weird property name)`
+"string\t\n\b\f\\\''\""
diff --git a/tests/examplefiles/test.ebnf b/tests/examplefiles/test.ebnf
new file mode 100644
index 00000000..a96171b0
--- /dev/null
+++ b/tests/examplefiles/test.ebnf
@@ -0,0 +1,31 @@
+letter = "A" | "B" | "C" | "D" | "E" | "F" | "G"
+ | "H" | "I" | "J" | "K" | "L" | "M" | "N"
+ | "O" | "P" | "Q" | "R" | "S" | "T" | "U"
+ | "V" | "W" | "X" | "Y" | "Z" ;
+digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9" ;
+symbol = "[" | "]" | "{" | "}" | "(" | ")" | "<" | ">"
+ | "'" | '"' | "=" | "|" | "." | "," | ";" ;
+character = letter | digit | symbol | " " ;
+
+identifier = letter , { letter | digit | " " } ;
+terminal = "'" , character , { character } , "'"
+ | '"' , character , { character } , '"' ;
+
+special = "?" , any , "?" ;
+
+comment = (* this is a comment "" *) "(*" , any-symbol , "*)" ;
+any-symbol = ? any visible character ? ; (* ? ... ? *)
+
+lhs = identifier ;
+rhs = identifier
+ | terminal
+ | comment , rhs
+ | rhs , comment
+ | "[" , rhs , "]"
+ | "{" , rhs , "}"
+ | "(" , rhs , ")"
+ | rhs , "|" , rhs
+ | rhs , "," , rhs ;
+
+rule = lhs , "=" , rhs , ";" | comment ;
+grammar = { rule } ;
diff --git a/tests/examplefiles/test.idr b/tests/examplefiles/test.idr
new file mode 100644
index 00000000..fd008d31
--- /dev/null
+++ b/tests/examplefiles/test.idr
@@ -0,0 +1,101 @@
+module Main
+
+data Ty = TyInt | TyBool | TyFun Ty Ty
+
+interpTy : Ty -> Type
+interpTy TyInt = Int
+interpTy TyBool = Bool
+interpTy (TyFun s t) = interpTy s -> interpTy t
+
+using (G : Vect n Ty)
+
+ data Env : Vect n Ty -> Type where
+ Nil : Env Nil
+ (::) : interpTy a -> Env G -> Env (a :: G)
+
+ data HasType : (i : Fin n) -> Vect n Ty -> Ty -> Type where
+ stop : HasType fZ (t :: G) t
+ pop : HasType k G t -> HasType (fS k) (u :: G) t
+
+ lookup : HasType i G t -> Env G -> interpTy t
+ lookup stop (x :: xs) = x
+ lookup (pop k) (x :: xs) = lookup k xs
+
+ data Expr : Vect n Ty -> Ty -> Type where
+ Var : HasType i G t -> Expr G t
+ Val : (x : Int) -> Expr G TyInt
+ Lam : Expr (a :: G) t -> Expr G (TyFun a t)
+ App : Expr G (TyFun a t) -> Expr G a -> Expr G t
+ Op : (interpTy a -> interpTy b -> interpTy c) -> Expr G a -> Expr G b ->
+ Expr G c
+ If : Expr G TyBool -> Expr G a -> Expr G a -> Expr G a
+ Bind : Expr G a -> (interpTy a -> Expr G b) -> Expr G b
+
+ dsl expr
+ lambda = Lam
+ variable = Var
+ index_first = stop
+ index_next = pop
+
+ (<$>) : |(f : Expr G (TyFun a t)) -> Expr G a -> Expr G t
+ (<$>) = \f, a => App f a
+
+ pure : Expr G a -> Expr G a
+ pure = id
+
+ syntax IF [x] THEN [t] ELSE [e] = If x t e
+
+ (==) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool
+ (==) = Op (==)
+
+ (<) : Expr G TyInt -> Expr G TyInt -> Expr G TyBool
+ (<) = Op (<)
+
+ instance Num (Expr G TyInt) where
+ (+) x y = Op (+) x y
+ (-) x y = Op (-) x y
+ (*) x y = Op (*) x y
+
+ abs x = IF (x < 0) THEN (-x) ELSE x
+
+ fromInteger = Val . fromInteger
+
+ ||| Evaluates an expression in the given context.
+ interp : Env G -> {static} Expr G t -> interpTy t
+ interp env (Var i) = lookup i env
+ interp env (Val x) = x
+ interp env (Lam sc) = \x => interp (x :: env) sc
+ interp env (App f s) = (interp env f) (interp env s)
+ interp env (Op op x y) = op (interp env x) (interp env y)
+ interp env (If x t e) = if (interp env x) then (interp env t) else (interp env e)
+ interp env (Bind v f) = interp env (f (interp env v))
+
+ eId : Expr G (TyFun TyInt TyInt)
+ eId = expr (\x => x)
+
+ eTEST : Expr G (TyFun TyInt (TyFun TyInt TyInt))
+ eTEST = expr (\x, y => y)
+
+ eAdd : Expr G (TyFun TyInt (TyFun TyInt TyInt))
+ eAdd = expr (\x, y => Op (+) x y)
+
+ eDouble : Expr G (TyFun TyInt TyInt)
+ eDouble = expr (\x => App (App eAdd x) (Var stop))
+
+ eFac : Expr G (TyFun TyInt TyInt)
+ eFac = expr (\x => IF x == 0 THEN 1 ELSE [| eFac (x - 1) |] * x)
+
+testFac : Int
+testFac = interp [] eFac 4
+
+--testFacTooBig : Int
+--testFacTooBig = interp [] eFac 100000
+
+ {-testFacTooBig2 : Int
+testFacTooBig2 = interp [] eFac 1000
+-}
+
+main : IO ()
+main = print testFac
+
+
diff --git a/tests/examplefiles/test.mask b/tests/examplefiles/test.mask
new file mode 100644
index 00000000..39134d74
--- /dev/null
+++ b/tests/examplefiles/test.mask
@@ -0,0 +1,41 @@
+
+// comment
+h4.class-1#id.class-2.other checked='true' disabled name = x param > 'Enter ..'
+input placeholder=Password type=password >
+ :dualbind x-signal='dom:create' value=user.passord;
+% each='flowers' >
+ div style='
+ position: absolute;
+ display: inline-block;
+ background: url("image.png") center center no-repeat;
+ ';
+#skippedDiv.other {
+ img src='~[url]';
+ div style="text-align:center;" {
+ '~[: $obj.foo("username", name) + 2]'
+ "~[Localize: stringId]"
+ }
+
+ p > """
+
+ Hello "world"
+ """
+
+ p > '
+ Hello "world"
+ '
+
+ p > "Hello 'world'"
+
+ :customComponent x-value='tt';
+ /* footer > '(c) 2014' */
+}
+
+.skippedDiv >
+ span >
+ #skipped >
+ table >
+ td >
+ tr > ';)'
+
+br; \ No newline at end of file
diff --git a/tests/examplefiles/test.p6 b/tests/examplefiles/test.p6
new file mode 100644
index 00000000..3d12b56c
--- /dev/null
+++ b/tests/examplefiles/test.p6
@@ -0,0 +1,252 @@
+#!/usr/bin/env perl6
+
+use v6;
+
+my $string = 'I look like a # comment!';
+
+if $string eq 'foo' {
+ say 'hello';
+}
+
+regex http-verb {
+ 'GET'
+ | 'POST'
+ | 'PUT'
+ | 'DELETE'
+ | 'TRACE'
+ | 'OPTIONS'
+ | 'HEAD'
+}
+
+# a sample comment
+
+say 'Hello from Perl 6!'
+
+
+#`{
+multi-line comment!
+}
+
+say 'here';
+
+#`(
+multi-line comment!
+)
+
+say 'here';
+
+#`{{{
+I'm a special comment!
+}}}
+
+say 'there';
+
+#`{{
+I'm { even } specialer!
+}}
+
+say 'there';
+
+#`{{
+does {{nesting}} work?
+}}
+
+#`«<
+trying mixed delimiters
+
+my $string = qq<Hooray, arbitrary delimiter!>;
+my $string = qq«Hooray, arbitrary delimiter!»;
+my $string = q <now with whitespace!>;
+my $string = qq<<more strings>>;
+
+my %hash := Hash.new;
+
+=begin pod
+
+Here's some POD! Wooo
+
+=end pod
+
+=for Testing
+ This is POD (see? role isn't highlighted)
+
+say('this is not!');
+
+=table
+ Of role things
+
+say('not in your table');
+#= A single line declarator "block" (with a keyword like role)
+#| Another single line declarator "block" (with a keyword like role)
+#={
+ A declarator block (with a keyword like role)
+ }
+#|{
+ Another declarator block (with a keyword like role)
+ }
+#= { A single line declarator "block" with a brace (with a keyword like role)
+#=«
+ More declarator blocks! (with a keyword like role)
+ »
+#|«
+ More declarator blocks! (with a keyword like role)
+ »
+
+say 'Moar code!';
+
+my $don't = 16;
+
+sub don't($x) {
+ !$x
+}
+
+say don't 'foo';
+
+my %hash = (
+ :foo(1),
+);
+
+say %hash<foo>;
+say %hash<<foo>>;
+say %hash«foo»;
+
+say %*hash<foo>;
+say %*hash<<foo>>;
+say %*hash«foo»;
+
+say $<todo>;
+say $<todo>;
+
+for (@A Z @B) -> $a, $b {
+ say $a + $b;
+}
+
+Q:PIR {
+ .loadlib "somelib"
+}
+
+my $longstring = q/
+ lots
+ of
+ text
+/;
+
+my $heredoc = q:to/END_SQL/;
+SELECT * FROM Users
+WHERE first_name = 'Rob'
+END_SQL
+my $hello;
+
+# Fun with regexen
+
+if 'food' ~~ /foo/ {
+ say 'match!'
+}
+
+my $re = /foo/;
+my $re2 = m/ foo /;
+my $re3 = m:i/ FOO /;
+
+call-a-sub(/ foo /);
+call-a-sub(/ foo \/ bar /);
+
+my $re4 = rx/something | something-else/;
+my $result = ms/regexy stuff/;
+my $sub0 = s/regexy stuff/more stuff/;
+my $sub = ss/regexy stuff/more stuff/;
+my $trans = tr/regexy stuff/more stuff/;
+
+my @values = <a b c d>;
+call-sub(<a b c d>);
+call-sub <a b c d>;
+
+my $result = $a < $b;
+
+for <a b c d> -> $letter {
+ say $letter;
+}
+
+sub test-sub {
+ say @_;
+ say $!;
+ say $/;
+ say $0;
+ say $1;
+ say @*ARGS;
+ say $*ARGFILES;
+ say &?BLOCK;
+ say ::?CLASS;
+ say $?CLASS;
+ say @=COMMENT;
+ say %?CONFIG;
+ say $*CWD;
+ say $=data;
+ say %?DEEPMAGIC;
+ say $?DISTRO;
+ say $*DISTRO;
+ say $*EGID;
+ say %*ENV;
+ say $*ERR;
+ say $*EUID;
+ say $*EXECUTABLE_NAME;
+ say $?FILE;
+ say $?GRAMMAR;
+ say $*GID;
+ say $*IN;
+ say @*INC;
+ say %?LANG;
+ say $*LANG;
+ say $?LINE;
+ say %*META-ARGS;
+ say $?MODULE;
+ say %*OPTS;
+ say %*OPT;
+ say $?KERNEL;
+ say $*KERNEL;
+ say $*OUT;
+ say $?PACKAGE;
+ say $?PERL;
+ say $*PERL;
+ say $*PID;
+ say %=pod;
+ say $*PROGRAM_NAME;
+ say %*PROTOCOLS;
+ say ::?ROLE;
+ say $?ROLE;
+ say &?ROUTINE;
+ say $?SCOPE;
+ say $*TZ;
+ say $*UID;
+ say $?USAGE;
+ say $?VM;
+ say $?XVM;
+}
+
+say <a b c>;
+
+my $perl5_re = m:P5/ fo{2} /;
+my $re5 = rx«something | something-else»;
+
+my $M := %*COMPILING<%?OPTIONS><M>;
+
+say $M;
+
+sub regex-name { ... }
+my $pair = role-name => 'foo';
+$pair = rolesque => 'foo';
+
+my sub something(Str:D $value) { ... }
+
+my $s = q«<
+some
+string
+stuff
+»;
+
+my $regex = m«< some chars »;
+# after
+
+say $/<foo><bar>;
+
+roleq;
diff --git a/tests/examplefiles/test.pan b/tests/examplefiles/test.pan
new file mode 100644
index 00000000..56c8bd62
--- /dev/null
+++ b/tests/examplefiles/test.pan
@@ -0,0 +1,54 @@
+object template pantest;
+
+# Very simple pan test file
+"/long/decimal" = 123;
+"/long/octal" = 0755;
+"/long/hexadecimal" = 0xFF;
+
+"/double/simple" = 0.01;
+"/double/pi" = 3.14159;
+"/double/exponent" = 1e-8;
+"/double/scientific" = 1.3E10;
+
+"/string/single" = 'Faster, but escapes like \t, \n and \x3d don''t work, but '' should work.';
+"/string/double" = "Slower, but escapes like \t, \n and \x3d do work";
+
+variable TEST = 2;
+
+"/x2" = to_string(TEST);
+"/x2" ?= 'Default value';
+
+"/x3" = 1 + 2 + value("/long/decimal");
+
+"/x4" = undef;
+
+"/x5" = null;
+
+variable e ?= error("Test error message");
+
+# include gmond config for services-monitoring
+include { 'site/ganglia/gmond/services-monitoring' };
+
+"/software/packages"=pkg_repl("httpd","2.2.3-43.sl5.3",PKG_ARCH_DEFAULT);
+"/software/packages"=pkg_repl("php");
+
+# Example function
+function show_things_view_for_stuff = {
+ thing = ARGV[0];
+ foreach( i; mything; STUFF ) {
+ if ( thing == mything ) {
+ return( true );
+ } else {
+ return SELF;
+ };
+ };
+ false;
+};
+
+variable HERE = <<EOF;
+; This example demonstrates an in-line heredoc style config file
+[main]
+awesome = true
+EOF
+
+variable small = false;#This should be highlighted normally again.
diff --git a/tests/examplefiles/test.php b/tests/examplefiles/test.php
index 97e21f73..2ce4023e 100644
--- a/tests/examplefiles/test.php
+++ b/tests/examplefiles/test.php
@@ -1,5 +1,7 @@
<?php
+$disapproval_ಠ_ಠ_of_php = 'unicode var';
+
$test = function($a) { $lambda = 1; }
/**
@@ -16,7 +18,7 @@ if(!defined('UNLOCK') || !UNLOCK)
// Load the parent archive class
require_once(ROOT_PATH.'/classes/archive.class.php');
-class Zip\Zipp {
+class Zip\Zippಠ_ಠ_ {
}
@@ -502,4 +504,12 @@ function &byref() {
$x = array();
return $x;
}
+
+ echo <<<EOF
+
+ Test the heredocs...
+
+ EOF;
+
?>
+
diff --git a/tests/examplefiles/test.pig b/tests/examplefiles/test.pig
new file mode 100644
index 00000000..f67b0268
--- /dev/null
+++ b/tests/examplefiles/test.pig
@@ -0,0 +1,148 @@
+/**
+ * This script is an example recommender (using made up data) showing how you might modify item-item links
+ * by defining similar relations between items in a dataset and customizing the change in weighting.
+ * This example creates metadata by using the genre field as the metadata_field. The items with
+ * the same genre have it's weight cut in half in order to boost the signals of movies that do not have the same genre.
+ * This technique requires a customization of the standard GetItemItemRecommendations macro
+ */
+import 'recommenders.pig';
+
+
+
+%default INPUT_PATH_PURCHASES '../data/retail/purchases.json'
+%default INPUT_PATH_WISHLIST '../data/retail/wishlists.json'
+%default INPUT_PATH_INVENTORY '../data/retail/inventory.json'
+%default OUTPUT_PATH '../data/retail/out/modify_item_item'
+
+
+/******** Custom GetItemItemRecommnedations *********/
+define recsys__GetItemItemRecommendations_ModifyCustom(user_item_signals, metadata) returns item_item_recs {
+
+ -- Convert user_item_signals to an item_item_graph
+ ii_links_raw, item_weights = recsys__BuildItemItemGraph(
+ $user_item_signals,
+ $LOGISTIC_PARAM,
+ $MIN_LINK_WEIGHT,
+ $MAX_LINKS_PER_USER
+ );
+ -- NOTE this function is added in order to combine metadata with item-item links
+ -- See macro for more detailed explination
+ ii_links_metadata = recsys__AddMetadataToItemItemLinks(
+ ii_links_raw,
+ $metadata
+ );
+
+ /********* Custom Code starts here ********/
+
+ --The code here should adjust the weights based on an item-item link and the equality of metadata.
+ -- In this case, if the metadata is the same, the weight is reduced. Otherwise the weight is left alone.
+ ii_links_adjusted = foreach ii_links_metadata generate item_A, item_B,
+ -- the amount of weight adjusted is dependant on the domain of data and what is expected
+ -- It is always best to adjust the weight by multiplying it by a factor rather than addition with a constant
+ (metadata_B == metadata_A ? (weight * 0.5): weight) as weight;
+
+
+ /******** Custom Code stops here *********/
+
+ -- remove negative numbers just incase
+ ii_links_adjusted_filt = foreach ii_links_adjusted generate item_A, item_B,
+ (weight <= 0 ? 0: weight) as weight;
+ -- Adjust the weights of the graph to improve recommendations.
+ ii_links = recsys__AdjustItemItemGraphWeight(
+ ii_links_adjusted_filt,
+ item_weights,
+ $BAYESIAN_PRIOR
+ );
+
+ -- Use the item-item graph to create item-item recommendations.
+ $item_item_recs = recsys__BuildItemItemRecommendationsFromGraph(
+ ii_links,
+ $NUM_RECS_PER_ITEM,
+ $NUM_RECS_PER_ITEM
+ );
+};
+
+
+/******* Load Data **********/
+
+--Get purchase signals
+purchase_input = load '$INPUT_PATH_PURCHASES' using org.apache.pig.piggybank.storage.JsonLoader(
+ 'row_id: int,
+ movie_id: chararray,
+ movie_name: chararray,
+ user_id: chararray,
+ purchase_price: int');
+
+--Get wishlist signals
+wishlist_input = load '$INPUT_PATH_WISHLIST' using org.apache.pig.piggybank.storage.JsonLoader(
+ 'row_id: int,
+ movie_id: chararray,
+ movie_name: chararray,
+ user_id: chararray');
+
+
+/******* Convert Data to Signals **********/
+
+-- Start with choosing 1 as max weight for a signal.
+purchase_signals = foreach purchase_input generate
+ user_id as user,
+ movie_name as item,
+ 1.0 as weight;
+
+
+-- Start with choosing 0.5 as weight for wishlist items because that is a weaker signal than
+-- purchasing an item.
+wishlist_signals = foreach wishlist_input generate
+ user_id as user,
+ movie_name as item,
+ 0.5 as weight;
+
+user_signals = union purchase_signals, wishlist_signals;
+
+
+/******** Changes for Modifying item-item links ******/
+inventory_input = load '$INPUT_PATH_INVENTORY' using org.apache.pig.piggybank.storage.JsonLoader(
+ 'movie_title: chararray,
+ genres: bag{tuple(content:chararray)}');
+
+
+metadata = foreach inventory_input generate
+ FLATTEN(genres) as metadata_field,
+ movie_title as item;
+-- requires the macro to be written seperately
+ --NOTE this macro is defined within this file for clarity
+item_item_recs = recsys__GetItemItemRecommendations_ModifyCustom(user_signals, metadata);
+/******* No more changes ********/
+
+
+user_item_recs = recsys__GetUserItemRecommendations(user_signals, item_item_recs);
+
+--Completely unrelated code stuck in the middle
+data = LOAD 's3n://my-s3-bucket/path/to/responses'
+ USING org.apache.pig.piggybank.storage.JsonLoader();
+responses = FOREACH data GENERATE object#'response' AS response: map[];
+out = FOREACH responses
+ GENERATE response#'id' AS id: int, response#'thread' AS thread: chararray,
+ response#'comments' AS comments: {t: (comment: chararray)};
+STORE out INTO 's3n://path/to/output' USING PigStorage('|');
+
+
+/******* Store recommendations **********/
+
+-- If your output folder exists already, hadoop will refuse to write data to it.
+
+rmf $OUTPUT_PATH/item_item_recs;
+rmf $OUTPUT_PATH/user_item_recs;
+
+store item_item_recs into '$OUTPUT_PATH/item_item_recs' using PigStorage();
+store user_item_recs into '$OUTPUT_PATH/user_item_recs' using PigStorage();
+
+-- STORE the item_item_recs into dynamo
+STORE item_item_recs
+ INTO '$OUTPUT_PATH/unused-ii-table-data'
+USING com.mortardata.pig.storage.DynamoDBStorage('$II_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY');
+
+-- STORE the user_item_recs into dynamo
+STORE user_item_recs
+ INTO '$OUTPUT_PATH/unused-ui-table-data'
+USING com.mortardata.pig.storage.DynamoDBStorage('$UI_TABLE', '$AWS_ACCESS_KEY_ID', '$AWS_SECRET_ACCESS_KEY');
diff --git a/tests/examplefiles/test.pwn b/tests/examplefiles/test.pwn
new file mode 100644
index 00000000..d6468617
--- /dev/null
+++ b/tests/examplefiles/test.pwn
@@ -0,0 +1,253 @@
+#include <core>
+
+// Single line comment
+/* Multi line
+ comment */
+
+/// documentation
+/**
+
+ documentation multi line
+
+**/
+
+public OnGameModeInit() {
+ printf("Hello, World!");
+}
+
+enum info {
+ Float:ex;
+ exa,
+ exam[5],
+}
+new arr[5][info];
+
+stock Float:test_func()
+{
+ new a = 5, Float:b = 10.3;
+ if (a == b) {
+
+ } else {
+
+ }
+
+ for (new i = 0; i < 10; i++) {
+ continue;
+ }
+
+ do {
+ a--;
+ } while (a > 0);
+
+ while (a < 5) {
+ a++;
+ break;
+ }
+
+ switch (a) {
+ case 0: {
+ }
+ case 0..4: {
+ }
+ case 5, 6: {
+ }
+ }
+
+ static x;
+ new xx = a > 5 ? 5 : 0;
+ new array[sizeof arr] = {0};
+ tagof a;
+ state a;
+ goto label;
+ new byte[2 char];
+ byte{0} = 'a';
+
+ return (float(a) + b);
+}
+
+
+// float.inc
+/* Float arithmetic
+ *
+ * (c) Copyright 1999, Artran, Inc.
+ * Written by Greg Garner (gmg@artran.com)
+ * Modified in March 2001 to include user defined
+ * operators for the floating point functions.
+ *
+ * This file is provided as is (no warranties).
+ */
+#if defined _Float_included
+ #endinput
+#endif
+#define _Float_included
+#pragma library Float
+
+/* Different methods of rounding */
+enum floatround_method {
+ floatround_round,
+ floatround_floor,
+ floatround_ceil,
+ floatround_tozero,
+ floatround_unbiased
+}
+enum anglemode {
+ radian,
+ degrees,
+ grades
+}
+
+/**************************************************/
+/* Convert an integer into a floating point value */
+native Float:float(value);
+
+/**************************************************/
+/* Convert a string into a floating point value */
+native Float:floatstr(const string[]);
+
+/**************************************************/
+/* Multiple two floats together */
+native Float:floatmul(Float:oper1, Float:oper2);
+
+/**************************************************/
+/* Divide the dividend float by the divisor float */
+native Float:floatdiv(Float:dividend, Float:divisor);
+
+/**************************************************/
+/* Add two floats together */
+native Float:floatadd(Float:oper1, Float:oper2);
+
+/**************************************************/
+/* Subtract oper2 float from oper1 float */
+native Float:floatsub(Float:oper1, Float:oper2);
+
+/**************************************************/
+/* Return the fractional part of a float */
+native Float:floatfract(Float:value);
+
+/**************************************************/
+/* Round a float into a integer value */
+native floatround(Float:value, floatround_method:method=floatround_round);
+
+/**************************************************/
+/* Compare two integers. If the two elements are equal, return 0.
+ If the first argument is greater than the second argument, return 1,
+ If the first argument is less than the second argument, return -1. */
+native floatcmp(Float:oper1, Float:oper2);
+
+/**************************************************/
+/* Return the square root of the input value, same as floatpower(value, 0.5) */
+native Float:floatsqroot(Float:value);
+
+/**************************************************/
+/* Return the value raised to the power of the exponent */
+native Float:floatpower(Float:value, Float:exponent);
+
+/**************************************************/
+/* Return the logarithm */
+native Float:floatlog(Float:value, Float:base=10.0);
+
+/**************************************************/
+/* Return the sine, cosine or tangent. The input angle may be in radian,
+ degrees or grades. */
+native Float:floatsin(Float:value, anglemode:mode=radian);
+native Float:floatcos(Float:value, anglemode:mode=radian);
+native Float:floattan(Float:value, anglemode:mode=radian);
+
+/**************************************************/
+/* Return the absolute value */
+native Float:floatabs(Float:value);
+
+
+/**************************************************/
+#pragma rational Float
+
+/* user defined operators */
+native Float:operator*(Float:oper1, Float:oper2) = floatmul;
+native Float:operator/(Float:oper1, Float:oper2) = floatdiv;
+native Float:operator+(Float:oper1, Float:oper2) = floatadd;
+native Float:operator-(Float:oper1, Float:oper2) = floatsub;
+native Float:operator=(oper) = float;
+
+stock Float:operator++(Float:oper)
+ return oper+1.0;
+
+stock Float:operator--(Float:oper)
+ return oper-1.0;
+
+stock Float:operator-(Float:oper)
+ return oper^Float:cellmin; /* IEEE values are sign/magnitude */
+
+stock Float:operator*(Float:oper1, oper2)
+ return floatmul(oper1, float(oper2)); /* "*" is commutative */
+
+stock Float:operator/(Float:oper1, oper2)
+ return floatdiv(oper1, float(oper2));
+
+stock Float:operator/(oper1, Float:oper2)
+ return floatdiv(float(oper1), oper2);
+
+stock Float:operator+(Float:oper1, oper2)
+ return floatadd(oper1, float(oper2)); /* "+" is commutative */
+
+stock Float:operator-(Float:oper1, oper2)
+ return floatsub(oper1, float(oper2));
+
+stock Float:operator-(oper1, Float:oper2)
+ return floatsub(float(oper1), oper2);
+
+stock bool:operator==(Float:oper1, Float:oper2)
+ return floatcmp(oper1, oper2) == 0;
+
+stock bool:operator==(Float:oper1, oper2)
+ return floatcmp(oper1, float(oper2)) == 0; /* "==" is commutative */
+
+stock bool:operator!=(Float:oper1, Float:oper2)
+ return floatcmp(oper1, oper2) != 0;
+
+stock bool:operator!=(Float:oper1, oper2)
+ return floatcmp(oper1, float(oper2)) != 0; /* "!=" is commutative */
+
+stock bool:operator>(Float:oper1, Float:oper2)
+ return floatcmp(oper1, oper2) > 0;
+
+stock bool:operator>(Float:oper1, oper2)
+ return floatcmp(oper1, float(oper2)) > 0;
+
+stock bool:operator>(oper1, Float:oper2)
+ return floatcmp(float(oper1), oper2) > 0;
+
+stock bool:operator>=(Float:oper1, Float:oper2)
+ return floatcmp(oper1, oper2) >= 0;
+
+stock bool:operator>=(Float:oper1, oper2)
+ return floatcmp(oper1, float(oper2)) >= 0;
+
+stock bool:operator>=(oper1, Float:oper2)
+ return floatcmp(float(oper1), oper2) >= 0;
+
+stock bool:operator<(Float:oper1, Float:oper2)
+ return floatcmp(oper1, oper2) < 0;
+
+stock bool:operator<(Float:oper1, oper2)
+ return floatcmp(oper1, float(oper2)) < 0;
+
+stock bool:operator<(oper1, Float:oper2)
+ return floatcmp(float(oper1), oper2) < 0;
+
+stock bool:operator<=(Float:oper1, Float:oper2)
+ return floatcmp(oper1, oper2) <= 0;
+
+stock bool:operator<=(Float:oper1, oper2)
+ return floatcmp(oper1, float(oper2)) <= 0;
+
+stock bool:operator<=(oper1, Float:oper2)
+ return floatcmp(float(oper1), oper2) <= 0;
+
+stock bool:operator!(Float:oper)
+ return (_:oper & cellmax) == 0;
+
+/* forbidden operations */
+forward operator%(Float:oper1, Float:oper2);
+forward operator%(Float:oper1, oper2);
+forward operator%(oper1, Float:oper2);
+
diff --git a/tests/examplefiles/test.pypylog b/tests/examplefiles/test.pypylog
index f85030cb..1a6aa5ed 100644
--- a/tests/examplefiles/test.pypylog
+++ b/tests/examplefiles/test.pypylog
@@ -998,842 +998,3 @@ setfield_gc(p73, i14, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntO
setarrayitem_gc(p60, 9, p73, descr=<GcPtrArrayDescr>)
p76 = new_with_vtable(19800744)
setfield_gc(p76, f15, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p60, 10, p76, descr=<GcPtrArrayDescr>)
-setfield_gc(p1, 1, descr=<BoolFieldDescr pypy.interpreter.pyframe.PyFrame.inst_frame_finished_execution 148>)
-setfield_gc(p1, ConstPtr(ptr79), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_pycode 112>)
-setfield_gc(p1, ConstPtr(ptr55), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_lastblock 104>)
-setfield_gc(p1, 0, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestackdepth 128>)
-setfield_gc(p1, p4, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_exception 88>)
-setfield_gc(p1, 0, descr=<BoolFieldDescr pypy.interpreter.pyframe.PyFrame.inst_is_being_profiled 149>)
-setfield_gc(p1, 307, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_instr 96>)
-p84 = new_with_vtable(19800744)
-setfield_gc(p84, f36, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-finish(p84, descr=<DoneWithThisFrameDescrRef object at 0x140bcc0>)
-[5ed6619e9448] jit-log-opt-bridge}
-[5ed74f2eef6e] {jit-log-opt-loop
-# Loop 2 : loop with 394 ops
-[p0, p1, p2, p3, p4, p5, p6, p7, i8, f9, i10, i11, p12, p13]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0)
-guard_nonnull_class(p7, 19800744, descr=<Guard180>) [p1, p0, p7, p2, p3, p4, p5, p6, i8]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #24 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #27 COMPARE_OP', 0)
-f15 = getfield_gc_pure(p7, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-i16 = float_gt(f15, f9)
-guard_true(i16, descr=<Guard181>) [p1, p0, p6, p7, p2, p3, p4, p5, i8]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #30 POP_JUMP_IF_FALSE', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #33 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #36 POP_JUMP_IF_FALSE', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #39 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #42 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #45 COMPARE_OP', 0)
-i17 = int_ge(i8, i10)
-guard_false(i17, descr=<Guard182>) [p1, p0, p5, p2, p3, p4, p6, p7, i8]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #48 POP_JUMP_IF_FALSE', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #55 LOAD_GLOBAL', 0)
-p18 = getfield_gc(p0, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>)
-guard_value(p18, ConstPtr(ptr19), descr=<Guard183>) [p1, p0, p18, p2, p3, p4, p5, p6, p7, i8]
-p20 = getfield_gc(p18, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>)
-guard_isnull(p20, descr=<Guard184>) [p1, p0, p20, p18, p2, p3, p4, p5, p6, p7, i8]
-p22 = getfield_gc(ConstPtr(ptr21), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_nonnull_class(p22, ConstClass(Function), descr=<Guard185>) [p1, p0, p22, p2, p3, p4, p5, p6, p7, i8]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #58 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #61 CALL_FUNCTION', 0)
-p24 = getfield_gc(p22, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>)
-guard_value(p24, ConstPtr(ptr25), descr=<Guard186>) [p1, p0, p24, p22, p2, p3, p4, p5, p6, p7, i8]
-p26 = getfield_gc(p22, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>)
-p27 = getfield_gc(p22, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>)
-i28 = force_token()
-i29 = int_is_zero(i11)
-guard_true(i29, descr=<Guard187>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, p26, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #0 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #3 LOAD_ATTR', 1)
-p30 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst_map 48>)
-guard_value(p30, ConstPtr(ptr31), descr=<Guard188>) [p1, p0, p12, p4, p30, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8]
-p33 = getfield_gc(ConstPtr(ptr32), descr=<GcPtrFieldDescr pypy.objspace.std.typeobject.W_TypeObject.inst__version_tag 16>)
-guard_value(p33, ConstPtr(ptr34), descr=<Guard189>) [p1, p0, p12, p4, p33, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8]
-p35 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value2 24>)
-guard_nonnull_class(p35, 19800744, descr=<Guard190>) [p1, p0, p12, p35, p4, p2, p3, p22, p5, p6, p7, p26, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #6 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #9 LOAD_ATTR', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #12 BINARY_MULTIPLY', 1)
-f37 = getfield_gc_pure(p35, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-f38 = float_mul(f37, f37)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #13 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #16 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #19 LOAD_ATTR', 1)
-p39 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value3 32>)
-guard_nonnull_class(p39, 19800744, descr=<Guard191>) [p1, p0, p12, p39, p4, p2, p3, p22, p5, p6, p7, f38, p26, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #22 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #25 LOAD_ATTR', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #28 BINARY_MULTIPLY', 1)
-f41 = getfield_gc_pure(p39, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-f42 = float_mul(f41, f41)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #29 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #32 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #35 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #38 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #41 BINARY_ADD', 1)
-f43 = float_add(f38, f42)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #42 BINARY_DIVIDE', 1)
-i45 = float_eq(f43, 0.000000)
-guard_false(i45, descr=<Guard192>) [p1, p0, p12, f43, p2, p3, p22, p4, p5, p6, p7, f42, f38, p26, p13, i28, i8]
-f47 = float_truediv(0.500000, f43)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #43 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #46 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #49 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #52 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #55 LOAD_ATTR', 1)
-p48 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value0 8>)
-guard_nonnull_class(p48, ConstClass(W_IntObject), descr=<Guard193>) [p1, p0, p12, p48, p4, p2, p3, p22, p5, p6, p7, f47, f42, f38, p26, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #58 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #61 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #64 LOAD_ATTR', 1)
-p50 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value1 16>)
-guard_nonnull_class(p50, ConstClass(W_IntObject), descr=<Guard194>) [p1, p0, p12, p50, p4, p2, p3, p22, p5, p6, p7, p48, f47, f42, f38, p26, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #67 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #70 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #73 LOAD_ATTR', 1)
-p52 = getfield_gc(p4, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value4 40>)
-guard_nonnull_class(p52, 19886912, descr=<Guard195>) [p1, p0, p12, p52, p4, p2, p3, p22, p5, p6, p7, p50, p48, f47, f42, f38, p26, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #76 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #79 SETUP_LOOP', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #82 LOAD_GLOBAL', 1)
-guard_value(p26, ConstPtr(ptr54), descr=<Guard196>) [p1, p0, p12, p26, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p56 = getfield_gc(p26, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>)
-guard_isnull(p56, descr=<Guard197>) [p1, p0, p12, p56, p26, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p58 = getfield_gc(ConstPtr(ptr57), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_isnull(p58, descr=<Guard198>) [p1, p0, p12, p58, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p60 = getfield_gc(ConstPtr(ptr59), descr=<GcPtrFieldDescr pypy.interpreter.module.Module.inst_w_dict 8>)
-guard_value(p60, ConstPtr(ptr61), descr=<Guard199>) [p1, p0, p12, p60, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p62 = getfield_gc(p60, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>)
-guard_isnull(p62, descr=<Guard200>) [p1, p0, p12, p62, p60, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p64 = getfield_gc(ConstPtr(ptr63), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_value(p64, ConstPtr(ptr65), descr=<Guard201>) [p1, p0, p12, p64, p2, p3, p22, p4, p5, p6, p7, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #85 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #88 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #91 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #94 BINARY_SUBTRACT', 1)
-i66 = getfield_gc_pure(p48, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i68 = int_sub_ovf(i66, 1)
-guard_no_overflow(, descr=<Guard202>) [p1, p0, p12, p48, i68, p2, p3, p22, p4, p5, p6, p7, p64, p52, p50, None, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #95 CALL_FUNCTION', 1)
-p70 = getfield_gc(ConstPtr(ptr69), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_name 40>)
-p71 = getfield_gc(ConstPtr(ptr69), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_defs 32>)
-i72 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i72, descr=<Guard203>) [p1, p0, p12, p70, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p73 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-i74 = arraylen_gc(p73, descr=<GcPtrArrayDescr>)
-i76 = int_sub(4, i74)
-i78 = int_ge(3, i76)
-guard_true(i78, descr=<Guard204>) [p1, p0, p12, p70, i76, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i79 = int_sub(3, i76)
-i80 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i80, descr=<Guard205>) [p1, p0, p12, p70, i79, i76, p71, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p81 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-p82 = getarrayitem_gc(p81, i79, descr=<GcPtrArrayDescr>)
-guard_class(p82, ConstClass(W_IntObject), descr=<Guard206>) [p1, p0, p12, p82, p2, p3, p22, p4, p5, p6, p7, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i84 = getfield_gc_pure(p82, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i85 = int_is_zero(i84)
-guard_false(i85, descr=<Guard207>) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i87 = int_lt(i84, 0)
-guard_false(i87, descr=<Guard208>) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i89 = int_lt(1, i68)
-guard_true(i89, descr=<Guard209>) [p1, p0, p12, i84, i68, p2, p3, p22, p4, p5, p6, p7, p82, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i90 = int_sub(i68, 1)
-i92 = int_sub(i90, 1)
-i93 = uint_floordiv(i92, i84)
-i95 = int_add(i93, 1)
-i97 = int_lt(i95, 0)
-guard_false(i97, descr=<Guard210>) [p1, p0, p12, i84, i95, p2, p3, p22, p4, p5, p6, p7, p82, i68, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #98 GET_ITER', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #99 FOR_ITER', 1)
-i99 = int_gt(i95, 0)
-guard_true(i99, descr=<Guard211>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, i84, i95, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i100 = int_add(1, i84)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #102 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #105 SETUP_LOOP', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #108 LOAD_GLOBAL', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #111 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #114 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #117 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #120 BINARY_SUBTRACT', 1)
-i101 = getfield_gc_pure(p50, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i103 = int_sub_ovf(i101, 1)
-guard_no_overflow(, descr=<Guard212>) [p1, p0, p12, p50, i103, p2, p3, p22, p4, p5, p6, p7, i100, i93, i84, None, None, None, None, p52, None, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #121 CALL_FUNCTION', 1)
-i104 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i104, descr=<Guard213>) [p1, p0, p12, p70, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p105 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-i106 = arraylen_gc(p105, descr=<GcPtrArrayDescr>)
-i108 = int_sub(4, i106)
-i110 = int_ge(3, i108)
-guard_true(i110, descr=<Guard214>) [p1, p0, p12, p70, i108, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i111 = int_sub(3, i108)
-i112 = getfield_gc_pure(p71, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i112, descr=<Guard215>) [p1, p0, p12, p70, i111, i108, p71, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p113 = getfield_gc_pure(p71, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-p114 = getarrayitem_gc(p113, i111, descr=<GcPtrArrayDescr>)
-guard_class(p114, ConstClass(W_IntObject), descr=<Guard216>) [p1, p0, p12, p114, p2, p3, p22, p4, p5, p6, p7, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i116 = getfield_gc_pure(p114, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i117 = int_is_zero(i116)
-guard_false(i117, descr=<Guard217>) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i119 = int_lt(i116, 0)
-guard_false(i119, descr=<Guard218>) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i121 = int_lt(1, i103)
-guard_true(i121, descr=<Guard219>) [p1, p0, p12, i116, i103, p2, p3, p22, p4, p5, p6, p7, p114, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i122 = int_sub(i103, 1)
-i124 = int_sub(i122, 1)
-i125 = uint_floordiv(i124, i116)
-i127 = int_add(i125, 1)
-i129 = int_lt(i127, 0)
-guard_false(i129, descr=<Guard220>) [p1, p0, p12, i116, i127, p2, p3, p22, p4, p5, p6, p7, p114, i103, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #124 GET_ITER', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1)
-i131 = int_gt(i127, 0)
-guard_true(i131, descr=<Guard221>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, i116, i127, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i132 = int_add(1, i116)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 1)
-i133 = int_add_ovf(i66, 1)
-guard_no_overflow(, descr=<Guard222>) [p1, p0, p12, i133, p2, p3, p22, p4, p5, p6, p7, i132, i125, i66, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 1)
-i134 = getfield_gc(p52, descr=<SignedFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_len 32>)
-i135 = int_lt(i133, i134)
-guard_true(i135, descr=<Guard223>) [p1, p0, p12, p52, i133, p2, p3, p22, p4, p5, p6, p7, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i136 = getfield_gc(p52, descr=<NonGcPtrFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_buffer 24>)
-f137 = getarrayitem_raw(i136, i133, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 1)
-f138 = getarrayitem_raw(i136, 1, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 1)
-i140 = int_mul_ovf(2, i66)
-guard_no_overflow(, descr=<Guard224>) [p1, p0, p12, p48, i140, p2, p3, p22, p4, p5, p6, p7, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, None, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 1)
-i141 = int_add_ovf(i140, 1)
-guard_no_overflow(, descr=<Guard225>) [p1, p0, p12, i141, p2, p3, p22, p4, p5, p6, p7, i140, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 1)
-i143 = int_lt(i141, 0)
-guard_false(i143, descr=<Guard226>) [p1, p0, p12, p52, i141, i134, p2, p3, p22, p4, p5, p6, p7, None, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8]
-i144 = int_lt(i141, i134)
-guard_true(i144, descr=<Guard227>) [p1, p0, p12, p52, i141, p2, p3, p22, p4, p5, p6, p7, None, f138, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8]
-f145 = getarrayitem_raw(i136, i141, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 1)
-f146 = float_add(f138, f145)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 1)
-f147 = float_mul(f146, f42)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 1)
-i148 = int_lt(i66, i134)
-guard_true(i148, descr=<Guard228>) [p1, p0, p12, p52, i66, p2, p3, p22, p4, p5, p6, p7, f147, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8]
-f149 = getarrayitem_raw(i136, i66, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 1)
-i151 = int_add(i133, 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 1)
-i152 = int_lt(i151, i134)
-guard_true(i152, descr=<Guard229>) [p1, p0, p12, p52, i151, p2, p3, p22, p4, p5, p6, p7, f149, f147, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, None, p50, p48, f47, f42, f38, None, p13, i28, i8]
-f153 = getarrayitem_raw(i136, i151, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 1)
-f154 = float_add(f149, f153)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 1)
-f155 = float_mul(f154, f38)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 1)
-f156 = float_add(f147, f155)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 1)
-f157 = float_mul(f156, f47)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 1)
-setarrayitem_raw(i136, i133, f157, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 1)
-p159 = getfield_gc(ConstPtr(ptr158), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_nonnull_class(p159, ConstClass(Function), descr=<Guard230>) [p1, p0, p12, p159, p2, p3, p22, p4, p5, p6, p7, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 1)
-f161 = getarrayitem_raw(i136, i133, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 1)
-f162 = float_sub(f161, f137)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 1)
-p163 = getfield_gc(p159, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>)
-guard_value(p163, ConstPtr(ptr164), descr=<Guard231>) [p1, p0, p12, p163, p159, p2, p3, p22, p4, p5, p6, p7, f162, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-p165 = getfield_gc(p159, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>)
-p166 = getfield_gc(p159, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>)
-i167 = force_token()
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 2)
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 2)
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 2)
-f168 = float_mul(f162, f162)
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 2)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 1)
-f170 = float_add(0.000000, f168)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 1)
-i172 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-i174 = int_sub(i172, 100)
-setfield_raw(38968960, i174, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-i176 = int_lt(i174, 0)
-guard_false(i176, descr=<Guard232>) [p1, p0, p12, p2, p3, p22, p4, p5, p6, p7, f170, None, None, None, None, None, f137, i132, i125, None, i116, None, None, None, i100, i93, i84, None, None, None, None, p52, p50, p48, f47, f42, f38, None, p13, i28, i8]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1)
-i177 = force_token()
-p179 = new_with_vtable(19809200)
-setfield_gc(p179, i28, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>)
-setfield_gc(p12, p179, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>)
-setfield_gc(p0, i177, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.vable_token 24>)
-p181 = new_with_vtable(19863424)
-setfield_gc(p181, p13, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>)
-setfield_gc(p181, ConstPtr(ptr54), descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>)
-setfield_gc(p181, 34, descr=<INTFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_lineno 144>)
-setfield_gc(p181, ConstPtr(ptr25), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_pycode 112>)
-p184 = new_array(8, descr=<GcPtrArrayDescr>)
-p186 = new_with_vtable(19861240)
-setfield_gc(p186, i100, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>)
-setfield_gc(p186, i93, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>)
-setfield_gc(p186, i84, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>)
-setarrayitem_gc(p184, 0, p186, descr=<GcPtrArrayDescr>)
-p189 = new_with_vtable(19861240)
-setfield_gc(p189, i132, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>)
-setfield_gc(p189, i125, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>)
-setfield_gc(p189, i116, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>)
-setarrayitem_gc(p184, 1, p189, descr=<GcPtrArrayDescr>)
-setfield_gc(p181, p184, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestack_w 120>)
-setfield_gc(p181, 125, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_instr 96>)
-p193 = new_with_vtable(19865144)
-setfield_gc(p193, 291, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>)
-setfield_gc(p193, 1, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>)
-p197 = new_with_vtable(19865144)
-setfield_gc(p197, 295, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>)
-setfield_gc(p193, p197, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>)
-setfield_gc(p181, p193, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_lastblock 104>)
-p200 = new_array(11, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p200, 0, p4, descr=<GcPtrArrayDescr>)
-p203 = new_with_vtable(19800744)
-setfield_gc(p203, f38, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p200, 1, p203, descr=<GcPtrArrayDescr>)
-p206 = new_with_vtable(19800744)
-setfield_gc(p206, f42, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p200, 2, p206, descr=<GcPtrArrayDescr>)
-p209 = new_with_vtable(19800744)
-setfield_gc(p209, f47, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p200, 3, p209, descr=<GcPtrArrayDescr>)
-p212 = new_with_vtable(19800744)
-setfield_gc(p212, f170, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p200, 4, p212, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p200, 5, p48, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p200, 6, p50, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p200, 7, p52, descr=<GcPtrArrayDescr>)
-p218 = new_with_vtable(ConstClass(W_IntObject))
-setfield_gc(p218, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-setarrayitem_gc(p200, 8, p218, descr=<GcPtrArrayDescr>)
-p221 = new_with_vtable(ConstClass(W_IntObject))
-setfield_gc(p221, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-setarrayitem_gc(p200, 9, p221, descr=<GcPtrArrayDescr>)
-p224 = new_with_vtable(19800744)
-setfield_gc(p224, f137, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p200, 10, p224, descr=<GcPtrArrayDescr>)
-setfield_gc(p181, p200, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_fastlocals_w 56>)
-setfield_gc(p181, 2, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestackdepth 128>)
-p235 = call_assembler(p181, p12, ConstPtr(ptr25), p193, 2, ConstPtr(ptr227), 0, 125, p186, p189, ConstPtr(ptr229), ConstPtr(ptr230), ConstPtr(ptr231), ConstPtr(ptr232), ConstPtr(ptr233), ConstPtr(ptr234), p4, p203, p206, p209, p212, p48, p50, p52, p218, p221, p224, descr=<Loop1>)
-guard_not_forced(, descr=<Guard233>) [p1, p0, p12, p181, p235, p179, p2, p3, p22, p4, p5, p6, p7, i8]
-guard_no_exception(, descr=<Guard234>) [p1, p0, p12, p181, p235, p179, p2, p3, p22, p4, p5, p6, p7, i8]
-p236 = getfield_gc(p12, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>)
-guard_isnull(p236, descr=<Guard235>) [p1, p0, p12, p235, p181, p236, p179, p2, p3, p22, p4, p5, p6, p7, i8]
-i237 = ptr_eq(p181, p0)
-guard_false(i237, descr=<Guard236>) [p1, p0, p12, p235, p181, p179, p2, p3, p22, p4, p5, p6, p7, i8]
-i238 = getfield_gc(p12, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>)
-setfield_gc(p181, ConstPtr(ptr239), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_exception 88>)
-i240 = int_is_true(i238)
-guard_false(i240, descr=<Guard237>) [p1, p0, p235, p181, p12, p179, p2, p3, p22, p4, p5, p6, p7, i8]
-p241 = getfield_gc(p181, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #64 STORE_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #67 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #70 LOAD_CONST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #73 INPLACE_ADD', 0)
-i243 = int_add(i8, 1)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #74 STORE_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #77 JUMP_ABSOLUTE', 0)
-i245 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-i247 = int_sub(i245, 100)
-setfield_raw(38968960, i247, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-setfield_gc(p12, p241, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>)
-setfield_gc(p179, p181, descr=<GcPtrFieldDescr JitVirtualRef.forced 16>)
-setfield_gc(p179, -3, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>)
-i250 = int_lt(i247, 0)
-guard_false(i250, descr=<Guard238>) [p1, p0, p2, p3, p4, p5, p6, p235, i243, None]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0)
-jump(p0, p1, p2, p3, p4, p5, p6, p235, i243, f9, i10, i238, p12, p241, descr=<Loop2>)
-[5ed74fc965fa] jit-log-opt-loop}
-[5ed74fe43ee0] {jit-log-opt-loop
-# Loop 3 : entry bridge with 413 ops
-[p0, p1, p2, p3, i4, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0)
-guard_value(i4, 0, descr=<Guard239>) [i4, p1, p0, p2, p3, p5, i6, i7, p8, p9, p10, p11, p12, p13, p14]
-guard_nonnull_class(p13, 19800744, descr=<Guard240>) [p1, p0, p13, p2, p3, p5, i6, p8, p9, p10, p11, p12, p14]
-guard_value(i6, 0, descr=<Guard241>) [i6, p1, p0, p2, p3, p5, p13, p9, p10, p11, p12, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #24 LOAD_FAST', 0)
-guard_nonnull_class(p12, 19800744, descr=<Guard242>) [p1, p0, p12, p2, p3, p5, p13, p9, p10, p11, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #27 COMPARE_OP', 0)
-f19 = getfield_gc_pure(p13, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-f20 = getfield_gc_pure(p12, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-i21 = float_gt(f19, f20)
-guard_true(i21, descr=<Guard243>) [p1, p0, p12, p13, p2, p3, p5, p10, p11, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #30 POP_JUMP_IF_FALSE', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #33 LOAD_FAST', 0)
-guard_nonnull_class(p11, ConstClass(W_IntObject), descr=<Guard244>) [p1, p0, p11, p2, p3, p5, p10, p12, p13, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #36 POP_JUMP_IF_FALSE', 0)
-i23 = getfield_gc_pure(p11, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i24 = int_is_true(i23)
-guard_true(i24, descr=<Guard245>) [p1, p0, p11, p2, p3, p5, p10, p12, p13, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #39 LOAD_FAST', 0)
-guard_nonnull_class(p14, ConstClass(W_IntObject), descr=<Guard246>) [p1, p0, p14, p2, p3, p5, p10, p11, p12, p13]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #42 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #45 COMPARE_OP', 0)
-i26 = getfield_gc_pure(p14, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i27 = int_ge(i26, i23)
-guard_false(i27, descr=<Guard247>) [p1, p0, p11, p14, p2, p3, p5, p10, p12, p13]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #48 POP_JUMP_IF_FALSE', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #55 LOAD_GLOBAL', 0)
-guard_value(p2, ConstPtr(ptr28), descr=<Guard248>) [p1, p0, p2, p3, p5, p10, p11, p12, p13, p14]
-p29 = getfield_gc(p0, descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>)
-guard_value(p29, ConstPtr(ptr30), descr=<Guard249>) [p1, p0, p29, p3, p5, p10, p11, p12, p13, p14]
-p31 = getfield_gc(p29, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>)
-guard_isnull(p31, descr=<Guard250>) [p1, p0, p31, p29, p3, p5, p10, p11, p12, p13, p14]
-p33 = getfield_gc(ConstPtr(ptr32), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_nonnull_class(p33, ConstClass(Function), descr=<Guard251>) [p1, p0, p33, p3, p5, p10, p11, p12, p13, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #58 LOAD_FAST', 0)
-guard_nonnull_class(p10, 19852624, descr=<Guard252>) [p1, p0, p10, p3, p5, p33, p11, p12, p13, p14]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #61 CALL_FUNCTION', 0)
-p36 = getfield_gc(p33, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>)
-guard_value(p36, ConstPtr(ptr37), descr=<Guard253>) [p1, p0, p36, p33, p3, p5, p10, p11, p12, p13, p14]
-p38 = getfield_gc(p33, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>)
-p39 = getfield_gc(p33, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>)
-p41 = call(ConstClass(getexecutioncontext), descr=<GcPtrCallDescr>)
-p42 = getfield_gc(p41, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>)
-i43 = force_token()
-p44 = getfield_gc(p41, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>)
-guard_isnull(p44, descr=<Guard254>) [p1, p0, p41, p44, p3, p5, p33, p10, p11, p12, p13, p14, i43, p42, p38]
-i45 = getfield_gc(p41, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>)
-i46 = int_is_zero(i45)
-guard_true(i46, descr=<Guard255>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i43, p42, p38]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #0 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #3 LOAD_ATTR', 1)
-p47 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst_map 48>)
-guard_value(p47, ConstPtr(ptr48), descr=<Guard256>) [p1, p0, p41, p10, p47, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38]
-p50 = getfield_gc(ConstPtr(ptr49), descr=<GcPtrFieldDescr pypy.objspace.std.typeobject.W_TypeObject.inst__version_tag 16>)
-guard_value(p50, ConstPtr(ptr51), descr=<Guard257>) [p1, p0, p41, p10, p50, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38]
-p52 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value2 24>)
-guard_nonnull_class(p52, 19800744, descr=<Guard258>) [p1, p0, p41, p52, p10, p3, p5, p33, p11, p12, p13, p14, i43, p42, p38]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #6 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #9 LOAD_ATTR', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #12 BINARY_MULTIPLY', 1)
-f54 = getfield_gc_pure(p52, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-f55 = float_mul(f54, f54)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #13 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #16 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #19 LOAD_ATTR', 1)
-p56 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value3 32>)
-guard_nonnull_class(p56, 19800744, descr=<Guard259>) [p1, p0, p41, p56, p10, p3, p5, p33, p11, p12, p13, p14, f55, i43, p42, p38]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #22 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #25 LOAD_ATTR', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #28 BINARY_MULTIPLY', 1)
-f58 = getfield_gc_pure(p56, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-f59 = float_mul(f58, f58)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #29 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #32 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #35 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #38 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #41 BINARY_ADD', 1)
-f60 = float_add(f55, f59)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #42 BINARY_DIVIDE', 1)
-i62 = float_eq(f60, 0.000000)
-guard_false(i62, descr=<Guard260>) [p1, p0, p41, f60, p3, p5, p33, p10, p11, p12, p13, p14, f59, f55, i43, p42, p38]
-f64 = float_truediv(0.500000, f60)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #43 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #46 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #49 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #52 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #55 LOAD_ATTR', 1)
-p65 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value0 8>)
-guard_nonnull_class(p65, ConstClass(W_IntObject), descr=<Guard261>) [p1, p0, p41, p65, p10, p3, p5, p33, p11, p12, p13, p14, f64, f59, f55, i43, p42, p38]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #58 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #61 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #64 LOAD_ATTR', 1)
-p67 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value1 16>)
-guard_nonnull_class(p67, ConstClass(W_IntObject), descr=<Guard262>) [p1, p0, p41, p67, p10, p3, p5, p33, p11, p12, p13, p14, p65, f64, f59, f55, i43, p42, p38]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #67 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #70 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #73 LOAD_ATTR', 1)
-p69 = getfield_gc(p10, descr=<GcPtrFieldDescr pypy.objspace.std.mapdict.W_ObjectObjectSize5.inst__value4 40>)
-guard_nonnull_class(p69, 19886912, descr=<Guard263>) [p1, p0, p41, p69, p10, p3, p5, p33, p11, p12, p13, p14, p67, p65, f64, f59, f55, i43, p42, p38]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #76 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #79 SETUP_LOOP', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #82 LOAD_GLOBAL', 1)
-guard_value(p38, ConstPtr(ptr71), descr=<Guard264>) [p1, p0, p41, p38, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p73 = getfield_gc(p38, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>)
-guard_isnull(p73, descr=<Guard265>) [p1, p0, p41, p73, p38, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p75 = getfield_gc(ConstPtr(ptr74), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_isnull(p75, descr=<Guard266>) [p1, p0, p41, p75, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p77 = getfield_gc(ConstPtr(ptr76), descr=<GcPtrFieldDescr pypy.interpreter.module.Module.inst_w_dict 8>)
-guard_value(p77, ConstPtr(ptr78), descr=<Guard267>) [p1, p0, p41, p77, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p79 = getfield_gc(p77, descr=<GcPtrFieldDescr pypy.objspace.std.dictmultiobject.W_DictMultiObject.inst_r_dict_content 8>)
-guard_isnull(p79, descr=<Guard268>) [p1, p0, p41, p79, p77, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p81 = getfield_gc(ConstPtr(ptr80), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_value(p81, ConstPtr(ptr82), descr=<Guard269>) [p1, p0, p41, p81, p3, p5, p33, p10, p11, p12, p13, p14, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #85 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #88 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #91 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #94 BINARY_SUBTRACT', 1)
-i83 = getfield_gc_pure(p65, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i85 = int_sub_ovf(i83, 1)
-guard_no_overflow(, descr=<Guard270>) [p1, p0, p41, p65, i85, p3, p5, p33, p10, p11, p12, p13, p14, p81, p69, p67, None, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #95 CALL_FUNCTION', 1)
-p87 = getfield_gc(ConstPtr(ptr86), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_name 40>)
-p88 = getfield_gc(ConstPtr(ptr86), descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_defs 32>)
-i89 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i89, descr=<Guard271>) [p1, p0, p41, p87, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p90 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-i91 = arraylen_gc(p90, descr=<GcPtrArrayDescr>)
-i93 = int_sub(4, i91)
-i95 = int_ge(3, i93)
-guard_true(i95, descr=<Guard272>) [p1, p0, p41, p87, i93, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i96 = int_sub(3, i93)
-i97 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i97, descr=<Guard273>) [p1, p0, p41, p87, i96, i93, p88, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p98 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-p99 = getarrayitem_gc(p98, i96, descr=<GcPtrArrayDescr>)
-guard_class(p99, ConstClass(W_IntObject), descr=<Guard274>) [p1, p0, p41, p99, p3, p5, p33, p10, p11, p12, p13, p14, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i101 = getfield_gc_pure(p99, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i102 = int_is_zero(i101)
-guard_false(i102, descr=<Guard275>) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i104 = int_lt(i101, 0)
-guard_false(i104, descr=<Guard276>) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i106 = int_lt(1, i85)
-guard_true(i106, descr=<Guard277>) [p1, p0, p41, i101, i85, p3, p5, p33, p10, p11, p12, p13, p14, p99, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i107 = int_sub(i85, 1)
-i109 = int_sub(i107, 1)
-i110 = uint_floordiv(i109, i101)
-i112 = int_add(i110, 1)
-i114 = int_lt(i112, 0)
-guard_false(i114, descr=<Guard278>) [p1, p0, p41, i101, i112, p3, p5, p33, p10, p11, p12, p13, p14, p99, i85, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #98 GET_ITER', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #99 FOR_ITER', 1)
-i116 = int_gt(i112, 0)
-guard_true(i116, descr=<Guard279>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i112, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i117 = int_add(1, i101)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #102 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #105 SETUP_LOOP', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #108 LOAD_GLOBAL', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #111 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #114 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #117 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #120 BINARY_SUBTRACT', 1)
-i118 = getfield_gc_pure(p67, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i120 = int_sub_ovf(i118, 1)
-guard_no_overflow(, descr=<Guard280>) [p1, p0, p41, p67, i120, p3, p5, p33, p10, p11, p12, p13, p14, i110, i117, None, i101, None, None, None, p69, None, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #121 CALL_FUNCTION', 1)
-i121 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i121, descr=<Guard281>) [p1, p0, p41, p87, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p122 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-i123 = arraylen_gc(p122, descr=<GcPtrArrayDescr>)
-i125 = int_sub(4, i123)
-i127 = int_ge(3, i125)
-guard_true(i127, descr=<Guard282>) [p1, p0, p41, p87, i125, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i128 = int_sub(3, i125)
-i129 = getfield_gc_pure(p88, descr=<BoolFieldDescr pypy.interpreter.function.Defaults.inst_promote 16>)
-guard_false(i129, descr=<Guard283>) [p1, p0, p41, p87, i128, i125, p88, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p130 = getfield_gc_pure(p88, descr=<GcPtrFieldDescr pypy.interpreter.function.Defaults.inst_items 8>)
-p131 = getarrayitem_gc(p130, i128, descr=<GcPtrArrayDescr>)
-guard_class(p131, ConstClass(W_IntObject), descr=<Guard284>) [p1, p0, p41, p131, p3, p5, p33, p10, p11, p12, p13, p14, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i133 = getfield_gc_pure(p131, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-i134 = int_is_zero(i133)
-guard_false(i134, descr=<Guard285>) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i136 = int_lt(i133, 0)
-guard_false(i136, descr=<Guard286>) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i138 = int_lt(1, i120)
-guard_true(i138, descr=<Guard287>) [p1, p0, p41, i133, i120, p3, p5, p33, p10, p11, p12, p13, p14, p131, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i139 = int_sub(i120, 1)
-i141 = int_sub(i139, 1)
-i142 = uint_floordiv(i141, i133)
-i144 = int_add(i142, 1)
-i146 = int_lt(i144, 0)
-guard_false(i146, descr=<Guard288>) [p1, p0, p41, i133, i144, p3, p5, p33, p10, p11, p12, p13, p14, p131, i120, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #124 GET_ITER', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1)
-i148 = int_gt(i144, 0)
-guard_true(i148, descr=<Guard289>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, i144, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-i149 = int_add(1, i133)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #128 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #131 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #134 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #137 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #140 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #141 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #144 BINARY_ADD', 1)
-i150 = int_add_ovf(i83, 1)
-guard_no_overflow(, descr=<Guard290>) [p1, p0, p41, i150, p3, p5, p33, p10, p11, p12, p13, p14, i83, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #145 BINARY_SUBSCR', 1)
-i151 = getfield_gc(p69, descr=<SignedFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_len 32>)
-i152 = int_lt(i150, i151)
-guard_true(i152, descr=<Guard291>) [p1, p0, p41, p69, i150, p3, p5, p33, p10, p11, p12, p13, p14, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None]
-i153 = getfield_gc(p69, descr=<NonGcPtrFieldDescr pypy.module.array.interp_array.W_ArrayTyped.inst_buffer 24>)
-f154 = getarrayitem_raw(i153, i150, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #146 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #149 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #152 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #155 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #158 BINARY_SUBTRACT', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #159 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #162 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #163 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #166 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #167 BINARY_SUBSCR', 1)
-f155 = getarrayitem_raw(i153, 1, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #168 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #171 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #174 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #177 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #178 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #181 BINARY_MULTIPLY', 1)
-i157 = int_mul_ovf(2, i83)
-guard_no_overflow(, descr=<Guard292>) [p1, p0, p41, p65, i157, p3, p5, p33, p10, p11, p12, p13, p14, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, None, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #182 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #185 BINARY_ADD', 1)
-i158 = int_add_ovf(i157, 1)
-guard_no_overflow(, descr=<Guard293>) [p1, p0, p41, i158, p3, p5, p33, p10, p11, p12, p13, p14, i157, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #186 BINARY_SUBSCR', 1)
-i160 = int_lt(i158, 0)
-guard_false(i160, descr=<Guard294>) [p1, p0, p41, p69, i158, i151, p3, p5, p33, p10, p11, p12, p13, p14, None, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None]
-i161 = int_lt(i158, i151)
-guard_true(i161, descr=<Guard295>) [p1, p0, p41, p69, i158, p3, p5, p33, p10, p11, p12, p13, p14, None, f154, f155, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None]
-f162 = getarrayitem_raw(i153, i158, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #187 BINARY_ADD', 1)
-f163 = float_add(f155, f162)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #188 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #191 BINARY_MULTIPLY', 1)
-f164 = float_mul(f163, f59)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #192 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #195 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #198 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #201 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #202 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #205 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #206 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #209 BINARY_SUBTRACT', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #210 BINARY_SUBSCR', 1)
-i165 = int_lt(i83, i151)
-guard_true(i165, descr=<Guard296>) [p1, p0, p41, p69, i83, p3, p5, p33, p10, p11, p12, p13, p14, f164, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None]
-f166 = getarrayitem_raw(i153, i83, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #211 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #214 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #217 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #220 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #221 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #224 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #225 LOAD_CONST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #228 BINARY_ADD', 1)
-i168 = int_add(i150, 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #229 BINARY_SUBSCR', 1)
-i169 = int_lt(i168, i151)
-guard_true(i169, descr=<Guard297>) [p1, p0, p41, p69, i168, p3, p5, p33, p10, p11, p12, p13, p14, f166, f164, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, None, p67, p65, f64, f59, f55, i43, p42, None]
-f170 = getarrayitem_raw(i153, i168, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #230 BINARY_ADD', 1)
-f171 = float_add(f166, f170)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #231 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #234 BINARY_MULTIPLY', 1)
-f172 = float_mul(f171, f55)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #235 BINARY_ADD', 1)
-f173 = float_add(f164, f172)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #236 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #239 BINARY_MULTIPLY', 1)
-f174 = float_mul(f173, f64)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #240 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #243 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #246 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #249 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #250 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #253 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #254 STORE_SUBSCR', 1)
-setarrayitem_raw(i153, i150, f174, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #255 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #258 LOAD_GLOBAL', 1)
-p176 = getfield_gc(ConstPtr(ptr175), descr=<GcPtrFieldDescr pypy.objspace.std.celldict.ModuleCell.inst_w_value 8>)
-guard_nonnull_class(p176, ConstClass(Function), descr=<Guard298>) [p1, p0, p41, p176, p3, p5, p33, p10, p11, p12, p13, p14, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #261 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #264 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #267 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #270 BINARY_MULTIPLY', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #271 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #274 BINARY_ADD', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #275 BINARY_SUBSCR', 1)
-f178 = getarrayitem_raw(i153, i150, descr=<FloatArrayNoLengthDescr>)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #276 LOAD_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #279 BINARY_SUBTRACT', 1)
-f179 = float_sub(f178, f154)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #280 CALL_FUNCTION', 1)
-p180 = getfield_gc(p176, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_code 24>)
-guard_value(p180, ConstPtr(ptr181), descr=<Guard299>) [p1, p0, p41, p180, p176, p3, p5, p33, p10, p11, p12, p13, p14, f179, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-p182 = getfield_gc(p176, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_w_func_globals 64>)
-p183 = getfield_gc(p176, descr=<GcPtrFieldDescr pypy.interpreter.function.Function.inst_closure 16>)
-i184 = force_token()
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #0 LOAD_FAST', 2)
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #3 LOAD_FAST', 2)
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #6 BINARY_MULTIPLY', 2)
-f185 = float_mul(f179, f179)
-debug_merge_point('<code object sqr, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 7> #7 RETURN_VALUE', 2)
-i186 = int_is_true(i45)
-guard_false(i186, descr=<Guard300>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, p182, i184, p176, f185, f179, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #283 INPLACE_ADD', 1)
-f188 = float_add(0.000000, f185)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #284 STORE_FAST', 1)
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #287 JUMP_ABSOLUTE', 1)
-i190 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-i192 = int_sub(i190, 100)
-setfield_raw(38968960, i192, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-i194 = int_lt(i192, 0)
-guard_false(i194, descr=<Guard301>) [p1, p0, p41, p3, p5, p33, p10, p11, p12, p13, p14, f188, None, None, None, None, None, None, None, None, f154, None, None, i149, i142, None, i133, None, None, i110, i117, None, i101, None, None, None, p69, p67, p65, f64, f59, f55, i43, p42, None]
-debug_merge_point('<code object time_step, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 34> #125 FOR_ITER', 1)
-i195 = force_token()
-p197 = new_with_vtable(19809200)
-setfield_gc(p197, i43, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>)
-setfield_gc(p41, p197, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>)
-setfield_gc(p0, i195, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.vable_token 24>)
-p199 = new_with_vtable(19863424)
-setfield_gc(p199, p42, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>)
-setfield_gc(p199, ConstPtr(ptr71), descr=<GcPtrFieldDescr pypy.interpreter.eval.Frame.inst_w_globals 8>)
-setfield_gc(p199, 34, descr=<INTFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_lineno 144>)
-setfield_gc(p199, ConstPtr(ptr37), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_pycode 112>)
-p202 = new_array(8, descr=<GcPtrArrayDescr>)
-p204 = new_with_vtable(19861240)
-setfield_gc(p204, i117, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>)
-setfield_gc(p204, i110, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>)
-setfield_gc(p204, i101, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>)
-setarrayitem_gc(p202, 0, p204, descr=<GcPtrArrayDescr>)
-p207 = new_with_vtable(19861240)
-setfield_gc(p207, i149, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_current 8>)
-setfield_gc(p207, i142, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_remaining 16>)
-setfield_gc(p207, i133, descr=<SignedFieldDescr pypy.module.__builtin__.functional.W_XRangeIterator.inst_step 24>)
-setarrayitem_gc(p202, 1, p207, descr=<GcPtrArrayDescr>)
-setfield_gc(p199, p202, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestack_w 120>)
-setfield_gc(p199, 125, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_instr 96>)
-p211 = new_with_vtable(19865144)
-setfield_gc(p211, 291, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>)
-setfield_gc(p211, 1, descr=<SignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_valuestackdepth 24>)
-p215 = new_with_vtable(19865144)
-setfield_gc(p215, 295, descr=<UnsignedFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_handlerposition 8>)
-setfield_gc(p211, p215, descr=<GcPtrFieldDescr pypy.interpreter.pyopcode.FrameBlock.inst_previous 16>)
-setfield_gc(p199, p211, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_lastblock 104>)
-p218 = new_array(11, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p218, 0, p10, descr=<GcPtrArrayDescr>)
-p221 = new_with_vtable(19800744)
-setfield_gc(p221, f55, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p218, 1, p221, descr=<GcPtrArrayDescr>)
-p224 = new_with_vtable(19800744)
-setfield_gc(p224, f59, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p218, 2, p224, descr=<GcPtrArrayDescr>)
-p227 = new_with_vtable(19800744)
-setfield_gc(p227, f64, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p218, 3, p227, descr=<GcPtrArrayDescr>)
-p230 = new_with_vtable(19800744)
-setfield_gc(p230, f188, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p218, 4, p230, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p218, 5, p65, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p218, 6, p67, descr=<GcPtrArrayDescr>)
-setarrayitem_gc(p218, 7, p69, descr=<GcPtrArrayDescr>)
-p236 = new_with_vtable(ConstClass(W_IntObject))
-setfield_gc(p236, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-setarrayitem_gc(p218, 8, p236, descr=<GcPtrArrayDescr>)
-p239 = new_with_vtable(ConstClass(W_IntObject))
-setfield_gc(p239, 1, descr=<SignedFieldDescr pypy.objspace.std.intobject.W_IntObject.inst_intval 8>)
-setarrayitem_gc(p218, 9, p239, descr=<GcPtrArrayDescr>)
-p242 = new_with_vtable(19800744)
-setfield_gc(p242, f154, descr=<FloatFieldDescr pypy.objspace.std.floatobject.W_FloatObject.inst_floatval 8>)
-setarrayitem_gc(p218, 10, p242, descr=<GcPtrArrayDescr>)
-setfield_gc(p199, p218, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_fastlocals_w 56>)
-setfield_gc(p199, 2, descr=<SignedFieldDescr pypy.interpreter.pyframe.PyFrame.inst_valuestackdepth 128>)
-p253 = call_assembler(p199, p41, ConstPtr(ptr37), p211, 2, ConstPtr(ptr245), 0, 125, p204, p207, ConstPtr(ptr247), ConstPtr(ptr248), ConstPtr(ptr249), ConstPtr(ptr250), ConstPtr(ptr251), ConstPtr(ptr252), p10, p221, p224, p227, p230, p65, p67, p69, p236, p239, p242, descr=<Loop1>)
-guard_not_forced(, descr=<Guard302>) [p1, p0, p41, p199, p253, p197, p3, p5, p33, p10, p11, p12, p13, p14]
-guard_no_exception(, descr=<Guard303>) [p1, p0, p41, p199, p253, p197, p3, p5, p33, p10, p11, p12, p13, p14]
-p254 = getfield_gc(p41, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_w_tracefunc 72>)
-guard_isnull(p254, descr=<Guard304>) [p1, p0, p41, p253, p199, p254, p197, p3, p5, p33, p10, p11, p12, p13, p14]
-i255 = ptr_eq(p199, p0)
-guard_false(i255, descr=<Guard305>) [p1, p0, p41, p253, p199, p197, p3, p5, p33, p10, p11, p12, p13, p14]
-i256 = getfield_gc(p41, descr=<NonGcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_profilefunc 40>)
-setfield_gc(p199, ConstPtr(ptr257), descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_last_exception 88>)
-i258 = int_is_true(i256)
-guard_false(i258, descr=<Guard306>) [p1, p0, p253, p199, p41, p197, p3, p5, p33, p10, p11, p12, p13, p14]
-p259 = getfield_gc(p199, descr=<GcPtrFieldDescr pypy.interpreter.pyframe.PyFrame.inst_f_backref 48>)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #64 STORE_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #67 LOAD_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #70 LOAD_CONST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #73 INPLACE_ADD', 0)
-i261 = int_add(i26, 1)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #74 STORE_FAST', 0)
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #77 JUMP_ABSOLUTE', 0)
-i263 = getfield_raw(38968960, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-i265 = int_sub(i263, 100)
-setfield_raw(38968960, i265, descr=<SignedFieldDescr pypysig_long_struct.c_value 0>)
-setfield_gc(p41, p259, descr=<GcPtrFieldDescr pypy.interpreter.executioncontext.ExecutionContext.inst_topframeref 56>)
-setfield_gc(p197, p199, descr=<GcPtrFieldDescr JitVirtualRef.forced 16>)
-setfield_gc(p197, -3, descr=<SignedFieldDescr JitVirtualRef.virtual_token 8>)
-i268 = int_lt(i265, 0)
-guard_false(i268, descr=<Guard307>) [p1, p0, p3, p5, p10, p11, p12, p253, i261]
-debug_merge_point('<code object laplace_solve, file '/home/alex/projects/hack/benchmarks/laplace/laplace.py', line 52> #21 LOAD_FAST', 0)
-jump(p0, p1, p3, p5, p10, p11, p12, p253, i261, f20, i23, i256, p41, p259, descr=<Loop2>)
-[5ed74ff695c8] jit-log-opt-loop}
-[5ed8737e9776] {jit-backend-counts
-0:493724565
-1:2281802
-2:1283242
-3:993105
-4:2933
-5:2163
-6:2492
-7:1799
-8:963
-9:36
-[5ed8737ee19c] jit-backend-counts}
diff --git a/tests/examplefiles/test.r3 b/tests/examplefiles/test.r3
index cad12a8d..707102db 100644
--- a/tests/examplefiles/test.r3
+++ b/tests/examplefiles/test.r3
@@ -1,3 +1,9 @@
+preface.... everything what is before header is not evaluated
+so this should not be colorized:
+1 + 2
+
+REBOL [] ;<- this is minimal header, everything behind it must be colorized
+
;## String tests ##
print "Hello ^"World" ;<- with escaped char
multiline-string: {
@@ -52,15 +58,29 @@ type? #ff0000 ;== issue!
to integer! (1 + (x / 4.5) * 1E-4)
;## some spec comments
-comment now
-comment 10
+1 + 1
+comment "aa"
+2 + 2
+comment {aa}
+3 + 3
+comment {a^{}
+4 + 4
+comment {{}}
+5 + 5
comment {
- bla
- bla
+ foo: 6
}
-comment [
- quit
-]
+6 + 6
+comment [foo: 6]
+7 + 7
+comment [foo: "[" ]
+8 + 8
+comment [foo: {^{} ]
+9 + 9
+comment [foo: {boo} ]
+10 + 10
+comment 5-May-2014/11:17:34+2:00
+5-May-2014/11:17:34+2:00 11 + 11
;## other tests ##
---: 1
diff --git a/tests/examplefiles/test.rsl b/tests/examplefiles/test.rsl
new file mode 100644
index 00000000..d6c9fc9a
--- /dev/null
+++ b/tests/examplefiles/test.rsl
@@ -0,0 +1,111 @@
+scheme COMPILER =
+class
+ type
+ Prog == mk_Prog(stmt : Stmt),
+
+ Stmt ==
+ mk_Asgn(ide : Identifier, expr : Expr) |
+ mk_If(cond : Expr, s1 : Stmt, s2 : Stmt) |
+ mk_Seq(head : Stmt, last : Stmt),
+
+ Expr ==
+ mk_Const(const : Int) |
+ mk_Plus(fst : Expr, snd : Expr) |
+ mk_Id(ide : Identifier),
+ Identifier = Text
+
+type /* storage for program variables */
+ `Sigma = Identifier -m-> Int
+
+value
+ m : Prog -> `Sigma -> `Sigma
+ m(p)(`sigma) is m(stmt(p))(`sigma),
+
+ m : Stmt -> `Sigma -> `Sigma
+ m(s)(`sigma) is
+ case s of
+ mk_Asgn(i, e) -> `sigma !! [i +> m(e)(`sigma)],
+ mk_Seq(s1, s2) -> m(s2)(m(s1)(`sigma)),
+ mk_If(c, s1, s2) ->
+ if m(c)(`sigma) ~= 0 then m(s1)(`sigma) else m(s2)(`sigma) end
+ end,
+
+ m : Expr -> `Sigma -> Int
+ m(e)(`sigma) is
+ case e of
+ mk_Const(n) -> n,
+ mk_Plus(e1, e2) -> m(e1)(`sigma) + m(e2)(`sigma),
+ mk_Id(id) -> if id isin dom `sigma then `sigma(id) else 0 end
+ end
+
+type
+ MProg = Inst-list,
+ Inst ==
+ mk_Push(ide1 : Identifier) |
+ mk_Pop(Unit) |
+ mk_Add(Unit) |
+ mk_Cnst(val : Int) |
+ mk_Store(ide2 : Identifier) |
+ mk_Jumpfalse(off1 : Int) |
+ mk_Jump(off2 : Int)
+
+
+/* An interpreter for SMALL instructions */
+
+type Stack = Int-list
+value
+ I : MProg >< Int >< Stack -> (`Sigma ->`Sigma)
+ I(mp, pc, s)(`sigma) is
+ if pc <= 0 \/ pc > len mp then `sigma else
+ case mp(pc) of
+ mk_Push(x) -> if x isin dom `sigma
+ then I(mp, pc + 1, <.`sigma(x).> ^ s)(`sigma)
+ else I(mp, pc + 1, <.0.> ^ s)(`sigma) end,
+ mk_Pop(()) -> if len s = 0 then `sigma
+ else I(mp, pc + 1, tl s)(`sigma) end,
+ mk_Cnst(n) -> I(mp, pc + 1, <.n.> ^ s)(`sigma),
+ mk_Add(()) -> if len s < 2 then `sigma
+ else I(mp, pc + 1,<.s(1) + s(2).> ^ tl tl s)(`sigma) end,
+ mk_Store(x) -> if len s = 0 then `sigma
+ else I(mp, pc + 1, s)(`sigma !! [x +> s(1)]) end,
+ mk_Jumpfalse(n) -> if len s = 0 then `sigma
+ elsif hd s ~= 0 then I(mp, pc + 1, s)(`sigma)
+ else I(mp, pc + n, s)(`sigma) end,
+ mk_Jump(n) -> I(mp, pc + n, s)(`sigma)
+ end
+ end
+
+value
+ comp_Prog : Prog -> MProg
+ comp_Prog(p) is comp_Stmt(stmt(p)),
+
+ comp_Stmt : Stmt -> MProg
+ comp_Stmt(s) is
+ case s of
+ mk_Asgn(id, e) -> comp_Expr(e) ^ <. mk_Store(id), mk_Pop() .>,
+ mk_Seq(s1, s2) -> comp_Stmt(s1) ^ comp_Stmt(s2),
+ mk_If(e, s1, s2) ->
+ let
+ ce = comp_Expr(e),
+ cs1 = comp_Stmt(s1), cs2 = comp_Stmt(s2)
+ in
+ ce ^
+ <. mk_Jumpfalse(len cs1 + 3) .> ^
+ <. mk_Pop() .> ^
+ cs1 ^
+ <. mk_Jump(len cs2 + 2) .> ^
+ <. mk_Pop() .> ^
+ cs2
+ end
+ end,
+
+ comp_Expr : Expr -> MProg
+ comp_Expr(e) is
+ case e of
+ mk_Const(n) -> <. mk_Cnst(n) .>,
+ mk_Plus(e1, e2) ->
+ comp_Expr(e1) ^ comp_Expr(e2) ^ <. mk_Add() .>,
+ mk_Id(id) -> <. mk_Push(id) .>
+ end
+
+end
diff --git a/tests/examplefiles/test.swift b/tests/examplefiles/test.swift
new file mode 100644
index 00000000..8ef19763
--- /dev/null
+++ b/tests/examplefiles/test.swift
@@ -0,0 +1,65 @@
+//
+// test.swift
+// from https://github.com/fullstackio/FlappySwift
+//
+// Created by Nate Murray on 6/2/14.
+// Copyright (c) 2014 Fullstack.io. All rights reserved.
+//
+
+import UIKit
+import SpriteKit
+
+extension SKNode {
+ class func unarchiveFromFile(file : NSString) -> SKNode? {
+
+ let path = NSBundle.mainBundle().pathForResource(file, ofType: "sks")
+
+ var sceneData = NSData.dataWithContentsOfFile(path, options: .DataReadingMappedIfSafe, error: nil)
+ var archiver = NSKeyedUnarchiver(forReadingWithData: sceneData)
+
+ archiver.setClass(self.classForKeyedUnarchiver(), forClassName: "SKScene")
+ let scene = archiver.decodeObjectForKey(NSKeyedArchiveRootObjectKey) as GameScene
+ archiver.finishDecoding()
+ return scene
+ }
+}
+
+class GameViewController: UIViewController {
+
+ override func viewDidLoad() {
+ super.viewDidLoad()
+
+ if let scene = GameScene.unarchiveFromFile("GameScene") as? GameScene {
+ // Configure the view.
+ let skView = self.view as SKView
+ skView.showsFPS = true
+ skView.showsNodeCount = true
+
+ /* Sprite Kit applies additional optimizations to improve rendering performance */
+ skView.ignoresSiblingOrder = true
+
+ /* Set the scale mode to scale to fit the window */
+ scene.scaleMode = .AspectFill
+
+ skView.presentScene(scene)
+ }
+ }
+
+ override func shouldAutorotate() -> Bool {
+ return true
+ }
+
+ override func supportedInterfaceOrientations() -> Int {
+ if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
+ return Int(UIInterfaceOrientationMask.AllButUpsideDown.toRaw())
+ } else {
+ return Int(UIInterfaceOrientationMask.All.toRaw())
+ }
+ }
+
+ override func didReceiveMemoryWarning() {
+ super.didReceiveMemoryWarning()
+ // Release any cached data, images, etc that aren't in use.
+ }
+
+}
diff --git a/tests/examplefiles/test.zep b/tests/examplefiles/test.zep
new file mode 100644
index 00000000..4724d4c4
--- /dev/null
+++ b/tests/examplefiles/test.zep
@@ -0,0 +1,33 @@
+namespace Test;
+
+use Test\Foo;
+
+class Bar
+{
+ protected a;
+ private b;
+ public c {set, get};
+
+ public function __construct(string str, boolean bool)
+ {
+ let this->c = str;
+ this->setC(bool);
+ let this->b = [];
+ }
+
+ public function sayHello(string name)
+ {
+ echo "Hello " . name;
+ }
+
+ protected function loops()
+ {
+ for a in b {
+ echo a;
+ }
+ loop {
+ return "boo!";
+ }
+ }
+
+} \ No newline at end of file
diff --git a/tests/examplefiles/type.lisp b/tests/examplefiles/type.lisp
index 9c769379..c02c29df 100644
--- a/tests/examplefiles/type.lisp
+++ b/tests/examplefiles/type.lisp
@@ -1200,3 +1200,19 @@ Henry Baker:
(unless (clos::funcallable-instance-p #'clos::class-name)
(fmakunbound 'clos::class-name))
+
+
+(keywordp :junk)
+ T
+
+(keywordp ::junk)
+ T
+
+(symbol-name ::junk)
+ "JUNK"
+
+(symbol-name :#junk)
+ "#JUNK"
+
+(symbol-name :#.junk)
+ "#.JUNK"
diff --git a/tests/examplefiles/unicode.go b/tests/examplefiles/unicode.go
new file mode 100644
index 00000000..d4bef4d1
--- /dev/null
+++ b/tests/examplefiles/unicode.go
@@ -0,0 +1,10 @@
+package main
+
+import "fmt"
+
+func main() {
+ 世界 := "Hello, world!"
+ さようなら := "Goodbye, world!"
+ fmt.Println(世界)
+ fmt.Println(さようなら)
+}
diff --git a/tests/examplefiles/unicode.js b/tests/examplefiles/unicode.js
new file mode 100644
index 00000000..e77bfb80
--- /dev/null
+++ b/tests/examplefiles/unicode.js
@@ -0,0 +1,5 @@
+var école;
+var sinθ;
+var เมือง;
+var a\u1234b;
+
diff --git a/tests/examplefiles/test.bas b/tests/examplefiles/vbnet_test.bas
index af5f2574..af5f2574 100644
--- a/tests/examplefiles/test.bas
+++ b/tests/examplefiles/vbnet_test.bas
diff --git a/tests/examplefiles/vctreestatus_hg b/tests/examplefiles/vctreestatus_hg
new file mode 100644
index 00000000..193ed803
--- /dev/null
+++ b/tests/examplefiles/vctreestatus_hg
@@ -0,0 +1,4 @@
+M LICENSE
+M setup.py
+! setup.cfg
+? vctreestatus_hg
diff --git a/tests/examplefiles/vimrc b/tests/examplefiles/vimrc
new file mode 100644
index 00000000..d2f9cd1b
--- /dev/null
+++ b/tests/examplefiles/vimrc
@@ -0,0 +1,21 @@
+" A comment
+
+:py print "py"
+::pyt print 'pyt'
+ pyth print '''pyth'''
+ : pytho print "pytho"
+python print """python"""
+
+ : : python<<E OF
+print """my script"""
+
+def MyFunc(str):
+ """ My Function """
+ print str
+E OF
+
+let py = 42
+echo py
+
+let foo = 42
+echo foo
diff --git a/tests/examplefiles/vpath.mk b/tests/examplefiles/vpath.mk
new file mode 100644
index 00000000..a7f18fc3
--- /dev/null
+++ b/tests/examplefiles/vpath.mk
@@ -0,0 +1,16 @@
+vpath %.c src
+vpath %.h header
+EXEC=hello
+SRC= hello.c main.c
+OBJ= $(SRC:.c=.o)
+
+all: $(EXEC)
+
+hello: $(OBJ)
+ $(CC) -o $@ $^ $(LDFLAGS)
+
+main.o: hello.h
+
+%.o: %.c
+ $(CC) -I header -o $@ \
+ -c $< $(CFLAGS)
diff --git a/tests/old_run.py b/tests/old_run.py
deleted file mode 100644
index 4f7cef16..00000000
--- a/tests/old_run.py
+++ /dev/null
@@ -1,138 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- Pygments unit tests
- ~~~~~~~~~~~~~~~~~~
-
- Usage::
-
- python run.py [testfile ...]
-
-
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
- :license: BSD, see LICENSE for details.
-"""
-
-import sys, os
-import unittest
-
-from os.path import dirname, basename, join, abspath
-
-import pygments
-
-try:
- import coverage
-except ImportError:
- coverage = None
-
-testdir = abspath(dirname(__file__))
-
-failed = []
-total_test_count = 0
-error_test_count = 0
-
-
-def err(file, what, exc):
- print >>sys.stderr, file, 'failed %s:' % what,
- print >>sys.stderr, exc
- failed.append(file[:-3])
-
-
-class QuietTestRunner(object):
- """Customized test runner for relatively quiet output"""
-
- def __init__(self, testname, stream=sys.stderr):
- self.testname = testname
- self.stream = unittest._WritelnDecorator(stream)
-
- def run(self, test):
- global total_test_count
- global error_test_count
- result = unittest._TextTestResult(self.stream, True, 1)
- test(result)
- if not result.wasSuccessful():
- self.stream.write(' FAIL:')
- result.printErrors()
- failed.append(self.testname)
- else:
- self.stream.write(' ok\n')
- total_test_count += result.testsRun
- error_test_count += len(result.errors) + len(result.failures)
- return result
-
-
-def run_tests(with_coverage=False):
- # needed to avoid confusion involving atexit handlers
- import logging
-
- if sys.argv[1:]:
- # test only files given on cmdline
- files = [entry + '.py' for entry in sys.argv[1:] if entry.startswith('test_')]
- else:
- files = [entry for entry in os.listdir(testdir)
- if (entry.startswith('test_') and entry.endswith('.py'))]
- files.sort()
-
- WIDTH = 85
-
- print >>sys.stderr, \
- ('Pygments %s Test Suite running%s, stand by...' %
- (pygments.__version__,
- with_coverage and " with coverage analysis" or "")).center(WIDTH)
- print >>sys.stderr, ('(using Python %s)' % sys.version.split()[0]).center(WIDTH)
- print >>sys.stderr, '='*WIDTH
-
- if with_coverage:
- coverage.erase()
- coverage.start()
-
- for testfile in files:
- globs = {'__file__': join(testdir, testfile)}
- try:
- execfile(join(testdir, testfile), globs)
- except Exception, exc:
- raise
- err(testfile, 'execfile', exc)
- continue
- sys.stderr.write(testfile[:-3] + ': ')
- try:
- runner = QuietTestRunner(testfile[:-3])
- # make a test suite of all TestCases in the file
- tests = []
- for name, thing in globs.iteritems():
- if name.endswith('Test'):
- tests.append((name, unittest.makeSuite(thing)))
- tests.sort()
- suite = unittest.TestSuite()
- suite.addTests([x[1] for x in tests])
- runner.run(suite)
- except Exception, exc:
- err(testfile, 'running test', exc)
-
- print >>sys.stderr, '='*WIDTH
- if failed:
- print >>sys.stderr, '%d of %d tests failed.' % \
- (error_test_count, total_test_count)
- print >>sys.stderr, 'Tests failed in:', ', '.join(failed)
- ret = 1
- else:
- if total_test_count == 1:
- print >>sys.stderr, '1 test happy.'
- else:
- print >>sys.stderr, 'All %d tests happy.' % total_test_count
- ret = 0
-
- if with_coverage:
- coverage.stop()
- modules = [mod for name, mod in sys.modules.iteritems()
- if name.startswith('pygments.') and mod]
- coverage.report(modules)
-
- return ret
-
-
-if __name__ == '__main__':
- with_coverage = False
- if sys.argv[1:2] == ['-C']:
- with_coverage = bool(coverage)
- del sys.argv[1]
- sys.exit(run_tests(with_coverage))
diff --git a/tests/run.py b/tests/run.py
index 18a1d824..94d629e8 100644
--- a/tests/run.py
+++ b/tests/run.py
@@ -8,42 +8,38 @@
python run.py [testfile ...]
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-import sys, os
-
-if sys.version_info >= (3,):
- # copy test suite over to "build/lib" and convert it
- print ('Copying and converting sources to build/lib/test...')
- from distutils.util import copydir_run_2to3
- testroot = os.path.dirname(__file__)
- newroot = os.path.join(testroot, '..', 'build/lib/test')
- copydir_run_2to3(testroot, newroot)
- # make nose believe that we run from the converted dir
- os.chdir(newroot)
-else:
- # only find tests in this directory
- if os.path.dirname(__file__):
- os.chdir(os.path.dirname(__file__))
+from __future__ import print_function
+
+import os
+import sys
+
+# only find tests in this directory
+if os.path.dirname(__file__):
+ os.chdir(os.path.dirname(__file__))
try:
import nose
except ImportError:
- print ('nose is required to run the Pygments test suite')
+ print('nose is required to run the Pygments test suite')
sys.exit(1)
try:
# make sure the current source is first on sys.path
sys.path.insert(0, '..')
import pygments
-except ImportError:
- print ('Cannot find Pygments to test: %s' % sys.exc_info()[1])
+except SyntaxError as err:
+ print('Syntax error: %s' % err)
+ sys.exit(1)
+except ImportError as err:
+ print('Cannot find Pygments to test: %s' % err)
sys.exit(1)
else:
- print ('Pygments %s test suite running (Python %s)...' %
- (pygments.__version__, sys.version.split()[0]))
+ print('Pygments %s test suite running (Python %s)...' %
+ (pygments.__version__, sys.version.split()[0]))
nose.main()
diff --git a/tests/string_asserts.py b/tests/string_asserts.py
new file mode 100644
index 00000000..3aa50420
--- /dev/null
+++ b/tests/string_asserts.py
@@ -0,0 +1,22 @@
+# -*- coding: utf-8 -*-
+"""
+ Pygments string assert utility
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+class StringTests(object):
+
+ def assertStartsWith(self, haystack, needle, msg=None):
+ if msg is None:
+ msg = "'{0}' does not start with '{1}'".format(haystack, needle)
+ if not haystack.startswith(needle):
+ raise(AssertionError(msg))
+
+ def assertEndsWith(self, haystack, needle, msg=None):
+ if msg is None:
+ msg = "'{0}' does not end with '{1}'".format(haystack, needle)
+ if not haystack.endswith(needle):
+ raise(AssertionError(msg))
diff --git a/tests/support.py b/tests/support.py
index 505c17da..c66ac663 100644
--- a/tests/support.py
+++ b/tests/support.py
@@ -5,6 +5,8 @@ Support for Pygments tests
import os
+from nose import SkipTest
+
def location(mod_name):
"""
diff --git a/tests/test_basic_api.py b/tests/test_basic_api.py
index 00dc26f0..7485df1a 100644
--- a/tests/test_basic_api.py
+++ b/tests/test_basic_api.py
@@ -3,11 +3,12 @@
Pygments basic API tests
~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-import os
+from __future__ import print_function
+
import random
import unittest
@@ -15,7 +16,7 @@ from pygments import lexers, formatters, filters, format
from pygments.token import _TokenType, Text
from pygments.lexer import RegexLexer
from pygments.formatters.img import FontNotFound
-from pygments.util import BytesIO, StringIO, bytes, b
+from pygments.util import text_type, StringIO, BytesIO, xrange, ClassNotFound
import support
@@ -26,10 +27,12 @@ random.shuffle(test_content)
test_content = ''.join(test_content) + '\n'
-def test_lexer_import_all():
+def test_lexer_instantiate_all():
# instantiate every lexer, to see if the token type defs are correct
- for x in lexers.LEXERS.keys():
- c = getattr(lexers, x)()
+ def verify(name):
+ getattr(lexers, name)
+ for x in lexers.LEXERS:
+ yield verify, x
def test_lexer_classes():
@@ -39,12 +42,14 @@ def test_lexer_classes():
for attr in 'aliases', 'filenames', 'alias_filenames', 'mimetypes':
assert hasattr(cls, attr)
assert type(getattr(cls, attr)) is list, \
- "%s: %s attribute wrong" % (cls, attr)
+ "%s: %s attribute wrong" % (cls, attr)
result = cls.analyse_text("abc")
assert isinstance(result, float) and 0.0 <= result <= 1.0
result = cls.analyse_text(".abc")
assert isinstance(result, float) and 0.0 <= result <= 1.0
+ assert all(al.lower() == al for al in cls.aliases)
+
inst = cls(opt1="val1", opt2="val2")
if issubclass(cls, RegexLexer):
if not hasattr(cls, '_tokens'):
@@ -60,19 +65,22 @@ def test_lexer_classes():
if cls.name in ['XQuery', 'Opa']: # XXX temporary
return
- tokens = list(inst.get_tokens(test_content))
+ try:
+ tokens = list(inst.get_tokens(test_content))
+ except KeyboardInterrupt:
+ raise KeyboardInterrupt(
+ 'interrupted %s.get_tokens(): test_content=%r' %
+ (cls.__name__, test_content))
txt = ""
for token in tokens:
assert isinstance(token, tuple)
assert isinstance(token[0], _TokenType)
- if isinstance(token[1], str):
- print repr(token[1])
- assert isinstance(token[1], unicode)
+ assert isinstance(token[1], text_type)
txt += token[1]
assert txt == test_content, "%s lexer roundtrip failed: %r != %r" % \
- (cls.name, test_content, txt)
+ (cls.name, test_content, txt)
- for lexer in lexers._iter_lexerclasses():
+ for lexer in lexers._iter_lexerclasses(plugins=False):
yield verify, lexer
@@ -81,7 +89,8 @@ def test_lexer_options():
def ensure(tokens, output):
concatenated = ''.join(token[1] for token in tokens)
assert concatenated == output, \
- '%s: %r != %r' % (lexer, concatenated, output)
+ '%s: %r != %r' % (lexer, concatenated, output)
+
def verify(cls):
inst = cls(stripnl=False)
ensure(inst.get_tokens('a\nb'), 'a\nb\n')
@@ -90,17 +99,18 @@ def test_lexer_options():
ensure(inst.get_tokens(' \n b\n\n\n'), 'b\n')
# some lexers require full lines in input
if cls.__name__ not in (
- 'PythonConsoleLexer', 'RConsoleLexer', 'RubyConsoleLexer',
- 'SqliteConsoleLexer', 'MatlabSessionLexer', 'ErlangShellLexer',
- 'BashSessionLexer', 'LiterateHaskellLexer', 'PostgresConsoleLexer',
- 'ElixirConsoleLexer', 'JuliaConsoleLexer', 'RobotFrameworkLexer',
- 'DylanConsoleLexer', 'ShellSessionLexer'):
+ 'PythonConsoleLexer', 'RConsoleLexer', 'RubyConsoleLexer',
+ 'SqliteConsoleLexer', 'MatlabSessionLexer', 'ErlangShellLexer',
+ 'BashSessionLexer', 'LiterateHaskellLexer', 'LiterateAgdaLexer',
+ 'PostgresConsoleLexer', 'ElixirConsoleLexer', 'JuliaConsoleLexer',
+ 'RobotFrameworkLexer', 'DylanConsoleLexer', 'ShellSessionLexer',
+ 'LiterateIdrisLexer', 'LiterateCryptolLexer'):
inst = cls(ensurenl=False)
ensure(inst.get_tokens('a\nb'), 'a\nb')
inst = cls(ensurenl=False, stripall=True)
ensure(inst.get_tokens('a\nb\n\n'), 'a\nb')
- for lexer in lexers._iter_lexerclasses():
+ for lexer in lexers._iter_lexerclasses(plugins=False):
if lexer.__name__ == 'RawTokenLexer':
# this one is special
continue
@@ -122,7 +132,7 @@ def test_get_lexers():
]:
yield verify, func, args
- for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.iteritems():
+ for cls, (_, lname, aliases, _, mimetypes) in lexers.LEXERS.items():
assert cls == lexers.find_lexer_class(lname).__name__
for alias in aliases:
@@ -131,34 +141,47 @@ def test_get_lexers():
for mimetype in mimetypes:
assert cls == lexers.get_lexer_for_mimetype(mimetype).__class__.__name__
+ try:
+ lexers.get_lexer_by_name(None)
+ except ClassNotFound:
+ pass
+ else:
+ raise Exception
+
def test_formatter_public_api():
- ts = list(lexers.PythonLexer().get_tokens("def f(): pass"))
- out = StringIO()
# test that every formatter class has the correct public API
- def verify(formatter, info):
- assert len(info) == 4
- assert info[0], "missing formatter name"
- assert info[1], "missing formatter aliases"
- assert info[3], "missing formatter docstring"
-
- if formatter.name == 'Raw tokens':
- # will not work with Unicode output file
- return
+ ts = list(lexers.PythonLexer().get_tokens("def f(): pass"))
+ string_out = StringIO()
+ bytes_out = BytesIO()
+
+ def verify(formatter):
+ info = formatters.FORMATTERS[formatter.__name__]
+ assert len(info) == 5
+ assert info[1], "missing formatter name"
+ assert info[2], "missing formatter aliases"
+ assert info[4], "missing formatter docstring"
try:
inst = formatter(opt1="val1")
except (ImportError, FontNotFound):
- return
+ raise support.SkipTest
+
try:
inst.get_style_defs()
except NotImplementedError:
# may be raised by formatters for which it doesn't make sense
pass
- inst.format(ts, out)
- for formatter, info in formatters.FORMATTERS.iteritems():
- yield verify, formatter, info
+ if formatter.unicodeoutput:
+ inst.format(ts, string_out)
+ else:
+ inst.format(ts, bytes_out)
+
+ for name in formatters.FORMATTERS:
+ formatter = getattr(formatters, name)
+ yield verify, formatter
+
def test_formatter_encodings():
from pygments.formatters import HtmlFormatter
@@ -167,7 +190,7 @@ def test_formatter_encodings():
fmt = HtmlFormatter()
tokens = [(Text, u"ä")]
out = format(tokens, fmt)
- assert type(out) is unicode
+ assert type(out) is text_type
assert u"ä" in out
# encoding option
@@ -191,12 +214,12 @@ def test_formatter_unicode_handling():
inst = formatter(encoding=None)
except (ImportError, FontNotFound):
# some dependency or font not installed
- return
+ raise support.SkipTest
if formatter.name != 'Raw tokens':
out = format(tokens, inst)
if formatter.unicodeoutput:
- assert type(out) is unicode
+ assert type(out) is text_type, '%s: %r' % (formatter, out)
inst = formatter(encoding='utf-8')
out = format(tokens, inst)
@@ -208,8 +231,10 @@ def test_formatter_unicode_handling():
out = format(tokens, inst)
assert type(out) is bytes, '%s: %r' % (formatter, out)
- for formatter, info in formatters.FORMATTERS.iteritems():
- yield verify, formatter
+ for formatter, info in formatters.FORMATTERS.items():
+ # this tests the automatic importing as well
+ fmter = getattr(formatters, formatter)
+ yield verify, fmter
def test_get_formatters():
@@ -226,27 +251,33 @@ def test_get_formatters():
def test_styles():
# minimal style test
from pygments.formatters import HtmlFormatter
- fmt = HtmlFormatter(style="pastie")
+ HtmlFormatter(style="pastie")
class FiltersTest(unittest.TestCase):
def test_basic(self):
- filter_args = {
- 'whitespace': {'spaces': True, 'tabs': True, 'newlines': True},
- 'highlight': {'names': ['isinstance', 'lexers', 'x']},
- }
- for x in filters.FILTERS.keys():
+ filters_args = [
+ ('whitespace', {'spaces': True, 'tabs': True, 'newlines': True}),
+ ('whitespace', {'wstokentype': False, 'spaces': True}),
+ ('highlight', {'names': ['isinstance', 'lexers', 'x']}),
+ ('codetagify', {'codetags': 'API'}),
+ ('keywordcase', {'case': 'capitalize'}),
+ ('raiseonerror', {}),
+ ('gobble', {'n': 4}),
+ ('tokenmerge', {}),
+ ]
+ for x, args in filters_args:
lx = lexers.PythonLexer()
- lx.add_filter(x, **filter_args.get(x, {}))
- fp = open(TESTFILE, 'rb')
- try:
+ lx.add_filter(x, **args)
+ with open(TESTFILE, 'rb') as fp:
text = fp.read().decode('utf-8')
- finally:
- fp.close()
tokens = list(lx.get_tokens(text))
+ self.assertTrue(all(isinstance(t[1], text_type)
+ for t in tokens),
+ '%s filter did not return Unicode' % x)
roundtext = ''.join([t[1] for t in tokens])
- if x not in ('whitespace', 'keywordcase'):
+ if x not in ('whitespace', 'keywordcase', 'gobble'):
# these filters change the text
self.assertEqual(roundtext, text,
"lexer roundtrip with %s filter failed" % x)
@@ -259,22 +290,16 @@ class FiltersTest(unittest.TestCase):
def test_whitespace(self):
lx = lexers.PythonLexer()
lx.add_filter('whitespace', spaces='%')
- fp = open(TESTFILE, 'rb')
- try:
+ with open(TESTFILE, 'rb') as fp:
text = fp.read().decode('utf-8')
- finally:
- fp.close()
lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))])
self.assertFalse(' ' in lxtext)
def test_keywordcase(self):
lx = lexers.PythonLexer()
lx.add_filter('keywordcase', case='capitalize')
- fp = open(TESTFILE, 'rb')
- try:
+ with open(TESTFILE, 'rb') as fp:
text = fp.read().decode('utf-8')
- finally:
- fp.close()
lxtext = ''.join([t[1] for t in list(lx.get_tokens(text))])
self.assertTrue('Def' in lxtext and 'Class' in lxtext)
diff --git a/tests/test_cfm.py b/tests/test_cfm.py
new file mode 100644
index 00000000..2ff25bd6
--- /dev/null
+++ b/tests/test_cfm.py
@@ -0,0 +1,46 @@
+# -*- coding: utf-8 -*-
+"""
+ Basic ColdfusionHtmlLexer Test
+ ~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+import os
+
+from pygments.token import Token
+from pygments.lexers import ColdfusionHtmlLexer
+
+
+class ColdfusionHtmlLexerTest(unittest.TestCase):
+
+ def setUp(self):
+ self.lexer = ColdfusionHtmlLexer()
+
+ def testBasicComment(self):
+ fragment = u'<!--- cfcomment --->'
+ expected = [
+ (Token.Text, u''),
+ (Token.Comment.Multiline, u'<!---'),
+ (Token.Comment.Multiline, u' cfcomment '),
+ (Token.Comment.Multiline, u'--->'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
+
+ def testNestedComment(self):
+ fragment = u'<!--- nested <!--- cfcomment ---> --->'
+ expected = [
+ (Token.Text, u''),
+ (Token.Comment.Multiline, u'<!---'),
+ (Token.Comment.Multiline, u' nested '),
+ (Token.Comment.Multiline, u'<!---'),
+ (Token.Comment.Multiline, u' cfcomment '),
+ (Token.Comment.Multiline, u'--->'),
+ (Token.Comment.Multiline, u' '),
+ (Token.Comment.Multiline, u'--->'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
diff --git a/tests/test_clexer.py b/tests/test_clexer.py
index 8b37bf57..4aac6d39 100644
--- a/tests/test_clexer.py
+++ b/tests/test_clexer.py
@@ -3,14 +3,15 @@
Basic CLexer Test
~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
import unittest
import os
+import textwrap
-from pygments.token import Text, Number
+from pygments.token import Text, Number, Token
from pygments.lexers import CLexer
@@ -27,5 +28,209 @@ class CLexerTest(unittest.TestCase):
Number.Float, Number.Float], code.split()):
wanted.append(item)
wanted.append((Text, ' '))
- wanted = [(Text, '')] + wanted[:-1] + [(Text, '\n')]
+ wanted = wanted[:-1] + [(Text, '\n')]
self.assertEqual(list(self.lexer.get_tokens(code)), wanted)
+
+ def testSwitch(self):
+ fragment = u'''\
+ int main()
+ {
+ switch (0)
+ {
+ case 0:
+ default:
+ ;
+ }
+ }
+ '''
+ tokens = [
+ (Token.Keyword.Type, u'int'),
+ (Token.Text, u' '),
+ (Token.Name.Function, u'main'),
+ (Token.Punctuation, u'('),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'{'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'switch'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u'('),
+ (Token.Literal.Number.Integer, u'0'),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u'{'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'case'),
+ (Token.Text, u' '),
+ (Token.Literal.Number.Integer, u'0'),
+ (Token.Operator, u':'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'default'),
+ (Token.Operator, u':'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u'}'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'}'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment))))
+
+ def testSwitchSpaceBeforeColon(self):
+ fragment = u'''\
+ int main()
+ {
+ switch (0)
+ {
+ case 0 :
+ default :
+ ;
+ }
+ }
+ '''
+ tokens = [
+ (Token.Keyword.Type, u'int'),
+ (Token.Text, u' '),
+ (Token.Name.Function, u'main'),
+ (Token.Punctuation, u'('),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'{'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'switch'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u'('),
+ (Token.Literal.Number.Integer, u'0'),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u'{'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'case'),
+ (Token.Text, u' '),
+ (Token.Literal.Number.Integer, u'0'),
+ (Token.Text, u' '),
+ (Token.Operator, u':'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'default'),
+ (Token.Text, u' '),
+ (Token.Operator, u':'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u'}'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'}'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment))))
+
+ def testLabel(self):
+ fragment = u'''\
+ int main()
+ {
+ foo:
+ goto foo;
+ }
+ '''
+ tokens = [
+ (Token.Keyword.Type, u'int'),
+ (Token.Text, u' '),
+ (Token.Name.Function, u'main'),
+ (Token.Punctuation, u'('),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'{'),
+ (Token.Text, u'\n'),
+ (Token.Name.Label, u'foo'),
+ (Token.Punctuation, u':'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'goto'),
+ (Token.Text, u' '),
+ (Token.Name, u'foo'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'}'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment))))
+
+ def testLabelSpaceBeforeColon(self):
+ fragment = u'''\
+ int main()
+ {
+ foo :
+ goto foo;
+ }
+ '''
+ tokens = [
+ (Token.Keyword.Type, u'int'),
+ (Token.Text, u' '),
+ (Token.Name.Function, u'main'),
+ (Token.Punctuation, u'('),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'{'),
+ (Token.Text, u'\n'),
+ (Token.Name.Label, u'foo'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u':'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'goto'),
+ (Token.Text, u' '),
+ (Token.Name, u'foo'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'}'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment))))
+
+ def testLabelFollowedByStatement(self):
+ fragment = u'''\
+ int main()
+ {
+ foo:return 0;
+ goto foo;
+ }
+ '''
+ tokens = [
+ (Token.Keyword.Type, u'int'),
+ (Token.Text, u' '),
+ (Token.Name.Function, u'main'),
+ (Token.Punctuation, u'('),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'{'),
+ (Token.Text, u'\n'),
+ (Token.Name.Label, u'foo'),
+ (Token.Punctuation, u':'),
+ (Token.Keyword, u'return'),
+ (Token.Text, u' '),
+ (Token.Literal.Number.Integer, u'0'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'goto'),
+ (Token.Text, u' '),
+ (Token.Name, u'foo'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ (Token.Punctuation, u'}'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(textwrap.dedent(fragment))))
diff --git a/tests/test_cmdline.py b/tests/test_cmdline.py
index 5ad815c0..9e26ce17 100644
--- a/tests/test_cmdline.py
+++ b/tests/test_cmdline.py
@@ -3,17 +3,18 @@
Command line test
~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
-# Test the command line interface
+from __future__ import print_function
-import sys, os
+import io
+import sys
import unittest
-import StringIO
from pygments import highlight
+from pygments.util import StringIO, BytesIO
from pygments.cmdline import main as cmdline_main
import support
@@ -24,14 +25,24 @@ TESTFILE, TESTDIR = support.location(__file__)
def run_cmdline(*args):
saved_stdout = sys.stdout
saved_stderr = sys.stderr
- new_stdout = sys.stdout = StringIO.StringIO()
- new_stderr = sys.stderr = StringIO.StringIO()
+ if sys.version_info > (3,):
+ stdout_buffer = BytesIO()
+ stderr_buffer = BytesIO()
+ new_stdout = sys.stdout = io.TextIOWrapper(stdout_buffer)
+ new_stderr = sys.stderr = io.TextIOWrapper(stderr_buffer)
+ else:
+ stdout_buffer = new_stdout = sys.stdout = StringIO()
+ stderr_buffer = new_stderr = sys.stderr = StringIO()
try:
ret = cmdline_main(["pygmentize"] + list(args))
finally:
sys.stdout = saved_stdout
sys.stderr = saved_stderr
- return (ret, new_stdout.getvalue(), new_stderr.getvalue())
+ new_stdout.flush()
+ new_stderr.flush()
+ out, err = stdout_buffer.getvalue().decode('utf-8'), \
+ stderr_buffer.getvalue().decode('utf-8')
+ return (ret, out, err)
class CmdLineTest(unittest.TestCase):
@@ -82,7 +93,7 @@ class CmdLineTest(unittest.TestCase):
def test_invalid_opts(self):
for opts in [("-L", "-lpy"), ("-L", "-fhtml"), ("-L", "-Ox"),
("-a",), ("-Sst", "-lpy"), ("-H",),
- ("-H", "formatter"),]:
+ ("-H", "formatter")]:
self.assertTrue(run_cmdline(*opts)[0] == 2)
def test_normal(self):
@@ -90,11 +101,8 @@ class CmdLineTest(unittest.TestCase):
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter
filename = TESTFILE
- fp = open(filename, 'rb')
- try:
+ with open(filename, 'rb') as fp:
code = fp.read()
- finally:
- fp.close()
output = highlight(code, PythonLexer(), HtmlFormatter())
diff --git a/tests/test_examplefiles.py b/tests/test_examplefiles.py
index d785cf3b..ac5b4244 100644
--- a/tests/test_examplefiles.py
+++ b/tests/test_examplefiles.py
@@ -3,59 +3,86 @@
Pygments tests with example files
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
+
import os
import pprint
import difflib
-import cPickle as pickle
+import pickle
from pygments.lexers import get_lexer_for_filename, get_lexer_by_name
from pygments.token import Error
-from pygments.util import ClassNotFound, b
+from pygments.util import ClassNotFound
STORE_OUTPUT = False
+STATS = {}
+
+TESTDIR = os.path.dirname(__file__)
+
+
# generate methods
def test_example_files():
- testdir = os.path.dirname(__file__)
- outdir = os.path.join(testdir, 'examplefiles', 'output')
+ global STATS
+ STATS = {}
+ outdir = os.path.join(TESTDIR, 'examplefiles', 'output')
if STORE_OUTPUT and not os.path.isdir(outdir):
os.makedirs(outdir)
- for fn in os.listdir(os.path.join(testdir, 'examplefiles')):
+ for fn in os.listdir(os.path.join(TESTDIR, 'examplefiles')):
if fn.startswith('.') or fn.endswith('#'):
continue
- absfn = os.path.join(testdir, 'examplefiles', fn)
+ absfn = os.path.join(TESTDIR, 'examplefiles', fn)
if not os.path.isfile(absfn):
continue
- outfn = os.path.join(outdir, fn)
+ print(absfn)
+ with open(absfn, 'rb') as f:
+ code = f.read()
try:
- lx = get_lexer_for_filename(absfn)
- except ClassNotFound:
- if "_" not in fn:
+ code = code.decode('utf-8')
+ except UnicodeError:
+ code = code.decode('latin1')
+
+ lx = None
+ if '_' in fn:
+ try:
+ lx = get_lexer_by_name(fn.split('_')[0])
+ except ClassNotFound:
+ pass
+ if lx is None:
+ try:
+ lx = get_lexer_for_filename(absfn, code=code)
+ except ClassNotFound:
raise AssertionError('file %r has no registered extension, '
'nor is of the form <lexer>_filename '
'for overriding, thus no lexer found.'
- % fn)
- try:
- name, rest = fn.split("_", 1)
- lx = get_lexer_by_name(name)
- except ClassNotFound:
- raise AssertionError('no lexer found for file %r' % fn)
- yield check_lexer, lx, absfn, outfn
+ % fn)
+ yield check_lexer, lx, fn
-def check_lexer(lx, absfn, outfn):
- fp = open(absfn, 'rb')
- try:
+ N = 7
+ stats = list(STATS.items())
+ stats.sort(key=lambda x: x[1][1])
+ print('\nExample files that took longest absolute time:')
+ for fn, t in stats[-N:]:
+ print('%-30s %6d chars %8.2f ms %7.3f ms/char' % ((fn,) + t))
+ print()
+ stats.sort(key=lambda x: x[1][2])
+ print('\nExample files that took longest relative time:')
+ for fn, t in stats[-N:]:
+ print('%-30s %6d chars %8.2f ms %7.3f ms/char' % ((fn,) + t))
+
+
+def check_lexer(lx, fn):
+ absfn = os.path.join(TESTDIR, 'examplefiles', fn)
+ with open(absfn, 'rb') as fp:
text = fp.read()
- finally:
- fp.close()
- text = text.replace(b('\r\n'), b('\n'))
- text = text.strip(b('\n')) + b('\n')
+ text = text.replace(b'\r\n', b'\n')
+ text = text.strip(b'\n') + b'\n'
try:
text = text.decode('utf-8')
if text.startswith(u'\ufeff'):
@@ -64,36 +91,36 @@ def check_lexer(lx, absfn, outfn):
text = text.decode('latin1')
ntext = []
tokens = []
+ import time
+ t1 = time.time()
for type, val in lx.get_tokens(text):
ntext.append(val)
assert type != Error, \
'lexer %s generated error token for %s: %r at position %d' % \
(lx, absfn, val, len(u''.join(ntext)))
tokens.append((type, val))
+ t2 = time.time()
+ STATS[os.path.basename(absfn)] = (len(text),
+ 1000 * (t2 - t1), 1000 * (t2 - t1) / len(text))
if u''.join(ntext) != text:
- print '\n'.join(difflib.unified_diff(u''.join(ntext).splitlines(),
- text.splitlines()))
+ print('\n'.join(difflib.unified_diff(u''.join(ntext).splitlines(),
+ text.splitlines())))
raise AssertionError('round trip failed for ' + absfn)
# check output against previous run if enabled
if STORE_OUTPUT:
# no previous output -- store it
+ outfn = os.path.join(TESTDIR, 'examplefiles', 'output', fn)
if not os.path.isfile(outfn):
- fp = open(outfn, 'wb')
- try:
+ with open(outfn, 'wb') as fp:
pickle.dump(tokens, fp)
- finally:
- fp.close()
return
# otherwise load it and compare
- fp = open(outfn, 'rb')
- try:
+ with open(outfn, 'rb') as fp:
stored_tokens = pickle.load(fp)
- finally:
- fp.close()
if stored_tokens != tokens:
f1 = pprint.pformat(stored_tokens)
f2 = pprint.pformat(tokens)
- print '\n'.join(difflib.unified_diff(f1.splitlines(),
- f2.splitlines()))
+ print('\n'.join(difflib.unified_diff(f1.splitlines(),
+ f2.splitlines())))
assert False, absfn
diff --git a/tests/test_html_formatter.py b/tests/test_html_formatter.py
index f7e7a542..5b1b2576 100644
--- a/tests/test_html_formatter.py
+++ b/tests/test_html_formatter.py
@@ -3,41 +3,40 @@
Pygments HTML formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
+
+import io
import os
import re
import unittest
-import StringIO
import tempfile
from os.path import join, dirname, isfile
+from pygments.util import StringIO
from pygments.lexers import PythonLexer
from pygments.formatters import HtmlFormatter, NullFormatter
from pygments.formatters.html import escape_html
-from pygments.util import uni_open
import support
TESTFILE, TESTDIR = support.location(__file__)
-fp = uni_open(TESTFILE, encoding='utf-8')
-try:
+with io.open(TESTFILE, encoding='utf-8') as fp:
tokensource = list(PythonLexer().get_tokens(fp.read()))
-finally:
- fp.close()
class HtmlFormatterTest(unittest.TestCase):
def test_correct_output(self):
hfmt = HtmlFormatter(nowrap=True)
- houtfile = StringIO.StringIO()
+ houtfile = StringIO()
hfmt.format(tokensource, houtfile)
nfmt = NullFormatter()
- noutfile = StringIO.StringIO()
+ noutfile = StringIO()
nfmt.format(tokensource, noutfile)
stripped_html = re.sub('<.*?>', '', houtfile.getvalue())
@@ -74,13 +73,13 @@ class HtmlFormatterTest(unittest.TestCase):
dict(linenos=True, full=True),
dict(linenos=True, full=True, noclasses=True)]:
- outfile = StringIO.StringIO()
+ outfile = StringIO()
fmt = HtmlFormatter(**optdict)
fmt.format(tokensource, outfile)
def test_linenos(self):
optdict = dict(linenos=True)
- outfile = StringIO.StringIO()
+ outfile = StringIO()
fmt = HtmlFormatter(**optdict)
fmt.format(tokensource, outfile)
html = outfile.getvalue()
@@ -88,7 +87,7 @@ class HtmlFormatterTest(unittest.TestCase):
def test_linenos_with_startnum(self):
optdict = dict(linenos=True, linenostart=5)
- outfile = StringIO.StringIO()
+ outfile = StringIO()
fmt = HtmlFormatter(**optdict)
fmt.format(tokensource, outfile)
html = outfile.getvalue()
@@ -96,7 +95,7 @@ class HtmlFormatterTest(unittest.TestCase):
def test_lineanchors(self):
optdict = dict(lineanchors="foo")
- outfile = StringIO.StringIO()
+ outfile = StringIO()
fmt = HtmlFormatter(**optdict)
fmt.format(tokensource, outfile)
html = outfile.getvalue()
@@ -104,7 +103,7 @@ class HtmlFormatterTest(unittest.TestCase):
def test_lineanchors_with_startnum(self):
optdict = dict(lineanchors="foo", linenostart=5)
- outfile = StringIO.StringIO()
+ outfile = StringIO()
fmt = HtmlFormatter(**optdict)
fmt.format(tokensource, outfile)
html = outfile.getvalue()
@@ -132,7 +131,7 @@ class HtmlFormatterTest(unittest.TestCase):
pass
else:
if ret:
- print output
+ print(output)
self.assertFalse(ret, 'nsgmls run reported errors')
os.unlink(pathname)
@@ -172,7 +171,7 @@ class HtmlFormatterTest(unittest.TestCase):
# anymore in the actual source
fmt = HtmlFormatter(tagsfile='support/tags', lineanchors='L',
tagurlformat='%(fname)s%(fext)s')
- outfile = StringIO.StringIO()
+ outfile = StringIO()
fmt.format(tokensource, outfile)
self.assertTrue('<a href="test_html_formatter.py#L-165">test_ctags</a>'
in outfile.getvalue())
diff --git a/tests/test_java.py b/tests/test_java.py
new file mode 100644
index 00000000..9cf96373
--- /dev/null
+++ b/tests/test_java.py
@@ -0,0 +1,42 @@
+# -*- coding: utf-8 -*-
+"""
+ Basic JavaLexer Test
+ ~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+
+from pygments.token import Text, Name, Operator, Keyword
+from pygments.lexers import JavaLexer
+
+
+class JavaTest(unittest.TestCase):
+
+ def setUp(self):
+ self.lexer = JavaLexer()
+ self.maxDiff = None
+
+ def testEnhancedFor(self):
+ fragment = u'label:\nfor(String var2: var1) {}\n'
+ tokens = [
+ (Name.Label, u'label:'),
+ (Text, u'\n'),
+ (Keyword, u'for'),
+ (Operator, u'('),
+ (Name, u'String'),
+ (Text, u' '),
+ (Name, u'var2'),
+ (Operator, u':'),
+ (Text, u' '),
+ (Name, u'var1'),
+ (Operator, u')'),
+ (Text, u' '),
+ (Operator, u'{'),
+ (Operator, u'}'),
+ (Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
diff --git a/tests/test_latex_formatter.py b/tests/test_latex_formatter.py
index 06a74c3d..0a433c85 100644
--- a/tests/test_latex_formatter.py
+++ b/tests/test_latex_formatter.py
@@ -3,10 +3,12 @@
Pygments LaTeX formatter tests
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
+from __future__ import print_function
+
import os
import unittest
import tempfile
@@ -22,11 +24,8 @@ TESTFILE, TESTDIR = support.location(__file__)
class LatexFormatterTest(unittest.TestCase):
def test_valid_output(self):
- fp = open(TESTFILE)
- try:
+ with open(TESTFILE) as fp:
tokensource = list(PythonLexer().get_tokens(fp.read()))
- finally:
- fp.close()
fmt = LatexFormatter(full=True, encoding='latin1')
handle, pathname = tempfile.mkstemp('.tex')
@@ -48,7 +47,7 @@ class LatexFormatterTest(unittest.TestCase):
pass
else:
if ret:
- print output
+ print(output)
self.assertFalse(ret, 'latex run reported errors')
os.unlink(pathname)
diff --git a/tests/test_lexers_other.py b/tests/test_lexers_other.py
new file mode 100644
index 00000000..e3625a2b
--- /dev/null
+++ b/tests/test_lexers_other.py
@@ -0,0 +1,65 @@
+# -*- coding: utf-8 -*-
+"""
+ Tests for other lexers
+ ~~~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import glob
+import os
+import unittest
+
+from pygments.lexers import guess_lexer
+from pygments.lexers.scripting import RexxLexer
+
+
+def _exampleFilePath(filename):
+ return os.path.join(os.path.dirname(__file__), 'examplefiles', filename)
+
+
+class AnalyseTextTest(unittest.TestCase):
+ def _testCanRecognizeAndGuessExampleFiles(self, lexer):
+ assert lexer is not None
+
+ for pattern in lexer.filenames:
+ exampleFilesPattern = _exampleFilePath(pattern)
+ for exampleFilePath in glob.glob(exampleFilesPattern):
+ with open(exampleFilePath, 'rb') as fp:
+ text = fp.read().decode('utf-8')
+ probability = lexer.analyse_text(text)
+ self.assertTrue(probability > 0,
+ '%s must recognize %r' % (
+ lexer.name, exampleFilePath))
+ guessedLexer = guess_lexer(text)
+ self.assertEqual(guessedLexer.name, lexer.name)
+
+ def testCanRecognizeAndGuessExampleFiles(self):
+ self._testCanRecognizeAndGuessExampleFiles(RexxLexer)
+
+
+class RexxLexerTest(unittest.TestCase):
+ def testCanGuessFromText(self):
+ self.assertAlmostEqual(0.01,
+ RexxLexer.analyse_text('/* */'))
+ self.assertAlmostEqual(1.0,
+ RexxLexer.analyse_text('''/* Rexx */
+ say "hello world"'''))
+ val = RexxLexer.analyse_text('/* */\n'
+ 'hello:pRoceduRe\n'
+ ' say "hello world"')
+ self.assertTrue(val > 0.5, val)
+ val = RexxLexer.analyse_text('''/* */
+ if 1 > 0 then do
+ say "ok"
+ end
+ else do
+ say "huh?"
+ end''')
+ self.assertTrue(val > 0.2, val)
+ val = RexxLexer.analyse_text('''/* */
+ greeting = "hello world!"
+ parse value greeting "hello" name "!"
+ say name''')
+ self.assertTrue(val > 0.2, val)
diff --git a/tests/test_objectiveclexer.py b/tests/test_objectiveclexer.py
new file mode 100644
index 00000000..7339f6f7
--- /dev/null
+++ b/tests/test_objectiveclexer.py
@@ -0,0 +1,81 @@
+# -*- coding: utf-8 -*-
+"""
+ Basic CLexer Test
+ ~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+import os
+
+from pygments.token import Token
+from pygments.lexers import ObjectiveCLexer
+
+
+class ObjectiveCLexerTest(unittest.TestCase):
+
+ def setUp(self):
+ self.lexer = ObjectiveCLexer()
+
+ def testLiteralNumberInt(self):
+ fragment = u'@(1);\n'
+ expected = [
+ (Token.Literal, u'@('),
+ (Token.Literal.Number.Integer, u'1'),
+ (Token.Literal, u')'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
+
+ def testLiteralNumberExpression(self):
+ fragment = u'@(1+2);\n'
+ expected = [
+ (Token.Literal, u'@('),
+ (Token.Literal.Number.Integer, u'1'),
+ (Token.Operator, u'+'),
+ (Token.Literal.Number.Integer, u'2'),
+ (Token.Literal, u')'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
+
+ def testLiteralNumberNestedExpression(self):
+ fragment = u'@(1+(2+3));\n'
+ expected = [
+ (Token.Literal, u'@('),
+ (Token.Literal.Number.Integer, u'1'),
+ (Token.Operator, u'+'),
+ (Token.Punctuation, u'('),
+ (Token.Literal.Number.Integer, u'2'),
+ (Token.Operator, u'+'),
+ (Token.Literal.Number.Integer, u'3'),
+ (Token.Punctuation, u')'),
+ (Token.Literal, u')'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
+
+ def testLiteralNumberBool(self):
+ fragment = u'@NO;\n'
+ expected = [
+ (Token.Literal.Number, u'@NO'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
+
+ def testLieralNumberBoolExpression(self):
+ fragment = u'@(YES);\n'
+ expected = [
+ (Token.Literal, u'@('),
+ (Token.Name.Builtin, u'YES'),
+ (Token.Literal, u')'),
+ (Token.Punctuation, u';'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
diff --git a/tests/test_perllexer.py b/tests/test_perllexer.py
index 315b20e3..e37539f2 100644
--- a/tests/test_perllexer.py
+++ b/tests/test_perllexer.py
@@ -3,7 +3,7 @@
Pygments regex lexer tests
~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
@@ -11,7 +11,7 @@ import time
import unittest
from pygments.token import String
-from pygments.lexers.agile import PerlLexer
+from pygments.lexers.perl import PerlLexer
class RunawayRegexTest(unittest.TestCase):
diff --git a/tests/test_qbasiclexer.py b/tests/test_qbasiclexer.py
new file mode 100644
index 00000000..0290b7a1
--- /dev/null
+++ b/tests/test_qbasiclexer.py
@@ -0,0 +1,43 @@
+# -*- coding: utf-8 -*-
+"""
+ Tests for QBasic
+ ~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import glob
+import os
+import unittest
+
+from pygments.token import Token
+from pygments.lexers.basic import QBasicLexer
+
+
+class QBasicTest(unittest.TestCase):
+ def setUp(self):
+ self.lexer = QBasicLexer()
+ self.maxDiff = None
+
+ def testKeywordsWithDollar(self):
+ fragment = u'DIM x\nx = RIGHT$("abc", 1)\n'
+ expected = [
+ (Token.Keyword.Declaration, u'DIM'),
+ (Token.Text.Whitespace, u' '),
+ (Token.Name.Variable.Global, u'x'),
+ (Token.Text, u'\n'),
+ (Token.Name.Variable.Global, u'x'),
+ (Token.Text.Whitespace, u' '),
+ (Token.Operator, u'='),
+ (Token.Text.Whitespace, u' '),
+ (Token.Keyword.Reserved, u'RIGHT$'),
+ (Token.Punctuation, u'('),
+ (Token.Literal.String.Double, u'"abc"'),
+ (Token.Punctuation, u','),
+ (Token.Text.Whitespace, u' '),
+ (Token.Literal.Number.Integer.Long, u'1'),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(expected, list(self.lexer.get_tokens(fragment)))
diff --git a/tests/test_regexlexer.py b/tests/test_regexlexer.py
index 28d9689b..546dfcae 100644
--- a/tests/test_regexlexer.py
+++ b/tests/test_regexlexer.py
@@ -3,7 +3,7 @@
Pygments regex lexer tests
~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
@@ -12,6 +12,7 @@ import unittest
from pygments.token import Text
from pygments.lexer import RegexLexer
from pygments.lexer import bygroups
+from pygments.lexer import default
class TestLexer(RegexLexer):
@@ -20,6 +21,7 @@ class TestLexer(RegexLexer):
'root': [
('a', Text.Root, 'rag'),
('e', Text.Root),
+ default(('beer', 'beer'))
],
'beer': [
('d', Text.Beer, ('#pop', '#pop')),
@@ -45,3 +47,8 @@ class TupleTransTest(unittest.TestCase):
self.assertEqual(toks,
[(0, Text.Root, 'a'), (1, Text, u'\n'),
(2, Text.Root, 'e')])
+
+ def test_default(self):
+ lx = TestLexer()
+ toks = list(lx.get_tokens_unprocessed('d'))
+ self.assertEqual(toks, [(0, Text.Beer, 'd')])
diff --git a/tests/test_regexopt.py b/tests/test_regexopt.py
new file mode 100644
index 00000000..f62a57ef
--- /dev/null
+++ b/tests/test_regexopt.py
@@ -0,0 +1,52 @@
+# -*- coding: utf-8 -*-
+"""
+ Tests for pygments.regexopt
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import re
+import random
+import unittest
+import itertools
+
+from pygments.regexopt import regex_opt
+
+ALPHABET = ['a', 'b', 'c', 'd', 'e']
+
+try:
+ from itertools import combinations_with_replacement
+ N_TRIES = 15
+except ImportError:
+ # Python 2.6
+ def combinations_with_replacement(iterable, r):
+ pool = tuple(iterable)
+ n = len(pool)
+ for indices in itertools.product(range(n), repeat=r):
+ if sorted(indices) == list(indices):
+ yield tuple(pool[i] for i in indices)
+ N_TRIES = 9
+
+
+class RegexOptTestCase(unittest.TestCase):
+
+ def generate_keywordlist(self, length):
+ return [''.join(p) for p in
+ combinations_with_replacement(ALPHABET, length)]
+
+ def test_randomly(self):
+ # generate a list of all possible keywords of a certain length using
+ # a restricted alphabet, then choose some to match and make sure only
+ # those do
+ for n in range(3, N_TRIES):
+ kwlist = self.generate_keywordlist(n)
+ to_match = random.sample(kwlist,
+ random.randint(1, len(kwlist) - 1))
+ no_match = set(kwlist) - set(to_match)
+ rex = re.compile(regex_opt(to_match))
+ for w in to_match:
+ self.assertTrue(rex.match(w))
+ for w in no_match:
+ self.assertFalse(rex.match(w))
diff --git a/tests/test_rtf_formatter.py b/tests/test_rtf_formatter.py
new file mode 100644
index 00000000..30b136fd
--- /dev/null
+++ b/tests/test_rtf_formatter.py
@@ -0,0 +1,109 @@
+# -*- coding: utf-8 -*-
+"""
+ Pygments RTF formatter tests
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+from string_asserts import StringTests
+
+from pygments.util import StringIO
+from pygments.formatters import RtfFormatter
+from pygments.lexers.special import TextLexer
+
+class RtfFormatterTest(StringTests, unittest.TestCase):
+ foot = (r'\par' '\n' r'}')
+
+ def _escape(self, string):
+ return(string.replace("\n", r"\n"))
+
+ def _build_message(self, *args, **kwargs):
+ string = kwargs.get('string', None)
+ t = self._escape(kwargs.get('t', ''))
+ expected = self._escape(kwargs.get('expected', ''))
+ result = self._escape(kwargs.get('result', ''))
+
+ if string is None:
+ string = (u"The expected output of '{t}'\n"
+ u"\t\tShould be '{expected}'\n"
+ u"\t\tActually outputs '{result}'\n"
+ u"\t(WARNING: Partial Output of Result!)")
+
+ end = -(len(self._escape(self.foot)))
+ start = end-len(expected)
+
+ return string.format(t=t,
+ result = result[start:end],
+ expected = expected)
+
+ def format_rtf(self, t):
+ tokensource = list(TextLexer().get_tokens(t))
+ fmt = RtfFormatter()
+ buf = StringIO()
+ fmt.format(tokensource, buf)
+ result = buf.getvalue()
+ buf.close()
+ return result
+
+ def test_rtf_header(self):
+ t = u''
+ result = self.format_rtf(t)
+ expected = r'{\rtf1\ansi\uc0'
+ msg = (u"RTF documents are expected to start with '{expected}'\n"
+ u"\t\tStarts intead with '{result}'\n"
+ u"\t(WARNING: Partial Output of Result!)".format(
+ expected = expected,
+ result = result[:len(expected)]))
+ self.assertStartsWith(result, expected, msg)
+
+ def test_rtf_footer(self):
+ t = u''
+ result = self.format_rtf(t)
+ expected = self.foot
+ msg = (u"RTF documents are expected to end with '{expected}'\n"
+ u"\t\tEnds intead with '{result}'\n"
+ u"\t(WARNING: Partial Output of Result!)".format(
+ expected = self._escape(expected),
+ result = self._escape(result[-len(expected):])))
+ self.assertEndsWith(result, expected, msg)
+
+ def test_ascii_characters(self):
+ t = u'a b c d ~'
+ result = self.format_rtf(t)
+ expected = (r'a b c d ~')
+ if not result.endswith(self.foot):
+ return(unittest.skip('RTF Footer incorrect'))
+ msg = self._build_message(t=t, result=result, expected=expected)
+ self.assertEndsWith(result, expected+self.foot, msg)
+
+ def test_escape_characters(self):
+ t = u'\ {{'
+ result = self.format_rtf(t)
+ expected = (r'\\ \{\{')
+ if not result.endswith(self.foot):
+ return(unittest.skip('RTF Footer incorrect'))
+ msg = self._build_message(t=t, result=result, expected=expected)
+ self.assertEndsWith(result, expected+self.foot, msg)
+
+ def test_single_characters(self):
+ t = u'â € ¤ каждой'
+ result = self.format_rtf(t)
+ expected = (r'{\u226} {\u8364} {\u164} '
+ r'{\u1082}{\u1072}{\u1078}{\u1076}{\u1086}{\u1081}')
+ if not result.endswith(self.foot):
+ return(unittest.skip('RTF Footer incorrect'))
+ msg = self._build_message(t=t, result=result, expected=expected)
+ self.assertEndsWith(result, expected+self.foot, msg)
+
+ def test_double_characters(self):
+ t = u'က 힣 ↕ ↕︎ 鼖'
+ result = self.format_rtf(t)
+ expected = (r'{\u4096} {\u55203} {\u8597} '
+ r'{\u8597}{\u65038} {\u55422}{\u56859}')
+ if not result.endswith(self.foot):
+ return(unittest.skip('RTF Footer incorrect'))
+ msg = self._build_message(t=t, result=result, expected=expected)
+ self.assertEndsWith(result, expected+self.foot, msg)
diff --git a/tests/test_ruby.py b/tests/test_ruby.py
new file mode 100644
index 00000000..89991f74
--- /dev/null
+++ b/tests/test_ruby.py
@@ -0,0 +1,145 @@
+# -*- coding: utf-8 -*-
+"""
+ Basic RubyLexer Test
+ ~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+
+from pygments.token import Operator, Number, Text, Token
+from pygments.lexers import RubyLexer
+
+
+class RubyTest(unittest.TestCase):
+
+ def setUp(self):
+ self.lexer = RubyLexer()
+ self.maxDiff = None
+
+ def testRangeSyntax1(self):
+ fragment = u'1..3\n'
+ tokens = [
+ (Number.Integer, u'1'),
+ (Operator, u'..'),
+ (Number.Integer, u'3'),
+ (Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
+ def testRangeSyntax2(self):
+ fragment = u'1...3\n'
+ tokens = [
+ (Number.Integer, u'1'),
+ (Operator, u'...'),
+ (Number.Integer, u'3'),
+ (Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
+ def testRangeSyntax3(self):
+ fragment = u'1 .. 3\n'
+ tokens = [
+ (Number.Integer, u'1'),
+ (Text, u' '),
+ (Operator, u'..'),
+ (Text, u' '),
+ (Number.Integer, u'3'),
+ (Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
+ def testInterpolationNestedCurly(self):
+ fragment = (
+ u'"A#{ (3..5).group_by { |x| x/2}.map '
+ u'do |k,v| "#{k}" end.join }" + "Z"\n')
+
+ tokens = [
+ (Token.Literal.String.Double, u'"'),
+ (Token.Literal.String.Double, u'A'),
+ (Token.Literal.String.Interpol, u'#{'),
+ (Token.Text, u' '),
+ (Token.Punctuation, u'('),
+ (Token.Literal.Number.Integer, u'3'),
+ (Token.Operator, u'..'),
+ (Token.Literal.Number.Integer, u'5'),
+ (Token.Punctuation, u')'),
+ (Token.Operator, u'.'),
+ (Token.Name, u'group_by'),
+ (Token.Text, u' '),
+ (Token.Literal.String.Interpol, u'{'),
+ (Token.Text, u' '),
+ (Token.Operator, u'|'),
+ (Token.Name, u'x'),
+ (Token.Operator, u'|'),
+ (Token.Text, u' '),
+ (Token.Name, u'x'),
+ (Token.Operator, u'/'),
+ (Token.Literal.Number.Integer, u'2'),
+ (Token.Literal.String.Interpol, u'}'),
+ (Token.Operator, u'.'),
+ (Token.Name, u'map'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'do'),
+ (Token.Text, u' '),
+ (Token.Operator, u'|'),
+ (Token.Name, u'k'),
+ (Token.Punctuation, u','),
+ (Token.Name, u'v'),
+ (Token.Operator, u'|'),
+ (Token.Text, u' '),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Literal.String.Interpol, u'#{'),
+ (Token.Name, u'k'),
+ (Token.Literal.String.Interpol, u'}'),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Text, u' '),
+ (Token.Keyword, u'end'),
+ (Token.Operator, u'.'),
+ (Token.Name, u'join'),
+ (Token.Text, u' '),
+ (Token.Literal.String.Interpol, u'}'),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Text, u' '),
+ (Token.Operator, u'+'),
+ (Token.Text, u' '),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Literal.String.Double, u'Z'),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
+ def testOperatorMethods(self):
+ fragment = u'x.==4\n'
+ tokens = [
+ (Token.Name, u'x'),
+ (Token.Operator, u'.'),
+ (Token.Name.Operator, u'=='),
+ (Token.Literal.Number.Integer, u'4'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
+ def testEscapedBracestring(self):
+ fragment = u'str.gsub(%r{\\\\\\\\}, "/")\n'
+ tokens = [
+ (Token.Name, u'str'),
+ (Token.Operator, u'.'),
+ (Token.Name, u'gsub'),
+ (Token.Punctuation, u'('),
+ (Token.Literal.String.Regex, u'%r{'),
+ (Token.Literal.String.Regex, u'\\\\'),
+ (Token.Literal.String.Regex, u'\\\\'),
+ (Token.Literal.String.Regex, u'}'),
+ (Token.Punctuation, u','),
+ (Token.Text, u' '),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Literal.String.Double, u'/'),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Punctuation, u')'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
diff --git a/tests/test_shell.py b/tests/test_shell.py
new file mode 100644
index 00000000..eb09e8d1
--- /dev/null
+++ b/tests/test_shell.py
@@ -0,0 +1,63 @@
+# -*- coding: utf-8 -*-
+"""
+ Basic Shell Tests
+ ~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+
+from pygments.token import Token
+from pygments.lexers import BashLexer
+
+
+class BashTest(unittest.TestCase):
+
+ def setUp(self):
+ self.lexer = BashLexer()
+ self.maxDiff = None
+
+ def testCurlyNoEscapeAndQuotes(self):
+ fragment = u'echo "${a//["b"]/}"\n'
+ tokens = [
+ (Token.Name.Builtin, u'echo'),
+ (Token.Text, u' '),
+ (Token.Literal.String.Double, u'"'),
+ (Token.String.Interpol, u'${'),
+ (Token.Name.Variable, u'a'),
+ (Token.Punctuation, u'//['),
+ (Token.Literal.String.Double, u'"b"'),
+ (Token.Punctuation, u']/'),
+ (Token.String.Interpol, u'}'),
+ (Token.Literal.String.Double, u'"'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
+ def testCurlyWithEscape(self):
+ fragment = u'echo ${a//[\\"]/}\n'
+ tokens = [
+ (Token.Name.Builtin, u'echo'),
+ (Token.Text, u' '),
+ (Token.String.Interpol, u'${'),
+ (Token.Name.Variable, u'a'),
+ (Token.Punctuation, u'//['),
+ (Token.Literal.String.Escape, u'\\"'),
+ (Token.Punctuation, u']/'),
+ (Token.String.Interpol, u'}'),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
+ def testParsedSingle(self):
+ fragment = u"a=$'abc\\''\n"
+ tokens = [
+ (Token.Name.Variable, u'a'),
+ (Token.Operator, u'='),
+ (Token.Literal.String.Single, u"$'abc\\''"),
+ (Token.Text, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
diff --git a/tests/test_smarty.py b/tests/test_smarty.py
new file mode 100644
index 00000000..20346afd
--- /dev/null
+++ b/tests/test_smarty.py
@@ -0,0 +1,40 @@
+# -*- coding: utf-8 -*-
+"""
+ Basic SmartyLexer Test
+ ~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+
+from pygments.token import Operator, Number, Text, Token
+from pygments.lexers import SmartyLexer
+
+
+class SmartyTest(unittest.TestCase):
+
+ def setUp(self):
+ self.lexer = SmartyLexer()
+
+ def testNestedCurly(self):
+ fragment = u'{templateFunction param={anotherFunction} param2=$something}\n'
+ tokens = [
+ (Token.Comment.Preproc, u'{'),
+ (Token.Name.Function, u'templateFunction'),
+ (Token.Text, u' '),
+ (Token.Name.Attribute, u'param'),
+ (Token.Operator, u'='),
+ (Token.Comment.Preproc, u'{'),
+ (Token.Name.Attribute, u'anotherFunction'),
+ (Token.Comment.Preproc, u'}'),
+ (Token.Text, u' '),
+ (Token.Name.Attribute, u'param2'),
+ (Token.Operator, u'='),
+ (Token.Name.Variable, u'$something'),
+ (Token.Comment.Preproc, u'}'),
+ (Token.Other, u'\n'),
+ ]
+ self.assertEqual(tokens, list(self.lexer.get_tokens(fragment)))
+
diff --git a/tests/test_string_asserts.py b/tests/test_string_asserts.py
new file mode 100644
index 00000000..90d81d67
--- /dev/null
+++ b/tests/test_string_asserts.py
@@ -0,0 +1,35 @@
+# -*- coding: utf-8 -*-
+"""
+ Pygments string assert utility tests
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
+ :license: BSD, see LICENSE for details.
+"""
+
+import unittest
+from string_asserts import StringTests
+
+class TestStringTests(StringTests, unittest.TestCase):
+
+ def test_startswith_correct(self):
+ self.assertStartsWith("AAA", "A")
+
+ # @unittest.expectedFailure not supported by nose
+ def test_startswith_incorrect(self):
+ self.assertRaises(AssertionError, self.assertStartsWith, "AAA", "B")
+
+ # @unittest.expectedFailure not supported by nose
+ def test_startswith_short(self):
+ self.assertRaises(AssertionError, self.assertStartsWith, "A", "AA")
+
+ def test_endswith_correct(self):
+ self.assertEndsWith("AAA", "A")
+
+ # @unittest.expectedFailure not supported by nose
+ def test_endswith_incorrect(self):
+ self.assertRaises(AssertionError, self.assertEndsWith, "AAA", "B")
+
+ # @unittest.expectedFailure not supported by nose
+ def test_endswith_short(self):
+ self.assertRaises(AssertionError, self.assertEndsWith, "A", "AA")
diff --git a/tests/test_token.py b/tests/test_token.py
index 6a5b00b7..c5cc4990 100644
--- a/tests/test_token.py
+++ b/tests/test_token.py
@@ -3,7 +3,7 @@
Test suite for the token module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
@@ -36,11 +36,11 @@ class TokenTest(unittest.TestCase):
stp = token.STANDARD_TYPES.copy()
stp[token.Token] = '---' # Token and Text do conflict, that is okay
t = {}
- for k, v in stp.iteritems():
+ for k, v in stp.items():
t.setdefault(v, []).append(k)
if len(t) == len(stp):
return # Okay
- for k, v in t.iteritems():
+ for k, v in t.items():
if len(v) > 1:
self.fail("%r has more than one key: %r" % (k, v))
diff --git a/tests/test_using_api.py b/tests/test_using_api.py
index bb89d1e2..9e53c206 100644
--- a/tests/test_using_api.py
+++ b/tests/test_using_api.py
@@ -3,7 +3,7 @@
Pygments tests for using()
~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
diff --git a/tests/test_util.py b/tests/test_util.py
index dbbc66ce..7bf03409 100644
--- a/tests/test_util.py
+++ b/tests/test_util.py
@@ -3,7 +3,7 @@
Test suite for the util module
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
- :copyright: Copyright 2006-2013 by the Pygments team, see AUTHORS.
+ :copyright: Copyright 2006-2014 by the Pygments team, see AUTHORS.
:license: BSD, see LICENSE for details.
"""
@@ -123,7 +123,7 @@ class UtilTest(unittest.TestCase):
r = re.compile(util.unirange(0x10000, 0x20000))
m = r.match(first_non_bmp)
self.assertTrue(m)
- self.assertEquals(m.end(), len(first_non_bmp))
+ self.assertEqual(m.end(), len(first_non_bmp))
self.assertFalse(r.match(u'\uffff'))
self.assertFalse(r.match(u'xxx'))
# Tests that end is inclusive
@@ -132,4 +132,12 @@ class UtilTest(unittest.TestCase):
# build
m = r.match(first_non_bmp * 2)
self.assertTrue(m)
- self.assertEquals(m.end(), len(first_non_bmp) * 2)
+ self.assertEqual(m.end(), len(first_non_bmp) * 2)
+
+ def test_format_lines(self):
+ lst = ['cat', 'dog']
+ output = util.format_lines('var', lst)
+ d = {}
+ exec(output, d)
+ self.assertTrue(isinstance(d['var'], tuple))
+ self.assertEqual(('cat', 'dog'), d['var'])