raz / commit 30b3c516

commit
30b3c516745666777e174bbcd8d7e1ebcd07c42a
author
Luis <42945842+ldiaz94@users.noreply.github.com>
date
parent
21350d28
Step 16: editor support, and a stress test of native threads

editor/vim: ftdetect (4 spaces), syntax and indent; editor/emacs:
jed-mode.el, indenting by jed-indent-offset. Both colour reserved
words, basic types, built-ins, numbers, characters, strings and
nested comments, and indent the same way: a block one level in from
the word that opens it, end and else at that word's level, match arms
at match's, declarations at the margin, comment text and continued
expressions as written. test/editors.sh, run by make check, loads
each headless: every example must indent back exactly as written, and
test/editors/Colours.jed must colour as Colours.expect says.

Thread's main is its stress test: n threads in waves of up to alive,
all waiting on one Mutex, each joined. make stress runs 40,000 at 200
at a time, then, under ulimit -v, checks that spawn fails with
Thread.Failed; make check runs 2,000 at 50 and the same failure. It
found that spawn ignored mprotect failing once the process had as many
mappings as it may, which let a stack join forgot to free go
unnoticed and left a thread without a guard page; spawn now checks it.

patch · log

15 files changed, +625 -6

CLAUDE.md modified +10 -2

@@ -13,6 +13,12 @@
1313 make loc # lines of the compiler; the code column is the budget
1414 make tests # the small Pascal tests of scan, x64, link and elf
1515 make gdb # gdb stops at a line of a test and names it
16+ make stress # 40,000 native threads; make check runs a small version
17+
18+`make check` also runs `tools/Doc.jed`, the report's whole examples,
19+each library module's own `main` (its test), and the vim and emacs
20+support headless where they are installed (`apt-get install -y vim
21+emacs-nox`): each example must indent back exactly as written.
1622
1723 `make check` must pass before every commit. Tests: `test/run/X.jed`
1824 with `X.expect` (stdout), optional `X.status` and `X.args`; modules they
@@ -38,8 +44,10 @@
3844
3945 ## Where things stand
4046
41-Stages 1 to 3 are done (steps 1-14), waiting for review. Next is step
42-15, `tools/Doc.jed` and the checked examples, on the owner's go-ahead.
47+Stages 1 to 4 are done (steps 1-16), waiting for review. Next is step
48+17, `README.md` and `doc/compiler.md`, on the owner's go-ahead. Left
49+for later at the owner's word: tagging versions, and a rewrite of var
50+parameters.
4351
4452 `test/libc` runs its programs over `lib/Sys.jed`, the C one, through
4553 a link in its `mods`. A test or example without `.expect` is only

Makefile (history) modified +9 -1

@@ -44,8 +44,16 @@
4444 echo "$$lines lines in $$((best / 1000000)) ms: $$rate lines a second"; \
4545 test $$rate -ge 400000
4646
47+# native threads under load: 40,000 spawned and joined, 200 alive at a
48+# time, all waiting on one Mutex; then, with little memory, spawn must
49+# fail with Thread.Failed. make check runs a small version.
50+stress: jed | build
51+ ./jed -o build/Stress lib/Thread.linux-x86_64.jed
52+ build/Stress 40000 200
53+ (ulimit -v 60000; build/Stress fail)
54+
4755 # lines of the compiler: all of them, and those that aren't blank or comments
4856 loc:
4957 @python3 test/loc.py src/*.pas
5058
51-.PHONY: units tests check gdb bench loc clean
59+.PHONY: units tests check gdb bench stress loc clean

PLAN.md (history) modified +1 -1

@@ -144,7 +144,7 @@
144144 compiler doesn't. (Tagging is left for later, at the owner's
145145 word.)
146146
147-- [ ] 16. Editor support: `editor/vim` (`syntax/jed.vim`, `indent/jed.vim`
147+- [x] 16. Editor support: `editor/vim` (`syntax/jed.vim`, `indent/jed.vim`
148148 by `shiftwidth()`, and `ftdetect/jed.vim`, which sets 4 spaces)
149149 and `editor/emacs/jed-mode.el` (indenting by `jed-indent-offset`,
150150 4 unless set). Both colour reserved words, basic types, built-in

editor/emacs/jed-mode.el added +230 -0

@@ -0,0 +1,230 @@
1+;;; jed-mode.el --- a major mode for jed -*- lexical-binding: t -*-
2+
3+;; Colours jed's reserved words, basic types, built-in procedures,
4+;; numbers, characters, strings and nested comments, and indents by
5+;; `jed-indent-offset': a block's statements one level in from the
6+;; word that opens it; end, until, else and elsif at that word's
7+;; level; match arms at the level of match; procedures, sections
8+;; (const, type, var) and module bodies at the left margin. The text
9+;; of a comment, and a line that goes on with the expression of the
10+;; line before, keep the indent they have.
11+;;
12+;; (add-to-list 'load-path "/path/to/jed/editor/emacs")
13+;; (require 'jed-mode)
14+
15+;;; Code:
16+
17+(defgroup jed nil "The jed programming language." :group 'languages)
18+
19+(defcustom jed-indent-offset 4
20+ "Columns that a block's statements are indented by."
21+ :type 'integer :group 'jed)
22+
23+(defconst jed-keywords
24+ '("and" "begin" "break" "by" "code" "const" "defer" "div" "do" "else"
25+ "elsif" "end" "extern" "for" "forward" "if" "import" "in" "link"
26+ "match" "mod" "module" "not" "of" "or" "packed" "proc" "record"
27+ "repeat" "return" "set" "shl" "shr" "then" "to" "type" "until" "var"
28+ "variant" "VOLATILE" "while" "xor"))
29+
30+(defconst jed-types
31+ '("I8" "I16" "I32" "I64" "U8" "U16" "U32" "U64" "BOOL" "F32" "F64" "ERROR"))
32+
33+(defconst jed-builtins
34+ '("SIZE" "ADR" "LEN" "NEW" "MSG" "SYSCALL" "FENCE" "CAS" "XCHG" "XADD"
35+ "ARGC" "ARGV" "INC" "DEC"))
36+
37+(defvar jed-mode-syntax-table
38+ (let ((st (make-syntax-table)))
39+ ;; (* ... *), nested
40+ (modify-syntax-entry ?\( "()1n" st)
41+ (modify-syntax-entry ?\) ")(4n" st)
42+ (modify-syntax-entry ?* ". 23n" st)
43+ (modify-syntax-entry ?\" "\"" st)
44+ (modify-syntax-entry ?\' "\"" st)
45+ (modify-syntax-entry ?\\ "\\" st)
46+ (modify-syntax-entry ?_ "_" st)
47+ (dolist (c '(?+ ?- ?/ ?= ?# ?< ?> ?: ?\; ?, ?. ?^ ?|))
48+ (modify-syntax-entry c "." st))
49+ st)
50+ "Syntax table for `jed-mode'.")
51+
52+(defvar jed-font-lock-keywords
53+ `((,(regexp-opt jed-keywords 'symbols) . font-lock-keyword-face)
54+ (,(regexp-opt jed-types 'symbols) . font-lock-type-face)
55+ (,(regexp-opt jed-builtins 'symbols) . font-lock-builtin-face)
56+ (,(regexp-opt '("true" "false" "nil") 'symbols) . font-lock-constant-face)
57+ ;; 123, 0FFH, 1.5, 2.0E-3
58+ ("\\_<[0-9][0-9A-F]*H\\_>\\|\\_<[0-9]+\\(?:\\.[0-9]+\\(?:E[-+]?[0-9]+\\)?\\)?\\_>"
59+ . font-lock-constant-face))
60+ "What `jed-mode' colours, besides strings and comments.")
61+
62+;;; Indenting
63+
64+(defconst jed--decl
65+ "^[ \t]*\\(?:module\\|import\\|link\\|extern\\|proc\\|const\\|type\\|var\\|begin\\)\\_>")
66+(defconst jed--leading "^[ \t]*\\(?:or\\|and\\)\\_>")
67+(defconst jed--block-word
68+ "\\_<\\(if\\|while\\|for\\|match\\|record\\|variant\\|begin\\|repeat\\|end\\|until\\)\\_>")
69+
70+(defun jed--line (n)
71+ "The text of line N."
72+ (save-excursion
73+ (goto-char (point-min))
74+ (forward-line (1- n))
75+ (buffer-substring-no-properties (line-beginning-position) (line-end-position))))
76+
77+(defun jed--indent-of (n)
78+ (save-excursion (goto-char (point-min)) (forward-line (1- n)) (current-indentation)))
79+
80+(defun jed--in-comment (n)
81+ "Whether line N starts inside a comment that began before it."
82+ (save-excursion
83+ (goto-char (point-min))
84+ (forward-line (1- n))
85+ (back-to-indentation)
86+ (and (nth 4 (syntax-ppss))
87+ (not (looking-at "(\\*")))))
88+
89+(defun jed--prev (n)
90+ "The last line before N that isn't blank, or 0."
91+ (let ((l (1- n)))
92+ (while (and (> l 0) (string-match-p "\\`[ \t]*\\'" (jed--line l)))
93+ (setq l (1- l)))
94+ l))
95+
96+(defun jed--code (n)
97+ "Line N's code, without strings, characters and comments."
98+ (let ((line (jed--line n)))
99+ (when (jed--in-comment n)
100+ (setq line (if (string-match "\\*)" line) (substring line (match-end 0)) "")))
101+ ;; one pattern, so that whichever comes first is taken
102+ (setq line (replace-regexp-in-string
103+ "\"\\(?:[^\"\\\\]\\|\\\\.\\)*\"\\|'\\(?:[^'\\\\]\\|\\\\.\\)*'\\|(\\*.*?\\*)"
104+ (lambda (m) (if (string-prefix-p "(" m) "" "0")) line t t))
105+ (setq line (replace-regexp-in-string "(\\*.*\\'" "" line t t))
106+ (string-trim line)))
107+
108+(defun jed--count (re s)
109+ (let ((n 0) (i 0))
110+ (while (string-match re s i)
111+ (setq n (1+ n) i (match-end 0)))
112+ n))
113+
114+(defun jed--continues (n)
115+ "Whether the expression on line N goes on to the next line."
116+ (let ((code (jed--code n)))
117+ (or (> (jed--count "[([{]" code) (jed--count "[])}]" code))
118+ (string-match-p "\\(?:,\\|:=\\|[-+*/=#<>]\\|\\_<and\\|\\_<or\\)\\'" code))))
119+
120+(defun jed--start (n)
121+ "The first line of the statement that ends on line N."
122+ (let ((l n) (done nil))
123+ (while (not done)
124+ (let ((p (jed--prev l)))
125+ (if (or (= p 0)
126+ (and (not (jed--continues p))
127+ (not (string-match-p jed--leading (jed--line l)))))
128+ (setq done t)
129+ (setq l p))))
130+ l))
131+
132+(defun jed--opens (code)
133+ "How many blocks CODE opens, less those it closes."
134+ (let ((n 0) (i 0) (case-fold-search nil))
135+ (while (string-match jed--block-word code i)
136+ (setq n (if (member (match-string 1 code) '("end" "until")) (1- n) (1+ n))
137+ i (match-end 0)))
138+ n))
139+
140+(defun jed--opener (n)
141+ "The indent of the word that opens the block line N is in, or nil."
142+ (save-excursion
143+ (goto-char (point-min))
144+ (forward-line (1- n))
145+ (let ((depth 0) (found nil) (case-fold-search nil))
146+ (while (and (not found) (re-search-backward jed--block-word nil t))
147+ (unless (nth 8 (syntax-ppss))
148+ (if (member (match-string 1) '("end" "until"))
149+ (setq depth (1+ depth))
150+ (if (= depth 0)
151+ (setq found (current-indentation))
152+ (setq depth (1- depth))))))
153+ found)))
154+
155+(defun jed--comment-start (n)
156+ "Where the comment that line N, holding only comment, began."
157+ (let ((l n))
158+ (while (and (> l 1) (not (string-match-p "(\\*" (jed--line l))))
159+ (setq l (1- l)))
160+ l))
161+
162+(defun jed-calculate-indent ()
163+ "The column line at point should start at, or nil to leave it."
164+ (let* ((case-fold-search nil)
165+ (n (line-number-at-pos))
166+ (cur (jed--line n))
167+ (prev (jed--prev n)))
168+ (catch 'done
169+ (when (jed--in-comment n) (throw 'done nil))
170+ (when (and (string-match-p jed--decl cur) (not (string-match-p "^[ \t]*proc[ \t]*(" cur)))
171+ (throw 'done 0))
172+ ;; a comment before a declaration goes with it, at the margin
173+ (when (string-match-p "^[ \t]*(\\*" cur)
174+ (let ((l n) (last (line-number-at-pos (point-max))))
175+ (while (and (< l last) (not (string-match-p "\\*)" (jed--line l))))
176+ (setq l (1+ l)))
177+ (setq l (1+ l))
178+ (while (and (<= l last) (string-match-p "\\`[ \t]*\\'" (jed--line l)))
179+ (setq l (1+ l)))
180+ (when (and (<= l last) (string-match-p jed--decl (jed--line l)))
181+ (throw 'done 0))))
182+ (when (string-match-p "^[ \t]*\\(?:end\\|until\\)\\_>" cur)
183+ (throw 'done (or (jed--opener n) 0)))
184+ (when (= prev 0) (throw 'done 0))
185+ (when (string-match-p "^[ \t]*\\(?:\\(?:else\\|elsif\\)\\_>\\||\\)" cur)
186+ (throw 'done (or (jed--opener n) (jed--indent-of prev))))
187+ (when (or (jed--continues prev) (string-match-p jed--leading cur))
188+ (throw 'done nil))
189+ (when (string= (jed--code prev) "")
190+ (throw 'done (jed--indent-of (jed--comment-start prev))))
191+ (let* ((start (jed--start prev))
192+ (ind (jed--indent-of start))
193+ (code (mapconcat #'jed--code (number-sequence start prev) " ")))
194+ (cond
195+ ((or (string-match-p "\\`\\(?:const\\|type\\|var\\)\\'" code)
196+ (and (string-match-p "\\`else\\_>" code) (>= (jed--opens code) 0))
197+ (string-match-p "\\`|.*:\\'" code)
198+ (string-match-p "\\`elsif\\_>.*\\_<then\\'" code))
199+ (+ ind jed-indent-offset))
200+ ((or (string-match-p "\\`|" code) (string-match-p "\\_<match\\_>.*\\_<of\\'" code))
201+ ind)
202+ ((> (jed--opens code) 0) (+ ind jed-indent-offset))
203+ (t ind))))))
204+
205+(defun jed-indent-line ()
206+ "Indent the current line as jed's blocks say."
207+ (interactive)
208+ (let ((col (save-excursion (jed-calculate-indent)))
209+ (offset (- (current-column) (current-indentation))))
210+ (when col
211+ (indent-line-to col)
212+ (when (> offset 0) (move-to-column (+ col offset))))))
213+
214+;;;###autoload
215+(define-derived-mode jed-mode prog-mode "jed"
216+ "Major mode for editing jed."
217+ :syntax-table jed-mode-syntax-table
218+ (setq-local font-lock-defaults '(jed-font-lock-keywords nil nil))
219+ (setq-local comment-start "(* ")
220+ (setq-local comment-end " *)")
221+ (setq-local comment-start-skip "(\\*+[ \t]*")
222+ (setq-local indent-tabs-mode nil)
223+ (setq-local indent-line-function #'jed-indent-line))
224+
225+;;;###autoload
226+(add-to-list 'auto-mode-alist '("\\.jed\\'" . jed-mode))
227+
228+(provide 'jed-mode)
229+
230+;;; jed-mode.el ends here

editor/vim/ftdetect/jed.vim added +3 -0

@@ -0,0 +1,3 @@
1+" jed: *.jed files, indented by 4 spaces.
2+autocmd BufRead,BufNewFile *.jed setfiletype jed
3+autocmd FileType jed setlocal shiftwidth=4 softtabstop=4 expandtab

editor/vim/indent/jed.vim added +157 -0

@@ -0,0 +1,157 @@
1+" Vim indent file for jed, by shiftwidth(): a block's statements one
2+" level in from the word that opens it; end, until, else and elsif at
3+" that word's level; match arms at the level of match; procedures,
4+" sections (const, type, var) and module bodies at the left margin.
5+" The text of a comment, and a line that goes on with the expression
6+" of the line before, keep the indent they have.
7+
8+if exists("b:did_indent")
9+ finish
10+endif
11+let b:did_indent = 1
12+
13+setlocal indentexpr=GetJedIndent(v:lnum)
14+setlocal indentkeys=o,O,0=end,0=else,0=elsif,0=until,0=\|,!^F
15+setlocal nolisp nosmartindent
16+
17+if exists("*GetJedIndent")
18+ finish
19+endif
20+
21+" searchpair() needs groups that don't capture
22+let s:opener = '\C\<\%(if\|while\|for\|match\|record\|variant\|begin\|repeat\)\>'
23+let s:closer = '\C\<\%(end\|until\)\>'
24+let s:skip = 'synIDattr(synID(line("."), col("."), 1), "name") =~? "string\\|char\\|comment"'
25+let s:decl = '^\s*\%(module\|import\|link\|extern\|proc\|const\|type\|var\|begin\)\>'
26+
27+" The line's code, without strings, characters and comments.
28+function! s:Code(lnum)
29+ let line = getline(a:lnum)
30+ " a line that starts inside a comment: its code is after the comment
31+ if s:InComment(a:lnum)
32+ let line = line =~ '\*)' ? substitute(line, '^.\{-}\*)', '', '') : ''
33+ endif
34+ " one pattern, so that whichever comes first is taken: a " in a
35+ " character, a ' in a string; strings become 0, comments go
36+ let line = substitute(line,
37+ \ '"\%([^"\\]\|\\.\)*"\|''\%([^''\\]\|\\.\)*''\|(\*.\{-}\*)',
38+ \ '\=submatch(0)[0] == "(" ? "" : "0"', 'g')
39+ let line = substitute(line, '(\*.*$', '', '')
40+ return substitute(line, '^\s*\(.\{-}\)\s*$', '\1', '')
41+endfunction
42+
43+" Whether the expression on lnum goes on to the next line.
44+function! s:Continues(lnum)
45+ let code = s:Code(a:lnum)
46+ if len(substitute(code, '[^([{]', '', 'g')) > len(substitute(code, '[^)\]}]', '', 'g'))
47+ return 1
48+ endif
49+ return code =~# '\%(,\|:=\|[-+*/=#<>]\|\<and\|\<or\)$'
50+endfunction
51+
52+let s:leading = '^\s*\%(or\|and\)\>'
53+
54+" The first line of the statement that ends on lnum.
55+function! s:Start(lnum)
56+ let l = a:lnum
57+ while 1
58+ let p = prevnonblank(l - 1)
59+ if p == 0 || !s:Continues(p) && getline(l) !~# s:leading
60+ return l
61+ endif
62+ let l = p
63+ endwhile
64+endfunction
65+
66+" The line itself, or where the comment it ends began, if it holds
67+" nothing but comment.
68+function! s:Reference(lnum)
69+ let l = a:lnum
70+ if s:Code(l) != ''
71+ return l
72+ endif
73+ while l > 1 && getline(l) !~ '(\*'
74+ let l -= 1
75+ endwhile
76+ return l
77+endfunction
78+
79+" How many blocks the code opens, less those it closes.
80+function! s:Opens(code)
81+ let n = 0
82+ let i = 0
83+ while 1
84+ let m = matchstrpos(a:code, '\C\<\%(if\|while\|for\|record\|variant\|begin\|repeat\|end\|until\)\>', i)
85+ if m[1] < 0
86+ return n
87+ endif
88+ let n += (m[0] ==# 'end' || m[0] ==# 'until') ? -1 : 1
89+ let i = m[2]
90+ endwhile
91+endfunction
92+
93+function! s:InComment(lnum)
94+ let col = match(getline(a:lnum), '\S') + 1
95+ return col > 0 && synIDattr(synID(a:lnum, col, 1), "name") =~? 'comment'
96+ \ && getline(a:lnum) !~ '^\s*(\*'
97+endfunction
98+
99+function! GetJedIndent(lnum)
100+ let cur = getline(a:lnum)
101+ if s:InComment(a:lnum)
102+ return -1
103+ endif
104+ if cur =~# s:decl && cur !~# '^\s*proc\s*('
105+ return 0
106+ endif
107+ " a comment before a declaration goes with it, at the margin
108+ if cur =~ '^\s*(\*'
109+ let l = a:lnum
110+ while l < line('$') && getline(l) !~ '\*)'
111+ let l += 1
112+ endwhile
113+ if getline(nextnonblank(l + 1)) =~# s:decl
114+ return 0
115+ endif
116+ endif
117+ if cur =~# '^\s*\%(end\|until\)\>'
118+ call cursor(a:lnum, 1)
119+ let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
120+ return l > 0 ? indent(l) : 0
121+ endif
122+ let prev = prevnonblank(a:lnum - 1)
123+ if prev == 0
124+ return 0
125+ endif
126+ if cur =~# '^\s*\%(else\|elsif\)\>'
127+ call cursor(a:lnum, 1)
128+ let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
129+ return l > 0 ? indent(l) : indent(prev)
130+ endif
131+ if cur =~# '^\s*|'
132+ call cursor(a:lnum, 1)
133+ let l = searchpair(s:opener, '', s:closer, 'bW', s:skip)
134+ return l > 0 ? indent(l) : indent(prev)
135+ endif
136+ if s:Continues(prev) || cur =~# s:leading
137+ return -1
138+ endif
139+ if s:Code(prev) == ''
140+ return indent(s:Reference(prev))
141+ endif
142+
143+ let start = s:Start(prev)
144+ let ind = indent(start)
145+ let code = join(map(range(start, prev), 's:Code(v:val)'), ' ')
146+ if code =~# '^\%(const\|type\|var\)$' || code =~# '^else\>' && s:Opens(code) >= 0
147+ \ || code =~# '^|.*:$' || code =~# '^elsif\>.*\<then$'
148+ return ind + shiftwidth()
149+ endif
150+ if code =~# '^|' || code =~# '\<match\>.*\<of$'
151+ return ind
152+ endif
153+ if s:Opens(code) > 0
154+ return ind + shiftwidth()
155+ endif
156+ return ind
157+endfunction

editor/vim/syntax/jed.vim added +42 -0

@@ -0,0 +1,42 @@
1+" Vim syntax file for jed: reserved words, basic types, built-in
2+" procedures, numbers, characters, strings and nested comments.
3+
4+if exists("b:current_syntax")
5+ finish
6+endif
7+
8+syntax case match
9+
10+syntax keyword jedKeyword and begin break by code const defer div do else
11+syntax keyword jedKeyword elsif end extern for forward if import in link
12+syntax keyword jedKeyword match mod module not of or packed proc record
13+syntax keyword jedKeyword repeat return set shl shr then to type until var
14+syntax keyword jedKeyword variant VOLATILE while xor
15+syntax keyword jedType I8 I16 I32 I64 U8 U16 U32 U64 BOOL F32 F64 ERROR
16+syntax keyword jedBuiltin SIZE ADR LEN NEW MSG SYSCALL FENCE CAS XCHG XADD
17+syntax keyword jedBuiltin ARGC ARGV INC DEC
18+syntax keyword jedConstant true false nil
19+
20+" 123, 0FFH, 1.5, 2.0E-3
21+syntax match jedNumber "\<\d[0-9A-F]*H\>"
22+syntax match jedNumber "\<\d\+\>"
23+syntax match jedNumber "\<\d\+\.\d\+\(E[+-]\=\d\+\)\=\>"
24+
25+syntax match jedEscape contained "\\\([ntr0\\'\"]\|x\x\x\|u{\x\+}\)"
26+syntax region jedString start=+"+ skip=+\\.+ end=+"+ contains=jedEscape oneline
27+syntax region jedChar start=+'+ skip=+\\.+ end=+'+ contains=jedEscape oneline
28+
29+syntax region jedComment start="(\*" end="\*)" contains=jedComment,@Spell
30+syntax sync fromstart
31+
32+highlight default link jedKeyword Statement
33+highlight default link jedType Type
34+highlight default link jedBuiltin Function
35+highlight default link jedConstant Constant
36+highlight default link jedNumber Number
37+highlight default link jedString String
38+highlight default link jedChar Character
39+highlight default link jedEscape SpecialChar
40+highlight default link jedComment Comment
41+
42+let b:current_syntax = "jed"

lib/Thread.linux-x86_64.jed modified +67 -2

@@ -6,7 +6,7 @@
66 a Mutex sleeps on a futex. A program with C threads uses C's,
77 through pthread_create, and so can't use these. *)
88 module Thread;
9-import Sys;
9+import Sys, Rt;
1010 link static;
1111
1212 const
@@ -64,7 +64,12 @@
6464 size := Stack + Page;
6565 base := Sys.mmap(size);
6666 if base = nil then return nil, Failed; end;
67- SYSCALL(10, base, Page, 0); (* mprotect: the guard page, no access *)
67+ (* mprotect: the guard page, no access; it fails when the process
68+ has as many mappings as it may *)
69+ if SYSCALL(10, base, Page, 0) < 0 then
70+ Sys.munmap(base, size);
71+ return nil, Failed;
72+ end;
6873 (* the Thread at the top, the stack below it, aligned to 16 *)
6974 t := ^Thread(base + size - 32);
7075 t^.base := base;
@@ -108,6 +113,66 @@
108113 XCHG(ADR(m^.state), 0);
109114 futex(ADR(m^.state), FutexWake + Private, 1);
110115 end;
116+end;
117+
118+(* The module's test, and make stress's. It starts n threads, in waves
119+ of up to alive at a time, all waiting on one Mutex the test holds
120+ until the wave is out; each, given it, adds one to a count. Every
121+ thread is joined, so that a stack join didn't free would, over
122+ enough of them, run the process out of mappings. With "fail", it
123+ starts threads, all waiting, until spawn fails, which it must do
124+ with Failed: make stress and make check run it with little memory.
125+ Thread [n alive], Thread fail *)
126+var
127+ testLock: Mutex;
128+ testCount: I64;
129+ wave: [1000]^Thread;
130+
131+proc testWork(arg: ^U8);
132+begin
133+ lock(ADR(testLock));
134+ INC(testCount);
135+ unlock(ADR(testLock));
136+end;
137+
138+proc testArg(i: I64): I64;
139+var s: ^U8; n, v: I64;
140+begin
141+ s := ARGV()[i];
142+ v := 0;
143+ n := 0;
144+ while s[n] # 0 do v := v * 10 + I64(s[n]) - '0'; INC(n); end;
145+ return v;
146+end;
147+
148+proc main*;
149+var n, alive, started, k, i: I64; t: ^Thread; err: ERROR; fail: BOOL;
150+begin
151+ n := 2000; alive := 50;
152+ fail := (ARGC() = 2) and (ARGV()[1][0] = 'f');
153+ if ARGC() = 3 then n := testArg(1); alive := testArg(2); end;
154+ if fail then n := LEN(wave); alive := LEN(wave); end;
155+ if (alive < 1) or (alive > LEN(wave)) then Rt.stop("Thread: alive is 1 to 1000"); end;
156+ started := 0;
157+ while started < n do
158+ lock(ADR(testLock));
159+ k := 0;
160+ while (k < alive) and (started + k < n) do
161+ t, err := spawn(testWork, nil);
162+ if err # nil then
163+ if not fail or (err # Failed) then Rt.stop("Thread.spawn failed"); end;
164+ n := started + k;
165+ break;
166+ end;
167+ wave[k] := t;
168+ INC(k);
169+ end;
170+ unlock(ADR(testLock));
171+ for i := 0 to k - 1 do join(wave[i]); end;
172+ started := started + k;
173+ end;
174+ if testCount # started then Rt.stop("Thread: a thread didn't run"); end;
175+ if fail and (started = LEN(wave)) then Rt.stop("Thread: spawn never failed"); end;
111176 end;
112177
113178 end Thread.

test/check.sh (history) modified +8 -0

@@ -103,5 +103,13 @@
103103 else pass=$((pass + 1)); fi
104104 done
105105
106+# Thread's test again, with too little memory for all its threads:
107+# spawn must fail, with Thread.Failed
108+if (ulimit -v 60000; $out/lib_Thread.linux-x86_64 fail) > /dev/null 2>&1; then pass=$((pass + 1))
109+else echo "FAIL Thread under a memory limit"; fail=$((fail + 1)); fi
110+
111+# the editors' support, headless, where the editors are installed
112+if test/editors.sh; then pass=$((pass + 1)); else fail=$((fail + 1)); fi
113+
106114 echo "$pass passed, $fail failed"
107115 [ $fail = 0 ]

test/doc/Thread.expect (history) modified +2 -0

@@ -27,3 +27,5 @@
2727 proc lock*(m: ^Mutex);
2828
2929 proc unlock*(m: ^Mutex);
30+
31+proc main*;

test/editors.sh (history) added (executable) +38 -0

@@ -0,0 +1,38 @@
1+#!/bin/sh
2+# Loads the editor support, headless, on each example: the file must be
3+# taken for jed, coloured without error, and indented again exactly as
4+# it is written; and test/editors/Colours.jed must be coloured as
5+# Colours.expect says. Prints one line per failure; quiet if the editor
6+# is missing.
7+
8+fail=0
9+if command -v vim >/dev/null; then
10+ for f in examples/*.jed; do
11+ vim -Nu NONE -i NONE -es \
12+ -c 'set rtp^=editor/vim' -c 'filetype plugin indent on' -c 'syntax on' \
13+ -c "edit $f" \
14+ -c 'if &filetype !=# "jed" || &shiftwidth != 4 | cquit | endif' \
15+ -c 'let before = getline(1, "$")' -c 'normal! gg=G' \
16+ -c 'if getline(1, "$") != before | cquit | endif' -c 'qall!' \
17+ || { echo "FAIL vim on $f"; fail=1; }
18+ done
19+ vim -Nu NONE -i NONE -es -c 'set rtp^=editor/vim' -c 'filetype plugin indent on' \
20+ -c 'syntax on' -c 'edit test/editors/Colours.jed' -S test/editors/colours.vim \
21+ || { echo "FAIL vim colours"; fail=1; }
22+fi
23+if command -v emacs >/dev/null; then
24+ for f in examples/*.jed; do
25+ emacs -Q --batch -l editor/emacs/jed-mode.el --eval "
26+ (progn
27+ (find-file \"$f\")
28+ (unless (eq major-mode 'jed-mode) (kill-emacs 1))
29+ (font-lock-ensure)
30+ (let ((before (buffer-string)))
31+ (indent-region (point-min) (point-max))
32+ (unless (string= before (buffer-string)) (kill-emacs 2))))" \
33+ 2>/dev/null || { echo "FAIL emacs on $f"; fail=1; }
34+ done
35+ emacs -Q --batch -l editor/emacs/jed-mode.el -l test/editors/colours.el 2>/dev/null \
36+ || { echo "FAIL emacs colours"; fail=1; }
37+fi
38+exit $fail

test/editors/Colours.expect (history) added +12 -0

@@ -0,0 +1,12 @@
1+1 23 comment
2+2 1 keyword
3+3 13 number
4+3 27 number
5+3 39 string
6+3 49 string
7+3 53 string
8+4 8 type
9+4 17 type
10+6 5 builtin
11+6 19 constant
12+5 1 keyword

test/editors/Colours.jed added +7 -0

@@ -0,0 +1,7 @@
1+(* outer (* nested *) still comment *)
2+module Colours;
3+const big = 0FFH; small = 2.5E-3; q = '\''; s = "a\"b";
4+var x: I64; ok: BOOL;
5+begin
6+ INC(x); ok := true;
7+end Colours.

test/editors/colours.el (history) added +27 -0

@@ -0,0 +1,27 @@
1+;; Checks each token of Colours.expect has the face it should.
2+(let ((wants (split-string (with-temp-buffer
3+ (insert-file-contents "test/editors/Colours.expect")
4+ (buffer-string))
5+ "\n" t)))
6+ (find-file "test/editors/Colours.jed")
7+ (font-lock-ensure)
8+ (dolist (want wants)
9+ (let* ((w (split-string want))
10+ (face (save-excursion
11+ (goto-char (point-min))
12+ (forward-line (1- (string-to-number (nth 0 w))))
13+ (forward-char (1- (string-to-number (nth 1 w))))
14+ (get-text-property (point) 'face)))
15+ (face (if (listp face) (car face) face))
16+ (kind (pcase face
17+ ((or 'font-lock-comment-face 'font-lock-comment-delimiter-face) "comment")
18+ ('font-lock-keyword-face "keyword")
19+ ('font-lock-string-face "string")
20+ ('font-lock-type-face "type")
21+ ('font-lock-builtin-face "builtin")
22+ ('font-lock-constant-face "constant"))))
23+ ;; numbers and constants share a face
24+ (unless (or (equal kind (nth 2 w))
25+ (and (equal kind "constant") (equal (nth 2 w) "number")))
26+ (message "%s: %s" want face)
27+ (kill-emacs 3)))))

test/editors/colours.vim (history) added +12 -0

@@ -0,0 +1,12 @@
1+" Checks each token of Colours.expect has the colour group it should.
2+let s:kinds = {'jedComment': 'comment', 'jedKeyword': 'keyword', 'jedNumber': 'number',
3+ \ 'jedString': 'string', 'jedChar': 'string', 'jedType': 'type',
4+ \ 'jedBuiltin': 'builtin', 'jedConstant': 'constant'}
5+for s:want in readfile('test/editors/Colours.expect')
6+ let [s:l, s:c, s:k] = split(s:want)
7+ let s:group = synIDattr(synID(str2nr(s:l), str2nr(s:c), 1), 'name')
8+ if get(s:kinds, s:group, '') !=# s:k
9+ cquit
10+ endif
11+endfor
12+qall!