27 KiB
Navigation
Parser's Algorithim
gencpp uses a hand-written recursive descent parser. Both the lexer and parser currently handle a full C/C++ file in a single pass.
Notable implementation background
Lexer
The lex procedure does the lexical pass of content provided as a Str
type.
The tokens are stored (for now) in Lexer_Tokens
.
Fields:
Array<Token> Arr;
s32 Idx;
What token types are supported can be found in ETokType.csv you can also find the token types in ETokType.h , which is the generated enum from the csv file.
Tokens are defined with the struct gen::parser::Token
:
Fields:
char const* Text;
sptr Length;
TokType Type;
s32 Line;
s32 Column;
u32 Flags;
Flags is a bitfield made up of TokFlags (Token Flags):
TF_Operator
: Any operator token used in expressionsTF_Assign
- Using statment assignment
- Parameter argument default value assignment
- Variable declaration initialization assignment
TF_Preprocess
: Related to a preprocessing directiveTF_Preprocess_Cond
: A preprocess conditionalTF_Attribute
: An attribute tokenTF_AccessSpecifier
: An accesor operation tokenTF_Specifier
: One of the specifier tokensTF_EndDefinition
: Can be interpreted as an end definition for a scope.TF_Formatting
: Considered a part of the formattingTF_Literal
: Anything considered a literal by C++.
I plan to replace IsAssign with a general flags field and properly keep track of all operator types instead of abstracting it away to ETokType::Operator
.
Traversing the tokens is done with the following interface macros:
Macro | Description |
---|---|
currtok_noskip |
Get the current token without skipping whitespace |
currtok |
Get the current token, skip any whitespace tokens |
prevtok |
Get the previous token (does not skip whitespace) |
nexttok |
Get the next token (does not skip whitespace) |
eat( Token Type ) |
Check to see if the current token is of the given type, if so, advance Token's index to the next token |
left |
Get the number of tokens left in the token array |
check_noskip |
Check to see if the current token is of the given type, without skipping whitespace |
check |
Check to see if the current token is of the given type, skip any whitespace tokens |
Parser
The parser has a limited user interface, only specific types of definitions or statements are expected to be provided by the user directly when using to construct an AST dynamically (See SOA for example). It however does attempt to provide capability to parse a full C/C++ from production codebases.
Each public user interface procedure has the following format:
<code type> parse_<definition type>( Str def )
{
check_parse_args( def );
using namespace Parser;
TokArray toks = lex( def );
if ( toks.Arr == nullptr )
return CodeInvalid;
// Parse the tokens and return a constructed AST using internal procedures
...
}
The most top-level parsing procedure used for C/C++ file parsing is parse_global_body
:
It uses a helper procedure called parse_global_nspace
.
Each internal procedure will have the following format:
internal
<code type> parse_<definition_type>( <empty or contextual params> )
{
push_scope();
...
<code type> result = (<code type>) make_code();
...
Context.pop();
return result;
}
Below is an outline of the general alogirithim used for these internal procedures. The intention is to provide a basic briefing to aid the user in traversing the actual code definitions. These appear in the same order as they are in the parser.cpp
file
NOTE: This is still heavily in an alpha state. A large swaph of this can change, make sure these docs are up to date before considering them 1:1 with the repo commit your considering.
parse_array_decl
- Check if its an array declaration with no expression.
- Consume and return empty array declaration
- Opening square bracket
- Consume expression
- Closing square bracket
- If adjacent opening bracket
- Repeat array declaration parse until no brackets remain
parse_assignment_expression
- Eat the assignment operator
- Make sure there is content or at least an end statement after.
- Flatten the assignment expression to an untyped Code string.
parse_attributes
- Check for standard attribute
- Check for GNU attribute
- Check for MSVC attribute
- Check for a token registered as an attribute a. Check and grab the arguments of a token registered of an attribute if it has any.
- Repeat for chained attributes. Flatten them to a single attribute AST node.
parse_class_struct
- Check for export module specifier
- class or struct keyword
parse_attributes
- If identifier :
parse_identifier
- Parse inherited parent or interfaces
- If opening curly brace :
parse_class_struct_body
- If not an inplace definition
- End statement
- Check for inline comment
parse_class_struct_body
- Opening curly brace
- Parse the body (Possible options):
- Ignore dangling end statements
- Newline : ast constant
- Comment :
parse_comment
- Access_Public : ast constant
- Access_Protected : ast constant
- Access_Private : ast constant
- Decl_Class :
parse_complicated_definition
- Decl_Enum :
parse_complicated_definition
- Decl_Friend :
parse_friend
- Decl_Operator :
parse_operator_cast
- Decl_Struct :
parse_complicated_definition
- Decl_Template :
parse_template
- Decl_Typedef :
parse_typedef
- Decl_Union :
parse_complicated_definition
- Decl_Using :
parse_using
- Operator == '~'
parse_destructor
- Preprocess_Define :
parse_define
- Preprocess_Include :
parse_include
- Preprocess_Conditional (if, ifdef, ifndef, elif, else, endif) :
parse_preprocess_cond
or else/endif ast constant - Preprocess_Macro :
parse_simple_preprocess
- Preprocess_Pragma :
parse_pragma
- Preprocess_Unsupported :
parse_simple_preprocess
- StaticAssert :
parse_static_assert
- The following compound into a resolved definition or declaration:
- Attributes (Standard, GNU, MSVC) :
parse_attributes
- Specifiers (consteval, constexpr, constinit, explicit, forceinline, inline, mutable, neverinline, static, volatile, virtual)
- Possible Destructor :
parse_destructor
- Possible User defined operator cast :
parse_operator_cast
- Possible Constructor :
parse_constructor
- Something that has the following: (identifier, const, unsigned, signed, short, long, bool, char, int, double)
- Possible Constructor
parse_constructor
- Possible Operator, Function, or varaible :
parse_operator_function_or_variable
- Possible Constructor
- Attributes (Standard, GNU, MSVC) :
- Something completely unknown (will just make untyped...) :
parse_untyped
parse_comment
- Just wrap the token into a cached string ( the lexer did the processing )
parse_compilcated_definition
This is a helper function used by the following functions to help resolve a declaration or definition:
parse_class_struct_body
parse_global_nspace
parse_union
A portion of the code in parse_typedef
is very similar to this as both have to resolve a similar issue.
- Look ahead to the termination token (End statement)
- Check to see if it fits the pattern for a forward declare
- If the previous token was an identifier (
token[-1]
):- Look back one more token :
[-2]
- If the token has a closing brace its an inplace definition
- If the
token[-2]
is an identifier &token[-3]
is the declaration type, its a variable using a namespaced type. - If the
token[-2]
is an indirection, then its a variable using a namespaced/forwarded type. - If the
token[-2]
is an assign classifier, and the starting tokens were the which type with possibleclass
token after, its an enum forward declaration. - If any of the above is the case,
parse_operator_function_or_variable
- Look back one more token :
- If the
token[2]
is a vendor fundamental type (builtin) then it is an enum forward declaration. - If the previous token was a closing curly brace, its a definition :
parse_forward_or_definition
- If the previous token was a closing square brace, its an array definition :
parse_operator_function_or_variable
parse_define
- Define directive
- Get identifier
- Get Content (Optional)
parse_forward_or_definition
- Parse any of the following for either a forward declaration or definition:
- Decl_Class :
parse_class
- Decl_Enum :
parse_enum
- Decl_Struct :
parse_struct
- Decl_Union :
parse_union
- Decl_Class :
parse_function_after_name
This is needed as a function defintion is not easily resolvable early on, as such this function handles resolving a function after its been made ceratin that the type of declaration or definition is indeed for a function signature.
By the point this function is called the following are known : export module flag, attributes, specifiers, return type, & name
parse_parameters
- parse postfix specifiers (we do not check if the specifier here is correct or not to be here... yet)
- If there is a body :
parse_body
- Otherwise :
- Statment end
- Check for inline comment
parse_function_body
Currently there is no actual parsing of the function body. Any content with the braces is shoved into an execution AST node. In the future statements and expressions will be parsed.
- Open curly brace
- Grab all tokens between the brace and the closing brace, shove them in a execution AST node.
- Closing curly brace
parse_global_nspace
- Make sure this is being called for a valid type (namespace, global body, export body, linkage body)
- If its not a global body, consume the opening curly brace
- Parse the body (Possible options):
- Ignore dangling end statements
- NewLine : ast constant
- Comment :
parse_comment
- Decl_Cass :
parse_complicated_definition
- Decl_Enum :
parse_complicated_definition
- Decl_Extern_Linkage :
parse_extern_link
- Decl_Namespace :
parse_namespace
- Decl_Struct :
parse_complicated_definition
- Decl_Template :
parse_template
- Decl_Typedef :
parse_typedef
- Decl_Union :
parse_complicated_definition
- Decl_Using :
parse_using
- Preprocess_Define :
parse_define
- Preprocess_Include :
parse_include
- Preprocess_If, IfDef, IfNotDef, Elif :
parse_preprocess_cond
- Preprocess_Else : ast constant
- Preprocess_Endif : ast constant
- Preprocess_Macro :
parse_simple_preprocess
- Preprocess_Pragma :
parse_pragma
- Preprocess_Unsupported :
parse_simple_preprocess
- StaticAssert :
parse_static_assert
- Module_Export :
parse_export_body
- Module_Import : NOT_IMPLEMENTED
- The following compound into a resolved definition or declaration:
- Attributes ( Standard, GNU, MSVC, Macro ) :
parse_attributes
- Specifiers ( consteval, constexpr, constinit, extern, forceinline, global, inline, internal_linkage, neverinline, static )
- Is either ( identifier, const specifier, long, short, signed, unsigned, bool, char, double, int)
- Attempt to parse as construtor or destructor :
parse_global_nspace_constructor_destructor
- If its an operator cast (definition outside class) :
parse_operator_cast
- Its an operator, function, or varaible :
parse_operator_function_or_varaible
- Attempt to parse as construtor or destructor :
- Attributes ( Standard, GNU, MSVC, Macro ) :
- If its not a global body, consume the closing curly brace
parse_global_nspace_constructor_destructor
- Look ahead for the start of the arguments for a possible constructor/destructor
- Go back past the identifier
- Check to see if its a destructor by checking for the
~
- Continue the next token should be a
::
- Determine if the next valid identifier (ignoring possible template parameters) is the same as the first identifier of the function.
- If it is we have either a constructor or destructor so parse using their respective functions (
parse_constructor
,parse_destructor
).
parse_identifier
This is going to get heavily changed down the line to have a more broken down "identifier expression" so that the qualifier, template args, etc, can be distinguished between the targeted identifier.
The function can parse all of them, however the AST node compresses them all into a string.
- Consume first identifier
parse_template_args
- While there is a static symbol accessor (
::
)- Consume
::
- Consume member identifier
parse_template args
(for member identifier)- If a
~
is encounted and the scope is for a destructor's identifier, do not consume it and return with what parsed.
- Consume
parse_include
- Consume include directive
- Consume the path
parse_operator_after_ret_type
This is needed as a operator defintion is not easily resolvable early on, as such this function handles resolving a operator after its been made ceratin that the type of declaration or definition is indeed for a operator signature.
By the point this function is called the following are known : export module flag, attributes, specifiers, return type
- If there is any qualifiers for the operator, parse them
- Consume operator keyword
- Determine the operator type (This will be offloaded to the lexer moreso than how it is now) & consume
parse_params
- If there is no parameters this is operator is a member of pointer if its symbols is a *.
- Parse postfix specifiers
- If there is a opening curly brace,
parse function_body
- Otherwise: consume end statement, check for inline comment.
parse_operator_function_or_variable
When this function is called, attribute and specifiers may have been resolved, however what comes next can still be either an operator, function, or varaible.
- Check for preprocessor macro, if there is one :
parse_simple_preprocess
parse_type
(Does the bulk of the work)- Begin lookahead to see if we get qualifiers or we eventually find the operator declaration
- If we find an operator keyword :
parse_operator_after_ret_type
- otherwise :
parse_identifier
- If we se a opening parenthesis (capture start), its a function :
parse_function_after_name
- Its a variable :
parse_variable_after_name
parse_pragma
- Consume pragma directive
- Process the token content into cached string
parse_params
- Consume either a
(
or<
based onuse_template_capture
arg - If the we immdiately find a closing token, consume it and finish.
- If we encounter a varadic argument, consume it and return a
param_varadic
ast constant parse_type
- If we have a macro, parse it (Unreal has macros as tags to parameters and or as entire arguments).
- So long as next token isn't a comma
a. If we have an identifier
- Consume it
- Check for assignment: a. Consume assign operator b. Parse the expression
- While we continue to encounter commas a. Consume them b. Repeat steps 3 to 6.2.b
- Consume the closing token
parse_preprocess_cond
- Parse conditional directive
- Process directive's content expression
parse_simple_preprocess
There is still decent room for improvement in this setup. Right now the entire macro's relevant tokens are shoved into an untyped AST. It would be better to store it instead in an AST_Macro
node instead down the line.
- Consume the macro token
- Check for an opening curly brace
- Consume opening curly brace
- Until the closing curly is encountered consume all tokens.
- If the parent context is a typedef
- Check for end stement
- Consume it
- Consume potential inline comment
- Check for end stement
- Otherwise do steps 3 to 3.1.2
- Shove it all in an untyped string
parse_static_assert
- Consume static assert and opening curly brace
- Consume all tokens until the the closing brace is reached.
- Consume curly brace and end statement
- Place all tokens within braces into a content for the assert.
parse_template_args
This will get changed heavily once we have better support for typename expressions
- Consume opening angle bracket
- Consume all tokens until closing angle bracket
- Consme closing angle bracket
- Return the currtok with the ammended length.
parse_variable_after_name
This is needed as a variable defintion is not easily resolvable early on, it takes a long evaluation period before its known that the declaration or definition is a variable. As such this function handles resolving a variable.
By the point this function is called the following are known : export module flag, attributes, specifiers, value type, name
- If its an assignment, parse the assignment expression (currently to an untyped string)
- If its an opening curly brace, parse the expression within (currnelty to an untyped stirng).
- Consume the closing curly brace
- If its a
:
, we're dealing with bitfield definition:- Consume the assign classifier
- Consume the expression (currently to an untyped string)
- If a comma is encountered :
parse_variable declaration_list
- Consume statement end
- Check for inline comment
parse_variable_declaration_list
- Consume the comma
- Parse specifiers
parse_variable_after_name
parse_class
parse_class_struct
parse_constructor
This currently doesn't support postfix specifiers (planning to in the future)
parse_identifier
parse_parameters
- If currtok is a
:
- Consume
:
- Parse the initializer list
parse_function_body
- Consume
- If currtok is an opening curly brace
parse_function_body
- Otherwise:
- Consume statement end
- Check for inline comment
parse_destructor
- Check for and consume virtual specifier
- Check for the
~
operator parse_identifier
- Consume opening and closing parenthesis
- Check for assignment operator:
- Consume assignment op
- Consume pure specifier
0
- If not pure virtual & currtok is opening curly brace:
parse_function_body
- Otherwise:
- Consume end statement
- If currtok is comment :
parse_comment
parse_enum
- Consume enum token
- Check for and consume class token
parse_attributes
- If there is an identifier consume it
- Check for a
:
- Consume
:
parse_type
- Consume
- If there is a body parse it (Consume
{
):- Newline : ast constant
- Comment :
parse_comment
- Preprocess_Define :
parse_define
- Preprocess_Conditional (if, ifdef, ifndef, elif ) :
parse_preprocess_cond
- Preprocess_Else : ast constant
- Preprocess_Endif : ast constant
- Preprocess_Macro :
parse_simple_preprocess
- Preprocess_Pragma :
parse_pragma
- Preprocess_Unsupported :
parse_smple_preprocess
- An actual enum entry
- Consume identifier
- If there is an assignment operator:
- Consume operator
- Consume the expression (assigned to untyped string for now)
- If a macro is encountered consume it (Unreal UMETA macro support)
- If there is a comma, consume it
parse_export_body
parse_global_nspace
parse_extern_link_body
parse_global_nspace
parse_extern_link
- Consume Decl_Extern_Linkage
- Consume the linkage identifier
parse_extern_link_body
parse_friend
- Consume
friend
parse_type
- If the currok is an identifier its a function declaration or definition
parse_function_after_name
- Consume end statement so long as its not a function definion
- Check for inline comment,
parse_comment
if exists
parse_function
- Check and parse for
export
parse_attributes
- Parse specifiers
parse_type
parse_identifier
parse_function_after_name
parse_namespace
- Consume namespace declaration
- Parse identifier
parse_global_namespace
parse_operator
- Check for and parse export declaration
parse_attributes
- Parse specifiers
parse_type
parse_operator_after_ret_type
parse_operator_cast
- Look for and parse a qualifier namespace for the cast (in-case this is defined outside the class's scope)
- Consume operator declaration
parse_type
- Consume opening and closing parethesis
- Check for a const qualifiying specifier
- Check to see if this is a definition (
{
)- Consume
{
- Parse body to untyped string (parsing statement and expressions not supported yet)
- Consume
}
- Consume
- Otherwise:
- Consume end statement
- Check for and consume comment :
parse_comment
parse_struct
parse_class_struct
parse_template
Note: This currently doesn't support templated operator casts (going to need to add support for it)
- Check for and parse export declaration
- Consume template declaration
parse_params
- Parse for any of the following:
- Decl_Class :
parse_class
- Decl_Struct :
parse_struct
- Decl_Union :
parse_union
- Decl_Using :
parse_using
- The following compound into a resolved definition or declaration:
parse_attributes
- Parse specifiers
- Attempt to parse as constructor or destructor:
parse_global_nspace_constructor_destructor
- Otherwise:
parse_operator_function_or_variable
- Decl_Class :
parse_type
This function's implementation is awful and not done correctly. It will most likely be overhauled in the future as I plan to segement the AST_Type into several AST varaints along with sub-types to help produce robust type expressions.
Hopefully I won't need to make authentic type expressions as I was hopeing to avoid that...
Current Algorithim
Anything that is in the qualifier capture of the function typename is treated as an expression abstracted as an untyped string
parse_attributes
- Parse specifiers
- If the
parse_type
was called from a template parse, check to see if class was used instead of typname and consume as name. - This is where things get ugly for each of these depend on what the next token is.
- If its an in-place definition of a class, enum, struct, or union:
- If its a decltype (Not supported yet but draft impl there)
- If its a compound native type expression (unsigned, char, short, long, int, float, dobule, etc )
- Ends up being a regular type alias of an identifier
- Parse specifiers (postfix)
- We need to now look ahead to see If we're dealing with a function typename
- If wer're dealing with a function typename:
- Shove the specifiers, and identifier code we have so far into a return type typename's Name (untyped string)
- Reset the specifiers code for the top-level typeanme
- Check to see if the next token is an identifier:
parse_identifier
- Check to see if the next token is capture start and is not the last capture ("qualifier capture"):
- Consume
(
- Consume expresssion between capture
- Consume
)
- Consume
parse_params
- Parse postfix specifiers
- Shove the specifiers, and identifier code we have so far into a return type typename's Name (untyped string)
- Check for varaidic argument (param pack) token:
- Consume varadic argument token
WIP - Alternative Algorithim
Currently wrapped up via macro: GEN_USE_NEW_TYPENAME_PARSING
Anything that is in the qualifier capture of the function typename is treated as an expression abstracted as an untyped string
parse_attributes
- Parse specifiers (prefix)
- This is where things get ugly for each of these depend on what the next token is.
- If its an in-place definition of a class, enum, struct, or union:
- If its a decltype (Not supported yet but draft impl there)
- If its a compound native type expression (unsigned, char, short, long, int, float, dobule, etc )
- Ends up being a regular type alias of an identifier
- Parse specifiers (postfix)
- If any specifiers are found populate specifiers code with them.
- We need to now look ahead to see If we're dealing with a function typename
- If wer're dealing with a function typename:
- Shove the specifiers, and identifier code we have so far into a return type typename's Name (untyped string)
- Reset the specifiers code for the top-level typename
- Check to see if the next token is an identifier:
parse_identifier
- Check to see if the next token is capture start and is not the last capture ("qualifier capture"):
- Consume
(
- Parse binding specifiers
parse_identifier
parse_parameters
-> params_nested- Consume
)
- Construct a nested function typename definition for the qualifier
Name
- Consume
parse_params
- > params- Parse postfix specifiers
- Shove the specifiers, and identifier code we have so far into a return type typename's Name (untyped string)
- Check for varaidic argument (param pack) token:
- Consume varadic argument token
Later: Algorithim based on typename expressions
parse_typedef
- Check for export module specifier
- typedef keyword
- If its a preprocess macro: Get the macro name
- Else:
- Check to see if its a complicated definition (in-place enum, class, struct, union)
- If its a complicated definition:
- Perform the look ahead similar to
parse_complicated_definition
's implementation - Check to see if its a forward declaration :
parse_forward_declaration
- If end[-1] is an identifier:
- Its either an in-place, varaible type qualified identifier, or indirection type:
parse_foward_or_definition
- Its either an in-place, varaible type qualified identifier, or indirection type:
- else if end[-1] is a closing curly brace
- Its a definition:
parse_forward_or_definition
- Its a definition:
- else if end[-1] is a closing square brace
2. Its an array definition:
parse_type
- Perform the look ahead similar to
- Else :
parse-type
- Check for identifier : Consume the token
parse_array_decl
- Consume end statement
- Check for inline comment :
parse_comment
parse_union
- Check for export module specifier
- union keyword
parse_attributes
- Check for identifier
- Parse the body (Possible options):
- Newline
- Comment
- Decl_Class
- Decl_Enum
- Decl_Struct
- Decl_Union
- Preprocess_Define
- Preprocess_Conditional (if, ifdef, ifndef, elif, else, endif)
- Preprocess_Macro
- Preprocess_Pragma
- Unsupported preprocess directive
- Variable
- If its not an inplace definiton: End Statement
parse_using
- Check for export module specifier
- using keyword
- Check to see if its a using namespace
- Get the identifier
- If its a regular using declaration:
parse_attributes
parse_type
parse_array_decl
- End statement
- Check for inline comment
parse_variable
- Check for export module specifier
parse_attributes
parse specifiers
parse_type
parse_identifier
parse_variable_after_name