Add encapsulation, sum types, type constraints and all the required machinery. Also -> threading macro #64
Reference in New Issue
Block a user
Delete Branch "static-dispatch"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Built and ran this on CHICKEN 6.0.0 at
0119c85.make run-testsis green, includingencapsulation,ops,records,specs,sums,threading,worked-example, andcheck-modules(the opaquetally, the pasted sum, the spec default synthesized again in the importer). The holes below are outside that suite. I compiled each one with./sexc -Cand then withcc -std=c11.The shape of the feature is right, and the parts the suite pins do what the commits say. A method in the head stays a call when a field of the same name appears.
(.length v)and(.length p)agree for a self written(* const vec2). A match that drops a variant is an error that names it. Apub recordwith no fields is an incompletestruct, completed by the private definition, and the importer only receives the handle.->threads,GL/gl.his included asGL/gl.h, and the C11 floor holds under-std=c11 -pedantic-errors.1. A required spec method stops being required as soon as it has a docstring or a comment
check-realizationtreats(= (length w) 4)as required and(> (length w) 4)as a default (semen.scm,realization-methodsandcheck-realization). A docstring and a comment are both extra elements, so they are a body.sexc accepts the empty realization and emits a static prototype with no definition:
A comment is worse, because it becomes a real function. This also accepts
(realize (p v))with nos, and(.s a)compiles:The signature check still runs when the method is written out. The hole is the missing-method check, and it is silent. Required versus default wants "a body remains after docstrings and comments are stripped".
2.
(self * const vec2)is a pointer in the method and a value at the callmake-fn-envrecords a spread parameter as the whole tail, which is why(. self x)inside the method isself->x.arglist-typesstill only unwraps a named parameter of length 2, sofn-type-ofstores(self * const v)andmethod-self-typetakes the car of that, the nameself.wants-pointer?is false.ccrejects both arguments. The same split makes the spec checker refuse two spellings of one type: a spec written(self * const T)against a realization written(self (* const v))is "method's arguments do not match the spec".arglist-typesshould use the same readingmake-fn-envalready does.3. match still lets through things it exists to refuse, and one of them crashes sexc
Two
elsearms compile.ccreportsmultiple default labels in one switch.A repeated variant compiles.
ccreports a redeclared enumerator and twoshapeːawith different types. A repeated method is already a sex error; a repeated variant is the same fact about a sum.A variant named
tagcompiles. The enum isenum shapeːtagand the payload isstruct shapeːtag, and those tags share a namespace:(match s foo)does not get a sex error. sexc dies inmatch-arm-variantwith(car) bad argument type: foo, because(car arm)runs before the pair check.match in expression position compiles to a switch where C wants an expression:
cc:expected expression before ‘switch’. match is a statement. sexc should say so at the form, the way it says so for a scrutinee that is not a sum.4. A macro in the receiver or the scrutinee is typed before it expands
walk-statementexpands a macro when the form it is looking at is the macro call.walk-method-callandwalk-matchaskexpression-typeof the receiver and the scrutinee first, and walk them afterwards. A macro standing in either place is still the unexpanded call, so it has no type.sexc:
receiver of this has no type to dispatch on: len, andmatch wants a sum, and this is not one: unknown. Both expansions are names it already knows how to type.(-> a .len)works only because->expands before the method call is walked.5. A typedef alias is the type for fields, and a different type for methods and match
get-fieldsfollows a typedef.ops-keyreturns the symbol as written, andget-sumlooks that symbol up.The alias has the fields and the constructors. Dispatch and match want the underlying name as well.
6. An array field in a variant compiles to C that is not C
cc:expected expression before ‘{’, andinvalid initializer. A struct field in the same position works (shapeːdot((point){3, 4}), and the binder is a copy). An array cannot be a function argument or the initializer of another array. sexc should refuse the field until it can emit somethingccaccepts.Notes, not blocking
Match binders are copies.
(= r 9)changes the local and leavess.u.circle.ralone. That matches the C the commit describes; it is worth one sentence next to the form, because the binder looks like a reference.(match p ...)withpa(* shape)is refused, and the error names(* shape).(match (* p) ...)works. Fine.A method can call a method already defined. A later one is
no such method, including a spec default that calls a default written further down the spec. A static function has the same forward-reference rule, and here the error is a sex error. Mutual recursion needs a prototype either way.A method that wants
(* v)accepts(* const v). sexc emits the call;cc -Wallwarnsdiscards ‘const’ qualifier. The adjustment only asks "is it a pointer".->with no import is the call->(p, x), whichccrejects.%->is still the arrow ((%-> p x)emittedp->xand compiled). The readme covers.and the threading macro. One line for%->would save the untyped-pointer case, where(. (no-such) x)warns and emitsno_such().x.(sum box ((inner ((x box)))))is an incomplete type atcc(field ‘x’ has incomplete type). The worked example already says a sum recurs through a pointer.opsandmatchindent insex-mode.eland are absent from the keyword regexp, which did gainrecord,spec,realize, andsum.The walk stopped at a vector, so whatever a literal held reached the writer as written: #(v : (.get a)) was (v){.get(a)}, and a path through a pointer inside one read it as a value.Thanks, all six are fixed on the branch, each with its repro turned into a test (
tests/encapsulation.scm,sums.sex).make run-testsis green.1. Required spec methods
f5c53cd. A method is a default when a body remains after the docstring and comments are stripped, as you put it;realization-methodsandcheck-realizationnow ask the samespec-default?. Both repros reportrealization is missing a method of.2.
(self * const v)5ba55f0.arglist-typesreads a spread parameter the waymake-fn-envdoes, so the repro isvːlen(&a) + vːlen(p), and a spec accepts a realization written in the other spelling. The const note is folded in here: a(* const v)receiver handed to a method taking(* v)is nowmethod may change its receiver, and this one is const.3. match
3baaafa. A secondelse, a variant declared twice, and an arm that is not one are sex errors;(match s foo)no longer crashes. A match where a value is wanted ismatch is a statement, and has no value: initializers, returns, arguments, receivers, literal elements. Aniforwhilecondition is not covered yet, sincewalk-partstakes every slot alike; cc still refuses that one.A variant named
tagis not refused: the enum moved out of its way. It isenum shapeǂnow, constantsshapeǂcircle(U+01C2, clean under-Wunicode-homoglyph), soshapeːtagis only ever a payload struct.4. Macros in the receiver and the scrutinee
bb2f05f.expression-typeexpands a macro call and types the expansion, so this holds wherever a type is asked of an unwalked form. The base of a.path had the same hole:(. (the p) x)warned and wrote..5. Typedef aliases
224ef8f. Methods, realizations and sums are filed under what a typedef names, soaliasdispatches and matches asvandshapedo. A typedef chain that ends in a scalar stops at its last typedef:(typedef meters float)keeps its methods rather than lending them to every float.6. Array fields
Not refused; supported, which took four commits.
9af9113: the walk never entered a brace literal, so#(v : (.get a))was(v){.get(a)}, and a path through a pointer inside a literal read it as a value. This one was already live on vs-map-viewer.e91b44d: a global's initializer is walked like a local's.427177d: constructors are written in place, with no function at all. A function cannot take an array, its parameter being a pointer, and two kinds of constructor were worse than none. In place,(shape/circle 1)is a constant at file scope, an lvalue a pointer-self method can be handed, and a pub sum pastes nothing but declarations. sexc now checks the argument count (a short compound literal zero-fills quietly) and converts an argument against its field's closure type. The price: a constructor is not a function value, and the error says to call it from a lambda.9c5f678: an array field takes a literal in place,(struct shapeːrow){{1, 2, 3, 4}}, and an array by its elements,{a[0], a[1], a[2], a[3]}. A binder is initialized the same way, so it stays a copy. The length has to be countable (a number or adefineof one), equal to the field's, and the array read from a path, not a call.Notes
worked-example.sex(0a56504).(match p ...)on a pointer: left as it is.(* v)accepting(* const v): refused now, in5ba55f0.%->: one line under Member access in the Readme (0a56504).9c5f678. A pointer back is fine.opsandmatchin the keyword regexp:b51cda0.Re-reviewed at
0a56504on CHICKEN 6.0.0.make run-testsis green, including the new cases inencapsulationandsums.sex. I recompiled the six repros with./sexc -Candcc -std=c11.All six are fixed.
realization is missing a method of, and providingsemits the body.(self * const v)isvːlen(&a) + vːlen(p), and that spelling realizes a spec written(* const v). A(* const v)receiver handed to(* v)ismethod may change its receiver, and this one is const.else, a repeated variant, and(match s foo)are sex errors. A variant namedtagcompiles: the enum isshapeǂ, the payload isstruct shapeːtag.(var n int (match ...))ismatch is a statement, and has no value.(.len (the a))and(match (the s) ...)compile to the expansion.(typedef meters float)does not lend its method to afloat.(shape/row src)is(struct shapeːrow){{src[0], src[1], src[2], src[3]}}, and the binder is the same copy element by element. A sum that holds itself by value is refused at the declaration.opsandmatchare in thesex-modekeyword list.%->is in the readme.Still open
if,while, andforstill walk every slot as a statement, so a match in the condition is a switch where C wants an expression:ccrejects each one. An argument, a returned value, an assignment, and(&& (match ...) ...)are alreadymatch is a statement. This is the gap you named;for's condition is the same one.A file-scope constructor is a compound literal, and
-std=c11 -pedantic-errorsrejects it asinitializer element is not constant, the same way it rejects(var g point #(point : 1 2)). Plaincc -std=c11accepts both. The new test checks that the spelling isstatic t g = (t){and does not compile it. A brace initializer would be a C11 constant; the nested(struct shapeːcircle){1}is the part that is not.A brace literal longer than an array field still reaches
cc(excess elements in array initializer). A shorter one zero-fills. A named array of the wrong length is alreadyarray is not as long as its field.Thanks. The three that were still open are closed on the branch.
make run-testsis green.match in a test
0a5eb1e.if,while,forandswitchno longer walk every slot alike. The slots C reads as values are walked as operands: anif's tests (not its trailing else), all three offor's header, the value awhiletests or aswitchswitches on. All three repros arematch is a statement. A match in a branch, the else among them, is still a switch.Globals
913af0b. A global's initializer is written as braces, the compound literal's type dropped at every level:static t g = {.tag = tǂa, .u = {.a = {1}}};, and(var g point #(point : 1 2))isstatic point g = {1, 2};. Locals keep their compound literals.c11.sexnow holds a global record and a global sum, so-std=c11 -pedantic-errorscompiles them. It fails there with gcc before the fix. Clang accepted the old spelling even under-pedantic-errors, which is why it got past my checks.Array literals
6cda087. A brace literal for an array field is held to the field's length, the same as a named array: longer or shorter isarray is not as long as its field. A shorter one no longer zero-fills quietly, the same reasoning as the constructor's argument count.Re-reviewed at
913af0bon CHICKEN 6.0.0.make run-testsis green, includingmodules okandexit code ok. The three programs from the last note compile.A match in an
iftest, awhiletest, aforheader or aswitchscrutinee ismatch is a statement, and has no value. A match in either branch, the else among them, is still a switch, and(for (var i int 0) (< i 3) (++ i) ...)isfor (int i = 0; i < 3; ++i).(for (var i _ 0) ...)infersint.A global is braces, and
cc -std=c11 -pedantic-errorsaccepts them:{2, 3},{.x = 4, .y = 5},{.tag = shapeǂsquare, .u = {.square = {1}}},{.tag = shapeǂdot},{.tag = shapeǂrow, .u = {.row = {{8, 9}}}},{{1, 2}, {3, 4}}. A local stays(point){6, 7}.#(1)and#(1 2 3)for an[int 2]field arearray is not as long as its field.#(1 2)stays{{1, 2}}.Two programs beside those still fail.
1. A case label is still a statement.
if,while,forandswitchwalk their value slots as operands.caseandcase/fallthroughstill walk every slot as a statement, and the label is a value.sexc accepts it. The C is
case switch:, and cc saysexpected expression before 'switch'.case/fallthroughsplices the same switch into the label:case switch:thencase s.tag:.2. Stripping a global's type happens before
_is solved.bare-bracesdrops the words before:and thenresolve-wildcardsees what remains. A brace list has no type of its own.is
cannot infer the type of: g. The same declaration insidemainispoint g = (point){2, 3}. A global(var n _ (+ 1 2))is stillstatic int n = 1 + 2, and(var xs [_ 3] #(4 5 6))is stillstatic int xs[3]. An array of typed literals loses the element type with the prefix:is
cannot infer the type of: ps.(var u _ (shape/square 1))at file scope fails the same way; inside a function it isshape u = (shape){.tag = shapeǂsquare, ...}.@@ -145,0 +176,4 @@~sexc~ looks for them beside itself, so a work tree needs nothing setup; installed, ~$(bindir)/sexc~ finds them under ~$(prefix)/share/sex~.There is one so far.That is a bit excessive. There will be others for sure.
True.
@@ -145,0 +178,4 @@There is one so far.*** threading-macrosI would look ahead a little and avoided introducing the whole standard library in the README. It'll better to create separate org file and link it here.
Indeed. But I don't think that one file will be enough. Every module should have it's own file at least.
@@ -184,1 +192,4 @@(('dot-access . rest) (cons '%. (map walk-expr rest)));; `%->' is the C arrow. Nothing writes it: it is what a member;; path lowers to where the thing it reads from is a pointer, the;; name `->' itself being the threading macroWhy C writer would know anything about what you do with the sex standard library? I suppose that mention should be rather deleted.
Well... Because it's a name clash with very well known and widely used bit of C syntax. So one might want to know why it's missing from Sex, while most of other semantics is accounted for.
However I don't have strong preference, might as well drop the comment.
@@ -0,0 +12,4 @@(record point ((x int) (y int)))(record named "Fields of more than one kind, and a docstring."Maybe that would be better, dunno.
@@ -0,0 +1,56 @@(input)Dunno, maybe stdlib tests deserve their own space.
They do, but I think we should do it later. Probably also groom sex-programs too, or even eliminate it altogether. I envision something like gcc's test suite, or autotools' feature test programs. In any case, for now test programs will do.
@@ -0,0 +6,4 @@"one step is just the value: 7")(return 0);;; `->' used to be C's arrow. The arrow is what `.' writes now whenWhy that story is important?
The language is in alpha stage, everything changes from PR to PR, no need to write it down everywhere.
I agree.
@@ -0,0 +3,4 @@"-5")(return 0);;; The worked example from Encapsulation.org, kept here so it staysWho? From where? Why worked-example.sex?
Something that moved from an uncommited doc. Will be rephrased.
@@ -93,0 +148,4 @@;;; Both of these refuse a second declaration of the same name, which;;; is per translation unit rather than per process -- so a process;;; that compiles two units has to start the second one clean.(define (reset-declarations!)The order of definitions here is quite chaotic.
+ops-db+defined below. That is difficult to read for a human.True, I'll rearrange them.
Thanks. Both programs are fixed on the branch, and the inline notes are addressed.
make run-testsis green.A case label
a0b3239.caseandcase/fallthroughread their label as a value, the wayswitchreads its scrutinee; their body is still statements. Both repros arematch is a statement. A match in a case body is still a switch._on a globala885c21. The type is now solved before the braces are stripped, so#(point : 2 3)still namespointwhen_needs it.(var g _ #(point : 2 3))isstatic point g = {2, 3};.(var ps [_ 2] #(#(point : 1 2) #(point : 3 4)))isstatic point ps[2] = {{1, 2}, {3, 4}};.(var u _ (shape/square 1))isstatic shape u = {.tag = shapeǂsquare, .u = {.square = {1}}};.c11.sexnow declares its globals with_and adds the array, so all three compile under-pedantic-errors.Inline notes
063770d: the standard library section no longer counts its modules. Each module gets its own doc file beside it, starting withlib/threading-macros.org, listed from the readme.958978e: the%->comment no longer mentions the threading macro.8f7b26e:worked-example.sexis nowencapsulation.sex, and its header says what the program covers.b5030e3:threading.sexsays what it checks, without the history.5f130f4:types.scmreads top down: lookups,type-key, sums, ops, specs, thenreset-declarations!.db5507b: the record's docstring is on its own line.Stdlib tests stay in
tests/sex-programs/for now, as discussed in the thread.Approved at
db5507bon CHICKEN 6.0.0.make run-testsis green, includingmodules okandexit code ok.Both programs from the last review are fixed.
A match in a
caselabel or acase/fallthroughlabel ismatch is a statement, and has no value. A match in the case body, and one indefault, is still a switch.(case (+ x 1) ...)is a separate matter, below._is solved before the braces are stripped. Withcc -std=c11 -pedantic-errors:(var n _ (+ 1 2))isstatic int n = 1 + 2, and a designated(var named point #(.x 4 .y 5))isstatic point named = {.x = 4, .y = 5}. A local stayspoint local = (point){6, 7}.c11.sexprintsc11: 42 43 6 4 6 12.Still open
c-casereads a pair label as several labels, which is how(case (1 2 3) ...)stackscase 1:case 2:case 3:. A call is a pair too, sois
case +:case 1:case 2:. An atom label is unchanged.This is fixed in 39a5f4, will be merged later