-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathREADME.en.html
More file actions
2362 lines (2179 loc) · 98.1 KB
/
README.en.html
File metadata and controls
2362 lines (2179 loc) · 98.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>C programming language extension: Cedro pre-processor</title>
<style type="text/css">@font-face { font-family: 'sorts_mill_goudyregular'; src: local('OFL Sorts Mill Goudy TT'), url('doc/fonts/GoudyStM-webfont.woff') format('woff'); font-weight: normal; font-style: normal; } /* WebKit-specific: */ :root { color-scheme: light dark; } html { background:#111; } body { margin:0; } section:first-child { margin-top:0; } section, footer { font-family:sans-serif; line-height:1.5; max-width:82em; margin:0.5em auto 0.5em auto; background:#222; color:#c92; text-shadow:0 0.1em 0.1em #000; border:thin solid #222; padding:1em; } section + section, section + footer { margin-top:2em; } section>h2:first-child { margin-top:0; } p,ul,table { } a, a:visited { color:#99e; text-decoration:none; box-shadow:0 2px 1px -1px #77e; } a.img { box-shadow:none; } a.img > img { vertical-align:bottom; } a>code { border-bottom:none; background-color:transparent; } code>a { color:inherit !important; } code>b { background:#000; } url, code, tt { display:inline; vertical-align:baseline; padding:0; font-family:'Input', 'Fira Code', 'monospace'; white-space:pre-wrap; } url { color:#ccc; } url:before, url:after { content:'"'; color:#777; } td > url, td > code.command-line-option { display:block; text-align:right; } td > code.command-line-option { font-style:italic; background:transparent; border:none; padding:0; } code { background:#111; color:#8d8; border:thin solid #333; border-radius:0.25em; padding:0.25em; } section > code, td > code { display:inline-block; vertical-align:baseline; overflow-wrap:anywhere; word-break:break-all; } h1 { font-size:200%; margin:0; background-color:#070707; color:#eee; font-family:sorts_mill_goudyregular, serif; font-weight:normal; } h1::after { clear:both; content:""; display:block; } h1>img { vertical-align:bottom; } h2 { font-size:128%; } h3 { font-size:116%; } h4 { font-size:110%; } h2, h3, h4 { font-family:sans-serif; font-weight:normal; color:#c72; border-left:0.75rem solid rgba(204,119,34,0.25); margin-left:-1rem; margin-right:-0.25rem; padding-left:0.25rem; padding-right:0.25rem; } h1>a.anchor, h2>a.anchor, h3>a.anchor, h4>a.anchor { visibility:hidden; } h1:hover>a.anchor, h2:hover>a.anchor, h3:hover>a.anchor, h4:hover>a.anchor { visibility:visible; } table { border-collapse:collapse; background:inherit; } th, td { vertical-align:top; border:thin solid #777; padding:0.5em; } th:empty, td:empty { border:none; } th { font-weight:normal; } p,ul,blockquote { max-width:50em; text-align:justify; } blockquote { border-left:thin solid; padding-left:0.5em; font-style:italic; margin-left:3em; max-width:45em; } blockquote>address { text-align:right; } blockquote>address::before { content:"— "; } .language-selector { padding:0.25rem; font-size:1rem; } .link-to-table-of-contents { background:#111; padding:0.25em; position:fixed; bottom:0; right:0; } @media (prefers-color-scheme:light) { html { background:#ddd; } section, footer { background:#eee; color:#111; text-shadow:none; border-color:#ccc; } a, a:visited { color:#11d; box-shadow:0 2px 1px -1px #ccd; } h1 a, h1 a:visited { color:#ccf; } code { background:#f7f7f7; color:#000; border-color:#eee; } code>b { background:#fff; } url { color:#444; } url:before, url:after { color:#999; } h2, h3, h4 { color:#222; border-color: rgba(34,34,34,0.15); } .link-to-table-of-contents { background:#ddd; } } [title]::after { content:" †"; font-size:75%; vertical-align:top; } table.benchmark td { text-align:right; font-family:monospace; font-family:'Input', 'Fira Code', 'monospace'; }</style>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
</head>
<body>
<section>
<h1 style="text-align:center"><span style="float:left"><a href="https://sentido-labs.com/en/library/?filter=cedro" class="img"><img alt="Atlas blue cedar" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAGFBMVEUAAAAWLxcoYCg5izpCsUNN1U1b9Fp7+3umzZ3RAAAAI2lUWHRBdXRob3IAAAAAAEFsYmVydG8gR29uesOhbGV6IFBhbG9tb8X116oAAAGpSURBVEjH5ZTBdpswEEWBnO4dO+dkawTZxwjsbQwjs66R4ANAow+Ipfn9qq7betUgs+xbcpir0byniaL/UElerOIF9Vl7ORBdinT1IOCVyEnVnJDMxyP1cYudR5D5HJqetuGAjW//oITSveqJ7DGc8G3aGzKOJTUTvcQpGJBmMOgz32Rc9NYgjkWgJS9y6CcFNedZCQorZagMMuRJK9e09vycsRzKhhUlSqyDCKsorXo0NEDBSgWclzCF2ZGsr//nOxZF6zROTuMxMAo+Bxr7UQiUSnLgVbMPCNXGJ9kaPRApIkLddnv8WMXn+beIcwCyvg3jENFYdD+jiUg8ZBLJUUjv4vTmnFGocRLaeBDtnmeboRSisjw/thYt+kghoK3M5+weXK+0kg2HZhvDwXo3kMhcqnHeHGIx+TP1SSifpvco/n7LaXdKZzbQErqxY+uMcYB8+8hqaN0twQlIqB9aLn/OLQXA+6JN+6SlhNUiBICQ3SJEpfwoFt3jTYFHdEE1/F5VzXabOmXw99PXBLw+qN/y2/qa6V/y7wu/JtCdbixyd4wZPfxb+geh0KANiaQN5QAAAABJRU5ErkJggg==" width="64" height="64"/></a> Cedro</span>
<span class="language-selector"><a href="README.es.html">Español</a>, English</span>
<a style="display:inline-block;float:right;font-size:1rem;padding:0.5em" href="http://sentido-labs.com" class="img"><img alt="Sentido-Labs.com" src="doc/sentido-labs-mono.svg" style="width:5em" width="157" height="33"/></a>
</h1>
<p style="clear:both"><em>Cedro</em> is a C language extension that works as a pre-processor with eight features:</p>
<ol>
<li>The <a href="#backstitch-macro"><em>backstitch</em> macro <code>x@ f(), g(y);</code> → <code>f(x); g(x, y);</code></a> (<a href="#backstitch-macro-related-work">related work</a>).</li>
<li><a href="#deferred-resource-release"><em>Deferred</em> resource release <code>auto ...</code></a> or <code>defer ...</code> (<a href="#deferred-resource-release-related-work">related work</a>).</li>
<li><a href="#label-break">Break out of <em>nested loops</em> <code>break <em>label</em>;</code></a> (<a href="#label-break-">related work</a>).</li>
<li><a href="#slice-notation">Notation for array <em>slices</em> <code>array[start..end]</code></a> (<a href="#slice-notation-related-work">related work</a>).</li>
<li><a href="#block-macros"><em>Block</em> macros <code>#define { ... #define }</code></a><!-- (<a href="#block-macros-related-work">related work</a>)-->.</li>
<li><a href="#loop-macros"><em>Loop</em> macros <code>#foreach { ... #foreach }</code></a> (<a href="#loop-macros-related-work">related work</a>).</li>
<li><a href="#binary-include"><em>Binary</em> inclusion <code>#embed "..."</code></a> (<a href="#binary-include-related-work">related work</a>).</li>
<li>Better <a href="#number-literals">number literals</a> (<code>12'34</code> | <code>12_34</code> → <code>1234</code>, <code>0b1010</code> → <code>0xA</code>).</li>
</ol>
<p>To activate it, the source file must contain this line:
<code>#pragma Cedro 1.0</code><br/>
Otherwise, the file is copied directly to the output.</p>
<p>This line can contain certain options, for instance
<code>#pragma Cedro 1.0 defer</code>
to activate the use of
<a href="#deferred-resource-release"><code>defer</code> instead of <code>auto</code></a>.</p>
<p>The <b>source code</b> (<a href="http://www.apache.org/licenses/LICENSE-2.0">Apache 2.0</a> license) can be found at <a href="https://sentido-labs.com/es/biblioteca/?filter=cedro">the library</a>.<br/>To compile it, see <a href="#compile">Compile</a>.<br/><code>cedro</code> only uses the standard C functions, <code>cedrocc</code> and <code>cedro-new</code> require <a href="https://es.wikipedia.org/wiki/POSIX">POSIX</a>.</p>
<code id="usage-cedro">Usage: cedro [options] <file.c>…
cedro new <name> # Runs: <a href="#cedro-new">cedro-new</a> <name>
To read from stdin, put - instead of <file.c>.
The result goes to stdout, can be compiled without intermediate file:
cedro file.c | cc -x c - -o file
It is what the <a href="#cedrocc">cedrocc</a> program does:
cedrocc -o file file.c
With cedrocc, the following options are the defaults:
--insert-line-directives
Code gets modified only after the line `#pragma Cedro 1.0`,
which can include certain options: `#pragma Cedro 1.0 defer`
--apply-macros Applies the macros: backstitch, defer, etc. (default)
--no-apply-macros Does not apply the macros.
--escape-ucn Escape non-ASCII in identifiers as UCN.
--no-escape-ucn Does not escape non-ASCII in identifiers. (default)
--discard-comments Discards the comments.
--discard-space Discards all whitespace.
--no-discard-comments Does not discard comments. (default)
--no-discard-space Does not discard whitespace. (default)
--insert-line-directives Insert `#line` directives.
--no-insert-line-directives Does not insert `#line` directives. (default)
--embed-as-string=<limit> Use string literals instead of bytes
for files smaller than <limit>.
Default value: 0
--c99 Produces source code for C99. (default)
Removes the digit separators (“'” | “_”),
converts binary literals into hexadecimal (“0b1010” → “0xA”),
and expands `#embed`.
It is not a translator between different C versions.
--c89 Produces source code for C89/C90. For now it is the same as --c99.
--c11 Produces source code for C11. For now it is the same as --c99.
--c17 Produces source code for C17. For now it is the same as --c99.
--c23 Produces source code for C23.
For instance, maintains the digit separators (“'” | “_” → “'”),
the binary literals (“0b1010” → “0b1010”),
and does not expand the `#embed` directives.
--print-markers Prints the markers.
--no-print-markers Does not print the markers. (default)
--benchmark Run a performance benchmark.
--validate=ref.c Compares the input to the given “ref.c” file.
Does not apply any macros: to compare the result of running Cedro
on a file, pipe its output through this option, for instance:
`cedro file.c | cedro - --validate=ref.c`
--version Show version: 1.0
The corresponding “pragma” is: `#pragma Cedro 1.0`</code>
<p>The option <code>--escape-ucn</code> encodes Unicode® characters
outside of the ASCII range, when they appear as part of an identifier,
as C99 universal character names
(“C99 standard”, page 65, “<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf#65">6.4.3 Universal character names</a>”),
which can be useful for older compilers without UTF-8 support such as
<a href="https://gcc.gnu.org/bugzilla/show_bug.cgi?id=67224#c32">GCC before version 10</a>.</p>
<p>For API documentation, see <url><a href="doc/api/index.html">doc/api/index.html</a></url>
after running <code>make doc</code> that requires having
<a href="https://www.doxygen.nl/index.html">Doxygen</a> installed.</p>
<h2><code id="compile">Compile</code> <a class="anchor" href="#compile">#compile</a></h2>
<p>The simplest way is <code>cc -o bin/cedro src/cedro.c</code>, but it’s more convenient to use <code>make</code>:</p>
<code>$ make help
Available targets:
release: optimized build, assertions disabled, NDEBUG defined.
→ bin/cedro*
debug: debugging build, assertions enabled.
→ bin/cedro*-debug
static: same as release, only statically linked.
→ bin/cedro*-static
doc: build documentation with Doxygen https://www.doxygen.org
→ doc/api/index.html
test: build both release and debug, then run test suite.
check: apply several static analysis tools:
sparse: <a href="https://sparse.docs.kernel.org/">https://sparse.docs.kernel.org/</a>
valgrind: <a href="https://valgrind.org/">https://valgrind.org/</a>
gcc -fanalyzer:
<a href="https://gcc.gnu.org/onlinedocs/gcc/Static-Analyzer-Options.html">https://gcc.gnu.org/onlinedocs/gcc/Static-Analyzer-Options.html</a>
clean: remove bin/ directory, and clean also inside doc/.</code>
<h2><code id="cedrocc">cedrocc</code> <a class="anchor" href="#cedrocc">#cedrocc</a></h2>
<p>The second executable, <code>cedrocc</code>, allows using Cedro as if it was part of the C compiler.</p>
<code id="usage-cedrocc">Usage: cedrocc [options] <file.c> [<file2.o>…]
Runs Cedro on the first file name that ends with “.c”,
and compiles the result with “cc -x c - -x none” plus the other arguments.
cedrocc -o file file.c
cedro file.c | cc -x c - -o file
The options get passed as is to the compiler, except for those that
start with “--cedro:…” that correspond to cedro options,
for instance “--cedro:escape-ucn” is like “cedro --escape-ucn”.
The following option is the default:
--cedro:insert-line-directives
Some GCC options activate Cedro options automatically:
--std=c90|c89|iso9899:1990|iso8999:199409 → --cedro:c90
--std=c99|c9x|iso9899:1999|iso9899:199x → --cedro:c99
--std=c11|c1x|iso9899:2011 → --cedro:c11
--std=c17|c18|iso9899:2017|iso9899:2018 → --cedro:c17
--std=c2x → --cedro:c23
In addition, for each `#include`, if it finds the file it reads it and
if it finds `#pragma Cedro 1.0` processes it and inserts the result
in place of the `#include`.
You can specify the compiler, e.g. `gcc`:
CEDRO_CC='gcc -x c - -x none' cedrocc …
For debugging, this writes the code that would be piped into `cc`,
into `stdout` instead:
CEDRO_CC='' cedrocc …</code>
<p>If you get an error message like “embedding a directive within macro arguments is not portable” (GCC) or “embedding a directive within macro arguments has undefined behavior” (clang), it means that you’re using Cedro with <code>--insert-line-directives</code> inside the parameters for a macro. You can either expand the code given to the macro manually, or avoid <code>--insert-line-directives</code> by replacing <code>cedrocc -o file file.c</code> with <code>cedro file.c | cc -x c - -o file</code>.</p>
<p><code>cedrocc</code> does another thing in addition to <code>cedro file.c | cc -x c - -o file</code>:
for each <code>#include</code>, if it finds the file (<code>-I ...</code>) it looks inside for <code>#pragma Cedro 1.0</code> and if found, processes the file and inserts the result in place of the <code>#include</code>. The reason is being able to compile in one go programs that use Cedro in several files, instead of having to transform each of them into temporary files to be compiled later.</p>
<h2 id="cedro-new"><code>cedro-new</code> <a class="anchor" href="#cedro-new">#cedro-new</a></h2>
<p>There is a third executable, <code>cedro-new</code>, that produces a program draft in a similar way to <code>cargo new</code> in Rust. <code>cedro new …</code> will actually run <code>cedro-new …</code>. The content is produced from the template in the <url>template/</url> directory, that gets included in the <code>cedro-new</code> executable at compilation.</p>
<code id="usage-cedro-new">Usage: cedro-new [options] <name>
Creates a directory named <name>/ with the template.
-h, --help Shows this message.
-i, --interactive Asks for the names for command and project.
Otherwise, they will be derived from the directory name.</code>
<p>When producing the draft, certain patterns get replaced in
<url>Makefile</url>, <url>README.md</url>, and all the files
under <url>src/</url>:</p>
<ul>
<li><code>{#year}</code>: the current year.</li>
<li><code>{#Author}</code>: name and email address
reported by
<code>git config user.name</code> and <code>… user.email</code>
if they are available, and if not
“Your Name Here <email@example.com>”.</li>
<li><code>{#Template}</code>: the project name,
e.g. “Cedro”.</li>
<li><code>{#template}</code>: the program name,
e.g. “cedro”.</li>
<li><code>{#TEMPLATE}</code>: the program name in uppercase,
e.g. “CEDRO”.</li>
</ul>
<p>The template includes several project drafts, that can be activated in the generated <url>Makefile</url>:</p>
<ul>
<li><p>Command line (“CLI”) tool
that identifies the type of each argument,
and uses a <code>btree</code>
to count how many times each one is repeated.
This gets built if the <url>Makefile</url> is not modified.</p></li>
<li><p>Graphical application with <em><a href="https://github.com/memononen/nanovg">nanovg</a></em>.
Downloads (with <code>curl</code>) and
compiles automatically nanovg, <a href="https://www.glfw.org/">GLFW</a>, and <a href="https://github.com/nigels-com/glew">GLEW</a>.</p>
<code style="display:inline-block;vertical-align:top">include Makefile.nanovg.mk
MAIN=src/main.nanovg.c</code></li>
<li><p>HTTP/1.1 server using <em><a href="https://libuv.org/">libuv</a></em>.
Downloads (with <code>curl</code>) and
compiles automatically libuv.</p>
<code style="display:inline-block;vertical-align:top">include Makefile.libuv.mk
MAIN=src/main.libuv.c</code></li>
</ul>
</section>
<section id="backstitch-macro">
<h2><a href="https://en.wikipedia.org/wiki/Backstitch">Backstitch</a> macro: @ <a class="anchor" href="#backstitch-macro">#backstitch-macro</a></h2>
<p>Threads a value through a sequence of function calls,
as first parameter for each of them.</p>
<p>It is an explicit version of what other programming languages
do to implement member functions, and the result is a usual pattern
in C libraries.</p>
<p>Note: the <code>@</code> symbol is not recognized
when written as <code>\u0040</code>,
but it gets converted to <code>@</code> in the output.
This serves to escape it when chaining Cedro with another
pre-processor that uses it.</p>
<table>
<tr>
<td><code>object @ f(a), g(b);</code></td>
<td><code>f(object, a);
g(object, b);</code></td>
</tr>
<tr>
<td><code>&object @ f(a), g(b);</code></td>
<td><code>f(&object, a);
g(&object, b);</code></td>
</tr>
<tr>
<td><code>object.field @ f(a), g(b);</code></td>
<td><code>f(object.field, a);
g(object.field, b);</code></td>
</tr>
<tr>
<td><code>int x = (object @ f(a), g(b));</code></td>
<td><code>int x = (f(object, a), g(object, b));</code>
<p>This is the C <a href="https://en.wikipedia.org/wiki/Comma_operator">comma operator</a>, it’s the same as</p>
<code>f(object, a); int x = g(object, b);</code></td>
</tr>
<tr>
<td><code>object @prefix_... f(a), g(b);</code></td>
<td><code>prefix_f(object, a);
prefix_g(object, b);</code></td>
</tr>
<tr>
<td><code>object @..._suffix f(a), g(b);</code></td>
<td><code>f_suffix(object, a);
g_suffix(object, b);</code></td>
</tr>
<tr>
<td>
<code>graphics_context @<a href="https://github.com/memononen/nanovg">nvg</a>...
BeginPath(),
Rect(100,100, 120,30),
Circle(120,120, 5),
PathWinding(NVG_HOLE),
FillColor(nvgRGBA(255,192,0,255)),
Fill();</code>
</td><td>
<br/><code>nvgBeginPath(graphics_context);
nvgRect(graphics_context, 100,100, 120,30);
nvgCircle(graphics_context, 120,120, 5);
nvgPathWinding(graphics_context, NVG_HOLE);
nvgFillColor(graphics_context, nvgRGBA(255,192,0,255));
nvgFill(graphics_context);</code>
</td>
</tr>
</table>
<p>For each comma-separated segment,
if it starts with any of the tokens
<code>[</code>,
<code>++</code>, <code>--</code>, <code>.</code>, <code>-></code>,
<code>=</code>, <code>+=</code>, <code>-=</code>, <code>*=</code>, <code>/=</code>, <code>%=</code>, <code><<=</code>, <code>>>=</code>, <code>&=</code>, <code>^=</code>, <code>|=</code>,
or there is nothing that looks like a function call,
the insertion point is the beginning of the segment:</p>
<table>
<tr>
<td><code>number_array @ [3]=44, [2]=11;</code></td>
<td><code>number_array[3]=44; number_array[2]=11;</code></td>
</tr>
<tr>
<td><code>*number_array++ @ = 1, = 2;</code></td>
<td><code>*number_array++ = 1; *number_array++ = 2;</code></td>
</tr>
<tr>
<td><code>figure_center_point @ .x=44, .y=11;</code></td>
<td><code>figure_center_point.x=44; figure_center_point.y=11;</code></td>
</tr>
</table>
<p>Complex expressions can be used as prefixes by putting them
to the left of the <code>@</code> and leaving the ellipsis
without prefix or suffix:</p>
<table>
<tr>
<td><code>// <a href="https://github.com/rryqszq4/ngx_sqlite/blob/785dbf1485bf347c260fa540c4d0955d4d079901/src/ngx_http_sqlite_module.c#L802">ngx_http_sqlite_module.c#L802</a>
(*chain->last)->buf->@ ...
pos = u_str,
last = u_str + ns.len,
memory = 1;</code></td>
<td><br/><code>// <a href="https://github.com/rryqszq4/ngx_sqlite/blob/785dbf1485bf347c260fa540c4d0955d4d079901/src/ngx_http_sqlite_module.c#L802">ngx_http_sqlite_module.c#L802</a>
(*chain->last)->buf->pos = u_str;
(*chain->last)->buf->last = u_str + ns.len;
(*chain->last)->buf->memory = 1;</code></td>
</tr>
</table>
<p>The object part can be left empty, which is useful for things like
adding prefixes or suffixes to enumerations:</p>
<table>
<tr>
<td>
<code>typedef enum {
@TOKEN_... SPACE, WORD, NUMBER
} TokenType;</code>
</td>
<td>
<code>typedef enum {
TOKEN_SPACE, TOKEN_WORD, TOKEN_NUMBER
} TokenType;</code>
</td>
</tr>
<tr>
<td><code>// <a href="http://docs.libuv.org/en/v1.x/guide/threads.html#core-thread-operations">http://docs.libuv.org/en/v1.x/guide/threads.html#core-thread-operations</a>
// `hare` and `tortoise` are functions.
int main() {
int tracklen = 10;
@uv_thread_...
t hare_id,
t tortoise_id,
create(&hare_id, hare, &tracklen),
create(&tortoise_id, tortoise, &tracklen),
join(&hare_id),
join(&tortoise_id);
return 0;
}
</code></td>
<td><br/><code>// <a href="http://docs.libuv.org/en/v1.x/guide/threads.html#core-thread-operations">http://docs.libuv.org/en/v1.x/guide/threads.html#core-thread-operations</a>
// `hare` and `tortoise` are functions.
int main() {
int tracklen = 10;
uv_thread_t hare_id;
uv_thread_t tortoise_id;
uv_thread_create(&hare_id, hare, &tracklen);
uv_thread_create(&tortoise_id, tortoise, &tracklen);
uv_thread_join(&hare_id);
uv_thread_join(&tortoise_id);
return 0;
}
</code></td>
</tr>
<tr>
<td><code>function(a, @prefix_... b, c)</code></td>
<td><code>function(a, prefix_b, prefix_c)</code></td>
</tr>
</table>
<p>The segments part can also be left empty
to add either a prefix or a suffix to an identifier:</p>
<table>
<tr>
<td><code>Next(reader) @xmlTextReader...;</code></td>
<td><code>xmlTextReaderNext(reader);</code></td>
</tr>
<tr>
<td><code>get(&vector, index) @..._Byte_vec;</code></td>
<td><code>get_Byte_vec(&vector, index);</code></td>
</tr>
<tr>
<td><code>function(a, b @prefix_..., c)</code></td>
<td><code>function(a, prefix_b, c)</code></td>
</tr>
</table>
<p>It is a left-associative operator:</p>
<table>
<tr>
<td><code>object @ f(a) @ g(b);</code></td>
<td><code>g(f(object, a), b);</code></td>
</tr>
<tr>
<td><code>x @ one() @ two() @ three() @ four();</code></td>
<td><code>four(three(two(one(x))));</code></td>
</tr>
</table>
<h3 id="backstitch-macro-related-work">Related work <a class="anchor" href="#backstitch-macro-related-work">#…-related-work</a></h3>
<p>Looking for prior implementations of this idea I’ve found
<a href="https://github.com/eudoxia0/magma">magma</a> (2014),
where it is called
<code><a href="https://github.com/eudoxia0/magma#doto">doto</a></code>.
It is a macro for the
<a href="https://github.com/eudoxia0/cmacro">cmacro</a>
pre-processor which has the inconvenient of needing the Common Lisp
<a href="http://www.sbcl.org/">SBCL</a> compiler
in addition to the C compiler.</p>
<p>Clojure also has a macro called <code>doto</code> which works
in a similar manner,
for instance to do <code>f₁(x); f₂(x); f₃(x);</code>:</p>
<table>
<tr><th><a href="https://github.com/eudoxia0/magma">Magma</a></th><td><code>doto</code></td><td><em><a href="https://github.com/eudoxia0/magma#doto">doto</a></em> macro</td><td><code>doto(x) { f₁(); f₂(); f₃(); }</code></td></tr>
<tr><th><a href="https://clojure.org/guides/threading_macros">Clojure</a></th><td><code>doto</code></td><td><em><a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/doto">doto</a></em> macro</td><td><code>(doto x f₁ f₂ f₃)</code></td></tr>
<tr><th><a href="#">Cedro</a></th><td><code>@</code></td><td><em><a href="#backstitch-macro">backstitch</a></em> macro</td><td><code>x @ f₁(), f₂(), f₃()</code></td></tr>
</table>
<p>Functional languages often have a similar operator
without the ability to thread a same value
through several functions.
For instance, the equivalent of <code>f₃(f₂(f₁(x)))</code>:</p>
<table>
<tr><th><a href="https://en.wikipedia.org/wiki/Thompson_shell">Shell</a></th><td><code>|</code></td><td><em><a href="http://doc.cat-v.org/unix/pipes/">pipe</a></em> operator</td><td><code>echo x | f₁ | f₂ | f₃</code></td></tr>
<tr><th><a href="https://www.haskell.org/">Haskell</a></th><td><code>&</code></td><td><em><a href="https://downloads.haskell.org/~ghc/9.2.1/docs/html/libraries/base-4.16.0.0/Data-Function.html#v:-38-">reverse application</a></em> operator</td><td><code>x & f₁ & f₂ & f₃</code></td></tr>
<tr><th><a href="https://ocaml.org/">OCaml</a></th><td><code>|></code></td><td><em><a href="https://v2.ocaml.org/api/Stdlib.html#VAL(|%3E)">reverse application</a></em> operator</td><td><code>x |> f₁ |> f₂ |> f₃</code></td></tr>
<tr><th><a href="https://elixir-lang.org/">Elixir</a></th><td><code>|></code></td><td><em><a href="https://hexdocs.pm/elixir/Kernel.html#%7C%3E/2">pipe</a></em> operator</td><td><code>x |> f₁ |> f₂ |> f₃</code></td></tr>
<tr><th><a href="https://clojure.org/guides/threading_macros">Clojure</a></th><td><code>-></code></td><td><em><a href="https://clojure.github.io/clojure/clojure.core-api.html#clojure.core/-%3E">threading</a></em> macro</td><td><code>(-> x f₁ f₂ f₃)</code></td></tr>
<tr><th><a href="#">Cedro</a></th><td><code>@</code></td><td><em><a href="#backstitch-macro">backstitch</a></em> macro</td><td><code>x @ f₁() @ f₂() @ f₃()</code></td></tr>
</table>
<p>Ada 2005 introduced a feature called
<a href="https://www.adaic.org/resources/add_content/standards/05rat/html/Rat-2-3.html">prefixed-view notation</a>
that is more similar to C++
as the exact function being called can not be determined without
knowing which methods are implemented for the object type.</p>
</section>
<section id="deferred-resource-release">
<h2>Deferred resource release: <a class="anchor" href="#deferred-resource-release">#deferred-resource-release</a></h2>
<p>Moves the clean-up code for a variable to the end of its scope
including the exit points
<code>break</code>, <code>continue</code>, <code>goto</code>,
<code>return</code>.</p>
<p>In C, resources must be released back to the system explicitly
once they are no longer needed, which usualy happens quite far
from the place where they were allocated.
As time passes and changes accumulate in the program,
it’s easy to forget releasing them in all cases
or to attempt releasing a resource twice.</p>
<p>Other programming languages have mechanisms for automatic
resource release:
C++ for instance, uses functions called <em>destructors</em>
that get run <strong>implicitly</strong>
when exiting a variable’s scope.</p>
<p>The programming language Go introduced an <strong>explicit</strong> notation called
“<a href="https://blog.golang.org/defer-panic-and-recover"><em>defer</em></a>”
that fits better the style of C.
The first difference is that in Go,
all releases happen when exiting the function,
while with Cedro the releases happen when exiting each block,
like the destructors in C++ do.</p>
<p>There are more differences, such as for instance that in Go it
can be used to modify the return value of the function,
and that Cedro does not even try to handle
<code><a href="https://en.cppreference.com/w/c/program/longjmp">longjmp()</a></code>,
<code><a href="https://en.cppreference.com/w/c/program/exit">exit()</a></code>,
<code><a href="https://en.cppreference.com/w/c/thread/thrd_exit">thrd_exit()</a></code> etc.
because it could only apply the deferred actions in the current function, not in any function that called this one. See “<i><a href="https://gustedt.wordpress.com/2020/12/14/a-defer-mechanism-for-c/">A defer mechanism for C</a></i>” (<a href="https://hal.inria.fr/hal-03090771/document">published academic paper as PDF</a> in the <a href="http://www.sigapp.org/sac/sac2021/program.html">SAC’21</a> conference) for a compiler-level implementation that does handle <code>longjmp()</code> and stack unwinding.</p>
<p>In Cedro, the release function is marked with the
<a href="https://en.cppreference.com/w/c/language/storage_duration">C keyword <b><code>auto</code></b></a>
which is not needed in standard C code
<em>before C23</em>
because it is the default and can be replaced with <code>signed</code> as
<a href="https://stackoverflow.com/a/60890064/291462">it has the same effect</a>.</p>
<p>It is also possible to use <code>defer</code> instead of <code>auto</code>
adding the keyword “defer” to the “pragma”:
<code>#pragma Cedro 1.0 <b>defer</b></code>.</p>
<table>
<tr>
<td>
<code><b>#pragma Cedro 1.0</b>
…
char* text = malloc(count + 1);
if (!text) return ENOMEM;
<b>auto free(text);</b>
…
if (file_name) {
FILE* file = fopen(file_name, "w");
if (!file) return errno;
<b>auto fclose(file);</b>
fwrite(text, sizeof(char), count, file);
…</code></td>
<td>
<code><b>#pragma Cedro 1.0 defer</b>
…
char* text = malloc(count + 1);
if (!text) return ENOMEM;
<b>defer free(text);</b>
…
if (file_name) {
FILE* file = fopen(file_name, "w");
if (!file) return errno;
<b>defer fclose(file);</b>
fwrite(text, sizeof(char), count, file);
…</code></td>
</tr>
</table>
<p>In this example, there is a <code>text</code> store and a <code>file</code> that must be released back to the system:</p>
<table>
<tr>
<td>
<code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
<b>#pragma Cedro 1.0</b>
int repeat_letter(char letter, size_t count,
char* file_name)
{
char* text = malloc(count + 1);
if (!text) return ENOMEM;
<b>auto free(text);</b>
for (size_t i = 0; i < count; ++i) {
text[i] = letter;
}
text[count] = 0;
if (file_name) {
FILE* file = fopen(file_name, "w");
if (!file) return errno;
<b>auto fclose(file);</b>
fwrite(text, sizeof(char), count, file);
fputc('\n', file);
}
printf("Repeated %lu times: %s\n",
count, text);
return 0;
}
int main(void)
{
return repeat_letter('A', 6, "aaaaaa.txt");
}</code></td><td>
<br/><br/><code>#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
int repeat_letter(char letter, size_t count,
char* file_name)
{
char* text = malloc(count + 1);
if (!text) return ENOMEM;
for (size_t i = 0; i < count; ++i) {
text[i] = letter;
}
text[count] = 0;
if (file_name) {
FILE* file = fopen(file_name, "w");
if (!file) {
<b>free(text);</b>
return errno;
}
fwrite(text, sizeof(char), count, file);
fputc('\n', file);
<b>fclose(file);</b>
}
printf("Repeated %lu times: %s\n",
count, text);
<b>free(text);</b>
return 0;
}
int main(void)
{
return repeat_letter('A', 6, "aaaaaa.txt");
}</code></td>
</tr>
</table>
<p>Compiling it with GCC or clang,
on the left running explicitly the compiler,
and on the right using <code>cedrocc</code>:</p>
<table>
<tr>
<td><code>$ cedro repeat.c | cc -o repeat -x c -
$ ./repeat
Repeated 6 times: AAAAAA
$ cat aaaaaa.txt
AAAAAA
$ valgrind --leak-check=yes ./repeat
…
==8795== HEAP SUMMARY:
==8795== in use at exit: 0 bytes in 0 blocks
==8795== total heap usage: 4 allocs, 4 frees,
5,599 bytes allocated
==8795==
==8795== All heap blocks were freed -- no leaks are possible</code>
</td><td>
<code>$ cedrocc -o repeat repeat.c
$ ./repeat
Repeated 6 times: AAAAAA
$ cat aaaaaa.txt
AAAAAA
$ valgrind --leak-check=yes ./repeat
…
==8795== HEAP SUMMARY:
==8795== in use at exit: 0 bytes in 0 blocks
==8795== total heap usage: 4 allocs, 4 frees,
5,599 bytes allocated
==8795==
==8795== All heap blocks were freed -- no leaks are possible</code>
</td>
</tr>
</table>
<p>In this example adapted from
<a href="http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2542.pdf#40">“Proposal for C2x, WG14 n2542, Defer Mechanism for C” p. 40</a>,
the released resources are spin locks:
<em>(the difference of course is that in this case the <code>spin_unlock()</code> calls do not run after the panic)</em></p>
<table>
<tr>
<td>
<code>/* Adapted from example in n2542.pdf#40 */
<b>#pragma Cedro 1.0</b>
int f1(void) {
puts("g called");
if (bad1()) { return 1; }
spin_lock(&lock1);
<b>auto spin_unlock(&lock1);</b>
if (bad2()) { return 1; }
spin_lock(&lock2);
<b>auto spin_unlock(&lock2);</b>
if (bad()) { return 1; }
/* Access data protected by the spinlock then force a panic */
completed += 1;
unforced(completed);
return 0;
}</code>
</td>
<td>
<code>/* Adapted from example in n2542.pdf#40 */
int f1(void) {
puts("g called");
if (bad1()) { return 1; }
spin_lock(&lock1);
if (bad2()) { <b>spin_unlock(&lock1);</b> return 1; }
spin_lock(&lock2);
if (bad()) { <b>spin_unlock(&lock2); spin_unlock(&lock1);</b> return 1; }
/* Access data protected by the spinlock then force a panic */
completed += 1;
unforced(completed);
<b>spin_unlock(&lock2);</b>
<b>spin_unlock(&lock1);</b>
return 0;
}
</code>
</td>
</tr>
</table>
<p>Andrew Kelley compared resource management between C and his
<a href="https://ziglang.org/">Zig programming language</a>
in a 2019 presentation titled
<a href="https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s">“The Road to Zig 1.0” at 29:21s</a>,
and here I’ve re-created his C example using Cedro to produce
the function as he showed it, except that Cedro does not know
that the final <code>for</code> loop never ends so it adds
unnecessary resource release code after it.</p>
<table>
<tr>
<td>
<code>// Example retrofitted from C example by Andrew Kelley:
// <a href="https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s">https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s</a>
<b>#pragma Cedro 1.0</b>
int main(int argc, char **argv) {
struct SoundIo *soundio = soundio_create();
if (!soundio) {
fprintf(stderr, "out of memory\n");
return 1;
}
<b>auto soundio_destroy(soundio);</b>
int err;
if ((err = soundio_connect(soundio))) {
fprintf(stderr, "unable to connect: %s\n", soundio_strerror(err));
return 1;
}
soundio_flush_events(soundio);
int default_output_index = soundio_default_output_device_index(soundio);
if (default_output_index < 0) {
fprintf(stderr, "No output device\n");
return 1;
}
struct SoundIoDevice *device = soundio_get_output_device(soundio, default_output_index);
if (!device) {
fprintf(stderr, "out of memory\n");
return 1;
}
<b>auto soundio_device_unref(device);</b>
struct SoundIoOutStream *outstream = soundio_outstream_create(device);
if (!outstream) {
fprintf(stderr, "out of memory\n");
return 1;
}
<b>auto soundio_outstream_destroy(outstream);</b>
outstream->format = SoundIoFormatFloat32NE;
outstream->write_callback = write_callback;
if ((err = soundio_outstream_open(outstream))) {
fprintf(stderr, "unable to open device: %s" "\n", soundio_strerror(err));
return 1;
}
if ((err = soundio_outstream_start(outstream))) {
fprintf(stderr, "unable to start device: %s\n", soundio_strerror(err));
return 1;
}
for (;;) soundio_wait_events(soundio);
}</code>
</td><td>
<code>// Example retrofitted from C example by Andrew Kelley:
// <a href="https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s">https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s</a>
int main(int argc, char **argv) {
struct SoundIo *soundio = soundio_create();
if (!soundio) {
fprintf(stderr, "out of memory\n");
return 1;
}
int err;
if ((err = soundio_connect(soundio))) {
fprintf(stderr, "unable to connect: %s\n", soundio_strerror(err));
<b>soundio_destroy(soundio);</b>
return 1;
}
soundio_flush_events(soundio);
int default_output_index = soundio_default_output_device_index(soundio);
if (default_output_index < 0) {
fprintf(stderr, "No output device\n");
<b>soundio_destroy(soundio);</b>
return 1;
}
struct SoundIoDevice *device = soundio_get_output_device(soundio, default_output_index);
if (!device) {
fprintf(stderr, "out of memory\n");
<b>soundio_destroy(soundio);</b>
return 1;
}
struct SoundIoOutStream *outstream = soundio_outstream_create(device);
if (!outstream) {
fprintf(stderr, "out of memory\n");
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
return 1;
}
outstream->format = SoundIoFormatFloat32NE;
outstream->write_callback = write_callback;
if ((err = soundio_outstream_open(outstream))) {
fprintf(stderr, "unable to open device: %s" "\n", soundio_strerror(err));
<b>soundio_outstream_destroy(outstream);</b>
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
return 1;
}
if ((err = soundio_outstream_start(outstream))) {
fprintf(stderr, "unable to start device: %s\n", soundio_strerror(err));
<b>soundio_outstream_destroy(outstream);</b>
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
return 1;
}
for (;;) soundio_wait_events(soundio);
<b>soundio_outstream_destroy(outstream);</b>
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
}</code>
</td>
</tr>
</table>
<p>However, his Zig example had the unfair advantage of
returning error values instead of printing error messages
which takes more space.
The following is a C function that
matches the Zig version more closely:</p>
<table>
<tr>
<td>
<code>// Example retrofitted from Zig example by Andrew Kelley:
// <a href="https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s">https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s</a>
<b>#pragma Cedro 1.0</b>
int main(int argc, char **argv) {
struct SoundIo *soundio = soundio_create();
if (!soundio) { return SoundIoErrorNoMem; }
<b>auto soundio_destroy(soundio);</b>
int err;
if ((err = soundio_connect(soundio))) return err;
soundio_flush_events(soundio);
const int default_output_index = soundio_default_output_device_index(soundio);
if (default_output_index < 0) return SoundIoErrorNoSuchDevice;
const struct SoundIoDevice *device = soundio_get_output_device(soundio, default_output_index);
if (!device) return SoundIoErrorNoMem;
<b>auto soundio_device_unref(device);</b>
const struct SoundIoOutStream *outstream = soundio_outstream_create(device);
if (!outstream) return SoundIoErrorNoMem;
<b>auto soundio_outstream_destroy(outstream);</b>
outstream->format = SoundIoFormatFloat32NE;
outstream->write_callback = write_callback;
if ((err = soundio_outstream_open(outstream))) return err;
if ((err = soundio_outstream_start(outstream))) return err;
while (true) soundio_wait_events(soundio);
}</code>
</td>
<td>
<code>// Example retrofitted from Zig example by Andrew Kelley:
// <a href="https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s">https://www.youtube.com/watch?v=Gv2I7qTux7g&t=1761s</a>
int main(int argc, char **argv) {
struct SoundIo *soundio = soundio_create();
if (!soundio) { return SoundIoErrorNoMem; }
int err;
if ((err = soundio_connect(soundio))) {
<b>soundio_destroy(soundio);</b>
return err;
}
soundio_flush_events(soundio);
const int default_output_index = soundio_default_output_device_index(soundio);
if (default_output_index < 0) {
<b>soundio_destroy(soundio);</b>
return SoundIoErrorNoSuchDevice;
}
const struct SoundIoDevice *device = soundio_get_output_device(soundio, default_output_index);
if (!device) {
<b>soundio_destroy(soundio);</b>
return SoundIoErrorNoMem;
}
const struct SoundIoOutStream *outstream = soundio_outstream_create(device);
if (!outstream) {
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
return SoundIoErrorNoMem;
}
outstream->format = SoundIoFormatFloat32NE;
outstream->write_callback = write_callback;
if ((err = soundio_outstream_open(outstream))) {
<b>soundio_outstream_destroy(outstream);</b>
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
return err;
}
if ((err = soundio_outstream_start(outstream))) {
<b>soundio_outstream_destroy(outstream);</b>
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
return err;
}
while (true) soundio_wait_events(soundio);
<b>soundio_outstream_destroy(outstream);</b>
<b>soundio_device_unref(device);</b>
<b>soundio_destroy(soundio);</b>
}</code>
</td>
</tr>
</table>
<p>The Cedro version is much closer,
but his point still stands because the plain C version
needs a lot of repeated code and is more fragile.
And of course Zig has
<a href="https://ziglang.org/learn/overview/">many other great features</a>.</p>
<h3 id="deferred-resource-release-related-work">Related work <a class="anchor" href="#deferred-resource-release-related-work">#…-related-work</a></h3>
<p>Apart from the already mentioned
“<a href="#a-defer-mechanism-for-c"><em>A defer mechanism for C</em></a>”,
there are macros that use a <code>for</code> loop as
<code>for (<em>allocation and initialization</em>; <em>condition</em>; <em>release</em>) { <em>actions</em> }</code>
[<a href="#note-defer-1" name="node-defer-1-ref">1</a>]
or other techniques
[<a href="#note-defer-2" name="node-defer-2-ref">2</a>].</p>
<div id="note-defer-1">
[<a href="#note-defer-1-ref">1</a>]
“<em><a href="https://gustedt.gitlabpages.inria.fr/p99/p99-html/utilities.html#blocks">P99 Scope-bound resource management with for-statements</a></em>” from the same author (2010), “<em><a href="https://www.reddit.com/r/C_Programming/comments/46lpna/would_it_be_possible_to_create_a_scoped_lock/">Would it be possible to create a scoped_lock implementation in C?</a></em>” (2016), ”<em><a href="https://news.ycombinator.com/item?id=25419916">C compatible scoped locks</a></em>“ (2021), “<em><a href="https://www.youtube.com/watch?v=QpAhX-gsHMs&t=1053s">Modern C and What We Can Learn From It - Luca Sas [ ACCU 2021 ] 00:17:18</a></em>”, 2021
<!-- C++: , o “<em><a href="https://stackoverflow.com/questions/48117908/is-the-a-practical-way-to-emulate-go-language-defer-in-c-or-c-destructors">Is there a practical way to emulate GO language defer in C?</a></em>” -->
</div>
<div id="note-defer-2">
[<a href="#note-defer-2-ref">2</a>]
“<em><a href="https://www.reddit.com/r/C_Programming/comments/46lpna/would_it_be_possible_to_create_a_scoped_lock/">Would it be possible to create a scoped_lock implementation in C?</a></em>” (2016), “<em><a href="https://github.com/trws/libdefer#limitations">libdefer: Go-style defer for C</a></em>” (2016), “<em><a href="https://github.com/moon-chilled/Defer">A Defer statement for C</a></em>” (2020), “<em><a href="https://gist.github.com/jart/aed0fd7a7fa68385d19e76a63db687ff">Go-like defer for C that works with most optimization flag combinations under GCC/Clang</a></em>” (2021)
</div>
<p>Compilers like GCC and clang have non-standard features to do this
like the <a href="https://echorand.me/site/notes/articles/c_cleanup/cleanup_attribute_c.html"><code>__cleanup__</code> variable attribute</a>.</p>
<p>Cedro does not have the limitation of the deferred code having to be a function: it can be a code block, with or without conditionals, which allows for instance to emulate <a href="https://ziglang.org/learn/overview/#manual-memory-management">Zig’s <code>errdefer</code></a> by performing different actions in case of error:</p>
<table>
<tr>
<td>
<code>char* allocate_block(size_t n, char** err_p)
{
char* result = malloc(n);
<b>auto if (*err_p) {
free(result);
result = NULL;
}</b>
if (n > 10) {
*err_p = "n is too big";
}
return result;
}</code>
</td><td>
<code>char* allocate_block(size_t n, char** err_p)
{
char* result = malloc(n);
if (n > 10) {
*err_p = "n is too big";
}
<b>if (*err_p) {
free(result);
result = NULL;
}</b>
return result;
}</code>
</td>
</tr>
</table>
</section>
<section id="label-break">
<h2>Break out of <em>nested loops</em>: <a class="anchor" href="#label-break">#label-break</a></h2>
<p>Converts <code><b>break</b> <em>label</em>;</code> or <code><b>continue</b> <em>label</em>;</code> into <code><b>goto</b> <em>label</em>;</code>. In C it’s only possible to break out of one loop at a time when using <code>break</code>, which is also a problem when the interruption comes from a <code>switch</code> block.</p>
<table>
<tr>
<td>
<code>#include <stdio.h>
#include <stdlib.h>
<b>#pragma Cedro 1.0</b>
int main(int argc, char* argv[])
{
int x = 0, y = 0;
for (x = 0; <b><em>next_x</em>:</b> x < 100; ++x) {
for (y = 0; y < 100; ++y) {
switch (x + y) {
case 157:
<b>break</b> <em>found_number_decomposition</em>;
case 11:
x = 37;
fprintf(stderr, "Jump from x=11 to x=%d\n", x);
--x;
<b>continue</b> <em>next_x</em>;
}
}
} <em>found_number_decomposition</em>:
if (x < 100 || y < 100) {
fprintf(stderr, "Found %d = %d + %d\n",
x + y, x, y);
}
return 0;
}</code>
</td><td>
<br/><br/><code>#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv[])
{
int x = 0, y = 0;
for (x = 0; x < 100; ++x) {
for (y = 0; y < 100; ++y) {
switch (x + y) {
case 157:
<b>goto</b> <em>found_number_decomposition</em>;
case 11:
x = 37;
fprintf(stderr, "Jump from x=11 to x=%d\n", x);
--x;
<b>goto</b> <em>next_x</em>;
}
}
<b><em>next_x</em>:;</b>
} <em>found_number_decomposition</em>:
if (x < 100 || y < 100) {
fprintf(stderr, "Found %d = %d + %d\n",
x + y, x, y);
}
return 0;
}</code>
</td>
</tr>