blob: a07f4295a6f949b53594f89695e79b23a9a22870 [file] [log] [blame]
David Reissea2cba82009-03-30 21:35:00 +00001/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
Mark Sleee9ce01c2007-05-16 02:29:53 +000019
Mark Slee31985722006-05-24 21:45:31 +000020/**
21 * thrift - a lightweight cross-language rpc/serialization tool
22 *
23 * This file contains the main compiler engine for Thrift, which invokes the
24 * scanner/parser to build the thrift object tree. The interface generation
Mark Sleef5377b32006-10-10 01:42:59 +000025 * code for each language lives in a file by the language name under the
26 * generate/ folder, and all parse structures live in parse/
Mark Slee31985722006-05-24 21:45:31 +000027 *
Mark Slee31985722006-05-24 21:45:31 +000028 */
29
David Reissf10984b2008-03-27 21:39:52 +000030#include <cassert>
Mark Slee31985722006-05-24 21:45:31 +000031#include <stdlib.h>
32#include <stdio.h>
33#include <stdarg.h>
David Reiss5ad12602010-08-31 16:51:30 +000034#include <time.h>
Mark Slee31985722006-05-24 21:45:31 +000035#include <string>
David Reiss739cbe22008-04-15 05:44:00 +000036#include <algorithm>
Mark Sleef0712dc2006-10-25 19:03:57 +000037#include <sys/types.h>
38#include <sys/stat.h>
dweatherford65b70752007-10-31 02:18:14 +000039#include <errno.h>
David Reissab55ed52008-06-11 01:17:00 +000040#include <limits.h>
Mark Slee31985722006-05-24 21:45:31 +000041
Ben Craige9576752013-10-11 08:19:16 -050042#ifdef _WIN32
Konrad Grochowski16a23a62014-11-13 15:33:38 +010043#include <windows.h> /* for GetFullPathName */
David Reiss204420f2008-01-11 20:59:03 +000044#endif
45
Mark Sleef0712dc2006-10-25 19:03:57 +000046// Careful: must include globals first for extern definitions
dtmuller052abc32016-07-26 11:58:28 +020047#include "thrift/common.h"
48#include "thrift/globals.h"
Mark Slee31985722006-05-24 21:45:31 +000049
dtmuller052abc32016-07-26 11:58:28 +020050#include "thrift/platform.h"
51#include "thrift/main.h"
52#include "thrift/parse/t_program.h"
53#include "thrift/parse/t_scope.h"
54#include "thrift/generate/t_generator.h"
55#include "thrift/audit/t_audit.h"
Mark Slee31985722006-05-24 21:45:31 +000056
dtmuller052abc32016-07-26 11:58:28 +020057#include "thrift/version.h"
David Reissdd08f6d2008-06-30 20:24:24 +000058
Mark Slee31985722006-05-24 21:45:31 +000059using namespace std;
60
Mark Sleef5377b32006-10-10 01:42:59 +000061/**
62 * Global program tree
63 */
Mark Slee31985722006-05-24 21:45:31 +000064t_program* g_program;
65
Mark Sleef5377b32006-10-10 01:42:59 +000066/**
Mark Sleef0712dc2006-10-25 19:03:57 +000067 * Global scope
68 */
69t_scope* g_scope;
70
71/**
72 * Parent scope to also parse types
73 */
74t_scope* g_parent_scope;
75
76/**
77 * Prefix for putting types in parent scope
78 */
79string g_parent_prefix;
80
81/**
82 * Parsing pass
83 */
84PARSE_MODE g_parse_mode;
85
86/**
87 * Current directory of file being parsed
88 */
89string g_curdir;
90
91/**
92 * Current file being parsed
93 */
94string g_curpath;
95
96/**
Martin Kraemer32c66e12006-11-09 00:06:36 +000097 * Search path for inclusions
98 */
Mark Slee2329a832006-11-09 00:23:30 +000099vector<string> g_incl_searchpath;
Martin Kraemer32c66e12006-11-09 00:06:36 +0000100
101/**
Mark Sleef5377b32006-10-10 01:42:59 +0000102 * Global debug state
103 */
Mark Slee31985722006-05-24 21:45:31 +0000104int g_debug = 0;
105
Mark Sleef5377b32006-10-10 01:42:59 +0000106/**
Bryan Duxburya145b4d2009-04-03 17:29:25 +0000107 * Strictness level
108 */
109int g_strict = 127;
110
111/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000112 * Warning level
113 */
114int g_warn = 1;
115
116/**
117 * Verbose output
118 */
119int g_verbose = 0;
120
121/**
Mark Sleef5377b32006-10-10 01:42:59 +0000122 * Global time string
123 */
Mark Slee31985722006-05-24 21:45:31 +0000124char* g_time_str;
125
Mark Slee31985722006-05-24 21:45:31 +0000126/**
David Reisscbd4bac2007-08-14 17:12:33 +0000127 * The last parsed doctext comment.
128 */
129char* g_doctext;
130
131/**
Jens Geyere8379b52014-01-25 00:59:45 +0100132 * The First doctext comment
133 */
134char* g_program_doctext_candidate;
Jens Geyere8379b52014-01-25 00:59:45 +0100135
David Reisscbd4bac2007-08-14 17:12:33 +0000136/**
Bryan Duxburyc7206a42011-08-17 23:17:04 +0000137 * Whether or not negative field keys are accepted.
138 */
139int g_allow_neg_field_keys;
140
141/**
Roger Meier887ff752011-08-19 11:25:39 +0000142 * Whether or not 64-bit constants will generate a warning.
143 */
144int g_allow_64bit_consts = 0;
145
146/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000147 * Flags to control code generation
148 */
Mark Sleef0712dc2006-10-25 19:03:57 +0000149bool gen_recurse = false;
150
151/**
Ben Craig262cfb42015-07-08 20:37:15 -0500152 * Flags to control thrift audit
153 */
154bool g_audit = false;
155
156/**
157 * Flag to control return status
158 */
159bool g_return_failure = false;
160bool g_audit_fatal = true;
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +0900161bool g_generator_failure = false;
Ben Craig262cfb42015-07-08 20:37:15 -0500162
163/**
Ben Craige9576752013-10-11 08:19:16 -0500164 * Win32 doesn't have realpath, so use fallback implementation in that case,
David Reiss204420f2008-01-11 20:59:03 +0000165 * otherwise this just calls through to realpath
166 */
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100167char* saferealpath(const char* path, char* resolved_path) {
Ben Craige9576752013-10-11 08:19:16 -0500168#ifdef _WIN32
David Reiss204420f2008-01-11 20:59:03 +0000169 char buf[MAX_PATH];
170 char* basename;
James E. King III17355422019-01-11 23:06:08 -0500171 DWORD len = GetFullPathNameA(path, MAX_PATH, buf, &basename);
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100172 if (len == 0 || len > MAX_PATH - 1) {
David Reiss204420f2008-01-11 20:59:03 +0000173 strcpy(resolved_path, path);
174 } else {
David Reiss204420f2008-01-11 20:59:03 +0000175 strcpy(resolved_path, buf);
176 }
Bryan Duxbury0137af62010-04-22 21:21:46 +0000177
178 // Replace backslashes with forward slashes so the
179 // rest of the code behaves correctly.
180 size_t resolved_len = strlen(resolved_path);
181 for (size_t i = 0; i < resolved_len; i++) {
182 if (resolved_path[i] == '\\') {
183 resolved_path[i] = '/';
184 }
185 }
David Reiss204420f2008-01-11 20:59:03 +0000186 return resolved_path;
187#else
188 return realpath(path, resolved_path);
189#endif
190}
191
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100192bool check_is_directory(const char* dir_name) {
Ben Craige9576752013-10-11 08:19:16 -0500193#ifdef _WIN32
Roger Meier061d4a22012-10-07 11:51:00 +0000194 DWORD attributes = ::GetFileAttributesA(dir_name);
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100195 if (attributes == INVALID_FILE_ATTRIBUTES) {
196 fprintf(stderr,
197 "Output directory %s is unusable: GetLastError() = %ld\n",
198 dir_name,
199 GetLastError());
Roger Meier061d4a22012-10-07 11:51:00 +0000200 return false;
201 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100202 if ((attributes & FILE_ATTRIBUTE_DIRECTORY) != FILE_ATTRIBUTE_DIRECTORY) {
Roger Meier061d4a22012-10-07 11:51:00 +0000203 fprintf(stderr, "Output directory %s exists but is not a directory\n", dir_name);
204 return false;
205 }
206 return true;
207#else
208 struct stat sb;
209 if (stat(dir_name, &sb) < 0) {
210 fprintf(stderr, "Output directory %s is unusable: %s\n", dir_name, strerror(errno));
211 return false;
212 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100213 if (!S_ISDIR(sb.st_mode)) {
Roger Meier061d4a22012-10-07 11:51:00 +0000214 fprintf(stderr, "Output directory %s exists but is not a directory\n", dir_name);
215 return false;
216 }
217 return true;
218#endif
219}
David Reiss204420f2008-01-11 20:59:03 +0000220
221/**
Mark Slee31985722006-05-24 21:45:31 +0000222 * Report an error to the user. This is called yyerror for historical
223 * reasons (lex and yacc expect the error reporting routine to be called
224 * this). Call this function to report any errors to the user.
225 * yyerror takes printf style arguments.
226 *
227 * @param fmt C format string followed by additional arguments
228 */
David Reiss0babe402008-06-10 22:56:12 +0000229void yyerror(const char* fmt, ...) {
Mark Slee31985722006-05-24 21:45:31 +0000230 va_list args;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100231 fprintf(stderr, "[ERROR:%s:%d] (last token was '%s')\n", g_curpath.c_str(), yylineno, yytext);
Mark Slee31985722006-05-24 21:45:31 +0000232
233 va_start(args, fmt);
234 vfprintf(stderr, fmt, args);
235 va_end(args);
236
237 fprintf(stderr, "\n");
238}
239
240/**
241 * Prints a debug message from the parser.
242 *
243 * @param fmt C format string followed by additional arguments
244 */
David Reiss0babe402008-06-10 22:56:12 +0000245void pdebug(const char* fmt, ...) {
Mark Slee31985722006-05-24 21:45:31 +0000246 if (g_debug == 0) {
247 return;
248 }
249 va_list args;
Mark Slee30152872006-11-28 01:24:07 +0000250 printf("[PARSE:%d] ", yylineno);
Mark Sleef0712dc2006-10-25 19:03:57 +0000251 va_start(args, fmt);
252 vprintf(fmt, args);
253 va_end(args);
254 printf("\n");
255}
256
257/**
258 * Prints a verbose output mode message
259 *
260 * @param fmt C format string followed by additional arguments
261 */
David Reiss0babe402008-06-10 22:56:12 +0000262void pverbose(const char* fmt, ...) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000263 if (g_verbose == 0) {
264 return;
265 }
266 va_list args;
267 va_start(args, fmt);
268 vprintf(fmt, args);
269 va_end(args);
270}
271
272/**
273 * Prints a warning message
274 *
275 * @param fmt C format string followed by additional arguments
276 */
David Reiss0babe402008-06-10 22:56:12 +0000277void pwarning(int level, const char* fmt, ...) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000278 if (g_warn < level) {
279 return;
280 }
281 va_list args;
282 printf("[WARNING:%s:%d] ", g_curpath.c_str(), yylineno);
Mark Slee31985722006-05-24 21:45:31 +0000283 va_start(args, fmt);
284 vprintf(fmt, args);
285 va_end(args);
286 printf("\n");
287}
288
289/**
290 * Prints a failure message and exits
291 *
292 * @param fmt C format string followed by additional arguments
293 */
Mark Slee30152872006-11-28 01:24:07 +0000294void failure(const char* fmt, ...) {
Mark Slee2c44d202007-05-16 02:18:07 +0000295 va_list args;
Mark Sleef0712dc2006-10-25 19:03:57 +0000296 fprintf(stderr, "[FAILURE:%s:%d] ", g_curpath.c_str(), yylineno);
Mark Slee31985722006-05-24 21:45:31 +0000297 va_start(args, fmt);
298 vfprintf(stderr, fmt, args);
299 va_end(args);
300 printf("\n");
301 exit(1);
302}
303
304/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000305 * Converts a string filename into a thrift program name
306 */
307string program_name(string filename) {
308 string::size_type slash = filename.rfind("/");
309 if (slash != string::npos) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100310 filename = filename.substr(slash + 1);
Mark Sleef0712dc2006-10-25 19:03:57 +0000311 }
312 string::size_type dot = filename.rfind(".");
313 if (dot != string::npos) {
314 filename = filename.substr(0, dot);
315 }
316 return filename;
317}
318
319/**
320 * Gets the directory path of a filename
321 */
322string directory_name(string filename) {
323 string::size_type slash = filename.rfind("/");
324 // No slash, just use the current directory
325 if (slash == string::npos) {
326 return ".";
327 }
328 return filename.substr(0, slash);
329}
330
331/**
332 * Finds the appropriate file path for the given filename
333 */
334string include_file(string filename) {
335 // Absolute path? Just try that
Martin Kraemer32c66e12006-11-09 00:06:36 +0000336 if (filename[0] == '/') {
337 // Realpath!
Ben Craige9576752013-10-11 08:19:16 -0500338 char rp[THRIFT_PATH_MAX];
Nobuaki Sukegawad479e232016-02-28 11:28:19 +0900339 // cppcheck-suppress uninitvar
zeshuai00726681fb2020-06-03 17:24:38 +0800340 if (saferealpath(filename.c_str(), rp) == nullptr) {
Martin Kraemer32c66e12006-11-09 00:06:36 +0000341 pwarning(0, "Cannot open include file %s\n", filename.c_str());
342 return std::string();
343 }
Mark Slee2c44d202007-05-16 02:18:07 +0000344
345 // Stat this file
Martin Kraemer32c66e12006-11-09 00:06:36 +0000346 struct stat finfo;
347 if (stat(rp, &finfo) == 0) {
348 return rp;
349 }
350 } else { // relative path, start searching
351 // new search path with current dir global
352 vector<string> sp = g_incl_searchpath;
353 sp.insert(sp.begin(), g_curdir);
Mark Slee2c44d202007-05-16 02:18:07 +0000354
Martin Kraemer32c66e12006-11-09 00:06:36 +0000355 // iterate through paths
356 vector<string>::iterator it;
357 for (it = sp.begin(); it != sp.end(); it++) {
358 string sfilename = *(it) + "/" + filename;
Mark Slee2c44d202007-05-16 02:18:07 +0000359
Martin Kraemer32c66e12006-11-09 00:06:36 +0000360 // Realpath!
Ben Craige9576752013-10-11 08:19:16 -0500361 char rp[THRIFT_PATH_MAX];
Nobuaki Sukegawad479e232016-02-28 11:28:19 +0900362 // cppcheck-suppress uninitvar
zeshuai00726681fb2020-06-03 17:24:38 +0800363 if (saferealpath(sfilename.c_str(), rp) == nullptr) {
Martin Kraemer32c66e12006-11-09 00:06:36 +0000364 continue;
365 }
Mark Slee2c44d202007-05-16 02:18:07 +0000366
Martin Kraemer32c66e12006-11-09 00:06:36 +0000367 // Stat this files
368 struct stat finfo;
369 if (stat(rp, &finfo) == 0) {
370 return rp;
371 }
372 }
Mark Sleef0712dc2006-10-25 19:03:57 +0000373 }
Mark Slee2c44d202007-05-16 02:18:07 +0000374
Mark Sleef0712dc2006-10-25 19:03:57 +0000375 // Uh oh
376 pwarning(0, "Could not find include file %s\n", filename.c_str());
377 return std::string();
378}
379
380/**
David Reisscbd4bac2007-08-14 17:12:33 +0000381 * Clears any previously stored doctext string.
382 * Also prints a warning if we are discarding information.
383 */
384void clear_doctext() {
zeshuai00726681fb2020-06-03 17:24:38 +0800385 if (g_doctext != nullptr) {
David Reisscbd4bac2007-08-14 17:12:33 +0000386 pwarning(2, "Uncaptured doctext at on line %d.", g_doctext_lineno);
387 }
388 free(g_doctext);
zeshuai00726681fb2020-06-03 17:24:38 +0800389 g_doctext = nullptr;
David Reisscbd4bac2007-08-14 17:12:33 +0000390}
391
392/**
Jens Geyere8379b52014-01-25 00:59:45 +0100393 * Reset program doctext information after processing a file
394 */
395void reset_program_doctext_info() {
zeshuai00726681fb2020-06-03 17:24:38 +0800396 if (g_program_doctext_candidate != nullptr) {
Jens Geyere8379b52014-01-25 00:59:45 +0100397 free(g_program_doctext_candidate);
zeshuai00726681fb2020-06-03 17:24:38 +0800398 g_program_doctext_candidate = nullptr;
Jens Geyere8379b52014-01-25 00:59:45 +0100399 }
400 g_program_doctext_lineno = 0;
401 g_program_doctext_status = INVALID;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100402 pdebug("%s", "program doctext set to INVALID");
Jens Geyere8379b52014-01-25 00:59:45 +0100403}
404
405/**
406 * We are sure the program doctext candidate is really the program doctext.
407 */
408void declare_valid_program_doctext() {
zeshuai00726681fb2020-06-03 17:24:38 +0800409 if ((g_program_doctext_candidate != nullptr) && (g_program_doctext_status == STILL_CANDIDATE)) {
Roger Meier4f4b15b2014-11-05 16:51:04 +0100410 g_program_doctext_status = ABSOLUTELY_SURE;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100411 pdebug("%s", "program doctext set to ABSOLUTELY_SURE");
Jens Geyer813749d2014-01-31 23:42:57 +0100412 } else {
Roger Meier4f4b15b2014-11-05 16:51:04 +0100413 g_program_doctext_status = NO_PROGRAM_DOCTEXT;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100414 pdebug("%s", "program doctext set to NO_PROGRAM_DOCTEXT");
Jens Geyere8379b52014-01-25 00:59:45 +0100415 }
416}
417
418/**
David Reiss1ac05802007-07-30 22:00:27 +0000419 * Cleans up text commonly found in doxygen-like comments
420 *
421 * Warning: if you mix tabs and spaces in a non-uniform way,
422 * you will get what you deserve.
423 */
424char* clean_up_doctext(char* doctext) {
425 // Convert to C++ string, and remove Windows's carriage returns.
426 string docstring = doctext;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100427 docstring.erase(remove(docstring.begin(), docstring.end(), '\r'), docstring.end());
David Reiss1ac05802007-07-30 22:00:27 +0000428
429 // Separate into lines.
430 vector<string> lines;
431 string::size_type pos = string::npos;
432 string::size_type last;
433 while (true) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100434 last = (pos == string::npos) ? 0 : pos + 1;
David Reiss1ac05802007-07-30 22:00:27 +0000435 pos = docstring.find('\n', last);
436 if (pos == string::npos) {
437 // First bit of cleaning. If the last line is only whitespace, drop it.
438 string::size_type nonwhite = docstring.find_first_not_of(" \t", last);
439 if (nonwhite != string::npos) {
440 lines.push_back(docstring.substr(last));
441 }
442 break;
443 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100444 lines.push_back(docstring.substr(last, pos - last));
David Reiss1ac05802007-07-30 22:00:27 +0000445 }
446
447 // A very profound docstring.
448 if (lines.empty()) {
zeshuai00726681fb2020-06-03 17:24:38 +0800449 return nullptr;
David Reiss1ac05802007-07-30 22:00:27 +0000450 }
451
452 // Clear leading whitespace from the first line.
453 pos = lines.front().find_first_not_of(" \t");
454 lines.front().erase(0, pos);
455
456 // If every nonblank line after the first has the same number of spaces/tabs,
457 // then a star, remove them.
458 bool have_prefix = true;
459 bool found_prefix = false;
460 string::size_type prefix_len = 0;
461 vector<string>::iterator l_iter;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100462 for (l_iter = lines.begin() + 1; l_iter != lines.end(); ++l_iter) {
David Reiss1ac05802007-07-30 22:00:27 +0000463 if (l_iter->empty()) {
464 continue;
465 }
466
467 pos = l_iter->find_first_not_of(" \t");
468 if (!found_prefix) {
469 if (pos != string::npos) {
470 if (l_iter->at(pos) == '*') {
471 found_prefix = true;
472 prefix_len = pos;
473 } else {
474 have_prefix = false;
475 break;
476 }
477 } else {
478 // Whitespace-only line. Truncate it.
479 l_iter->clear();
480 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100481 } else if (l_iter->size() > pos && l_iter->at(pos) == '*' && pos == prefix_len) {
David Reiss1ac05802007-07-30 22:00:27 +0000482 // Business as usual.
483 } else if (pos == string::npos) {
484 // Whitespace-only line. Let's truncate it for them.
485 l_iter->clear();
486 } else {
487 // The pattern has been broken.
488 have_prefix = false;
489 break;
490 }
491 }
492
493 // If our prefix survived, delete it from every line.
494 if (have_prefix) {
495 // Get the star too.
496 prefix_len++;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100497 for (l_iter = lines.begin() + 1; l_iter != lines.end(); ++l_iter) {
David Reiss1ac05802007-07-30 22:00:27 +0000498 l_iter->erase(0, prefix_len);
499 }
500 }
501
502 // Now delete the minimum amount of leading whitespace from each line.
503 prefix_len = string::npos;
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100504 for (l_iter = lines.begin() + 1; l_iter != lines.end(); ++l_iter) {
David Reiss1ac05802007-07-30 22:00:27 +0000505 if (l_iter->empty()) {
506 continue;
507 }
508 pos = l_iter->find_first_not_of(" \t");
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100509 if (pos != string::npos && (prefix_len == string::npos || pos < prefix_len)) {
David Reiss1ac05802007-07-30 22:00:27 +0000510 prefix_len = pos;
511 }
512 }
513
514 // If our prefix survived, delete it from every line.
515 if (prefix_len != string::npos) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100516 for (l_iter = lines.begin() + 1; l_iter != lines.end(); ++l_iter) {
David Reiss1ac05802007-07-30 22:00:27 +0000517 l_iter->erase(0, prefix_len);
518 }
519 }
520
521 // Remove trailing whitespace from every line.
522 for (l_iter = lines.begin(); l_iter != lines.end(); ++l_iter) {
523 pos = l_iter->find_last_not_of(" \t");
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100524 if (pos != string::npos && pos != l_iter->length() - 1) {
525 l_iter->erase(pos + 1);
David Reiss1ac05802007-07-30 22:00:27 +0000526 }
527 }
528
529 // If the first line is empty, remove it.
530 // Don't do this earlier because a lot of steps skip the first line.
531 if (lines.front().empty()) {
532 lines.erase(lines.begin());
533 }
534
535 // Now rejoin the lines and copy them back into doctext.
536 docstring.clear();
537 for (l_iter = lines.begin(); l_iter != lines.end(); ++l_iter) {
538 docstring += *l_iter;
539 docstring += '\n';
540 }
541
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100542 // assert(docstring.length() <= strlen(doctext)); may happen, see THRIFT-1755
543 if (docstring.length() <= strlen(doctext)) {
Jens Geyer8cd3efe2013-09-16 22:17:52 +0200544 strcpy(doctext, docstring.c_str());
545 } else {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100546 free(doctext); // too short
Jens Geyer8cd3efe2013-09-16 22:17:52 +0200547 doctext = strdup(docstring.c_str());
548 }
David Reiss1ac05802007-07-30 22:00:27 +0000549 return doctext;
550}
551
552/** Set to true to debug docstring parsing */
553static bool dump_docs = false;
554
555/**
556 * Dumps docstrings to stdout
David Reisscdffe262007-08-14 17:12:31 +0000557 * Only works for top-level definitions and the whole program doc
558 * (i.e., not enum constants, struct fields, or functions.
David Reiss1ac05802007-07-30 22:00:27 +0000559 */
560void dump_docstrings(t_program* program) {
David Reisscdffe262007-08-14 17:12:31 +0000561 string progdoc = program->get_doc();
David Reissc2532a92007-07-30 23:46:11 +0000562 if (!progdoc.empty()) {
563 printf("Whole program doc:\n%s\n", progdoc.c_str());
564 }
David Reiss1ac05802007-07-30 22:00:27 +0000565 const vector<t_typedef*>& typedefs = program->get_typedefs();
566 vector<t_typedef*>::const_iterator t_iter;
567 for (t_iter = typedefs.begin(); t_iter != typedefs.end(); ++t_iter) {
568 t_typedef* td = *t_iter;
569 if (td->has_doc()) {
David Reisscdffe262007-08-14 17:12:31 +0000570 printf("typedef %s:\n%s\n", td->get_name().c_str(), td->get_doc().c_str());
571 }
572 }
573 const vector<t_enum*>& enums = program->get_enums();
574 vector<t_enum*>::const_iterator e_iter;
575 for (e_iter = enums.begin(); e_iter != enums.end(); ++e_iter) {
576 t_enum* en = *e_iter;
577 if (en->has_doc()) {
578 printf("enum %s:\n%s\n", en->get_name().c_str(), en->get_doc().c_str());
579 }
580 }
581 const vector<t_const*>& consts = program->get_consts();
582 vector<t_const*>::const_iterator c_iter;
583 for (c_iter = consts.begin(); c_iter != consts.end(); ++c_iter) {
584 t_const* co = *c_iter;
585 if (co->has_doc()) {
586 printf("const %s:\n%s\n", co->get_name().c_str(), co->get_doc().c_str());
587 }
588 }
589 const vector<t_struct*>& structs = program->get_structs();
590 vector<t_struct*>::const_iterator s_iter;
591 for (s_iter = structs.begin(); s_iter != structs.end(); ++s_iter) {
592 t_struct* st = *s_iter;
593 if (st->has_doc()) {
594 printf("struct %s:\n%s\n", st->get_name().c_str(), st->get_doc().c_str());
595 }
596 }
597 const vector<t_struct*>& xceptions = program->get_xceptions();
598 vector<t_struct*>::const_iterator x_iter;
599 for (x_iter = xceptions.begin(); x_iter != xceptions.end(); ++x_iter) {
600 t_struct* xn = *x_iter;
601 if (xn->has_doc()) {
602 printf("xception %s:\n%s\n", xn->get_name().c_str(), xn->get_doc().c_str());
603 }
604 }
605 const vector<t_service*>& services = program->get_services();
606 vector<t_service*>::const_iterator v_iter;
607 for (v_iter = services.begin(); v_iter != services.end(); ++v_iter) {
608 t_service* sv = *v_iter;
609 if (sv->has_doc()) {
610 printf("service %s:\n%s\n", sv->get_name().c_str(), sv->get_doc().c_str());
David Reiss1ac05802007-07-30 22:00:27 +0000611 }
612 }
613}
614
615/**
Jens Geyer6fe77e82014-03-16 16:48:53 +0200616 * Emits a warning on list<byte>, binary type is typically a much better choice.
617 */
618void check_for_list_of_bytes(t_type* list_elem_type) {
zeshuai00726681fb2020-06-03 17:24:38 +0800619 if ((g_parse_mode == PROGRAM) && (list_elem_type != nullptr) && list_elem_type->is_base_type()) {
Jens Geyer6fe77e82014-03-16 16:48:53 +0200620 t_base_type* tbase = (t_base_type*)list_elem_type;
Jens Geyer40c28d32015-10-20 23:13:02 +0200621 if (tbase->get_base() == t_base_type::TYPE_I8) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100622 pwarning(1, "Consider using the more efficient \"binary\" type instead of \"list<byte>\".");
Jens Geyer6fe77e82014-03-16 16:48:53 +0200623 }
624 }
625}
626
Jens Geyer40c28d32015-10-20 23:13:02 +0200627static bool g_byte_warning_emitted = false;
628
629/**
630 * Emits a one-time warning on byte type, promoting the new i8 type instead
631 */
632void emit_byte_type_warning() {
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +0100633 if (!g_byte_warning_emitted) {
634 pwarning(1,
635 "The \"byte\" type is a compatibility alias for \"i8\". Use \"i8\" to emphasize the "
636 "signedness of this type.\n");
637 g_byte_warning_emitted = true;
638 }
Jens Geyer40c28d32015-10-20 23:13:02 +0200639}
640
David Reiss18bf22d2007-08-28 20:49:17 +0000641/**
Jens Geyer73880372015-11-14 15:21:57 +0100642 * Prints deprecation notice for old NS declarations that are no longer supported
zeshuai00726681fb2020-06-03 17:24:38 +0800643 * If new_form is nullptr, old_form is assumed to be a language identifier, such as "cpp"
644 * If new_form is not nullptr, both arguments are used exactly as given
Jens Geyer73880372015-11-14 15:21:57 +0100645 */
Jens Geyereb5f1172015-12-11 20:58:45 +0100646void error_unsupported_namespace_decl(const char* old_form, const char* new_form) {
647 const char* remainder = "";
zeshuai00726681fb2020-06-03 17:24:38 +0800648 if( new_form == nullptr) {
Jens Geyer73880372015-11-14 15:21:57 +0100649 new_form = old_form;
650 remainder = "_namespace";
651 }
652 failure("Unsupported declaration '%s%s'. Use 'namespace %s' instead.", old_form, remainder, new_form);
653}
654
655/**
David Reissdd08f6d2008-06-30 20:24:24 +0000656 * Prints the version number
657 */
658void version() {
Jens Geyerb5fe1db2021-02-11 22:49:49 +0100659 printf("Thrift version %s\n", THRIFT_VERSION);
David Reissdd08f6d2008-06-30 20:24:24 +0000660}
661
662/**
Jake Farrell2fd8a152012-09-29 00:26:36 +0000663 * Display the usage message and then exit with an error code.
Mark Slee31985722006-05-24 21:45:31 +0000664 */
665void usage() {
Jake Farrell2fd8a152012-09-29 00:26:36 +0000666 fprintf(stderr, "Usage: thrift [options] file\n\n");
667 fprintf(stderr, "Use thrift -help for a list of options\n");
668 exit(1);
669}
670
671/**
672 * Diplays the help message and then exits with an error code.
673 */
674void help() {
Mark Sleeb15a68b2006-06-07 06:46:24 +0000675 fprintf(stderr, "Usage: thrift [options] file\n");
676 fprintf(stderr, "Options:\n");
David Reissdd08f6d2008-06-30 20:24:24 +0000677 fprintf(stderr, " -version Print the compiler version\n");
dweatherford65b70752007-10-31 02:18:14 +0000678 fprintf(stderr, " -o dir Set the output directory for gen-* packages\n");
679 fprintf(stderr, " (default: current directory)\n");
Bryan Duxburybdca9f62011-03-01 19:53:07 +0000680 fprintf(stderr, " -out dir Set the ouput location for generated files.\n");
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100681 fprintf(stderr, " (no gen-* folder will be created)\n");
David Reissd779cbe2007-08-31 01:42:55 +0000682 fprintf(stderr, " -I dir Add a directory to the list of directories\n");
Mark Slee227ac2c2007-03-07 05:46:50 +0000683 fprintf(stderr, " searched for include directives\n");
Mark Slee2329a832006-11-09 00:23:30 +0000684 fprintf(stderr, " -nowarn Suppress all compiler warnings (BAD!)\n");
685 fprintf(stderr, " -strict Strict compiler warnings on\n");
686 fprintf(stderr, " -v[erbose] Verbose mode\n");
687 fprintf(stderr, " -r[ecurse] Also generate included files\n");
688 fprintf(stderr, " -debug Parse debug trace to stdout\n");
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100689 fprintf(stderr,
690 " --allow-neg-keys Allow negative field keys (Used to "
Bryan Duxburyc7206a42011-08-17 23:17:04 +0000691 "preserve protocol\n");
692 fprintf(stderr, " compatibility with older .thrift files)\n");
Roger Meier887ff752011-08-19 11:25:39 +0000693 fprintf(stderr, " --allow-64bit-consts Do not print warnings about using 64-bit constants\n");
David Reissbd0db882008-02-27 01:54:51 +0000694 fprintf(stderr, " --gen STR Generate code with a dynamically-registered generator.\n");
Jens Geyere8c51ed2014-04-18 02:27:57 +0200695 fprintf(stderr, " STR has the form language[:key1=val1[,key2[,key3=val3]]].\n");
David Reissbd0db882008-02-27 01:54:51 +0000696 fprintf(stderr, " Keys and values are options passed to the generator.\n");
697 fprintf(stderr, " Many options will not require values.\n");
698 fprintf(stderr, "\n");
Ben Craig262cfb42015-07-08 20:37:15 -0500699 fprintf(stderr, "Options related to audit operation\n");
700 fprintf(stderr, " --audit OldFile Old Thrift file to be audited with 'file'\n");
701 fprintf(stderr, " -Iold dir Add a directory to the list of directories\n");
702 fprintf(stderr, " searched for include directives for old thrift file\n");
703 fprintf(stderr, " -Inew dir Add a directory to the list of directories\n");
704 fprintf(stderr, " searched for include directives for new thrift file\n");
705 fprintf(stderr, "\n");
David Reissbd0db882008-02-27 01:54:51 +0000706 fprintf(stderr, "Available generators (and options):\n");
707
708 t_generator_registry::gen_map_t gen_map = t_generator_registry::get_generator_map();
709 t_generator_registry::gen_map_t::iterator iter;
710 for (iter = gen_map.begin(); iter != gen_map.end(); ++iter) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100711 fprintf(stderr,
712 " %s (%s):\n",
713 iter->second->get_short_name().c_str(),
714 iter->second->get_long_name().c_str());
David Reissbd0db882008-02-27 01:54:51 +0000715 fprintf(stderr, "%s", iter->second->get_documentation().c_str());
716 }
Mark Slee31985722006-05-24 21:45:31 +0000717 exit(1);
718}
719
720/**
Mark Slee30152872006-11-28 01:24:07 +0000721 * You know, when I started working on Thrift I really thought it wasn't going
722 * to become a programming language because it was just a generator and it
723 * wouldn't need runtime type information and all that jazz. But then we
724 * decided to add constants, and all of a sudden that means runtime type
725 * validation and inference, except the "runtime" is the code generator
David Reiss3bb5e052010-01-25 19:31:31 +0000726 * runtime.
Mark Slee30152872006-11-28 01:24:07 +0000727 */
728void validate_const_rec(std::string name, t_type* type, t_const_value* value) {
729 if (type->is_void()) {
730 throw "type error: cannot declare a void const: " + name;
731 }
732
733 if (type->is_base_type()) {
734 t_base_type::t_base tbase = ((t_base_type*)type)->get_base();
735 switch (tbase) {
736 case t_base_type::TYPE_STRING:
737 if (value->get_type() != t_const_value::CV_STRING) {
738 throw "type error: const \"" + name + "\" was declared as string";
739 }
740 break;
Jens Geyer62445c12022-06-29 00:00:00 +0200741 case t_base_type::TYPE_UUID:
742 if (value->get_type() != t_const_value::CV_STRING) {
743 throw "type error: const \"" + name + "\" was declared as uuid";
744 }
745 value->get_uuid(); // validates constant
746 break;
Mark Slee30152872006-11-28 01:24:07 +0000747 case t_base_type::TYPE_BOOL:
748 if (value->get_type() != t_const_value::CV_INTEGER) {
749 throw "type error: const \"" + name + "\" was declared as bool";
750 }
751 break;
Jens Geyer40c28d32015-10-20 23:13:02 +0200752 case t_base_type::TYPE_I8:
Mark Slee30152872006-11-28 01:24:07 +0000753 if (value->get_type() != t_const_value::CV_INTEGER) {
754 throw "type error: const \"" + name + "\" was declared as byte";
755 }
756 break;
757 case t_base_type::TYPE_I16:
758 if (value->get_type() != t_const_value::CV_INTEGER) {
759 throw "type error: const \"" + name + "\" was declared as i16";
760 }
761 break;
762 case t_base_type::TYPE_I32:
763 if (value->get_type() != t_const_value::CV_INTEGER) {
764 throw "type error: const \"" + name + "\" was declared as i32";
765 }
766 break;
767 case t_base_type::TYPE_I64:
768 if (value->get_type() != t_const_value::CV_INTEGER) {
769 throw "type error: const \"" + name + "\" was declared as i64";
770 }
771 break;
772 case t_base_type::TYPE_DOUBLE:
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100773 if (value->get_type() != t_const_value::CV_INTEGER
774 && value->get_type() != t_const_value::CV_DOUBLE) {
Mark Slee30152872006-11-28 01:24:07 +0000775 throw "type error: const \"" + name + "\" was declared as double";
776 }
777 break;
778 default:
David Reissdd7796f2007-08-28 21:09:06 +0000779 throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase) + name;
Mark Slee30152872006-11-28 01:24:07 +0000780 }
781 } else if (type->is_enum()) {
Bryan Duxbury2d804702009-12-18 19:41:11 +0000782 if (value->get_type() != t_const_value::CV_IDENTIFIER) {
Mark Slee30152872006-11-28 01:24:07 +0000783 throw "type error: const \"" + name + "\" was declared as enum";
784 }
Bryan Duxbury2d804702009-12-18 19:41:11 +0000785
Bryan Duxbury1606f252010-11-24 00:25:57 +0000786 // see if there's a dot in the identifier
787 std::string name_portion = value->get_identifier_name();
788
Bryan Duxbury2d804702009-12-18 19:41:11 +0000789 const vector<t_enum_value*>& enum_values = ((t_enum*)type)->get_constants();
790 vector<t_enum_value*>::const_iterator c_iter;
791 bool found = false;
Bryan Duxbury9f0a7862010-09-12 14:38:36 +0000792
Bryan Duxbury1606f252010-11-24 00:25:57 +0000793 for (c_iter = enum_values.begin(); c_iter != enum_values.end(); ++c_iter) {
Bryan Duxbury9f0a7862010-09-12 14:38:36 +0000794 if ((*c_iter)->get_name() == name_portion) {
Bryan Duxbury2d804702009-12-18 19:41:11 +0000795 found = true;
796 break;
797 }
798 }
799 if (!found) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100800 throw "type error: const " + name + " was declared as type " + type->get_name()
801 + " which is an enum, but " + value->get_identifier()
802 + " is not a valid value for that enum";
Bryan Duxbury2d804702009-12-18 19:41:11 +0000803 }
Mark Slee30152872006-11-28 01:24:07 +0000804 } else if (type->is_struct() || type->is_xception()) {
805 if (value->get_type() != t_const_value::CV_MAP) {
806 throw "type error: const \"" + name + "\" was declared as struct/xception";
807 }
808 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
809 vector<t_field*>::const_iterator f_iter;
810
Roman Sorokae58f75d2018-03-08 15:45:22 -0800811 const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
812 map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
Mark Slee30152872006-11-28 01:24:07 +0000813 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
814 if (v_iter->first->get_type() != t_const_value::CV_STRING) {
815 throw "type error: " + name + " struct key must be string";
816 }
zeshuai00726681fb2020-06-03 17:24:38 +0800817 t_type* field_type = nullptr;
Mark Slee30152872006-11-28 01:24:07 +0000818 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
819 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
820 field_type = (*f_iter)->get_type();
821 }
822 }
zeshuai00726681fb2020-06-03 17:24:38 +0800823 if (field_type == nullptr) {
Mark Slee30152872006-11-28 01:24:07 +0000824 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
825 }
826
827 validate_const_rec(name + "." + v_iter->first->get_string(), field_type, v_iter->second);
828 }
829 } else if (type->is_map()) {
830 t_type* k_type = ((t_map*)type)->get_key_type();
831 t_type* v_type = ((t_map*)type)->get_val_type();
Roman Sorokae58f75d2018-03-08 15:45:22 -0800832 const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
833 map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
Mark Slee30152872006-11-28 01:24:07 +0000834 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
835 validate_const_rec(name + "<key>", k_type, v_iter->first);
836 validate_const_rec(name + "<val>", v_type, v_iter->second);
Mark Slee2c44d202007-05-16 02:18:07 +0000837 }
Mark Slee30152872006-11-28 01:24:07 +0000838 } else if (type->is_list() || type->is_set()) {
839 t_type* e_type;
840 if (type->is_list()) {
841 e_type = ((t_list*)type)->get_elem_type();
842 } else {
843 e_type = ((t_set*)type)->get_elem_type();
844 }
845 const vector<t_const_value*>& val = value->get_list();
846 vector<t_const_value*>::const_iterator v_iter;
847 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
848 validate_const_rec(name + "<elem>", e_type, *v_iter);
849 }
850 }
851}
852
853/**
Jens Geyer12c09f42013-08-25 14:16:27 +0200854 * Check simple identifier names
855 * It's easier to do it this way instead of rewriting the whole grammar etc.
856 */
857void validate_simple_identifier(const char* identifier) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100858 string name(identifier);
859 if (name.find(".") != string::npos) {
Jens Geyer12c09f42013-08-25 14:16:27 +0200860 yyerror("Identifier %s can't have a dot.", identifier);
861 exit(1);
862 }
863}
864
865/**
Mark Slee30152872006-11-28 01:24:07 +0000866 * Check the type of the parsed const information against its declared type
867 */
868void validate_const_type(t_const* c) {
869 validate_const_rec(c->get_name(), c->get_type(), c->get_value());
870}
871
872/**
Mark Slee7ff32452007-02-01 05:26:18 +0000873 * Check the type of a default value assigned to a field.
874 */
875void validate_field_value(t_field* field, t_const_value* cv) {
876 validate_const_rec(field->get_name(), field->get_type(), cv);
877}
878
879/**
Mark Slee91f2b7b2008-01-31 01:49:16 +0000880 * Check that all the elements of a throws block are actually exceptions.
881 */
882bool validate_throws(t_struct* throws) {
883 const vector<t_field*>& members = throws->get_members();
884 vector<t_field*>::const_iterator m_iter;
885 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
Bryan Duxburycff83572011-08-24 20:53:03 +0000886 if (!t_generator::get_true_type((*m_iter)->get_type())->is_xception()) {
Mark Slee91f2b7b2008-01-31 01:49:16 +0000887 return false;
888 }
889 }
890 return true;
891}
892
893/**
Jens Geyer03d49442013-09-04 22:34:41 +0200894 * Skips UTF-8 BOM if there is one
895 */
896bool skip_utf8_bom(FILE* f) {
897
898 // pretty straightforward, but works
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100899 if (fgetc(f) == 0xEF) {
900 if (fgetc(f) == 0xBB) {
901 if (fgetc(f) == 0xBF) {
Jens Geyer03d49442013-09-04 22:34:41 +0200902 return true;
Roger Meier4f4b15b2014-11-05 16:51:04 +0100903 }
904 }
905 }
906
907 rewind(f);
Jens Geyer03d49442013-09-04 22:34:41 +0200908 return false;
909}
910
911/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000912 * Parses a program
913 */
Mark Slee2c44d202007-05-16 02:18:07 +0000914void parse(t_program* program, t_program* parent_program) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000915 // Get scope file path
916 string path = program->get_path();
Mark Slee2c44d202007-05-16 02:18:07 +0000917
Mark Sleef0712dc2006-10-25 19:03:57 +0000918 // Set current dir global, which is used in the include_file function
919 g_curdir = directory_name(path);
920 g_curpath = path;
921
922 // Open the file
Jens Geyer03d49442013-09-04 22:34:41 +0200923 // skip UTF-8 BOM if there is one
Mark Sleef0712dc2006-10-25 19:03:57 +0000924 yyin = fopen(path.c_str(), "r");
925 if (yyin == 0) {
926 failure("Could not open input file: \"%s\"", path.c_str());
927 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100928 if (skip_utf8_bom(yyin))
Jens Geyer03d49442013-09-04 22:34:41 +0200929 pverbose("Skipped UTF-8 BOM at %s\n", path.c_str());
Roger Meier4f4b15b2014-11-05 16:51:04 +0100930
Mark Sleef0712dc2006-10-25 19:03:57 +0000931 // Create new scope and scan for includes
932 pverbose("Scanning %s for includes\n", path.c_str());
Mark Slee2c44d202007-05-16 02:18:07 +0000933 g_parse_mode = INCLUDES;
Mark Sleef0712dc2006-10-25 19:03:57 +0000934 g_program = program;
935 g_scope = program->scope();
Mark Slee30152872006-11-28 01:24:07 +0000936 try {
Mark Slee36bfa2e2007-01-19 20:09:51 +0000937 yylineno = 1;
Mark Slee30152872006-11-28 01:24:07 +0000938 if (yyparse() != 0) {
939 failure("Parser error during include pass.");
940 }
Gaurav Singh7d30e2c2020-02-02 10:56:26 -0500941 } catch (string &x) {
Mark Slee30152872006-11-28 01:24:07 +0000942 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000943 }
944 fclose(yyin);
945
946 // Recursively parse all the include programs
947 vector<t_program*>& includes = program->get_includes();
948 vector<t_program*>::iterator iter;
949 for (iter = includes.begin(); iter != includes.end(); ++iter) {
950 parse(*iter, program);
951 }
952
Jens Geyere8379b52014-01-25 00:59:45 +0100953 // reset program doctext status before parsing a new file
954 reset_program_doctext_info();
955
David Reiss204420f2008-01-11 20:59:03 +0000956 // Parse the program file
Mark Sleef0712dc2006-10-25 19:03:57 +0000957 g_parse_mode = PROGRAM;
958 g_program = program;
959 g_scope = program->scope();
zeshuai00726681fb2020-06-03 17:24:38 +0800960 g_parent_scope = (parent_program != nullptr) ? parent_program->scope() : nullptr;
Mark Sleef0712dc2006-10-25 19:03:57 +0000961 g_parent_prefix = program->get_name() + ".";
962 g_curpath = path;
Jens Geyer03d49442013-09-04 22:34:41 +0200963
964 // Open the file
965 // skip UTF-8 BOM if there is one
Mark Sleef0712dc2006-10-25 19:03:57 +0000966 yyin = fopen(path.c_str(), "r");
967 if (yyin == 0) {
968 failure("Could not open input file: \"%s\"", path.c_str());
969 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100970 if (skip_utf8_bom(yyin))
Jens Geyer03d49442013-09-04 22:34:41 +0200971 pverbose("Skipped UTF-8 BOM at %s\n", path.c_str());
Roger Meier4f4b15b2014-11-05 16:51:04 +0100972
Mark Sleef0712dc2006-10-25 19:03:57 +0000973 pverbose("Parsing %s for types\n", path.c_str());
Mark Slee36bfa2e2007-01-19 20:09:51 +0000974 yylineno = 1;
David Reiss877237a2007-07-27 00:40:19 +0000975 try {
976 if (yyparse() != 0) {
977 failure("Parser error during types pass.");
978 }
Gaurav Singh7d30e2c2020-02-02 10:56:26 -0500979 } catch (string &x) {
David Reiss877237a2007-07-27 00:40:19 +0000980 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000981 }
982 fclose(yyin);
983}
984
985/**
986 * Generate code
987 */
David Reissbd0db882008-02-27 01:54:51 +0000988void generate(t_program* program, const vector<string>& generator_strings) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000989 // Oooohh, recursive code generation, hot!!
990 if (gen_recurse) {
Mustafa Senol Cosar3f0d4442019-03-01 18:57:09 +0300991 program->set_recursive(true);
Mark Sleef0712dc2006-10-25 19:03:57 +0000992 const vector<t_program*>& includes = program->get_includes();
cyy64750162019-02-08 13:40:59 +0800993 for (auto include : includes) {
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +0100994 // Propagate output path from parent to child programs
cyy64750162019-02-08 13:40:59 +0800995 include->set_out_path(program->get_out_path(), program->is_out_path_absolute());
Mark Slee5b743072007-11-13 04:00:29 +0000996
cyy64750162019-02-08 13:40:59 +0800997 generate(include, generator_strings);
Mark Sleef0712dc2006-10-25 19:03:57 +0000998 }
999 }
1000
1001 // Generate code!
1002 try {
1003 pverbose("Program: %s\n", program->get_path().c_str());
1004
David Reiss1ac05802007-07-30 22:00:27 +00001005 if (dump_docs) {
1006 dump_docstrings(program);
1007 }
David Reissbd0db882008-02-27 01:54:51 +00001008
Jens Geyer19f60f22022-03-16 23:26:37 +01001009 // make sure all symbolic constants are properly resolved
1010 program->scope()->resolve_all_consts();
1011
David Reissbd0db882008-02-27 01:54:51 +00001012 vector<string>::const_iterator iter;
1013 for (iter = generator_strings.begin(); iter != generator_strings.end(); ++iter) {
1014 t_generator* generator = t_generator_registry::get_generator(program, *iter);
1015
zeshuai00726681fb2020-06-03 17:24:38 +08001016 if (generator == nullptr) {
David Reissbd0db882008-02-27 01:54:51 +00001017 pwarning(1, "Unable to get a generator for \"%s\".\n", iter->c_str());
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001018 g_generator_failure = true;
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001019 } else if (generator) {
nsrtvwls014f53f2018-09-28 08:11:21 -07001020 generator->validate_input();
David Reissbd0db882008-02-27 01:54:51 +00001021 pverbose("Generating \"%s\"\n", iter->c_str());
1022 generator->generate_program();
David Reissc9342682008-03-27 21:39:49 +00001023 delete generator;
David Reissbd0db882008-02-27 01:54:51 +00001024 }
1025 }
Gaurav Singh7d30e2c2020-02-02 10:56:26 -05001026 } catch (string &s) {
Jens Geyerd4722d92016-02-13 23:25:11 +01001027 failure("Error: %s\n", s.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +00001028 } catch (const char* exc) {
Jens Geyerd4722d92016-02-13 23:25:11 +01001029 failure("Error: %s\n", exc);
Mustafa Senol Cosar3f0d4442019-03-01 18:57:09 +03001030 } catch (const std::invalid_argument& invalid_argument_exception) {
1031 failure("Error: %s\n", invalid_argument_exception.what());
Mark Sleef0712dc2006-10-25 19:03:57 +00001032 }
Mark Sleef0712dc2006-10-25 19:03:57 +00001033}
1034
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001035void audit(t_program* new_program,
1036 t_program* old_program,
1037 string new_thrift_include_path,
1038 string old_thrift_include_path) {
Ben Craig262cfb42015-07-08 20:37:15 -05001039 vector<string> temp_incl_searchpath = g_incl_searchpath;
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001040 if (!old_thrift_include_path.empty()) {
Ben Craig262cfb42015-07-08 20:37:15 -05001041 g_incl_searchpath.push_back(old_thrift_include_path);
1042 }
1043
zeshuai00726681fb2020-06-03 17:24:38 +08001044 parse(old_program, nullptr);
Ben Craig262cfb42015-07-08 20:37:15 -05001045
1046 g_incl_searchpath = temp_incl_searchpath;
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001047 if (!new_thrift_include_path.empty()) {
Ben Craig262cfb42015-07-08 20:37:15 -05001048 g_incl_searchpath.push_back(new_thrift_include_path);
1049 }
1050
zeshuai00726681fb2020-06-03 17:24:38 +08001051 parse(new_program, nullptr);
Ben Craig262cfb42015-07-08 20:37:15 -05001052
1053 compare_namespace(new_program, old_program);
1054 compare_services(new_program->get_services(), old_program->get_services());
1055 compare_enums(new_program->get_enums(), old_program->get_enums());
1056 compare_structs(new_program->get_structs(), old_program->get_structs());
1057 compare_structs(new_program->get_xceptions(), old_program->get_xceptions());
1058 compare_consts(new_program->get_consts(), old_program->get_consts());
1059}
1060
Mark Sleef0712dc2006-10-25 19:03:57 +00001061/**
Mark Sleef5377b32006-10-10 01:42:59 +00001062 * Parse it up.. then spit it back out, in pretty much every language. Alright
1063 * not that many languages, but the cool ones that we care about.
Mark Slee31985722006-05-24 21:45:31 +00001064 */
1065int main(int argc, char** argv) {
1066 int i;
dweatherford65b70752007-10-31 02:18:14 +00001067 std::string out_path;
Bryan Duxburybdca9f62011-03-01 19:53:07 +00001068 bool out_path_is_absolute = false;
Mark Sleef5377b32006-10-10 01:42:59 +00001069
Mark Sleeb15a68b2006-06-07 06:46:24 +00001070 // Setup time string
zeshuai00726681fb2020-06-03 17:24:38 +08001071 time_t now = time(nullptr);
Mark Sleeb15a68b2006-06-07 06:46:24 +00001072 g_time_str = ctime(&now);
Mark Slee31985722006-05-24 21:45:31 +00001073
Mark Sleef0712dc2006-10-25 19:03:57 +00001074 // Check for necessary arguments, you gotta have at least a filename and
1075 // an output language flag
Mark Sleeb15a68b2006-06-07 06:46:24 +00001076 if (argc < 2) {
1077 usage();
1078 }
Mark Slee31985722006-05-24 21:45:31 +00001079
David Reissbd0db882008-02-27 01:54:51 +00001080 vector<string> generator_strings;
Ben Craig262cfb42015-07-08 20:37:15 -05001081 string old_thrift_include_path;
1082 string new_thrift_include_path;
1083 string old_input_file;
David Reissbd0db882008-02-27 01:54:51 +00001084
David Reiss9cc2c132008-02-27 01:54:47 +00001085 // Set the current path to a dummy value to make warning messages clearer.
1086 g_curpath = "arguments";
1087
Mark Sleef5377b32006-10-10 01:42:59 +00001088 // Hacky parameter handling... I didn't feel like using a library sorry!
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001089 for (i = 1; i < argc - 1; i++) {
Mark Sleefdbee812006-09-27 18:50:48 +00001090 char* arg;
Mark Slee2329a832006-11-09 00:23:30 +00001091
Mark Sleefdbee812006-09-27 18:50:48 +00001092 arg = strtok(argv[i], " ");
zeshuai00726681fb2020-06-03 17:24:38 +08001093 while (arg != nullptr) {
Mark Slee2329a832006-11-09 00:23:30 +00001094 // Treat double dashes as single dashes
Mark Slee52cb2232006-11-10 22:32:07 +00001095 if (arg[0] == '-' && arg[1] == '-') {
Mark Slee2329a832006-11-09 00:23:30 +00001096 ++arg;
1097 }
1098
Jake Farrell2fd8a152012-09-29 00:26:36 +00001099 if (strcmp(arg, "-help") == 0) {
1100 help();
1101 } else if (strcmp(arg, "-version") == 0) {
David Reissdd08f6d2008-06-30 20:24:24 +00001102 version();
jfarrell70969422013-09-09 20:33:38 -04001103 exit(0);
David Reissdd08f6d2008-06-30 20:24:24 +00001104 } else if (strcmp(arg, "-debug") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +00001105 g_debug = 1;
Mark Slee2329a832006-11-09 00:23:30 +00001106 } else if (strcmp(arg, "-nowarn") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +00001107 g_warn = 0;
Mark Slee2329a832006-11-09 00:23:30 +00001108 } else if (strcmp(arg, "-strict") == 0) {
Bryan Duxburya145b4d2009-04-03 17:29:25 +00001109 g_strict = 255;
Mark Sleef0712dc2006-10-25 19:03:57 +00001110 g_warn = 2;
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001111 } else if (strcmp(arg, "-v") == 0 || strcmp(arg, "-verbose") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +00001112 g_verbose = 1;
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001113 } else if (strcmp(arg, "-r") == 0 || strcmp(arg, "-recurse") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +00001114 gen_recurse = true;
Bryan Duxburyc7206a42011-08-17 23:17:04 +00001115 } else if (strcmp(arg, "-allow-neg-keys") == 0) {
1116 g_allow_neg_field_keys = true;
Roger Meier887ff752011-08-19 11:25:39 +00001117 } else if (strcmp(arg, "-allow-64bit-consts") == 0) {
1118 g_allow_64bit_consts = true;
David Reissbd0db882008-02-27 01:54:51 +00001119 } else if (strcmp(arg, "-gen") == 0) {
1120 arg = argv[++i];
zeshuai00726681fb2020-06-03 17:24:38 +08001121 if (arg == nullptr) {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001122 fprintf(stderr, "Missing generator specification\n");
David Reissbd0db882008-02-27 01:54:51 +00001123 usage();
1124 }
cyy64750162019-02-08 13:40:59 +08001125 generator_strings.emplace_back(arg);
Martin Kraemer32c66e12006-11-09 00:06:36 +00001126 } else if (strcmp(arg, "-I") == 0) {
1127 // An argument of "-I\ asdf" is invalid and has unknown results
1128 arg = argv[++i];
1129
zeshuai00726681fb2020-06-03 17:24:38 +08001130 if (arg == nullptr) {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001131 fprintf(stderr, "Missing Include directory\n");
Martin Kraemer32c66e12006-11-09 00:06:36 +00001132 usage();
1133 }
cyy64750162019-02-08 13:40:59 +08001134 g_incl_searchpath.emplace_back(arg);
Bryan Duxburybdca9f62011-03-01 19:53:07 +00001135 } else if ((strcmp(arg, "-o") == 0) || (strcmp(arg, "-out") == 0)) {
1136 out_path_is_absolute = (strcmp(arg, "-out") == 0) ? true : false;
Roger Meier6d7473d2013-05-06 01:08:36 +02001137 arg = argv[++i];
zeshuai00726681fb2020-06-03 17:24:38 +08001138 if (arg == nullptr) {
David Reiss9d866ac2008-06-10 22:56:19 +00001139 fprintf(stderr, "-o: missing output directory\n");
dweatherford65b70752007-10-31 02:18:14 +00001140 usage();
Mark Slee5b743072007-11-13 04:00:29 +00001141 }
dweatherford65b70752007-10-31 02:18:14 +00001142 out_path = arg;
David Reiss204420f2008-01-11 20:59:03 +00001143
Ben Craige9576752013-10-11 08:19:16 -05001144#ifdef _WIN32
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001145 // strip out trailing \ on Windows
Jim King9de9b1f2015-04-30 16:03:34 -04001146 std::string::size_type last = out_path.length() - 1;
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001147 if (out_path[last] == '\\') {
David Reiss204420f2008-01-11 20:59:03 +00001148 out_path.erase(last);
1149 }
1150#endif
Roger Meier061d4a22012-10-07 11:51:00 +00001151 if (!check_is_directory(out_path.c_str()))
dweatherford65b70752007-10-31 02:18:14 +00001152 return -1;
Ben Craig262cfb42015-07-08 20:37:15 -05001153 } else if (strcmp(arg, "-audit") == 0) {
1154 g_audit = true;
1155 arg = argv[++i];
zeshuai00726681fb2020-06-03 17:24:38 +08001156 if (arg == nullptr) {
Ben Craig262cfb42015-07-08 20:37:15 -05001157 fprintf(stderr, "Missing old thrift file name for audit operation\n");
1158 usage();
1159 }
1160 char old_thrift_file_rp[THRIFT_PATH_MAX];
1161
Nobuaki Sukegawad479e232016-02-28 11:28:19 +09001162 // cppcheck-suppress uninitvar
zeshuai00726681fb2020-06-03 17:24:38 +08001163 if (saferealpath(arg, old_thrift_file_rp) == nullptr) {
Ben Craig262cfb42015-07-08 20:37:15 -05001164 failure("Could not open input file with realpath: %s", arg);
1165 }
1166 old_input_file = string(old_thrift_file_rp);
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001167 } else if (strcmp(arg, "-audit-nofatal") == 0) {
Ben Craig262cfb42015-07-08 20:37:15 -05001168 g_audit_fatal = false;
1169 } else if (strcmp(arg, "-Iold") == 0) {
1170 arg = argv[++i];
zeshuai00726681fb2020-06-03 17:24:38 +08001171 if (arg == nullptr) {
Ben Craig262cfb42015-07-08 20:37:15 -05001172 fprintf(stderr, "Missing Include directory for old thrift file\n");
1173 usage();
1174 }
1175 old_thrift_include_path = string(arg);
1176 } else if (strcmp(arg, "-Inew") == 0) {
1177 arg = argv[++i];
zeshuai00726681fb2020-06-03 17:24:38 +08001178 if (arg == nullptr) {
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001179 fprintf(stderr, "Missing Include directory for new thrift file\n");
1180 usage();
Ben Craig262cfb42015-07-08 20:37:15 -05001181 }
1182 new_thrift_include_path = string(arg);
Mark Sleefdbee812006-09-27 18:50:48 +00001183 } else {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001184 fprintf(stderr, "Unrecognized option: %s\n", arg);
Mark Sleefdbee812006-09-27 18:50:48 +00001185 usage();
1186 }
1187
1188 // Tokenize more
zeshuai00726681fb2020-06-03 17:24:38 +08001189 arg = strtok(nullptr, " ");
Mark Slee31985722006-05-24 21:45:31 +00001190 }
1191 }
Mark Slee2c44d202007-05-16 02:18:07 +00001192
Jake Farrell2fd8a152012-09-29 00:26:36 +00001193 // display help
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001194 if ((strcmp(argv[argc - 1], "-help") == 0) || (strcmp(argv[argc - 1], "--help") == 0)) {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001195 help();
1196 }
1197
David Reissdd08f6d2008-06-30 20:24:24 +00001198 // if you're asking for version, you have a right not to pass a file
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001199 if ((strcmp(argv[argc - 1], "-version") == 0) || (strcmp(argv[argc - 1], "--version") == 0)) {
David Reissdd08f6d2008-06-30 20:24:24 +00001200 version();
jfarrell8b1799f2014-04-10 22:06:11 -04001201 exit(0);
David Reissdd08f6d2008-06-30 20:24:24 +00001202 }
1203
Mark Sleef0712dc2006-10-25 19:03:57 +00001204 // Initialize global types
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001205 initGlobals();
Mark Sleee8540632006-05-30 09:24:40 +00001206
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001207 if (g_audit) {
Ben Craig262cfb42015-07-08 20:37:15 -05001208 // Audit operation
Mark Slee31985722006-05-24 21:45:31 +00001209
Ben Craig262cfb42015-07-08 20:37:15 -05001210 if (old_input_file.empty()) {
1211 fprintf(stderr, "Missing file name of old thrift file for audit\n");
1212 usage();
1213 }
David Reiss9cc2c132008-02-27 01:54:47 +00001214
Ben Craig262cfb42015-07-08 20:37:15 -05001215 char new_thrift_file_rp[THRIFT_PATH_MAX];
zeshuai00726681fb2020-06-03 17:24:38 +08001216 if (argv[i] == nullptr) {
Ben Craig262cfb42015-07-08 20:37:15 -05001217 fprintf(stderr, "Missing file name of new thrift file for audit\n");
1218 usage();
1219 }
Nobuaki Sukegawad479e232016-02-28 11:28:19 +09001220 // cppcheck-suppress uninitvar
zeshuai00726681fb2020-06-03 17:24:38 +08001221 if (saferealpath(argv[i], new_thrift_file_rp) == nullptr) {
Ben Craig262cfb42015-07-08 20:37:15 -05001222 failure("Could not open input file with realpath: %s", argv[i]);
1223 }
1224 string new_input_file(new_thrift_file_rp);
1225
1226 t_program new_program(new_input_file);
1227 t_program old_program(old_input_file);
1228
1229 audit(&new_program, &old_program, new_thrift_include_path, old_thrift_include_path);
1230
1231 } else {
1232 // Generate options
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001233
Ben Craig262cfb42015-07-08 20:37:15 -05001234 // You gotta generate something!
1235 if (generator_strings.empty()) {
1236 fprintf(stderr, "No output language(s) specified\n");
1237 usage();
1238 }
1239
1240 // Real-pathify it
1241 char rp[THRIFT_PATH_MAX];
zeshuai00726681fb2020-06-03 17:24:38 +08001242 if (argv[i] == nullptr) {
Ben Craig262cfb42015-07-08 20:37:15 -05001243 fprintf(stderr, "Missing file name\n");
1244 usage();
1245 }
Nobuaki Sukegawad479e232016-02-28 11:28:19 +09001246 // cppcheck-suppress uninitvar
zeshuai00726681fb2020-06-03 17:24:38 +08001247 if (saferealpath(argv[i], rp) == nullptr) {
Ben Craig262cfb42015-07-08 20:37:15 -05001248 failure("Could not open input file with realpath: %s", argv[i]);
1249 }
1250 string input_file(rp);
1251
1252 // Instance of the global parse tree
1253 t_program* program = new t_program(input_file);
1254 if (out_path.size()) {
1255 program->set_out_path(out_path, out_path_is_absolute);
1256 }
1257
1258 // Compute the cpp include prefix.
1259 // infer this from the filename passed in
1260 string input_filename = argv[i];
1261 string include_prefix;
1262
1263 string::size_type last_slash = string::npos;
1264 if ((last_slash = input_filename.rfind("/")) != string::npos) {
1265 include_prefix = input_filename.substr(0, last_slash);
1266 }
1267
1268 program->set_include_prefix(include_prefix);
1269
1270 // Parse it!
zeshuai00726681fb2020-06-03 17:24:38 +08001271 parse(program, nullptr);
Ben Craig262cfb42015-07-08 20:37:15 -05001272
1273 // The current path is not really relevant when we are doing generation.
1274 // Reset the variable to make warning messages clearer.
1275 g_curpath = "generation";
1276 // Reset yylineno for the heck of it. Use 1 instead of 0 because
1277 // That is what shows up during argument parsing.
1278 yylineno = 1;
1279
1280 // Generate it!
1281 generate(program, generator_strings);
1282 delete program;
1283 }
Mark Sleeb15a68b2006-06-07 06:46:24 +00001284
Mark Sleef0712dc2006-10-25 19:03:57 +00001285 // Clean up. Who am I kidding... this program probably orphans heap memory
1286 // all over the place, but who cares because it is about to exit and it is
1287 // all referenced and used by this wacky parse tree up until now anyways.
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001288 clearGlobals();
Mark Slee31985722006-05-24 21:45:31 +00001289
1290 // Finished
Ben Craig262cfb42015-07-08 20:37:15 -05001291 if (g_return_failure && g_audit_fatal) {
1292 exit(2);
1293 }
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001294 if (g_generator_failure) {
1295 exit(3);
1296 }
Ben Craig262cfb42015-07-08 20:37:15 -05001297 // Finished
Mark Slee31985722006-05-24 21:45:31 +00001298 return 0;
1299}