polserver/pol-core/bscript/compiler/file/SourceFile.cpp
turleypol 7627e3d353
"Preview/Initial"- Version sourcecode formatting feature (#626)
* Squash only prettify changes from escript_formating_try

* support of "format-off" / "format-on" comments to mark areas without
formatting

* fix typo

* added FormatterIdentLevel, FormatterMergeEmptyLines cfg entry
better line splits for dicts/arrays

* added several spacing options. the current setting list is now:
//LineWidth
FormatterLineWidth 80
// keep original keyword spelling
FormatterKeepKeywords 0
// number of spaces for ident
FormatterIdentLevel 2
// multiple newlines get merged to a single
FormatterMergeEmptyLines 1
// space between emtpy parenthesis eg foo() vs foo( )
FormatterEmptyParenthesisSpacing 0
// space between emtpy brackets eg struct{} vs struct{ }
FormatterEmptyBracketSpacing 0
// space after/before parenthesis in conditionals
// eg if ( true ) vs if (true)
FormatterConditionalParenthesisSpacing 1
// space after/before parenthesis
// eg foo( true ) vs foo(true)
FormatterParenthesisSpacing 1
// space after/before brackets
// eg array{ true } vs array{true}
FormatterBracketSpacing 1
// add space after delimiter comma or semi in for loops
// eg {1, 2, 3} vs {1,2,3}
FormatterDelimiterSpacing 1
// add space around assignment
// eg a := 1; vs a:=1;
FormatterAssignmentSpacing 1
// add space around comparison
// eg a == 1 vs a==1
FormatterComparisonSpacing 1
// add space around operations
// eg a + 1 vs a+1
FormatterOperatorSpacing 1
// use \r\n as newline instead of \n
FormatterWindowsLineEndings 0

* added tab support
// use tabs instead of spaces
FormatterUseTabs 0
// tab width
FormatterTabWidth 4

* extended example ecompile.cfg with formatter settings

* cleanup

* program args comma is optional...
fixed line comments in group splitting

* since tokenids are now correct no more guessing for linecomments needed

* comments use as start tokenid the whitespace token if its on the same
line

* splitted processing from linebuilding

* renamed TokenPart to FmtToken better matches the purpose.
Comments get directly stored as FmtToken
started with a context enum

* better(?) formatting for groups

* fix eof rawlines
added check that all comments/rawlines got parsed

* const correctness

* datatype adapted to antlr

* fixed warnings

* added InsertNewlineAtEOF

* add newline at the end if the original file had one
dont strip comment whitespace if its somejind of "header block"
use the defined lineending for /* */ comments

* docs

* \r\n is default on windows \n otherwise

* fixed warning

---------

Co-authored-by: Kevin Eady <8634912+KevinEady@users.noreply.github.com>
2024-02-26 21:21:44 +01:00

285 lines
7.3 KiB
C++

#include "SourceFile.h"
#include <cstring>
#include "clib/filecont.h"
#include "clib/fileutil.h"
#include "clib/strutil.h"
#include "bscript/compiler/Report.h"
#include "bscript/compiler/file/SourceFileIdentifier.h"
#include "compilercfg.h"
#include <EscriptGrammar/EscriptParserVisitor.h>
using EscriptGrammar::EscriptLexer;
using EscriptGrammar::EscriptParser;
using EscriptGrammar::EscriptParserVisitor;
namespace Pol::Bscript::Compiler
{
bool is_web_script( const char* filename );
std::string preprocess_web_script( const std::string& input );
SourceFile::SourceFile( const std::string& pathname, const std::string& contents, Profile& profile )
: pathname( pathname ),
input( contents ),
conformer( &input ),
lexer( &conformer ),
token_stream( &lexer ),
parser( &token_stream ),
error_listener( pathname, profile ),
compilation_unit( nullptr ),
module_unit( nullptr ),
evaluate_unit( nullptr ),
access_count( 0 )
{
input.name = pathname;
lexer.removeErrorListeners();
lexer.addErrorListener( &error_listener );
parser.removeErrorListeners();
parser.addErrorListener( &error_listener );
}
SourceFile::~SourceFile() = default;
void SourceFile::propagate_errors_to( Report& report, const SourceFileIdentifier& ident )
{
error_listener.propagate_errors_to( report, ident );
}
#if defined( _WIN32 ) || defined( __APPLE__ )
bool SourceFile::enforced_case_sensitivity_mismatch( const SourceLocation& referencing_location,
const std::string& pathname, Report& report )
{
std::string truename = Clib::GetTrueName( pathname.c_str() );
std::string filepart = Clib::GetFilePart( pathname.c_str() );
if ( truename != filepart && Clib::FileExists( pathname ) )
{
if ( compilercfg.ErrorOnFileCaseMissmatch )
{
report.error( referencing_location,
"Case mismatch: \n"
" Specified: {}\n"
" Filesystem: {}",
filepart, truename );
return true;
}
report.warning( referencing_location,
"Case mismatch: \n"
" Specified: {}\n"
" Filesystem: {}",
filepart, truename );
}
return false;
}
#else
bool SourceFile::enforced_case_sensitivity_mismatch( const SourceLocation&, const std::string&,
Report& )
{
return false;
}
#endif
std::shared_ptr<SourceFile> SourceFile::load( const SourceFileIdentifier& ident, Profile& profile,
Report& report )
{
const std::string& pathname = ident.pathname;
try
{
Clib::FileContents fc( pathname.c_str(), true );
std::string contents( fc.contents() );
Clib::sanitizeUnicodeWithIso( &contents );
if ( is_web_script( pathname.c_str() ) )
{
contents = preprocess_web_script( contents );
}
return std::make_shared<SourceFile>( pathname, contents, profile );
}
catch ( ... )
{
report.error( ident, "Unable to read file '{}'.", pathname );
return {};
}
}
EscriptGrammar::EscriptParser::CompilationUnitContext* SourceFile::get_compilation_unit(
Report& report, const SourceFileIdentifier& ident )
{
if ( !compilation_unit )
{
std::lock_guard<std::mutex> guard( mutex );
if ( !compilation_unit )
compilation_unit = parser.compilationUnit();
}
++access_count;
propagate_errors_to( report, ident );
return compilation_unit;
}
EscriptGrammar::EscriptParser::ModuleUnitContext* SourceFile::get_module_unit(
Report& report, const SourceFileIdentifier& ident )
{
if ( !module_unit )
{
std::lock_guard<std::mutex> guard( mutex );
if ( !module_unit )
module_unit = parser.moduleUnit();
}
++access_count;
propagate_errors_to( report, ident );
return module_unit;
}
EscriptGrammar::EscriptParser::EvaluateUnitContext* SourceFile::get_evaluate_unit(
Report& report )
{
if ( !evaluate_unit )
{
std::lock_guard<std::mutex> guard( mutex );
if ( !evaluate_unit )
evaluate_unit = parser.evaluateUnit();
}
++access_count;
propagate_errors_to( report, SourceFileIdentifier( 0, "<eval>" ) );
return evaluate_unit;
}
std::vector<antlr4::Token*> SourceFile::get_hidden_tokens_before( const Position& position )
{
auto tokens = get_all_tokens();
size_t token_index = 0;
for ( const auto& token : tokens )
{
if ( token->getLine() == position.line_number &&
token->getCharPositionInLine() + 1 <= position.character_column &&
token->getCharPositionInLine() + 1 + token->getText().length() >=
position.character_column )
{
break;
}
token_index++;
}
if ( token_index < tokens.size() )
{
return get_hidden_tokens_before( token_index );
}
return std::vector<antlr4::Token*>();
}
std::vector<antlr4::Token*> SourceFile::get_hidden_tokens_before( size_t tokenIndex )
{
return token_stream.getHiddenTokensToLeft( tokenIndex );
}
antlr4::Token* SourceFile::get_token_at( const Position& position )
{
auto tokens = get_all_tokens();
auto result =
std::find_if( tokens.begin(), tokens.end(),
[&]( const auto& token )
{
return token->getLine() == position.line_number &&
token->getCharPositionInLine() + 1 <= position.character_column &&
token->getCharPositionInLine() + 1 + token->getText().length() >=
position.character_column;
} );
if ( result != tokens.end() )
{
return *result;
}
return nullptr;
}
std::vector<antlr4::Token*> SourceFile::get_all_tokens()
{
return token_stream.getTokens();
}
/**
* Given a file name, tells if this is a web script
*/
bool is_web_script( const char* file )
{
const char* ext = strstr( file, ".hsr" );
if ( ext && memcmp( ext, ".hsr", 5 ) == 0 )
return true;
ext = strstr( file, ".asp" );
if ( ext && memcmp( ext, ".asp", 5 ) == 0 )
return true;
return false;
}
/**
* Transforms the raw html page into a script with a single WriteHtml() instruction
*/
std::string preprocess_web_script( const std::string& input )
{
std::string output;
output = "use http;";
output += '\n';
bool reading_html = true;
bool source_is_emit = false;
const char* s = input.c_str();
std::string acc;
while ( *s )
{
if ( reading_html )
{
if ( s[0] == '<' && s[1] == '%' )
{
reading_html = false;
if ( !acc.empty() )
{
output += "WriteHtmlRaw( \"" + acc + "\");\n";
acc = "";
}
s += 2;
source_is_emit = ( s[0] == '=' );
if ( source_is_emit )
{
output += "WriteHtmlRaw( ";
++s;
}
}
else
{
if ( *s == '\"' )
acc += "\\\"";
else if ( *s == '\r' )
;
else if ( *s == '\n' )
acc += "\\n";
else
acc += *s;
++s;
}
}
else
{
if ( s[0] == '%' && s[1] == '>' )
{
reading_html = true;
s += 2;
if ( source_is_emit )
output += " );\n";
}
else
{
output += *s++;
}
}
}
if ( !acc.empty() )
output += "WriteHtmlRaw( \"" + acc + "\");\n";
return output;
}
} // namespace Pol::Bscript::Compiler