compiler.c 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699
  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. typedef struct {
  17. Token current;
  18. Token previous;
  19. bool hadError;
  20. bool panicMode;
  21. } Parser;
  22. typedef enum {
  23. PREC_NONE,
  24. PREC_ASSIGNMENT,// =
  25. PREC_OR, // or
  26. PREC_AND, // and
  27. PREC_EQUALITY, // == !=
  28. PREC_COMPARISON,// < > <= >=
  29. PREC_TERM, // + -
  30. PREC_FACTOR, // * /
  31. PREC_UNARY, // ! -
  32. PREC_CALL, // . ()
  33. PREC_PRIMARY
  34. } Precedence;
  35. typedef void (*ParseFn)(bool canAssign);
  36. typedef struct {
  37. ParseFn prefix;
  38. ParseFn infix;
  39. Precedence precedence;
  40. } ParseRule;
  41. typedef struct {
  42. Token name;
  43. int depth;
  44. } Local;
  45. typedef struct {
  46. Local locals[UINT8_COUNT];
  47. int localCount;/// how many locals are in scope
  48. int scopeDepth;
  49. } Compiler;
  50. Parser parser;
  51. Compiler *current = NULL;
  52. Chunk *compilingChunk;
  53. static void parsePrecedence(Precedence);
  54. static uint8_t parseVariable(const char *);
  55. static void defineVariable(uint8_t);
  56. static uint8_t identifierConstant(Token *name);
  57. static bool identifiersEqual(Token *a, Token *b);
  58. static ParseRule *getRule(TokenType);
  59. static void statement();
  60. static void declaration();
  61. static void beginScope();
  62. static void endScope();
  63. static Chunk *currentChunk() {
  64. return compilingChunk;
  65. }
  66. static void errorAt(Token *token, const char *message) {
  67. if (parser.panicMode) return;
  68. parser.panicMode = true;
  69. fprintf(stderr, "[line %d] Error", token->line);
  70. if (token->type == TOKEN_EOF) {
  71. fprintf(stderr, " at end");
  72. } else if (token->type == TOKEN_ERROR) {
  73. ///! Nothing.
  74. } else {
  75. fprintf(stderr, " at '%.*s'", token->length, token->start);
  76. }
  77. fprintf(stderr, ": %s\n", message);
  78. parser.hadError = true;
  79. }
  80. static void error(const char *message) {
  81. errorAt(&parser.previous, message);
  82. }
  83. static void errorAtCurrent(const char *message) {
  84. errorAt(&parser.current, message);
  85. }
  86. static void advance() {
  87. parser.previous = parser.current;
  88. for (;;) {
  89. parser.current = scanToken();
  90. if (parser.current.type != TOKEN_ERROR) break;
  91. errorAtCurrent(parser.current.start);
  92. }
  93. }
  94. void consume(TokenType type, const char *message) {
  95. if (parser.current.type == type) {
  96. advance();
  97. return;
  98. }
  99. errorAtCurrent(message);
  100. }
  101. static bool check(TokenType type) {
  102. return parser.current.type == type;
  103. }
  104. static bool match(TokenType type) {
  105. if (!check(type)) return false;
  106. advance();
  107. return true;
  108. }
  109. static void emitByte(uint8_t byte) {
  110. writeChunk(currentChunk(), byte, parser.previous.line);
  111. }
  112. static void emitBytes(uint8_t byte1, uint8_t byte2) {
  113. emitByte(byte1);
  114. emitByte(byte2);
  115. }
  116. static void emitLoop(int loopStart) {
  117. emitByte(OP_LOOP);
  118. int offset = currentChunk()->count - loopStart + 2;
  119. if (offset > UINT16_MAX) error("Loop body too large.");
  120. emitByte((offset >> 8) & 0xFF);
  121. emitByte(offset & 0xFF);
  122. }
  123. static int emitJump(uint8_t instruction) {
  124. emitByte(instruction);
  125. emitByte(0xff);// 占位字节,后面填入需要跳转的 offset
  126. emitByte(0xff);//
  127. return currentChunk()->count - 2;
  128. }
  129. static void emitReturn() {
  130. emitByte(OP_RETURN);
  131. }
  132. static uint8_t makeConstant(Value value) {
  133. int constant = addConstant(currentChunk(), value);
  134. if (constant > UINT8_MAX) {
  135. error("Too many constants in one chunk.");
  136. return 0;
  137. }
  138. return (uint8_t) constant;
  139. }
  140. static void expression() {
  141. parsePrecedence(PREC_ASSIGNMENT);
  142. }
  143. /// for example: var a; var b = 10;
  144. static void varDeclaration() {
  145. uint8_t global = parseVariable("Expect variable name.");
  146. // 变量初始化
  147. if (match(TOKEN_EQUAL)) {
  148. expression();
  149. } else {
  150. emitByte(OP_NIL);
  151. }
  152. consume(TOKEN_SEMICOLON, "Expect ';' after variable declaration.");
  153. defineVariable(global);
  154. }
  155. static void expressionStatement() {
  156. expression();
  157. consume(TOKEN_SEMICOLON, "Expect ';' after expression.");
  158. emitByte(OP_POP);
  159. }
  160. static void patchJump(int offset) {
  161. // -2 to adjust for the bytecode for the jump offset itself.
  162. int jump = currentChunk()->count - offset - 2;
  163. if (jump > UINT16_MAX) error("Too much code to jump over.");
  164. currentChunk()->code[offset] = (jump >> 8) & 0xFF;
  165. currentChunk()->code[offset + 1] = jump & 0xFF;
  166. }
  167. static void forStatement() {
  168. /**
  169. * *********************************************************
  170. * initializer clause
  171. * L4: condition expression
  172. * OP_JUMP_IF_FALSE L1
  173. * OP_POP
  174. * OP_JUMP L3
  175. * L2: increment expression
  176. * OP_POP
  177. * OP_LOOP L4
  178. * L3: body statement
  179. * OP_LOOP L2
  180. * L1: OP_POP
  181. * continues...
  182. * *********************************************************
  183. */
  184. beginScope();
  185. // for(I;II;III)
  186. consume(TOKEN_LEFT_PAREN, "Expect '(' after 'for'.");
  187. ///! I.<<Initializer Part>>
  188. if (match(TOKEN_SEMICOLON)) {
  189. // No initializer.
  190. } else if (match(TOKEN_VAR)) {
  191. varDeclaration();
  192. } else {
  193. expressionStatement();// ; op_pop
  194. }
  195. ///! II.<<Condition Part>>
  196. int loopStart = currentChunk()->count;
  197. int exitJump = -1;
  198. if (!match(TOKEN_SEMICOLON)) {
  199. expression();
  200. consume(TOKEN_SEMICOLON, "Expect ';' after loop conditon. ");
  201. // Jump out of the loop if the condition is false.
  202. exitJump = emitJump(OP_JUMP_IF_FALSE);
  203. emitByte(OP_POP);
  204. }
  205. ///! III.<<Increment Clause>>
  206. if (!match(TOKEN_RIGHT_PAREN)) {
  207. int bodyJump = emitJump(OP_JUMP);
  208. int incrementStart = currentChunk()->count;
  209. expression();
  210. emitByte(OP_POP);
  211. consume(TOKEN_RIGHT_PAREN, "Expect ')' after for clauses.");
  212. emitLoop(loopStart);
  213. loopStart = incrementStart;
  214. patchJump(bodyJump);
  215. }
  216. ///! <<Body Part>>
  217. statement();
  218. emitLoop(loopStart);
  219. if (exitJump != -1) {
  220. patchJump(exitJump);
  221. emitByte(OP_POP);// Condition.
  222. }
  223. endScope();
  224. }
  225. static void ifStatement() {
  226. consume(TOKEN_LEFT_PAREN, "Expect '(' after 'if'.");
  227. expression();
  228. consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
  229. int thenJump = emitJump(OP_JUMP_IF_FALSE);
  230. emitByte(OP_POP);
  231. statement();// then branch statement
  232. int elseJump = emitJump(OP_JUMP);
  233. patchJump(thenJump);
  234. emitByte(OP_POP);
  235. if (match(TOKEN_ELSE)) statement();// else branch statement
  236. patchJump(elseJump);
  237. }
  238. static void whileStatement() {
  239. int loopStart = currentChunk()->count;
  240. consume(TOKEN_LEFT_PAREN, "Expect '(' after 'while'.");
  241. expression();// while condition.
  242. consume(TOKEN_RIGHT_PAREN, "Expect ')' after condition.");
  243. int exitJump = emitJump(OP_JUMP_IF_FALSE);
  244. emitByte(OP_POP);
  245. statement();// while body.
  246. emitLoop(loopStart);
  247. patchJump(exitJump);
  248. emitByte(OP_POP);
  249. }
  250. static void printStatement() {
  251. expression();
  252. consume(TOKEN_SEMICOLON, "Expect ';' after value.");
  253. emitByte(OP_PRINT);
  254. }
  255. static void synchronize() {
  256. parser.panicMode = false;
  257. while (parser.current.type != TOKEN_EOF) {
  258. if (parser.previous.type == TOKEN_SEMICOLON) return;
  259. switch (parser.current.type) {
  260. case TOKEN_CLASS:
  261. case TOKEN_FUN:
  262. case TOKEN_VAR:
  263. case TOKEN_FOR:
  264. case TOKEN_IF:
  265. case TOKEN_WHILE:
  266. case TOKEN_PRINT:
  267. case TOKEN_RETURN:
  268. return;
  269. default:;// Do nothing.
  270. }
  271. advance();
  272. }
  273. }
  274. ///declaration → classDecl
  275. /// | funDecl
  276. /// | varDecl
  277. /// | statement ;
  278. static void declaration() {
  279. if (match(TOKEN_VAR)) {
  280. varDeclaration();
  281. } else {
  282. statement();
  283. }
  284. if (parser.panicMode) synchronize();
  285. }
  286. static void block() {
  287. while (!check(TOKEN_RIGHT_BRACE) && !check(TOKEN_EOF)) {
  288. declaration();
  289. }
  290. consume(TOKEN_RIGHT_BRACE, "Expect '}' after block.");
  291. }
  292. ///statement → exprStmt
  293. /// | forStmt
  294. /// | ifStmt
  295. /// | printStmt
  296. /// | returnStmt
  297. /// | whileStmt
  298. /// | block ;
  299. static void statement() {
  300. if (match(TOKEN_PRINT)) {
  301. printStatement();
  302. } else if (match(TOKEN_FOR)) {
  303. forStatement();
  304. } else if (match(TOKEN_IF)) {
  305. ifStatement();
  306. } else if (match(TOKEN_WHILE)) {
  307. whileStatement();
  308. } else if (match(TOKEN_LEFT_BRACE)) {
  309. ///! block → "{" declaration* "}" ;
  310. beginScope();
  311. block();
  312. endScope();
  313. } else {
  314. expressionStatement();
  315. }
  316. }
  317. static void beginScope() {
  318. current->scopeDepth++;
  319. }
  320. static void endScope() {
  321. current->scopeDepth--;
  322. while (current->localCount > 0
  323. && current->locals[current->localCount - 1].depth > current->scopeDepth) {
  324. emitByte(OP_POP);
  325. current->localCount--;
  326. }
  327. }
  328. static void emitConstant(Value value) {
  329. emitBytes(OP_CONSTANT, makeConstant(value));
  330. }
  331. static void initCompiler(Compiler *compiler) {
  332. compiler->localCount = 0;
  333. compiler->scopeDepth = 0;
  334. current = compiler;
  335. }
  336. static void endCompiler() {
  337. emitReturn();
  338. #ifdef DEBUG_PRINT_CODE
  339. if (!parser.hadError) {
  340. disassembleChunk(currentChunk(), "code");
  341. }
  342. #endif
  343. }
  344. static void grouping(__attribute__((unused)) bool canAssign) {
  345. expression();
  346. consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression.");
  347. }
  348. /// \brief parse number token
  349. /// Number literals: 123
  350. static void number(__attribute__((unused)) bool canAssign) {
  351. double value = strtod(parser.previous.start, NULL);
  352. emitConstant(NUMBER_VAL(value));
  353. }
  354. static void string(__attribute__((unused)) bool canAssign) {
  355. emitConstant(OBJ_VAL(copyString(parser.previous.start + 1,
  356. parser.previous.length - 2)));
  357. }
  358. static void and_(__attribute__((unused)) bool canAssign) {
  359. /// left operand expression
  360. /// OP_JUMP_IF_FALSE b
  361. /// OP_POP
  362. /// right operand expression
  363. /// b: continues...
  364. int endJump = emitJump(OP_JUMP_IF_FALSE);
  365. emitByte(OP_POP);
  366. parsePrecedence(PREC_AND);// right operand expression
  367. patchJump(endJump);
  368. }
  369. static void or_(__attribute__((unused)) bool canAssign) {
  370. /// left operand expression
  371. /// OP_JUMP_IF_FALSE b1
  372. /// OP_JUMP b2
  373. /// b1: OP_POP
  374. /// right operand expression
  375. /// b2: continue
  376. int elseJump = emitJump(OP_JUMP_IF_FALSE);
  377. int endJump = emitJump(OP_JUMP);
  378. patchJump(elseJump);
  379. emitByte(OP_POP);
  380. parsePrecedence(PREC_OR);// right operand expression
  381. patchJump(endJump);
  382. }
  383. static int resolveLocal(Compiler *compile, Token *name) {
  384. for (int i = compile->localCount - 1; i >= 0; i--) {
  385. Local *local = &compile->locals[i];
  386. if (identifiersEqual(name, &local->name)) {
  387. if (local->depth == -1) {
  388. error("Can't read local variable in ints own initializer.");
  389. }
  390. return i;
  391. }
  392. }
  393. return -1;
  394. }
  395. static void namedVariable(Token name, bool canAssign) {
  396. uint8_t getOp, setOp;
  397. int arg = resolveLocal(current, &name);
  398. if (arg != -1) {
  399. getOp = OP_GET_LOCAL;
  400. setOp = OP_SET_LOCAL;
  401. } else {
  402. arg = identifierConstant(&name);
  403. getOp = OP_GET_GLOBAL;
  404. setOp = OP_SET_GLOBAL;
  405. }
  406. if (canAssign && match(TOKEN_EQUAL)) {
  407. // 如 menu.brunch(sunday).beverage = "mimosa";
  408. expression();
  409. emitBytes(setOp, (uint8_t) arg);
  410. } else {
  411. emitBytes(getOp, (uint8_t) arg);
  412. }
  413. }
  414. static void variable(bool canAssign) {
  415. namedVariable(parser.previous, canAssign);
  416. }
  417. /// Unary negation: -123
  418. static void unary(__attribute__((unused)) bool canAssign) {
  419. TokenType operatorType = parser.previous.type;
  420. // Compile the operand.
  421. parsePrecedence(PREC_UNARY);
  422. // Emit the operator instruction.
  423. switch (operatorType) {
  424. case TOKEN_BANG:
  425. emitByte(OP_NOT);
  426. break;
  427. case TOKEN_MINUS:
  428. emitByte(OP_NEGATE);
  429. break;
  430. default: return;// Unreachable.
  431. }
  432. }
  433. /// \brief infix parser
  434. static void binary(__attribute__((unused)) bool canAssign) {
  435. TokenType operatorType = parser.previous.type;
  436. ParseRule *rule = getRule(operatorType);
  437. parsePrecedence((Precedence) rule->precedence + 1);
  438. switch (operatorType) {
  439. case TOKEN_BANG_EQUAL:
  440. emitBytes(OP_EQUAL, OP_NOT);
  441. break;
  442. case TOKEN_EQUAL_EQUAL:
  443. emitByte(OP_EQUAL);
  444. break;
  445. case TOKEN_GREATER:
  446. emitByte(OP_GREATER);
  447. break;
  448. case TOKEN_GREATER_EQUAL:
  449. emitBytes(OP_LESS, OP_NOT);
  450. break;
  451. case TOKEN_LESS:
  452. emitByte(OP_LESS);
  453. break;
  454. case TOKEN_LESS_EQUAL:
  455. emitBytes(OP_GREATER, OP_NOT);
  456. break;
  457. case TOKEN_PLUS:
  458. emitByte(OP_ADD);
  459. break;
  460. case TOKEN_MINUS:
  461. emitByte(OP_SUBTRACT);
  462. break;
  463. case TOKEN_STAR:
  464. emitByte(OP_MULTIPLY);
  465. break;
  466. case TOKEN_SLASH:
  467. emitByte(OP_DIVIDE);
  468. break;
  469. default: return;// Unreachable.
  470. }
  471. }
  472. static void literal(__attribute__((unused)) bool canAssign) {
  473. switch (parser.previous.type) {
  474. case TOKEN_FALSE:
  475. emitByte(OP_FALSE);
  476. break;
  477. case TOKEN_NIL:
  478. emitByte(OP_NIL);
  479. break;
  480. case TOKEN_TRUE:
  481. emitByte(OP_TRUE);
  482. break;
  483. default: return;// Unreachable
  484. }
  485. }
  486. ParseRule rules[] = {
  487. [TOKEN_LEFT_PAREN] = {grouping, NULL, PREC_NONE},
  488. [TOKEN_RIGHT_PAREN] = {NULL, NULL, PREC_NONE},
  489. [TOKEN_LEFT_BRACE] = {NULL, NULL, PREC_NONE},
  490. [TOKEN_RIGHT_BRACE] = {NULL, NULL, PREC_NONE},
  491. [TOKEN_COMMA] = {NULL, NULL, PREC_NONE},
  492. [TOKEN_DOT] = {NULL, NULL, PREC_NONE},
  493. [TOKEN_MINUS] = {unary, binary, PREC_TERM},
  494. [TOKEN_PLUS] = {NULL, binary, PREC_TERM},
  495. [TOKEN_SEMICOLON] = {NULL, NULL, PREC_NONE},
  496. [TOKEN_SLASH] = {NULL, binary, PREC_FACTOR},
  497. [TOKEN_STAR] = {NULL, binary, PREC_FACTOR},
  498. [TOKEN_BANG] = {unary, NULL, PREC_NONE},
  499. [TOKEN_BANG_EQUAL] = {NULL, binary, PREC_EQUALITY},
  500. [TOKEN_EQUAL] = {NULL, NULL, PREC_NONE},
  501. [TOKEN_EQUAL_EQUAL] = {NULL, binary, PREC_EQUALITY},
  502. [TOKEN_GREATER] = {NULL, binary, PREC_COMPARISON},
  503. [TOKEN_GREATER_EQUAL] = {NULL, binary, PREC_COMPARISON},
  504. [TOKEN_LESS] = {NULL, binary, PREC_COMPARISON},
  505. [TOKEN_LESS_EQUAL] = {NULL, binary, PREC_COMPARISON},
  506. [TOKEN_IDENTIFIER] = {variable, NULL, PREC_NONE},
  507. [TOKEN_STRING] = {string, NULL, PREC_NONE},
  508. [TOKEN_NUMBER] = {number, NULL, PREC_NONE},
  509. [TOKEN_AND] = {NULL, and_, PREC_AND},
  510. [TOKEN_CLASS] = {NULL, NULL, PREC_NONE},
  511. [TOKEN_ELSE] = {NULL, NULL, PREC_NONE},
  512. [TOKEN_FALSE] = {literal, NULL, PREC_NONE},
  513. [TOKEN_FOR] = {NULL, NULL, PREC_NONE},
  514. [TOKEN_FUN] = {NULL, NULL, PREC_NONE},
  515. [TOKEN_IF] = {NULL, NULL, PREC_NONE},
  516. [TOKEN_NIL] = {literal, NULL, PREC_NONE},
  517. [TOKEN_OR] = {NULL, or_, PREC_OR},
  518. [TOKEN_PRINT] = {NULL, NULL, PREC_NONE},
  519. [TOKEN_RETURN] = {NULL, NULL, PREC_NONE},
  520. [TOKEN_SUPER] = {NULL, NULL, PREC_NONE},
  521. [TOKEN_THIS] = {NULL, NULL, PREC_NONE},
  522. [TOKEN_TRUE] = {literal, NULL, PREC_NONE},
  523. [TOKEN_VAR] = {NULL, NULL, PREC_NONE},
  524. [TOKEN_WHILE] = {NULL, NULL, PREC_NONE},
  525. [TOKEN_ERROR] = {NULL, NULL, PREC_NONE},
  526. [TOKEN_EOF] = {NULL, NULL, PREC_NONE},
  527. };
  528. /// \brief 优先级处理
  529. /// \param precedence
  530. static void parsePrecedence(Precedence precedence) {
  531. advance();
  532. ParseFn prefixRule = getRule(parser.previous.type)->prefix;
  533. if (prefixRule == NULL) {
  534. error("Expect expression.");
  535. return;
  536. }
  537. bool canAssign = precedence <= PREC_ASSIGNMENT;
  538. prefixRule(canAssign);///! 执行具体函数
  539. while (precedence <= getRule(parser.current.type)->precedence) {
  540. advance();
  541. ParseFn infixRule = getRule(parser.previous.type)->infix;
  542. infixRule(canAssign);///! 执行具体函数
  543. }
  544. if (canAssign && match(TOKEN_EQUAL)) {
  545. error("Invalid assignment target.");
  546. }
  547. }
  548. static uint8_t identifierConstant(Token *name) {
  549. return makeConstant(OBJ_VAL(copyString(name->start, name->length)));
  550. }
  551. static bool identifiersEqual(Token *a, Token *b) {
  552. if (a->length != b->length) return false;
  553. return memcmp(a->start, b->start, a->length) == 0;
  554. }
  555. static void addLocal(Token name) {
  556. if (current->localCount == UINT8_COUNT) {
  557. error("Too many local variables in function.");
  558. return;
  559. }
  560. Local *local = &current->locals[current->localCount++];
  561. local->name = name;
  562. local->depth = -1;// 未初始化
  563. }
  564. static void declareVariable() {
  565. if (current->scopeDepth == 0) return;
  566. Token *name = &parser.previous;
  567. // we detect the error like:
  568. // {
  569. // var a = "first";
  570. // var a = "second";
  571. // }
  572. for (int i = current->localCount - 1; i >= 0; i--) {
  573. Local *local = &current->locals[i];
  574. if (local->depth != -1 && local->depth < current->scopeDepth) {
  575. break;
  576. }
  577. if (identifiersEqual(name, &local->name)) {
  578. error("Already a variable with the name in this scope.");
  579. }
  580. }
  581. addLocal(*name);
  582. }
  583. static uint8_t parseVariable(const char *errorMessage) {
  584. consume(TOKEN_IDENTIFIER, errorMessage);
  585. declareVariable();// 处理本地变量
  586. if (current->scopeDepth > 0) return 0;
  587. return identifierConstant(&parser.previous);
  588. }
  589. static void defineVariable(uint8_t global) {
  590. if (current->scopeDepth > 0) {
  591. // markInitialized 未初始化时值 为 -1
  592. current->locals[current->localCount - 1].depth = current->scopeDepth;
  593. // 本地变量,直接退出
  594. return;
  595. }
  596. emitBytes(OP_DEFINE_GLOBAL, global);
  597. }
  598. static ParseRule *getRule(TokenType type) {
  599. return &rules[type];
  600. }
  601. /**
  602. ******************************************************************************
  603. * statement → exprStmt
  604. | forStmt
  605. | ifStmt
  606. | printStmt
  607. | returnStmt
  608. | whileStmt
  609. | block ;
  610. block → "{" declaration* "}" ;
  611. declaration → classDecl
  612. | funDecl
  613. | varDecl
  614. | statement ;
  615. ******************************************************************************
  616. */
  617. bool compile(const char *source, Chunk *chunk) {
  618. Compiler compiler;
  619. initScanner(source);
  620. initCompiler(&compiler);
  621. compilingChunk = chunk;
  622. parser.hadError = false;
  623. parser.panicMode = false;
  624. advance();
  625. while (!match(TOKEN_EOF)) {
  626. declaration();
  627. }
  628. endCompiler();//! return opcode
  629. return !parser.hadError;
  630. }