@@ -94,20 +94,20 @@ parse_transform_serialize <- function(text, transformers) {
94
94
return (" " )
95
95
}
96
96
transformed_pd <- apply_transformers(pd_nested , transformers )
97
- # TODO verify_roundtrip
98
97
flattened_pd <- post_visit(transformed_pd , list (extract_terminals )) %> %
99
98
enrich_terminals(transformers $ use_raw_indention ) %> %
100
99
apply_ref_indention() %> %
101
100
set_regex_indention(
102
101
pattern = transformers $ reindention $ regex_pattern ,
103
102
target_indention = transformers $ reindention $ indention ,
104
- comments_only = transformers $ reindention $ comments_only )
105
-
103
+ comments_only = transformers $ reindention $ comments_only
104
+ )
106
105
serialized_transformed_text <-
107
106
serialize_parse_data_flattened(flattened_pd , start_line = start_line )
107
+ verify_roundtrip(text , serialized_transformed_text , transformers )
108
108
serialized_transformed_text
109
- }
110
109
110
+ }
111
111
112
112
# ' Apply transformers to a parse table
113
113
# '
@@ -154,5 +154,43 @@ apply_transformers <- function(pd_nested, transformers) {
154
154
outer_indention_refs = NA
155
155
)
156
156
transformed_absolute_indent
157
+ }
157
158
159
+
160
+ # ' Verify the styling if possible
161
+ # '
162
+ # ' If scope was set to "line_breaks" or lower (compare [tidyverse_style()]),
163
+ # ' we can compare the expression before and after styling and return an error if
164
+ # ' it is not the same. Note that this method ignores comments and no
165
+ # ' verification can be conducted if scope > "line_breaks".
166
+ # ' @param old_text The initial expression in its character representation.
167
+ # ' @param new_text The styled expression in its character representation.
168
+ # ' @param transformers The list of transformer functions used for styling.
169
+ # ' Needed for reverse engineering the scope.
170
+ # ' @examples
171
+ # ' styler:::verify_roundtrip("a+1", "a + 1", tidyverse_style(scope = "line_breaks"))
172
+ # ' styler:::verify_roundtrip(
173
+ # ' "a+1",
174
+ # ' "a + 1 # comments are dropped",
175
+ # ' tidyverse_style(scope = "line_breaks")
176
+ # ' )
177
+ # ' \dontrun{
178
+ # ' styler:::verify_roundtrip("a+1", "b - 3", tidyverse_style(scope = "line_breaks"))
179
+ # ' }
180
+ verify_roundtrip <- function (old_text , new_text , transformers ) {
181
+ if (is.null(transformers $ token )) {
182
+ expressions_are_identical <- identical(
183
+ parse(text = old_text , keep.source = FALSE ),
184
+ parse(text = new_text , keep.source = FALSE )
185
+ )
186
+ if (! expressions_are_identical ) {
187
+ msg <- paste(
188
+ " The expression evaluated before the styling is not the same as the" ,
189
+ " expression after styling. This should not happen. Please file a" ,
190
+ " bug report on GitHub (https://github.com/r-lib/styler/issues)" ,
191
+ " using a reprex."
192
+ )
193
+ stop(msg , call. = FALSE )
194
+ }
195
+ }
158
196
}
0 commit comments