compiler.c 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  1. /**
  2. ******************************************************************************
  3. * @file : compiler.c
  4. * @author : simon
  5. * @brief : None
  6. * @attention : None
  7. * @date : 2023/8/17
  8. ******************************************************************************
  9. */
  10. #include "compiler.h"
  11. #include "common.h"
  12. #include "scanner.h"
  13. #ifdef DEBUG_PRINT_CODE
  14. #include "debug.h"
  15. #endif
  16. #include "memory.h"
  17. typedef struct {
  18. Token current;
  19. Token previous;
  20. bool hadError;
  21. bool panicMode;
  22. } Parser;
  23. typedef enum {
  24. PREC_NONE,
  25. PREC_ASSIGNMENT,// =
  26. PREC_OR, // or
  27. PREC_AND, // and
  28. PREC_EQUALITY, // == !=
  29. PREC_COMPARISON,// < > <= >=
  30. PREC_TERM, // + -
  31. PREC_FACTOR, // * /
  32. PREC_UNARY, // ! -
  33. PREC_CALL, // . ()
  34. PREC_PRIMARY
  35. } Precedence;
  36. typedef void (*ParseFn)(bool canAssign);
  37. typedef struct {
  38. ParseFn prefix;
  39. ParseFn infix;
  40. Precedence precedence;
  41. } ParseRule;
  42. typedef struct {
  43. Token name;
  44. int depth;
  45. bool isCaptured;
  46. } Local;
  47. typedef struct {
  48. uint8_t index;
  49. bool isLocal;
  50. } Upvalue;
  51. typedef enum {
  52. TYPE_FUNCTION,
  53. TYPE_SCRIPT,
  54. } FunctionType;
  55. typedef struct Compiler {
  56. struct Compiler *enclosing;
  57. ObjFunction *function;
  58. FunctionType type;
  59. Local locals[UINT8_COUNT];
  60. int localCount;/// how many locals are in scope
  61. Upvalue upvalues[UINT8_COUNT];
  62. int scopeDepth;
  63. } Compiler;
  64. Parser parser;
  65. Compiler *current = NULL;
  66. static void parsePrecedence(Precedence);
  67. static uint8_t parseVariable(const char *);
  68. static void defineVariable(uint8_t);
  69. static uint8_t identifierConstant(Token *name);
  70. static bool identifiersEqual(Token *a, Token *b);
  71. static ParseRule *getRule(TokenType);
  72. static void statement();
  73. static void declaration();
  74. static void markInitialized();
  75. static void initCompiler(Compiler *compiler, FunctionType type);
  76. static void beginScope();
  77. static void endScope();
  78. static void block();
  79. static ObjFunction *endCompiler();
  80. static Chunk *currentChunk() {
  81. return &current->function->chunk;
  82. }
  83. static void errorAt(Token *token, const char *message) {
  84. if (parser.panicMode) return;
  85. parser.panicMode = true;
  86. fprintf(stderr, "[line %d] Error", token->line);
  87. if (token->type == TOKEN_EOF) {
  88. fprintf(stderr, " at end");
  89. } else if (token->type == TOKEN_ERROR) {
  90. ///! Nothing.
  91. } else {
  92. fprintf(stderr, " at '%.*s'", token->length, token->start);
  93. }
  94. fprintf(stderr, ": %s\n", message);
  95. parser.hadError = true;
  96. }
  97. static void error(const char *message) {
  98. errorAt(&parser.previous, message);
  99. }
  100. static void errorAtCurrent(const char *message) {
  101. errorAt(&parser.current, message);
  102. }
  103. static void advance() {
  104. parser.previous = parser.current;
  105. for (;;) {
  106. parser.current = scanToken();
  107. if (parser.current.type != TOKEN_ERROR) break;
  108. errorAtCurrent(parser.current.start);
  109. }
  110. }
  111. void consume(TokenType type, const char *message) {
  112. if (parser.current.type == type) {
  113. advance();
  114. return;
  115. }
  116. errorAtCurrent(message);
  117. }
  118. static bool check(TokenType type) {
  119. return parser.current.type == type;
  120. }
  121. static bool match(TokenType type) {
  122. if (!check(type)) return false;
  123. advance();
  124. return true;
  125. }
  126. static void emitByte(uint8_t byte) {
  127. writeChunk(currentChunk(), byte, parser.previous.line);
  128. }
  129. static void emitBytes(uint8_t byte1, uint8_t byte2) {
  130. emitByte(byte1);
  131. emitByte(byte2);
  132. }
  133. static void emitLoop(int loopStart) {
  134. emitByte(OP_LOOP);
  135. int offset = currentChunk()->count - loopStart + 2;
  136. if (offset > UINT16_MAX) error("Loop body too large.");
  137. emitByte((offset >> 8) & 0xFF);
  138. emitByte(offset & 0xFF);
  139. }
  140. static int emitJump(uint8_t instruction) {
  141. emitByte(instruction);
  142. emitByte(0xff);// 占位字节,后面填入需要跳转的 offset
  143. emitByte(0xff);//
  144. return currentChunk()->count - 2;
  145. }
  146. static void emitReturn() {
  147. emitByte(OP_NIL);
  148. emitByte(OP_RETURN);
  149. }
  150. static uint8_t makeConstant(Value value) {
  151. int constant = addConstant(currentChunk(), value);
  152. if (constant > UINT8_MAX) {
  153. error("Too many constants in one chunk.");
  154. return 0;
  155. }
  156. return (uint8_t) constant;
  157. }
  158. static void expression() {
  159. parsePrecedence(PREC_ASSIGNMENT);
  160. }
  161. static void function(FunctionType type) {
  162. Compiler compiler;
  163. initCompiler(&compiler, type);
  164. beginScope();
  165. consume(TOKEN_LEFT_PAREN, "Expect '(' after function name.");
  166. ///! Parameters
  167. if (!check(TOKEN_RIGHT_PAREN)) {
  168. do {
  169. current->function->arity++;
  170. if (current->function->arity > 255) {
  171. errorAtCurrent("Can't have more than 255 parameters.");
  172. }
  173. uint8_t constant = parseVariable("Expect parameter name.");
  174. defineVariable(constant);
  175. } while (match(TOKEN_COMMA));
  176. }
  177. consume(TOKEN_RIGHT_PAREN, "Expect ')' after parameters.");
  178. consume(TOKEN_LEFT_BRACE, "Expect '{' before function body.");
  179. ///! Body
  180. block();
  181. ObjFunction *fun = endCompiler();
  182. emitBytes(OP_CLOSURE, makeConstant(OBJ_VAL(fun)));
  183. for (int i = 0; i < fun->upvalueCount; i++) {
  184. emitByte(compiler.upvalues[i].isLocal ? 1 : 0);
  185. emitByte(compiler.upvalues[i].index);
  186. }
  187. }
  188. static void funDeclaration() {
  189. uint8_t global = parseVariable("Expect function name.");
  190. markInitialized();
  191. function(TYPE_FUNCTION);
  192. defineVariable(global);
  193. }
  194. /// for example: var a; var b = 10;
  195. static void varDeclaration() {
  196. uint8_t global = parseVariable("Expect variable name.");
  197. // 变量初始化
  198. if (match(TOKEN_EQUAL)) {
  199. expression();
  200. } else {
  201. emitByte(OP_NIL);
  202. }
  203. consume(TOKEN_SEMICOLON, "Expect ';' after variable declaration.");
  204. defineVariable(global);
  205. }
  206. static void expressionStatement() {
  207. expression();
  208. consume(TOKEN_SEMICOLON, "Expect ';' after expression.");
  209. emitByte(OP_POP);
  210. }
  211. static void patchJump(int offset) {
  212. // -2 to adjust for the bytecode for the jump offset itself.
  213. int jump = currentChunk()->count - offset - 2;
  214. if (jump > UINT16_MAX) error("Too much code to jump over.");
  215. currentChunk()->code[offset] = (jump >> 8) & 0xFF;
  216. currentChunk()->code[offset + 1] = jump & 0xFF;
  217. }
  218. static void forStatement() {
  219. /**
  220. * *********************************************************
  221. * initializer clause
  222. * L4: condition expression
  223. * OP_JUMP_IF_FALSE L1
  224. * OP_POP
  225. * OP_JUMP L3
  226. * L2: increment expression
  227. * OP_POP
  228. * OP_LOOP L4
  229. * L3: body statement
  230. * OP_LOOP L2
  231. * L1: OP_POP
  232. * continues...
  233. * *********************************************************
  234. */
  235. beginScope();
  236. // for(I;II;III)
  237. consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");
  238. ///! I.<<Initializer Part>>
  239. if (match(TOKEN_SEMICOLON)) {
  240. // No initializer.
  241. } else if (match(TOKEN_VAR)) {
  242. varDeclaration();
  243. } else {
  244. expressionStatement();// ; op_pop
  245. }
  246. ///! II.<<Condition Part>>
  247. int loopStart = currentChunk()->count;
  248. int exitJump = -1;
  249. if (!match(TOKEN_SEMICOLON)) {
  250. expression();
  251. consume(TOKEN_SEMICOLON, "Expect ';' after loop conditon. ");
  252. // Jump out of the loop if the condition is false.
  253. exitJump = emitJump(OP_JUMP_IF_FALSE);
  254. emitByte(OP_POP);
  255. }
  256. ///! III.<<Increment Clause>>
  257. if (!match(TOKEN_RIGHT_PAREN)) {
  258. int bodyJump = emitJump(OP_JUMP);
  259. int incrementStart = currentChunk()->count;
  260. expression();
  261. emitByte(OP_POP);
  262. consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses.");
  263. emitLoop(loopStart);
  264. loopStart = incrementStart;
  265. patchJump(bodyJump);
  266. }
  267. ///! <<Body Part>>
  268. statement();
  269. emitLoop(loopStart);
  270. if (exitJump != -1) {
  271. patchJump(exitJump);
  272. emitByte(OP_POP);// Condition.
  273. }
  274. endScope();
  275. }
  276. static void returnStatement() {
  277. if (current->type == TYPE_SCRIPT) {
  278. error("Can't return from top-level code.");
  279. }
  280. if (match(TOKEN_SEMICOLON)) {
  281. emitReturn();
  282. } else {
  283. expression();
  284. consume(TOKEN_SEMICOLON, "Expect ';' after return value.");
  285. emitByte(OP_RETURN);
  286. }
  287. }
  288. static void ifStatement() {
  289. consume(TOKEN_LEFT_PAREN, "Expect '(' after 'if'.");
  290. expression();
  291. consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
  292. int thenJump = emitJump(OP_JUMP_IF_FALSE);
  293. emitByte(OP_POP);
  294. statement();// then branch statement
  295. int elseJump = emitJump(OP_JUMP);
  296. patchJump(thenJump);
  297. emitByte(OP_POP);
  298. if (match(TOKEN_ELSE)) statement();// else branch statement
  299. patchJump(elseJump);
  300. }
  301. static void whileStatement() {
  302. int loopStart = currentChunk()->count;
  303. consume(TOKEN_LEFT_PAREN, "Expect '(' after 'while'.");
  304. expression();// while condition.
  305. consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
  306. int exitJump = emitJump(OP_JUMP_IF_FALSE);
  307. emitByte(OP_POP);
  308. statement();// while body.
  309. emitLoop(loopStart);
  310. patchJump(exitJump);
  311. emitByte(OP_POP);
  312. }
  313. static void printStatement() {
  314. expression();
  315. consume(TOKEN_SEMICOLON, "Expect ';' after value.");
  316. emitByte(OP_PRINT);
  317. }
  318. static void synchronize() {
  319. parser.panicMode = false;
  320. while (parser.current.type != TOKEN_EOF) {
  321. if (parser.previous.type == TOKEN_SEMICOLON) return;
  322. switch (parser.current.type) {
  323. case TOKEN_CLASS:
  324. case TOKEN_FUN:
  325. case TOKEN_VAR:
  326. case TOKEN_FOR:
  327. case TOKEN_IF:
  328. case TOKEN_WHILE:
  329. case TOKEN_PRINT:
  330. case TOKEN_RETURN:
  331. return;
  332. default:;// Do nothing.
  333. }
  334. advance();
  335. }
  336. }
  337. ///declaration → classDecl
  338. /// | funDecl
  339. /// | varDecl
  340. /// | statement ;
  341. static void declaration() {
  342. if (match(TOKEN_FUN)) {
  343. funDeclaration();
  344. } else if (match(TOKEN_VAR)) {
  345. varDeclaration();
  346. } else {
  347. statement();
  348. }
  349. if (parser.panicMode) synchronize();
  350. }
  351. static void block() {
  352. while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) {
  353. declaration();
  354. }
  355. consume(TOKEN_RIGHT_BRACE, "Expect '}' after block.");
  356. }
  357. ///statement → exprStmt
  358. /// | forStmt
  359. /// | ifStmt
  360. /// | printStmt
  361. /// | returnStmt
  362. /// | whileStmt
  363. /// | block ;
  364. static void statement() {
  365. if (match(TOKEN_PRINT)) {
  366. printStatement();
  367. } else if (match(TOKEN_FOR)) {
  368. forStatement();
  369. } else if (match(TOKEN_IF)) {
  370. ifStatement();
  371. } else if (match(TOKEN_RETURN)) {
  372. returnStatement();
  373. } else if (match(TOKEN_WHILE)) {
  374. whileStatement();
  375. } else if (match(TOKEN_LEFT_BRACE)) {
  376. ///! block → "{" declaration* "}" ;
  377. beginScope();
  378. block();
  379. endScope();
  380. } else {
  381. expressionStatement();
  382. }
  383. }
  384. static void beginScope() {
  385. current->scopeDepth++;
  386. }
  387. static void endScope() {
  388. current->scopeDepth--;
  389. while (current->localCount > 0
  390. && current->locals[current->localCount - 1].depth > current->scopeDepth) {
  391. if (current->locals[current->localCount - 1].isCaptured) {
  392. emitByte(OP_CLOSE_UPVALUE);
  393. } else {
  394. emitByte(OP_POP);
  395. }
  396. current->localCount--;
  397. }
  398. }
  399. static void emitConstant(Value value) {
  400. emitBytes(OP_CONSTANT, makeConstant(value));
  401. }
  402. static void initCompiler(Compiler *compiler, FunctionType type) {
  403. compiler->enclosing = current;// 上一极的 compiler
  404. compiler->function = NULL;
  405. compiler->type = type;
  406. compiler->localCount = 0;
  407. compiler->scopeDepth = 0;
  408. compiler->function = newFunction();
  409. current = compiler;
  410. if (type != TYPE_SCRIPT) {
  411. ///! Function name
  412. current->function->name = copyString(parser.previous.start, parser.previous.length);
  413. }
  414. Local *local = &current->locals[current->localCount++];
  415. local->depth = 0;
  416. local->isCaptured = false;
  417. local->name.start = "";
  418. local->name.length = 0;
  419. }
  420. static ObjFunction *endCompiler() {
  421. emitReturn();
  422. ObjFunction *function = current->function;
  423. #ifdef DEBUG_PRINT_CODE
  424. if (!parser.hadError) {
  425. disassembleChunk(currentChunk(), function->name != NULL ? function->name->chars : "<script>");
  426. }
  427. #endif
  428. current = current->enclosing;// 当前的 compiler 变成上级 compiler
  429. return function;
  430. }
  431. static void grouping(__attribute__((unused)) bool canAssign) {
  432. expression();
  433. consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression.");
  434. }
  435. /// \brief parse number token
  436. /// Number literals: 123
  437. static void number(__attribute__((unused)) bool canAssign) {
  438. double value = strtod(parser.previous.start, NULL);
  439. emitConstant(NUMBER_VAL(value));
  440. }
  441. static void string(__attribute__((unused)) bool canAssign) {
  442. emitConstant(OBJ_VAL(copyString(parser.previous.start + 1,
  443. parser.previous.length - 2)));
  444. }
  445. static void and_(__attribute__((unused)) bool canAssign) {
  446. /// left operand expression
  447. /// OP_JUMP_IF_FALSE b
  448. /// OP_POP
  449. /// right operand expression
  450. /// b: continues...
  451. int endJump = emitJump(OP_JUMP_IF_FALSE);
  452. emitByte(OP_POP);
  453. parsePrecedence(PREC_AND);// right operand expression
  454. patchJump(endJump);
  455. }
  456. static void or_(__attribute__((unused)) bool canAssign) {
  457. /// left operand expression
  458. /// OP_JUMP_IF_FALSE b1
  459. /// OP_JUMP b2
  460. /// b1: OP_POP
  461. /// right operand expression
  462. /// b2: continue
  463. int elseJump = emitJump(OP_JUMP_IF_FALSE);
  464. int endJump = emitJump(OP_JUMP);
  465. patchJump(elseJump);
  466. emitByte(OP_POP);
  467. parsePrecedence(PREC_OR);// right operand expression
  468. patchJump(endJump);
  469. }
  470. static int resolveLocal(Compiler *compile, Token *name) {
  471. for (int i = compile->localCount - 1; i >= 0; i--) {
  472. Local *local = &compile->locals[i];
  473. if (identifiersEqual(name, &local->name)) {
  474. if (local->depth == -1) {
  475. error("Can't read local variable in ints own initializer.");
  476. }
  477. return i;
  478. }
  479. }
  480. return -1;
  481. }
  482. static int addUpvalue(Compiler *compiler, uint8_t index, bool isLocal) {
  483. int upvalueCount = compiler->function->upvalueCount;
  484. //! before we add a new upvalue,
  485. //! we first check to see if the function already has an upvalue
  486. //! that closes over that variable.
  487. for (int i = 0; i < upvalueCount; i++) {
  488. Upvalue *upvalue = &compiler->upvalues[i];
  489. if (upvalue->index == index && upvalue->isLocal == isLocal) {
  490. return i;
  491. }
  492. }
  493. if (upvalueCount == UINT8_COUNT) {
  494. error("Too many closure variable in function.");
  495. return 0;
  496. }
  497. compiler->upvalues[upvalueCount].isLocal = isLocal;
  498. compiler->upvalues[upvalueCount].index = index;
  499. return compiler->function->upvalueCount++;
  500. }
  501. static int resolveUpvalue(Compiler *compiler, Token *name) {
  502. if (compiler->enclosing == NULL) return -1;
  503. int local = resolveLocal(compiler->enclosing, name);
  504. if (local != -1) {
  505. compiler->enclosing->locals[local].isCaptured = true;
  506. return addUpvalue(compiler, (uint8_t) local, true);
  507. }
  508. // 递归
  509. int upvalue = resolveUpvalue(compiler->enclosing, name);
  510. if (upvalue != -1) {
  511. return addUpvalue(compiler, (uint8_t) upvalue, false);
  512. }
  513. return -1;
  514. }
  515. static void namedVariable(Token name, bool canAssign) {
  516. uint8_t getOp, setOp;
  517. int arg = resolveLocal(current, &name);
  518. if (arg != -1) {
  519. getOp = OP_GET_LOCAL;
  520. setOp = OP_SET_LOCAL;
  521. } else if ((arg = resolveUpvalue(current, &name)) != -1) {
  522. getOp = OP_GET_UPVALUE;
  523. setOp = OP_SET_UPVALUE;
  524. } else {
  525. arg = identifierConstant(&name);
  526. getOp = OP_GET_GLOBAL;
  527. setOp = OP_SET_GLOBAL;
  528. }
  529. if (canAssign && match(TOKEN_EQUAL)) {
  530. // 如 menu.brunch(sunday).beverage = "mimosa";
  531. expression();
  532. emitBytes(setOp, (uint8_t) arg);
  533. } else {
  534. emitBytes(getOp, (uint8_t) arg);
  535. }
  536. }
  537. static void variable(bool canAssign) {
  538. namedVariable(parser.previous, canAssign);
  539. }
  540. /// Unary negation: -123
  541. static void unary(__attribute__((unused)) bool canAssign) {
  542. TokenType operatorType = parser.previous.type;
  543. // Compile the operand.
  544. parsePrecedence(PREC_UNARY);
  545. // Emit the operator instruction.
  546. switch (operatorType) {
  547. case TOKEN_BANG:
  548. emitByte(OP_NOT);
  549. break;
  550. case TOKEN_MINUS:
  551. emitByte(OP_NEGATE);
  552. break;
  553. default: return;// Unreachable.
  554. }
  555. }
  556. /// \brief infix parser
  557. static void binary(__attribute__((unused)) bool canAssign) {
  558. TokenType operatorType = parser.previous.type;
  559. ParseRule *rule = getRule(operatorType);
  560. parsePrecedence((Precedence) rule->precedence + 1);
  561. switch (operatorType) {
  562. case TOKEN_BANG_EQUAL:
  563. emitBytes(OP_EQUAL, OP_NOT);
  564. break;
  565. case TOKEN_EQUAL_EQUAL:
  566. emitByte(OP_EQUAL);
  567. break;
  568. case TOKEN_GREATER:
  569. emitByte(OP_GREATER);
  570. break;
  571. case TOKEN_GREATER_EQUAL:
  572. emitBytes(OP_LESS, OP_NOT);
  573. break;
  574. case TOKEN_LESS:
  575. emitByte(OP_LESS);
  576. break;
  577. case TOKEN_LESS_EQUAL:
  578. emitBytes(OP_GREATER, OP_NOT);
  579. break;
  580. case TOKEN_PLUS:
  581. emitByte(OP_ADD);
  582. break;
  583. case TOKEN_MINUS:
  584. emitByte(OP_SUBTRACT);
  585. break;
  586. case TOKEN_STAR:
  587. emitByte(OP_MULTIPLY);
  588. break;
  589. case TOKEN_SLASH:
  590. emitByte(OP_DIVIDE);
  591. break;
  592. default: return;// Unreachable.
  593. }
  594. }
  595. static uint8_t argumentList() {
  596. uint8_t argCount = 0;
  597. if (!check(TOKEN_RIGHT_PAREN)) {
  598. do {
  599. expression();
  600. if (argCount == 255) error("Can't have more than 255 arguments.");
  601. argCount++;
  602. } while (match(TOKEN_COMMA));
  603. }
  604. consume(TOKEN_RIGHT_PAREN, "Expect ')' after arguments.");
  605. return argCount;
  606. }
  607. /// Function call expression is kind of an infix ( operator.
  608. /// You have a high-precedence expression on the left for the thing
  609. /// being called - usually just a single identifier.
  610. /// Then the ( in the middle, followed by the argument expressions
  611. /// separated by commas, and a final ) to wrap it up at the end.
  612. static void call(__attribute__((unused)) bool canAssign) {
  613. uint8_t argCount = argumentList();
  614. emitBytes(OP_CALL, argCount);
  615. }
  616. static void literal(__attribute__((unused)) bool canAssign) {
  617. switch (parser.previous.type) {
  618. case TOKEN_FALSE:
  619. emitByte(OP_FALSE);
  620. break;
  621. case TOKEN_NIL:
  622. emitByte(OP_NIL);
  623. break;
  624. case TOKEN_TRUE:
  625. emitByte(OP_TRUE);
  626. break;
  627. default: return;// Unreachable
  628. }
  629. }
  630. ParseRule rules[] = {
  631. [TOKEN_LEFT_PAREN] = {grouping, call, PREC_CALL},
  632. [TOKEN_RIGHT_PAREN] = {NULL, NULL, PREC_NONE},
  633. [TOKEN_LEFT_BRACE] = {NULL, NULL, PREC_NONE},
  634. [TOKEN_RIGHT_BRACE] = {NULL, NULL, PREC_NONE},
  635. [TOKEN_COMMA] = {NULL, NULL, PREC_NONE},
  636. [TOKEN_DOT] = {NULL, NULL, PREC_NONE},
  637. [TOKEN_MINUS] = {unary, binary, PREC_TERM},
  638. [TOKEN_PLUS] = {NULL, binary, PREC_TERM},
  639. [TOKEN_SEMICOLON] = {NULL, NULL, PREC_NONE},
  640. [TOKEN_SLASH] = {NULL, binary, PREC_FACTOR},
  641. [TOKEN_STAR] = {NULL, binary, PREC_FACTOR},
  642. [TOKEN_BANG] = {unary, NULL, PREC_NONE},
  643. [TOKEN_BANG_EQUAL] = {NULL, binary, PREC_EQUALITY},
  644. [TOKEN_EQUAL] = {NULL, NULL, PREC_NONE},
  645. [TOKEN_EQUAL_EQUAL] = {NULL, binary, PREC_EQUALITY},
  646. [TOKEN_GREATER] = {NULL, binary, PREC_COMPARISON},
  647. [TOKEN_GREATER_EQUAL] = {NULL, binary, PREC_COMPARISON},
  648. [TOKEN_LESS] = {NULL, binary, PREC_COMPARISON},
  649. [TOKEN_LESS_EQUAL] = {NULL, binary, PREC_COMPARISON},
  650. [TOKEN_IDENTIFIER] = {variable, NULL, PREC_NONE},
  651. [TOKEN_STRING] = {string, NULL, PREC_NONE},
  652. [TOKEN_NUMBER] = {number, NULL, PREC_NONE},
  653. [TOKEN_AND] = {NULL, and_, PREC_AND},
  654. [TOKEN_CLASS] = {NULL, NULL, PREC_NONE},
  655. [TOKEN_ELSE] = {NULL, NULL, PREC_NONE},
  656. [TOKEN_FALSE] = {literal, NULL, PREC_NONE},
  657. [TOKEN_FOR] = {NULL, NULL, PREC_NONE},
  658. [TOKEN_FUN] = {NULL, NULL, PREC_NONE},
  659. [TOKEN_IF] = {NULL, NULL, PREC_NONE},
  660. [TOKEN_NIL] = {literal, NULL, PREC_NONE},
  661. [TOKEN_OR] = {NULL, or_, PREC_OR},
  662. [TOKEN_PRINT] = {NULL, NULL, PREC_NONE},
  663. [TOKEN_RETURN] = {NULL, NULL, PREC_NONE},
  664. [TOKEN_SUPER] = {NULL, NULL, PREC_NONE},
  665. [TOKEN_THIS] = {NULL, NULL, PREC_NONE},
  666. [TOKEN_TRUE] = {literal, NULL, PREC_NONE},
  667. [TOKEN_VAR] = {NULL, NULL, PREC_NONE},
  668. [TOKEN_WHILE] = {NULL, NULL, PREC_NONE},
  669. [TOKEN_ERROR] = {NULL, NULL, PREC_NONE},
  670. [TOKEN_EOF] = {NULL, NULL, PREC_NONE},
  671. };
  672. /// \brief 优先级处理
  673. /// \param precedence
  674. static void parsePrecedence(Precedence precedence) {
  675. advance();
  676. ParseFn prefixRule = getRule(parser.previous.type)->prefix;
  677. if (prefixRule == NULL) {
  678. error("Expect expression.");
  679. return;
  680. }
  681. bool canAssign = precedence <= PREC_ASSIGNMENT;
  682. prefixRule(canAssign);///! 执行具体函数
  683. while (precedence <= getRule(parser.current.type)->precedence) {
  684. advance();
  685. ParseFn infixRule = getRule(parser.previous.type)->infix;
  686. infixRule(canAssign);///! 执行具体函数
  687. }
  688. if (canAssign && match(TOKEN_EQUAL)) {
  689. error("Invalid assignment target.");
  690. }
  691. }
  692. static uint8_t identifierConstant(Token *name) {
  693. return makeConstant(OBJ_VAL(copyString(name->start, name->length)));
  694. }
  695. static bool identifiersEqual(Token *a, Token *b) {
  696. if (a->length != b->length) return false;
  697. return memcmp(a->start, b->start, a->length) == 0;
  698. }
  699. static void addLocal(Token name) {
  700. if (current->localCount == UINT8_COUNT) {
  701. error("Too many local variables in function.");
  702. return;
  703. }
  704. Local *local = &current->locals[current->localCount++];
  705. local->name = name;
  706. local->depth = -1;// 未初始化
  707. local->isCaptured = false;
  708. }
  709. static void declareVariable() {
  710. if (current->scopeDepth == 0) return;
  711. Token *name = &parser.previous;
  712. // we detect the error like:
  713. // {
  714. // var a = "first";
  715. // var a = "second";
  716. // }
  717. for (int i = current->localCount - 1; i >= 0; i--) {
  718. Local *local = &current->locals[i];
  719. if (local->depth != -1 && local->depth < current->scopeDepth) {
  720. break;
  721. }
  722. if (identifiersEqual(name, &local->name)) {
  723. error("Already a variable with the name in this scope.");
  724. }
  725. }
  726. addLocal(*name);
  727. }
  728. static uint8_t parseVariable(const char *errorMessage) {
  729. consume(TOKEN_IDENTIFIER, errorMessage);
  730. declareVariable();// 处理本地变量
  731. if (current->scopeDepth > 0) return 0;
  732. return identifierConstant(&parser.previous);
  733. }
  734. static void markInitialized() {
  735. if (current->scopeDepth == 0) return;
  736. current->locals[current->localCount - 1].depth = current->scopeDepth;
  737. }
  738. static void defineVariable(uint8_t global) {
  739. if (current->scopeDepth > 0) {
  740. // markInitialized 未初始化时值 为 -1
  741. markInitialized();
  742. // 本地变量,直接退出
  743. return;
  744. }
  745. emitBytes(OP_DEFINE_GLOBAL, global);
  746. }
  747. static ParseRule *getRule(TokenType type) {
  748. return &rules[type];
  749. }
  750. /**
  751. ******************************************************************************
  752. * statement → exprStmt
  753. | forStmt
  754. | ifStmt
  755. | printStmt
  756. | returnStmt
  757. | whileStmt
  758. | block ;
  759. block → "{" declaration* "}" ;
  760. declaration → classDecl
  761. | funDecl
  762. | varDecl
  763. | statement ;
  764. ******************************************************************************
  765. */
  766. ObjFunction *compile(const char *source) {
  767. initScanner(source);
  768. Compiler compiler;
  769. initCompiler(&compiler, TYPE_SCRIPT);
  770. parser.hadError = false;
  771. parser.panicMode = false;
  772. advance();
  773. while (!match(TOKEN_EOF)) {
  774. declaration();
  775. }
  776. ObjFunction *function = endCompiler();
  777. return parser.hadError ? NULL : function;
  778. }
  779. void markCompilerRoots() {
  780. Compiler *compiler = current;
  781. while (compiler != NULL) {
  782. markObject((Obj *) compiler->function);
  783. compiler = compiler->enclosing;
  784. }
  785. }