Skip to content
This repository was archived by the owner on Jul 19, 2025. It is now read-only.

Conversation

@Zffu
Copy link
Member

@Zffu Zffu commented Dec 14, 2024

Summary by CodeRabbit

  • New Features

    • Added support for parsing assembly function declarations in the lexer and parser.
    • Introduced new token type ASM_FUNCTION for assembly functions.
    • Added new AST node type AST_ASM_FUNCTION_DECLARATION for assembly function declarations.
  • Bug Fixes

    • Enhanced error handling for assembly function parsing.
  • Documentation

    • Updated documentation to reflect new features related to assembly functions.

@coderabbitai
Copy link

coderabbitai bot commented Dec 14, 2024

Walkthrough

The pull request introduces support for assembly function declarations in the compiler. This involves extending the lexer to recognize a new "asmf" keyword, adding a corresponding token type, updating the Abstract Syntax Tree (AST) to include a new node type for assembly function declarations, and modifying the parser to handle the new syntax. The changes are focused on expanding the language's capabilities by allowing inline assembly function definitions with a specific parsing mechanism.

Changes

File Change Summary
src/lexer/lexer.c Added conditional branch to handle "asmf" keyword, creating ASM_FUNCTION token
src/lexer/tokens.h Introduced new ASM_FUNCTION enum value in TokenType
src/parser/ast.h Added AST_ASM_FUNCTION_DECLARATION to ASTNodeType enum
src/parser/asts/functions.c Implemented parseASMFunctionDeclaration() to parse assembly function declarations
src/parser/asts/functions.h Added function declaration for parseASMFunctionDeclaration()
src/parser/parser.c Updated parseNodes() to handle ASM_FUNCTION token type

Sequence Diagram

sequenceDiagram
    participant Lexer
    participant Parser
    participant AST

    Lexer->>Lexer: Recognize "asmf" keyword
    Lexer->>Parser: Send ASM_FUNCTION token
    Parser->>Parser: Call parseASMFunctionDeclaration()
    Parser->>AST: Create AST_ASM_FUNCTION_DECLARATION node
    AST-->>Parser: Return parsed node
    Parser->>AST: Link node to AST
Loading

Poem

🐰 A lexer's hop, a parser's leap,
Assembly functions now we keep!
With "asmf" keyword, magic unfurled,
A new syntax in our coding world 🚀
Compiler's magic, rabbit's delight! 🎩

Tip

CodeRabbit's docstrings feature is now available as part of our Early Access Program! Simply use the command @coderabbitai generate docstrings to have CodeRabbit automatically generate docstrings for your pull request. This feature will be included in our Pro Plan when released.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR. (Beta)
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@Zffu Zffu linked an issue Dec 14, 2024 that may be closed by this pull request
Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 4

🧹 Outside diff range and nitpick comments (5)
src/lexer/tokens.h (1)

5-5: Maintain logical grouping of token types in the enum

The new token ASM_FUNCTION is added at the top of the TokenType enum. For better readability and maintainability, consider placing it near related tokens, such as FUNCTION, to group similar token types together.

Apply this diff to reposition the new token type:

 enum TokenType {
-    ASM_FUNCTION,
     FUNCTION,
+    ASM_FUNCTION,
     RETURN,
     VAR,
src/parser/asts/functions.h (2)

33-36: Correct typo in function documentation comment

There's a typographical error in the comment: "defintition" should be "definition".

Apply this diff to fix the typo:

 /**
- * Parse the parameters from a function defintition (for example).
+ * Parse the parameters from a function definition (for example).
  * @param result the lexer result.
  * @param index the starting index of the parsing.
  */

38-38: Add missing newline at the end of file

For consistency and to adhere to POSIX standards, add a newline character at the end of the file.

src/parser/ast.h (1)

22-23: Ensure consistent ordering of AST node types

The new AST_ASM_FUNCTION_DECLARATION node is added between existing node types. For better organization, consider placing it alongside other function-related node types, such as near AST_FUNCTION_DECLARATION.

Apply this diff to reposition the new AST node type:

     AST_VARIABLE_REFERENCE,

+    AST_FUNCTION_DECLARATION,
+    AST_ASM_FUNCTION_DECLARATION,
+    AST_FUNCTION_HEADER,
-
-    AST_ASM_FUNCTION_DECLARATION,
-
-    AST_FUNCTION_DECLARATION,
-    AST_FUNCTION_HEADER,
src/lexer/lexer.c (1)

77-79: Consider consistent naming convention

The keyword "asmf" might not be intuitive. Consider using a more descriptive keyword like "asm_func" or "asmfunc" to maintain consistency with other keywords.

📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 89f6cc2 and 9f48fdf.

📒 Files selected for processing (6)
  • src/lexer/lexer.c (1 hunks)
  • src/lexer/tokens.h (1 hunks)
  • src/parser/ast.h (1 hunks)
  • src/parser/asts/functions.c (3 hunks)
  • src/parser/asts/functions.h (1 hunks)
  • src/parser/parser.c (1 hunks)
🧰 Additional context used
🪛 cppcheck (2.10-2)
src/parser/asts/functions.c

[error] 185-185: Common realloc mistake

(memleakOnRealloc)

🔇 Additional comments (3)
src/parser/asts/functions.c (1)

151-153: Verify token type before parsing parameters

The condition if(result.tokens[index].type != KEYWORD) may not accurately represent all valid cases for parsing parameters. Ensure that this condition aligns with the lexer's token definitions and consider whether other token types should be accepted.

Please confirm that only KEYWORD tokens are valid at this point, or adjust the condition accordingly.

src/parser/parser.c (1)

47-54: Verify the implementation of parseASMFunctionDeclaration

The ASM function parsing logic follows the same pattern as other declarations, which is good. However, we need to verify the implementation of parseASMFunctionDeclaration.

Consider adding error handling for invalid ASM function declarations:

 case ASM_FUNCTION:
     node = parseASMFunctionDeclaration(result, index);
     if(node != NULL) {
         current->next = node;
         current = node;
         index = node->endingIndex;
+    } else {
+        // Log error or handle invalid ASM function declaration
     }
     break;
src/lexer/lexer.c (1)

77-79: 🛠️ Refactor suggestion

Verify ASM_FUNCTION token type definition

The lexer correctly recognizes the "asmf" keyword, but we should verify the ASM_FUNCTION token type definition.

Consider improving the keyword handling:

  1. Use a hash table or switch statement for better performance with multiple keywords
  2. Add validation for keyword length to prevent buffer overflow:
 else if(isalpha(c)) {
     int keywordLen = 0;
+    const int MAX_KEYWORD_LENGTH = 31;  // buffLen - 1 for null terminator
     
     while(isalpha(c)) {
+        if (keywordLen >= MAX_KEYWORD_LENGTH) {
+            // Handle keyword too long error
+            break;
+        }
         buff[keywordLen] = c;
         keywordLen++;
         c = *string++;
     }
+    buff[keywordLen] = '\0';  // Ensure null termination
✅ Verification successful

ASM_FUNCTION token type is properly integrated

The token type is correctly defined in the enum and properly integrated across the codebase:

  • Defined in tokens.h enum
  • Used in parser's AST definitions (ast.h)
  • Handled in parser implementation (parser.c)
  • Correctly processed in AST function declarations (functions.c)

The lexer changes are consistent with the token's usage throughout the codebase.

🏁 Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Search for ASM_FUNCTION token type definition
echo "Searching for token type definition..."
rg "ASM_FUNCTION" "./src/lexer/tokens.h"

Length of output: 143


Script:

#!/bin/bash
# Let's check the complete token enum definition to understand the context
echo "Checking token enum definition..."
rg -A 5 -B 5 "ASM_FUNCTION" "./src/lexer/tokens.h"

# Also verify if ASM_FUNCTION is used in other parts of the codebase
echo -e "\nChecking ASM_FUNCTION usage across codebase..."
rg "ASM_FUNCTION" -g '!tokens.h'

Length of output: 648

Comment on lines +167 to +168
for(; index <= result.size; ++index) {
struct Token t = result.tokens[index];
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Correct loop boundary condition to prevent out-of-bounds access

The loop condition index <= result.size may cause an out-of-bounds access on result.tokens[index] when index == result.size. Since array indices start from 0, the last valid index is result.size - 1.

Apply this diff to fix the loop condition:

-    for(; index <= result.size; ++index) {
+    for(; index < result.size; ++index) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
for(; index <= result.size; ++index) {
struct Token t = result.tokens[index];
for(; index < result.size; ++index) {
struct Token t = result.tokens[index];

Comment on lines +178 to +180
char c;
while(c = *t.value++) {
buff[buffIndex] = c;
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion

Avoid modifying the original token value pointer

The line while(c = *t.value++) advances t.value, which might affect subsequent operations that rely on t.value. To prevent unintended side effects, use a separate pointer to iterate over the string.

Apply this diff to refactor the code:

-        while(c = *t.value++) {
+        char* valPtr = t.value;
+        while((c = *valPtr++)) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
char c;
while(c = *t.value++) {
buff[buffIndex] = c;
char c;
char* valPtr = t.value;
while((c = *valPtr++)) {
buff[buffIndex] = c;

Comment on lines +183 to +186
if(buffIndex >= buffSize) {
buffSize *= 1.5;
buff = realloc(buff, buffSize);
}
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Fix potential memory leak when reallocating buffer

If realloc fails, it returns NULL and the original memory is not freed, leading to a memory leak. Assigning the result of realloc directly to buff without checking for NULL could overwrite the original pointer. Use a temporary pointer to check the result before assigning it back to buff.

Apply this diff to fix the issue:

-        buff = realloc(buff, buffSize);
+        char* temp = realloc(buff, buffSize);
+        if (temp == NULL) {
+            free(buff);
+            return NULL;
+        }
+        buff = temp;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if(buffIndex >= buffSize) {
buffSize *= 1.5;
buff = realloc(buff, buffSize);
}
if(buffIndex >= buffSize) {
buffSize *= 1.5;
char* temp = realloc(buff, buffSize);
if (temp == NULL) {
free(buff);
return NULL;
}
buff = temp;
}
🧰 Tools
🪛 cppcheck (2.10-2)

[error] 185-185: Common realloc mistake

(memleakOnRealloc)

Comment on lines +165 to +166
char* buff = malloc(buffSize);

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue

Check for malloc failure to ensure robust memory allocation

The malloc call for buff does not check if the allocation was successful. If malloc returns NULL, subsequent operations on buff will result in undefined behavior. Add a check to handle allocation failure.

Apply this diff to handle malloc failure:

     char* buff = malloc(buffSize);
+    if (buff == NULL) {
+        // Handle allocation failure
+        return NULL;
+    }

Committable suggestion skipped: line range outside the PR's diff.

@Zffu Zffu merged commit acfaa8b into master Dec 14, 2024
2 checks passed
@coderabbitai coderabbitai bot mentioned this pull request Dec 18, 2024
@Zffu Zffu deleted the feat/asm-f branch December 24, 2024 12:08
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Add "ASM" functions

2 participants