compiler.c 23 KB

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