summaryrefslogtreecommitdiffstats
path: root/source/slang/preprocessor.cpp
diff options
context:
space:
mode:
authorTim Foley <tfoleyNV@users.noreply.github.com>2019-02-15 09:08:19 -0800
committerGitHub <noreply@github.com>2019-02-15 09:08:19 -0800
commita3fd4e2bc40cfc77db953b14744c30e7a18e7c1d (patch)
tree5c226a6a4304086412c051f642a5f45fb043083c /source/slang/preprocessor.cpp
parent4cd317bcae0a13dc2bbb78448c8d60cd1dcc76bd (diff)
Split front- and back-ends (#846)
* Split front- and back-ends This change is a major refactor of several of the types that provide the behind-the-scenes implementation of the public C API. The goal of this refactor is primarily to allow for future API services that let the user operate both the front- and back-ends of the compiler in a more complex fashion. For example, as user should be able to compile a bunch of source code into modules, look up types, functions, etc. in those modules, specialize generic types/functions to the types they've looked up, and then finally request target code to be gernerated for specialized entry points. The back-end code generation they trigger should re-use the front-end compilation work (parsing, semantic checking, IR generation) that was already performed. The most visible change is that `CompileRequest` has been split up into several smaller types that take responsibility for parts of what it did: * The `Linkage` type owns the storage for `import`ed modules, and well as the `TargetRequest`s that represent code-generation targets. The intention is that an application could use a single `Linkage` for the duration of its runtime (so long as it was okay with the memory usage), so that each `import`ed module only gets loaded once. For now, this type needs to manage the search paths, file system, and source manager, because of its responsibility for loading files. * A `FrontEndCompileRequest` owns the stuff related to parsing, semantic checking, and initial IR generation. This most notably includes the `TranslationUnitRequest`s and the `FrontEndEntryPointRequest`s (which used to be just `EntryPointRequest`s). It's main job is to produce AST and IR modules for each translation unit, and to find and validate the entry points. The front-end request does *not* interact with generic arguments for global or entry-point generic parameters. * The main output of both `import` operations and front-end translation units is the `Module` type, which is just a simple container for both the AST module (to service the reflection/layout APIs, and also for semantic checking of code that `import`s the module) and the IR module (for linking and code generation). This type captures the commonalities between the old `LoadedModule` (which is now just an alias for `Module`) and `TranslationUnitRequest` (which now owns a `Module`). * The secondary output of front-end compilation is a `Program`, which comprises a list of referenced `Module`s and validated `EntryPoint`s that will be used together. Layout and code generation both need a `Program` to tell them what modules and entry points will be used together (we don't want to just code-gen everythin that has ever been loaded into the linakge). The `Program`s created by the front-end do not include generic arguments, so they may provide incomplete layout information and/or be unsuitable for code generation. * A `BackEndCompileRequest` owns stuff related to turning a `Program` into output kernels for the targets of a `Linkage`. Most of the data it owns beyond the `Program` to be compiled is minor, so this is a good candidate for demotion from a heap-allocated object to just a `struct` of options that gets passed around. * The `CompileRequestBase` type is an attempt to wrap up the common functionality of both front-end and back-end compile requests. Most of it is just exposing the availability of a linkage and `DiagnosticSink`, so this type is a good candidate for subsequent removal. The main interesting thing it has is the flags related to dumping and validation of IR, so there is probably a good refactoring still to be made around deciding how options should be handled going forward. * Behind the scenes, the `Program` type is set up to handle some level of on-line compilation and layout work. The `Program` knows the `Linkage` it belongs to, and allows for a `TargetProgram` to be looked up based on a specific `TargetRequest`. A `TargetProgram` then allows layout information and compiled kernel code to be asked for on-demand, in order to support eventual "live" compilation scenarios. * The `EndToEndCompileRequest` type is a composition/coordination type that replaces the old `CompileRequest` in a way that uses the services of the various other types. It owns a few pieces of state that only make sense in the context of an end-to-end compile (e.g., there is really no way to "pass through" code when the front- and back-ends are run separately) or a command-line compile (everything to do with specifying output paths for files is really just for the benefit of `slangc`, and might even be moved there over time). * One important detail is that the `EndToEndCompilRequest` owns all of the string-based generic arguments for both global and entry-point generic parameters. The logic in `check.cpp` for dealing with those arguments has been heavily refactored to separate out the parsings steps that are specific to end-to-end compilation with string-based type arguments, and the semantic checking steps that result in a specialized `Program` (which can be exposed through new APIs that aren't tied to end-to-end compilation). It is perhaps not surprising that this change had a lot of consequences, so I'll briefly run over some of the main categories of changes required: * I changed the way that global generic arguments are passed via API (use `spSetGlobalGenericArgs` instead of the generic arguments for `spAddEntryPointEx`, which are not just for entry-point generics), which has been a change that we've needed for a long time. This is technically a breaking API change, although we should have very few client applications that care about it. * A bunch of places that used to take "big" objects like `CompileRequest` now just take the sub-pieces they care about (e.g., a function might have only needed a `Linkage` and a `DiagnosticSink`). This makes many subroutines or "context" struct types more generally useful, at the cost of taking more parameters. * In a few cases the conceptually clean separation of the layers breaks down (often for edge-case or compatibility features), and so we may pass along additional objects that are allowed to be null, but are used when present. A big example of this is how the back-end code generation routines accept an `EndToEndCompileRequest` that is optional, and only used to check whether "pass through" compilation is needed. We should probably look into cleaning this kind of logic up over time so that we don't need to violate the apparent separation of phases of compilation. * In cases where separation of layers was being broken for the sake of GLSL features, I went ahead and ripped them out, since all of that should be dead code anyway. * In many cases I increased the encapsulation of data in the core types to help track down use sites and make sure they are following invariants better. * In cases where code was doing, e.g., `context->shared->compileRequest->session->getThing()` I have tried to introduce convenience routines so that the usage site is just `context->getThing()` to improve encapsulation and allow changes to be made more easily going forward. * The `noteInternalErrorLoc` functionality was moved off of the compile request and into `DiagnosticSink`, since that is the one type you can rely on having around when you want to note an internal error. We may consider going forward if (and how) it should reset the counter used for noting locations on internal errors. * A few APIs now take `DiagnosticSink*` arguments where they didn't before, and as a result some public APIs need to create `DiagnosticSink`s to pass in, before going ahead and ignoring the messages. In the future there should be variations of these APIs that accept an `ISlangBlob**` parameter for the output. * fixup: missing include for compilers with accurate template checking (non-VS) * fixup: review feedback
Diffstat (limited to 'source/slang/preprocessor.cpp')
-rw-r--r--source/slang/preprocessor.cpp166
1 files changed, 49 insertions, 117 deletions
diff --git a/source/slang/preprocessor.cpp b/source/slang/preprocessor.cpp
index c6c438ef6..103db7dcb 100644
--- a/source/slang/preprocessor.cpp
+++ b/source/slang/preprocessor.cpp
@@ -194,27 +194,18 @@ struct Preprocessor
// represent end-of-input situations.
Token endOfFileToken;
- // The translation unit that is being parsed
- TranslationUnitRequest* translationUnit;
+ /// The linkage the provides the context for preprocessing
+ Linkage* linkage = nullptr;
+
+ /// The module, if any, that the preprocessed result will belong to
+ Module* parentModule = nullptr;
// The unique identities of any paths that have issued `#pragma once` directives to
// stop them from being included again.
HashSet<String> pragmaOnceUniqueIdentities;
- TranslationUnitRequest* getTranslationUnit()
- {
- return translationUnit;
- }
-
- ModuleDecl* getSyntax()
- {
- return getTranslationUnit()->SyntaxNode.Ptr();
- }
-
- CompileRequest* getCompileRequest()
- {
- return getTranslationUnit()->compileRequest;
- }
+ NamePool* getNamePool() { return linkage->getNamePool(); }
+ SourceManager* getSourceManager() { return linkage->getSourceManager(); }
};
// Convenience routine to access the diagnostic sink
@@ -255,11 +246,6 @@ static void destroyInputStream(Preprocessor* /*preprocessor*/, PreprocessorInput
delete inputStream;
}
-static NamePool* getNamePool(Preprocessor* preprocessor)
-{
- return preprocessor->translationUnit->compileRequest->getNamePool();
-}
-
// Create an input stream to represent a pre-tokenized input file.
// TODO(tfoley): pre-tokenizing files isn't going to work in the long run.
static PreprocessorInputStream* CreateInputStreamForSource(
@@ -272,7 +258,7 @@ static PreprocessorInputStream* CreateInputStreamForSource(
initializePrimaryInputStream(preprocessor, inputStream);
// initialize the embedded lexer so that it can generate a token stream
- inputStream->lexer.initialize(sourceView, GetSink(preprocessor), getNamePool(preprocessor), memoryArena);
+ inputStream->lexer.initialize(sourceView, GetSink(preprocessor), preprocessor->getNamePool(), memoryArena);
inputStream->token = inputStream->lexer.lexToken();
return inputStream;
@@ -836,7 +822,7 @@ top:
// Now re-lex the input
- SourceManager* sourceManager = preprocessor->getCompileRequest()->getSourceManager();
+ SourceManager* sourceManager = preprocessor->getSourceManager();
// We create a dummy file to represent the token-paste operation
PathInfo pathInfo = PathInfo::makeTokenPaste();
@@ -845,7 +831,7 @@ top:
SourceView* sourceView = sourceManager->createSourceView(sourceFile, nullptr);
Lexer lexer;
- lexer.initialize(sourceView, GetSink(preprocessor), getNamePool(preprocessor), sourceManager->getMemoryArena());
+ lexer.initialize(sourceView, GetSink(preprocessor), preprocessor->getNamePool(), sourceManager->getMemoryArena());
SimpleTokenInputStream* inputStream = new SimpleTokenInputStream();
initializeInputStream(preprocessor, inputStream);
@@ -1564,7 +1550,7 @@ static void HandleEndIfDirective(PreprocessorDirectiveContext* context)
// we expect it.
//
// Most directives do not need to call this directly, since we have
-// a catch-all case in the main `HandleDirective()` funciton.
+// a catch-all case in the main `HandleDirective()` function.
// The `#include` case will call it directly to avoid complications
// when it switches the input stream.
static void expectEndOfDirective(PreprocessorDirectiveContext* context)
@@ -1589,6 +1575,31 @@ static void expectEndOfDirective(PreprocessorDirectiveContext* context)
AdvanceRawToken(context->preprocessor);
}
+ /// Read a file in the context of handling a preprocessor directive
+static SlangResult readFile(
+ PreprocessorDirectiveContext* context,
+ String const& path,
+ ISlangBlob** outBlob)
+{
+ // The actual file loading will be handled by the file system
+ // associated with the parent linkage.
+ //
+ auto linkage = context->preprocessor->linkage;
+ auto fileSystemExt = linkage->getFileSystemExt();
+ SLANG_RETURN_ON_FAIL(fileSystemExt->loadFile(path.Buffer(), outBlob));
+
+ // If we are running the preprocessor as part of compiling a
+ // specific module, then we must keep track of the file we've
+ // read as yet another file that the module will depend on.
+ //
+ if(auto module = context->preprocessor->parentModule)
+ {
+ module->addFilePathDependency(path);
+ }
+
+ return SLANG_OK;
+}
+
// Handle a `#include` directive
static void HandleIncludeDirective(PreprocessorDirectiveContext* context)
{
@@ -1603,7 +1614,7 @@ static void HandleIncludeDirective(PreprocessorDirectiveContext* context)
auto directiveLoc = GetDirectiveLoc(context);
- PathInfo includedFromPathInfo = context->preprocessor->translationUnit->compileRequest->getSourceManager()->getPathInfo(directiveLoc, SourceLocType::Actual);
+ PathInfo includedFromPathInfo = context->preprocessor->getSourceManager()->getPathInfo(directiveLoc, SourceLocType::Actual);
IncludeHandler* includeHandler = context->preprocessor->includeHandler;
if (!includeHandler)
@@ -1644,7 +1655,7 @@ static void HandleIncludeDirective(PreprocessorDirectiveContext* context)
// Push the new file onto our stack of input streams
// TODO(tfoley): check if we have made our include stack too deep
- auto sourceManager = context->preprocessor->getCompileRequest()->getSourceManager();
+ auto sourceManager = context->preprocessor->getSourceManager();
// See if this an already loaded source file
SourceFile* sourceFile = sourceManager->findSourceFileRecursively(filePathInfo.uniqueIdentity);
@@ -1652,7 +1663,7 @@ static void HandleIncludeDirective(PreprocessorDirectiveContext* context)
if (!sourceFile)
{
ComPtr<ISlangBlob> foundSourceBlob;
- if (SLANG_FAILED(includeHandler->readFile(filePathInfo.foundPath, foundSourceBlob.writeRef())))
+ if (SLANG_FAILED(readFile(context, filePathInfo.foundPath, foundSourceBlob.writeRef())))
{
GetSink(context)->diagnose(pathToken.loc, Diagnostics::includeFailed, path);
return;
@@ -1843,7 +1854,7 @@ static void HandleLineDirective(PreprocessorDirectiveContext* context)
return;
}
- auto sourceManager = context->preprocessor->translationUnit->compileRequest->getSourceManager();
+ auto sourceManager = context->preprocessor->getSourceManager();
String file;
if (PeekTokenType(context) == TokenType::EndOfDirective)
@@ -1891,7 +1902,7 @@ SLANG_PRAGMA_DIRECTIVE_CALLBACK(handlePragmaOnceDirective)
// We are using the 'uniqueIdentity' as determined by the ISlangFileSystemEx interface to determine file identities.
auto directiveLoc = GetDirectiveLoc(context);
- auto issuedFromPathInfo = context->preprocessor->translationUnit->compileRequest->getSourceManager()->getPathInfo(directiveLoc, SourceLocType::Actual);
+ auto issuedFromPathInfo = context->preprocessor->getSourceManager()->getPathInfo(directiveLoc, SourceLocType::Actual);
// Must have uniqueIdentity for a #pragma once to work
if (!issuedFromPathInfo.hasUniqueIdentity())
@@ -1962,82 +1973,6 @@ static void HandlePragmaDirective(PreprocessorDirectiveContext* context)
(subDirective->callback)(context, subDirectiveToken);
}
-// Handle a `#version` directive
-static void handleGLSLVersionDirective(PreprocessorDirectiveContext* context)
-{
- Token versionNumberToken;
- if(!ExpectRaw(
- context,
- TokenType::IntegerLiteral,
- Diagnostics::expectedTokenInPreprocessorDirective,
- &versionNumberToken))
- {
- return;
- }
-
- Token glslProfileToken;
- if(PeekTokenType(context) == TokenType::Identifier)
- {
- glslProfileToken = AdvanceToken(context);
- }
-
- // Need to construct a representation taht we can hook into our compilation result
-
- auto modifier = new GLSLVersionDirective();
- modifier->versionNumberToken = versionNumberToken;
- modifier->glslProfileToken = glslProfileToken;
-
- // Attach the modifier to the program we are parsing!
-
- addModifier(
- context->preprocessor->getSyntax(),
- modifier);
-}
-
-// Handle a `#extension` directive, e.g.,
-//
-// #extension some_extension_name : enable
-//
-static void handleGLSLExtensionDirective(PreprocessorDirectiveContext* context)
-{
- Token extensionNameToken;
- if(!ExpectRaw(
- context,
- TokenType::Identifier,
- Diagnostics::expectedTokenInPreprocessorDirective,
- &extensionNameToken))
- {
- return;
- }
-
- if( !ExpectRaw(context, TokenType::Colon, Diagnostics::expectedTokenInPreprocessorDirective) )
- {
- return;
- }
-
- Token dispositionToken;
- if(!ExpectRaw(
- context,
- TokenType::Identifier,
- Diagnostics::expectedTokenInPreprocessorDirective,
- &dispositionToken))
- {
- return;
- }
-
- // Need to construct a representation taht we can hook into our compilation result
-
- auto modifier = new GLSLExtensionDirective();
- modifier->extensionNameToken = extensionNameToken;
- modifier->dispositionToken = dispositionToken;
-
- // Attach the modifier to the program we are parsing!
-
- addModifier(
- context->preprocessor->getSyntax(),
- modifier);
-}
-
// Handle an invalid directive
static void HandleInvalidDirective(PreprocessorDirectiveContext* context)
{
@@ -2092,11 +2027,6 @@ static const PreprocessorDirective kDirectives[] =
{ "line", &HandleLineDirective, 0 },
{ "pragma", &HandlePragmaDirective, 0 },
- // TODO(tfoley): These are specific to GLSL, and probably
- // shouldn't be enabled for HLSL or Slang
- { "version", &handleGLSLVersionDirective, 0 },
- { "extension", &handleGLSLExtensionDirective, 0 },
-
{ nullptr, nullptr, 0 },
};
@@ -2270,7 +2200,7 @@ static void DefineMacro(
PreprocessorMacro* macro = CreateMacro(preprocessor);
- auto sourceManager = preprocessor->translationUnit->compileRequest->getSourceManager();
+ auto sourceManager = preprocessor->getSourceManager();
SourceFile* keyFile = sourceManager->createSourceFileWithString(pathInfo, key);
SourceFile* valueFile = sourceManager->createSourceFileWithString(pathInfo, value);
@@ -2280,10 +2210,10 @@ static void DefineMacro(
// Use existing `Lexer` to generate a token stream.
Lexer lexer;
- lexer.initialize(valueView, GetSink(preprocessor), getNamePool(preprocessor), sourceManager->getMemoryArena());
+ lexer.initialize(valueView, GetSink(preprocessor), preprocessor->getNamePool(), sourceManager->getMemoryArena());
macro->tokens = lexer.lexAllTokens();
- Name* keyName = preprocessor->translationUnit->compileRequest->getNamePool()->getName(key);
+ Name* keyName = preprocessor->getNamePool()->getName(key);
macro->nameAndLoc.name = keyName;
macro->nameAndLoc.loc = keyView->getRange().begin;
@@ -2321,11 +2251,13 @@ TokenList preprocessSource(
DiagnosticSink* sink,
IncludeHandler* includeHandler,
Dictionary<String, String> defines,
- TranslationUnitRequest* translationUnit)
+ Linkage* linkage,
+ Module* parentModule)
{
Preprocessor preprocessor;
InitializePreprocessor(&preprocessor, sink);
- preprocessor.translationUnit = translationUnit;
+ preprocessor.linkage = linkage;
+ preprocessor.parentModule = parentModule;
preprocessor.includeHandler = includeHandler;
for (auto p : defines)
@@ -2333,7 +2265,7 @@ TokenList preprocessSource(
DefineMacro(&preprocessor, p.Key, p.Value);
}
- SourceManager* sourceManager = translationUnit->compileRequest->getSourceManager();
+ SourceManager* sourceManager = linkage->getSourceManager();
SourceView* sourceView = sourceManager->createSourceView(file, nullptr);