@cella-lang/c 0.0.0-stage → 0.1.202610110557

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGES.md ADDED
@@ -0,0 +1,46 @@
1
+ # @cella-lang/c 的變更
2
+
3
+ 給使用這個套件的工具(產生 `c.*` 項的翻譯器)看的 API 變更。雜湊(每個定義的 own/merkle,見 `index.json`)在不穩定期可能改變;下面列出改變的定義。
4
+
5
+ ## 未發佈
6
+
7
+ - 寬字元:`tWChar`、`wstrArr`、`wstrLit`、`WCStr`、`wcstrOk`、`wcslen`、`wcscmp`、`wcscpy`、`wcscat`。
8
+ - 位元欄位(**不相容**:`CType` 多一個建構子 `ctBits t w`,對 `CType` 做 match 的程式要補分支):`bitsStore`、`bitsVal`;`sizeofV` 的 struct 佈局改以位元計算(`bitsPlace`),不含位元欄位時結果不變。
9
+ - 三維陣列:`init3`、`arr3ToMem`、`planePtr`、`at3`、`set3`。
10
+ - `remquoQ8`(`remquo` 的商只提供 `q % 8`,帶符號;餘數用 `remainder`)。
11
+
12
+ ## 2026-10-10
13
+
14
+ 第一版:C11 的整數。
15
+ - 型別:`_Bool`、`char`、`signed char`、`unsigned char`、`short`、`int`、`long`、`long long` 與其無號版本(`c.tInt p` 等);平台 `c.lp64P`(char 有號)、`c.aarch64P`(char 無號)。
16
+ - 值 `c.Val t`、字面量 `c.litV`、轉換 `c.cast`;算術 `c.addV`/`subV`/`mulV`/`divV`/`remV`/`negV`;位元 `c.andV`/`orV`/`xorV`/`notV`;移位 `c.shlV`/`shrV`;比較 `c.ltV` 等與邏輯 `c.lnotV`/`landV`/`lorV`(結果是 int)。
17
+ - 控制流:`c.ifC`/`whileC`/`doWhileC`/`forC`(條件是純量不等於 0)、`c.switchC`(標籤轉成提升後的型別;不重複是證明引數);敘述沿用 `cpp.Stmt`。
18
+ - 輸出:`c.format`、`c.printf`(`printf` 的整數子集;引數 `c.Arg` 由 `c.argV` 做預設引數提升;前置條件 `c.printfOkB`;結果 `c.Printed p`,`c.printedSt`、`c.printedN`)。
19
+ - 陣列:`c.Arr`(`zerosA`、`uninitA`、`initA`)、`c.at`/`setAt`(前置條件 `c.Readable`/`c.InBounds`)、`lenA`、`sizeofA`;迴圈用的 `c.Full t n`(`getK`、`putK`、`fullOf`、`valuesK`、`getKAt`、`readableOfFull`、`ltPred`、`ltPredSucc`);與 C++ 陣列的 `arrToCpp`、`atToCpp`、`setAtToCpp`。
20
+ - 指標與記憶體(沿用 cpp 的記憶體模型):`c.Mem`、`c.Ptr`、`c.addrOf`、`c.load`/`store`(前置條件 `c.DerefOk`/`StoreOk`)、`c.endScope`、`loadStore`;陣列退化 `c.arrToMem`、`declArrM`,指標算術 `c.ptrAdd`、`idx`(`c.PtrAddOk`)、`c.ptrDiff`、`ptrLt`、`ptrEq`(`c.SameBlock`)、`loadFullK`;`c.malloc`/`calloc`(失敗是參數)、`c.free`(`c.FreeOk`),引理 `storeDerefOk`、`mallocStoreOk`、`mallocFreeOk`;`void*`:`c.VoidPtr`、`toVoid`、`fromVoid`(`c.UncastOk`)、`voidRoundTrip`;與 C++ 的 `loadToCpp`。
21
+ - 字串:`c.strArr`、`strArrN`、`strLit`(唯讀的字面量);`<string.h>` 的 `c.strlen`、`strcmp`、`strncmp`、`strcpy`、`strncpy`、`strcat`、`strchr`(前置條件 `c.CStr`/`cstrOk`、`c.CStrN`/`cstrNOk`、`c.strcpyOk`、`strcatOk`、`strncpyOk`);`printf` 的 `%s`(`c.argS`);`<ctype.h>` 的 `c.isdigit`、`isalpha`、`isspace`、`isupper`、`islower`、`toupper`、`tolower`(`c.ctypeArg`)。
22
+ - struct:`c.CType`、`c.Members`(`mNil`、`mCons`;成員 `ctInt`、`ctPtr`、`ctArr`、`ctStruct`)、`c.Obj`、`c.Struct`、`memberTy`、`member`、`setMember`、`scalar`、`ptrScalar`、`uninitS`、`zeroS`、`initS`(初始值 `iInt`、`iPtr`、`iList`、`iStr`);記憶體裡的 struct:`smemNew`、`objAt`、`arrow`、`arrowSet`;`structArr`;成員陣列:`idxOkB`、`elemAt`、`setElem`、`strcpyArr`、`strlenArr`、`readArr`、`argSArr`。`c.malloc`、`c.free`、`c.FreeOk`、`c.ptrAdd`、`c.PtrAddOk`、`c.amem`、`c.aptr` 與 malloc 的引理對任意元素型別(`PtrAddOk`/`FreeOk` 的第一個索引是元素型別:整數寫 `cpp.Val t`)。
23
+ - 陣列參數:`c.readableNB`、`writableNB`、`readK`、`writeK`、`allCells`、`cellAt`、`storeKeepsWritable`、`writableAfterStore`、`writableAfterWriteK`、`ltSelfSucc`;指標的指標:`c.loadP`;argv:`c.Argv`、`mkArgv`、`argvMem`、`argvPtrs`、`argvBase`、`argc`、`argvAt`。
24
+ - 輸入:`c.scanf`、`c.scanfOkB`、目標 `c.STarget`(`tgtInt`、`tgtChars`)、`c.Scanned`(`scanCount`、`scanSt`、`scanVals`、`assignInt`、`scannedBytes`)、`c.bytesToArr`。
25
+ - 多維陣列:`c.rowPtr`、`arr2ToMem`、`at2`、`set2`、`readable2`、`writable2`、`read2K`、`write2K`、`writable2AfterWrite`;泛型的 `allUpTo`、`allUpToAt`、`allUpToCong`。
26
+ - 浮點:`c.Double`、`c.Float`、`dlit`、`flit32`、`infD`、`nanD`、`toDouble`、`toFloat`、`toInt`(`TruncOk`、`truncOk`)、`ltD`、`leD`、`eqD`;printf 的 `f F e E g G`(`c.argF`);scanf 的 `f e g`(`c.tgtFloat`、`c.assignF`);`<math.h>`:`sqrt`、`fabs`、`floor`、`ceil`、`round`、`trunc`、`pow`、`fmod`。
27
+ - 函式指標:`c.FTy`、`Sig`、`SigFn`、`FnPtr`、`fnOf`、`fnNull`、`fnCast`、`fnEq`、`callable`、`call`、`call1`、`call2`、`addM`、`subM`、`mulM`;`<stdlib.h>`:`qsort`、`bsearch`(`cmpSig`、`qsortOkB`、`bsearchOkB`)、`readN`。
28
+ - `realloc`(`ReallocOk`、`reallocOk`、`reallocB`);`memcpy`、`memmove`、`memset`(`MemOk`、`memOk`、`memcpyB`、`memmoveB`、`memsetB`)。
29
+ - `union`:`c.ctUnion`、`Union`、`uactive`、`uget`、`uset`、`initU`、`iField`(初始值的指定成員)、`umemNew`、`uObjAt`、`uArrow`、`uArrowSet`。
30
+ - `<string.h>`:`strstr`、`strrchr`、`strncat`(`strncatB`)、`memcmp`(`memcmpB`)、`memchr`(`memchrB`)。
31
+ - `scanf` 的 `%[`;`strtok`(`TokState`、`tokInit`、`TokRes`、`tokPtr`、`tokMem`、`tokState`、`strtokM`)。
32
+ - 成員陣列的字串函式(值版本):`strcmpArr`、`strcmpArrLit`、`strcatArr`、`strcpyArrMem`、`strcpyMemArr`。
33
+ - `sprintf`、`snprintf`(`sprintfB`、`snprintfB`、`Written`、`writtenMem`、`writtenN`)、`sscanf`;`Arg` 的 `argStr` 多一個欄位記來源的指標(`argS`、`argSArr` 的用法不變)。
34
+ - 字元與行的 I/O:`putchar`、`puts`、`getchar`(`GotChar`、`gotCh`、`gotSt`)、`fgets`(`fgetsB`、`Fgot`、`fgotPtr`、`fgotMem`、`fgotSt`)。
35
+ - `<stdlib.h>`:`atoi`、`strtol`(`Strtol`、`strtolVal`、`strtolEnd`、`baseOkB`、`parseNum`)、`abs`、`labs`。
36
+ - 可變長度陣列:`vla`、`vla2`、`vlaLen`、`vlaOkB`。
37
+ - `const` 物件:`constArrToMem`、`constAddrOf`。
38
+ - `rand`/`srand`:`RandEnv`、`randEnv`、`RandSt`、`randInit`、`srand`、`rand`、`RandRes`、`randVal`、`randSt2`、`randNat`、`randMaxV`、`randMaxAtLeast`、`randBelow`。
39
+ - 檔案 I/O:`FState`、`fsInit`、`FH`、`fhIsNull`、`fopen`(`Opened`、`openedH`、`openedSt`)、`fclose`、`fprintf`(`FPrinted`)、`fputs`、`fscanf`(`FScanned`)、`fgetsF`(`FFgot`)、`fgetc`、`fileContent`;`fgets` 的核心抽成 `fgetsCore`。
40
+ - `goto` 與標籤:`Jump`、`gotoS`、`retJ`、`withLabels`。
41
+ - `<math.h>` 的其餘:`exp`、`log`、`log10`、`log2`、`exp2`、`sin`、`cos`、`tan`、`asin`、`acos`、`atan`、`atan2`、`expm1`、`log1p`、`sinh`、`cosh`、`tanh`、`asinh`、`acosh`、`atanh`、`cbrt`、`hypot`(沿用 cpp 的正確捨入模型);`fmin`、`fmax`、`fdim`、`remainder`、`ldexp`、`frexpM`、`frexpE`、`isnan`、`isinf`、`isfinite`、`signbit`、`fma`、`nextafter`、`modfInt`、`modfFrac`、`copysign`、`scalbn`、`logb`、`ilogb`。
42
+ - `<time.h>`:`timeT`、`TimeEnv`(`timeEnv`)、`time`、`srandSeed`、`srandTime`、`difftime`。
43
+ - 跟著 cpp:串流狀態多了 `err` 欄位(`cpp.mkIOS` 多一個參數),C 的輸入函式照樣保留它。
44
+ - 長度修飾 `z`、`j`、`t`(printf 與 scanf;`Len` 多 `lenZ`、`lenJ`、`lenT`)。
45
+ - `sizeof`:`layout`、`sizeofN`、`sizeofV`、`sizeofDouble`、`sizeofFloat`;`strspn`、`strcspn`、`strpbrk`。
46
+ - 依賴 `@cella-lang/cpp`(C 家族共用的整數核心、敘述與輸出狀態)。
package/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,7 @@
1
+ Cella
2
+ Copyright 2026 SungYu Chang
3
+
4
+ This product includes software developed by SungYu Chang
5
+ (the Cella proof language: checker, standard library, and playground).
6
+
7
+ Licensed under the Apache License, Version 2.0 (see LICENSE).
package/README.md CHANGED
@@ -1,3 +1,206 @@
1
- # Temporary Holding Version
1
+ # @cella-lang/c
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ C11 integer types for the [Cella](https://www.npmjs.com/package/cella-lang) proof checker, as a compiled module pack.
4
+
5
+ C's integers are not mathematical integers: widths depend on the platform, signed overflow, division by zero and
6
+ out-of-range shifts are undefined behaviour, and `char` may be signed or unsigned. This library defines the C semantics directly:
7
+
8
+ - `c.Val t` — a C value of integer type `t` (`c.tInt p`, `c.tUChar`, `c.tBool`, …): an integer plus a proof that it lies in the range of `t`;
9
+ - integer promotions and the usual arithmetic conversions compute the result type (`c.addV p a b ok : c.Val (cpp.common p s t)`);
10
+ - every operation that can be undefined takes the condition as an argument — for concrete values `(cpp.inT refl)` (signed: no overflow),
11
+ `unit` (unsigned: wraps modulo 2^N), `refl` (divisor not zero), `(c.shlOk refl)` / `(c.shrOk refl)` (shift amount and, for signed `<<`,
12
+ a result that fits the result type);
13
+ - comparisons and logical operators yield an `int` 0 or 1, as in C;
14
+ - conversions: to `_Bool` is "not zero", to unsigned is modulo 2^N, to signed wraps (implementation-defined; as clang);
15
+ - platforms: `c.lp64P` (x86-64 Linux/macOS, `char` signed), `c.aarch64P` (AArch64 Linux, `char` unsigned).
16
+
17
+ Statements reuse the language-neutral statement model of `@cella-lang/cpp` (`cpp.Stmt`, `cpp.seq`, `cpp.breakS`, `cpp.continueS`,
18
+ `cpp.returnS`); C adds what differs:
19
+
20
+ - `c.ifC`, `c.whileC`, `c.doWhileC`, `c.forC` — the condition is a C scalar, true when it is not zero; loops take fuel and end in
21
+ `cpp.outOfFuel` rather than assuming termination;
22
+ - `c.switchC p e blocks refl` — the controlling expression is promoted, `case` labels are converted to the promoted type before comparing;
23
+ the last argument proves the converted labels are distinct and there is at most one `default` (in `unsigned int`, `-1` and `4294967295`
24
+ are the same label, so `refl` fails).
25
+
26
+ Output: `c.format p fmt args refl : String` and `c.printf p fmt args refl st` (appends to the stream state shared with the C++ model and
27
+ returns the number of characters as an `int`), the integer subset of `printf`: `%d %i %u %o %x %X %c %%`, flags `- + space # 0`, field width
28
+ and precision (digits or `*`), length modifiers `hh h l ll`. Arguments go through the default argument promotions (`c.argV p x`). Undefined
29
+ behaviour is the precondition `c.printfOkB p fmt args ≡ true`: a malformed or unknown conversion, too few arguments, an argument whose type
30
+ does not match the conversion (a signed/unsigned counterpart is allowed only when the value fits both), `#` with `d i u c`, `0` or a
31
+ precision with `c`, anything inside `%%`.
32
+
33
+ ```cella
34
+ import c
35
+ def p : cpp.Platform := c.lp64P
36
+ def n (v : Int) (ok : cpp.inTB (c.tInt p) v ≡ true) : c.Arg := c.argV p (c.litV (c.tInt p) v ok)
37
+ def s : c.format p "%5d|%-+4d|%#x" [n (pos 42) refl, n (pos 7) refl, n (pos 255) refl] refl ≡ " 42|+7 |0xff" := refl -- accept
38
+ def t : String := c.format p "%d %d" [n (pos 1) refl] refl -- reject: too few arguments
39
+ ```
40
+
41
+ Arrays: `c.Arr t` (fixed length; elements may be uninitialized). `c.zerosA t n` (`static`, `= {0}`), `c.uninitA t n` (automatic),
42
+ `c.initA t n [x0, …] refl` (`{…}`; missing elements are zero, too many initializers do not check). `c.at a i (c.readable refl)` reads an
43
+ element that is in bounds and initialized, `c.setAt a i x (c.inBounds refl)` writes in bounds; the index is a C value of any integer
44
+ type. `c.sizeofA p a` is `N * sizeof(T)` as a `size_t`. For loops, `c.Full t n` carries its length and "all initialized" in its type:
45
+ `c.getK f k h` / `c.putK f k h x` take the `h : k < n` given by a counting loop, so the body needs no separate proof of bounds.
46
+
47
+ ```cella
48
+ import c
49
+ def p : cpp.Platform := c.lp64P
50
+ def a : c.Arr (c.tInt p) := c.initA (c.tInt p) 5 [c.litV (c.tInt p) (pos 1) refl, c.litV (c.tInt p) (pos 2) refl] refl
51
+ def s : c.get (c.at a (c.litV (c.tInt p) (pos 3) refl) (c.readable refl)) ≡ pos 0 := refl -- accept: a[3] is zero
52
+ def t : c.Val (c.tInt p) := c.at a (c.litV (c.tInt p) (pos 5) refl) (c.readable refl) -- reject: a[5] is out of bounds
53
+ ```
54
+
55
+ Pointers and memory reuse the provenance memory model of `@cella-lang/cpp`: `c.Mem t` and `c.Ptr` (a pointer remembers its allocation
56
+ block and offset). `c.addrOf m x` is `&x`, `c.load m q (c.derefOk refl)` is `*q` (not NULL, block alive, in bounds, initialized),
57
+ `c.store m q v (c.storeOk refl)` is `*q = v`. Arrays decay with `c.arrToMem`; `c.ptrAdd` / `c.idx` require the result to stay inside the
58
+ array or one past its end, `c.ptrDiff` / `c.ptrLt` require both pointers to be in the same array. `c.malloc m n fails` takes whether the
59
+ allocation fails as a parameter (the environment's choice; failure returns NULL), so a verdict must hold for both outcomes — dereferencing
60
+ without a NULL check does not prove. `c.calloc` zero-fills; `c.free` requires NULL or a live block from `malloc`, pointed at its start.
61
+ `c.toVoid` / `c.fromVoid` convert through `void*`, back to the original type only.
62
+
63
+ ```cella
64
+ import c
65
+ def t : cpp.IType := cpp.tInt cpp.lp64P
66
+ def r : c.Allocated t := c.addrOf (c.memNew t) (c.litV t (pos 5) refl) -- int x = 5; int *q = &x;
67
+ def s : c.get (c.load (c.amem r) (c.aptr r) (c.derefOk refl)) ≡ pos 5 := refl -- accept: *q is 5
68
+ def u : c.Val t := c.load (c.memNew t) c.nullP (c.derefOk refl) -- reject: *NULL
69
+ ```
70
+
71
+ Strings are NUL-terminated `char` arrays in that memory. `c.strArr p m "abc"` is `char s[] = "abc"`, `c.strArrN p m 10 "abc" refl` is
72
+ `char s[10] = "abc"` (zero-filled; exactly N bytes leaves no NUL), and `c.strLit p m "abc"` is `char *s = "abc"` — a read-only allocation, so
73
+ writing through it does not prove. `<string.h>`: `c.strlen`, `c.strcmp`, `c.strncmp`, `c.strcpy`, `c.strncpy` (writes no NUL when the source is
74
+ not shorter than n), `c.strcat`, `c.strchr`; their preconditions are `c.cstrOk refl` (a NUL is reachable), `c.cstrNOk refl` (the first n bytes
75
+ or a NUL), and `c.strcpyOk refl refl` etc. (the destination is writable and large enough, no overlap). `printf` takes strings with
76
+ `c.argS m q` for `%s` (width, `-`, precision; with a precision the array needs no NUL). `<ctype.h>`: `c.isdigit`, `isalpha`, `isspace`,
77
+ `isupper`, `islower`, `toupper`, `tolower`, whose argument must be an `unsigned char` value or `EOF` (`c.ctypeArg refl`).
78
+
79
+ ```cella
80
+ import c
81
+ def p : cpp.Platform := c.lp64P
82
+ def C : cpp.IType := c.tChar p
83
+ def r : c.Allocated C := c.strLit p (c.memNew C) "hello"
84
+ def s : c.format p "[%-7s]" [c.argS (c.amem r) (c.aptr r)] refl ≡ "[hello ]" := refl -- accept
85
+ def t : c.Mem C := c.store (c.amem r) (c.aptr r) (c.litV C (pos 72) refl) (c.storeOk refl) -- reject: writes a string literal
86
+ ```
87
+
88
+ Structs are described by their members, `c.mCons "x" (c.ctInt t) (c.mCons "next" c.ctPtr c.mNil)`, and a struct value has type
89
+ `c.Struct ms`; every scalar member may be uninitialized on its own. `c.initS ms [c.iInt x, …] refl` is an initializer list (missing members
90
+ are zero), `c.member ms "x" s` / `c.setMember ms "x" v s` access by name, and `c.scalar … refl` reads a member that has been initialized.
91
+ In memory, a struct type gets its own `cpp.GMem (c.Struct ms)`: `c.malloc` and `c.free` work for any element type, `c.arrow ms "v" m q` is
92
+ `q->v`, and `c.arrowSet ms "v" x m q (cpp.storeOk refl)` is `q->v = x` — a `malloc`ed struct is initialized member by member, so this
93
+ needs no other member to be initialized. Arrays of structs: `c.structArr`; member arrays and strings are handled as values (`c.setElem`,
94
+ `c.strcpyArr`, `c.strcmpArr`, `c.strcatArr`, `c.strcpyArrMem` / `c.strcpyMemArr` to and from memory, `c.argSArr` for `%s`). A linked list whose every `malloc` may fail is in `tests/t_linked_list.cella`.
95
+
96
+ ```cella
97
+ import c
98
+ def I : cpp.IType := c.tInt c.lp64P
99
+ def Point : c.Members := c.mCons "x" (c.ctInt I) (c.mCons "y" (c.ctInt I) c.mNil)
100
+ def p : c.Struct Point := c.initS Point [c.iInt (c.litV I (pos 1) refl)] refl
101
+ def y : c.get (c.scalar (c.member Point "y" p) refl) ≡ pos 0 := refl -- accept: y is zero-filled
102
+ def u : c.Val I := c.scalar (c.member Point "y" (c.uninitS Point)) refl -- reject: y is uninitialized
103
+ ```
104
+
105
+ Array parameters are pointers, so a function does not know the length: `int sum(int a[], int n)` takes the precondition
106
+ `c.readableNB m a n ≡ true` ("n cells after a are readable"), and `c.readK m a n ok k h` reads `a[k]` for `h : k < n` — the function is
107
+ checked once for any memory and pointer, and a caller with a concrete array proves the precondition by `refl`. Writing is the same with
108
+ `c.writableNB` / `c.writeK`, and `c.writableAfterWriteK` keeps the precondition through a loop. Pointers can be stored in memory
109
+ (`cpp.GMem c.Ptr`, `c.loadP` for `*pp`), and `c.mkArgv p ["prog", "x"]` builds `argv` (NUL-terminated strings, a NULL at `argv[argc]`).
110
+
111
+ Input: `c.scanf p "%d %s" [c.tgtInt t, c.tgtChars 8] st refl` reads from the input state shared with the C++ model (`cpp.ios "12 abc"`)
112
+ and returns what was read: `c.scanCount p r` (the number of assignments, or EOF), `c.assignInt r k t old` (the k-th assigned value, or the
113
+ old value when the conversion failed), `c.scannedBytes r k` and `c.scanSt r` (the rest of the input). The precondition rejects a target of the
114
+ wrong type, a result that does not fit (`%d` reading `99999999999`), and a `%s` that does not fit its array.
115
+
116
+ Multi-dimensional arrays: `c.arr2ToMem m R C inits refl` declares `T a[R][C]` (nested or flat initializers), and `c.at2 m a R C i j hi hj ok`
117
+ reads `a[i][j]` with the bounds checked per dimension — `a[0][C]` is out of bounds for the inner array even though it is inside the object.
118
+ A function taking `int a[][C]` gets `c.readable2 m a n C ≡ true` and reads with `c.read2K`.
119
+
120
+ Floating point: `c.Double` and `c.Float` are IEEE 754 binary64 and binary32 (shared with the C++ model). `c.dlit m e` is the literal
121
+ m × 10^e; `c.toInt t x (c.truncOk refl)` truncates toward zero with the result required to fit; division needs a nonzero divisor.
122
+ `printf` takes doubles through `c.argF` (`%f %e %g` with flags, width and precision), `scanf` reads them into `c.tgtFloat`, and
123
+ `c.sqrt`, `floor`, `ceil`, `round`, `trunc`, `pow`, `fmod`, `fabs`, `exp`, `log`, `log10`, `log2`, `exp2`, `sin`, `cos`, `tan`, `asin`, `acos`,
124
+ `atan`, `atan2`, `expm1`, `log1p`, `sinh`, `cosh`, `tanh`, `asinh`, `acosh`, `atanh`, `cbrt`, `hypot` follow `<math.h>` with correctly rounded results (the standard does not require a correctly rounded libm).
125
+
126
+ Function pointers: a signature `c.sig [c.fInt t, …] r` describes the type; C functions return `Maybe` (`nothing` is undefined
127
+ behavior in that call, e.g. `c.addM` overflowing). `c.fnOf "f" s f` takes `&f`, `c.fnCast` converts (the pointer remembers the
128
+ function it points to), and `c.call2 s p x y refl` calls through it — the proof says the pointer is not NULL, its type matches the
129
+ function, and the call is defined. `c.qsort` and `c.bsearch` take a comparator `c.FnPtr (c.cmpSig p t)` that must be a consistent
130
+ total order on the array.
131
+
132
+ Memory functions: `c.realloc m q n fails ok` keeps the first min(old, n) cells and ends the old allocation (failure is a
133
+ parameter, as with `malloc`; `n = 0` is not in the subset). `c.memcpy`, `c.memmove` and `c.memset` count elements, not bytes;
134
+ `memcpy` requires the two ranges not to overlap.
135
+
136
+ Unions: `c.ctUnion ms` uses the same member list as a struct. A `c.Union ms` remembers which member was written last;
137
+ `c.uset` writes a member and `c.uget ms k u refl` reads it only if it is that member (reading another member reinterprets
138
+ bytes in C, which the model does not represent). `c.initU ms [c.iField "k" v] refl` is `= {.k = v}`.
139
+
140
+ More of `<string.h>`: `c.strstr`, `c.strrchr`, `c.strncat` (reads at most n bytes of the source), and `c.memcmp` / `c.memchr`
141
+ on character arrays (on `int` arrays `memcmp` compares bytes in memory order, so its sign depends on the representation).
142
+
143
+ Tokens and lines: `scanf` supports `%[...]` (scan sets, `^` for the complement); `c.strtok` makes the hidden state of
144
+ `strtok` an explicit value — pass `c.tokInit` the first time and the previous `c.tokState` (with a NULL string) afterwards.
145
+
146
+ Formatting into memory: `c.sprintf` and `c.snprintf` write `c.format`'s output into a buffer (the output must fit and must not
147
+ overlap a `%s` argument; `snprintf` truncates to n − 1 bytes and returns the full length); `c.sscanf` reads from a string in memory.
148
+
149
+ Character and line I/O: `c.putchar`, `c.puts`, `c.getchar` (EOF at the end of input) and `c.fgets` (at most n − 1 bytes,
150
+ keeping the newline) share the `cpp.IOS` state with `printf` and `scanf`.
151
+
152
+ Number conversions: `c.atoi` (overflow is undefined, so the result must fit), `c.strtol` (base 0 or 2–36, clamps to
153
+ `LONG_MAX` / `LONG_MIN` and reports where it stopped), `c.abs` and `c.labs` (the most negative value is excluded).
154
+
155
+ Variable length arrays: `c.vla t m n ok` declares `T a[n]` with a run-time length that must be positive, and `c.vla2` declares
156
+ `T a[r][c]`; the elements start uninitialized.
157
+
158
+ Const objects: `c.constArrToMem` and `c.constAddrOf` allocate read-only storage, so writing through a pointer that cast the
159
+ `const` away (or passing the array to a function that writes it) is rejected.
160
+
161
+ Random numbers: the sequence of `rand` is implementation-defined, so it is a parameter (`c.RandEnv`) and a verdict holds for
162
+ every environment — e.g. `rand() % 6 + 1` is between 1 and 6 for any `RAND_MAX` ≥ 32767 and any sequence.
163
+
164
+ Files: `c.FState` is the file system (an environment given by `c.fsInit`) plus the open files. `c.fopen` takes a `fails`
165
+ parameter like `malloc`, so the NULL check is required; `c.fscanf`, `c.fgetsF`, `c.fgetc`, `c.fprintf`, `c.fputs` and
166
+ `c.fclose` require the handle to be open in a suitable mode.
167
+
168
+ `goto`: a function body is a table of labeled blocks (`c.withLabels`); `c.gotoS "l"` leaves nested loops and ifs like a
169
+ `return` and resumes at block `l`, and `c.retJ` is the real return. Labels live at the top level of the body.
170
+
171
+ Length modifiers `z`, `j` and `t` (`printf("%zu", strlen(s))`) use the LP64 types: `size_t` is `unsigned long`, `ptrdiff_t` and
172
+ `intmax_t` are `long`.
173
+
174
+ `sizeof`: `c.sizeofV pl ct` computes sizes from a type descriptor (struct padding follows the LP64 ABI, which is
175
+ implementation-defined); `c.strspn`, `c.strcspn` and `c.strpbrk` complete the common `<string.h>` functions.
176
+
177
+ The integer core shared by the C family (type descriptors, platforms, promotions) comes from `@cella-lang/cpp`; C's value type is its own,
178
+ and its relation to C++'s is a proved path on the fragment where both languages agree.
179
+
180
+ ```cella
181
+ import c
182
+ def p : cpp.Platform := c.lp64P
183
+ def x : c.Val (c.tInt p) := c.addV p (c.litV (c.tInt p) (pos 2) refl) (c.litV (c.tInt p) (pos 3) refl) (cpp.inT refl) -- accept
184
+ def y : c.Val (c.tInt p) := c.shlV p (c.litV (c.tInt p) (pos 1) refl) (c.litV (c.tInt p) (pos 31) refl) (c.shlOk refl) -- reject: 1 << 31 does not fit int
185
+ ```
186
+
187
+ ## Loading
188
+
189
+ The pack only loads into the `cella-lang` build named by `index.json` (`checkerHash`, `cbfVersion`), on top of the packages it depends on
190
+ (`index.requires.packages`, here `@cella-lang/cpp`); the `peerDependencies` entries pin those versions.
191
+
192
+ ```js
193
+ import init, { init_stdlib_cached, load_module_pack, load_library_pack, check } from 'cella-lang';
194
+ import assets from 'cella-lang/assets';
195
+ // 1. the standard modules it and its dependencies need: index.requires["cella-lang"].modules
196
+ for (const m of JSON.parse(index).requires['cella-lang'].modules) load_module_pack(await bytes(assets.module(m)));
197
+ // 2. the packages it depends on, in order: index.requires.packages (each with its own index.json)
198
+ load_library_pack(cppIndex, 'cpp', await bytes(cppPackUrl));
199
+ // 3. the library itself
200
+ const r = JSON.parse(load_library_pack(index, 'c', await bytes(new URL('./c.cell', libUrl))));
201
+ if (!r.ok) throw new Error(r.error);
202
+ ```
203
+
204
+ ## Per-definition hashes
205
+
206
+ `index.json` lists, for every definition, `own` (its own content) and `merkle` (its content plus everything it depends on).
package/c.cell ADDED
Binary file