diff --git a/Readme.md b/Readme.md index f1aab97..ad1502c 100644 --- a/Readme.md +++ b/Readme.md @@ -8,12 +8,6 @@ These build up a code AST to then serialize with a file builder. This code base attempts follow the [handmade philosophy](https://handmade.network/manifesto), its not meant to be a black box metaprogramming utility, its meant for the user to extend for their project domain. -### TOC - -* [Notes](#notes) -* [Usage](#usage) -* [Building](#building) - ## Notes The project has reached an *alpha* state, all the current functionality works for the test cases but it will most likely break in many other cases. @@ -23,7 +17,7 @@ A `natvis` and `natstepfilter` are provided in the scripts directory. ***The editor and scanner have not been implemented yet. The scanner will come first, then the editor.*** -A C variant is hosted [here](https://github.com/Ed94/genc); I haven't gotten headwind on it, should be easier to make than this... +A C variant is hosted [here](https://github.com/Ed94/genc); I will complete it when this library is feature complete, it should be easier to make than this... ## Usage diff --git a/docs/Parsing.md b/docs/Parsing.md index e3e23e0..518f22a 100644 --- a/docs/Parsing.md +++ b/docs/Parsing.md @@ -3,26 +3,6 @@ The library features a naive parser tailored for only what the library needs to construct the supported syntax of C++ into its AST. This parser does not, and should not do the compiler's job. By only supporting this minimal set of features, the parser is kept under 5000 loc. - -Everything is done in one pass for both the preprocessor directives and the rest of the language. -The parser performs no macro expansion as the scope of gencpp feature-set is to only support the preprocessor for the goal of having rudimentary awareness of preprocessor ***conditionals***, ***defines***, and ***includes***. -*(Conditionals and defines are a TODO)* - -The keywords supported for the preprocessor are: - -* include -* define -* if -* ifdef -* elif -* endif -* undef - -Just like with actual preprocessor, each directive # line is considered one preproecessor unit, and will be treated as one Preprocessor AST. *These ASTs will be considered members or entries of braced scope they reside within*. -All keywords except *include* are suppported as members of a scope for a class/struct, global, or namespace body. - -Any preprocessor definition abuse that changes the syntax of the core language is unsupported and will fail to parse if not kept within an execution scope (function body, or expression assignment). - The parsing implementation supports the following for the user: ```cpp @@ -47,3 +27,26 @@ CodeVar parse_variable ( StrC var_def ); ***Parsing will aggregate any tokens within a function body or expression statement to an untyped Code AST.*** +Everything is done in one pass for both the preprocessor directives and the rest of the language. +The parser performs no macro expansion as the scope of gencpp feature-set is to only support the preprocessor for the goal of having rudimentary awareness of preprocessor ***conditionals***, ***defines***, and ***includes***, and ***`pragmas`**. + +The keywords supported for the preprocessor are: + +* include +* define +* if +* ifdef +* elif +* endif +* undef +* pragma + +Each directive `#` line is considered one preproecessor unit, and will be treated as one Preprocessor AST. *These ASTs will be considered members or entries of braced scope they reside within*. +All keywords except *include* are suppported as members of a scope for a class/struct, global, or namespace body. + +Any preprocessor definition abuse that changes the syntax of the core language is unsupported and will fail to parse if not kept within an execution scope (function body, or expression assignment). + +Exceptions to the above rule (If its too hard to keep track of just follow the above notion): + +* Typedefs allow of a macro exansion to be defined after the keyword; Ex: `typedef GEN_FILE_OPEN_PROC( file_open_proc );` + diff --git a/docs/Readme.md b/docs/Readme.md index 1787d75..145a2e8 100644 --- a/docs/Readme.md +++ b/docs/Readme.md @@ -42,6 +42,7 @@ Otherwise the library is free of any templates. * Execution statement validation : Execution expressions are defined using the untyped AST. * Lambdas (This naturally means its unsupported) +* Non-trivial template validation support. * RAII : This needs support for constructors/destructor parsing * Haven't gotten around to yet (its in the github issues) diff --git a/docs/Upfront.md b/docs/Upfront.md new file mode 100644 index 0000000..e69de29 diff --git a/gencpp.10x b/gencpp.10x index 8fba690..8cb3c94 100644 --- a/gencpp.10x +++ b/gencpp.10x @@ -8,8 +8,8 @@ true false false - powershell ./scripts/build.ps1 - powershell ./scripts/rebuild.ps1 + powershell ./scripts/test.gen_run.ps1 + powershell ./scripts/clean.ps1 @@ -38,7 +38,9 @@ C:\Program Files (x86)\Windows Kits\10\\include\10.0.19041.0\\cppwinrt C:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um - + + GEN_TIME + Debug:x64 diff --git a/project/Readme.md b/project/Readme.md index 5698371..cfe968f 100644 --- a/project/Readme.md +++ b/project/Readme.md @@ -12,7 +12,7 @@ Just like the `gen.` they include their components: `dependencies/.` ) They directly include `depedencies/file_handling.` as the core library does not include file processing by defualt. -**TODO : Right now the library is not finished structurally, as such the first self-hosting iteration is still WIP** +**TODO : Right now the library is not finished, as such the first self-hosting iteration is still WIP** Both libraries use *pre-generated* (self-hosting I guess) version of the library to then generate the latest version of itself. (sort of a verification that the generated version is equivalent). diff --git a/project/components/ast.cpp b/project/components/ast.cpp index 846af4d..8804942 100644 --- a/project/components/ast.cpp +++ b/project/components/ast.cpp @@ -38,10 +38,13 @@ String AST::to_string() case Comment: { + result.append("\n"); + static char line[MaxCommentLineLength]; s32 left = Content.length(); s32 index = 0; + s32 curr = 0; do { s32 length = 0; @@ -49,12 +52,17 @@ String AST::to_string() { length++; left--; + index++; } + index++; - str_copy( line, Content, length ); - line[length] = '\0'; + str_copy( line, Content + curr, length ); + result.append_fmt( "//%.*s", length, line ); + mem_set( line, 0, MaxCommentLineLength); - result.append_fmt( "// %s", line ); + length++; + left--; + curr = index; } while ( left--, left > 0 ); } @@ -107,13 +115,16 @@ String AST::to_string() } else { - result.append_fmt( "%s \n{\n%s\n};", Name, Body->to_string() ); + result.append_fmt( "%s \n{\n%s\n}", Name, Body->to_string() ); } } else { - result.append_fmt( "class %s\n{\n%s\n};", Name, Body->to_string() ); + result.append_fmt( "class %s\n{\n%s\n}", Name, Body->to_string() ); } + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -123,9 +134,12 @@ String AST::to_string() result.append( "export " ); if ( Attributes ) - result.append_fmt( "class %s %s;", Attributes->to_string(), Name ); + result.append_fmt( "class %s %s", Attributes->to_string(), Name ); - else result.append_fmt( "class %s;", Name ); + else result.append_fmt( "class %s", Name ); + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -142,21 +156,24 @@ String AST::to_string() result.append_fmt( "%s ", Attributes->to_string() ); if ( UnderlyingType ) - result.append_fmt( "%s : %s\n{\n%s\n};" + result.append_fmt( "%s : %s\n{\n%s\n}" , Name , UnderlyingType->to_string() , Body->to_string() ); - else result.append_fmt( "%s\n{\n%s\n};" + else result.append_fmt( "%s\n{\n%s\n}" , Name , Body->to_string() ); } - else result.append_fmt( "enum %s\n{\n%s\n};" + else result.append_fmt( "enum %s\n{\n%s\n}" , Name , Body->to_string() ); + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -168,7 +185,10 @@ String AST::to_string() if ( Attributes ) result.append_fmt( "%s ", Attributes->to_string() ); - result.append_fmt( "enum %s : %s;", Name, UnderlyingType->to_string() ); + result.append_fmt( "enum %s : %s", Name, UnderlyingType->to_string() ); + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -188,7 +208,7 @@ String AST::to_string() if ( UnderlyingType ) { - result.append_fmt( "%s : %s\n{\n%s\n};" + result.append_fmt( "%s : %s\n{\n%s\n}" , Name , UnderlyingType->to_string() , Body->to_string() @@ -196,7 +216,7 @@ String AST::to_string() } else { - result.append_fmt( "%s\n{\n%s\n};" + result.append_fmt( "%s\n{\n%s\n}" , Name , Body->to_string() ); @@ -204,10 +224,13 @@ String AST::to_string() } else { - result.append_fmt( "enum class %s\n{\n%s\n};" + result.append_fmt( "enum class %s\n{\n%s\n}" , Body->to_string() ); } + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -221,7 +244,10 @@ String AST::to_string() if ( Attributes ) result.append_fmt( "%s ", Attributes->to_string() ); - result.append_fmt( "%s : %s;", Name, UnderlyingType->to_string() ); + result.append_fmt( "%s : %s", Name, UnderlyingType->to_string() ); + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -264,7 +290,7 @@ String AST::to_string() result.append_fmt( "%s ", Attributes->to_string() ); if ( Specs ) - result.append_fmt( "%s\n", Specs->to_string() ); + result.append_fmt( "%s", Specs->to_string() ); if ( ReturnType ) result.append_fmt( "%s %s(", ReturnType->to_string(), Name ); @@ -304,7 +330,7 @@ String AST::to_string() result.append_fmt( "%s ", Attributes->to_string() ); if ( Specs ) - result.append_fmt( "%s\n", Specs->to_string() ); + result.append_fmt( "%s", Specs->to_string() ); if ( ReturnType ) result.append_fmt( "%s %s(", ReturnType->to_string(), Name ); @@ -430,7 +456,10 @@ String AST::to_string() { if ( Specs ) { - result.append_fmt( "operator %s()" ); + if ( Name && Name.length() ) + result.append_fmt( "%.*soperator %s()", Name.length(), Name, EOperator::to_str( Op )); + else + result.append_fmt( "operator %s()", EOperator::to_str( Op ) ); CodeSpecifiers specs = cast(); @@ -444,14 +473,17 @@ String AST::to_string() break; } - result.append_fmt("operator %s()\n{\n%s\n}", ValueType->to_string(), Body->to_string() ); + if ( Name && Name.length() ) + result.append_fmt("%.*soperator %s()\n{\n%s\n}", Name.length(), Name, ValueType->to_string(), Body->to_string() ); + else + result.append_fmt("operator %s()\n{\n%s\n}", ValueType->to_string(), Body->to_string() ); } break; case Operator_Cast_Fwd: if ( Specs ) { - result.append_fmt( "operator %s()" ); + result.append_fmt( "operator %s()", ValueType->to_string() ); CodeSpecifiers specs = cast(); @@ -461,7 +493,7 @@ String AST::to_string() result.append_fmt( " %s", (char const*)ESpecifier::to_str( spec ) ); } - result.append_fmt( ";", Body->to_string() ); + result.append( ";" ); break; } @@ -470,6 +502,12 @@ String AST::to_string() case Parameters: { + if ( ValueType == nullptr ) + { + result.append_fmt( "%s", Name ); + break; + } + if ( Name ) result.append_fmt( "%s %s", ValueType->to_string(), Name ); @@ -489,8 +527,40 @@ String AST::to_string() } break; - case Preprocessor_Include: - result.append_fmt( "#include \"%s\"", Name ); + case Preprocess_Define: + result.append_fmt( "#define %s%s", Name, Content ); + break; + + case Preprocess_If: + result.append_fmt( "#if %s", Content ); + break; + + case Preprocess_IfDef: + result.append_fmt( "#ifdef %s", Content ); + break; + + case Preprocess_IfNotDef: + result.append_fmt( "#ifndef %s", Content ); + break; + + case Preprocess_Include: + result.append_fmt( "#include \"%s\"", Content ); + break; + + case Preprocess_ElIf: + result.append_fmt( "#elif %s", Content ); + break; + + case Preprocess_Else: + result.append_fmt( "#else" ); + break; + + case Preprocess_EndIf: + result.append_fmt( "#endif\n" ); + break; + + case Preprocess_Pragma: + result.append_fmt( "#pragma %s", Content ); break; case Specifiers: @@ -555,13 +625,16 @@ String AST::to_string() { if ( Name ) - result.append_fmt( "%s \n{\n%s\n};", Name, Body->to_string() ); + result.append_fmt( "%s \n{\n%s\n}", Name, Body->to_string() ); } } else { - result.append_fmt( "struct %s\n{\n%s\n};", Name, Body->to_string() ); + result.append_fmt( "struct %s\n{\n%s\n}", Name, Body->to_string() ); } + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -571,9 +644,12 @@ String AST::to_string() result.append( "export " ); if ( Attributes ) - result.append_fmt( "struct %s %s;", Attributes->to_string(), Name ); + result.append_fmt( "struct %s %s", Attributes->to_string(), Name ); - else result.append_fmt( "struct %s;", Name ); + else result.append_fmt( "struct %s", Name ); + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -638,7 +714,7 @@ String AST::to_string() if ( Name ) { - result.append_fmt( "%s\n{\n%s\n};" + result.append_fmt( "%s\n{\n%s\n}" , Name , Body->to_string() ); @@ -646,10 +722,13 @@ String AST::to_string() else { // Anonymous union - result.append_fmt( "\n{\n%s\n};" + result.append_fmt( "\n{\n%s\n}" , Body->to_string() ); } + + if ( Parent == nullptr || ( Parent->Type != ECode::Typedef && Parent->Type != ECode::Variable ) ) + result.append(";"); } break; @@ -697,6 +776,9 @@ String AST::to_string() if ( ValueType->ArrExpr ) result.append_fmt( "[%s]", ValueType->ArrExpr->to_string() ); + if ( BitfieldSize ) + result.append_fmt( " : %s", BitfieldSize->to_string() ); + if ( Value ) result.append_fmt( " = %s", Value->to_string() ); @@ -705,7 +787,10 @@ String AST::to_string() break; } - if ( UnderlyingType->ArrExpr ) + if ( BitfieldSize ) + result.append_fmt( "%s : %s", ValueType->to_string(), BitfieldSize->to_string() ); + + else if ( UnderlyingType->ArrExpr ) result.append_fmt( "%s %s[%s];", UnderlyingType->to_string(), Name, UnderlyingType->ArrExpr->to_string() ); else diff --git a/project/components/data_structures.hpp b/project/components/data_structures.hpp index a70033b..65cd330 100644 --- a/project/components/data_structures.hpp +++ b/project/components/data_structures.hpp @@ -12,6 +12,7 @@ struct AST_Body; struct AST_Attributes; struct AST_Comment; struct AST_Class; +struct AST_Define; struct AST_Enum; struct AST_Exec; struct AST_Extern; @@ -23,6 +24,8 @@ struct AST_Namespace; struct AST_Operator; struct AST_OpCast; struct AST_Param; +struct AST_Pragma; +struct AST_PreprocessCond; struct AST_Specifiers; struct AST_Struct; struct AST_Template; @@ -38,6 +41,7 @@ struct CodeBody; struct CodeAttributes; struct CodeComment; struct CodeClass; +struct CodeDefine; struct CodeEnum; struct CodeExec; struct CodeExtern; @@ -49,6 +53,8 @@ struct CodeNamespace; struct CodeOperator; struct CodeOpCast; struct CodeParam; +struct CodePreprocessCond; +struct CodePragma; struct CodeSpecifiers; struct CodeStruct; struct CodeTemplate; @@ -115,6 +121,7 @@ struct Code operator CodeAttributes() const; operator CodeComment() const; operator CodeClass() const; + operator CodeDefine() const; operator CodeExec() const; operator CodeEnum() const; operator CodeExtern() const; @@ -126,6 +133,8 @@ struct Code operator CodeOperator() const; operator CodeOpCast() const; operator CodeParam() const; + operator CodePragma() const; + operator CodePreprocessCond() const; operator CodeSpecifiers() const; operator CodeStruct() const; operator CodeTemplate() const; @@ -175,6 +184,7 @@ struct AST operator CodeAttributes(); operator CodeComment(); operator CodeClass(); + operator CodeDefine(); operator CodeEnum(); operator CodeExec(); operator CodeExtern(); @@ -186,6 +196,8 @@ struct AST operator CodeOperator(); operator CodeOpCast(); operator CodeParam(); + operator CodePragma(); + operator CodePreprocessCond(); operator CodeSpecifiers(); operator CodeStruct(); operator CodeTemplate(); @@ -219,7 +231,10 @@ struct AST AST* UnderlyingType; // Enum, Typedef AST* ValueType; // Parameter, Variable }; - AST* Params; // Function, Operator, Template + union { + AST* Params; // Function, Operator, Template + AST* BitfieldSize; // Varaiable (Class/Struct Data Member) + }; union { AST* ArrExpr; // Type Symbol AST* Body; // Class, Enum, Function, Namespace, Struct, Union @@ -263,7 +278,10 @@ struct AST_POD AST* UnderlyingType; // Enum, Typedef AST* ValueType; // Parameter, Variable }; - AST* Params; // Function, Operator, Template + union { + AST* Params; // Function, Operator, Template + AST* BitfieldSize; // Varaiable (Class/Struct Data Member) + }; union { AST* ArrExpr; // Type Symbol AST* Body; // Class, Enum, Function, Namespace, Struct, Union @@ -378,6 +396,7 @@ struct CodeBody Define_CodeType( Attributes ); Define_CodeType( Comment ); +Define_CodeType( Define ); Define_CodeType( Enum ); Define_CodeType( Exec ); Define_CodeType( Extern ); @@ -388,6 +407,8 @@ Define_CodeType( Module ); Define_CodeType( Namespace ); Define_CodeType( Operator ); Define_CodeType( OpCast ); +Define_CodeType( Pragma ); +Define_CodeType( PreprocessCond ); Define_CodeType( Template ); Define_CodeType( Type ); Define_CodeType( Typedef ); @@ -474,6 +495,12 @@ struct CodeSpecifiers bool append( SpecifierT spec ) { + if ( ast == nullptr ) + { + log_failure("CodeSpecifiers: Attempted to append to a null specifiers AST!"); + return false; + } + if ( raw()->NumEntries == AST::ArrSpecs_Cap ) { log_failure("CodeSpecifiers: Attempted to append over %d specifiers to a specifiers AST!", AST::ArrSpecs_Cap ); @@ -631,6 +658,21 @@ struct AST_Class }; static_assert( sizeof(AST_Class) == sizeof(AST), "ERROR: AST_Class is not the same size as AST"); +struct AST_Define +{ + union { + char _PAD_[ sizeof(SpecifierT) * AST::ArrSpecs_Cap ]; + StringCached Content; + }; + Code Prev; + Code Next; + Code Parent; + StringCached Name; + CodeT Type; + char _PAD_UNUSED_[ sizeof(ModuleFlag) + sizeof(u32) ]; +}; +static_assert( sizeof(AST_Define) == sizeof(AST), "ERROR: AST_Define is not the same size as AST"); + struct AST_Enum { union { @@ -847,6 +889,36 @@ struct AST_Param }; static_assert( sizeof(AST_Param) == sizeof(AST), "ERROR: AST_Param is not the same size as AST"); +struct AST_Pragma +{ + union { + char _PAD_[ sizeof(SpecifierT) * AST::ArrSpecs_Cap ]; + StringCached Content; + }; + Code Prev; + Code Next; + Code Parent; + StringCached Name; + CodeT Type; + char _PAD_UNUSED_[ sizeof(ModuleFlag) + sizeof(u32) ]; +}; +static_assert( sizeof(AST_Pragma) == sizeof(AST), "ERROR: AST_Pragma is not the same size as AST"); + +struct AST_PreprocessCond +{ + union { + char _PAD_[ sizeof(SpecifierT) * AST::ArrSpecs_Cap ]; + StringCached Content; + }; + Code Prev; + Code Next; + Code Parent; + StringCached Name; + CodeT Type; + char _PAD_UNUSED_[ sizeof(ModuleFlag) + sizeof(u32) ]; +}; +static_assert( sizeof(AST_PreprocessCond) == sizeof(AST), "ERROR: AST_PreprocessCond is not the same size as AST"); + struct AST_Specifiers { SpecifierT ArrSpecs[ AST::ArrSpecs_Cap ]; @@ -998,7 +1070,7 @@ struct AST_Var CodeAttributes Attributes; CodeSpecifiers Specs; CodeType ValueType; - char _PAD_PROPERTIES_[ sizeof(AST*) ]; + Code BitfieldSize; Code Value; }; }; diff --git a/project/components/ecode.hpp b/project/components/ecode.hpp index 80a2bd3..8422e77 100644 --- a/project/components/ecode.hpp +++ b/project/components/ecode.hpp @@ -37,7 +37,15 @@ namespace ECode Entry( Operator_Cast ) \ Entry( Operator_Cast_Fwd ) \ Entry( Parameters ) \ - Entry( Preprocessor_Include ) \ + Entry( Preprocess_Define ) \ + Entry( Preprocess_If ) \ + Entry( Preprocess_IfDef ) \ + Entry( Preprocess_IfNotDef ) \ + Entry( Preprocess_ElIf ) \ + Entry( Preprocess_Else ) \ + Entry( Preprocess_EndIf ) \ + Entry( Preprocess_Include ) \ + Entry( Preprocess_Pragma ) \ Entry( Specifiers ) \ Entry( Struct ) \ Entry( Struct_Fwd ) \ diff --git a/project/components/especifier.hpp b/project/components/especifier.hpp index 9affa84..e2939ac 100644 --- a/project/components/especifier.hpp +++ b/project/components/especifier.hpp @@ -20,6 +20,7 @@ namespace ESpecifier Entry( Internal_Linkage, internal ) \ Entry( Local_Persist, local_persist ) \ Entry( Mutable, mutable ) \ + Entry( NeverInline, neverinline ) \ Entry( Ptr, * ) \ Entry( Ref, & ) \ Entry( Register, register ) \ @@ -56,9 +57,11 @@ namespace ESpecifier # pragma push_macro( "global" ) # pragma push_macro( "internal" ) # pragma push_macro( "local_persist" ) + # pragma push_macro( "neverinline" ) # undef global # undef internal # undef local_persist + # undef neverinline # define Entry( Spec_, Code_ ) { sizeof(stringize(Code_)), stringize(Code_) }, Define_Specifiers @@ -67,6 +70,7 @@ namespace ESpecifier # pragma pop_macro( "global" ) # pragma pop_macro( "internal" ) # pragma pop_macro( "local_persist" ) + # pragma pop_macro( "neverinline" ) }; return lookup[ specifier ]; diff --git a/project/components/etoktype.cpp b/project/components/etoktype.cpp index adaea66..78a5932 100644 --- a/project/components/etoktype.cpp +++ b/project/components/etoktype.cpp @@ -6,7 +6,7 @@ namespace Parser For the sake of scanning files, it can scan preprocessor directives - Attributes_Start is only used to indicate the start of the user_defined attribute list. + __Attributes_Start is only used to indicate the start of the user_defined attribute list. */ #ifndef GEN_DEFINE_ATTRIBUTE_TOKENS @@ -15,7 +15,7 @@ namespace Parser Entry( API_Import, "GEN_API_Import_Code" ) #endif -# define Define_TokType \ +# define Define_TokType \ Entry( Invalid, "INVALID" ) \ Entry( Access_Private, "private" ) \ Entry( Access_Protected, "protected" ) \ @@ -33,11 +33,11 @@ namespace Parser Entry( BraceSquare_Close, "]" ) \ Entry( Capture_Start, "(" ) \ Entry( Capture_End, ")" ) \ - Entry( Comment, "comment" ) \ - Entry( Char, "character" ) \ + Entry( Comment, "__comment__" ) \ + Entry( Char, "__character__" ) \ Entry( Comma, "," ) \ Entry( Decl_Class, "class" ) \ - Entry( Decl_GNU_Attribute, "__attribute__" ) \ + Entry( Decl_GNU_Attribute, "__attribute__" ) \ Entry( Decl_MSVC_Attribute, "__declspec" ) \ Entry( Decl_Enum, "enum" ) \ Entry( Decl_Extern_Linkage, "extern" ) \ @@ -50,17 +50,23 @@ namespace Parser Entry( Decl_Typedef, "typedef" ) \ Entry( Decl_Using, "using" ) \ Entry( Decl_Union, "union" ) \ - Entry( Identifier, "identifier" ) \ + Entry( Identifier, "__identifier__" ) \ Entry( Module_Import, "import" ) \ Entry( Module_Export, "export" ) \ - Entry( Number, "number" ) \ - Entry( Operator, "operator" ) \ - Entry( Preprocess_Define, "#define") \ - Entry( Preproces_Include, "include" ) \ - Entry( Preprocess_If, "#if") \ - Entry( Preprocess_Elif, "#elif") \ - Entry( Preprocess_Else, "#else") \ - Entry( Preprocess_EndIf, "#endif") \ + Entry( Number, "__number__" ) \ + Entry( Operator, "__operator__" ) \ + Entry( Preprocess_Define, "define") \ + Entry( Preprocess_If, "if") \ + Entry( Preprocess_IfDef, "ifdef") \ + Entry( Preprocess_IfNotDef, "ifndef") \ + Entry( Preprocess_ElIf, "elif") \ + Entry( Preprocess_Else, "else") \ + Entry( Preprocess_EndIf, "endif") \ + Entry( Preprocess_Include, "include" ) \ + Entry( Preprocess_Pragma, "pragma") \ + Entry( Preprocess_Content, "__macro_content__") \ + Entry( Preprocess_Macro, "__macro__") \ + Entry( Preprocess_Unsupported, "__unsupported__" ) \ Entry( Spec_Alignas, "alignas" ) \ Entry( Spec_Const, "const" ) \ Entry( Spec_Consteval, "consteval" ) \ @@ -74,13 +80,15 @@ namespace Parser Entry( Spec_Internal_Linkage, "internal" ) \ Entry( Spec_LocalPersist, "local_persist" ) \ Entry( Spec_Mutable, "mutable" ) \ + Entry( Spec_NeverInline, "neverinline" ) \ Entry( Spec_Override, "override" ) \ Entry( Spec_Static, "static" ) \ Entry( Spec_ThreadLocal, "thread_local" ) \ Entry( Spec_Volatile, "volatile") \ Entry( Star, "*" ) \ Entry( Statement_End, ";" ) \ - Entry( String, "string" ) \ + Entry( StaticAssert, "static_assert" ) \ + Entry( String, "__string__" ) \ Entry( Type_Unsigned, "unsigned" ) \ Entry( Type_Signed, "signed" ) \ Entry( Type_Short, "short" ) \ @@ -88,8 +96,13 @@ namespace Parser Entry( Type_char, "char" ) \ Entry( Type_int, "int" ) \ Entry( Type_double, "double" ) \ + Entry( Type_MS_int8, "__int8" ) \ + Entry( Type_MS_int16, "__int16" ) \ + Entry( Type_MS_int32, "__int32" ) \ + Entry( Type_MS_int64, "__int64" ) \ + Entry( Type_MS_W64, "_W64" ) \ Entry( Varadic_Argument, "..." ) \ - Entry( Attributes_Start, "__attrib_start__" ) + Entry( __Attributes_Start, "__attrib_start__" ) namespace ETokType { diff --git a/project/components/header_end.hpp b/project/components/header_end.hpp index d40961d..47f923e 100644 --- a/project/components/header_end.hpp +++ b/project/components/header_end.hpp @@ -26,12 +26,29 @@ void AST::append( AST* other ) char const* AST::debug_str() { + if ( Parent ) + { + char const* fmt = stringize( + \nType : %s + \nParent : %s %s + \nName : %s + ); + + // These should be used immediately in a log. + // Thus if its desired to keep the debug str + // for multiple calls to bprintf, + // allocate this to proper string. + return str_fmt_buf( fmt + , type_str() + , Parent->Name + , Parent->type_str() + , Name ? Name : "" + ); + } + char const* fmt = stringize( - \nCode Debug: \nType : %s - \nParent : %s \nName : %s - \nComment : %s ); // These should be used immediately in a log. @@ -40,7 +57,6 @@ char const* AST::debug_str() // allocate this to proper string. return str_fmt_buf( fmt , type_str() - , Parent ? Parent->Name : "" , Name ? Name : "" ); } @@ -162,6 +178,7 @@ Define_CodeImpl( CodeBody ); Define_CodeImpl( CodeAttributes ); Define_CodeImpl( CodeComment ); Define_CodeImpl( CodeClass ); +Define_CodeImpl( CodeDefine ); Define_CodeImpl( CodeEnum ); Define_CodeImpl( CodeExec ); Define_CodeImpl( CodeExtern ); @@ -173,6 +190,8 @@ Define_CodeImpl( CodeNamespace ); Define_CodeImpl( CodeOperator ); Define_CodeImpl( CodeOpCast ); Define_CodeImpl( CodeParam ); +Define_CodeImpl( CodePragma ); +Define_CodeImpl( CodePreprocessCond ); Define_CodeImpl( CodeSpecifiers ); Define_CodeImpl( CodeStruct ); Define_CodeImpl( CodeTemplate ); @@ -193,6 +212,7 @@ Define_AST_Cast( Body ); Define_AST_Cast( Attributes ); Define_AST_Cast( Comment ); Define_AST_Cast( Class ); +Define_AST_Cast( Define ); Define_AST_Cast( Enum ); Define_AST_Cast( Exec ); Define_AST_Cast( Extern ); @@ -204,6 +224,8 @@ Define_AST_Cast( Namespace ); Define_AST_Cast( Operator ); Define_AST_Cast( OpCast ); Define_AST_Cast( Param ); +Define_AST_Cast( Pragma ); +Define_AST_Cast( PreprocessCond ); Define_AST_Cast( Struct ); Define_AST_Cast( Specifiers ); Define_AST_Cast( Template ); @@ -223,6 +245,7 @@ Code::operator Code ## type() const \ Define_CodeCast( Attributes ); Define_CodeCast( Comment ); Define_CodeCast( Class ); +Define_CodeCast( Define ); Define_CodeCast( Exec ); Define_CodeCast( Enum ); Define_CodeCast( Extern ); @@ -234,6 +257,8 @@ Define_CodeCast( Namespace ); Define_CodeCast( Operator ); Define_CodeCast( OpCast ); Define_CodeCast( Param ); +Define_CodeCast( Pragma ); +Define_CodeCast( PreprocessCond ); Define_CodeCast( Specifiers ); Define_CodeCast( Struct ); Define_CodeCast( Template ); @@ -343,7 +368,7 @@ CodeBody def_body( CodeT type ) } Code - result = make_code(); + result = make_code(); result->Type = type; return (CodeBody)result; } @@ -368,28 +393,6 @@ StrC token_fmt_impl( sw num, ... ) #pragma region Constants -#ifdef GEN_DEFINE_LIBRARY_CODE_CONSTANTS - // Predefined typename codes. Are set to readonly and are setup during gen::init() - - extern CodeType t_b32; - - extern CodeType t_s8; - extern CodeType t_s16; - extern CodeType t_s32; - extern CodeType t_s64; - - extern CodeType t_u8; - extern CodeType t_u16; - extern CodeType t_u32; - extern CodeType t_u64; - - extern CodeType t_sw; - extern CodeType t_uw; - - extern CodeType t_f32; - extern CodeType t_f64; -#endif - #ifndef GEN_GLOBAL_BUCKET_SIZE # define GEN_GLOBAL_BUCKET_SIZE megabytes(10) #endif @@ -437,29 +440,22 @@ constexpr s32 TokenFmt_TokenMap_MemSize = GEN_TOKEN_FMT_TOKEN_MAP_MEM_SIZE; constexpr s32 LexAllocator_Size = GEN_LEX_ALLOCATOR_SIZE; constexpr s32 Builder_StrBufferReserve = GEN_BUILDER_STR_BUFFER_RESERVE; -extern CodeType t_empty; // Used with varaidc parameters. (Exposing just in case its useful for another circumstance) -extern CodeType t_auto; -extern CodeType t_void; -extern CodeType t_int; -extern CodeType t_bool; -extern CodeType t_char; -extern CodeType t_wchar_t; -extern CodeType t_class; -extern CodeType t_typename; - -extern CodeParam param_varadic; - -extern CodeAttributes attrib_api_export; -extern CodeAttributes attrib_api_import; - extern Code access_public; extern Code access_protected; extern Code access_private; +extern CodeAttributes attrib_api_export; +extern CodeAttributes attrib_api_import; + extern Code module_global_fragment; extern Code module_private_fragment; -extern Code pragma_once; +extern CodePragma pragma_once; + +extern CodeParam param_varadic; + +extern CodePreprocessCond preprocess_else; +extern CodePreprocessCond preprocess_endif; extern CodeSpecifiers spec_const; extern CodeSpecifiers spec_consteval; @@ -472,6 +468,7 @@ extern CodeSpecifiers spec_inline; extern CodeSpecifiers spec_internal_linkage; extern CodeSpecifiers spec_local_persist; extern CodeSpecifiers spec_mutable; +extern CodeSpecifiers spec_neverinline; extern CodeSpecifiers spec_override; extern CodeSpecifiers spec_ptr; extern CodeSpecifiers spec_ref; @@ -482,6 +479,38 @@ extern CodeSpecifiers spec_thread_local; extern CodeSpecifiers spec_virtual; extern CodeSpecifiers spec_volatile; +extern CodeType t_empty; // Used with varaidc parameters. (Exposing just in case its useful for another circumstance) +extern CodeType t_auto; +extern CodeType t_void; +extern CodeType t_int; +extern CodeType t_bool; +extern CodeType t_char; +extern CodeType t_wchar_t; +extern CodeType t_class; +extern CodeType t_typename; + +#ifdef GEN_DEFINE_LIBRARY_CODE_CONSTANTS + // Predefined typename codes. Are set to readonly and are setup during gen::init() + + extern CodeType t_b32; + + extern CodeType t_s8; + extern CodeType t_s16; + extern CodeType t_s32; + extern CodeType t_s64; + + extern CodeType t_u8; + extern CodeType t_u16; + extern CodeType t_u32; + extern CodeType t_u64; + + extern CodeType t_sw; + extern CodeType t_uw; + + extern CodeType t_f32; + extern CodeType t_f64; +#endif + #pragma endregion Constants #pragma region Macros diff --git a/project/components/interface.cpp b/project/components/interface.cpp index d1e7d56..ca4fc3a 100644 --- a/project/components/interface.cpp +++ b/project/components/interface.cpp @@ -1,3 +1,6 @@ +internal void init_parser(); +internal void deinit_parser(); + internal void* Global_Allocator_Proc( void* allocator_data, AllocType type, sw size, sw alignment, void* old_memory, sw old_size, u64 flags ) { @@ -71,6 +74,64 @@ void define_constants() Code::Invalid = make_code(); Code::Invalid.set_global(); + t_empty = (CodeType) make_code(); + t_empty->Type = ECode::Typename; + t_empty->Name = get_cached_string( txt_StrC("") ); + t_empty.set_global(); + + access_private = make_code(); + access_private->Type = ECode::Access_Private; + access_private->Name = get_cached_string( txt_StrC("private:") ); + access_private.set_global(); + + access_protected = make_code(); + access_protected->Type = ECode::Access_Protected; + access_protected->Name = get_cached_string( txt_StrC("protected:") ); + access_protected.set_global(); + + access_public = make_code(); + access_public->Type = ECode::Access_Public; + access_public->Name = get_cached_string( txt_StrC("public:") ); + access_public.set_global(); + + attrib_api_export = def_attributes( code(GEN_API_Export_Code)); + attrib_api_export.set_global(); + + attrib_api_import = def_attributes( code(GEN_API_Import_Code)); + attrib_api_import.set_global(); + + module_global_fragment = make_code(); + module_global_fragment->Type = ECode::Untyped; + module_global_fragment->Name = get_cached_string( txt_StrC("module;") ); + module_global_fragment->Content = module_global_fragment->Name; + module_global_fragment.set_global(); + + module_private_fragment = make_code(); + module_private_fragment->Type = ECode::Untyped; + module_private_fragment->Name = get_cached_string( txt_StrC("module : private;") ); + module_private_fragment->Content = module_private_fragment->Name; + module_private_fragment.set_global(); + + pragma_once = (CodePragma) make_code(); + pragma_once->Type = ECode::Untyped; + pragma_once->Name = get_cached_string( txt_StrC("once") ); + pragma_once->Content = pragma_once->Name; + pragma_once.set_global(); + + param_varadic = (CodeType) make_code(); + param_varadic->Type = ECode::Parameters; + param_varadic->Name = get_cached_string( txt_StrC("...") ); + param_varadic->ValueType = t_empty; + param_varadic.set_global(); + + preprocess_else = (CodePreprocessCond) make_code(); + preprocess_else->Type = ECode::Preprocess_Else; + preprocess_else.set_global(); + + preprocess_endif = (CodePreprocessCond) make_code(); + preprocess_endif->Type = ECode::Preprocess_EndIf; + preprocess_endif.set_global(); + # define def_constant_code_type( Type_ ) \ t_##Type_ = def_type( name(Type_) ); \ t_##Type_.set_global(); @@ -105,62 +166,14 @@ void define_constants() #endif # undef def_constant_code_type - t_empty = (CodeType) make_code(); - t_empty->Type = ECode::Typename; - t_empty->Name = get_cached_string( txt_StrC("") ); - t_empty.set_global(); - - param_varadic = (CodeType) make_code(); - param_varadic->Type = ECode::Parameters; - param_varadic->Name = get_cached_string( txt_StrC("...") ); - param_varadic->ValueType = t_empty; - param_varadic.set_global(); - - attrib_api_export = def_attributes( code(GEN_API_Export_Code)); - attrib_api_export.set_global(); - - attrib_api_import = def_attributes( code(GEN_API_Import_Code)); - attrib_api_import.set_global(); - - access_private = make_code(); - access_private->Type = ECode::Access_Private; - access_private->Name = get_cached_string( txt_StrC("private:") ); - access_private.set_global(); - - access_protected = make_code(); - access_protected->Type = ECode::Access_Protected; - access_protected->Name = get_cached_string( txt_StrC("protected:") ); - access_protected.set_global(); - - access_public = make_code(); - access_public->Type = ECode::Access_Public; - access_public->Name = get_cached_string( txt_StrC("public:") ); - access_public.set_global(); - - module_global_fragment = make_code(); - module_global_fragment->Type = ECode::Untyped; - module_global_fragment->Name = get_cached_string( txt_StrC("module;") ); - module_global_fragment->Content = module_global_fragment->Name; - module_global_fragment.set_global(); - - module_private_fragment = make_code(); - module_private_fragment->Type = ECode::Untyped; - module_private_fragment->Name = get_cached_string( txt_StrC("module : private;") ); - module_private_fragment->Content = module_private_fragment->Name; - module_private_fragment.set_global(); - - pragma_once = make_code(); - pragma_once->Type = ECode::Untyped; - pragma_once->Name = get_cached_string( txt_StrC("#pragma once") ); - pragma_once->Content = pragma_once->Name; - pragma_once.set_global(); - # pragma push_macro( "global" ) # pragma push_macro( "internal" ) # pragma push_macro( "local_persist" ) +# pragma push_macro( "neverinline" ) # undef global # undef internal # undef local_persist +# undef neverinline # define def_constant_spec( Type_, ... ) \ spec_##Type_ = def_specifiers( num_args(__VA_ARGS__), __VA_ARGS__); \ @@ -177,6 +190,7 @@ void define_constants() def_constant_spec( internal_linkage, ESpecifier::Internal_Linkage ); def_constant_spec( local_persist, ESpecifier::Local_Persist ); def_constant_spec( mutable, ESpecifier::Mutable ); + def_constant_spec( neverinline, ESpecifier::NeverInline ); def_constant_spec( override, ESpecifier::Override ); def_constant_spec( ptr, ESpecifier::Ptr ); def_constant_spec( ref, ESpecifier::Ref ); @@ -193,6 +207,7 @@ void define_constants() # pragma pop_macro( "global" ) # pragma pop_macro( "internal" ) # pragma pop_macro( "local_persist" ) +# pragma pop_macro( "neverinline" ) # undef def_constant_spec } @@ -258,6 +273,7 @@ void init() } define_constants(); + init_parser(); } void deinit() @@ -300,6 +316,7 @@ void deinit() while ( left--, left ); Global_AllocatorBuckets.free(); + deinit_parser(); } void reset() diff --git a/project/components/interface.hpp b/project/components/interface.hpp index b1fb94a..00dc4c5 100644 --- a/project/components/interface.hpp +++ b/project/components/interface.hpp @@ -45,6 +45,8 @@ CodeClass def_class( StrC name , ModuleFlag mflags = ModuleFlag::None , CodeType* interfaces = nullptr, s32 num_interfaces = 0 ); +CodeDefine def_define( StrC name, StrC content ); + CodeEnum def_enum( StrC name , Code body = NoCode, CodeType type = NoCode , EnumT specifier = EnumRegular, CodeAttributes attributes = NoCode @@ -63,14 +65,18 @@ CodeInclude def_include ( StrC content ); CodeModule def_module ( StrC name, ModuleFlag mflags = ModuleFlag::None ); CodeNamespace def_namespace( StrC name, Code body, ModuleFlag mflags = ModuleFlag::None ); -CodeOperator def_operator( OperatorT op +CodeOperator def_operator( OperatorT op, StrC nspace , CodeParam params = NoCode, CodeType ret_type = NoCode, Code body = NoCode , CodeSpecifiers specifiers = NoCode, CodeAttributes attributes = NoCode , ModuleFlag mflags = ModuleFlag::None ); CodeOpCast def_operator_cast( CodeType type, Code body = NoCode, CodeSpecifiers specs = NoCode ); -CodeParam def_param ( CodeType type, StrC name, Code value = NoCode ); +CodeParam def_param ( CodeType type, StrC name, Code value = NoCode ); +CodePragma def_pragma( StrC directive ); + +CodePreprocessCond def_preprocess_cond( EPreprocessCond type, StrC content ); + CodeSpecifiers def_specifier( SpecifierT specifier ); CodeStruct def_struct( StrC name diff --git a/project/components/interface.parsing.cpp b/project/components/interface.parsing.cpp index 22b46cd..8de7a61 100644 --- a/project/components/interface.parsing.cpp +++ b/project/components/interface.parsing.cpp @@ -1,6 +1,3 @@ -/* -These constructors are the most implementation intensive other than the editor or scanner. -*/ namespace Parser { @@ -9,9 +6,9 @@ namespace Parser char const* Text; sptr Length; TokType Type; - bool IsAssign; s32 Line; s32 Column; + bool IsAssign; // TokFlags Flags; operator bool() @@ -31,12 +28,17 @@ namespace Parser bool is_attribute() { - return Type > TokType::Attributes_Start; + return Type > TokType::__Attributes_Start; } bool is_preprocessor() { - return Type >= TokType::Preprocess_Define && Type <= TokType::Preprocess_EndIf; + return Type >= TokType::Preprocess_Define && Type <= TokType::Preprocess_Pragma; + } + + bool is_preprocess_cond() + { + return Type >= TokType::Preprocess_If && Type <= TokType::Preprocess_EndIf; } bool is_specifier() @@ -76,6 +78,11 @@ namespace Parser { return Idx + 1 < Arr.num() ? &Arr[Idx + 1] : nullptr; } + + Token& operator []( s32 idx ) + { + return Arr[idx]; + } }; struct StackNode @@ -119,14 +126,17 @@ namespace Parser } String line = String::make( GlobalAllocator, { length, scope_start.Text } ); - result.append_fmt("\tScope: %s\n", line ); + result.append_fmt("\tScope : %s\n", line ); line.free(); - sptr dist = (sptr)last_valid.Text - (sptr)scope_start.Text; + sptr dist = (sptr)last_valid.Text - (sptr)scope_start.Text + 2; sptr length_from_err = dist; String line_from_err = String::make( GlobalAllocator, { length_from_err, last_valid.Text } ); - result.append_fmt("\t(%d, %d):%*c\n", last_valid.Line, last_valid.Column, length_from_err, '^' ); + if ( length_from_err < 100 ) + result.append_fmt("\t(%d, %d):%*c\n", last_valid.Line, last_valid.Column, length_from_err, '^' ); + else + result.append_fmt("\t(%d, %d)\n", last_valid.Line, last_valid.Column ); StackNode* curr_scope = Scope; s32 level = 0; @@ -134,7 +144,7 @@ namespace Parser { if ( curr_scope->Name ) { - result.append_fmt("\t%d: %s, AST Name: %s\n", level, curr_scope->ProcName.Ptr, (StrC)curr_scope->Name ); + result.append_fmt("\t%d: %s, AST Name: %.*s\n", level, curr_scope->ProcName.Ptr, curr_scope->Name.Length, (StrC)curr_scope->Name ); } else { @@ -163,7 +173,13 @@ namespace Parser { String token_str = String::make( GlobalAllocator, { Arr[Idx].Length, Arr[Idx].Text } ); - log_failure( "Parse Error, TokArray::eat, Expected: %s, not '%s' (%d, %d)`\n%s", ETokType::to_str(type), token_str, current().Line, current().Column, Context.to_string() ); + log_failure( "Parse Error, TokArray::eat, Expected: ' %s ' not ' %s ' (%d, %d)`\n%s" + , ETokType::to_str(type) + , token_str + , current().Line + , current().Column + , Context.to_string() + ); return false; } @@ -177,7 +193,9 @@ namespace Parser IsAssign = bit(0), }; - TokArray lex( StrC content, bool keep_preprocess_directives = true ) + global Array Tokens; + + TokArray lex( StrC content ) { # define current ( * scanner ) @@ -202,28 +220,14 @@ namespace Parser move_forward(); \ } - # define SkipWhitespace_Checked( Context_, Msg_, ... ) \ - while ( left && char_is_space( current ) ) \ - { \ - move_forward(); \ - } \ - if ( left <= 0 ) \ - { \ - log_failure( "gen::" txt(Context_) ": " Msg_, __VA_ARGS__ ); \ - return { 0, nullptr }; \ - } - - local_persist thread_local - Array Tokens = { nullptr }; - s32 left = content.Len; char const* scanner = content.Ptr; char const* word = scanner; s32 word_length = 0; - s32 line = 0; - s32 column = 0; + s32 line = 1; + s32 column = 1; SkipWhitespace(); if ( left <= 0 ) @@ -232,16 +236,26 @@ namespace Parser return { { nullptr }, 0 }; } - if ( Tokens ) + local_persist char defines_map_mem[ kilobytes(64) ]; + local_persist Arena defines_map_arena; + HashTable defines; { - Tokens.free(); + defines_map_arena = Arena::init_from_memory( defines_map_mem, sizeof(defines_map_mem) ); + defines = HashTable::init( defines_map_arena ); } - Tokens = Array::init_reserve( LexArena, content.Len / 6 ); + Tokens.clear(); while (left ) { - Token token = { nullptr, 0, TokType::Invalid, false, line, column }; + Token token = { nullptr, 0, TokType::Invalid, line, column, false }; + + if ( line == 4921 ) + { + log_fmt("here"); + } + + bool is_define = false; SkipWhitespace(); if ( left <= 0 ) @@ -249,34 +263,206 @@ namespace Parser switch ( current ) { - // TODO : Need to handle the preprocessor as a separate pass. case '#': - token.Text = scanner; - token.Length = 1; + { + char const* hash = scanner; + move_forward(); + SkipWhitespace(); - while (left && current != '\n' ) + token.Text = scanner; + while (left && ! char_is_space(current) ) { - if ( token.Type == ETokType::Invalid && current == ' ' ) - { - token.Type = ETokType::to_type( token ); - } - - if ( current == '\\' ) - { - move_forward(); - - if ( current != '\n' && keep_preprocess_directives ) - { - log_failure( "gen::lex: invalid preprocessor directive, will still grab but will not compile %s", token.Text ); - } - } - move_forward(); token.Length++; } - goto FoundToken; + token.Type = ETokType::to_type( token ); + + if ( ! token.is_preprocessor() ) + { + token.Type = TokType::Preprocess_Unsupported; + + // Its an unsupported directive, skip it + s32 within_string = false; + s32 within_char = false; + while ( left ) + { + if ( current == '"' ) + within_string ^= true; + + if ( current == '\'' ) + within_char ^= true; + + if ( current == '\\' && ! within_string && ! within_char ) + { + move_forward(); + token.Length++; + + if ( current == '\r' ) + { + move_forward(); + // token.Length++; + } + + if ( current == '\n' ) + { + move_forward(); + // token.Length++; + continue; + } + else + { + String directive_str = String::make_length( GlobalAllocator, token.Text, token.Length ); + + log_failure( "gen::Parser::lex: Invalid escape sequence '\\%c' (%d, %d)" + " in preprocessor directive (%d, %d)\n%s" + , current, line, column + , token.Line, token.Column, directive_str ); + break; + } + } + + if ( current == '\n' ) + { + move_forward(); + // token.Length++; + break; + } + + move_forward(); + token.Length++; + } + + token.Text = hash; + token.Length = (sptr)token.Text + token.Length - (sptr)hash; + Tokens.append( token ); + continue; // Skip found token, its all handled here. + } + + if ( token.Type == TokType::Preprocess_Else || token.Type == TokType::Preprocess_EndIf ) + { + Tokens.append( token ); + continue; + } + + Tokens.append( token ); + + SkipWhitespace(); + + if ( token.Type == TokType::Preprocess_Define ) + { + Token name = { scanner, 0, TokType::Identifier, line, column, false }; + + name.Text = scanner; + name.Length = 1; + move_forward(); + + while ( left && ( char_is_alphanumeric(current) || current == '_' ) ) + { + move_forward(); + name.Length++; + } + + if ( left && current == '(' ) + { + move_forward(); + name.Length++; + } + + Tokens.append( name ); + + u64 key = crc32( name.Text, name.Length ); + defines.set( key, name ); + } + + Token content = { scanner, 0, TokType::Preprocess_Content, line, column, false }; + + if ( token.Type == TokType::Preprocess_Include ) + { + content.Type = TokType::String; + + if ( current != '"' && current != '<' ) + { + String directive_str = String::fmt_buf( GlobalAllocator, "%.*s", min( 80, left + content.Length ), token.Text ); + + log_failure( "gen::Parser::lex: Expected '\"' or '<' after #include, not '%c' (%d, %d)\n%s" + , current + , content.Line + , content.Column + , directive_str.Data + ); + return { { nullptr }, 0 }; + } + + while ( left && current != '"' && current != '>' ) + { + move_forward(); + content.Length++; + } + + move_forward(); + content.Length++; + + Tokens.append( content ); + continue; // Skip found token, its all handled here. + } + + s32 within_string = false; + s32 within_char = false; + while ( left ) + { + if ( current == '"' ) + within_string ^= true; + + if ( current == '\'' ) + within_char ^= true; + + if ( current == '\\' && ! within_string && ! within_char ) + { + move_forward(); + content.Length++; + + if ( current == '\r' ) + { + move_forward(); + content.Length++; + } + + if ( current == '\n' ) + { + move_forward(); + content.Length++; + continue; + } + else + { + String directive_str = String::make_length( GlobalAllocator, token.Text, token.Length ); + String content_str = String::fmt_buf( GlobalAllocator, "%.*s", min( 400, left + content.Length ), content.Text ); + + log_failure( "gen::Parser::lex: Invalid escape sequence '\\%c' (%d, %d)" + " in preprocessor directive '%s' (%d, %d)\n%s" + , current, line, column + , directive_str, content.Line, content.Column + , content_str ); + break; + } + } + + if ( current == '\n' ) + { + move_forward(); + // content.Length++; + break; + } + + move_forward(); + content.Length++; + } + + Tokens.append( content ); + continue; // Skip found token, its all handled here. + } case '.': token.Text = scanner; token.Length = 1; @@ -297,7 +483,9 @@ namespace Parser } else { - log_failure( "gen::lex: invalid varadic argument, expected '...' got '..%c'", current ); + String context_str = String::fmt_buf( GlobalAllocator, "%s", scanner, min( 100, left ) ); + + log_failure( "gen::lex: invalid varadic argument, expected '...' got '..%c' (%d, %d)\n%s", current, line, column, context_str ); } } @@ -407,6 +595,18 @@ namespace Parser move_forward(); + if ( left && current == '\\' ) + { + move_forward(); + token.Length++; + + if ( current == '\'' ) + { + move_forward(); + token.Length++; + } + } + while ( left && current != '\'' ) { move_forward(); @@ -479,6 +679,17 @@ namespace Parser } goto FoundToken; + case '?': + token.Text = scanner; + token.Length = 1; + token.Type = TokType::Operator; + token.IsAssign = false; + + if (left) + move_forward(); + + goto FoundToken; + // All other operators we just label as an operator and move forward. case '=': token.Text = scanner; @@ -489,6 +700,15 @@ namespace Parser if (left) move_forward(); + if ( current == '=' ) + { + token.Length++; + token.IsAssign = false; + + if (left) + move_forward(); + } + goto FoundToken; case '+': @@ -592,10 +812,17 @@ namespace Parser token.Text = scanner; token.Length = 0; - while ( left && ( current != '*' && *(scanner + 1) != '/' ) ) + bool star = current == '*'; + bool slash = scanner[1] == '/'; + bool at_end = star && slash; + while ( left && ! at_end ) { move_forward(); token.Length++; + + star = current == '*'; + slash = scanner[1] == '/'; + at_end = star && slash; } move_forward(); move_forward(); @@ -667,9 +894,9 @@ namespace Parser } else { - String context_str = String::fmt_buf( GlobalAllocator, "%s", scanner, min( 100, left ) ); + String context_str = String::fmt_buf( GlobalAllocator, "%.*s", min( 100, left ), scanner ); - log_failure( "Failed to lex token %s", context_str ); + log_failure( "Failed to lex token '%c' (%d, %d)\n%s", current, line, column, context_str ); // Skip to next whitespace since we can't know if anything else is valid until then. while ( left && ! char_is_space( current ) ) @@ -682,19 +909,70 @@ namespace Parser if ( token.Type != TokType::Invalid ) { - if ( token.is_preprocessor() && keep_preprocess_directives == false ) - continue; - Tokens.append( token ); continue; } TokType type = ETokType::to_type( token ); - if ( type == TokType::Invalid) - type = TokType::Identifier; + if ( type == ETokType::Decl_Extern_Linkage ) + { + SkipWhitespace(); + + if ( current != '"' ) + type = ETokType::Spec_Extern; + + token.Type = type; + Tokens.append( token ); + continue; + } + + if ( type != TokType::Invalid ) + { + token.Type = type; + Tokens.append( token ); + continue; + } + + u64 key = 0; + if ( current == '(') + key = crc32( token.Text, token.Length + 1 ); + else + key = crc32( token.Text, token.Length ); + + StrC* define = defines.get( key ); + if ( define ) + { + token.Type = TokType::Preprocess_Macro; + + // Want to ignore any arguments the define may have as they can be execution expressions. + if ( left && current == '(' ) + { + move_forward(); + token.Length++; + + s32 level = 0; + while ( left && (current != ')' || level > 0) ) + { + if ( current == '(' ) + level++; + + else if ( current == ')' && level > 0 ) + level--; + + move_forward(); + token.Length++; + } + + move_forward(); + token.Length++; + } + } + else + { + token.Type = TokType::Identifier; + } - token.Type = type; Tokens.append( token ); } @@ -704,26 +982,45 @@ namespace Parser return { { nullptr }, 0 }; } + defines.clear(); + defines_map_arena.free(); return { Tokens, 0 }; # undef current # undef move_forward # undef SkipWhitespace - # undef SkipWhitespace_Checked } } +internal +void init_parser() +{ + using namespace Parser; + + Tokens = Array::init_reserve( LexArena + , ( LexAllocator_Size - sizeof( Array::Header ) ) / sizeof(Token) + ); +} + +internal +void deinit_parser() +{ + Parser::Tokens = { nullptr }; +} + #pragma region Helper Macros -# define check_parse_args( def ) \ -if ( def.Len <= 0 ) \ -{ \ +# define check_parse_args( def ) \ +if ( def.Len <= 0 ) \ +{ \ log_failure( "gen::" stringize(__func__) ": length must greater than 0" ); \ - return CodeInvalid; \ -} \ -if ( def.Ptr == nullptr ) \ -{ \ + Parser::Context.pop(); \ + return CodeInvalid; \ +} \ +if ( def.Ptr == nullptr ) \ +{ \ log_failure( "gen::" stringize(__func__) ": def was null" ); \ - return CodeInvalid; \ + Parser::Context.pop(); \ + return CodeInvalid; \ } # define nexttok Context.Tokens.next() @@ -734,7 +1031,7 @@ if ( def.Ptr == nullptr ) # define check( Type_ ) ( left && currtok.Type == Type_ ) -# define push_scope() \ +# define push_scope() \ StackNode scope { nullptr, currtok, NullToken, txt_StrC( __func__ ) }; \ Context.push( & scope ) @@ -743,8 +1040,8 @@ if ( def.Ptr == nullptr ) internal Code parse_function_body(); internal Code parse_global_nspace(); -internal CodeClass parse_class (); -internal CodeEnum parse_enum (); +internal CodeClass parse_class ( bool inplace_def = false ); +internal CodeEnum parse_enum ( bool inplace_def = false ); internal CodeBody parse_export_body (); internal CodeBody parse_extern_link_body(); internal CodeExtern parse_exten_link (); @@ -752,20 +1049,195 @@ internal CodeFriend parse_friend (); internal CodeFn parse_function (); internal CodeNamespace parse_namespace (); internal CodeOpCast parse_operator_cast (); -internal CodeStruct parse_struct (); +internal CodeStruct parse_struct ( bool inplace_def = false ); internal CodeVar parse_variable (); internal CodeTemplate parse_template (); internal CodeType parse_type (); internal CodeTypedef parse_typedef (); -internal CodeUnion parse_union (); +internal CodeUnion parse_union ( bool inplace_def = false ); internal CodeUsing parse_using (); +constexpr bool inplace_def = true; + +internal inline +CodeDefine parse_define() +{ + using namespace Parser; + push_scope(); + + eat( TokType::Preprocess_Define ); + + CodeDefine + define = (CodeDefine) make_code(); + define->Type = ECode::Preprocess_Define; + + if ( ! check( TokType::Identifier ) ) + { + log_failure( "Error, expected identifier after #define\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + Context.Scope->Name = currtok; + define->Name = get_cached_string( currtok ); + eat( TokType::Identifier ); + + if ( ! check( TokType::Preprocess_Content )) + { + log_failure( "Error, expected content after #define %s\n%s", define->Name, Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + define->Content = get_cached_string( currtok ); + eat( TokType::Preprocess_Content ); + + Context.pop(); + return define; +} + +internal inline +CodePreprocessCond parse_preprocess_cond() +{ + using namespace Parser; + push_scope(); + + if ( ! currtok.is_preprocess_cond() ) + { + log_failure( "Error, expected preprocess conditional\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + CodePreprocessCond + cond = (CodePreprocessCond) make_code(); + cond->Type = scast(CodeT, currtok.Type - (ETokType::Preprocess_If - ECode::Preprocess_If) ); + eat( currtok.Type ); + + if ( ! check( TokType::Preprocess_Content )) + { + log_failure( "Error, expected content after #define\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + Context.Scope->Name = currtok; + cond->Content = get_cached_string( currtok ); + eat( TokType::Preprocess_Content ); + + Context.pop(); + return cond; +} + +internal inline +CodeInclude parse_include() +{ + using namespace Parser; + push_scope(); + + CodeInclude + include = (CodeInclude) make_code(); + include->Type = ECode::Preprocess_Include; + eat( TokType::Preprocess_Include ); + + if ( ! check( TokType::String )) + { + log_failure( "Error, expected include string after #include\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + Context.Scope->Name = currtok; + include->Content = get_cached_string( currtok ); + eat( TokType::String ); + + Context.pop(); + return include; +} + +internal inline +CodePragma parse_pragma() +{ + using namespace Parser; + push_scope(); + + CodePragma + pragma = (CodePragma) make_code(); + pragma->Type = ECode::Preprocess_Pragma; + eat( TokType::Preprocess_Pragma ); + + if ( ! check( TokType::Preprocess_Content )) + { + log_failure( "Error, expected content after #pragma\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + Context.Scope->Name = currtok; + pragma->Content = get_cached_string( currtok ); + eat( TokType::Preprocess_Content ); + + Context.pop(); + return pragma; +} + +internal inline +Code parse_static_assert() +{ + using namespace Parser; + push_scope(); + + Code + assert = make_code(); + assert->Type = ECode::Untyped; + + Token content = currtok; + + Context.Scope->Name = content; + + eat( TokType::StaticAssert ); + eat( TokType::Capture_Start ); + + s32 level = 0; + while ( left && ( currtok.Type != TokType::Capture_End || level > 0 ) ) + { + if ( currtok.Type == TokType::Capture_Start ) + level++; + else if ( currtok.Type == TokType::Capture_End ) + level--; + + eat( currtok.Type ); + } + eat( TokType::Capture_End ); + eat( TokType::Statement_End ); + + content.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)content.Text; + + // content.Text = str_fmt_buf( "%.*s\n", content.Length, content.Text ); + // content.Length++; + + assert->Content = get_cached_string( content ); + assert->Name = assert->Content; + + Context.pop(); + return assert; +} + internal inline Code parse_array_decl() { using namespace Parser; push_scope(); + if ( check( TokType::Operator ) && currtok.Text[0] == '[' && currtok.Text[1] == ']' ) + { + Code array_expr = untyped_str( currtok ); + eat( TokType::Operator ); + + Context.pop(); + return array_expr; + } + if ( check( TokType::BraceSquare_Open ) ) { eat( TokType::BraceSquare_Open ); @@ -773,13 +1245,15 @@ Code parse_array_decl() if ( left == 0 ) { log_failure( "Error, unexpected end of array declaration ( '[]' scope started )\n%s", Context.to_string() ); - return Code::Invalid; + Context.pop(); + return CodeInvalid; } if ( currtok.Type == TokType::BraceSquare_Close ) { log_failure( "Error, empty array expression in typedef definition\n%s", Context.to_string() ); - return Code::Invalid; + Context.pop(); + return CodeInvalid; } Token untyped_tok = currtok; @@ -796,16 +1270,19 @@ Code parse_array_decl() if ( left == 0 ) { log_failure( "Error, unexpected end of array declaration, expected ]\n%s", Context.to_string() ); - return Code::Invalid; + Context.pop(); + return CodeInvalid; } if ( currtok.Type != TokType::BraceSquare_Close ) { log_failure( "%s: Error, expected ] in array declaration, not %s\n%s", ETokType::to_str( currtok.Type ), Context.to_string() ); - return Code::Invalid; + Context.pop(); + return CodeInvalid; } eat( TokType::BraceSquare_Close ); + Context.pop(); return array_expr; } @@ -876,6 +1353,7 @@ CodeAttributes parse_attributes() if ( len > 0 ) { StrC attribute_txt = { len, start.Text }; + Context.pop(); return def_attributes( attribute_txt ); } @@ -890,6 +1368,7 @@ Parser::Token parse_identifier() push_scope(); Token name = currtok; + Context.Scope->Name = name; eat( TokType::Identifier ); @@ -900,12 +1379,14 @@ Parser::Token parse_identifier() if ( left == 0 ) { log_failure( "Error, unexpected end of static symbol identifier\n%s", Context.to_string() ); + Context.pop(); return { nullptr, 0, TokType::Invalid }; } if ( currtok.Type != TokType::Identifier ) { log_failure( "Error, expected static symbol identifier, not %s\n%s", ETokType::to_str( currtok.Type ), Context.to_string() ); + Context.pop(); return { nullptr, 0, TokType::Invalid }; } @@ -932,6 +1413,7 @@ Parser::Token parse_identifier() if ( left == 0 ) { log_failure( "Error, unexpected end of template arguments\n%s", Context.to_string() ); + Context.pop(); return { nullptr, 0, TokType::Invalid }; } @@ -960,6 +1442,7 @@ Parser::Token parse_identifier() if ( left == 0 ) { log_failure( "Error, unexpected end of template arguments\n%s", Context.to_string() ); + Context.pop(); return { nullptr, 0, TokType::Invalid }; } @@ -991,6 +1474,7 @@ CodeParam parse_params( bool use_template_capture = false ) if ( ! use_template_capture && check(TokType::Capture_End) ) { eat( TokType::Capture_End ); + Context.pop(); return { nullptr }; } @@ -1001,14 +1485,18 @@ CodeParam parse_params( bool use_template_capture = false ) { eat( TokType::Varadic_Argument ); + Context.pop(); return param_varadic; } type = parse_type(); if ( type == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } - Token name = { nullptr, 0, TokType::Invalid, false }; + Token name = NullToken; if ( check( TokType::Identifier ) ) { @@ -1021,19 +1509,23 @@ CodeParam parse_params( bool use_template_capture = false ) Token value_tok = currtok; - if ( currtok.Type == TokType::Statement_End ) + if ( currtok.Type == TokType::Comma ) { log_failure( "Expected value after assignment operator\n%s.", Context.to_string() ); + Context.pop(); return CodeInvalid; } - while ( left && currtok.Type != TokType::Statement_End ) + while ( left + && currtok.Type != TokType::Comma + && currtok.Type != TokType::Capture_End + ) { value_tok.Length = ( (sptr)currtok.Text + currtok.Length ) - (sptr)value_tok.Text; eat( currtok.Type ); } - value = parse_type(); + value = untyped_str( value_tok ); } } @@ -1070,7 +1562,10 @@ CodeParam parse_params( bool use_template_capture = false ) type = parse_type(); if ( type == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } name = { nullptr, 0, TokType::Invalid, false }; @@ -1085,19 +1580,22 @@ CodeParam parse_params( bool use_template_capture = false ) Token value_tok = currtok; - if ( currtok.Type == TokType::Statement_End ) + if ( currtok.Type == TokType::Comma ) { log_failure( "Expected value after assignment operator\n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; } - while ( left && currtok.Type != TokType::Statement_End ) + while ( left + && currtok.Type != TokType::Comma && currtok.Type != TokType::Capture_End + ) { value_tok.Length = ( (sptr)currtok.Text + currtok.Length ) - (sptr)value_tok.Text; eat( currtok.Type ); } - value = parse_type(); + value = untyped_str( value_tok ); } } @@ -1124,6 +1622,7 @@ CodeParam parse_params( bool use_template_capture = false ) if ( ! check( TokType::Operator) || currtok.Text[0] != '>' ) { log_failure("Expected '<' after 'template' keyword\n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; } eat( TokType::Operator ); @@ -1141,7 +1640,7 @@ CodeFn parse_function_after_name( , CodeAttributes attributes , CodeSpecifiers specifiers , CodeType ret_type - , StrC name + , Parser::Token name ) { using namespace Parser; @@ -1151,6 +1650,13 @@ CodeFn parse_function_after_name( while ( left && currtok.is_specifier() ) { + if ( specifiers.ast == nullptr ) + { + specifiers = def_specifier( ESpecifier::to_type(currtok) ); + eat( currtok.Type ); + continue; + } + specifiers.append( ESpecifier::to_type(currtok) ); eat( currtok.Type ); } @@ -1160,7 +1666,10 @@ CodeFn parse_function_after_name( { body = parse_function_body(); if ( body == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } } else { @@ -1185,6 +1694,7 @@ CodeFn parse_function_after_name( default: { log_failure("Body must be either of Function_Body or Untyped type, %s\n%s", body.debug_str(), Context.to_string()); + Context.pop(); return CodeInvalid; } } @@ -1221,15 +1731,35 @@ CodeOperator parse_operator_after_ret_type( using namespace EOperator; push_scope(); - // Parse Operator + Token nspace = NullToken; + if ( check( TokType::Identifier ) ) + { + nspace = currtok; + while ( left && currtok.Type == TokType::Identifier ) + { + eat( TokType::Identifier ); + + if ( currtok.Type == TokType::Access_StaticSymbol ) + eat( TokType::Access_StaticSymbol ); + } + + nspace.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)nspace.Text; + } + eat( TokType::Decl_Operator ); - if ( ! check( TokType::Operator ) ) + if ( ! left && currtok.Type != TokType::Operator + && currtok.Type != TokType::Star + && currtok.Type != TokType::Ampersand + && currtok.Type != TokType::Ampersand_DBL ) { log_failure( "Expected operator after 'operator' keyword\n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; } + Context.Scope->Name = currtok; + OperatorT op = Invalid; switch ( currtok.Text[0] ) { @@ -1238,12 +1768,26 @@ CodeOperator parse_operator_after_ret_type( if ( currtok.Text[1] == '=' ) op = Assign_Add; + if ( currtok.Text[1] == '+' ) + op = Increment; + else op = Add; } break; case '-': { + if ( currtok.Text[1] == '>' ) + { + if ( currtok.Text[2] == '*' ) + op = MemberOfPointer; + + else + op = MemberOfPointer; + + break; + } + if ( currtok.Text[1] == '=' ) op = Assign_Subtract; @@ -1413,16 +1957,27 @@ CodeOperator parse_operator_after_ret_type( if ( op == Invalid ) { log_failure( "Invalid operator '%s'\n%s", currtok.Text, Context.to_string() ); + Context.pop(); return CodeInvalid; } - eat( TokType::Operator ); + eat( currtok.Type ); // Parse Params CodeParam params = parse_params(); + if ( params.ast == nullptr && op == EOperator::Multiply ) + op = MemberOfPointer; + while ( left && currtok.is_specifier() ) { + if ( specifiers.ast == nullptr ) + { + specifiers = def_specifier( ESpecifier::to_type(currtok) ); + eat( currtok.Type ); + continue; + } + specifiers.append( ESpecifier::to_type(currtok) ); eat( currtok.Type ); } @@ -1433,7 +1988,10 @@ CodeOperator parse_operator_after_ret_type( { body = parse_function_body(); if ( body == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } } else { @@ -1441,7 +1999,7 @@ CodeOperator parse_operator_after_ret_type( } // OpValidateResult check_result = operator__validate( op, params, ret_type, specifiers ); - CodeOperator result = def_operator( op, params, ret_type, body, specifiers, attributes, mflags ); + CodeOperator result = def_operator( op, nspace, params, ret_type, body, specifiers, attributes, mflags ); Context.pop(); return result; } @@ -1459,8 +2017,9 @@ CodeVar parse_variable_after_name( using namespace Parser; push_scope(); - Code array_expr = parse_array_decl(); - Code expr = { nullptr }; + Code array_expr = parse_array_decl(); + Code expr = { nullptr }; + Code bitfield_expr = { nullptr }; if ( currtok.IsAssign ) { @@ -1471,6 +2030,52 @@ CodeVar parse_variable_after_name( if ( currtok.Type == TokType::Statement_End ) { log_failure( "Expected expression after assignment operator\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + while ( left && currtok.Type != TokType::Statement_End ) + { + eat( currtok.Type ); + } + + expr_tok.Length = ( (sptr)currtok.Text + currtok.Length ) - (sptr)expr_tok.Text - 1; + expr = untyped_str( expr_tok ); + } + + if ( currtok.Type == TokType::BraceCurly_Open ) + { + Token expr_tok = currtok; + + eat( TokType::BraceCurly_Open ); + + s32 level = 0; + while ( left && ( currtok.Type != TokType::BraceCurly_Close || level > 0 ) ) + { + if ( currtok.Type == TokType::BraceCurly_Open ) + level++; + + else if ( currtok.Type == TokType::BraceCurly_Close && level > 0 ) + level--; + + eat( currtok.Type ); + } + eat( TokType::BraceCurly_Close ); + + expr_tok.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)expr_tok.Text; + expr = untyped_str( expr_tok ); + } + + if ( currtok.Type == TokType::Assign_Classifer ) + { + eat( TokType::Assign_Classifer ); + + Token expr_tok = currtok; + + if ( currtok.Type == TokType::Statement_End ) + { + log_failure( "Expected expression after bitfield \n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -1480,7 +2085,7 @@ CodeVar parse_variable_after_name( } expr_tok.Length = ( (sptr)currtok.Text + currtok.Length ) - (sptr)expr_tok.Text; - expr = untyped_str( expr_tok ); + bitfield_expr = untyped_str( expr_tok ); } eat( TokType::Statement_End ); @@ -1498,6 +2103,9 @@ CodeVar parse_variable_after_name( if (array_expr ) type->ArrExpr = array_expr; + if ( bitfield_expr ) + result->BitfieldSize = bitfield_expr; + if ( attributes ) result->Attributes = attributes; @@ -1512,36 +2120,48 @@ CodeVar parse_variable_after_name( } internal inline -Code parse_variable_assignment() +Code parse_simple_preprocess( Parser::TokType which ) { using namespace Parser; push_scope(); - Code expr = Code::Invalid; + Token tok = currtok; + eat( which ); - if ( currtok.IsAssign ) + if ( currtok.Type == TokType::BraceCurly_Open ) { - eat( TokType::Operator ); + // Eat the block scope right after the macro. Were assuming the macro defines a function definition's signature + eat( TokType::BraceCurly_Open ); - Token expr_tok = currtok; - - if ( currtok.Type == TokType::Statement_End ) + s32 level = 0; + while ( left && ( currtok.Type != TokType::BraceCurly_Close || level > 0 ) ) { - log_failure( "Expected expression after assignment operator\n%s", Context.to_string() ); - return Code::Invalid; - } + if ( currtok.Type == TokType::BraceCurly_Open ) + level++; + + else if ( currtok.Type == TokType::BraceCurly_Close && level > 0 ) + level--; - while ( left && currtok.Type != TokType::Statement_End ) - { - expr_tok.Length = ( (sptr)currtok.Text + currtok.Length ) - (sptr)expr_tok.Text; eat( currtok.Type ); } + eat( TokType::BraceCurly_Close ); - expr = untyped_str( expr_tok ); + tok.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)tok.Text; + } + + Code result = untyped_str( tok ); + Context.Scope->Name = tok; + + if ( str_compare( Context.Scope->Prev->ProcName.Ptr, "parse_typedef", Context.Scope->Prev->ProcName.Len ) != 0 ) + { + if ( check( TokType::Statement_End )) + { + eat( TokType::Statement_End ); + } } Context.pop(); - return expr; + return result; } internal inline @@ -1550,22 +2170,56 @@ Code parse_operator_function_or_variable( bool expects_function, CodeAttributes using namespace Parser; push_scope(); - Code result = Code::Invalid; + Code result = CodeInvalid; + + if ( currtok.Type == TokType::Preprocess_Macro ) + { + // Were dealing with a macro after attributes/specifiers. + result = parse_simple_preprocess( TokType::Preprocess_Macro ); + Context.pop(); + return result; + } CodeType type = parse_type(); - if ( type == Code::Invalid ) + if ( type == CodeInvalid ) + { + Context.pop(); return CodeInvalid; + } - if ( check( TokType::Operator) ) + bool found_operator = false; + s32 idx = Context.Tokens.Idx; + + for ( ; idx < Context.Tokens.Arr.num(); idx++ ) + { + Token tok = Context.Tokens[ idx ]; + + if ( tok.Type == TokType::Identifier ) + { + idx++; + tok = Context.Tokens[ idx ]; + if ( tok.Type == TokType::Access_StaticSymbol ) + continue; + + break; + } + + if ( tok.Type == TokType::Decl_Operator ) + found_operator = true; + + break; + } + + if ( found_operator ) { // Dealing with an operator overload result = parse_operator_after_ret_type( ModuleFlag::None, attributes, specifiers, type ); } else { - StrC name = currtok; - eat( TokType::Identifier ); + Token name = parse_identifier(); + Context.Scope->Name = name; if ( check( TokType::Capture_Start) ) { @@ -1578,7 +2232,8 @@ Code parse_operator_function_or_variable( bool expects_function, CodeAttributes if ( expects_function ) { log_failure( "Expected function declaration (consteval was used)\n%s", Context.to_string() ); - return Code::Invalid; + Context.pop(); + return CodeInvalid; } // Dealing with a variable @@ -1590,6 +2245,136 @@ Code parse_operator_function_or_variable( bool expects_function, CodeAttributes return result; } +internal inline +Code parse_complicated_definition( Parser::TokType which ) +{ + using namespace Parser; + push_scope(); + + bool is_inplace = false; + + labeled_scope_start + PARSE_FORWARD_OR_DEFINITION: + Code result = CodeInvalid; + + // ; + switch ( which ) + { + case TokType::Decl_Class: + result = parse_class( is_inplace ); + Context.pop(); + return result; + + case TokType::Decl_Enum: + result = parse_enum( is_inplace ); + Context.pop(); + return result; + + case TokType::Decl_Struct: + result = parse_struct( is_inplace ); + Context.pop(); + return result; + + case TokType::Decl_Union: + result = parse_union( is_inplace ); + Context.pop(); + return result; + + default: + log_failure( "Error, wrong token type given to parse_complicated_definition " + "(only supports class, enum, struct, union) \n%s" + , Context.to_string() ); + + Context.pop(); + return CodeInvalid; + } + labeled_scope_end + + TokArray tokens = Context.Tokens; + + s32 idx = tokens.Idx; + s32 level = 0; + for ( ; idx < tokens.Arr.num(); idx ++ ) + { + if ( tokens[idx].Type == TokType::BraceCurly_Open ) + level++; + + if ( tokens[idx].Type == TokType::BraceCurly_Close ) + level--; + + if ( level == 0 && tokens[idx].Type == TokType::Statement_End ) + break; + } + + if ( (idx - 2 ) == tokens.Idx ) + { + // Its a forward declaration only + goto PARSE_FORWARD_OR_DEFINITION; + } + + Token tok = tokens[ idx - 1 ]; + if ( tok.Type == TokType::Identifier ) + { + tok = tokens[ idx - 2 ]; + + bool is_indirection = tok.Type == TokType::Ampersand + || tok.Type == TokType::Star; + + bool ok_to_parse = false; + + if ( tok.Type == TokType::BraceCurly_Close ) + { + // Its an inplace definition + // { ... } ; + ok_to_parse = true; + is_inplace = true; + } + else if ( tok.Type == TokType::Identifier && tokens[ idx - 3 ].Type == TokType::Decl_Struct ) + { + // Its a variable with type ID using struct namespace. + // ; + ok_to_parse = true; + } + else if ( is_indirection ) + { + // Its a indirection type with type ID using struct namespace. + // ; + ok_to_parse = true; + } + + if ( ! ok_to_parse ) + { + log_failure( "Unsupported or bad member definition after struct declaration\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + + Code result = parse_operator_function_or_variable( false, { nullptr }, { nullptr } ); + Context.pop(); + return result; + } + else if ( tok.Type == TokType::BraceCurly_Close ) + { + // Its a definition + // { ... }; + goto PARSE_FORWARD_OR_DEFINITION; + } + else if ( tok.Type == TokType::BraceSquare_Close) + { + // Its an array definition + // [ ... ]; + Code result = parse_operator_function_or_variable( false, { nullptr }, { nullptr } ); + Context.pop(); + return result; + } + else + { + log_failure( "Unsupported or bad member definition after struct declaration\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } +} + internal CodeBody parse_class_struct_body( Parser::TokType which ) { @@ -1642,11 +2427,11 @@ CodeBody parse_class_struct_body( Parser::TokType which ) break; case TokType::Decl_Class: - member = parse_class(); + member = parse_complicated_definition( TokType::Decl_Class ); break; case TokType::Decl_Enum: - member = parse_enum(); + member = parse_complicated_definition( TokType::Decl_Enum ); break; case TokType::Decl_Friend: @@ -1658,7 +2443,7 @@ CodeBody parse_class_struct_body( Parser::TokType which ) break; case TokType::Decl_Struct: - member = parse_struct(); + member = parse_complicated_definition( TokType::Decl_Struct ); break; case TokType::Decl_Template: @@ -1670,13 +2455,54 @@ CodeBody parse_class_struct_body( Parser::TokType which ) break; case TokType::Decl_Union: - member = parse_variable(); + member = parse_complicated_definition( TokType::Decl_Union ); break; case TokType::Decl_Using: member = parse_using(); break; + case TokType::Preprocess_Define: + member = parse_define(); + break; + + case TokType::Preprocess_Include: + member = parse_include(); + break; + + case TokType::Preprocess_If: + case TokType::Preprocess_IfDef: + case TokType::Preprocess_IfNotDef: + case TokType::Preprocess_ElIf: + member = parse_preprocess_cond(); + break; + + case TokType::Preprocess_Macro: + member = parse_simple_preprocess( TokType::Preprocess_Macro ); + break; + + case TokType::Preprocess_Pragma: + member = parse_pragma(); + break; + + case TokType::Preprocess_Else: + member = preprocess_else; + eat( TokType::Preprocess_Else ); + break; + + case TokType::Preprocess_EndIf: + member = preprocess_endif; + eat( TokType::Preprocess_EndIf ); + break; + + case TokType::Preprocess_Unsupported: + member = parse_simple_preprocess( TokType::Preprocess_Unsupported ); + break; + + case TokType::StaticAssert: + member = parse_static_assert(); + break; + case TokType::Attribute_Open: case TokType::Decl_GNU_Attribute: case TokType::Decl_MSVC_Attribute: @@ -1718,6 +2544,7 @@ CodeBody parse_class_struct_body( Parser::TokType which ) default: log_failure( "Invalid specifier %s for variable\n%s", ESpecifier::to_str(spec), Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -1762,6 +2589,7 @@ CodeBody parse_class_struct_body( Parser::TokType which ) if ( member == Code::Invalid ) { log_failure( "Failed to parse member\n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -1774,7 +2602,7 @@ CodeBody parse_class_struct_body( Parser::TokType which ) } internal -Code parse_class_struct( Parser::TokType which ) +Code parse_class_struct( Parser::TokType which, bool inplace_def = false ) { using namespace Parser; @@ -1804,7 +2632,11 @@ Code parse_class_struct( Parser::TokType which ) attributes = parse_attributes(); - name = parse_identifier(); + if ( check( TokType::Identifier ) ) + { + name = parse_identifier(); + Context.Scope->Name = name; + } local_persist char interface_arr_mem[ kilobytes(4) ] {0}; @@ -1842,7 +2674,8 @@ Code parse_class_struct( Parser::TokType which ) body = parse_class_struct_body( which ); } - eat( TokType::Statement_End ); + if ( ! inplace_def ) + eat( TokType::Statement_End ); if ( which == TokType::Decl_Class ) result = def_class( name, body, parent, access, attributes, mflags ); @@ -1920,6 +2753,8 @@ CodeBody parse_global_nspace( CodeT which ) bool expects_function = false; + Context.Scope->Start = currtok; + switch ( currtok.Type ) { case TokType::Comment: @@ -1927,12 +2762,12 @@ CodeBody parse_global_nspace( CodeT which ) eat( TokType::Comment ); break; - case TokType::Decl_Enum: - member = parse_enum(); + case TokType::Decl_Class: + member = parse_complicated_definition( TokType::Decl_Class ); break; - case TokType::Decl_Class: - member = parse_class(); + case TokType::Decl_Enum: + member = parse_complicated_definition( TokType::Decl_Enum ); break; case TokType::Decl_Extern_Linkage: @@ -1947,7 +2782,7 @@ CodeBody parse_global_nspace( CodeT which ) break; case TokType::Decl_Struct: - member = parse_struct(); + member = parse_complicated_definition( TokType::Decl_Struct ); break; case TokType::Decl_Template: @@ -1959,13 +2794,54 @@ CodeBody parse_global_nspace( CodeT which ) break; case TokType::Decl_Union: - member = parse_union(); + member = parse_complicated_definition( TokType::Decl_Union ); break; case TokType::Decl_Using: member = parse_using(); break; + case TokType::Preprocess_Define: + member = parse_define(); + break; + + case TokType::Preprocess_Include: + member = parse_include(); + break; + + case TokType::Preprocess_If: + case TokType::Preprocess_IfDef: + case TokType::Preprocess_IfNotDef: + case TokType::Preprocess_ElIf: + member = parse_preprocess_cond(); + break; + + case TokType::Preprocess_Macro: + member = parse_simple_preprocess( TokType::Preprocess_Macro ); + break; + + case TokType::Preprocess_Pragma: + member = parse_pragma(); + break; + + case TokType::Preprocess_Else: + member = preprocess_else; + eat( TokType::Preprocess_Else ); + break; + + case TokType::Preprocess_EndIf: + member = preprocess_endif; + eat( TokType::Preprocess_EndIf ); + break; + + case TokType::Preprocess_Unsupported: + member = parse_simple_preprocess( TokType::Preprocess_Unsupported ); + break; + + case TokType::StaticAssert: + member = parse_static_assert(); + break; + case TokType::Module_Export: if ( which == Export_Body ) log_failure( "Nested export declaration\n%s", Context.to_string() ); @@ -1994,6 +2870,7 @@ CodeBody parse_global_nspace( CodeT which ) case TokType::Spec_Global: case TokType::Spec_Inline: case TokType::Spec_Internal_Linkage: + case TokType::Spec_NeverInline: case TokType::Spec_Static: { SpecifierT specs_found[16] { ESpecifier::NumSpecifiers }; @@ -2003,12 +2880,18 @@ CodeBody parse_global_nspace( CodeT which ) { SpecifierT spec = ESpecifier::to_type( currtok ); + bool ignore_spec = false; + switch ( spec ) { case ESpecifier::Constexpr: case ESpecifier::Constinit: + case ESpecifier::Global: + case ESpecifier::External_Linkage: + case ESpecifier::Internal_Linkage: case ESpecifier::Inline: case ESpecifier::Mutable: + case ESpecifier::NeverInline: case ESpecifier::Static: case ESpecifier::Volatile: break; @@ -2017,11 +2900,20 @@ CodeBody parse_global_nspace( CodeT which ) expects_function = true; break; + case ESpecifier::Const: + ignore_spec = true; + break; + default: - log_failure( "Invalid specifier %s for variable\n%s", ESpecifier::to_str(spec), Context.to_string() ); + StrC spec_str = ESpecifier::to_str(spec); + + log_failure( "Invalid specifier %.*s for variable\n%s", spec_str.Len, spec_str, Context.to_string() ); return CodeInvalid; } + if (ignore_spec) + break; + specs_found[NumSpecifiers] = spec; NumSpecifiers++; eat( currtok.Type ); @@ -2043,6 +2935,32 @@ CodeBody parse_global_nspace( CodeT which ) case TokType::Type_double: case TokType::Type_int: { + bool found_operator_cast = false; + s32 idx = Context.Tokens.Idx; + + for ( ; idx < Context.Tokens.Arr.num(); idx++ ) + { + Token tok = Context.Tokens[ idx ]; + + if ( tok.Type == TokType::Identifier ) + { + idx++; + tok = Context.Tokens[ idx ]; + if ( tok.Type == TokType::Access_StaticSymbol ) + continue; + + break; + } + + if ( tok.Type == TokType::Decl_Operator ) + found_operator_cast = true; + + break; + } + + if ( found_operator_cast ) + member = parse_operator_cast(); + member = parse_operator_function_or_variable( expects_function, attributes, specifiers ); } } @@ -2053,6 +2971,7 @@ CodeBody parse_global_nspace( CodeT which ) return CodeInvalid; } + // log_fmt("Global Body Member: %s", member->debug_str()); result.append( member ); } @@ -2063,11 +2982,11 @@ CodeBody parse_global_nspace( CodeT which ) } internal -CodeClass parse_class() +CodeClass parse_class( bool inplace_def ) { using namespace Parser; push_scope(); - CodeClass result = (CodeClass) parse_class_struct( Parser::TokType::Decl_Class ); + CodeClass result = (CodeClass) parse_class_struct( Parser::TokType::Decl_Class, inplace_def ); Context.pop(); return result; } @@ -2089,7 +3008,7 @@ CodeClass parse_class( StrC def ) } internal -CodeEnum parse_enum() +CodeEnum parse_enum( bool inplace_def ) { using namespace Parser; using namespace ECode; @@ -2098,10 +3017,11 @@ CodeEnum parse_enum() SpecifierT specs_found[16] { ESpecifier::NumSpecifiers }; s32 NumSpecifiers = 0; + CodeAttributes attributes = { nullptr }; + Token name = { nullptr, 0, TokType::Invalid }; Code array_expr = { nullptr }; CodeType type = { nullptr }; - Token body = { nullptr, 0, TokType::Invalid }; char entries_code[ kilobytes(128) ] { 0 }; s32 entries_length = 0; @@ -2116,72 +3036,132 @@ CodeEnum parse_enum() is_enum_class = true; } - // TODO : Parse attributes + attributes = parse_attributes(); - if ( currtok.Type != TokType::Identifier ) + if ( check( TokType::Identifier ) ) { - log_failure( "Expected identifier for enum name\n%s", Context.to_string() ); - return CodeInvalid; + name = currtok; + Context.Scope->Name = currtok; + eat( TokType::Identifier ); } - name = currtok; - eat( TokType::Identifier ); - if ( currtok.Type == TokType::Assign_Classifer ) { eat( TokType::Assign_Classifer ); type = parse_type(); if ( type == Code::Invalid ) + { + log_failure( "Failed to parse enum classifier\n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; + } } + CodeBody body = { nullptr }; + if ( currtok.Type == TokType::BraceCurly_Open ) { + body = (CodeBody) make_code(); + body->Type = ECode::Enum_Body; + eat( TokType::BraceCurly_Open ); - body = currtok; + Code member = CodeInvalid; while ( currtok.Type != TokType::BraceCurly_Close ) { - eat( TokType::Identifier); - - if ( currtok.Type == TokType::Operator && currtok.Text[0] == '=' ) + switch ( currtok.Type ) { - eat( TokType::Operator ); + case TokType::Comment: + member = def_comment( currtok ); + eat( TokType::Comment ); + break; - while ( currtok.Type != TokType::Comma && currtok.Type != TokType::BraceCurly_Close ) - { - eat( currtok.Type ); - } + case TokType::Preprocess_Define: + member = parse_define(); + break; + + case TokType::Preprocess_If: + case TokType::Preprocess_IfDef: + case TokType::Preprocess_IfNotDef: + case TokType::Preprocess_ElIf: + member = parse_preprocess_cond(); + break; + + case TokType::Preprocess_Else: + member = preprocess_else; + eat( TokType::Preprocess_Else ); + break; + + case TokType::Preprocess_EndIf: + member = preprocess_endif; + eat( TokType::Preprocess_EndIf ); + break; + + case TokType::Preprocess_Macro: + member = parse_simple_preprocess( TokType::Preprocess_Macro ); + break; + + case TokType::Preprocess_Pragma: + member = parse_pragma(); + break; + + case TokType::Preprocess_Unsupported: + member = parse_simple_preprocess( TokType::Preprocess_Unsupported ); + break; + + default: + Token entry = currtok; + + eat( TokType::Identifier); + + if ( currtok.Type == TokType::Operator && currtok.Text[0] == '=' ) + { + eat( TokType::Operator ); + + while ( currtok.Type != TokType::Comma && currtok.Type != TokType::BraceCurly_Close ) + { + eat( currtok.Type ); + } + } + + if ( currtok.Type == TokType::Comma ) + { + eat( TokType::Comma ); + } + + entry.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)entry.Text; + + member = untyped_str( entry ); + break; } - if ( currtok.Type == TokType::Comma ) + if ( member == Code::Invalid ) { - eat( TokType::Comma ); + log_failure( "Failed to parse member\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; } + + body.append( member ); } - body.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)body.Text; - eat( TokType::BraceCurly_Close ); } - eat( TokType::Statement_End ); + if ( ! inplace_def ) + eat( TokType::Statement_End ); using namespace ECode; CodeEnum result = (CodeEnum) make_code(); - if ( body.Length ) + if ( body.ast ) { - // mem_copy( entries_code, body.Text, body.Length ); - - Code untyped_body = untyped_str( body ); - result->Type = is_enum_class ? Enum_Class : Enum; - result->Body = untyped_body; + result->Body = body; } else { @@ -2190,6 +3170,9 @@ CodeEnum parse_enum() result->Name = get_cached_string( name ); + if ( attributes ) + result->Attributes = attributes; + if ( type ) result->UnderlyingType = type; @@ -2204,7 +3187,10 @@ CodeEnum parse_enum( StrC def ) TokArray toks = lex( def ); if ( toks.Arr == nullptr ) + { + Context.pop(); return CodeInvalid; + } Context.Tokens = toks; return parse_enum(); @@ -2266,6 +3252,7 @@ CodeExtern parse_extern_link() if ( entry == Code::Invalid ) { log_failure( "Failed to parse body\n%s", Context.to_string() ); + Context.pop(); return result; } @@ -2302,13 +3289,17 @@ CodeFriend parse_friend() // Type declaration or return type CodeType type = parse_type(); if ( type == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } // Funciton declaration if ( currtok.Type == TokType::Identifier ) { // Name Token name = parse_identifier(); + Context.Scope->Name = name; // Parameter list CodeParam params = parse_params(); @@ -2388,6 +3379,7 @@ CodeFn parse_functon() default: log_failure( "Invalid specifier %s for functon\n%s", ESpecifier::to_str(spec), Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -2406,11 +3398,18 @@ CodeFn parse_functon() CodeType ret_type = parse_type(); if ( ret_type == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } Token name = parse_identifier(); + Context.Scope->Name = name; if ( ! name ) + { + Context.pop(); return CodeInvalid; + } CodeFn result = parse_function_after_name( mflags, attributes, specifiers, ret_type, name ); @@ -2456,10 +3455,14 @@ CodeNamespace parse_namespace() eat( TokType::Decl_Namespace ); Token name = parse_identifier(); + Context.Scope->Name = name; CodeBody body = parse_global_nspace( ECode::Namespace_Body ); if ( body == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } CodeNamespace result = (CodeNamespace) make_code(); @@ -2520,6 +3523,7 @@ CodeOperator parse_operator() default: log_failure( "Invalid specifier " "%s" " for operator\n%s", ESpecifier::to_str(spec), Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -2563,17 +3567,37 @@ CodeOpCast parse_operator_cast() using namespace Parser; push_scope(); + Token name = NullToken; + if ( check( TokType::Identifier ) ) + { + name = currtok; + while ( left && currtok.Type == TokType::Identifier ) + { + eat( TokType::Identifier ); + + if ( currtok.Type == TokType::Access_StaticSymbol ) + eat( TokType::Access_StaticSymbol ); + } + + name.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)name.Text; + } + eat( TokType::Decl_Operator ); Code type = parse_type(); + Context.Scope->Name = { type->Name.Data, type->Name.length() }; + eat( TokType::Capture_Start ); eat( TokType::Capture_End ); CodeSpecifiers specifiers = { nullptr }; if ( check(TokType::Spec_Const)) + { specifiers = spec_const; + eat( TokType::Spec_Const ); + } Code body = { nullptr }; @@ -2594,16 +3618,22 @@ CodeOpCast parse_operator_cast() eat( currtok.Type ); } + eat( TokType::BraceCurly_Close ); body_str.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)body_str.Text; body = untyped_str( body_str ); - - eat( TokType::BraceCurly_Close ); + } + else + { + eat( TokType::Statement_End ); } CodeOpCast result = (CodeOpCast) make_code(); + if ( name ) + result->Name = get_cached_string( name ); + if (body) { result->Type = ECode::Operator_Cast; @@ -2637,11 +3667,11 @@ CodeOpCast parse_operator_cast( StrC def ) } internal inline -CodeStruct parse_struct() +CodeStruct parse_struct( bool inplace_def ) { using namespace Parser; push_scope(); - CodeStruct result = (CodeStruct) parse_class_struct( TokType::Decl_Struct ); + CodeStruct result = (CodeStruct) parse_class_struct( TokType::Decl_Struct, inplace_def ); Context.pop(); return result; } @@ -2682,7 +3712,10 @@ CodeTemplate parse_template() Code params = parse_params( UseTemplateCapture ); if ( params == Code::Invalid ) + { + Context.pop(); return CodeInvalid; + } Code definition = { nullptr }; @@ -2696,7 +3729,7 @@ CodeTemplate parse_template() if ( check( TokType::Decl_Struct ) ) { - definition = parse_enum(); + definition = parse_struct(); break; } @@ -2744,6 +3777,7 @@ CodeTemplate parse_template() default: log_failure( "Invalid specifier %s for variable or function\n%s", ESpecifier::to_str( spec ), Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -2813,6 +3847,7 @@ CodeType parse_type() if ( spec != ESpecifier::Const ) { log_failure( "Error, invalid specifier used in type definition: %s\n%s", currtok.Text, Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -2824,6 +3859,7 @@ CodeType parse_type() if ( left == 0 ) { log_failure( "Error, unexpected end of type definition\n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -2836,24 +3872,31 @@ CodeType parse_type() name.Length = ( (sptr)currtok.Text + currtok.Length ) - (sptr)name.Text; eat( TokType::Identifier ); + Context.Scope->Name = name; } - else if ( currtok.Type >= TokType::Type_Unsigned ) + else if ( currtok.Type >= TokType::Type_Unsigned && currtok.Type <= TokType::Type_MS_W64 ) { name = currtok; eat( currtok.Type ); - while (currtok.Type >= TokType::Type_Unsigned) + while (currtok.Type >= TokType::Type_Unsigned && currtok.Type <= TokType::Type_MS_W64 ) { eat( currtok.Type ); } name.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)name.Text; + Context.Scope->Name = name; } else { name = parse_identifier(); + Context.Scope->Name = name; if ( ! name ) + { + log_failure( "Error, failed to type signature\n%s", Context.to_string() ); + Context.pop(); return CodeInvalid; + } // Problably dealing with a templated symbol if ( currtok.Type == TokType::Operator && currtok.Text[0] == '<' && currtok.Length == 1 ) @@ -2889,6 +3932,7 @@ CodeType parse_type() && spec != ESpecifier::RValue ) { log_failure( "Error, invalid specifier used in type definition: %s\n%s", currtok.Text, Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -2897,43 +3941,27 @@ CodeType parse_type() eat( currtok.Type ); } - // Not sure if its technically possible to cast ot a function pointer user defined operator cast... - // Supporting it is not worth the effort. +BruteforceCaptureAgain: if ( check( TokType::Capture_Start ) && context_tok.Type != TokType::Decl_Operator ) { - // Its a function type + // Brute force capture the entire thing. + // Function typedefs are complicated and there are not worth dealing with for validation at this point... eat( TokType::Capture_Start ); - while ( check( TokType::Star ) || currtok.Type == TokType::Spec_Const ) - { - eat( currtok.Type ); - } - - // if its a using statement there will not be an ID. - if ( check( TokType::Identifier ) ) - eat(TokType::Identifier); - - eat( TokType::Capture_End ); - - // Parameters - - eat( TokType::Capture_Start ); - - // TODO : Change this to validate the parameters... - // Bruteforce lex the parameters, no validation. s32 level = 0; - while ( ! check( TokType::Capture_End ) || level > 0 ) + while ( left && ( currtok.Type != TokType::Capture_End || level > 0 )) { - if ( check( TokType::Capture_Start ) ) + if ( currtok.Type == TokType::Capture_Start ) level++; - if ( check( TokType::Capture_End ) ) + if ( currtok.Type == TokType::Capture_End ) level--; eat( currtok.Type ); } + eat( TokType::Capture_End ); - eat(TokType::Capture_End); + goto BruteforceCaptureAgain; brute_sig.Length = ( (sptr)prevtok.Text + prevtok.Length ) - (sptr)brute_sig.Text; } @@ -3000,29 +4028,49 @@ CodeTypedef parse_typedef() eat( TokType::Decl_Typedef ); - if ( check( TokType::Decl_Enum ) ) - type = parse_enum(); - - else if ( check(TokType::Decl_Class ) ) - type = parse_class(); - - else if ( check(TokType::Decl_Struct ) ) - type = parse_struct(); - - else if ( check(TokType::Decl_Union) ) - type = parse_union(); - - else - type = parse_type(); - - if ( ! check( TokType::Identifier ) ) + if ( currtok.Line == 2196 ) { - log_failure( "Error, expected identifier for typedef\n%s", Context.to_string() ); - return CodeInvalid; + log_fmt("here"); } - name = currtok; - eat( TokType::Identifier ); + constexpr bool from_typedef = true; + + if ( check( TokType::Preprocess_Macro )) + { + type = t_empty; + name = currtok; + Context.Scope->Name = name; + eat( TokType::Preprocess_Macro ); + } + else + { + if ( check( TokType::Decl_Enum ) ) + type = parse_enum( from_typedef ); + + else if ( check(TokType::Decl_Class ) ) + type = parse_class( from_typedef ); + + else if ( check(TokType::Decl_Struct ) ) + type = parse_struct( from_typedef ); + + else if ( check(TokType::Decl_Union) ) + type = parse_union( from_typedef ); + + else + type = parse_type(); + + if ( check( TokType::Identifier ) ) + { + name = currtok; + eat( TokType::Identifier ); + } + else + { + log_failure( "Error, expected identifier for typedef\n%s", Context.to_string() ); + Context.pop(); + return CodeInvalid; + } + } array_expr = parse_array_decl(); @@ -3059,7 +4107,7 @@ CodeTypedef parse_typedef( StrC def ) } internal -CodeUnion parse_union() +CodeUnion parse_union( bool inplace_def ) { using namespace Parser; push_scope(); @@ -3081,6 +4129,7 @@ CodeUnion parse_union() if ( check( TokType::Identifier ) ) { name = currtok; + Context.Scope->Name = currtok; eat( TokType::Identifier ); } @@ -3093,14 +4142,76 @@ CodeUnion parse_union() while ( ! check( TokType::BraceCurly_Close ) ) { - Code entry = parse_variable(); + Code member = { nullptr }; + switch ( currtok.Type ) + { + case TokType::Comment: + member = def_comment( currtok ); + eat( TokType::Comment ); + break; - if ( entry ) - body.append( entry ); + case TokType::Decl_Class: + member = parse_complicated_definition( TokType::Decl_Class ); + break; + + case TokType::Decl_Enum: + member = parse_complicated_definition( TokType::Decl_Enum ); + break; + + case TokType::Decl_Struct: + member = parse_complicated_definition( TokType::Decl_Struct ); + break; + + case TokType::Decl_Union: + member = parse_complicated_definition( TokType::Decl_Union ); + break; + + case TokType::Preprocess_Define: + member = parse_define(); + break; + + case TokType::Preprocess_If: + case TokType::Preprocess_IfDef: + case TokType::Preprocess_IfNotDef: + case TokType::Preprocess_ElIf: + member = parse_preprocess_cond(); + break; + + case TokType::Preprocess_Else: + member = preprocess_else; + eat( TokType::Preprocess_Else ); + break; + + case TokType::Preprocess_EndIf: + member = preprocess_endif; + eat( TokType::Preprocess_EndIf ); + break; + + case TokType::Preprocess_Macro: + member = parse_simple_preprocess( TokType::Preprocess_Macro ); + break; + + case TokType::Preprocess_Pragma: + member = parse_pragma(); + break; + + case TokType::Preprocess_Unsupported: + member = parse_simple_preprocess( TokType::Preprocess_Unsupported ); + break; + + default: + member = parse_variable(); + break; + } + + if ( member ) + body.append( member ); } eat( TokType::BraceCurly_Close ); - eat( TokType::Statement_End ); + + if ( ! inplace_def ) + eat( TokType::Statement_End ); CodeUnion result = (CodeUnion) make_code(); @@ -3166,6 +4277,7 @@ CodeUsing parse_using() } name = currtok; + Context.Scope->Name = name; eat( TokType::Identifier ); if ( currtok.IsAssign ) @@ -3265,6 +4377,7 @@ CodeVar parse_variable() default: log_failure( "Invalid specifier %s for variable\n%s", ESpecifier::to_str( spec ), Context.to_string() ); + Context.pop(); return CodeInvalid; } @@ -3287,8 +4400,7 @@ CodeVar parse_variable() if ( type == Code::Invalid ) return CodeInvalid; - Context.Scope->Name = currtok; - eat( TokType::Identifier ); + Context.Scope->Name = parse_identifier(); CodeVar result = parse_variable_after_name( mflags, attributes, specifiers, type, Context.Scope->Name ); diff --git a/project/components/interface.upfront.bodies.cpp b/project/components/interface.upfront.bodies.cpp new file mode 100644 index 0000000..e69de29 diff --git a/project/components/interface.upfront.cpp b/project/components/interface.upfront.cpp index 8245157..35c9f92 100644 --- a/project/components/interface.upfront.cpp +++ b/project/components/interface.upfront.cpp @@ -489,6 +489,26 @@ CodeClass def_class( StrC name return result; } +CodeDefine def_define( StrC name, StrC content ) +{ + using namespace ECode; + + name_check( def_define, name ); + + if ( content.Len <= 0 || content.Ptr == nullptr ) + { + log_failure( "gen::def_define: Invalid value provided" ); + return CodeInvalid; + } + + CodeDefine + result = (CodeDefine) make_code(); + result->Name = get_cached_string( name ); + result->Content = get_cached_string( content ); + + return result; +} + CodeEnum def_enum( StrC name , Code body, CodeType type , EnumT specifier, CodeAttributes attributes @@ -719,7 +739,7 @@ CodeInclude def_include ( StrC path ) Code result = make_code(); - result->Type = ECode::Preprocessor_Include; + result->Type = ECode::Preprocess_Include; result->Name = get_cached_string( path ); result->Content = result->Name; @@ -763,7 +783,7 @@ CodeNamespace def_namespace( StrC name, Code body, ModuleFlag mflags ) return result; } -CodeOperator def_operator( OperatorT op +CodeOperator def_operator( OperatorT op, StrC nspace , CodeParam params_code, CodeType ret_type, Code body , CodeSpecifiers specifiers, CodeAttributes attributes , ModuleFlag mflags ) @@ -789,7 +809,7 @@ CodeOperator def_operator( OperatorT op return CodeInvalid; } - char const* name = str_fmt_buf( "operator %s", to_str(op) ); + char const* name = str_fmt_buf( "%.*soperator %s", nspace.Len, nspace.Ptr, to_str(op) ); CodeOperator result = (CodeOperator) make_code(); @@ -910,6 +930,53 @@ CodeParam def_param( CodeType type, StrC name, Code value ) return result; } +CodePragma def_pragma( StrC directive ) +{ + using namespace ECode; + + if ( directive.Len <= 0 || directive.Ptr == nullptr ) + { + log_failure( "gen::def_comment: Invalid comment provided:" ); + return CodeInvalid; + } + + CodePragma + result = (CodePragma) make_code(); + result->Type = Preprocess_Pragma; + result->Content = get_cached_string( directive ); + + return result; +} + +CodePreprocessCond def_preprocess_cond( EPreprocessCond type, StrC expr ) +{ + using namespace ECode; + + if ( expr.Len <= 0 || expr.Ptr == nullptr ) + { + log_failure( "gen::def_comment: Invalid comment provided:" ); + return CodeInvalid; + } + + CodePreprocessCond + result = (CodePreprocessCond) make_code(); + result->Content = get_cached_string( expr ); + + switch (type) + { + case EPreprocessCond::If: + result->Type = ECode::Preprocess_If; + case EPreprocessCond::IfDef: + result->Type = Preprocess_IfDef; + case EPreprocessCond::IfNotDef: + result->Type = Preprocess_IfNotDef; + case EPreprocessCond::ElIf: + result->Type = Preprocess_ElIf; + } + + return result; +} + CodeSpecifiers def_specifier( SpecifierT spec ) { CodeSpecifiers diff --git a/project/components/static_data.cpp b/project/components/static_data.cpp index 99cbdcd..f914d94 100644 --- a/project/components/static_data.cpp +++ b/project/components/static_data.cpp @@ -22,6 +22,45 @@ global AllocatorInfo Allocator_TypeTable = heap(); #pragma region Constants +global Code access_public; +global Code access_protected; +global Code access_private; + +global CodeAttributes attrib_api_export; +global CodeAttributes attrib_api_import; + +global Code module_global_fragment; +global Code module_private_fragment; + +global CodeParam param_varadic; + +global CodePragma pragma_once; + +global CodePreprocessCond preprocess_else; +global CodePreprocessCond preprocess_endif; + +global CodeSpecifiers spec_const; +global CodeSpecifiers spec_consteval; +global CodeSpecifiers spec_constexpr; +global CodeSpecifiers spec_constinit; +global CodeSpecifiers spec_extern_linkage; +global CodeSpecifiers spec_final; +global CodeSpecifiers spec_global; +global CodeSpecifiers spec_inline; +global CodeSpecifiers spec_internal_linkage; +global CodeSpecifiers spec_local_persist; +global CodeSpecifiers spec_mutable; +global CodeSpecifiers spec_neverinline; +global CodeSpecifiers spec_override; +global CodeSpecifiers spec_ptr; +global CodeSpecifiers spec_ref; +global CodeSpecifiers spec_register; +global CodeSpecifiers spec_rvalue; +global CodeSpecifiers spec_static_member; +global CodeSpecifiers spec_thread_local; +global CodeSpecifiers spec_virtual; +global CodeSpecifiers spec_volatile; + global CodeType t_empty; global CodeType t_auto; global CodeType t_void; @@ -52,39 +91,4 @@ global CodeType t_f32; global CodeType t_f64; #endif -global CodeParam param_varadic; - -global CodeAttributes attrib_api_export; -global CodeAttributes attrib_api_import; - -global Code access_public; -global Code access_protected; -global Code access_private; - -global Code module_global_fragment; -global Code module_private_fragment; - -global Code pragma_once; - -global CodeSpecifiers spec_const; -global CodeSpecifiers spec_consteval; -global CodeSpecifiers spec_constexpr; -global CodeSpecifiers spec_constinit; -global CodeSpecifiers spec_extern_linkage; -global CodeSpecifiers spec_final; -global CodeSpecifiers spec_global; -global CodeSpecifiers spec_inline; -global CodeSpecifiers spec_internal_linkage; -global CodeSpecifiers spec_local_persist; -global CodeSpecifiers spec_mutable; -global CodeSpecifiers spec_override; -global CodeSpecifiers spec_ptr; -global CodeSpecifiers spec_ref; -global CodeSpecifiers spec_register; -global CodeSpecifiers spec_rvalue; -global CodeSpecifiers spec_static_member; -global CodeSpecifiers spec_thread_local; -global CodeSpecifiers spec_virtual; -global CodeSpecifiers spec_volatile; - #pragma endregion Constants diff --git a/project/components/types.hpp b/project/components/types.hpp index 0e9d6a3..99c4865 100644 --- a/project/components/types.hpp +++ b/project/components/types.hpp @@ -8,16 +8,6 @@ using LogFailType = sw(*)(char const*, ...); constexpr LogFailType log_failure = fatal; #endif -// Used to indicate if enum definitoin is an enum class or regular enum. -enum class EnumT : u8 -{ - Regular, - Class -}; - -constexpr EnumT EnumClass = EnumT::Class; -constexpr EnumT EnumRegular = EnumT::Regular; - enum class AccessSpec : u32 { Default, @@ -46,6 +36,17 @@ char const* to_str( AccessSpec type ) return lookup[ (u32)type ]; } +// Used to indicate if enum definitoin is an enum class or regular enum. +enum class EnumT : u8 +{ + Regular, + Class +}; + +constexpr EnumT EnumClass = EnumT::Class; +constexpr EnumT EnumRegular = EnumT::Regular; + + enum class ModuleFlag : u32 { None = 0, @@ -62,6 +63,19 @@ ModuleFlag operator|( ModuleFlag A, ModuleFlag B) return (ModuleFlag)( (u32)A | (u32)B ); } +enum class EPreprocessCond : u32 +{ + If, + IfDef, + IfNotDef, + ElIf +}; + +constexpr EPreprocessCond PreprocessCond_If = EPreprocessCond::If; +constexpr EPreprocessCond PreprocessCond_IfDef = EPreprocessCond::IfDef; +constexpr EPreprocessCond PreprocessCond_IfNotDef = EPreprocessCond::IfNotDef; +constexpr EPreprocessCond PreprocessCond_ElIf = EPreprocessCond::ElIf; + /* Predefined attributes Used for the parser constructors to identify non-standard attributes diff --git a/project/components/untyped.cpp b/project/components/untyped.cpp index 12f4971..46c6e14 100644 --- a/project/components/untyped.cpp +++ b/project/components/untyped.cpp @@ -99,17 +99,35 @@ sw token_fmt_va( char* buf, uw buf_size, s32 num_tokens, va_list va ) Code untyped_str( StrC content ) { + if ( content.Len == 0 ) + { + log_failure( "untyped_str: empty string" ); + return CodeInvalid; + } + Code result = make_code(); result->Name = get_cached_string( content ); result->Type = ECode::Untyped; result->Content = result->Name; + if ( result->Name == nullptr ) + { + log_failure( "untyped_str: could not cache string" ); + return CodeInvalid; + } + return result; } Code untyped_fmt( char const* fmt, ...) { + if ( fmt == nullptr ) + { + log_failure( "untyped_fmt: null format string" ); + return CodeInvalid; + } + local_persist thread_local char buf[GEN_PRINTF_MAXLEN] = { 0 }; @@ -124,11 +142,23 @@ Code untyped_fmt( char const* fmt, ...) result->Type = ECode::Untyped; result->Content = get_cached_string( { length, buf } ); + if ( result->Name == nullptr ) + { + log_failure( "untyped_fmt: could not cache string" ); + return CodeInvalid; + } + return result; } Code untyped_token_fmt( s32 num_tokens, ... ) { + if ( num_tokens == 0 ) + { + log_failure( "untyped_token_fmt: zero tokens" ); + return CodeInvalid; + } + local_persist thread_local char buf[GEN_PRINTF_MAXLEN] = { 0 }; @@ -143,5 +173,11 @@ Code untyped_token_fmt( s32 num_tokens, ... ) result->Type = ECode::Untyped; result->Content = result->Name; + if ( result->Name == nullptr ) + { + log_failure( "untyped_fmt: could not cache string" ); + return CodeInvalid; + } + return result; } diff --git a/project/dependencies/file_handling.cpp b/project/dependencies/file_handling.cpp index 56d25b8..3c9a931 100644 --- a/project/dependencies/file_handling.cpp +++ b/project/dependencies/file_handling.cpp @@ -224,7 +224,7 @@ internal GEN_FILE_CLOSE_PROC( _posix_file_close ) FileOperations const default_file_operations = { _posix_file_read, _posix_file_write, _posix_file_seek, _posix_file_close }; -GEN_NEVER_INLINE GEN_FILE_OPEN_PROC( _posix_file_open ) +neverinline GEN_FILE_OPEN_PROC( _posix_file_open ) { s32 os_mode; switch ( mode & GEN_FILE_MODES ) diff --git a/project/dependencies/macros.hpp b/project/dependencies/macros.hpp index 2e3125e..752dc3c 100644 --- a/project/dependencies/macros.hpp +++ b/project/dependencies/macros.hpp @@ -86,6 +86,9 @@ } \ while(0); +#define labeled_scope_start if ( false ) { +#define labeled_scope_end } + #define clamp( x, lower, upper ) min( max( ( x ), ( lower ) ), ( upper ) ) #define count_of( x ) ( ( size_of( x ) / size_of( 0 [ x ] ) ) / ( ( sw )( ! ( size_of( x ) % size_of( 0 [ x ] ) ) ) ) ) #define is_between( x, lower, upper ) ( ( ( lower ) <= ( x ) ) && ( ( x ) <= ( upper ) ) ) diff --git a/project/enums/ECode.csv b/project/enums/ECode.csv index 9bfabfd..bf6b82b 100644 --- a/project/enums/ECode.csv +++ b/project/enums/ECode.csv @@ -32,7 +32,15 @@ Operator_Member_Fwd Operator_Cast Operator_Cast_Fwd Parameters -Preprocessor_Include +Preprocess_Define +Preprocess_Include +Preprocess_If +Preprocess_IfDef +Preprocess_IfNotDef +Preprocess_ElIf +Preprocess_Else +Preprocess_EndIf +Preprocess_Pragma Specifiers Struct Struct_Fwd diff --git a/project/enums/ESpecifier.csv b/project/enums/ESpecifier.csv index 1dc7a4e..736628e 100644 --- a/project/enums/ESpecifier.csv +++ b/project/enums/ESpecifier.csv @@ -9,6 +9,7 @@ Inline, inline Internal_Linkage, internal Local_Persist, local_persist Mutable, mutable +NeverInline, neverinline Ptr, * Ref, & Register, register diff --git a/project/enums/ETokType.csv b/project/enums/ETokType.csv index e0ff1f5..4f6c717 100644 --- a/project/enums/ETokType.csv +++ b/project/enums/ETokType.csv @@ -7,16 +7,16 @@ Access_StaticSymbol, "::" Ampersand, "&" Ampersand_DBL, "&&" Assign_Classifer, ":" -Attribute_Open, "[[" -Attribute_Close, "]]" +Attribute_Open, "[[" +Attribute_Close, "]]" BraceCurly_Open, "{" BraceCurly_Close, "}" BraceSquare_Open, "[" BraceSquare_Close, "]" Capture_Start, "(" Capture_End, ")" -Comment, "comemnt" -Char, "character" +Comment, "__comemnt__" +Char, "__character__" Comma, "," Decl_Class, "class" Decl_GNU_Attribute, "__attribute__" @@ -26,49 +26,61 @@ Decl_Extern_Linkage, "extern" Decl_Friend, "friend" Decl_Module, "module" Decl_Namespace, "namespace" -Decl_Operator, "operator" +Decl_Operator, "__operator__" Decl_Struct, "struct" Decl_Template, "template" Decl_Typedef, "typedef" Decl_Using, "using" Decl_Union, "union" -Identifier, "identifier" +Identifier, "__identifier__" Module_Import, "import" Module_Export, "export" -Number, "number" -Operator, "operator" -Preprocess_Define, "#define" -Preprocess_Include, "#include" -Preprocess_If, "#if" -Preprocess_ElIF, "#elif" -Preprocess_Else, "#else" -Preprocess_EndIf, "#endif" +Number, "__number__" +Operator, "__operator__" +Preprocess_Define, "define" +Preprocess_If, "if" +Preprocess_IfDef, "ifdef" +Preprocess_IfNotDef, "ifndef" +Preprocess_ElIf, "elif" +Preprocess_Else, "else" +Preprocess_EndIf, "endif" +Preprocess_Include, "include" +Preprocess_Pragma, "pragma" +Preprocess_Macro, "__macro__" +Preprocess_Unsupported, "__unsupported__" Spec_Alignas, "alignas" Spec_Const, "const" Spec_Consteval, "consteval" Spec_Constexpr, "constexpr" Spec_Constinit, "constinit" -Spec_Explicit, "explicit" +Spec_Explicit, "explicit" Spec_Extern, "extern" -Spec_Final, "final" -Spec_Global, "global" +Spec_Final, "final" +Spec_Global, "global" Spec_Inline, "inline" Spec_Internal_Linkage, "internal" Spec_LocalPersist, "local_persist" Spec_Mutable, "mutable" +Spec_NeverInline, "neverinline" Spec_Override, "override" Spec_Static, "static" Spec_ThreadLocal, "thread_local" Spec_Volatile, "volatile" Star, "*" Statement_End, ";" -String, "string" -Type_Unsigned, "unsigned" +StaticAssert, "static_assert" +String, "__string__" +Type_Unsigned, "unsigned" Type_Signed, "signed" Type_Short, "short" Type_Long, "long" -Type_char, "char" -Type_int, "int" -Type_double, "double" +Type_char, "char" +Type_int, "int" +Type_double, "double" +Type_MS_int8, "__int8" +Type_MS_int16, "__int16" +Type_MS_int32, "__int32" +Type_MS_int64, "__int64" +Type_MS_W64, "_W64" Varadic_Argument, "..." -Attributes_Start, "__attrib_start__" +__Attributes_Start, "__attrib_start__" diff --git a/project/file_processors/builder.cpp b/project/file_processors/builder.cpp index b8d5bc5..e747d43 100644 --- a/project/file_processors/builder.cpp +++ b/project/file_processors/builder.cpp @@ -1,6 +1,6 @@ void Builder::print( Code code ) { - Buffer.append_fmt( "%s\n", code->to_string() ); + Buffer.append( code->to_string() ); } void Builder::print_fmt( char const* fmt, ... ) diff --git a/scripts/.clang-format b/scripts/.clang-format index 26f9cc8..3b57be7 100644 --- a/scripts/.clang-format +++ b/scripts/.clang-format @@ -73,7 +73,7 @@ BreakBeforeTernaryOperators: true BreakConstructorInitializers: BeforeComma BreakStringLiterals: true -ColumnLimit: 180 +ColumnLimit: 120 CompactNamespaces: true @@ -94,16 +94,16 @@ IncludeBlocks: Preserve IndentCaseBlocks: false -IndentCaseLabels: false +IndentCaseLabels: true IndentExternBlock: AfterExternBlock IndentGotoLabels: true IndentPPDirectives: AfterHash IndentRequires: true IndentWidth: 4 -IndentWrappedFunctionNames: false +IndentWrappedFunctionNames: true # InsertNewlineAtEOF: true -InsertTrailingCommas: Wrapped +# InsertTrailingCommas: Wrapped LambdaBodyIndentation: OuterScope diff --git a/scripts/msvc/devshell.ps1 b/scripts/msvc/devshell.ps1 index 459a164..531bdfa 100644 --- a/scripts/msvc/devshell.ps1 +++ b/scripts/msvc/devshell.ps1 @@ -1,26 +1,23 @@ -# This script is used to iniitate the MSVC DevShell -$vs_devshell = @() -@("enterprise", "professional", "community") | ForEach-Object { - $vs_devshell_2022 = "C:\Program Files\Microsoft Visual Studio\2022\" + $_ + "\Common7\Tools\Launch-VsDevShell.ps1" - $vs_devshell_2019 = "C:\Program Files (x86)\Microsoft Visual Studio\2019\" + $_ + "\Common7\Tools\Launch-VsDevShell.ps1" +$ErrorActionPreference = "Stop" - $vs_devshell += @( $vs_devshell_2022, $vs_devshell_2019 ) +# Use vswhere to find the latest Visual Studio installation +$vswhere_out = & "C:\Program Files (x86)\Microsoft Visual Studio\Installer\vswhere.exe" -latest -property installationPath +if ($null -eq $vswhere_out) { + Write-Host "ERROR: Visual Studio installation not found" + exit 1 } -$found = $false -foreach($path in $vs_devshell) { - if (Test-Path $path) { - write-host "Found $path" +# Find Launch-VsDevShell.ps1 in the Visual Studio installation +$vs_path = $vswhere_out +$vs_devshell = Join-Path $vs_path "\Common7\Tools\Launch-VsDevShell.ps1" - Push-Location # Save the current path, loading the script will change it. - & $path - Pop-Location - - $found = $true - break; - } +if ( -not (Test-Path $vs_devshell) ) { + Write-Host "ERROR: Launch-VsDevShell.ps1 not found in Visual Studio installation" + Write-Host Tested path: $vs_devshell + exit 1 } -if (-not $found) { - write-host "MSVC DevShell: No valid path found" -} +# Launch the Visual Studio Developer Shell +Push-Location +& $vs_devshell @args +Pop-Location diff --git a/test/test.cpp b/test/test.cpp index a91dbfa..50aceba 100644 --- a/test/test.cpp +++ b/test/test.cpp @@ -5,6 +5,7 @@ #include "gen.cpp" #include "sanity.cpp" #include "SOA.cpp" +#include "test.singleheader_ast.cpp" #if GEN_TIME int gen_main() @@ -12,10 +13,12 @@ int gen_main() using namespace gen; log_fmt("\ngen_time:"); - check_sanity(); + // check_sanity(); check_SOA(); + check_singleheader_ast(); + return 0; } #endif diff --git a/test/test.singleheader_ast.cpp b/test/test.singleheader_ast.cpp new file mode 100644 index 0000000..7fa0efe --- /dev/null +++ b/test/test.singleheader_ast.cpp @@ -0,0 +1,42 @@ +#pragma once + +#define GEN_DEFINE_LIBRARY_CODE_CONSTANTS +#define GEN_ENFORCE_STRONG_CODE_TYPES +#define GEN_EXPOSE_BACKEND +#define GEN_BENCHMARK +#include "gen.hpp" +#include "file_processors/scanner.hpp" +using namespace gen; + +void check_singleheader_ast() +{ + #define project_dir "../../" + gen::init(); + log_fmt("\ncheck_singleheader_ast:\n"); + + FileContents file = file_read_contents( GlobalAllocator, true, project_dir "singleheader/gen/gen.hpp" ); + + CodeBody ast = parse_global_body( { file.size, (char const*)file.data } ); + + log_fmt("generated AST!!!\n"); + + s32 idx = 0; + for ( Code entry : ast ) + { + if (idx == 900) + { + log_fmt("break here\n"); + } + log_fmt("Entry %d: %s\n", idx, entry.to_string() ); + idx++; + } + + Builder builder; + builder.open( "singleheader_copy.gen.hpp" ); + log_fmt("\n\nserializng ast\n"); + builder.print( ast ); + builder.write(); + + log_fmt("passed!!\n"); + gen::deinit(); +}