├── .gitignore ├── 7Sharp.Compiler.Tests ├── 7Sharp.Compiler.Tests.csproj ├── Lexing │ ├── CharLexerTests.cs │ ├── CommentLexerTests.cs │ ├── FloatLexerTests.cs │ ├── IdentifierLexerTests.cs │ ├── IntegerLexerTests.cs │ ├── InvalidNumberSizeTests.cs │ ├── LexingTester.cs │ ├── StringLexerTests.cs │ └── SymbolLexerTests.cs └── Usings.cs ├── 7Sharp.Compiler ├── 7Sharp.Compiler.csproj ├── DelimeterMatch.cs ├── DelimeterMatchResult.cs ├── DelimeterMatcher.cs ├── FileLocation.cs ├── Lexing │ ├── Lexer.cs │ ├── LexerError.cs │ ├── LexerResult.cs │ ├── Token.cs │ └── TokenType.cs ├── TransactionalCharStream.cs └── TransactionalStream.cs ├── 7Sharp.sln └── 7Sharp ├── 7Sharp.csproj ├── Editor └── Editor.cs └── Program.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | **/[Dd]ebug/ 21 | **/[Dd]ebugPublic/ 22 | **/[Rr]elease/ 23 | **/[Rr]eleases/ 24 | **/x64/ 25 | **/x86/ 26 | **/[Ww][Ii][Nn]32/ 27 | **/[Aa][Rr][Mm]/ 28 | **/[Aa][Rr][Mm]64/ 29 | **/bld/ 30 | **/[Bb]in/ 31 | **/[Oo]bj/ 32 | **/[Ll]og/ 33 | */[Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/** 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # Tye 66 | .tye/ 67 | 68 | # ASP.NET Scaffolding 69 | ScaffoldingReadMe.txt 70 | 71 | # StyleCop 72 | StyleCopReport.xml 73 | 74 | # Files built by Visual Studio 75 | *_i.c 76 | *_p.c 77 | *_h.h 78 | *.ilk 79 | *.meta 80 | *.obj 81 | *.iobj 82 | *.pch 83 | *.pdb 84 | *.ipdb 85 | *.pgc 86 | *.pgd 87 | *.rsp 88 | *.sbr 89 | *.tlb 90 | *.tli 91 | *.tlh 92 | *.tmp 93 | *.tmp_proj 94 | *_wpftmp.csproj 95 | *.log 96 | *.tlog 97 | *.vspscc 98 | *.vssscc 99 | .builds 100 | *.pidb 101 | *.svclog 102 | *.scc 103 | 104 | # Chutzpah Test files 105 | _Chutzpah* 106 | 107 | # Visual C++ cache files 108 | ipch/ 109 | *.aps 110 | *.ncb 111 | *.opendb 112 | *.opensdf 113 | *.sdf 114 | *.cachefile 115 | *.VC.db 116 | *.VC.VC.opendb 117 | 118 | # Visual Studio profiler 119 | *.psess 120 | *.vsp 121 | *.vspx 122 | *.sap 123 | 124 | # Visual Studio Trace Files 125 | *.e2e 126 | 127 | # TFS 2012 Local Workspace 128 | $tf/ 129 | 130 | # Guidance Automation Toolkit 131 | *.gpState 132 | 133 | # ReSharper is a .NET coding add-in 134 | _ReSharper*/ 135 | *.[Rr]e[Ss]harper 136 | *.DotSettings.user 137 | 138 | # TeamCity is a build add-in 139 | _TeamCity* 140 | 141 | # DotCover is a Code Coverage Tool 142 | *.dotCover 143 | 144 | # AxoCover is a Code Coverage Tool 145 | .axoCover/* 146 | !.axoCover/settings.json 147 | 148 | # Coverlet is a free, cross platform Code Coverage Tool 149 | coverage*.json 150 | coverage*.xml 151 | coverage*.info 152 | 153 | # Visual Studio code coverage results 154 | *.coverage 155 | *.coveragexml 156 | 157 | # NCrunch 158 | _NCrunch_* 159 | .*crunch*.local.xml 160 | nCrunchTemp_* 161 | 162 | # MightyMoose 163 | *.mm.* 164 | AutoTest.Net/ 165 | 166 | # Web workbench (sass) 167 | .sass-cache/ 168 | 169 | # Installshield output folder 170 | [Ee]xpress/ 171 | 172 | # DocProject is a documentation generator add-in 173 | DocProject/buildhelp/ 174 | DocProject/Help/*.HxT 175 | DocProject/Help/*.HxC 176 | DocProject/Help/*.hhc 177 | DocProject/Help/*.hhk 178 | DocProject/Help/*.hhp 179 | DocProject/Help/Html2 180 | DocProject/Help/html 181 | 182 | # Click-Once directory 183 | publish/ 184 | 185 | # Publish Web Output 186 | *.[Pp]ublish.xml 187 | *.azurePubxml 188 | # Note: Comment the next line if you want to checkin your web deploy settings, 189 | # but database connection strings (with potential passwords) will be unencrypted 190 | *.pubxml 191 | *.publishproj 192 | 193 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 194 | # checkin your Azure Web App publish settings, but sensitive information contained 195 | # in these scripts will be unencrypted 196 | PublishScripts/ 197 | 198 | # NuGet Packages 199 | *.nupkg 200 | # NuGet Symbol Packages 201 | *.snupkg 202 | # The packages folder can be ignored because of Package Restore 203 | **/[Pp]ackages/* 204 | # except build/, which is used as an MSBuild target. 205 | !**/[Pp]ackages/build/ 206 | # Uncomment if necessary however generally it will be regenerated when needed 207 | #!**/[Pp]ackages/repositories.config 208 | # NuGet v3's project.json files produces more ignorable files 209 | *.nuget.props 210 | *.nuget.targets 211 | 212 | # Microsoft Azure Build Output 213 | csx/ 214 | *.build.csdef 215 | 216 | # Microsoft Azure Emulator 217 | ecf/ 218 | rcf/ 219 | 220 | # Windows Store app package directories and files 221 | AppPackages/ 222 | BundleArtifacts/ 223 | Package.StoreAssociation.xml 224 | _pkginfo.txt 225 | *.appx 226 | *.appxbundle 227 | *.appxupload 228 | 229 | # Visual Studio cache files 230 | # files ending in .cache can be ignored 231 | *.[Cc]ache 232 | # but keep track of directories ending in .cache 233 | !?*.[Cc]ache/ 234 | 235 | # Others 236 | ClientBin/ 237 | ~$* 238 | *~ 239 | *.dbmdl 240 | *.dbproj.schemaview 241 | *.jfm 242 | *.pfx 243 | *.publishsettings 244 | orleans.codegen.cs 245 | 246 | # Including strong name files can present a security risk 247 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 248 | #*.snk 249 | 250 | # Since there are multiple workflows, uncomment next line to ignore bower_components 251 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 252 | #bower_components/ 253 | 254 | # RIA/Silverlight projects 255 | Generated_Code/ 256 | 257 | # Backup & report files from converting an old project file 258 | # to a newer Visual Studio version. Backup files are not needed, 259 | # because we have git ;-) 260 | _UpgradeReport_Files/ 261 | Backup*/ 262 | UpgradeLog*.XML 263 | UpgradeLog*.htm 264 | ServiceFabricBackup/ 265 | *.rptproj.bak 266 | 267 | # SQL Server files 268 | *.mdf 269 | *.ldf 270 | *.ndf 271 | 272 | # Business Intelligence projects 273 | *.rdl.data 274 | *.bim.layout 275 | *.bim_*.settings 276 | *.rptproj.rsuser 277 | *- [Bb]ackup.rdl 278 | *- [Bb]ackup ([0-9]).rdl 279 | *- [Bb]ackup ([0-9][0-9]).rdl 280 | 281 | # Microsoft Fakes 282 | FakesAssemblies/ 283 | 284 | # GhostDoc plugin setting file 285 | *.GhostDoc.xml 286 | 287 | # Node.js Tools for Visual Studio 288 | .ntvs_analysis.dat 289 | node_modules/ 290 | 291 | # Visual Studio 6 build log 292 | *.plg 293 | 294 | # Visual Studio 6 workspace options file 295 | *.opt 296 | 297 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 298 | *.vbw 299 | 300 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 301 | *.vbp 302 | 303 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 304 | *.dsw 305 | *.dsp 306 | 307 | # Visual Studio 6 technical files 308 | *.ncb 309 | *.aps 310 | 311 | # Visual Studio LightSwitch build output 312 | **/*.HTMLClient/GeneratedArtifacts 313 | **/*.DesktopClient/GeneratedArtifacts 314 | **/*.DesktopClient/ModelManifest.xml 315 | **/*.Server/GeneratedArtifacts 316 | **/*.Server/ModelManifest.xml 317 | _Pvt_Extensions 318 | 319 | # Paket dependency manager 320 | .paket/paket.exe 321 | paket-files/ 322 | 323 | # FAKE - F# Make 324 | .fake/ 325 | 326 | # CodeRush personal settings 327 | .cr/personal 328 | 329 | # Python Tools for Visual Studio (PTVS) 330 | __pycache__/ 331 | *.pyc 332 | 333 | # Cake - Uncomment if you are using it 334 | # tools/** 335 | # !tools/packages.config 336 | 337 | # Tabs Studio 338 | *.tss 339 | 340 | # Telerik's JustMock configuration file 341 | *.jmconfig 342 | 343 | # BizTalk build output 344 | *.btp.cs 345 | *.btm.cs 346 | *.odx.cs 347 | *.xsd.cs 348 | 349 | # OpenCover UI analysis results 350 | OpenCover/ 351 | 352 | # Azure Stream Analytics local run output 353 | ASALocalRun/ 354 | 355 | # MSBuild Binary and Structured Log 356 | *.binlog 357 | 358 | # NVidia Nsight GPU debugger configuration file 359 | *.nvuser 360 | 361 | # MFractors (Xamarin productivity tool) working folder 362 | .mfractor/ 363 | 364 | # Local History for Visual Studio 365 | .localhistory/ 366 | 367 | # Visual Studio History (VSHistory) files 368 | .vshistory/ 369 | 370 | # BeatPulse healthcheck temp database 371 | healthchecksdb 372 | 373 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 374 | MigrationBackup/ 375 | 376 | # Ionide (cross platform F# VS Code tools) working folder 377 | .ionide/ 378 | 379 | # Fody - auto-generated XML schema 380 | FodyWeavers.xsd 381 | 382 | # VS Code files for those working on multiple tools 383 | .vscode/* 384 | !.vscode/settings.json 385 | !.vscode/tasks.json 386 | !.vscode/launch.json 387 | !.vscode/extensions.json 388 | *.code-workspace 389 | 390 | # Local History for Visual Studio Code 391 | .history/ 392 | 393 | # Windows Installer files from build outputs 394 | *.cab 395 | *.msi 396 | *.msix 397 | *.msm 398 | *.msp 399 | 400 | # JetBrains Rider 401 | *.sln.iml 402 | 403 | ## 404 | ## Visual studio for Mac 405 | ## 406 | 407 | 408 | # globs 409 | Makefile.in 410 | *.userprefs 411 | *.usertasks 412 | config.make 413 | config.status 414 | aclocal.m4 415 | install-sh 416 | autom4te.cache/ 417 | *.tar.gz 418 | tarballs/ 419 | test-results/ 420 | 421 | # Mac bundle stuff 422 | *.dmg 423 | *.app 424 | 425 | # content below from: https://github.com/github/gitignore/blob/master/Global/macOS.gitignore 426 | # General 427 | .DS_Store 428 | .AppleDouble 429 | .LSOverride 430 | 431 | # Icon must end with two \r 432 | Icon 433 | 434 | 435 | # Thumbnails 436 | ._* 437 | 438 | # Files that might appear in the root of a volume 439 | .DocumentRevisions-V100 440 | .fseventsd 441 | .Spotlight-V100 442 | .TemporaryItems 443 | .Trashes 444 | .VolumeIcon.icns 445 | .com.apple.timemachine.donotpresent 446 | 447 | # Directories potentially created on remote AFP share 448 | .AppleDB 449 | .AppleDesktop 450 | Network Trash Folder 451 | Temporary Items 452 | .apdisk 453 | 454 | # content below from: https://github.com/github/gitignore/blob/master/Global/Windows.gitignore 455 | # Windows thumbnail cache files 456 | Thumbs.db 457 | ehthumbs.db 458 | ehthumbs_vista.db 459 | 460 | # Dump file 461 | *.stackdump 462 | 463 | # Folder config file 464 | [Dd]esktop.ini 465 | 466 | # Recycle Bin used on file shares 467 | $RECYCLE.BIN/ 468 | 469 | # Windows Installer files 470 | *.cab 471 | *.msi 472 | *.msix 473 | *.msm 474 | *.msp 475 | 476 | # Windows shortcuts 477 | *.lnk 478 | -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/7Sharp.Compiler.Tests.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | _7Sharp.Compiler.Tests 6 | enable 7 | enable 8 | 9 | false 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/CharLexerTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class CharLexerTests 6 | { 7 | [Theory] 8 | [TestCase(@"' '", new[] { TokenType.CHAR })] 9 | [TestCase(@"'\0'", new[] { TokenType.CHAR })] 10 | [TestCase(@"'\n'", new[] { TokenType.CHAR })] 11 | [TestCase(@"'\r'", new[] { TokenType.CHAR })] 12 | [TestCase(@"'\t'", new[] { TokenType.CHAR })] 13 | [TestCase(@"'\\'", new[] { TokenType.CHAR })] 14 | [TestCase(@"'\u0123'", new[] { TokenType.CHAR })] 15 | [TestCase(@"'\u4567'", new[] { TokenType.CHAR })] 16 | [TestCase(@"'\u89AB'", new[] { TokenType.CHAR })] 17 | [TestCase(@"'\uDEFG'", new[] { TokenType.CHAR })] 18 | public void Valid(string s, TokenType[] tokens) => LexingTester.ExpectTokens(s, tokens); 19 | 20 | [Theory] 21 | [TestCase(@"'", LexerErrorType.UNCLOSED_CHAR)] 22 | [TestCase(@"''", LexerErrorType.INVALID_CHAR_LITERAL)] 23 | public void Invalid(string s, LexerErrorType? error) => LexingTester.ExpectError(s, error); 24 | 25 | 26 | [Theory] 27 | [TestCaseSource(nameof(GetInvalidEscapeSequences))] 28 | public void EscapeSequences(char c) => LexingTester.ExpectError($"'\\{c}'", LexerErrorType.INVALID_ESCAPE_SEQUENCE); 29 | 30 | internal static IEnumerable GetInvalidEscapeSequences() 31 | { 32 | List list = new(); 33 | for (int i = ' '; i <= '~'; i++) 34 | { 35 | char c = (char)i; 36 | if (i is not ('0' or 'n' or 'r' or 't' or 'u' or '\\' or '\'' or '"')) 37 | { 38 | list.Add(new object[] { c }); 39 | } 40 | } 41 | return list; 42 | } 43 | } -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/CommentLexerTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class CommentLexerTests 6 | { 7 | [Theory] 8 | [TestCase("// hello\n// world", new[] { TokenType.SINGLE_LINE_COMMENT, TokenType.SINGLE_LINE_COMMENT })] 9 | [TestCase("/* multi\nline\ncomment\n\r\n\n*/", new[] { TokenType.MULTI_LINE_COMMENT })] 10 | public void Valid(string s, TokenType[] tokens) => LexingTester.ExpectTokens(s, tokens); 11 | 12 | [Theory] 13 | [TestCase("/* unclosed", LexerErrorType.UNCLOSED_MULTILINE_COMMENT)] 14 | public void Invalid(string s, LexerErrorType error) => LexingTester.ExpectError(s, error); 15 | } 16 | -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/FloatLexerTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class FloatLexerTests 6 | { 7 | [Theory] 8 | [TestCase("0.f32", new[] { TokenType.FLOAT })] 9 | [TestCase("-0.f32", new[] { TokenType.FLOAT })] 10 | [TestCase("0123456789f32", new[] { TokenType.FLOAT })] 11 | [TestCase("1234567890f32", new[] { TokenType.FLOAT })] 12 | [TestCase("-0123456789f32", new[] { TokenType.FLOAT })] 13 | [TestCase("-1234567890f32", new[] { TokenType.FLOAT })] 14 | [TestCase("0123456789.f32", new[] { TokenType.FLOAT })] 15 | [TestCase("1234567890.f32", new[] { TokenType.FLOAT })] 16 | [TestCase("-0123456789.f32", new[] { TokenType.FLOAT })] 17 | [TestCase("-1234567890.f32", new[] { TokenType.FLOAT })] 18 | [TestCase("0123456789.0123456789f32", new[] { TokenType.FLOAT })] 19 | [TestCase("1234567890.0123456789f32", new[] { TokenType.FLOAT })] 20 | [TestCase("-0123456789.0123456789f32", new[] { TokenType.FLOAT })] 21 | [TestCase("-1234567890.0123456789f32", new[] { TokenType.FLOAT })] 22 | [TestCase("0123456789.1234567890f32", new[] { TokenType.FLOAT })] 23 | [TestCase("1234567890.1234567890f32", new[] { TokenType.FLOAT })] 24 | [TestCase("-0123456789.1234567890f32", new[] { TokenType.FLOAT })] 25 | [TestCase("-1234567890.1234567890f32", new[] { TokenType.FLOAT })] 26 | [TestCase("0.f64", new[] { TokenType.FLOAT })] 27 | [TestCase("-0.f64", new[] { TokenType.FLOAT })] 28 | [TestCase("0123456789f64", new[] { TokenType.FLOAT })] 29 | [TestCase("1234567890f64", new[] { TokenType.FLOAT })] 30 | [TestCase("-0123456789f64", new[] { TokenType.FLOAT })] 31 | [TestCase("-1234567890f64", new[] { TokenType.FLOAT })] 32 | [TestCase("0123456789.f64", new[] { TokenType.FLOAT })] 33 | [TestCase("1234567890.f64", new[] { TokenType.FLOAT })] 34 | [TestCase("-0123456789.f64", new[] { TokenType.FLOAT })] 35 | [TestCase("-1234567890.f64", new[] { TokenType.FLOAT })] 36 | [TestCase("0123456789.0123456789f64", new[] { TokenType.FLOAT })] 37 | [TestCase("1234567890.0123456789f64", new[] { TokenType.FLOAT })] 38 | [TestCase("-0123456789.0123456789f64", new[] { TokenType.FLOAT })] 39 | [TestCase("-1234567890.0123456789f64", new[] { TokenType.FLOAT })] 40 | [TestCase("0123456789.1234567890f64", new[] { TokenType.FLOAT })] 41 | [TestCase("1234567890.1234567890f64", new[] { TokenType.FLOAT })] 42 | [TestCase("-0123456789.1234567890f64", new[] { TokenType.FLOAT })] 43 | [TestCase("-1234567890.1234567890f64", new[] { TokenType.FLOAT })] 44 | public void Valid(string s, TokenType[] tokens) => LexingTester.ExpectTokens(s, tokens); 45 | 46 | [Theory] 47 | [TestCase("1.2.3f32", LexerErrorType.MULTIPLE_DECIMAL_POINTS)] 48 | [TestCase("-4.5.6f32", LexerErrorType.MULTIPLE_DECIMAL_POINTS)] 49 | [TestCase("7.8.9f64", LexerErrorType.MULTIPLE_DECIMAL_POINTS)] 50 | [TestCase("-10.11.12f64", LexerErrorType.MULTIPLE_DECIMAL_POINTS)] 51 | public void Invalid(string s, LexerErrorType error) => LexingTester.ExpectError(s, error); 52 | } -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/IdentifierLexerTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class IdentifierLexerTests 6 | { 7 | [Theory] 8 | [TestCase("abcdefghijklmnopqrstuvwxyz_ABCDEFGHIJKLMNOPQRSTUVWXYZ", new[] { TokenType.IDENFITIER })] 9 | [TestCase("ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz", new[] { TokenType.IDENFITIER })] 10 | [TestCase("_startsWithUnderscores", new[] { TokenType.IDENFITIER })] 11 | [TestCase("__", new[] { TokenType.IDENFITIER })] 12 | [TestCase("numbersAFTER_0123456789", new[] { TokenType.IDENFITIER })] 13 | public void Valid(string s, TokenType[] tokens) => LexingTester.ExpectTokens(s, tokens); 14 | 15 | [Theory] 16 | [TestCase("0starts_WITH_number", null)] 17 | [TestCase("1starts_WITH_number", null)] 18 | [TestCase("2starts_WITH_number", null)] 19 | [TestCase("3starts_WITH_number", null)] 20 | [TestCase("4starts_WITH_number", null)] 21 | [TestCase("5starts_WITH_number", null)] 22 | [TestCase("6starts_WITH_number", null)] 23 | [TestCase("7starts_WITH_number", null)] 24 | [TestCase("8starts_WITH_number", null)] 25 | [TestCase("9starts_WITH_number", null)] 26 | public void Invalid(string s, LexerErrorType? error) => LexingTester.ExpectError(s, error); 27 | } 28 | 29 | //public sealed class LexerTests 30 | //{ 31 | // [Theory] 32 | // [TestCase("", new[] { })] 33 | // public void Valid(string s, TokenType[] tokens) => LexingTester.Valid(s, tokens); 34 | 35 | // [Theory] 36 | // [TestCase("", LexerErrorType.)] 37 | // public void Invalid(string s, LexerErrorType error) => LexingTester.Invalid(s, error); 38 | //} -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/IntegerLexerTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class IntegerLexerTests 6 | { 7 | [Theory] 8 | [TestCase("0", new[] { TokenType.INTEGER })] 9 | [TestCase("0123456789", new[] { TokenType.INTEGER })] 10 | [TestCase("1234567890", new[] { TokenType.INTEGER })] 11 | [TestCase("1234567890u8", new[] { TokenType.INTEGER })] 12 | [TestCase("1234567890u16", new[] { TokenType.INTEGER })] 13 | [TestCase("1234567890u32", new[] { TokenType.INTEGER })] 14 | [TestCase("1234567890u64", new[] { TokenType.INTEGER })] 15 | [TestCase("1234567890s8", new[] { TokenType.INTEGER })] 16 | [TestCase("1234567890s16", new[] { TokenType.INTEGER })] 17 | [TestCase("1234567890s32", new[] { TokenType.INTEGER })] 18 | [TestCase("1234567890s64", new[] { TokenType.INTEGER })] 19 | [TestCase("-1234567890s8", new[] { TokenType.INTEGER })] 20 | [TestCase("-1234567890s16", new[] { TokenType.INTEGER })] 21 | [TestCase("-1234567890s32", new[] { TokenType.INTEGER })] 22 | [TestCase("-1234567890s64", new[] { TokenType.INTEGER })] 23 | public void Valid(string s, TokenType[] tokens) => LexingTester.ExpectTokens(s, tokens); 24 | 25 | [Theory] 26 | [TestCase("1.0u8", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 27 | [TestCase("2.0u16", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 28 | [TestCase("3.0u32", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 29 | [TestCase("4.0u64", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 30 | [TestCase("5.0s8", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 31 | [TestCase("6.0s16", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 32 | [TestCase("7.0s32", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 33 | [TestCase("8.0s64", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 34 | [TestCase("-9.0s8", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 35 | [TestCase("-1.0s16", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 36 | [TestCase("-1.1s32", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 37 | [TestCase("-1.2s64", LexerErrorType.INTEGER_WITH_DECIMAL_POINT)] 38 | public void Invalid(string s, LexerErrorType error) => LexingTester.ExpectError(s, error); 39 | } 40 | -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/InvalidNumberSizeTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class InvalidNumberSizeTests 6 | { 7 | [Test] 8 | public void InvalidInt8Size([Range(0, 8 - 1)] int size, [Range(0, 1)] int isSigned) => LexingTester.ExpectError($"123{(isSigned == 1 ? 's' : 'u')}{size}", LexerErrorType.INVALID_NUMBER_SIZE); 9 | 10 | [Test] 11 | public void InvalidInt16Size([Range(8 + 1, 16 - 1)] int size, [Range(0, 1)] int isSigned) => LexingTester.ExpectError($"123{(isSigned == 1 ? 's' : 'u')}{size}", LexerErrorType.INVALID_NUMBER_SIZE); 12 | 13 | [Test] 14 | public void InvalidInt32Size([Range(16 + 1, 32 - 1)] int size, [Range(0, 1)] int isSigned) => LexingTester.ExpectError($"123{(isSigned == 1 ? 's' : 'u')}{size}", LexerErrorType.INVALID_NUMBER_SIZE); 15 | 16 | [Test] 17 | public void InvalidInt64Size([Range(32 + 1, 64 - 1)] int size, [Range(0, 1)] int isSigned) => LexingTester.ExpectError($"123{(isSigned == 1 ? 's' : 'u')}{size}", LexerErrorType.INVALID_NUMBER_SIZE); 18 | 19 | [Test] 20 | public void InvalidIntOtherSize([Range(64 + 1, 100)] int size, [Range(0, 1)] int isSigned) => LexingTester.ExpectError($"123{(isSigned == 1 ? 's' : 'u')}{size}", LexerErrorType.INVALID_NUMBER_SIZE); 21 | 22 | [Test] 23 | public void InvalidFloat32Size([Range(0, 32 - 1)] int size) => LexingTester.ExpectError($"123.456f{size}", LexerErrorType.INVALID_NUMBER_SIZE); 24 | 25 | [Test] 26 | public void InvalidFloat64Size([Range(32 + 1, 64 - 1)] int size) => LexingTester.ExpectError($"123.456f{size}", LexerErrorType.INVALID_NUMBER_SIZE); 27 | 28 | [Test] 29 | public void InvalidFloatOtherSize([Range(64 + 1, 100)] int size) => LexingTester.ExpectError($"123.456f{size}", LexerErrorType.INVALID_NUMBER_SIZE); 30 | } -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/LexingTester.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public static class LexingTester 6 | { 7 | public static void ExpectTokens(string s, TokenType[] expected) 8 | { 9 | LexerResult result = Lexer.Lex(s); 10 | 11 | Assert.That(result.IsOk, Is.True, () => $"Lexer Error: {result.Error}"); 12 | Console.Write("[\n\t"); 13 | Console.Write(string.Join(",\n\t", result.Tokens)); 14 | Console.WriteLine("\n]"); 15 | Assert.That(result.Tokens, Has.Count.EqualTo(expected.Length)); 16 | Assert.That(result.Tokens.Select(x => x.Type).ToArray(), Is.EqualTo(expected)); 17 | } 18 | 19 | public static void ExpectError(string s, LexerErrorType? expected) 20 | { 21 | LexerResult result = Lexer.Lex(s); 22 | 23 | Assert.That(result.IsOk, Is.False, () => $"Lexing Success: {string.Join(", ", result.Tokens)}"); 24 | Console.WriteLine(result.Error); 25 | if (expected is not null) 26 | { 27 | Assert.That(result.Error.Type, Is.EqualTo(expected)); 28 | } 29 | } 30 | } 31 | 32 | // Template 33 | //public sealed class LexerTests 34 | //{ 35 | // [Theory] 36 | // [TestCase("", new[] { })] 37 | // public void Valid(string s, TokenType[] tokens) => LexingTester.Valid(s, tokens); 38 | 39 | // [Theory] 40 | // [TestCase("", LexerErrorType.)] 41 | // public void Invalid(string s, LexerErrorType error) => LexingTester.Invalid(s, error); 42 | //} 43 | -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/StringLexerTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class StringLexerTests 6 | { 7 | [Theory] 8 | [TestCase("\"\"", new[] { TokenType.STRING })] 9 | [TestCase("\"hello world\"", new[] { TokenType.STRING })] 10 | [TestCase("\"hello\nworld\"", new[] { TokenType.STRING })] 11 | [TestCase("\"hello\\\"world\"", new[] { TokenType.STRING })] 12 | [TestCase("\"hello\\\'world\"", new[] { TokenType.STRING })] 13 | [TestCase("\"hello\\nworld\"", new[] { TokenType.STRING })] 14 | [TestCase("\"hello\\rworld\"", new[] { TokenType.STRING })] 15 | [TestCase("\"hello\\tworld\"", new[] { TokenType.STRING })] 16 | [TestCase("\"hello\\0world\"", new[] { TokenType.STRING })] 17 | [TestCase("\"hello\\\\world\"", new[] { TokenType.STRING })] 18 | public void Valid(string s, TokenType[] tokens) => LexingTester.ExpectTokens(s, tokens); 19 | 20 | [Theory] 21 | [TestCase("\"unclosed string", LexerErrorType.UNCLOSED_STRING)] 22 | public void Invalid(string s, LexerErrorType error) => LexingTester.ExpectError(s, error); 23 | 24 | [Theory] 25 | [TestCaseSource(typeof(CharLexerTests), nameof(CharLexerTests.GetInvalidEscapeSequences))] 26 | public void Escapes(char c) => LexingTester.ExpectError($"\"\\{c}\"", LexerErrorType.INVALID_ESCAPE_SEQUENCE); 27 | } 28 | -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Lexing/SymbolLexerTests.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Compiler.Lexing; 2 | 3 | namespace _7Sharp.Compiler.Tests.Lexing; 4 | 5 | public sealed class SymbolLexerTests 6 | { 7 | [Theory] 8 | [TestCase(";", new[] { TokenType.SEMICOLON })] 9 | [TestCase("(", new[] { TokenType.OPEN_PAREN })] 10 | [TestCase(")", new[] { TokenType.CLOSE_PAREN })] 11 | [TestCase("{", new[] { TokenType.OPEN_BRACE })] 12 | [TestCase("}", new[] { TokenType.CLOSE_BRACE })] 13 | [TestCase("[", new[] { TokenType.OPEN_BRACKET })] 14 | [TestCase("]", new[] { TokenType.CLOSE_BRACKET })] 15 | [TestCase("+", new[] { TokenType.PLUS })] 16 | [TestCase("-", new[] { TokenType.MINUS })] 17 | [TestCase("*", new[] { TokenType.TIMES })] 18 | [TestCase("/", new[] { TokenType.DIVIDE })] 19 | [TestCase("%", new[] { TokenType.MOD })] 20 | [TestCase("++", new[] { TokenType.INCREMENT })] 21 | [TestCase("--", new[] { TokenType.DECREMENT })] 22 | [TestCase("==", new[] { TokenType.EQUALS })] 23 | [TestCase("!=", new[] { TokenType.NOT_EQUALS })] 24 | [TestCase("&&", new[] { TokenType.BOOL_AND })] 25 | [TestCase("||", new[] { TokenType.BOOL_OR })] 26 | [TestCase("^^", new[] { TokenType.BOOL_XOR })] 27 | [TestCase(">", new[] { TokenType.GREATER_THAN })] 28 | [TestCase("<", new[] { TokenType.LESS_THAN })] 29 | [TestCase(">=", new[] { TokenType.GREATER_THAN_OR_EQUAL })] 30 | [TestCase("<=", new[] { TokenType.LESS_THAN_OR_EQUAL })] 31 | [TestCase("!", new[] { TokenType.BOOL_NOT })] 32 | [TestCase("&", new[] { TokenType.BIT_AND })] 33 | [TestCase("|", new[] { TokenType.BIT_OR })] 34 | [TestCase("^", new[] { TokenType.BIT_XOR })] 35 | [TestCase("~", new[] { TokenType.BIT_NOT })] 36 | [TestCase("=", new[] { TokenType.ASSIGNMENT })] 37 | [TestCase(".", new[] { TokenType.DOT })] 38 | [TestCase("??", new[] { TokenType.DEFAULT })] 39 | [TestCase("!>>", new[] { TokenType.ERROR_MAP })] 40 | [TestCase("!??", new[] { TokenType.ERROR_DEFAULT })] 41 | [TestCase("?.", new[] { TokenType.VALUE_CHAIN })] 42 | [TestCase("!.", new[] { TokenType.ERROR_CHAIN })] 43 | [TestCase("_", new[] { TokenType.CATCH_ALL })] 44 | [TestCase("=>", new[] { TokenType.LAMBDA })] 45 | public void Valid(string s, TokenType[] tokens) => LexingTester.ExpectTokens(s, tokens); 46 | } 47 | -------------------------------------------------------------------------------- /7Sharp.Compiler.Tests/Usings.cs: -------------------------------------------------------------------------------- 1 | global using NUnit.Framework; -------------------------------------------------------------------------------- /7Sharp.Compiler/7Sharp.Compiler.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | _7Sharp.Compiler 6 | enable 7 | enable 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /7Sharp.Compiler/DelimeterMatch.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler; 2 | 3 | public readonly record struct DelimeterMatch(DelimeterMatchResult Result, int Index) 4 | { 5 | public static implicit operator bool(DelimeterMatch value) => value.Result == DelimeterMatchResult.FOUND; 6 | public static implicit operator DelimeterMatch(int i) => new(DelimeterMatchResult.FOUND, i); 7 | } 8 | -------------------------------------------------------------------------------- /7Sharp.Compiler/DelimeterMatchResult.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler; 2 | 3 | public enum DelimeterMatchResult 4 | { 5 | FOUND, 6 | TOO_MANY_OPENERS, 7 | TOO_MANY_CLOSERS 8 | } -------------------------------------------------------------------------------- /7Sharp.Compiler/DelimeterMatcher.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler; 2 | 3 | public static class DelimeterMatcher 4 | { 5 | public static DelimeterMatch FindMatch(IReadOnlyList list, int start, T opener, T closer, T? escape = default) 6 | where T : IEquatable 7 | { 8 | int depth = 0; 9 | bool wasEscape = true; 10 | for (int i = start; i < list.Count; i++) 11 | { 12 | T t = list[i]; 13 | if (t is null) 14 | { 15 | continue; 16 | } 17 | if (t.Equals(opener) && !wasEscape) 18 | { 19 | depth++; 20 | } 21 | else if (t.Equals(closer) && !wasEscape) 22 | { 23 | depth--; 24 | if (depth == 0) 25 | { 26 | return i; 27 | } 28 | else if (depth < 0) 29 | { 30 | return new(DelimeterMatchResult.TOO_MANY_CLOSERS, -1); 31 | } 32 | } 33 | wasEscape = t.Equals(escape); 34 | } 35 | return new(DelimeterMatchResult.TOO_MANY_OPENERS, -1); 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /7Sharp.Compiler/FileLocation.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler; 2 | 3 | public readonly record struct FileLocation(int Line, int Column); -------------------------------------------------------------------------------- /7Sharp.Compiler/Lexing/Lexer.cs: -------------------------------------------------------------------------------- 1 | using System.Data; 2 | using System.Text; 3 | 4 | namespace _7Sharp.Compiler.Lexing; 5 | 6 | public static class Lexer 7 | { 8 | private static readonly string IDENTIFIER_START_CHARS = "_" + 9 | new string(Enumerable.Range(0, 26).Select(i => (char)(i + 'A')).ToArray()) + 10 | new string(Enumerable.Range(0, 26).Select(i => (char)(i + 'a')).ToArray()); 11 | private static readonly string IDENTIFIER_END_CHARS = IDENTIFIER_START_CHARS + "0123456789"; 12 | 13 | public static LexerResult Lex(string code) 14 | { 15 | TransactionalCharStream stream = new(code); 16 | 17 | List tokens = new(); 18 | 19 | Span threeCharBuf = stackalloc char[3]; 20 | 21 | while (!stream.AtEnd) 22 | { 23 | char current = stream.Next(); 24 | switch (current) 25 | { 26 | case '/' when stream.Peek() == '/': 27 | _ = stream.Next(); // Eat second slash 28 | tokens.Add(LexSingleLineComment(stream)); 29 | stream.Commit(); 30 | break; 31 | case '/' when stream.Peek() == '*': 32 | { 33 | _ = stream.Next(); // eat * 34 | if (!TryLexMultiLineComment(stream, out Token comment, out LexerError error)) 35 | { 36 | return error; 37 | } 38 | tokens.Add(comment); 39 | stream.Commit(); 40 | break; 41 | } 42 | case '\"': 43 | { 44 | if (!TryLexString(stream, out Token str, out LexerError error)) 45 | { 46 | return error; 47 | } 48 | tokens.Add(str); 49 | stream.Commit(); 50 | break; 51 | } 52 | case '\'': 53 | { 54 | if (!TryLexChar(stream, out Token chr, out LexerError error)) 55 | { 56 | return error; 57 | } 58 | tokens.Add(chr); 59 | stream.Commit(); 60 | break; 61 | } 62 | case '-' when stream.Peek() is >= '0' and <= '9': 63 | case >= '0' and <= '9': 64 | { 65 | if (!TryLexNumber(stream, out Token number, out LexerError error)) 66 | { 67 | return error; 68 | } 69 | tokens.Add(number); 70 | stream.Commit(); 71 | break; 72 | } 73 | case '_' or (>= 'A' and <= 'Z') or (>= 'a' and <= 'z'): 74 | { 75 | if (!TryLexIdentifier(stream, out Token id, out LexerError error)) 76 | { 77 | return error; 78 | } 79 | tokens.Add(id); 80 | stream.Commit(); 81 | break; 82 | } 83 | case ' ' or '\t' or '\r' or '\n': 84 | stream.Commit(); 85 | continue; 86 | default: 87 | { 88 | threeCharBuf[0] = current; 89 | threeCharBuf[1] = stream.Peek() ?? '\0'; 90 | threeCharBuf[2] = stream.Peek(2) ?? '\0'; 91 | (int count, TokenType type) = threeCharBuf switch 92 | { 93 | // 3 chars 94 | ['!', '>', '>'] => (3, TokenType.ERROR_MAP), 95 | ['!', '?', '?'] => (3, TokenType.ERROR_DEFAULT), 96 | // 2 chars 97 | ['?', '?', _] => (2, TokenType.DEFAULT), 98 | ['?', '.', _] => (2, TokenType.VALUE_CHAIN), 99 | ['!', '.', _] => (2, TokenType.ERROR_CHAIN), 100 | ['!', '=', _] => (2, TokenType.NOT_EQUALS), 101 | ['=', '=', _] => (2, TokenType.EQUALS), 102 | ['>', '=', _] => (2, TokenType.GREATER_THAN_OR_EQUAL), 103 | ['>', '>', _] => (2, TokenType.BIT_RIGHT), 104 | ['<', '=', _] => (2, TokenType.LESS_THAN_OR_EQUAL), 105 | ['<', '<', _] => (2, TokenType.BIT_LEFT), 106 | ['=', '>', _] => (2, TokenType.LAMBDA), 107 | ['+', '+', _] => (2, TokenType.INCREMENT), 108 | ['-', '-', _] => (2, TokenType.DECREMENT), 109 | ['&', '&', _] => (2, TokenType.BOOL_AND), 110 | ['|', '|', _] => (2, TokenType.BOOL_OR), 111 | ['^', '^', _] => (2, TokenType.BOOL_XOR), 112 | // 1 char 113 | ['>', _, _] => (1, TokenType.GREATER_THAN), 114 | ['<', _, _] => (1, TokenType.LESS_THAN), 115 | ['!', _, _] => (1, TokenType.BOOL_NOT), 116 | ['=', _, _] => (1, TokenType.ASSIGNMENT), 117 | ['+', _, _] => (1, TokenType.PLUS), 118 | ['-', _, _] => (1, TokenType.MINUS), 119 | ['&', _, _] => (1, TokenType.BIT_AND), 120 | ['|', _, _] => (1, TokenType.BIT_OR), 121 | ['^', _, _] => (1, TokenType.BIT_XOR), 122 | ['~', _, _] => (1, TokenType.BIT_NOT), 123 | ['.', _, _] => (1, TokenType.DOT), 124 | ['*', _, _] => (1, TokenType.TIMES), 125 | ['/', _, _] => (1, TokenType.DIVIDE), 126 | ['%', _, _] => (1, TokenType.MOD), 127 | [';', _, _] => (1, TokenType.SEMICOLON), 128 | ['(', _, _] => (1, TokenType.OPEN_PAREN), 129 | [')', _, _] => (1, TokenType.CLOSE_PAREN), 130 | ['[', _, _] => (1, TokenType.OPEN_BRACKET), 131 | [']', _, _] => (1, TokenType.CLOSE_BRACKET), 132 | ['{', _, _] => (1, TokenType.OPEN_BRACE), 133 | ['}', _, _] => (1, TokenType.CLOSE_BRACE), 134 | _ => (0, default) 135 | }; 136 | if (count == 0) 137 | { 138 | return new LexerError(LexerErrorType.INVALID_CHAR, new(), 1); 139 | } 140 | tokens.Add(new Token(type, new(threeCharBuf[0..count]), new(stream.Line, stream.Column))); 141 | // Eat extra chars 142 | for (int i = 1; i < count; i++) 143 | { 144 | _ = stream.Next(); 145 | } 146 | stream.Commit(); 147 | break; 148 | } 149 | } 150 | } 151 | 152 | return new(tokens); 153 | } 154 | 155 | private static bool TryLexIdentifier(TransactionalCharStream stream, out Token id, out LexerError error) 156 | { 157 | int startLine = stream.Line, startCol = stream.Column; // pos of first char 158 | id = default; 159 | error = default; 160 | // Start with first char 161 | StringBuilder sb = new(stream.Peek(0).ToString()); 162 | char c = stream.Peek() ?? '\0'; 163 | while (!stream.AtEnd && c is '_' or (>= 'A' and <= 'Z') or (>= 'a' and <= 'z') or (>= '0' and <= '9')) 164 | { 165 | c = stream.Next(); 166 | _ = sb.Append(c); 167 | } 168 | string s = sb.ToString(); 169 | id = new(s switch 170 | { 171 | "true" => TokenType.TRUE, 172 | "false" => TokenType.FALSE, 173 | "empty" => TokenType.EMPTY, 174 | "if" => TokenType.IF, 175 | "else" => TokenType.ELSE, 176 | "while" => TokenType.WHILE, 177 | "function" => TokenType.FUNCTION, 178 | "_" => TokenType.CATCH_ALL, 179 | _ => TokenType.IDENFITIER 180 | }, s, new(startLine, startCol)); 181 | return true; 182 | } 183 | 184 | private static bool TryLexString(TransactionalCharStream stream, out Token str, out LexerError error) 185 | { 186 | int startLine = stream.Line, startCol = stream.Column; // pos of first " 187 | error = default; 188 | str = default; 189 | StringBuilder sb = new(); 190 | bool closed = false; 191 | int count = 0; 192 | while (!stream.AtEnd) 193 | { 194 | char c = stream.Next(); 195 | count++; 196 | if (c == '"') 197 | { 198 | closed = true; 199 | break; 200 | } 201 | else if (c == '\\') 202 | { 203 | if (!TryLexEscapeSequence(stream, out string esc)) 204 | { 205 | error = new(LexerErrorType.INVALID_ESCAPE_SEQUENCE, new(stream.Line, stream.Column), esc.Length + 1, esc); 206 | return false; 207 | } 208 | else 209 | { 210 | _ = sb.Append(esc); 211 | } 212 | } 213 | else 214 | { 215 | _ = sb.Append(c); 216 | } 217 | } 218 | if (!closed) 219 | { 220 | error = new(LexerErrorType.UNCLOSED_STRING, new(startLine, startCol), count + 1); 221 | return false; 222 | } 223 | str = new(TokenType.STRING, sb.ToString(), new(startLine, startCol)); 224 | return true; 225 | } 226 | 227 | private static bool TryLexChar(TransactionalCharStream stream, out Token token, out LexerError error) 228 | { 229 | int startLine = stream.Line, startCol = stream.Column; // pos of first ' 230 | token = default; 231 | error = default; 232 | if (stream.AtEnd) 233 | { 234 | error = new(LexerErrorType.UNCLOSED_CHAR, new(startLine, startCol), 1); 235 | return false; 236 | } 237 | char c = stream.Next(); 238 | switch (c) 239 | { 240 | case '\'': 241 | error = new(LexerErrorType.INVALID_CHAR_LITERAL, new(startLine, startCol), 2); 242 | return false; 243 | case '\\': 244 | if (!TryLexEscapeSequence(stream, out string esc)) 245 | { 246 | startCol++; 247 | error = new(LexerErrorType.INVALID_ESCAPE_SEQUENCE, new(startLine, startCol), stream.Column - startCol, esc); 248 | return false; 249 | } 250 | token = new(TokenType.CHAR, esc, new(startLine, startCol)); 251 | break; 252 | default: 253 | token = new(TokenType.CHAR, c.ToString(), new(startLine, startCol)); 254 | break; 255 | } 256 | if (stream.Next() != '\'') 257 | { 258 | error = new(LexerErrorType.UNCLOSED_CHAR, new(startLine, startCol), token.Value.Length + 1); 259 | return false; 260 | } 261 | return true; 262 | } 263 | 264 | private static bool TryLexEscapeSequence(TransactionalCharStream stream, out string esc) 265 | { 266 | int startLine = stream.Line, startCol = stream.Column; // pos of \ 267 | esc = string.Empty; 268 | char c = stream.Next(); 269 | bool r = false; 270 | (esc, r) = c switch 271 | { 272 | '\'' => ("'", true), 273 | '"' => ("\"", true), 274 | 'n' => ("\n", true), 275 | 't' => ("\t", true), 276 | 'r' => ("\r", true), 277 | '\\' => ("\\", true), 278 | '0' => ("\0", true), 279 | _ => (string.Empty, false) 280 | }; 281 | if (c == 'u') 282 | { 283 | char? n1 = stream.Peek(1); 284 | char? n2 = stream.Peek(2); 285 | char? n3 = stream.Peek(3); 286 | char? n4 = stream.Peek(4); 287 | esc = $"\\u{n1?.ToString() ?? string.Empty}{n2?.ToString() ?? string.Empty}{n3?.ToString() ?? string.Empty}{n4?.ToString() ?? string.Empty}"; 288 | Span chars = stackalloc char?[] { n1, n2, n3, n4 }; 289 | foreach (char? i in chars) 290 | { 291 | if (n1 is (not >= '0' or not <= '9') and (not >= 'A' or not <= 'F') and (not >= 'a' or not <= 'f')) 292 | { 293 | return false; 294 | } 295 | } 296 | const int OFFSET = 'A' - '9' - 1; 297 | n1 ??= '\0'; 298 | n2 ??= '\0'; 299 | n3 ??= '\0'; 300 | n4 ??= '\0'; 301 | int d1 = (n1.Value >= 'A' ? n1.Value - OFFSET : n1.Value) - '0'; 302 | int d2 = (n2.Value >= 'A' ? n2.Value - OFFSET : n2.Value) - '0'; 303 | int d3 = (n3.Value >= 'A' ? n3.Value - OFFSET : n3.Value) - '0'; 304 | int d4 = (n4.Value >= 'A' ? n4.Value - OFFSET : n4.Value) - '0'; 305 | int h = d4 | (d3 << 4) | (d2 << 8) | (d1 << 12); 306 | Span bytes = stackalloc byte[4]; 307 | switch (h) 308 | { 309 | case <= 0x7F: 310 | bytes = bytes[0..1]; 311 | bytes[0] = (byte)(h & 0x7F); 312 | break; 313 | case <= 0x7FF: 314 | bytes = bytes[0..2]; 315 | bytes[0] |= 0b10000000; 316 | bytes[0] |= (byte)(h & 0b00111111); 317 | bytes[1] |= 0b11000000; 318 | bytes[1] |= (byte)((h >> 6) & 0b00011111); 319 | break; 320 | case <= 0xFFFF: 321 | bytes = bytes[0..3]; 322 | bytes[0] |= 0b10000000; 323 | bytes[0] |= (byte)(h & 0b00111111); 324 | bytes[1] |= 0b10000000; 325 | bytes[1] |= (byte)((h >> 6) & 0b00111111); 326 | bytes[2] |= 0b11100000; 327 | bytes[2] |= (byte)((h >> 12) & 0b00001111); 328 | break; 329 | default: 330 | return false; 331 | } 332 | bytes.Reverse(); 333 | try 334 | { 335 | esc = Encoding.UTF8.GetString(bytes); 336 | // eat escape sequence 337 | _ = stream.Next(); 338 | _ = stream.Next(); 339 | _ = stream.Next(); 340 | _ = stream.Next(); 341 | return true; 342 | } 343 | catch 344 | { 345 | return false; 346 | } 347 | } 348 | return r; 349 | } 350 | 351 | private static Token LexSingleLineComment(TransactionalCharStream stream) 352 | { 353 | int startLine = stream.Line, startCol = stream.Column; 354 | StringBuilder sb = new(); 355 | char current = '\0'; 356 | while (!stream.AtEnd && current is not '\n') 357 | { 358 | current = stream.Next(); 359 | _ = sb.Append(current); 360 | } 361 | _ = sb.Remove(sb.Length - 1, 1); 362 | string s = sb.ToString(); 363 | return new(TokenType.SINGLE_LINE_COMMENT, s, new(startLine, startCol)); 364 | } 365 | 366 | private static bool TryLexMultiLineComment(TransactionalCharStream stream, out Token token, out LexerError error) 367 | { 368 | int startLine = stream.Line, startCol = stream.Column; 369 | token = default; 370 | error = default; 371 | StringBuilder sb = new(); 372 | bool closed = false; 373 | while (!stream.AtEnd) 374 | { 375 | char c = stream.Next(); 376 | char c2 = stream.Peek() ?? '\0'; 377 | if (c == '*' && c2 == '/') 378 | { 379 | closed = true; 380 | break; 381 | } 382 | else 383 | { 384 | _ = sb.Append(c); 385 | } 386 | } 387 | if (!closed) 388 | { 389 | error = new(LexerErrorType.UNCLOSED_MULTILINE_COMMENT, new(startLine, startCol), 2); 390 | return false; 391 | } 392 | _ = sb.Remove(sb.Length - 1, 1); // remove * (we break when we are at * and see /) 393 | // Eat second / 394 | _ = stream.Next(); 395 | string s = sb.ToString(); 396 | token = new(TokenType.MULTI_LINE_COMMENT, s, new(startLine, startCol)); 397 | return true; 398 | } 399 | 400 | private static bool TryLexNumber(TransactionalCharStream stream, out Token number, out LexerError error) 401 | { 402 | int startLine = stream.Line, startCol = stream.Column; 403 | number = default; 404 | error = default; 405 | StringBuilder sb = new(); 406 | _ = sb.Append(stream.Peek(0)!.Value); 407 | // Assume s32 408 | bool isInt = true; 409 | int size = 32; 410 | bool signed = true; 411 | int? dotPos = default; 412 | while (!stream.AtEnd) 413 | { 414 | char c = stream.Next(); 415 | switch (c) 416 | { 417 | case >= '0' and <= '9': 418 | _ = sb.Append(c); 419 | break; 420 | case '.': 421 | isInt = false; 422 | if (dotPos.HasValue) 423 | { 424 | error = new(LexerErrorType.MULTIPLE_DECIMAL_POINTS, new(stream.Line, stream.Column), 1); 425 | return false; 426 | } 427 | dotPos = stream.Column; 428 | break; 429 | case 'u' or 's': 430 | { 431 | signed = c is 's'; 432 | isInt = true; 433 | char? next1 = stream.Peek(1); 434 | char? next2 = stream.Peek(2); 435 | if (next1 is '8' && (next2 ?? '\0') is < '0' or > '9') 436 | { 437 | size = 8; 438 | _ = stream.Next(); 439 | } 440 | else if (next1 is '1' && next2 is '6') 441 | { 442 | size = 16; 443 | _ = stream.Next(); 444 | _ = stream.Next(); 445 | } 446 | else if (next1 is '3' && next2 is '2') 447 | { 448 | size = 32; 449 | _ = stream.Next(); 450 | _ = stream.Next(); 451 | } 452 | else if (next1 is '6' && next2 is '4') 453 | { 454 | size = 64; 455 | _ = stream.Next(); 456 | _ = stream.Next(); 457 | } 458 | else 459 | { 460 | error = new( 461 | LexerErrorType.INVALID_NUMBER_SIZE, 462 | new(), 463 | (next1.HasValue ? 1 : 0) + (next2.HasValue ? 1 : 0), 464 | $"{c}{next1?.ToString() ?? string.Empty}{next2?.ToString() ?? string.Empty}"); 465 | return false; 466 | } 467 | break; 468 | } 469 | case 'f': 470 | { 471 | isInt = false; 472 | signed = true; 473 | char? next1 = stream.Peek(1); 474 | char? next2 = stream.Peek(2); 475 | if (next1 is '3' && next2 is '2') { } 476 | else if (next1 is '6' && next2 is '4') { } 477 | else 478 | { 479 | error = new( 480 | LexerErrorType.INVALID_NUMBER_SIZE, 481 | new(), 482 | (next1.HasValue ? 1 : 0) + (next2.HasValue ? 1 : 0), 483 | $"{c}{next1?.ToString() ?? string.Empty}{next2?.ToString() ?? string.Empty}"); 484 | return false; 485 | } 486 | break; 487 | } 488 | default: 489 | error = new(LexerErrorType.INVALID_CHAR, new(stream.Line, stream.Column), 1, c.ToString()); 490 | return false; 491 | } 492 | } 493 | if (isInt && dotPos.HasValue) 494 | { 495 | error = new LexerError(LexerErrorType.INTEGER_WITH_DECIMAL_POINT, new(startLine, dotPos.Value), 1); 496 | return false; 497 | } 498 | _ = sb.Append(isInt ? (signed ? 's' : 'u') : 'f'); 499 | _ = sb.Append(size); 500 | if (sb.Length > 0 && sb[0] == '-' && !signed) 501 | { 502 | error = new LexerError(LexerErrorType.NEGATIVE_UINT, number.Location, 1); 503 | return false; 504 | } 505 | number = new(isInt ? TokenType.INTEGER : TokenType.FLOAT, sb.ToString(), new(startLine, startCol)); 506 | return true; 507 | } 508 | } -------------------------------------------------------------------------------- /7Sharp.Compiler/Lexing/LexerError.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler.Lexing; 2 | 3 | public readonly record struct LexerError(LexerErrorType Type, FileLocation Location, int Length, string? Data = null); 4 | 5 | public enum LexerErrorType 6 | { 7 | INVALID_CHAR, 8 | MISSING_SEMICOLON, 9 | MISSING_OPEN_PAREN, 10 | MISSING_CLOSE_PAREN, 11 | MISSING_OPEN_BRACE, 12 | MISSING_CLOSE_BRACE, 13 | MISSING_OPEN_BRACKET, 14 | MISSING_CLOSE_BRACKET, 15 | UNCLOSED_MULTILINE_COMMENT, 16 | INTEGER_WITH_DECIMAL_POINT, 17 | INVALID_NUMBER_SIZE, 18 | MULTIPLE_DECIMAL_POINTS, 19 | NEGATIVE_UINT, 20 | INVALID_CHAR_LITERAL, 21 | INVALID_ESCAPE_SEQUENCE, 22 | UNCLOSED_CHAR, 23 | UNCLOSED_STRING, 24 | } -------------------------------------------------------------------------------- /7Sharp.Compiler/Lexing/LexerResult.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler.Lexing; 2 | 3 | public sealed class LexerResult 4 | { 5 | public bool IsOk { get; } 6 | public IReadOnlyList Tokens => IsOk ? tokens : throw new InvalidOperationException("LexerResult is not OK"); 7 | public LexerError Error => !IsOk ? error : throw new InvalidOperationException("LexerResult is OK"); 8 | 9 | private readonly LexerError error; 10 | private readonly IReadOnlyList tokens; 11 | 12 | public LexerResult(IReadOnlyList tokens) 13 | { 14 | this.tokens = tokens; 15 | IsOk = true; 16 | } 17 | 18 | public LexerResult(LexerError error) 19 | { 20 | this.error = error; 21 | IsOk = false; 22 | tokens = Array.Empty(); 23 | } 24 | 25 | public static implicit operator bool(LexerResult result) => result.IsOk; 26 | 27 | public static implicit operator LexerResult(LexerError error) => new(error); 28 | } 29 | -------------------------------------------------------------------------------- /7Sharp.Compiler/Lexing/Token.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler.Lexing; 2 | 3 | public readonly record struct Token(TokenType Type, string Value, FileLocation Location); 4 | -------------------------------------------------------------------------------- /7Sharp.Compiler/Lexing/TokenType.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler.Lexing; 2 | 3 | public enum TokenType 4 | { 5 | // Comments 6 | // "// ..." or "/* ... */" 7 | SINGLE_LINE_COMMENT, 8 | MULTI_LINE_COMMENT, 9 | 10 | SEMICOLON, 11 | IDENFITIER, 12 | 13 | // Delimeters 14 | // () 15 | OPEN_PAREN, 16 | CLOSE_PAREN, 17 | // {} 18 | OPEN_BRACE, 19 | CLOSE_BRACE, 20 | // [] 21 | OPEN_BRACKET, 22 | CLOSE_BRACKET, 23 | 24 | // Literals 25 | TRUE, 26 | FALSE, 27 | INTEGER, 28 | FLOAT, 29 | CHAR, 30 | STRING, 31 | EMPTY, 32 | 33 | // Keywords 34 | FUNCTION, 35 | IF, 36 | ELSE, 37 | WHILE, 38 | 39 | // Operators 40 | // Math 41 | PLUS, 42 | MINUS, 43 | TIMES, 44 | DIVIDE, 45 | MOD, 46 | INCREMENT, 47 | DECREMENT, 48 | // Bool 49 | EQUALS, 50 | NOT_EQUALS, 51 | BOOL_AND, 52 | BOOL_OR, 53 | BOOL_XOR, 54 | BOOL_NOT, 55 | GREATER_THAN, 56 | LESS_THAN, 57 | GREATER_THAN_OR_EQUAL, 58 | LESS_THAN_OR_EQUAL, 59 | // Bit 60 | BIT_AND, 61 | BIT_OR, 62 | BIT_XOR, 63 | BIT_NOT, 64 | BIT_LEFT, 65 | BIT_RIGHT, 66 | // Other 67 | ASSIGNMENT, // = 68 | DOT, // . 69 | DEFAULT, // ?? 70 | ERROR_MAP, // !>> 71 | ERROR_DEFAULT, // !?? 72 | VALUE_CHAIN, // ?. 73 | ERROR_CHAIN, // !. 74 | CATCH_ALL, // _ 75 | LAMBDA, // => 76 | } 77 | -------------------------------------------------------------------------------- /7Sharp.Compiler/TransactionalCharStream.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler; 2 | 3 | // A TranscationalStream that keeps track of lines and columns 4 | public sealed class TransactionalCharStream 5 | { 6 | public bool AtEnd => stream.AtEnd; 7 | public int Line { get; private set; } = 1; 8 | public int Column { get; private set; } = 1; 9 | 10 | private readonly TransactionalStream stream; 11 | private int committedLine = 1, committedCol = 1; 12 | 13 | public TransactionalCharStream(string s) 14 | { 15 | stream = new(s?.ToArray()!); 16 | } 17 | 18 | public void Rollback() 19 | { 20 | stream.Rollback(); 21 | Line = committedLine; 22 | Column = committedCol; 23 | } 24 | 25 | public void Commit() 26 | { 27 | stream.Commit(); 28 | committedLine = Line; 29 | committedCol = Column; 30 | } 31 | 32 | public char Next() 33 | { 34 | Column++; 35 | char c = stream.Next(); 36 | if (c is '\n') 37 | { 38 | Column = 1; 39 | Line++; 40 | } 41 | return c; 42 | } 43 | 44 | public char? PeekPrev(int count = -1) => stream.PeekPrev(count); 45 | public char? Peek(int count = 1) => stream.Peek(count); 46 | } -------------------------------------------------------------------------------- /7Sharp.Compiler/TransactionalStream.cs: -------------------------------------------------------------------------------- 1 | namespace _7Sharp.Compiler; 2 | 3 | public sealed class TransactionalStream 4 | { 5 | public bool AtEnd => index >= list.Count; 6 | 7 | private readonly IReadOnlyList list; 8 | private int committedIndex = 0; 9 | private int index = 0; 10 | 11 | public TransactionalStream(IReadOnlyList list) 12 | { 13 | ArgumentNullException.ThrowIfNull(list); 14 | this.list = list; 15 | } 16 | 17 | public void Rollback() => index = committedIndex; 18 | public void Commit() => committedIndex = index; 19 | 20 | public T? PeekPrev(int count = 1) 21 | { 22 | count--; 23 | return index >= 0 && index < list.Count - count ? list[index - count] : default; 24 | } 25 | 26 | public T? Peek(int count = 1) 27 | { 28 | count--; 29 | return index >= 0 && index < list.Count - count ? list[index + count] : default; 30 | } 31 | 32 | public T Next() => list[index++]; 33 | } 34 | -------------------------------------------------------------------------------- /7Sharp.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33424.131 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "7Sharp", "7Sharp\7Sharp.csproj", "{F603C8F7-41E9-4024-89D9-CDBEADCB4125}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "7Sharp.Compiler", "7Sharp.Compiler\7Sharp.Compiler.csproj", "{E2890360-E2D7-41E9-BFAC-94AE8DED378B}" 9 | EndProject 10 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "test", "test", "{70BF5B41-D9DD-4532-B397-048624E96FB9}" 11 | EndProject 12 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "7Sharp.Compiler.Tests", "7Sharp.Compiler.Tests\7Sharp.Compiler.Tests.csproj", "{BA04BE96-A8AE-4295-8F93-946DE609078E}" 13 | EndProject 14 | Global 15 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 16 | Debug|Any CPU = Debug|Any CPU 17 | Release|Any CPU = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 20 | {F603C8F7-41E9-4024-89D9-CDBEADCB4125}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 21 | {F603C8F7-41E9-4024-89D9-CDBEADCB4125}.Debug|Any CPU.Build.0 = Debug|Any CPU 22 | {F603C8F7-41E9-4024-89D9-CDBEADCB4125}.Release|Any CPU.ActiveCfg = Release|Any CPU 23 | {F603C8F7-41E9-4024-89D9-CDBEADCB4125}.Release|Any CPU.Build.0 = Release|Any CPU 24 | {E2890360-E2D7-41E9-BFAC-94AE8DED378B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 25 | {E2890360-E2D7-41E9-BFAC-94AE8DED378B}.Debug|Any CPU.Build.0 = Debug|Any CPU 26 | {E2890360-E2D7-41E9-BFAC-94AE8DED378B}.Release|Any CPU.ActiveCfg = Release|Any CPU 27 | {E2890360-E2D7-41E9-BFAC-94AE8DED378B}.Release|Any CPU.Build.0 = Release|Any CPU 28 | {BA04BE96-A8AE-4295-8F93-946DE609078E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 29 | {BA04BE96-A8AE-4295-8F93-946DE609078E}.Debug|Any CPU.Build.0 = Debug|Any CPU 30 | {BA04BE96-A8AE-4295-8F93-946DE609078E}.Release|Any CPU.ActiveCfg = Release|Any CPU 31 | {BA04BE96-A8AE-4295-8F93-946DE609078E}.Release|Any CPU.Build.0 = Release|Any CPU 32 | EndGlobalSection 33 | GlobalSection(SolutionProperties) = preSolution 34 | HideSolutionNode = FALSE 35 | EndGlobalSection 36 | GlobalSection(NestedProjects) = preSolution 37 | {BA04BE96-A8AE-4295-8F93-946DE609078E} = {70BF5B41-D9DD-4532-B397-048624E96FB9} 38 | EndGlobalSection 39 | GlobalSection(ExtensibilityGlobals) = postSolution 40 | SolutionGuid = {A1E58485-C259-471E-B708-C3A9377E8D2A} 41 | EndGlobalSection 42 | EndGlobal 43 | -------------------------------------------------------------------------------- /7Sharp/7Sharp.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | _7Sharp 7 | enable 8 | enable 9 | 10 | 11 | 12 | -------------------------------------------------------------------------------- /7Sharp/Editor/Editor.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | namespace _7Sharp.Editor; 4 | 5 | public class Editor 6 | { 7 | private readonly List lines = new(); 8 | private int cursorLine, cursorCol, hScroll, vScroll; 9 | 10 | public Editor(string text) => lines.AddRange(text 11 | .Split('\n') 12 | .Select(x => x.Length > 0 && x[^1] == '\r' ? x[..^1] : x) 13 | .Select(x => 14 | { 15 | StringBuilder sb = new(); 16 | _ = sb.Append(x); 17 | return sb; 18 | })); 19 | 20 | public string Edit() 21 | { 22 | Console.Clear(); 23 | Render(); 24 | Console.CancelKeyPress += OnControlC; 25 | bool editing = true; 26 | while (editing) 27 | { 28 | int numLines = lines.Count; 29 | (int w, int h) lastSize = (Console.WindowWidth, Console.WindowHeight); 30 | ConsoleKeyInfo key = Console.ReadKey(true); 31 | switch (key.Key) 32 | { 33 | case ConsoleKey.Backspace: 34 | case ConsoleKey.LeftArrow: 35 | cursorCol--; 36 | if (cursorCol < 0) 37 | { 38 | cursorCol = 0; 39 | if (cursorLine > 0) 40 | { 41 | cursorLine--; 42 | cursorCol = lines[cursorLine].Length; 43 | if (key.Key == ConsoleKey.Backspace) 44 | { 45 | _ = lines[cursorLine].Append(lines[cursorLine + 1]); 46 | lines.RemoveAt(cursorLine + 1); 47 | } 48 | } 49 | } 50 | else if (key.Key == ConsoleKey.Backspace) 51 | { 52 | _ = lines[cursorLine].Remove(lines[cursorLine].Length - 1, 1); 53 | } 54 | break; 55 | case ConsoleKey.RightArrow: 56 | cursorCol++; 57 | if (cursorCol > lines[cursorLine].Length) 58 | { 59 | if (cursorLine < lines.Count - 1) 60 | { 61 | cursorCol = 0; 62 | cursorLine++; 63 | } 64 | else 65 | { 66 | cursorCol = lines[cursorLine].Length; 67 | } 68 | } 69 | break; 70 | case ConsoleKey.Delete: 71 | if (cursorCol < lines[cursorLine].Length) 72 | { 73 | _ = lines[cursorLine].Remove(cursorCol, 1); 74 | } 75 | else if (cursorLine < lines.Count - 1) 76 | { 77 | _ = lines[cursorLine].Append(lines[cursorLine + 1]); 78 | lines.RemoveAt(cursorLine); 79 | } 80 | break; 81 | case ConsoleKey.Home: 82 | cursorCol = 0; 83 | break; 84 | case ConsoleKey.End: 85 | cursorCol = lines[cursorLine].Length; 86 | break; 87 | case ConsoleKey.UpArrow: 88 | if (cursorLine > 0) 89 | { 90 | cursorLine--; 91 | cursorCol = Math.Min(cursorCol, lines[cursorLine].Length); 92 | } 93 | break; 94 | case ConsoleKey.DownArrow: 95 | if (cursorLine < lines.Count - 1) 96 | { 97 | cursorLine++; 98 | cursorCol = Math.Min(cursorCol, lines[cursorLine].Length); 99 | } 100 | break; 101 | case ConsoleKey.Tab: 102 | _ = lines[cursorLine].Append(" "); 103 | cursorCol += 4; 104 | break; 105 | case ConsoleKey.Enter: 106 | cursorLine++; 107 | cursorCol = 0; 108 | lines.Insert(cursorLine, new()); 109 | break; 110 | case ConsoleKey.S when key.Modifiers == ConsoleModifiers.Control: 111 | editing = false; 112 | break; 113 | default: 114 | if (key.KeyChar is >= ' ' and <= '~') 115 | { 116 | _ = lines[cursorLine].Insert(cursorCol, key.KeyChar); 117 | cursorCol++; 118 | } 119 | break; 120 | } 121 | if (lastSize != (Console.WindowWidth, Console.WindowHeight)) 122 | { 123 | Console.Clear(); 124 | } 125 | Scroll(); 126 | Render(lines.Count - numLines); 127 | } 128 | Console.CancelKeyPress -= OnControlC; 129 | Console.Clear(); 130 | return string.Join("\n", lines.Select(sb => sb.ToString())); 131 | } 132 | 133 | private void Render(int deltaNumLines = 0) 134 | { 135 | string emtpyLine = new(' ', Console.WindowWidth); 136 | // Add 1 if line gets deleted to clear the line 137 | for (int y = 0; y < Math.Min(Console.WindowHeight - 2, lines.Count + (deltaNumLines < 0 ? 1 : 0)); y++) 138 | { 139 | int i = y + vScroll; 140 | Console.SetCursorPosition(0, y); 141 | if (i >= 0 && i < lines.Count) 142 | { 143 | string s = lines[i].ToString(); 144 | s = s[hScroll..]; 145 | s = s.PadRight(Console.WindowWidth); 146 | Console.Write(s); 147 | } 148 | else 149 | { 150 | Console.Write(emtpyLine); 151 | } 152 | } 153 | Console.SetCursorPosition(0, Console.WindowHeight - 2); 154 | string dashLine = new('-', Console.WindowWidth); 155 | Console.Write(dashLine); 156 | Console.Write("Ctrl+S: Exit"); 157 | Console.SetCursorPosition(cursorCol - hScroll, cursorLine - vScroll); 158 | } 159 | 160 | private void Scroll() 161 | { 162 | while (cursorLine - vScroll < 0) 163 | { 164 | vScroll--; 165 | } 166 | while (cursorLine - vScroll >= Console.WindowHeight - 2) 167 | { 168 | vScroll++; 169 | } 170 | while (cursorCol - hScroll < 0) 171 | { 172 | hScroll--; 173 | } 174 | while (cursorCol - hScroll >= Console.WindowWidth) 175 | { 176 | hScroll++; 177 | } 178 | } 179 | 180 | // Cancel Control+C killing program 181 | private static void OnControlC(object? sender, ConsoleCancelEventArgs e) => e.Cancel = true; 182 | } 183 | -------------------------------------------------------------------------------- /7Sharp/Program.cs: -------------------------------------------------------------------------------- 1 | using _7Sharp.Editor; 2 | using System.Text; 3 | 4 | string editorText = string.Empty; 5 | 6 | while (true) 7 | { 8 | WriteColor("7", ConsoleColor.Yellow); 9 | WriteColor("Sharp", ConsoleColor.Green); 10 | WriteColor("> ", ConsoleColor.Cyan); 11 | string? line = Console.ReadLine(); 12 | if (line is null) 13 | { 14 | break; 15 | } 16 | string[] split = Split(line); 17 | if (split.Length < 1) 18 | { 19 | continue; 20 | } 21 | switch (split[0].ToLower()) 22 | { 23 | case "edit": 24 | case "editor": 25 | editorText = new Editor(editorText).Edit(); 26 | break; 27 | case "exit": 28 | return; 29 | case "help": 30 | Console.WriteLine("help - show this message"); 31 | Console.WriteLine("exit - exit the CLI"); 32 | break; 33 | default: 34 | WriteLineColor("Invalid command", ConsoleColor.Red); 35 | break; 36 | } 37 | } 38 | 39 | static string[] Split(string s) 40 | { 41 | List result = new(); 42 | StringBuilder sb = new(); 43 | Queue chars = new(s); 44 | bool inString = false; 45 | while (chars.TryDequeue(out char c)) 46 | { 47 | if (inString && c == '\\' && chars.TryPeek(out char next) && next == '\"') 48 | { 49 | sb.Append('\"'); 50 | _ = chars.Dequeue(); // Eat " 51 | } 52 | else if (c == '\"') 53 | { 54 | inString = !inString; 55 | } 56 | else if (c == ' ' && !inString && sb.Length > 0) 57 | { 58 | result.Add(sb.ToString()); 59 | sb.Clear(); 60 | } 61 | else 62 | { 63 | sb.Append(c); 64 | } 65 | } 66 | if (sb.Length > 0) 67 | { 68 | result.Add(sb.ToString()); 69 | } 70 | return result.ToArray(); 71 | } 72 | 73 | static void WriteLineColor(string str, ConsoleColor fg, ConsoleColor bg = ConsoleColor.Black) 74 | { 75 | Console.BackgroundColor = bg; 76 | Console.ForegroundColor = fg; 77 | Console.WriteLine(str); 78 | Console.ResetColor(); 79 | } 80 | 81 | static void WriteColor(string str, ConsoleColor fg, ConsoleColor bg = ConsoleColor.Black) 82 | { 83 | Console.BackgroundColor = bg; 84 | Console.ForegroundColor = fg; 85 | Console.Write(str); 86 | Console.ResetColor(); 87 | } --------------------------------------------------------------------------------