Files
UnrealEngineUWP/Engine/Source/Programs/UnrealHeaderTool/Private/HeaderParser.h
Ben Marsh 7c77078af1 Copying //UE4/Dev-Core to //UE4/Dev-Main (Source: //UE4/Dev-Core @ 3345728)
#lockdown Nick.Penwarden

==========================
MAJOR FEATURES + CHANGES
==========================

Change 3315219 on 2017/02/21 by Steve.Robb

	Fix for FObjectAndNameAsStringProxyArchive when serializing a TWeakObjectPtr.

Change 3315285 on 2017/02/21 by Steve.Robb

	Explicitly pass string builder into code generation functions.

Change 3315341 on 2017/02/21 by Ben.Marsh

	UAT: Clean up some formatting in StreamCopyDescription output - remove #fyi lines, exclude merge commits, and remove some blank lines.

Change 3315350 on 2017/02/21 by Ben.Marsh

	Fix shared resource files not being rebuilt if the version header changes.

Change 3315823 on 2017/02/21 by Ben.Marsh

	UAT: Use a class derived from AutomationException to return information specific to commandlets failing, rather than putting it in the base class.

Change 3315826 on 2017/02/21 by Ben.Marsh

	UAT: Move Distiller class from general use in UAT; FileFilter provides a much safer and fully featured implementation of the same concepts.

Change 3315857 on 2017/02/21 by Ben.Marsh

	UBT: Remove the StripBaseDirectory() and MakeRerootedFilePath() utility functions from UBT. These operations can now be done more safely with FileReference objects.

Change 3315942 on 2017/02/21 by Ben.Marsh

	UBT: Convert FileFilter to use FileReference and DirectoryReference arguments everywhere.

Change 3316236 on 2017/02/22 by Maciej.Mroz

	#jira UE-42045

	Nativization
	Fixed Warning: TEnumAsByte is not intended for use with enum

Change 3316253 on 2017/02/22 by Robert.Manuszewski

	Fixes for the async log file writer hangs and crashes.

	- potential fix for the logging system hang when running out of disk space while flushing log
	- fix for unexpected concurrency assert when flushing the log buffer to disk

Change 3316293 on 2017/02/22 by Steve.Robb

	GetTypeHash and lexicographical comparison operators (operator<() etc.) for TTuple.

Change 3316342 on 2017/02/22 by Maciej.Mroz

	Nativization: Wrappers (stubs) required only by other wrappers are properly generated.

	#codereview: Mike.Beach

Change 3316344 on 2017/02/22 by Maciej.Mroz

	Fixed crash in nativized Odin
	Async loading properly handles nativized structs.

Change 3316359 on 2017/02/22 by Steve.Robb

	GitHub #3287 : Ignore #pragma in USTRUCTs

	#jira UE-42248

Change 3316389 on 2017/02/22 by Matthew.Griffin

	Switched Installed Engine Filters to multiline properties to make them more readable
	Added Oodle to list of excluded plugins
	#jira UE-42030

Change 3316392 on 2017/02/22 by Ben.Marsh

	UBT: Split out FileReference/DirectoryReference classes into their own file.

Change 3316394 on 2017/02/22 by Ben.Marsh

	UBT: Move FileReference/DirectoryReference extension methods into the appropriate file.

Change 3316411 on 2017/02/22 by Ben.Marsh

	UAT: Remove file functions that take multiple arguments. There's not really a compelling use case for these to exist over looping from the calling code.

Change 3316446 on 2017/02/22 by Ben.Marsh

	UAT: Try disabling function name prefix to log output from UAT, to see if it improves readability. Function names are still included in the log file for debugging.

Change 3316575 on 2017/02/22 by Ben.Marsh

	UAT: Remove unused functionality for dealing with labels, and output a more human readable list of P4 settings at startup.

Change 3318481 on 2017/02/22 by Steve.Robb

	Use of FMath::IsPowerOfTwo in check.
	Static assert to ensure that an inline set allocator will have a hash size of a power of two.

Change 3318496 on 2017/02/22 by Steve.Robb

	Fix for TSet visualizers.

Change 3318919 on 2017/02/23 by Steve.Robb

	Fix for hot reloading UScriptStruct-derived objects in a module, where the CDOs of these objects haven't had PrepareCppStructOps() called on them.

	#jira UE-42178

Change 3318942 on 2017/02/23 by Steve.Robb

	Removal of a redundant insertion which can cause problems on reallocation of the map.

Change 3319010 on 2017/02/23 by Ben.Marsh

	UBT: Fix exception when a file that was previously part of the working set is deleted.

Change 3319134 on 2017/02/23 by Robert.Manuszewski

	Better fix for a deadlock when flushing log while it's already being flushed due to flush timer on the async log writer thread.

Change 3319249 on 2017/02/23 by Matthew.Griffin

	Added a function to check if running with debug game libs instead of checking command line in multiple places
	Added -RunConfig parameter, which has equivalent result to -debug if value of parameter starts with 'debug'
	Added -RunConfig=$(Configuration) as a default commandline argument for Mac so that editor can use debug game libs
	Removed -Shipping argument from VCProject generation as it's not used anymore

Change 3319253 on 2017/02/23 by Maciej.Mroz

	#jira UE-41846

	New mechanism to gather modules necessary for Nativized Assets. The modules are listed based on included headers. Previously the dependencies was gathered only in FBlueprintNativeCodeGenManifest::GatherModuleDependencies.

Change 3319591 on 2017/02/23 by Ben.Marsh

	Don't strip prefixes beginning with WARNING: or ERROR: using the Postp filter.

Change 3320357 on 2017/02/23 by Steven.Hutton

	Slight changes to Add Crash method - Returning select fields instead of entity objects in queries for perf reasons.

Change 3320361 on 2017/02/23 by Steven.Hutton

	Performance improvements subsequent to the recent database changes.

Change 3320446 on 2017/02/23 by Steven.Hutton

	adding my temporary performance tracker class - reports to a private slack channel with add crash performance data.

Change 3320479 on 2017/02/23 by Ben.Marsh

	Fix CIS errors.

Change 3320576 on 2017/02/23 by Jin.Zhang

	Update CrashReporter to use AWS

Change 3320742 on 2017/02/23 by Jin.Zhang

	Merging crash caching

Change 3321119 on 2017/02/24 by Robert.Manuszewski

	DLL injection protection support for non-monolithic builds

Change 3323308 on 2017/02/27 by Matthew.Griffin

	Moved compilation of SwarmInterface after its dependencies so that we will see a build failure immediately if they change version in future

Change 3323423 on 2017/02/27 by Chad.Garyet

	Adding a script to check and warn about csproj targeted .net versions being mismatched

	#JIRA UE-39624

Change 3323442 on 2017/02/27 by Ben.Marsh

	UBT: Output an error if an engine module references a game module.

Change 3323743 on 2017/02/27 by Ben.Marsh

	PR #3303: Resolved PVS scan issues (Contributed by projectgheist)

Change 3323748 on 2017/02/27 by Ben.Marsh

	Convert whitespace to tabs.

Change 3324851 on 2017/02/28 by Chris.Wood

	Add Odin symbol locations to engine config for MDD on CR server.

	NotForLicensees

Change 3324979 on 2017/02/28 by Gil.Gribb

	Fixed bad merge of priority change in the EDL.

Change 3326889 on 2017/03/01 by Steven.Hutton

	Update to buggs controller to generate faster queries.

Change 3326910 on 2017/03/01 by Robert.Manuszewski

	Removing legacy #if from PackageFileSummary.

Change 3327118 on 2017/03/01 by Gil.Gribb

	UE4 - Fixed race that resulted in a memory leak when reading compressed paks.

Change 3327633 on 2017/03/01 by Gil.Gribb

	UE4 - Added a cvar to control the pak precacher thottle.

Change 3327674 on 2017/03/01 by Steve.Robb

	Unified boilerplate between all generated code files.

Change 3328544 on 2017/03/01 by Chris.Wood

	CrashReportProcess.config update (CRP v1.2.17)

	Tweaks to a few values.
	Update website URL to explicitly point to old, non-cloud site on devweb-02.

Change 3328714 on 2017/03/01 by Chris.Wood

	Correct CRP config regression. Point website at new cloud site. Still v1.2.17

Change 3329192 on 2017/03/02 by Matthew.Griffin

	Added Shared Build Id file to the list of Precompiled Build Dependencies in a target receipt so that it's brought into an installed build

Change 3329285 on 2017/03/02 by Ben.Marsh

	UGS: Allow a project to specify a filters for the streams that should be displayed for fast-switching to. The QuickSelectStreamList seting in the [Options] section of the project settings references a depot path containing a list of strings used to filter the stream list. An option is shown to switch back to showing all available streams, if desired.

Change 3330636 on 2017/03/02 by Ben.Marsh

	UBT: Bump version number of C++ include cache to force it to be rebuilt with additional include information for the default RC files.

Change 3331262 on 2017/03/03 by Robert.Manuszewski

	Merging Dev-LoadTimes to Dev-Core (Garbage Collection performance improvements)

	- Improved GC multithreading
	- Improved BeginDestroy performance
	- Introduced ULevelActorCluster for StaticMeshActor and ReflectionCapture actor clustering (can be toggled through project settings or console command gc.ActorClusterEnabled)
	- A few improvements to AddReferencedObjects functions
	- Misc improvements to GC code
	- Garbage Collector now properly handles clusters which had their objects marked as pending kill
	- Blueprints can now create clusters too (can be toggled through project settings or console command gc.BlueprintClusteringEnabled, defaults to disabled)

Change 3331285 on 2017/03/03 by Robert.Manuszewski

	A few fixes for the previous check-in.

Change 3332001 on 2017/03/03 by Ben.Marsh

	UBT: Add support for generating a UDN file containing the valid settings for BuildConfiguration.xml. Pass -configdoc=<filename> on the command line to generate such a file.

Change 3332022 on 2017/03/03 by Ben.Marsh

	Update documentation for where to find the BuildConfiguration settings.

Change 3332031 on 2017/03/03 by Ben.Marsh

	Remove documentation for Windows XP support; it has been removed in the 4.16 release.

Change 3332256 on 2017/03/03 by Ben.Marsh

	UBT: Add support for generating a UDN page containing module and target settings.

Change 3332458 on 2017/03/03 by Ben.Marsh

	UBT: Improvements to generated documentation.

Change 3332459 on 2017/03/03 by Ben.Marsh

	Add generated documentation for .target.cs files, .build.cs files, and BuildConfiguration.xml files.

Change 3332460 on 2017/03/03 by Ben.Marsh

	UBT: Make LinkTypePrivate actually private, so it doesn't show up in the docs.

Change 3332899 on 2017/03/06 by Robert.Manuszewski

	Making sure actor clustering is not used in the editor (fix for actors being deleted when GC runs in the editor)

	#jira UE-42548

Change 3332955 on 2017/03/06 by Maciej.Mroz

	Nativization distinguishes client and server platform:
	- Separated lists on additional assets, additional modules, excluded assets, excluded modules, excluded paths (in config)
	- Context (compilation options, nativization options and platform) is deliveren to BPCOmpilerCppBackend in FCompilerNativizationOptions struct.
	- Wrappers (for unconverted BPs) are created only when they are directly called.

	- Fortnite dedicated server can be nativized

Change 3332990 on 2017/03/06 by Ben.Marsh

	UBT: Add more comprehensive wrapper methods for System.IO.File and System.IO.Directory to FileReference and DirectoryReference.

Change 3333032 on 2017/03/06 by Ben.Marsh

	Documentation for build tools

Change 3333037 on 2017/03/06 by Ben.Marsh

	Add a build step to extract UAT and UBT documentation from XML comments.

Change 3333089 on 2017/03/06 by Ben.Marsh

	UAT: Re-enable logging the calling function to the console in UAT. Needs a pass for readability first.

Change 3333651 on 2017/03/06 by Gil.Gribb

	UE4 - Fix a werid recursive situation where StaticLoadObject could return an object that has not finished loading. Also produces a fatal error if this sometimes happens. EDL only.

Change 3335236 on 2017/03/07 by Ben.Marsh

	UGS: Set the sync changelist separately to the compatibility changelist.

Change 3335261 on 2017/03/07 by Gil.Gribb

	UE4 - Fixed batched render fences when BeginDestroy calls FlushRenderingCommands.

Change 3335740 on 2017/03/07 by Gil.Gribb

	maybe fix static analysis warning

Change 3335945 on 2017/03/07 by Steve.Robb

	Move FFindInstancedReferenceSubobjectHelper code out of header.
	Add map/set property support to allow instanced members of these container types to be handled during CPFUO.

	https://udn.unrealengine.com/questions/349232/tmap-with-instanced-object-as-value-gets-cleared-o.html

Change 3336693 on 2017/03/07 by Ben.Marsh

	UBT: Use shared PCHs for game plugins by default, to reduce time spent generating individual PCHs.

Change 3336694 on 2017/03/07 by Steve.Robb

	Static assert added to TMap to prevent the use of keys which don't implement a GetTypeHash.
	Fixes to types which relied on implicit conversions when calling GetTypeHash.
	Workaround in SAssetView.h and PropertyEditorModule.h for an apparent VC bug where the compiler wrongly instantiates TPointerIsConvertibleFromTo for certain forward-declared types, causing future TSharedPtr conversions to fail.

	#jira UE-42441

Change 3336698 on 2017/03/07 by Steve.Robb

	Hardcoded endpoint handling replaced with a generic string.
	Obsolete .proto and .java code generation removed.

Change 3336811 on 2017/03/07 by Wes.Hunt

	Add a game blacklist to the crash report processor. Fixed a syntax error in Config.cs, added a XML comment to shut up a warning.

Change 3336973 on 2017/03/08 by Steve.Robb

	Fix for missing GetTypeHash in a plugin.

Change 3336996 on 2017/03/08 by Steve.Robb

	Significant refactor of code generation, to try and make data flow more apparent.

Change 3337571 on 2017/03/08 by Steve.Robb

	CIS fixes for missing GetTypeHash functions.
	Non-unity fix.

Change 3337588 on 2017/03/08 by Gil.Gribb

	UE4 - Fixed obscure check with flushing rhi resources.

Change 3337620 on 2017/03/08 by Steve.Robb

	WITH_HOT_RELOAD_CTORS macros removed.
	UseVTableConstructors config option removed.

Change 3339369 on 2017/03/09 by Steve.Robb

	GetTypeHash overload for nn::account::Uid.

Change 3339464 on 2017/03/09 by Daniel.Lamb

	Fixed assert in 4.15 to do with trying to gather dependency info from invalid packages.
	#jira UE-42583
	#test Editor + Cook + Run shootergame

Change 3339465 on 2017/03/09 by Maciej.Mroz

	Fixed serialization issue, after UserDefinedEnum was used in EnumProperty.

Change 3339469 on 2017/03/09 by Maciej.Mroz

	Fixed Nativization problem, when default value is passed as non-const reference.

Change 3340178 on 2017/03/09 by Daniel.Lamb

	Added support for in memory only packages.  The Cooker ignores these and added core functions to recognize these packages.
	Other systems will need to add support where nessisary.

Change 3341002 on 2017/03/10 by Maciej.Mroz

	Nativization: Fixed FFindHeadersToInclude. Headers necessary for owners of subobjects are properly included.

Change 3341076 on 2017/03/10 by Steve.Robb

	Fix for FBakedTextureSourceInfo move semantics.

	#jira UE-42658

Change 3341160 on 2017/03/10 by Gil.Gribb

	UE4 - Fix hazard with SetMaterialUsage from a thread.

Change 3341409 on 2017/03/10 by Steve.Robb

	Reduction of the generated code size for StaticRegisterNatives functions.

Change 3341523 on 2017/03/10 by Steve.Robb

	Code generation simplified.

Change 3341800 on 2017/03/10 by Ben.Marsh

	UnrealVS: Fix UnrealVS compatibility with RTM version of Visual Studio 2017. 2017 toolchain for extensions is no longer able to build <= 2015 extensions due to validation of the VSIX manifest, so create a separate solution for it.

Change 3342034 on 2017/03/10 by Ben.Marsh

	Fix compiler setting not being loaded correctly into the Windows target settings dialog.

	#jira UE-42746

Change 3342041 on 2017/03/10 by Ben.Marsh

	Fix -ErrorOnEngineContentUse not being set in the cooker options correctly.

Change 3342094 on 2017/03/10 by Steve.Robb

	Fix to deteministic name order during code generation.

Change 3342251 on 2017/03/10 by Daniel.Lamb

	Integrate fix for resave lightmaps commandlet when upgrading from no mapbuilddatapackages to mapbuilddatapackages.
	#thanks Tim.Hagberg

	#test None

Change 3342961 on 2017/03/13 by Robert.Manuszewski

	Fixing memory leak when playing while running -nullrhi on the commandline in cooked games caused by shader resources not being destroyed.

	#jira FORT-38977

Change 3343022 on 2017/03/13 by Steve.Robb

	GetTypeHash fixes for FUniqueNetIdLive.

	#jira UE-42788

Change 3343448 on 2017/03/13 by Steve.Robb

	Compiled-in defer object order fixed.
	Debuggability of the deferred registration map improved.

	#jira UE-42828

[CL 3345747 by Ben Marsh in Main branch]
2017-03-14 15:48:33 -04:00

763 lines
25 KiB
C++

// Copyright 1998-2017 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreMinimal.h"
#include "ParserHelper.h"
#include "BaseParser.h"
#include "Misc/CompilationResult.h"
#include "Scope.h"
class UClass;
enum class EGeneratedCodeVersion : uint8;
class FFeedbackContext;
class UPackage;
struct FManifestModule;
class IScriptGeneratorPluginInterface;
class FStringOutputDevice;
class UProperty;
class FUnrealSourceFile;
class UFunction;
class UEnum;
class UScriptStruct;
class UDelegateFunction;
class UStruct;
class FClass;
class FClasses;
class FScope;
class FHeaderProvider;
class FUHTMakefile;
extern double GPluginOverheadTime;
extern double GHeaderCodeGenTime;
/*-----------------------------------------------------------------------------
Constants & types.
-----------------------------------------------------------------------------*/
enum {MAX_NEST_LEVELS = 16};
/* Code nesting types. */
enum class ENestType
{
GlobalScope,
Class,
FunctionDeclaration,
Interface,
NativeInterface
};
/** Types of statements to allow within a particular nesting block. */
enum class ENestAllowFlags
{
None = 0,
Function = 1, // Allow Event declarations at this level.
VarDecl = 2, // Allow variable declarations at this level.
Class = 4, // Allow class definition heading.
Return = 8, // Allow 'return' within a function.
TypeDecl = 16, // Allow declarations which do not affect memory layout, such as structs, enums, and consts, but not implicit delegates
ImplicitDelegateDecl = 32, // Allow implicit delegates (i.e. those not decorated with UDELEGATE) to be declared
};
ENUM_CLASS_FLAGS(ENestAllowFlags)
namespace EDelegateSpecifierAction
{
enum Type
{
DontParse,
Parse
};
}
/** The category of variable declaration being parsed */
namespace EVariableCategory
{
enum Type
{
RegularParameter,
ReplicatedParameter,
Return,
Member
};
}
/** Information for a particular nesting level. */
class FNestInfo
{
/** Link to the stack node. */
FScope* Scope;
public:
/**
* Gets nesting scope.
*/
FScope* GetScope() const
{
return Scope;
}
/**
* Sets nesting scope.
*/
void SetScope(FScope* InScope)
{
this->Scope = InScope;
}
/** Statement that caused the nesting. */
ENestType NestType;
/** Types of statements to allow at this nesting level. */
ENestAllowFlags Allow;
};
struct FIndexRange
{
int32 StartIndex;
int32 Count;
};
struct ClassDefinitionRange
{
ClassDefinitionRange(const TCHAR* InStart, const TCHAR* InEnd)
: Start(InStart)
, End(InEnd)
, bHasGeneratedBody(false)
{ }
ClassDefinitionRange()
: Start(nullptr)
, End(nullptr)
, bHasGeneratedBody(false)
{ }
void Validate()
{
if (End <= Start)
{
FError::Throwf(TEXT("The class definition range is invalid. Most probably caused by previous parsing error."));
}
}
const TCHAR* Start;
const TCHAR* End;
bool bHasGeneratedBody;
};
extern TMap<UClass*, ClassDefinitionRange> ClassDefinitionRanges;
/////////////////////////////////////////////////////
// FHeaderParser
//
// Header parser class. Extracts metadata from annotated C++ headers and gathers enough
// information to autogenerate additional headers and other boilerplate code.
//
class FHeaderParser : public FBaseParser, public FContextSupplier
{
public:
// Default version of generated code. Defaults to oldest possible, unless specified otherwise in config.
static EGeneratedCodeVersion DefaultGeneratedCodeVersion;
// Compute the function parameter size and save the return offset
static void ComputeFunctionParametersSize(UClass* InClass);
// Parse all headers for classes that are inside LimitOuter.
static ECompilationResult::Type ParseAllHeadersInside(
FClasses& ModuleClasses,
FFeedbackContext* Warn,
UPackage* LimitOuter,
const FManifestModule& Module,
TArray<class IScriptGeneratorPluginInterface*>& ScriptPlugins,
FUHTMakefile& UHTMakefile
);
// Performs a preliminary parse of the text in the specified buffer, pulling out:
// Class name and parent class name
// Is it an interface
// The list of other classes/interfaces it is dependent on
//
// It also splits the buffer up into:
// ScriptText (text outside of #if CPP and #if DEFAULTS blocks)
static void SimplifiedClassParse(const TCHAR* Filename, const TCHAR* Buffer, TArray<FSimplifiedParsingClassInfo>& OutParsedClassArray, TArray<FHeaderProvider>& DependentOn, FStringOutputDevice& ScriptText);
/**
* Returns True if the given class name includes a valid Unreal prefix and matches up with the given original class Name.
*
* @param InNameToCheck - Name w/ potential prefix to check
* @param OriginalClassName - Name of class w/ no prefix to check against
*/
static bool ClassNameHasValidPrefix(const FString InNameToCheck, const FString OriginalClassName);
/**
* Tries to convert the header file name to a class name (with 'U' prefix)
*
* @param HeaderFilename Filename.
* @param OutClass The resulting class name (if successfull)
* @return true if the filename was a header filename (.h), false otherwise (in which case OutClassName is unmodified).
*/
static bool DependentClassNameFromHeader(const TCHAR* HeaderFilename, FString& OutClassName);
/**
* Transforms CPP-formated string containing default value, to inner formated string
* If it cannot be transformed empty string is returned.
*
* @param Property The property that owns the default value.
* @param CppForm A CPP-formated string.
* @param out InnerForm Inner formated string
* @return true on success, false otherwise.
*/
static bool DefaultValueStringCppFormatToInnerFormat(const UProperty* Property, const FString& CppForm, FString &InnerForm);
/**
* Parse Class's annotated headers and optionally its child classes. Marks the class as CLASS_Parsed.
*
* @param AllClasses the class tree containing all classes in the current package
* @param HeaderParser the header parser
* @param SourceFile Source file info.
*
* @return Result enumeration.
*/
static ECompilationResult::Type ParseHeaders(FClasses& AllClasses, FHeaderParser& HeaderParser, FUnrealSourceFile* SourceFile, FUHTMakefile& UHTMakefile);
protected:
friend struct FScriptLocation;
// For compiling messages and errors.
FFeedbackContext* Warn;
// Filename currently being parsed
FString Filename;
// Makefile to which parsing intermediate data will be saved.
FUHTMakefile& UHTMakefile;
// Was the first include in the file a validly formed auto-generated header include?
bool bSpottedAutogeneratedHeaderInclude;
// Current nest level, starts at 0.
int32 NestLevel;
// Top nesting level.
FNestInfo* TopNest;
/**
* Gets current nesting scope.
*/
FScope* GetCurrentScope() const
{
return TopNest->GetScope();
}
/**
* Gets current file scope.
*/
FFileScope* GetCurrentFileScope() const
{
int32 Index = 0;
if (!TopNest)
{
check(!NestLevel);
return nullptr;
}
while (TopNest[Index].NestType != ENestType::GlobalScope)
{
--Index;
}
return (FFileScope*)TopNest[Index].GetScope();
}
/**
* Gets current source file.
*/
FUnrealSourceFile* GetCurrentSourceFile() const
{
return CurrentSourceFile;
}
void SetCurrentSourceFile(FUnrealSourceFile* UnrealSourceFile)
{
CurrentSourceFile = UnrealSourceFile;
}
/**
* Gets current class scope.
*/
FStructScope* GetCurrentClassScope() const
{
check(TopNest->NestType == ENestType::Class || TopNest->NestType == ENestType::Interface || TopNest->NestType == ENestType::NativeInterface);
return (FStructScope*)TopNest->GetScope();
}
/**
* Tells if parser is currently in a class.
*/
bool IsInAClass() const
{
int32 Index = 0;
while (TopNest[Index].NestType != ENestType::GlobalScope)
{
if (TopNest[Index].NestType == ENestType::Class || TopNest->NestType == ENestType::Interface || TopNest->NestType == ENestType::NativeInterface)
{
return true;
}
--Index;
}
return false;
}
/**
* Gets current class.
*/
UClass* GetCurrentClass() const
{
return (UClass*)GetCurrentClassScope()->GetStruct();
}
/**
* Gets current class's metadata.
*/
FClassMetaData* GetCurrentClassData()
{
return GScriptHelper.FindClassData(GetCurrentClass());
}
// Information about all nesting levels.
FNestInfo Nest[MAX_NEST_LEVELS];
// enum for complier directives used to build up the directive stack
struct ECompilerDirective
{
enum Type
{
// this directive is insignificant and does not change the code generation at all
Insignificant = 0,
// this indicates we are in a WITH_EDITOR #if-Block
WithEditor = 1<<0,
// this indicates we are in a WITH_EDITORONLY_DATA #if-Block
WithEditorOnlyData = 1<<1,
};
};
/**
* Compiler directive nest in which the parser currently is
* NOTE: compiler directives are combined when more are added onto the stack, so
* checking the only the top of stack is enough to determine in which #if-Block(s) the current code
* is.
*
* ex. Stack.Num() == 1 while entering #if WITH_EDITOR:
* CompilerDirectiveStack[1] == CompilerDirectiveStack[0] | ECompilerDirective::WithEditor ==
* CompilerDirecitveStack[1] == CompilerDirectiveStack.Num()-1 | ECompilerDirective::WithEditor
*
* ex. Stack.Num() == 2 while entering #if WITH_EDITOR:
* CompilerDirectiveStack[3] == CompilerDirectiveStack[0] | CompilerDirectiveStack[1] | CompilerDirectiveStack[2] | ECompilerDirective::WithEditor ==
* CompilerDirecitveStack[3] == CompilerDirectiveStack.Num()-1 | ECompilerDirective::WithEditor
*/
TArray<uint32> CompilerDirectiveStack;
// Pushes the Directive specified to the CompilerDirectiveStack according to the rules described above
void FORCEINLINE PushCompilerDirective(ECompilerDirective::Type Directive)
{
CompilerDirectiveStack.Push(CompilerDirectiveStack.Num()>0 ? (CompilerDirectiveStack[CompilerDirectiveStack.Num()-1] | Directive) : Directive);
}
/**
* The starting class flags (i.e. the class flags that were set before the
* CLASS_RecompilerClear mask was applied) for the class currently being compiled
*/
uint32 PreviousClassFlags;
// For new-style classes, used to keep track of an unmatched {} pair
bool bEncounteredNewStyleClass_UnmatchedBrackets;
// Indicates that UCLASS/USTRUCT/UINTERFACE has already been parsed in this .h file..
bool bHaveSeenUClass;
// Indicates that a GENERATED_UCLASS_BODY or GENERATED_BODY has been found in the UClass.
bool bClassHasGeneratedBody;
// Indicates that a GENERATED_UINTERFACE_BODY has been found in the UClass.
bool bClassHasGeneratedUInterfaceBody;
// Indicates that a GENERATED_IINTERFACE_BODY has been found in the UClass.
bool bClassHasGeneratedIInterfaceBody;
// public, private, etc at the current parse spot
EAccessSpecifier CurrentAccessSpecifier;
////////////////////////////////////////////////////
// Special parsed struct names that do not require a prefix
TArray<FString> StructsWithNoPrefix;
// Special parsed struct names that have a 'T' prefix
TArray<FString> StructsWithTPrefix;
// Mapping from 'human-readable' macro substring to # of parameters for delegate declarations
// Index 0 is 1 parameter, Index 1 is 2, etc...
TArray<FString> DelegateParameterCountStrings;
// List of all used identifiers for net service function declarations (every function must be unique)
TMap<int32, FString> UsedRPCIds;
// List of all net service functions with undeclared response functions
TMap<int32, FString> RPCsNeedingHookup;
protected:
// Constructor.
FHeaderParser(FFeedbackContext* InWarn, FUHTMakefile& InUHTMakefile);
~FHeaderParser()
{
if ( FScriptLocation::Compiler == this )
{
FScriptLocation::Compiler = NULL;
}
}
// Returns true if the token is a dynamic delegate declaration
bool IsValidDelegateDeclaration(const FToken& Token) const;
// Returns true if the current token is a bitfield type
bool IsBitfieldProperty();
// Parse the parameter list of a function or delegate declaration
void ParseParameterList(FClasses& AllClasses, UFunction* Function, bool bExpectCommaBeforeName = false, TMap<FName, FString>* MetaData = NULL);
public:
// Throws if a specifier value wasn't provided
static void RequireSpecifierValue(const FPropertySpecifier& Specifier, bool bRequireExactlyOne = false);
static FString RequireExactlyOneSpecifierValue(const FPropertySpecifier& Specifier);
protected:
/**
* Parse rest of the module's source files.
*
* @param AllClasses The class tree containing all classes in the current package.
* @param ModulePackage Current package.
* @param HeaderParser The header parser.
* @param UHTMakefile Makefile to which parsing data is saved.
*
* @return Result enumeration.
*/
static ECompilationResult::Type ParseRestOfModulesSourceFiles(FClasses& AllClasses, UPackage* ModulePackage, FHeaderParser& HeaderParser, FUHTMakefile& UHTMakefile);
//@TODO: Remove this method
static void ParseClassName(const TCHAR* Temp, FString& ClassName);
/**
* @param Input An input string, expected to be a script comment.
* @return The input string, reformatted in such a way as to be appropriate for use as a tooltip.
*/
static FString FormatCommentForToolTip(const FString& Input);
/**
* Begins the process of exporting C++ class declarations for native classes in the specified package
*
* @param CurrentPackage The package being compiled.
* @param AllClasses The class tree for CurrentPackage.
* @param UHTMakefile Makefile to which parsing data is saved.
* @param Module Currently exported module.
*/
static void ExportNativeHeaders(
UPackage* CurrentPackage,
FClasses& AllClasses,
bool bAllowSaveExportedHeaders,
FUHTMakefile& UHTMakefile,
const FManifestModule& Module
);
// FContextSupplier interface.
virtual FString GetContext() override;
// End of FContextSupplier interface.
// High-level compiling functions.
/**
* Parses given source file.
*
* @param AllClasses The class tree for current package.
* @param SourceFile Source file to parse.
*
* @returns Compilation result enum.
*/
ECompilationResult::Type ParseHeader(FClasses& AllClasses, FUnrealSourceFile* SourceFile);
void CompileDirective(FClasses& AllClasses);
void FinalizeScriptExposedFunctions(UClass* Class);
UEnum* CompileEnum();
UScriptStruct* CompileStructDeclaration(FClasses& AllClasses);
bool CompileDeclaration(FClasses& AllClasses, TArray<UDelegateFunction*>& DelegatesToFixup, FToken& Token);
/** Skip C++ (noexport) declaration. */
bool SkipDeclaration(FToken& Token);
/** Similar to MatchSymbol() but will return to the exact location as on entry if the symbol was not found. */
bool SafeMatchSymbol(const TCHAR* Match);
void HandleOneInheritedClass(FClasses& AllClasses, UClass* Class, FString InterfaceName);
FClass* ParseClassNameDeclaration(FClasses& AllClasses, FString& DeclaredClassName, FString& RequiredAPIMacroIfPresent);
/** The property style of a variable declaration being parsed */
struct EPropertyDeclarationStyle
{
enum Type
{
None,
UPROPERTY
};
};
/**
* Resets current class data back to its defaults.
*/
void ResetClassData();
/**
* Create new function object based on given info structure.
*/
UFunction* CreateFunction(const FFuncInfo &FuncInfo) const;
/**
* Create new delegate function object based on given info structure.
*/
UDelegateFunction* CreateDelegateFunction(const FFuncInfo &FuncInfo) const;
void CompileClassDeclaration(FClasses& AllClasses);
UDelegateFunction* CompileDelegateDeclaration(FClasses& AllClasses, const TCHAR* DelegateIdentifier, EDelegateSpecifierAction::Type SpecifierAction = EDelegateSpecifierAction::DontParse);
void CompileFunctionDeclaration(FClasses& AllClasses);
void CompileVariableDeclaration (FClasses& AllClasses, UStruct* Struct);
void CompileInterfaceDeclaration(FClasses& AllClasses);
FClass* ParseInterfaceNameDeclaration(FClasses& AllClasses, FString& DeclaredInterfaceName, FString& RequiredAPIMacroIfPresent);
bool TryParseIInterfaceClass(FClasses& AllClasses);
bool CompileStatement(FClasses& AllClasses, TArray<UDelegateFunction*>& DelegatesToFixup);
// Checks to see if a particular kind of command is allowed on this nesting level.
bool IsAllowedInThisNesting(ENestAllowFlags AllowFlags);
// Make sure that a particular kind of command is allowed on this nesting level.
// If it's not, issues a compiler error referring to the token and the current
// nesting level.
void CheckAllow(const TCHAR* Thing, ENestAllowFlags AllowFlags);
UStruct* GetSuperScope( UStruct* CurrentScope, const FName& SearchName );
/**
* Find a field in the specified context. Starts with the specified scope, then iterates
* through the Outer chain until the field is found.
*
* @param InScope scope to start searching for the field in
* @param InIdentifier name of the field we're searching for
* @param bIncludeParents whether to allow searching in the scope of a parent struct
* @param FieldClass class of the field to search for. used to e.g. search for functions only
* @param Thing hint text that will be used in the error message if an error is encountered
*
* @return a pointer to a UField with a name matching InIdentifier, or NULL if it wasn't found
*/
UField* FindField( UStruct* InScope, const TCHAR* InIdentifier, bool bIncludeParents=true, UClass* FieldClass=UField::StaticClass(), const TCHAR* Thing=NULL );
void SkipStatements( int32 SubCount, const TCHAR* ErrorTag );
/**
* Parses a variable or return value declaration and determines the variable type and property flags.
*
* @param AllClasses the class tree for CurrentPackage
* @param Scope struct to create the property in
* @param VarProperty will be filled in with type and property flag data for the property declaration that was parsed
* @param Disallow contains a mask of variable modifiers that are disallowed in this context
* @param OuterPropertyType only specified when compiling the inner properties for arrays or maps. corresponds to the FToken for the outer property declaration.
* @param PropertyDeclarationStyle if the variable is defined with a UPROPERTY
* @param VariableCategory what kind of variable is being parsed
* @param ParsedVarIndexRange The source text [Start, End) index range for the parsed type.
*/
void GetVarType(
FClasses& AllClasses,
FScope* Scope,
FPropertyBase& VarProperty,
uint64 Disallow,
FToken* OuterPropertyType,
EPropertyDeclarationStyle::Type PropertyDeclarationStyle,
EVariableCategory::Type VariableCategory,
FIndexRange* ParsedVarIndexRange = nullptr);
/**
* Parses a variable name declaration and creates a new UProperty object.
*
* @param Scope struct to create the property in
* @param VarProperty type and propertyflag info for the new property (inout)
* @param VariableCategory what kind of variable is being created
*
* @return a pointer to the new UProperty if successful, or NULL if there was no property to parse
*/
UProperty* GetVarNameAndDim(
UStruct* Struct,
FToken& VarProperty,
EVariableCategory::Type VariableCategory);
/**
* Returns whether the specified class can be referenced from the class currently being compiled.
*
* @param Scope The scope we are currently parsing.
* @param CheckClass The class we want to reference.
*
* @return true if the specified class is an intrinsic type or if the class has successfully been parsed
*/
bool AllowReferenceToClass(UStruct* Scope, UClass* CheckClass) const;
/**
* @return true if Scope has UProperty objects in its list of fields
*/
static bool HasMemberProperties( const UStruct* Scope );
/**
* Parses optional metadata text.
*
* @param MetaData the metadata map to store parsed metadata in
* @param FieldName the field being parsed (used for logging)
*
* @return true if metadata was specified
*/
void ParseFieldMetaData(TMap<FName, FString>& MetaData, const TCHAR* FieldName);
/**
* Formats the current comment, if any, and adds it to the metadata as a tooltip.
*
* @param MetaData the metadata map to store the tooltip in
*/
void AddFormattedPrevCommentAsTooltipMetaData(TMap<FName, FString>& MetaData);
/**
* Tries to parse the token as an access protection specifier (public:, protected:, or private:)
*
* @return EAccessSpecifier this is, or zero if it is none
*/
EAccessSpecifier ParseAccessProtectionSpecifier(FToken& Token);
const TCHAR* NestTypeName( ENestType NestType );
FClass* GetQualifiedClass(const FClasses& AllClasses, const TCHAR* Thing);
/**
* Increase the nesting level, setting the new top nesting level to
* the one specified. If pushing a function or state and it overrides a similar
* thing declared on a lower nesting level, verifies that the override is legal.
*
* @param NestType the new nesting type
* @param InNode @todo
*/
void PushNest(ENestType NestType, UStruct* InNode, FUnrealSourceFile* SourceFile = nullptr);
void PopNest(ENestType NestType, const TCHAR* Descr);
/**
* Tasks that need to be done after popping function declaration
* from parsing stack.
*
* @param AllClasses The class tree for current package.
* @param PoppedFunction Function that have just been popped.
*/
void PostPopFunctionDeclaration(FClasses& AllClasses, UFunction* PoppedFunction);
/**
* Tasks that need to be done after popping interface definition
* from parsing stack.
*
* @param AllClasses The class tree for current package.
* @param CurrentInterface Interface that have just been popped.
*/
void PostPopNestInterface(FClasses& AllClasses, UClass* CurrentInterface);
/**
* Tasks that need to be done after popping class definition
* from parsing stack.
*
* @param CurrentClass Class that have just been popped.
*/
void PostPopNestClass(UClass* CurrentClass);
/**
* Binds all delegate properties declared in ValidationScope the delegate functions specified in the variable declaration, verifying that the function is a valid delegate
* within the current scope. This must be done once the entire class has been parsed because instance delegate properties must be declared before the delegate declaration itself.
*
* @todo: this function will no longer be required once the post-parse fixup phase is added (TTPRO #13256)
*
* @param AllClasses the class tree for CurrentPackage
* @param Struct the struct to validate delegate properties for
* @param Scope the current scope
* @param DelegateCache cached map of delegates that have already been found; used for faster lookup.
*/
void FixupDelegateProperties(FClasses& AllClasses, UStruct* ValidationScope, FScope& Scope, TMap<FName, UFunction*>& DelegateCache);
/**
* Verifies that all specified class's UProperties with CFG_RepNotify have valid callback targets with no parameters nor return values
*
* @param TargetClass class to verify rep notify properties for
*/
void VerifyRepNotifyCallbacks( UClass* TargetClass );
// Retry functions.
void InitScriptLocation( FScriptLocation& Retry );
void ReturnToLocation( const FScriptLocation& Retry, bool Binary=1, bool Text=1 );
/**
* If the property has already been seen during compilation, then return add. If not,
* then return replace so that INI files don't mess with header exporting
*
* @param PropertyName the string token for the property
*
* @return FNAME_Replace_Not_Safe_For_Threading or FNAME_Add
*/
EFindName GetFindFlagForPropertyName(const TCHAR* PropertyName);
static void ValidatePropertyIsDeprecatedIfNecessary(FPropertyBase& VarProperty, FToken* OuterPropertyType);
private:
// Source file currently parsed by UHT.
FUnrealSourceFile* CurrentSourceFile;
// Module currently parsed by UHT.
const FManifestModule* CurrentlyParsedModule;
/**
* Tries to match constructor parameter list. Assumes that constructor
* name is already matched.
*
* If fails it reverts all parsing done.
*
* @param Token Token to start parsing from.
*
* @returns True if matched. False otherwise.
*/
bool TryToMatchConstructorParameterList(FToken Token);
void SkipDeprecatedMacroIfNecessary();
// Parses possible version declaration in generated code, e.g. GENERATED_BODY(<some_version>).
void CompileVersionDeclaration(UStruct* Struct);
};
/////////////////////////////////////////////////////
// FHeaderPreParser
class FHeaderPreParser : public FBaseParser
{
public:
FHeaderPreParser()
{
}
void ParseClassDeclaration(
const TCHAR* Filename,
const TCHAR* InputText,
int32 InLineNumber,
const TCHAR*
StartingMatchID,
FName& out_StrippedClassName,
FString& out_ClassName,
FString& out_BaseClassName,
TArray<FHeaderProvider>& out_ClassNames,
const TArray<FSimplifiedParsingClassInfo>& ParsedClassArray
);
};