compiler.c 22 KB

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