blob: 4c900f71331aa9ffd3b7e8dc93a44baf0c06c523 [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
David Reiss204420f2008-01-11 20:59:03 +0000340 if (saferealpath(filename.c_str(), rp) == NULL) {
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
David Reiss204420f2008-01-11 20:59:03 +0000363 if (saferealpath(sfilename.c_str(), rp) == NULL) {
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() {
385 if (g_doctext != NULL) {
386 pwarning(2, "Uncaptured doctext at on line %d.", g_doctext_lineno);
387 }
388 free(g_doctext);
389 g_doctext = NULL;
390}
391
392/**
Jens Geyere8379b52014-01-25 00:59:45 +0100393 * Reset program doctext information after processing a file
394 */
395void reset_program_doctext_info() {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100396 if (g_program_doctext_candidate != NULL) {
Jens Geyere8379b52014-01-25 00:59:45 +0100397 free(g_program_doctext_candidate);
398 g_program_doctext_candidate = NULL;
399 }
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() {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100409 if ((g_program_doctext_candidate != NULL) && (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()) {
449 return NULL;
450 }
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) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100619 if ((g_parse_mode == PROGRAM) && (list_elem_type != NULL) && 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
643 * If new_form is NULL, old_form is assumed to be a language identifier, such as "cpp"
644 * If new_form is not NULL, both arguments are used exactly as given
645 */
Jens Geyereb5f1172015-12-11 20:58:45 +0100646void error_unsupported_namespace_decl(const char* old_form, const char* new_form) {
647 const char* remainder = "";
Jens Geyer73880372015-11-14 15:21:57 +0100648 if( new_form == NULL) {
649 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() {
Bryan Duxburya1e268c2010-05-03 21:33:00 +0000659 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;
741 case t_base_type::TYPE_BOOL:
742 if (value->get_type() != t_const_value::CV_INTEGER) {
743 throw "type error: const \"" + name + "\" was declared as bool";
744 }
745 break;
Jens Geyer40c28d32015-10-20 23:13:02 +0200746 case t_base_type::TYPE_I8:
Mark Slee30152872006-11-28 01:24:07 +0000747 if (value->get_type() != t_const_value::CV_INTEGER) {
748 throw "type error: const \"" + name + "\" was declared as byte";
749 }
750 break;
751 case t_base_type::TYPE_I16:
752 if (value->get_type() != t_const_value::CV_INTEGER) {
753 throw "type error: const \"" + name + "\" was declared as i16";
754 }
755 break;
756 case t_base_type::TYPE_I32:
757 if (value->get_type() != t_const_value::CV_INTEGER) {
758 throw "type error: const \"" + name + "\" was declared as i32";
759 }
760 break;
761 case t_base_type::TYPE_I64:
762 if (value->get_type() != t_const_value::CV_INTEGER) {
763 throw "type error: const \"" + name + "\" was declared as i64";
764 }
765 break;
766 case t_base_type::TYPE_DOUBLE:
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100767 if (value->get_type() != t_const_value::CV_INTEGER
768 && value->get_type() != t_const_value::CV_DOUBLE) {
Mark Slee30152872006-11-28 01:24:07 +0000769 throw "type error: const \"" + name + "\" was declared as double";
770 }
771 break;
772 default:
David Reissdd7796f2007-08-28 21:09:06 +0000773 throw "compiler error: no const of base type " + t_base_type::t_base_name(tbase) + name;
Mark Slee30152872006-11-28 01:24:07 +0000774 }
775 } else if (type->is_enum()) {
Bryan Duxbury2d804702009-12-18 19:41:11 +0000776 if (value->get_type() != t_const_value::CV_IDENTIFIER) {
Mark Slee30152872006-11-28 01:24:07 +0000777 throw "type error: const \"" + name + "\" was declared as enum";
778 }
Bryan Duxbury2d804702009-12-18 19:41:11 +0000779
Bryan Duxbury1606f252010-11-24 00:25:57 +0000780 // see if there's a dot in the identifier
781 std::string name_portion = value->get_identifier_name();
782
Bryan Duxbury2d804702009-12-18 19:41:11 +0000783 const vector<t_enum_value*>& enum_values = ((t_enum*)type)->get_constants();
784 vector<t_enum_value*>::const_iterator c_iter;
785 bool found = false;
Bryan Duxbury9f0a7862010-09-12 14:38:36 +0000786
Bryan Duxbury1606f252010-11-24 00:25:57 +0000787 for (c_iter = enum_values.begin(); c_iter != enum_values.end(); ++c_iter) {
Bryan Duxbury9f0a7862010-09-12 14:38:36 +0000788 if ((*c_iter)->get_name() == name_portion) {
Bryan Duxbury2d804702009-12-18 19:41:11 +0000789 found = true;
790 break;
791 }
792 }
793 if (!found) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100794 throw "type error: const " + name + " was declared as type " + type->get_name()
795 + " which is an enum, but " + value->get_identifier()
796 + " is not a valid value for that enum";
Bryan Duxbury2d804702009-12-18 19:41:11 +0000797 }
Mark Slee30152872006-11-28 01:24:07 +0000798 } else if (type->is_struct() || type->is_xception()) {
799 if (value->get_type() != t_const_value::CV_MAP) {
800 throw "type error: const \"" + name + "\" was declared as struct/xception";
801 }
802 const vector<t_field*>& fields = ((t_struct*)type)->get_members();
803 vector<t_field*>::const_iterator f_iter;
804
Roman Sorokae58f75d2018-03-08 15:45:22 -0800805 const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
806 map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
Mark Slee30152872006-11-28 01:24:07 +0000807 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
808 if (v_iter->first->get_type() != t_const_value::CV_STRING) {
809 throw "type error: " + name + " struct key must be string";
810 }
811 t_type* field_type = NULL;
812 for (f_iter = fields.begin(); f_iter != fields.end(); ++f_iter) {
813 if ((*f_iter)->get_name() == v_iter->first->get_string()) {
814 field_type = (*f_iter)->get_type();
815 }
816 }
817 if (field_type == NULL) {
818 throw "type error: " + type->get_name() + " has no field " + v_iter->first->get_string();
819 }
820
821 validate_const_rec(name + "." + v_iter->first->get_string(), field_type, v_iter->second);
822 }
823 } else if (type->is_map()) {
824 t_type* k_type = ((t_map*)type)->get_key_type();
825 t_type* v_type = ((t_map*)type)->get_val_type();
Roman Sorokae58f75d2018-03-08 15:45:22 -0800826 const map<t_const_value*, t_const_value*, t_const_value::value_compare>& val = value->get_map();
827 map<t_const_value*, t_const_value*, t_const_value::value_compare>::const_iterator v_iter;
Mark Slee30152872006-11-28 01:24:07 +0000828 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
829 validate_const_rec(name + "<key>", k_type, v_iter->first);
830 validate_const_rec(name + "<val>", v_type, v_iter->second);
Mark Slee2c44d202007-05-16 02:18:07 +0000831 }
Mark Slee30152872006-11-28 01:24:07 +0000832 } else if (type->is_list() || type->is_set()) {
833 t_type* e_type;
834 if (type->is_list()) {
835 e_type = ((t_list*)type)->get_elem_type();
836 } else {
837 e_type = ((t_set*)type)->get_elem_type();
838 }
839 const vector<t_const_value*>& val = value->get_list();
840 vector<t_const_value*>::const_iterator v_iter;
841 for (v_iter = val.begin(); v_iter != val.end(); ++v_iter) {
842 validate_const_rec(name + "<elem>", e_type, *v_iter);
843 }
844 }
845}
846
847/**
Jens Geyer12c09f42013-08-25 14:16:27 +0200848 * Check simple identifier names
849 * It's easier to do it this way instead of rewriting the whole grammar etc.
850 */
851void validate_simple_identifier(const char* identifier) {
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100852 string name(identifier);
853 if (name.find(".") != string::npos) {
Jens Geyer12c09f42013-08-25 14:16:27 +0200854 yyerror("Identifier %s can't have a dot.", identifier);
855 exit(1);
856 }
857}
858
859/**
Mark Slee30152872006-11-28 01:24:07 +0000860 * Check the type of the parsed const information against its declared type
861 */
862void validate_const_type(t_const* c) {
863 validate_const_rec(c->get_name(), c->get_type(), c->get_value());
864}
865
866/**
Mark Slee7ff32452007-02-01 05:26:18 +0000867 * Check the type of a default value assigned to a field.
868 */
869void validate_field_value(t_field* field, t_const_value* cv) {
870 validate_const_rec(field->get_name(), field->get_type(), cv);
871}
872
873/**
Mark Slee91f2b7b2008-01-31 01:49:16 +0000874 * Check that all the elements of a throws block are actually exceptions.
875 */
876bool validate_throws(t_struct* throws) {
877 const vector<t_field*>& members = throws->get_members();
878 vector<t_field*>::const_iterator m_iter;
879 for (m_iter = members.begin(); m_iter != members.end(); ++m_iter) {
Bryan Duxburycff83572011-08-24 20:53:03 +0000880 if (!t_generator::get_true_type((*m_iter)->get_type())->is_xception()) {
Mark Slee91f2b7b2008-01-31 01:49:16 +0000881 return false;
882 }
883 }
884 return true;
885}
886
887/**
Jens Geyer03d49442013-09-04 22:34:41 +0200888 * Skips UTF-8 BOM if there is one
889 */
890bool skip_utf8_bom(FILE* f) {
891
892 // pretty straightforward, but works
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100893 if (fgetc(f) == 0xEF) {
894 if (fgetc(f) == 0xBB) {
895 if (fgetc(f) == 0xBF) {
Jens Geyer03d49442013-09-04 22:34:41 +0200896 return true;
Roger Meier4f4b15b2014-11-05 16:51:04 +0100897 }
898 }
899 }
900
901 rewind(f);
Jens Geyer03d49442013-09-04 22:34:41 +0200902 return false;
903}
904
905/**
Mark Sleef0712dc2006-10-25 19:03:57 +0000906 * Parses a program
907 */
Mark Slee2c44d202007-05-16 02:18:07 +0000908void parse(t_program* program, t_program* parent_program) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000909 // Get scope file path
910 string path = program->get_path();
Mark Slee2c44d202007-05-16 02:18:07 +0000911
Mark Sleef0712dc2006-10-25 19:03:57 +0000912 // Set current dir global, which is used in the include_file function
913 g_curdir = directory_name(path);
914 g_curpath = path;
915
916 // Open the file
Jens Geyer03d49442013-09-04 22:34:41 +0200917 // skip UTF-8 BOM if there is one
Mark Sleef0712dc2006-10-25 19:03:57 +0000918 yyin = fopen(path.c_str(), "r");
919 if (yyin == 0) {
920 failure("Could not open input file: \"%s\"", path.c_str());
921 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100922 if (skip_utf8_bom(yyin))
Jens Geyer03d49442013-09-04 22:34:41 +0200923 pverbose("Skipped UTF-8 BOM at %s\n", path.c_str());
Roger Meier4f4b15b2014-11-05 16:51:04 +0100924
Mark Sleef0712dc2006-10-25 19:03:57 +0000925 // Create new scope and scan for includes
926 pverbose("Scanning %s for includes\n", path.c_str());
Mark Slee2c44d202007-05-16 02:18:07 +0000927 g_parse_mode = INCLUDES;
Mark Sleef0712dc2006-10-25 19:03:57 +0000928 g_program = program;
929 g_scope = program->scope();
Mark Slee30152872006-11-28 01:24:07 +0000930 try {
Mark Slee36bfa2e2007-01-19 20:09:51 +0000931 yylineno = 1;
Mark Slee30152872006-11-28 01:24:07 +0000932 if (yyparse() != 0) {
933 failure("Parser error during include pass.");
934 }
Gaurav Singh7d30e2c2020-02-02 10:56:26 -0500935 } catch (string &x) {
Mark Slee30152872006-11-28 01:24:07 +0000936 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000937 }
938 fclose(yyin);
939
940 // Recursively parse all the include programs
941 vector<t_program*>& includes = program->get_includes();
942 vector<t_program*>::iterator iter;
943 for (iter = includes.begin(); iter != includes.end(); ++iter) {
944 parse(*iter, program);
945 }
946
Jens Geyere8379b52014-01-25 00:59:45 +0100947 // reset program doctext status before parsing a new file
948 reset_program_doctext_info();
949
David Reiss204420f2008-01-11 20:59:03 +0000950 // Parse the program file
Mark Sleef0712dc2006-10-25 19:03:57 +0000951 g_parse_mode = PROGRAM;
952 g_program = program;
953 g_scope = program->scope();
954 g_parent_scope = (parent_program != NULL) ? parent_program->scope() : NULL;
955 g_parent_prefix = program->get_name() + ".";
956 g_curpath = path;
Jens Geyer03d49442013-09-04 22:34:41 +0200957
958 // Open the file
959 // skip UTF-8 BOM if there is one
Mark Sleef0712dc2006-10-25 19:03:57 +0000960 yyin = fopen(path.c_str(), "r");
961 if (yyin == 0) {
962 failure("Could not open input file: \"%s\"", path.c_str());
963 }
Konrad Grochowski16a23a62014-11-13 15:33:38 +0100964 if (skip_utf8_bom(yyin))
Jens Geyer03d49442013-09-04 22:34:41 +0200965 pverbose("Skipped UTF-8 BOM at %s\n", path.c_str());
Roger Meier4f4b15b2014-11-05 16:51:04 +0100966
Mark Sleef0712dc2006-10-25 19:03:57 +0000967 pverbose("Parsing %s for types\n", path.c_str());
Mark Slee36bfa2e2007-01-19 20:09:51 +0000968 yylineno = 1;
David Reiss877237a2007-07-27 00:40:19 +0000969 try {
970 if (yyparse() != 0) {
971 failure("Parser error during types pass.");
972 }
Gaurav Singh7d30e2c2020-02-02 10:56:26 -0500973 } catch (string &x) {
David Reiss877237a2007-07-27 00:40:19 +0000974 failure(x.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +0000975 }
976 fclose(yyin);
977}
978
979/**
980 * Generate code
981 */
David Reissbd0db882008-02-27 01:54:51 +0000982void generate(t_program* program, const vector<string>& generator_strings) {
Mark Sleef0712dc2006-10-25 19:03:57 +0000983 // Oooohh, recursive code generation, hot!!
984 if (gen_recurse) {
Mustafa Senol Cosar3f0d4442019-03-01 18:57:09 +0300985 program->set_recursive(true);
Mark Sleef0712dc2006-10-25 19:03:57 +0000986 const vector<t_program*>& includes = program->get_includes();
cyy64750162019-02-08 13:40:59 +0800987 for (auto include : includes) {
Konrad Grochowski3b5dacb2014-11-24 10:55:31 +0100988 // Propagate output path from parent to child programs
cyy64750162019-02-08 13:40:59 +0800989 include->set_out_path(program->get_out_path(), program->is_out_path_absolute());
Mark Slee5b743072007-11-13 04:00:29 +0000990
cyy64750162019-02-08 13:40:59 +0800991 generate(include, generator_strings);
Mark Sleef0712dc2006-10-25 19:03:57 +0000992 }
993 }
994
995 // Generate code!
996 try {
997 pverbose("Program: %s\n", program->get_path().c_str());
998
David Reiss1ac05802007-07-30 22:00:27 +0000999 if (dump_docs) {
1000 dump_docstrings(program);
1001 }
David Reissbd0db882008-02-27 01:54:51 +00001002
1003 vector<string>::const_iterator iter;
1004 for (iter = generator_strings.begin(); iter != generator_strings.end(); ++iter) {
1005 t_generator* generator = t_generator_registry::get_generator(program, *iter);
1006
1007 if (generator == NULL) {
1008 pwarning(1, "Unable to get a generator for \"%s\".\n", iter->c_str());
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001009 g_generator_failure = true;
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001010 } else if (generator) {
nsrtvwls014f53f2018-09-28 08:11:21 -07001011 generator->validate_input();
David Reissbd0db882008-02-27 01:54:51 +00001012 pverbose("Generating \"%s\"\n", iter->c_str());
1013 generator->generate_program();
David Reissc9342682008-03-27 21:39:49 +00001014 delete generator;
David Reissbd0db882008-02-27 01:54:51 +00001015 }
1016 }
Gaurav Singh7d30e2c2020-02-02 10:56:26 -05001017 } catch (string &s) {
Jens Geyerd4722d92016-02-13 23:25:11 +01001018 failure("Error: %s\n", s.c_str());
Mark Sleef0712dc2006-10-25 19:03:57 +00001019 } catch (const char* exc) {
Jens Geyerd4722d92016-02-13 23:25:11 +01001020 failure("Error: %s\n", exc);
Mustafa Senol Cosar3f0d4442019-03-01 18:57:09 +03001021 } catch (const std::invalid_argument& invalid_argument_exception) {
1022 failure("Error: %s\n", invalid_argument_exception.what());
Mark Sleef0712dc2006-10-25 19:03:57 +00001023 }
Mark Sleef0712dc2006-10-25 19:03:57 +00001024}
1025
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001026void audit(t_program* new_program,
1027 t_program* old_program,
1028 string new_thrift_include_path,
1029 string old_thrift_include_path) {
Ben Craig262cfb42015-07-08 20:37:15 -05001030 vector<string> temp_incl_searchpath = g_incl_searchpath;
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001031 if (!old_thrift_include_path.empty()) {
Ben Craig262cfb42015-07-08 20:37:15 -05001032 g_incl_searchpath.push_back(old_thrift_include_path);
1033 }
1034
1035 parse(old_program, NULL);
1036
1037 g_incl_searchpath = temp_incl_searchpath;
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001038 if (!new_thrift_include_path.empty()) {
Ben Craig262cfb42015-07-08 20:37:15 -05001039 g_incl_searchpath.push_back(new_thrift_include_path);
1040 }
1041
1042 parse(new_program, NULL);
1043
1044 compare_namespace(new_program, old_program);
1045 compare_services(new_program->get_services(), old_program->get_services());
1046 compare_enums(new_program->get_enums(), old_program->get_enums());
1047 compare_structs(new_program->get_structs(), old_program->get_structs());
1048 compare_structs(new_program->get_xceptions(), old_program->get_xceptions());
1049 compare_consts(new_program->get_consts(), old_program->get_consts());
1050}
1051
Mark Sleef0712dc2006-10-25 19:03:57 +00001052/**
Mark Sleef5377b32006-10-10 01:42:59 +00001053 * Parse it up.. then spit it back out, in pretty much every language. Alright
1054 * not that many languages, but the cool ones that we care about.
Mark Slee31985722006-05-24 21:45:31 +00001055 */
1056int main(int argc, char** argv) {
1057 int i;
dweatherford65b70752007-10-31 02:18:14 +00001058 std::string out_path;
Bryan Duxburybdca9f62011-03-01 19:53:07 +00001059 bool out_path_is_absolute = false;
Mark Sleef5377b32006-10-10 01:42:59 +00001060
Mark Sleeb15a68b2006-06-07 06:46:24 +00001061 // Setup time string
1062 time_t now = time(NULL);
1063 g_time_str = ctime(&now);
Mark Slee31985722006-05-24 21:45:31 +00001064
Mark Sleef0712dc2006-10-25 19:03:57 +00001065 // Check for necessary arguments, you gotta have at least a filename and
1066 // an output language flag
Mark Sleeb15a68b2006-06-07 06:46:24 +00001067 if (argc < 2) {
1068 usage();
1069 }
Mark Slee31985722006-05-24 21:45:31 +00001070
David Reissbd0db882008-02-27 01:54:51 +00001071 vector<string> generator_strings;
Ben Craig262cfb42015-07-08 20:37:15 -05001072 string old_thrift_include_path;
1073 string new_thrift_include_path;
1074 string old_input_file;
David Reissbd0db882008-02-27 01:54:51 +00001075
David Reiss9cc2c132008-02-27 01:54:47 +00001076 // Set the current path to a dummy value to make warning messages clearer.
1077 g_curpath = "arguments";
1078
Mark Sleef5377b32006-10-10 01:42:59 +00001079 // Hacky parameter handling... I didn't feel like using a library sorry!
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001080 for (i = 1; i < argc - 1; i++) {
Mark Sleefdbee812006-09-27 18:50:48 +00001081 char* arg;
Mark Slee2329a832006-11-09 00:23:30 +00001082
Mark Sleefdbee812006-09-27 18:50:48 +00001083 arg = strtok(argv[i], " ");
1084 while (arg != NULL) {
Mark Slee2329a832006-11-09 00:23:30 +00001085 // Treat double dashes as single dashes
Mark Slee52cb2232006-11-10 22:32:07 +00001086 if (arg[0] == '-' && arg[1] == '-') {
Mark Slee2329a832006-11-09 00:23:30 +00001087 ++arg;
1088 }
1089
Jake Farrell2fd8a152012-09-29 00:26:36 +00001090 if (strcmp(arg, "-help") == 0) {
1091 help();
1092 } else if (strcmp(arg, "-version") == 0) {
David Reissdd08f6d2008-06-30 20:24:24 +00001093 version();
jfarrell70969422013-09-09 20:33:38 -04001094 exit(0);
David Reissdd08f6d2008-06-30 20:24:24 +00001095 } else if (strcmp(arg, "-debug") == 0) {
Mark Sleefdbee812006-09-27 18:50:48 +00001096 g_debug = 1;
Mark Slee2329a832006-11-09 00:23:30 +00001097 } else if (strcmp(arg, "-nowarn") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +00001098 g_warn = 0;
Mark Slee2329a832006-11-09 00:23:30 +00001099 } else if (strcmp(arg, "-strict") == 0) {
Bryan Duxburya145b4d2009-04-03 17:29:25 +00001100 g_strict = 255;
Mark Sleef0712dc2006-10-25 19:03:57 +00001101 g_warn = 2;
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001102 } else if (strcmp(arg, "-v") == 0 || strcmp(arg, "-verbose") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +00001103 g_verbose = 1;
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001104 } else if (strcmp(arg, "-r") == 0 || strcmp(arg, "-recurse") == 0) {
Mark Sleef0712dc2006-10-25 19:03:57 +00001105 gen_recurse = true;
Bryan Duxburyc7206a42011-08-17 23:17:04 +00001106 } else if (strcmp(arg, "-allow-neg-keys") == 0) {
1107 g_allow_neg_field_keys = true;
Roger Meier887ff752011-08-19 11:25:39 +00001108 } else if (strcmp(arg, "-allow-64bit-consts") == 0) {
1109 g_allow_64bit_consts = true;
David Reissbd0db882008-02-27 01:54:51 +00001110 } else if (strcmp(arg, "-gen") == 0) {
1111 arg = argv[++i];
1112 if (arg == NULL) {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001113 fprintf(stderr, "Missing generator specification\n");
David Reissbd0db882008-02-27 01:54:51 +00001114 usage();
1115 }
cyy64750162019-02-08 13:40:59 +08001116 generator_strings.emplace_back(arg);
Martin Kraemer32c66e12006-11-09 00:06:36 +00001117 } else if (strcmp(arg, "-I") == 0) {
1118 // An argument of "-I\ asdf" is invalid and has unknown results
1119 arg = argv[++i];
1120
1121 if (arg == NULL) {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001122 fprintf(stderr, "Missing Include directory\n");
Martin Kraemer32c66e12006-11-09 00:06:36 +00001123 usage();
1124 }
cyy64750162019-02-08 13:40:59 +08001125 g_incl_searchpath.emplace_back(arg);
Bryan Duxburybdca9f62011-03-01 19:53:07 +00001126 } else if ((strcmp(arg, "-o") == 0) || (strcmp(arg, "-out") == 0)) {
1127 out_path_is_absolute = (strcmp(arg, "-out") == 0) ? true : false;
Roger Meier6d7473d2013-05-06 01:08:36 +02001128 arg = argv[++i];
dweatherford65b70752007-10-31 02:18:14 +00001129 if (arg == NULL) {
David Reiss9d866ac2008-06-10 22:56:19 +00001130 fprintf(stderr, "-o: missing output directory\n");
dweatherford65b70752007-10-31 02:18:14 +00001131 usage();
Mark Slee5b743072007-11-13 04:00:29 +00001132 }
dweatherford65b70752007-10-31 02:18:14 +00001133 out_path = arg;
David Reiss204420f2008-01-11 20:59:03 +00001134
Ben Craige9576752013-10-11 08:19:16 -05001135#ifdef _WIN32
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001136 // strip out trailing \ on Windows
Jim King9de9b1f2015-04-30 16:03:34 -04001137 std::string::size_type last = out_path.length() - 1;
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001138 if (out_path[last] == '\\') {
David Reiss204420f2008-01-11 20:59:03 +00001139 out_path.erase(last);
1140 }
1141#endif
Roger Meier061d4a22012-10-07 11:51:00 +00001142 if (!check_is_directory(out_path.c_str()))
dweatherford65b70752007-10-31 02:18:14 +00001143 return -1;
Ben Craig262cfb42015-07-08 20:37:15 -05001144 } else if (strcmp(arg, "-audit") == 0) {
1145 g_audit = true;
1146 arg = argv[++i];
1147 if (arg == NULL) {
1148 fprintf(stderr, "Missing old thrift file name for audit operation\n");
1149 usage();
1150 }
1151 char old_thrift_file_rp[THRIFT_PATH_MAX];
1152
Nobuaki Sukegawad479e232016-02-28 11:28:19 +09001153 // cppcheck-suppress uninitvar
Ben Craig262cfb42015-07-08 20:37:15 -05001154 if (saferealpath(arg, old_thrift_file_rp) == NULL) {
1155 failure("Could not open input file with realpath: %s", arg);
1156 }
1157 old_input_file = string(old_thrift_file_rp);
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001158 } else if (strcmp(arg, "-audit-nofatal") == 0) {
Ben Craig262cfb42015-07-08 20:37:15 -05001159 g_audit_fatal = false;
1160 } else if (strcmp(arg, "-Iold") == 0) {
1161 arg = argv[++i];
1162 if (arg == NULL) {
1163 fprintf(stderr, "Missing Include directory for old thrift file\n");
1164 usage();
1165 }
1166 old_thrift_include_path = string(arg);
1167 } else if (strcmp(arg, "-Inew") == 0) {
1168 arg = argv[++i];
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001169 if (arg == NULL) {
1170 fprintf(stderr, "Missing Include directory for new thrift file\n");
1171 usage();
Ben Craig262cfb42015-07-08 20:37:15 -05001172 }
1173 new_thrift_include_path = string(arg);
Mark Sleefdbee812006-09-27 18:50:48 +00001174 } else {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001175 fprintf(stderr, "Unrecognized option: %s\n", arg);
Mark Sleefdbee812006-09-27 18:50:48 +00001176 usage();
1177 }
1178
1179 // Tokenize more
1180 arg = strtok(NULL, " ");
Mark Slee31985722006-05-24 21:45:31 +00001181 }
1182 }
Mark Slee2c44d202007-05-16 02:18:07 +00001183
Jake Farrell2fd8a152012-09-29 00:26:36 +00001184 // display help
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001185 if ((strcmp(argv[argc - 1], "-help") == 0) || (strcmp(argv[argc - 1], "--help") == 0)) {
Jake Farrell2fd8a152012-09-29 00:26:36 +00001186 help();
1187 }
1188
David Reissdd08f6d2008-06-30 20:24:24 +00001189 // if you're asking for version, you have a right not to pass a file
Konrad Grochowski16a23a62014-11-13 15:33:38 +01001190 if ((strcmp(argv[argc - 1], "-version") == 0) || (strcmp(argv[argc - 1], "--version") == 0)) {
David Reissdd08f6d2008-06-30 20:24:24 +00001191 version();
jfarrell8b1799f2014-04-10 22:06:11 -04001192 exit(0);
David Reissdd08f6d2008-06-30 20:24:24 +00001193 }
1194
Mark Sleef0712dc2006-10-25 19:03:57 +00001195 // Initialize global types
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001196 initGlobals();
Mark Sleee8540632006-05-30 09:24:40 +00001197
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001198 if (g_audit) {
Ben Craig262cfb42015-07-08 20:37:15 -05001199 // Audit operation
Mark Slee31985722006-05-24 21:45:31 +00001200
Ben Craig262cfb42015-07-08 20:37:15 -05001201 if (old_input_file.empty()) {
1202 fprintf(stderr, "Missing file name of old thrift file for audit\n");
1203 usage();
1204 }
David Reiss9cc2c132008-02-27 01:54:47 +00001205
Ben Craig262cfb42015-07-08 20:37:15 -05001206 char new_thrift_file_rp[THRIFT_PATH_MAX];
1207 if (argv[i] == NULL) {
1208 fprintf(stderr, "Missing file name of new thrift file for audit\n");
1209 usage();
1210 }
Nobuaki Sukegawad479e232016-02-28 11:28:19 +09001211 // cppcheck-suppress uninitvar
Ben Craig262cfb42015-07-08 20:37:15 -05001212 if (saferealpath(argv[i], new_thrift_file_rp) == NULL) {
1213 failure("Could not open input file with realpath: %s", argv[i]);
1214 }
1215 string new_input_file(new_thrift_file_rp);
1216
1217 t_program new_program(new_input_file);
1218 t_program old_program(old_input_file);
1219
1220 audit(&new_program, &old_program, new_thrift_include_path, old_thrift_include_path);
1221
1222 } else {
1223 // Generate options
Konrad Grochowski7f4be5f2015-11-05 20:23:11 +01001224
Ben Craig262cfb42015-07-08 20:37:15 -05001225 // You gotta generate something!
1226 if (generator_strings.empty()) {
1227 fprintf(stderr, "No output language(s) specified\n");
1228 usage();
1229 }
1230
1231 // Real-pathify it
1232 char rp[THRIFT_PATH_MAX];
1233 if (argv[i] == NULL) {
1234 fprintf(stderr, "Missing file name\n");
1235 usage();
1236 }
Nobuaki Sukegawad479e232016-02-28 11:28:19 +09001237 // cppcheck-suppress uninitvar
Ben Craig262cfb42015-07-08 20:37:15 -05001238 if (saferealpath(argv[i], rp) == NULL) {
1239 failure("Could not open input file with realpath: %s", argv[i]);
1240 }
1241 string input_file(rp);
1242
1243 // Instance of the global parse tree
1244 t_program* program = new t_program(input_file);
1245 if (out_path.size()) {
1246 program->set_out_path(out_path, out_path_is_absolute);
1247 }
1248
1249 // Compute the cpp include prefix.
1250 // infer this from the filename passed in
1251 string input_filename = argv[i];
1252 string include_prefix;
1253
1254 string::size_type last_slash = string::npos;
1255 if ((last_slash = input_filename.rfind("/")) != string::npos) {
1256 include_prefix = input_filename.substr(0, last_slash);
1257 }
1258
1259 program->set_include_prefix(include_prefix);
1260
1261 // Parse it!
1262 parse(program, NULL);
1263
1264 // The current path is not really relevant when we are doing generation.
1265 // Reset the variable to make warning messages clearer.
1266 g_curpath = "generation";
1267 // Reset yylineno for the heck of it. Use 1 instead of 0 because
1268 // That is what shows up during argument parsing.
1269 yylineno = 1;
1270
1271 // Generate it!
1272 generate(program, generator_strings);
1273 delete program;
1274 }
Mark Sleeb15a68b2006-06-07 06:46:24 +00001275
Mark Sleef0712dc2006-10-25 19:03:57 +00001276 // Clean up. Who am I kidding... this program probably orphans heap memory
1277 // all over the place, but who cares because it is about to exit and it is
1278 // all referenced and used by this wacky parse tree up until now anyways.
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001279 clearGlobals();
Mark Slee31985722006-05-24 21:45:31 +00001280
1281 // Finished
Ben Craig262cfb42015-07-08 20:37:15 -05001282 if (g_return_failure && g_audit_fatal) {
1283 exit(2);
1284 }
Nobuaki Sukegawa11da87e2016-09-10 14:02:19 +09001285 if (g_generator_failure) {
1286 exit(3);
1287 }
Ben Craig262cfb42015-07-08 20:37:15 -05001288 // Finished
Mark Slee31985722006-05-24 21:45:31 +00001289 return 0;
1290}