-
Notifications
You must be signed in to change notification settings - Fork 314
/
deparse.c
1884 lines (1786 loc) · 55.3 KB
/
deparse.c
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
/*
* R : A Computer Language for Statistical Data Analysis
* Copyright (C) 1997--2021 The R Core Team
* Copyright (C) 1995, 1996 Robert Gentleman and Ross Ihaka
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, a copy is available at
* https://www.R-project.org/Licenses/
*
*
* IMPLEMENTATION NOTES:
*
* Deparsing has 3 layers.
* - The user interfaces, do_deparse(), do_dput(), and do_dump() should
* not be called from an internal function.
* - unless nlines > 0, the actual deparsing via deparse2() needs
* to be done twice, once to count things up and a second time to put
* them into the string vector for return.
* - Printing this to a file is handled by the calling routine.
*
* Current call paths:
*
* do_deparse() ------------> deparse1WithCutoff()
* do_dput() -> deparse1() -> deparse1WithCutoff()
* do_dump() -> deparse1() -> deparse1WithCutoff()
* ---------
* Workhorse: deparse1WithCutoff() -> deparse2() -> deparse2buff() --> {<itself>, ...}
* --------- ~~~~~~~~~~~~~~~~~~ implicit arg R_BrowseLines == getOption("deparse.max.lines")
*
* ./errors.c: PrintWarnings() | warningcall_dflt() ... -> deparse1s() -> deparse1WithCutoff()
* ./print.c : Print[Language|Closure|Expression]() --> deparse1w() -> deparse1WithCutoff()
* bind.c,match.c,..: c|rbind(), match(), switch()...-> deparse1line() -> deparse1WithCutoff()
*
* INDENTATION:
*
* Indentation is carried out in the routine printtab2buff at the
* bottom of this file. It seems like this should be settable via
* options.
*
*
* LocalParseData VARIABLES (historically GLOBALs):
*
* linenumber: counts the number of lines that have been written,
* this is used to setup storage for deparsing.
*
* len: counts the length of the current line, it will be
* used to determine when to break lines.
*
* incurly: keeps track of whether we are inside a curly or not,
* this affects the printing of if-then-else.
*
* inlist: keeps track of whether we are inside a list or not,
* this affects the printing of if-then-else.
*
* startline: indicator TRUE=start of a line (so we can tab out to
* the correct place).
*
* indent: how many tabs should be written at the start of
* a line.
*
* buff: contains the current string, we attempt to break
* lines at cutoff, but can unlimited length.
*
* lbreak: often used to indicate whether a line has been
* broken, this makes sure that that indenting behaves
* itself.
*/
/* DTL ('duncan'):
* The code here used to use static variables to share values
* across the different routines. These have now been collected
* into a struct named LocalParseData and this is explicitly
* passed between the different routines. This avoids the needs
* for the global variables and allows multiple evaluators, potentially
* in different threads, to work on their own independent copies
* that are local to their call stacks. This avoids any issues
* with interrupts, etc. not restoring values.
* The previous issue with the global "cutoff" variable is now implemented
* by creating a deparse1WithCutoff() routine which takes the cutoff from
* the caller and passes this to the different routines as a member of the
* LocalParseData struct. Access to the deparse1() routine remains unaltered.
* This is exactly as Ross had suggested ...
*
* One possible fix is to restructure the code with another function which
* takes a cutoff value as a parameter. Then "do_deparse" and "deparse1"
* could each call this deeper function with the appropriate argument.
* I wonder why I didn't just do this? -- it would have been quicker than
* writing this note. I guess it needs a bit more thought ...
*/
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#define R_USE_SIGNALS 1
#include <Defn.h>
#include <Internal.h>
#include <float.h> /* for DBL_DIG */
#include <Print.h>
#include <Fileio.h>
#ifdef Win32
#include <trioremap.h>
#endif
#define BUFSIZE 512
#define MIN_Cutoff 20
#define DEFAULT_Cutoff 60
#define MAX_Cutoff (BUFSIZE - 12)
/* ----- MAX_Cutoff < BUFSIZE !! */
#include "RBufferUtils.h"
typedef R_StringBuffer DeparseBuffer;
typedef struct {
int linenumber;
int len; // FIXME: size_t
int incurly;
int inlist;
Rboolean startline; /* = TRUE; */
int indent;
SEXP strvec;
DeparseBuffer buffer;
int cutoff;
int backtick;
int opts;
int sourceable;
#ifdef longstring_WARN
int longstring;
#endif
int maxlines;
Rboolean active;
int isS4;
Rboolean fnarg; /* fn argument, so parenthesize = as assignment */
} LocalParseData;
static SEXP deparse1WithCutoff(SEXP call, Rboolean abbrev, int cutoff,
Rboolean backtick, int opts, int nlines);
static void args2buff(SEXP, int, int, LocalParseData *);
static void deparse2buff(SEXP, LocalParseData *);
static void print2buff(const char *, LocalParseData *);
static void printtab2buff(int, LocalParseData *);
static void writeline(LocalParseData *);
static void vec2buff (SEXP, LocalParseData *, Rboolean do_names);
static void vector2buff(SEXP, LocalParseData *);
static void src2buff1(SEXP, LocalParseData *);
static Rboolean src2buff(SEXP, int, LocalParseData *);
static void linebreak(Rboolean *lbreak, LocalParseData *);
static void deparse2(SEXP, SEXP, LocalParseData *);
// .Internal(deparse(expr, width.cutoff, backtick, .deparseOpts(control), nlines))
SEXP attribute_hidden do_deparse(SEXP call, SEXP op, SEXP args, SEXP rho)
{
checkArity(op, args);
SEXP expr = CAR(args); args = CDR(args);
int cut0 = DEFAULT_Cutoff;
if(!isNull(CAR(args))) {
cut0 = asInteger(CAR(args));
if(cut0 == NA_INTEGER|| cut0 < MIN_Cutoff || cut0 > MAX_Cutoff) {
warning(_("invalid 'cutoff' value for 'deparse', using default"));
cut0 = DEFAULT_Cutoff;
}
}
args = CDR(args);
int backtick = isNull(CAR(args)) ? 0 : asLogical(CAR(args));
args = CDR(args);
int opts = isNull(CAR(args)) ? SHOWATTRIBUTES : asInteger(CAR(args));
args = CDR(args);
int nlines = asInteger(CAR(args));
if (nlines == NA_INTEGER) nlines = -1;
return deparse1WithCutoff(expr, FALSE, cut0, backtick, opts, nlines);
}
// deparse1() version *looking* at getOption("deparse.max.lines")
SEXP deparse1m(SEXP call, Rboolean abbrev, int opts)
{
Rboolean backtick = TRUE;
int old_bl = R_BrowseLines,
blines = asInteger(GetOption1(install("deparse.max.lines")));
if (blines != NA_INTEGER && blines > 0)
R_BrowseLines = blines;
SEXP result = deparse1WithCutoff(call, abbrev, DEFAULT_Cutoff, backtick,
opts, 0);
R_BrowseLines = old_bl;
return result;
}
// deparse1() version with R_BrowseLines := 0
SEXP deparse1(SEXP call, Rboolean abbrev, int opts)
{
Rboolean backtick = TRUE;
int old_bl = R_BrowseLines;
R_BrowseLines = 0;
SEXP result = deparse1WithCutoff(call, abbrev, DEFAULT_Cutoff, backtick,
opts, 0);
R_BrowseLines = old_bl;
return result;
}
/* used for language objects in print() */
attribute_hidden
SEXP deparse1w(SEXP call, Rboolean abbrev, int opts)
{
Rboolean backtick = TRUE;
return deparse1WithCutoff(call, abbrev, R_print.cutoff, backtick, opts, -1);
}
static SEXP deparse1WithCutoff(SEXP call, Rboolean abbrev, int cutoff,
Rboolean backtick, int opts, int nlines)
{
/* Arg. abbrev:
If abbrev is TRUE, then the returned value
is a STRSXP of length 1 with at most 13 characters.
This is used for plot labelling etc.
*/
SEXP svec;
int savedigits;
Rboolean need_ellipses = FALSE;
LocalParseData localData =
{/* linenumber */ 0,
0, 0, 0, /*startline = */TRUE, 0,
NULL,
/* DeparseBuffer= */ {NULL, 0, BUFSIZE},
DEFAULT_Cutoff, FALSE, 0, TRUE,
#ifdef longstring_WARN
FALSE,
#endif
/* maxlines = */ INT_MAX,
/* active = */TRUE, 0, FALSE};
localData.cutoff = cutoff;
localData.backtick = backtick;
localData.opts = opts;
localData.strvec = R_NilValue;
PrintDefaults(); /* from global options() */
savedigits = R_print.digits;
R_print.digits = DBL_DIG;/* MAX precision */
print2buff("", &localData); /* ensure allocation of buffer.data, PR#17876 */
svec = R_NilValue;
if (nlines > 0) {
localData.linenumber = localData.maxlines = nlines;
} else { // default: nlines = -1 (from R), or = 0 (from other C fn's)
if(R_BrowseLines > 0)// not by default; e.g. from getOption("deparse.max.lines")
localData.maxlines = R_BrowseLines + 1; // enough to determine linenumber
deparse2(call, svec, &localData);
localData.active = TRUE;
if(R_BrowseLines > 0 && localData.linenumber > R_BrowseLines) {
localData.linenumber = R_BrowseLines + 1;
need_ellipses = TRUE;
}
}
PROTECT(svec = allocVector(STRSXP, localData.linenumber));
deparse2(call, svec, &localData);
if (abbrev) {
char data[14];
strncpy(data, CHAR(STRING_ELT(svec, 0)), 10);
data[10] = '\0';
if (strlen(CHAR(STRING_ELT(svec, 0))) > 10) strcat(data, "...");
svec = mkString(data);
} else if(need_ellipses) {
SET_STRING_ELT(svec, R_BrowseLines, mkChar(" ..."));
}
if(nlines > 0 && localData.linenumber < nlines) {
UNPROTECT(1); /* old svec value */
PROTECT(svec);
svec = lengthgets(svec, localData.linenumber);
}
UNPROTECT(1);
PROTECT(svec); /* protect from warning() allocating, PR#14356 */
R_print.digits = savedigits;
/*: Don't warn anymore, we do deal with most (-> 'S4SXP' below)
if ((opts & WARNINCOMPLETE) && localData.isS4)
warning(_("deparse of an S4 object may not always be source()able"));
else */
if ((opts & WARNINCOMPLETE) && !localData.sourceable)
warning(_("deparse may be incomplete"));
#ifdef longstring_WARN
if ((opts & WARNINCOMPLETE) && localData.longstring)
warning(_("deparse may be not be source()able in R < 2.7.0"));
#endif
/* somewhere lower down might have allocated ... */
R_FreeStringBuffer(&(localData.buffer));
UNPROTECT(1);
return svec;
}
/* deparse1line(), e.g. for non-trivial list entries in as.character(<list>).
* --------------
* Concatenates all lines into one long one.
* This is needed in terms.formula, where we must be able
* to deparse a term label into a single line of text so
* that it can be reparsed correctly */
SEXP deparse1line_(SEXP call, Rboolean abbrev, int opts)
{
Rboolean backtick=TRUE;
int lines;
SEXP temp = PROTECT(
deparse1WithCutoff(call, abbrev, MAX_Cutoff, backtick, opts, -1));
if ((lines = length(temp)) > 1) {
char *buf;
int i;
size_t len;
const void *vmax;
cetype_t enc = CE_NATIVE;
for (len = 0, i = 0; i < length(temp); i++) {
SEXP s = STRING_ELT(temp, i);
cetype_t thisenc = getCharCE(s);
len += strlen(CHAR(s)); // FIXME: check for overflow?
if (thisenc != CE_NATIVE)
enc = thisenc; /* assume only one non-native encoding */
}
vmax = vmaxget();
buf = R_alloc((size_t) len+lines, sizeof(char));
*buf = '\0';
for (i = 0; i < length(temp); i++) {
if (i % 1000 == 999) R_CheckUserInterrupt();
strcat(buf, CHAR(STRING_ELT(temp, i)));
if (i < lines - 1)
strcat(buf, "\n");
}
temp = ScalarString(mkCharCE(buf, enc));
vmaxset(vmax);
}
UNPROTECT(1);
return(temp);
}
SEXP deparse1line(SEXP call, Rboolean abbrev)
{
return deparse1line_(call, abbrev, SIMPLEDEPARSE);
}
// called only from ./errors.c for calls in warnings and errors :
SEXP attribute_hidden deparse1s(SEXP call)
{
Rboolean backtick=TRUE;
return
deparse1WithCutoff(call, FALSE, DEFAULT_Cutoff, backtick,
DEFAULTDEPARSE, /* nlines = */ 1);
}
#include "Rconnections.h"
static void con_cleanup(void *data)
{
Rconnection con = data;
if(con->isopen) con->close(con);
}
// .Internal(dput(x, file, .deparseOpts(control)))
SEXP attribute_hidden do_dput(SEXP call, SEXP op, SEXP args, SEXP rho)
{
checkArity(op, args);
SEXP tval = CAR(args);
int opts = isNull(CADDR(args)) ? SHOWATTRIBUTES : asInteger(CADDR(args));
if (TYPEOF(tval) == CLOSXP) {
SEXP clo = PROTECT(duplicate(tval));
SET_CLOENV(clo, R_GlobalEnv);
tval = deparse1(clo, 0, opts);
UNPROTECT(1);
} else
tval = deparse1(tval, 0, opts);
PROTECT(tval); /* against Rconn_printf */
if(!inherits(CADR(args), "connection"))
error(_("'file' must be a character string or connection"));
int ifile = asInteger(CADR(args));
if (ifile != 1) {
Rconnection con = getConnection(ifile);
RCNTXT cntxt;
Rboolean wasopen = con->isopen;
if(!wasopen) {
char mode[5];
strcpy(mode, con->mode);
strcpy(con->mode, "w");
if(!con->open(con)) error(_("cannot open the connection"));
strcpy(con->mode, mode);
/* Set up a context which will close the connection on error */
begincontext(&cntxt, CTXT_CCODE, R_NilValue, R_BaseEnv, R_BaseEnv,
R_NilValue, R_NilValue);
cntxt.cend = &con_cleanup;
cntxt.cenddata = con;
}
if(!con->canwrite) error(_("cannot write to this connection"));
Rboolean havewarned = FALSE;
for (int i = 0; i < LENGTH(tval); i++) {
int res = Rconn_printf(con, "%s\n", CHAR(STRING_ELT(tval, i)));
if(!havewarned &&
res < strlen(CHAR(STRING_ELT(tval, i))) + 1) {
warning(_("wrote too few characters"));
havewarned = TRUE;
}
}
if(!wasopen) {endcontext(&cntxt); con->close(con);}
}
else { // ifile == 1 : "Stdout"
for (int i = 0; i < LENGTH(tval); i++)
Rprintf("%s\n", CHAR(STRING_ELT(tval, i)));
}
UNPROTECT(1); /* tval */
return (CAR(args));
}
// .Internal(dump(list, file, envir, opts, evaluate))
SEXP attribute_hidden do_dump(SEXP call, SEXP op, SEXP args, SEXP rho)
{
checkArity(op, args);
SEXP names = CAR(args),
file = CADR(args);
if(!inherits(file, "connection"))
error(_("'file' must be a character string or connection"));
if(!isString(names))
error( _("character arguments expected"));
int nobjs = length(names);
if(nobjs < 1 || length(file) < 1)
error(_("zero-length argument"));
SEXP source = CADDR(args);
if (source != R_NilValue && TYPEOF(source) != ENVSXP)
error(_("invalid '%s' argument"), "envir");
int opts = asInteger(CADDDR(args));
/* <NOTE>: change this if extra options are added */
if(opts == NA_INTEGER || opts < 0 || opts > 2048)
error(_("'opts' should be small non-negative integer"));
// evaluate :
if (!asLogical(CAD4R(args))) opts |= DELAYPROMISES;
SEXP objs, o = PROTECT(objs = allocList(nobjs));
int nout = 0;
for (int i = 0; i < nobjs; i++, o = CDR(o)) {
SET_TAG(o, installTrChar(STRING_ELT(names, i)));
SETCAR(o, findVar(TAG(o), source));
if (CAR(o) == R_UnboundValue)
warning(_("object '%s' not found"), EncodeChar(PRINTNAME(TAG(o))));
else nout++;
}
o = objs;
SEXP outnames = PROTECT(allocVector(STRSXP, nout)); // -> result
if(nout > 0) {
if(INTEGER(file)[0] == 1) {
for (int i = 0, nout = 0; i < nobjs; i++) {
if (CAR(o) == R_UnboundValue) continue;
const char *obj_name = translateChar(STRING_ELT(names, i));
SET_STRING_ELT(outnames, nout++, STRING_ELT(names, i));
if(isValidName(obj_name)) Rprintf("%s <-\n", obj_name);
else if(opts & S_COMPAT) Rprintf("\"%s\" <-\n", obj_name);
else Rprintf("`%s` <-\n", obj_name);
SEXP tval = PROTECT(deparse1(CAR(o), 0, opts));
for (int j = 0; j < LENGTH(tval); j++)
Rprintf("%s\n", CHAR(STRING_ELT(tval, j)));/* translated */
UNPROTECT(1); /* tval */
o = CDR(o);
}
}
else {
Rconnection con = getConnection(INTEGER(file)[0]);
Rboolean wasopen = con->isopen;
RCNTXT cntxt;
if(!wasopen) {
char mode[5];
strcpy(mode, con->mode);
strcpy(con->mode, "w");
if(!con->open(con)) error(_("cannot open the connection"));
strcpy(con->mode, mode);
/* Set up a context which will close the connection on error */
begincontext(&cntxt, CTXT_CCODE, R_NilValue, R_BaseEnv, R_BaseEnv,
R_NilValue, R_NilValue);
cntxt.cend = &con_cleanup;
cntxt.cenddata = con;
}
if(!con->canwrite) error(_("cannot write to this connection"));
Rboolean havewarned = FALSE;
for (int i = 0, nout = 0; i < nobjs; i++) {
if (CAR(o) == R_UnboundValue) continue;
SET_STRING_ELT(outnames, nout++, STRING_ELT(names, i));
int res;
const char *s = translateChar(STRING_ELT(names, i));
unsigned int extra = 6;
if(isValidName(s)) {
extra = 4;
res = Rconn_printf(con, "%s <-\n", s);
} else if(opts & S_COMPAT)
res = Rconn_printf(con, "\"%s\" <-\n", s);
else
res = Rconn_printf(con, "`%s` <-\n", s);
if(!havewarned && res < strlen(s) + extra)
warning(_("wrote too few characters"));
SEXP tval = PROTECT(deparse1(CAR(o), 0, opts));
for (int j = 0; j < LENGTH(tval); j++) {
res = Rconn_printf(con, "%s\n", CHAR(STRING_ELT(tval, j)));
if(!havewarned &&
res < strlen(CHAR(STRING_ELT(tval, j))) + 1) {
warning(_("wrote too few characters"));
havewarned = TRUE;
}
}
UNPROTECT(1); /* tval */
o = CDR(o);
}
if(!wasopen) {endcontext(&cntxt); con->close(con);}
}
}
UNPROTECT(2);
return outnames;
}
static void linebreak(Rboolean *lbreak, LocalParseData *d)
{
if (d->len > d->cutoff) {
if (!*lbreak) {
*lbreak = TRUE;
d->indent++;
}
writeline(d);
}
}
static void deparse2(SEXP what, SEXP svec, LocalParseData *d)
{
d->strvec = svec;
d->linenumber = 0;
d->indent = 0;
deparse2buff(what, d);
writeline(d);
}
/* curlyahead looks at s to see if it is a list with
the first op being a curly. You need this kind of
lookahead info to print if statements correctly. */
static Rboolean
curlyahead(SEXP s)
{
if (isList(s) || isLanguage(s))
if (TYPEOF(CAR(s)) == SYMSXP && CAR(s) == R_BraceSymbol)
return TRUE;
return FALSE;
}
/* needsparens looks at an arg to a unary or binary operator to
determine if it needs to be parenthesized when deparsed
mainop is a unary or binary operator,
arg is an argument to it, on the left if left == 1 */
static Rboolean needsparens(PPinfo mainop, SEXP arg, unsigned int left)
{
PPinfo arginfo;
if (TYPEOF(arg) == LANGSXP) {
if (TYPEOF(CAR(arg)) == SYMSXP) {
if ((TYPEOF(SYMVALUE(CAR(arg))) == BUILTINSXP) ||
(TYPEOF(SYMVALUE(CAR(arg))) == SPECIALSXP)) {
arginfo = PPINFO(SYMVALUE(CAR(arg)));
switch(arginfo.kind) {
case PP_BINARY: /* Not all binary ops are binary! */
case PP_BINARY2:
switch(length(CDR(arg))) {
case 1:
if (!left)
return FALSE;
if (arginfo.precedence == PREC_SUM) /* binary +/- precedence upgraded as unary */
arginfo.precedence = PREC_SIGN;
case 2:
if (mainop.precedence == PREC_COMPARE &&
arginfo.precedence == PREC_COMPARE)
return TRUE; /* a < b < c is not legal syntax */
break;
default:
return FALSE;
}
case PP_SUBSET:
if (mainop.kind == PP_DOLLAR)
return FALSE;
/* fall through, don't break... */
case PP_ASSIGN:
case PP_ASSIGN2:
case PP_UNARY:
case PP_DOLLAR:
/* Same as other unary operators above */
if (arginfo.precedence == PREC_NOT && !left)
return FALSE;
if (mainop.precedence > arginfo.precedence
|| (mainop.precedence == arginfo.precedence && left == mainop.rightassoc)) {
return TRUE;
}
break;
case PP_FOR:
case PP_IF:
case PP_WHILE:
case PP_REPEAT:
return left == 1;
break;
default:
return FALSE;
}
} else if (isUserBinop(CAR(arg))) {
if (mainop.precedence > PREC_PERCENT
|| (mainop.precedence == PREC_PERCENT && left == mainop.rightassoc)) {
return TRUE;
}
}
}
}
else if ((TYPEOF(arg) == CPLXSXP) && (length(arg) == 1)) {
if (mainop.precedence > PREC_SUM
|| (mainop.precedence == PREC_SUM && left == mainop.rightassoc)) {
return TRUE;
}
}
return FALSE;
}
/* does the character() vector x contain one `NA_character_` or is all "",
* or if(isAtomic) does it have one "recursive" or "use.names" ? */
static Rboolean usable_nice_names(SEXP x, Rboolean isAtomic)
{
if(TYPEOF(x) == STRSXP) {
R_xlen_t i, n = xlength(x);
Rboolean all_0 = TRUE;
if(isAtomic) // c(*, recursive=, use.names=): cannot use these as nice_names
for (i = 0; i < n; i++) {
if (STRING_ELT(x, i) == NA_STRING
|| strcmp(CHAR(STRING_ELT(x, i)), "recursive") == 0
|| strcmp(CHAR(STRING_ELT(x, i)), "use.names") == 0)
return FALSE;
else if (all_0 && *CHAR(STRING_ELT(x, i))) /* length test */
all_0 = FALSE;
}
else
for (i = 0; i < n; i++) {
if (STRING_ELT(x, i) == NA_STRING)
return FALSE;
else if (all_0 && *CHAR(STRING_ELT(x, i))) /* length test */
all_0 = FALSE;
}
return !all_0;
}
return TRUE;
}
typedef enum { UNKNOWN = -1,
SIMPLE = 0,
OK_NAMES, // no structure(*); names written as (n1 = v1, ..)
STRUC_ATTR, // use structure(*, <attr> = *, ..) for non-names only
STRUC_NMS_A // use structure(*, <attr> = *, ..) for names, too
} attr_type;
#ifdef DEBUG_DEPARSE
static const char* attrT2char(attr_type typ) {
switch(typ) {
case UNKNOWN: return "UNKNOWN";
case SIMPLE: return "SIMPLE";
case OK_NAMES: return "OK_NAMES";
case STRUC_ATTR: return "STRUC_ATTR";
case STRUC_NMS_A: return "STRUC_NMS_A";
default: return "_unknown_ attr_type -- should *NOT* happen!";
}
}
# define ChTF(_logic_) (_logic_ ? "TRUE" : "FALSE")
#endif
/* Exact semantic of NICE_NAMES and SHOWATTRIBUTES i.e. "niceNames" and "showAttributes"
C| depCtrl | attr1() result
-| -----------+-----------------------------------------------------------------------------
1| NN && SA | STRUCT_ATTR + NN or STRUC_NMS_A (if NN are not "allowed")
2| !NN && SA | if(has attr) STRUC_NMS_A else "SIMPLE"
3| NN && !SA | OK_NAMES || SIMPLE if(!has_names)
4| !NN && !SA | SIMPLE
C| depCtrl : what should deparse(*, control = depCtrl) do ?
-| -----------+-----------------------------------------------------------------------------
1| NN && SA : all attributes(but srcref); names "NICE"ly (<nam> = <val>) if valid [no NA]
2| !NN && SA : all attributes( " " ) use structure(..) incl names but no _nice_ names
3| NN && !SA : no attributes but names, names nicely even when "wrong" (i.e. NA in names(.))
4| !NN && !SA : no attributes shown, not even names
*/
// is *only* called if (d->opts & SHOW_ATTR_OR_NMS) = d->opts & (SHOW_A | NICE_N)
static attr_type attr1(SEXP s, LocalParseData *d)
{
SEXP a = ATTRIB(s), nm = getAttrib(s, R_NamesSymbol);
attr_type attr = UNKNOWN;
Rboolean
nice_names = d->opts & NICE_NAMES,
show_attr = d->opts & SHOWATTRIBUTES,
has_names = !isNull(nm), ok_names;
#ifdef DEBUG_DEPARSE
REprintf(" attr1(): has_names = %s", ChTF(has_names));
#endif
if(has_names) {
// ok only if there's no NA_character_,.. in names() nor all """
ok_names = nice_names && usable_nice_names(nm, isVectorAtomic(s));
#ifdef DEBUG_DEPARSE
REprintf(", ok_names = %s", ChTF(ok_names));
#endif
if(!ok_names)
attr = show_attr ? STRUC_NMS_A :
/* nice_names */ OK_NAMES; // even when not ok
}
while(attr == UNKNOWN && !isNull(a)) {
if(has_names && TAG(a) == R_NamesSymbol) {
// also ok_names = TRUE
} else if(show_attr && TAG(a) != R_SrcrefSymbol) {
attr = STRUC_ATTR;
break;
}
// else
a = CDR(a);
}
if(attr == UNKNOWN)
attr = has_names ? OK_NAMES : SIMPLE;
if(attr >= STRUC_ATTR) {
print2buff("structure(", d);
} else if(has_names) { // attr <= OK_NAMES
}
#ifdef DEBUG_DEPARSE
REprintf(", return()ing %s\n", attrT2char(attr));
#endif
return attr;
}
static void attr2(SEXP s, LocalParseData *d, Rboolean not_names)
{
SEXP a = ATTRIB(s);
while(!isNull(a)) {
if(TAG(a) != R_SrcrefSymbol &&
!(TAG(a) == R_NamesSymbol && not_names)) {
print2buff(", ", d);
if(TAG(a) == R_DimSymbol) {
print2buff(".Dim", d);
}
else if(TAG(a) == R_DimNamesSymbol) {
print2buff(".Dimnames", d);
}
else if(TAG(a) == R_NamesSymbol) {
print2buff(".Names", d);
}
else if(TAG(a) == R_TspSymbol) {
print2buff(".Tsp", d);
}
else if(TAG(a) == R_LevelsSymbol) {
print2buff(".Label", d);
}
else {
/* TAG(a) might contain spaces etc */
const char *tag = CHAR(PRINTNAME(TAG(a)));
int d_opts_in = d->opts;
d->opts = SIMPLEDEPARSE; /* turn off quote()ing */
if(isValidName(tag))
deparse2buff(TAG(a), d);
else {
print2buff("\"", d);
deparse2buff(TAG(a), d);
print2buff("\"", d);
}
d->opts = d_opts_in;
}
print2buff(" = ", d);
Rboolean fnarg = d->fnarg;
d->fnarg = TRUE;
deparse2buff(CAR(a), d);
d->fnarg = fnarg;
}
a = CDR(a);
}
print2buff(")", d);
}
static const char *quotify(SEXP name, int quote)
{
const char *s = CHAR(name);
/* If a symbol is not a valid name, put it in quotes, escaping
* any quotes in the string itself */
if (isValidName(s) || *s == '\0') return s;
return EncodeString(name, 0, quote, Rprt_adj_none);
}
/* check for whether we need to parenthesize a caller. The unevaluated ones
are tricky:
We want
x$f(z)
x[n](z)
base::mean(x)
but
(f+g)(z)
(function(x) 1)(x)
etc.
*/
static Rboolean parenthesizeCaller(SEXP s)
{
SEXP op, sym;
if (TYPEOF(s) == LANGSXP) { /* unevaluated */
op = CAR(s);
if (TYPEOF(op) == SYMSXP) {
if (isUserBinop(op)) return TRUE; /* %foo% */
sym = SYMVALUE(op);
if (TYPEOF(sym) == BUILTINSXP
|| TYPEOF(sym) == SPECIALSXP) {
if (PPINFO(sym).precedence >= PREC_SUBSET
|| PPINFO(sym).kind == PP_FUNCALL
|| PPINFO(sym).kind == PP_PAREN
|| PPINFO(sym).kind == PP_CURLY) return FALSE; /* x$f(z) or x[n](z) or f(z) or (f) or {f} */
else return TRUE; /* (f+g)(z) etc. */
}
return FALSE; /* regular function call */
} else
return TRUE; /* something strange, like (1)(x) */
} else
return TYPEOF(s) == CLOSXP;
}
/* This is the recursive part of deparsing. */
#define SIMPLE_OPTS (~QUOTEEXPRESSIONS & ~SHOWATTRIBUTES & ~DELAYPROMISES)
/* keep KEEPINTEGER | USESOURCE | KEEPNA | S_COMPAT, also
WARNINCOMPLETE but that is not used below this point. */
#define SHOW_ATTR_OR_NMS (SHOWATTRIBUTES | NICE_NAMES)
static void deparse2buff(SEXP s, LocalParseData *d)
{
Rboolean lookahead = FALSE, lbreak = FALSE, fnarg = d->fnarg;
attr_type attr = STRUC_ATTR;
SEXP t;
int d_opts_in = d->opts, i, n;
d->fnarg = FALSE;
if (!d->active) return;
Rboolean hasS4_t = TYPEOF(s) == S4SXP;
if (IS_S4_OBJECT(s) || hasS4_t) {
d->isS4 = TRUE;
/* const void *vmax = vmaxget(); */
SEXP class = getAttrib(s, R_ClassSymbol),
cl_def = TYPEOF(class) == STRSXP ? STRING_ELT(class, 0) : R_NilValue;
if(TYPEOF(cl_def) == CHARSXP) { // regular S4 objects
print2buff("new(\"", d);
print2buff(translateChar(cl_def), d);
print2buff("\", ", d);
SEXP slotNms; // ---- slotNms := methods::.slotNames(s) ---------
// computed alternatively, slotNms := names(getClassDef(class)@slots) :
static SEXP R_getClassDef = NULL, R_slots = NULL, R_asS3 = NULL;
if(R_getClassDef == NULL)
R_getClassDef = findFun(install("getClassDef"), R_MethodsNamespace);
if(R_slots == NULL) R_slots = install("slots");
if(R_asS3 == NULL) R_asS3 = install("asS3");
SEXP e = PROTECT(lang2(R_getClassDef, class));
cl_def = PROTECT(eval(e, R_BaseEnv)); // correct env?
slotNms = // names( cl_def@slots ) :
getAttrib(R_do_slot(cl_def, R_slots), R_NamesSymbol);
UNPROTECT(2); // (e, cl_def)
int n;
Rboolean has_Data = FALSE;// does it have ".Data" slot?
if(TYPEOF(slotNms) == STRSXP && (n = LENGTH(slotNms))) {
PROTECT(slotNms);
SEXP slotlist = PROTECT(allocVector(VECSXP, n));
// := structure(lapply(slotNms, slot, object=s), names=slotNms)
for(int i=0; i < n; i++) {
SEXP slot_i = STRING_ELT(slotNms, i);
SET_VECTOR_ELT(slotlist, i, R_do_slot(s, installTrChar(slot_i)));
if(!hasS4_t && !has_Data)
has_Data = (strcmp(CHAR(slot_i), ".Data") == 0);
}
setAttrib(slotlist, R_NamesSymbol, slotNms);
vec2buff(slotlist, d, TRUE);
/*-----------------*/
UNPROTECT(2); // (slotNms, slotlist)
}
if(!hasS4_t && !has_Data) {
// may have *non*-slot contents, (i.e., not in .Data)
// ==> additionally deparse asS3(s) :
e = PROTECT(lang2(R_asS3, s)); // = asS3(s)
SEXP S3_s = PROTECT(eval(e, R_BaseEnv)); // correct env?
print2buff(", ", d);
deparse2buff(S3_s, d);
UNPROTECT(2); // (e, S3_s)
}
print2buff(")", d);
}
else { // exception: class is not CHARSXP
if(isNull(cl_def) && isNull(ATTRIB(s))) // special
print2buff("getClass(\"S4\")@prototype", d);
else { // irregular S4 ((does this ever trigger ??))
d->sourceable = FALSE;
print2buff("<S4 object of class ", d);
deparse2buff(class, d);
print2buff(">", d);
}
}
/* vmaxset(vmax); */
return;
} // if( S4 )
// non-S4 cases:
switch (TYPEOF(s)) {
case NILSXP:
print2buff("NULL", d);
break;
case SYMSXP: {
Rboolean
doquote = (d_opts_in & QUOTEEXPRESSIONS) && strlen(CHAR(PRINTNAME(s)));
if (doquote) {
attr = (d_opts_in & SHOW_ATTR_OR_NMS) ? attr1(s, d) : SIMPLE;
print2buff("quote(", d);
}
if (d_opts_in & S_COMPAT) {
print2buff(quotify(PRINTNAME(s), '"'), d);
} else if (d->backtick)
print2buff(quotify(PRINTNAME(s), '`'), d);
else
print2buff(CHAR(PRINTNAME(s)), d);
if (doquote) {
print2buff(")", d);
if(attr >= STRUC_ATTR) attr2(s, d, (attr == STRUC_ATTR));
}
break;
}
case CHARSXP:
{
const void *vmax = vmaxget();
const char *ts = translateChar(s);
#ifdef longstring_WARN
/* versions of R < 2.7.0 cannot parse strings longer than 8192 chars */
if(strlen(ts) >= 8192) d->longstring = TRUE;
#endif
print2buff(ts, d);
vmaxset(vmax);
break;
}
case SPECIALSXP:
case BUILTINSXP:
print2buff(".Primitive(\"", d);
print2buff(PRIMNAME(s), d);
print2buff("\")", d);
break;
case PROMSXP:
if(d->opts & DELAYPROMISES) {
d->sourceable = FALSE;
print2buff("<promise: ", d);
d->opts &= ~QUOTEEXPRESSIONS; /* don't want delay(quote()) */
deparse2buff(PREXPR(s), d);
d->opts = d_opts_in;
print2buff(">", d);
} else {
PROTECT(s = eval(s, R_EmptyEnv)); /* eval uses env of promise */
deparse2buff(s, d);
UNPROTECT(1);
}
break;
case CLOSXP:
attr = (d_opts_in & SHOW_ATTR_OR_NMS) ? attr1(s, d) : SIMPLE;
if ((d->opts & USESOURCE)
&& !isNull(t = getAttrib(s, R_SrcrefSymbol)))
src2buff1(t, d);
else {
/* We have established that we don't want to use the
source for this function */
d->opts &= SIMPLE_OPTS & ~USESOURCE;
print2buff("function (", d);
args2buff(FORMALS(s), 0, 1, d);
print2buff(") ", d);
writeline(d);
deparse2buff(BODY_EXPR(s), d);
d->opts = d_opts_in;
}
if(attr >= STRUC_ATTR) attr2(s, d, (attr == STRUC_ATTR));
break;
case ENVSXP:
d->sourceable = FALSE;
print2buff("<environment>", d);
break;