Move all command implementations into a single 'commands' directory.
[pspp] / src / language / commands / define.c
1 /* PSPP - a program for statistical analysis.
2    Copyright (C) 2021 Free Software Foundation, Inc.
3
4    This program is free software: you can redistribute it and/or modify
5    it under the terms of the GNU General Public License as published by
6    the Free Software Foundation, either version 3 of the License, or
7    (at your option) any later version.
8
9    This program is distributed in the hope that it will be useful,
10    but WITHOUT ANY WARRANTY; without even the implied warranty of
11    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12    GNU General Public License for more details.
13
14    You should have received a copy of the GNU General Public License
15    along with this program.  If not, see <http://www.gnu.org/licenses/>. */
16
17 #include <config.h>
18
19 #include <limits.h>
20
21 #include "language/command.h"
22 #include "language/lexer/lexer.h"
23 #include "language/lexer/macro.h"
24 #include "language/lexer/scan.h"
25 #include "language/lexer/token.h"
26 #include "libpspp/intern.h"
27 #include "libpspp/message.h"
28
29 #include "gl/xalloc.h"
30
31 #include "gettext.h"
32 #define _(msgid) gettext (msgid)
33
34 static bool
35 match_macro_id (struct lexer *lexer, const char *keyword)
36 {
37   if (keyword[0] != '!')
38     return lex_match_id (lexer, keyword);
39   else if (lex_token (lexer) == T_MACRO_ID
40            && lex_id_match_n (ss_cstr (keyword), lex_tokss (lexer), 4))
41     {
42       lex_get (lexer);
43       return true;
44     }
45   else
46     return false;
47 }
48
49 /* Obtains a quoted string from LEXER and then tokenizes the quoted string's
50    content to obtain a single TOKEN.  Returns true if successful, false
51    otherwise.  The caller takes ownership of TOKEN on success, otherwise TOKEN
52    is indeterminate. */
53 static bool
54 parse_quoted_token (struct lexer *lexer, struct token *token)
55 {
56   if (!lex_force_string (lexer))
57     return false;
58
59   struct substring s = lex_tokss (lexer);
60   struct string_lexer slex;
61   string_lexer_init (&slex, s.string, s.length, SEG_MODE_INTERACTIVE, true);
62   struct token another_token = { .type = T_STOP };
63   if (string_lexer_next (&slex, token) != SLR_TOKEN
64       || string_lexer_next (&slex, &another_token) != SLR_END)
65     {
66       token_uninit (token);
67       token_uninit (&another_token);
68       lex_error (lexer, _("String must contain exactly one token."));
69       return false;
70     }
71   lex_get (lexer);
72   return true;
73 }
74
75 static bool
76 dup_arg_type (struct lexer *lexer, bool *saw_arg_type)
77 {
78   if (*saw_arg_type)
79     {
80       lex_next_error (lexer, -1, -1,
81                       _("Only one of !TOKENS, !CHAREND, !ENCLOSE, or "
82                         "!CMDEND is allowed."));
83       return false;
84     }
85   else
86     {
87       *saw_arg_type = true;
88       return true;
89     }
90 }
91
92 static bool
93 parse_macro_body (struct lexer *lexer, struct macro_tokens *mts)
94 {
95   *mts = (struct macro_tokens) { .n = 0 };
96   struct string body = DS_EMPTY_INITIALIZER;
97   struct msg_point start = lex_ofs_start_point (lexer, lex_ofs (lexer));
98   while (!match_macro_id (lexer, "!ENDDEFINE"))
99     {
100       if (lex_token (lexer) != T_STRING)
101         {
102           lex_error (lexer,
103                      _("Syntax error expecting macro body or !ENDDEFINE."));
104           ds_destroy (&body);
105           return false;
106         }
107
108       ds_put_substring (&body, lex_tokss (lexer));
109       ds_put_byte (&body, '\n');
110       lex_get (lexer);
111     }
112
113   struct segmenter segmenter = segmenter_init (lex_get_syntax_mode (lexer),
114                                                true);
115   struct substring p = body.ss;
116   bool ok = true;
117   while (p.length > 0)
118     {
119       enum segment_type type;
120       int seg_len = segmenter_push (&segmenter, p.string,
121                                     p.length, true, &type);
122       assert (seg_len >= 0);
123
124       struct macro_token mt = {
125         .token = { .type = T_STOP },
126         .syntax = ss_head (p, seg_len),
127       };
128       enum tokenize_result result
129         = token_from_segment (type, mt.syntax, &mt.token);
130       ss_advance (&p, seg_len);
131
132       switch (result)
133         {
134         case TOKENIZE_EMPTY:
135           break;
136
137         case TOKENIZE_TOKEN:
138           macro_tokens_add (mts, &mt);
139           break;
140
141         case TOKENIZE_ERROR:
142           {
143             size_t start_offset = mt.syntax.string - body.ss.string;
144             size_t end_offset = start_offset + (mt.syntax.length ? mt.syntax.length - 1 : 0);
145
146             const struct msg_location loc = {
147               .file_name = intern_new_if_nonnull (lex_get_file_name (lexer)),
148               .start = msg_point_advance (start, ss_buffer (body.ss.string, start_offset)),
149               .end = msg_point_advance (start, ss_buffer (body.ss.string, end_offset)),
150               .src = CONST_CAST (struct lex_source *, lex_source (lexer)),
151             };
152             msg_at (SE, &loc, "%s", mt.token.string.string);
153             intern_unref (loc.file_name);
154
155             ok = false;
156           }
157           break;
158         }
159
160       token_uninit (&mt.token);
161     }
162   ds_destroy (&body);
163   return ok;
164 }
165
166 int
167 cmd_define (struct lexer *lexer, struct dataset *ds UNUSED)
168 {
169   /* Parse macro name.
170
171      The macro name is a T_STRING token, even though it's an identifier,
172      because that's the way that the segmenter prevents it from getting
173      macro-expanded. */
174   if (lex_token (lexer) != T_STRING)
175     {
176       lex_error (lexer, _("Syntax error expecting identifier."));
177       return CMD_FAILURE;
178     }
179   const char *name = lex_tokcstr (lexer);
180   if (!id_is_plausible (name + (name[0] == '!')))
181     {
182       lex_error (lexer, _("Syntax error expecting identifier."));
183       return CMD_FAILURE;
184     }
185
186   struct macro *m = xmalloc (sizeof *m);
187   *m = (struct macro) { .name = xstrdup (name) };
188   struct msg_point macro_start = lex_ofs_start_point (lexer, lex_ofs (lexer));
189   lex_get (lexer);
190
191   if (!lex_force_match (lexer, T_LPAREN))
192     goto error;
193
194   size_t allocated_params = 0;
195   int keyword_ofs = 0;
196   while (!lex_match (lexer, T_RPAREN))
197     {
198       if (m->n_params >= allocated_params)
199         m->params = x2nrealloc (m->params, &allocated_params,
200                                 sizeof *m->params);
201
202       size_t param_index = m->n_params++;
203       struct macro_param *p = &m->params[param_index];
204       *p = (struct macro_param) { .expand_arg = true };
205
206       /* Parse parameter name. */
207       if (match_macro_id (lexer, "!POSITIONAL"))
208         {
209           if (param_index > 0 && !m->params[param_index - 1].positional)
210             {
211               lex_next_error (lexer, -1, -1,
212                               _("Positional parameters must precede "
213                                 "keyword parameters."));
214               lex_ofs_msg (lexer, SN, keyword_ofs, keyword_ofs,
215                            _("Here is a previous keyword parameter."));
216               goto error;
217             }
218
219           p->positional = true;
220           p->name = xasprintf ("!%zu", param_index + 1);
221         }
222       else
223         {
224           if (keyword_ofs == 0)
225             keyword_ofs = lex_ofs (lexer);
226           if (lex_token (lexer) == T_MACRO_ID)
227             {
228               lex_error (lexer, _("Keyword macro parameter must be named in "
229                                   "definition without \"!\" prefix."));
230               goto error;
231             }
232           if (!lex_force_id (lexer))
233             goto error;
234
235           if (is_macro_keyword (lex_tokss (lexer)))
236             {
237               lex_error (lexer, _("Cannot use macro keyword \"%s\" "
238                                   "as an argument name."),
239                          lex_tokcstr (lexer));
240               goto error;
241             }
242
243           p->positional = false;
244           p->name = xasprintf ("!%s", lex_tokcstr (lexer));
245           lex_get (lexer);
246         }
247       lex_match (lexer, T_EQUALS);
248
249       bool saw_default = false;
250       bool saw_arg_type = false;
251       for (;;)
252         {
253           if (match_macro_id (lexer, "!DEFAULT"))
254             {
255               if (saw_default)
256                 {
257                   lex_next_error (
258                     lexer, -1, -1,
259                     _("!DEFAULT is allowed only once per argument."));
260                   goto error;
261                 }
262               saw_default = true;
263
264               if (!lex_force_match (lexer, T_LPAREN))
265                 goto error;
266
267               /* XXX Should this handle balanced inner parentheses? */
268               while (!lex_match (lexer, T_RPAREN))
269                 {
270                   if (lex_token (lexer) == T_ENDCMD)
271                     {
272                       lex_error_expecting (lexer, ")");
273                       goto error;
274                     }
275                   char *syntax = lex_next_representation (lexer, 0, 0);
276                   const struct macro_token mt = {
277                     .token = *lex_next (lexer, 0),
278                     .syntax = ss_cstr (syntax),
279                   };
280                   macro_tokens_add (&p->def, &mt);
281                   free (syntax);
282
283                   lex_get (lexer);
284                 }
285             }
286           else if (match_macro_id (lexer, "!NOEXPAND"))
287             p->expand_arg = false;
288           else if (match_macro_id (lexer, "!TOKENS"))
289             {
290               if (!dup_arg_type (lexer, &saw_arg_type)
291                   || !lex_force_match (lexer, T_LPAREN)
292                   || !lex_force_int_range (lexer, "!TOKENS", 1, INT_MAX))
293                 goto error;
294               p->arg_type = ARG_N_TOKENS;
295               p->n_tokens = lex_integer (lexer);
296               lex_get (lexer);
297               if (!lex_force_match (lexer, T_RPAREN))
298                 goto error;
299             }
300           else if (match_macro_id (lexer, "!CHAREND"))
301             {
302               if (!dup_arg_type (lexer, &saw_arg_type))
303                 goto error;
304
305               p->arg_type = ARG_CHAREND;
306
307               if (!lex_force_match (lexer, T_LPAREN)
308                   || !parse_quoted_token (lexer, &p->end)
309                   || !lex_force_match (lexer, T_RPAREN))
310                 goto error;
311             }
312           else if (match_macro_id (lexer, "!ENCLOSE"))
313             {
314               if (!dup_arg_type (lexer, &saw_arg_type))
315                 goto error;
316
317               p->arg_type = ARG_ENCLOSE;
318
319               if (!lex_force_match (lexer, T_LPAREN)
320                   || !parse_quoted_token (lexer, &p->start)
321                   || !lex_force_match (lexer, T_COMMA)
322                   || !parse_quoted_token (lexer, &p->end)
323                   || !lex_force_match (lexer, T_RPAREN))
324                 goto error;
325             }
326           else if (match_macro_id (lexer, "!CMDEND"))
327             {
328               if (!dup_arg_type (lexer, &saw_arg_type))
329                 goto error;
330
331               p->arg_type = ARG_CMDEND;
332             }
333           else
334             break;
335         }
336       if (!saw_arg_type)
337         {
338           lex_error_expecting (lexer, "!TOKENS", "!CHAREND", "!ENCLOSE",
339                                "!CMDEND");
340           goto error;
341         }
342
343       if (lex_token (lexer) != T_RPAREN && !lex_force_match (lexer, T_SLASH))
344         goto error;
345     }
346
347   if (!parse_macro_body (lexer, &m->body))
348     goto error;
349
350   struct msg_point macro_end = lex_ofs_end_point (lexer, lex_ofs (lexer) - 1);
351   m->location = xmalloc (sizeof *m->location);
352   *m->location = (struct msg_location) {
353     .file_name = intern_new_if_nonnull (lex_get_file_name (lexer)),
354     .start = { .line = macro_start.line },
355     .end = { .line = macro_end.line },
356   };
357
358   lex_define_macro (lexer, m);
359
360   return CMD_SUCCESS;
361
362 error:
363   macro_destroy (m);
364   return CMD_FAILURE;
365 }
366
367 int
368 cmd_debug_expand (struct lexer *lexer, struct dataset *ds UNUSED)
369 {
370   settings_set_mprint (true);
371
372   while (lex_token (lexer) != T_STOP)
373     {
374       if (!lex_next_is_from_macro (lexer, 0) && lex_token (lexer) != T_ENDCMD)
375         {
376           char *rep = lex_next_representation (lexer, 0, 0);
377           msg (MN, "unexpanded token \"%s\"", rep);
378           free (rep);
379         }
380       lex_get (lexer);
381     }
382   return CMD_SUCCESS;
383 }