compiler.c 23 KB

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