gravity_parser.c 72 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170
  1. //
  2. // gravity_parser.c
  3. // gravity
  4. //
  5. // Created by Marco Bambini on 01/09/14.
  6. // Copyright (c) 2014 CreoLabs. All rights reserved.
  7. //
  8. #include "gravity_symboltable.h"
  9. #include "gravity_parser.h"
  10. #include "gravity_macros.h"
  11. #include "gravity_lexer.h"
  12. #include "gravity_token.h"
  13. #include "gravity_utils.h"
  14. #include "gravity_array.h"
  15. #include "gravity_core.h"
  16. #include "gravity_ast.h"
  17. typedef marray_t(gravity_lexer_t*) lexer_r;
  18. struct gravity_parser_t {
  19. lexer_r *lexer;
  20. gnode_r *statements;
  21. uint16_r declarations;
  22. gravity_delegate_t *delegate;
  23. double time;
  24. uint32_t nerrors;
  25. uint32_t unique_id;
  26. uint32_t last_error_lineno;
  27. // state ivars used by Pratt parser
  28. gtoken_t current_token;
  29. gnode_t *current_node;
  30. };
  31. // MARK: - PRATT parser specs -
  32. // http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
  33. // http://javascript.crockford.com/tdop/tdop.html
  34. // Precedence table as defined in Swift
  35. // http://nshipster.com/swift-operators/
  36. typedef enum {
  37. PREC_LOWEST,
  38. PREC_ASSIGN = 90, // = *= /= %= += -= <<= >>= &= ^= |= (11 cases)
  39. PREC_TERNARY = 100, // ?: (1 case)
  40. PREC_LOGICAL_OR = 110, // || (1 case)
  41. PREC_LOGICAL_AND = 120, // && (1 case)
  42. PREC_COMPARISON = 130, // < <= > >= == != === !== ~= (9 cases)
  43. PREC_ISA = 132, // isa (1 case)
  44. PREC_RANGE = 135, // ..< ... (2 cases)
  45. PREC_TERM = 140, // + - | ^ (4 cases)
  46. PREC_FACTOR = 150, // * / % & (4 cases)
  47. PREC_SHIFT = 160, // << >> (2 cases)
  48. PREC_UNARY = 170, // + - ! ~ (4 cases)
  49. PREC_CALL = 200 // . ( [ (3 cases)
  50. } prec_level;
  51. typedef gnode_t* (*parse_func) (gravity_parser_t *parser);
  52. typedef struct {
  53. parse_func prefix;
  54. parse_func infix;
  55. prec_level precedence;
  56. const char *name;
  57. bool right;
  58. } grammar_rule;
  59. // This table defines all of the parsing rules for the prefix and infix expressions in the grammar.
  60. #define RULE(prec, fn1, fn2) (grammar_rule){ fn1, fn2, prec, NULL, false}
  61. #define PREFIX(prec, fn) (grammar_rule){ fn, NULL, prec, NULL, false}
  62. #define INFIX(prec, fn) (grammar_rule){ NULL, fn, prec, NULL, false}
  63. #define INFIX_OPERATOR(prec, name) (grammar_rule){ NULL, parse_infix, prec, name, false}
  64. #define INFIX_OPERATOR_RIGHT(prec,name) (grammar_rule){ NULL, parse_infix, prec, name, true}
  65. #define PREFIX_OPERATOR(name) (grammar_rule){ parse_unary, NULL, PREC_LOWEST, name, false}
  66. #define OPERATOR(prec, name) (grammar_rule){ parse_unary, parse_infix, prec, name, false}
  67. // Global singleton grammar rule table
  68. static grammar_rule rules[TOK_END];
  69. // MARK: - Internal macros -
  70. #define SEMICOLON_IS_OPTIONAL 1
  71. #define REPORT_ERROR(_tok,...) report_error(parser, GRAVITY_ERROR_SYNTAX, _tok, __VA_ARGS__)
  72. #define REPORT_WARNING(_tok,...) report_error(parser, GRAVITY_WARNING, _tok, __VA_ARGS__)
  73. #define PUSH_DECLARATION(_decl) marray_push(uint16_t, parser->declarations, (uint16_t)_decl)
  74. #define PUSH_FUNCTION_DECLARATION() PUSH_DECLARATION(NODE_FUNCTION_DECL)
  75. #define PUSH_CLASS_DECLARATION() PUSH_DECLARATION(NODE_CLASS_DECL)
  76. #define POP_DECLARATION() marray_pop(parser->declarations)
  77. #define LAST_DECLARATION() (marray_size(parser->declarations) ? marray_last(parser->declarations) : 0)
  78. #define IS_FUNCTION_ENCLOSED() (LAST_DECLARATION() == NODE_FUNCTION_DECL)
  79. #define IS_CLASS_ENCLOSED() (LAST_DECLARATION() == NODE_CLASS_DECL)
  80. #define CHECK_NODE(_n) if (!_n) return NULL
  81. #define POP_LEXER (gravity_lexer_t *)marray_pop(*parser->lexer)
  82. #define CURRENT_LEXER (gravity_lexer_t *)marray_last(*parser->lexer)
  83. #define DECLARE_LEXER gravity_lexer_t *lexer = CURRENT_LEXER; DEBUG_LEXER(lexer)
  84. #define STATIC_TOKEN_CSTRING(_s,_n,_l,_b,_t) char _s[_n] = {0}; uint32_t _l = 0; \
  85. const char *_b = token_string(_t, &_l); \
  86. if (_l) memcpy(_s, _b, MINNUM(_n, _l))
  87. // MARK: - Prototypes -
  88. static const char *parse_identifier (gravity_parser_t *parser);
  89. static gnode_t *parse_statement (gravity_parser_t *parser);
  90. static gnode_r *parse_optional_parameter_declaration (gravity_parser_t *parser);
  91. static gnode_t *parse_compound_statement (gravity_parser_t *parser);
  92. static gnode_t *parse_expression (gravity_parser_t *parser);
  93. static gnode_t *parse_declaration_statement (gravity_parser_t *parser);
  94. static gnode_t *parse_function (gravity_parser_t *parser, bool is_declaration, gtoken_t access_specifier, gtoken_t storage_specifier);
  95. static gnode_t *adjust_assignment_expression (gtoken_t tok, gnode_t *lnode, gnode_t *rnode);
  96. // MARK: - Utils functions -
  97. static void report_error (gravity_parser_t *parser, error_type_t error_type, gtoken_s token, const char *format, ...) {
  98. // consider just one error for each line;
  99. if (parser->last_error_lineno == token.lineno) return;
  100. parser->last_error_lineno = token.lineno;
  101. // increment internal error counter
  102. ++parser->nerrors;
  103. // get error callback (if any)
  104. void *data = (parser->delegate) ? parser->delegate->xdata : NULL;
  105. gravity_error_callback error_fn = (parser->delegate) ? ((gravity_delegate_t *)parser->delegate)->error_callback : NULL;
  106. // build error message
  107. char buffer[1024];
  108. va_list arg;
  109. if (format) {
  110. va_start (arg, format);
  111. vsnprintf(buffer, sizeof(buffer), format, arg);
  112. va_end (arg);
  113. }
  114. // setup error struct
  115. error_desc_t error_desc = {
  116. .code = 0,
  117. .lineno = token.lineno,
  118. .colno = token.colno,
  119. .fileid = token.fileid,
  120. .offset = token.position
  121. };
  122. // finally call error callback
  123. if (error_fn) error_fn(error_type, buffer, error_desc, data);
  124. else printf("%s\n", buffer);
  125. }
  126. static gnode_t *parse_error (gravity_parser_t *parser) {
  127. DECLARE_LEXER;
  128. gravity_lexer_next(lexer);
  129. gtoken_s token = gravity_lexer_token(lexer);
  130. REPORT_ERROR(token, "%s", token.value);
  131. return NULL;
  132. }
  133. // RETURN:
  134. // - true if next token is equal to token passed as parameter (token is also consumed)
  135. // - false if next token is not equal (and no error is reported)
  136. //
  137. static bool parse_optional (gravity_parser_t *parser, gtoken_t token) {
  138. DECLARE_LEXER;
  139. gtoken_t peek = gravity_lexer_peek(lexer);
  140. if (token_iserror(peek)) {
  141. parse_error(parser);
  142. peek = gravity_lexer_peek(lexer);
  143. }
  144. if (peek == token) {
  145. gravity_lexer_next(lexer); // consume expected token
  146. return true;
  147. }
  148. // do not report any error in this case
  149. return false;
  150. }
  151. static bool parse_required (gravity_parser_t *parser, gtoken_t token) {
  152. if (parse_optional(parser, token)) return true;
  153. // token not found (and not consumed) so an error strategy must be implemented here
  154. // simple (but not simpler) error recovery
  155. // parser should keep track of what I am parsing
  156. // so based on tok I could have a token list of terminal symbols
  157. // call next until first sync symbol (or EOF or start of another terminal symbol is found)
  158. // simple error recovery, just consume next and report error
  159. DECLARE_LEXER;
  160. gtoken_t next = gravity_lexer_next(lexer);
  161. gtoken_s unexpected_token = gravity_lexer_token(lexer);
  162. REPORT_ERROR(unexpected_token, "Expected %s but found %s.", token_name(token), token_name(next));
  163. return false;
  164. }
  165. static bool parse_semicolon (gravity_parser_t *parser) {
  166. #if SEMICOLON_IS_OPTIONAL
  167. DECLARE_LEXER;
  168. if (gravity_lexer_peek(lexer) == TOK_OP_SEMICOLON) {gravity_lexer_next(lexer); return true;}
  169. return false;
  170. #else
  171. return parse_required(parser, TOK_OP_SEMICOLON);
  172. #endif
  173. }
  174. gnode_t *parse_function (gravity_parser_t *parser, bool is_declaration, gtoken_t access_specifier, gtoken_t storage_specifier) {
  175. DECLARE_LEXER;
  176. // access_specifier? storage_specifier? already parsed
  177. // 'function' IDENTIFIER '(' parameter_declaration_clause? ')' compound_statement
  178. // consume FUNC keyword (or peek for OPEN_CURLYBRACE)
  179. bool is_implicit = (gravity_lexer_peek(lexer) == TOK_OP_OPEN_CURLYBRACE);
  180. gtoken_s token = gravity_lexer_token(lexer);
  181. if (!is_implicit) {
  182. gtoken_t type = gravity_lexer_next(lexer);
  183. token = gravity_lexer_token(lexer);
  184. assert(type == TOK_KEY_FUNC);
  185. }
  186. // parse IDENTIFIER
  187. const char *identifier = NULL;
  188. if (is_declaration) {
  189. gtoken_t peek = gravity_lexer_peek(lexer);
  190. if (token_isoperator(peek)) {
  191. gravity_lexer_next(lexer);
  192. identifier = string_dup(token_name(peek));
  193. } else {
  194. identifier = parse_identifier(parser);
  195. }
  196. DEBUG_PARSER("parse_function_declaration %s", identifier);
  197. }
  198. // check and consume TOK_OP_OPEN_PARENTHESIS
  199. if (!is_implicit) parse_required(parser, TOK_OP_OPEN_PARENTHESIS);
  200. // parse optional parameter declaration clause
  201. gnode_r *params = (!is_implicit) ? parse_optional_parameter_declaration(parser) : NULL;
  202. // check and consume TOK_OP_CLOSED_PARENTHESIS
  203. if (!is_implicit) parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  204. // parse compound statement
  205. PUSH_FUNCTION_DECLARATION();
  206. gnode_compound_stmt_t *compound = (gnode_compound_stmt_t*)parse_compound_statement(parser);
  207. POP_DECLARATION();
  208. // parse optional semicolon
  209. parse_semicolon(parser);
  210. return gnode_function_decl_create(token, identifier, access_specifier, storage_specifier, params, compound);
  211. }
  212. static char *cstring_from_token (gravity_parser_t *parser, gtoken_s token) {
  213. #pragma unused(parser)
  214. uint32_t len = 0;
  215. const char *buffer = token_string(token, &len);
  216. char *str = (char *)mem_alloc(len+1);
  217. memcpy(str, buffer, len);
  218. return str;
  219. }
  220. static gnode_t *local_store_declaration (const char *identifier, gtoken_t access_specifier, gtoken_t storage_specifier, gnode_t *declaration) {
  221. gnode_r *decls = gnode_array_create();
  222. gnode_t *decl = gnode_variable_create(declaration->token, identifier ? string_dup(identifier) : NULL, NULL, access_specifier, declaration);
  223. gnode_array_push(decls, decl);
  224. return gnode_variable_decl_create(declaration->token, TOK_KEY_VAR, access_specifier, storage_specifier, decls);
  225. }
  226. static gliteral_t decode_number_binary (gtoken_s token, int64_t *n) {
  227. // from 2 in order to skip 0b
  228. *n = number_from_bin(&token.value[2], token.bytes-2);
  229. return LITERAL_INT;
  230. }
  231. static gliteral_t decode_number_octal (gtoken_s token, int64_t *n) {
  232. STATIC_TOKEN_CSTRING(str, 512, len, buffer, token);
  233. if (len) *n = (int64_t) number_from_oct(&str[2], len-2);
  234. return LITERAL_INT;
  235. }
  236. static gliteral_t decode_number_hex (gtoken_s token, int64_t *n, double *d) {
  237. #pragma unused(d)
  238. STATIC_TOKEN_CSTRING(str, 512, len, buffer, token);
  239. if (len) *n = (int64_t) number_from_hex(str, token.bytes);
  240. return LITERAL_INT;
  241. }
  242. // MARK: - Expressions -
  243. static gnode_t *parse_ternary_expression (gravity_parser_t *parser) {
  244. DEBUG_PARSER("parse_ternary_expression");
  245. DECLARE_LEXER;
  246. // conditional expression already parsed
  247. gnode_t *cond = parser->current_node;
  248. if (!cond) return NULL;
  249. // '?' expression ':' expression
  250. // '?' already consumed
  251. gtoken_s token = gravity_lexer_token(lexer);
  252. // parse expression 1
  253. gnode_t *expr1 = parse_expression(parser);
  254. CHECK_NODE(expr1);
  255. parse_required(parser, TOK_OP_COLON);
  256. // parse expression 2
  257. gnode_t *expr2 = parse_expression(parser);
  258. CHECK_NODE(expr2);
  259. return gnode_flow_stat_create(token, cond, expr1, expr2);
  260. }
  261. static gnode_t *parse_file_expression (gravity_parser_t *parser) {
  262. DEBUG_PARSER("parse_file_expression");
  263. DECLARE_LEXER;
  264. // at least one identifier is mandatory
  265. // 'file' ('.' IDENTIFIER)+
  266. gravity_lexer_next(lexer);
  267. gtoken_s token = gravity_lexer_token(lexer);
  268. if (gravity_lexer_peek(lexer) != TOK_OP_DOT) {
  269. REPORT_ERROR(token, "A .identifier list is expected here.");
  270. return NULL;
  271. }
  272. cstring_r *list = cstring_array_create();
  273. while (gravity_lexer_peek(lexer) == TOK_OP_DOT) {
  274. gravity_lexer_next(lexer); // consume TOK_OP_DOT
  275. const char *identifier = parse_identifier(parser);
  276. if (!identifier) return NULL;
  277. cstring_array_push(list, identifier);
  278. }
  279. return gnode_file_expr_create(token, list);
  280. }
  281. static const char *parse_identifier (gravity_parser_t *parser) {
  282. DECLARE_LEXER;
  283. // parse IDENTIFIER is always mandatory
  284. gtoken_t type = gravity_lexer_peek(lexer);
  285. if (type != TOK_IDENTIFIER) {
  286. if (type == TOK_ERROR) parse_error(parser);
  287. else REPORT_ERROR(gravity_lexer_token(lexer), "Expected identifier but found %s", token_name(type));
  288. return NULL;
  289. }
  290. gravity_lexer_next(lexer);
  291. gtoken_s token = gravity_lexer_token(lexer);
  292. const char *identifier = cstring_from_token(parser, token);
  293. return identifier;
  294. }
  295. static const char *parse_optional_type_annotation (gravity_parser_t *parser) {
  296. DECLARE_LEXER;
  297. const char *type_annotation = NULL;
  298. gtoken_t peek = gravity_lexer_peek(lexer);
  299. // type annotation
  300. // function foo (a: string, b: number)
  301. // check for optional type_annotation
  302. if (peek == TOK_OP_COLON) {
  303. gravity_lexer_next(lexer); // consume TOK_OP_COLON
  304. // parse identifier
  305. type_annotation = parse_identifier(parser);
  306. if (!type_annotation) return NULL;
  307. }
  308. return type_annotation;
  309. }
  310. static gnode_t *parse_parentheses_expression (gravity_parser_t *parser) {
  311. DEBUG_PARSER("parse_parentheses_expression");
  312. // check and consume TOK_OP_OPEN_PARENTHESIS
  313. parse_required(parser, TOK_OP_OPEN_PARENTHESIS);
  314. // parse expression
  315. gnode_t *expr = parse_expression(parser);
  316. CHECK_NODE(expr);
  317. // check and consume TOK_OP_CLOSED_PARENTHESIS
  318. parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  319. return expr;
  320. }
  321. static gnode_t *parse_list_expression (gravity_parser_t *parser) {
  322. DEBUG_PARSER("parse_list_expression");
  323. DECLARE_LEXER;
  324. /*
  325. list_expression
  326. : '[' ((expression) (',' expression)*)? ']' // array or empty array
  327. | '[' ((map_entry (',' map_entry)*) | ':') ']' // map or empty map
  328. ;
  329. map_entry
  330. : STRING ':' expression
  331. ;
  332. */
  333. // consume first '['
  334. parse_required(parser, TOK_OP_OPEN_SQUAREBRACKET);
  335. // this saved token is necessary to save start of the list/map
  336. gtoken_s token = gravity_lexer_token(lexer);
  337. // check for special empty list
  338. if (gravity_lexer_peek(lexer) == TOK_OP_CLOSED_SQUAREBRACKET) {
  339. gravity_lexer_next(lexer); // consume TOK_OP_CLOSED_SQUAREBRACKET
  340. return gnode_list_expr_create(token, NULL, NULL, false);
  341. }
  342. // check for special empty map
  343. if (gravity_lexer_peek(lexer) == TOK_OP_COLON) {
  344. gravity_lexer_next(lexer); // consume TOK_OP_COLON
  345. parse_required(parser, TOK_OP_CLOSED_SQUAREBRACKET);
  346. return gnode_list_expr_create(token, NULL, NULL, true);
  347. }
  348. // parse first expression (if any) outside of the list/map loop
  349. // in order to check if it is a list or map expression
  350. gnode_t *expr1 = parse_expression(parser);
  351. // if next token is a colon then assume a map
  352. bool ismap = (gravity_lexer_peek(lexer) == TOK_OP_COLON);
  353. // a list expression can be an array [expr1, expr2] or a map [string1: expr1, string2: expr2]
  354. // cannot be mixed so be very restrictive here
  355. gnode_r *list1 = gnode_array_create();
  356. gnode_r *list2 = (ismap) ? gnode_array_create() : NULL;
  357. if (expr1) gnode_array_push(list1, expr1);
  358. if (ismap) {
  359. parse_required(parser, TOK_OP_COLON);
  360. gnode_t *expr2 = parse_expression(parser);
  361. if (expr2) gnode_array_push(list2, expr2);
  362. }
  363. while (gravity_lexer_peek(lexer) == TOK_OP_COMMA) {
  364. gravity_lexer_next(lexer); // consume TOK_OP_COMMA
  365. // parse first expression
  366. expr1 = parse_expression(parser);
  367. if (expr1) gnode_array_push(list1, expr1);
  368. if (ismap) {
  369. parse_required(parser, TOK_OP_COLON);
  370. gnode_t *expr2 = parse_expression(parser);
  371. if (expr2) gnode_array_push(list2, expr2);
  372. }
  373. }
  374. parse_required(parser, TOK_OP_CLOSED_SQUAREBRACKET);
  375. return gnode_list_expr_create(token, list1, list2, ismap);
  376. }
  377. static gnode_t *parse_function_expression (gravity_parser_t *parser) {
  378. DEBUG_PARSER("parse_function_expression");
  379. // 'func' '(' parameter_declaration_clause? ')' compound_statement
  380. // or
  381. // compound_statement (implicit func and implicit parameters)
  382. /*
  383. example:
  384. func foo () {
  385. var bar = func(x) {return x*2;}
  386. return bar(3);
  387. }
  388. it is equivalent to:
  389. func foo () {
  390. func bar(x) {return x*2;}
  391. return bar(3);
  392. }
  393. */
  394. // check if func is a function expression or
  395. // if it is a func keyword used to refers to
  396. // the current executing function
  397. return parse_function(parser, false, 0, 0);
  398. }
  399. static gnode_t *parse_identifier_expression (gravity_parser_t *parser) {
  400. DEBUG_PARSER("parse_identifier_expression");
  401. DECLARE_LEXER;
  402. const char *identifier = parse_identifier(parser);
  403. if (!identifier) return NULL;
  404. DEBUG_PARSER("IDENTIFIER: %s", identifier);
  405. gtoken_s token = gravity_lexer_token(lexer);
  406. return gnode_identifier_expr_create(token, identifier, NULL);
  407. }
  408. static gnode_t *parse_number_expression (gtoken_s token) {
  409. DEBUG_PARSER("parse_number_expression");
  410. // what I know here is that token is a well formed NUMBER
  411. // so I just need to properly decode it
  412. const char *value = token.value;
  413. gliteral_t type;
  414. int64_t n = 0;
  415. double d = 0;
  416. if (value[0] == '0') {
  417. int c = toupper(value[1]);
  418. if (c == 'B') {type = decode_number_binary(token, &n); goto report_node;}
  419. else if (c == 'O') {type = decode_number_octal(token, &n); goto report_node;}
  420. else if (c == 'X') {type = decode_number_hex(token, &n, &d); goto report_node;}
  421. }
  422. // number is decimal (check if is float)
  423. bool isfloat = false;
  424. for (uint32_t i=0; i<token.bytes; ++i) {
  425. if (value[i] == '.') {isfloat = true; break;}
  426. }
  427. STATIC_TOKEN_CSTRING(str, 512, len, buffer, token);
  428. if (isfloat) {
  429. d = strtod(str, NULL);
  430. type = LITERAL_FLOAT;
  431. DEBUG_PARSER("FLOAT: %.2f", d);
  432. }
  433. else {
  434. n = (int64_t) strtoll(str, NULL, 0);
  435. type = LITERAL_INT;
  436. DEBUG_PARSER("INT: %lld", n);
  437. }
  438. report_node:
  439. if (type == LITERAL_FLOAT) return gnode_literal_float_expr_create(token, (double)d);
  440. else if (type == LITERAL_INT) return gnode_literal_int_expr_create(token, n);
  441. else assert(0);
  442. return NULL;
  443. }
  444. static gnode_t *parse_literal_expression (gravity_parser_t *parser) {
  445. DEBUG_PARSER("parse_literal_expression");
  446. DECLARE_LEXER;
  447. gtoken_t type = gravity_lexer_next(lexer);
  448. gtoken_s token = gravity_lexer_token(lexer);
  449. if (type == TOK_STRING) {
  450. uint32_t len = 0;
  451. const char *value = token_string(token, &len);
  452. DEBUG_PARSER("STRING: %.*s", len, value);
  453. return gnode_literal_string_expr_create(token, value, len);
  454. }
  455. if (type == TOK_KEY_TRUE || type == TOK_KEY_FALSE) {
  456. return gnode_literal_bool_expr_create(token, (int32_t)(type == TOK_KEY_TRUE) ? 1 : 0);
  457. }
  458. if (type != TOK_NUMBER) {
  459. REPORT_ERROR(token, "Expected literal expression but found %s.", token_name(type));
  460. return NULL;
  461. }
  462. return parse_number_expression(token);
  463. }
  464. static gnode_t *parse_keyword_expression (gravity_parser_t *parser) {
  465. DEBUG_PARSER("parse_keyword_expression");
  466. DECLARE_LEXER;
  467. gravity_lexer_next(lexer);
  468. gtoken_s token = gravity_lexer_token(lexer);
  469. return gnode_keyword_expr_create(token);
  470. }
  471. static gnode_r *parse_arguments_expression (gravity_parser_t *parser) {
  472. DEBUG_PARSER("parse_call_expression_list");
  473. DECLARE_LEXER;
  474. // it's OK for a call_expression_list to be empty
  475. if (gravity_lexer_peek(lexer) == TOK_OP_CLOSED_PARENTHESIS) return NULL;
  476. gnode_r *list = gnode_array_create();
  477. while (1) {
  478. gtoken_t peek = gravity_lexer_peek(lexer);
  479. if (peek == TOK_OP_COMMA) {
  480. // added the ability to convert ,, to ,undefined,
  481. gnode_array_push(list, gnode_keyword_expr_create(UNDEF_TOKEN));
  482. // consume next TOK_OP_COMMA and check for special ,) case
  483. gravity_lexer_next(lexer);
  484. if (gravity_lexer_peek(lexer) == TOK_OP_CLOSED_PARENTHESIS) gnode_array_push(list, gnode_keyword_expr_create(UNDEF_TOKEN));
  485. } else {
  486. // check exit condition
  487. if ((peek == TOK_EOF) || (peek == TOK_OP_CLOSED_PARENTHESIS)) break;
  488. // parse expression
  489. gnode_t *expr = parse_expression(parser);
  490. if (expr) gnode_array_push(list, expr);
  491. // consume next TOK_OP_COMMA and check for special ,) case
  492. if (gravity_lexer_peek(lexer) == TOK_OP_COMMA) {
  493. gravity_lexer_next(lexer);
  494. if (gravity_lexer_peek(lexer) == TOK_OP_CLOSED_PARENTHESIS) gnode_array_push(list, gnode_keyword_expr_create(UNDEF_TOKEN));
  495. }
  496. }
  497. }
  498. return list;
  499. }
  500. static gnode_t *parse_postfix_expression (gravity_parser_t *parser, gtoken_t tok) {
  501. DEBUG_PARSER("parse_postfix_expression");
  502. DECLARE_LEXER;
  503. // '[' assignment_expression ']' => Subscript operator
  504. // '(' expression_list? ')' => Function call operator
  505. // '.' IDENTIFIER => Member access operator
  506. // tok already consumed and used to identify postfix sub-expression
  507. gnode_t *lnode = parser->current_node;
  508. gtoken_s token = gravity_lexer_token(lexer);
  509. // a postfix expression is an expression followed by a list of other expressions (separated by specific tokens)
  510. gnode_r *list = gnode_array_create();
  511. while (1) {
  512. gnode_t *node = NULL;
  513. if (tok == TOK_OP_OPEN_SQUAREBRACKET) {
  514. gnode_t *expr = parse_expression(parser);
  515. gtoken_s subtoken = gravity_lexer_token(lexer);
  516. parse_required(parser, TOK_OP_CLOSED_SQUAREBRACKET);
  517. node = gnode_postfix_subexpr_create(subtoken, NODE_SUBSCRIPT_EXPR, expr, NULL);
  518. } else if (tok == TOK_OP_OPEN_PARENTHESIS) {
  519. gnode_r *args = parse_arguments_expression(parser); // can be NULL and it's OK
  520. gtoken_s subtoken = gravity_lexer_token(lexer);
  521. parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  522. node = gnode_postfix_subexpr_create(subtoken, NODE_CALL_EXPR, NULL, args);
  523. } else if (tok == TOK_OP_DOT) {
  524. gnode_t *expr = parse_identifier_expression(parser);
  525. gtoken_s subtoken = gravity_lexer_token(lexer);
  526. node = gnode_postfix_subexpr_create(subtoken, NODE_ACCESS_EXPR, expr, NULL);
  527. } else {
  528. // should never reach this point
  529. assert(0);
  530. }
  531. // add subnode to list
  532. gnode_array_push(list, node);
  533. // check if postifx expression has more sub-nodes
  534. gtoken_t peek = gravity_lexer_peek(lexer);
  535. if ((peek != TOK_OP_OPEN_SQUAREBRACKET) && (peek != TOK_OP_OPEN_PARENTHESIS) && (peek != TOK_OP_DOT)) break;
  536. tok = gravity_lexer_next(lexer);
  537. }
  538. return gnode_postfix_expr_create(token, lnode, list);
  539. }
  540. static gnode_t *parse_postfix_subscript (gravity_parser_t *parser) {
  541. // NOTE:
  542. // Gravity does not support a syntax like m[1,2] for matrix access (not m[1,2,3])
  543. // but it supports a syntax like m[1][2] (or m[1][2][3])
  544. DEBUG_PARSER("parse_postfix_subscript");
  545. return parse_postfix_expression(parser, TOK_OP_OPEN_SQUAREBRACKET);
  546. }
  547. static gnode_t *parse_postfix_access (gravity_parser_t *parser) {
  548. DEBUG_PARSER("parse_postfix_access");
  549. return parse_postfix_expression(parser, TOK_OP_DOT);
  550. }
  551. static gnode_t *parse_postfix_call (gravity_parser_t *parser) {
  552. DEBUG_PARSER("parse_postfix_call");
  553. return parse_postfix_expression(parser, TOK_OP_OPEN_PARENTHESIS);
  554. }
  555. static gnode_t *parse_precedence(gravity_parser_t *parser, prec_level precedence) {
  556. DEBUG_PARSER("parse_precedence (level %d)", precedence);
  557. DECLARE_LEXER;
  558. // peek next
  559. gtoken_t type = gravity_lexer_peek(lexer);
  560. if (type == TOK_EOF) return NULL;
  561. parse_func prefix = rules[type].prefix;
  562. if (prefix == NULL) {
  563. // gravity_lexer_token reports the latest succesfully scanned token but since we need to report
  564. // an error for a peeked token then we force reporting "next" token
  565. REPORT_ERROR(gravity_lexer_token_next(lexer), "Expected expression but found %s.", token_name(type));
  566. return NULL;
  567. }
  568. gnode_t *node = prefix(parser);
  569. gtoken_t peek = gravity_lexer_peek(lexer);
  570. if (peek == TOK_EOF) return NULL;
  571. while (precedence < rules[peek].precedence) {
  572. gtoken_t tok = gravity_lexer_next(lexer);
  573. grammar_rule *rule = &rules[tok];
  574. parser->current_token = tok;
  575. parser->current_node = node;
  576. node = rule->infix(parser);
  577. peek = gravity_lexer_peek(lexer);
  578. if (peek == TOK_EOF) return NULL;
  579. }
  580. return node;
  581. }
  582. static gnode_t *parse_expression (gravity_parser_t *parser) {
  583. DEBUG_PARSER("parse_expression");
  584. DECLARE_LEXER;
  585. // parse_expression is the default case called when no other case in parse_statament can be resolved
  586. // due to some syntax errors an infinte loop condition can be verified
  587. gtoken_s tok1 = gravity_lexer_token(lexer);
  588. gnode_t *expr = parse_precedence(parser, PREC_LOWEST);
  589. // expr is NULL means than an error condition has been encountered (and a potential infite loop)
  590. if (expr == NULL) {
  591. gtoken_s tok2 = gravity_lexer_token(lexer);
  592. // if current token is equal to the token saved before the recursion than skip token in order to avoid infinite loop
  593. if (token_identical(&tok1, &tok2)) gravity_lexer_next(lexer);
  594. }
  595. return expr;
  596. }
  597. static gnode_t *parse_unary (gravity_parser_t *parser) {
  598. DEBUG_PARSER("parse_unary");
  599. DECLARE_LEXER;
  600. gtoken_t tok = gravity_lexer_next(lexer);
  601. gnode_t *node = parse_precedence(parser, PREC_UNARY);
  602. return gnode_unary_expr_create(tok, node);
  603. }
  604. static gnode_t *parse_infix (gravity_parser_t *parser) {
  605. DEBUG_PARSER("parse_infix");
  606. gtoken_t tok = parser->current_token;
  607. gnode_t *lnode = parser->current_node;
  608. // we can make right associative operators by reducing the right binding power
  609. grammar_rule *rule = &rules[tok];
  610. prec_level precedence = (rule->right) ? rule->precedence-1 : rule->precedence;
  611. gnode_t *rnode = parse_precedence(parser, precedence);
  612. if ((tok != TOK_OP_ASSIGN) && token_isassignment(tok)) return adjust_assignment_expression(tok, lnode, rnode);
  613. return gnode_binary_expr_create(tok, lnode, rnode);
  614. }
  615. // MARK: -
  616. static gnode_t *adjust_assignment_expression (gtoken_t tok, gnode_t *lnode, gnode_t *rnode) {
  617. DEBUG_PARSER("adjust_assignment_expression");
  618. // called when tok is an assignment != TOK_OP_ASSIGN
  619. // convert expressions:
  620. // a += 1 => a = a + 1
  621. // a -= 1 => a = a - 1
  622. // a *= 1 => a = a * 1
  623. // a /= 1 => a = a / 1
  624. // a %= 1 => a = a % 1
  625. // a <<=1 => a = a << 1
  626. // a >>=1 => a = a >> 1
  627. // a &= 1 => a = a & 1
  628. // a |= 1 => a = a | 1
  629. // a ^= 1 => a = a ^ 1
  630. gtoken_t t;
  631. switch (tok) {
  632. case TOK_OP_MUL_ASSIGN: t = TOK_OP_MUL; break;
  633. case TOK_OP_DIV_ASSIGN: t = TOK_OP_DIV; break;
  634. case TOK_OP_REM_ASSIGN: t = TOK_OP_REM; break;
  635. case TOK_OP_ADD_ASSIGN: t = TOK_OP_ADD; break;
  636. case TOK_OP_SUB_ASSIGN: t = TOK_OP_SUB; break;
  637. case TOK_OP_SHIFT_LEFT_ASSIGN: t = TOK_OP_SHIFT_LEFT; break;
  638. case TOK_OP_SHIFT_RIGHT_ASSIGN: t = TOK_OP_SHIFT_RIGHT; break;
  639. case TOK_OP_BIT_AND_ASSIGN: t = TOK_OP_BIT_AND; break;
  640. case TOK_OP_BIT_OR_ASSIGN: t = TOK_OP_BIT_OR; break;
  641. case TOK_OP_BIT_XOR_ASSIGN: t = TOK_OP_BIT_XOR; break;
  642. // should never reach this point
  643. default: assert(0); break;
  644. }
  645. // duplicate node is mandatory here, otherwise the deallocator will try to free memory occopied by the same node twice
  646. rnode = gnode_binary_expr_create(t, gnode_duplicate(lnode, true), rnode);
  647. tok = TOK_OP_ASSIGN;
  648. // its an assignment expression so switch the order
  649. return gnode_binary_expr_create(tok, lnode, rnode);
  650. }
  651. static void init_grammer_rules (void) {
  652. static bool created = false;
  653. if (created) return;
  654. created = true;
  655. // rules is a static variable initialized to 0
  656. // so we automatically have all members initialized to UNUSED
  657. rules[TOK_OP_OPEN_PARENTHESIS] = RULE(PREC_CALL, parse_parentheses_expression, parse_postfix_call);
  658. rules[TOK_OP_OPEN_SQUAREBRACKET] = RULE(PREC_CALL, parse_list_expression, parse_postfix_subscript);
  659. rules[TOK_OP_DOT] = RULE(PREC_CALL, parse_literal_expression, parse_postfix_access);
  660. rules[TOK_OP_OPEN_CURLYBRACE] = PREFIX(PREC_LOWEST, parse_function_expression);
  661. rules[TOK_KEY_FUNC] = PREFIX(PREC_LOWEST, parse_function_expression);
  662. rules[TOK_IDENTIFIER] = PREFIX(PREC_LOWEST, parse_identifier_expression);
  663. rules[TOK_STRING] = PREFIX(PREC_LOWEST, parse_literal_expression);
  664. rules[TOK_NUMBER] = PREFIX(PREC_LOWEST, parse_literal_expression);
  665. rules[TOK_KEY_UNDEFINED] = PREFIX(PREC_LOWEST, parse_keyword_expression);
  666. rules[TOK_KEY_CURRARGS] = PREFIX(PREC_LOWEST, parse_keyword_expression);
  667. rules[TOK_KEY_CURRFUNC] = PREFIX(PREC_LOWEST, parse_keyword_expression);
  668. rules[TOK_KEY_SUPER] = PREFIX(PREC_LOWEST, parse_keyword_expression);
  669. rules[TOK_KEY_FILE] = PREFIX(PREC_LOWEST, parse_file_expression);
  670. rules[TOK_KEY_NULL] = PREFIX(PREC_LOWEST, parse_keyword_expression);
  671. rules[TOK_KEY_TRUE] = PREFIX(PREC_LOWEST, parse_keyword_expression);
  672. rules[TOK_KEY_FALSE] = PREFIX(PREC_LOWEST, parse_keyword_expression);
  673. rules[TOK_OP_SHIFT_LEFT] = INFIX_OPERATOR(PREC_SHIFT, "<<");
  674. rules[TOK_OP_SHIFT_RIGHT] = INFIX_OPERATOR(PREC_SHIFT, ">>");
  675. rules[TOK_OP_MUL] = INFIX_OPERATOR(PREC_FACTOR, "*");
  676. rules[TOK_OP_DIV] = INFIX_OPERATOR(PREC_FACTOR, "/");
  677. rules[TOK_OP_REM] = INFIX_OPERATOR(PREC_FACTOR, "%");
  678. rules[TOK_OP_BIT_AND] = INFIX_OPERATOR(PREC_FACTOR, "&");
  679. rules[TOK_OP_ADD] = OPERATOR(PREC_TERM, "+");
  680. rules[TOK_OP_SUB] = OPERATOR(PREC_TERM, "-");
  681. rules[TOK_OP_BIT_OR] = INFIX_OPERATOR(PREC_TERM, "|");
  682. rules[TOK_OP_BIT_XOR] = INFIX_OPERATOR(PREC_TERM, "^");
  683. rules[TOK_OP_BIT_NOT] = PREFIX_OPERATOR("~");
  684. rules[TOK_OP_RANGE_EXCLUDED] = INFIX_OPERATOR(PREC_RANGE, "..<");
  685. rules[TOK_OP_RANGE_INCLUDED] = INFIX_OPERATOR(PREC_RANGE, "...");
  686. rules[TOK_KEY_ISA] = INFIX_OPERATOR(PREC_ISA, "is");
  687. rules[TOK_OP_LESS] = INFIX_OPERATOR(PREC_COMPARISON, "<");
  688. rules[TOK_OP_LESS_EQUAL] = INFIX_OPERATOR(PREC_COMPARISON, "<=");
  689. rules[TOK_OP_GREATER] = INFIX_OPERATOR(PREC_COMPARISON, ">");
  690. rules[TOK_OP_GREATER_EQUAL] = INFIX_OPERATOR(PREC_COMPARISON, ">=");
  691. rules[TOK_OP_ISEQUAL] = INFIX_OPERATOR(PREC_COMPARISON, "==");
  692. rules[TOK_OP_ISNOTEQUAL] = INFIX_OPERATOR(PREC_COMPARISON, "!=");
  693. rules[TOK_OP_ISIDENTICAL] = INFIX_OPERATOR(PREC_COMPARISON, "===");
  694. rules[TOK_OP_ISNOTIDENTICAL] = INFIX_OPERATOR(PREC_COMPARISON, "!==");
  695. rules[TOK_OP_PATTERN_MATCH] = INFIX_OPERATOR(PREC_COMPARISON, "~=");
  696. rules[TOK_OP_AND] = INFIX_OPERATOR_RIGHT(PREC_LOGICAL_AND, "&&");
  697. rules[TOK_OP_OR] = INFIX_OPERATOR_RIGHT(PREC_LOGICAL_OR, "||");
  698. rules[TOK_OP_TERNARY] = INFIX(PREC_TERNARY, parse_ternary_expression);
  699. rules[TOK_OP_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "=");
  700. rules[TOK_OP_MUL_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "*=");
  701. rules[TOK_OP_DIV_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "/=");
  702. rules[TOK_OP_REM_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "%=");
  703. rules[TOK_OP_ADD_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "+=");
  704. rules[TOK_OP_SUB_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "-=");
  705. rules[TOK_OP_SHIFT_LEFT_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "<<=");
  706. rules[TOK_OP_SHIFT_RIGHT_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, ">>=");
  707. rules[TOK_OP_BIT_AND_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "=&");
  708. rules[TOK_OP_BIT_OR_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "|=");
  709. rules[TOK_OP_BIT_XOR_ASSIGN] = INFIX_OPERATOR(PREC_ASSIGN, "^=");
  710. rules[TOK_OP_NOT] = PREFIX_OPERATOR("!");
  711. }
  712. // MARK: - Declarations -
  713. static gnode_t *parse_getter_setter (gravity_parser_t *parser) {
  714. DEBUG_PARSER("parse_getter_setter");
  715. DECLARE_LEXER;
  716. gnode_t *getter = NULL;
  717. gnode_t *setter = NULL;
  718. gtoken_s token_block = gravity_lexer_token(lexer);
  719. while (gravity_lexer_peek(lexer) != TOK_OP_CLOSED_CURLYBRACE) {
  720. const char *identifier = parse_identifier(parser);
  721. if (!identifier) goto parse_error;
  722. bool is_getter = false;
  723. gtoken_s token = gravity_lexer_token(lexer);
  724. gnode_r *params = NULL;
  725. // getter case: does not have explicit parameters (only implicit self)
  726. if (strcmp(identifier, GETTER_FUNCTION_NAME) == 0) {
  727. is_getter = true;
  728. params = gnode_array_create(); // add implicit SELF param
  729. gnode_array_push(params, gnode_variable_create(NO_TOKEN, string_dup(SELF_PARAMETER_NAME), NULL, 0, NULL));
  730. }
  731. // setter case: could have explicit parameters (otherwise value is implicit)
  732. if (strcmp(identifier, SETTER_FUNCTION_NAME) == 0) {
  733. is_getter = false;
  734. // check if parameters are explicit
  735. if (gravity_lexer_peek(lexer) == TOK_OP_OPEN_PARENTHESIS) {
  736. parse_required(parser, TOK_OP_OPEN_PARENTHESIS);
  737. params = parse_optional_parameter_declaration(parser); // add implicit SELF
  738. parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  739. } else {
  740. params = gnode_array_create(); // add implicit SELF and VALUE params
  741. gnode_array_push(params, gnode_variable_create(NO_TOKEN, string_dup(SELF_PARAMETER_NAME), NULL, 0, NULL));
  742. gnode_array_push(params, gnode_variable_create(NO_TOKEN, string_dup(SETTER_PARAMETER_NAME), NULL, 0, NULL));
  743. }
  744. }
  745. mem_free(identifier);
  746. // parse compound statement
  747. PUSH_FUNCTION_DECLARATION();
  748. gnode_compound_stmt_t *compound = (gnode_compound_stmt_t*)parse_compound_statement(parser);
  749. POP_DECLARATION();
  750. gnode_t *f = gnode_function_decl_create(token, NULL, 0, 0, params, compound);
  751. // assign f to the right function
  752. if (is_getter) getter = f; else setter = f;
  753. }
  754. gnode_r *functions = gnode_array_create();
  755. gnode_array_push(functions, (getter) ? getter : NULL); // getter is at index 0
  756. gnode_array_push(functions, (setter) ? setter : NULL); // setter is at index 1
  757. // a compound node is used to capture getter and setter
  758. return gnode_block_stat_create(NODE_COMPOUND_STAT, token_block, functions);
  759. parse_error:
  760. return NULL;
  761. }
  762. static gnode_t *parse_variable_declaration (gravity_parser_t *parser, bool isstatement, gtoken_t access_specifier, gtoken_t storage_specifier) {
  763. DEBUG_PARSER("parse_variable_declaration");
  764. DECLARE_LEXER;
  765. gnode_r *decls = NULL;
  766. gnode_t *decl = NULL;
  767. gnode_t *expr = NULL;
  768. const char *identifier = NULL;
  769. const char *type_annotation = NULL;
  770. gtoken_t type;
  771. gtoken_t peek;
  772. gtoken_s token, token2;
  773. // access_specifier? storage_specifier? variable_declaration ';'
  774. // variable_declaration: variable_declarator decl_item
  775. // variable_declarator: 'const' | 'var'
  776. // decl_item: (IDENTIFIER assignment?) (',' IDENTIFIER assignment?)*
  777. // assignment
  778. // sanity check on variable type
  779. type = gravity_lexer_next(lexer);
  780. if (!token_isvariable_declaration(type)) {
  781. REPORT_ERROR(gravity_lexer_token(lexer), "VAR or CONST expected here but found %s.", token_name(type));
  782. return NULL;
  783. }
  784. token = gravity_lexer_token(lexer);
  785. // initialize node array
  786. decls = gnode_array_create();
  787. loop:
  788. identifier = parse_identifier(parser);
  789. if (!identifier) return NULL;
  790. token2 = gravity_lexer_token(lexer);
  791. // type annotation is optional so it can be NULL
  792. type_annotation = parse_optional_type_annotation(parser);
  793. DEBUG_PARSER("IDENTIFIER: %s %s", identifier, (type_annotation) ? type_annotation : "");
  794. // check for optional assignment or getter/setter declaration (ONLY = is ALLOWED here!)
  795. expr = NULL;
  796. peek = gravity_lexer_peek(lexer);
  797. if (token_isvariable_assignment(peek)) {
  798. gravity_lexer_next(lexer); // consume ASSIGNMENT
  799. expr = parse_expression(parser);
  800. } else if (peek == TOK_OP_OPEN_CURLYBRACE) {
  801. gravity_lexer_next(lexer); // consume TOK_OP_OPEN_CURLYBRACE
  802. expr = parse_getter_setter(parser);
  803. parse_required(parser, TOK_OP_CLOSED_CURLYBRACE);
  804. }
  805. // sanity checks
  806. // 1. CONST must be followed by an assignment expression ?
  807. // 2. check if identifier is unique inside variable declarations
  808. decl = gnode_variable_create(token2, identifier, type_annotation, access_specifier, expr);
  809. if (decl) gnode_array_push(decls, decl);
  810. peek = gravity_lexer_peek(lexer);
  811. if (peek == TOK_OP_COMMA) {
  812. gravity_lexer_next(lexer); // consume TOK_OP_COMMA
  813. goto loop;
  814. }
  815. // check and consume TOK_OP_SEMICOLON (ALWAYS required for assignments)
  816. // Aaron: I would keep it consistent, even if it's not strictly required.
  817. // Otherwise we end up with all of JavaScript's terrible ideas. ;-)
  818. // So I would require the semicolon at the end of any assignment statement.
  819. if (isstatement) parse_semicolon(parser);
  820. return gnode_variable_decl_create(token, type, access_specifier, storage_specifier, decls);
  821. }
  822. static gnode_t *parse_enum_declaration (gravity_parser_t *parser, gtoken_t access_specifier, gtoken_t storage_specifier) {
  823. DEBUG_PARSER("parse_enum_declaration");
  824. DECLARE_LEXER;
  825. // enum is a bit different than the traditional C like enum statements
  826. // in Gravity enum can contains String, Integer, Boolean and Float BUT cannot be mixed
  827. // Integer case can also skip values and autoincrement will be applied
  828. // String and Float must have a default value
  829. // in any case default value must be unique (as identifiers)
  830. // this code will take care of parsing and syntax check for the above restrictions
  831. // in order to simplify node struct all the sematic checks are performed here
  832. // even if it is not a best practice, I find a lot easier to perform all the checks
  833. // directly into the parser
  834. // parse_enum_declaration is the only reason why gravity_symboltable.h is included here
  835. // checks are:
  836. // 1: unique internal identifiers
  837. // 2: unique internal values
  838. // 3: if not INT then a default value is mandatory
  839. // 4: all values must be literals
  840. // 'enum' IDENTIFIER '{' enum_list '}' ';'
  841. // enum_list: enum_list_item (',' enum_list_item)*
  842. // enum_list_item: IDENTIFIER ('=' LITERAL)?
  843. // NODE_ENUM_DECL
  844. // optional scope already consumed
  845. gtoken_t type = gravity_lexer_next(lexer);
  846. gtoken_s token = gravity_lexer_token(lexer);
  847. assert(type == TOK_KEY_ENUM);
  848. // parse IDENTIFIER
  849. const char *identifier = parse_identifier(parser);
  850. DEBUG_PARSER("parse_enum_declaration %s", identifier);
  851. // check and consume TOK_OP_OPEN_CURLYBRACE
  852. parse_required(parser, TOK_OP_OPEN_CURLYBRACE);
  853. symboltable_t *symtable = symboltable_create(true); // enum symbol table (symtable is OK because order is not important inside an enum)
  854. int64_t enum_autoint = 0; // autoincrement value (in case of INT enum)
  855. uint32_t enum_counter = 0; // enum internal counter (first value (if any) determines enum type)
  856. gliteral_t enum_type = LITERAL_INT; // enum type (default to int)
  857. while (1) {
  858. // check for empty enum
  859. if (gravity_lexer_peek(lexer) == TOK_OP_CLOSED_CURLYBRACE) break;
  860. // identifier is mandatory here
  861. const char *enum_id = NULL;
  862. gtoken_t peek = gravity_lexer_peek(lexer);
  863. gtoken_s enumid_token = NO_TOKEN;
  864. if (peek == TOK_IDENTIFIER) {
  865. enum_id = parse_identifier(parser);
  866. enumid_token = gravity_lexer_token(lexer);
  867. }
  868. if (!enum_id) {
  869. REPORT_ERROR(enumid_token, "Identifier expected here (found %s).", token_name(peek));
  870. }
  871. // peek next that can be only = or , or }
  872. peek = gravity_lexer_peek(lexer);
  873. gtoken_s enum_token = gravity_lexer_token(lexer);
  874. if (!token_isvariable_assignment(peek) && (peek != TOK_OP_COMMA) && (peek != TOK_OP_CLOSED_CURLYBRACE)) {
  875. REPORT_ERROR(enum_token, "Token %s not allowed here.", token_name(peek));
  876. }
  877. // check for assignment (ONLY = is ALLOWED here!)
  878. // assignment is optional ONLY for LITERAL_TYPE_INT case
  879. if ((!token_isvariable_assignment(peek)) && (enum_type != LITERAL_INT)) {
  880. REPORT_ERROR(enum_token, "A default value is expected here (found %s).", token_name(peek));
  881. }
  882. // check for optional default value (optional only in LITERAL_INT case)
  883. gnode_base_t *enum_value = NULL;
  884. if (token_isvariable_assignment(peek)) {
  885. gravity_lexer_next(lexer); // consume ASSIGNMENT
  886. enum_value = (gnode_base_t *)parse_expression(parser);
  887. }
  888. if (enum_value) {
  889. // make sure that value is a literal (or a unary expression like +num or -num)
  890. gnode_literal_expr_t *enum_literal = NULL;
  891. if (enum_value->base.tag == NODE_LITERAL_EXPR) {
  892. enum_literal = (gnode_literal_expr_t *)enum_value;
  893. } else if (enum_value->base.tag == NODE_UNARY_EXPR) {
  894. gnode_unary_expr_t *unary = (gnode_unary_expr_t *)enum_value;
  895. gnode_base_t *expr = (gnode_base_t *)unary->expr;
  896. // sanity check on unary expression
  897. if (expr->base.tag != NODE_LITERAL_EXPR) {
  898. REPORT_ERROR(enum_token, "%s", "Literal value expected here.");
  899. continue;
  900. }
  901. if ((unary->op != TOK_OP_SUB) && (unary->op != TOK_OP_ADD)) {
  902. REPORT_ERROR(enum_token, "%s", "Only + or - allowed in enum value definition.");
  903. continue;
  904. }
  905. enum_literal = (gnode_literal_expr_t *)expr;
  906. if ((enum_literal->type != LITERAL_FLOAT) && (enum_literal->type != LITERAL_INT)) {
  907. REPORT_ERROR(enum_token, "%s", "A number is expected after a + or - unary expression in an enum definition.");
  908. continue;
  909. }
  910. if (unary->op == TOK_OP_SUB) {
  911. if (enum_literal->type == LITERAL_FLOAT) enum_literal->value.d = -enum_literal->value.d;
  912. else if (enum_literal->type == LITERAL_INT) enum_literal->value.n64 = -enum_literal->value.n64;
  913. else assert(0); // should never reach this point
  914. }
  915. } else {
  916. REPORT_ERROR(enum_token, "%s", "Literal value expected here.");
  917. continue;
  918. }
  919. // first assignment (if any) determines enum type, otherwise default INT case is assumed
  920. if (enum_counter == 0) {
  921. if (enum_literal->type == LITERAL_STRING) enum_type = LITERAL_STRING;
  922. else if (enum_literal->type == LITERAL_FLOAT) enum_type = LITERAL_FLOAT;
  923. else if (enum_literal->type == LITERAL_BOOL) enum_type = LITERAL_BOOL;
  924. }
  925. // check if literal value conforms to enum type
  926. if (enum_literal->type != enum_type) {
  927. REPORT_ERROR(enum_token, "%s", "Literal value of type %s expected here.", token_literal_name(enum_literal->type));
  928. }
  929. // update enum_autoint value to next value
  930. if (enum_literal->type == LITERAL_INT) {
  931. enum_autoint = enum_literal->value.n64 + 1;
  932. }
  933. } else {
  934. enum_value = (gnode_base_t *)gnode_literal_int_expr_create(NO_TOKEN, enum_autoint);
  935. ++enum_autoint;
  936. }
  937. // update internal enum counter
  938. ++enum_counter;
  939. // enum identifier could be NULL due to an already reported error
  940. if (enum_id) {
  941. if (!symboltable_insert(symtable, enum_id, (void *)enum_value)) {
  942. REPORT_ERROR(enumid_token, "Identifier %s redeclared.", enum_id);
  943. gnode_free((gnode_t *)enum_value); // free value here because it has not beed saved into symbol table
  944. }
  945. mem_free(enum_id); // because key is duplicated inside internal hash table
  946. }
  947. peek = gravity_lexer_peek(lexer);
  948. if (peek != TOK_OP_COMMA) break;
  949. // consume TOK_OP_COMMA and continue loop
  950. gravity_lexer_next(lexer);
  951. }
  952. // check and consume TOK_OP_CLOSED_CURLYBRACE
  953. parse_required(parser, TOK_OP_CLOSED_CURLYBRACE);
  954. // consume semicolon
  955. parse_semicolon(parser);
  956. // check for empty enum (not allowed)
  957. if (enum_counter == 0) {
  958. REPORT_ERROR(token, "Empty enum %s not allowed.", identifier);
  959. }
  960. gnode_t *node = gnode_enum_decl_create(token, identifier, access_specifier, storage_specifier, symtable);
  961. if (IS_FUNCTION_ENCLOSED()) return local_store_declaration(identifier, access_specifier, storage_specifier, node);
  962. return node;
  963. }
  964. static gnode_t *parse_module_declaration (gravity_parser_t *parser, gtoken_t access_specifier, gtoken_t storage_specifier) {
  965. DEBUG_PARSER("parse_module_declaration");
  966. // 'module' IDENTIFIER '{' declaration_statement* '}' ';'
  967. // optional scope already consumed
  968. DECLARE_LEXER;
  969. gtoken_t type = gravity_lexer_next(lexer);
  970. gtoken_s token = gravity_lexer_token(lexer);
  971. assert(type == TOK_KEY_MODULE);
  972. // parse IDENTIFIER
  973. const char *identifier = parse_identifier(parser);
  974. DEBUG_PARSER("parse_module_declaration %s", identifier);
  975. // parse optional curly brace
  976. bool curly_brace = parse_optional(parser, TOK_OP_OPEN_CURLYBRACE);
  977. gnode_r *declarations = gnode_array_create();
  978. while (token_isdeclaration_statement(gravity_lexer_peek(lexer))) {
  979. gnode_t *decl = parse_declaration_statement(parser);
  980. if (decl) gnode_array_push(declarations, decl);
  981. }
  982. // check and consume TOK_OP_CLOSED_CURLYBRACE
  983. if (curly_brace) parse_required(parser, TOK_OP_CLOSED_CURLYBRACE);
  984. parse_semicolon(parser);
  985. return gnode_module_decl_create(token, identifier, access_specifier, storage_specifier, declarations);
  986. }
  987. static gnode_t *parse_event_declaration (gravity_parser_t *parser, gtoken_t access_specifier, gtoken_t storage_specifier) {
  988. #pragma unused(parser, access_specifier, storage_specifier)
  989. // 'event' IDENTIFIER '(' parameter_declaration_clause? ')' ';'
  990. // NODE_EVENT_DECL
  991. assert(0);
  992. return NULL;
  993. }
  994. static gnode_t *parse_function_declaration (gravity_parser_t *parser, gtoken_t access_specifier, gtoken_t storage_specifier) {
  995. gnode_t *node = parse_function(parser, true, access_specifier, storage_specifier);
  996. // convert a function declaration within another function to a local variable assignment
  997. // for example:
  998. //
  999. // func foo() {
  1000. // func bar() {...}
  1001. // }
  1002. //
  1003. // is converter to:
  1004. //
  1005. // func foo() {
  1006. // var bar = func() {...}
  1007. // }
  1008. //
  1009. // conversion is performed inside the parser
  1010. // so next semantic checks can perform
  1011. // identifier uniqueness checks
  1012. if (IS_FUNCTION_ENCLOSED()) return local_store_declaration(((gnode_function_decl_t *)node)->identifier, access_specifier, storage_specifier, node);
  1013. return node;
  1014. }
  1015. static gnode_t *parse_id (gravity_parser_t *parser) {
  1016. DECLARE_LEXER;
  1017. const char *identifier1 = NULL;
  1018. const char *identifier2 = NULL;
  1019. gtoken_t peek;
  1020. gtoken_s token;
  1021. // IDENTIFIER | (IDENTIFIER)('.' IDENTIFIER)
  1022. DEBUG_PARSER("parse_id");
  1023. identifier1 = parse_identifier(parser);
  1024. token = gravity_lexer_token(lexer);
  1025. peek = gravity_lexer_peek(lexer);
  1026. if (peek == TOK_OP_DOT) {
  1027. gravity_lexer_next(lexer); // consume TOK_OP_DOT
  1028. identifier2 = parse_identifier(parser);
  1029. }
  1030. DEBUG_PARSER("ID: %s %s", identifier1, (identifier2) ? identifier2 : "");
  1031. return gnode_identifier_expr_create(token, identifier1, identifier2);
  1032. }
  1033. static gnode_r *parse_protocols (gravity_parser_t *parser) {
  1034. DECLARE_LEXER;
  1035. gtoken_t peek;
  1036. gnode_t *node = NULL;
  1037. gnode_r *list = NULL;
  1038. // (id) (',' id)*
  1039. peek = gravity_lexer_peek(lexer);
  1040. if (peek == TOK_OP_GREATER) return NULL; // just an empty protocols implementation statement
  1041. list = gnode_array_create();
  1042. loop:
  1043. if (!token_isidentifier(peek)) goto abort;
  1044. node = parse_id(parser);
  1045. if (node) gnode_array_push(list, node);
  1046. peek = gravity_lexer_peek(lexer);
  1047. if (peek == TOK_OP_COMMA) {
  1048. gravity_lexer_next(lexer); // consume TOK_OP_COMMA
  1049. goto loop;
  1050. }
  1051. return list;
  1052. abort:
  1053. if (list) gnode_array_free(list);
  1054. return NULL;
  1055. }
  1056. static gnode_t *parse_class_declaration (gravity_parser_t *parser, gtoken_t access_specifier, gtoken_t storage_specifier) {
  1057. DEBUG_PARSER("parse_class_declaration");
  1058. DECLARE_LEXER;
  1059. // access_specifier? storage_specifier? 'class' IDENTIFIER class_superclass? class_protocols? '{' declaration_statement* '}' ';'
  1060. // class_superclass: (':') id
  1061. // class_protocols: '<' (id) (',' id)* '>'
  1062. // optional scope already consumed (when here I am sure type is TOK_KEY_CLASS or TOK_KEY_STRUCT)
  1063. gtoken_t type = gravity_lexer_next(lexer);
  1064. gtoken_s token = gravity_lexer_token(lexer);
  1065. bool is_struct = (type == TOK_KEY_STRUCT);
  1066. // parse IDENTIFIER
  1067. const char *identifier = parse_identifier(parser);
  1068. // check for optional superclass
  1069. gnode_t *super = NULL;
  1070. gnode_r *protocols = NULL;
  1071. gtoken_t peek = gravity_lexer_peek(lexer);
  1072. if (peek == TOK_OP_COLON) {
  1073. gravity_lexer_next(lexer); // consume TOK_OP_COLON
  1074. super = parse_id(parser);
  1075. }
  1076. // check for optional protocols (not supported in this version)
  1077. peek = gravity_lexer_peek(lexer);
  1078. if (peek == TOK_OP_LESS) {
  1079. gravity_lexer_next(lexer); // consume '<'
  1080. protocols = parse_protocols(parser);
  1081. parse_required(parser, TOK_OP_GREATER); // consume '>'
  1082. }
  1083. // check and consume TOK_OP_OPEN_CURLYBRACE
  1084. parse_required(parser, TOK_OP_OPEN_CURLYBRACE);
  1085. gnode_r *declarations = gnode_array_create();
  1086. // if class is declared inside another class then a hidden implicit privare "outer" instance var at index 0
  1087. // is automatically added
  1088. if (IS_CLASS_ENCLOSED()) {
  1089. gnode_r *decls = gnode_array_create();
  1090. gnode_t *outer_var = gnode_variable_create(NO_TOKEN, string_dup(OUTER_IVAR_NAME), NULL, 0, NULL);
  1091. gnode_array_push(decls, outer_var);
  1092. gnode_t *outer_decl = gnode_variable_decl_create(NO_TOKEN, TOK_KEY_VAR, TOK_KEY_PRIVATE, 0, decls);
  1093. gnode_array_push(declarations, outer_decl);
  1094. }
  1095. PUSH_CLASS_DECLARATION();
  1096. while (token_isdeclaration_statement(gravity_lexer_peek(lexer))) {
  1097. gnode_t *decl = parse_declaration_statement(parser);
  1098. if (decl) gnode_array_push(declarations, decl);
  1099. }
  1100. POP_DECLARATION();
  1101. // check and consume TOK_OP_CLOSED_CURLYBRACE
  1102. parse_required(parser, TOK_OP_CLOSED_CURLYBRACE);
  1103. // to check
  1104. parse_semicolon(parser);
  1105. gnode_t *node = gnode_class_decl_create(token, identifier, access_specifier, storage_specifier, super, protocols, declarations, is_struct);
  1106. if (IS_FUNCTION_ENCLOSED()) return local_store_declaration(identifier, access_specifier, storage_specifier, node);
  1107. return node;
  1108. }
  1109. static gnode_r *parse_optional_parameter_declaration (gravity_parser_t *parser) {
  1110. DEBUG_PARSER("parse_parameter_declaration");
  1111. DECLARE_LEXER;
  1112. gtoken_s token = NO_TOKEN;
  1113. gnode_t *node = NULL;
  1114. const char *identifier = NULL;
  1115. const char *type_annotation = NULL;
  1116. // (IDENTIFIER type_annotation?) (',' type_annotation)*
  1117. // type_annotation: ':' identifier
  1118. gnode_r *params = gnode_array_create();
  1119. assert(params);
  1120. // check if implicit self parameter must be added
  1121. // was if (IS_CLASS_ENCLOSED()*/) { ... add SELF PARAMETER ...}
  1122. // but we decided to ALWAYS pass SELF because it simplified cases
  1123. // like c1().p1.p1.p1(1234);
  1124. // ALWAYS add an implicit SELF parameter
  1125. // string_dup mandatory here because when the node will be freed
  1126. // memory for the identifier will be deallocated
  1127. node = gnode_variable_create(token, string_dup(SELF_PARAMETER_NAME), type_annotation, 0, NULL);
  1128. if (node) gnode_array_push(params, node);
  1129. // parameter declaration clause is ALWAYS optional
  1130. gtoken_t peek = gravity_lexer_peek(lexer);
  1131. if (peek == TOK_OP_CLOSED_PARENTHESIS) return params;
  1132. // so there is at leat one explicit parameter
  1133. loop:
  1134. // initialize variables
  1135. type_annotation = NULL;
  1136. // parse identifier
  1137. identifier = parse_identifier(parser);
  1138. token = gravity_lexer_token(lexer);
  1139. // parse optional type annotation
  1140. type_annotation = parse_optional_type_annotation(parser);
  1141. // fill parameters array with the new node
  1142. node = gnode_variable_create(token, identifier, type_annotation, 0, NULL);
  1143. if (node) gnode_array_push(params, node);
  1144. // check for optional comma in order to decide
  1145. // if the loop should continue or not
  1146. peek = gravity_lexer_peek(lexer);
  1147. if (peek == TOK_OP_COMMA) {
  1148. gravity_lexer_next(lexer); // consume TOK_OP_COMMA
  1149. goto loop;
  1150. }
  1151. return params;
  1152. }
  1153. // MARK: - UnitTest -
  1154. typedef enum {
  1155. UNITTEST_NONE,
  1156. UNITTEST_NAME,
  1157. UNITTEST_ERROR,
  1158. UNITTEST_RESULT,
  1159. UNITTEST_ERROR_ROW,
  1160. UNITTEST_ERROR_COL,
  1161. UNITTEST_NOTE
  1162. } unittest_t;
  1163. static unittest_t parse_unittest_identifier(const char *identifier) {
  1164. if (string_cmp(identifier, "name") == 0) return UNITTEST_NAME;
  1165. if (string_cmp(identifier, "note") == 0) return UNITTEST_NOTE;
  1166. if (string_cmp(identifier, "error") == 0) return UNITTEST_ERROR;
  1167. if (string_cmp(identifier, "error_row") == 0) return UNITTEST_ERROR_ROW;
  1168. if (string_cmp(identifier, "error_col") == 0) return UNITTEST_ERROR_COL;
  1169. if (string_cmp(identifier, "result") == 0) return UNITTEST_RESULT;
  1170. return UNITTEST_NONE;
  1171. }
  1172. static gnode_t *parse_unittest_declaration(gravity_parser_t *parser) {
  1173. DECLARE_LEXER;
  1174. DEBUG_PARSER("parse_unittest_declaration");
  1175. // @unittest {
  1176. // name: "Unit test name";
  1177. // note: "Some notes here";
  1178. // error: NONE, SYNTAX, RUNTIME, WARNING;
  1179. // error_row: number;
  1180. // error_col: number;
  1181. // result: LITERAL;
  1182. // '}' ';'?
  1183. gnode_literal_expr_t *name_node = NULL;
  1184. gnode_literal_expr_t *note_node = NULL;
  1185. gnode_identifier_expr_t *err_node = NULL;
  1186. gnode_literal_expr_t *row_node = NULL;
  1187. gnode_literal_expr_t *col_node = NULL;
  1188. gnode_literal_expr_t *value_node = NULL;
  1189. parse_required(parser, TOK_OP_OPEN_CURLYBRACE);
  1190. while (gravity_lexer_peek(lexer) != TOK_OP_CLOSED_CURLYBRACE) {
  1191. const char *id = parse_identifier(parser);
  1192. if (id == NULL) goto handle_error;
  1193. parse_required(parser, TOK_OP_COLON);
  1194. unittest_t type = parse_unittest_identifier(id);
  1195. mem_free(id);
  1196. if (type == UNITTEST_NAME) {
  1197. name_node = (gnode_literal_expr_t *)parse_literal_expression(parser);
  1198. if (name_node == NULL) goto handle_error;
  1199. }
  1200. else if (type == UNITTEST_NOTE) {
  1201. note_node = (gnode_literal_expr_t *)parse_literal_expression(parser);
  1202. if (note_node == NULL) goto handle_error;
  1203. }
  1204. else if (type == UNITTEST_ERROR) {
  1205. err_node = (gnode_identifier_expr_t *)parse_identifier_expression(parser);
  1206. if (err_node == NULL) goto handle_error;
  1207. }
  1208. else if (type == UNITTEST_ERROR_ROW) {
  1209. row_node = (gnode_literal_expr_t *)parse_literal_expression(parser);
  1210. if (row_node == NULL) goto handle_error;
  1211. }
  1212. else if (type == UNITTEST_ERROR_COL) {
  1213. col_node = (gnode_literal_expr_t *)parse_literal_expression(parser);
  1214. if (col_node == NULL) goto handle_error;
  1215. }
  1216. else if (type == UNITTEST_RESULT) {
  1217. gtoken_t op = TOK_EOF;
  1218. gtoken_t peek = gravity_lexer_peek(lexer);
  1219. // check if peek is a + or - sign
  1220. if ((peek == TOK_OP_SUB) || (peek == TOK_OP_ADD))
  1221. op = gravity_lexer_next(lexer);
  1222. else if (peek == TOK_KEY_NULL) {
  1223. // an expected return value can now be keyword NULL
  1224. gravity_lexer_next(lexer); // consume NULL keyword
  1225. value_node = NULL;
  1226. goto handle_continue;
  1227. }
  1228. value_node = (gnode_literal_expr_t *)parse_literal_expression(parser);
  1229. if (value_node == NULL) goto handle_error;
  1230. // if a negative sign has been parsed then manually fix the literal expression (if it is a number)
  1231. if (op == TOK_OP_SUB) {
  1232. if (value_node->type == LITERAL_INT) value_node->value.n64 = -value_node->value.n64;
  1233. else if (value_node->type == LITERAL_FLOAT) value_node->value.d = -value_node->value.d;
  1234. }
  1235. }
  1236. else {
  1237. REPORT_ERROR(gravity_lexer_token(lexer), "Unknown token found in @unittest declaration.");
  1238. goto handle_error;
  1239. }
  1240. handle_continue:
  1241. parse_semicolon(parser);
  1242. }
  1243. parse_required(parser, TOK_OP_CLOSED_CURLYBRACE);
  1244. parse_semicolon(parser);
  1245. // decode unit array and report error/unittest
  1246. // unit test name max length is 1024
  1247. const char *description = NULL;
  1248. const char *note = NULL;
  1249. char buffer[1024];
  1250. char buffer2[1024];
  1251. error_type_t expected_error = GRAVITY_ERROR_NONE;
  1252. gravity_value_t expected_value = VALUE_FROM_NULL;
  1253. int32_t expected_nrow = -1;
  1254. int32_t expected_ncol = -1;
  1255. // unittest name should be a literal string
  1256. if ((name_node) && (name_node->type == LITERAL_STRING)) {
  1257. // no more C strings in AST so we need a static buffer
  1258. snprintf(buffer, sizeof(buffer), "%.*s", name_node->len, name_node->value.str);
  1259. description = buffer;
  1260. }
  1261. // note (optional) should be a literal string
  1262. if ((note_node) && (note_node->type == LITERAL_STRING)) {
  1263. // no more C strings in AST so we need a static buffer
  1264. snprintf(buffer2, sizeof(buffer2), "%.*s", note_node->len, note_node->value.str);
  1265. note = buffer2;
  1266. }
  1267. // decode expected error: NONE, SYNTAX, SEMANTIC, RUNTIME, WARNING
  1268. if (err_node) {
  1269. if (string_cmp(err_node->value, "NONE") == 0)
  1270. expected_error = GRAVITY_ERROR_NONE;
  1271. else if (string_cmp(err_node->value, "SYNTAX") == 0)
  1272. expected_error = GRAVITY_ERROR_SYNTAX;
  1273. else if (string_cmp(err_node->value, "SEMANTIC") == 0)
  1274. expected_error = GRAVITY_ERROR_SEMANTIC;
  1275. else if (string_cmp(err_node->value, "RUNTIME") == 0)
  1276. expected_error = GRAVITY_ERROR_RUNTIME;
  1277. else if (string_cmp(err_node->value, "WARNING") == 0)
  1278. expected_error = GRAVITY_WARNING;
  1279. }
  1280. // decode error line/col
  1281. if ((row_node) && (row_node->type == LITERAL_INT)) {
  1282. expected_nrow = (int32_t)row_node->value.n64;
  1283. }
  1284. if ((col_node) && (col_node->type == LITERAL_INT)) {
  1285. expected_ncol = (int32_t)col_node->value.n64;
  1286. }
  1287. // decode unittest expected result
  1288. if (value_node) {
  1289. if (value_node->type == LITERAL_STRING)
  1290. expected_value = VALUE_FROM_CSTRING(NULL, value_node->value.str);
  1291. else if (value_node->type == LITERAL_INT)
  1292. expected_value = VALUE_FROM_INT((gravity_int_t)value_node->value.n64);
  1293. else if (value_node->type == LITERAL_FLOAT)
  1294. expected_value = VALUE_FROM_FLOAT((gravity_float_t)value_node->value.d);
  1295. else if (value_node->type == LITERAL_BOOL)
  1296. expected_value = (value_node->value.n64) ? VALUE_FROM_TRUE : VALUE_FROM_FALSE;
  1297. }
  1298. // report unittest to delegate
  1299. if ((parser->delegate) && (parser->delegate->unittest_callback)) {
  1300. gravity_unittest_callback unittest_cb = parser->delegate->unittest_callback;
  1301. unittest_cb(expected_error, description, note, expected_value, expected_nrow, expected_ncol, parser->delegate->xdata);
  1302. } else {
  1303. // it was unit test responsability to free expected_value but if no unit test delegate is set I should take care of it
  1304. gravity_value_free(NULL, expected_value);
  1305. }
  1306. // free temp nodes
  1307. if (name_node) gnode_free((gnode_t*)name_node);
  1308. if (note_node) gnode_free((gnode_t*)note_node);
  1309. if (err_node) gnode_free((gnode_t*)err_node);
  1310. if (row_node) gnode_free((gnode_t*)row_node);
  1311. if (col_node) gnode_free((gnode_t*)col_node);
  1312. if (value_node) gnode_free((gnode_t*)value_node);
  1313. // always return NULL
  1314. handle_error:
  1315. return NULL;
  1316. }
  1317. // MARK: - Statements -
  1318. static gnode_t *parse_label_statement (gravity_parser_t *parser) {
  1319. DEBUG_PARSER("parse_label_statement");
  1320. // 'case' expression ':' statement
  1321. // 'default' ':' statement
  1322. DECLARE_LEXER;
  1323. gtoken_t type = gravity_lexer_next(lexer);
  1324. gtoken_s token = gravity_lexer_token(lexer);
  1325. assert((type == TOK_KEY_CASE) || (type == TOK_KEY_DEFAULT));
  1326. // case specific expression
  1327. gnode_t *expr = NULL;
  1328. if (type == TOK_KEY_CASE) {
  1329. expr = parse_expression(parser);
  1330. }
  1331. // common part
  1332. parse_required(parser, TOK_OP_COLON);
  1333. gnode_t *stmt = parse_statement(parser);
  1334. return gnode_label_stat_create(token, expr, stmt);
  1335. }
  1336. static gnode_t *parse_flow_statement (gravity_parser_t *parser) {
  1337. DEBUG_PARSER("parse_flow_statement");
  1338. // 'if' '(' expression ')' statement ('else' statement)?
  1339. // 'switch' '(' expression ')' statement
  1340. DECLARE_LEXER;
  1341. gtoken_t type = gravity_lexer_next(lexer);
  1342. gtoken_s token = gravity_lexer_token(lexer);
  1343. assert((type == TOK_KEY_IF) || (type == TOK_KEY_SWITCH));
  1344. // check optional TOK_OP_OPEN_PARENTHESIS
  1345. bool is_parenthesize = parse_optional(parser, TOK_OP_OPEN_PARENTHESIS);
  1346. // parse common expression
  1347. gnode_t *cond = parse_expression(parser);
  1348. // check and consume TOK_OP_CLOSED_PARENTHESIS
  1349. if (is_parenthesize) parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  1350. // parse common statement
  1351. gnode_t *stmt1 = parse_statement(parser);
  1352. gnode_t *stmt2 = NULL;
  1353. if ((type == TOK_KEY_IF) && (gravity_lexer_peek(lexer) == TOK_KEY_ELSE)) {
  1354. gravity_lexer_next(lexer); // consume TOK_KEY_ELSE
  1355. stmt2 = parse_statement(parser);
  1356. }
  1357. return gnode_flow_stat_create(token, cond, stmt1, stmt2);
  1358. }
  1359. static gnode_t *parse_loop_statement (gravity_parser_t *parser) {
  1360. DEBUG_PARSER("parse_loop_statement");
  1361. // 'while' '(' expression ')' statement
  1362. // 'repeat' statement 'while' '(' expression ')' ';'
  1363. // 'for' '(' condition 'in' expression ')' statement
  1364. DECLARE_LEXER;
  1365. gnode_t *cond = NULL;
  1366. gnode_t *stmt = NULL;
  1367. gnode_t *expr = NULL;
  1368. gtoken_t type = gravity_lexer_next(lexer);
  1369. gtoken_s token = gravity_lexer_token(lexer);
  1370. assert((type == TOK_KEY_WHILE) || (type == TOK_KEY_REPEAT) || (type == TOK_KEY_FOR));
  1371. // 'while' '(' expression ')' statement
  1372. if (type == TOK_KEY_WHILE) {
  1373. // check optional TOK_OP_OPEN_PARENTHESIS
  1374. bool is_parenthesize = parse_optional(parser, TOK_OP_OPEN_PARENTHESIS);
  1375. // parse while condition
  1376. cond = parse_expression(parser);
  1377. // check and consume TOK_OP_CLOSED_PARENTHESIS
  1378. if (is_parenthesize) parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  1379. // parse while statement
  1380. stmt = parse_statement(parser);
  1381. goto return_node;
  1382. }
  1383. // 'repeat' statement 'while' '(' expression ')' ';'
  1384. if (type == TOK_KEY_REPEAT) {
  1385. // parse repeat statement
  1386. stmt = parse_statement(parser);
  1387. // check and consume TOK_KEY_WHILE
  1388. parse_required(parser, TOK_KEY_WHILE);
  1389. // check optional TOK_OP_OPEN_PARENTHESIS
  1390. bool is_parenthesize = parse_optional(parser, TOK_OP_OPEN_PARENTHESIS);
  1391. // parse while expression
  1392. expr = parse_expression(parser);
  1393. // check and consume TOK_OP_CLOSED_PARENTHESIS
  1394. if (is_parenthesize) parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  1395. // semicolon
  1396. parse_semicolon(parser);
  1397. goto return_node;
  1398. }
  1399. // 'for' '(' condition 'in' expression ')' statement
  1400. if (type == TOK_KEY_FOR) {
  1401. // check optional TOK_OP_OPEN_PARENTHESIS
  1402. bool is_parenthesize = parse_optional(parser, TOK_OP_OPEN_PARENTHESIS);
  1403. // parse condition (means parse variable declaration or expression)
  1404. if (token_isvariable_declaration(gravity_lexer_peek(lexer))) {
  1405. cond = parse_variable_declaration(parser, false, 0, 0);
  1406. } else {
  1407. cond = parse_expression(parser);
  1408. }
  1409. // check and consume TOK_KEY_IN
  1410. parse_required(parser, TOK_KEY_IN);
  1411. // parse expression
  1412. expr = parse_expression(parser);
  1413. // check and consume TOK_OP_CLOSED_PARENTHESIS
  1414. if (is_parenthesize) parse_required(parser, TOK_OP_CLOSED_PARENTHESIS);
  1415. // parse for statement
  1416. stmt = parse_statement(parser);
  1417. }
  1418. return_node:
  1419. return gnode_loop_stat_create(token, cond, stmt, expr);
  1420. }
  1421. static gnode_t *parse_jump_statement (gravity_parser_t *parser) {
  1422. DEBUG_PARSER("parse_jump_statement");
  1423. // 'break' ';'
  1424. // 'continue' ';'
  1425. // 'return' expression? ';'
  1426. DECLARE_LEXER;
  1427. gtoken_t type = gravity_lexer_next(lexer);
  1428. gtoken_s token = gravity_lexer_token(lexer);
  1429. assert((type == TOK_KEY_BREAK) || (type == TOK_KEY_CONTINUE) || (type == TOK_KEY_RETURN));
  1430. gnode_t *expr = NULL;
  1431. if ((type == TOK_KEY_RETURN) && (gravity_lexer_peek(lexer) != TOK_OP_SEMICOLON)) {
  1432. expr = parse_expression(parser);
  1433. }
  1434. parse_semicolon(parser);
  1435. return gnode_jump_stat_create(token, expr);
  1436. }
  1437. static gnode_t *parse_compound_statement (gravity_parser_t *parser) {
  1438. DEBUG_PARSER("parse_compound_statement");
  1439. // '{' (statement+)? '}'
  1440. // check and consume TOK_OP_OPEN_CURLYBRACE
  1441. parse_required(parser, TOK_OP_OPEN_CURLYBRACE);
  1442. DECLARE_LEXER;
  1443. gtoken_s token = gravity_lexer_token(lexer);
  1444. gnode_r *stmts = gnode_array_create();
  1445. while (token_isstatement(gravity_lexer_peek(lexer))) {
  1446. gnode_t *node = parse_statement(parser);
  1447. if (node) gnode_array_push(stmts, node);
  1448. }
  1449. // check and consume TOK_OP_CLOSED_CURLYBRACE
  1450. parse_required(parser, TOK_OP_CLOSED_CURLYBRACE);
  1451. return gnode_block_stat_create(NODE_COMPOUND_STAT, token, stmts);
  1452. }
  1453. static gnode_t *parse_empty_statement (gravity_parser_t *parser) {
  1454. DEBUG_PARSER("parse_empty_statement");
  1455. // ;
  1456. DECLARE_LEXER;
  1457. gravity_lexer_next(lexer);
  1458. gtoken_s token = gravity_lexer_token(lexer);
  1459. return gnode_empty_stat_create(token);
  1460. }
  1461. static gnode_t *parse_declaration_statement (gravity_parser_t *parser) {
  1462. DEBUG_PARSER("parse_declaration_statement");
  1463. DECLARE_LEXER;
  1464. gtoken_t peek = gravity_lexer_peek(lexer);
  1465. gtoken_t access_specifier = 0; // 0 means no access specifier set
  1466. gtoken_t storage_specifier = 0; // 0 means no storage specifier set
  1467. // check if an access specifier is set
  1468. if (token_isaccess_specifier(peek)) {
  1469. access_specifier = gravity_lexer_next(lexer);
  1470. peek = gravity_lexer_peek(lexer);
  1471. }
  1472. // check if a storage specifier is set
  1473. if (token_isstorage_specifier(peek)) {
  1474. storage_specifier = gravity_lexer_next(lexer);
  1475. peek = gravity_lexer_peek(lexer);
  1476. }
  1477. // it is a syntax error to specify an access or storage specifier followed by an empty declaration
  1478. if ((peek == TOK_OP_SEMICOLON) && ((access_specifier) || (storage_specifier))) {
  1479. REPORT_ERROR(gravity_lexer_token(lexer), "%s", "Access or storage specifier cannot be used here.");
  1480. }
  1481. switch (peek) {
  1482. case TOK_KEY_FUNC: return parse_function_declaration(parser, access_specifier, storage_specifier);
  1483. case TOK_KEY_ENUM: return parse_enum_declaration(parser, access_specifier, storage_specifier);
  1484. case TOK_KEY_MODULE: return parse_module_declaration(parser, access_specifier, storage_specifier);
  1485. case TOK_KEY_EVENT: return parse_event_declaration(parser, access_specifier, storage_specifier);
  1486. case TOK_KEY_CLASS:
  1487. case TOK_KEY_STRUCT: return parse_class_declaration(parser, access_specifier, storage_specifier);
  1488. case TOK_OP_SEMICOLON: return parse_empty_statement(parser);
  1489. case TOK_KEY_VAR:
  1490. case TOK_KEY_CONST: return parse_variable_declaration(parser, true, access_specifier, storage_specifier);
  1491. default: REPORT_ERROR(gravity_lexer_token(lexer), "Unrecognized token %s.", token_name(peek)); return NULL;
  1492. }
  1493. // should never reach this point
  1494. assert(0);
  1495. return NULL;
  1496. }
  1497. static gnode_t *parse_import_statement (gravity_parser_t *parser) {
  1498. DEBUG_PARSER("parse_import_statement");
  1499. DECLARE_LEXER;
  1500. // parse import keyword
  1501. gravity_lexer_next(lexer);
  1502. // process filename (can be an identifier or a literal string)
  1503. // identifier to import modules ?
  1504. // only literals are supported in this version
  1505. gtoken_t type;
  1506. gtoken_s token;
  1507. const char *module_name;
  1508. gravity_lexer_t *newlexer;
  1509. loop:
  1510. newlexer = NULL;
  1511. type = gravity_lexer_next(lexer);
  1512. token = gravity_lexer_token(lexer);
  1513. // check if it is a string token
  1514. if (type != TOK_STRING) {
  1515. REPORT_ERROR(token, "Expected file name but found %s.", token_name(type));
  1516. return NULL;
  1517. }
  1518. // check pre-requisites
  1519. if ((!parser->delegate) || (!parser->delegate->loadfile_callback)) {
  1520. REPORT_ERROR(gravity_lexer_token(lexer), "%s", "Unable to load file because no loadfile callback registered in delegate.");
  1521. return NULL;
  1522. }
  1523. // parse string
  1524. module_name = cstring_from_token(parser, token);
  1525. size_t size = 0;
  1526. uint32_t fileid = 0;
  1527. // module_name is a filename and it is used by lexer to store filename into tokens
  1528. // tokens are then stored inside AST nodes in order to locate errors into source code
  1529. // AST can live a lot longer than both lexer and parser so we need a way to persistent
  1530. // store these chuncks of memory
  1531. const char *source = parser->delegate->loadfile_callback(module_name, &size, &fileid, parser->delegate->xdata);
  1532. if (source) newlexer = gravity_lexer_create(source, size, fileid, false);
  1533. if (newlexer) {
  1534. // push new lexer into lexer stack
  1535. marray_push(gravity_lexer_t*, *parser->lexer, newlexer);
  1536. } else {
  1537. REPORT_ERROR(token, "Unable to load file %s.", module_name);
  1538. }
  1539. // check for optional comma
  1540. if (gravity_lexer_peek(lexer) == TOK_OP_COMMA) {
  1541. gravity_lexer_next(lexer); // consume TOK_OP_COMMA
  1542. goto loop;
  1543. }
  1544. // parse semicolon
  1545. parse_semicolon(parser);
  1546. return NULL;
  1547. }
  1548. static gnode_t *parse_macro_statement (gravity_parser_t *parser) {
  1549. DEBUG_PARSER("parse_macro_statement");
  1550. DECLARE_LEXER;
  1551. // consume special # symbol
  1552. gtoken_t type = gravity_lexer_next(lexer);
  1553. assert(type == TOK_MACRO);
  1554. // check for #! and interpret #! shebang bash as one line comment
  1555. // only if found on first line (https://github.com/marcobambini/gravity/issues/86)
  1556. if (gravity_lexer_peek(lexer) == TOK_OP_NOT && gravity_lexer_lineno(lexer) == 1) {
  1557. // consume special ! symbol
  1558. type = gravity_lexer_next(lexer);
  1559. assert(type == TOK_OP_NOT);
  1560. // skip until EOL
  1561. gravity_lexer_skip_line(lexer);
  1562. return NULL;
  1563. }
  1564. // macro has its own parser because I don't want to mess standard syntax
  1565. const char *macroid = parse_identifier(parser);
  1566. if (macroid == NULL) goto handle_error;
  1567. // check #unittest macro
  1568. bool is_unittest = (string_cmp(macroid, "unittest") == 0);
  1569. mem_free(macroid);
  1570. if (is_unittest) {
  1571. return parse_unittest_declaration(parser);
  1572. }
  1573. handle_error:
  1574. REPORT_WARNING(gravity_lexer_token(lexer), "%s", "Unknown macro token. Declaration will be ignored.");
  1575. return NULL;
  1576. }
  1577. static gnode_t *parse_special_statement (gravity_parser_t *parser) {
  1578. DEBUG_PARSER("parse_special_statement");
  1579. DECLARE_LEXER;
  1580. // consume special @ symbol
  1581. gtoken_t type = gravity_lexer_next(lexer);
  1582. assert(type == TOK_SPECIAL);
  1583. // special is really special so it has its own parser
  1584. // because I don't want to mess standard syntax
  1585. const char *specialid = parse_identifier(parser);
  1586. if (specialid == NULL) goto handle_error;
  1587. handle_error:
  1588. REPORT_WARNING(gravity_lexer_token(lexer), "%s", "Unknown special token. Declaration will be ignored.");
  1589. return NULL;
  1590. }
  1591. static gnode_t *parse_expression_statement (gravity_parser_t *parser) {
  1592. DEBUG_PARSER("parse_expression_statement");
  1593. gnode_t *expr = parse_expression(parser);
  1594. parse_semicolon(parser);
  1595. return expr;
  1596. }
  1597. static gnode_t *parse_statement (gravity_parser_t *parser) {
  1598. DEBUG_PARSER("parse_statement");
  1599. // label_statement
  1600. // flow_statement
  1601. // loop_statement
  1602. // jump_statement
  1603. // compound_statement
  1604. // declaration_statement
  1605. // empty_statement
  1606. // import_statement
  1607. // expression_statement (default)
  1608. DECLARE_LEXER;
  1609. gtoken_t token = gravity_lexer_peek(lexer);
  1610. if (token_iserror(token)) return parse_error(parser);
  1611. if (token_islabel_statement(token)) return parse_label_statement(parser);
  1612. else if (token_isflow_statement(token)) return parse_flow_statement(parser);
  1613. else if (token_isloop_statement(token)) return parse_loop_statement(parser);
  1614. else if (token_isjump_statement(token)) return parse_jump_statement(parser);
  1615. else if (token_iscompound_statement(token)) return parse_compound_statement(parser);
  1616. else if (token_isdeclaration_statement(token)) return parse_declaration_statement(parser);
  1617. else if (token_isempty_statement(token)) return parse_empty_statement(parser);
  1618. else if (token_isimport_statement(token)) return parse_import_statement(parser);
  1619. else if (token_isspecial_statement(token)) return parse_special_statement(parser);
  1620. else if (token_ismacro(token)) return parse_macro_statement(parser);
  1621. return parse_expression_statement(parser); // DEFAULT
  1622. }
  1623. // MARK: - Internal functions -
  1624. static void parser_register_core_classes (gravity_parser_t *parser) {
  1625. const char **list = NULL;
  1626. uint32_t n = gravity_core_identifiers(&list);
  1627. if (!n) return;
  1628. // for each core identifier create a dummy extern variable node
  1629. gnode_r *decls = gnode_array_create();
  1630. for (uint32_t i=0; i<n; ++i) {
  1631. const char *identifier = list[i];
  1632. gnode_t *node = gnode_variable_create(NO_TOKEN, string_dup(identifier), NULL, 0, NULL);
  1633. gnode_array_push(decls, node);
  1634. }
  1635. // register a variable declaration node in global statements
  1636. gnode_t *node = gnode_variable_decl_create(NO_TOKEN, TOK_KEY_VAR, 0, TOK_KEY_EXTERN, decls);;
  1637. gnode_array_push(parser->statements, (gnode_t *)node);
  1638. }
  1639. static uint32_t parser_run (gravity_parser_t *parser) {
  1640. DEBUG_PARSER("=== BEGIN PARSING ===");
  1641. // register core classes as extern globals
  1642. parser_register_core_classes(parser);
  1643. nanotime_t t1 = nanotime();
  1644. do {
  1645. while (gravity_lexer_peek(CURRENT_LEXER)) {
  1646. gnode_t *node = parse_statement(parser);
  1647. if (node) gnode_array_push(parser->statements, node);
  1648. }
  1649. // since it is a stack of lexers then check if it is a real EOF
  1650. gravity_lexer_t *lexer = CURRENT_LEXER;
  1651. gravity_lexer_free(lexer);
  1652. marray_pop(*parser->lexer);
  1653. } while (marray_size(*parser->lexer));
  1654. nanotime_t t2 = nanotime();
  1655. parser->time = millitime(t1, t2);
  1656. DEBUG_PARSER("=== END PARSING ===\n");
  1657. return parser->nerrors;
  1658. }
  1659. static void parser_cleanup (gravity_parser_t *parser) {
  1660. // in case of error (so AST is not returned)
  1661. // then cleanup internal nodes
  1662. gnode_t *node= gnode_block_stat_create(NODE_LIST_STAT, NO_TOKEN, parser->statements);
  1663. gnode_free(node);
  1664. }
  1665. static void parser_appendcode (const char *source, gravity_parser_t *parser) {
  1666. if (source == NULL) return;
  1667. size_t len = strlen(source);
  1668. if (len <= 0) return;
  1669. // build a new lexer based on source code to prepend
  1670. gravity_lexer_t *lexer1 = gravity_lexer_create(source, len, 0, true);
  1671. if (!lexer1) return;
  1672. // pop current lexer
  1673. gravity_lexer_t *lexer2 = POP_LEXER;
  1674. // swap lexer2 with lexer1
  1675. marray_push(gravity_lexer_t*, *parser->lexer, lexer1);
  1676. marray_push(gravity_lexer_t*, *parser->lexer, lexer2);
  1677. }
  1678. // MARK: - Public functions -
  1679. gravity_parser_t *gravity_parser_create (const char *source, size_t len, uint32_t fileid, bool is_static) {
  1680. init_grammer_rules();
  1681. gravity_parser_t *parser = mem_alloc(sizeof(gravity_parser_t));
  1682. if (!parser) return NULL;
  1683. gravity_lexer_t *lexer = gravity_lexer_create(source, len, fileid, is_static);
  1684. if (!lexer) goto abort_init;
  1685. parser->lexer = mem_alloc(sizeof(lexer_r));
  1686. marray_init(*parser->lexer);
  1687. marray_push(gravity_lexer_t*, *parser->lexer, lexer);
  1688. parser->statements = gnode_array_create();
  1689. if (!parser->statements) goto abort_init;
  1690. marray_init(parser->declarations);
  1691. parser->last_error_lineno = UINT32_MAX;
  1692. return parser;
  1693. abort_init:
  1694. gravity_parser_free(parser);
  1695. return NULL;
  1696. }
  1697. gnode_t *gravity_parser_run (gravity_parser_t *parser, gravity_delegate_t *delegate) {
  1698. parser->delegate = delegate;
  1699. gravity_lexer_setdelegate(CURRENT_LEXER, delegate);
  1700. // check if some user code needs to be prepended
  1701. if ((delegate) && (delegate->precode_callback))
  1702. parser_appendcode(delegate->precode_callback(delegate->xdata), parser);
  1703. // if there are syntax errors then just returns
  1704. if (parser_run(parser) > 0) {
  1705. parser_cleanup (parser);
  1706. return NULL;
  1707. }
  1708. // if there are some open declarations then there should be an error somewhere
  1709. if (marray_size(parser->declarations) > 0) return NULL;
  1710. // return ast
  1711. return gnode_block_stat_create(NODE_LIST_STAT, NO_TOKEN, parser->statements);
  1712. }
  1713. void gravity_parser_free (gravity_parser_t *parser) {
  1714. // free memory for stack of lexers
  1715. if (parser->lexer) {
  1716. size_t _len = marray_size(*parser->lexer);
  1717. for (size_t i=0; i<_len; ++i) {
  1718. gravity_lexer_t *lexer = (gravity_lexer_t *)marray_get(*parser->lexer, i);
  1719. gravity_lexer_free(lexer);
  1720. }
  1721. marray_destroy(*parser->lexer);
  1722. mem_free(parser->lexer);
  1723. }
  1724. marray_destroy(parser->declarations);
  1725. // parser->statements is returned from gravity_parser_run
  1726. // and must be deallocated using gnode_free
  1727. mem_free(parser);
  1728. }