compiler.c 21 KB

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