compiler.c 20 KB

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