texts
stringlengths 0
1.24M
| names
stringlengths 13
33
|
---|---|
DevAlienTool
DEFINITION DevAlienTool;
PROCEDURE Analyze;
END DevAlienTool.
Alien views are views which, for some reason, cannot be loaded correctly. The reason may be a programming error, e.g. a different number of bytes is read than was written, or it may be a version problem (an unknown version was detected). Usually however, the problem is that some code for the view cannot be loaded, because it is missing or inconsistent. The alien tool helps to analyze such problems.
PROCEDURE Analyze
Guard: StdCmds.SingletonGuard
This command analyzes the singleton alien view, and opens a window with the textual analysis. | Dev/Docu/AlienTool.odc |
DevAnalyzer
Overview
DevAnalyzer can be applied just like the normal Component Pascal compiler for checking a program's syntactic and semantic correctness (it even uses the base modules of the Component Pascal compiler). In the examples below you can, for instance, remove a semicolon somewhere and DevAnalyzer will report the resulting syntax error.
Click on any of the underlined blue warning messages to jump directly to the corresponding tutorial section.
Warning message Number Explanation: item is ... Option
neverused 900 never referenced in program default
neverset 901 never assigned to default
usedbeforeset 902 accessed before assigned to default
setbutneverused 903 assigned to but never accessed default
usedasvarpar,possiblynotset 904 passed as a varpar before assigned to VAR Par
alsodeclaredinouterscope 905 also declared in outer scope Levels
access/assignmenttointermediate 906 referenced in different scope Intermed.
statementafterRETURN/EXIT 909 superfluous statement default
forloopvariableset 910 changed, although being a loop variable default
evaluationsequenceofparams 913 function call inside procedure call Side Effects
superfluoussemicolon 930 semicolon before END, etc. Semicolons
Introduction
During the development of a program, many design iterations are made. The source text is changed repeatedly and enhanced, errors are corrected, output statements are inserted and removed again later. The programmer changes procedure bodies and thereby inserts variables that are later not needed anymore. Modules are imported for temporary purposes but later never used.
To clean up such modules, which have evolved over time, DevAnalyzer has been developed. It is a "normal" Component Pascal compiler, which does a full syntactic and semantic analysis with error checking of the program at hand, but does not generate a symbol file or object code. Instead, it examines the program and reports problems in the code. The analysis takes place per module. Inter-module dependencies are not taken into account.
Tutorial
In the following sections, the different warnings generated by DevAnalyzer are explained in detail. A short source code example is given for illustration. To try out an example, simply click inside the embedded text view containing the example and select Analyze Module from the Info menu. You may also use the Analyzer Options... dialog. The Analyze button in the dialog has the same effect as Info->Analyze Module, i.e., both operate on the focus view.
Definitions
A program item (or item for short) denotes a construct of Component Pascal occurring in a declaration sequence. These are in particular: constants, types, variables, receivers, parameters, procedures, and modules. The terms variable, field, and parameter are used with their normal meaning.
Default Warnings, Always Enabled
Never Used
An item declared in the source code but never referenced again is flagged as never used. Frequent examples of such items are variables in declarations that were copied over from other declarations, or modules. Except for modules, the occurrence of such an item can be deleted.
Caution: Some modules in BlackBox Component Builder are imported because of a side effect in the module body, but are never used in the code. Be careful when removing module names from an import list. Typical examples are modules installing a new directory object in some base module.
When analyzing the next example, you will see that the following items are marked as never used: StdLog, Size, the y field of record Rec, SameRec, Dont, and j in procedure Dont.
MODULE NeverUsed;
IMPORT StdLog;
CONST N = 16; Size = 2*N;
TYPE
Rec = RECORD x, y: INTEGER END;
SameRec = Rec;
PROCEDURE Do;
VAR r: Rec;
BEGIN
r.x := N; r.x := 2*r.x
END Do;
PROCEDURE Dont;
VAR i, j, k: INTEGER;
BEGIN
k := 0;
FOR i := 0 TO N-1 DO k := k+i END
END Dont;
BEGIN Do
END NeverUsed.
Set But Never Used
An item that is initialized but never used again is marked as set but never used. Examples of such items are parameters of a procedure, which are set by definition but may never be used in the body of the procedure, because the programmer changed its implementation. Other examples are variables that were meant to be used in a loop or dummy variables to which a return value is assigned. Sometimes, these items are superfluous and can be deleted.
In the following example, the y field of Rec, the k parameter, and the val variable of Proc are set but never used.
MODULE SetButNeverUsed;
TYPE Rec = RECORD x, y: INTEGER END;
PROCEDURE Log2(u: INTEGER): INTEGER;
VAR i: INTEGER;
BEGIN
ASSERT(u > 0, 20);
i := 0;
WHILE u > 0 DO u := u DIV 2; INC(i) END;
RETURN i
END Log2;
PROCEDURE Proc(i, j, k: INTEGER);
VAR r: Rec; val: INTEGER;
BEGIN
r.x := i; r.y := j;
val := Log2(r.x)
END Proc;
BEGIN Proc(5, 5, 5)
END SetButNeverUsed.
Used Before Set
Variables and record fields, which are used before they are set denote possible errors in the program and are marked as used before set. Furthermore, the first usage of such a variable is marked (except for records and arrays). Not all warnings are errors, though: A variable, which is set in one branch of an IF statement inside a loop and used before this assignment is marked by DevAnalyzer, although the code might be correct.
In the following example, variables r, i, and k and the first use of i and k are marked used before set. The usage and initialization of k might be correct, depending on the initial value of j. DevAnalyzer is not capable of tracking these dependencies, but flags dubious program parts so that the programmer takes a closer look at it.
MODULE UsedBeforeSet;
TYPE Rec = RECORD x, y: INTEGER END;
PROCEDURE Proc;
VAR r: Rec; i, j, k: INTEGER;
BEGIN
r.x := r.y; j := i+1; r.y := i*r.x;
LOOP
IF j > 10 THEN i := 2*k; DEC(j)
ELSIF j > 5 THEN i := 3*k; DEC(j)
ELSIF j = 0 THEN k := 1
ELSE EXIT
END
END
END Proc;
BEGIN Proc
END UsedBeforeSet.
Never Set
A variable or a field of a record that never occurs on the left side of an assignment operator is marked as never set. This warning signals a real error in the program. It means that the variable or field is read but never gets a value assigned to.
In the following example, the y field of Rec and the variable i of Proc are never set. Furthermore, the first use of i is flagged as used before set.
MODULE NeverSet;
TYPE Rec = RECORD x, y: INTEGER END;
PROCEDURE Proc;
VAR r: Rec; i, j: INTEGER;
BEGIN
r.x := i; j := r.x+r.y; j := 2*j
END Proc;
BEGIN Proc
END NeverSet.
For Loop Variable Set
In a FOR loop, the loop variable should be read only, but never set. When a loop variable is set or passed to a procedure treating it as a VAR parameter (which might change the value of the parameter), the warning for loop variable set is issued. The first case usually is a programming error, whereas the second case needs to be looked at more closely.
In the following example, the local variable i is changed by the INC statement, while the local variable j is passed to a procedure treating it as a VAR parameter.
MODULE LoopVariables;
IMPORT StdLog;
PROCEDURE Init(VAR k: INTEGER);
BEGIN k := 0
END Init;
PROCEDURE Do;
VAR i, j: INTEGER;
BEGIN
FOR i := 0 TO 9 DO StdLog.Int(i); INC(i) END;
StdLog.Ln;
FOR j := 0 TO 9 DO Init(j) END
END Do;
BEGIN Do
END LoopVariables.
Statement After RETURN/EXIT
Statements following an EXIT or a RETURN statement are never executed and may therefore be removed. This is an obvious error, but sometimes such code can be the result of various design iterations, where many changes were made. The superfluous statements are marked as statement after RETURN/EXIT.
In the following example, x := 0 in Sgn and i := i DIV 2 in Do are superfluous.
MODULE ReturnExit;
PROCEDURE Sgn(x: INTEGER): INTEGER;
BEGIN
IF x < 0 THEN RETURN -1; x := 0 ELSIF x = 0 THEN RETURN 0 ELSE RETURN 1 END
END Sgn;
PROCEDURE Do;
VAR i: INTEGER;
BEGIN
i := 15;
LOOP
IF Sgn(i) = -1 THEN EXIT; i := i DIV 2
ELSIF ODD(i) THEN i := 3*i+1
ELSE i := 2*i; EXIT
END
END
END Do;
BEGIN Do
END ReturnExit.
Warnings Enabled Using The Analyze... Dialog
The following warnings are only generated, if the corresponding option in the Analyze... dialog is enabled. These options may be saved, reset to the default, or loaded with the various buttons in the dialog. When starting up, DevAnalyzer initializes itself with the last saved options.
Additionally, DevAnalyzer counts the number of statements in a module and displays it in the dialog. This gives a very good measure for the complexity of a module, as it is independent of the formatting style. One statement is counted for one of the possible alternatives in the Statement production of the Component Pascal report.
Used as Varpar, Possibly Not Set (VAR Parameter Option)
An item that before being initialized is passed as an actual variable parameter to a procedure, might never be initialized. I.e., it cannot be guaranteed from outside the procedure that the item is set before used inside the procedure. Since this is not always an error but merely a fact of insufficient analysis, this warning is only issued when enabled through the VAR parameter option in the Analyze... dialog. The generated warning is used as varpar, possibly not set.
In the following example, j is marked as used as varpar, possibly not set, while i is not marked since it is initialized in Do.
MODULE VarPar;
PROCEDURE Varpars(VAR i: INTEGER; VAR j: INTEGER; k: INTEGER);
BEGIN
i := 5; j := 6; k := 7*k
END Varpars;
PROCEDURE Do;
VAR i, j, k: INTEGER;
BEGIN
i := 1; k := 2;
Varpars(i, j, k)
END Do;
BEGIN Do
END VarPar.
Analysis of Exported and Intermediate Items (Exported Items and Levels Option)
Items, which are exported are not subjected to analysis (used before set, never used etc.). If these items should be included in the analysis, enable the Exported items option.
Local items, which are declared in a different scope are excluded from the analysis as well. It cannot be determined efficiently, if an item is initialized in a local procedure, for instance. Enable the Levels option in the Analyze... dialog to include such items in the analysis.
In the following example, analyzing without these options enabled will give no warnings. When you enable the options, however, the exported procedure Do is marked as never used, the local variable k is marked as never set, and its use in Local is marked as used before set.
MODULE ExportLevel;
CONST Local = 5;
VAR i: LONGINT;
PROCEDURE Do*;
VAR i, j, k: INTEGER;
PROCEDURE Local(i: INTEGER);
BEGIN j := i+k
END Local;
BEGIN
j := 0;
FOR i := 0 TO 7 DO j := j+i END;
Local(j)
END Do;
BEGIN i := 0; i := i+Local
END ExportLevel.
Also Declared in Outer Scope, Access/Assignment to Intermediate (Intermediate Items Option)
Reusing names of items declared outside the current scope can lead to confusion, especially when looking at the code after some time. To mark these items, the warning also declared in outer scope is issued when encountering such an item.
Also, assigning to or using an item from a different scope can be erroneous, as one might think that a global item is changed or accessed. Therefore, such assignments or uses are marked as access/assignment to intermediate.
The Intermediate items option in the Analyze... dialog controls this feature.
In the following example, the local variable i, the local procedure Local, and the parameter i of Local are marked as also declared in outer scope. The assignment to j and the use of k in Local are marked as access/assignment to intermediate.
MODULE Intermediates;
CONST Local = 5;
VAR i: LONGINT;
PROCEDURE Do;
VAR i, j, k: INTEGER;
PROCEDURE Local(i: INTEGER);
BEGIN j := i+k
END Local;
BEGIN
j := 0;
FOR i := 0 TO 7 DO j := j+i END;
Local(j)
END Do;
BEGIN i := 0; i := i+Local; Do
END Intermediates.
Evaluation Sequence of Params. (Side Effects Option)
As the evaluation sequence of parameters in a procedure call is not defined in Component Pascal, function calls in parameter lists are problematic, if the functions have side effects on the global state. Therefore (and for other reasons), functions with side effects should be avoided (at least calling them in parameter lists).
E.g., a function call returning a value, which in turn is passed as a parameter to a procedure, and which might change the global state of which some variable is used again in the parameter list, depends heavily on the evaluation sequence. DevAnalyzer marks this problematic code with evaluation sequence of params..
Enable the Side Effects option in the Analyze Options... dialog for this analysis.
In the example, function F changes the global variable x. The result of F and x are used in the procedure call writing out the values. Try this code on two different machine architectures or using two different Component Pascal compilers, and compare the results.
MODULE Evaluation;
IMPORT StdLog;
VAR x: INTEGER;
PROCEDURE F(): INTEGER;
BEGIN
INC(x); RETURN x
END F;
PROCEDURE Write(a, b: INTEGER);
BEGIN
StdLog.Int(a); StdLog.Int(b); StdLog.Ln
END Write;
BEGIN x := 5; Write(x, F())
END Evaluation.
Superfluous Semicolon (Semicolons Option)
This warning is for the programmer with aesthetic ambitions (or simply for picky people). It marks superfluous semicolons in the code, i.e. semicolons before END or other statement-ending symbols. These semicolons are marked with superfluous semicolon.
Enable it with the Semicolons option in the Analyze Options... dialog.
Try it out and see for yourself.
MODULE Semicolons;
TYPE R = RECORD x: INTEGER; END;
PROCEDURE Do(i: INTEGER);
VAR j: INTEGER; r: R;
BEGIN
IF i < 0 THEN j := -1; ELSIF i = 0 THEN j := 0; ELSE j := 1; END;
REPEAT DEC(i); UNTIL i = 0;
CASE j OF
| -1: r.x := 17;
| 0: r.x := 3; r.x := 2*r.x;
ELSE i := 0
END;
END Do;
BEGIN Do(28);
END Semicolons.
Stefan H.-M. Ludwig 24 March 1998
| Dev/Docu/Analyzer.odc |
DevBrowser
DEFINITION DevBrowser;
PROCEDURE ImportSymFile (f: Files.File; OUT s: Stores.Store);
PROCEDURE ShowInterface (opts: ARRAY OF CHAR);
PROCEDURE ImportCodeFile (f: Files.File; OUT s: Stores.Store);
PROCEDURE ShowCodeFile;
END DevBrowser.
The browser shows the interface of a module or of an item in a module. It extract the necessary interface information out of the module's symbol file. A symbol file contains only minimal information, it doesn't contain comments nor does it retain information about the textual order in which a module's item have been defined (their display is sorted alphabetically). For records, the browser only shows newly introduced fields and procedures (or procedures redefined with covariant function results). You can follow the record type hiearchy to the base type by applying the browser command again on the base type name in the record declaration.
The browser is also able to decode a code file and to display important information about the code file. In particular, the imported items (types, procedures, etc.) are shown to indicate on which features provided by other modules a given module depends (sometimes called the "required interface" of a module, in contrast to the "provided interface", i.e., the exported functionality of the module).
Both browser functions are available also as importers (-> Converters), which can be installed with the following statements for example in StdConfig.Startup:
Converters.Register("DevBrowser.ImportSymFile", "", "TextViews.View", "OSF", {});
Converters.Register("DevBrowser.ImportCodeFile", "", "TextViews.View", "OCF", {});
Possible menu:
MENU
"&Interface" "" "DevBrowser.ShowInterface('')" "TextCmds.SelectionGuard"
"&Flat Interface" "" "DevBrowser.ShowInterface('!')" "TextCmds.SelectionGuard"
"Import Interface" "" "DevBrowser.ShowCodeFile" "TextCmds.SelectionGuard"
END
PROCEDURE ImportSymFile (f: Files.File; OUT s: Stores.Store)
This procedure is installed upon startup of BlackBox as an importer for symbol files (-> Converters). The importer converts the symbol file into a textual browser output.
PROCEDURE ShowInterface (opts: ARRAY OF CHAR)
Guard: TextCmds.SelectionGuard
If a module name is selected, this command shows the complete definition of the module. If a qualident is selected, only the definition of the corresponding item is shown.
opts = "" creates an output which only shows the newly introduced extensions in the case of record types.
opts = "!" creates an output which also shows the inherited base type features of record types ("flat interface").
opts = "+" creates an output which shows some additional low-level information useful for a compiler developer (not further documented).
opts = "/" creates an output which is formatted in a special way. Inofficially known as the "Dijkstra option".
opts = "&" creates an output which also shows hooks in the interface.
opts = "@" creates an output using the settings from the interface browser dialog.
opts = "c" creates an output which shows only the items being usable in client modules.
opts = "e" creates an output which shows only the items being extensible.
Several options may be combined.
PROCEDURE ImportCodeFile (f: Files.File; OUT s: Stores.Store)
This procedure is installed upon startup of BlackBox as an importer for code files (-> Converters). The importer converts the code file into a textual browser output in the same way as the command ShowCodeFile.
PROCEDURE ShowCodeFile
Guard: TextCmds.SelectionGuard
If a module name is selected, this command opens a text view in browser mode that shows information about the code file of the compiled module. This includes the code file's header information and the generated code both in hex form and in the form of symbolic instruction codes. In order to simplify reading of the generated code it is possible to merge the code of a procedure with its source code, if available, by clicking on the link at the beginning of a procedure. In the generated detail view, the source code pieces are links that navigate to the corresponding source code.
Note that absolute addresses in the code are resolved only at load time and are simply displayed as generated by the compiler. The fixup-chains used by the loader for resolving absolute addresses and the meta-information about program entities are (currently) not included in the output. | Dev/Docu/Browser.odc |
DevCmds
DEFINITION DevCmds;
IMPORT Dialog;
PROCEDURE FlushResources;
PROCEDURE OpenModuleList;
PROCEDURE OpenFileList;
PROCEDURE RevalidateViewGuard (VAR par: Dialog.Par);
PROCEDURE RevalidateView;
PROCEDURE SetCancelButton;
PROCEDURE SetDefaultButton;
PROCEDURE ShowControlList;
END DevCmds.
Possible menu:
MENU
"&Open Module List" "" "DevCmds.OpenModuleList" "TextCmds.SelectionGuard"
"Open &File List" "" "DevCmds.OpenFileList" "TextCmds.SelectionGuard"
"Flus&h Resources" "" "DevCmds.FlushResources" ""
"Re&validate View" "" "DevCmds.RevalidateView" "DevCmds.RevalidateViewGuard"
SEPARATOR
"&Control List" "" "DevCmds.ShowControlList" "StdCmds.ContainerGuard"
"Set &Default Button" "" "DevCmds.SetDefaultButton" "StdCmds.ContainerGuard"
"Set Canc&el Button" "" "DevCmds.SetCancelButton" "StdCmds.ContainerGuard"
END
PROCEDURE FlushResources
Flush menu guard and string translation resources. This command is needed when a menu item is disabled because its code could not be executed, but since then the code has become executable (e.g., due to a recompilation of a module, and possibly unloading an old module version). It is also needed if the string resource texts have been edited and saved, if the changes should become effective immediately, rather than only when BlackBox is started the next time.
PROCEDURE OpenModuleList
Guard: TextCmds.SelectionGuard
Opens the modules whose names are selected, e.g.,
"FormModels FormViews".
PROCEDURE OpenFileList
Guard: TextCmds.SelectionGuard
Opens the files whose names are selected. The names must use the portable path name syntax, e.g.,
"Form/Mod/Models Form/Mod/Views".
PROCEDURE RevalidateViewGuard (VAR par: Dialog.Par)
Menu guard for Revalidate View.
PROCEDURE RevalidateView
Guard: RevalidateViewGuard
A view may have become invalid after a trap occurred. As a result, the view is greyed out and made passive (so that the same trap cannot occur anymore, thus preventing trap avalanches). However, sometimes it can be useful to revalidate the view and continue to work with it.
PROCEDURE SetCancelButton
Guard: StdCmds.ContainerGuard
Makes the selected view in the focus container a "cancel" button, i.e., in mask mode (-> Containers) it is considered pressed when the user enters the escape character.
PROCEDURE SetDefaultButton
Guard: StdCmds.ContainerGuard
Makes the selected view in the focus container a "default" button, i.e., in mask mode (-> Containers) it is considered pressed when the user enters a carriage return character.
PROCEDURE ShowControlList
Guard: StdCmds.ContainerGuard
Lists the properties of all views in the focus container which return control properties (-> Controls).
| Dev/Docu/Cmds.odc |
DevCommanders
DEFINITION DevCommanders;
TYPE
Par = POINTER TO RECORD
text: TextModels.Model;
beg, end: INTEGER
END;
VAR
par: Par;
PROCEDURE Deposit;
PROCEDURE DepositEnd;
... plus some private items ...
END DevCommanders.
A commander is a view which interprets and executes the command or command sequence written behind the commander. It only operates when embedded in a text.
Commanders can be useful during development; e.g., they may be embedded directly in the source code of a program. They are not intended for use in end-user applications, due to their non-standard user interface experience.
Typical menu:
"Insert Commander" "" "DevCommanders.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"Insert End Commander" "" "DevCommanders.DepositEnd; StdCmds.PasteView" "StdCmds.PasteViewGuard"
TYPE Par
Parameter context of a command's execution. This is used with commands such as
DevCompiler.CompileThis ObxViews1 ObxViews2
text: TextModels.Model
The text containing the activated commander and command.
beg: INTEGER
Begin of the parameters to the command, that is, the text position immediately behind the last character of the command itself.
end: INTEGER
End of the parameters to the command. This is either the end of the text or the position of the next commander or EndView in the text.
VAR par-: Par par # NIL exactly during the currently executed command
A command can get access to the text, and thus to its context, via this variable during the execution of the command.
PROCEDURE Deposit
Deposit command for commanders.
PROCEDURE DepositEnd
Deposit command for a DevCommanders.EndView. Marks the end of the command for the preceding commander. If no end view is present the commander reads until another commander is found or until the text ends.
This module contains several other items which are used internally.
| Dev/Docu/Commanders.odc |
DevCompiler
DEFINITION DevCompiler;
PROCEDURE Compile;
PROCEDURE CompileAndUnload;
PROCEDURE CompileModuleList;
PROCEDURE CompileSelection;
PROCEDURE CompileThis;
PROCEDURE CompileSubs;
PROCEDURE MakeList;
... plus some private commands ...
END DevCompiler.
Command package for the Component Pascal compiler. The compiler provides several options for exceptional situations. The options are defined after the name of the module to which they apply in the command DevCompiler.CompileModuleList. See Platform-SpecificIssues for details. Safety-critical runtime checks are always performed (type guards, array range checks, etc.), while non-critical runtime checks may not be generated (SHORT, integer overflows, testing of set membership). "Critical" means that non-local memory may be destroyed, with unknown global effects.
Typical menu:
MENU
"&Compile" "" "DevCompiler.Compile" "TextCmds.FocusGuard"
"Compile and Unload" "" "DevCompiler.CompileAndUnload" "TextCmds.FocusGuard"
"Compile &Selection" "" "DevCompiler.CompileSelection" "TextCmds.SelectionGuard"
"Com&pile Module List" "" "DevCompiler.CompileModuleList" "TextCmds.SelectionGuard"
END
PROCEDURE Compile
Guard: TextCmds.FocusGuard
Compile the Component Pascal module whose source is in the focus view.
PROCEDURE CompileAndUnload
Guard: TextCmds.FocusGuard
Compile the module whose source is in the focus view. If compilation is successful, it is attempted to unload the old version of this module. CompileAndUnload is convenient when developing top-level modules, i.e., modules which are not imported by any other modules, and thus can be unloaded individually.
PROCEDURE CompileModuleList
Guard: TextCmds.SelectionGuard
Compile the list of modules whose names are selected. When the first error is detected, the offending source is opened to show the error and the remaining uncompiled modules are selected. For generating a compile list for a set of subsystems see MakeList.
PROCEDURE CompileSelection
Guard: TextCmds.SelectionGuard
Compile the module, whose beginning is selected.
PROCEDURE CompileThis
Used in a text with a DevCommanders.View. This command takes the text following it and interprets it as a list of modules that should be compiled. Similar to CompileModuleList except that no selection is necessary. Examples are:
DevCompiler.CompileThis ObxHello0
DevCompiler.CompileThis ObxViews1 ObxViews2
PROCEDURE CompileSubs
Used in a text with a DevCommanders.View. This command takes the text following it and interprets it as a list of subsystems that should be compiled. The special symbol '*' refers to all subsystems, '+' refers to all subsystems except the standard subsystems. Directories and file names are expected to be capitalized according to the related module names. When the first error is detected, the offending source is opened to show the error and compilation is terminated. Examples are:
DevCompiler.CompileSubs +
DevCompiler.CompileSubs Obx
DevCompiler.CompileSubs Obx Text System (Attention: this recompiles a part of your BlackBox system.)
PROCEDURE MakeList
Used in a text with a DevCommanders.View. This command takes the text following it and interprets it as a list of subsystems that should be compiled. The special symbol '*' refers to all subsystems, '+' refers to all subsystems except the standard subsystems. Directories and file names are expected to be capitalized according to the related module names. The command generates and opens a text view that contains a properly ordered list of modules to be compiled with CompileModuleList. When a syntax error is detected while analyzing the import dependencies, the offending source is opened to show the error. Examples are:
DevCompiler.MakeList +
DevCompiler.MakeList Obx
DevCompiler.MakeList Obx Text System
... plus some private commands ...
| Dev/Docu/Compiler.odc |
DevCPB
This module has a private interface, it is only used internally.
| Dev/Docu/CPB.odc |
DevCPC486
This module has a private interface, it is only used internally.
| Dev/Docu/CPC486.odc |
DevCPE
This module has a private interface, it is only used internally.
| Dev/Docu/CPE.odc |
DevCPH
This module has a private interface, it is only used internally.
| Dev/Docu/CPH.odc |
DevCPL486
This module has a private interface, it is only used internally.
| Dev/Docu/CPL486.odc |
DevCPM
This module has a private interface, it is only used internally.
| Dev/Docu/CPM.odc |
DevCPP
This module has a private interface, it is only used internally.
| Dev/Docu/CPP.odc |
DevCPS
This module has a private interface, it is only used internally.
| Dev/Docu/CPS.odc |
DevCPT
This module has a private interface, it is only used internally.
| Dev/Docu/CPT.odc |
DevCPV486
This module has a private interface, it is only used internally.
| Dev/Docu/CPV486.odc |
DevDebug
DEFINITION DevDebug;
IMPORT Views, Kernel;
PROCEDURE Execute;
PROCEDURE ShowGlobalVariables;
PROCEDURE ShowLoadedModules;
PROCEDURE ShowViewState;
PROCEDURE Unload;
PROCEDURE UnloadModuleList;
PROCEDURE UnloadThis;
PROCEDURE HeapRefView (adr: INTEGER; name: ARRAY OF CHAR): Views.View;
PROCEDURE ShowHeapObject (adr: INTEGER; title: ARRAY OF CHAR);
PROCEDURE SourcePos (mod: Kernel.Module; codePos: INTEGER): INTEGER;
PROCEDURE UpdateGlobals (name: ARRAY OF CHAR);
PROCEDURE UpdateModules;
END DevDebug.
When a run-time error occurs, e.g., a division by zero, a "trap text" is opened which displays the procedure call chain. It is possible to use this text to navigate through data structures. Several other commands are useful when analyzing the state of the system.
Note that this kind of debugging is done completely within BlackBox; there is no separate debugger environment. Debugging occurs "post mortem" with respect to commands, i.e., a command produces a run-time error, is aborted, and then debugged. However, the run-time error usually does not affect the loaded modules and the data structures which are anchored there, nor the open documents.
For situations where a post-mortem analysis is not sufficient, the module DevDebugCmds provides an interface for attaching a run-time debugger to the running BlackBox process. A run-time debugger allows for example to single-step through code or to set breakpoints.
A possible menu:
MENU
"&Loaded Modules" "" "DevDebug.ShowLoadedModules" ""
"&Global Variables" "" "DevDebug.ShowGlobalVariables" "TextCmds.SelectionGuard"
"&View State" "" "DevDebug.ShowViewState" "StdCmds.SingletonGuard"
"E&xecute" "" "DevDebug.Execute" "TextCmds.SelectionGuard"
"&Unload" "" "DevDebug.Unload" "TextCmds.FocusGuard"
"Unloa&d Module List" "" "DevDebug.UnloadModuleList" "TextCmds.SelectionGuard"
END
PROCEDURE Execute
Guard: TextCmds.SelectionGuard
Execute the string (between quotation marks), which must have the form of a Component Pascal command sequence, e.g., "Dialog.Beep; Dialog.Beep". For simple commands, the string delimiters may be omitted, e.g., Dialog.Beep (-> StdInterpreter).
PROCEDURE ShowGlobalVariables
Guard: TextCmds.SelectionGuard
Show the global variables of the module whose name is selected. The module name may be either given in full, or by alias if an alias has been defined in the enclosing module's IMPORT statement.
PROCEDURE ShowLoadedModules
Show the list of all loaded modules. This command can be convenient to determine the modules which should be linked together when building an application.
PROCEDURE ShowViewState
Guard: TextCmds.FocusGuard
Show the state of the current focus view.
PROCEDURE Unload
Guard: TextCmds.FocusGuard
Tries to unload the module whose source is in the focus view. Unloading fails if the specified module is not loaded yet, or if it is not a top module.
PROCEDURE UnloadModuleList
Guard: TextCmds.SelectionGuard
Tries to unload a list of modules whose names are selected. Unloading may partially or completely fail if one of the specified modules is not loaded yet, or if it is still being imported by at least one client module. Modules must be unloaded from top to bottom.
PROCEDURE UnloadThis
Used in a text with a DevCommanders.View. This command takes the text following it and interprets it as a list of modules that should be unloaded. Similar to UnloadModuleList except that no selection is necessary.
PROCEDURE HeapRefView (adr: INTEGER; name: ARRAY OF CHAR): Views.View
PROCEDURE ShowHeapObject (adr: INTEGER; title: ARRAY OF CHAR)
PROCEDURE SourcePos (mod: Kernel.Module; codePos: INTEGER): INTEGER
PROCEDURE UpdateGlobals (name: ARRAY OF CHAR)
PROCEDURE UpdateModules
These procedures are used internally.
| Dev/Docu/Debug.odc |
DevDecoder386
Module DevDecoder386 contains a decoder for Intel i386/387 code. This module has a private interface, it is only used internally.
| Dev/Docu/Decoder386.odc |
DevDependencies
DEFINITION DevDependencies;
IMPORT Dialog;
PROCEDURE ArrangeClick;
PROCEDURE CollapseAllClick;
PROCEDURE CollapseClick;
PROCEDURE CreateTool;
PROCEDURE CreateToolClick;
PROCEDURE Deposit;
PROCEDURE ExpandAllClick;
PROCEDURE ExpandClick;
PROCEDURE HideClick;
PROCEDURE ModsGuard (VAR par: Dialog.Par);
PROCEDURE NewAnalysisClick;
PROCEDURE SelGuard (VAR par: Dialog.Par);
PROCEDURE ShowAllClick;
PROCEDURE ShowBasicGuard (VAR par: Dialog.Par);
PROCEDURE SubsGuard (VAR par: Dialog.Par);
PROCEDURE ToggleBasicSystemsClick;
END DevDependencies.
This tool analyzes the code files of a given list of modules. The dependencies from the given modules to other modules are displayed in a graph. By default all selected modules are displayed, but all other modules are only displayed as subsystems. Clicking with the right mouse button displays a context menu. This menu contains several commands to manipulate the view of the graph.
A subsystem can be expanded by double-clicking on it. In the same way, all modules belonging to a particular subsystem can be collapsed into a subsystem by double-clicking on any of the modules in the subsystem.
By clicking on a node in the graph this node gets selected. It is possible to select more than one node by Ctrl‑clicking on other nodes or by "drawing" a selection square around some nodes. After nodes have been selected they can be rearranged using drag and drop with the mouse or using the arrow keys on the keyboard. Ctrl-A can be used to select all nodes.
To avoid cluttering of the graph, the basic BlackBox subsystems are hidden by default. It is however possible to toggle an option to show these modules.
There are several implicit dependencies in the system (e.g., via Dialog.Call). These dependencies cannot be found using the code files. To be able to incorporate these dependencies, at least in a static way, they can be specified in the string resources for the Dev subsystem. The syntax for specifying implicit dependencies is:
Implicit.<modName> <modname>{, <modname>}
DevDependencies reads this resource and adds these dependencies to the graph. Such dependencies are displayed as gray arrows in the graph.
It is also possible to create a tool document using the command CreateTool. This creates a tool document which contains compiling, unloading, linking and packing commands for the given modules. The compiling and unloading commands are only created for the currently expanded subsystems. The linking command includes the standard BlackBox icons, and the packing command always includes all modules independent of which modules are currently expanded or hidden.
In the created tool document all the modules, which are only included due to implicit dependencies are written with gray color.
At the end of the tool document there is a list of all the root modules. These are the modules, which are not imported from any other modules, i.e. the top level modules.
Typical menu:
MENU
"&Dependencies" "" "DevDependencies.Deposit;StdCmds.Open" "TextCmds.SelectionGuard"
"&Create Tool" "" "DevDependencies.CreateTool" "TextCmds.SelectionGuard"
END
By clicking on the right mouse button a context menu is displayed. Typically it has the following entries:
MENU "*" ("DevDependencies.View")
"Expand" "" "DevDependencies.ExpandClick" "DevDependencies.SubsGuard"
"Collapse" "" "DevDependencies.CollapseClick" "DevDependencies.ModsGuard"
"New Analysis" "" "DevDependencies.NewAnalysisClick" "DevDependencies.ModsGuard"
"Hide" "" "DevDependencies.HideClick" "DevDependencies.SelGuard"
SEPARATOR
"Show All Items" "" "DevDependencies.ShowAllClick" ""
"Show Basic System" "" "DevDependencies.ToggleBasicSystemsClick" "DevDependencies.ShowBasicGuard"
"Expand All" "" "DevDependencies.ExpandAllClick" ""
"Collapse All" "" "DevDependencies.CollapseAllClick" ""
"Arrange Items" "" "DevDependencies.ArrangeClick" ""
SEPARATOR
"Create tool..." "" "DevDependencies.CreateToolClick" ""
SEPARATOR
"P&roperties..." "" "StdCmds.ShowProp" "StdCmds.ShowPropGuard"
END
The item called Properties in this menu opens the standard font dialog and lets the user select a font for the view. The typeface and style of the chosen font effects the text displaying the names of the modules.The size of the font effects the text and the width of the lines and the arrows.
PROCEDURE Deposit
Analyzes the dependencies for each module in the selected list of modules. Then a view, displaying a graph of the dependencies, is created and deposited. The base module name may be either given in full, or by alias if an alias has been defined in the enclosing module's IMPORT statement.
PROCEDURE CreateTool
Analyzes the dependencies for each module in the selected list of modules. Then a tool document is created for the given modules. The tool document contains compiling, unloading, linking and packing commands. The compiling and unloading commands are only created for the currently expanded modules. The linking command includes the standard BlackBox icons and the packing command always includes all modules independent of which modules are currently expanded or hidden. The base module name may be either given in full, or by alias if an alias has been defined in the enclosing module's IMPORT statement.
The following commands are only used for manipulating the view (ordered the way they appear in the menu above):
PROCEDURE CollapseClick
Called when Collapse is chosen from the menu. This procedure collapses the the selected modules in the graph.
PROCEDURE ExpandClick
Called when Expand is chosen from the menu. This procedure expands the the selected subsystems in the graph.
PROCEDURE NewAnalysisClick
Called when New Analysis is chosen from the menu. Starts a new analysis with the selected node as root, i.e. it creates a subgraph of the original graph.
PROCEDURE HideClick
Called when Hide is chosen from the menu. This procedure hides the selected nodes in the graph.
PROCEDURE ShowAllClick
Called when Show All Items is chosen from the menu. This procedure makes sure that all nodes in the graph are visible.
PROCEDURE ToggleBasicSystemsClick
Called when Show Basic System is chosen from the menu. This procedure shows or hides modules belonging to the basic BlackBox system.
PROCEDURE ExpandAllClick
Called when Expand All is chosen from the menu. This procedure expands all subsystems to modules.
PROCEDURE CollapseAllClick
Called when Collapse All is chosen from the menu. This procedure collapses all modules into subsystems.
PROCEDURE ArrangeClick
Called when Arrange Items is chosen from the menu. This procedure arranges the nodes in the graph in a structured way, with the modules from the original module list at the top.
PROCEDURE CreateToolClick
Called when Create tool is chosen from the menu. Calls CreateTool.
PROCEDURE SelGuard (VAR par: Dialog.Par)
Guard that checks if any nodes in the graph are selected.
PROCEDURE ModsGuard (VAR par: Dialog.Par)
Guard that checks if any modules in the graph are selected.
PROCEDURE SubsGuard (VAR par: Dialog.Par)
Guard that checks if any subsystems in the graph are selected.
PROCEDURE ShowBasicGuard (VAR par: Dialog.Par)
Guard for the Show Basic System menu item. | Dev/Docu/Dependencies.odc |
DevHeapSpy
DEFINITION DevHeapSpy;
VAR
par-: RECORD
allocated-, clusters-, heapsize-: INTEGER
END;
PROCEDURE GetAnchor (adr: INTEGER; OUT anchor: ARRAY OF CHAR);
PROCEDURE ShowAnchor (adr: INTEGER);
PROCEDURE ShowHeap;
END DevHeapSpy.
DevHeapSpy is a tool that visualizes the contents of heap memory. The dynamically allocated memory blocks are shown in an "interactive memory map" that is updated periodically. DevHeapSpy displays symbolic information about every memory block you point to with the mouse. This allows you to inspect the values of record fields in objects and browse through complex data structures.
The BlackBox heap is partitioned into clusters. Clusters are contiguous blocks of memory. Each cluster contains a number of heap objects. DevHeapSpy visualizes clusters with large grey blocks. The heap objects within a cluster are visualized by red and blue areas. The red areas represent portions of memory allocated to variables of some record type. The blue areas represent portions of memory allocated to dynamic arrays.
To display heap information, choose Heap Spy... from menu Info. This openes a small dialog box showing summary information about the heap.
To open a DevHeapSpy window, click on button Show Heap in the dialog box opened with Heap Spy.... This opens a window similar to the one shown in Figure 1. When you press the left mouse button within the area of a cluster, DevHeapSpy gives information about the object the mouse points to. If the mouse points to a heap object, i.e., to a red or blue area, the object is highlighted. If you release the mouse button while a heap object is highlighted, a debugger window will be opened that shows detailed symbolic information about the object.
The following command can be used:
"Heap Spy..." "" "StdCmds.OpenAuxDialog('Dev/Rsrc/HeapSpy', 'Heap Spy')" ""
VAR par-: RECORD
Interactor for the heap spy dialog.
allocated-: INTEGER
The number of currently allocated bytes.
clusters-: INTEGER
The number of currently allocated clusters.
heapsize-: INTEGER
The number of currently used bytes (the number of clusters times the size of one cluster).
PROCEDURE GetAnchor (adr: INTEGER; OUT anchor: ARRAY OF CHAR)
PROCEDURE ShowAnchor (adr: INTEGER)
PROCEDURE ShowHeap
Various procedures used in the heap spy dialog.
| Dev/Docu/HeapSpy.odc |
DevInspector
DEFINITION DevInspector;
IMPORT Dialog;
VAR
inspect: RECORD
control-: Dialog.String;
label: ARRAY 40 OF CHAR;
link, guard, notifier: Dialog.String;
level: INTEGER;
opt0, opt1, opt2, opt3, opt4: BOOLEAN
END;
PROCEDURE GetNext;
PROCEDURE Set;
PROCEDURE InitDialog;
PROCEDURE ControlGuard (VAR par: Dialog.Par);
PROCEDURE GuardGuard (VAR par: Dialog.Par);
PROCEDURE LabelGuard (VAR par: Dialog.Par);
PROCEDURE LevelGuard (VAR par: Dialog.Par);
PROCEDURE LinkGuard (VAR par: Dialog.Par);
PROCEDURE OptGuard (opt: INTEGER; VAR par: Dialog.Par);
PROCEDURE NotifierGuard (VAR par: Dialog.Par);
PROCEDURE Notifier (idx, op, from, to: INTEGER);
END DevInspector.
The inspector makes it possible to inspect and modify properties of a control. Currently, various types of controls are supported: command buttons, check boxes, radio buttons, edit fields, date fields, time fields, color fields, up/down-fields list boxes, selection boxes, combo boxes, and groups.
The inspector is opened with the Edit->ObjectProperties... command. It takes a singleton control as input (-> Controls). Starting the inspector is done indirectly by the framework, using the StdCmds.ShowProp command.
VAR inspect: RECORD
Interactor for a control view property dialog.
control-: Dialog.String
The control's name. This is the (possibly mapped) name of the control type.
label: ARRAY 40 OF CHAR
Label string of the control.
link: Dialog.String
Link to the interactor field, in the form module.variable.field.
guard: Dialog.String
Name of the control's guard command.
notifier: Dialog.String
Name of the control's notifier command.
level: INTEGER
Iff the value of a radio button is equal to level, the radio button is "on".
opt0, opt1, opt2, opt3, opt3: BOOLEAN
Various options which depend on the currently selected control. For example, a command button uses opt0 and opt1 to indicate the "default" or "cancel" properties.
PROCEDURE GetNext
Show the next control in this container. After the last control, GetNext wraps around to the first control.
PROCEDURE Set
Set the control's properties to the currently displayed values.
PROCEDURE InitDialog
Sets up the interactor according to the currently selected control.
PROCEDURE ControlGuard (VAR par: Dialog.Par)
PROCEDURE GuardGuard (VAR par: Dialog.Par)
PROCEDURE LabelGuard (VAR par: Dialog.Par)
PROCEDURE LevelGuard (VAR par: Dialog.Par)
PROCEDURE LinkGuard (VAR par: Dialog.Par)
PROCEDURE OptGuard (opt: INTEGER; VAR par: Dialog.Par)
PROCEDURE NotifierGuard (VAR par: Dialog.Par)
PROCEDURE Notifier (idx, op, from, to: INTEGER)
Various guards and notifiers used in the inspector dialog.
| Dev/Docu/Inspector.odc |
DevLinkChk
DEFINITION DevLinkChk;
IMPORT Dialog;
CONST oneSubsystem = 0; globalSubsystem = 1; allSubsystems = 2;
VAR
par: RECORD
scope: INTEGER;
subsystem: ARRAY 9 OF CHAR
END;
PROCEDURE Check (subsystem: ARRAY OF CHAR; scope: INTEGER; check: BOOLEAN);
PROCEDURE CheckLinks;
PROCEDURE ListLinks;
PROCEDURE Open (path, file: ARRAY OF CHAR; pos: INTEGER);
PROCEDURE SubsystemGuard (VAR p: Dialog.Par);
PROCEDURE CommandGuard (VAR p: Dialog.Par);
PROCEDURE SubsystemNotifier (op, from, to: INTEGER);
END DevLinkChk.
This tool module allows to check whether a hyperlink (-> StdLinks) points to an existing BlackBox document. this allows to find most "stale" links, i.e., links to non-existing files.
Menu command:
"Check Links..." "" "StdCmds.OpenAuxDialog('Dev/Rsrc/LinkChk', 'Check Links')" ""
CONST oneSubsystem , globalSubsystem, allSubsystems
Checking can occur in one specific subsystem (more exactly, in the files contained in the subsystem's Docu and Mod subdirectories); in the global Docu and Mod directories, or in these directories plus the Docu and Mod directories of all subsystems.
VAR par: RECORD
Interactor for CheckLinks and ListLinks. It defines what documents these commands operate on.
scope: INTEGER scope IN {oneSubsystem, globalSubsyste, allSubsystems}
The scope in which checking will occur, i.e., the directory or directories whose Docu and Mod subdirectories will be searched for files with links.
subsystem: ARRAY 9 OF CHAR valid iff scope = oneSubsystem
Subsystem name. Only legal if scope = oneSubsystem.
PROCEDURE Check (subsystem: ARRAY OF CHAR; scope: INTEGER; check: BOOLEAN)
Used internally.
PROCEDURE CheckLinks
Guard: CommandGuard
Check all links in the scope defined by the par interactor. Checking means that it is tested whether the target file of the following link-commands exists:
StdCmds.OpenMask
StdCmds.OpenBrowser
StdCmds.OpenDoc
StdCmds.OpenAuxDialog
Links that are stale are listed in a report text. For every stale link, the report contains one link that directly opens the culpable text and scrolls to the offending link view (using the Open command below).
PROCEDURE ListLinks
Guard: CommandGuard
Lists all links in the scope defined by the par interactor. Links are listed in a report text. For every link, the report contains one link that directly opens the relevant text and scrolls to the link view (using the Open command below).
PROCEDURE Open (path, file: ARRAY OF CHAR; pos: INTEGER)
Used internally. The procedure opens a file at location path and name file; scrolls to position pos; and selects the range [pos .. pos+1[.
PROCEDURE SubsystemGuard (VAR p: Dialog.Par)
PROCEDURE CommandGuard (VAR p: Dialog.Par)
PROCEDURE SubsystemNotifier (op, from, to: INTEGER)
Various guards and notifiers used for dialog Dev/Rsrc/LinkChk.
| Dev/Docu/LinkChk.odc |
DevLinker
DevLinker is the BlackBox linker. It is used to pack several BlackBox code files together into one executable file (.dll or .exe). It can be used to make independent versions of applications based on the BlackBox Component Framework. It can also be used to produce executables written in Component Pascal which don't relate to the BlackBox framework or use only a few BlackBox modules like the Kernel.
The linker can be started with one of the commands described below. Each of the commands needs a parameter text with the syntax:
<destFile> := {<module> {option}} {idNumber <resourceFile>}.
destFile is the name of the executable file to be created.
module is a Component Pascal module, the code file is loaded from the corresponding directory.
option is one of the following characters:
$ main module: the body of this module is called when the program starts.
+ identifies the kernel. A kernel must be present if the standard function NEW is used in some module. The kernel must export the procedures NewRec and NewArr.
# interface module: the exported procedures of this module are added to the export list.
See the description of the individual commands for a list of the legal options.
resourceFile is the name of a resource file. Currently icons (.ico), cursors (.cur), bitmaps (.bmp), windows resource files (.res), and type libraries (.tlb) are supported. The resource files are loaded from the Rsrc or Win/Rsrc directory.
idNumber is an integer used to reference the corresponding resource from the program.
The module list must be sorted such that an imported module textually precedes the module importing it. This rule also applies to the implicit kernel import when using NEW.
DevLinker.Link
Links a module set containing a dynamic module loader to an exe file.
At startup, the body of the main module is called.
Initialization and termination of the other modules is not done by the loader, it must be done by the runtime system (typically the loader).
BlackBox itself is linked with this command.
Legal options: $ +
DevLinker.LinkExe
Links an unextensible module set to an exe file (i.e., no loader is included).
At startup, the bodies of all modules are called in the correct order.
When the last body terminates, the terminators (CLOSE sections) of all modules are called in reverse order.
No runtime system is needed for initialization and termination.
Legal options: +
DevLinker.LinkDll
Links an unextensible module set to a dll file.
When the dll is attached to a process, the bodies of all modules are called in the correct order.
When the dll is released from the process, the terminators (CLOSE sections) of all modules are called in reverse order.
No runtime system is needed for initialization and termination.
Legal options: + #
DevLinker.LinkDynDll
(rarely used, present for completeness)
Links a module set containing a dynamic module loader to a dll file.
When the dll is attached to a process, the body of the main module is called.
When the dll is released from the process, the terminator (CLOSE section) of the main module is called.
Initialization and termination of the other modules must be done by the runtime system.
Legal options: $ + #
The reason for the different commands for static and dynamic systems is that there is no statically defined initialization sequence in a system that includes a dynamic loader. In BlackBox the Kernel (which is the lowest module in the module hierarchy) is specified as the main module. The body of the kernel then calls the bodies of all linked modules dynamically in the correct sequence. If there are no calls to the dynamic loader (via Dialog.Call) in the module bodies, the modules are initialized in the order in which they appear in the parameter text.
Examples
Standard BlackBox:
DevLinker.Link
BlackBox2.exe := Kernel$+ Utf WinKernel Files WinEnv WinFiles WinGui StdLoader WinLoader
1 BlackBox.res 1 Applogo.ico 2 Doclogo.ico 3 SFLogo.ico 4 CFLogo.ico 5 DtyLogo.ico 6 folderimg.ico 7 openimg.ico 8 leafimg.ico 1 Move.cur 2 Copy.cur 3 Link.cur 4 Pick.cur 5 Stop.cur 6 Hand.cur 7 Table.cur
Fully linked redistributable part of BlackBox:
DevLinker.Link MyBlackBox.exe :=
Kernel$+ Utf WinKernel Files WinEnv WinFiles WinPackedFiles WinGui StdLoader
Math Strings Dates Meta Fonts Log Librarian Dialog
Services Ports Stores Converters Sequencers Models Printers Views
Controllers Properties Printing Mechanisms Containers
Documents Windows StdCFrames Controls
StdRegistry StdInterpreter
WinRegistry WinFonts WinDates
TextModels TextRulers TextSetters TextViews
StdScrollers StdDialog StdApi StdCmds
WinPorts OleData WinMechanisms WinPrinters WinDialog WinClipboard WinCFrames WinCmds
TextControllers TextMappers TextCmds
StdLinks StdMenuTool StdScrollbars StdRasters
StdDocuments StdWindows StdMenus StdGrids StdLog StdTiles StdInflate StdRastersPng
FormModels FormViews FormControllers FormGen FormCmds
StdFolds StdDebug StdTextConv StdClocks StdStamps StdCoder StdStdCFrames
OleWindows OleStorage
Loop Console In Out
WinConsole WinBackends WinShowHook WinRasters WinConfig WinInit
StdConfig
1 Applogo.ico 2 Doclogo.ico 3 SFLogo.ico 4 CFLogo.ico 5 DtyLogo.ico
1 Move.cur 2 Copy.cur 3 Link.cur 4 Pick.cur 5 Stop.cur 6 Hand.cur 7 Table.cur
MyBlackBox.exe will need System/Rsrc/Menus.odc to be destributed with it or to be packed (see DevPacker documentation)
DevPacker.PackThis MyBlackBox.exe :=
System/Rsrc/Menus.odc
Simple independent application:
DevLinker.LinkExe
Simple.exe := Simple 1 Applogo.ico ~
Simple DLL:
DevLinker.LinkDll
Mydll.dll := Mydll# ~
MODULE Simple;
(* simple windows application *)
IMPORT S := SYSTEM, WinApi;
CONST
message = "Hello World";
iconId = 1;
VAR
instance: WinApi.HINSTANCE;
mainWnd: WinApi.HWND;
PROCEDURE WndHandler (wnd, msg, wParam, lParam: INTEGER): INTEGER;
VAR res: INTEGER; ps: WinApi.PAINTSTRUCT; dc: WinApi.HDC;
BEGIN
IF msg = WinApi.WM_DESTROY THEN
WinApi.PostQuitMessage(0)
ELSIF msg = WinApi.WM_PAINT THEN
dc := WinApi.BeginPaint(wnd, ps);
res := WinApi.TextOut(dc, 50, 50, message, LEN(message));
res := WinApi.EndPaint(wnd, ps)
ELSIF msg = WinApi.WM_CHAR THEN
res := WinApi.Beep(800, 200)
ELSE
RETURN WinApi.DefWindowProc(wnd, msg, wParam, lParam)
END;
RETURN 0
END WndHandler;
PROCEDURE OpenWindow;
VAR class: WinApi.WNDCLASS; res: INTEGER;
BEGIN
class.hCursor := WinApi.LoadCursor(0, S.VAL(WinApi.PtrSTR,
WinApi.IDC_ARROW));
class.hIcon := WinApi.LoadIcon(instance, S.VAL(WinApi.PtrSTR, iconId));
class.lpszMenuName := NIL;
class.lpszClassName := "Simple";
class.hbrBackground := WinApi.GetStockObject(WinApi.WHITE_BRUSH);
class.style := WinApi.CS_VREDRAW + WinApi.CS_HREDRAW
(* + WinApi.CS_OWNDC + WinApi.CS_PARENTDC *);
class.hInstance := instance;
class.lpfnWndProc := WndHandler;
class.cbClsExtra := 0;
class.cbWndExtra := 0;
res := WinApi.RegisterClass(class);
mainWnd := WinApi.CreateWindowEx({}, "Simple", "Simple Application",
WinApi.WS_OVERLAPPEDWINDOW,
WinApi.CW_USEDEFAULT, WinApi.CW_USEDEFAULT,
WinApi.CW_USEDEFAULT, WinApi.CW_USEDEFAULT,
0, 0, instance, 0);
res := WinApi.ShowWindow(mainWnd, WinApi.SW_SHOWDEFAULT);
res := WinApi.UpdateWindow(mainWnd);
END OpenWindow;
PROCEDURE MainLoop;
VAR msg: WinApi.MSG; res: INTEGER;
BEGIN
WHILE WinApi.GetMessage(msg, 0, 0, 0) # 0 DO
res := WinApi.TranslateMessage(msg);
res := WinApi.DispatchMessage(msg);
END;
WinApi.ExitProcess(msg.wParam)
END MainLoop;
BEGIN
instance := WinApi.GetModuleHandle(NIL);
OpenWindow;
MainLoop
END Simple.
MODULE Mydll;
(* sample module to be linked into a dll *)
PROCEDURE Gcd* (a, b: INTEGER): INTEGER;
BEGIN
WHILE a # b DO
IF a > b THEN a := a - b ELSE b := b - a END
END;
RETURN a
END Gcd;
PROCEDURE Lcm* (a, b: INTEGER): INTEGER;
BEGIN
RETURN a * b DIV Gcd(a, b)
END Lcm;
END Mydll.
| Dev/Docu/Linker.odc |
DevMarkers
DEFINITION DevMarkers;
PROCEDURE NextError;
PROCEDURE ToggleCurrent;
PROCEDURE UnmarkErrors;
... plus some private items ...
END DevMarkers.
Error markers indicate compiler errors in-place in the compiled text.
This module contains several other items which are used internally.
Possible menu:
MENU
"Unmar&k Errors" "" "DevMarkers.UnmarkErrors" "TextCmds.FocusGuard"
"Next E&rror" "" "DevMarkers.NextError" "TextCmds.FocusGuard"
"To&ggle Error Mark" "" "DevMarkers.ToggleCurrent" "TextCmds.FocusGuard"
END
PROCEDURE NextError
Guard: TextCmds.FocusGuard
Move caret forward after the next error marker. If there is none, the text is scrolled to the beginning.
PROCEDURE ToggleCurrent
Guard: TextCmds.FocusGuard
Toggle the state of the marker before the caret.
PROCEDURE UnmarkErrors
Guard: TextCmds.FocusGuard
Removes all error markers.
| Dev/Docu/Markers.odc |
DevMsgSpy
A tool that allows to inspect the messages which are sent to a view.
About the message spy
Message Spy is a tool that logs the messages which are sent to a view through one of the methods HandleCtrlMsg, HandleModelMsg, HandlePropMsg, or HandleViewMsg. The message spy displays the type of all messages which are sent to the view and, upon request, also the complete message records.
This tool can help you if your view does not behave as you expect. With the message spy you can learn which messages the frameworks sends to your view and thus which messages you should answer.
How to inspect a view
To open the Message Spy, choose Message Spy... from menu Info. This opens a dialog box similar to the one shown in Figure 1. If you want to inspect a view with the message spy, select it as a singleton and press the Add View button. If you want to remove a view from the message spy, select it as a singleton and press the same button, which is now labeled Remove View.
Figure 1: The tool window of Message Spy
The tool dialog box of the message spy is divided into two parts. In the upper part, all recognized message types are displayed. This list grows over time. Whenever the message spy meets a message of a new type through any of its inspected views, this type is added to the list of recognized types. Since you might loose the overview over the message types soon, the Mark New Messages in List option causes all newly added message types to be selected. In this way you easily learn about messages involved in a particular action. The list of message types can be cleared with the Clear List button.
If the option Show Messages in Log is selected, then all messages sent to all inspected views whose types are selected in the type selection box are displayed in the lower part of the message spy dialog box. For each message, the type name is displayed followed by a diamond. If this diamond is clicked, then all instance variables of the message record are displayed in a separate window. The log is a regular text which can be scrolled and edited.
More information
As message records are static (stack-allocated) variables they have to be copied in order to make them accessible beyond the call of the message handler. The consequence thereof is that only the contents of the message upon message call can be inspected, not how the message is answered by a particular view.
Note that the message spy displays messages of any type sent to an intercepted view, this also includes messages of types which are not exported.
In order to intercept a view, the message spy adds a wrapper around the original view. This wrapper displays the messages and then forwards them to the wrapped view. By replacing a view by its wrapper, the type of the view changes, and thus some tools which depend on a view's type no longer work with inspected views.
Menu command:
"Message Spy..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/MsgSpy', 'Message Spy')" ""
| Dev/Docu/MsgSpy.odc |
DevPacker
DEFINITION DevPacker;
PROCEDURE ListFromSub (sdir: ARRAY OF CHAR);
PROCEDURE ListLoadedModules;
PROCEDURE PackThis;
END DevPacker.
Module DevPacker is used to pack any kind of files into an existing exe-file. These files can be read with the help of HostPackedFiles. There is no explicit dependency between DevPacker and HostPackedFiles, but since one writes to the exe-file and the other reads from it, there is an implicit dependency, with the file format of the exe-file as interface.
DevDependencies.CreateTool can be used to create a pack command for a set of modules.
PROCEDURE PackThis;
Used together with a DevCommander. It reads a list of file names and packs the given files into an exe-file. The exe-file appears first in the list followed by the symbol ":=". It is also possible to pack a file under a different name than it appears in the current filesystem. To specify another name for a file the special symbol "=>" is used.
Thus, the syntax in EBNF is as follows:
<exeFileName> := <filename> [=> <filename>] {<filename> [=> <filename>]}
Both the exeFileName and the fileName can be specified using absolute paths (including drive name) or using relative paths to the BlackBox directory. If any file contains special characters in their name, such as space or dash, then the file name should be embedded in quotation marks ("filename") to be parsed correctly. The parsing stops as soon as it encounters any unrecognized character such as a comma or a tilde.
Before the packing starts the list of files are validated. If some files are not found, then the package command is discontinued and the exe-file is left untouched. If a file name appears more than once in the list, a message that the file appears more than once is presented but the package command is continued and the file is packed just once into the exe-file.
It is important that the exe-file does not appear in the list of files to be packed. This would cause the exe-file to be packed into itself with undefined result. Therefore the packing is cacelled if the exe-file appears in the list.
Example:
DevPacker.PackThis exefilename.exe :=
Docu/Tour.odc "C:\Program files\BlackBox\License.txt" Test/Code/MyConfig.ocf => Code/Config.ocf
PROCEDURE ListFromSub (sdir: ARRAY OF CHAR);
Examines the directory sdir and all its subdirectories. If it finds any files it opens a new document and writes a packing command for the files found. sdir can be an absolute path, including a drive name, or a relative path to the BlackBox directory. It can also be an empty string, in which case the entire BlackBox directory will be listed.
Example: "DevPacker.ListFromSub('Text')"
PROCEDURE ListLoadedModules;
Examines the currently loaded modules and creates a text with a packing command for them. This can be used to quickly find out which modules are needed for a running application. The problem is that too many modules may be packed and that files such as resources and documentaion are not included.
Example: DevPacker.ListLoadedModules
Absolute vs. Relative paths in filenames
Imagine that BlackBox is installed in directory D:\BlackBox. Then the file name D:\BlackBox\Std\Code\Log.ocf (absolute path) denotes the same file as Std\Code\Log.ocf (relative path) as far as the packer is concerned. But the packer packs the file into the exe-file with the path given in the command. This makes a crucial difference for HostPackedFiles which reads the exe-file. If the exe-file for example is started in directory C:\temp, and the program makes a call to StdLog, then this command will work if the file was packed using a relative path, but not if it was packed using an absolute path. On the other hand, if the file was packed using an absolute path, a call to open file D:\BlackBox\Std\Code\Log.ocf will work even if no physical drive called D: is present on the machine.
Regarding exe-files
The packer cannot create an exe-file, it can only pack files into an existing exe-file. This means that the linker has to be used to create a minimum exe-file for the packer to use. This minimum exe-file must have HostPackedFiles linked in since this is the module that allows for extraction of the files. The minimum linker command is as follows:
DevLinker.Link exefilename.exe := Kernel$+ Files Utf HostEnv HostFiles HostPackedFiles StdLoader
For HostPackedFiles to be able to find files in the exe-file, it must have the same format as when the packer packed the files into it. This means that it is not possible to add resource, like icons and cursors, after files have been packed to an exe-file. Any such operations should be done before the packing starts. (See the DevLinker‑documentation for details about how to add icons already when linking.) It is however possible to change the name of the exe-file after the packing is done.
Another limitation is that the packer is not able to append files. It packs the whole list of files and writes a table of these files. If PackThis is called again it destroys the information about the former files in the exe-file.
| Dev/Docu/Packer.odc |
Platform-Specific Issues
1: Cross-plarform
1 ModuleSYSTEM
2 StartupofBlackBox
3 Using NEW and garbage collection in your applications
4 Component Pascal compiler options
5 Runtime range checks
6 Stack Size
10: Windows
10 Command line parametersofBlackBox
11 UsingDLLsinBlackBoxmodules
12 UsingCOMwithoutDirect-To-COMcompiler
13 Windows-specificinformationinBlackBox
14 Runtime type system
15 LinkingBlackBoxapplications
Windowsprogramminginterfaces
OLEAutomation
TheBlackBoxlinker
20: Linux
21 Linux Environment parameters of BlackBox
22 Endless loop
25 LinkingBlackBoxapplications
30: OpenBSD
40: FreeBSD
1 Module SYSTEM
Module SYSTEM contains certain procedures that are necessary to implement low-level operations. It is strongly recommended to restrict the use of these features to specific low-level modules, as such modules are inherently non-portable and usually unsafe. SYSTEM is not considered as part of the language Component Pascal proper.
The procedures contained in module SYSTEM are listed in the following table. v stands for a variable. x, y, and n stands for expressions. T stands for a type. P stands for a procedure. M[a] stands for memory value at address a.
Function procedures
Name Argument types Result type Description
ADR(v) any INTEGER address of variable v
ADR(P) P: PROCEDURE INTEGER address of Procedure P
ADR(T) T: a record type INTEGER address of Descriptor of T
LSH(x, n) x, n: integer type* type of x logical shift (n > 0: left, n < 0: right)
ROT(x, n) x, n: integer type* type of x rotation (n > 0: left, n < 0: right)
TYP(v) record type INTEGER type tag of record variable v
VAL(T, x) T, x: any type T x interpreted as of type T
* integer types without LONGINT
Proper procedures
Name Argument types Description
GET(a, v) a: INTEGER; v: any basic type, v := M[a]
pointer type, procedure type
PUT(a, x) a: INTEGER; x: any basic type, M[a] := x
pointer type, procedure type
GETREG(n, v) n: integer constant, v: any basic type, v := Register n
pointer type, procedure type
PUTREG(n, x) n: integer constant, x: any basic type, Register n := x
pointer type, procedure type
MOVE(a0, a1, n) a0, a1: INTEGER; n: integer type M[a1..a1+n-1] :=
M[a0..a0+n-1]
The register numbers for PUTREG and GETREG are:
0: EAX, 1: ECX, 2: EDX, 3: EBX, 4: ESP, 5: EBP, 6: ESI, 7: EDI.
Warning
VAL, PUT, PUTREG, and MOVE may crash BlackBox and/or Windows when not used properly.
Never use VAL (or PUT or MOVE) to assign a value to a BlackBox pointer. Doing this would corrupt the garbage collector, with fatal consequences.
System Flags
The import of module SYSTEM allows to override some default behavior of the compiler by the usage of system flags. System flags are used to configure type- and procedure declarations. The extended syntax is given below.
Type = Qualident
| ARRAY ["[" SysFlag "]"] [ConstExpr {"," ConstExpr}]
OF Type
| RECORD ["[" SysFlag "]"] ["("Qualident")"] FieldList
{";" FieldList} END
| POINTER ["[" SysFlag "]"] TO Type
| PROCEDURE [FormalPars].
ProcDecl = PROCEDURE ["[" SysFlag "]"] [Receiver] IdentDef
[FormalPars] ";"
DeclSeq [BEGIN StatementSeq] END ident.
FPSection = [VAR ["[" SysFlag "]"]] ident {"," ident} ":" Type.
SysFlag = ConstExpr | ident.
For SysFlags either the name of the flag or the corresponding numeric value can be used.
System flags for record types
Name Value Description
untagged 1 No type tag and no type descriptor is allocated.
The garbage collector ignores untagged variables.
NEW is not allowed on pointers to untagged variables.
No type-bound procedures are allowed for the record.
Pointers to untagged record type or extensions of this
record type inherit the attribute of being untagged.
The offsets of the fields are aligned to
MIN(4-byte, size), where size is the size of the field.
The size of the record and the offsets of the fields are
aligned to 32-bit boundaries.
noalign 3 Same as untagged but without alignment.
align2 4 Same as untagged but with
MIN(2-byte, size) alignment.
align8 6 Same as untagged but with
MIN(8-byte, size) alignment.
union 7 Untagged record with all fields allocated at offset 0.
The size of the record is equal to the size of the
largest field.
Used to emulate C union types.
System flags for array types
Name Value Description
untagged 1 No typetag and no type descriptor is allocated.
The garbage collector ignores untagged variables.
NEW is not allowed on pointers to untagged variables.
Pointers to this array type inherit the attribute of
being untagged.
Only one-dimensional untagged open arrays
are allowed.
For open untagged arrays, index bounds are
not checked.
System flags for pointer types
Name Value Description
untagged 1 Not traced by the garbage collector.
No type-bound procedures are allowed for the pointer.
Must point to an untagged record.
System flags for VAR parameters
Name Value Description
nil 1 NIL is accepted as formal parameter.
Used in interfaces to C
functions with pointer type parameters.
System flags for procedures
Name Value Description
code 1 Definition of a Code procedure (see below).
callback 2 WinApi callback function; uses __stdcall calling conventions.
ccall -10 Procedure uses CCall calling convention.
Code procedures
Code procedures make it possible to use special code sequences not generated by the compiler. They are declared using the following special syntax:
ProcDecl = PROCEDURE "[" SysFlag "]" IdentDef [FormalPars]
[ConstExpr {"," ConstExpr}] ";".
The list of constants declared with the procedure is interpreted as a byte string and directly inserted in the code ("in-line") whenever the procedure is called. If a parameter list is supplied, the actual parameters are pushed on the stack from right to left. The first parameter however is kept in a register. If the type of the first parameter is REAL or SHORTREAL, it is stored in the top floating-point register. Otherwise the parameter (or in the case of a VAR/IN/OUT parameter its address) is loaded into EAX. For function procedures the result is also expected to be either in the top floating-point register or in EAX, depending on its type. Be careful when using registers in code procedures. In general, the registers ECX, EDX, ESI, and EDI may be used. Parameters on the stack must be removed by the procedure.
Examples
PROCEDURE [code] Sqrt (x: REAL): REAL (* Math.Sqrt *)
0D9H, 0FAH; (* FSQRT *)
PROCEDURE [code] Erase (adr, words: INTEGER) (* erase memory area *)
089H, 0C7H, (* MOV EDI, EAX *)
031H, 0C0H, (* XOR EAX, EAX *)
059H, (* POP ECX *)
0F2H, 0ABH; (* REP STOS *)
2 Startup of BlackBox
The startup of BlackBox happens in several steps.
Step 1: The operating system starts the application
BlackBox consists of a small linked application and many unlinked code files (one per module). The linked application consists of at least the BlackBox Kernel module. When the operating system starts up BlackBox, it gives control to the module body of Kernel.
Step 2: The kernel loads all prelinked modules
The kernel initializes its data structures, in particular for memory management and exception handling. Then it executes the module bodies of the other modules which are linked in the application, in the correct order.
Usually, the module StdLoader is among the prelinked modules, along with several modules that it needs, in particular Files and LinFiles/WinFiles. Module StdLoader implements the linking loader which can dynamically link and load a module's code file. LinLoader/WinLoader loads LinInit/WinInit accordinly.
Step 3: LinLoader or WinLoader loads the BlackBox library and core framework
The standard implementation of Init imports all core framework modules and their standard implementations, but not extension subsystems such as the Text or Form subsystem. These modules are loaded before the body of Init performs the following actions:
• It tries to call Startup.Setup.
Usually, module Startup does not exist. It could be used to install some services before the main window is opened and before the text subsystem or other subsystems are loaded.
• It tries to load module DevDebug.
DevDebug is expected to replace the kernel's rudimentary exception handling facilities by a more convenient tool. Note that the standard implementation of DevDebug uses the text subsystem, which thus is loaded also.
If loading of DevDebug is not successful, it is attempted to load module StdDebug. This is a reduced version of DevDebug which can be distributed along with an application.
• It registers the document file converter (importer/exporter).
This enables BlackBox to open and save standard BlackBox documents.
• It tries to call StdMenuTool.UpdateAllMenus.
This command reads and interprets the System/Rsrc/Menus text, and builds up the menus accordingly. Note that the standard implementation of StdMenuTool uses the text subsystem.
• It tries to call StdConfig.Setup.
This is the usual way to configure BlackBox. The standard implementation of StdConfig.Setup installs the standard file converters, calls StdMenuTool.UpdateAllMenus to read and interpret the System/Rsrc/Menus text, and builds up the menus accordingly, then it creates workspace and opens the log text.
• It calls the main event loop (Loop.Start).
After the event loop is left (because the user wants to quit the application), the kernel is called to clean up, before the application is left entirely.
3 Using NEW and garbage collection in your applications
If you are calling NEW in your application and thereby implicitly use the garbage collector, you must link the Kernel into the application. The NEW-procedure is implemented in the kernel, the compiler just generates the code to call this procedure. So every module using NEW has a hidden import of the kernel.
Don't call WinApi.ExitProcess directly when "importing" the kernel, call Kernel.Quit with parameter 0 instead to assure that occupied system resources get properly released before the application is terminated.
Programs don't need to call the garbage collector explicitly. If the NEW-procedure cannot satisfy a request for heap space, it calls the garbage collector internally before allocating a new heap block from the Windows Memory Manager. The garbage collector marks pointers in stack frames and is able to run anytime.
The garbage collector reclaims all heap objects (dynamic record or array variables) that are not used anymore. "Unused" means that the object isn't directly reachable from some "root" pointer, or indirectly via a pointer chain starting from a root pointer. Any global variable which contains a pointer is such a root. If a root pointer isn't NIL, then it "anchors" a data structure. A heap object that isn't anchored anymore will eventually be collected by the garbage collector.
To allow the collector to follow pointer chains, there must be some information about the heap objects that are being traversed. In particular, it must be known where there are pointers in the object, if any. All objects of the same type share a common type descriptor, which is created when its defining module is loaded.
All dynamically allocated Component Pascal records contain a hidden field, which is called the type tag. The type tag points to the type descriptor that contains all type information needed at run-time. Method calls, type tests and the garbage collector all use the information which is stored in the type descriptor. The type descriptor is allocated only once for every record type in the system.
Dynamically allocated arrays use a size descriptor to check the bounds of indexes. The size descriptor also contains the type tag of the element type. For every single dynamic array a size descriptor is needed.
The additional storage required to "tag" objects makes their memory layout different from untagged records provided by the operating system or some procedural shared library. Type tags are critical; they must not be damaged, otherwise the garbage collector will crash the system at some point in time.
4 Component Pascal compiler options
The Component Pascal compiler supports the following options for compiling a module. Generally, it is recommended to use the default settings (no options) but there may be exceptions.
+ Switch on all runtime range checks. This generates slightly larger code files and increases the runtime. In most situations the difference is small. For the default behavior see Runtime range checks below.
- Switch off emitting the source code position. This generates slightly more compact code files but removes the link to the terminated procedure's source code position in the trap viewer.
-- In addition to "-" switch off emitting symbolic information for structured global variables.
--- In addition to "--" switch off emitting symbolic information for all global variables.
---- In addition to "---" switch off code file generation.
! Switch off runtime checking of ASSERT statements. Use this option only for very time critical code.
!! In addition to "!" switch off array index checks and pointer initialization. Use this option at your own risk.
? Switch on emitting of (COM related) warnings or hints even if there are no errors.
@ Switch on trapping on first error.
$ Switch on syntax extensions for compatibility with Oberon.
(...) DevSelector options.
5 Runtime range checks
The Component Pascal Language Report does not specify the out-of-range behaviour of the built in arithmetic and set functions, but deliberately allows the compiler writer freedom to make implementation decisions. Some of the current default decisions with this compiler are documented below, primarily because they can lead to unexpected behaviour. These behaviours are not considered to be bugs, and are considered to be within the freedom permitted by the Language Report. Developers are advised to exploit these behaviours with care as:
- other compilers may behave differently
- this compiler may behave differently in the future
- code that uses them may be hard for another reader to understand.
INTEGER arithmetic (+, -, *, DIV, INC, DEC) is not range checked, and the low order 32 bits of the result are returned. This is equivalent to reducing the result MOD 2^32, to a number in the range [-2^31 : 2^31).
LONGINT arithmetic (+, -, *, DIV) is range checked, and overflows lead to a run-time "undefined real result" exception. The explanation for this behaviour is that INTEGER arithmetic uses integer instructions on the main CPU, whereas LONGINT arithmetic uses floating point instructions on the co-processor. INC and DEC are not range-checked, and the low order 64 bits of the result are returned. This is equivalent to reducing the result MOD 2^64, to a number in the range [-2^63 : 2^63).
SHORT(x) is without range checking. In case of x: REAL an overflow leads to infinity. In case of x being any integer type, it returns the low order half of the argument.
ENTIER(x) is range checked. Overflows lead to a run-time "undefined real result" exception.
SHORT(ENTIER(x)) and SHORT(SHORT(ENTIER(x))) are range checked with respect to the outermost integer type. Overflows lead to a run-time "undefined real result" exception. A third SHORT leading to BYTE is range checked with respect to INTEGER.
Note carefully that using a compound expression in case of out-of-range values is not functionally equivalent to assigning the intermediate LONGINT value to a variable.
Explanation: Using the floating point unit to perform the compound type transfer in one operation is more efficient than performing the two operations sequentially. The SHORT function is defined as the identity operation, which is clearly only possible for in-range values. It is not defined for out-of-range values.
REAL arithmetic (+, -, *, /) is not range checked but overflows lead to infinity (INF) and underflows lead to zero (0). Internally, all REAL operations are done using the extended 80 bits precision format of the IA32 floating point unit, then converted to 64 bit precision when assigned to a REAL variable or when floating point registers are saved on the stack prior to a function call. This design choice generally reduces arithmetic rounding errors. It does mean that breaking a compound expression into parts may not lead to exactly equivalent results. Constant expression evaluation in the compiler uses 64 bits only because it needs to store intermediate values to memory.
Example:
x := Math.Pi(); ASSERT(x = Math.Pi(), 30)
leads to a TRAP, and so does
ASSERT(Math.Pi() = Math.Pi(), 30).
In this case the first call is rounded to 64 bits, the second is left at 80.
The SET expression e IN s does not check if e is within {0..31}. The resulting behavior depends on s being in a register or in memory. In case of a register e MOD 32 IN s is returned. In case of memory, s is treated as an ARRAY of SET and e MOD 32 IN s[e DIV 32] is returned, so out-of-range values for e attempt to read memory outside the actual memory allocated for s. This leads to an "illegal memory read" exception if the resulting address is not mapped. If the resulting address is mapped, it leads to a result which is very random.
INCL(s, e) and EXCL(s, e) use e MOD 32 in order not to violate memory integrity.
6 Stack Size
The reserved stack size of a linked executable is 2MB of which 64KB are committed immediately. The uncommitted stack space grows on demand up to 2MB where a stack overflow trap would be reported. These settings are hard-coded in the module DevLinker and are also used for the BlackBox.exe file in the standard BlackBox distribution. They are a good choice for most applications and it is best not to change them.
For rare cases, however, it might be necessary to configure a larger stack size. This can be accomplished by adapting the source code of DevLinker. The value marked as stack reserve size in DevLinker.WriteHeader defines the reserved stack size when linking a new exe file but there is a subtle dependency on the heap size reserved in WinKernel.AllocClusterMem (see constant monoClusterSize). The total size of the reserved heap plus the committed stack must not exceed some limit or otherwise Windows API functions may run out of memory. A good test for a working setup is to commit all the stack (i.e. set the value marked as stack commit size to the same value as stack reserve size), link a new exe file, start it, open a file dialog box with the menu item File->Open..., and see if it shows any anomalies. Examples are black squares instead of icons, missing tree view, or a TRAP 100 in Dialog.GetIntSpec with res = 2 indicating an out-of-memory error. The File->Open test should be repeated at least ten times. Experiments showed that for a stack reserve/commit size of 32MB the heap must be reduced to 150MB.
Windows Specific
10 Command line parameters of BlackBox
The command line parameters of BlackBox start with the letter '/' or alternatively the letter '-' immediately followed by a case insensitive parameter name. Depending on the parameter, further parameter values may be required. Each parameter value is separated by white space. If a parameter value contains spaces, it must be enclosed in single or double quotes.
The parameters are:
/USE path
Use path for lookup of relative file paths prior to looking them up in the startup or custom directory.
If path is relative it refers to the current directory.
/CUSTOM path
Use path for lookup of relative file paths prior to looking them up in the startup directory.
/PAR parameters
Specify parameters available via Dialog.commandLinePars.
/INIFILE iniFile
Do not use the Windows registry but use the specified Windows .ini file instead.
The path to the iniFile may be relative or absolute.
/PORTABLE
Short form of /INIFILE where the relative path Dialog.appName followed by ".ini" is used for the .ini file.
/O file
Open the specified file upon startup.
Any parameter value not belonging to a parameter name will also be opened, i.e. /O can be omitted.
/P file
Open and print the specified file.
/LOAD module
Load the specified module upon startup.
/EMBEDDING
Start as server.
/NOAPPWIN
Start without an application window.
/NOSCROLL
Do not show scroll bars in the application window.
/FULLSIZE
Start in fullscreen mode.
/LTRB left top right bottom
Specify the window position of the next window to be opened with /O.
/LANG language
Run BlackBox localized to the specified two letter language code.
11 Using DLLs in BlackBox modules
Any 32-bit DLL can be imported in Component Pascal like a normal Component Pascal module. This holds for Windows system modules (kernel, user, gdi, ...) as well as for any custom DLL written in any programming language. Be aware that the safety qualities of Component Pascal (no dangling pointers, strict type-checking, etc.) are lost if you interface to a DLL written in another programming language.
Interface modules
Type information about objects imported from a DLL must be present in a symbol file for the compiler to work properly. Such special symbol files can be generated through so-called interface modules. An interface module is a Component Pascal module marked by a system flag after the module name. The system flag consists of the name of the corresponding DLL enclosed in square brackets. An interface module can only contain declarations of constants, types, and procedures headings. No code file is generated when an interface module is compiled.
Name aliasing
The Component Pascal name of an object imported from a DLL can be different from the corresponding name in the export table of the DLL. To achieve this the DLL name is appended to the Component Pascal name as a system flag. In addition, the system flag may specify a different DLL than the one declared in the module header. This allows to use a single interface module for a whole set of related DLLs. It is also possible to have multiple interface modules referring to the same DLL. Interface procedures cannot have a body, nor an "END identifier" part, they are only signatures.
The extend syntax for interface modules is given below:
Module = MODULE ident ["[" SysString "]"] ";"
[ImportList] DeclSeq [BEGIN StatementSeq] END ident ".".
ProcDecl = PROCEDURE ["[" SysFlag "]"] [Receiver]
IdentDef ["[" [SysString ","] SysString "]"] [FormalPars] ";"
DeclSeq [[BEGIN StatementSeq] END ident].
SysString = string.
There is no aliasing for types and constants, because they are not present in export lists and thus may have arbitrary names.
The following example summarizes the aliasing capabilities:
MODULE MyInterface ["MyDll"];
PROCEDURE Proc1*; (* Proc1 from MyDll *)
PROCEDURE Proc2* ["BlaBla"]; (* BlaBla from MyDll *)
PROCEDURE Proc3* ["OtherDll", ""]; (* Proc3 from OtherDll *)
PROCEDURE Proc4* ["OtherDll", "DoIt"]; (* DoIt from OtherDll *)
END MyInterface.
A SysString for a DLL may not contain an entire path name. It should be just the name of the DLL, without the ".dll" suffix. The following search strategy is used:
- BlackBox directory
- Windows\System directory
- Windows directory
Data types in interface modules
Always use untagged records as replacements for C structures, in order to avoid the allocation of a type tag for the garbage collector. The system flag [untagged] marks a type as untagged (no type information is available at run-time) with standard alignment rules for record fields (2-byte fields are aligned to 2-byte boundaries, 4-byte or larger fields to 4-byte boundaries). The system flags [noalign], [align2], and [align8] also identify untagged types but with different alignments for record fields.
Like all system flags, "untagged" can only be used if module SYSTEM is imported.
Example:
RECORD [noalign] (* untagged, size = 7 bytes *)
c: SHORTCHAR; (* offset 0, size = 1 byte *)
x: INTEGER; (* offset 1 , size = 4 bytes *)
i: SHORTINT (* offset 5, size = 2 bytes *)
END
Procedures
Component Pascal procedure calls conform to the StdCall calling convention (parameters pushed from right to left, removed by called procedure). If the CCall convention (parameters removed by caller) is needed for some DLL procedures, the corresponding procedure declaration in the interface module must be decorated with the [ccall] system flag.
No special handling is required for callback procedures.
For parameters of type POINTER TO T it is often better to use a variable parameter of type T rather than to declare a corresponding pointer type. Declare the VAR parameter with system flag [nil] if NIL must be accepted as legal actual parameter.
Example:
C:
BOOL MoveToEx(HDC hdc, int X, int Y, LPPOINT lpPoint)
Component Pascal:
PROCEDURE MoveToEx* (dc: Handle; x, y: INTEGER; VAR [nil] old: Point): Bool
Correspondence between Component Pascal and C data types
unsigned char = SHORTCHAR (1 byte)
WCHAR = CHAR (2 bytes)
signed char = BYTE (1 byte)
short = SHORTINT (2 bytes)
int = INTEGER (4 bytes)
long = INTEGER (4 bytes)
LARGE_INTEGER = LONGINT (8 bytes)
float = SHORTREAL (4 bytes)
double = REAL (8 bytes)
Note that Bool is not a data type in C but is defined as int (= INTEGER). 0 and 1 must be used for assignments of FALSE and TRUE and comparisons with 0 have to be used in conditional statements (IF b # 0 THEN ... END instead of IF b THEN ... END).
Note that it is not possible to unload a DLL from within BlackBox. To avoid having to exit and restart your development environment repeatedly, it is a good idea to test the DLL that you are developing from within another instance of the BlackBox application.
12 Using COM without Direct-To-COM compiler
Microsoft's Component Object Model (COM) is supported by a Direct-To-COM compiler. This compiler makes using COM safer and more convenient. However, for casual use of COM, the approach described in this chapter can be used. It uses normal untagged records and procedure variables to create COM-style method tables ("vtbl") for objects. The following example shows how it works:
MODULE Ddraw ["DDRAW.DLL"];
TYPE
GUID = ARRAY 4 OF INTEGER;
PtrIUnknown = POINTER TO RECORD [untagged]
vtbl: POINTER TO RECORD [untagged]
QueryInterface: PROCEDURE (this: PtrIUnknown; IN iid: GUID; OUT obj: PtrIUnknown): INTEGER;
AddRef: PROCEDURE (this: PtrIUnknown): INTEGER;
Release: PROCEDURE (this: PtrIUnknown): INTEGER;
END
END;
PtrDirectDraw = POINTER TO RECORD [untagged]
vtbl: POINTER TO RECORD [untagged]
QueryInterface: PROCEDURE (this: PtrDirectDraw; IN iid: GUID; OUT obj: PtrIUnknown): INTEGER;
AddRef: PROCEDURE (this: PtrDirectDraw): INTEGER;
Release: PROCEDURE (this: PtrDirectDraw): INTEGER;
Compact: PROCEDURE (this: PtrDirectDraw): INTEGER;
...
SetCooperativeLevel: PROCEDURE (this: PtrDirectDraw; w, x: INTEGER): INTEGER;
...
END
END;
PROCEDURE DirectDrawCreate* (IN guid: GUID; OUT PDD: PtrDirectDraw; outer: PtrIUnknown) : INTEGER;
END Ddraw.
MODULE Directone;
IMPORT Out, Ddraw, SYSTEM;
CONST
DDSCL_EXCLUSIVE = 00000010H;
DDSCL_FULLSCREEN = 00000001H;
PROCEDURE Initialize;
VAR
Handle, Addr, Res: INTEGER;
PDD: Ddraw.PtrDirectDraw;
nul: Ddraw.GUID;
BEGIN
PDD := NIL;
nul[0] := 0; nul[1] := 0; nul[2] := 0; nul[3] := 0;
Res := Ddraw.DirectDrawCreate(nul, PDD, NIL);
Out.String("Res"); Out.Int(Res, 8); Out.Ln();
Res := SYSTEM.VAL(INTEGER, PDD);
Out.String("Res"); Out.Int(Res, 8); Out.Ln();
Res := PDD.vtbl.SetCooperativeLevel(PDD, 0, DDSCL_EXCLUSIVE + DDSCL_FULLSCREEN);
Out.String("Res"); Out.Int(Res, 8); Out.Ln();
Res := PDD.vtbl.Release(PDD)
END Initialize;
BEGIN
Initialize
END Directone.
Some important points:
• COM GUIDs are 128 bit entities, not integers.
• DO NOT use ANYPTR or other BlackBox pointers for COM interface pointers. (BlackBox pointers are garbage collected, COM pointers are reference counted.)
• Use pointers to [untagged] records or integers instead.
Be careful to declare all methods in the method table in the correct order with the correct parameter list.
13 Windows-specific information in BlackBox
Windows -specific cursors
The module WinPorts exports constants for Windows-specific cursors which can be used like the standard cursors defined in module Ports:
CONST
resizeHCursor = 16; (* cursors used for window resizing *)
resizeVCursor = 17;
resizeLCursor = 18;
resizeRCursor = 19;
resizeCursor = 20;
busyCursor = 21; (* busy cursor *)
stopCursor = 22; (* drag and drop cursors *)
moveCursor = 23;
copyCursor = 24;
linkCursor = 25;
pickCursor = 26; (* drag and pick cursor *)
Specific mouse and keyboard modifiers
Modifier sets are used in Controllers.TrackMsg, Controllers.EditMsg, and Ports.Frame.Input. The BlackBox platform independant modifier elements doubleClick, extend, modify, popup, and pick are defined in module Controllers. Additional Windows platform-specific modifier elements are defined in module WinPorts. The correspondence between these elements is shown in the table below. If the WinPorts element is included it implies that the corresponding Controllers element will also be included.
WinPorts WinPorts Controllers Controllers Mouse button
element value element value or key
-- -- doubleClick 0 double click
left 16 -- -- left mouse button
middle 17 pick 4 middle mouse button
right 18 popup 3 right mouse button
shift 24 extend 1 Shift key
ctrl 25 modify 2 Ctrl key
alt 28 pick 4 Alt key
Window and device context handles
Many of the functions in the Windows API refer either to a window or to a device context handle. In the Windows BlackBox implementation, both of them are stored in the WinPorts.Port record:
TYPE
Port = POINTER TO RECORD (Ports.PortDesc)
dc: WinApi.Handle;
wnd: WinApi.Handle
END;
In the usual case where a frame (Ports.Frame or Views.Frame) is given, the handles can be obtained through one of the following selectors:
frame.rider(WinPorts.Rider).port.dc
or
frame.rider(WinPorts.Rider).port.wnd
If the window handle is null, the port is a printer port.
Examples
The following simple DLL definition is a subset of the Windows standard library GDI32:
MODULE GDI ["GDI32"];
CONST
WhiteBrush* = 0; BlackBrush* = 4; NullBrush* = 5;
WhitePen* = 6; BlackPen* = 7; NullPen* = 8;
PSSolid* = 0; PSDash* = 1; PSDot* = 2;
TYPE
Bool* = INTEGER;
Handle* = INTEGER;
ColorRef* = INTEGER;
Point* = RECORD [untagged] x*, y*: INTEGER END;
Rect* = RECORD [untagged] left*, top*, right*, bottom*: INTEGER END;
PROCEDURE CreatePen* (style, width: INTEGER; color: ColorRef): Handle;
PROCEDURE CreateSolidBrush* (color: ColorRef): Handle;
PROCEDURE GetStockObject* (object: INTEGER): Handle;
PROCEDURE SelectObject* (dc, obj: Handle): Handle;
PROCEDURE DeleteObject* (obj: Handle): Bool;
PROCEDURE Rectangle* (dc: Handle; left, top, right, bottom: INTEGER): Bool;
PROCEDURE SelectClipRgn* (dc, rgn: Handle): INTEGER;
PROCEDURE IntersectClipRect* (dc: Handle; left, top, right, bottom: INTEGER): INTEGER;
PROCEDURE SaveDC* (dc: Handle): INTEGER;
PROCEDURE RestoreDC* (dc: Handle; saved: INTEGER): Bool;
END GDI.
The following example is a simplified version of the BlackBox standard DrawRect routines implemented in Ports and WinPorts. It uses the GDI interface presented above.
MODULE Ex;
IMPORT Ports, WinPorts, GDI;
PROCEDURE DrawRect (f: Ports.Frame; l, t, r, b, s: INTEGER; col: Ports.Color);
VAR res, h, rl, rt, rr, rb: INTEGER; p: WinPorts.Port; dc, oldb, oldp: GDI.Handle;
BEGIN
(* change local universal coordinates to window pixel coordinates *)
l := (f.gx + l) DIV f.unit; t := (f.gy + t) DIV f.unit;
r := (f.gx + r) DIV f.unit; b := (f.gy + b) DIV f.unit;
s := s DIV f.unit;
(* get device context *)
p := f.rider(WinPorts.Rider).port; dc := p.dc;
(* set clip region *)
IF p.wnd = 0 THEN res := GDI.SaveDC(dc)
ELSE res := GDI.SelectClipRgn(dc, 0)
END;
f.rider.GetRect(rl, rt, rr, rb);
res := GDI.IntersectClipRect(dc, rl, rt, rr, rb);
(* use black as default color *)
IF col = Ports.defaultColor THEN col := Ports.black END;
IF s = 0 THEN s := 1 END;
IF (s < 0) OR (r-l < 2*s) OR (b-t < 2*s) THEN (* filled rectangle *)
INC(r); INC(b);
oldb := GDI.SelectObject(dc, GDI.CreateSolidBrush(col));
oldp := GDI.SelectObject(dc, GDI.GetStockObject(GDI.NullPen));
res := GDI.Rectangle(dc, l, t, r, b);
res := GDI.DeleteObject(GDI.SelectObject(dc, oldb));
res := GDI.SelectObject(dc, oldp)
ELSE (* outline rectangle *)
h := s DIV 2; INC(l, h); INC(t, h); h := (s-1) DIV 2; DEC(r, h); DEC(b, h);
oldb := GDI.SelectObject(dc, GDI.GetStockObject(GDI.NullBrush));
oldp := GDI.SelectObject(dc, GDI.CreatePen(GDI.PSSolid, s, col));
res := GDI.Rectangle(dc, l, t, r, b);
res := GDI.SelectObject(dc, oldb);
res := GDI.DeleteObject(GDI.SelectObject(dc, oldp))
END;
IF p.wnd = 0 THEN res := GDI.RestoreDC(dc, -1) END
END DrawRect;
END Ex.
14 Runtime type system
All dynamically allocated Component Pascal records contain a hidden field, which is called the type tag. The type tag points to the type descriptor that contains all type information needed at runtime. Calls of type-bound procedures, type tests and the garbage collector all use the information which is stored in the type descriptor. The type descriptor is allocated only once for every record type in the system.
Dynamically allocated arrays use a size descriptor to check the bounds of indexes. The size descriptor also contains the type tag of the element type. For every single dynamic array a size descriptor is needed.
15 Linking BlackBox applications
If you want to distribute an application you have written in BlackBox, you may want to link all modules into a single file for distribution. In this case you need to link the framework to your application. To illustrate the necessary actions we will give an example.
Adapt the module StdConfig to your needs:
MODULE StdConfig;
IMPORT StdCmds, StdWindows, StdDocuments, Converters;
PROCEDURE Setup*;
VAR res: INTEGER;
BEGIN
StdWindows.Init;
StdDocuments.Install;
Converters.Register(
"StdDocuments.ImportDocument",
"StdDocuments.ExportDocument", "", "odc", {});
StdCmds.OpenAuxDialog('Obx/Rsrc/BlackBox', 'BlackBox Game Dialog')
END Setup;
END StdConfig.
DevCompiler.Compile
Then link the framework with your modules into the new application file.
Blue modules are platform-specific realizations for the set of abstract interfaces.
WinPackedFiles module should be linked if you packing some resoureces to the executable file after linking of application.
DevLinker.Link BlackBoxGameDemo.exe :=
Kernel$+ Utf WinKernel Files WinEnv WinFiles WinPackedFiles WinGui StdLoader
Math Strings Dates Meta Fonts Log Librarian Dialog
Services Ports Stores Converters Sequencers Models Printers Views
Controllers Properties Printing Mechanisms Containers
Documents Windows StdCFrames Controls
StdRegistry StdInterpreter
WinRegistry WinFonts WinDates
TextModels TextRulers TextSetters TextViews
StdScrollers StdDialog StdApi StdCmds
WinPorts OleData WinMechanisms WinPrinters WinDialog WinClipboard WinCFrames WinCmds
TextControllers TextMappers TextCmds
StdLinks StdMenuTool StdScrollbars StdRasters
StdDocuments StdWindows StdMenus StdGrids StdLog StdTiles
FormModels FormViews FormControllers FormGen FormCmds
StdFolds StdDebug StdTextConv StdClocks StdStamps StdCoder StdStdCFrames
OleWindows OleStorage
Loop Console In Out StdInflate StdRastersPng
WinConsole WinBackends WinShowHook WinRasters WinConfig WinInit
StdConfig
ObxBlackBox
1 Applogo.ico 2 Doclogo.ico 3 SFLogo.ico 4 CFLogo.ico 5 DtyLogo.ico
1 Move.cur 2 Copy.cur 3 Link.cur 4 Pick.cur 5 Stop.cur 6 Hand.cur 7 Table.cur
You may need to distribute some additional files such as forms and documetation with application or they can be packed into executable file.
DevPacker.PackThis BlackBoxGameDemo.exe :=
Obx/Rsrc/BlackBox.odc
Obx/Docu/BB-Rules.odc
System/Rsrc/Strings.odc
Do not forget to restore code file for regular StdConfig
DevCompiler.CompileThis StdConfig (* the second commander here to terminate reading *)
Linux Specific Information
21 Linux Environment parameters of BlackBox
The command line parameters of BlackBox start with the letter '/' or alternatively the letter '-' immediately followed by a case insensitive parameter name. Depending on the parameter, further parameter values may be required. Each parameter value is separated by white space. If a parameter value contains spaces, it must be enclosed in single or double quotes.
The parameters are:
BB_STANDARD_DIR=path
Use pat for "bottom" directory to lookup for files.
BB_USE_DIR=path
Use path for lookup of relative file paths prior to looking them up in the startup or custom directory.
If path is relative it refers to the current directory.
BB_CUSTOM_DIR=path
Use path for lookup of relative file paths prior to looking them up in the startup directory.
PAR parameters
Specify parameters available via Dialog.commandLinePars.
BB_PACKED_NAME
Name of file for LinPackedFiles module to read packed files from it.
BB_PACKED_FIRST
Set priority for reading files first from the packed file.
LANG language
Run BlackBox localized to the specified two letter language code.
22 Endless loop
Endless loop
Send SIGILL signal to BlackBox to terminate endless loop.
SS
25 Linking BlackBox applications
If you want to distribute an application you have written in BlackBox, you may want to link all modules into a single file for distribution. In this case you need to link the framework to your application. To illustrate the necessary actions we will give an example.
Adapt the module StdConfig to your needs:
MODULE StdConfig;
IMPORT StdCmds, StdWindows, StdDocuments, Converters;
PROCEDURE Setup*;
VAR res: INTEGER;
BEGIN
StdWindows.Init;
StdDocuments.Install;
Converters.Register(
"StdDocuments.ImportDocument",
"StdDocuments.ExportDocument", "", "odc", {});
StdCmds.OpenAuxDialog('Obx/Rsrc/BlackBox', 'BlackBox Game Dialog')
END Setup;
END StdConfig.
DevCompiler.Compile
Then link the framework with your modules into the new application file.
Blue modules are platform-specific realizations for the set of abstract interfaces.
LinPackedFiles module should be linked if you packing some resoureces to the executable file after linking of application.
DevLinker1.LinkElf Linux BlackBoxGameDemo :=
Kernel$+ Utf LinKernel Files LinEnv LinFiles LinPackedFiles LinGui StdLoader
Math Strings Dates Meta Fonts Log Librarian Dialog
Services Ports Stores Converters Sequencers Models Printers Views
Controllers Properties Printing Mechanisms Containers
Documents Windows StdCFrames Controls
StdRegistry StdInterpreter
LinRegistry LinFonts LinDates
TextModels TextRulers TextSetters TextViews
StdScrollers StdDialog StdApi StdCmds
LinPorts LinMechanisms LinDialog LinClipboard
TextControllers TextMappers TextCmds
StdLinks StdMenuTool StdScrollbars StdRasters
StdDocuments StdWindows StdMenus StdGrids StdLog StdTiles
FormModels FormViews FormControllers FormGen FormCmds
StdFolds StdDebug StdTextConv StdClocks StdStamps StdCoder StdStdCFrames
Loop Console In Out
LinConsole LinBackends LinRastersPng LinConfig LinInit
StdFilesBrowser StdConfig
ObxBlackBox
You may need to distribute some additional files such as forms and documetation with application or they can be packed into executable file.
DevPacker.PackThis BlackBoxGameDemo :=
Obx/Rsrc/BlackBox.odc
Obx/Docu/BB-Rules.odc
System/Rsrc/Strings.odc
Do not forget to restore code file for regular StdConfig
DevCompiler.CompileThis StdConfig (* the second commander here to terminate reading *)
| Dev/Docu/Platform-Specific.odc |
DevProfiler
DEFINITION DevProfiler;
PROCEDURE SetProfileList;
PROCEDURE SetModuleList (list: ARRAY OF CHAR);
PROCEDURE Start;
PROCEDURE Stop;
PROCEDURE ShowProfile;
PROCEDURE Reset;
PROCEDURE Execute;
PROCEDURE StartGuard (VAR par: Dialog.Par);
PROCEDURE StopGuard (VAR par: Dialog.Par);
END DevProfiler.
DevProfiler is a statistical profiler for Component Pascal programs. A profiler measures how much processing time is spent in the individual procedures of a program. A statistical profiler determines at regular time intervals (interrupt-driven) in which procedure of which module the program currently executes. These measurements are stored, and can later be used to display the profile.
Profiles can be taken over all modules, or over a selected list of particularly interesting modules. Profiling can be started and stopped interactively, or via a programming interface. The latter often allows a more precise measurement.
Possible menus:
MENUS
"Set Profile List" "" "DevProfiler.SetProfileList" "DevProfiler.StartGuard"
"Start Profiler" "" "DevProfiler.Start" "DevProfiler.StartGuard"
"Stop Profiler" "" "DevProfiler.Stop; DevProfiler.ShowProfile" "DevProfiler.StopGuard"
"Execute" "" "DevProfiler.Execute" "TextCmds.SelectionGuard"
END
Programming Example
The following example shows how the programming interface of the profiler can be used. It profiles the compilation of a module, i.e., of command DevCompiler.Compile.
PROCEDURE ProfiledCompile*;
VAR res: INTEGER;
BEGIN
DevProfiler.SetModuleList("DevCPM DevCPS DevCPT DevCPB DevCPP");
DevProfiler.Start;
Dialog.Call("DevCompiler.Compile", "", res);
DevProfiler.Stop;
DevProfiler.ShowProfile;
DevProfiler.Reset
END ProfiledCompile;
The above procedure produces something like the following output:
Module % per module
Procedure % per procedure
DevCPT 37
InsertImport 7
Find 4
InName 4
InStruct 4
FPrintName 3
FPrintSign 1
IdFPrint 1
FPrintObj 1
DevCPM 16
ReadNum 4
Get 3
FPrint 2
SymRCh 2
SymRInt 2
DevCPS 7
Identifier 4
Get 1
DevCPB 6
DevCPP 6
selector 1
samples: 782 100%
in profiled modules 306 39%
other 476 61%
In this example, about 37% of the measured time period has been spent in some procedures of module DevCPT. Procedure InsertImport alone has taken about 7% of the time. Note that procedures which used less than 1% of the time are not displayed, thus the sum over all DevCPT procedures doesn't add up to 37%.
Some time may be spent in modules not measured, or not in Component Pascal modules at all, e.g., in the host operating system's file system implementation. For this reason, and because modules which used less than 1% of the time are not shown, the sum over all modules doesn't add up to 100%.
PROCEDURE SetProfileList
This procedure takes the list of selected module names and registers it. This list of modules will be profiled when Start is called. If there is no selection, all listed modules will be profiled.
PROCEDURE SetModuleList (list: ARRAY OF CHAR)
Same as SetProfileList but with an explicit parameter instead of the selection as implicit parameter. This procedure is useful when the profiler is called from a program rather than interactively.
PROCEDURE Start
Starts profiling.
PROCEDURE Stop
Stops profiling.
PROCEDURE ShowProfile
Displays the most recently measured profile in a new window.
PROCEDURE Reset
Releases memory used for the profiler, including the most recently measured profile and the module list.
PROCEDURE Execute
Same as DevDebug.Execute. The execution time (in milliseconds) is written to the log.
| Dev/Docu/Profiler.odc |
DevRBrowser
DEFINITION DevRBrowser;
PROCEDURE ShowRepository;
PROCEDURE Update;
PROCEDURE OpenFile (path, name: ARRAY OF CHAR);
PROCEDURE ShowFiles (path: ARRAY OF CHAR);
END DevRBrowser.
This tool module allows to list all subsystems as folds (-> StdFolds). A fold contains links to its subsystem's symbol, code, source, and documentation files. It makes it easier to get an overview over the elements of a large BlackBox application, or over BlackBox itself.
For the resources of a subsystem, a Rsrc link is generated. Clicking this link creates a list of all documents in the Rsrc subdirectory.
For the documentation files, those which contain one or several dashes ("-") in their names are not treated as module documentations, but rather as auxiliary documentation files which are listed at the beginning. In particular, files with name Sys-Map, User-Man, and Dev-Man are extracted this way. They are the standard names for a map document which contains hyperlinks to the relevant files of the subsystems; the user manual for the subsystem (user in this context means a programmer); and the programmer's reference.
Menu command:
"Repository" "" "DevRBrowser.ShowRepository" ""
PROCEDURE ShowRepository
Create a report which lists all subsystems.
PROCEDURE Update
Update the report (used as command in the update link that is on top of the generated report).
PROCEDURE OpenFile (path, name: ARRAY OF CHAR)
Used internally. Opens the file at location path and with name name.
PROCEDURE ShowFiles (path: ARRAY OF CHAR)
Used internally. Lists all resource documents at location path.
| Dev/Docu/RBrowser.odc |
DevReferences
DEFINITION DevReferences;
IMPORT TextMappers, Files;
PROCEDURE ResolveImportAlias (VAR mod: TextMappers.String; t: TextModels.Model);
PROCEDURE ShowDocu;
PROCEDURE ShowSource;
PROCEDURE ShowText (module, ident: TextMappers.String; category: Files.Name);
END DevReferences.
This module provides two commands which, given the name of a module or of a qualified identifier, look up the corresponding documentation or source text.
Typical menu:
MENU
"&Source" "" "DevReferences.ShowSource" "TextCmds.SelectionGuard"
"&Documentation" "" "DevReferences.ShowDocu" "TextCmds.SelectionGuard"
END
PROCEDURE ResolveImportAlias (VAR mod: TextMappers.String; t: TextModels.Model)
On input mod is assumed to contain either the name of a Module, or a Qualident, where the Module referenced in mod is imported by another Module whose source code is in t.
For example, if t contains the line "IMPORT Ref := DevReferences;" mod may be "Ref" or "DevReferences".
On output, in this example, mod would be set to "DevReferences".
PROCEDURE ShowDocu
Guard: TextCmds.SelectionGuard
Looks up the documentation text of the module whose name is selected. If a qualified identifier is selected, i.e., "module.ident", the corresponding item is searched. It must be written in boldface and in a smaller than 14 point type. The document must be located in the Docu directory of the module's subsystem.
The selected module name or qualident may be either given in full, or by alias if an alias has been defined in the enclosing module's IMPORT statement.
PROCEDURE ShowSource
Guard: TextCmds.SelectionGuard
Looks up the source text of the module whose name is selected. If a qualified identifier is selected, i.e., "module.ident", the corresponding item is searched. It must be written in boldface and in a smaller than 14 point type. The document must be located in the Mod directory of the module's subsystem.
The selected module name or qualident may be either given in full, or by alias if an alias has been defined in the enclosing module's IMPORT statement.
PROCEDURE ShowText (module, ident: TextMappers.String; category: Files.Name)
Used internally.
| Dev/Docu/References.odc |
DevSearch
DEFINITION DevSearch;
PROCEDURE Compare;
PROCEDURE SearchInDocu (opts: ARRAY OF CHAR);
PROCEDURE SearchInSources;
PROCEDURE SelectCaseInSens (pat: ARRAY OF CHAR);
PROCEDURE SelectCaseSens (pat: ARRAY OF CHAR);
END DevSearch.
This tool provides global search facilities (in all subsystems' Docu or Mod directories) and a text comparison feature. The search engine cooperates with module TextCmds, in that it uses the latter's find & replace interactor. This means that after having found a string using one of the search commands, the text command "Find Again" can be used to conveniently find further occurrences of the same string in the same text.
Typical menu:
MENU
"Search In Sources" "" "TextCmds.InitFindDialog; DevSearch.SearchInSources" "TextCmds.SelectionGuard"
"Search In Docu (Case Sensitive)" "" "TextCmds.InitFindDialog; DevSearch.SearchInDocu('s')" "TextCmds.SelectionGuard"
"Search In Docu (Case Insensitive)" "" "TextCmds.InitFindDialog; DevSearch.SearchInDocu('i')" "TextCmds.SelectionGuard"
"Compare Texts" "" "DevSearch.Compare" "TextCmds.FocusGuard"
END
PROCEDURE Compare
Guard: top two windows are document windows
Perform a textual comparison of the two topmost windows' contents. The comparison starts at each window's current caret position, or alternatively, at the end of its selection. The next difference which is found is indicated by advancing the caret or selection to the found difference. White space (spaces, tabs, carriage returns) are ignored during comparison.
PROCEDURE SearchInSources
Guard: TextCmds.SelectionGuard
Search all available sources (in all subsystems) for the occurrence of the selected text pattern. Search is case-sensitive.
PROCEDURE SearchInDocu (opts: ARRAY OF CHAR)
Guard: TextCmds.SelectionGuard
Search all available documentation texts (in all subsystems and in the Docu directory) for the occurrence of the selected text pattern. If the string opts starts with an 's' or 'S' then the search is case sensitive, if it starts with an 'i' or 'I' the search is case-insensitive and in all other cases the value from the Find /Replace... dialog is used.
Searching for docu is language aware. If a language other than the base language en is selected in Edit->Preferences..., the related language subdirectory is used for searching. Otherwise only the english version is searched. Note that in any case only files that exist for the base language en are considered.
PROCEDURE SelectCaseInSens (pat: ARRAY OF CHAR)
Sets up TextCmds.find.find with pat, calls TextCmds.FindFirst and opens the find dialog. This procedure is used by link views created with the above procedure SearchInDocu when the search was performed case-insensitive.
PROCEDURE SelectCaseSens (pat: ARRAY OF CHAR)
Sets up TextCmds.find.find with pat and calls TextCmds.FindFirst. This procedure is used by link views created with the above procedures SearchInSource and SearchInDocu when the search was performed case-sensitive.
| Dev/Docu/Search.odc |
DevSelectors
DEFINITION DevSelectors;
IMPORT TextModels, Models, Stores, Views;
CONST
left = 1;
middle = 2;
right = 3;
TYPE
Directory = POINTER TO ABSTRACT RECORD
(d: Directory) New (position: INTEGER): Selector, NEW, ABSTRACT
END;
Selector = POINTER TO RECORD (Views.View)
position-: INTEGER;
END;
VAR
dir-: Directory;
stdDir-: Directory;
PROCEDURE Change (text: TextModels.Model; title: ARRAY OF CHAR; selection: INTEGER);
PROCEDURE ChangeTo (text: TextModels.Model; title, entry: ARRAY OF CHAR);
PROCEDURE DepositLeft;
PROCEDURE DepositMiddle;
PROCEDURE DepositRight;
PROCEDURE SetDir (d: Directory);
END DevSelectors.
Introduction
Selector Views serve to specify conditional parts of a text document. The idea is that the document can be configured into one of two, or more, variants, and each variant may involve several changes spread throughout the document.
A simple example is to change the language of comments in a source file.
When any of the changes is selected anywhere in the Document, all the related changes are automatically made consistently.
Selector Views should be inserted into a Text in sets comprising a left View "", 0 or more middle Views "", and a right View "". These Views then identify short stretches of text. The first stretch is called the selector title and the subsequent stretches are called its selections.
For example:
MyTitleSelection 1Selection 2Selection 3
MyTitleValue 1Value 2Value 3
If you click on either the "" or "" Views the selector opens to display all its fields. If you click on one of the "" Views it collapses to show only the immediately following selection.
Normally one would have a group (or groups) of several selectors, each selector would have two or more middle Views, and all the selectors in the same group would have the same number of middle Views.
Different selectors are in the same group if they have the same (case-sensitive) title.
When you open or collapse any selector, all the selectors in the same group (ie with the same title) open or collapse together.
(An exception is when you click on the n'th middle View in a selector, other selectors in that group with less than n middle Views do not respond.)
Changes to selections are recorded on the Edit -> Undo/Redo stack, but do not make the Text dirty.
Selectors in the source code
Some suggested uses for Selectors are:
→ During development when there is a desire to experiment with different options
→ To insert comments in source code in different languages
→ To translate 'c' header files by simulating conditional compilation.
It can then be convenient to have control selectors in comments in the module header such as:
(* FeatureOnOff *)
(* Commentenrufr *)
(* Macro Idvalue 1 value 2value 3 *)
and corresponding selectors in each group to implement the selected functionality.
The Compiler also responds directly to selectors so, for example, one can call at the command line
DevCompiler.CompileThis MyModule ("Feature A": "On", "Feature B": "Off")
and the source file is configured appropriately if it includes selectors with matching titles and selections.
Installation
It may be convenient to include the Menu items:
SEPARATOR
"Insert Left" "*F5" "DevSelectors.DepositLeft; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"Insert Middle" "*F6" "DevSelectors.DepositMiddle; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"Insert Right" "*F7" "DevSelectors.DepositRight; StdCmds.PasteView" "StdCmds.PasteViewGuard"
A suitable location would be after the "Fold" Menu items in the Tools section of (Dev)Menus.odc.
Reference Manual
CONST left, middle, right
Constants used by the Directory New procedure position parameter to define which kind of Selector will be returned.
TYPE Directory
ABSTRACT
Directory for selector Views.
PROCEDURE (d: Directory) New (position: INTEGER): Selector
NEW, ABSTRACT
Returns a new selector View.
position should be one of left, middle, or right (not explicitly checked).
TYPE Selector (Views.View)
View type of a selector.
position-: INTEGER
Indicates if the selector is a left, middle, or right selector.
VAR dir-, stdDir-: Directory
Directory and standard directory for selectors.
PROCEDURE Change (text: TextModels.Model; title: ARRAY OF CHAR; selection: INTEGER)
Collapses the selectors in text with title title to show the specified selection.
The first selection corresponds to number selection = 1.
(If the selector has less than selection selections it is unchanged.)
If selection = 0 all the selectors in this group opened.
PROCEDURE ChangeTo (text: TextModels.Model; title, entry: ARRAY OF CHAR)
If any selector in text has title = text, and a selection = entry then all the selectors with title text are collapsed to show only the corresponding selection.
Both comparisons are case sensitive.
PROCEDURE DepositLeft
Creates a new left selector and deposits it in the Views queue.
PROCEDURE DepositMiddle
Creates a new middle selector and deposits it in the Views queue.
PROCEDURE DepositRight
Creates a new right selector and deposits it in the Views queue.
PROCEDURE SetDir (d: Directory)
Sets the selector directory.
Pre
d # NIL 20
| Dev/Docu/Selectors.odc |
DevSubTool
DEFINITION DevSubTool;
CONST
textCmds = 0; formCmds = 1; otherCmds = 2;
simpleView = 3; standardView = 4; complexView = 5;
wrapper = 6; specialContainer = 7; generalContainer = 8;
VAR
create: RECORD
subsystem: ARRAY 9 OF CHAR;
kind: INTEGER;
Create: PROCEDURE
END;
END DevSubTool.
Module DevSubTool provides a code generator (sometimes such a tool is called a "wizard" or "expert") which creates source code skeletons for typical view implementations. Theses skeletons are extended with your own code pieces and then compiled.
DevSubTool supports several kinds of projects, from simple text commands to general containers. The source document(s) are always created in the form of a new subsystem, i.e., as a subdirectory with the generic subsystem structure (Sym, Code, Docu, Mod subdirectories).
Note that the tool uses template texts which are stored in the Dev/Rsrc/New directory. Studying these texts, in particular the more complex model/view/commands templates, can be worthwile to learn more about typical BlackBox design and code patterns.
Typical command:
"Create Subsystem..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/SubTool', 'Create Subsystem')" ""
CONST textCmds
This value can be assigned to create.kind, to create a command package for text commands, i.e., a module which imports the standard Text subsystem and enhances it with its own exported commands or interactors.
CONST formCmds
This value can be assigned to create.kind, to create a command package for form commands, i.e., a module which imports the standard Form subsystem and enhances it with its own exported commands or interactors.
CONST otherCmds
This value can be assigned to create.kind, to create a command package for arbitrary commands, i.e., a module which enhances BlackBox with its own exported commands or interactors.
CONST simpleView
This value can be assigned to create.kind, to create a view implementation for a simple view which has no model. The view and its commands are packaged into one module. The view is not exported.
CONST standardView
This value can be assigned to create.kind, to create a view implementation for a view with a model. The model, view, and its commands are packaged into one module. Model and view are not exported.
CONST complexView
This value can be assigned to trans.kind, to create a view implementation for a view with a model. The model, view, and its commands are packaged into one module each. Model and view are exported as definition types, concrete implementations are created via directory objects.
This category is currently not supported.
CONST wrapper
This value can be assigned to trans.kind, to create a wrapper implementation for wrapping an arbitrary view. The wrapper view and its commands are packaged into one module. The wrapper view is not exported.
This category is currently not supported.
CONST specialContainer
Creates a container with a static layout and no intrinsic contents, possibly for containing only views of a particular type. The container view and its commands are packaged into one module. The container view is not exported.
CONST generalContainer
Creates a container view with dynamic layout, possibly some intrinsic contents, and able to contain any view type. The model, view, controller, and its commands are packaged into one module each. Model and view are exported as definition types, concrete implementations are created via directory objects. Model, view, and controller are extensions of their base types in module Containers.
This category is currently not supported.
VAR trans
Interactor for the translation dialog.
subsystem: ARRAY 9 OF CHAR
Name of the subsystem to be translated. The name must be a legal subsystem name, between 3 to 8 characters in length, and start with a capital letter.
kind: INTEGER kind IN {textCmds..generalContainer}
Kind of program to generate.
Create: PROCEDURE
Creation command. As input, a legal subsystem name must be entered. As a result, a new subsystem directory is created.
The Dev/Rsrc/New directory contains a number of template documents. Create translates some of these documents (depending on kind) by replacing all strings with the strikeout attribute (like here: strikeout) by the subsystem name. The template files are then deleted.
| Dev/Docu/SubTool.odc |
Map to the Dev Subsystem
UserManual
DevAlienTool display infos on aliens
DevAnalyzer source code analyzer
DevBrowser symbol file browser
DevCmds miscellaneous commands
DevCommanders command interpreters
DevCompiler Component Pascal compiler
DevDebug symbolic post mortem debugger
DevDebugCmds attaching a run-time debugger
DevDependencies display module graph
DevHeapSpy visual heap display
DevInspector control property inspector
DevLinkChk check hyperlinks
DevLinker linker
DevMarkers error markers
DevMsgSpy log messages to a view
DevPacker pack files into an EXE file
DevProfiler statistical profiler
DevRBrowser repository browser
DevReferences source/docu symbol lookup
DevRTDebug symbolic run-time debugger
DevSearch global search tool
DevSubTool template generator
| Dev/Docu/Sys-Map.odc |
Dev Subsystem
User Manual
Contents
1 CompilingComponentPascalmodules
2 Browsingtools
3 Loadingandunloadingmodules
4 Executingcommands
5 Debugging
6 Deployment
1 Compiling ComponentPascal modules
Besides consuming stored text documents, the Component Pascal compiler can compile modules from anywhere in any displayed text document. If the beginning of a displayed text is also the beginning of a module, the command Dev->Compile is used to compile the module. If the module begins somewhere in the middle of a displayed text, its beginning can be selected, e.g., by doubleclicking on the keyword MODULE, and then the command Dev->CompileSelection is used.
To compile a list of modules at once, a list of module names needs to appear in some displayed text, e.g.,
FormModels FormViews FormControllers FormCmds
By selecting the part of the list that should be considered by the compiler, and by invoking the command Dev->CompileModuleList, the list of modules is compiled consecutively. The process stops as soon as an erroneous module has been encountered. The compiler reports on the success or failure of compilations by writing into the system log. The log is a special text displayed in an auxiliary window. It can be opened using Info->OpenLog and cleared using Info->ClearLog.
The log is a development tool, i.e., it is mainly used for debugging purposes and for development tools. End-user applications are not expected to display a log. Whether or not a log window is opened upon startup of BlackBox is determined by the configuration's StdConfig module (in directory Std/Mod). This module can be changed by the programmer as desired; by default its Setup procedure only contains a statement which opens the log.
Dev->OpenModuleList is a convenient command which opens the module sources of one or several modules: select a module name, e.g., FormCmds, and then execute Dev->OpenModuleList. This command can save you much time when you work with multiple subsystems (cf. Modules and Subsystems) at the same time.
When compiling a newly created or a modified module, direct compilation of the displayed program text with Dev->Compile is recommended. In addition to writing to the system log, the compiler then also inserts error markers into the source text and places the caret after the first marker, if some syntax error was encountered. Each marker represents an error flagged by the compiler in the source text. Normally, a marker is displayed as a crossedout box. However, simply by clicking into it, a marker expands to display the corresponding error message. If the insertion point is directly behind a marker, it can be expanded via the command Dev->ToggleErrorMark (or more likely via its keyboard shortcut).
At the bottom of a window there is a status bar. If the user clicks into an error marker, the error message is written into the status bar instead of expanding the error marker. The error marker can be forced to expand by a ctrl-click or a double-click on the marker.
The command Dev->NextError can be used to skip forward to the next marker. Dev->UnmarkErrors removes all remaining markers from a text. However, this command is rarely required: The compiler automatically removes all old markers when recompiling a text; and when storing a text, contained markers are filtered out, i.e., do not appear anymore when the text is opened again.
If a compiled module contains one or several errors, the text is scrolled to the first one. If this doesn't happen, the module was successfully compiled. In addition to this feedback, the compiler writes the number of errors found to the log, if there are errors. If the module interface has changed compared to a previous version, the changes are listed in the log as well.
The successful compilation of a module yields two files: a symbol file and a code file. A symbol file contains the information about a module's interface, and is used by the compiler to check imported modules for consistency. The code file represents the generated code (Intel 386 code on Windows, Motorola 68020 code on Macintosh). The contents of a code file is linked and loaded dynamically when needed, thus there is no need for a separate linker.
Symbol files are only needed during development (used by the compiler and the interface browser), they are not needed to run modules. A symbol file is a special encoding of a module's interface, i.e. of its exported constants, variables, types, and procedures. If the interface of a module is changed and the module recompiled, a new symbol file is written to disk. When compiling a module, the compiler reads the symbol files of all imported modules. This information is used to generate code, but also to type-check the correct use of imported identifiers.
After the interface of a module has been modified, all modules importing it (i.e., all its clients) must be recompiled. Only those modules need to be recompiled which actually use a feature that has been changed. A mere addition of features does not invalidate the clients of a module: if you export a further procedure, for example, no clients need to be recompiled. This also holds for constants, variables, and types, but not for methods. Addition of a method is not considered an extension, but rather a modification of an interface, and thus may invalidate clients.
Code files are produced, but never read during compilation. They are necessary to run modules, i.e. the dynamic (linking) loader must be able to read them. They can be regarded as special very light-weight DLLs (dynamic link libraries).
See also modules DevCompiler, DevCmds, and DevMarkers.
2 Browsing tools
A common cause of compiletime errors is the wrong use of interfaces. To quickly retrieve the actual definitions of items exported by modules, the browser may be used. The interface of a whole module is displayed when selecting the name of a module and executing Info->Client Interface. To display the definition of an individual item, e.g., a type or procedure, the qualified name of that item, i.e., module.item should be selected with the same command. The browser displays its output in a form that can directly be used as input for further browsing actions. Command Info->Client Interface only shows the part of a module's interface which is relevant for clients, i.e., it leaves out implement-only methods and similar items that are only relevant for implementers of object types. For implementers, the command Info->Extension Interface shows the full interface.
Two related commands, Info->Source and Info->Documentation, allow to look up an item's definition in a source file, or in an on-line documentation, respectively. They both work on selected module names as well as on names in the form module.item, just as the Info->Interface command.
The general text search commands Info->SearchinSources and Info->SearchinDocu search a selected string in the available source files, respectively documentation files. For source files, this means in the global Mod directory and in each subsystems' Mod directory. For documentation files, this means in the global Docu directory and in each subsystem's Docu directory. As a result of these commands, a new text is opened which contains a hyperlink for each file where the string occurs, and the count of how many times it occurs there. When the user clicks on the hyperlink, the corresponding file is opened and first instance of the string is selected. With Text->FindAgain, the next instance can be found. Note that these commands may take up to several minutes to complete.
See also modules DevBrowser, DevReferences, DevSearch, and DevDependencies.
3 Loading and unloading modules
Once a module successfully passes the compiler it can be loaded to the system and used.
The BlackBox loader can dynamically link and load a module at run-time. A code file basically is a language-specific light-weight DLL (dynamic link library). The loader can be invoked from within a program by calling the procedure Dialog.Call. This procedure takes a command name as parameter. It loads the command's module, if it isn't loaded yet. Afterwards, it executes the command's procedure. For example,
Dialog.Call("DevDebug.ShowLoadedModules", "", res)
causes the loading of module DevDebug (if necessary) and the execution of its ShowLoadedModules procedure.
A loading attempt may cause the following errors:
Code file not found
The code file of a module has not been found.
For example, loading of module FormCmds requires the code file Form/Code/Cmds.
Corrupted code file
The module's code file exists, but its internal format is not correct.
Object not found
The module imports some object (constant, type, variable, procedure) from another module, where this object is not exported.
Object inconsistently imported
The module imports some object (constant, type, variable, procedure) from another module, where this object is exported, but with a different signature.
Such inconsistencies typically occur if a module's interface was changed (e.g., a procedure got an additional parameter), but not all client modules were recompiled afterwards. Another possibility is that the module whose interface was changed has not been reloaded after compilation. In this case, everything will work fine after it has been unloaded (e.g., after a restart of BlackBox).
Cyclic import
Modules may not import each other cyclically. For example, it is not alllowed that module A imports module B, and module B imports module C, and module C imports module A.
Not enough memory
There is not enough memory left for loading the module.
Once loaded, a module remains loaded if it isn't unloaded explicitly. The list of all currently loaded modules is displayed by Info->LoadedModules.
In order to use a new version of a module that is already loaded, the module needs to be unloaded first.
Command Dev->Unload takes a focused module source as input and tries to unload the corresponding module. Dev->Unload fails if the module is still in use, i.e., if it is imported by at least one other module that is still loaded. (In general, modules can only be released top down.) The command Dev->UnloadModuleList takes a selection as input, which must consist of a sequence of module names. You may directly use a selection in the text produced by Info->LoadedModules as input.
See also module DevDebug.
4 Executing commands
There are several ways to execute commands (i.e., procedures exported by Component Pascal modules, intended for direct invocation by the user) within BlackBox. A command name can be written to a text, as a string of the form "module.procedure", selected, and executed using Dev->Execute. An easier way is to insert a commander in front of the command name, using Tools->InsertCommander. Clicking on a commander interprets the string following it as a sequence of commands, e.g.
"Dialog.Beep; DevDebug.ShowLoadedModules"
If the string consists of only one parameterless command, the string delimiters may be omitted, e.g.,
Dialog.Beep
With such simple commands, it is possible to combine the unloading of an old version with the execution of a new version of a command (resp. of its module): ctrl-click on the commander causes the command's module to be unloaded, and then the new module version is loaded and the procedure executed. Note that this "unload shortcut" only works for top-level modules, i.e. for modules which are not imported by any other modules.
The allowed parameter lists for commands are documented with module StdInterpreter.
The BlackBox Component Framework tries to call the command StdConfig.Setup when it is starting up. You can change StdConfig in order to customize your configuration upon startup.
See also modules DevDebug and StdConfig.
5 Debugging
Post-mortem Debugging
When a run-time error occurs, e.g., a division by zero or some assertion trap, a trap window is opened. Such a window contains a text which shows the stack contents at the time when the trap occurred. An extract of such a trap text is shown below:
index out of range
ObxTrap.Do [00000049H]
i INTEGER 777
str Dialog.String "String"
v Views.View [85D29730H]
StdInterpreter.CallProc [00000BC1H]
i Meta.Item
.obj SHORTINT 4
.typ SHORTINT 20
.vis SHORTINT 4
.adr LONGINT -2034827097
.mod undefined: 86B60000H
.desc undefined: 00000004H
.ptr Meta.ArrayPtr [85CDF4B0H]
mn Meta.Name "ObxTrap"
mod StdInterpreter.Ident "ObxTrap"
ok BOOLEAN TRUE
parType INTEGER 0
pn Meta.Name "Do"
proc StdInterpreter.Ident "Do"
StdInterpreter.Command [0000187EH]
left StdInterpreter.Ident "ObxTrap"
ptype INTEGER 0
right StdInterpreter.Ident "Do"
In the first line, the exception or trap number is given, e.g., "Index out of range" or "TRAP 0". Further below, a sequence of procedure activations is given, e.g., the last active procedure (where the trap occurred) was ObxTrap.Do, which had been called by StdInterpreter.CallProc, which had been called by StdInterpreter.Command, etc. Each procedure is marked with a small diamond mark to the left of its name. Clicking on this diamond mark produces a new window which shows the global variables of the module in which this procedure is defined, e.g.,
ObxTrap
global INTEGER 13
The diamond mark to the right of a procedure opens the source of the module in which this procedure is defined, selects the statement which has been interrupted, and scrolls to this selection. Of course, this is only possible for modules whose source code is available.
But now let us go back to the stack display. The lines below a procedure's name show the parameters and local variables of the procedure, sorted alphabetically. The following example
str Dialog.String "String"
means that a local variable str of type Dialog.String had the value "String" when the trap occurred. If the variable name is displayed in italics, this means that it is a variable parameter (i.e., representing another variable).
After a pointer variable, a diamond mark allows to follow the pointer to the record to which it points, e.g. the pointer v
v Views.View [85D29730H]
can be followed (by clicking on the diamond mark) to the record
ObxTrap.Do:v^
[85D29730H] TextViews.StdViewDesc
.context Models.Context [85D29CC0H]
.era LONGINT 3
.guard LONGINT 0
.bad SET {}
.model Containers.Model [85D29780H]
.controller Containers.Controller [85D29A20H]
.alienCtrl Stores.Store NIL
.text TextModels.Model [85D29780H]
.org LONGINT 0
.dy LONGINT 0
.defRuler TextRulers.Ruler [85D29AD0H]
.defAttr TextModels.Attributes [85D29BD0H]
.hideMarks BOOLEAN TRUE
.cachedRd TextSetters.Reader [85D1A470H]
.trailer TextViews.Line [85D20390H]
.bot LONGINT 2339975
.setter TextSetters.Setter [85D29BF0H]
.setter0 TextSetters.Setter [85D29BF0H]
Such a display is opened in another window. The fields of a record are indicated by the preceding ".". On the first line, the path you have followed is indicated. If you have followed more than one dereferencing step, a diamond mark at the right end of this line lets you trace back again step by step.
Array elements and record fields are wrapped into folds (-> StdFolds), which can be opened or closed by clicking on the fold views. Folding of structured data types makes it easier to get an overview in complex situations.
Note that the debugger only finds source text files if they are located at their correct places and under their correct names, according to their subsystems. For example, for module "FormViews", the debugger looks for file Form/Mod/Views. If the file is stored somewhere else, or under another name, the debugger will look for an open window with the appropriate module source in it. It this also fails, it opens a dialog box so that the user can show the debugger where to find the correct file.
When a trap occurs in a view implementation, e.g., in the view's Restore procedure, the error which caused it might later lead to another trap again, e.g., when the view becomes uncovered, its Restore procedure is called again. In the worst case, this may lead to a never-ending sequence of traps. BlackBox prevents this by partially disabling a trapped view. Such a view is overlaid with a light grey pattern; its contents won't be restored again. However, the view's remaining behavior is still intact, i.e., it may be saved to a file. If saving leads to a trap, the view is turned into an alien; this is indicated by a cross overlaid over the view. The rest of the container document could still be saved, however.
BlackBox distinguishes three categories of view traps:
• refresh: a trap in the view's Restore or RestoreMarks procedures
• save: a trap in the view's Internalize or Externalize procedures
• other: a trap in any other of the view procedures
If a trap in one of those categories occurs, this behavior will be disabled (i.e., the system won't call the procedures in this category anymore), behavior of the other categories remains intact. In the worst case, a view can lead to three traps, one for each category.
This means that erroneous views "degrade gracefully", by freezing only those behaviors that already have led to traps. If for some reason a view should be "unfrozen" again, the command Dev->RevalidateView can be used.
An endless loop can be interrupted by pressing ctrl-break.
The following standard traps may occur at run-time (depending on the platform, some of these errors don't occur):
invalid WITH
invalid CASE
function without return
type guard
value out of range
index out of range
string too long
stack overflow
integer overflow
division by zero
infinite real result
real underflow
real overflow
undefined real result
not a number
keyboard interrupt
NIL dereference
illegal instruction
NIL dereference (read)
illegal memory read
NIL dereference (write)
illegal memory write
NIL procedure call
illegal execution
out of memory
bus error
address error
fpu error
exception
Besides these standard traps, there are custom traps. Each custom trap has a trap number associated with it. The following conventions are used:
Free 0 .. 19
Preconditions 20 .. 59
Postconditions 60 .. 99
Invariants 100 .. 120
Reserved 121 .. 125
Not Yet Implemented 126
Reserved 127
Silent Trap 128
Silent Trap is a special case. It terminates the execution of the current command without generating a trap window.
You can use trap codes 0..19 freely in your programs, typically as temporary breakpoints during debugging. By convention, the other trap codes are generated by various assertions, i.e., statements which check a certain condition, and terminate the command if the condition is violated. Conditions which must be fulfilled upon entry of a procedure are called preconditions, conditions which must be fulfilled upon exit of a procedure are called postconditions, and conditions which must be fulfilled in between are called invariants. Most procedures in the BlackBox Component Framework check some preconditions. Typically, trap numbers are kept unique inside of a procedure. Thus, if a trap occurs, consult the documentation (or source, if available) of the trapped procedure. There you should get more information about the cause of the trap.
The developer may even provide a plain-text description of the trap's cause, by providing suitable resources in the subsystem's string resource file: module name without subsystem prefix, followed by ".", followed by the procedure name, followed by ".", followed by the trap number. The following are examples:
Math.Power.23 Pre: x # 1.0 OR ABS(y) # INF
Views.View.CopyFrom.20 Views.CopyFrom and Views.CopyFromModelView must not both
be overwritten
If such a resource exists, the corresponding text is shown in the trap display.
It should be noted that at no time during debugging the normal BlackBox Component Builder environment is left, there is no special "debugging mode" or "debugging environment"; everything is integrated instead!
Example: ObxTrapdocu
The BlackBox debugger is a cross between a "post-mortem" debugger and a "run-time" debugger. It is invoked after a command has trapped (post-mortem), but it doesn't cause a termination of the BlackBox environment (run-time). Some features, such as the Info->ViewState command, which makes it possible to follow data structures starting from a selected view, are usually associated with run-time debuggers only.
It is typical for object-oriented programs that their control flows can become extremely convoluted and hard to follow. Thus following a program statement for statement (single step), by message sends, or by procedure calls in practice turns out to be unpractical for debugging large systems. Instead, BlackBox uses a more effective debugging strategy:
Let errors become manifest as soon as possible.
Instead of waiting for some error to occur, and then trying to find one's way backward to the cause of the error, it was attempted to flag errors as closely to their cause as possible. This is the only way to truly save debugging time. The language implementation follows the same strategy, by checking index overflows when accessing arrays, by checking NIL accesses when dereferencing a pointer, etc. In addition to these built-in checks, Component Pascal provides the standard procedure ASSERT, which allows to test for an arbitrary condition. If the condition is violated, a trap window is opened. Procedures of the BlackBox Component Framework consequently use assertions e.g. at the beginning of a procedure to check whether its input is valid. This prevents that a procedure with illegal input may perform any damage to the rest of the system.
This defensive programming strategy has proven itself again and again during the development of BlackBox, and is strongly recommended for serious development work.
See also module DevDebug.
Run-time Debugging (not yet implemented in BlackBox 2.0)
Since BlackBox version 1.7.2 there is also a run-time debugger included for exceptional situations where the post-mortem analysis is not sufficient. In addition to the features provided by the post-mortem debugger, the run-time debugger provides for stopping execution, single-step execution, and setting of code and data breakpoints. The run-time debugger can be activated with the commands Dev->Debug Command and Dev->Debug Module after selecting a command or module name in a text document. For operating the debugger please see the help text of the Debug tool opened in the attached debugger. Note that the run-time debugger is another BlackBox instance that is started automatically when requested. Source code must be saved in order to be visible consistently in the debugger.
If a debugger is attached, a trap in the running BlackBox instance will switch to the debugger instead of opening a trap window immediately. The debugger can be used to inspect the program state similar to using BlackBox's post-mortem debugging facility. Continuing with trap handling (command Handle Trap) in the Debug tool continues the debugged process and opens the trap window.
Warning: Copying text or other contents from the debugged application to another application via the Windows clipboard is not possible when the debugged application has been stopped by the debugger. Moreover, copying to the debugger leads to a deadlock.
See also module DevDebugCmds.
6 Deployment
If you develop add-on components (i.e., new subsystems) for BlackBox, deployment simply means to distribute copies of your subsystem directory. You may not want to distribute the source texts, in order to protect your intellectual property rights. In this case you should not put them into the distribution copies. You may not want to make one or several of your module interfaces public, or none at all if your application is not meant to be extensible. In this case, you should not put the corresponding symbol files into the distribution copies. However, for each public module you should put a documentation file into the subsystem's Docu directory. For example, for module FormCmds there is a docu file Form/Docu/Cmds.
It is customary to put a Sys-Map file in the Docu directory. This map text contains a list of all public modules; the elements of the list are hyperlinks.
If the subsystem implements user interface elements such as views or commands, a user manual should be made available. This document is called User-Man and also resides in the Docu directory.
If the subsystem is meant for use by programmers, and if the individual modules' documentation files are not sufficient, the Docu directory should contain an overview text called Dev-Man.
The previous paragraph has shown everything you need to do to distribute an add-on component, i.e., an extension in the form of a subystem. On the other hand, if you want to distribute a stand-alone application for some reason, you have three possibilities:
1) This approach is suited for applications where updates and extensions are frequent: you provide the unlinked code files of your application and of BlackBox, together with a minimal linked application to boot the whole software system.
To make an unpacked and unlinked stand-alone version you need to copy some files and directories from the BlackBox directory to a new directory. BlackBox.exe may be renamed to the name of your new application.
2) This approach is suitable for applications that are closed or where incremental updates and extensions are relatively rare: you pack the BlackBox directory's contents into one large executable file. In contrast to the linker (see below), the packer is not limited to code files; it can also pack resources and documentation and any other kind of files into the application. In contrast to approach 1), the end user cannot easily destroy the applications just by deleting some code or resource file. See the packerdocumentation for details.
3) This approach is most relevant for native applications (i.e., Component Pascal applications which don't use the BlackBox framework) and for linked libraries (DLLs under Windows): you use the linker tool to combine several code files into one application file.
For a linked version you need to use the linker to pack your code files together with the BlackBox code files into a single application. See the linkerdocumentation for details. After linking, you need to copy the new application to a new directory. You also need to copy the Rsrc subdirectories of the Form, Std, System, Text, and of your own subsystems. If the resource files are missing, the application would still operate (kind of), but lose all string mappings, all dialog box layouts, and all custom menus.
All approaches:
In addition, you need to create your own versions of the menu definition file and of the About... dialog box (System/Rsrc/Menus and System/Rsrc/About). If your application is meant to be extensible, you also need to copy the symbol files (Sym/Xyz) of all modules whose interfaces should be public. This may or may not encompass the standard BlackBox modules. Make sure the structure of your new directories matches the subdirectory structure in the original BlackBox directory!
Adapt the Help menu command, and the corresponding help text in an appropriate way.
To distribute software electronically over a medium which doesn't support binary distribution, e.g., over e-mail, a standardASCIIencoder is available.
| Dev/Docu/User-Man.odc |
MODULE DevAlienTool;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
IMPORT
Services, Ports, Stores, Models, Views, Controllers, Properties, Dialog, Containers, Documents,
TextModels, TextMappers, TextViews, StdFolds;
PROCEDURE Indent (VAR f: TextMappers.Formatter; level: INTEGER);
BEGIN
WHILE level > 0 DO f.WriteTab; DEC(level) END
END Indent;
PROCEDURE WriteCause (VAR f: TextMappers.Formatter; cause: INTEGER);
BEGIN
f.rider.SetAttr(TextModels.NewColor(f.rider.attr, Ports.red));
CASE cause OF
| Stores.typeNotFound: f.WriteString("type in module not found")
| Stores.inconsModuleVersion: f.WriteString("inconsistent module version")
| Stores.invalidModuleFile: f.WriteString("invalid module file")
| Stores.moduleFileNotFound: f.WriteString("module not found")
| Stores.inconsistentType: f.WriteString("type path in module inconsistent with stored version")
| Stores.inconsistentVersion: f.WriteString("inconsistent version / program error")
| Stores.alienVersion: f.WriteString("alien version - outdated program")
| Stores.alienComponent: f.WriteString("alien component - required sub-part failed to internalize")
ELSE f.WriteString("unknown (code"); f.WriteInt(cause); f.WriteChar(")")
END;
f.rider.SetAttr(TextModels.NewColor(f.rider.attr, Ports.black));
END WriteCause;
PROCEDURE Out (VAR f: TextMappers.Formatter; level: INTEGER; st: Stores.Store);
VAR t: Stores.TypeName;
PROCEDURE OutAlien (VAR f: TextMappers.Formatter;
path: Stores.TypePath; cause: INTEGER; c: Stores.AlienComp);
VAR i: INTEGER; t: TextModels.Model; form: TextMappers.Formatter;
BEGIN
f.WriteString(" ");
t := TextModels.dir.New(); form.ConnectTo(t);
form.rider.SetAttr(TextModels.NewColor(form.rider.attr, Ports.blue));
form.WriteString(path[0]);
form.rider.SetAttr(TextModels.NewColor(form.rider.attr, Ports.black));
form.WriteLn;
INC(level);
IF path[1] # "" THEN
Indent(form, level); form.WriteString("path: (");
i := 1;
WHILE path[i] # "" DO
form.WriteString(path[i]);
INC(i);
IF path[i] # "" THEN form.WriteString(", ") END
END;
form.WriteChar(")"); form.WriteLn
END;
Indent(form, level); form.WriteString("cause: "); WriteCause(form, cause); form.WriteLn;
Indent(form, level); form.WriteString("comps: "); form.WriteLn;
INC(level);
WHILE c # NIL DO
WITH c: Stores.AlienPiece DO
Indent(form, level); form.WriteInt(c.len); form.WriteString(" bytes data"); form.WriteLn
| c: Stores.AlienPart DO
IF c.store # NIL THEN
Out(form, level, c.store)
ELSE Indent(form, level); form.WriteString("NIL reference"); form.WriteLn
END
END;
c := c.next
END;
DEC(level, 2);
Indent(form, level);
f.WriteView(StdFolds.dir.New(StdFolds.collapsed, "", t));
f.rider.SetAttr(TextModels.NewColor(f.rider.attr, Ports.blue));
f.WriteString(path[0]);
f.rider.SetAttr(TextModels.NewColor(f.rider.attr, Ports.black));
f.WriteView(StdFolds.dir.New(StdFolds.collapsed, "", NIL));
f.WriteLn;
END OutAlien;
BEGIN
Indent(f, level);
WITH st: Stores.Alien DO
f.WriteString("Alien Store"); OutAlien(f, st.path, st.cause, st.comps)
ELSE
Services.GetTypeName(st, t);
WITH st: Documents.Document DO f.WriteString("Document")
| st: Containers.Controller DO f.WriteString("Container Controller")
| st: Containers.View DO f.WriteString("Container View")
| st: Containers.Model DO f.WriteString("Container Model")
| st: Controllers.Controller DO f.WriteString("Controller")
| st: Views.View DO f.WriteString("View")
| st: Models.Model DO f.WriteString("Model")
ELSE f.WriteString("Store")
END;
f.WriteString(' "'); f.WriteString(t); f.WriteChar('"'); f.WriteLn
END
END Out;
PROCEDURE Analyze*;
VAR v: Views.View; f: TextMappers.Formatter; d: Documents.Document;
ops: Controllers.PollOpsMsg; bp: Properties.BoundsPref; t: TextModels.Model;
BEGIN
Controllers.PollOps(ops); v := ops.singleton;
IF v # NIL THEN
IF v IS Views.Alien THEN
t := TextModels.dir.New();
f.ConnectTo(t);
Out(f, 0, v(Views.Alien).store);
StdFolds.ExpandFolds(t, FALSE, "");
v := TextViews.dir.New(t);
Views.OpenAux(v, "Alien Info");
(*
bp.w := Views.undefined; bp.h := Views.undefined;
Views.HandlePropMsg(v, bp);
d := Documents.dir.New(v, bp.w, bp.h);
Views.OpenAux(d, "Alien Info")
*)
ELSE Dialog.ShowMsg("#Dev:NoAlienView")
END
ELSE Dialog.ShowMsg("#Dev:NoSingletonFound")
END
END Analyze;
END DevAlienTool.
Strings
NoAlienView no alien view
NoSingletonFound no singleton found
Info
SEPARATOR
"&Aliens" "" "DevAlienTool.Analyze" "DevAlienTool.SingletonGuard"
END
C | Dev/Mod/AlienTool.odc |
MODULE DevAnalyzer;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070123, bh, NewString call changed (Unicode support)
- 20140929, center #16, bug fix in SetObj/UseObj when reusing FOR-loop variables in nested FOR-loops
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150513, center #43, extending the size of code procedures
- 20160324, center #111, code cleanups
- 20210929, adimetrius, treat underscore vars as anonymous: don't report Used before set, Never used etc.
"
issues = "
- ...
"
**)
IMPORT
TextMappers, TextModels, TextViews, DevMarkers, Stores, Models, Dialog, StdLog,
CPT := DevCPT, CPS := DevCPS, CPM := DevCPM, CPB := DevCPB, StdRegistry, Utf;
CONST
(* numtyp values *)
char = 1; integer = 2; real = 4; int64 = 5; real32 = 6; real64 = 7;
(*symbol values*)
null = 0; times = 1;
and = 5; plus = 6; minus = 7; or = 8; eql = 9;
leq = 12; geq = 14;
in = 15; is = 16; arrow = 17; dollar = 18; period = 19;
comma = 20; colon = 21; upto = 22; rparen = 23; rbrak = 24;
rbrace = 25; of = 26; then = 27; do = 28; to = 29;
by = 30; not = 33;
lparen = 40; lbrak = 41; lbrace = 42; becomes = 44;
number = 45; nil = 46; string = 47; ident = 48; semicolon = 49;
bar = 50; end = 51; else = 52; elsif = 53; until = 54;
if = 55; case = 56; while = 57; repeat = 58; for = 59;
loop = 60; with = 61; exit = 62; return = 63; array = 64;
record = 65; pointer = 66; begin = 67; const = 68; type = 69;
var = 70; out = 71; procedure = 72; close = 73; import = 74;
module = 75; eof = 76;
(* object modes *)
Var = 1; VarPar = 2; Con = 3; Fld = 4; Typ = 5; LProc = 6; XProc = 7;
SProc = 8; CProc = 9; IProc = 10; Mod = 11; TProc = 13; Attr = 20;
(* Structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Set = 9;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; Int64 = 18;
intSet = {Int8..Int32, Int64}; charSet = {Char8, Char16};
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(*function number*)
newfn = 1; incfn = 13; sysnewfn = 30;
(*<< function number*)
ordfn = 4;
minfn = 7; maxfn = 8; chrfn = 9;
sizefn = 12; decfn = 14;
inclfn = 15; exclfn = 16; lenfn = 17; bitsfn = 37;
(*<< SYSTEM function number*)
adrfn = 20;
getfn = 24; getrfn = 26;
valfn = 29;
(* nodes classes *)
Nvar = 0; Nvarpar = 1; Nfield = 2; Nderef = 3; Nindex = 4;
Nconst = 7; Ntype = 8; Nproc = 9; Ncall = 13;
Nif = 15; Ncaselse = 16; Ncasedo = 17;
Nifelse = 20; Ncase = 21; Nwhile = 22; Nrepeat = 23; Nloop = 24; Nexit = 25;
Nwith = 27; Ncomp = 30;
(* node subclasses *)
super = 1;
(* module visibility of objects *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* procedure flags (conval.setval) *)
hasBody = 1; isRedef = 2;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval)*)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
(* case statement flags (conval.setval) *)
useTable = 1; useTree = 2;
(* sysflags *)
inBit = 2; outBit = 4; newBit = 8; iidBit = 16; interface = 10;
clean = CPM.ConstNotAlloc; (*<< values for obj.linkadr: untouched *)
used = clean+1; usedSet = clean+2; set = clean+3; (*<< used, used then set, set *)
setUsed = clean+4; setUsedP = clean+5; (*<< set then used, possibly set and used (var par) *)
noChange = (setUsedP+15) DIV 16 * 16; (*<< for loop variables shouldn't be changed *)
(*<< error messages *)
neverUsed = 900; neverSet = 901; usedBSet = 902; setBNUsed = 903; usedVarPar = 904;
outerScope = 905; interAcc = 906; (*redefinition = 907; newdefinition = 908;*)
statAfterRetEx = 909; loopVarSet = 910; (*impliedTypeGuard = 911;*)
superfluousTypeGuard = 912; evaluationSeq = 913; superfluousShort = 914;
semicolons = 930; (*<< special stuff *)
(*<< selector flags for Selector *)
SelAssign = TRUE; SelNoAssign = FALSE;
SelVarPar = TRUE; SelNoVarPar = FALSE;
SelUseBSet = TRUE; SelNoUseBSet = FALSE;
regKey = "Dev\Analyzer\";
TYPE
Elem = POINTER TO RECORD
next: Elem;
struct: CPT.Struct;
obj, base: CPT.Object;
pos: INTEGER;
name: CPT.String
END;
Warning = POINTER TO RECORD (*<< list of warning positions *)
next: Warning;
n: SHORTINT;
pos: INTEGER
END;
VAR
options*: RECORD (*<<O/F*)
varpar*, exported*, intermediate*, levels*, tbProcs*,
sideEffects*, semicolons*: BOOLEAN;
statements-: INTEGER; fileName-: TextMappers.String
END;
errHead: Warning; (*<< root for warning position list *)
nofStats: INTEGER; (*<< number of statements in module *)
sourceR: TextModels.Reader;
str: Dialog.String;
sym, level: BYTE;
LoopLevel: SHORTINT;
TDinit, lastTDinit: CPT.Node;
userList: Elem;
recList: Elem;
hasReturn: BOOLEAN;
PROCEDURE^ Type(VAR typ: CPT.Struct; VAR name: CPT.String);
PROCEDURE^ Expression(VAR x: CPT.Node);
PROCEDURE^ Block(VAR procdec, statseq: CPT.Node);
(* forward type handling *)
PROCEDURE IncompleteType (typ: CPT.Struct): BOOLEAN;
BEGIN
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
RETURN (typ = CPT.undftyp) OR (typ.comp = Record) & (typ.BaseTyp = CPT.undftyp)
END IncompleteType;
PROCEDURE SetType (struct: CPT.Struct; obj: CPT.Object; typ: CPT.Struct; name: CPT.String);
VAR u: Elem;
BEGIN
IF obj # NIL THEN obj.typ := typ ELSE struct.BaseTyp := typ END;
IF name # NIL THEN
NEW(u); u.struct := struct; u.obj := obj; u.pos := CPM.errpos; u.name := name;
u.next := userList; userList := u
END
END SetType;
PROCEDURE CheckAlloc (VAR typ: CPT.Struct; dynAllowed: BOOLEAN; pos: INTEGER);
BEGIN
typ.pvused := TRUE;
IF typ.comp = DynArr THEN
IF ~dynAllowed THEN CPM.Mark(88, pos); typ := CPT.undftyp END
ELSIF typ.comp = Record THEN
IF (typ.attribute = absAttr) OR (typ.attribute = limAttr) & (typ.mno # 0) THEN
CPM.Mark(193, pos); typ := CPT.undftyp
END
END
END CheckAlloc;
PROCEDURE CheckRecursiveType (outer, inner: CPT.Struct; pos: INTEGER);
VAR fld: CPT.Object;
BEGIN
IF outer = inner THEN CPM.Mark(58, pos)
ELSIF inner.comp IN {Array, DynArr} THEN CheckRecursiveType(outer, inner.BaseTyp, pos)
ELSIF inner.comp = Record THEN
fld := inner.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
CheckRecursiveType(outer, fld.typ, pos);
fld := fld.link
END;
IF inner.BaseTyp # NIL THEN CheckRecursiveType(outer, inner.BaseTyp, pos) END
END
END CheckRecursiveType;
PROCEDURE FixType (struct: CPT.Struct; obj: CPT.Object; typ: CPT.Struct; pos: INTEGER); (* fix forward reference *)
VAR t: CPT.Struct; f, bf: CPT.Object; i: SHORTINT;
BEGIN
IF obj # NIL THEN
IF obj.mode = Var THEN (* variable type *)
IF struct # NIL THEN (* receiver type *)
IF (typ.form # Pointer) OR (typ.BaseTyp # struct) THEN CPM.Mark(180, pos) END
ELSE CheckAlloc(typ, obj.mnolev > level, pos) (* TRUE for parameters *)
END
ELSIF obj.mode = VarPar THEN (* varpar type *)
IF struct # NIL THEN (* varpar receiver type *)
IF typ # struct THEN CPM.Mark(180, pos) END
END
ELSIF obj.mode = Fld THEN (* field type *)
CheckAlloc(typ, FALSE, pos);
CheckRecursiveType(struct, typ, pos)
ELSIF obj.mode = TProc THEN (* proc return type *)
IF typ.form = Comp THEN typ := CPT.undftyp; CPM.Mark(54, pos) END
ELSIF obj.mode = Typ THEN (* alias type *)
IF typ.form IN {Byte..Set, Char16, Int64} THEN (* make alias structure *)
t := CPT.NewStr(typ.form, Basic); i := t.ref;
t^ := typ^; t.ref := i; t.strobj := obj; t.mno := 0;
t.BaseTyp := typ; typ := t
END;
IF obj.vis # internal THEN
IF typ.comp = Record THEN typ.exp := TRUE
ELSIF typ.form = Pointer THEN typ.BaseTyp.exp := TRUE
END
END
ELSE HALT(100)
END;
obj.typ := typ
ELSE
IF struct.form = Pointer THEN (* pointer base type *)
IF typ.comp = Record THEN CPM.PropagateRecPtrSysFlag(typ.sysflag, struct.sysflag)
ELSIF typ.comp IN {Array, DynArr} THEN CPM.PropagateArrPtrSysFlag(typ.sysflag, struct.sysflag)
ELSE typ := CPT.undftyp; CPM.Mark(57, pos)
END;
struct.untagged := struct.sysflag # 0;
IF (struct.strobj # NIL) & (struct.strobj.vis # internal) THEN typ.exp := TRUE END
ELSIF struct.comp = Array THEN (* array base type *)
CheckAlloc(typ, FALSE, pos);
CheckRecursiveType(struct, typ, pos)
ELSIF struct.comp = DynArr THEN (* array base type *)
CheckAlloc(typ, TRUE, pos);
CheckRecursiveType(struct, typ, pos)
ELSIF struct.comp = Record THEN (* record base type *)
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
typ.pvused := TRUE; struct.extlev := SHORT(SHORT(typ.extlev + 1));
CPM.PropagateRecordSysFlag(typ.sysflag, struct.sysflag);
IF (typ.attribute = 0) OR (typ.attribute = limAttr) & (typ.mno # 0) THEN CPM.Mark(181, pos)
ELSIF (struct.attribute = absAttr) & (typ.attribute # absAttr) THEN CPM.Mark(191, pos)
ELSIF (typ.attribute = limAttr) & (struct.attribute # limAttr) THEN CPM.Mark(197, pos)
END;
f := struct.link;
WHILE f # NIL DO (* check for field name conflicts *)
CPT.FindField(f.name, typ, bf);
IF bf # NIL THEN CPM.Mark(1, pos) END;
f := f.link
END;
CheckRecursiveType(struct, typ, pos);
struct.untagged := struct.sysflag # 0
ELSIF struct.form = ProcTyp THEN (* proc type return type *)
IF typ.form = Comp THEN typ := CPT.undftyp; CPM.Mark(54, pos) END;
ELSE HALT(100)
END;
struct.BaseTyp := typ
END
END FixType;
PROCEDURE CheckForwardTypes;
VAR u, next: Elem; progress: BOOLEAN;
BEGIN
u := userList; userList := NIL;
WHILE u # NIL DO
next := u.next; CPS.name := u.name$; CPT.Find(CPS.name, u.base);
IF u.base = NIL THEN CPM.Mark(0, u.pos)
ELSIF u.base.mode # Typ THEN CPM.Mark(72, u.pos)
ELSE u.next := userList; userList := u; (* reinsert *)
IF u.base.num < set THEN (* BJ: If already also used, don't reset *)
u.base.num := set (*<< forward types are set by default *)
END
END;
u := next
END;
REPEAT (* iteration for multy level alias *)
u := userList; userList := NIL; progress := FALSE;
WHILE u # NIL DO
next := u.next;
IF IncompleteType(u.base.typ) THEN
u.next := userList; userList := u (* reinsert *)
ELSE
progress := TRUE;
FixType(u.struct, u.obj, u.base.typ, u.pos)
END;
u := next
END
UNTIL (userList = NIL) OR ~progress;
u := userList; (* remaining type relations are cyclic *)
WHILE u # NIL DO
IF (u.obj = NIL) OR (u.obj.mode = Typ) THEN CPM.Mark(58, u.pos) END;
u := u.next
END
END CheckForwardTypes;
PROCEDURE CheckUnimpl (m: CPT.Object; typ: CPT.Struct; pos: INTEGER);
VAR obj: CPT.Object; res: INTEGER; n: ARRAY 256 OF CHAR;
BEGIN
IF m # NIL THEN
IF (m.mode = TProc) & (absAttr IN m.conval.setval) THEN
CPT.FindField(m.name^, typ, obj);
IF (obj = NIL) OR (obj.mode # TProc) OR (absAttr IN obj.conval.setval) THEN
CPM.Mark(192, pos);
CPM.LogWLn; CPM.LogWStr(" "); Utf.Utf8ToString(m.name, n, res); CPM.LogWStr(n);
CPM.LogWStr(" not implemented in "); Utf.Utf8ToString(typ.strobj.name^, n, res); CPM.LogWStr(n)
END
END;
CheckUnimpl(m.left, typ, pos);
CheckUnimpl(m.right, typ, pos)
END
END CheckUnimpl;
PROCEDURE CheckRecords (rec: Elem);
VAR b: CPT.Struct;
BEGIN
WHILE rec # NIL DO (* check for unimplemented methods in base type *)
b := rec.struct.BaseTyp;
WHILE (b # NIL) & (b # CPT.undftyp) DO
CheckUnimpl(b.link, rec.struct, rec.pos);
b := b.BaseTyp
END;
rec := rec.next
END
END CheckRecords;
PROCEDURE err(n: SHORTINT);
BEGIN CPM.err(n)
END err;
PROCEDURE CheckSym(s: SHORTINT);
BEGIN
IF sym = s THEN CPS.Get(sym) ELSE CPM.err(s) END
END CheckSym;
PROCEDURE err2(n: SHORTINT; pos: INTEGER); (*<<*)
VAR e, h: Warning;
BEGIN
e := errHead;
WHILE (e.next # NIL) & (e.next.pos < pos) DO e := e.next END;
IF e.next = NIL THEN
NEW(e.next); h := e.next (* end of list *)
ELSIF (e.next.pos = pos) & (e.next.n = n) THEN
RETURN (* don't allow duplicates *)
ELSE
NEW(h); h.next := e.next; e.next := h
END;
h.n := n; h.pos := pos
END err2;
PROCEDURE DumpObj(obj: CPT.Object);
(* BEGIN
CPM.LogWStr("message for object: "); CPM.LogWStr(obj.name); CPM.LogWLn
*) END DumpObj;
PROCEDURE CheckScope(scope: CPT.Object); (*<<*)
PROCEDURE^ Check(obj: CPT.Object);
PROCEDURE CheckTyp(typ: CPT.Struct);
BEGIN
IF (typ.form = Pointer) & (typ.BaseTyp.strobj = NIL) THEN (* only if PTR TO RECORD END *)
typ := typ.BaseTyp
END;
IF (typ.form = Comp) & (typ.comp = Record) THEN Check(typ.link) END
END CheckTyp;
PROCEDURE IsAnon (name: CPT.String): BOOLEAN;
BEGIN
RETURN (name[0] = "_") OR (name[LEN(name$)-1] = "_")
END IsAnon;
PROCEDURE Check(obj: CPT.Object);
BEGIN
IF obj # NIL THEN
Check(obj.left);
IF (obj.num # setUsed) & (options.exported OR (obj.vis = internal) OR (obj.mode = Mod)) THEN
CASE obj.mode OF
| (*Var, VarPar,*) Fld:
CASE obj.num OF
| clean: DumpObj(obj); err2(neverUsed, obj.adr)
| used: IF obj.name[0] # "@" THEN DumpObj(obj); err2(neverSet, obj.adr) END
| usedSet: IF obj.mode # Fld THEN DumpObj(obj); err2(usedBSet, obj.adr) END
| set: DumpObj(obj); err2(setBNUsed, obj.adr);
| setUsedP: IF options.varpar & (obj.mode # Fld) THEN DumpObj(obj); err2(usedVarPar, obj.adr); END
END;
IF obj.typ.strobj = NIL THEN CheckTyp(obj.typ) END (*x: RECORD ... END*)
| Var, VarPar(*, Fld*):
CASE obj.num OF
| clean: DumpObj(obj); err2(neverUsed, obj.adr)
| used: IF (obj.name[0] # "@") & ~IsAnon(obj.name) THEN DumpObj(obj); err2(neverSet, obj.adr) END
| usedSet: IF (*obj.mode # Fld*) ~IsAnon(obj.name) THEN DumpObj(obj); err2(usedBSet, obj.adr) END
| set: IF ~IsAnon(obj.name) THEN DumpObj(obj); err2(setBNUsed, obj.adr) END
| setUsedP:
IF options.varpar & (obj.mode # Fld) & ~IsAnon(obj.name) THEN
DumpObj(obj); err2(usedVarPar, obj.adr);
END
END;
IF obj.typ.strobj = NIL THEN CheckTyp(obj.typ) END (*x: RECORD ... END*)
| Con, Typ: CASE obj.num OF set: DumpObj(obj); err2(neverUsed, obj.adr) END
| LProc, XProc, CProc, IProc: CASE obj.num OF set: DumpObj(obj); err2(neverUsed, obj.adr) END
| TProc: (* neverUsed not determinable for redefined methods because of dynamic binding *)
(* IF ((obj.link.typ.form = Pointer) & (obj.link.typ.BaseTyp.BaseTyp = NIL) OR
(* (obj.link.typ.comp = Record) & *) (obj.link.typ.BaseTyp = NIL)) & (obj.num = set) THEN*)
(* BJ: Changed this IF to correct ABSTRACT and EMPTY procedures*)
IF ~(absAttr IN obj.conval.setval) & ~(empAttr IN obj.conval.setval) &
((obj.link.typ.form = Pointer) & (obj.link.typ.BaseTyp.BaseTyp = NIL) OR
(obj.link.typ.BaseTyp = NIL)) & (obj.num = set) THEN
DumpObj(obj); err2(neverUsed, obj.adr)
END
| Mod: DumpObj(obj); err2(neverUsed, obj.adr)
ELSE
END
END; (*IF*)
CASE obj.mode OF
| LProc, XProc, IProc, TProc: CheckScope(obj.scope)
| Typ:
IF obj.typ.mno = 0 THEN
CheckTyp(obj.typ) (* checking of fields and type bound procedures, only if not imported type! *)
END
ELSE
END;
Check(obj.right)
END
END Check;
BEGIN Check(scope.right)
END CheckScope;
PROCEDURE CheckOuter; (*<< check outer scopes for obj with OPS.name*)
VAR o: CPT.Object;
BEGIN
IF options.intermediate THEN
CPT.Find(CPS.name, o);
IF o # NIL THEN DumpObj(o); err2(outerScope, CPM.curpos) END
END
END CheckOuter;
PROCEDURE UseType(obj: CPT.Object; pos: INTEGER); (*<< type obj gets used*)
BEGIN
IF (obj # NIL) & ((obj.vis = internal) OR options.exported) THEN
IF options.intermediate & (obj.mnolev # level) & (obj.mnolev > 0) THEN (*mnolev > 0 -> intermediate*)
DumpObj(obj); err2(interAcc, pos)
END;
CASE obj.num OF clean, set: obj.num := setUsed
| used, setUsed: (* used only for non-declarded type *)
END
END
END UseType;
PROCEDURE UseObj(obj: CPT.Object; markUseBSet: BOOLEAN; pos: INTEGER); (*<< obj gets used *)
BEGIN
IF (obj # NIL) & (obj.mnolev >= 0) THEN
IF options.intermediate & (obj.mnolev # level) & (obj.mnolev > 0) & (obj.mode < LProc) THEN
DumpObj(obj); err2(interAcc, pos)
END;
CASE obj.num OF
| clean:
IF (obj.mode = Con) OR (obj.mode # Fld) & (obj.mnolev # level) & ~options.levels THEN
obj.num := setUsed
ELSE
obj.num := used;
IF markUseBSet & (obj.mode # SProc) & (obj.mode # Fld) & (obj.typ.form # Comp) THEN
DumpObj(obj); err2(usedBSet, pos)
END
END
| set: obj.num := setUsed
ELSE (* already marked as being used *)
END
END
END UseObj;
PROCEDURE SetObj(obj: CPT.Object; varPar: BOOLEAN; pos: INTEGER); (*<< var/proc/const/field obj gets set*)
BEGIN
IF (obj # NIL) & (obj.mnolev >= 0) THEN
CASE obj.num OF
| clean: IF varPar THEN obj.num := setUsedP ELSE obj.num := set END
| used:
IF varPar THEN obj.num := setUsedP
ELSIF (obj.mnolev = level) OR options.levels THEN obj.num := usedSet
ELSIF ~options.levels THEN obj.num := setUsed
END
| usedSet, setUsed, setUsedP:
| set: IF varPar THEN obj.num := setUsed END
ELSE DumpObj(obj); err2(loopVarSet, pos) (* for loop variable gets set!*)
END
END
END SetObj;
PROCEDURE Selector(x: CPT.Node; assignment, varPar, markUseBSet: BOOLEAN; pos: INTEGER); (*<<*)
BEGIN
IF assignment THEN
CASE x.class OF
| Nvar, Nvarpar, Nfield:
IF (x.class # Nfield) & options.intermediate & (x.obj.mnolev # level) & (x.obj.mnolev > 0) THEN
DumpObj(x.obj); err2(interAcc, pos) (* assignment to intermediate *)
END;
SetObj(x.obj, varPar, pos); x := x.left; (* assignment to b in {a.}b := ... *)
| Nindex: (* assignment to b in {a.}b{[i]} := ... *)
REPEAT x := x.left UNTIL x.class # Nindex;
IF x.class IN {Nvar, Nvarpar, Nfield} THEN SetObj(x.obj, varPar, pos); x := x.left END
ELSE
END;
WHILE (x # NIL) & (x.class IN {Nvar, Nvarpar, Nfield}) DO SetObj(x.obj, varPar, pos); x := x.left END
END;
WHILE x # NIL DO
IF x.class IN {Nvar, Nvarpar, Nfield, Nconst, Nproc} THEN UseObj(x.obj, markUseBSet, pos); END;
x := x.left
END
END Selector;
PROCEDURE qualident(VAR id: CPT.Object);
VAR obj: CPT.Object; lev: BYTE; m: BOOLEAN;
BEGIN (*sym = ident*)
CPT.Find(CPS.name, obj); CPS.Get(sym);
m := FALSE; (*<<*)
IF (sym = period) & (obj # NIL) & (obj.mode = Mod) THEN
obj.num := setUsed; (*<< module gets used (set by default) *)
m := TRUE; (*<< it's a module! *)
CPS.Get(sym);
IF sym = ident THEN
CPT.FindImport(CPS.name, obj, obj); CPS.Get(sym)
ELSE err(ident); obj := NIL
END
END ;
IF obj = NIL THEN err(0);
obj := CPT.NewObj(); obj.mode := Var; obj.typ := CPT.undftyp; obj.adr := 0
ELSE lev := obj.mnolev;
IF (obj.mode IN {Var, VarPar}) & (lev # level) THEN
obj.leaf := FALSE;
IF lev > 0 THEN CPB.StaticLink(SHORT(SHORT(level-lev)), TRUE) END (* !!! *)
END
END ;
IF m & (obj # NIL) THEN obj.num := setUsed END; (*<< imported obj get used always! *)
id := obj
END qualident;
PROCEDURE ConstExpression(VAR x: CPT.Node);
BEGIN Expression(x);
IF x.class # Nconst THEN
err(50); x := CPB.NewIntConst(1)
END
END ConstExpression;
PROCEDURE CheckMark(obj: CPT.Object); (* !!! *)
BEGIN
CPS.Get(sym);
IF (sym = times) OR (sym = minus) THEN
IF (level > 0) OR ~(obj.mode IN {Var, Fld, TProc}) & (sym = minus) THEN err(41) END ;
IF sym = times THEN obj.vis := external ELSE obj.vis := externalR END ;
CPS.Get(sym)
ELSE obj.vis := internal
END;
IF (obj.mode IN {LProc, XProc, Var, Typ}) & (sym = lbrak) THEN
CPS.Get(sym);
IF sym = string THEN
IF obj.conval = NIL THEN obj.conval := CPT.NewConst() END;
IF CPS.str^ # "" THEN obj.conval.ext := CPS.str END;
CPS.Get(sym);
IF sym = comma THEN
CPS.Get(sym);
IF sym = string THEN
IF obj.conval.ext # NIL THEN
obj.conval.link := CPT.NewConst(); obj.conval.link.ext := obj.conval.ext
END;
obj.conval.ext := NIL;
IF CPS.str^ # "" THEN obj.conval.ext := CPS.str END;
CPS.Get(sym)
ELSE err(string)
END
END
ELSE err(string)
END;
CheckSym(rbrak);
IF ~(CPM.interface IN CPM.options) THEN err(225) END
END
END CheckMark;
PROCEDURE CheckSysFlag (VAR sysflag: SHORTINT;
GetSF: PROCEDURE(IN id: ARRAY OF SHORTCHAR; num: SHORTINT;
VAR flag: SHORTINT));
VAR x: CPT.Object; i: SHORTINT;
BEGIN
sysflag := 0;
IF sym = lbrak THEN
CPS.Get(sym);
WHILE (sym = number) OR (sym = ident) OR (sym = string) DO
IF sym = number THEN
IF CPS.numtyp = integer THEN
i := SHORT(CPS.intval); GetSF("", i, sysflag)
ELSE err(225)
END
ELSIF sym = ident THEN
CPT.Find(CPS.name, x);
IF (x # NIL) & (x.mode = Con) & (x.typ.form IN {Int8, Int16, Int32}) THEN
i := SHORT(x.conval.intval); GetSF("", i, sysflag)
ELSE
GetSF(CPS.name, 0, sysflag)
END
ELSE
GetSF(CPS.str, 0, sysflag)
END;
CPS.Get(sym);
IF (sym = comma) OR (sym = plus) THEN CPS.Get(sym) END
END;
CheckSym(rbrak)
END
END CheckSysFlag;
PROCEDURE Receiver(VAR mode, vis: BYTE; VAR name: CPT.Name; VAR typ, rec: CPT.Struct);
VAR tname: CPT.String;
BEGIN
typ := CPT.undftyp; rec := NIL; vis := 0;
IF sym = var THEN CPS.Get(sym); mode := VarPar
ELSIF sym = in THEN CPS.Get(sym); mode := VarPar; vis := inPar (* ??? *)
ELSE mode := Var
END ;
name := CPS.name; CheckSym(ident); CheckSym(colon);
IF sym # ident THEN err(ident) END;
Type(typ, tname);
IF tname = NIL THEN
IF typ.form = Pointer THEN rec := typ.BaseTyp ELSE rec := typ END;
IF ~((mode = Var) & (typ.form = Pointer) & (rec.comp = Record) OR
(mode = VarPar) & (typ.comp = Record)) THEN err(70); rec := NIL END;
IF (rec # NIL) & (rec.mno # level) THEN err(72); rec := NIL END
ELSE err(0)
END;
CheckSym(rparen);
IF rec = NIL THEN rec := CPT.NewStr(Comp, Record); rec.BaseTyp := NIL END
END Receiver;
PROCEDURE FormalParameters(VAR firstPar: CPT.Object; VAR resTyp: CPT.Struct; VAR name: CPT.String);
VAR mode, vis: BYTE; sys: SHORTINT;
par, first, last, newPar, iidPar: CPT.Object; typ: CPT.Struct;
BEGIN
first := NIL; last := firstPar;
newPar := NIL; iidPar := NIL;
IF (sym = ident) OR (sym = var) OR (sym = in) OR (sym = out) THEN
LOOP
sys := 0; vis := 0;
IF sym = var THEN CPS.Get(sym); mode := VarPar
ELSIF sym = in THEN CPS.Get(sym); mode := VarPar; vis := inPar
ELSIF sym = out THEN CPS.Get(sym); mode := VarPar; vis := outPar
ELSE mode := Var
END ;
IF mode = VarPar THEN CheckSysFlag(sys, CPM.GetVarParSysFlag) END;
IF ODD(sys DIV inBit) THEN vis := inPar
ELSIF ODD(sys DIV outBit) THEN vis := outPar
END;
IF ODD(sys DIV newBit) & (vis # outPar) THEN err(225)
ELSIF ODD(sys DIV iidBit) & (vis # inPar) THEN err(225)
END;
LOOP
IF sym = ident THEN
CheckOuter; (*<<*)
CPT.Insert(CPS.name, par); CPS.Get(sym);
par.adr := CPM.errpos; (*<<*)
par.mode := mode; par.link := NIL; par.vis := vis; par.sysflag := SHORT(sys);
IF mode = VarPar THEN (*<< parameters are set, except for out parameters *)
IF vis = inPar THEN par.num := setUsedP
ELSIF vis = outPar THEN
(* out parameters are not initialized, except for pointers and procedure variables *)
par.num := clean
ELSE par.num := setUsed
END
ELSE
par.num := set
END;
IF first = NIL THEN first := par END ;
IF firstPar = NIL THEN firstPar := par ELSE last.link := par END ;
last := par;
ELSE err(ident)
END;
IF sym = comma THEN CPS.Get(sym)
ELSIF sym = ident THEN err(comma)
ELSIF sym = var THEN err(comma); CPS.Get(sym)
ELSE EXIT
END
END ;
CheckSym(colon); Type(typ, name);
IF mode # VarPar THEN CheckAlloc(typ, TRUE, CPM.errpos) END;
IF (mode = VarPar) & (vis = inPar) & (typ.form # Undef) & (typ.form # Comp) & (typ.sysflag = 0) THEN
err(177)
END;
(* typ.pbused is set when parameter type name is parsed *)
WHILE first # NIL DO
SetType (NIL, first, typ, name);
IF ODD(sys DIV newBit) THEN
IF (newPar # NIL) OR (typ.form # Pointer) OR (typ.sysflag # interface) THEN err(168) END;
newPar := first
ELSIF ODD(sys DIV iidBit) THEN
IF (iidPar # NIL) OR (typ # CPT.guidtyp) THEN err(168) END;
iidPar := first
END;
first := first.link
END;
IF sym = semicolon THEN CPS.Get(sym)
ELSIF sym = ident THEN err(semicolon)
ELSE EXIT
END
END
END;
CheckSym(rparen);
IF (newPar = NIL) # (iidPar = NIL) THEN err(168) END;
name := NIL;
IF sym = colon THEN
CPS.Get(sym);
Type(resTyp, name);
IF resTyp.form = Comp THEN resTyp := CPT.undftyp; err(54) END
ELSE resTyp := CPT.notyp
END
END FormalParameters;
PROCEDURE CheckOverwrite (proc, base: CPT.Object; rec: CPT.Struct);
VAR o, bo: CPT.Object;
BEGIN
IF base # NIL THEN
IF base.conval.setval * {absAttr, empAttr, extAttr} = {} THEN err(182) END;
IF (proc.link.mode # base.link.mode) OR (proc.link.vis # base.link.vis)
OR ~CPT.Extends(proc.link.typ, base.link.typ) THEN err(115) END;
o := proc.link; bo := base.link;
WHILE (o # NIL) & (bo # NIL) DO
IF (bo.sysflag # 0) & (o.sysflag = 0) THEN (* propagate sysflags *)
o.sysflag := bo.sysflag
END;
o := o.link; bo := bo.link
END;
CPB.CheckParameters(proc.link.link, base.link.link, FALSE);
IF ~CPT.Extends(proc.typ, base.typ) THEN err(117) END;
IF (base.vis # proc.vis) & ((proc.vis # internal) OR rec.exp) THEN err(183) END;
INCL(proc.conval.setval, isRedef)
END
END CheckOverwrite;
PROCEDURE GetAttributes (proc, base: CPT.Object; owner: CPT.Struct); (* read method attributes *)
VAR attr, battr: SET; o: CPT.Object;
BEGIN
attr := {};
IF sym = comma THEN (* read attributes *)
CPS.Get(sym);
IF sym = ident THEN
CPT.Find(CPS.name, o);
IF (o # NIL) & (o.mode = SProc) & (o.adr = newfn) THEN
IF ~(CPM.oberon IN CPM.options) THEN INCL(attr, newAttr) ELSE err(178) END;
CPS.Get(sym);
IF sym = comma THEN
CPS.Get(sym);
IF sym = ident THEN CPT.Find(CPS.name, o) ELSE o := NIL; err(ident) END
ELSE o := NIL
END
END;
IF o # NIL THEN
IF (o.mode # Attr) OR (o.adr = limAttr) OR (CPM.oberon IN CPM.options) THEN err(178)
ELSE INCL(attr, o.adr)
END;
CPS.Get(sym)
END
ELSE err(ident)
END
END;
IF (base = NIL) & ~(newAttr IN attr) THEN err(185); INCL(attr, newAttr)
ELSIF (base # NIL) & (newAttr IN attr) THEN err(186)
END;
IF (owner.attribute # absAttr) & (absAttr IN attr) THEN err(190) END;
IF (owner.attribute = 0) OR (owner.attribute = limAttr) THEN
IF (empAttr IN attr) & (newAttr IN attr) THEN err(187)
ELSIF extAttr IN attr THEN err(188)
END
END;
IF base # NIL THEN
battr := base.conval.setval;
IF empAttr IN battr THEN
IF absAttr IN attr THEN err(189) END
ELSIF ~(absAttr IN battr) THEN
IF (absAttr IN attr) OR (empAttr IN attr) THEN err(189) END
END
END;
IF empAttr IN attr THEN
IF proc.typ # CPT.notyp THEN err(195)
ELSE
o := proc.link; WHILE (o # NIL) & (o.vis # outPar) DO o := o.link END;
IF o # NIL THEN err(195) END
END
END;
IF (owner.sysflag = interface) & ~(absAttr IN attr) THEN err(162) END;
proc.conval.setval := attr
END GetAttributes;
PROCEDURE RecordType(VAR typ: CPT.Struct; attr: CPT.Object);
VAR fld, first, last: CPT.Object; r: Elem; ftyp: CPT.Struct; name: CPT.String;
BEGIN typ := CPT.NewStr(Comp, Record); typ.BaseTyp := NIL;
CheckSysFlag(typ.sysflag, CPM.GetRecordSysFlag);
IF attr # NIL THEN
IF ~(CPM.oberon IN CPM.options) & (attr.adr # empAttr) THEN typ.attribute := SHORT(SHORT(attr.adr))
ELSE err(178)
END
END;
IF typ.sysflag = interface THEN
IF (CPS.str # NIL) & (CPS.str[0] = "{") THEN typ.ext := CPS.str END;
IF typ.attribute # absAttr THEN err(163) END;
IF sym # lparen THEN err(160) END
END;
IF sym = lparen THEN
CPS.Get(sym); (*record extension*)
IF sym = ident THEN
Type(ftyp, name);
IF ftyp.form = Pointer THEN ftyp := ftyp.BaseTyp END;
SetType(typ, NIL, ftyp, name);
IF (ftyp.comp = Record) & (ftyp # CPT.anytyp) THEN
ftyp.pvused := TRUE; typ.extlev := SHORT(SHORT(ftyp.extlev + 1));
CPM.PropagateRecordSysFlag(ftyp.sysflag, typ.sysflag);
IF (ftyp.attribute = 0) OR (ftyp.attribute = limAttr) & (ftyp.mno # 0) THEN err(181)
ELSIF (typ.attribute = absAttr) & (ftyp.attribute # absAttr) THEN err(191)
ELSIF (ftyp.attribute = limAttr) & (typ.attribute # limAttr) THEN err(197)
END
ELSIF ftyp # CPT.undftyp THEN err(53)
END
ELSE err(ident)
END ;
IF typ.attribute # absAttr THEN (* save typ for unimplemented method check *)
NEW(r); r.struct := typ; r.pos := CPM.errpos; r.next := recList; recList := r
END;
CheckSym(rparen)
END;
(*
CPT.OpenScope(0, NIL);
*)
first := NIL; last := NIL;
LOOP
IF sym = ident THEN
LOOP
IF sym = ident THEN
IF (typ.BaseTyp # NIL) & (typ.BaseTyp # CPT.undftyp) THEN
CPT.FindBaseField(CPS.name, typ, fld);
IF fld # NIL THEN err(1) END
END ;
CPT.FindField(CPS.name, typ, fld); (* not needed with actual CPT *)
IF fld # NIL THEN err(1) END;
CPT.InsertField(CPS.name, typ, fld);
fld.mode := Fld; fld.link := NIL; fld.typ := CPT.undftyp;
CheckMark(fld);
fld.adr := CPM.errpos; fld.num := clean; (*<<*)
IF first = NIL THEN first := fld END ;
IF last = NIL THEN typ.link := fld ELSE last.link := fld END ;
last := fld
ELSE err(ident)
END ;
IF sym = comma THEN CPS.Get(sym)
ELSIF sym = ident THEN err(comma)
ELSE EXIT
END
END ;
CheckSym(colon); Type(ftyp, name);
CheckAlloc(ftyp, FALSE, CPM.errpos);
WHILE first # NIL DO
SetType(typ, first, ftyp, name); first := first.link
END;
IF typ.sysflag = interface THEN err(161) END
END;
IF sym = semicolon THEN CPS.Get(sym);
IF ((sym = end) OR (sym = semicolon)) & options.semicolons THEN (*<< superfluous semicolon *)
err2(semicolons, CPM.errpos)
END
ELSIF sym = ident THEN err(semicolon)
ELSE EXIT
END
END;
(*
IF typ.link # NIL THEN ASSERT(typ.link = CPT.topScope.right) END;
typ.link := CPT.topScope.right; CPT.CloseScope;
*)
typ.untagged := typ.sysflag # 0;
CPB.Inittd(TDinit, lastTDinit, typ); CheckSym(end)
END RecordType;
PROCEDURE ArrayType(VAR typ: CPT.Struct);
VAR x: CPT.Node; n: INTEGER; sysflag: SHORTINT; name: CPT.String;
BEGIN CheckSysFlag(sysflag, CPM.GetArraySysFlag);
IF sym = of THEN (*dynamic array*)
typ := CPT.NewStr(Comp, DynArr); typ.mno := 0; typ.sysflag := sysflag;
CPS.Get(sym); Type(typ.BaseTyp, name); SetType(typ, NIL, typ.BaseTyp, name);
CheckAlloc(typ.BaseTyp, TRUE, CPM.errpos);
IF typ.BaseTyp.comp = DynArr THEN typ.n := typ.BaseTyp.n + 1 ELSE typ.n := 0 END
ELSE
typ := CPT.NewStr(Comp, Array); typ.sysflag := sysflag; ConstExpression(x);
IF x.typ.form IN {Int8, Int16, Int32} THEN n := x.conval.intval;
IF (n <= 0) OR (n > CPM.MaxIndex) THEN err(63); n := 1 END
ELSE err(42); n := 1
END ;
typ.n := n;
IF sym = of THEN
CPS.Get(sym); Type(typ.BaseTyp, name); SetType(typ, NIL, typ.BaseTyp, name);
CheckAlloc(typ.BaseTyp, FALSE, CPM.errpos)
ELSIF sym = comma THEN
CPS.Get(sym);
IF sym # of THEN ArrayType(typ.BaseTyp) END
ELSE err(35)
END
END;
typ.untagged := typ.sysflag # 0
END ArrayType;
PROCEDURE PointerType(VAR typ: CPT.Struct);
VAR name: CPT.String;
BEGIN typ := CPT.NewStr(Pointer, Basic); CheckSysFlag(typ.sysflag, CPM.GetPointerSysFlag);
CheckSym(to);
Type(typ.BaseTyp, name);
SetType(typ, NIL, typ.BaseTyp, name);
IF (typ.BaseTyp # CPT.undftyp) & (typ.BaseTyp.comp = Basic) THEN
typ.BaseTyp := CPT.undftyp; err(57)
END;
IF typ.BaseTyp.comp = Record THEN CPM.PropagateRecPtrSysFlag(typ.BaseTyp.sysflag, typ.sysflag)
ELSIF typ.BaseTyp.comp IN {Array, DynArr} THEN CPM.PropagateArrPtrSysFlag(typ.BaseTyp.sysflag, typ.sysflag)
END;
typ.untagged := typ.sysflag # 0
END PointerType;
PROCEDURE Type (VAR typ: CPT.Struct; VAR name: CPT.String); (* name # NIL => forward reference *)
VAR id: CPT.Object; tname: CPT.String;
BEGIN
typ := CPT.undftyp; name := NIL;
IF sym < lparen THEN err(12);
REPEAT CPS.Get(sym) UNTIL sym >= lparen
END ;
IF sym = ident THEN
CPT.Find(CPS.name, id);
IF (id = NIL) OR (id.mode = -1) OR (id.mode = Typ) & IncompleteType(id.typ) THEN (* forward type definition *)
name := CPT.NewName(CPS.name); CPS.Get(sym);
IF (id = NIL) & (sym = period) THEN (* missing module *)
err(0); CPS.Get(sym); name := NIL;
IF sym = ident THEN CPS.Get(sym) END
ELSIF sym = record THEN (* wrong attribute *)
err(178); CPS.Get(sym); name := NIL; RecordType(typ, NIL)
END
ELSE
qualident(id);
UseType(id, CPM.errpos); (*<< type gets used*)
IF id.mode = Typ THEN
IF ~(CPM.oberon IN CPM.options)
& ((id.typ = CPT.lreal64typ) OR (id.typ = CPT.lint64typ) OR (id.typ = CPT.lchar16typ)) THEN err(198) END;
typ := id.typ
ELSIF id.mode = Attr THEN
IF sym = record THEN
CPS.Get(sym); RecordType(typ, id)
ELSE err(12)
END
ELSE err(52)
END
END
ELSIF sym = array THEN
CPS.Get(sym); ArrayType(typ)
ELSIF sym = record THEN
CPS.Get(sym); RecordType(typ, NIL)
ELSIF sym = pointer THEN
CPS.Get(sym); PointerType(typ)
ELSIF sym = procedure THEN
CPS.Get(sym); typ := CPT.NewStr(ProcTyp, Basic);
(*
CheckSysFlag(typ.sysflag, CPM.GetProcTypSysFlag);
typ.untagged := typ.sysflag # 0;
*)
IF sym = lparen THEN
CPS.Get(sym); CPT.OpenScope(level, NIL);
FormalParameters(typ.link, typ.BaseTyp, tname); SetType(typ, NIL, typ.BaseTyp, tname); CPT.CloseScope
ELSE typ.BaseTyp := CPT.notyp; typ.link := NIL
END
ELSE err(12)
END ;
LOOP
IF (sym >= semicolon) & (sym <= else) OR (sym = rparen) OR (sym = eof)
OR (sym = number) OR (sym = comma) THEN EXIT END;
err(15); IF sym = ident THEN EXIT END;
CPS.Get(sym)
END
END Type;
PROCEDURE ^ selector(VAR x: CPT.Node);
PROCEDURE ^ StandProcCall(VAR x: CPT.Node);
PROCEDURE ActualParameters(VAR aparlist: CPT.Node; fpar: CPT.Object; VAR pre, lastp: CPT.Node);
VAR apar, last, newPar, iidPar: CPT.Node; id: CPT.Object; moreThan1: BOOLEAN; (*<< id, moreThan1 *)
BEGIN
aparlist := NIL; last := NIL;
IF sym # rparen THEN
moreThan1 := (fpar # NIL) & (fpar.link # NIL); (*<<*)
newPar := NIL; iidPar := NIL;
LOOP
(*<< Expression(apar) old code *)
IF sym # nil THEN
IF (fpar # NIL) & (fpar.mode = VarPar) & (fpar.vis # inPar) THEN (*<<*)
qualident(id); apar := CPB.NewLeaf(id); selector(apar);
IF (apar.class = Nproc) & (apar.obj.mode = SProc) & (apar.obj.adr = valfn) THEN
StandProcCall(apar)
END;
Selector(apar, SelAssign, SelVarPar, SelUseBSet, CPM.errpos)
ELSE (*<<*)
Expression(apar);
IF options.sideEffects & moreThan1 & (apar.class = Ncall) THEN
(*<< proc-calls in param-list: code might depend on evaluation sequence (if more than one param.) *)
err2(evaluationSeq, CPM.errpos)
END
END;
IF fpar # NIL THEN
IF (apar.typ.form = Pointer) & (fpar.typ.form = Comp) THEN CPB.DeRef(apar) END;
CPB.Param(apar, fpar);
IF fpar.mode = Var THEN CPB.CheckBuffering(apar, NIL, fpar, pre, lastp) END;
CPB.Link(aparlist, last, apar);
IF ODD(fpar.sysflag DIV newBit) THEN newPar := apar
ELSIF ODD(fpar.sysflag DIV iidBit) THEN iidPar := apar
END;
IF (newPar # NIL) & (iidPar # NIL) THEN CPB.CheckNewParamPair(newPar, iidPar) END;
fpar := fpar.link
ELSE err(64)
END;
ELSE
fpar := fpar.link; CPS.Get(sym)
END;
IF sym = comma THEN CPS.Get(sym)
ELSIF (lparen <= sym) & (sym <= ident) THEN err(comma)
ELSE EXIT
END
END
END;
IF fpar # NIL THEN err(65) END
END ActualParameters;
PROCEDURE selector(VAR x: CPT.Node);
VAR obj, proc, fpar: CPT.Object; y, apar, pre, lastp: CPT.Node; typ: CPT.Struct; name: CPT.Name;
BEGIN
LOOP
IF sym = lbrak THEN CPS.Get(sym);
LOOP
IF (x.typ # NIL) & (x.typ.form = Pointer) THEN CPB.DeRef(x) END ;
Expression(y); CPB.Index(x, y);
IF sym = comma THEN CPS.Get(sym) ELSE EXIT END
END ;
CheckSym(rbrak)
ELSIF sym = period THEN
CPS.Get(sym);
IF sym = ident THEN name := CPS.name; CPS.Get(sym);
IF x.typ # NIL THEN
IF x.typ.form = Pointer THEN
IF x.obj # NIL THEN UseObj(x.obj, TRUE, x.obj.adr) END;
CPB.DeRef(x)
END ;
IF x.typ.comp = Record THEN
typ := x.typ; CPT.FindField(name, typ, obj); CPB.Field(x, obj);
IF (obj # NIL) & (obj.mode = TProc) THEN
IF sym = arrow THEN (* super call *) CPS.Get(sym);
y := x.left;
IF y.class = Nderef THEN y := y.left END ; (* y = record variable *)
IF y.obj # NIL THEN
proc := CPT.topScope; (* find innermost scope which owner is a TProc *)
WHILE (proc.link # NIL) & (proc.link.mode # TProc) DO proc := proc.left END ;
IF (proc.link = NIL) OR (proc.link.link # y.obj) THEN err(75) END ;
typ := y.obj.typ;
IF typ.form = Pointer THEN typ := typ.BaseTyp END ;
CPT.FindBaseField(x.obj.name^, typ, proc);
IF proc # NIL THEN x.subcl := super;
UseObj(proc, TRUE, proc.adr); (*<< touch super proc*)
IF proc.conval.setval * {absAttr, empAttr} # {} THEN err(194) END
ELSE err(74)
END
ELSE err(75)
END
ELSE
UseObj(obj, TRUE, obj.adr); (*<< touch obj only if not super call! *)
proc := obj;
WHILE (proc.mnolev >= 0) & ~(newAttr IN proc.conval.setval) & (typ.BaseTyp # NIL) DO
(* find base method *)
typ := typ.BaseTyp; CPT.FindField(name, typ, proc);
END;
IF (proc.vis = externalR) & (proc.mnolev < 0) THEN err(196) END;
END ;
IF (obj.typ # CPT.notyp) & (sym # lparen) THEN err(lparen) END
END
ELSE err(53)
END
ELSE err(52)
END
ELSE err(ident)
END
ELSIF sym = arrow THEN CPS.Get(sym); CPB.DeRef(x)
ELSIF sym = dollar THEN
IF x.typ.form = Pointer THEN CPB.DeRef(x) END;
CPS.Get(sym); CPB.StrDeref(x)
ELSIF sym = lparen THEN
IF (x.obj # NIL) & (x.obj.mode IN {XProc, LProc, CProc, TProc}) THEN typ := x.obj.typ
ELSIF x.typ.form = ProcTyp THEN typ := x.typ.BaseTyp
ELSIF x.class = Nproc THEN EXIT (* standard procedure *)
ELSE typ := NIL
END;
IF typ # CPT.notyp THEN
CPS.Get(sym);
IF typ = NIL THEN (* type guard *)
IF sym = ident THEN
qualident(obj);
IF obj.mode = Typ THEN CPB.TypTest(x, obj, TRUE);
UseType(obj, CPM.errpos) (*<< type gets used*)
ELSE err(52)
END
ELSE err(ident)
END
ELSE (* function call *)
pre := NIL; lastp := NIL;
CPB.PrepCall(x, fpar);
IF (x.obj # NIL) & (x.obj.mode = TProc) THEN CPB.CheckBuffering(x.left, NIL, x.obj.link, pre, lastp) END;
ActualParameters(apar, fpar, pre, lastp);
CPB.Call(x, apar, fpar);
IF pre # NIL THEN CPB.Construct(Ncomp, pre, x); pre.typ := x.typ; x := pre END;
IF level > 0 THEN CPT.topScope.link.leaf := FALSE END
END;
CheckSym(rparen)
ELSE EXIT
END
(*
ELSIF (sym = lparen) & (x.class # Nproc) & (x.typ.form # ProcTyp) &
((x.obj = NIL) OR (x.obj.mode # TProc)) THEN
CPS.Get(sym);
IF sym = ident THEN
qualident(obj);
IF obj.mode = Typ THEN CPB.TypTest(x, obj, TRUE)
ELSE err(52)
END
ELSE err(ident)
END ;
CheckSym(rparen)
*)
ELSE EXIT
END
END
END selector;
PROCEDURE StandProcCall(VAR x: CPT.Node);
VAR y: CPT.Node; m: BYTE; n: SHORTINT; id: CPT.Object; (*<< id *)
BEGIN
m := SHORT(SHORT(x.obj.adr)); n := 0;
IF sym = lparen THEN CPS.Get(sym);
IF sym # rparen THEN
LOOP
IF n = 0 THEN
(*<< Expression(x); old code *)
CASE m OF (*<<*)
| newfn, sysnewfn: (* id will be set by NEW => varPar = FALSE *)
qualident(id); x := CPB.NewLeaf(id); selector(x);
IF (x.class = Nproc) & (x.obj.mode = SProc) & (x.obj.adr = valfn) THEN StandProcCall(x) END;
Selector(x, SelAssign, SelNoVarPar, SelUseBSet, CPM.errpos)
| incfn, decfn, inclfn, exclfn: (* id will be used and then set *)
qualident(id); x := CPB.NewLeaf(id); selector(x);
IF (x.class = Nproc) & (x.obj.mode = SProc) & (x.obj.adr = valfn) THEN StandProcCall(x) END;
Selector(x, SelNoAssign, SelNoVarPar, SelUseBSet, CPM.errpos); (* use *)
Selector(x, SelAssign, SelNoVarPar, SelUseBSet, CPM.errpos) (* set *)
| adrfn:
IF sym = ident THEN (* no usedBSet message if ADR(id) *)
qualident(id); x := CPB.NewLeaf(id); selector(x);
Selector(x, SelNoAssign, SelNoVarPar, SelNoUseBSet, CPM.errpos)
ELSE
Expression(x);
END
| lenfn:
qualident(id); x := CPB.NewLeaf(id); selector(x);
(* no usedBSet message if LEN(id) *)
Selector(x, SelNoAssign, SelNoVarPar, SelNoUseBSet, CPM.errpos)
ELSE Expression(x)
END;
CPB.StPar0(x, m); n := 1
ELSIF n = 1 THEN
(*<< Expression(y); old code *)
IF m IN {getfn, getrfn} THEN (*<< id will be set by GET, GETREG => varPar = FALSE *)
qualident(id); y := CPB.NewLeaf(id); selector(y);
IF (y.class = Nproc) & (y.obj.mode = SProc) & (y.obj.adr = valfn) THEN StandProcCall(y) END;
Selector(y, SelAssign, SelNoVarPar, SelUseBSet, CPM.errpos)
ELSE Expression(y)
END;
CPB.StPar1(x, y, m); n := 2
ELSE Expression(y); CPB.StParN(x, y, m, n); INC(n)
END ;
IF sym = comma THEN CPS.Get(sym)
ELSIF (lparen <= sym) & (sym <= ident) THEN err(comma)
ELSE EXIT
END
END ;
CheckSym(rparen)
ELSE CPS.Get(sym)
END ;
CPB.StFct(x, m, n)
ELSE err(lparen)
END ;
IF (level > 0) & ((m = newfn) OR (m = sysnewfn)) THEN CPT.topScope.link.leaf := FALSE END
END StandProcCall;
PROCEDURE Element(VAR x: CPT.Node);
VAR y: CPT.Node;
BEGIN Expression(x);
IF sym = upto THEN
CPS.Get(sym); Expression(y); CPB.SetRange(x, y)
ELSE CPB.SetElem(x)
END
END Element;
PROCEDURE Sets(VAR x: CPT.Node);
VAR y: CPT.Node;
BEGIN
IF sym # rbrace THEN
Element(x);
LOOP
IF sym = comma THEN CPS.Get(sym)
ELSIF (lparen <= sym) & (sym <= ident) THEN err(comma)
ELSE EXIT
END ;
Element(y); CPB.Op(plus, x, y)
END
ELSE x := CPB.EmptySet()
END ;
CheckSym(rbrace)
END Sets;
PROCEDURE Factor(VAR x: CPT.Node);
VAR id: CPT.Object; pos: INTEGER; (*<< pos *)
BEGIN
IF sym < not THEN err(13);
REPEAT CPS.Get(sym) UNTIL sym >= lparen
END ;
IF sym = ident THEN
qualident(id);
pos := CPM.curpos; (*<<*)
x := CPB.NewLeaf(id);
UseObj(x.obj, SelUseBSet, pos);
selector(x);
IF (x.class = Nfield) & (x.obj.mode = TProc) & (x.obj.link.mode = VarPar) & (x.obj.link.typ.comp = Record) THEN
(*<< receiver is var parameter and record *)
Selector(x.left, SelAssign, SelVarPar, SelUseBSet, pos)
END;
Selector(x, SelNoAssign, SelNoVarPar, SelUseBSet, pos); (*<<*)
IF (x.class = Nproc) & (x.obj.mode = SProc) THEN
IF ~((x.obj.adr IN {ordfn, minfn, maxfn, chrfn, sizefn, adrfn, valfn}) OR (x.obj.adr = bitsfn)) THEN
INC(nofStats) (*<<*)
END;
StandProcCall(x) (* x may be NIL *)
(*
ELSIF sym = lparen THEN
CPS.Get(sym); CPB.PrepCall(x, fpar);
ActualParameters(apar, fpar);
INC(nofStats); (*<<*)
CPB.Call(x, apar, fpar);
CheckSym(rparen);
IF level > 0 THEN CPT.topScope.link.leaf := FALSE END
ELSIF id.mode = Typ THEN UseType(id, CPM.errpos) (*<< type gets used, e.g. SIZE(Node) *)
*)
END;
ELSIF sym = number THEN
CASE CPS.numtyp OF
char:
x := CPB.NewIntConst(CPS.intval); x.typ := CPT.char8typ;
IF CPS.intval > 255 THEN x.typ := CPT.char16typ END
| integer: x := CPB.NewIntConst(CPS.intval)
| int64: x := CPB.NewLargeIntConst(CPS.intval, CPS.realval)
| real: x := CPB.NewRealConst(CPS.realval, NIL)
| real32: x := CPB.NewRealConst(CPS.realval, CPT.real32typ)
| real64: x := CPB.NewRealConst(CPS.realval, CPT.real64typ)
END ;
CPS.Get(sym)
ELSIF sym = string THEN
x := CPB.NewString(CPS.str, CPS.lstr, CPS.intval);
CPS.Get(sym)
ELSIF sym = nil THEN
x := CPB.Nil(); CPS.Get(sym)
ELSIF sym = lparen THEN
CPS.Get(sym); Expression(x); CheckSym(rparen)
ELSIF sym = lbrak THEN
CPS.Get(sym); err(lparen); Expression(x); CheckSym(rparen)
ELSIF sym = lbrace THEN CPS.Get(sym); Sets(x)
ELSIF sym = not THEN
CPS.Get(sym); Factor(x); CPB.MOp(not, x)
ELSE err(13); CPS.Get(sym); x := NIL
END ;
IF x = NIL THEN x := CPB.NewIntConst(1); x.typ := CPT.undftyp END
END Factor;
PROCEDURE Term(VAR x: CPT.Node);
VAR y: CPT.Node; mulop: BYTE;
BEGIN Factor(x);
WHILE (times <= sym) & (sym <= and) DO
mulop := sym; CPS.Get(sym);
Factor(y); CPB.Op(mulop, x, y)
END
END Term;
PROCEDURE SimpleExpression(VAR x: CPT.Node);
VAR y: CPT.Node; addop: BYTE;
BEGIN
IF sym = minus THEN CPS.Get(sym); Term(x); CPB.MOp(minus, x)
ELSIF sym = plus THEN CPS.Get(sym); Term(x); CPB.MOp(plus, x)
ELSE Term(x)
END ;
WHILE (plus <= sym) & (sym <= or) DO
addop := sym; CPS.Get(sym); Term(y);
IF x.typ.form = Pointer THEN CPB.DeRef(x) END;
IF (x.typ.comp IN {Array, DynArr}) & (x.typ.BaseTyp.form IN charSet) THEN CPB.StrDeref(x) END;
IF y.typ.form = Pointer THEN CPB.DeRef(y) END;
IF (y.typ.comp IN {Array, DynArr}) & (y.typ.BaseTyp.form IN charSet) THEN CPB.StrDeref(y) END;
CPB.Op(addop, x, y)
END
END SimpleExpression;
PROCEDURE Expression(VAR x: CPT.Node);
VAR y, pre, last: CPT.Node; obj: CPT.Object; relation: BYTE;
BEGIN SimpleExpression(x);
IF (eql <= sym) & (sym <= geq) THEN
relation := sym; CPS.Get(sym); SimpleExpression(y);
pre := NIL; last := NIL;
IF (x.typ.comp IN {Array, DynArr}) & (x.typ.BaseTyp.form IN charSet) THEN CPB.StrDeref(x) END;
IF (y.typ.comp IN {Array, DynArr}) & (y.typ.BaseTyp.form IN charSet) THEN CPB.StrDeref(y) END;
CPB.CheckBuffering(x, NIL, NIL, pre, last);
CPB.CheckBuffering(y, NIL, NIL, pre, last);
CPB.Op(relation, x, y);
IF pre # NIL THEN CPB.Construct(Ncomp, pre, x); pre.typ := x.typ; x := pre END;
ELSIF sym = in THEN
CPS.Get(sym); SimpleExpression(y); CPB.In(x, y)
ELSIF sym = is THEN
CPS.Get(sym);
IF sym = ident THEN
qualident(obj);
UseType(obj, CPM.errpos); (*<< type gets used*)
IF obj.mode = Typ THEN CPB.TypTest(x, obj, FALSE)
ELSE err(52)
END
ELSE err(ident)
END
END
END Expression;
PROCEDURE ProcedureDeclaration(VAR x: CPT.Node);
VAR proc, fwd: CPT.Object;
name: CPT.Name;
mode: BYTE;
forward: BOOLEAN;
sys: SHORTINT;
pos: INTEGER; (*<< *)
PROCEDURE GetCode;
VAR ext: CPT.ConstExt; i, n, c: INTEGER; s, s2: POINTER TO ARRAY OF SHORTCHAR;
BEGIN
n := 0; NEW(s, 256);
LOOP
IF sym = number THEN c := CPS.intval; INC(n); i := LEN(s^);
IF n > i THEN (* if overflow then increase size of array s *)
NEW(s2, i * 2); WHILE i > 0 DO DEC(i); s2[i] := s[i] END; s := s2; s2 := NIL;
END;
IF (c < 0) OR (c > 255) OR (n = MAX(INTEGER)) THEN
err(63); c := 1; n := 1
END ;
CPS.Get(sym); s[n - 1] := SHORT(CHR(c))
END ;
IF sym = comma THEN CPS.Get(sym)
ELSIF sym = number THEN err(comma)
ELSE EXIT
END
END;
IF n # 0 THEN NEW(ext, n); i := 0;
WHILE i < n DO ext[i] := s[i]; INC(i) END
ELSE ext := NIL
END;
proc.conval.ext := ext;
INCL(proc.conval.setval, hasBody)
END GetCode;
PROCEDURE GetParams;
VAR name: CPT.String;
BEGIN
proc.mode := mode; proc.typ := CPT.notyp;
proc.sysflag := SHORT(sys);
proc.conval.setval := {};
IF sym = lparen THEN
CPS.Get(sym); FormalParameters(proc.link, proc.typ, name);
IF name # NIL THEN err(0) END
END;
CheckForwardTypes; userList := NIL;
IF fwd # NIL THEN
CPB.CheckParameters(proc.link, fwd.link, TRUE);
IF ~CPT.EqualType(proc.typ, fwd.typ) THEN err(117) END ;
proc := fwd; CPT.topScope := proc.scope;
IF mode = IProc THEN proc.mode := IProc END
END
END GetParams;
PROCEDURE Body;
VAR procdec, statseq: CPT.Node; c: INTEGER;
BEGIN
c := CPM.errpos;
INCL(proc.conval.setval, hasBody);
CheckSym(semicolon); Block(procdec, statseq);
CPB.Enter(procdec, statseq, proc); x := procdec;
x.conval := CPT.NewConst(); x.conval.intval := c; x.conval.intval2 := CPM.startpos;
CheckSym(end);
IF sym = ident THEN
IF CPS.name # proc.name^ THEN err(4) END ;
CPS.Get(sym)
ELSE err(ident)
END
END Body;
PROCEDURE TProcDecl;
VAR baseProc, o: CPT.Object;
objTyp, recTyp: CPT.Struct;
objMode, objVis: BYTE;
objName: CPT.Name;
pnode: CPT.Node;
pos1, pos2: INTEGER; (*<<*)
BEGIN
CPS.Get(sym); mode := TProc;
IF level > 0 THEN err(73) END;
pos1 := CPM.errpos; (*<<*)
Receiver(objMode, objVis, objName, objTyp, recTyp);
IF sym = ident THEN
name := CPS.name;
CPT.FindField(name, recTyp, fwd);
CPT.FindBaseField(name, recTyp, baseProc);
IF (baseProc # NIL) & (baseProc.mode # TProc) THEN baseProc := NIL END ;
IF fwd = baseProc THEN fwd := NIL END ;
IF (fwd # NIL) & (fwd.mnolev # level) THEN fwd := NIL END ;
IF (fwd # NIL) & (fwd.mode = TProc) & (fwd.conval.setval * {hasBody, absAttr, empAttr} = {}) THEN
(* there exists a corresponding forward declaration *)
proc := CPT.NewObj(); proc.leaf := TRUE;
proc.mode := TProc; proc.conval := CPT.NewConst();
CheckMark(proc);
IF fwd.vis # proc.vis THEN err(118) END
ELSE
IF fwd # NIL THEN err(1); fwd := NIL END ;
CPT.InsertField(name, recTyp, proc);
proc.mode := TProc; proc.conval := CPT.NewConst();
CheckMark(proc);
IF recTyp.strobj # NIL THEN (* preserve declaration order *)
o := recTyp.strobj.link;
IF o = NIL THEN recTyp.strobj.link := proc
ELSE
WHILE o.nlink # NIL DO o := o.nlink END;
o.nlink := proc
END
END
END;
pos2 := CPM.errpos; proc.num := set; (*<< methods are set*)
INC(level); CPT.OpenScope(level, proc);
CPT.Insert(objName, proc.link); proc.link.mode := objMode; proc.link.vis := objVis; proc.link.typ := objTyp;
proc^.link.adr := pos1; (*<< *)
(*
(*<< receiver is set/setUsed *)
IF objMode = VarPar THEN proc^.link.num := setUsed ELSE proc^.link.num := set END;
*)
proc.link.num := setUsed; (* BJ: No point in warning about recievers. (commented out the line above...)*)
ASSERT(CPT.topScope # NIL);
GetParams;
ASSERT(CPT.topScope # NIL);
GetAttributes(proc, baseProc, recTyp);
IF ((absAttr IN proc.conval.setval) OR (empAttr IN proc.conval.setval)) & (proc.link.link # NIL) THEN
o := proc.link.link;
WHILE o # NIL DO o.num := setUsed; o := o.link END;
END;
IF (fwd # NIL) & (fwd.conval.setval / proc.conval.setval * {absAttr, empAttr, extAttr} # {}) THEN err(184) END;
CheckOverwrite(proc, baseProc, recTyp);
IF ~forward THEN
IF empAttr IN proc.conval.setval THEN (* insert empty procedure *)
pnode := NIL; CPB.Enter(pnode, NIL, proc);
pnode.conval := CPT.NewConst();
pnode.conval.intval := CPM.errpos;
pnode.conval.intval2 := CPM.errpos;
x := pnode
ELSIF ~(absAttr IN proc.conval.setval) THEN Body
END;
proc.adr := 0
ELSE proc.adr := CPM.errpos
END;
proc.adr := pos2; (*<< *)
DEC(level); CPT.CloseScope
ELSE err(ident)
END
END TProcDecl;
BEGIN proc := NIL; forward := FALSE; x := NIL; mode := LProc; sys := 0;
IF (sym # ident) & (sym # lparen) THEN
CheckSysFlag(sys, CPM.GetProcSysFlag);
IF sys # 0 THEN
(*
IF ~CPT.SYSimported THEN err(135) END;
*)
IF sys = CPM.CProcFlag THEN mode := CProc END
ELSE
IF sym = times THEN (* mode set later in CPB.CheckAssign *)
ELSIF sym = arrow THEN forward := TRUE
ELSE err(ident)
END;
CPS.Get(sym)
END
END ;
IF sym = lparen THEN TProcDecl
ELSIF sym = ident THEN CPT.Find(CPS.name, fwd);
name := CPS.name;
IF (fwd # NIL) & ((fwd.mnolev # level) OR (fwd.mode = SProc)) THEN fwd := NIL END ;
IF (fwd # NIL) & (fwd.mode IN {LProc, XProc}) & ~(hasBody IN fwd.conval.setval) THEN
(* there exists a corresponding forward declaration *)
proc := CPT.NewObj(); proc.leaf := TRUE;
proc.mode := mode; proc.conval := CPT.NewConst();
CheckMark(proc);
IF fwd.vis # proc.vis THEN err(118) END
ELSE
IF fwd # NIL THEN err(1); fwd := NIL END ;
CheckOuter; (*<<*)
CPT.Insert(name, proc);
proc.mode := mode; proc.conval := CPT.NewConst();
CheckMark(proc)
END ;
pos := CPM.errpos; proc.num := set; (*<< procedures are set *)
IF (proc.vis # internal) & (mode = LProc) THEN mode := XProc END ;
IF (mode # LProc) & (level > 0) THEN err(73) END ;
INC(level); CPT.OpenScope(level, proc);
proc.link := NIL; GetParams;
IF mode = CProc THEN GetCode
ELSIF CPM.interface IN CPM.options THEN INCL(proc.conval.setval, hasBody)
ELSIF ~forward THEN Body; proc.adr := 0
ELSE proc.adr := CPM.errpos
END ;
proc.adr := pos; (*<< *)
DEC(level); CPT.CloseScope
ELSE err(ident)
END
END ProcedureDeclaration;
PROCEDURE CaseLabelList(VAR lab, root: CPT.Node; LabelForm: SHORTINT; VAR min, max: INTEGER);
VAR x, y: CPT.Node; f: SHORTINT; xval, yval: INTEGER;
PROCEDURE Insert(VAR n: CPT.Node); (* build binary tree of label ranges *) (* !!! *)
BEGIN
IF n = NIL THEN
IF x.hint # 1 THEN n := x END
ELSIF yval < n.conval.intval THEN Insert(n.left)
ELSIF xval > n.conval.intval2 THEN Insert(n.right)
ELSE err(63)
END
END Insert;
BEGIN lab := NIL;
LOOP ConstExpression(x); f := x.typ.form;
IF f IN intSet + charSet THEN xval := x.conval.intval
ELSE err(61); xval := 1
END ;
IF (f IN intSet) # (LabelForm IN intSet) THEN err(60) END;
IF sym = upto THEN
CPS.Get(sym); ConstExpression(y); yval := y.conval.intval;
IF (y.typ.form IN intSet) # (LabelForm IN intSet) THEN err(60) END;
IF yval < xval THEN err(63); yval := xval END
ELSE yval := xval
END ;
x.conval.intval2 := yval;
IF xval < min THEN min := xval END;
IF yval > max THEN max := yval END;
IF lab = NIL THEN lab := x; Insert(root)
ELSIF yval < lab.conval.intval - 1 THEN x.link := lab; lab := x; Insert(root)
ELSIF yval = lab.conval.intval - 1 THEN x.hint := 1; Insert(root); lab.conval.intval := xval
ELSIF xval = lab.conval.intval2 + 1 THEN x.hint := 1; Insert(root); lab.conval.intval2 := yval
ELSE
y := lab;
WHILE (y.link # NIL) & (xval > y.link.conval.intval2 + 1) DO y := y.link END;
IF y.link = NIL THEN y.link := x; Insert(root)
ELSIF yval < y.link.conval.intval - 1 THEN x.link := y.link; y.link := x; Insert(root)
ELSIF yval = y.link.conval.intval - 1 THEN x.hint := 1; Insert(root); y.link.conval.intval := xval
ELSIF xval = y.link.conval.intval2 + 1 THEN x.hint := 1; Insert(root); y.link.conval.intval2 := yval
END
END;
IF sym = comma THEN CPS.Get(sym)
ELSIF (sym = number) OR (sym = ident) THEN err(comma)
ELSE EXIT
END
END
END CaseLabelList;
PROCEDURE Evaluate (n: CPT.Node; VAR min, max, num, dist: INTEGER; VAR head: CPT.Node);
VAR a: INTEGER;
BEGIN
a := MIN(INTEGER);
IF n.left # NIL THEN
a := MIN(INTEGER); Evaluate(n.left, min, a, num, dist, head);
IF n.conval.intval - a > dist THEN dist := n.conval.intval - a; head := n END
ELSIF n.conval.intval < min THEN
min := n.conval.intval
END;
IF n.right # NIL THEN
a := MAX(INTEGER); Evaluate(n.right, a, max, num, dist, head);
IF a - n.conval.intval2 > dist THEN dist := a - n.conval.intval2; head := n END
ELSIF n.conval.intval2 > max THEN
max := n.conval.intval2
END;
INC(num);
IF n.conval.intval < n.conval.intval2 THEN
INC(num);
IF n.conval.intval2 - n.conval.intval > dist THEN dist := n.conval.intval2 - n.conval.intval; head := n END
END
END Evaluate;
PROCEDURE Rebuild (VAR root: CPT.Node; head: CPT.Node);
VAR n: CPT.Node;
BEGIN
IF root # head THEN
IF head.conval.intval2 < root.conval.intval THEN
Rebuild(root.left, head);
n := head; WHILE n.right # NIL DO n := n.right END;
n.right := root; root.left := NIL; root := head
ELSE
Rebuild(root.right, head);
n := head; WHILE n.left # NIL DO n := n.left END;
n.left := root; root.right := NIL; root := head
END
END
END Rebuild;
PROCEDURE Optimize (VAR n: CPT.Node);
VAR min, max, num, dist, limit: INTEGER; head: CPT.Node;
BEGIN
IF n # NIL THEN
min := MAX(INTEGER); max := MIN(INTEGER); num := 0; dist := 0; head := n;
Evaluate(n, min, max, num, dist, head);
limit := 6 * num;
IF limit < 100 THEN limit := 100 END;
IF (num > 4) & ((min > MAX(INTEGER) - limit) OR (max < min + limit)) THEN
INCL(n.conval.setval, useTable)
ELSE
IF num > 4 THEN Rebuild(n, head) END;
INCL(n.conval.setval, useTree);
Optimize(n.left);
Optimize(n.right)
END
END
END Optimize;
(*
PROCEDURE ShowTree (n: CPT.Node; opts: SET);
BEGIN
IF n # NIL THEN
IF opts = {} THEN opts := n.conval.setval END;
IF useTable IN opts THEN
IF n.left # NIL THEN ShowTree(n.left, opts); CPM.LogW(",") END;
CPM.LogWNum(n.conval.intval, 1);
IF n.conval.intval2 > n.conval.intval THEN CPM.LogW("-"); CPM.LogWNum(n.conval.intval2, 1) END;
IF n.right # NIL THEN CPM.LogW(","); ShowTree(n.right, opts) END
ELSIF useTree IN opts THEN
CPM.LogW("("); ShowTree(n.left, {}); CPM.LogW("|"); CPM.LogWNum(n.conval.intval, 1);
IF n.conval.intval2 > n.conval.intval THEN CPM.LogW("-"); CPM.LogWNum(n.conval.intval2, 1) END;
CPM.LogW("|"); ShowTree(n.right, {}); CPM.LogW(")")
ELSE
ShowTree(n.left, opts); CPM.LogW(" "); CPM.LogWNum(n.conval.intval, 1);
IF n.conval.intval2 > n.conval.intval THEN CPM.LogW("-"); CPM.LogWNum(n.conval.intval2, 1) END;
CPM.LogW(" "); ShowTree(n.right, opts)
END
END
END ShowTree;
*)
PROCEDURE StatSeq(VAR stat: CPT.Node);
VAR fpar, id, t: CPT.Object; idtyp: CPT.Struct; e: BOOLEAN; oldSym: BYTE; (*<< oldSym*)
s, x, y, z, apar, last, lastif, pre, lastp: CPT.Node; pos, p: INTEGER; pos1, lastSemiPos: INTEGER;
(*<< pos1, pos2, oldPos *)
lastSemi: BOOLEAN; (*<<*)
PROCEDURE CasePart(VAR x: CPT.Node);
VAR low, high: INTEGER; e: BOOLEAN; cases, lab, y, lastcase, root: CPT.Node;
BEGIN
Expression(x);
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF x.typ.form = Int64 THEN err(260)
ELSIF ~(x.typ.form IN intSet + charSet) THEN err(125)
END ;
CheckSym(of); cases := NIL; lastcase := NIL; root := NIL;
low := MAX(INTEGER); high := MIN(INTEGER);
LOOP
IF sym < bar THEN
CaseLabelList(lab, root, x.typ.form, low, high);
CheckSym(colon); StatSeq(y);
CPB.Construct(Ncasedo, lab, y); CPB.Link(cases, lastcase, lab)
END ;
IF sym = bar THEN CPS.Get(sym) ELSE EXIT END
END;
e := sym = else;
IF e THEN CPS.Get(sym); StatSeq(y) ELSE y := NIL END ;
CPB.Construct(Ncaselse, cases, y); CPB.Construct(Ncase, x, cases);
cases.conval := CPT.NewConst();
cases.conval.intval := low; cases.conval.intval2 := high;
IF e THEN cases.conval.setval := {1} ELSE cases.conval.setval := {} END;
Optimize(root); cases.link := root (* !!! *)
END CasePart;
PROCEDURE SetPos(x: CPT.Node);
BEGIN
x.conval := CPT.NewConst(); x.conval.intval := pos
END SetPos;
PROCEDURE CheckBool(VAR x: CPT.Node);
BEGIN
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126); x := CPB.NewBoolConst(FALSE)
ELSIF x.typ.form # Bool THEN err(120); x := CPB.NewBoolConst(FALSE)
END
END CheckBool;
BEGIN stat := NIL; last := NIL;
lastSemi := FALSE; lastSemiPos := 0; (*<<*)
LOOP x := NIL;
IF sym < ident THEN err(14);
REPEAT CPS.Get(sym) UNTIL sym >= ident
END ;
INC(nofStats); oldSym := null; (*<<*)
pos := CPM.startpos;
IF sym = ident THEN
pos1 := CPM.curpos; (*<<*)
qualident(id); x := CPB.NewLeaf(id); selector(x);
IF sym = becomes THEN
(*<<
pos2 := CPM.curpos; (*<<*)
*)
CPS.Get(sym); Expression(y);
Selector(x, SelAssign, SelNoVarPar, SelUseBSet, pos1); (*<< id gets set for the first time *)
IF (y.typ.form = Pointer) & (x.typ.form = Comp) THEN CPB.DeRef(y) END;
pre := NIL; lastp := NIL;
CPB.CheckBuffering(y, x, NIL, pre, lastp);
CPB.Assign(x, y);
(*<< fixed in CP
IF (x.left.class = Neguard) & (x.right.typ.comp = Record) THEN (*<< record assignment to varpar *)
err2(impliedTypeGuard, pos2)
END;
*)
IF pre # NIL THEN SetPos(x); CPB.Construct(Ncomp, pre, x); x := pre END
ELSIF sym = eql THEN
err(becomes); CPS.Get(sym); Expression(y); CPB.Assign(x, y)
ELSIF (x.class = Nproc) & (x.obj.mode = SProc) THEN
StandProcCall(x);
IF (x # NIL) & (x.typ # CPT.notyp) THEN err(55) END;
IF (x # NIL) & (x.class = Nifelse) THEN (* error pos for ASSERT *)
SetPos(x.left); SetPos(x.left.right)
END;
ELSIF x.class = Ncall THEN err(55)
ELSE
pre := NIL; lastp := NIL;
IF (x.class = Nfield) & (x.obj.mode = TProc)
& (x.obj.link.mode = VarPar) & (x.obj.link.typ.comp = Record) THEN
Selector(x.left, SelAssign, SelVarPar, SelUseBSet, pos1) (*<< receiver is var parameter and record *)
END;
Selector(x, SelNoAssign, SelNoVarPar, SelUseBSet, pos1); (*<< proc in node x gets called *)
CPB.PrepCall(x, fpar);
IF (x.obj # NIL) & (x.obj.mode = TProc) THEN CPB.CheckBuffering(x.left, NIL, x.obj.link, pre, lastp) END;
IF sym = lparen THEN
CPS.Get(sym); ActualParameters(apar, fpar, pre, lastp); CheckSym(rparen)
ELSE apar := NIL;
IF fpar # NIL THEN err(65) END
END ;
CPB.Call(x, apar, fpar);
IF x.typ # CPT.notyp THEN err(55) END;
IF pre # NIL THEN SetPos(x); CPB.Construct(Ncomp, pre, x); x := pre END;
IF level > 0 THEN CPT.topScope.link.leaf := FALSE END
END
ELSIF sym = if THEN
CPS.Get(sym); pos := CPM.startpos; Expression(x); CheckBool(x); CheckSym(then); StatSeq(y);
CPB.Construct(Nif, x, y); SetPos(x); lastif := x;
WHILE sym = elsif DO
CPS.Get(sym); pos := CPM.startpos; Expression(y); CheckBool(y); CheckSym(then); StatSeq(z);
CPB.Construct(Nif, y, z); SetPos(y); CPB.Link(x, lastif, y)
END ;
pos := CPM.startpos;
IF sym = else THEN CPS.Get(sym); StatSeq(y) ELSE y := NIL END ;
CPB.Construct(Nifelse, x, y); CheckSym(end); CPB.OptIf(x)
ELSIF sym = case THEN
CPS.Get(sym); pos := CPM.startpos; CasePart(x); CheckSym(end)
ELSIF sym = while THEN
CPS.Get(sym); pos := CPM.startpos; Expression(x); CheckBool(x); CheckSym(do); StatSeq(y);
CPB.Construct(Nwhile, x, y); CheckSym(end)
ELSIF sym = repeat THEN
CPS.Get(sym); StatSeq(x);
IF sym = until THEN CPS.Get(sym); pos := CPM.startpos; Expression(y); CheckBool(y)
ELSE err(43)
END ;
CPB.Construct(Nrepeat, x, y)
ELSIF sym = for THEN
CPS.Get(sym); pos := CPM.startpos;
IF sym = ident THEN qualident(id);
SetObj(id, FALSE, CPM.errpos); UseObj(id, TRUE, CPM.errpos); (*<< for variable gets set & used*)
INC(id.num, noChange); (*<< loop variable shouldn't be changed!*)
IF ~(id.typ.form IN intSet) THEN err(68) END ;
CheckSym(becomes); Expression(y);
x := CPB.NewLeaf(id); CPB.Assign(x, y); SetPos(x);
CheckSym(to); pos := CPM.startpos; Expression(y);
IF y.class # Nconst THEN
CPB.GetTempVar("@for", x.left.typ, t);
t.num := setUsed; (*<< temporary var gets set and used*)
z := CPB.NewLeaf(t); CPB.Assign(z, y); SetPos(z); CPB.Link(stat, last, z);
y := CPB.NewLeaf(t)
ELSE
CPB.CheckAssign(x.left.typ, y)
END ;
CPB.Link(stat, last, x);
p := CPM.startpos;
IF sym = by THEN CPS.Get(sym); ConstExpression(z) ELSE z := CPB.NewIntConst(1) END ;
x := CPB.NewLeaf(id);
IF z.conval.intval > 0 THEN CPB.Op(leq, x, y)
ELSIF z.conval.intval < 0 THEN CPB.Op(geq, x, y)
ELSE err(63); CPB.Op(geq, x, y)
END ;
CheckSym(do); StatSeq(s);
y := CPB.NewLeaf(id); CPB.StPar1(y, z, incfn); pos := CPM.startpos; SetPos(y);
IF s = NIL THEN s := y
ELSE z := s;
WHILE z.link # NIL DO z := z.link END ;
z.link := y
END ;
CheckSym(end); CPB.Construct(Nwhile, x, s); pos := p;
DEC(id.num, noChange) (*<< reset noChange attribute for loopvariable*)
ELSE err(ident)
END
ELSIF sym = loop THEN
CPS.Get(sym); INC(LoopLevel); StatSeq(x); DEC(LoopLevel);
CPB.Construct(Nloop, x, NIL); CheckSym(end)
ELSIF sym = with THEN
CPS.Get(sym); idtyp := NIL; x := NIL;
LOOP
IF sym < bar THEN (* bj: added to be compliant with DevCPP.StatSeq *)
pos := CPM.startpos;
IF sym = ident THEN
qualident(id);
UseObj(id, TRUE, CPM.errpos); (*<<*)
y := CPB.NewLeaf(id);
IF (id # NIL) & (id.typ.form = Pointer) & ((id.mode = VarPar) OR ~id.leaf) THEN
err(-302) (* warning 302 *)
END ;
CheckSym(colon);
IF sym = ident THEN qualident(t);
UseType(t, CPM.errpos); (*<< type gets used*)
IF t.mode = Typ THEN
IF id # NIL THEN
idtyp := id.typ; CPB.TypTest(y, t, FALSE); id.typ := t.typ;
IF id.ptyp = NIL THEN id.ptyp := idtyp END
ELSE err(130)
END
ELSE err(52)
END
ELSE err(ident)
END
ELSE err(ident)
END ;
pos1 := CPM.errpos; (* << *)
CheckSym(do); StatSeq(s); CPB.Construct(Nif, y, s); SetPos(y);
IF idtyp # NIL THEN
IF id.ptyp = idtyp THEN id.ptyp := NIL END;
id.typ := idtyp; idtyp := NIL
END ;
IF x = NIL THEN x := y; lastif := x ELSE CPB.Link(x, lastif, y) END
END;
IF sym = bar THEN CPS.Get(sym) ELSE EXIT END
END;
e := sym = else; pos := CPM.startpos;
IF e THEN CPS.Get(sym); StatSeq(s) ELSE s := NIL END ;
CPB.Construct(Nwith, x, s); CheckSym(end);
IF e THEN x.subcl := 1 END
ELSIF sym = exit THEN
CPS.Get(sym);
IF LoopLevel = 0 THEN err(46) END ;
CPB.Construct(Nexit, x, NIL);
oldSym := exit (*<<*)
ELSIF sym = return THEN CPS.Get(sym);
IF sym < semicolon THEN Expression(x) END ;
IF level > 0 THEN CPB.Return(x, CPT.topScope.link)
ELSE (* not standard Oberon *) CPB.Return(x, NIL)
END;
hasReturn := TRUE;
oldSym := return (*<<*)
ELSE (*<< empty statement*)
IF options.semicolons THEN
IF sym = semicolon THEN err2(semicolons, CPM.errpos)
ELSIF lastSemi THEN err2(semicolons, lastSemiPos)
END
END;
DEC(nofStats)
END ;
IF x # NIL THEN SetPos(x); CPB.Link(stat, last, x) END ;
IF sym = semicolon THEN (*<<*)
lastSemi := TRUE; lastSemiPos := CPM.errpos
ELSE lastSemi := FALSE (*<<*)
END;
IF sym = semicolon THEN CPS.Get(sym)
ELSIF (sym <= ident) OR (if <= sym) & (sym <= return) THEN err(semicolon)
ELSE EXIT
END;
IF (exit <= oldSym) & (oldSym <= return) & ((sym < bar) OR (until < sym)) THEN (*<< statement after return/exit*)
err2(statAfterRetEx, CPM.errpos)
END
END
END StatSeq;
PROCEDURE Block(VAR procdec, statseq: CPT.Node);
VAR typ: CPT.Struct;
obj, first, last, o: CPT.Object;
x, lastdec: CPT.Node;
i: SHORTINT;
rname: CPT.Name;
name: CPT.String;
rec: Elem;
pos, save: INTEGER; (*<<*)
BEGIN
first := NIL; last := NIL; userList := NIL; recList := NIL;
save := nofStats; (*<<*)
LOOP
IF sym = const THEN
CPS.Get(sym);
WHILE sym = ident DO
CheckOuter; (*<<*)
CPT.Insert(CPS.name, obj);
obj.mode := Con; CheckMark(obj);
obj.typ := CPT.int8typ; obj.mode := Var; (* Var to avoid recursive definition *)
pos := CPM.errpos; (*<<*)
IF sym = eql THEN
CPS.Get(sym); ConstExpression(x)
ELSIF sym = becomes THEN
err(eql); CPS.Get(sym); ConstExpression(x)
ELSE err(eql); x := CPB.NewIntConst(1)
END ;
obj.mode := Con; obj.typ := x.typ; obj.conval := x.conval; (* ConstDesc ist not copied *)
obj.adr := pos; obj.num := set; (*<< constants are set by default*)
CheckSym(semicolon)
END
END ;
IF sym = type THEN
CPS.Get(sym);
WHILE sym = ident DO
CheckOuter; (*<<*)
CPT.Find(CPS.name, obj); (* could have been used as a forward type definition *)
IF obj = NIL THEN CPT.Insert(CPS.name, obj) END;
obj.mode := -1; obj.typ := CPT.undftyp;
CheckMark(obj);
obj.adr := CPM.errpos;
IF obj.num > clean THEN obj.num := setUsed ELSE obj.num := set END; (*<< types are set by default*)
IF sym # eql THEN err(eql) END;
IF (sym = eql) OR (sym = becomes) OR (sym = colon) THEN
CPS.Get(sym); Type(obj.typ, name); SetType(NIL, obj, obj.typ, name)
END;
obj.mode := Typ;
IF obj.typ.form IN {Byte..Set, Char16, Int64} THEN (* make alias structure *)
typ := CPT.NewStr(obj.typ.form, Basic); i := typ.ref;
typ^ := obj.typ^; typ.ref := i; typ.strobj := NIL; typ.mno := 0;
typ.BaseTyp := obj.typ; obj.typ := typ
END;
IF obj.typ.strobj = NIL THEN obj.typ.strobj := obj END ;
IF obj.typ.form = Pointer THEN (* !!! *)
typ := obj.typ.BaseTyp;
IF (typ # NIL) & (typ.comp = Record) & (typ.strobj = NIL) THEN
(* pointer to unnamed record: name record as "pointerName^" *)
rname := obj.name$; i := 0;
WHILE rname[i] # 0X DO INC(i) END;
rname[i] := "^"; rname[i+1] := 0X;
CPT.Insert(rname, o); o.mode := Typ; o.typ := typ; typ.strobj := o;
o.adr := CPM.errpos; o.num := setUsed (*<< anonymous record types are set and used by default*)
END
END;
IF obj.vis # internal THEN
typ := obj.typ;
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
IF typ.comp = Record THEN typ.exp := TRUE END
END;
CheckSym(semicolon)
END
END ;
IF sym = var THEN
CPS.Get(sym);
WHILE sym = ident DO
LOOP
IF sym = ident THEN
CheckOuter; (*<<*)
CPT.Insert(CPS.name, obj);
obj.mode := Var; obj.link := NIL; obj.leaf := obj.vis = internal; obj.typ := CPT.undftyp;
CheckMark(obj);
obj.adr := CPM.errpos; obj.num := clean; (*<<*)
IF first = NIL THEN first := obj END ;
IF last = NIL THEN CPT.topScope.scope := obj ELSE last.link := obj END;
last := obj
ELSE err(ident)
END;
IF sym = comma THEN CPS.Get(sym)
ELSIF sym = ident THEN err(comma);
ELSE EXIT
END
END ;
CheckSym(colon); Type(typ, name);
CheckAlloc(typ, FALSE, CPM.errpos);
WHILE first # NIL DO SetType(NIL, first, typ, name); first := first.link END ;
CheckSym(semicolon)
END
END ;
IF (sym < const) OR (sym > var) THEN EXIT END
END ;
nofStats := save; (*<<*)
CheckForwardTypes;
userList := NIL; rec := recList; recList := NIL;
CPT.topScope.adr := CPM.errpos;
procdec := NIL; lastdec := NIL;
WHILE sym = procedure DO
CPS.Get(sym); ProcedureDeclaration(x);
IF x # NIL THEN
IF lastdec = NIL THEN procdec := x ELSE lastdec.link := x END ;
lastdec := x
END ;
CheckSym(semicolon)
END ;
IF CPM.noerr & ~(CPM.oberon IN CPM.options) THEN CheckRecords(rec) END;
hasReturn := FALSE;
IF sym = begin THEN CPS.Get(sym); StatSeq(statseq)
ELSE statseq := NIL
END ;
IF (CPT.topScope.link # NIL) & (CPT.topScope.link.typ # CPT.notyp)
& ~hasReturn & (CPT.topScope.link.sysflag = 0) THEN err(133) END;
IF (level = 0) & (TDinit # NIL) THEN
lastTDinit.link := statseq; statseq := TDinit
END
END Block;
PROCEDURE Module*(VAR prog: CPT.Node);
VAR impName, aliasName: CPT.Name; obj: CPT.Object; (*<< obj *)
procdec, statseq: CPT.Node;
c: INTEGER; done: BOOLEAN;
BEGIN
CPS.Init; LoopLevel := 0; level := 0; CPS.Get(sym);
NEW(errHead); nofStats := 0; (*<<*)
IF sym = module THEN CPS.Get(sym) ELSE err(16) END ;
IF sym = ident THEN
CPT.Open(CPS.name); CPS.Get(sym);
CPT.libName := "";
IF sym = lbrak THEN
INCL(CPM.options, CPM.interface); CPS.Get(sym);
IF sym = string THEN CPT.libName := CPS.str$; CPS.Get(sym)
ELSE err(string)
END;
CheckSym(rbrak)
END;
CheckSym(semicolon);
IF sym = import THEN CPS.Get(sym);
INCL(CPM.options, CPM.comAware); (* BJ: to avoid error when importing COM *)
LOOP
IF sym = ident THEN
aliasName := CPS.name$; impName := aliasName$; CPS.Get(sym);
IF sym = becomes THEN CPS.Get(sym);
IF sym = ident THEN impName := CPS.name$; CPS.Get(sym) ELSE err(ident) END
END ;
CPT.Import(aliasName, impName, done);
CPS.name := aliasName$; (*<<*)
CPT.Find(CPS.name, obj);
IF obj # NIL THEN obj.adr := CPM.errpos; obj.num := set END (*<< modules are set by default *)
ELSE err(ident)
END ;
IF sym = comma THEN CPS.Get(sym)
ELSIF sym = ident THEN err(comma)
ELSE EXIT
END
END ;
CheckSym(semicolon)
END ;
IF CPM.noerr THEN
TDinit := NIL; lastTDinit := NIL; c := CPM.errpos;
Block(procdec, statseq); CPB.Enter(procdec, statseq, NIL); prog := procdec;
prog.conval := CPT.NewConst(); prog.conval.intval := c; prog.conval.intval2 := CPM.startpos;
IF sym = close THEN CPS.Get(sym); StatSeq(prog.link) END;
prog.conval.realval := CPM.startpos;
CheckSym(end);
IF sym = ident THEN
IF CPS.name # CPT.SelfName THEN err(4) END ;
CPS.Get(sym)
ELSE err(ident)
END;
IF sym # period THEN err(period) END;
CheckScope(CPT.topScope) (*<<*)
END
ELSE err(ident)
END ;
TDinit := NIL; lastTDinit := NIL
END Module;
PROCEDURE WriteWarnings(text: TextModels.Model; VAR warning: BOOLEAN); (*<<O/F*)
VAR e: Warning; inserted: SHORTINT;
BEGIN
IF errHead.next = NIL THEN warning := FALSE; CPM.LogWStr(" done")
ELSE
warning := TRUE;
e := errHead.next; inserted := 0;
WHILE e # NIL DO
DevMarkers.Insert(text, e.pos+inserted, DevMarkers.dir.New(e.n)); (*<<*)
e := e.next; INC(inserted)
END
END;
errHead := NIL
END WriteWarnings;
(*<<OP2 procedures *)
PROCEDURE TypeSize(typ: CPT.Struct);
END TypeSize;
PROCEDURE ProcessModule (source: TextModels.Reader; log: TextModels.Model; VAR error, warning: BOOLEAN);
VAR p: CPT.Node; script: Stores.Operation; text: TextModels.Model;
BEGIN (* similar to DevCompiler.Module *)
text := source.Base();
Models.BeginModification(Models.clean, text);
Models.BeginScript(text, "#Dev:InsertMarkers", script);
CPM.Init(source, log);
CPT.Init({});
CPB.typSize := TypeSize;
(*CPT.processor := CPV.processor;*)
Module(p);
CPT.Close;
error := ~CPM.noerr;
CPM.Close;
p := NIL;
IF error THEN
CPM.InsertMarks(source.Base());
CPM.LogWLn; CPM.LogWStr(" ");
IF CPM.errors = 1 THEN
Dialog.MapString("#Dev:OneErrorDetected", str)
ELSE
CPM.LogWNum(CPM.errors, 0); Dialog.MapString("#Dev:ErrorsDetected", str)
END;
CPM.LogWStr(str)
ELSE
options.statements := nofStats;
WriteWarnings(text, warning);
CPM.LogWLn; CPM.LogWNum(nofStats, 0); CPM.LogWStr(" statements")
END;
CPM.LogWLn; CPM.Close;
Models.EndScript(source.Base(), script);
Models.EndModification(Models.clean, text)
END ProcessModule;
PROCEDURE Do (source, log: TextModels.Model; beg: INTEGER; VAR error, warning: BOOLEAN);
VAR r: TextMappers.Scanner;
BEGIN
Dialog.MapString("#Dev:Analyzing", str);
StdLog.String(str); StdLog.Char(" ");
options.fileName := "";
r.ConnectTo(source); r.SetPos(beg); r.Scan;
IF (r.type = TextMappers.string) & (r.string = "MODULE") THEN
r.Scan;
IF r.type = TextMappers.string THEN
StdLog.Char('"'); StdLog.String(r.string); StdLog.Char('"');
options.fileName := r.string
END
END;
sourceR := source.NewReader(NIL); sourceR.SetPos(beg);
ProcessModule(sourceR, log, error, warning); Dialog.Update(options)
END Do;
PROCEDURE Open;
BEGIN
Dialog.ShowStatus("#Dev:Analyzing");
StdLog.buf.Delete(0, StdLog.buf.Length())
END Open;
PROCEDURE Close (noerr: BOOLEAN);
BEGIN
StdLog.text.Append(StdLog.buf);
IF noerr & CPM.noerr THEN Dialog.ShowStatus("#Dev:Ok")
END;
sourceR := NIL;
END Close;
PROCEDURE Analyze*;
VAR t: TextModels.Model; error, warning: BOOLEAN;
BEGIN
Open;
t := TextViews.FocusText();
IF t # NIL THEN
Do(t, StdLog.text, 0, error, warning);
IF error OR warning THEN DevMarkers.ShowFirstError(t, TextViews.focusOnly) END
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END;
Close(~error & ~warning)
END Analyze;
PROCEDURE ResetOptions*;
BEGIN
options.varpar := FALSE; options.exported := FALSE;
options.intermediate := FALSE; options.levels := FALSE;
options.tbProcs := FALSE; options.semicolons := FALSE;
options.sideEffects := FALSE;
options.statements := 0; options.fileName := "";
Dialog.Update(options)
END ResetOptions;
PROCEDURE SaveOptions*;
BEGIN
StdRegistry.WriteBool(regKey + 'varPar', options.varpar);
StdRegistry.WriteBool(regKey + 'exported', options.exported);
StdRegistry.WriteBool(regKey + 'intermediate', options.intermediate);
StdRegistry.WriteBool(regKey + 'levels', options.levels);
StdRegistry.WriteBool(regKey + 'tbProcs', options.tbProcs);
StdRegistry.WriteBool(regKey + 'semicolons', options.semicolons);
StdRegistry.WriteBool(regKey + 'sideEffects', options.sideEffects);
END SaveOptions;
PROCEDURE LoadOptions*;
VAR res: INTEGER;
BEGIN
StdRegistry.ReadBool(regKey + 'varPar', options.varpar, res);
IF res # 0 THEN options.varpar := FALSE END;
StdRegistry.ReadBool(regKey + 'exported', options.exported, res);
IF res # 0 THEN options.exported := FALSE END;
StdRegistry.ReadBool(regKey + 'intermediate', options.intermediate,res);
IF res # 0 THEN options.intermediate := FALSE END;
StdRegistry.ReadBool(regKey + 'levels', options.levels, res);
IF res # 0 THEN options.levels := FALSE END;
StdRegistry.ReadBool(regKey + 'tbProcs', options.tbProcs, res);
IF res # 0 THEN options.tbProcs := FALSE END;
StdRegistry.ReadBool(regKey + 'semicolons', options.semicolons, res);
IF res # 0 THEN options.semicolons := FALSE END;
StdRegistry.ReadBool(regKey + 'sideEffects', options.sideEffects, res);
IF res # 0 THEN options.sideEffects := FALSE END;
Dialog.Update(options)
END LoadOptions;
BEGIN ResetOptions; LoadOptions
END DevAnalyzer.
Warnings:
900 never used
901 never set
902 used before set
903 set but never used
904 used as varpar, possibly not set
905 also declared in outer scope
906 access/assignment to intermediate
907 redefinition
908 new definition
909 statement after RETURN/EXIT
910 for loop variable set
911 implied type guard
912 superfluous type guard
913 call might depend on evaluation sequence of params.
930 superfluous semicolon
Menu entry:
SEPARATOR
"Analyze" "=" "DevAnalyzer.Analyze" "TextCmds.FocusGuard"
"Analyze Selection" "" "DevAnalyzer.AnalyzeSelection" "TextCmds.SelectionGuard"
"Analyze..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/Analyzer', 'Analyze')" ""
| Dev/Mod/Analyzer.odc |
MODULE DevBrowser;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070123, bh, StringConst changed to show Unicode strings
- 20070123, bh, ProcSysFlag call in Structure (sysflags for procedure types)
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150513, center #43, extending the size of code procedures
- 20150530, center #19, missing Utf-8 conversions added
- 20160324, center #111, code cleanups
- 20160803, center #19, missing Utf-8 conversion added in CheckModName
- 20160820, center #123, Show Extension Interface is not showing *Hook procedures
- 20161002, center #132, bug in ProperString fixed
- 20161103, center #140, unwrapping import aliasses
- 20161104, center #142, adding a disassembler to the ocf importer
- 20170724, center #167, endless loop in DevBrowser for cyclic pointer type
- 20170811, center #170, DevBrowser.ImportSymFile should return TextViews.View
"
issues = "
- ...
"
**)
IMPORT
Kernel, Files, Fonts, Dates, Ports, Stores, Views, Properties, Dialog, Documents,
TextModels, TextMappers, TextRulers, TextViews, TextControllers, StdDialog, StdFolds,
DevReferences, DevCPM, DevCPT, DevDecoder386, StdRegistry, Utf;
CONST
width = 170 * Ports.mm; (* view width *)
height = 300 * Ports.mm;
(* visibility *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* object modes *)
var = 1; varPar = 2; const = 3; field = 4; type = 5; lProc = 6; xProc = 7; cProc = 9; iProc = 10;
mod = 11; head = 12; tProc = 13; ptrType = 31;
(* structure forms *)
undef = 0; bool = 2; sChar = 3; byte = 4; sInt = 5; int = 6; sReal = 7; real = 8;
set = 9; sString = 10; nilTyp = 11; noTyp = 12; pointer = 13; procTyp = 14; comp = 15;
char = 16; string = 17; lInt = 18;
(* composite structure forms *)
basic = 1; array = 2; dynArray = 3; record = 4;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval) *)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
modNotFoundKey = "#Dev:ModuleNotFound";
noSuchItemExportedKey = "#Dev:NoSuchItemExported";
noSuchExtItemExportedKey = "#Dev:NoSuchExtItemExported";
noModuleNameSelectedKey = "#Dev:NoModuleNameSelected";
regKey = "Dev\Browser\";
TYPE
TProcList = POINTER TO RECORD
fld: DevCPT.Object;
attr: SET; (* newAttr *)
next: TProcList
END;
VAR
global: RECORD
hints: BOOLEAN; (* display low-level hints such as field offsets *)
flatten: BOOLEAN; (* include fields/bound procs of base types as well *)
hideHooks: BOOLEAN; (* hide hook procedures and interfaces *)
clientinterface, extensioninterface: BOOLEAN;
sectAttr, keyAttr: TextModels.Attributes; (* formatting of section and other keywords *)
level: INTEGER; (* current indentation level *)
gap: BOOLEAN; (* request for lazy Ln, issued with next Indent *)
singleton: BOOLEAN; (* selectively display one object's definition *)
thisObj: DevCPT.Name; (* singleton => selected object *)
out: TextMappers.Formatter; (* formatter used to produce definition text *)
systemUsed: BOOLEAN;
comUsed: BOOLEAN;
modUsed: ARRAY 127 OF BOOLEAN;
pos: INTEGER
END;
inp: Files.Reader;
imp: ARRAY 256 OF Kernel.Utf8Name;
num, lev, max: INTEGER;
options*: RECORD
hints*: BOOLEAN; (* display low-level hints such as field offsets *)
flatten*: BOOLEAN; (* include fields/bound procs of base types as well *)
formatted*: BOOLEAN;
shints, sflatten, sformatted: BOOLEAN (* saved values *)
END;
PROCEDURE IsHook(typ: DevCPT.Struct): BOOLEAN;
VAR cnt: INTEGER; (* for breaking cycles in exotic cases such as T = POINTER TO ARRAY ... OF T *)
BEGIN
cnt := 0;
WHILE ((typ.form = pointer) OR (typ.form = comp)) & (typ.BaseTyp # NIL) & (cnt < 100) DO
typ := typ.BaseTyp; INC(cnt)
END;
RETURN (DevCPT.GlbMod[typ.mno].name^ = "Kernel") & (typ.strobj.name^ = "Hook^")
END IsHook;
(* auxilliary *)
PROCEDURE GetSelection (VAR text: TextModels.Model; VAR beg, end: INTEGER);
VAR c: TextControllers.Controller;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
text := c.text; c.GetSelection(beg, end)
ELSE
text := NIL
END
END GetSelection;
PROCEDURE GetQualIdent (VAR mod, ident: DevCPT.Name; VAR t: TextModels.Model);
VAR s: TextMappers.Scanner; beg, end, res: INTEGER;
BEGIN
GetSelection(t, beg, end);
IF t # NIL THEN
s.ConnectTo(t); s.SetOpts({7}); (* acceptUnderscores *)
s.SetPos(beg); s.Scan;
IF (s.type = TextMappers.string) & (s.len < LEN(mod)) THEN
DevReferences.ResolveImportAlias(s.string, t);
Utf.StringToUtf8(s.string, mod, res);
s.Scan;
IF (s.type = TextMappers.char) & (s.char = ".") & (s.Pos() <= end) THEN
s.Scan;
IF (s.type = TextMappers.string) & (s.len < LEN(ident)) THEN
Utf.StringToUtf8(s.string, ident, res);
ELSE mod[0] := 0X; ident[0] := 0X
END
ELSE ident[0] := 0X
END
ELSE mod[0] := 0X; ident[0] := 0X
END
ELSE mod[0] := 0X; ident[0] := 0X
END
END GetQualIdent;
PROCEDURE NewRuler (): TextRulers.Ruler;
VAR ra: TextRulers.Attributes; p: TextRulers.Prop;
BEGIN
NEW(p); p.valid := {TextRulers.right, TextRulers.opts};
p.opts.val := {(*TextRulers.rightFixed*)}; p.opts.mask := p.opts.val;
p.right := width;
NEW(ra); ra.InitFromProp(p);
RETURN TextRulers.dir.New(TextRulers.dir.NewStyle(ra))
END NewRuler;
PROCEDURE Append (VAR d: ARRAY OF CHAR; s: ARRAY OF SHORTCHAR);
VAR l, ld, ls: INTEGER;
BEGIN
l := LEN(d); ld := LEN(d$); ls := LEN(s$);
IF ld + ls >= l THEN
s[l - ld - 1] := 0X; d := d + s;
d[l - 2] := "."; d[l - 3] := "."; d[l - 4] := "."
ELSE
d := d + s
END
END Append;
PROCEDURE IsLegal (name: POINTER TO ARRAY OF SHORTCHAR): BOOLEAN;
VAR i: INTEGER;
BEGIN
IF name^ = "" THEN RETURN FALSE END;
IF name[0] = "@" THEN RETURN global.hints END;
i := 0;
WHILE name[i] # 0X DO INC(i) END;
RETURN name[i-1] # "^"
END IsLegal;
(* output formatting *)
PROCEDURE Char (ch: CHAR);
BEGIN
global.out.WriteChar(ch)
END Char;
PROCEDURE String (IN s: ARRAY OF SHORTCHAR);
VAR res: INTEGER; n: ARRAY 256 OF CHAR;
BEGIN
Utf.Utf8ToString(s, n, res);
global.out.WriteString(n)
END String;
PROCEDURE StringConst (s: ARRAY OF SHORTCHAR; long: BOOLEAN);
VAR i, x, y: INTEGER; quoted, first: BOOLEAN;
BEGIN
IF long THEN
i := 0; REPEAT DevCPM.GetUtf8(s, y, i) UNTIL (y = 0) OR (y >= 100H);
IF y = 0 THEN global.out.WriteString("LONG(") END
END;
i := 0; quoted := FALSE; first := TRUE;
IF long THEN DevCPM.GetUtf8(s, x, i) ELSE x := ORD(s[i]); INC(i) END;
WHILE x # 0 DO
IF (x < ORD(" "))
OR (x >= 7FH) & (x <= 9FH)
OR (x >= 0D800H) & (x <= 0F8FFH)
OR (x >= 0FFF0H) THEN (* nonprintable character *)
IF quoted THEN global.out.WriteChar('"') END;
IF ~first THEN global.out.WriteString(" + ") END;
IF x >= 0A00H THEN global.out.WriteIntForm(x, TextMappers.hexadecimal, 4, "0", FALSE)
ELSIF x >= 0A0H THEN global.out.WriteIntForm(x, TextMappers.hexadecimal, 3, "0", FALSE)
ELSE global.out.WriteIntForm(x, TextMappers.hexadecimal, 2, "0", FALSE)
END;
global.out.WriteChar("X");
quoted := FALSE
ELSE (* printable character *)
IF ~quoted THEN
IF ~first THEN global.out.WriteString(" + ") END;
global.out.WriteChar('"')
END;
global.out.WriteChar(CHR(x));
quoted := TRUE
END;
IF long THEN DevCPM.GetUtf8(s, x, i) ELSE x := ORD(s[i]); INC(i) END;
first := FALSE
END;
IF first THEN global.out.WriteString('""') END;
IF quoted THEN global.out.WriteChar('"') END;
IF long & (y = 0) THEN global.out.WriteChar(")") END
END StringConst;
PROCEDURE ProperString (s: ARRAY OF SHORTCHAR);
VAR i, res: INTEGER; str: ARRAY LEN(DevCPT.Name) OF CHAR;
BEGIN
IF s # "" THEN
Utf.Utf8ToString(s, str, res);
i := 0;
WHILE (str[i] # 0X) & (str[i] # "^") DO
global.out.WriteChar(str[i]); INC(i)
END
END
END ProperString;
PROCEDURE Keyword (s: ARRAY OF CHAR);
VAR a: TextModels.Attributes;
BEGIN
IF global.keyAttr # NIL THEN a := global.out.rider.attr; global.out.rider.SetAttr(global.keyAttr) END;
global.out.WriteString(s);
IF global.keyAttr # NIL THEN global.out.rider.SetAttr(a) END
END Keyword;
PROCEDURE Section (VAR out: TextMappers.Formatter; s: ARRAY OF CHAR);
VAR a: TextModels.Attributes;
BEGIN
IF global.sectAttr # NIL THEN a := out.rider.attr; out.rider.SetAttr(global.sectAttr) END;
out.WriteString(s);
IF global.sectAttr # NIL THEN out.rider.SetAttr(a) END
END Section;
PROCEDURE Int (i: INTEGER);
BEGIN
global.out.WriteInt(i)
END Int;
PROCEDURE Hex (x, n: INTEGER);
BEGIN
IF n > 1 THEN Hex(x DIV 16, n - 1) END;
x := x MOD 16;
IF x >= 10 THEN global.out.WriteChar(CHR(x + ORD("A") - 10))
ELSE global.out.WriteChar(CHR(x + ORD("0")))
END
END Hex;
PROCEDURE Ln;
BEGIN
global.out.WriteLn
END Ln;
PROCEDURE Indent;
VAR i: INTEGER;
BEGIN
IF global.gap THEN global.gap := FALSE; Ln END;
i := global.level; WHILE i > 0 DO global.out.WriteTab; DEC(i) END
END Indent;
PROCEDURE Guid (ext: DevCPT.ConstExt);
BEGIN
Char("{");
Hex(ORD(ext[2]) + 256 * ORD(ext[3]), 4);
Hex(ORD(ext[0]) + 256 * ORD(ext[1]), 4);
Char("-");
Hex(ORD(ext[4]) + 256 * ORD(ext[5]), 4);
Char("-");
Hex(ORD(ext[6]) + 256 * ORD(ext[7]), 4);
Char("-");
Hex(ORD(ext[8]), 2);
Hex(ORD(ext[9]), 2);
Char("-");
Hex(ORD(ext[10]), 2);
Hex(ORD(ext[11]), 2);
Hex(ORD(ext[12]), 2);
Hex(ORD(ext[13]), 2);
Hex(ORD(ext[14]), 2);
Hex(ORD(ext[15]), 2);
Char("}")
END Guid;
(* special marks *)
PROCEDURE Hint (label: ARRAY OF SHORTCHAR; i: INTEGER; adj: BOOLEAN);
BEGIN
IF global.hints THEN
Char("["); String(label);
IF adj & (0 <= i) & (i < 10) THEN Char(TextModels.digitspace) END;
Int(i);
String("] ")
END
END Hint;
PROCEDURE Hint3 (label1, label2, label3: ARRAY OF SHORTCHAR; i1, i2, i3: INTEGER);
BEGIN
IF global.hints THEN
Char("["); String(label1); Int(i1); String(label2); Int(i2); String(label3); Int(i3); String("] ")
END
END Hint3;
PROCEDURE Vis (i: INTEGER);
BEGIN
IF i # external THEN Char("-") END
END Vis;
PROCEDURE ProcSysFlag (flag: INTEGER);
BEGIN
IF flag # 0 THEN
String(" [");
IF flag = -10 THEN String("ccall")
ELSE Int(flag)
END;
Char("]")
END
END ProcSysFlag;
PROCEDURE ParSysFlag (flag: INTEGER);
VAR pos: INTEGER;
BEGIN
IF flag # 0 THEN
String(" [");
pos := global.out.Pos();
IF ODD(flag) THEN String("nil") END;
(*
IF ODD(flag DIV 2) & (flag # 18) THEN
IF global.out.Pos() # pos THEN String(", ") END;
String("in")
END;
IF ODD(flag DIV 4) & (flag # 12) THEN
IF global.out.Pos() # pos THEN String(", ") END;
String("out")
END;
*)
IF flag DIV 8 = 1 THEN
IF global.out.Pos() # pos THEN String(", ") END;
String("new")
ELSIF flag DIV 8 = 2 THEN
IF global.out.Pos() # pos THEN String(", ") END;
String("iid")
ELSIF flag DIV 8 # 0 THEN
IF global.out.Pos() # pos THEN String(", ") END;
Int(flag DIV 8 * 8)
END;
Char("]")
END
END ParSysFlag;
PROCEDURE StructSysFlag (typ: DevCPT.Struct);
VAR flag: INTEGER;
BEGIN
flag := typ.sysflag;
IF (flag # 0) & ((typ.form # pointer) OR (flag = 2)) THEN
String(" [");
IF flag = 1 THEN String("untagged")
ELSIF flag = 2 THEN String("handle")
ELSIF flag = 3 THEN String("noalign")
ELSIF flag = 4 THEN String("align2")
ELSIF flag = 5 THEN String("align4")
ELSIF flag = 6 THEN String("align8")
ELSIF flag = 7 THEN String("union")
ELSIF flag = 10 THEN
IF typ.ext # NIL THEN Char('"'); String(typ.ext^); Char('"')
ELSE String("interface")
END
ELSIF flag = 20 THEN String("som")
ELSE Int(flag)
END;
Char("]")
END
END StructSysFlag;
PROCEDURE SysStrings (obj: DevCPT.Object);
BEGIN
IF global.hints & ((obj.entry # NIL) OR (obj.library # NIL)) THEN
String(' ["');
IF obj.library # NIL THEN String(obj.library^); String('", "') END;
IF obj.entry # NIL THEN String(obj.entry^) END;
String('"]')
END
END SysStrings;
(* non-terminals *)
PROCEDURE ^ Structure (typ: DevCPT.Struct);
PROCEDURE Qualifier (mno: INTEGER);
BEGIN
IF (mno > 1) OR (mno = 1) & global.singleton THEN
global.modUsed[mno] := TRUE;
String(DevCPT.GlbMod[mno].name^); Char(".")
END
END Qualifier;
PROCEDURE LocalName (obj: DevCPT.Object);
BEGIN
Qualifier(0); String(obj.name^)
END LocalName;
PROCEDURE TypName (typ: DevCPT.Struct; force: BOOLEAN);
BEGIN
IF force OR IsLegal(typ.strobj.name) THEN
IF (typ.mno > 1) OR (typ.mno = 1)
& ((typ.form >= pointer) OR (typ.BaseTyp # DevCPT.undftyp)) & global.singleton
THEN
Qualifier(typ.mno)
ELSIF typ = DevCPT.sysptrtyp THEN (* PTR is in SYSTEM *)
String("SYSTEM.");
global.systemUsed := TRUE
ELSIF
(typ = DevCPT.guidtyp) OR (typ = DevCPT.restyp) OR (typ = DevCPT.iunktyp) OR (typ = DevCPT.punktyp)
THEN
String("COM.");
global.comUsed := TRUE
END;
IF force THEN ProperString(typ.strobj.name^) ELSE String(typ.strobj.name^) END
ELSE
Structure(typ)
END
END TypName;
PROCEDURE ParList (VAR par: DevCPT.Object);
BEGIN
IF par.mode = varPar THEN
IF par.vis = inPar THEN Keyword("IN")
ELSIF par.vis = outPar THEN Keyword("OUT")
ELSE Keyword("VAR")
END;
ParSysFlag(par.sysflag); Char(" ")
END;
String(par.name^);
WHILE (par.link # NIL) & (par.link.typ = par.typ) & (par.link.mode = par.mode)
& (par.link.vis = par.vis) & (par.link.sysflag = par.sysflag) DO
par := par.link; String(", "); String(par.name^)
END;
String(": "); TypName(par.typ, FALSE)
END ParList;
PROCEDURE Signature (result: DevCPT.Struct; par: DevCPT.Object);
VAR paren, res: BOOLEAN;
BEGIN
res := result # DevCPT.notyp; paren := res OR (par # NIL);
IF paren THEN String(" (") END;
IF par # NIL THEN
ParList(par); par := par.link;
WHILE par # NIL DO String("; "); ParList(par); par := par.link END
END;
IF paren THEN Char(")") END;
IF res THEN String(": "); TypName(result, FALSE) END
END Signature;
PROCEDURE TProcs (rec: DevCPT.Struct; fld: DevCPT.Object; oldProcs: TProcList; VAR newProcs: TProcList);
VAR old: DevCPT.Object; p, elem: TProcList;
BEGIN
IF fld # NIL THEN
TProcs(rec, fld.left, oldProcs, newProcs);
IF (fld.mode = tProc) & IsLegal(fld.name) THEN
DevCPT.FindBaseField(fld.name^, rec, old);
IF (old = NIL) OR (fld.typ # old.typ) OR (* (rec.attribute # 0) & *) (fld.conval.setval # old.conval.setval)
THEN
IF global.extensioninterface OR global.clientinterface THEN
(* do not show methods with equal name *)
p := oldProcs;
WHILE (p # NIL) & (p.fld.name^ # fld.name^) DO p := p.next END
END;
IF p = NIL THEN
NEW(elem); elem.next := newProcs; newProcs := elem;
elem.fld := fld;
IF old = NIL THEN INCL(elem.attr, newAttr) END;
IF absAttr IN fld.conval.setval THEN INCL(elem.attr, absAttr)
ELSIF empAttr IN fld.conval.setval THEN INCL(elem.attr, empAttr)
ELSIF extAttr IN fld.conval.setval THEN INCL(elem.attr, extAttr)
END
END
END
END;
TProcs(rec, fld.right, oldProcs, newProcs)
END
END TProcs;
(*
PROCEDURE AdjustTProcs (typ: DevCPT.Struct; fld: DevCPT.Object);
VAR receiver, old: DevCPT.Object; base: DevCPT.Struct;
BEGIN
IF fld # NIL THEN
AdjustTProcs(typ, fld.left);
IF (fld.mode = tProc) & IsLegal(fld.name) THEN
DevCPT.FindBaseField(fld.name^, typ, old);
IF old # NIL THEN
IF fld.conval.setval * {absAttr, empAttr, extAttr} = {} THEN
old.conval.setval := old.conval.setval - {absAttr, empAttr, extAttr}
ELSIF (extAttr IN fld.conval.setval) & (empAttr IN old.conval.setval) THEN
(* do not list methods which only change attribute from empty to extensible *)
old.conval.setval := old.conval.setval + {extAttr} - {empAttr}
END;
IF fld.typ # old.typ THEN (* do not show base methods of covariant overwritten methods *)
old.typ := fld.typ; old.conval.setval := {}
END;
END
END;
AdjustTProcs(typ, fld.right)
END;
IF (typ.BaseTyp # NIL) & (typ.BaseTyp # DevCPT.iunktyp) THEN
AdjustTProcs(typ.BaseTyp, typ.BaseTyp.link)
END
END AdjustTProcs;
*)
PROCEDURE TypeboundProcs (typ: DevCPT.Struct; VAR cont: BOOLEAN; top: BOOLEAN;
VAR list: TProcList; recAttr: INTEGER);
VAR receiver: DevCPT.Object; new, p, q: TProcList;
BEGIN
IF (typ # NIL) & (typ # DevCPT.iunktyp) THEN
TProcs(typ, typ.link, list, new);
p := list;
WHILE new # NIL DO
q := new.next; new.next := p; p := new; new := q
END;
list := p;
IF global.flatten THEN
TypeboundProcs(typ.BaseTyp, cont, FALSE, list, recAttr);
IF (typ.BaseTyp = NIL) OR (typ.BaseTyp = DevCPT.iunktyp) THEN
(*
IF global.extensioninterface & (recAttr IN {absAttr, extAttr}) THEN
IF cont THEN Char(";") END;
Ln; Indent;
String("(a: ANYPTR) FINALIZE-, "); Keyword("NEW"); String(", "); Keyword("EMPTY");
cont := TRUE
END
*)
END
END;
IF top THEN (* writeList *)
WHILE list # NIL DO
IF ~global.clientinterface & ~global.extensioninterface (* default *)
OR global.clientinterface & (list.fld.vis = external)
OR global.extensioninterface & (recAttr IN {absAttr, extAttr}) & (list.attr * {absAttr, empAttr, extAttr} # {})
THEN
IF cont THEN Char(";") END;
Ln;
receiver := list.fld.link;
Indent; Hint("entry ", list.fld.num, TRUE);
(*
Keyword("PROCEDURE"); String(" (");
*)
Char("(");
IF receiver.mode = varPar THEN
IF receiver.vis = inPar THEN Keyword("IN") ELSE Keyword("VAR") END;
Char(" ")
END;
String(receiver.name^); String(": ");
IF IsLegal(receiver.typ.strobj.name) & (receiver.typ.mno = 1) THEN
String(receiver.typ.strobj.name^)
ELSE TypName(receiver.typ, FALSE)
END;
String(") "); String(list.fld.name^); Vis(list.fld.vis);
SysStrings(list.fld);
Signature(list.fld.typ, receiver.link);
IF newAttr IN list.attr THEN String(", "); Keyword("NEW") END;
IF absAttr IN list.attr THEN String(", "); Keyword("ABSTRACT")
ELSIF empAttr IN list.attr THEN String(", "); Keyword("EMPTY")
ELSIF extAttr IN list.attr THEN String(", "); Keyword("EXTENSIBLE")
END;
cont := TRUE
END;
list := list.next
END
END
END
END TypeboundProcs;
PROCEDURE Flds (typ: DevCPT.Struct; VAR cont: BOOLEAN);
VAR fld: DevCPT.Object;
BEGIN
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = field) DO
IF IsLegal(fld.name) THEN
IF cont THEN Char(";") END;
Ln;
Indent; Hint("offset ", fld.adr, TRUE);
IF typ.mno > 1 THEN String("(* "); TypName(typ, TRUE); String(" *) ") END;
String(fld.name^);
WHILE (fld.link # NIL) & (fld.link.typ = fld.typ) & (fld.link.name # NIL) DO
Vis(fld.vis); fld := fld.link; String(", "); String(fld.name^)
END;
Vis(fld.vis); String(": "); TypName(fld.typ, FALSE);
cont := TRUE
END;
fld := fld.link
END
END Flds;
PROCEDURE Fields (typ: DevCPT.Struct; VAR cont: BOOLEAN);
BEGIN
IF typ # NIL THEN
IF global.flatten THEN Fields(typ.BaseTyp, cont) END;
Flds(typ, cont)
END
END Fields;
PROCEDURE BaseTypes (typ: DevCPT.Struct);
BEGIN
IF typ.BaseTyp # NIL THEN
Char("("); TypName(typ.BaseTyp, TRUE);
IF global.flatten THEN BaseTypes(typ.BaseTyp) END;
Char(")")
END
END BaseTypes;
PROCEDURE Structure (typ: DevCPT.Struct);
VAR cont: BOOLEAN; p: TProcList;
BEGIN
INC(global.level);
CASE typ.form OF
pointer:
Keyword("POINTER"); StructSysFlag(typ); Char(" ");
Keyword("TO"); Char(" "); DEC(global.level); TypName(typ.BaseTyp, FALSE); INC(global.level)
| procTyp:
Keyword("PROCEDURE"); ProcSysFlag(typ.sysflag); Signature(typ.BaseTyp, typ.link)
| comp:
CASE typ.comp OF
array:
Keyword("ARRAY"); StructSysFlag(typ); Char(" "); Int(typ.n); Char(" ");
Keyword("OF"); Char(" "); TypName(typ.BaseTyp, FALSE)
| dynArray:
Keyword("ARRAY"); StructSysFlag(typ); Char(" ");
Keyword("OF"); Char(" "); TypName(typ.BaseTyp, FALSE)
| record:
IF typ.attribute = absAttr THEN Keyword("ABSTRACT ")
ELSIF typ.attribute = limAttr THEN Keyword("LIMITED ")
ELSIF typ.attribute = extAttr THEN Keyword("EXTENSIBLE ")
END;
Keyword("RECORD"); StructSysFlag(typ);
Char(" "); Hint3("tprocs ", ", size ", ", align ", typ.n, typ.size, typ.align);
cont := FALSE;
BaseTypes(typ); Fields(typ, cont); TypeboundProcs(typ, cont, TRUE, p, typ.attribute);
IF cont THEN Ln; DEC(global.level); Indent; INC(global.level) ELSE Char (" ") END;
Keyword("END")
END
ELSE
IF (typ.BaseTyp # DevCPT.undftyp) THEN TypName(typ.BaseTyp, FALSE) END (* alias structures *)
END;
DEC(global.level)
END Structure;
PROCEDURE Const (obj: DevCPT.Object);
VAR con: DevCPT.Const; s: SET; i, x, y: INTEGER; r: REAL;
BEGIN
Indent; LocalName(obj); SysStrings(obj); String(" = ");
con := obj.conval;
CASE obj.typ.form OF
bool:
IF con.intval = 1 THEN String("TRUE") ELSE String("FALSE") END
| sChar, char:
IF con.intval >= 0A000H THEN
Hex(con.intval, 5); Char("X")
ELSIF con.intval >= 0100H THEN
Hex(con.intval, 4); Char("X")
ELSIF con.intval >= 0A0H THEN
Hex(con.intval, 3); Char("X")
ELSIF (con.intval >= 32) & (con.intval <= 126) THEN
Char(22X); Char(CHR(con.intval)); Char(22X)
ELSE
Hex(con.intval, 2); Char("X")
END
| byte, sInt, int:
Int(con.intval)
| lInt:
y := SHORT(ENTIER((con.realval + con.intval) / 4294967296.0));
r := con.realval + con.intval - y * 4294967296.0;
IF r > MAX(INTEGER) THEN r := r - 4294967296.0 END;
x := SHORT(ENTIER(r));
Hex(y, 8); Hex(x, 8); Char("L")
| set:
Char("{"); i := 0; s := con.setval;
WHILE i <= MAX(SET) DO
IF i IN s THEN Int(i); EXCL(s, i);
IF s # {} THEN String(", ") END
END;
INC(i)
END;
Char("}")
| sReal, real:
global.out.WriteReal(con.realval)
| sString:
StringConst(con.ext, FALSE)
| string:
StringConst(con.ext, TRUE)
| nilTyp:
Keyword("NIL")
| comp: (* guid *)
Char("{"); Guid(con.ext); Char("}")
END;
Char(";"); Ln
END Const;
PROCEDURE AliasType (typ: DevCPT.Struct);
BEGIN
IF global.singleton & IsLegal(typ.strobj.name) THEN
WHILE typ.BaseTyp # DevCPT.undftyp DO
Char(";"); Ln; Indent;
String(typ.strobj.name^); SysStrings(typ.strobj); String(" = ");
IF typ.form >= pointer THEN
Structure(typ); typ := DevCPT.int16typ
ELSE
typ := typ.BaseTyp;
TypName(typ, FALSE)
END
END
END
END AliasType;
PROCEDURE NotExtRec(typ: DevCPT.Struct): BOOLEAN;
BEGIN
RETURN (typ.form = comp) & ((typ.comp # record) OR ~(typ.attribute IN {absAttr, extAttr}))
OR (typ.form = procTyp)
END NotExtRec;
PROCEDURE Type (obj: DevCPT.Object);
BEGIN
IF global.hideHooks & IsHook(obj.typ) THEN RETURN END;
IF global.extensioninterface
& (NotExtRec(obj.typ)
OR
(obj.typ.form = pointer) & ~IsLegal(obj.typ.BaseTyp.strobj.name) &
NotExtRec(obj.typ.BaseTyp)
)
THEN
IF global.singleton THEN RETURN END;
global.out.rider.SetAttr(TextModels.NewColor(global.out.rider.attr, Ports.grey50));
IF global.pos < global.out.rider.Pos() THEN
global.out.rider.Base().SetAttr(global.pos, global.out.rider.Pos()-1, global.out.rider.attr)
END
END;
Indent; LocalName(obj); SysStrings(obj); String(" = ");
IF obj.typ.strobj # obj THEN
TypName(obj.typ, FALSE);
AliasType(obj.typ)
ELSIF (obj.typ.form < pointer) & (obj.typ.BaseTyp # DevCPT.undftyp) THEN
TypName(obj.typ.BaseTyp, FALSE);
AliasType(obj.typ.BaseTyp)
ELSE
Structure(obj.typ)
END;
Char(";"); Ln;
global.gap := TRUE
END Type;
PROCEDURE PtrType (obj: DevCPT.Object);
VAR base: DevCPT.Object;
BEGIN
Type(obj);
base := obj.typ.BaseTyp.strobj;
IF (base # NIL) & (base # DevCPT.anytyp.strobj) & (base # DevCPT.iunktyp.strobj)
& (base.vis # internal) & (base.typ.strobj # NIL) & ~(global.hideHooks & IsHook(base.typ)) THEN
(* show named record with pointer; avoid repetition *)
IF global.extensioninterface
& (base.typ.strobj = base) & ~((obj.typ.form < pointer) & (obj.typ.BaseTyp # DevCPT.undftyp))
& (NotExtRec(base.typ)
OR
(base.typ.form = pointer) & ~IsLegal(base.typ.BaseTyp.strobj.name) &
NotExtRec(base.typ.BaseTyp)
)
THEN
IF global.singleton THEN
IF global.pos < global.out.rider.Pos() THEN
global.out.rider.Base().Delete(global.pos, global.out.rider.Pos());
global.out.rider.SetPos(global.pos)
END;
RETURN
END;
global.out.rider.SetAttr(TextModels.NewColor(global.out.rider.attr, Ports.grey50));
IF global.pos < global.out.rider.Pos() THEN
global.out.rider.Base().SetAttr(global.pos, global.out.rider.Pos()-1, global.out.rider.attr)
END
END;
global.gap := FALSE;
Indent;
String(base.name^); SysStrings(base); String(" = ");
IF base.typ.strobj # base THEN
TypName(base.typ, FALSE);
AliasType(obj.typ)
ELSIF (obj.typ.form < pointer) & (obj.typ.BaseTyp # DevCPT.undftyp) THEN
TypName(obj.typ.BaseTyp, FALSE);
AliasType(obj.typ.BaseTyp)
ELSE
Structure(base.typ)
END;
Char(";"); Ln;
base.vis := internal;
global.gap := TRUE
END
END PtrType;
PROCEDURE Var (obj: DevCPT.Object);
BEGIN
IF global.hideHooks & IsHook(obj.typ) THEN RETURN END;
Indent; LocalName(obj); Vis(obj.vis); SysStrings(obj); String(": ");
TypName(obj.typ, FALSE); Char(";"); Ln
END Var;
PROCEDURE Proc (obj: DevCPT.Object);
VAR ext: DevCPT.ConstExt; i, m: INTEGER;
BEGIN
IF global.hideHooks & (obj.link # NIL) & (obj.link.link = NIL) & IsHook(obj.link.typ) THEN RETURN END;
IF global.extensioninterface & ~((obj.link # NIL) & (obj.link.link = NIL) & IsHook(obj.link.typ)) THEN RETURN END;
Indent; Keyword("PROCEDURE"); (* Char(" "); *)
IF obj.mode = cProc THEN String(" [code]")
ELSIF obj.mode = iProc THEN String(" [callback]")
ELSE ProcSysFlag(obj.sysflag)
END;
Char(" "); LocalName(obj);
(*IF obj.mode # cProc THEN SysStrings(obj) END;*)
SysStrings(obj);
Signature(obj.typ, obj.link);
IF (obj.mode = cProc) & global.hints THEN
Ln;
INC(global.level); Indent;
ext := obj.conval.ext;
IF ext # NIL THEN m := LEN(ext^); i := 0;
WHILE i < m DO
global.out.WriteIntForm(ORD(ext^[i]), TextMappers.hexadecimal, 3, "0", TextMappers.showBase);
INC(i);
IF i < m THEN String(", ") END;
END;
END;
DEC(global.level)
END;
Char(";"); Ln
END Proc;
(* tree traversal *)
PROCEDURE Objects (obj: DevCPT.Object; mode: SET);
VAR m: BYTE; a: TextModels.Attributes;
BEGIN
IF obj # NIL THEN
INC(lev); INC(num); max := MAX(max, lev);
Objects(obj.left, mode);
m := obj.mode; IF (m = type) & (obj.typ.form = pointer) THEN m := ptrType END;
IF (m IN mode) & (obj.vis # internal) & (obj.name # NIL) &
(~global.singleton OR (obj.name^ = global.thisObj)) THEN
global.pos := global.out.rider.Pos(); a := global.out.rider.attr;
CASE m OF
const: Const(obj)
| type: Type(obj)
| ptrType: PtrType(obj)
| var: Var(obj)
| xProc, cProc, iProc: Proc(obj)
END;
global.out.rider.SetAttr(a)
END;
Objects(obj.right, mode);
DEC(lev)
END
END Objects;
(* definition formatting *)
PROCEDURE PutSection (VAR out: TextMappers.Formatter; s: ARRAY OF CHAR);
VAR buf, def: TextModels.Model; i: INTEGER;
BEGIN
buf := global.out.rider.Base();
IF buf.Length() > 0 THEN
IF ~global.singleton THEN Ln END;
def := out.rider.Base(); out.SetPos(def.Length());
IF s # "" THEN (* prepend section keyword *)
i := global.level - 1; WHILE i > 0 DO out.WriteTab; DEC(i) END;
Section(out, s); out.WriteLn
END;
def.Append(buf);
global.pos := 0;
global.out.rider.SetPos(0)
END;
global.gap := FALSE
END PutSection;
PROCEDURE Scope (def: TextModels.Model; this: DevCPT.Name);
VAR out: TextMappers.Formatter; i: INTEGER; a: TextModels.Attributes;
BEGIN
global.gap := FALSE; global.thisObj := this; global.singleton := (this # "");
global.systemUsed := FALSE; global.comUsed := FALSE;
i := 1; WHILE i < LEN(global.modUsed) DO global.modUsed[i] := FALSE; INC(i) END;
out.ConnectTo(def);
INC(global.level);
IF ~(global.extensioninterface & global.singleton) THEN
IF global.extensioninterface THEN
a := global.out.rider.attr; global.out.rider.SetAttr(TextModels.NewColor(a, Ports.grey50))
END;
Objects(DevCPT.GlbMod[1].right, {const});
IF global.extensioninterface THEN global.out.rider.SetAttr(a) END;
PutSection(out, "CONST")
END;
Objects(DevCPT.GlbMod[1].right, {ptrType});
Objects(DevCPT.GlbMod[1].right, {type}); PutSection(out, "TYPE");
IF ~global.extensioninterface THEN
Objects(DevCPT.GlbMod[1].right, {var}); PutSection(out, "VAR")
END;
DEC(global.level);
num := 0; lev := 0; max := 0;
Objects(DevCPT.GlbMod[1].right, {xProc, cProc}); PutSection(out, "")
END Scope;
PROCEDURE Modules;
VAR i, j, n: INTEGER;
BEGIN
n := 0; j := 2;
IF global.systemUsed THEN INC(n) END;
IF global.comUsed THEN INC(n) END;
WHILE j < DevCPT.nofGmod DO
IF global.modUsed[j] THEN INC(n) END;
INC(j)
END;
IF n > 0 THEN
Indent; Section(global.out, "IMPORT"); INC(global.level);
IF n < 10 THEN Char(" ") ELSE Ln; Indent END;
i := 0; j := 2;
IF global.systemUsed THEN
String("SYSTEM"); INC(i);
IF i < n THEN String(", ") END
END;
IF global.comUsed THEN
String("COM"); INC(i);
IF i < n THEN String(", ") END
END;
WHILE i < n DO
IF global.modUsed[j] THEN
String(DevCPT.GlbMod[j].name^); INC(i);
(*
IF (DevCPT.GlbMod[j].strings # NIL) & (DevCPT.GlbMod[j].strings.ext # NIL) THEN
String(' ["'); String(DevCPT.GlbMod[j].strings.ext^); String('"]')
END;
*)
IF i < n THEN
Char(",");
IF i MOD 10 = 0 THEN Ln; Indent ELSE Char(" ") END
END
END;
INC(j)
END;
Char(";"); Ln; Ln
END
END Modules;
(* compiler interfacing *)
PROCEDURE OpenCompiler (mod: DevCPT.Name; VAR noerr: BOOLEAN);
VAR null: TextModels.Model; main: DevCPT.Name;
BEGIN
null := TextModels.dir.New();
DevCPM.Init(null.NewReader(NIL), null);
DevCPT.Init({}); main := "@mainMod"; DevCPT.Open(main);
DevCPT.processor := 0; (* accept all sym files *)
DevCPT.Import("@notself", mod, noerr);
IF ~DevCPM.noerr THEN noerr := FALSE END
END OpenCompiler;
PROCEDURE CloseCompiler;
BEGIN
DevCPT.Close;
DevCPM.Close
END CloseCompiler;
PROCEDURE Browse (
ident: DevCPT.Name; opts: ARRAY OF CHAR; VAR view: Views.View; VAR title: Views.Title
);
VAR def, buf: TextModels.Model; v: TextViews.View; h: BOOLEAN;
p: Properties.BoundsPref; mod: DevCPT.Name; i: INTEGER;
str, str1: ARRAY LEN(DevCPT.Name) OF CHAR;
res: INTEGER; n: DevCPT.Name;
BEGIN
mod := DevCPT.GlbMod[1].name$;
i := 0;
global.hints := FALSE; global.flatten := FALSE; global.hideHooks := TRUE;
global.clientinterface := FALSE; global.extensioninterface := FALSE;
global.keyAttr := NIL; global.sectAttr := NIL;
IF opts[0] = '@' THEN
IF options.hints THEN opts := opts + "+" END;
IF options.flatten THEN opts := opts + "!" END;
IF options.formatted THEN opts := opts + "/" END
END;
WHILE opts[i] # 0X DO
CASE opts[i] OF
| '+': global.hints := TRUE
| '!': global.flatten := TRUE
| '&': global.hideHooks := FALSE
| '/':
(* global.keyAttr := TextModels.NewStyle(TextModels.dir.attr, {Fonts.underline}); *)
global.keyAttr := TextModels.NewWeight(TextModels.dir.attr, Fonts.bold);
global.sectAttr := TextModels.NewWeight(TextModels.dir.attr, Fonts.bold)
| 'c': global.clientinterface := TRUE
| 'e' : global.extensioninterface := TRUE
ELSE
END;
INC(i)
END;
IF global.clientinterface & global.extensioninterface THEN
global.clientinterface := FALSE; global.extensioninterface := FALSE
END;
IF global.extensioninterface THEN global.hideHooks := FALSE END;
def := TextModels.dir.New();
buf := TextModels.dir.New(); global.out.ConnectTo(buf);
IF ident # "" THEN
h := global.hideHooks; global.hideHooks := FALSE;
global.level := 0; Scope(def, ident);
global.hideHooks := h;
def.Append(buf);
IF def.Length() > 0 THEN
v := TextViews.dir.New(def);
v.SetDefaults(NewRuler(), TextViews.dir.defAttr);
p.w := Views.undefined; p.h := Views.undefined; Views.HandlePropMsg(v, p);
n := mod$ + "." + ident; Utf.Utf8ToString(n, title, res);
view := Documents.dir.New(v, p.w, p.h)
ELSE
Utf.Utf8ToString(mod$, str, res);
Utf.Utf8ToString(ident$, str1, res);
title := "";
IF global.extensioninterface THEN
Dialog.ShowParamMsg(noSuchExtItemExportedKey, str, str1, "")
ELSE
Dialog.ShowParamMsg(noSuchItemExportedKey, str, str1, "")
END
END
ELSE
global.level := 1; Scope(def, "");
Section(global.out, "END"); Char(" "); String(mod); Char("."); Ln;
def.Append(buf);
Section(global.out, "DEFINITION"); Char(" "); String(mod);
IF (DevCPT.GlbMod[1].library # NIL) THEN
String(' ["'); String(DevCPT.GlbMod[1].library^); String('"]')
ELSIF DevCPT.impProc # 0 THEN
global.out.WriteTab; String("(* nonportable");
IF DevCPT.impProc = 10 THEN String(" (i386)")
ELSIF DevCPT.impProc = 20 THEN String(" (68k)")
END;
String(" *)")
END;
Char(";"); Ln; Ln;
Modules;
buf.Append(def);
v := TextViews.dir.New(buf);
v.SetDefaults(NewRuler(), TextViews.dir.defAttr);
Utf.Utf8ToString(mod, title, res);
view := Documents.dir.New(v, width, height)
END;
global.out.ConnectTo(NIL);
global.keyAttr := NIL; global.sectAttr := NIL
END Browse;
PROCEDURE ShowInterface* (opts: ARRAY OF CHAR);
VAR noerr: BOOLEAN; mod, ident: DevCPT.Name; v: Views.View; title: Views.Title; t: TextModels.Model;
str: ARRAY 256 OF CHAR; res: INTEGER;
BEGIN
GetQualIdent(mod, ident, t);
IF mod # "" THEN
OpenCompiler(mod, noerr);
IF noerr & (DevCPT.GlbMod[1] # NIL) & (DevCPT.GlbMod[1].name^ = mod) THEN
Browse(ident, opts, v, title);
IF v # NIL THEN
IF global.clientinterface THEN Append(title, " (client interface)")
ELSIF global.extensioninterface THEN Append(title, " (extension interface)")
END;
Views.OpenAux(v, title)
END
ELSE Utf.Utf8ToString(mod$, str, res); Dialog.ShowParamMsg(modNotFoundKey, str, "", "")
END;
CloseCompiler
ELSE Dialog.ShowMsg(noModuleNameSelectedKey)
END;
Kernel.Cleanup
END ShowInterface;
PROCEDURE ImportSymFile* (f: Files.File; OUT s: Stores.Store);
VAR v: Views.View; title: Views.Title; noerr: BOOLEAN;
BEGIN
ASSERT(f # NIL, 20);
DevCPM.file := f;
OpenCompiler("@file", noerr);
IF noerr THEN
Browse("", "", v, title);
IF v IS Documents.Document THEN v := v(Documents.Document).ThisView() END;
s := v
END;
CloseCompiler;
DevCPM.file := NIL;
Kernel.Cleanup
END ImportSymFile;
(* codefile browser *)
PROCEDURE RWord (VAR x: INTEGER);
VAR b: BYTE; y: INTEGER;
BEGIN
inp.ReadByte(b); y := b MOD 256;
inp.ReadByte(b); y := y + 100H * (b MOD 256);
inp.ReadByte(b); y := y + 10000H * (b MOD 256);
inp.ReadByte(b); x := y + 1000000H * b
END RWord;
PROCEDURE RNum (VAR x: INTEGER);
VAR b: BYTE; s, y: INTEGER;
BEGIN
s := 0; y := 0; inp.ReadByte(b);
WHILE b < 0 DO INC(y, ASH(b + 128, s)); INC(s, 7); inp.ReadByte(b) END;
x := ASH((b + 64) MOD 128 - 64, s) + y
END RNum;
PROCEDURE RName (VAR name: ARRAY OF SHORTCHAR);
VAR b: BYTE; i, n: INTEGER;
BEGIN
i := 0; n := LEN(name) - 1; inp.ReadByte(b);
WHILE (i < n) & (b # 0) DO name[i] := SHORT(CHR(b)); INC(i); inp.ReadByte(b) END;
WHILE b # 0 DO inp.ReadByte(b) END;
name[i] := 0X
END RName;
PROCEDURE RLink;
VAR x: INTEGER;
BEGIN
RNum(x);
WHILE x # 0 DO RNum(x); RNum(x) END
END RLink;
PROCEDURE RShort (p: INTEGER; OUT x: INTEGER);
VAR b0, b1: BYTE;
BEGIN
inp.ReadByte(b0); inp.ReadByte(b1);
IF p = 10 THEN x := b0 MOD 256 + b1 * 256 (* little endian *)
ELSE x := b1 MOD 256 + b0 * 256 (* big endian *)
END
END RShort;
PROCEDURE Decode (file: Files.File; VAR view: Views.View; VAR title: Views.Title);
VAR n, i, p, q, fp, hs, ms, ds, cs, vs, m, res: INTEGER; name: Kernel.Utf8Name; first: BOOLEAN;
text: TextModels.Model; v: TextViews.View; fold: StdFolds.Fold; d: Dates.Date; t: Dates.Time;
str: ARRAY 64 OF CHAR;
BEGIN
text := TextModels.dir.New(); global.out.ConnectTo(text);
inp := file.NewReader(NIL);
inp.SetPos(0); RWord(n);
IF n = 6F4F4346H THEN
RWord(p); RWord(hs); RWord(ms); RWord(ds); RWord(cs); RWord(vs);
RNum(n); RName(name); Utf.Utf8ToString(name, title, res); i := 0;
WHILE i < n DO RName(imp[i]); INC(i) END;
String("MODULE "); String(name); Ln;
String("processor: ");
IF p = 10 THEN String("80x86")
ELSIF p = 20 THEN String("68000")
ELSIF p = 30 THEN String("PPC")
ELSIF p = 40 THEN String("SH3")
ELSE Int(p)
END;
Ln;
String("meta size: "); Int(ms); Ln;
String("desc size: "); Int(ds); Ln;
String("code size: "); Int(cs); Ln;
String("data size: "); Int(vs); Ln;
inp.SetPos(hs + ms + 12);
RShort(p, d.year); RShort(p, d.month); RShort(p, d.day);
RShort(p, t.hour); RShort(p, t.minute); RShort(p, t.second);
String("compiled: ");
Dates.DateToString(d, Dates.short, str); global.out.WriteString(str); String(" ");
Dates.TimeToString(t, str); global.out.WriteString(str); Ln;
Int(n); String(" imports:"); Ln;
inp.SetPos(hs + ms + ds + cs);
RLink; RLink; RLink; RLink; RLink; RLink; i := 0;
WHILE i < n DO
global.out.WriteTab; String(imp[i]); global.out.WriteTab;
RNum(q);
IF q # 0 THEN
fold := StdFolds.dir.New(StdFolds.expanded, "", TextModels.dir.New());
global.out.WriteView(fold); Char(" "); first := TRUE;
WHILE q # 0 DO
RName(name); RNum(fp);
IF q = 2 THEN RNum(m) END;
IF q # 1 THEN RLink END;
IF name # "" THEN
IF ~first THEN String(", ") END;
first := FALSE; String(name)
END;
RNum(q)
END;
Char(" ");
fold := StdFolds.dir.New(StdFolds.expanded, "", NIL);
global.out.WriteView(fold);
fold.Flip(); global.out.SetPos(text.Length())
END;
INC(i); Ln
END;
IF p = 10 THEN DevDecoder386.Decode(title, inp, hs, ms, ds, cs, vs, -1, global.out) END
ELSE String("wrong file tag: "); Hex(n, 8)
END;
v := TextViews.dir.New(text);
v.SetDefaults(NewRuler(), TextViews.dir.defAttr);
view := Documents.dir.New(v, width, height);
global.out.ConnectTo(NIL);
inp := NIL
END Decode;
PROCEDURE ShowCodeFile*;
VAR t: TextModels.Model; f: Files.File; v: Views.View; title: Views.Title; mod, ident: DevCPT.Name;
name: Files.Name; loc: Files.Locator; str: ARRAY 256 OF CHAR; res: INTEGER;
BEGIN
GetQualIdent(mod, ident, t);
IF mod # "" THEN
Utf.Utf8ToString(mod$, str, res);
StdDialog.GetSubLoc(str, "Code", loc, name);
f := Files.dir.Old(loc, name, Files.shared);
IF f # NIL THEN
Decode(f, v, title);
IF v # NIL THEN Views.OpenAux(v, title) END
ELSE Dialog.ShowParamMsg(modNotFoundKey, str, "", "")
END
ELSE Dialog.ShowMsg(noModuleNameSelectedKey)
END
END ShowCodeFile;
PROCEDURE ImportCodeFile* (f: Files.File; OUT s: Stores.Store);
VAR v: Views.View; title: Views.Title;
BEGIN
ASSERT(f # NIL, 20);
Decode(f, v, title);
IF v IS Documents.Document THEN v := v(Documents.Document).ThisView() END;
s := v
END ImportCodeFile;
PROCEDURE SaveOptions*;
BEGIN
StdRegistry.WriteBool(regKey + 'hints', options.hints);
StdRegistry.WriteBool(regKey + 'flatten', options.flatten);
StdRegistry.WriteBool(regKey + 'formatted', options.formatted);
END SaveOptions;
PROCEDURE SaveGuard*(VAR par: Dialog.Par);
BEGIN
par.disabled := (options.sflatten = options.flatten)
& (options.shints = options.hints)
& (options.sformatted = options.formatted)
END SaveGuard;
PROCEDURE Init*;
VAR res: INTEGER;
BEGIN
StdRegistry.ReadBool(regKey + 'hints', options.hints, res);
IF res # 0 THEN options.hints := FALSE END;
StdRegistry.ReadBool(regKey + 'flatten', options.flatten, res);
IF res # 0 THEN options.flatten := TRUE END;
StdRegistry.ReadBool(regKey + 'formatted', options.formatted, res);
IF res # 0 THEN options.formatted := FALSE END;
Dialog.Update(options);
options.sflatten := options.flatten;
options.shints := options.hints;
options.sformatted := options.formatted
END Init;
BEGIN
Init
END DevBrowser.
| Dev/Mod/Browser.odc |
MODULE DevChmod__Fbsd;
IMPORT Libc := FbsdLibc, Files, DevLnkBase, Utf;
TYPE
ChmodHook = POINTER TO RECORD (DevLnkBase.ChmodHook) END;
VAR
hook: ChmodHook;
PROCEDURE (hook: ChmodHook) Chmod* (name0: Files.Name; mode: SET);
VAR name: ARRAY LEN(Files.Name) OF SHORTCHAR; res_: INTEGER;
BEGIN
IF DevLnkBase.outputType # "" THEN
Files.dir.GetFileName(name0, DevLnkBase.outputType, name0)
END;
Utf.StringToUtf8(name0, name, res_);
res_ := Libc.chmod(name, SHORT(ORD(mode))) (* rwxrwxr-x *)
END Chmod;
BEGIN
NEW(hook);
DevLnkBase.SetChmodHook(hook)
END DevChmod__Fbsd.
| Dev/Mod/Chmod__Fbsd.odc |
MODULE DevChmod__Lin;
IMPORT Libc := LinLibc, Files, DevLnkBase, Utf;
TYPE
ChmodHook = POINTER TO RECORD (DevLnkBase.ChmodHook) END;
VAR
hook: ChmodHook;
PROCEDURE (hook: ChmodHook) Chmod* (name0: Files.Name; mode: SET);
VAR name: ARRAY LEN(Files.Name) OF SHORTCHAR; res_: INTEGER;
BEGIN
IF DevLnkBase.outputType # "" THEN
Files.dir.GetFileName(name0, DevLnkBase.outputType, name0)
END;
Utf.StringToUtf8(name0, name, res_);
res_ := Libc.chmod(name, mode) (* rwxrwxr-x *)
END Chmod;
BEGIN
NEW(hook);
DevLnkBase.SetChmodHook(hook)
END DevChmod__Lin. | Dev/Mod/Chmod__Lin.odc |
MODULE DevChmod__Obsd;
IMPORT Libc := ObsdLibc, Files, DevLnkBase, Utf;
TYPE
ChmodHook = POINTER TO RECORD (DevLnkBase.ChmodHook) END;
VAR
hook: ChmodHook;
PROCEDURE (hook: ChmodHook) Chmod* (name0: Files.Name; mode: SET);
VAR name: ARRAY LEN(Files.Name) OF SHORTCHAR; res_: INTEGER;
BEGIN
IF DevLnkBase.outputType # "" THEN
Files.dir.GetFileName(name0, DevLnkBase.outputType, name0)
END;
Utf.StringToUtf8(name0, name, res_);
res_ := Libc.chmod(name, mode) (* rwxrwxr-x *)
END Chmod;
BEGIN
NEW(hook);
DevLnkBase.SetChmodHook(hook)
END DevChmod__Obsd. | Dev/Mod/Chmod__Obsd.odc |
MODULE DevCmds;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
"
issues = "
- ...
"
**)
IMPORT
Services, Files, Fonts, Ports, Stores, Models, Views, Controllers, Dialog,
Containers, Controls, Properties, Documents,
TextModels, TextMappers, TextRulers, TextViews, TextControllers,
StdDialog, StdCmds, StdMenuTool;
PROCEDURE OpenModuleList*;
VAR v: Views.View;
c: TextControllers.Controller; s: TextMappers.Scanner;
loc: Files.Locator; name: Files.Name;
beg, end: INTEGER; error, one: BOOLEAN;
BEGIN
c := TextControllers.Focus();
IF c # NIL THEN
s.ConnectTo(c.text);
IF c.HasSelection() THEN c.GetSelection(beg, end)
ELSE beg := 0; end := c.text.Length()
END;
s.SetPos(beg); s.Scan; one := FALSE;
WHILE (s.start < end) & (s.type = TextMappers.string) & (s.len < LEN(name)) DO
s.Scan; one := TRUE
END;
IF one & ((s.start >= end) OR (s.type = TextMappers.eot)) THEN
s.SetPos(beg); s.Scan; error := FALSE;
WHILE (s.start < end) & (s.type = TextMappers.string) & ~error DO
StdDialog.GetSubLoc(s.string, "Mod", loc, name);
IF loc.res = 0 THEN
v := Views.OldView(loc, name);
IF v # NIL THEN
Views.Open(v, loc, name, NIL)
ELSE
Dialog.ShowParamMsg("#System:CannotOpenFile", name, "", "");
error := TRUE
END
ELSE
Dialog.ShowParamMsg("#Dev:ModuleNotFound", s.string, "", "");
error := TRUE
END;
s.Scan
END
ELSE Dialog.ShowMsg("#Dev:NotOnlyModNames")
END;
s.ConnectTo(NIL)
ELSE Dialog.ShowMsg("#Text:FocusShouldBeText")
END
END OpenModuleList;
PROCEDURE Scan (VAR s: TextMappers.Scanner);
VAR ch: CHAR; i, max: INTEGER;
BEGIN
s.Skip(ch);
IF s.type # TextMappers.eot THEN
IF ch = '"' THEN s.Scan;
ELSE i := 0; max := LEN(s.string)-1;
WHILE (i < max) & ~s.rider.eot & (ch > " ") DO
s.string[i] := ch; s.rider.ReadChar(ch); INC(i);
END;
s.string[i] := 0X; s.len := SHORT(i);
IF s.len > 0 THEN s.type := TextMappers.string
ELSE s.type := TextMappers.invalid
END
END
END
END Scan;
PROCEDURE OpenFileList*; (* Pre: focus is text and has a selection *)
VAR c: TextControllers.Controller; s: TextMappers.Scanner; beg, end: INTEGER;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
s.ConnectTo(c.text);
s.SetPos(beg); Scan(s);
WHILE (s.type # TextMappers.eot) & (s.start < end) DO
IF s.type = TextMappers.string THEN StdCmds.OpenDoc(s.string) END;
Scan(s);
END
ELSE Dialog.ShowMsg("#Text:FocusShouldBeText")
END
END OpenFileList;
PROCEDURE FlushResources*;
BEGIN
(* flush menu guards *)
StdMenuTool.dir.RevalidateGuards;
(* flush string cache *)
Dialog.FlushMappings
END FlushResources;
PROCEDURE RevalidateView*;
VAR ops: Controllers.PollOpsMsg; v: Views.View;
BEGIN
Controllers.PollOps(ops);
IF ops.singleton # NIL THEN v := ops.singleton
ELSE v := Controllers.FocusView();
END;
IF v # NIL THEN Views.RevalidateView(v) END
END RevalidateView;
PROCEDURE RevalidateViewGuard* (VAR par: Dialog.Par);
VAR ops: Controllers.PollOpsMsg; v: Views.View;
BEGIN
Controllers.PollOps(ops);
IF ops.singleton # NIL THEN v := ops.singleton
ELSE v := Controllers.FocusView();
END;
IF (v = NIL) OR ~Views.IsInvalid(v) THEN par.disabled := TRUE END
END RevalidateViewGuard;
PROCEDURE SetDefault (c: Views.View; default: BOOLEAN);
VAR p: Controls.Prop; msg: Properties.SetMsg;
BEGIN
NEW(p); p.valid := {Controls.opt0}; p.opt[Controls.default] := default;
msg.prop := p; Views.HandlePropMsg(c, msg)
END SetDefault;
PROCEDURE SetDefaultButton*;
VAR s, v: Views.View; c: Containers.Controller; script: Stores.Operation;
BEGIN
c := Containers.Focus();
IF c # NIL THEN
s := c.Singleton();
c.SelectAll(FALSE);
Views.BeginScript(c.ThisView(), "#Dev:SetDefault", script);
c.GetFirstView(Containers.any, v);
WHILE v # NIL DO SetDefault(v, FALSE); c.GetNextView(Containers.any, v) END;
IF s # NIL THEN SetDefault(s, TRUE); c.SetSingleton(s) END;
Views.EndScript(c.ThisView(), script)
ELSE Dialog.Beep
END
END SetDefaultButton;
PROCEDURE SetCancel (c: Views.View; cancel: BOOLEAN);
VAR p: Controls.Prop; msg: Properties.SetMsg;
BEGIN
NEW(p); p.valid := {Controls.opt1}; p.opt[Controls.cancel] := cancel;
msg.prop := p; Views.HandlePropMsg(c, msg)
END SetCancel;
PROCEDURE SetCancelButton*;
VAR s, v: Views.View; c: Containers.Controller; script: Stores.Operation;
BEGIN
c := Containers.Focus();
IF c # NIL THEN
s := c.Singleton();
c.SelectAll(FALSE);
Views.BeginScript(c.ThisView(), "#Dev:SetCancel", script);
c.GetFirstView(Containers.any, v);
WHILE v # NIL DO SetCancel(v, FALSE); c.GetNextView(Containers.any, v) END;
IF s # NIL THEN SetCancel(s, TRUE); c.SetSingleton(s) END;
Views.EndScript(c.ThisView(), script)
ELSE Dialog.Beep
END
END SetCancelButton;
PROCEDURE NewRuler (): TextRulers.Ruler;
CONST mm = Ports.mm; pt = Ports.point;
VAR p: TextRulers.Prop;
BEGIN
NEW(p);
p.valid := {TextRulers.right, TextRulers.tabs, TextRulers.opts};
p.opts.val := {TextRulers.rightFixed}; p.opts.mask := p.opts.val;
p.tabs.len := 7;
p.right := 200 * mm;
p.tabs.tab[0].stop := 40 * mm; p.tabs.tab[0].type := {TextRulers.rightTab};
p.tabs.tab[1].stop := 50 * mm; p.tabs.tab[1].type := {TextRulers.rightTab};
p.tabs.tab[2].stop := 55 * mm;
p.tabs.tab[3].stop := 90 * mm;
p.tabs.tab[4].stop := 100 * mm;
p.tabs.tab[5].stop := 140 * mm;
p.tabs.tab[6].stop := 180 * mm; p.tabs.tab[6].type := {TextRulers.rightTab};
RETURN TextRulers.dir.NewFromProp(p)
END NewRuler;
PROCEDURE ShowControlList*;
(** Guard: StdCmds.ContainerGuard **)
VAR c: Containers.Controller; v: Views.View; s, t: Stores.TypeName;
msg: Properties.PollMsg; p: Properties.Property;
out: TextMappers.Formatter; str: Dialog.String; w, h: INTEGER;
PROCEDURE WriteEntry(name, value: Dialog.String);
BEGIN
out.WriteTab; out.WriteString(name); out.WriteTab; out.WriteString(value); out.WriteLn
END WriteEntry;
BEGIN
c := Containers.Focus();
IF c # NIL THEN
out.ConnectTo(TextModels.dir.New());out.WriteView(NewRuler());
out.rider.SetAttr(TextModels.NewStyle(out.rider.attr, {Fonts.italic}));
out.WriteString("type"); out.WriteTab;
out.WriteString("width"); out.WriteTab;
out.WriteString("height"); out.WriteTab;
out.WriteString("label"); out.WriteTab;
out.WriteString("link"); out.WriteTab;
out.WriteString("guard"); out.WriteTab;
out.WriteString("notifier"); out.WriteTab;
out.WriteString("level"); out.WriteTab;
out.WriteLn; out.WriteLn;
out.rider.SetAttr(TextModels.NewStyle(out.rider.attr, {}));
c.GetFirstView(Containers.any, v);
WHILE v # NIL DO
Services.GetTypeName(v, t);
s := "#Dev:"; s := s + t;
Dialog.MapString(s, s);
out.WriteString(s); out.WriteTab;
v.context.GetSize(w, h);
out.WriteInt(w DIV Ports.point); out.WriteTab;
out.WriteInt(h DIV Ports.point); out.WriteTab;
msg.prop := NIL; Views.HandlePropMsg(v, msg);
p := msg.prop; WHILE (p # NIL) & ~(p IS Controls.Prop) DO p := p.next END;
IF p # NIL THEN
WITH p: Controls.Prop DO
IF Controls.label IN p.valid THEN out.WriteString(p.label) END; out.WriteTab;
IF Controls.link IN p.valid THEN out.WriteString(p.link) END; out.WriteTab;
IF Controls.level IN p.valid THEN out.WriteTab; out.WriteTab; out.WriteInt(p.level) END;
IF (Controls.guard IN p.valid) & (p.guard # "") OR
(Controls.notifier IN p.valid) & (p.notifier # "") THEN
out.WriteLn; out.WriteTab; out.WriteTab; out.WriteTab; out.WriteTab; out.WriteTab;
IF Controls.guard IN p.valid THEN out.WriteString(p.guard) END; out.WriteTab;
IF Controls.notifier IN p.valid THEN out.WriteString(p.notifier) END
END
END
END;
out.WriteLn;
c.GetNextView(Containers.any, v)
END;
Views.OpenAux(Documents.dir.New(TextViews.dir.New(out.rider.Base()), 200*Ports.mm, -1), "Controls");
END
END ShowControlList;
END DevCmds.
| Dev/Mod/Cmds.odc |
MODULE DevCommanders;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems, Alexander Iljin"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20061112, ai, fixed EndView.Restore for partial updates
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150524, center #52, fixing wrong DevCommanders.par.beg/end
- 20160721, center #118, commander does not show error message
- 20170214, center #145, adding scanner option 'maskViews' in DevCommanders
"
issues = "
- ...
"
**)
IMPORT
Kernel, Strings, Fonts, Ports, Stores, Models, Views, Controllers, Properties, Dialog, Controls,
TextModels, TextSetters, TextMappers, Services, StdLog;
CONST
(* additional Scan types *)
ident = 19; qualident = 20; execMark = 21;
point = Ports.point;
minVersion = 0; maxVersion = 0; maxStdVersion = 0;
TYPE
View* = POINTER TO ABSTRACT RECORD (Views.View)
END;
EndView* = POINTER TO ABSTRACT RECORD (Views.View)
END;
Par* = POINTER TO RECORD
text*: TextModels.Model;
beg*, end*: INTEGER
END;
Directory* = POINTER TO ABSTRACT RECORD END;
StdView = POINTER TO RECORD (View) END;
StdEndView = POINTER TO RECORD (EndView) END;
StdDirectory = POINTER TO RECORD (Directory) END;
Scanner = RECORD
s: TextMappers.Scanner;
ident: ARRAY LEN(Kernel.Name) OF CHAR;
qualident: ARRAY LEN(Kernel.Name) * 2 - 1 OF CHAR
END;
TrapCleaner = POINTER TO RECORD (Kernel.TrapCleaner) END;
VAR
par*: Par;
dir-, stdDir-: Directory;
cleaner: TrapCleaner;
cleanerInstalled: BOOLEAN;
(** Cleaner **)
PROCEDURE (c: TrapCleaner) Cleanup;
BEGIN
par := NIL;
cleanerInstalled := FALSE;
END Cleanup;
(** View **)
PROCEDURE (v: View) Externalize- (VAR wr: Stores.Writer), EXTENSIBLE;
BEGIN
v.Externalize^(wr);
wr.WriteVersion(maxVersion);
wr.WriteXInt(execMark)
END Externalize;
PROCEDURE (v: View) Internalize- (VAR rd: Stores.Reader), EXTENSIBLE;
VAR thisVersion, type: INTEGER;
BEGIN
v.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxVersion, thisVersion);
IF rd.cancelled THEN RETURN END;
rd.ReadXInt(type)
END Internalize;
(** Directory **)
PROCEDURE (d: Directory) New* (): View, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewEnd* (): EndView, NEW, ABSTRACT;
(* auxilliary procedures *)
PROCEDURE IsIdent (IN s: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; ch: CHAR;
BEGIN
ch := s[0]; i := 1;
IF Strings.IsIdentStart(ch) THEN
REPEAT
ch := s[i]; INC(i)
UNTIL ~Strings.IsIdent(ch);
RETURN (ch = 0X) & (i <= LEN(Kernel.Name))
ELSE
RETURN FALSE
END
END IsIdent;
PROCEDURE Scan (VAR s: Scanner);
VAR done: BOOLEAN;
BEGIN
s.s.Scan;
IF (s.s.type = TextMappers.view) THEN
IF Properties.ThisType(s.s.view, "DevCommanders.View") # NIL THEN s.s.type := execMark END
ELSIF (s.s.type = TextMappers.string) & TextMappers.IsQualIdent(s.s.string) THEN
s.s.type := qualident; s.qualident := s.s.string$
ELSIF (s.s.type = TextMappers.string) & IsIdent(s.s.string) THEN
s.ident := s.s.string$;
TextMappers.ScanQualIdent(s.s, s.qualident, done);
IF done THEN s.s.type := qualident ELSE s.s.type := ident END
END
END Scan;
PROCEDURE ScanLongString(rd: TextModels.Reader; OUT cmd: POINTER TO ARRAY OF CHAR);
VAR ch: CHAR; first, last, i: INTEGER;
BEGIN
rd.ReadChar(ch);
WHILE ~rd.eot & (ch <= " ") DO rd.ReadChar(ch) END;
IF ~rd.eot & (ch = '"') THEN (* starts with a double quote *)
first := rd.Pos(); rd.ReadChar(ch);
WHILE ~rd.eot & (ch # '"') DO rd.ReadChar(ch) END;
IF ~rd.eot THEN (* ends with a double quote *)
last := rd.Pos(); NEW(cmd, last - first);
rd.SetPos(first); rd.ReadChar(ch); i := 0;
WHILE ch # '"' DO cmd[i] := ch; INC(i); rd.ReadChar(ch) END;
cmd[i] := 0X; rd.Read
END
END
END ScanLongString;
PROCEDURE GetParExtend (rd: TextModels.Reader; OUT end: INTEGER);
VAR v: Views.View;
BEGIN
IF rd.view # NIL THEN v := rd.view ELSE rd.ReadView(v) END;
WHILE ~rd.eot
& (Properties.ThisType(v, "DevCommanders.View") = NIL)
& (Properties.ThisType(v, "DevCommanders.EndView") = NIL) DO
rd.ReadView(v)
END;
end := rd.Pos(); IF ~rd.eot THEN DEC(end) END
END GetParExtend;
PROCEDURE Unload (IN cmd: Dialog.String);
VAR modname: Kernel.Name; str: Dialog.String; i: INTEGER; ch: CHAR; mod: Kernel.Module;
BEGIN
i := 0; ch := cmd[0];
WHILE (ch # 0X) & (ch # ".") DO modname[i] := ch; INC(i); ch := cmd[i] END;
modname[i] := 0X;
mod := Kernel.ThisLoadedMod(modname);
IF mod # NIL THEN
Kernel.UnloadMod(mod);
IF mod.refcnt < 0 THEN
Dialog.MapParamString("#Dev:Unloaded", modname, "", "", str);
StdLog.String(str); StdLog.Ln;
Controls.Relink
ELSE
Dialog.ShowParamMsg("#Dev:UnloadingFailed", modname, "", "")
END
END
END Unload;
PROCEDURE Execute (t: TextModels.Model; pos: INTEGER; VAR end: INTEGER; unload: BOOLEAN);
VAR s: Scanner; beg, res: INTEGER; cmd: POINTER TO ARRAY OF CHAR;
BEGIN
cmd := NIL;
s.s.ConnectTo(t); s.s.SetPos(pos); s.s.SetOpts({TextMappers.returnViews, TextMappers.maskViews});
Scan(s); ASSERT(s.s.type = execMark, 100);
Scan(s);
IF s.s.type = qualident THEN
NEW(cmd, LEN(s.qualident$) + 1); cmd^ := s.qualident$
ELSIF s.s.type = TextMappers.string THEN
NEW(cmd, LEN(s.s.string$) + 1); cmd^ := s.s.string$
ELSIF s.s.type = TextMappers.invalid THEN
s.s.SetPos(pos + 1);
ScanLongString(s.s.rider, cmd);
END;
IF cmd # NIL THEN
beg := s.s.Pos(); IF ~s.s.rider.eot THEN DEC(beg) END; GetParExtend(s.s.rider, end);
ASSERT(~cleanerInstalled, 101);
Kernel.PushTrapCleaner(cleaner); cleanerInstalled := TRUE;
NEW(par); par.text := t; par.beg := beg; par.end := end;
IF unload THEN Unload(cmd$) END;
Dialog.Call(cmd, " ", res);
par := NIL;
Kernel.PopTrapCleaner(cleaner); cleanerInstalled := FALSE;
ELSE
Dialog.ShowStatus("#System:SyntaxError")
END
END Execute;
PROCEDURE Track (v: View; f: Views.Frame; x, y: INTEGER; buttons: SET);
VAR c: Models.Context; w, h, end: INTEGER; isDown, in, in0: BOOLEAN; m: SET;
BEGIN
c := v.context; c.GetSize(w, h); in0 := FALSE; in := TRUE;
REPEAT
IF in # in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.show); in0 := in
END;
f.Input(x, y, m, isDown);
in := (0 <= x) & (x < w) & (0 <= y) & (y < h)
UNTIL ~isDown;
IF in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.invert, Ports.hide);
WITH c:TextModels.Context DO
Execute(c.ThisModel(), c.Pos(), end,Controllers.modify IN buttons)
ELSE Dialog.Beep
END
END
END Track;
(* StdView *)
PROCEDURE (v: StdView) Externalize (VAR wr: Stores.Writer);
BEGIN
v.Externalize^(wr);
wr.WriteVersion(maxStdVersion)
END Externalize;
PROCEDURE (v: StdView) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER;
BEGIN
v.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, maxStdVersion, thisVersion)
END Internalize;
PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
CONST u = point;
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; color: Ports.Color;
size, d, w, asc, dsc, fw: INTEGER; s: ARRAY 2 OF CHAR;
BEGIN
ASSERT(v.context # NIL, 20);
c := v.context;
WITH c: TextModels.Context DO a := c.Attr(); font := a.font; color := a.color
ELSE font := Fonts.dir.Default(); color := Ports.defaultColor
END;
font.GetBounds(asc, dsc, fw);
size := asc + dsc; d := size DIV 2;
f.DrawOval(u, 0, u + size, size, Ports.fill, color);
s := "!";
w := font.StringWidth(s);
f.DrawString(u + d - w DIV 2, size - dsc, Ports.background, s, font)
END Restore;
PROCEDURE (v: StdView) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH msg: Controllers.TrackMsg DO
Track(v, f, msg.x, msg.y, msg.modifiers)
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; asc, dsc, fw: INTEGER;
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.SizePref DO
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr(); font := a.font
ELSE font := Fonts.dir.Default()
END;
font.GetBounds(asc, dsc, fw);
msg.h := asc + dsc; msg.w := msg.h + 2 * point
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: Properties.FocusPref DO
msg.hotFocus := TRUE
| msg: TextSetters.Pref DO
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr(); font := a.font
ELSE font := Fonts.dir.Default()
END;
font.GetBounds(asc, msg.dsc, fw)
| msg: Properties.TypePref DO
IF Services.Is(v, msg.type) THEN msg.view := v END
ELSE
END
ELSE
END
END HandlePropMsg;
(* StdEndView *)
PROCEDURE (v: StdEndView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
CONST u = point;
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; color: Ports.Color;
size, asc, dsc, fw: INTEGER;
points: ARRAY 3 OF Ports.Point;
BEGIN
ASSERT(v.context # NIL, 20);
c := v.context;
WITH c: TextModels.Context DO a := c.Attr(); font := a.font; color := a.color
ELSE font := Fonts.dir.Default(); color := Ports.defaultColor
END;
font.GetBounds(asc, dsc, fw);
size := asc + dsc;
points[0].x := 0; points[0].y := size;
points[1].x := u + (size DIV 2); points[1].y := size DIV 2;
points[2].x := u + (size DIV 2); points[2].y := size;
f.DrawPath(points, 3, Ports.fill, color, Ports.closedPoly)
END Restore;
PROCEDURE (v: StdEndView) HandlePropMsg (VAR msg: Properties.Message);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; asc, dsc, fw: INTEGER;
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.SizePref DO
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr(); font := a.font
ELSE font := Fonts.dir.Default()
END;
font.GetBounds(asc, dsc, fw);
msg.h := asc + dsc; msg.w := (msg.h + 2 * point) DIV 2
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: Properties.FocusPref DO
msg.hotFocus := TRUE
| msg: TextSetters.Pref DO
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr(); font := a.font
ELSE font := Fonts.dir.Default()
END;
font.GetBounds(asc, msg.dsc, fw)
| msg: Properties.TypePref DO
IF Services.Is(v, msg.type) THEN msg.view := v END
ELSE
END
ELSE
END
END HandlePropMsg;
(* StdDirectory *)
PROCEDURE (d: StdDirectory) New (): View;
VAR v: StdView;
BEGIN
NEW(v); RETURN v
END New;
PROCEDURE (d: StdDirectory) NewEnd (): EndView;
VAR v: StdEndView;
BEGIN
NEW(v); RETURN v
END NewEnd;
PROCEDURE Deposit*;
BEGIN
Views.Deposit(dir.New())
END Deposit;
PROCEDURE DepositEnd*;
BEGIN
Views.Deposit(dir.NewEnd())
END DepositEnd;
PROCEDURE SetDir* (d: Directory);
BEGIN
dir := d
END SetDir;
PROCEDURE Init;
VAR d: StdDirectory;
BEGIN
NEW(d); dir := d; stdDir := d;
NEW(cleaner); cleanerInstalled := FALSE;
END Init;
BEGIN
Init
END DevCommanders.
| Dev/Mod/Commanders.odc |
MODULE DevCompiler;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, A.A. Dmitriev, I.A. Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, signatures added to defopt
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150527, center #53, support for empty text in CompileText
- 20160907, center #129, command for generating a compile list for a set of subsystems
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 20170612, center #160, outdated link to OP2.Paper.ps
- 20210709, dia, comAware always true
- 20210720, ad, use StdLibrarian
"
issues = "
-
"
**)
IMPORT Kernel,
Files, Strings, Views, Dialog, Controls, Utf, Librarian, Converters,
TextModels, TextMappers, TextViews, TextControllers,
StdLog,
DevMarkers, DevCommanders, DevSelectors,
DevCPM, DevCPT, DevCPB, DevCPP, DevCPE, DevCPV := DevCPV486, DevCPS;
CONST
(* compiler options: *)
checks = 0; allchecks = 1; assert = 2; obj = 3; ref = 4;
allref = 5; srcpos = 6; reallib = 7; signatures = 8;
hint = 29; oberon = 30; errorTrap = 31;
defopt = {checks, assert, obj, ref, allref, srcpos, signatures};
(* additional scanner types *)
module = 101; comEnd = 104;
(* symbol values *)
comma = 20; rbrak = 24; lbrak = 41; becomes = 44; ident = 48; semicolon = 49;
import = 74; moduleSym = 75; eof = 76;
TYPE
String = POINTER TO ARRAY OF CHAR;
NameNode = POINTER TO RECORD next: NameNode; name: String END;
VAR
sourceR: TextModels.Reader;
s: TextMappers.Scanner;
str: Dialog.String;
found: BOOLEAN; (* DevComDebug was found -> DTC *)
select: ARRAY 16 OF CHAR; (* filter for filenames in subsystems *)
PROCEDURE Module (source: TextModels.Reader; opt: SET; log: TextModels.Model; VAR error: BOOLEAN);
VAR ext, new: BOOLEAN; p: DevCPT.Node;
BEGIN
DevCPM.Init(source, log);
(* IF found THEN *) INCL(DevCPM.options, DevCPM.comAware); (* END; *)
IF errorTrap IN opt THEN INCL(DevCPM.options, DevCPM.trap) END;
IF oberon IN opt THEN INCL(DevCPM.options, DevCPM.oberon) END;
DevCPT.Init(opt);
DevCPB.typSize := DevCPV.TypeSize;
DevCPT.processor := DevCPV.processor;
DevCPP.Module(p);
IF DevCPM.noerr THEN
IF DevCPT.libName # "" THEN EXCL(opt, obj) END;
(*
IF errorTrap IN opt THEN DevCPDump.DumpTree(p) END;
*)
DevCPV.Init(opt); DevCPV.Allocate; DevCPT.Export(ext, new);
IF DevCPM.noerr & (obj IN opt) THEN
DevCPV.Module(p)
END;
DevCPV.Close
END;
IF DevCPM.noerr & (new OR ext) THEN DevCPM.RegisterNewSym
ELSE DevCPM.DeleteNewSym
END;
DevCPT.Close;
error := ~DevCPM.noerr;
DevCPM.Close;
p := NIL;
Kernel.FastCollect;
IF error THEN
DevCPM.InsertMarks(source.Base());
DevCPM.LogWLn; DevCPM.LogWStr(" ");
IF DevCPM.errors = 1 THEN
Dialog.MapString("#Dev:OneErrorDetected", str)
ELSE
DevCPM.LogWNum(DevCPM.errors, 0); Dialog.MapString("#Dev:ErrorsDetected", str)
END;
StdLog.String(str)
ELSE
IF hint IN opt THEN DevCPM.InsertMarks(source.Base()) END;
DevCPM.LogWStr(" "); DevCPM.LogWNum(DevCPE.pc, 8);
DevCPM.LogWStr(" "); DevCPM.LogWNum(DevCPE.dsize, 8)
END;
DevCPM.LogWLn
END Module;
PROCEDURE Scan (VAR s: TextMappers.Scanner);
BEGIN
s.Scan;
IF s.type = TextMappers.string THEN
IF s.string = "MODULE" THEN s.type := module END
ELSIF s.type = TextMappers.char THEN
IF s.char = "(" THEN
IF s.rider.char = "*" THEN
s.rider.Read;
REPEAT Scan(s) UNTIL (s.type = TextMappers.eot) OR (s.type = comEnd);
Scan(s)
END
ELSIF s.char = "*" THEN
IF s.rider.char = ")" THEN s.rider.Read; s.type := comEnd END
END
END
END Scan;
PROCEDURE Do (source, log: TextModels.Model; beg: INTEGER; opt: SET; VAR error: BOOLEAN);
VAR s: TextMappers.Scanner;
BEGIN
Dialog.MapString("#Dev:Compiling", str);
StdLog.String(str); StdLog.Char(" ");
s.ConnectTo(source); s.SetPos(beg);
Scan(s);
WHILE (s.type # TextMappers.eot) & (s.type # module) DO Scan(s) END;
IF s.type = module THEN
Scan(s);
IF s.type = TextMappers.string THEN
StdLog.Char('"'); StdLog.String(s.string); StdLog.Char('"')
END
END;
sourceR := source.NewReader(NIL); sourceR.SetPos(beg);
Module(sourceR, opt, log, error)
END Do;
PROCEDURE Open;
BEGIN
Dialog.ShowStatus("#Dev:Compiling");
StdLog.buf.Delete(0, StdLog.buf.Length())
END Open;
PROCEDURE Close;
BEGIN
StdLog.text.Append(StdLog.buf);
IF DevCPM.noerr THEN Dialog.ShowStatus("#Dev:Ok")
END;
sourceR := NIL;
Kernel.Cleanup
END Close;
PROCEDURE Compile*;
VAR t: TextModels.Model; error: BOOLEAN;
BEGIN
Open;
t := TextViews.FocusText();
IF t # NIL THEN
Do(t, StdLog.text, 0, defopt, error);
IF error THEN DevMarkers.ShowFirstError(t, TextViews.focusOnly) END
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END;
Close
END Compile;
PROCEDURE CompileOpt* (opt: ARRAY OF CHAR);
VAR t: TextModels.Model; error: BOOLEAN; i: INTEGER; opts: SET;
BEGIN
i := 0; opts := defopt;
WHILE opt[i] # 0X DO
IF opt[i] = "-" THEN
IF srcpos IN opts THEN EXCL(opts, srcpos)
ELSIF allref IN opts THEN EXCL(opts, allref)
ELSIF ref IN opts THEN EXCL(opts, ref)
ELSE EXCL(opts, obj)
END
ELSIF opt[i] = "!" THEN
IF assert IN opts THEN EXCL(opts, assert)
ELSE EXCL(opts, checks)
END
ELSIF opt[i] = "+" THEN INCL(opts, allchecks)
ELSIF opt[i] = "?" THEN INCL(opts, hint)
ELSIF opt[i] = "@" THEN INCL(opts, errorTrap)
ELSIF opt[i] = "$" THEN INCL(opts, oberon)
END;
INC(i)
END;
Open;
t := TextViews.FocusText();
IF t # NIL THEN
Do(t, StdLog.text, 0, opts, error);
IF error THEN DevMarkers.ShowFirstError(t, TextViews.focusOnly) END
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END;
Close
END CompileOpt;
PROCEDURE CompileText* (text: TextModels.Model; beg: INTEGER; OUT error: BOOLEAN);
BEGIN
ASSERT(text # NIL, 20); ASSERT((beg >= 0) & (beg <= text.Length()), 21);
Open;
Do(text, StdLog.text, beg, defopt, error);
IF error THEN DevMarkers.ShowFirstError(text, TextViews.focusOnly) END;
Close
END CompileText;
PROCEDURE CompileAndUnload*;
VAR t: TextModels.Model; error: BOOLEAN; mod: Kernel.Module;
n: ARRAY LEN(DevCPT.Name) OF CHAR; res: INTEGER;
BEGIN
Open;
t := TextViews.FocusText();
IF t # NIL THEN
Do(t, StdLog.text, 0, defopt, error);
IF error THEN DevMarkers.ShowFirstError(t, TextViews.focusOnly)
ELSE
Utf.Utf8ToString(DevCPT.SelfName, n, res);
mod := Kernel.ThisLoadedMod(n);
IF mod # NIL THEN
Kernel.UnloadMod(mod);
Utf.Utf8ToString(DevCPT.SelfName, n, res);
IF mod.refcnt < 0 THEN
Dialog.MapParamString("#Dev:Unloaded", n, "", "", str);
StdLog.String(str); StdLog.Ln;
Controls.Relink
ELSE
Dialog.MapParamString("#Dev:UnloadingFailed", n, "", "", str);
StdLog.String(str); StdLog.Ln
END
END
END
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END;
Close
END CompileAndUnload;
PROCEDURE CompileSelection*;
VAR c: TextControllers.Controller; t: TextModels.Model; beg, end: INTEGER; error: BOOLEAN;
BEGIN
Open;
c := TextControllers.Focus();
IF c # NIL THEN
t := c.text;
IF c.HasSelection() THEN
c.GetSelection(beg, end); Do(t, StdLog.text, beg, defopt, error);
IF error THEN DevMarkers.ShowFirstError(t, TextViews.focusOnly) END
ELSE Dialog.ShowMsg("#Dev:NoSelectionFound")
END
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END;
Close
END CompileSelection;
PROCEDURE GetSource (IN mod: ARRAY OF CHAR; OUT v: Views.View;
OUT loc: Files.Locator; OUT fname: Files.Name; OUT conv: Converters.Converter);
BEGIN
Librarian.lib.GetSpec(mod, "Mod", loc, fname);
IF loc # NIL THEN v := Views.Old(Views.dontAsk, loc, fname, conv) END
END GetSource;
PROCEDURE CompileList (beg, end: INTEGER; c: TextControllers.Controller);
VAR v: Views.View; i: INTEGER; error, one: BOOLEAN; name: Files.Name;
conv: Converters.Converter;
loc: Files.Locator; t: TextModels.Model; opts: SET; title, entry: ARRAY 64 OF CHAR;
BEGIN
s.SetPos(beg); s.Scan; one := FALSE;
WHILE (s.start < end) & (s.type = TextMappers.string) & (s.len < LEN(name)) DO
s.Scan; one := TRUE;
WHILE (s.start < end) & (s.type = TextMappers.char) &
((s.char = "-") OR (s.char = "+") OR (s.char = "!")
OR (s.char = "*") OR (s.char = "?") OR (s.char = "^") OR (s.char = "("))
DO
IF s.char = "(" THEN
WHILE (s.start < end) & ((s.type # TextMappers.char) OR (s.char # ")")) DO
s.Scan
END
END;
s.Scan
END
END;
IF one & (s.start >= end) THEN
s.SetPos(beg); s.Scan; error := FALSE;
WHILE (s.start < end) & (s.type = TextMappers.string) & ~error DO
i := 0; WHILE i < LEN(name) DO name[i] := 0X; INC(i) END;
t := NIL;
GetSource(s.string, v, loc, name, conv);
IF (loc # NIL) & (loc.res = 0) THEN
IF v # NIL THEN
WITH v: TextViews.View DO
t := v.ThisModel()
ELSE
Dialog.ShowParamMsg("#Dev:NoTextFileFound", name, "", ""); error := TRUE
END
ELSE
Dialog.ShowParamMsg("#Dev:CannotOpenFile", name, "", ""); error := TRUE
END
ELSE
Dialog.ShowParamMsg("#System:FileNotFound", name, "", ""); error := TRUE;
v := NIL;
END;
s.Scan; opts := defopt;
WHILE (s.start < end) & (s.type = TextMappers.char) DO
IF s.char = "-" THEN
IF srcpos IN opts THEN EXCL(opts, srcpos)
ELSIF allref IN opts THEN EXCL(opts, allref)
ELSIF ref IN opts THEN EXCL(opts, ref)
ELSE EXCL(opts, obj)
END
ELSIF s.char = "!" THEN
IF assert IN opts THEN EXCL(opts, assert)
ELSE EXCL(opts, checks)
END
ELSIF s.char = "+" THEN INCL(opts, allchecks)
ELSIF s.char = "?" THEN INCL(opts, hint)
ELSIF s.char = "@" THEN INCL(opts, errorTrap)
ELSIF s.char = "$" THEN INCL(opts, oberon)
ELSIF s.char = "(" THEN
s.Scan;
WHILE (s.start < end) & (s.type = TextMappers.string) DO
title := s.string$; s.Scan;
IF (s.start < end) & (s.type = TextMappers.char) & (s.char = ":") THEN
s.Scan;
IF (s.start < end) & (s.type = TextMappers.string) THEN
entry := s.string$; s.Scan;
IF t # NIL THEN DevSelectors.ChangeTo(t, title, entry) END
END
END;
IF (s.start < end) & (s.type = TextMappers.char) & (s.char = ",") THEN
s.Scan
END
END
END;
s.Scan
END;
IF t # NIL THEN
Do(t, StdLog.text, 0, opts, error)
END
END
ELSE Dialog.ShowMsg("#Dev:NotOnlyFileNames")
END;
s.ConnectTo(NIL);
IF error & (c # NIL) & c.HasSelection() & (s.start < end) THEN
c.SetSelection(s.start, end)
END;
IF error & (v # NIL) THEN
Views.Open(v, loc, name, conv);
DevMarkers.ShowFirstError(t, TextViews.any)
END
END CompileList;
PROCEDURE CompileModuleList*;
VAR c: TextControllers.Controller; beg, end: INTEGER;
BEGIN
Open;
c := TextControllers.Focus();
IF c # NIL THEN
s.ConnectTo(c.text);
IF c.HasSelection() THEN c.GetSelection(beg, end)
ELSE beg := 0; end := c.text.Length()
END;
CompileList(beg, end, c)
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END;
Close
END CompileModuleList;
PROCEDURE CompileThis*;
VAR p: DevCommanders.Par; beg, end: INTEGER;
BEGIN
Open;
p := DevCommanders.par;
IF p # NIL THEN
DevCommanders.par := NIL;
s.ConnectTo(p.text); beg := p.beg; end := p.end;
CompileList(beg, end, NIL)
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END;
Close
END CompileThis;
PROCEDURE ContainsName(list: NameNode; IN name: ARRAY OF CHAR): BOOLEAN;
BEGIN
WHILE (list # NIL) & (list.name^ # name) DO list := list.next END;
RETURN list # NIL
END ContainsName;
PROCEDURE NewName(IN name: ARRAY OF CHAR): NameNode;
VAR n: NameNode;
BEGIN NEW(n); NEW(n.name, LEN(name$) + 1); n.name^ := name$; RETURN n
END NewName;
PROCEDURE AppendName(VAR list: NameNode; IN name: ARRAY OF CHAR);
VAR n, last: NameNode;
BEGIN
n := NewName(name);
IF list = NIL THEN list := n
ELSE last := list; WHILE last.next # NIL DO last := last.next END; last.next := n
END
END AppendName;
PROCEDURE CheckSym(VAR sym: BYTE; expected: SHORTINT);
BEGIN
IF sym = expected THEN DevCPS.Get(sym) ELSE DevCPM.err(expected) END
END CheckSym;
PROCEDURE MakeFile (subList, importPath: NameNode; VAR fileList: NameNode;
loc: Files.Locator; IN sub, file: ARRAY OF CHAR);
VAR v: Views.View; source: TextModels.Model; sym: BYTE;
fileName, impName, fname_: Files.Name; importList: NameNode;
impNameUtf8: DevCPT.Name; res: INTEGER; p: NameNode;
conv: Converters.Converter;
PROCEDURE ProcessFile;
VAR import: NameNode; impSub, impFile: Files.Name;
BEGIN
p := NewName(fileName); p.next := importPath; importPath := p; (* push *)
import := importList;
WHILE import # NIL DO
Librarian.lib.SplitName(import.name, impSub, impFile);
IF ContainsName(subList, impSub) & ~ContainsName(fileList, import.name) THEN
MakeFile(subList, importPath, fileList, Files.dir.This(impSub + "/Mod"), impSub, impFile)
END;
import := import.next
END;
IF ~ContainsName(fileList, fileName) THEN
AppendName(fileList, fileName)
END;
END ProcessFile;
PROCEDURE Terminate;
BEGIN
DevCPM.InsertMarks(source); Views.Open(v, loc, file$, NIL);
DevMarkers.ShowFirstError(source, TextViews.any); DevCPM.Close;
HALT(128) (* silent halt *)
END Terminate;
BEGIN
IF sub # "System" THEN fileName := sub + file ELSE fileName := file$ END;
GetSource(fileName, v, loc, fname_, conv);
IF v # NIL THEN
WITH v: TextViews.View DO
source := v.ThisModel();
DevCPM.Init(source.NewReader(NIL), StdLog.text); DevCPS.Init;
DevCPS.Get(sym);
IF sym = moduleSym THEN DevCPS.Get(sym);
IF sym = ident THEN
DevCPS.Get(sym);
IF sym = lbrak THEN
REPEAT DevCPS.Get(sym) UNTIL (sym = rbrak) OR (sym = eof);
CheckSym(sym, rbrak)
END;
CheckSym(sym, semicolon);
p := NewName(fileName); p.next := importPath; importPath := p; (* push *)
importList := NIL;
(* compiler cannot be invoked recursively; therefore we use an auxiliary list *)
IF sym = import THEN DevCPS.Get(sym);
LOOP
IF sym = ident THEN
impNameUtf8 := DevCPS.name$; DevCPS.Get(sym);
IF sym = becomes THEN DevCPS.Get(sym);
IF sym = ident THEN
impNameUtf8 := DevCPS.name$; DevCPS.Get(sym);
ELSE
DevCPM.err(ident)
END
END;
Utf.Utf8ToString(impNameUtf8, impName, res); ASSERT(res = 0);
IF ContainsName(importPath, impName) THEN
DevCPM.err(154)
ELSIF (impName # "SYSTEM") & (impName # "COM") THEN
AppendName(importList, impName)
END
ELSE DevCPM.err(ident)
END;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF sym = ident THEN DevCPM.err(comma)
ELSE EXIT
END
END; (* LOOP *)
CheckSym(sym, semicolon)
END
ELSE DevCPM.err(ident)
END;
IF DevCPM.noerr THEN
ProcessFile; importPath := importPath.next (* pop *)
ELSE
Terminate
END
(* ELSE ignore non module texts *)
END
(* ELSE ignore non text files *)
END
ELSE Dialog.ShowParamMsg("#Dev:SourcefileNotFound", fileName, "", "");
AppendName(fileList, fileName); (* report missing module only once *)
END
END MakeFile;
PROCEDURE MakeSubsystem(subList: NameNode; VAR fileList: NameNode;
IN sub: ARRAY OF CHAR);
VAR loc: Files.Locator; files: Files.FileInfo; importPath: NameNode;
pos1, pos2: INTEGER;
BEGIN
loc := Files.dir.This(sub + "/Mod");
files := Files.dir.FileList(loc);
WHILE files # NIL DO
IF (files.type = Files.docType) OR (files.type = "cp") THEN
(* strip off extension, note: file name may differ from module name *)
files.name[LEN(files.name$) - LEN(files.type$) - 1] := 0X;
importPath := NIL;
IF select = "" THEN
MakeFile(subList, importPath, fileList, loc, sub, files.name)
ELSE
Strings.Find(files.name, "__", 1, pos1);
IF pos1 > 0 THEN
Strings.Find(files.name, select, pos1 + 2, pos2);
IF pos2 = pos1 + 2 THEN
MakeFile(subList, importPath, fileList, loc, sub, files.name)
END
ELSE
MakeFile(subList, importPath, fileList, loc, sub, files.name)
END
END;
(* ELSE ignore e.g. temporary files *)
END;
files := files.next
END
END MakeSubsystem;
PROCEDURE AppendSubs(VAR subList: NameNode; IN excl: ARRAY OF CHAR);
VAR dirs: Files.LocInfo; i, pos: INTEGER;
BEGIN
dirs := Files.dir.LocList(Files.dir.This(""));
WHILE dirs # NIL DO (* check first if this directory name is a possible subsystem *)
IF Strings.IsIdentStart(dirs.name[0]) THEN i := 1;
WHILE Strings.IsIdent(dirs.name[i]) DO INC(i) END;
IF dirs.name[i] = 0X THEN
Strings.Find(excl, ":" + dirs.name + ":", 0, pos);
IF pos < 0 THEN AppendName(subList, dirs.name) END
END
END;
dirs := dirs.next
END
END AppendSubs;
(* uses the compiler for analyzing module headers; terminates command in case of syntax error *)
PROCEDURE MakeSubsystems (OUT subList: NameNode; OUT fileList: NameNode);
CONST
noneSubs = ":Code:Docu:Sym:";
baseSubs = ":Com:Comm:Ctl:Dev:Form:Host:Obx:Ole:Sql:Std:System:Text:Win:Xhtml:";
VAR par: DevCommanders.Par; beg, end: INTEGER; s: TextMappers.Scanner;
sub: NameNode;
BEGIN
par := DevCommanders.par; subList := NIL; fileList := NIL; select := "";
IF par # NIL THEN
DevCommanders.par := NIL;
s.ConnectTo(par.text); beg := par.beg; end := par.end;
s.SetPos(beg); s.Scan;
WHILE (s.start < end)
& ((s.type = TextMappers.string) OR (s.type = TextMappers.char) & ((s.char = "+") OR (s.char = "*") OR (s.char = "@"))) DO
IF s.type = TextMappers.string THEN
AppendName(subList, s.string)
ELSIF (s.char = "@") & (select = "") THEN
s.Scan;
IF s.type = TextMappers.string THEN
select := s.string$
END
ELSIF s.char = "+" THEN AppendSubs(subList, baseSubs + noneSubs)
ELSIF s.char = "*" THEN AppendSubs(subList, noneSubs)
END;
s.Scan;
END;
sub := subList;
WHILE sub # NIL DO
MakeSubsystem(subList, fileList, sub.name);
sub := sub.next
END;
DevCPM.Close
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END
END MakeSubsystems;
PROCEDURE MakeList*;
VAR subList: NameNode (* in textual order *); fileList: NameNode; (* in compile order *)
t: TextModels.Model; f: TextMappers.Formatter; v: TextViews.View;
file: NameNode; title: Views.Title; sub: NameNode; pos: INTEGER;
BEGIN
MakeSubsystems(subList, fileList);
t := TextModels.dir.New();
f.ConnectTo(t);
file := fileList;
WHILE file # NIL DO
f.WriteString(file.name); f.WriteLn; file := file.next
END;
v := TextViews.dir.New(t);
Dialog.MapString("#Dev:MakeList", title);
sub := subList;
WHILE (sub # NIL) & (LEN(title + " " + sub.name) < LEN(title)) DO
title := title + " " + sub.name; sub := sub.next
END;
IF sub # NIL THEN pos := MIN(LEN(Views.Title) - 4, LEN(title$));
title[pos] := "."; title[pos + 1] := "."; title[pos + 2] := "."; title[pos + 3] := 0X
END;
Views.OpenAux(v, title$)
END MakeList;
PROCEDURE CompileSubs*;
VAR subList: NameNode (* in textual order *); fileList: NameNode; (* in compile order *)
file: NameNode; loc: Files.Locator; name: Files.Name;
v: Views.View; t: TextModels.Model; error: BOOLEAN;
conv: Converters.Converter;
BEGIN
MakeSubsystems(subList, fileList);
file := fileList;
WHILE file # NIL DO
GetSource(file.name, v, loc, name, conv);
IF (v # NIL) & (v IS TextViews.View) THEN
t := v(TextViews.View).ThisModel();
Do(t, StdLog.text, 0, defopt, error);
IF error THEN
Views.Open(v, loc, name, conv);
DevMarkers.ShowFirstError(t, TextViews.any);
RETURN
END
END;
file := file.next
END
END CompileSubs;
END DevCompiler.
| Dev/Mod/Compiler.odc |
MODULE DevCPB;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems, Robert Campbell"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, NewString changed (Unicode support)
- 20070123, bh, CheckAssign changed to check procedure type sysflags
- 20070307, bh, added char to string conversion in LEN handling
- 20070300, bh, x.obj := NIL in ConstOp
- 20080202, bh, Real constant operations corrected (proposed by Robert Campbell)
- 20150422, center #39, checking illegal use of SYSTEM.ADR function
- 20150422, center #40, fixing concatenation of Unicode character constants
- 20160324, center #111, code cleanups
- 20160907, center #128, Assignment of named empty string to ARRAY OF SHORTCHAR does not work
- 20161220, center #141, Comparison of named empty string with array of SHORTCHAR does not work
- 20170612, center #160, outdated link to OP2.Paper.ps
- 20170712, center #165, adding a check for passing guarded function result as VAR parameter
- 20181111, center #191, Compiler trap by erroneous program
- 20190622, center #199, compiler trap with SYSTEM.ADR(BasicType)
- 20200623, center #208, ASSERT(FALSE) rejected by compiler
"
issues = "
- ...
"
**)
IMPORT DevCPT, DevCPM;
CONST
(* symbol values or ops *)
times = 1; slash = 2; div = 3; mod = 4;
and = 5; plus = 6; minus = 7; or = 8; eql = 9;
neq = 10; lss = 11; leq = 12; gtr = 13; geq = 14;
in = 15; is = 16; ash = 17; msk = 18; len = 19;
conv = 20; abs = 21; cap = 22; odd = 23; not = 33;
(*SYSTEM*)
adr = 24; cc = 25; bit = 26; lsh = 27; rot = 28; val = 29;
min = 34; max = 35; typfn = 36; size = 37;
(* object modes *)
Var = 1; VarPar = 2; Con = 3; Fld = 4; Typ = 5; LProc = 6; XProc = 7;
SProc = 8; CProc = 9; IProc = 10; Mod = 11; Head = 12; TProc = 13;
(* Structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; String16 = 17; Int64 = 18;
intSet = {Int8..Int32, Int64}; realSet = {Real32, Real64}; charSet = {Char8, Char16};
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(* nodes classes *)
Nvar = 0; Nvarpar = 1; Nfield = 2; Nderef = 3; Nindex = 4; Nguard = 5; Neguard = 6;
Nconst = 7; Ntype = 8; Nproc = 9; Nupto = 10; Nmop = 11; Ndop = 12; Ncall = 13;
Ninittd = 14; Nif = 15; Ncaselse = 16; Ncasedo = 17; Nenter = 18; Nassign = 19;
Nifelse = 20; Ncase = 21; Nwhile = 22; Nrepeat = 23; Nloop = 24; Nexit = 25;
Nreturn = 26; Nwith = 27; Ntrap = 28;
(*function number*)
assign = 0;
haltfn = 0; newfn = 1; absfn = 2; capfn = 3; ordfn = 4;
entierfn = 5; oddfn = 6; minfn = 7; maxfn = 8; chrfn = 9;
shortfn = 10; longfn = 11; sizefn = 12; incfn = 13; decfn = 14;
inclfn = 15; exclfn = 16; lenfn = 17; copyfn = 18; ashfn = 19; assertfn = 32;
lchrfn = 33; lentierfcn = 34; bitsfn = 37; bytesfn = 38;
(*SYSTEM function number*)
adrfn = 20; ccfn = 21; lshfn = 22; rotfn = 23;
getfn = 24; putfn = 25; getrfn = 26; putrfn = 27;
bitfn = 28; valfn = 29; sysnewfn = 30; movefn = 31;
thisrecfn = 45; thisarrfn = 46;
(* COM function number *)
validfn = 40; iidfn = 41; queryfn = 42;
(* module visibility of objects *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* procedure flags (conval.setval) *)
hasBody = 1; isRedef = 2; slNeeded = 3; imVar = 4;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval)*)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
(* case statement flags (conval.setval) *)
useTable = 1; useTree = 2;
(* sysflags *)
nilBit = 1; inBit = 2; outBit = 4; newBit = 8; iidBit = 16; interface = 10; jint = -11; jstr = -13;
AssertTrap = 0; (* default trap number *)
covarOut = FALSE;
VAR
typSize*: PROCEDURE(typ: DevCPT.Struct);
zero, one, two, dummy, quot: DevCPT.Const;
PROCEDURE err(n: SHORTINT);
BEGIN DevCPM.err(n)
END err;
PROCEDURE NewLeaf*(obj: DevCPT.Object): DevCPT.Node;
VAR node: DevCPT.Node; typ: DevCPT.Struct;
BEGIN
typ := obj.typ;
CASE obj.mode OF
Var:
node := DevCPT.NewNode(Nvar); node.readonly := (obj.vis = externalR) & (obj.mnolev < 0)
| VarPar:
node := DevCPT.NewNode(Nvarpar); node.readonly := obj.vis = inPar;
| Con:
node := DevCPT.NewNode(Nconst); node.conval := DevCPT.NewConst();
node.conval^ := obj.conval^ (* string is not copied, only its ref *)
| Typ:
node := DevCPT.NewNode(Ntype)
| LProc..IProc, TProc:
node := DevCPT.NewNode(Nproc)
ELSE err(127); node := DevCPT.NewNode(Nvar); typ := DevCPT.notyp
END ;
node.obj := obj; node.typ := typ;
RETURN node
END NewLeaf;
PROCEDURE Construct*(class: BYTE; VAR x: DevCPT.Node; y: DevCPT.Node);
VAR node: DevCPT.Node;
BEGIN
node := DevCPT.NewNode(class); node.typ := DevCPT.notyp;
node.left := x; node.right := y; x := node
END Construct;
PROCEDURE Link*(VAR x, last: DevCPT.Node; y: DevCPT.Node);
BEGIN
IF x = NIL THEN x := y ELSE last.link := y END ;
WHILE y.link # NIL DO y := y.link END ;
last := y
END Link;
PROCEDURE BoolToInt(b: BOOLEAN): INTEGER;
BEGIN
IF b THEN RETURN 1 ELSE RETURN 0 END
END BoolToInt;
PROCEDURE IntToBool(i: INTEGER): BOOLEAN;
BEGIN
RETURN i # 0
END IntToBool;
PROCEDURE NewBoolConst*(boolval: BOOLEAN): DevCPT.Node;
VAR x: DevCPT.Node;
BEGIN
x := DevCPT.NewNode(Nconst); x.typ := DevCPT.booltyp;
x.conval := DevCPT.NewConst(); x.conval.intval := BoolToInt(boolval); RETURN x
END NewBoolConst;
PROCEDURE OptIf*(VAR x: DevCPT.Node); (* x.link = NIL *)
VAR if, pred: DevCPT.Node;
BEGIN
if := x.left;
WHILE if.left.class = Nconst DO
IF IntToBool(if.left.conval.intval) THEN x := if.right; RETURN
ELSIF if.link = NIL THEN x := x.right; RETURN
ELSE if := if.link; x.left := if
END
END ;
pred := if; if := if.link;
WHILE if # NIL DO
IF if.left.class = Nconst THEN
IF IntToBool(if.left.conval.intval) THEN
pred.link := NIL; x.right := if.right; RETURN
ELSE if := if.link; pred.link := if
END
ELSE pred := if; if := if.link
END
END
END OptIf;
PROCEDURE Nil*(): DevCPT.Node;
VAR x: DevCPT.Node;
BEGIN
x := DevCPT.NewNode(Nconst); x.typ := DevCPT.niltyp;
x.conval := DevCPT.NewConst(); x.conval.intval := 0; RETURN x
END Nil;
PROCEDURE EmptySet*(): DevCPT.Node;
VAR x: DevCPT.Node;
BEGIN
x := DevCPT.NewNode(Nconst); x.typ := DevCPT.settyp;
x.conval := DevCPT.NewConst(); x.conval.setval := {}; RETURN x
END EmptySet;
PROCEDURE MarkAsUsed (node: DevCPT.Node);
VAR c: BYTE;
BEGIN
c := node.class;
WHILE (c = Nfield) OR (c = Nindex) OR (c = Nguard) OR (c = Neguard) DO node := node.left; c := node.class END;
IF (c = Nvar) & (node.obj.mnolev > 0) THEN node.obj.used := TRUE END
END MarkAsUsed;
PROCEDURE GetTempVar* (IN name: ARRAY OF SHORTCHAR; typ: DevCPT.Struct; VAR obj: DevCPT.Object);
VAR n: DevCPT.Name; o: DevCPT.Object;
BEGIN
n := "@@ "; DevCPT.Insert(n, obj); obj.name^ := name$; (* avoid err 1 *)
obj.mode := Var; obj.typ := typ;
o := DevCPT.topScope.scope;
IF o = NIL THEN DevCPT.topScope.scope := obj
ELSE
WHILE o.link # NIL DO o := o.link END;
o.link := obj
END
END GetTempVar;
(* ---------- constant operations ---------- *)
PROCEDURE Log (x: DevCPT.Node): INTEGER;
VAR val, exp: INTEGER;
BEGIN
exp := 0;
IF x.typ.form = Int64 THEN
RETURN -1
ELSE
val := x.conval.intval;
IF val > 0 THEN
WHILE ~ODD(val) DO val := val DIV 2; INC(exp) END
END;
IF val # 1 THEN exp := -1 END
END;
RETURN exp
END Log;
PROCEDURE Floor (x: REAL): REAL;
VAR y: REAL;
BEGIN
IF ABS(x) > 9007199254740992.0 (* 2^53 *) THEN RETURN x
ELSIF (x >= MAX(INTEGER) + 1.0) OR (x < MIN(INTEGER)) THEN
y := Floor(x / (MAX(INTEGER) + 1.0)) * (MAX(INTEGER) + 1.0);
RETURN SHORT(ENTIER(x - y)) + y
ELSE RETURN SHORT(ENTIER(x))
END
END Floor;
PROCEDURE SetToInt (s: SET): INTEGER;
VAR x, i: INTEGER;
BEGIN
i := 31; x := 0;
IF 31 IN s THEN x := -1 END;
WHILE i > 0 DO
x := x * 2; DEC(i);
IF i IN s THEN INC(x) END
END;
RETURN x
END SetToInt;
PROCEDURE IntToSet (x: INTEGER): SET;
VAR i: INTEGER; s: SET;
BEGIN
i := 0; s := {};
WHILE i < 32 DO
IF ODD(x) THEN INCL(s, i) END;
x := x DIV 2; INC(i)
END;
RETURN s
END IntToSet;
PROCEDURE GetConstType (x: DevCPT.Const; form: INTEGER; errno: SHORTINT; VAR typ: DevCPT.Struct);
CONST MAXL = 9223372036854775808.0; (* 2^63 *)
BEGIN
IF (form IN intSet + charSet) & (x.realval + x.intval >= MIN(INTEGER))
& (x.realval + x.intval <= MAX(INTEGER)) THEN
x.intval := SHORT(ENTIER(x.realval + x.intval)); x.realval := 0
END;
IF form IN intSet THEN
IF x.realval = 0 THEN typ := DevCPT.int32typ
ELSIF (x.intval >= -MAXL - x.realval) & (x.intval < MAXL - x.realval) THEN typ := DevCPT.int64typ
ELSE err(errno); x.intval := 1; x.realval := 0; typ := DevCPT.int32typ
END
ELSIF form IN realSet THEN (* SR *)
typ := DevCPT.real64typ
ELSIF form IN charSet THEN
IF x.intval <= 255 THEN typ := DevCPT.char8typ
ELSE typ := DevCPT.char16typ
END
ELSE typ := DevCPT.undftyp
END
END GetConstType;
PROCEDURE CheckConstType (x: DevCPT.Const; form: INTEGER; errno: SHORTINT);
VAR type: DevCPT.Struct;
BEGIN
GetConstType(x, form, errno, type);
IF ~DevCPT.Includes(form, type.form)
& ((form # Int8) OR (x.realval # 0) OR (x.intval < -128) OR (x.intval > 127))
& ((form # Int16) OR (x.realval # 0) OR (x.intval < -32768) OR (x.intval > 32767))
& ((form # Real32) OR (ABS(x.realval) > DevCPM.MaxReal32) & (ABS(x.realval) # DevCPM.InfReal)) THEN
err(errno); x.intval := 1; x.realval := 0
END
END CheckConstType;
PROCEDURE ConvConst (x: DevCPT.Const; from, to: INTEGER);
VAR sr: SHORTREAL;
BEGIN
IF from = Set THEN
x.intval := SetToInt(x.setval); x.realval := 0; x.setval := {};
ELSIF from IN intSet + charSet THEN
IF to = Set THEN CheckConstType(x, Int32, 203); x.setval := IntToSet(x.intval)
ELSIF to IN intSet THEN CheckConstType(x, to, 203)
ELSIF to IN realSet THEN x.realval := x.realval + x.intval; x.intval := DevCPM.ConstNotAlloc
ELSE (*to IN charSet*) CheckConstType(x, to, 220)
END
ELSIF from IN realSet THEN
IF to IN realSet THEN CheckConstType(x, to, 203);
IF to = Real32 THEN sr := SHORT(x.realval); x.realval := sr END (* reduce precision *)
ELSE x.realval := Floor(x.realval); x.intval := 0; CheckConstType(x, to, 203)
END
END
END ConvConst;
PROCEDURE Prepare (x: DevCPT.Const);
VAR r: REAL;
BEGIN
x.realval := x.realval + x.intval DIV 32768 * 32768;
x.intval := x.intval MOD 32768;
r := Floor(x.realval / 4096) * 4096;
x.intval := x.intval + SHORT(ENTIER(x.realval - r));
x.realval := r
(* ABS(x.intval) < 2^15 & ABS(x.realval) MOD 2^12 = 0 *)
END Prepare;
PROCEDURE AddConst (x, y, z: DevCPT.Const; VAR type: DevCPT.Struct); (* z := x + y *)
BEGIN
IF type.form IN intSet THEN
Prepare(x); Prepare(y);
z.intval := x.intval + y.intval; z.realval := x.realval + y.realval
ELSIF type.form IN realSet THEN
IF (ABS(x.realval) = DevCPM.InfReal) & (x.realval = - y.realval) THEN err(212)
ELSE z.realval := x.realval + y.realval
END
ELSE HALT(100)
END;
GetConstType(z, type.form, 206, type)
END AddConst;
PROCEDURE NegateConst (y, z: DevCPT.Const; VAR type: DevCPT.Struct); (* z := - y *)
BEGIN
IF type.form IN intSet THEN Prepare(y); z.intval := -y.intval; z.realval := -y.realval
ELSIF type.form IN realSet THEN z.realval := -y.realval
ELSE HALT(100)
END;
GetConstType(z, type.form, 207, type)
END NegateConst;
PROCEDURE SubConst (x, y, z: DevCPT.Const; VAR type: DevCPT.Struct); (* z := x - y *)
BEGIN
IF type.form IN intSet THEN
Prepare(x); Prepare(y);
z.intval := x.intval - y.intval; z.realval := x.realval - y.realval
ELSIF type.form IN realSet THEN
IF (ABS(x.realval) = DevCPM.InfReal) & (x.realval = y.realval) THEN err(212)
ELSE z.realval := x.realval - y.realval
END
ELSE HALT(100)
END;
GetConstType(z, type.form, 207, type)
END SubConst;
PROCEDURE MulConst (x, y, z: DevCPT.Const; VAR type: DevCPT.Struct); (* z := x * y *)
BEGIN
IF type.form IN intSet THEN
Prepare(x); Prepare(y);
z.realval := x.realval * y.realval + x.intval * y.realval + x.realval * y.intval;
z.intval := x.intval * y.intval
ELSIF type.form IN realSet THEN
IF (ABS(x.realval) = DevCPM.InfReal) & ( y.realval = 0.0) THEN err(212)
ELSIF (ABS(y.realval) = DevCPM.InfReal) & (x.realval = 0.0) THEN err(212)
ELSE z.realval := x.realval * y.realval
END
ELSE HALT(100)
END;
GetConstType(z, type.form, 204, type)
END MulConst;
PROCEDURE DivConst (x, y, z: DevCPT.Const; VAR type: DevCPT.Struct); (* z := x / y *)
BEGIN
IF type.form IN realSet THEN
IF (x.realval = 0.0) & (y.realval = 0.0) THEN err(212)
ELSIF (ABS(x.realval) = DevCPM.InfReal) & (ABS(y.realval) = DevCPM.InfReal) THEN err(212)
ELSE z.realval := x.realval / y.realval
END
ELSE HALT(100)
END;
GetConstType(z, type.form, 204, type)
END DivConst;
PROCEDURE DivModConst (x, y: DevCPT.Const; div: BOOLEAN; VAR type: DevCPT.Struct);
(* x := x DIV y | x MOD y *)
BEGIN
IF type.form IN intSet THEN
IF y.realval + y.intval # 0 THEN
Prepare(x); Prepare(y);
quot.realval := Floor((x.realval + x.intval) / (y.realval + y.intval));
quot.intval := 0; Prepare(quot);
x.realval := x.realval - quot.realval * y.realval - quot.realval * y.intval - quot.intval * y.realval;
x.intval := x.intval - quot.intval * y.intval;
IF y.realval + y.intval > 0 THEN
WHILE x.realval + x.intval > 0 DO SubConst(x, y, x, type); INC(quot.intval) END;
WHILE x.realval + x.intval < 0 DO AddConst(x, y, x, type); DEC(quot.intval) END
ELSE
WHILE x.realval + x.intval < 0 DO SubConst(x, y, x, type); INC(quot.intval) END;
WHILE x.realval + x.intval > 0 DO AddConst(x, y, x, type); DEC(quot.intval) END
END;
IF div THEN x.realval := quot.realval; x.intval := quot.intval END;
GetConstType(x, type.form, 204, type)
ELSE err(205)
END
ELSE HALT(100)
END
END DivModConst;
PROCEDURE EqualConst (x, y: DevCPT.Const; form: INTEGER): BOOLEAN; (* x = y *)
VAR res: BOOLEAN;
BEGIN
CASE form OF
| Undef: res := TRUE
| Bool, Byte, Char8..Int32, Char16: res := x.intval = y.intval
| Int64: Prepare(x); Prepare(y); res := (x.realval - y.realval) + (x.intval - y.intval) = 0
| Real32, Real64: res := x.realval = y.realval
| Set: res := x.setval = y.setval
| String8, String16, Comp (* guid *): res := x.ext^ = y.ext^
| NilTyp, Pointer, ProcTyp: res := x.intval = y.intval
END;
RETURN res
END EqualConst;
PROCEDURE LessConst (x, y: DevCPT.Const; form: INTEGER): BOOLEAN; (* x < y *)
VAR res: BOOLEAN;
BEGIN
CASE form OF
| Undef: res := TRUE
| Byte, Char8..Int32, Char16: res := x.intval < y.intval
| Int64: Prepare(x); Prepare(y); res := (x.realval - y.realval) + (x.intval - y.intval) < 0
| Real32, Real64: res := x.realval < y.realval
| String8, String16: res := x.ext^ < y.ext^
| Bool, Set, NilTyp, Pointer, ProcTyp, Comp: err(108)
END;
RETURN res
END LessConst;
PROCEDURE IsNegConst (x: DevCPT.Const; form: INTEGER): BOOLEAN; (* x < 0 OR x = (-0.0) *)
VAR res: BOOLEAN;
BEGIN
CASE form OF
| Int8..Int32: res := x.intval < 0
| Int64: Prepare(x); res := x.realval + x.intval < 0
| Real32, Real64: res := (x.realval <= 0.) & (1. / x.realval <= 0.)
END;
RETURN res
END IsNegConst;
PROCEDURE NewIntConst*(intval: INTEGER): DevCPT.Node;
VAR x: DevCPT.Node;
BEGIN
x := DevCPT.NewNode(Nconst); x.conval := DevCPT.NewConst();
x.conval.intval := intval; x.conval.realval := 0; x.typ := DevCPT.int32typ; RETURN x
END NewIntConst;
PROCEDURE NewLargeIntConst* (intval: INTEGER; realval: REAL): DevCPT.Node;
VAR x: DevCPT.Node;
BEGIN
x := DevCPT.NewNode(Nconst); x.conval := DevCPT.NewConst();
x.conval.intval := intval; x.conval.realval := realval; x.typ := DevCPT.int64typ; RETURN x
END NewLargeIntConst;
PROCEDURE NewRealConst*(realval: REAL; typ: DevCPT.Struct): DevCPT.Node;
VAR x: DevCPT.Node;
BEGIN
x := DevCPT.NewNode(Nconst); x.conval := DevCPT.NewConst();
x.conval.realval := realval; x.conval.intval := DevCPM.ConstNotAlloc;
IF typ = NIL THEN typ := DevCPT.real64typ END;
x.typ := typ;
RETURN x
END NewRealConst;
PROCEDURE NewString*(str: DevCPT.String; lstr: POINTER TO ARRAY OF CHAR; len: INTEGER): DevCPT.Node;
VAR i, j, c: INTEGER; x: DevCPT.Node; ext: DevCPT.ConstExt;
BEGIN
x := DevCPT.NewNode(Nconst); x.conval := DevCPT.NewConst();
IF lstr # NIL THEN
x.typ := DevCPT.string16typ;
NEW(ext, 3 * len); i := 0; j := 0;
REPEAT c := ORD(lstr[i]); INC(i); DevCPM.PutUtf8(ext^, c, j) UNTIL c = 0;
x.conval.ext := ext
ELSE
x.typ := DevCPT.string8typ; x.conval.ext := str
END;
x.conval.intval := DevCPM.ConstNotAlloc; x.conval.intval2 := len;
RETURN x
END NewString;
PROCEDURE CharToString8(n: DevCPT.Node);
VAR ch: SHORTCHAR;
BEGIN
n.typ := DevCPT.string8typ; ch := SHORT(CHR(n.conval.intval)); NEW(n.conval.ext, 2);
IF ch = 0X THEN n.conval.intval2 := 1 ELSE n.conval.intval2 := 2; n.conval.ext[1] := 0X END ;
n.conval.ext[0] := ch; n.conval.intval := DevCPM.ConstNotAlloc; n.obj := NIL
END CharToString8;
PROCEDURE CharToString16 (n: DevCPT.Node);
VAR i: INTEGER;
BEGIN
n.typ := DevCPT.string16typ; NEW(n.conval.ext, 4);
IF n.conval.intval = 0 THEN
n.conval.ext[0] := 0X; n.conval.intval2 := 1
ELSE
i := 0; DevCPM.PutUtf8(n.conval.ext^, n.conval.intval, i);
n.conval.ext[i] := 0X; n.conval.intval2 := 2
END;
n.conval.intval := DevCPM.ConstNotAlloc; n.obj := NIL
END CharToString16;
PROCEDURE String8ToString16 (n: DevCPT.Node);
VAR i, j, x: INTEGER; ext, new: DevCPT.ConstExt;
BEGIN
n.typ := DevCPT.string16typ; ext := n.conval.ext;
NEW(new, 2 * n.conval.intval2); i := 0; j := 0;
REPEAT x := ORD(ext[i]); INC(i); DevCPM.PutUtf8(new^, x, j) UNTIL x = 0;
n.conval.ext := new; n.obj := NIL
END String8ToString16;
PROCEDURE String16ToString8 (n: DevCPT.Node);
VAR i, j, x: INTEGER; ext, new: DevCPT.ConstExt;
BEGIN
n.typ := DevCPT.string8typ; ext := n.conval.ext;
NEW(new, n.conval.intval2); i := 0; j := 0;
REPEAT DevCPM.GetUtf8(ext^, x, i); new[j] := SHORT(CHR(x MOD 256)); INC(j) UNTIL x = 0;
n.conval.ext := new; n.obj := NIL
END String16ToString8;
PROCEDURE StringToGuid (VAR n: DevCPT.Node);
BEGIN
ASSERT((n.class = Nconst) & (n.typ.form = String8));
IF ~DevCPM.ValidGuid(n.conval.ext^) THEN err(165) END;
n.typ := DevCPT.guidtyp
END StringToGuid;
PROCEDURE CheckString (n: DevCPT.Node; typ: DevCPT.Struct; e: SHORTINT);
VAR ntyp: DevCPT.Struct;
BEGIN
ntyp := n.typ;
IF (typ = DevCPT.guidtyp) & (n.class = Nconst) & (ntyp.form = String8) THEN StringToGuid(n)
ELSIF (typ.comp IN {Array, DynArr}) & (typ.BaseTyp.form = Char8) OR (typ.form = String8) THEN
IF (n.class = Nconst) & (ntyp.form = Char8) THEN CharToString8(n)
ELSIF (ntyp.comp IN {Array, DynArr}) & (ntyp.BaseTyp.form = Char8) OR (ntyp.form = String8) THEN (* ok *)
ELSE err(e)
END
ELSIF (typ.comp IN {Array, DynArr}) & (typ.BaseTyp.form = Char16) OR (typ.form = String16) THEN
IF (n.class = Nconst) & (ntyp.form IN charSet) THEN CharToString16(n)
ELSIF (n.class = Nconst) & (ntyp.form = String8) THEN String8ToString16(n)
ELSIF (ntyp.comp IN {Array, DynArr}) & (ntyp.BaseTyp.form = Char16) OR (ntyp.form = String16) THEN
(* ok *)
ELSE err(e)
END
ELSE err(e)
END
END CheckString;
PROCEDURE BindNodes(class: BYTE; typ: DevCPT.Struct; VAR x: DevCPT.Node; y: DevCPT.Node);
VAR node: DevCPT.Node;
BEGIN
node := DevCPT.NewNode(class); node.typ := typ;
node.left := x; node.right := y; x := node
END BindNodes;
PROCEDURE NotVar(x: DevCPT.Node): BOOLEAN;
BEGIN
RETURN (x.class >= Nconst) & ((x.class # Nmop) OR (x.subcl # val) OR NotVar(x.left))
OR (x.typ.form IN {String8, String16})
OR (x.class = Nguard) & NotVar(x.left)
END NotVar;
PROCEDURE Convert(VAR x: DevCPT.Node; typ: DevCPT.Struct);
VAR node: DevCPT.Node; f, g: SHORTINT;
BEGIN f := x.typ.form; g := typ.form;
IF x.class = Nconst THEN
IF g = String8 THEN
IF f = String16 THEN String16ToString8(x)
ELSIF f IN charSet THEN CharToString8(x)
ELSE typ := DevCPT.undftyp
END
ELSIF g = String16 THEN
IF f = String8 THEN String8ToString16(x)
ELSIF f IN charSet THEN CharToString16(x)
ELSE typ := DevCPT.undftyp
END
ELSE ConvConst(x.conval, f, g)
END;
x.obj := NIL
ELSIF (x.class = Nmop) & (x.subcl = conv) & (DevCPT.Includes(f, x.left.typ.form) OR DevCPT.Includes(f, g))
THEN
(* don't create new node *)
IF x.left.typ.form = typ.form THEN (* and suppress existing node *) x := x.left END
ELSE
IF (x.class = Ndop) & (x.typ.form IN {String8, String16}) THEN (* propagate to leaf nodes *)
Convert(x.left, typ); Convert(x.right, typ)
ELSE
node := DevCPT.NewNode(Nmop); node.subcl := conv; node.left := x; x := node;
END
END;
x.typ := typ
END Convert;
PROCEDURE Promote (VAR left, right: DevCPT.Node; op: INTEGER); (* check expression compatibility *)
VAR f, g: INTEGER; new: DevCPT.Struct;
BEGIN
f := left.typ.form; g := right.typ.form; new := left.typ;
IF f IN intSet + realSet THEN
IF g IN intSet + realSet THEN
IF (f = Real32) & (right.class = Nconst) & (g IN realSet) & (left.class # Nconst)
(* & ((ABS(right.conval.realval) <= DevCPM.MaxReal32)
OR (ABS(right.conval.realval) = DevCPM.InfReal)) *)
OR (g = Real32) & (left.class = Nconst) & (f IN realSet) & (right.class # Nconst)
(* & ((ABS(left.conval.realval) <= DevCPM.MaxReal32)
OR (ABS(left.conval.realval) = DevCPM.InfReal)) *) THEN
new := DevCPT.real32typ (* SR *)
ELSIF (f = Real64) OR (g = Real64) THEN new := DevCPT.real64typ
ELSIF (f = Real32) OR (g = Real32) THEN new := DevCPT.real32typ (* SR *)
ELSIF op = slash THEN new := DevCPT.real64typ
ELSIF (f = Int64) OR (g = Int64) THEN new := DevCPT.int64typ
ELSE new := DevCPT.int32typ
END
ELSE err(100)
END
ELSIF (left.typ = DevCPT.guidtyp) OR (right.typ = DevCPT.guidtyp) THEN
IF f = String8 THEN StringToGuid(left) END;
IF g = String8 THEN StringToGuid(right) END;
IF left.typ # right.typ THEN err(100) END;
f := Comp
ELSIF f IN charSet + {String8, String16} THEN
IF g IN charSet + {String8, String16} THEN
IF (f = String16) OR (g = String16) OR (f = Char16) & (g = String8) OR (f = String8) & (g = Char16) THEN
new := DevCPT.string16typ
ELSIF ((f = Char16) OR (g = Char16)) & (op # plus) THEN new := DevCPT.char16typ
ELSIF (f = String8) OR (g = String8) THEN new := DevCPT.string8typ
ELSIF op = plus THEN
IF (f = Char16) OR (g = Char16) THEN new := DevCPT.string16typ
ELSE new := DevCPT.string8typ
END
END;
IF (new.form IN {String8, String16})
& ((f IN charSet) & (left.class # Nconst) OR (g IN charSet) & (right.class # Nconst))
THEN
err(100)
END
ELSE err(100)
END
ELSIF (f IN {NilTyp, Pointer, ProcTyp}) & (g IN {NilTyp, Pointer, ProcTyp}) THEN
IF ~DevCPT.SameType(left.typ, right.typ) & (f # NilTyp) & (g # NilTyp)
& ~((f = Pointer) & (g = Pointer)
& (DevCPT.Extends(left.typ, right.typ) OR DevCPT.Extends(right.typ, left.typ))) THEN err(100) END
ELSIF f # g THEN err(100)
END;
IF ~(f IN {NilTyp, Pointer, ProcTyp, Comp}) THEN
IF g # new.form THEN Convert(right, new) END;
IF f # new.form THEN Convert(left, new) END
END
END Promote;
PROCEDURE CheckParameters* (fp, ap: DevCPT.Object; checkNames: BOOLEAN); (* checks par list match *)
VAR ft, at: DevCPT.Struct;
BEGIN
WHILE fp # NIL DO
IF ap # NIL THEN
ft := fp.typ; at := ap.typ;
IF fp.ptyp # NIL THEN ft := fp.ptyp END; (* get original formal type *)
IF ap.ptyp # NIL THEN at := ap.ptyp END; (* get original formal type *)
IF ~DevCPT.EqualType(ft, at)
OR (fp.mode # ap.mode) OR (fp.sysflag # ap.sysflag) OR (fp.vis # ap.vis)
OR checkNames & (fp.name^ # ap.name^) THEN err(115) END ;
ap := ap.link
ELSE err(116)
END;
fp := fp.link
END;
IF ap # NIL THEN err(116) END
END CheckParameters;
PROCEDURE CheckNewParamPair* (newPar, iidPar: DevCPT.Node);
VAR ntyp: DevCPT.Struct;
BEGIN
ntyp := newPar.typ.BaseTyp;
IF (newPar.class = Nvarpar) & ODD(newPar.obj.sysflag DIV newBit) THEN
IF (iidPar.class = Nvarpar) & ODD(iidPar.obj.sysflag DIV iidBit) & (iidPar.obj.mnolev = newPar.obj.mnolev)
THEN (* ok *)
ELSE err(168)
END
ELSIF ntyp.extlev = 0 THEN (* ok *)
ELSIF (iidPar.class = Nconst) & (iidPar.obj # NIL) & (iidPar.obj.mode = Typ) THEN
IF ~DevCPT.Extends(iidPar.obj.typ, ntyp) THEN err(168) END
ELSE err(168)
END
END CheckNewParamPair;
PROCEDURE DeRef*(VAR x: DevCPT.Node);
VAR strobj, bstrobj: DevCPT.Object; typ, btyp: DevCPT.Struct;
BEGIN
typ := x.typ;
IF (x.class = Nconst) OR (x.class = Ntype) OR (x.class = Nproc) THEN err(78)
ELSIF typ.form = Pointer THEN
btyp := typ.BaseTyp; strobj := typ.strobj; bstrobj := btyp.strobj;
IF (strobj # NIL) & (strobj.name # DevCPT.null) & (bstrobj # NIL) & (bstrobj.name # DevCPT.null) THEN
btyp.pbused := TRUE
END ;
BindNodes(Nderef, btyp, x, NIL); x.subcl := 0
ELSE err(84)
END
END DeRef;
PROCEDURE StrDeref*(VAR x: DevCPT.Node);
VAR typ, btyp: DevCPT.Struct;
BEGIN
typ := x.typ;
IF (x.class = Nconst) OR (x.class = Ntype) OR (x.class = Nproc) THEN err(78)
ELSIF ((typ.comp IN {Array, DynArr}) & (typ.BaseTyp.form IN charSet)) OR (typ.sysflag = jstr) THEN
IF (typ.BaseTyp # NIL) & (typ.BaseTyp.form = Char8) THEN btyp := DevCPT.string8typ
ELSE btyp := DevCPT.string16typ
END;
BindNodes(Nderef, btyp, x, NIL); x.subcl := 1
ELSE err(90)
END
END StrDeref;
PROCEDURE Index*(VAR x: DevCPT.Node; y: DevCPT.Node);
VAR f: SHORTINT; typ: DevCPT.Struct;
BEGIN
f := y.typ.form;
IF (x.class = Nconst) OR (x.class = Ntype) OR (x.class = Nproc) THEN err(79)
ELSIF ~(f IN intSet) OR (y.class IN {Nproc, Ntype}) THEN err(80); y.typ := DevCPT.int32typ END ;
IF f = Int64 THEN Convert(y, DevCPT.int32typ) END;
IF x.typ.comp = Array THEN typ := x.typ.BaseTyp;
IF (y.class = Nconst) & ((y.conval.intval < 0) OR (y.conval.intval >= x.typ.n)) THEN err(81) END
ELSIF x.typ.comp = DynArr THEN typ := x.typ.BaseTyp;
IF (y.class = Nconst) & (y.conval.intval < 0) THEN err(81) END
ELSE err(82); typ := DevCPT.undftyp
END ;
BindNodes(Nindex, typ, x, y); x.readonly := x.left.readonly
END Index;
PROCEDURE Field*(VAR x: DevCPT.Node; y: DevCPT.Object);
BEGIN (*x.typ.comp = Record*)
IF (x.class = Nconst) OR (x.class = Ntype) OR (x.class = Nproc) THEN err(77) END ;
IF (y # NIL) & (y.mode IN {Fld, TProc}) THEN
BindNodes(Nfield, y.typ, x, NIL); x.obj := y;
x.readonly := x.left.readonly OR ((y.vis = externalR) & (y.mnolev < 0))
ELSE err(83); x.typ := DevCPT.undftyp
END
END Field;
PROCEDURE TypTest*(VAR x: DevCPT.Node; obj: DevCPT.Object; guard: BOOLEAN);
PROCEDURE GTT(t0, t1: DevCPT.Struct);
VAR node: DevCPT.Node;
BEGIN
IF (t0 # NIL) & DevCPT.SameType(t0, t1) & (guard OR (x.class # Nguard)) THEN
IF ~guard THEN x := NewBoolConst(TRUE) END
ELSIF (t0 = NIL) OR DevCPT.Extends(t1, t0) OR (t0.sysflag = jint) OR (t1.sysflag = jint)
OR (t1.comp = DynArr) & (DevCPM.java IN DevCPM.options) THEN
IF guard THEN BindNodes(Nguard, NIL, x, NIL); x.readonly := x.left.readonly
ELSE node := DevCPT.NewNode(Nmop); node.subcl := is; node.left := x; node.obj := obj; x := node
END
ELSE err(85)
END
END GTT;
BEGIN
IF (x.class = Nconst) OR (x.class = Ntype) OR (x.class = Nproc) THEN err(112)
ELSIF x.typ.form = Pointer THEN
IF x.typ = DevCPT.sysptrtyp THEN
IF obj.typ.form = Pointer THEN GTT(NIL, obj.typ.BaseTyp)
ELSE err(86)
END
ELSIF x.typ.BaseTyp.comp # Record THEN err(85)
ELSIF obj.typ.form = Pointer THEN GTT(x.typ.BaseTyp, obj.typ.BaseTyp)
ELSE err(86)
END
ELSIF (x.typ.comp = Record) & (x.class = Nvarpar) & (x.obj.vis # outPar) & (obj.typ.comp = Record) THEN
GTT(x.typ, obj.typ)
ELSE err(87)
END ;
IF guard THEN x.typ := obj.typ ELSE x.typ := DevCPT.booltyp END
END TypTest;
PROCEDURE In*(VAR x: DevCPT.Node; y: DevCPT.Node);
VAR f: SHORTINT; k: INTEGER;
BEGIN f := x.typ.form;
IF (x.class = Ntype) OR (x.class = Nproc) OR (y.class = Ntype) OR (y.class = Nproc) THEN err(126)
ELSIF (f IN intSet) & (y.typ.form = Set) THEN
IF f = Int64 THEN Convert(x, DevCPT.int32typ) END;
IF x.class = Nconst THEN
k := x.conval.intval;
IF (k < 0) OR (k > DevCPM.MaxSet) THEN err(202)
ELSIF y.class = Nconst THEN x.conval.intval := BoolToInt(k IN y.conval.setval); x.obj := NIL
ELSE BindNodes(Ndop, DevCPT.booltyp, x, y); x.subcl := in
END
ELSE BindNodes(Ndop, DevCPT.booltyp, x, y); x.subcl := in
END
ELSE err(92)
END ;
x.typ := DevCPT.booltyp
END In;
PROCEDURE MOp*(op: BYTE; VAR x: DevCPT.Node);
VAR f: SHORTINT; typ: DevCPT.Struct; z: DevCPT.Node;
PROCEDURE NewOp(op: BYTE; typ: DevCPT.Struct; z: DevCPT.Node): DevCPT.Node;
VAR node: DevCPT.Node;
BEGIN
node := DevCPT.NewNode(Nmop); node.subcl := op; node.typ := typ;
node.left := z; RETURN node
END NewOp;
BEGIN z := x;
IF ((z.class = Ntype) OR (z.class = Nproc)) & (op # adr) & (op # typfn) & (op # size) THEN err(126) (* !!! *)
ELSE
typ := z.typ; f := typ.form;
CASE op OF
| not:
IF f = Bool THEN
IF z.class = Nconst THEN
z.conval.intval := BoolToInt(~IntToBool(z.conval.intval)); z.obj := NIL
ELSE z := NewOp(op, typ, z)
END
ELSE err(98)
END
| plus:
IF ~(f IN intSet + realSet) THEN err(96) END
| minus:
IF f IN intSet + realSet + {Set} THEN
IF z.class = Nconst THEN
IF f = Set THEN z.conval.setval := -z.conval.setval
ELSE NegateConst(z.conval, z.conval, z.typ)
END;
z.obj := NIL
ELSE
IF f < Int32 THEN Convert(z, DevCPT.int32typ) END;
z := NewOp(op, z.typ, z)
END
ELSE err(97)
END
| abs:
IF f IN intSet + realSet THEN
IF z.class = Nconst THEN
IF IsNegConst(z.conval, f) THEN NegateConst(z.conval, z.conval, z.typ) END;
z.obj := NIL
ELSE
IF f < Int32 THEN Convert(z, DevCPT.int32typ) END;
z := NewOp(op, z.typ, z)
END
ELSE err(111)
END
| cap:
IF f IN charSet THEN
IF z.class = Nconst THEN
IF ODD(z.conval.intval DIV 32) THEN DEC(z.conval.intval, 32) END;
z.obj := NIL
ELSE z := NewOp(op, typ, z)
END
ELSE err(111); z.typ := DevCPT.char8typ
END
| odd:
IF f IN intSet THEN
IF z.class = Nconst THEN
DivModConst(z.conval, two, FALSE, z.typ); (* z MOD 2 *)
z.obj := NIL
ELSE z := NewOp(op, typ, z)
END
ELSE err(111)
END ;
z.typ := DevCPT.booltyp
| adr: (*ADR*)
IF (z.class = Nproc) & (z.obj.mode # CProc) THEN
IF z.obj.mnolev > 0 THEN err(73)
ELSIF z.obj.mode = LProc THEN z.obj.mode := XProc
END;
z := NewOp(op, typ, z)
ELSIF z.class = Ntype THEN
IF z.obj.typ.untagged THEN err(111)
ELSE (* https://forum.blackboxframework.org/viewtopic.php?f=40&t=755 *)
CASE z.obj.typ.form OF
|Byte..Set, Char16,Int64: err(111)
ELSE
END
END;
z := NewOp(op, typ, z)
ELSIF (z.class < Nconst) OR (z.class = Nconst) & (f IN {String8, String16}) THEN
z := NewOp(op, typ, z)
ELSE err(127)
END ;
z.typ := DevCPT.int32typ
| typfn, size: (*TYP, SIZE*)
z := NewOp(op, typ, z);
z.typ := DevCPT.int32typ
| cc: (*SYSTEM.CC*)
IF (f IN intSet) & (z.class = Nconst) THEN
IF (0 <= z.conval.intval) & (z.conval.intval <= DevCPM.MaxCC) & (z.conval.realval = 0) THEN
z := NewOp(op, typ, z)
ELSE err(219)
END
ELSE err(69)
END;
z.typ := DevCPT.booltyp
END
END;
x := z
END MOp;
PROCEDURE ConstOp(op: SHORTINT; x, y: DevCPT.Node);
VAR f: SHORTINT; i, j: INTEGER; xval, yval: DevCPT.Const; ext: DevCPT.ConstExt;
BEGIN
f := x.typ.form;
IF f = y.typ.form THEN
xval := x.conval; yval := y.conval;
CASE op OF
| times:
IF f IN intSet + realSet THEN MulConst(xval, yval, xval, x.typ)
ELSIF f = Set THEN xval.setval := xval.setval * yval.setval
ELSIF f # Undef THEN err(101)
END
| slash:
IF f IN realSet THEN DivConst(xval, yval, xval, x.typ)
ELSIF f = Set THEN xval.setval := xval.setval / yval.setval
ELSIF f # Undef THEN err(102)
END
| div:
IF f IN intSet THEN DivModConst(xval, yval, TRUE, x.typ)
ELSIF f # Undef THEN err(103)
END
| mod:
IF f IN intSet THEN DivModConst(xval, yval, FALSE, x.typ)
ELSIF f # Undef THEN err(104)
END
| and:
IF f = Bool THEN xval.intval := BoolToInt(IntToBool(xval.intval) & IntToBool(yval.intval))
ELSE err(94)
END
| plus:
IF f IN intSet + realSet THEN AddConst(xval, yval, xval, x.typ)
ELSIF f = Set THEN xval.setval := xval.setval + yval.setval
ELSIF (f IN {String8, String16}) & (xval.ext # NIL) & (yval.ext # NIL) THEN
NEW(ext, LEN(xval.ext^) + LEN(yval.ext^));
i := 0; WHILE xval.ext[i] # 0X DO ext[i] := xval.ext[i]; INC(i) END;
j := 0; WHILE yval.ext[j] # 0X DO ext[i] := yval.ext[j]; INC(i); INC(j) END;
ext[i] := 0X; xval.ext := ext; INC(xval.intval2, yval.intval2 - 1)
ELSIF f # Undef THEN err(105)
END
| minus:
IF f IN intSet + realSet THEN SubConst(xval, yval, xval, x.typ)
ELSIF f = Set THEN xval.setval := xval.setval - yval.setval
ELSIF f # Undef THEN err(106)
END
| min:
IF f IN intSet + realSet THEN
IF LessConst(yval, xval, f) THEN xval^ := yval^ END
ELSIF f # Undef THEN err(111)
END
| max:
IF f IN intSet + realSet THEN
IF LessConst(xval, yval, f) THEN xval^ := yval^ END
ELSIF f # Undef THEN err(111)
END
| or:
IF f = Bool THEN xval.intval := BoolToInt(IntToBool(xval.intval) OR IntToBool(yval.intval))
ELSE err(95)
END
| eql: xval.intval := BoolToInt(EqualConst(xval, yval, f)); x.typ := DevCPT.booltyp
| neq: xval.intval := BoolToInt(~EqualConst(xval, yval, f)); x.typ := DevCPT.booltyp
| lss: xval.intval := BoolToInt(LessConst(xval, yval, f)); x.typ := DevCPT.booltyp
| leq: xval.intval := BoolToInt(~LessConst(yval, xval, f)); x.typ := DevCPT.booltyp
| gtr: xval.intval := BoolToInt(LessConst(yval, xval, f)); x.typ := DevCPT.booltyp
| geq: xval.intval := BoolToInt(~LessConst(xval, yval, f)); x.typ := DevCPT.booltyp
END
ELSE err(100)
END;
x.obj := NIL
END ConstOp;
PROCEDURE Op*(op: BYTE; VAR x: DevCPT.Node; y: DevCPT.Node);
VAR f, g: SHORTINT; t, z: DevCPT.Node; typ: DevCPT.Struct; do: BOOLEAN; val: INTEGER;
PROCEDURE NewOp(op: BYTE; typ: DevCPT.Struct; VAR x: DevCPT.Node; y: DevCPT.Node);
VAR node: DevCPT.Node;
BEGIN
node := DevCPT.NewNode(Ndop); node.subcl := op; node.typ := typ;
node.left := x; node.right := y; x := node
END NewOp;
BEGIN z := x;
IF (z.class = Ntype) OR (z.class = Nproc) OR (y.class = Ntype) OR (y.class = Nproc) THEN err(126)
ELSE
Promote(z, y, op);
IF (z.class = Nconst) & (y.class = Nconst) THEN ConstOp(op, z, y)
ELSE
typ := z.typ; f := typ.form; g := y.typ.form;
CASE op OF
| times:
do := TRUE;
IF f IN intSet THEN
IF z.class = Nconst THEN
IF EqualConst(z.conval, one, f) THEN do := FALSE; z := y
ELSIF EqualConst(z.conval, zero, f) THEN do := FALSE
ELSE val := Log(z);
IF val >= 0 THEN
t := y; y := z; z := t;
op := ash; y.typ := DevCPT.int32typ; y.conval.intval := val; y.obj := NIL
END
END
ELSIF y.class = Nconst THEN
IF EqualConst(y.conval, one, f) THEN do := FALSE
ELSIF EqualConst(y.conval, zero, f) THEN do := FALSE; z := y
ELSE val := Log(y);
IF val >= 0 THEN
op := ash; y.typ := DevCPT.int32typ; y.conval.intval := val; y.obj := NIL
END
END
END
ELSIF ~(f IN {Undef, Real32..Set}) THEN err(105); typ := DevCPT.undftyp
END ;
IF do THEN NewOp(op, typ, z, y) END;
| slash:
IF f IN realSet THEN (* OK *)
ELSIF (f # Set) & (f # Undef) THEN err(102); typ := DevCPT.undftyp
END ;
NewOp(op, typ, z, y)
| div:
do := TRUE;
IF f IN intSet THEN
IF y.class = Nconst THEN
IF EqualConst(y.conval, zero, f) THEN err(205)
ELSIF EqualConst(y.conval, one, f) THEN do := FALSE
ELSE val := Log(y);
IF val >= 0 THEN
op := ash; y.typ := DevCPT.int32typ; y.conval.intval := -val; y.obj := NIL
END
END
END
ELSIF f # Undef THEN err(103); typ := DevCPT.undftyp
END ;
IF do THEN NewOp(op, typ, z, y) END;
| mod:
IF f IN intSet THEN
IF y.class = Nconst THEN
IF EqualConst(y.conval, zero, f) THEN err(205)
ELSE val := Log(y);
IF val >= 0 THEN
op := msk; y.conval.intval := ASH(-1, val); y.obj := NIL
END
END
END
ELSIF f # Undef THEN err(104); typ := DevCPT.undftyp
END ;
NewOp(op, typ, z, y);
| and:
IF f = Bool THEN
IF z.class = Nconst THEN
IF IntToBool(z.conval.intval) THEN z := y END
ELSIF (y.class = Nconst) & IntToBool(y.conval.intval) THEN (* optimize z & TRUE -> z *)
ELSE NewOp(op, typ, z, y)
END
ELSIF f # Undef THEN err(94); z.typ := DevCPT.undftyp
END
| plus:
IF ~(f IN {Undef, Int8..Set, Int64, String8, String16}) THEN err(105); typ := DevCPT.undftyp END;
do := TRUE;
IF f IN intSet THEN
IF (z.class = Nconst) & EqualConst(z.conval, zero, f) THEN do := FALSE; z := y END ;
IF (y.class = Nconst) & EqualConst(y.conval, zero, f) THEN do := FALSE END
ELSIF f IN {String8, String16} THEN
IF (z.class = Nconst) & (z.conval.intval2 = 1) THEN do := FALSE; z := y END ;
IF (y.class = Nconst) & (y.conval.intval2 = 1) THEN do := FALSE END;
IF do THEN
IF z.class = Ndop THEN
t := z; WHILE t.right.class = Ndop DO t := t.right END;
IF (t.right.class = Nconst) & (y.class = Nconst) THEN
ConstOp(op, t.right, y); do := FALSE
ELSIF (t.right.class = Nconst) & (y.class = Ndop) & (y.left.class = Nconst) THEN
ConstOp(op, t.right, y.left); y.left := t.right; t.right := y; do := FALSE
ELSE
NewOp(op, typ, t.right, y); do := FALSE
END
ELSE
IF (z.class = Nconst) & (y.class = Ndop) & (y.left.class = Nconst) THEN
ConstOp(op, z, y.left); y.left := z; z := y; do := FALSE
END
END
END
END ;
IF do THEN NewOp(op, typ, z, y) END;
| minus:
IF ~(f IN {Undef, Int8..Set, Int64}) THEN err(106); typ := DevCPT.undftyp END;
IF ~(f IN intSet) OR (y.class # Nconst) OR ~EqualConst(y.conval, zero, f) THEN NewOp(op, typ, z, y)
END;
| min, max:
IF ~(f IN {Undef} + intSet + realSet + charSet) THEN err(111); typ := DevCPT.undftyp END;
NewOp(op, typ, z, y);
| or:
IF f = Bool THEN
IF z.class = Nconst THEN
IF ~IntToBool(z.conval.intval) THEN z := y END
ELSIF (y.class = Nconst) & ~IntToBool(y.conval.intval) THEN (* optimize z OR FALSE -> z *)
ELSE NewOp(op, typ, z, y)
END
ELSIF f # Undef THEN err(95); z.typ := DevCPT.undftyp
END
| eql, neq, lss, leq, gtr, geq:
IF f IN {String8, String16} THEN
IF (f = String16) & (z.class = Nmop) & (z.subcl = conv) & (y.class = Nmop) & (y.subcl = conv) THEN
z := z.left; y := y.left (* remove LONG on both sides *)
ELSIF (z.class = Nconst) & (z.conval.intval2 = 1) & (y.class = Nderef) THEN (* y$ = "" -> y[0] = 0X *)
y := y.left; Index(y, NewIntConst(0)); z.typ := y.typ; z.conval.intval := 0; z.obj := NIL
ELSIF (y.class = Nconst) & (y.conval.intval2 = 1) & (z.class = Nderef) THEN (* z$ = "" -> z[0] = 0X *)
z := z.left; Index(z, NewIntConst(0)); y.typ := z.typ; y.conval.intval := 0; y.obj := NIL
END;
typ := DevCPT.booltyp
ELSIF (f IN {Undef, Char8..Real64, Char16, Int64})
OR (op <= neq) & ((f IN {Bool, Set, NilTyp, Pointer, ProcTyp}) OR (typ = DevCPT.guidtyp)) THEN
typ := DevCPT.booltyp
ELSE err(107); typ := DevCPT.undftyp
END;
NewOp(op, typ, z, y)
END
END
END;
x := z
END Op;
PROCEDURE SetRange*(VAR x: DevCPT.Node; y: DevCPT.Node);
VAR k, l: INTEGER;
BEGIN
IF (x.class = Ntype) OR (x.class = Nproc) OR (y.class = Ntype) OR (y.class = Nproc) THEN err(126)
ELSIF (x.typ.form IN intSet) & (y.typ.form IN intSet) THEN
IF x.typ.form = Int64 THEN Convert(x, DevCPT.int32typ) END;
IF y.typ.form = Int64 THEN Convert(y, DevCPT.int32typ) END;
IF x.class = Nconst THEN
k := x.conval.intval;
IF (0 > k) OR (k > DevCPM.MaxSet) OR (x.conval.realval # 0) THEN err(202) END
END ;
IF y.class = Nconst THEN
l := y.conval.intval;
IF (0 > l) OR (l > DevCPM.MaxSet) OR (y.conval.realval # 0) THEN err(202) END
END ;
IF (x.class = Nconst) & (y.class = Nconst) THEN
IF k <= l THEN
x.conval.setval := {k..l}
ELSE err(201); x.conval.setval := {l..k}
END ;
x.obj := NIL
ELSE BindNodes(Nupto, DevCPT.settyp, x, y)
END
ELSE err(93)
END ;
x.typ := DevCPT.settyp
END SetRange;
PROCEDURE SetElem*(VAR x: DevCPT.Node);
VAR k: INTEGER;
BEGIN
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126) END;
IF x.typ.form IN intSet THEN
IF x.typ.form = Int64 THEN Convert(x, DevCPT.int32typ) END;
IF x.class = Nconst THEN
k := x.conval.intval;
IF (0 <= k) & (k <= DevCPM.MaxSet) & (x.conval.realval = 0) THEN x.conval.setval := {k}
ELSE err(202)
END ;
x.obj := NIL
ELSE BindNodes(Nmop, DevCPT.settyp, x, NIL); x.subcl := bit
END ;
ELSE err(93)
END;
x.typ := DevCPT.settyp
END SetElem;
PROCEDURE CheckAssign* (x: DevCPT.Struct; VAR ynode: DevCPT.Node);
(* x := y, checks assignment compatibility *)
VAR f, g: SHORTINT; y, b: DevCPT.Struct;
BEGIN
y := ynode.typ; f := x.form; g := y.form;
IF (ynode.class = Ntype) OR (ynode.class = Nproc) & (f # ProcTyp) THEN err(126) END ;
CASE f OF
| Undef, String8, String16, Byte:
| Bool, Set:
IF g # f THEN err(113) END
| Int8, Int16, Int32, Int64, Real32, Real64: (* SR *)
IF (g IN intSet) OR (g IN realSet) & (f IN realSet) THEN
IF ynode.class = Nconst THEN Convert(ynode, x)
ELSIF ~DevCPT.Includes(f, g) THEN err(113)
END
ELSE err(113)
END
(*
IF ~(g IN intSet + realSet) OR ~DevCPT.Includes(f, g) & (~(g IN intSet) OR (ynode.class # Nconst)) THEN
err(113)
ELSIF ynode.class = Nconst THEN Convert(ynode, x)
END
*)
| Char8, Char16:
IF ~(g IN charSet) OR ~DevCPT.Includes(f, g) THEN err(113)
ELSIF ynode.class = Nconst THEN Convert(ynode, x)
END
| Pointer:
b := x.BaseTyp;
IF DevCPT.Extends(y, x)
OR (g = NilTyp)
OR (g = Pointer)
& ((x = DevCPT.sysptrtyp) OR (DevCPM.java IN DevCPM.options) & (x = DevCPT.anyptrtyp))
THEN (* ok *)
ELSIF (b.comp = DynArr) & b.untagged THEN (* pointer to untagged open array *)
IF ynode.class = Nconst THEN CheckString(ynode, b, 113)
ELSIF ~(y.comp IN {Array, DynArr}) OR ~DevCPT.EqualType(b.BaseTyp, y.BaseTyp) THEN err(113)
END
ELSIF b.untagged & (ynode.class = Nmop) & (ynode.subcl = adr) THEN (* p := ADR(r) *)
IF (b.comp = DynArr) & (ynode.left.class = Nconst) THEN CheckString(ynode.left, b, 113)
ELSIF ~DevCPT.Extends(ynode.left.typ, b) THEN err(113)
END
ELSIF (b.sysflag = jstr) & ((g = String16) OR (ynode.class = Nconst) & (g IN {Char8, Char16, String8}))
THEN
IF g # String16 THEN Convert(ynode, DevCPT.string16typ) END
ELSE err(113)
END
| ProcTyp:
IF DevCPT.EqualType(x, y) OR (g = NilTyp) THEN (* ok *)
ELSIF (ynode.class = Nproc) & (ynode.obj.mode IN {XProc, IProc, LProc}) THEN
IF ynode.obj.mode = LProc THEN
IF ynode.obj.mnolev = 0 THEN ynode.obj.mode := XProc ELSE err(73) END
END;
IF (x.sysflag = 0) & (ynode.obj.sysflag >= 0) OR (x.sysflag = ynode.obj.sysflag) THEN
IF DevCPT.EqualType(x.BaseTyp, ynode.obj.typ) THEN CheckParameters(x.link, ynode.obj.link, FALSE)
ELSE err(117)
END
ELSE err(113)
END
ELSE err(113)
END
| NoTyp, NilTyp: err(113)
| Comp:
x.pvused := TRUE; (* idfp of y guarantees assignment compatibility with x *)
IF x.comp = Record THEN
IF ~DevCPT.EqualType(x, y) OR (x.attribute # 0) THEN err(113) END
ELSIF g IN {Char8, Char16, String8, String16} THEN
IF (x.BaseTyp.form = Char16) & (g = String8) THEN Convert(ynode, DevCPT.string16typ)
ELSE CheckString(ynode, x, 113);
END;
IF (x # DevCPT.guidtyp) & (x.comp = Array) & (ynode.class = Nconst) & (ynode.conval.intval2 > x.n) THEN
err(114)
END
ELSIF (x.comp = Array) & DevCPT.EqualType(x, y) THEN (* ok *)
ELSE err(113)
END
END
END CheckAssign;
PROCEDURE AssignString (VAR x: DevCPT.Node; str: DevCPT.Node); (* x := str or x[0] := 0X *)
BEGIN
ASSERT((str.class = Nconst) & (str.typ.form IN {String8, String16}));
IF (x.typ.comp IN {Array, DynArr}) & (str.conval.intval2 = 1) THEN (* x := "" -> x[0] := 0X *)
Index(x, NewIntConst(0));
str.typ := x.typ; str.conval.intval := 0; str.obj := NIL
END;
BindNodes(Nassign, DevCPT.notyp, x, str); x.subcl := assign
END AssignString;
PROCEDURE CheckLeaf(x: DevCPT.Node; dynArrToo: BOOLEAN);
BEGIN
IF (x.class = Nmop) & (x.subcl = val) THEN x := x.left END ;
IF x.class = Nguard THEN x := x.left END ; (* skip last (and unique) guard *)
IF (x.class = Nvar) & (dynArrToo OR (x.typ.comp # DynArr)) THEN x.obj.leaf := FALSE END
END CheckLeaf;
PROCEDURE CheckOldType (x: DevCPT.Node);
BEGIN
IF ~(DevCPM.oberon IN DevCPM.options)
& ((x.typ = DevCPT.lreal64typ) OR (x.typ = DevCPT.lint64typ) OR (x.typ = DevCPT.lchar16typ)) THEN
err(198)
END
END CheckOldType;
PROCEDURE StPar0*(VAR par0: DevCPT.Node; fctno: SHORTINT); (* par0: first param of standard proc *)
VAR f: SHORTINT; typ: DevCPT.Struct; x: DevCPT.Node;
BEGIN x := par0; f := x.typ.form;
CASE fctno OF
haltfn: (*HALT*)
IF (f IN intSet - {Int64}) & (x.class = Nconst) THEN
IF (DevCPM.MinHaltNr <= x.conval.intval) & (x.conval.intval <= DevCPM.MaxHaltNr) THEN
BindNodes(Ntrap, DevCPT.notyp, x, x)
ELSE err(218)
END
ELSIF (DevCPM.java IN DevCPM.options)
& ((x.class = Ntype) OR (x.class = Nvar))
& (x.typ.form = Pointer)
THEN
BindNodes(Ntrap, DevCPT.notyp, x, x)
ELSE err(69)
END ;
x.typ := DevCPT.notyp
| newfn: (*NEW*)
typ := DevCPT.notyp;
IF NotVar(x) THEN err(112)
ELSIF f = Pointer THEN
IF DevCPM.NEWusingAdr THEN CheckLeaf(x, TRUE) END ;
IF x.readonly THEN err(76)
ELSIF (x.typ.BaseTyp.attribute = absAttr)
OR (x.typ.BaseTyp.attribute = limAttr) & (x.typ.BaseTyp.mno # 0) THEN err(193)
ELSIF (x.obj # NIL) & ODD(x.obj.sysflag DIV newBit) THEN err(167)
END ;
MarkAsUsed(x);
f := x.typ.BaseTyp.comp;
IF f IN {Record, DynArr, Array} THEN
IF f = DynArr THEN typ := x.typ.BaseTyp END ;
BindNodes(Nassign, DevCPT.notyp, x, NIL); x.subcl := newfn
ELSE err(111)
END
ELSE err(111)
END ;
x.typ := typ
| absfn: (*ABS*)
MOp(abs, x)
| capfn: (*CAP*)
MOp(cap, x)
| ordfn: (*ORD*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f = Char8 THEN Convert(x, DevCPT.int16typ)
ELSIF f = Char16 THEN Convert(x, DevCPT.int32typ)
ELSIF f = Set THEN Convert(x, DevCPT.int32typ)
ELSE err(111)
END
| bitsfn: (*BITS*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN {Int8, Int16, Int32} THEN Convert(x, DevCPT.settyp)
ELSE err(111)
END
| entierfn: (*ENTIER*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN realSet THEN Convert(x, DevCPT.int64typ)
ELSE err(111)
END ;
x.typ := DevCPT.int64typ
| lentierfcn: (* LENTIER *)
IF ~(DevCPM.oberon IN DevCPM.options) THEN err(199) END;
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN realSet THEN Convert(x, DevCPT.int64typ)
ELSE err(111)
END ;
x.typ := DevCPT.int64typ
| oddfn: (*ODD*)
MOp(odd, x)
| minfn: (*MIN*)
IF x.class = Ntype THEN
CheckOldType(x);
CASE f OF
Bool: x := NewBoolConst(FALSE)
| Char8: x := NewIntConst(0); x.typ := DevCPT.char8typ
| Char16: x := NewIntConst(0); x.typ := DevCPT.char8typ
| Int8: x := NewIntConst(-128)
| Int16: x := NewIntConst(-32768)
| Int32: x := NewIntConst(-2147483648)
| Int64: x := NewLargeIntConst(0, -9223372036854775808.0E0) (* -2^63 *)
| Set: x := NewIntConst(0) (*; x.typ := DevCPT.int16typ *)
| Real32: x := NewRealConst(DevCPM.MinReal32, DevCPT.real64typ)
| Real64: x := NewRealConst(DevCPM.MinReal64, DevCPT.real64typ)
ELSE err(111)
END;
x.hint := 1
ELSIF ~(f IN intSet + realSet + charSet) THEN err(111)
END
| maxfn: (*MAX*)
IF x.class = Ntype THEN
CheckOldType(x);
CASE f OF
Bool: x := NewBoolConst(TRUE)
| Char8: x := NewIntConst(0FFH); x.typ := DevCPT.char8typ
| Char16: x := NewIntConst(0FFFFH); x.typ := DevCPT.char16typ
| Int8: x := NewIntConst(127)
| Int16: x := NewIntConst(32767)
| Int32: x := NewIntConst(2147483647)
| Int64: x := NewLargeIntConst(-1, 9223372036854775808.0E0) (* 2^63 - 1 *)
| Set: x := NewIntConst(31) (*; x.typ := DevCPT.int16typ *)
| Real32: x := NewRealConst(DevCPM.MaxReal32, DevCPT.real64typ)
| Real64: x := NewRealConst(DevCPM.MaxReal64, DevCPT.real64typ)
ELSE err(111)
END;
x.hint := 1
ELSIF ~(f IN intSet + realSet + charSet) THEN err(111)
END
| chrfn: (*CHR*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN {Undef, Int8..Int32, Int64} THEN Convert(x, DevCPT.char16typ)
ELSE err(111); x.typ := DevCPT.char16typ
END
| lchrfn: (* LCHR *)
IF ~(DevCPM.oberon IN DevCPM.options) THEN err(199) END;
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN {Undef, Int8..Int32, Int64} THEN Convert(x, DevCPT.char16typ)
ELSE err(111); x.typ := DevCPT.char16typ
END
| shortfn: (*SHORT*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSE
IF (x.typ.comp IN {Array, DynArr}) & (x.typ.BaseTyp.form IN charSet) THEN StrDeref(x); f := x.typ.form
END;
IF f = Int16 THEN Convert(x, DevCPT.int8typ)
ELSIF f = Int32 THEN Convert(x, DevCPT.int16typ)
ELSIF f = Int64 THEN Convert(x, DevCPT.int32typ)
ELSIF f = Real64 THEN Convert(x, DevCPT.real32typ)
ELSIF f = Char16 THEN Convert(x, DevCPT.char8typ)
ELSIF f = String16 THEN Convert(x, DevCPT.string8typ)
ELSE err(111)
END
END
| longfn: (*LONG*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSE
IF (x.typ.comp IN {Array, DynArr}) & (x.typ.BaseTyp.form IN charSet) THEN StrDeref(x); f := x.typ.form
END;
IF f = Int8 THEN Convert(x, DevCPT.int16typ)
ELSIF f = Int16 THEN Convert(x, DevCPT.int32typ)
ELSIF f = Int32 THEN Convert(x, DevCPT.int64typ)
ELSIF f = Real32 THEN Convert(x, DevCPT.real64typ)
ELSIF f = Char8 THEN Convert(x, DevCPT.char16typ)
ELSIF f = String8 THEN Convert(x, DevCPT.string16typ)
ELSE err(111)
END
END
| incfn, decfn: (*INC, DEC*)
IF NotVar(x) THEN err(112)
ELSIF ~(f IN intSet) THEN err(111)
ELSIF x.readonly THEN err(76)
END;
MarkAsUsed(x)
| inclfn, exclfn: (*INCL, EXCL*)
IF NotVar(x) THEN err(112)
ELSIF f # Set THEN err(111); x.typ := DevCPT.settyp
ELSIF x.readonly THEN err(76)
END;
MarkAsUsed(x)
| lenfn: (*LEN*)
IF (* (x.class = Ntype) OR *) (x.class = Nproc) THEN err(126) (* !!! *)
(* ELSIF x.typ.sysflag = jstr THEN StrDeref(x) *)
ELSE
IF x.typ.form = Pointer THEN DeRef(x) END;
IF x.class = Nconst THEN
IF x.typ.form = Char8 THEN CharToString8(x)
ELSIF x.typ.form = Char16 THEN CharToString16(x)
END
END;
IF ~(x.typ.comp IN {DynArr, Array}) & ~(x.typ.form IN {String8, String16}) THEN err(131) END
END
| copyfn: (*COPY*)
IF ~(DevCPM.oberon IN DevCPM.options) THEN err(199) END;
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126) END
| ashfn: (*ASH*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN intSet THEN
IF f < Int32 THEN Convert(x, DevCPT.int32typ) END
ELSE err(111); x.typ := DevCPT.int32typ
END
| adrfn: (*ADR*)
IF x.class = Ntype THEN CheckOldType(x) END;
CheckLeaf(x, FALSE); MOp(adr, x)
| typfn: (*TYP*)
CheckLeaf(x, FALSE);
IF x.class = Ntype THEN
CheckOldType(x);
IF x.typ.form = Pointer THEN x := NewLeaf(x.typ.BaseTyp.strobj) END;
IF x.typ.comp # Record THEN err(111) END;
MOp(adr, x)
ELSE
IF x.typ.form = Pointer THEN DeRef(x) END;
IF x.typ.comp # Record THEN err(111) END;
MOp(typfn, x)
END
| sizefn: (*SIZE*)
IF x.class # Ntype THEN err(110); x := NewIntConst(1)
ELSIF (f IN {Byte..Set, Pointer, ProcTyp, Char16, Int64}) OR (x.typ.comp IN {Array, Record}) THEN
CheckOldType(x); x.typ.pvused := TRUE;
IF typSize # NIL THEN
typSize(x.typ); x := NewIntConst(x.typ.size)
ELSE
MOp(size, x)
END
ELSE err(111); x := NewIntConst(1)
END
| thisrecfn, (*THISRECORD*)
thisarrfn: (*THISARRAY*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN {Int8, Int16} THEN Convert(x, DevCPT.int32typ)
ELSIF f # Int32 THEN err(111)
END
| ccfn: (*SYSTEM.CC*)
MOp(cc, x)
| lshfn, rotfn: (*SYSTEM.LSH, SYSTEM.ROT*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF ~(f IN intSet + charSet + {Byte, Set}) THEN err(111)
END
| getfn, putfn, bitfn, movefn: (*SYSTEM.GET, SYSTEM.PUT, SYSTEM.BIT, SYSTEM.MOVE*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF (x.class = Nconst) & (f IN {Int8, Int16}) THEN Convert(x, DevCPT.int32typ)
ELSIF ~(f IN {Int32, Pointer}) THEN err(111); x.typ := DevCPT.int32typ
END
| getrfn, putrfn: (*SYSTEM.GETREG, SYSTEM.PUTREG*)
IF (f IN intSet) & (x.class = Nconst) THEN
IF (x.conval.intval < DevCPM.MinRegNr) OR (x.conval.intval > DevCPM.MaxRegNr) THEN err(220)
END
ELSE err(69)
END
| valfn: (*SYSTEM.VAL*)
IF x.class # Ntype THEN err(110)
ELSIF (f IN {Undef, String8, String16, NoTyp, NilTyp}) (* OR (x.typ.comp = DynArr) *) THEN err(111)
ELSE CheckOldType(x)
END
| assertfn: (*ASSERT*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126); x := NewBoolConst(FALSE)
ELSIF f # Bool THEN err(120); x := NewBoolConst(FALSE)
ELSE MOp(not, x)
END
| validfn: (* VALID *)
IF (x.class = Nvarpar) & ODD(x.obj.sysflag DIV nilBit) THEN
MOp(adr, x); x.typ := DevCPT.sysptrtyp; Op(neq, x, Nil())
ELSE err(111)
END;
x.typ := DevCPT.booltyp
| iidfn: (* COM.IID *)
IF (x.class = Nconst) & (f = String8) THEN StringToGuid(x)
ELSE
typ := x.typ;
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
IF (typ.sysflag = interface) & (typ.ext # NIL) & (typ.strobj # NIL) THEN
IF x.obj # typ.strobj THEN x := NewLeaf(typ.strobj) END
ELSE err(111)
END;
x.class := Nconst; x.typ := DevCPT.guidtyp
END
| queryfn: (* COM.QUERY *)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f # Pointer THEN err(111)
END
END ;
par0 := x
END StPar0;
PROCEDURE StPar1*(VAR par0: DevCPT.Node; x: DevCPT.Node; fctno: BYTE);
(* x: second parameter of standard proc *)
VAR f, n, L, i: INTEGER; typ, tp1: DevCPT.Struct; p, t: DevCPT.Node;
PROCEDURE NewOp(class, subcl: BYTE; left, right: DevCPT.Node): DevCPT.Node;
VAR node: DevCPT.Node;
BEGIN
node := DevCPT.NewNode(class); node.subcl := subcl;
node.left := left; node.right := right; RETURN node
END NewOp;
BEGIN p := par0; f := x.typ.form;
CASE fctno OF
incfn, decfn: (*INC DEC*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126); p.typ := DevCPT.notyp
ELSE
IF f # p.typ.form THEN
IF f IN intSet THEN Convert(x, p.typ)
ELSE err(111)
END
END ;
p := NewOp(Nassign, fctno, p, x);
p.typ := DevCPT.notyp
END
| inclfn, exclfn: (*INCL, EXCL*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN intSet THEN
IF f = Int64 THEN Convert(x, DevCPT.int32typ) END;
IF (x.class = Nconst) & ((0 > x.conval.intval) OR (x.conval.intval > DevCPM.MaxSet)) THEN err(202)
END ;
p := NewOp(Nassign, fctno, p, x)
ELSE err(111)
END ;
p.typ := DevCPT.notyp
| lenfn: (*LEN*)
IF ~(f IN intSet) OR (x.class # Nconst) THEN err(69)
ELSE
IF f = Int64 THEN Convert(x, DevCPT.int32typ) END;
L := SHORT(x.conval.intval); typ := p.typ;
WHILE (L > 0) & (typ.comp IN {DynArr, Array}) DO typ := typ.BaseTyp; DEC(L) END ;
IF (L # 0) OR ~(typ.comp IN {DynArr, Array}) THEN err(132)
ELSE x.obj := NIL;
IF typ.comp = DynArr THEN
WHILE p.class = Nindex DO
p := p.left; INC(x.conval.intval) (* possible side effect ignored *)
END;
p := NewOp(Ndop, len, p, x); p.typ := DevCPT.int32typ
ELSE p := x; p.conval.intval := typ.n; p.typ := DevCPT.int32typ
END
END
END
| copyfn: (*COPY*)
IF NotVar(x) THEN err(112)
ELSIF x.readonly THEN err(76)
ELSE
CheckString(p, x.typ, 111); t := x; x := p; p := t;
IF (x.class = Nconst) & (x.typ.form IN {String8, String16}) THEN AssignString(p, x)
ELSE p := NewOp(Nassign, copyfn, p, x)
END
END ;
p.typ := DevCPT.notyp; MarkAsUsed(x)
| ashfn: (*ASH*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN intSet THEN
IF (x.class = Nconst) & ((x.conval.intval > 64) OR (x.conval.intval < -64)) THEN err(208)
ELSIF (p.class = Nconst) & (x.class = Nconst) THEN
n := x.conval.intval;
IF n > 0 THEN
WHILE n > 0 DO MulConst(p.conval, two, p.conval, p.typ); DEC(n) END
ELSE
WHILE n < 0 DO DivModConst(p.conval, two, TRUE, p.typ); INC(n) END
END;
p.obj := NIL
ELSE
IF f = Int64 THEN Convert(x, DevCPT.int32typ) END;
typ := p.typ; p := NewOp(Ndop, ash, p, x); p.typ := typ
END
ELSE err(111)
END
| minfn: (*MIN*)
IF p.class # Ntype THEN Op(min, p, x) ELSE err(64) END
| maxfn: (*MAX*)
IF p.class # Ntype THEN Op(max, p, x) ELSE err(64) END
| newfn: (*NEW(p, x...)*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF p.typ.comp = DynArr THEN
IF f IN intSet THEN
IF f = Int64 THEN Convert(x, DevCPT.int32typ) END;
IF (x.class = Nconst) & (x.conval.intval <= 0)
& (~(DevCPM.java IN DevCPM.options) OR (x.conval.intval < 0))THEN err(63) END
ELSE err(111)
END ;
p.right := x; p.typ := p.typ.BaseTyp
ELSIF (p.left # NIL) & (p.left.typ.form = Pointer) THEN
typ := p.left.typ;
WHILE (typ # DevCPT.undftyp) & (typ.BaseTyp # NIL) DO typ := typ.BaseTyp END;
IF typ.sysflag = interface THEN
typ := x.typ;
WHILE (typ # DevCPT.undftyp) & (typ.BaseTyp # NIL) DO typ := typ.BaseTyp END;
IF (f = Pointer) & (typ.sysflag = interface) THEN
p.right := x
ELSE err(169)
END
ELSE err(64)
END
ELSE err(111)
END
| thisrecfn, (*THISRECORD*)
thisarrfn: (*THISARRAY*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN {Int8, Int16, Int32} THEN
IF f < Int32 THEN Convert(x, DevCPT.int32typ) END;
p := NewOp(Ndop, fctno, p, x); p.typ := DevCPT.undftyp
ELSE err(111)
END
| lshfn, rotfn: (*SYSTEM.LSH, SYSTEM.ROT*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF ~(f IN intSet) THEN err(111)
ELSE
IF fctno = lshfn THEN p := NewOp(Ndop, lsh, p, x) ELSE p := NewOp(Ndop, rot, p, x) END ;
p.typ := p.left.typ
END
| getfn, putfn, getrfn, putrfn: (*SYSTEM.GET, SYSTEM.PUT, SYSTEM.GETREG, SYSTEM.PUTREG*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN {Undef..Set, NilTyp, Pointer, ProcTyp, Char16, Int64} THEN
IF (fctno = getfn) OR (fctno = getrfn) THEN
IF NotVar(x) THEN err(112) END ;
t := x; x := p; p := t
END ;
p := NewOp(Nassign, fctno, p, x)
ELSE err(111)
END ;
p.typ := DevCPT.notyp
| bitfn: (*SYSTEM.BIT*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN intSet THEN
p := NewOp(Ndop, bit, p, x)
ELSE err(111)
END ;
p.typ := DevCPT.booltyp
| valfn: (*SYSTEM.VAL*) (* type is changed without considering the byte ordering on the target machine *)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF x.typ.comp = DynArr THEN
IF x.typ.untagged & ((p.typ.comp # DynArr) OR p.typ.untagged) THEN (* ok *)
ELSIF (p.typ.comp = DynArr) & (x.typ.n = p.typ.n) THEN
typ := x.typ;
WHILE typ.comp = DynArr DO typ := typ.BaseTyp END;
tp1 := p.typ;
WHILE tp1.comp = DynArr DO tp1 := tp1.BaseTyp END;
IF typ.size # tp1.size THEN err(115) END
ELSE err(115)
END
ELSIF p.typ.comp = DynArr THEN err(115)
ELSIF (x.class = Nconst) & (f = String8) & (p.typ.form = Int32) & (x.conval.intval2 <= 5) THEN
i := 0; n := 0;
WHILE i < x.conval.intval2 - 1 DO n := 256 * n + ORD(x.conval.ext[i]); INC(i) END;
x := NewIntConst(n)
ELSIF (f IN {Undef, NoTyp, NilTyp}) OR (f IN {String8, String16}) & ~(DevCPM.java IN DevCPM.options) THEN err(111)
END ;
IF (x.class = Nconst) & (x.typ = p.typ) THEN (* ok *)
ELSIF (x.class >= Nconst) OR ((f IN realSet) # (p.typ.form IN realSet))
OR (DevCPM.options * {DevCPM.java, DevCPM.allSysVal} # {}) THEN
t := DevCPT.NewNode(Nmop); t.subcl := val; t.left := x; x := t
ELSE x.readonly := FALSE
END ;
x.typ := p.typ; p := x
| movefn: (*SYSTEM.MOVE*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF (x.class = Nconst) & (f IN {Int8, Int16}) THEN Convert(x, DevCPT.int32typ)
ELSIF ~(f IN {Int32, Pointer}) THEN err(111); x.typ := DevCPT.int32typ
END ;
p.link := x
| assertfn: (*ASSERT*)
IF (f IN intSet - {Int64}) & (x.class = Nconst) THEN
IF (DevCPM.MinHaltNr <= x.conval.intval) & (x.conval.intval <= DevCPM.MaxHaltNr) THEN
BindNodes(Ntrap, DevCPT.notyp, x, x);
Construct(Nif, p, x); Construct(Nifelse, p, NIL); OptIf(p);
ELSE err(218)
END
ELSIF
(DevCPM.java IN DevCPM.options) & ((x.class = Ntype) OR (x.class = Nvar)) & (x.typ.form = Pointer)
THEN
BindNodes(Ntrap, DevCPT.notyp, x, x);
Construct(Nif, p, x); Construct(Nifelse, p, NIL); OptIf(p);
ELSE err(69)
END;
IF p = NIL THEN (* ASSERT(TRUE, num) *)
ELSIF p.class = Ntrap THEN (* ASSERT(FALSE, num) *)
ELSE p.subcl := assertfn
END
| queryfn: (* COM.QUERY *)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF x.typ # DevCPT.guidtyp THEN err(111); x.typ := DevCPT.guidtyp
END;
p.link := x
ELSE err(64)
END ;
par0 := p
END StPar1;
PROCEDURE StParN*(VAR par0: DevCPT.Node; x: DevCPT.Node; fctno, n: SHORTINT);
(* x: n+1-th param of standard proc *)
VAR node: DevCPT.Node; f: SHORTINT; p: DevCPT.Node;
BEGIN p := par0; f := x.typ.form;
IF fctno = newfn THEN (*NEW(p, ..., x...*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF p.typ.comp # DynArr THEN err(64)
ELSIF f IN intSet THEN
IF f = Int64 THEN Convert(x, DevCPT.int32typ) END;
IF (x.class = Nconst) & (x.conval.intval <= 0) THEN err(63) END;
node := p.right;
IF node # NIL THEN (* append x to param list *)
WHILE node.link # NIL DO node := node.link END;
node.link := x
ELSE p.right := x (* error recovery *)
END;
p.typ := p.typ.BaseTyp
ELSE err(111)
END
ELSIF (fctno = movefn) & (n = 2) THEN (*SYSTEM.MOVE*)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF f IN intSet THEN
node := DevCPT.NewNode(Nassign); node.subcl := movefn; node.right := p;
node.left := p.link; p.link := x; p := node
ELSE err(111)
END ;
p.typ := DevCPT.notyp
ELSIF (fctno = queryfn) & (n = 2) THEN (* COM.QUERY *)
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF (x.class < Nconst) & (f = Pointer) & (x.typ.sysflag = interface) THEN
IF ~DevCPT.Extends(p.typ, x.typ) THEN err(164) END;
IF x.readonly THEN err(76) END;
CheckNewParamPair(x, p.link);
MarkAsUsed(x);
node := DevCPT.NewNode(Ndop); node.subcl := queryfn;
node.left := p; node.right := p.link; p.link := NIL; node.right.link := x; p := node
ELSE err(111)
END;
p.typ := DevCPT.booltyp
ELSE err(64)
END ;
par0 := p
END StParN;
PROCEDURE StFct*(VAR par0: DevCPT.Node; fctno: BYTE; parno: SHORTINT);
VAR dim: SHORTINT; x, p: DevCPT.Node;
BEGIN p := par0;
IF fctno <= ashfn THEN
IF (fctno = newfn) & (p.typ # DevCPT.notyp) THEN
IF p.typ.comp = DynArr THEN err(65) END ;
p.typ := DevCPT.notyp
ELSIF (fctno = minfn) OR (fctno = maxfn) THEN
IF (parno < 1) OR (parno = 1) & (p.hint # 1) THEN err(65) END;
p.hint := 0
ELSIF fctno <= sizefn THEN (* 1 param *)
IF parno < 1 THEN err(65) END
ELSE (* more than 1 param *)
IF ((fctno = incfn) OR (fctno = decfn)) & (parno = 1) THEN (*INC, DEC*)
BindNodes(Nassign, DevCPT.notyp, p, NewIntConst(1)); p.subcl := fctno; p.right.typ := p.left.typ
ELSIF (fctno = lenfn) & (parno = 1) THEN (*LEN*)
IF p.typ.form IN {String8, String16} THEN
IF p.class = Nconst THEN p := NewIntConst(p.conval.intval2 - 1)
ELSIF (p.class = Ndop) & (p.subcl = plus) THEN (* propagate to leaf nodes *)
StFct(p.left, lenfn, 1); StFct(p.right, lenfn, 1); p.typ := DevCPT.int32typ
ELSE
WHILE (p.class = Nmop) & (p.subcl = conv) DO p := p.left END;
IF DevCPM.errors = 0 THEN ASSERT(p.class = Nderef) END;
BindNodes(Ndop, DevCPT.int32typ, p, NewIntConst(0)); p.subcl := len
END
ELSIF p.typ.comp = DynArr THEN dim := 0;
WHILE p.class = Nindex DO p := p.left; INC(dim) END ; (* possible side effect ignored *)
BindNodes(Ndop, DevCPT.int32typ, p, NewIntConst(dim)); p.subcl := len
ELSE
p := NewIntConst(p.typ.n)
END
ELSIF parno < 2 THEN err(65)
END
END
ELSIF fctno = assertfn THEN
IF parno = 1 THEN x := NIL;
BindNodes(Ntrap, DevCPT.notyp, x, NewIntConst(AssertTrap));
Construct(Nif, p, x); Construct(Nifelse, p, NIL); OptIf(p);
IF p = NIL THEN (* ASSERT(TRUE) *)
ELSIF p.class = Ntrap THEN (* ASSERT(FALSE) *)
ELSE p.subcl := assertfn
END
ELSIF parno < 1 THEN err(65)
END
ELSIF (fctno >= lchrfn) & (fctno <= bytesfn) THEN
IF parno < 1 THEN err(65) END
ELSIF fctno < validfn THEN (*SYSTEM*)
IF (parno < 1) OR
(fctno > ccfn) & (parno < 2) OR
(fctno = movefn) & (parno < 3) THEN err(65)
END
ELSIF (fctno = thisrecfn) OR (fctno = thisarrfn) THEN
IF parno < 2 THEN err(65) END
ELSE (* COM *)
IF fctno = queryfn THEN
IF parno < 3 THEN err(65) END
ELSE
IF parno < 1 THEN err(65) END
END
END ;
par0 := p
END StFct;
PROCEDURE DynArrParCheck (ftyp: DevCPT.Struct; VAR ap: DevCPT.Node; fvarpar: BOOLEAN);
(* check array compatibility *)
VAR atyp: DevCPT.Struct;
BEGIN (* ftyp.comp = DynArr *)
atyp := ap.typ;
IF atyp.form IN {Char8, Char16, String8, String16} THEN
IF ~fvarpar & (ftyp.BaseTyp.form = Char16) & (atyp.form = String8) THEN Convert(ap, DevCPT.string16typ)
ELSE CheckString(ap, ftyp, 67)
END
ELSE
WHILE (ftyp.comp = DynArr) & ((atyp.comp IN {Array, DynArr}) OR (atyp.form IN {String8, String16})) DO
ftyp := ftyp.BaseTyp; atyp := atyp.BaseTyp
END;
IF ftyp.comp = DynArr THEN err(67)
ELSIF ~fvarpar & (ftyp.form = Pointer) & DevCPT.Extends(atyp, ftyp) THEN (* ok *)
ELSIF ~DevCPT.EqualType(ftyp, atyp) THEN err(66)
END
END
END DynArrParCheck;
PROCEDURE PrepCall*(VAR x: DevCPT.Node; VAR fpar: DevCPT.Object);
BEGIN
IF (x.obj # NIL) & (x.obj.mode IN {LProc, XProc, TProc, CProc}) THEN
fpar := x.obj.link;
IF x.obj.mode = TProc THEN
IF fpar.typ.form = Pointer THEN
IF x.left.class = Nderef THEN x.left := x.left.left (*undo DeRef*) ELSE err(71) END
END;
fpar := fpar.link
END
ELSIF (x.class # Ntype) & (x.typ # NIL) & (x.typ.form = ProcTyp) THEN
fpar := x.typ.link
ELSE err(121); fpar := NIL; x.typ := DevCPT.undftyp
END
END PrepCall;
PROCEDURE Param* (VAR ap: DevCPT.Node; fp: DevCPT.Object); (* checks parameter compatibilty *)
VAR at, ft: DevCPT.Struct;
BEGIN
at := ap.typ; ft := fp.typ;
IF fp.ptyp # NIL THEN ft := fp.ptyp END; (* get original formal type *)
IF ft.form # Undef THEN
IF (ap.class = Ntype) OR (ap.class = Nproc) & (ft.form # ProcTyp) THEN err(126) END;
IF fp.mode = VarPar THEN
IF ODD(fp.sysflag DIV nilBit) & (at = DevCPT.niltyp) THEN (* ok *)
ELSIF (ft.comp = Record) & ~ft.untagged & (ap.class = Ndop) & (ap.subcl = thisrecfn) THEN (* ok *)
ELSIF (ft.comp = DynArr) & ~ft.untagged & (ft.n = 0) & (ap.class = Ndop) & (ap.subcl = thisarrfn) THEN
(* ok *)
ELSE
IF fp.vis = inPar THEN
IF (ft = DevCPT.guidtyp) & (ap.class = Nconst) & (at.form = String8) THEN
StringToGuid(ap); at := ap.typ
END;
IF ~NotVar(ap) THEN CheckLeaf(ap, FALSE) END
ELSE
IF NotVar(ap) THEN err(122)
ELSIF ap.readonly THEN err(76)
ELSIF (ap.obj # NIL) & ODD(ap.obj.sysflag DIV newBit) & ~ODD(fp.sysflag DIV newBit) THEN
err(167)
ELSE MarkAsUsed(ap); CheckLeaf(ap, FALSE)
END
END;
IF ft.comp = DynArr THEN DynArrParCheck(ft, ap, fp.vis # inPar)
ELSIF ODD(fp.sysflag DIV newBit) THEN
IF ~DevCPT.Extends(at, ft) THEN err(123) END
ELSIF (ft = DevCPT.sysptrtyp) & (at.form = Pointer) THEN (* ok *)
ELSIF (fp.vis # outPar) & (ft.comp = Record) & DevCPT.Extends(at, ft) THEN (* ok *)
ELSIF covarOut & (fp.vis = outPar) & (ft.form = Pointer) & DevCPT.Extends(ft, at) THEN (* ok *)
ELSIF fp.vis = inPar THEN CheckAssign(ft, ap)
ELSIF ~DevCPT.EqualType(ft, at) THEN err(123)
END
END
ELSIF ft.comp = DynArr THEN DynArrParCheck(ft, ap, FALSE)
ELSE CheckAssign(ft, ap)
END
END
END Param;
PROCEDURE StaticLink*(dlev: BYTE; var: BOOLEAN);
VAR scope: DevCPT.Object;
BEGIN
scope := DevCPT.topScope;
WHILE dlev > 0 DO DEC(dlev);
INCL(scope.link.conval.setval, slNeeded);
scope := scope.left
END;
IF var THEN INCL(scope.link.conval.setval, imVar) END (* !!! *)
END StaticLink;
PROCEDURE Call*(VAR x: DevCPT.Node; apar: DevCPT.Node; fp: DevCPT.Object);
VAR typ: DevCPT.Struct; p: DevCPT.Node; lev: BYTE;
BEGIN
IF x.class = Nproc THEN typ := x.typ;
lev := x.obj.mnolev;
IF lev > 0 THEN StaticLink(SHORT(SHORT(DevCPT.topScope.mnolev-lev)), FALSE) END ; (* !!! *)
IF x.obj.mode = IProc THEN err(121) END
ELSIF (x.class = Nfield) & (x.obj.mode = TProc) THEN typ := x.typ;
x.class := Nproc; p := x.left; x.left := NIL; p.link := apar; apar := p; fp := x.obj.link
ELSE typ := x.typ.BaseTyp
END ;
BindNodes(Ncall, typ, x, apar); x.obj := fp
END Call;
PROCEDURE Enter*(VAR procdec: DevCPT.Node; stat: DevCPT.Node; proc: DevCPT.Object);
VAR x: DevCPT.Node;
BEGIN
x := DevCPT.NewNode(Nenter); x.typ := DevCPT.notyp; x.obj := proc;
x.left := procdec; x.right := stat; procdec := x
END Enter;
PROCEDURE Return*(VAR x: DevCPT.Node; proc: DevCPT.Object);
VAR node: DevCPT.Node;
BEGIN
IF proc = NIL THEN (* return from module *)
IF x # NIL THEN err(124) END
ELSE
IF x # NIL THEN CheckAssign(proc.typ, x)
ELSIF proc.typ # DevCPT.notyp THEN err(124)
END
END ;
node := DevCPT.NewNode(Nreturn); node.typ := DevCPT.notyp; node.obj := proc; node.left := x; x := node
END Return;
PROCEDURE Assign*(VAR x: DevCPT.Node; y: DevCPT.Node);
BEGIN
IF (x.class >= Nconst) OR (x.typ.form IN {String8, String16}) THEN err(56) END ;
CheckAssign(x.typ, y);
IF x.readonly THEN err(76)
ELSIF (x.obj # NIL) & ODD(x.obj.sysflag DIV newBit) THEN err(167)
END ;
MarkAsUsed(x);
IF (y.class = Nconst) & (y.typ.form IN {String8, String16}) & (x.typ.form # Pointer) THEN AssignString(x, y)
ELSE BindNodes(Nassign, DevCPT.notyp, x, y); x.subcl := assign
END
END Assign;
PROCEDURE Inittd*(VAR inittd, last: DevCPT.Node; typ: DevCPT.Struct);
VAR node: DevCPT.Node;
BEGIN
node := DevCPT.NewNode(Ninittd); node.typ := typ;
node.conval := DevCPT.NewConst(); node.conval.intval := typ.txtpos;
IF inittd = NIL THEN inittd := node ELSE last.link := node END ;
last := node
END Inittd;
(* handling of temporary variables for string operations *)
PROCEDURE Overlap (left, right: DevCPT.Node): BOOLEAN;
BEGIN
IF right.class = Nconst THEN
RETURN FALSE
ELSIF (right.class = Ndop) & (right.subcl = plus) THEN
RETURN Overlap(left, right.left) OR Overlap(left, right.right)
ELSE
WHILE right.class = Nmop DO right := right.left END;
IF right.class = Nderef THEN right := right.left END;
IF left.typ.BaseTyp # right.typ.BaseTyp THEN RETURN FALSE END;
LOOP
IF left.class = Nvarpar THEN
WHILE (right.class = Nindex) OR (right.class = Nfield) OR (right.class = Nguard) DO
right := right.left
END;
RETURN (right.class # Nvar) OR (right.obj.mnolev < left.obj.mnolev)
ELSIF right.class = Nvarpar THEN
WHILE (left.class = Nindex) OR (left.class = Nfield) OR (left.class = Nguard) DO left := left.left END;
RETURN (left.class # Nvar) OR (left.obj.mnolev < right.obj.mnolev)
ELSIF (left.class = Nvar) & (right.class = Nvar) THEN
RETURN left.obj = right.obj
ELSIF (left.class = Nderef) & (right.class = Nderef) THEN
RETURN TRUE
ELSIF (left.class = Nindex) & (right.class = Nindex) THEN
IF (left.right.class = Nconst) & (right.right.class = Nconst)
& (left.right.conval.intval # right.right.conval.intval) THEN RETURN FALSE END;
left := left.left; right := right.left
ELSIF (left.class = Nfield) & (right.class = Nfield) THEN
IF left.obj # right.obj THEN RETURN FALSE END;
left := left.left; right := right.left;
WHILE left.class = Nguard DO left := left.left END;
WHILE right.class = Nguard DO right := right.left END
ELSE
RETURN FALSE
END
END
END
END Overlap;
PROCEDURE GetStaticLength (n: DevCPT.Node; OUT length: INTEGER);
VAR x: INTEGER;
BEGIN
IF n.class = Nconst THEN
length := n.conval.intval2 - 1
ELSIF (n.class = Ndop) & (n.subcl = plus) THEN
GetStaticLength(n.left, length); GetStaticLength(n.right, x);
IF (length >= 0) & (x >= 0) THEN length := length + x ELSE length := -1 END
ELSE
WHILE (n.class = Nmop) & (n.subcl = conv) DO n := n.left END;
IF (n.class = Nderef) & (n.subcl = 1) THEN n := n.left END;
IF n.typ.comp = Array THEN
length := n.typ.n - 1
ELSIF n.typ.comp = DynArr THEN
length := -1
ELSE (* error case *)
length := 4
END
END
END GetStaticLength;
PROCEDURE GetMaxLength (n: DevCPT.Node; VAR stat, last: DevCPT.Node; OUT length: DevCPT.Node);
VAR x: DevCPT.Node; d: INTEGER; obj: DevCPT.Object;
BEGIN
IF n.class = Nconst THEN
length := NewIntConst(n.conval.intval2 - 1)
ELSIF (n.class = Ndop) & (n.subcl = plus) THEN
GetMaxLength(n.left, stat, last, length); GetMaxLength(n.right, stat, last, x);
IF (length.class = Nconst) & (x.class = Nconst) THEN ConstOp(plus, length, x)
ELSE BindNodes(Ndop, length.typ, length, x); length.subcl := plus
END
ELSE
WHILE (n.class = Nmop) & (n.subcl = conv) DO n := n.left END;
IF (n.class = Nderef) & (n.subcl = 1) THEN n := n.left END;
IF n.typ.comp = Array THEN
length := NewIntConst(n.typ.n - 1)
ELSIF n.typ.comp = DynArr THEN
d := 0;
WHILE n.class = Nindex DO n := n.left; INC(d) END;
ASSERT((n.class = Nderef) OR (n.class = Nvar) OR (n.class = Nvarpar));
IF (n.class = Nderef) & (n.left.class # Nvar) & (n.left.class # Nvarpar) THEN
GetTempVar("@tmp", n.left.typ, obj);
x := NewLeaf(obj); Assign(x, n.left); Link(stat, last, x);
n.left := NewLeaf(obj); (* tree is manipulated here *)
n := NewLeaf(obj); DeRef(n)
END;
IF n.typ.untagged & (n.typ.comp = DynArr) & (n.typ.BaseTyp.form IN {Char8, Char16}) THEN
StrDeref(n);
BindNodes(Ndop, DevCPT.int32typ, n, NewIntConst(d)); n.subcl := len;
BindNodes(Ndop, DevCPT.int32typ, n, NewIntConst(1)); n.subcl := plus
ELSE
BindNodes(Ndop, DevCPT.int32typ, n, NewIntConst(d)); n.subcl := len;
END;
length := n
ELSE (* error case *)
length := NewIntConst(4)
END
END
END GetMaxLength;
PROCEDURE CheckBuffering* (
VAR n: DevCPT.Node; left: DevCPT.Node; par: DevCPT.Object; VAR stat, last: DevCPT.Node
);
VAR length, x: DevCPT.Node; obj: DevCPT.Object; typ: DevCPT.Struct; len, xlen: INTEGER;
BEGIN
IF (n.typ.form IN {String8, String16}) & ~(DevCPM.java IN DevCPM.options)
& ((n.class = Ndop) & (n.subcl = plus) & ((left = NIL) OR Overlap(left, n.right))
OR (n.class = Nmop) & (n.subcl = conv) & (left = NIL)
OR (par # NIL) & (par.vis = inPar) & (par.typ.comp = Array)) THEN
IF (par # NIL) & (par.typ.comp = Array) THEN
len := par.typ.n - 1
ELSE
IF left # NIL THEN GetStaticLength(left, len) ELSE len := -1 END;
GetStaticLength(n, xlen);
IF (len = -1) OR (xlen # -1) & (xlen < len) THEN len := xlen END
END;
IF len # -1 THEN
typ := DevCPT.NewStr(Comp, Array); typ.n := len + 1; typ.BaseTyp := n.typ.BaseTyp;
GetTempVar("@str", typ, obj);
x := NewLeaf(obj); Assign(x, n); Link(stat, last, x);
n := NewLeaf(obj)
ELSE
IF left # NIL THEN GetMaxLength(left, stat, last, length)
ELSE GetMaxLength(n, stat, last, length)
END;
typ := DevCPT.NewStr(Pointer, Basic);
typ.BaseTyp := DevCPT.NewStr(Comp, DynArr); typ.BaseTyp.BaseTyp := n.typ.BaseTyp;
GetTempVar("@ptr", typ, obj);
x := NewLeaf(obj); Construct(Nassign, x, length); x.subcl := newfn; Link(stat, last, x);
x := NewLeaf(obj); DeRef(x); Assign(x, n); Link(stat, last, x);
n := NewLeaf(obj); DeRef(n)
END;
StrDeref(n)
ELSIF (n.typ.form = Pointer) & (n.typ.sysflag = interface) & (left = NIL)
& ((par # NIL) OR (n.class = Ncall))
& ((n.class # Nvar) OR (n.obj.mnolev <= 0)) THEN
GetTempVar("@cip", DevCPT.punktyp, obj);
x := NewLeaf(obj); Assign(x, n); Link(stat, last, x);
n := NewLeaf(obj)
END
END CheckBuffering;
PROCEDURE CheckVarParBuffering* (VAR n: DevCPT.Node; VAR stat, last: DevCPT.Node);
VAR x: DevCPT.Node; obj: DevCPT.Object;
BEGIN
IF (n.class # Nvar) OR (n.obj.mnolev <= 0) THEN
GetTempVar("@ptr", n.typ, obj);
x := NewLeaf(obj); Assign(x, n); Link(stat, last, x);
n := NewLeaf(obj)
END
END CheckVarParBuffering;
(* case optimization *)
PROCEDURE Evaluate (n: DevCPT.Node; VAR min, max, num, dist: INTEGER; VAR head: DevCPT.Node);
VAR a: INTEGER;
BEGIN
IF n.left # NIL THEN
a := MIN(INTEGER); Evaluate(n.left, min, a, num, dist, head);
IF n.conval.intval - a > dist THEN dist := n.conval.intval - a; head := n END
ELSIF n.conval.intval < min THEN
min := n.conval.intval
END;
IF n.right # NIL THEN
a := MAX(INTEGER); Evaluate(n.right, a, max, num, dist, head);
IF a - n.conval.intval2 > dist THEN dist := a - n.conval.intval2; head := n END
ELSIF n.conval.intval2 > max THEN
max := n.conval.intval2
END;
INC(num);
IF n.conval.intval < n.conval.intval2 THEN
INC(num);
IF n.conval.intval2 - n.conval.intval > dist THEN dist := n.conval.intval2 - n.conval.intval; head := n END
END
END Evaluate;
PROCEDURE Rebuild (VAR root: DevCPT.Node; head: DevCPT.Node);
BEGIN
IF root # head THEN
IF head.conval.intval2 < root.conval.intval THEN
Rebuild(root.left, head);
root.left := head.right; head.right := root; root := head
ELSE
Rebuild(root.right, head);
root.right := head.left; head.left := root; root := head
END
END
END Rebuild;
PROCEDURE OptimizeCase* (VAR n: DevCPT.Node);
VAR min, max, num, dist, limit: INTEGER; head: DevCPT.Node;
BEGIN
IF n # NIL THEN
min := MAX(INTEGER); max := MIN(INTEGER); num := 0; dist := 0; head := n;
Evaluate(n, min, max, num, dist, head);
limit := 6 * num;
IF limit < 100 THEN limit := 100 END;
IF (num > 4) & ((min > MAX(INTEGER) - limit) OR (max < min + limit)) THEN
INCL(n.conval.setval, useTable)
ELSE
IF num > 4 THEN Rebuild(n, head) END;
INCL(n.conval.setval, useTree);
OptimizeCase(n.left);
OptimizeCase(n.right)
END
END
END OptimizeCase;
(*
PROCEDURE ShowTree (n: DevCPT.Node; opts: SET);
BEGIN
IF n # NIL THEN
IF opts = {} THEN opts := n.conval.setval END;
IF useTable IN opts THEN
IF n.left # NIL THEN ShowTree(n.left, opts); DevCPM.LogW(",") END;
DevCPM.LogWNum(n.conval.intval, 1);
IF n.conval.intval2 > n.conval.intval THEN DevCPM.LogW("-"); DevCPM.LogWNum(n.conval.intval2, 1)
END;
IF n.right # NIL THEN DevCPM.LogW(","); ShowTree(n.right, opts) END
ELSIF useTree IN opts THEN
DevCPM.LogW("("); ShowTree(n.left, {}); DevCPM.LogW("|"); DevCPM.LogWNum(n.conval.intval, 1);
IF n.conval.intval2 > n.conval.intval THEN DevCPM.LogW("-"); DevCPM.LogWNum(n.conval.intval2, 1)
END;
DevCPM.LogW("|"); ShowTree(n.right, {}); DevCPM.LogW(")")
ELSE
ShowTree(n.left, opts); DevCPM.LogW(" "); DevCPM.LogWNum(n.conval.intval, 1);
IF n.conval.intval2 > n.conval.intval THEN DevCPM.LogW("-"); DevCPM.LogWNum(n.conval.intval2, 1)
END;
DevCPM.LogW(" "); ShowTree(n.right, opts)
END
END
END ShowTree;
*)
BEGIN
zero := DevCPT.NewConst(); zero.intval := 0; zero.realval := 0;
one := DevCPT.NewConst(); one.intval := 1; one.realval := 0;
two := DevCPT.NewConst(); two.intval := 2; two.realval := 0;
dummy := DevCPT.NewConst();
quot := DevCPT.NewConst()
END DevCPB.
| Dev/Mod/CPB.odc |
MODULE DevCPC486;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, ccall support for procedure variable calls
- 20070409, bh, OUT pointer initialization in empty procedures
- 20091228, bh, corrections for S.VAL(LONGINT, real) in Convert & ConvMove
- 20150422, center #41, fixing a register allocation problem
- 20150422, center #42, fixing LONGINT division TRAP
- 20150513, center #43, extending the size of code procedures
- 20160324, center #111, code cleanups
- 20160809, center #121, compiler warning regarding unreleased register
- 20160826, center #126, Compiler TRAP for SYSTEM.VAL(LONGINT, intreg)
- 20170612, center #160, outdated link to OP2.Paper.ps
- 20170811, luowy, support for 16 bit aligment "ccall16" (includes center #169)
- 20180614, center #188, compiler trap with SYSTEM.VAL
- 20200608, center #207, fixed compiler trap with constant boolean expression
"
issues = "
- ...
"
**)
IMPORT SYSTEM, DevCPM, DevCPT, DevCPE, DevCPL486;
CONST
initializeAll = FALSE; (* initialize all local variable to zero *)
initializeOut = FALSE; (* initialize all OUT parameters to zero *)
initializeDyn = FALSE; (* initialize all open array OUT parameters to zero *)
initializeStr = FALSE; (* initialize rest of string value parameters to zero *)
FpuControlRegister = 33EH; (* value for fpu control register initialization *)
(* structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; String16 = 17; Int64 = 18; Guid = 23;
VString16to8 = 29; VString8 = 30; VString16 = 31;
intSet = {Int8..Int32, Int64}; realSet = {Real32, Real64};
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(* item base modes (=object modes) *)
Var = 1; VarPar = 2; Con = 3; Fld = 4; Typ = 5; LProc = 6; XProc = 7; CProc = 9; IProc = 10; TProc = 13;
(* item modes for i386 *)
Ind = 14; Abs = 15; Stk = 16; Cond = 17; Reg = 18; DInd = 19;
(* symbol values and ops *)
times = 1; slash = 2; div = 3; mod = 4;
and = 5; plus = 6; minus = 7; or = 8; eql = 9;
neq = 10; lss = 11; leq = 12; gtr = 13; geq = 14;
in = 15; is = 16; ash = 17; msk = 18; len = 19;
conv = 20; abs = 21; cap = 22; odd = 23; not = 33;
adr = 24; cc = 25; bit = 26; lsh = 27; rot = 28; val = 29;
getrfn = 26; putrfn = 27;
min = 34; max = 35; typ = 36;
(* procedure flags (conval.setval) *)
hasBody = 1; isRedef = 2; slNeeded = 3; imVar = 4; isGuarded = 30; isCallback = 31;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval) *)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
false = 0; true = 1; nil = 0;
(* registers *)
AX = 0; CX = 1; DX = 2; BX = 3; SP = 4; BP = 5; SI = 6; DI = 7; AH = 4; CH = 5; DH = 6; BH = 7;
stk = 31; mem = 30; con = 29; float = 28; high = 27; short = 26; deref = 25; wreg = {AX, BX, CX, DX, SI, DI};
(* GenShiftOp *)
ROL = 0; ROR = 8H; SHL = 20H; SHR = 28H; SAR = 38H;
(* GenBitOp *)
BT = 20H; BTS = 28H; BTR = 30H;
(* GenFDOp *)
FADD = 0; FMUL = 8H; FCOM = 10H; FCOMP = 18H; FSUB = 20H; FSUBR = 28H; FDIV = 30H; FDIVR = 38H;
(* GenFMOp *)
FABS = 1E1H; FCHS = 1E0H; FTST = 1E4H; FSTSW = 7E0H; FUCOM = 2E9H;
(* GenCode *)
SAHF = 9EH; WAIT = 9BH;
(* condition codes *)
ccB = 2; ccAE = 3; ccBE = 6; ccA = 7; (* unsigned *)
ccL = 12; ccGE = 13; ccLE = 14; ccG = 15; (* signed *)
ccE = 4; ccNE = 5; ccS = 8; ccNS = 9; ccO = 0; ccNO = 1;
ccAlways = -1; ccNever = -2; ccCall = -3;
(* sysflag *)
untagged = 1; callback = 2; noAlign = 3; union = 7;
interface = 10; ccall = -10; guarded = 10; noframe = 16;
nilBit = 1; enumBits = 8; new = 1; iid = 2;
stackArray = 120;
(* system trap numbers *)
withTrap = -1; caseTrap = -2; funcTrap = -3; typTrap = -4;
recTrap = -5; ranTrap = -6; inxTrap = -7; copyTrap = -8;
(* module visibility of objects *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* pointer init limits *)
MaxPtrs = 10; MaxPush = 4;
Tag0Offset = 12;
Mth0Offset = -4;
ArrDOffs = 8;
numPreIntProc = 2;
stackAllocLimit = 2048;
VAR
imLevel*: ARRAY 64 OF BYTE;
intHandler*: DevCPT.Object;
inxchk, ovflchk, ranchk, typchk, ptrinit, hints: BOOLEAN;
WReg, BReg, AllReg: SET; FReg: INTEGER;
ptrTab: ARRAY MaxPtrs OF INTEGER;
stkAllocLbl: DevCPL486.Label;
procedureUsesFpu: BOOLEAN;
PROCEDURE Init* (opt: SET);
CONST chk = 0; achk = 1; hint = 29;
BEGIN
inxchk := chk IN opt; ovflchk := achk IN opt; ranchk := achk IN opt; typchk := chk IN opt; ptrinit := chk IN opt;
hints := hint IN opt;
stkAllocLbl := DevCPL486.NewLbl
END Init;
PROCEDURE Reversed (cond: BYTE): BYTE; (* reversed condition *)
BEGIN
IF cond = lss THEN RETURN gtr
ELSIF cond = gtr THEN RETURN lss
ELSIF cond = leq THEN RETURN geq
ELSIF cond = geq THEN RETURN leq
ELSE RETURN cond
END
END Reversed;
PROCEDURE Inverted (cc: INTEGER): INTEGER; (* inverted sense of condition code *)
BEGIN
IF ODD(cc) THEN RETURN cc-1 ELSE RETURN cc+1 END
END Inverted;
PROCEDURE setCC* (VAR x: DevCPL486.Item; rel: BYTE; reversed, signed: BOOLEAN);
BEGIN
IF reversed THEN rel := Reversed(rel) END;
CASE rel OF
false: x.offset := ccNever
| true: x.offset := ccAlways
| eql: x.offset := ccE
| neq: x.offset := ccNE
| lss: IF signed THEN x.offset := ccL ELSE x.offset := ccB END
| leq: IF signed THEN x.offset := ccLE ELSE x.offset := ccBE END
| gtr: IF signed THEN x.offset := ccG ELSE x.offset := ccA END
| geq: IF signed THEN x.offset := ccGE ELSE x.offset := ccAE END
END;
x.mode := Cond; x.form := Bool; x.reg := 0;
IF reversed THEN x.reg := 1 END;
IF signed THEN INC(x.reg, 2) END
END setCC;
PROCEDURE StackAlloc*; (* pre: len = CX bytes; post: len = CX words *)
BEGIN
DevCPL486.GenJump(ccCall, stkAllocLbl, FALSE)
END StackAlloc;
PROCEDURE^ CheckAv* (reg: INTEGER);
PROCEDURE AdjustStack (val: INTEGER);
VAR c, sp: DevCPL486.Item;
BEGIN
IF val < -stackAllocLimit THEN
CheckAv(CX);
DevCPL486.MakeConst(c, -val, Int32); DevCPL486.MakeReg(sp, CX, Int32); DevCPL486.GenMove(c, sp);
StackAlloc
ELSIF val # 0 THEN
DevCPL486.MakeConst(c, val, Int32); DevCPL486.MakeReg(sp, SP, Int32); DevCPL486.GenAdd(c, sp, FALSE)
END
END AdjustStack;
PROCEDURE DecStack (form: INTEGER);
BEGIN
IF form IN {Real64, Int64} THEN AdjustStack(-8) ELSE AdjustStack(-4) END
END DecStack;
PROCEDURE IncStack (form: INTEGER);
BEGIN
IF form IN {Real64, Int64} THEN AdjustStack(8) ELSE AdjustStack(4) END
END IncStack;
(*-----------------register handling------------------*)
PROCEDURE SetReg* (reg: SET);
BEGIN
AllReg := reg; WReg := reg; BReg := reg * {0..3} + SYSTEM.LSH(reg * {0..3}, 4); FReg := 8
END SetReg;
PROCEDURE CheckReg*;
VAR reg: SET;
BEGIN
reg := AllReg - WReg;
IF reg # {} THEN
DevCPM.err(-777); (* register not released *)
IF AX IN reg THEN DevCPM.LogWStr(" AX") END;
IF BX IN reg THEN DevCPM.LogWStr(" BX") END;
IF CX IN reg THEN DevCPM.LogWStr(" CX") END;
IF DX IN reg THEN DevCPM.LogWStr(" DX") END;
IF SI IN reg THEN DevCPM.LogWStr(" SI") END;
IF DI IN reg THEN DevCPM.LogWStr(" DI") END;
WReg := AllReg; BReg := AllReg * {0..3} + SYSTEM.LSH(AllReg * {0..3}, 4)
END;
IF FReg < 8 THEN DevCPM.err(-778); FReg := 8 (* float register not released *)
ELSIF FReg > 8 THEN DevCPM.err(-779); FReg := 8
END
END CheckReg;
PROCEDURE CheckAv* (reg: INTEGER);
BEGIN
ASSERT(reg IN WReg)
END CheckAv;
PROCEDURE GetReg (VAR x: DevCPL486.Item; f: BYTE; hint, stop: SET);
VAR n: INTEGER; s, s1: SET;
BEGIN
CASE f OF
| Byte, Bool, Char8, Int8:
s := BReg * {0..3} - stop;
IF (high IN stop) OR (high IN hint) & (s - hint # {}) THEN n := 0;
IF s = {} THEN DevCPM.err(215); WReg := wreg; BReg := {0..7}; s := {0..7} END;
IF s - hint # {} THEN s := s - hint END;
WHILE ~(n IN s) DO INC(n) END
ELSE
s := BReg - (stop * {0..3}) - SYSTEM.LSH(stop * {0..3}, 4); n := 0;
IF s = {} THEN DevCPM.err(215); WReg := wreg; BReg := {0..7}; s := {0..7} END;
s1 := s - (hint * {0..3}) - SYSTEM.LSH(hint * {0..3}, 4);
IF s1 # {} THEN s := s1 END;
WHILE ~(n IN s) & ~(n + 4 IN s) DO INC(n) END;
IF ~(n IN s) THEN n := n + 4 END
END;
EXCL(BReg, n); EXCL(WReg, n MOD 4)
| Int16, Int32, Set, String8, NilTyp, Pointer, ProcTyp, Comp, Char16, String16:
s := WReg - stop;
IF high IN stop THEN s := s * {0..3} END;
IF s = {} THEN DevCPM.err(215); WReg := wreg; BReg := {0..7}; s := wreg END;
s1 := s - hint;
IF high IN hint THEN s1 := s1 * {0..3} END;
IF s1 # {} THEN s := s1 END;
IF AX IN s THEN n := AX
ELSIF DX IN s THEN n := DX
ELSIF CX IN s THEN n := CX
ELSIF SI IN s THEN n := SI
ELSIF DI IN s THEN n := DI
ELSE n := BX (* not used *)
END;
EXCL(WReg, n);
IF n < 4 THEN EXCL(BReg, n); EXCL(BReg, n + 4) END
| Real32, Real64:
IF (FReg = 0) OR (float IN stop) THEN DevCPM.err(216); FReg := 99 END;
DEC(FReg); n := 0
END;
DevCPL486.MakeReg(x, n, f);
END GetReg;
PROCEDURE FreeReg (n, f: INTEGER);
BEGIN
IF f <= Int8 THEN
INCL(BReg, n);
IF (n + 4) MOD 8 IN BReg THEN INCL(WReg, n MOD 4) END
ELSIF f IN realSet THEN
INC(FReg)
ELSIF n IN AllReg THEN
INCL(WReg, n);
IF n < 4 THEN INCL(BReg, n); INCL(BReg, n + 4) END
END
END FreeReg;
PROCEDURE FreeWReg (n: INTEGER);
BEGIN
IF n IN AllReg THEN
INCL(WReg, n);
IF n < 4 THEN INCL(BReg, n); INCL(BReg, n + 4) END
END
END FreeWReg;
PROCEDURE Free* (VAR x: DevCPL486.Item);
BEGIN
CASE x.mode OF
| Var, VarPar, Abs: IF x.scale # 0 THEN FreeWReg(x.index) END
| Ind: FreeWReg(x.reg);
IF x.scale # 0 THEN FreeWReg(x.index) END
| Reg: FreeReg(x.reg, x.form);
IF x.form = Int64 THEN FreeWReg(x.index) END
ELSE
END
END Free;
PROCEDURE FreeHi (VAR x: DevCPL486.Item); (* free hi byte of word reg *)
BEGIN
IF x.mode = Reg THEN
IF x.form = Int64 THEN FreeWReg(x.index)
ELSIF x.reg < 4 THEN INCL(BReg, x.reg + 4)
END
END
END FreeHi;
PROCEDURE Fits* (VAR x: DevCPL486.Item; stop: SET): BOOLEAN; (* x.mode = Reg *)
BEGIN
IF (short IN stop) & (x.form <= Int8) THEN RETURN FALSE END;
IF x.form <= Int8 THEN RETURN ~(x.reg MOD 4 IN stop) & ((x.reg < 4) OR ~(high IN stop))
ELSIF x.form IN realSet THEN RETURN ~(float IN stop)
ELSIF x.form = Int64 THEN RETURN ~(x.reg IN stop) & ~(x.index IN stop)
ELSE RETURN ~(x.reg IN stop) & ((x.reg < 4) OR ~(high IN stop))
END
END Fits;
PROCEDURE Pop* (VAR r: DevCPL486.Item; f: BYTE; hint, stop: SET);
VAR rh: DevCPL486.Item;
BEGIN
IF f = Int64 THEN
GetReg(r, Int32, hint, stop); DevCPL486.GenPop(r);
GetReg(rh, Int32, hint, stop); DevCPL486.GenPop(rh);
r.form := Int64; r.index := rh.reg
ELSE
IF f < Int16 THEN INCL(stop, high) END;
GetReg(r, f, hint, stop); DevCPL486.GenPop(r)
END
END Pop;
PROCEDURE^ LoadLong (VAR x: DevCPL486.Item; hint, stop: SET);
PROCEDURE Load* (VAR x: DevCPL486.Item; hint, stop: SET); (* = Assert(x, hint, stop + {mem, stk}) *)
VAR r: DevCPL486.Item; f: BYTE;
BEGIN
f := x.typ.form;
IF x.mode = Con THEN
IF (short IN stop) & (x.form IN {Int8, Int16, Bool, Char8, Char16}) THEN f := Int32; x.form := Int32 END;
IF con IN stop THEN
IF f = Int64 THEN LoadLong(x, hint, stop)
ELSE
GetReg(r, f, hint, stop); DevCPL486.GenMove(x, r);
x.mode := Reg; x.reg := r.reg; x.form := f
END
END
ELSIF x.mode = Stk THEN
IF f IN realSet THEN
GetReg(r, f, hint, stop); DevCPL486.GenFLoad(x); IncStack(x.form)
ELSE
Pop(r, f, hint, stop)
END;
x.mode := Reg; x.reg := r.reg; x.index := r.index; x.form := f
ELSIF (short IN stop) & (x.form IN {Int8, Int16, Bool, Char8, Char16}) THEN
Free(x); GetReg(r, Int32, hint, stop); DevCPL486.GenExtMove(x, r);
x.mode := Reg; x.reg := r.reg; x.form := Int32
ELSIF (x.mode # Reg) OR ~Fits(x, stop) THEN
IF f = Int64 THEN LoadLong(x, hint, stop)
ELSE
Free(x); GetReg(r, f, hint, stop);
IF f IN realSet THEN DevCPL486.GenFLoad(x) ELSE DevCPL486.GenMove(x, r) END;
x.mode := Reg; x.reg := r.reg; x.form := f
END
END
END Load;
PROCEDURE Push* (VAR x: DevCPL486.Item);
VAR y: DevCPL486.Item;
BEGIN
IF x.form IN realSet THEN
Load(x, {}, {}); DecStack(x.form);
Free(x); x.mode := Stk;
IF x.typ = DevCPT.intrealtyp THEN x.form := Int64 END;
DevCPL486.GenFStore(x, TRUE)
ELSIF x.form = Int64 THEN
Free(x); x.form := Int32; y := x;
IF x.mode = Reg THEN y.reg := x.index ELSE INC(y.offset, 4) END;
DevCPL486.GenPush(y); DevCPL486.GenPush(x);
x.mode := Stk; x.form := Int64
ELSE
IF x.form < Int16 THEN Load(x, {}, {high})
ELSIF x.form = Int16 THEN Load(x, {}, {})
END;
Free(x); DevCPL486.GenPush(x); x.mode := Stk
END
END Push;
PROCEDURE Assert* (VAR x: DevCPL486.Item; hint, stop: SET);
BEGIN
IF (short IN stop) & (x.form IN {Int8, Int16, Bool, Char8, Char16}) & (x.mode # Con) THEN
IF (wreg - stop = {}) & ~(stk IN stop) THEN Load(x, {}, {short}); Push(x)
ELSE Load(x, hint, stop);
END
ELSE
CASE x.mode OF
| Var, VarPar: IF ~(mem IN stop) THEN RETURN END
| Con: IF ~(con IN stop) THEN RETURN END
| Ind: IF ~(mem IN stop) & ~(x.reg IN stop) & ((x.scale = 0) OR ~(x.index IN stop)) THEN RETURN END
| Abs: IF ~(mem IN stop) & ((x.scale = 0) OR ~(x.index IN stop)) THEN RETURN END
| Stk: IF ~(stk IN stop) THEN RETURN END
| Reg: IF Fits(x, stop) THEN RETURN END
ELSE RETURN
END;
IF ((float IN stop) OR ~(x.typ.form IN realSet) & (wreg - stop = {})) & ~(stk IN stop) THEN Push(x)
ELSE Load(x, hint, stop)
END
END
END Assert;
(*------------------------------------------------*)
PROCEDURE LoadR (VAR x: DevCPL486.Item);
BEGIN
IF x.mode # Reg THEN
Free(x); DevCPL486.GenFLoad(x);
IF x.mode = Stk THEN IncStack(x.form) END;
GetReg(x, Real32, {}, {})
END
END LoadR;
PROCEDURE PushR (VAR x: DevCPL486.Item);
BEGIN
IF x.mode # Reg THEN LoadR(x) END;
DecStack(x.form);
Free(x); x.mode := Stk; DevCPL486.GenFStore(x, TRUE)
END PushR;
PROCEDURE LoadW (VAR x: DevCPL486.Item; hint, stop: SET);
VAR r: DevCPL486.Item;
BEGIN
IF x.mode = Stk THEN
Pop(x, x.form, hint, stop)
ELSE
Free(x); GetReg(r, x.form, hint, stop);
DevCPL486.GenMove(x, r);
x.mode := Reg; x.reg := r.reg
END
END LoadW;
PROCEDURE LoadL (VAR x: DevCPL486.Item; hint, stop: SET);
VAR r: DevCPL486.Item;
BEGIN
IF x.mode = Stk THEN
Pop(x, x.form, hint, stop);
IF (x.form < Int32) OR (x.form = Char16) THEN
r := x; x.form := Int32; DevCPL486.GenExtMove(r, x)
END
ELSE
Free(x);
IF (x.form < Int32) OR (x.form = Char16) THEN GetReg(r, Int32, hint, stop) ELSE GetReg(r, x.form, hint, stop) END;
IF x.mode = Con THEN x.form := r.form END;
IF x.form # r.form THEN DevCPL486.GenExtMove(x, r) ELSE DevCPL486.GenMove(x, r) END;
x.mode := Reg; x.reg := r.reg; x.form := r.form
END
END LoadL;
PROCEDURE LoadLong (VAR x: DevCPL486.Item; hint, stop: SET);
VAR r, rh: DevCPL486.Item; offs: INTEGER;
BEGIN
IF x.form = Int64 THEN
IF x.mode = Stk THEN
Pop(x, x.form, hint, stop)
ELSIF x.mode = Reg THEN
FreeReg(x.reg, Int32); GetReg(r, Int32, hint, stop);
FreeReg(x.index, Int32); GetReg(rh, Int32, hint, stop);
x.form := Int32; DevCPL486.GenMove(x, r);
x.reg := x.index; DevCPL486.GenMove(x, rh);
x.reg := r.reg; x.index := rh.reg
ELSE
GetReg(rh, Int32, hint, stop + {AX});
Free(x);
GetReg(r, Int32, hint, stop);
x.form := Int32; offs := x.offset;
IF x.mode = Con THEN x.offset := x.scale ELSE INC(x.offset, 4) END;
DevCPL486.GenMove(x, rh);
x.offset := offs;
DevCPL486.GenMove(x, r);
x.mode := Reg; x.reg := r.reg; x.index := rh.reg
END
ELSE
LoadL(x, hint, stop); GetReg(rh, Int32, hint, stop); DevCPL486.GenSignExt(x, rh);
x.index := rh.reg
END;
x.form := Int64
END LoadLong;
(*------------------------------------------------*)
PROCEDURE CopyReg* (VAR x, y: DevCPL486.Item; hint, stop: SET);
BEGIN
ASSERT(x.mode = Reg);
GetReg(y, x.form, hint, stop);
DevCPL486.GenMove(x, y)
END CopyReg;
PROCEDURE GetAdr* (VAR x: DevCPL486.Item; hint, stop: SET);
VAR r: DevCPL486.Item;
BEGIN
IF x.mode = DInd THEN
x.mode := Ind
ELSIF (x.mode = Ind) & (x.offset = 0) & (x.scale = 0) & (x.reg IN wreg) THEN
x.mode := Reg
ELSE
Free(x); GetReg(r, Pointer, hint, stop);
IF x.mode = Con THEN DevCPL486.GenMove(x, r) ELSE DevCPL486.GenLoadAdr(x, r) END;
x.mode := Reg; x.reg := r.reg; x.form := Pointer
END;
x.form := Pointer; x.typ := DevCPT.anyptrtyp;
Assert(x, hint, stop)
END GetAdr;
PROCEDURE PushAdr (VAR x: DevCPL486.Item; niltest: BOOLEAN);
VAR r, v: DevCPL486.Item;
BEGIN
IF (x.mode = Abs) & (x.scale = 0) THEN x.mode := Con; x.form := Pointer
ELSIF niltest THEN
GetAdr(x, {}, {mem, stk});
DevCPL486.MakeReg(r, AX, Int32);
v.mode := Ind; v.form := Int32; v.offset := 0; v.scale := 0; v.reg := x.reg;
DevCPL486.GenTest(r, v)
ELSIF x.mode = DInd THEN x.mode := Ind; x.form := Pointer
ELSE GetAdr(x, {}, {})
END;
Free(x); DevCPL486.GenPush(x)
END PushAdr;
PROCEDURE LevelBase (VAR a: DevCPL486.Item; lev: INTEGER; hint, stop: SET);
VAR n: BYTE;
BEGIN
a.mode := Ind; a.scale := 0; a.form := Int32; a.typ := DevCPT.int32typ;
IF lev = DevCPL486.level THEN a.reg := BP
ELSE
a.reg := BX; n := SHORT(SHORT(imLevel[DevCPL486.level] - imLevel[lev]));
WHILE n > 0 DO
a.offset := -4; LoadL(a, hint, stop); a.mode := Ind; DEC(n)
END
END
END LevelBase;
PROCEDURE LenDesc (VAR x, len: DevCPL486.Item; typ: DevCPT.Struct); (* set len to LEN(x, -typ.n) *)
BEGIN
IF x.tmode = VarPar THEN
LevelBase(len, x.obj.mnolev, {}, {}); len.offset := x.obj.adr;
ELSE ASSERT((x.tmode = Ind) & (x.mode = Ind));
len := x; len.offset := ArrDOffs; len.scale := 0; len.form := Int32
END;
INC(len.offset, typ.n * 4 + 4);
IF typ.sysflag = stackArray THEN len.offset := -4 END
END LenDesc;
PROCEDURE Tag* (VAR x, tag: DevCPL486.Item);
VAR typ: DevCPT.Struct;
BEGIN
typ := x.typ;
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
IF (x.typ # DevCPT.sysptrtyp) & (typ.attribute = 0) & ~(DevCPM.oberon IN DevCPM.options) THEN (* final type *)
DevCPL486.MakeConst(tag, 0, Pointer); tag.obj := DevCPE.TypeObj(typ)
ELSIF x.typ.form = Pointer THEN
ASSERT(x.mode = Reg);
tag.mode := Ind; tag.reg := x.reg; tag.offset := -4;
IF x.typ.sysflag = interface THEN tag.offset := 0 END
ELSIF x.tmode = VarPar THEN
LevelBase(tag, x.obj.mnolev, {}, {}); tag.offset := x.obj.adr + 4;
Free(tag) (* ??? *)
ELSIF x.tmode = Ind THEN
ASSERT(x.mode = Ind);
tag := x; tag.offset := -4
ELSE
DevCPL486.MakeConst(tag, 0, Pointer); tag.obj := DevCPE.TypeObj(x.typ)
END;
tag.scale := 0; tag.form := Pointer; tag.typ := DevCPT.sysptrtyp
END Tag;
PROCEDURE NumOfIntProc (typ: DevCPT.Struct): INTEGER;
BEGIN
WHILE (typ # NIL) & (typ.sysflag # interface) DO typ := typ.BaseTyp END;
IF typ # NIL THEN RETURN typ.n
ELSE RETURN 0
END
END NumOfIntProc;
PROCEDURE ContainsIPtrs* (typ: DevCPT.Struct): BOOLEAN;
VAR fld: DevCPT.Object;
BEGIN
WHILE typ.comp IN {DynArr, Array} DO typ := typ.BaseTyp END;
IF (typ.form = Pointer) & (typ.sysflag = interface) THEN RETURN TRUE
ELSIF (typ.comp = Record) & (typ.sysflag # union) THEN
REPEAT
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF (fld.sysflag = interface) & (fld.name^ = DevCPM.HdUtPtrName)
OR ContainsIPtrs(fld.typ) THEN RETURN TRUE END;
fld := fld.link
END;
typ := typ.BaseTyp
UNTIL typ = NIL
END;
RETURN FALSE
END ContainsIPtrs;
PROCEDURE GuidFromString* (str: DevCPT.ConstExt; VAR x: DevCPL486.Item);
VAR cv: DevCPT.Const;
BEGIN
IF ~DevCPM.ValidGuid(str) THEN DevCPM.err(165) END;
cv := DevCPT.NewConst();
cv.intval := DevCPM.ConstNotAlloc; cv.intval2 := 16; cv.ext := str;
DevCPL486.AllocConst(x, cv, Guid); x.typ := DevCPT.guidtyp
END GuidFromString;
PROCEDURE IPAddRef* (VAR x: DevCPL486.Item; offset: INTEGER; nilTest: BOOLEAN);
VAR r, p, c: DevCPL486.Item; lbl: DevCPL486.Label;
BEGIN
ASSERT(x.mode IN {Reg, Ind, Abs});
ASSERT({AX, CX, DX} - WReg = {});
IF hints THEN
IF nilTest THEN DevCPM.err(-701) ELSE DevCPM.err(-700) END
END;
IF x.mode # Reg THEN
GetReg(r, Pointer, {}, {});
p := x; INC(p.offset, offset); p.form := Pointer; DevCPL486.GenMove(p, r);
ELSE r := x
END;
IF nilTest THEN
DevCPL486.MakeConst(c, 0, Pointer); DevCPL486.GenComp(c, r);
lbl := DevCPL486.NewLbl; DevCPL486.GenJump(ccE, lbl, TRUE)
END;
DevCPL486.GenPush(r); p := r;
IF x.mode # Reg THEN Free(r) END;
GetReg(r, Pointer, {}, {});
p.mode := Ind; p.offset := 0; p.scale := 0; p.form := Pointer; DevCPL486.GenMove(p, r);
p.offset := 4; p.reg := r.reg; Free(r); DevCPL486.GenCall(p);
IF nilTest THEN DevCPL486.SetLabel(lbl) END;
END IPAddRef;
PROCEDURE IPRelease* (VAR x: DevCPL486.Item; offset: INTEGER; nilTest, nilSet: BOOLEAN);
VAR r, p, c: DevCPL486.Item; lbl: DevCPL486.Label;
BEGIN
ASSERT(x.mode IN {Ind, Abs});
ASSERT({AX, CX, DX} - WReg = {});
IF hints THEN
IF nilTest THEN DevCPM.err(-703) ELSE DevCPM.err(-702) END
END;
GetReg(r, Pointer, {}, {});
p := x; INC(p.offset, offset); p.form := Pointer; DevCPL486.GenMove(p, r);
DevCPL486.MakeConst(c, 0, Pointer);
IF nilTest THEN
DevCPL486.GenComp(c, r);
lbl := DevCPL486.NewLbl; DevCPL486.GenJump(ccE, lbl, TRUE)
END;
IF nilSet THEN DevCPL486.GenMove(c, p) END;
DevCPL486.GenPush(r);
p.mode := Ind; p.reg := r.reg; p.offset := 0; p.scale := 0; DevCPL486.GenMove(p, r);
p.offset := 8; Free(r); DevCPL486.GenCall(p);
IF nilTest THEN DevCPL486.SetLabel(lbl) END;
END IPRelease;
PROCEDURE Prepare* (VAR x: DevCPL486.Item; hint, stop: SET);
VAR n, i, lev: INTEGER; len, y: DevCPL486.Item; typ: DevCPT.Struct;
BEGIN
IF (x.mode IN {Var, VarPar, Ind, Abs}) & (x.scale # 0) THEN
DevCPL486.MakeReg(y, x.index, Int32); typ := x.typ;
WHILE typ.comp = DynArr DO (* complete dynamic array iterations *)
LenDesc(x, len, typ); DevCPL486.GenMul(len, y, FALSE); typ := typ.BaseTyp;
IF x.tmode = VarPar THEN Free(len) END; (* ??? *)
END;
n := x.scale; i := 0;
WHILE (n MOD 2 = 0) & (i < 3) DO n := n DIV 2; INC(i) END;
IF n > 1 THEN (* assure scale factor in {1, 2, 4, 8} *)
DevCPL486.MakeConst(len, n, Int32); DevCPL486.GenMul(len, y, FALSE); x.scale := x.scale DIV n
END
END;
CASE x.mode OF
Var, VarPar:
lev := x.obj.mnolev;
IF lev <= 0 THEN
x.mode := Abs
ELSE
LevelBase(y, lev, hint, stop);
IF x.mode # VarPar THEN
x.mode := Ind
ELSIF (deref IN hint) & (x.offset = 0) & (x.scale = 0) THEN
x.mode := DInd; x.offset := x.obj.adr
ELSE
y.offset := x.obj.adr; Load(y, hint, stop); x.mode := Ind
END;
x.reg := y.reg
END;
x.form := x.typ.form
| LProc, XProc, IProc:
x.mode := Con; x.offset := 0; x.form := ProcTyp
| TProc, CProc:
x.form := ProcTyp
| Ind, Abs, Stk, Reg:
IF ~(x.typ.form IN {String8, String16}) THEN x.form := x.typ.form END
END
END Prepare;
PROCEDURE Field* (VAR x: DevCPL486.Item; field: DevCPT.Object);
BEGIN
INC(x.offset, field.adr); x.tmode := Con
END Field;
PROCEDURE DeRef* (VAR x: DevCPL486.Item);
VAR btyp: DevCPT.Struct;
BEGIN
x.mode := Ind; x.tmode := Ind; x.scale := 0;
btyp := x.typ.BaseTyp;
IF btyp.untagged OR (btyp.sysflag = stackArray) THEN x.offset := 0
ELSIF btyp.comp = DynArr THEN x.offset := ArrDOffs + btyp.size
ELSIF btyp.comp = Array THEN x.offset := ArrDOffs + 4
ELSE x.offset := 0
END
END DeRef;
PROCEDURE Index* (VAR x, y: DevCPL486.Item; hint, stop: SET); (* x[y] *)
VAR idx, len: DevCPL486.Item; btyp: DevCPT.Struct; elsize: INTEGER;
BEGIN
btyp := x.typ.BaseTyp; elsize := btyp.size;
IF elsize = 0 THEN Free(y)
ELSIF x.typ.comp = Array THEN
len.mode := Con; len.obj := NIL;
IF y.mode = Con THEN
INC(x.offset, y.offset * elsize)
ELSE
Load(y, hint, stop + {mem, stk, short});
IF inxchk THEN
DevCPL486.MakeConst(len, x.typ.n, Int32);
DevCPL486.GenComp(len, y); DevCPL486.GenAssert(ccB, inxTrap)
END;
IF x.scale = 0 THEN x.index := y.reg
ELSE
IF x.scale MOD elsize # 0 THEN
IF (x.scale MOD 4 = 0) & (elsize MOD 4 = 0) THEN elsize := 4
ELSIF (x.scale MOD 2 = 0) & (elsize MOD 2 = 0) THEN elsize := 2
ELSE elsize := 1
END;
DevCPL486.MakeConst(len, btyp.size DIV elsize, Int32);
DevCPL486.GenMul(len, y, FALSE)
END;
DevCPL486.MakeConst(len, x.scale DIV elsize, Int32);
DevCPL486.MakeReg(idx, x.index, Int32);
DevCPL486.GenMul(len, idx, FALSE); DevCPL486.GenAdd(y, idx, FALSE); Free(y)
END;
x.scale := elsize
END;
x.tmode := Con
ELSE (* x.typ.comp = DynArr *)
IF (btyp.comp = DynArr) & x.typ.untagged THEN DevCPM.err(137) END;
LenDesc(x, len, x.typ);
IF x.scale # 0 THEN
DevCPL486.MakeReg(idx, x.index, Int32);
DevCPL486.GenMul(len, idx, FALSE)
END;
IF (y.mode # Con) OR (y.offset # 0) THEN
IF (y.mode # Con) OR (btyp.comp = DynArr) & (x.scale = 0) THEN
Load(y, hint, stop + {mem, stk, con, short})
ELSE y.form := Int32
END;
IF inxchk & ~x.typ.untagged THEN
DevCPL486.GenComp(y, len); DevCPL486.GenAssert(ccA, inxTrap)
END;
IF (y.mode = Con) & (btyp.comp # DynArr) THEN
INC(x.offset, y.offset * elsize)
ELSIF x.scale = 0 THEN
WHILE btyp.comp = DynArr DO btyp := btyp.BaseTyp END;
x.index := y.reg; x.scale := btyp.size
ELSE
DevCPL486.GenAdd(y, idx, FALSE); Free(y)
END
END;
IF x.tmode = VarPar THEN Free(len) END; (* ??? *)
IF x.typ.BaseTyp.comp # DynArr THEN x.tmode := Con END
END
END Index;
PROCEDURE TypTest* (VAR x: DevCPL486.Item; testtyp: DevCPT.Struct; guard, equal: BOOLEAN);
VAR tag, tdes, r: DevCPL486.Item; typ: DevCPT.Struct;
BEGIN
typ := x.typ;
IF typ.form = Pointer THEN testtyp := testtyp.BaseTyp; typ := typ.BaseTyp END;
IF ~guard & typ.untagged THEN DevCPM.err(139)
ELSIF ~guard OR typchk & ~typ.untagged THEN
IF testtyp.untagged THEN DevCPM.err(139)
ELSE
IF (x.typ.form = Pointer) & (x.mode # Reg) THEN
GetReg(r, Pointer, {}, {}); DevCPL486.GenMove(x, r); Free(r); r.typ := x.typ; Tag(r, tag)
ELSE Tag(x, tag)
END;
IF ~guard THEN Free(x) END;
IF ~equal THEN
GetReg(r, Pointer, {}, {}); DevCPL486.GenMove(tag, r); Free(r);
tag.mode := Ind; tag.reg := r.reg; tag.scale := 0; tag.offset := Tag0Offset + 4 * testtyp.extlev
END;
DevCPL486.MakeConst(tdes, 0, Pointer); tdes.obj := DevCPE.TypeObj(testtyp);
DevCPL486.GenComp(tdes, tag);
IF guard THEN
IF equal THEN DevCPL486.GenAssert(ccE, recTrap) ELSE DevCPL486.GenAssert(ccE, typTrap) END
ELSE setCC(x, eql, FALSE, FALSE)
END
END
END
END TypTest;
PROCEDURE ShortTypTest* (VAR x: DevCPL486.Item; testtyp: DevCPT.Struct);
VAR tag, tdes: DevCPL486.Item;
BEGIN
(* tag must be in AX ! *)
IF testtyp.form = Pointer THEN testtyp := testtyp.BaseTyp END;
IF testtyp.untagged THEN DevCPM.err(139)
ELSE
tag.mode := Ind; tag.reg := AX; tag.scale := 0; tag.offset := Tag0Offset + 4 * testtyp.extlev; tag.form := Pointer;
DevCPL486.MakeConst(tdes, 0, Pointer); tdes.obj := DevCPE.TypeObj(testtyp);
DevCPL486.GenComp(tdes, tag);
setCC(x, eql, FALSE, FALSE)
END
END ShortTypTest;
PROCEDURE Check (VAR x: DevCPL486.Item; min, max: INTEGER);
VAR c: DevCPL486.Item;
BEGIN
ASSERT((x.mode # Reg) OR (max > 255) OR (max = 31) OR (x.reg < 4));
IF ranchk & (x.mode # Con) THEN
DevCPL486.MakeConst(c, max, x.form); DevCPL486.GenComp(c, x);
IF min # 0 THEN
DevCPL486.GenAssert(ccLE, ranTrap);
c.offset := min; DevCPL486.GenComp(c, x);
DevCPL486.GenAssert(ccGE, ranTrap)
ELSIF max # 0 THEN
DevCPL486.GenAssert(ccBE, ranTrap)
ELSE
DevCPL486.GenAssert(ccNS, ranTrap)
END
END
END Check;
PROCEDURE Floor (VAR x: DevCPL486.Item; useSt1: BOOLEAN);
VAR c: DevCPL486.Item; local: DevCPL486.Label;
BEGIN
IF useSt1 THEN DevCPL486.GenFMOp(5D1H); (* FST ST1 *)
ELSE DevCPL486.GenFMOp(1C0H); (* FLD ST0 *)
END;
DevCPL486.GenFMOp(1FCH); (* FRNDINT *)
DevCPL486.GenFMOp(0D1H); (* FCOM *)
CheckAv(AX);
DevCPL486.GenFMOp(FSTSW);
DevCPL486.GenFMOp(5D9H); (* FSTP ST1 *)
(* DevCPL486.GenCode(WAIT); *) DevCPL486.GenCode(SAHF);
local := DevCPL486.NewLbl; DevCPL486.GenJump(ccBE, local, TRUE);
DevCPL486.AllocConst(c, DevCPL486.one, Real32);
DevCPL486.GenFDOp(FSUB, c);
DevCPL486.SetLabel(local);
END Floor;
PROCEDURE Entier(VAR x: DevCPL486.Item; typ: DevCPT.Struct; hint, stop: SET);
BEGIN
IF typ # DevCPT.intrealtyp THEN Floor(x, FALSE) END;
DevCPL486.GenFStore(x, TRUE);
IF (x.mode = Stk) & (stk IN stop) THEN Pop(x, x.form, hint, stop) END
END Entier;
PROCEDURE ConvMove (VAR x, y: DevCPL486.Item; sysval: BOOLEAN; hint, stop: SET); (* x := y *)
(* scalar values only, y.mode # Con, all kinds of conversions, x.mode = Undef => convert y only *)
VAR f, m: BYTE; s: INTEGER; z: DevCPL486.Item;
BEGIN
f := x.form; m := x.mode; ASSERT(m IN {Undef, Reg, Abs, Ind, Stk});
IF y.form IN {Real32, Real64} THEN
IF f IN {Real32, Real64} THEN
IF m = Undef THEN
IF (y.form = Real64) & (f = Real32) THEN
IF y.mode # Reg THEN LoadR(y) END;
Free(y); DecStack(Real32); y.mode := Stk; y.form := Real32; DevCPL486.GenFStore(y, TRUE)
END
ELSE
IF y.mode # Reg THEN LoadR(y) END;
IF m = Stk THEN DecStack(f) END;
IF m # Reg THEN Free(y); DevCPL486.GenFStore(x, TRUE) END;
END
ELSE (* x not real *)
IF sysval THEN
IF y.mode = Reg THEN Free(y);
IF (m # Stk) & (m # Undef) & (m # Reg) & (f >= Int32) THEN
x.form := y.form; DevCPL486.GenFStore(x, TRUE); x.form := f
ELSIF y.form = Real64 THEN (* S.VAL(LONGINT, real) *)
ASSERT((m = Undef) & (f = Int64));
DecStack(y.form); y.mode := Stk; DevCPL486.GenFStore(y, TRUE); y.form := Int64;
Pop(y, y.form, hint, stop)
ELSE
ASSERT(y.form # Real64);
DecStack(y.form); y.mode := Stk; DevCPL486.GenFStore(y, TRUE); y.form := Int32;
IF m # Stk THEN
Pop(y, y.form, hint, stop);
IF f < Int16 THEN ASSERT(y.reg < 4) END;
y.form := f;
IF m # Undef THEN Free(y); DevCPL486.GenMove(y, x) END
END
END
ELSE (* y.mode # Reg *)
y.form := f;
IF m # Undef THEN LoadW(y, hint, stop); Free(y);
IF m = Stk THEN DevCPL486.GenPush(y) ELSE DevCPL486.GenMove(y, x) END
END
END
ELSE (* not sysval *)
IF y.mode # Reg THEN LoadR(y) END;
Free(y);
IF (m # Stk) & (m # Undef) & (m # Reg) & (f >= Int16) & (f # Char16) THEN
Entier(x, y.typ, hint, stop);
ELSE
DecStack(f); y.mode := Stk;
IF (f < Int16) OR (f = Char16) THEN y.form := Int32 ELSE y.form := f END;
IF m = Stk THEN Entier(y, y.typ, {}, {})
ELSIF m = Undef THEN Entier(y, y.typ, hint, stop)
ELSE Entier(y, y.typ, hint, stop + {stk})
END;
IF f = Int8 THEN Check(y, -128, 127); FreeHi(y)
ELSIF f = Char8 THEN Check(y, 0, 255); FreeHi(y)
ELSIF f = Char16 THEN Check(y, 0, 65536); FreeHi(y)
END;
y.form := f;
IF (m # Undef) & (m # Stk) THEN
IF f = Int64 THEN
Free(y); y.form := Int32; z := x; z.form := Int32; DevCPL486.GenMove(y, z);
IF z.mode = Reg THEN z.reg := z.index ELSE INC(z.offset, 4) END;
y.reg := y.index; DevCPL486.GenMove(y, z);
ELSE
Free(y); DevCPL486.GenMove(y, x);
END
END
END
END
END
ELSE (* y not real *)
IF sysval THEN
IF (y.form < Int16) & (f >= Int16) OR (y.form IN {Int16, Char16}) & (f >= Int32) & (f < Char16) THEN LoadL(y, hint, stop) END;
IF (y.form >= Int16) & (f < Int16) THEN FreeHi(y) END
ELSE
CASE y.form OF
| Byte, Bool:
IF f = Int64 THEN LoadLong(y, hint, stop)
ELSIF f >= Int16 THEN LoadL(y, hint, stop)
END
| Char8:
IF f = Int8 THEN Check(y, 0, 0)
ELSIF f = Int64 THEN LoadLong(y, hint, stop)
ELSIF f >= Int16 THEN LoadL(y, hint, stop)
END
| Char16:
IF f = Char8 THEN Check(y, 0, 255); FreeHi(y)
ELSIF f = Int8 THEN Check(y, -128, 127); FreeHi(y)
ELSIF f = Int16 THEN Check(y, 0, 0)
ELSIF f = Char16 THEN (* ok *)
ELSIF f = Int64 THEN LoadLong(y, hint, stop)
ELSIF f >= Int32 THEN LoadL(y, hint, stop)
END
| Int8:
IF f = Char8 THEN Check(y, 0, 0)
ELSIF f = Int64 THEN LoadLong(y, hint, stop)
ELSIF f >= Int16 THEN LoadL(y, hint, stop)
END
| Int16:
IF f = Char8 THEN Check(y, 0, 255); FreeHi(y)
ELSIF f = Char16 THEN Check(y, 0, 0)
ELSIF f = Int8 THEN Check(y, -128, 127); FreeHi(y)
ELSIF f = Int64 THEN LoadLong(y, hint, stop)
ELSIF (f = Int32) OR (f = Set) THEN LoadL(y, hint, stop)
END
| Int32, Set, Pointer, ProcTyp:
IF f = Char8 THEN Check(y, 0, 255); FreeHi(y)
ELSIF f = Char16 THEN Check(y, 0, 65536)
ELSIF f = Int8 THEN Check(y, -128, 127); FreeHi(y)
ELSIF f = Int16 THEN Check(y, -32768, 32767)
ELSIF f = Int64 THEN LoadLong(y, hint, stop)
END
| Int64:
IF f IN {Bool..Int32, Char16} THEN
(* make range checks !!! *)
FreeHi(y);
IF f IN {Bool..Int8} THEN y.form := Int32; FreeHi(y) END
END
END
END;
IF f IN {Real32, Real64} THEN
IF sysval THEN
IF (m # Undef) & (m # Reg) THEN
IF y.mode # Reg THEN LoadW(y, hint, stop) END;
Free(y);
IF m = Stk THEN DevCPL486.GenPush(y)
ELSE x.form := Int32; DevCPL486.GenMove(y, x); x.form := f
END
ELSE
IF y.mode = Reg THEN Push(y) END;
y.form := f;
IF m = Reg THEN LoadR(y) END
END
ELSE (* not sysval *) (* int -> float *)
IF y.mode = Reg THEN Push(y) END;
IF m = Stk THEN
Free(y); DevCPL486.GenFLoad(y); s := -4;
IF f = Real64 THEN DEC(s, 4) END;
IF y.mode = Stk THEN
IF y.form = Int64 THEN INC(s, 8) ELSE INC(s, 4) END
END;
IF s # 0 THEN AdjustStack(s) END;
GetReg(y, Real32, {}, {});
Free(y); DevCPL486.GenFStore(x, TRUE)
ELSIF m = Reg THEN
LoadR(y)
ELSIF m # Undef THEN
LoadR(y); Free(y); DevCPL486.GenFStore(x, TRUE)
END
END
ELSE
y.form := f;
IF m = Stk THEN
IF ((f < Int32) OR (f = Char16)) & (y.mode # Reg) THEN LoadW(y, hint, stop) END;
Push(y)
ELSIF m # Undef THEN
IF f = Int64 THEN
IF y.mode # Reg THEN LoadLong(y, hint, stop) END;
Free(y); y.form := Int32; z := x; z.form := Int32; DevCPL486.GenMove(y, z);
IF z.mode = Reg THEN ASSERT(z.reg # y.index); z.reg := z.index ELSE INC(z.offset, 4) END;
y.reg := y.index; DevCPL486.GenMove(y, z);
ELSE
IF y.mode # Reg THEN LoadW(y, hint, stop) END;
Free(y); DevCPL486.GenMove(y, x)
END
END
END
END
END ConvMove;
PROCEDURE Convert* (VAR x: DevCPL486.Item; f: BYTE; size: INTEGER; hint, stop: SET); (* size >= 0: sysval *)
VAR y: DevCPL486.Item;
BEGIN
ASSERT(x.mode # Con);
IF (size >= 0)
& ((size # x.typ.size) & ((size > 4) OR (x.typ.size > 4))
OR (f IN {Comp, Real64}) & (x.mode IN {Reg, Stk})
OR (f = Int64) & (x.mode = Stk)) THEN
DevCPM.err(261); Free(x); x.mode := Stk; x.form := f
ELSE
y.mode := Undef; y.form := f; ConvMove(y, x, size >= 0, hint, stop)
END
END Convert;
PROCEDURE LoadCond* (VAR x, y: DevCPL486.Item; F, T: DevCPL486.Label; hint, stop: SET);
VAR end, T1: DevCPL486.Label; c, r: DevCPL486.Item;
BEGIN
IF mem IN stop THEN GetReg(x, Bool, hint, stop) END;
IF (F = DevCPL486.NewLbl) & (T = DevCPL486.NewLbl) THEN (* no label used *)
IF y.offset >= 0 THEN DevCPL486.GenSetCC(y.offset, x)
ELSIF y.offset = ccAlways THEN Free(x); DevCPL486.MakeConst(x, 1, Bool)
ELSIF y.offset = ccNever THEN Free(x); DevCPL486.MakeConst(x, 0, Bool)
ELSE HALT(100) (* internal error *)
END
ELSE
end := DevCPL486.NewLbl; T1 := DevCPL486.NewLbl;
DevCPL486.GenJump(y.offset, T1, TRUE); (* T1 to enable short jump *)
DevCPL486.SetLabel(F);
DevCPL486.MakeConst(c, 0, Bool); DevCPL486.GenMove(c, x);
DevCPL486.GenJump(ccAlways, end, TRUE);
DevCPL486.SetLabel(T); DevCPL486.SetLabel(T1);
DevCPL486.MakeConst(c, 1, Bool); DevCPL486.GenMove(c, x);
DevCPL486.SetLabel(end)
END;
IF x.mode # Reg THEN Free(x) END
END LoadCond;
PROCEDURE IntDOp* (VAR x, y: DevCPL486.Item; subcl: BYTE; rev: BOOLEAN);
VAR local: DevCPL486.Label;
BEGIN
ASSERT((x.mode = Reg) OR (y.mode = Reg) OR (y.mode = Con));
CASE subcl OF
| eql..geq:
DevCPL486.GenComp(y, x); Free(x);
setCC(x, subcl, rev, x.typ.form IN {Int8..Int32})
| times:
IF x.form = Set THEN DevCPL486.GenAnd(y, x) ELSE DevCPL486.GenMul(y, x, ovflchk) END
| slash:
DevCPL486.GenXor(y, x)
| plus:
IF x.form = Set THEN DevCPL486.GenOr(y, x) ELSE DevCPL486.GenAdd(y, x, ovflchk) END
| minus, msk:
IF (x.form = Set) OR (subcl = msk) THEN (* and not *)
IF rev THEN DevCPL486.GenNot(x); DevCPL486.GenAnd(y, x) (* y and not x *)
ELSIF y.mode = Con THEN y.offset := -1 - y.offset; DevCPL486.GenAnd(y, x) (* x and y' *)
ELSIF y.mode = Reg THEN DevCPL486.GenNot(y); DevCPL486.GenAnd(y, x) (* x and not y *)
ELSE DevCPL486.GenNot(x); DevCPL486.GenOr(y, x); DevCPL486.GenNot(x) (* not (not x or y) *)
END
ELSE (* minus *)
IF rev THEN (* y - x *)
IF (y.mode = Con) & (y.offset = -1) THEN DevCPL486.GenNot(x)
ELSE DevCPL486.GenNeg(x, ovflchk); DevCPL486.GenAdd(y, x, ovflchk) (* ??? *)
END
ELSE (* x - y *)
DevCPL486.GenSub(y, x, ovflchk)
END
END
| min, max:
local := DevCPL486.NewLbl;
DevCPL486.GenComp(y, x);
IF subcl = min THEN
IF x.typ.form IN {Char8, Char16} THEN DevCPL486.GenJump(ccBE, local, TRUE)
ELSE DevCPL486.GenJump(ccLE, local, TRUE)
END
ELSE
IF x.typ.form IN {Char8, Char16} THEN DevCPL486.GenJump(ccAE, local, TRUE)
ELSE DevCPL486.GenJump(ccGE, local, TRUE)
END
END;
DevCPL486.GenMove(y, x);
DevCPL486.SetLabel(local)
END;
Free(y);
IF x.mode # Reg THEN Free(x) END
END IntDOp;
PROCEDURE LargeInc* (VAR x, y: DevCPL486.Item; dec: BOOLEAN); (* INC(x, y) or DEC(x, y) *)
BEGIN
ASSERT(x.form = Int64);
IF ~(y.mode IN {Reg, Con}) THEN LoadLong(y, {}, {}) END;
Free(x); Free(y); x.form := Int32; y.form := Int32;
IF dec THEN DevCPL486.GenSubC(y, x, TRUE, FALSE) ELSE DevCPL486.GenAddC(y, x, TRUE, FALSE) END;
INC(x.offset, 4);
IF y.mode = Reg THEN y.reg := y.index ELSE y.offset := y.scale END;
IF dec THEN DevCPL486.GenSubC(y, x, FALSE, ovflchk) ELSE DevCPL486.GenAddC(y, x, FALSE, ovflchk) END;
END LargeInc;
PROCEDURE FloatDOp* (VAR x, y: DevCPL486.Item; subcl: BYTE; rev: BOOLEAN);
VAR local: DevCPL486.Label; a, b: DevCPL486.Item;
BEGIN
ASSERT(x.mode = Reg);
IF y.form = Int64 THEN LoadR(y) END;
IF y.mode = Reg THEN rev := ~rev END;
CASE subcl OF
| eql..geq: DevCPL486.GenFDOp(FCOMP, y)
| times: DevCPL486.GenFDOp(FMUL, y)
| slash: IF rev THEN DevCPL486.GenFDOp(FDIVR, y) ELSE DevCPL486.GenFDOp(FDIV, y) END
| plus: DevCPL486.GenFDOp(FADD, y)
| minus: IF rev THEN DevCPL486.GenFDOp(FSUBR, y) ELSE DevCPL486.GenFDOp(FSUB, y) END
| min, max:
IF y.mode = Reg THEN
DevCPL486.GenFMOp(0D1H); (* FCOM ST1 *)
CheckAv(AX); DevCPL486.GenFMOp(FSTSW); (* DevCPL486.GenCode(WAIT); *) DevCPL486.GenCode(SAHF);
local := DevCPL486.NewLbl;
IF subcl = min THEN DevCPL486.GenJump(ccAE, local, TRUE) ELSE DevCPL486.GenJump(ccBE, local, TRUE) END;
DevCPL486.GenFMOp(5D1H); (* FST ST1 *)
DevCPL486.SetLabel(local);
DevCPL486.GenFMOp(5D8H) (* FSTP ST0 *)
ELSE
DevCPL486.GenFDOp(FCOM, y);
CheckAv(AX); DevCPL486.GenFMOp(FSTSW); (* DevCPL486.GenCode(WAIT); *) DevCPL486.GenCode(SAHF);
local := DevCPL486.NewLbl;
IF subcl = min THEN DevCPL486.GenJump(ccBE, local, TRUE) ELSE DevCPL486.GenJump(ccAE, local, TRUE) END;
DevCPL486.GenFMOp(5D8H); (* FSTP ST0 *)
DevCPL486.GenFLoad(y);
DevCPL486.SetLabel(local)
END
(* largeint support *)
| div:
IF y.mode # Reg THEN LoadR(y); rev := ~rev END;
IF rev THEN DevCPL486.GenFDOp(FDIVR, y) ELSE DevCPL486.GenFDOp(FDIV, y) END;
Floor(y, FALSE)
| mod:
IF y.mode # Reg THEN LoadR(y); rev := ~rev END;
IF rev THEN DevCPL486.GenFMOp(1C9H); (* FXCH ST1 *) END;
DevCPL486.GenFMOp(1F8H); (* FPREM *)
DevCPL486.GenFMOp(1E4H); (* FTST *)
CheckAv(AX);
DevCPL486.GenFMOp(FSTSW);
DevCPL486.MakeReg(a, AX, Int32); GetReg(b, Int32, {}, {AX});
DevCPL486.GenMove(a, b);
DevCPL486.GenFMOp(0D1H); (* FCOM *)
DevCPL486.GenFMOp(FSTSW);
DevCPL486.GenXor(b, a); Free(b);
(* DevCPL486.GenCode(WAIT); *) DevCPL486.GenCode(SAHF);
local := DevCPL486.NewLbl; DevCPL486.GenJump(ccBE, local, TRUE);
DevCPL486.GenFMOp(0C1H); (* FADD ST1 *)
DevCPL486.SetLabel(local);
DevCPL486.GenFMOp(5D9H); (* FSTP ST1 *)
| ash:
IF y.mode # Reg THEN LoadR(y); rev := ~rev END;
IF rev THEN DevCPL486.GenFMOp(1C9H); (* FXCH ST1 *) END;
DevCPL486.GenFMOp(1FDH); (* FSCALE *)
Floor(y, TRUE)
END;
IF y.mode = Stk THEN IncStack(y.form) END;
Free(y);
IF (subcl >= eql) & (subcl <= geq) THEN
Free(x); CheckAv(AX);
DevCPL486.GenFMOp(FSTSW);
(* DevCPL486.GenCode(WAIT); *) DevCPL486.GenCode(SAHF);
setCC(x, subcl, rev, FALSE)
END
END FloatDOp;
PROCEDURE IntMOp* (VAR x: DevCPL486.Item; subcl: BYTE);
VAR L: DevCPL486.Label; c: DevCPL486.Item;
BEGIN
CASE subcl OF
| minus:
IF x.form = Set THEN DevCPL486.GenNot(x) ELSE DevCPL486.GenNeg(x, ovflchk) END
| abs:
L := DevCPL486.NewLbl; DevCPL486.MakeConst(c, 0, x.form);
DevCPL486.GenComp(c, x);
DevCPL486.GenJump(ccNS, L, TRUE);
DevCPL486.GenNeg(x, ovflchk);
DevCPL486.SetLabel(L)
| cap:
DevCPL486.MakeConst(c, -1 - 20H, x.form);
DevCPL486.GenAnd(c, x)
| not:
DevCPL486.MakeConst(c, 1, x.form);
DevCPL486.GenXor(c, x)
END;
IF x.mode # Reg THEN Free(x) END
END IntMOp;
PROCEDURE FloatMOp* (VAR x: DevCPL486.Item; subcl: BYTE);
BEGIN
ASSERT(x.mode = Reg);
IF subcl = minus THEN DevCPL486.GenFMOp(FCHS)
ELSE ASSERT(subcl = abs); DevCPL486.GenFMOp(FABS)
END
END FloatMOp;
PROCEDURE MakeSet* (VAR x: DevCPL486.Item; range, neg: BOOLEAN; hint, stop: SET);
(* range neg result
F F {x}
F T -{x}
T F {x..31}
T T -{0..x} *)
VAR c, r: DevCPL486.Item; val: INTEGER;
BEGIN
IF x.mode = Con THEN
IF range THEN
IF neg THEN val := -2 ELSE val := -1 END;
x.offset := SYSTEM.LSH(val, x.offset)
ELSE
val := 1; x.offset := SYSTEM.LSH(val, x.offset);
IF neg THEN x.offset := -1 - x.offset END
END
ELSE
Check(x, 0, 31);
IF neg THEN val := -2
ELSIF range THEN val := -1
ELSE val := 1
END;
DevCPL486.MakeConst(c, val, Set); GetReg(r, Set, hint, stop); DevCPL486.GenMove(c, r);
IF range THEN DevCPL486.GenShiftOp(SHL, x, r) ELSE DevCPL486.GenShiftOp(ROL, x, r) END;
Free(x); x.reg := r.reg
END;
x.typ := DevCPT.settyp; x.form := Set
END MakeSet;
PROCEDURE MakeCond* (VAR x: DevCPL486.Item);
VAR c: DevCPL486.Item;
BEGIN
IF x.mode = Con THEN
setCC(x, SHORT(SHORT(x.offset)), FALSE, FALSE)
ELSE
DevCPL486.MakeConst(c, 0, x.form);
DevCPL486.GenComp(c, x); Free(x);
setCC(x, neq, FALSE, FALSE)
END
END MakeCond;
PROCEDURE Not* (VAR x: DevCPL486.Item);
BEGIN
x.offset := Inverted(x.offset); (* invert cc *)
END Not;
PROCEDURE Odd* (VAR x: DevCPL486.Item);
VAR c: DevCPL486.Item;
BEGIN
IF x.mode = Stk THEN Pop(x, x.form, {}, {}) END;
Free(x); DevCPL486.MakeConst(c, 1, x.form);
IF x.mode = Reg THEN
IF x.form IN {Int16, Int64} THEN x.form := Int32; c.form := Int32 END;
DevCPL486.GenAnd(c, x)
ELSE
c.form := Int8; x.form := Int8; DevCPL486.GenTest(c, x)
END;
setCC(x, neq, FALSE, FALSE)
END Odd;
PROCEDURE In* (VAR x, y: DevCPL486.Item);
BEGIN
IF y.form = Set THEN Check(x, 0, 31) END;
DevCPL486.GenBitOp(BT, x, y); Free(x); Free(y);
setCC(x, lss, FALSE, FALSE); (* carry set *)
END In;
PROCEDURE Shift* (VAR x, y: DevCPL486.Item; subcl: BYTE); (* ASH, LSH, ROT *)
VAR L1, L2: DevCPL486.Label; c: DevCPL486.Item; opl, opr: INTEGER;
BEGIN
IF subcl = ash THEN opl := SHL; opr := SAR
ELSIF subcl = lsh THEN opl := SHL; opr := SHR
ELSE opl := ROL; opr := ROR
END;
IF y.mode = Con THEN
IF y.offset > 0 THEN
DevCPL486.GenShiftOp(opl, y, x)
ELSIF y.offset < 0 THEN
y.offset := -y.offset;
DevCPL486.GenShiftOp(opr, y, x)
END
ELSE
ASSERT(y.mode = Reg);
Check(y, -31, 31);
L1 := DevCPL486.NewLbl; L2 := DevCPL486.NewLbl;
DevCPL486.MakeConst(c, 0, y.form); DevCPL486.GenComp(c, y);
DevCPL486.GenJump(ccNS, L1, TRUE);
DevCPL486.GenNeg(y, FALSE);
DevCPL486.GenShiftOp(opr, y, x);
DevCPL486.GenJump(ccAlways, L2, TRUE);
DevCPL486.SetLabel(L1);
DevCPL486.GenShiftOp(opl, y, x);
DevCPL486.SetLabel(L2);
Free(y)
END;
IF x.mode # Reg THEN Free(x) END
END Shift;
PROCEDURE DivMod* (VAR x, y: DevCPL486.Item; mod: BOOLEAN);
VAR r: DevCPL486.Item; pos: BOOLEAN;
BEGIN
ASSERT((x.mode = Reg) & (x.reg = AX)); pos := FALSE;
IF y.mode = Con THEN pos := (y.offset > 0) & (y.obj = NIL); Load(y, {}, {AX, DX, con}) END;
DevCPL486.GenDiv(y, mod, pos); Free(y);
IF mod THEN
r := x; GetReg(x, x.form, {}, wreg - {AX, DX}); Free(r) (* ax -> dx; al -> ah *) (* ??? *)
END
END DivMod;
PROCEDURE Mem* (VAR x: DevCPL486.Item; offset: INTEGER; typ: DevCPT.Struct); (* x := Mem[x+offset] *)
BEGIN
IF x.mode = Con THEN x.mode := Abs; x.obj := NIL; INC(x.offset, offset)
ELSE ASSERT(x.mode = Reg); x.mode := Ind; x.offset := offset
END;
x.scale := 0; x.typ := typ; x.form := typ.form
END Mem;
PROCEDURE SysMove* (VAR len: DevCPL486.Item); (* implementation of SYSTEM.MOVE *)
BEGIN
IF len.mode = Con THEN
IF len.offset > 0 THEN DevCPL486.GenBlockMove(1, len.offset) END
ELSE
Load(len, {}, wreg - {CX} + {short, mem, stk}); DevCPL486.GenBlockMove(1, 0); Free(len)
END;
FreeWReg(SI); FreeWReg(DI)
END SysMove;
PROCEDURE Len* (VAR x, y: DevCPL486.Item);
VAR typ: DevCPT.Struct; dim: INTEGER;
BEGIN
dim := y.offset; typ := x.typ;
IF typ.untagged THEN DevCPM.err(136) END;
WHILE dim > 0 DO typ := typ.BaseTyp; DEC(dim) END;
LenDesc(x, x, typ);
END Len;
PROCEDURE StringWSize (VAR x: DevCPL486.Item): INTEGER;
BEGIN
CASE x.form OF
| String8, VString8: RETURN 1
| String16, VString16: RETURN 2
| VString16to8: RETURN 0
| Comp: RETURN x.typ.BaseTyp.size
END
END StringWSize;
PROCEDURE CmpString* (VAR x, y: DevCPL486.Item; rel: BYTE; rev: BOOLEAN);
BEGIN
CheckAv(CX);
IF (x.typ = DevCPT.guidtyp) OR (y.typ = DevCPT.guidtyp) THEN
DevCPL486.GenBlockComp(4, 4)
ELSIF x.form = String8 THEN DevCPL486.GenBlockComp(1, x.index)
ELSIF y.form = String8 THEN DevCPL486.GenBlockComp(1, y.index)
ELSIF x.form = String16 THEN DevCPL486.GenBlockComp(2, x.index)
ELSIF y.form = String16 THEN DevCPL486.GenBlockComp(2, y.index)
ELSE DevCPL486.GenStringComp(StringWSize(y), StringWSize(x))
END;
FreeWReg(SI); FreeWReg(DI); setCC(x, rel, ~rev, FALSE);
END CmpString;
PROCEDURE VarParDynArr (ftyp: DevCPT.Struct; VAR y: DevCPL486.Item);
VAR len, z: DevCPL486.Item; atyp: DevCPT.Struct;
BEGIN
atyp := y.typ;
WHILE ftyp.comp = DynArr DO
IF ftyp.BaseTyp = DevCPT.bytetyp THEN
IF atyp.comp = DynArr THEN
IF atyp.untagged THEN DevCPM.err(137) END;
LenDesc(y, len, atyp);
IF y.tmode = VarPar THEN Free(len) END; (* ??? *)
GetReg(z, Int32, {}, {}); DevCPL486.GenMove(len, z);
len.mode := Reg; len.reg := z.reg; atyp := atyp.BaseTyp;
WHILE atyp.comp = DynArr DO
LenDesc(y, z, atyp); DevCPL486.GenMul(z, len, FALSE);
IF y.tmode = VarPar THEN Free(z) END; (* ??? *)
atyp := atyp.BaseTyp
END;
DevCPL486.MakeConst(z, atyp.size, Int32); DevCPL486.GenMul(z, len, FALSE);
Free(len)
ELSE
DevCPL486.MakeConst(len, atyp.size, Int32)
END
ELSE
IF atyp.comp = DynArr THEN LenDesc(y, len, atyp);
IF atyp.untagged THEN DevCPM.err(137) END;
IF y.tmode = VarPar THEN Free(len) END; (* ??? *)
ELSE DevCPL486.MakeConst(len, atyp.n, Int32)
END
END;
DevCPL486.GenPush(len);
ftyp := ftyp.BaseTyp; atyp := atyp.BaseTyp
END
END VarParDynArr;
PROCEDURE Assign* (VAR x, y: DevCPL486.Item); (* x := y *)
BEGIN
IF y.mode = Con THEN
IF y.form IN {Real32, Real64} THEN
DevCPL486.GenFLoad(y); GetReg(y, Real32, {}, {});
IF x.mode # Reg THEN Free(y); DevCPL486.GenFStore(x, TRUE) END (* ??? move const *)
ELSIF x.form = Int64 THEN
ASSERT(x.mode IN {Ind, Abs});
y.form := Int32; x.form := Int32; DevCPL486.GenMove(y, x);
y.offset := y.scale; INC(x.offset, 4); DevCPL486.GenMove(y, x);
DEC(x.offset, 4); x.form := Int64
ELSE
DevCPL486.GenMove(y, x)
END
ELSE
IF y.form IN {Comp, String8, String16, VString8, VString16} THEN (* convert to pointer *)
ASSERT(x.form = Pointer);
GetAdr(y, {}, {}); y.typ := x.typ; y.form := Pointer
END;
IF ~(x.form IN realSet) OR ~(y.form IN intSet) THEN Assert(y, {}, {stk}) END;
ConvMove(x, y, FALSE, {}, {})
END;
Free(x)
END Assign;
PROCEDURE ArrayLen* (VAR x, len: DevCPL486.Item; hint, stop: SET);
VAR c: DevCPL486.Item;
BEGIN
IF x.typ.comp = Array THEN DevCPL486.MakeConst(c, x.typ.n, Int32); GetReg(len, Int32, hint, stop); DevCPL486.GenMove(c, len)
ELSIF ~x.typ.untagged THEN LenDesc(x, c, x.typ); GetReg(len, Int32, hint, stop); DevCPL486.GenMove(c, len)
ELSE len.mode := Con
END;
len.typ := DevCPT.int32typ
END ArrayLen;
(*
src dest zero
sx = sy x b y b
SHORT(lx) = sy x b+ x w y b
SHORT(lx) = SHORT(ly) x b+ x w y b+
lx = ly x w y w
LONG(sx) = ly x b y w *
LONG(SHORT(lx)) = ly x b+ x w* y w *
sx := sy y b x b
sx := SHORT(ly) y b+ y w x b
lx := ly y w x w
lx := LONG(sy) y b x w *
lx := LONG(SHORT(ly)) y b+ y w* x w *
*)
PROCEDURE AddCopy* (VAR x, y: DevCPL486.Item; last: BOOLEAN); (* x := .. + y + .. *)
BEGIN
IF (x.typ.comp = DynArr) & x.typ.untagged THEN
DevCPL486.GenStringMove(~last, StringWSize(y), StringWSize(x), -1)
ELSE
DevCPL486.GenStringMove(~last, StringWSize(y), StringWSize(x), 0)
END;
FreeWReg(SI); FreeWReg(DI)
END AddCopy;
PROCEDURE Copy* (VAR x, y: DevCPL486.Item; short: BOOLEAN); (* x := y *)
VAR sx, sy, sy2, sy4: INTEGER; c, r: DevCPL486.Item;
BEGIN
sx := x.typ.size; CheckAv(CX);
IF y.form IN {String8, String16} THEN
sy := y.index * y.typ.BaseTyp.size;
IF x.typ.comp = Array THEN (* adjust size for optimal performance *)
sy2 := sy + sy MOD 2; sy4 := sy2 + sy2 MOD 4;
IF sy4 <= sx THEN sy := sy4
ELSIF sy2 <= sx THEN sy := sy2
ELSIF sy > sx THEN DevCPM.err(114); sy := 1
END
ELSIF inxchk & ~x.typ.untagged THEN (* check array length *)
Free(x); LenDesc(x, c, x.typ);
DevCPL486.MakeConst(y, y.index, Int32);
DevCPL486.GenComp(y, c); DevCPL486.GenAssert(ccAE, copyTrap);
Free(c)
END;
DevCPL486.GenBlockMove(1, sy)
ELSIF x.typ.comp = DynArr THEN
IF x.typ.untagged THEN
DevCPL486.GenStringMove(FALSE, StringWSize(y), StringWSize(x), -1)
ELSE
Free(x); LenDesc(x, c, x.typ); DevCPL486.MakeReg(r, CX, Int32); DevCPL486.GenMove(c, r); Free(c);
DevCPL486.GenStringMove(FALSE, StringWSize(y), StringWSize(x), 0)
END
ELSIF y.form IN {VString16to8, VString8, VString16} THEN
DevCPL486.GenStringMove(FALSE, StringWSize(y), StringWSize(x), x.typ.n);
ASSERT(y.mode # Stk)
ELSIF short THEN (* COPY *)
sy := y.typ.size;
IF (y.typ.comp # DynArr) & (sy < sx) THEN sx := sy END;
DevCPL486.GenStringMove(FALSE, StringWSize(y), StringWSize(x), x.typ.n);
IF y.mode = Stk THEN AdjustStack(sy) END
ELSE (* := *)
IF sx > 0 THEN DevCPL486.GenBlockMove(1, sx) END;
IF y.mode = Stk THEN AdjustStack(sy) END
END;
FreeWReg(SI); FreeWReg(DI)
END Copy;
PROCEDURE StrLen* (VAR x: DevCPL486.Item; typ: DevCPT.Struct; incl0x: BOOLEAN);
VAR c: DevCPL486.Item;
BEGIN
CheckAv(AX); CheckAv(CX);
DevCPL486.GenStringLength(typ.BaseTyp.size, -1);
Free(x); GetReg(x, Int32, {}, wreg - {CX});
DevCPL486.GenNot(x);
IF ~incl0x THEN DevCPL486.MakeConst(c, 1, Int32); DevCPL486.GenSub(c, x, FALSE) END;
FreeWReg(DI)
END StrLen;
PROCEDURE MulDim* (VAR y, z: DevCPL486.Item; VAR fact: INTEGER; dimtyp: DevCPT.Struct); (* z := z * y *)
VAR c: DevCPL486.Item;
BEGIN
IF y.mode = Con THEN
IF y.offset <= MAX(INTEGER) DIV fact THEN fact := fact * y.offset
ELSE fact := 1; DevCPM.err(214)
END
ELSE
IF ranchk OR inxchk THEN
DevCPL486.MakeConst(c, 0, Int32); DevCPL486.GenComp(c, y); DevCPL486.GenAssert(ccG, ranTrap)
END;
DevCPL486.GenPush(y);
IF z.mode = Con THEN z := y
ELSE DevCPL486.GenMul(y, z, ovflchk OR inxchk); Free(y)
END
END
END MulDim;
PROCEDURE SetDim* (VAR x, y: DevCPL486.Item; dimtyp: DevCPT.Struct); (* set LEN(x^, -dimtyp.n) *)
(* y const or on stack *)
VAR z: DevCPL486.Item; end: DevCPL486.Label;
BEGIN
ASSERT((x.mode = Reg) & (x.form = Pointer));
z.mode := Ind; z.reg := x.reg; z.offset := ArrDOffs + 4 + dimtyp.n * 4; z.scale := 0; z.form := Int32;
IF y.mode = Con THEN y.form := Int32
ELSE Pop(y, Int32, {}, {})
END;
end := DevCPL486.NewLbl; DevCPL486.GenJump(ccE, end, TRUE); (* flags set in New *)
DevCPL486.GenMove(y, z);
DevCPL486.SetLabel(end);
IF y.mode = Reg THEN Free(y) END
END SetDim;
PROCEDURE SysNew* (VAR x: DevCPL486.Item);
BEGIN
DevCPM.err(141)
END SysNew;
PROCEDURE New* (VAR x, nofel: DevCPL486.Item; fact: INTEGER);
(* x.typ.BaseTyp.comp IN {Record, Array, DynArr} *)
VAR p, tag, c: DevCPL486.Item; nofdim, dlen, n: INTEGER; typ, eltyp: DevCPT.Struct; lbl: DevCPL486.Label;
BEGIN
typ := x.typ.BaseTyp;
IF typ.untagged THEN DevCPM.err(138) END;
IF typ.comp = Record THEN (* call to Kernel.NewRec(tag: Tag): ADDRESS *)
DevCPL486.MakeConst(tag, 0, Pointer); tag.obj := DevCPE.TypeObj(typ);
IF ContainsIPtrs(typ) THEN INC(tag.offset) END;
DevCPL486.GenPush(tag);
p.mode := XProc; p.obj := DevCPE.KNewRec;
ELSE eltyp := typ.BaseTyp;
IF typ.comp = Array THEN
nofdim := 0; nofel.mode := Con; nofel.form := Int32; fact := typ.n
ELSE (* DynArr *)
nofdim := typ.n+1;
WHILE eltyp.comp = DynArr DO eltyp := eltyp.BaseTyp END
END ;
WHILE eltyp.comp = Array DO fact := fact * eltyp.n; eltyp := eltyp.BaseTyp END;
IF eltyp.comp = Record THEN
IF eltyp.untagged THEN DevCPM.err(138) END;
DevCPL486.MakeConst(tag, 0, Pointer); tag.obj := DevCPE.TypeObj(eltyp);
IF ContainsIPtrs(eltyp) THEN INC(tag.offset) END;
ELSIF eltyp.form = Pointer THEN
IF ~eltyp.untagged THEN
DevCPL486.MakeConst(tag, 0, Pointer) (* special TDesc in Kernel for ARRAY OF pointer *)
ELSIF eltyp.sysflag = interface THEN
DevCPL486.MakeConst(tag, -1, Pointer) (* special TDesc in Kernel for ARRAY OF interface pointer *)
ELSE
DevCPL486.MakeConst(tag, 12, Pointer)
END
ELSE (* eltyp is pointerless basic type *)
CASE eltyp.form OF
| Undef, Byte, Char8: n := 1;
| Int16: n := 2;
| Int8: n := 3;
| Int32: n := 4;
| Bool: n := 5;
| Set: n := 6;
| Real32: n := 7;
| Real64: n := 8;
| Char16: n := 9;
| Int64: n := 10;
| ProcTyp: n := 11;
END;
DevCPL486.MakeConst(tag, n, Pointer)
(*
DevCPL486.MakeConst(tag, eltyp.size, Pointer)
*)
END;
IF nofel.mode = Con THEN nofel.offset := fact; nofel.obj := NIL
ELSE DevCPL486.MakeConst(p, fact, Int32); DevCPL486.GenMul(p, nofel, ovflchk OR inxchk)
END;
DevCPL486.MakeConst(p, nofdim, Int32); DevCPL486.GenPush(p);
DevCPL486.GenPush(nofel); Free(nofel); DevCPL486.GenPush(tag);
p.mode := XProc; p.obj := DevCPE.KNewArr;
END;
DevCPL486.GenCall(p); GetReg(x, Pointer, {}, wreg - {AX});
IF typ.comp = DynArr THEN (* set flags for nil test *)
DevCPL486.MakeConst(c, 0, Pointer); DevCPL486.GenComp(c, x)
ELSIF typ.comp = Record THEN
n := NumOfIntProc(typ);
IF n > 0 THEN (* interface method table pointer setup *)
DevCPL486.MakeConst(c, 0, Pointer); DevCPL486.GenComp(c, x);
lbl := DevCPL486.NewLbl; DevCPL486.GenJump(ccE, lbl, TRUE);
tag.offset := - 4 * (n + numPreIntProc);
p.mode := Ind; p.reg := AX; p.offset := 0; p.scale := 0; p.form := Pointer;
DevCPL486.GenMove(tag, p);
IF nofel.mode # Con THEN (* unk pointer setup *)
p.offset := 8;
DevCPL486.GenMove(nofel, p);
Free(nofel)
END;
DevCPL486.SetLabel(lbl);
END
END
END New;
PROCEDURE Param* (fp: DevCPT.Object; rec, niltest: BOOLEAN; VAR ap, tag: DevCPL486.Item); (* returns tag if rec *)
VAR f: BYTE; s, ss: INTEGER; par, a, c: DevCPL486.Item; recTyp: DevCPT.Struct;
BEGIN
par.mode := Stk; par.typ := fp.typ; par.form := par.typ.form;
IF ODD(fp.sysflag DIV nilBit) THEN niltest := FALSE END;
IF ap.typ = DevCPT.niltyp THEN
IF ((par.typ.comp = Record) OR (par.typ.comp = DynArr)) & ~par.typ.untagged THEN
DevCPM.err(142)
END;
DevCPL486.GenPush(ap)
ELSIF par.typ.comp = DynArr THEN
IF ap.form IN {String8, String16} THEN
IF ~par.typ.untagged THEN
DevCPL486.MakeConst(c, ap.index (* * ap.typ.BaseTyp.size *), Int32); DevCPL486.GenPush(c)
END;
ap.mode := Con; DevCPL486.GenPush(ap);
ELSIF ap.form IN {VString8, VString16} THEN
DevCPL486.MakeReg(a, DX, Pointer); DevCPL486.GenLoadAdr(ap, a);
IF ~par.typ.untagged THEN
DevCPL486.MakeReg(c, DI, Pointer); DevCPL486.GenMove(a, c);
Free(ap); StrLen(c, ap.typ, TRUE);
DevCPL486.GenPush(c); Free(c)
END;
DevCPL486.GenPush(a)
ELSE
IF ~par.typ.untagged THEN
IF ap.typ.comp = DynArr THEN niltest := FALSE END; (* ap dereferenced for length descriptor *)
VarParDynArr(par.typ, ap)
END;
PushAdr(ap, niltest)
END
ELSIF fp.mode = VarPar THEN
recTyp := ap.typ;
IF recTyp.form = Pointer THEN recTyp := recTyp.BaseTyp END;
IF (par.typ.comp = Record) & (~fp.typ.untagged) THEN
Tag(ap, tag);
IF rec & (tag.mode # Con) THEN
GetReg(c, Pointer, {}, {}); DevCPL486.GenMove(tag, c); tag := c
END;
DevCPL486.GenPush(tag);
IF tag.mode # Con THEN niltest := FALSE END;
PushAdr(ap, niltest);
IF rec THEN Free(tag) END
ELSE PushAdr(ap, niltest)
END;
tag.typ := recTyp
ELSIF par.form = Comp THEN
s := par.typ.size;
IF initializeStr & (ap.form IN {String8, String16, VString8, VString16, VString16to8}) THEN
s := (s + 3) DIV 4 * 4; AdjustStack(-s);
IF ap.form IN {String8, String16} THEN
IF ap.index > 1 THEN (* nonempty string *)
ss := (ap.index * ap.typ.BaseTyp.size + 3) DIV 4 * 4;
DevCPL486.MakeReg(c, SI, Pointer); DevCPL486.GenLoadAdr(ap, c); Free(ap);
DevCPL486.MakeReg(c, DI, Pointer); DevCPL486.GenLoadAdr(par, c);
DevCPL486.GenBlockMove(1, ss);
ELSE
ss := 0;
DevCPL486.MakeReg(c, DI, Pointer); DevCPL486.GenLoadAdr(par, c)
END;
IF s > ss THEN
DevCPL486.MakeReg(a, AX, Int32); DevCPL486.MakeConst(c, 0, Int32); DevCPL486.GenMove(c, a);
DevCPL486.GenBlockStore(1, s - ss)
END;
ELSE
DevCPL486.MakeReg(c, SI, Pointer); DevCPL486.GenLoadAdr(ap, c); Free(ap);
DevCPL486.MakeReg(c, DI, Pointer); DevCPL486.GenLoadAdr(par, c);
DevCPL486.GenStringMove(TRUE, StringWSize(ap), StringWSize(par), par.typ.n);
DevCPL486.MakeReg(a, AX, Int32); DevCPL486.MakeConst(c, 0, Int32); DevCPL486.GenMove(c, a);
DevCPL486.GenBlockStore(StringWSize(par), 0)
END
ELSE
IF (ap.form IN {String8, String16}) & (ap.index = 1) THEN (* empty string *)
AdjustStack((4 - s) DIV 4 * 4);
DevCPL486.MakeConst(c, 0, Int32); DevCPL486.GenPush(c)
ELSE
AdjustStack((-s) DIV 4 * 4);
DevCPL486.MakeReg(c, SI, Pointer); DevCPL486.GenLoadAdr(ap, c); Free(ap);
DevCPL486.MakeReg(c, DI, Pointer); DevCPL486.GenLoadAdr(par, c);
IF ap.form IN {String8, String16} THEN
DevCPL486.GenBlockMove(1, (ap.index * ap.typ.BaseTyp.size + 3) DIV 4 * 4)
ELSIF ap.form IN {VString8, VString16, VString16to8} THEN
DevCPL486.GenStringMove(FALSE, StringWSize(ap), StringWSize(par), par.typ.n)
ELSE
DevCPL486.GenBlockMove(1, (s + 3) DIV 4 * 4)
END
END
END
ELSIF ap.mode = Con THEN
IF ap.form IN {Real32, Real64} THEN (* ??? push const *)
DevCPL486.GenFLoad(ap); DecStack(par.typ.form); DevCPL486.GenFStore(par, TRUE)
ELSE
ap.form := Int32;
IF par.form = Int64 THEN DevCPL486.MakeConst(c, ap.scale, Int32); DevCPL486.GenPush(c) END;
DevCPL486.GenPush(ap)
END
ELSIF ap.typ.form = Pointer THEN
recTyp := ap.typ.BaseTyp;
IF rec THEN
Load(ap, {}, {}); Tag(ap, tag);
IF tag.mode = Con THEN (* explicit nil test needed *)
DevCPL486.MakeReg(a, AX, Int32);
c.mode := Ind; c.form := Int32; c.offset := 0; c.scale := 0; c.reg := ap.reg;
DevCPL486.GenTest(a, c)
END
END;
DevCPL486.GenPush(ap); Free(ap);
tag.typ := recTyp
ELSIF ap.form IN {Comp, String8, String16, VString8, VString16} THEN (* convert to pointer *)
ASSERT(par.form = Pointer);
PushAdr(ap, FALSE)
ELSE
ConvMove(par, ap, FALSE, {}, {high});
END
END Param;
PROCEDURE Result* (proc: DevCPT.Object; VAR res: DevCPL486.Item);
VAR r: DevCPL486.Item;
BEGIN
DevCPL486.MakeReg(r, AX, proc.typ.form); (* don't allocate AX ! *)
IF res.mode = Con THEN
IF r.form IN {Real32, Real64} THEN DevCPL486.GenFLoad(res);
ELSIF r.form = Int64 THEN
r.form := Int32; res.form := Int32; DevCPL486.GenMove(res, r);
r.reg := DX; res.offset := res.scale; DevCPL486.GenMove(res, r)
ELSE DevCPL486.GenMove(res, r);
END
ELSIF res.form IN {Comp, String8, String16, VString8, VString16} THEN (* convert to pointer *)
ASSERT(r.form = Pointer);
GetAdr(res, {}, wreg - {AX})
ELSE
r.index := DX; (* for int64 *)
ConvMove(r, res, FALSE, wreg - {AX} + {high}, {});
END;
Free(res)
END Result;
PROCEDURE InitFpu;
VAR x: DevCPL486.Item;
BEGIN
DevCPL486.MakeConst(x, FpuControlRegister, Int32); DevCPL486.GenPush(x);
DevCPL486.GenFMOp(12CH); DevCPL486.GenCode(24H); (* FLDCW 0(SP) *)
DevCPL486.MakeReg(x, CX, Int32); DevCPL486.GenPop(x); (* reset stack *)
END InitFpu;
PROCEDURE PrepCall* (proc: DevCPT.Object);
VAR lev: BYTE; r: DevCPL486.Item;
BEGIN
lev := proc.mnolev;
IF (slNeeded IN proc.conval.setval) & (imLevel[lev] > 0) & (imLevel[DevCPL486.level] > imLevel[lev]) THEN
DevCPL486.MakeReg(r, BX, Pointer); DevCPL486.GenPush(r)
END
END PrepCall;
(* ccall16: Prologue / epilogue *)
PROCEDURE PreCcall16* (val: INTEGER);
VAR c, sp,cx: DevCPL486.Item;
BEGIN
CheckAv(CX);
DevCPL486.MakeReg(cx, CX, Int32);
DevCPL486.MakeReg(sp, SP, Int32);
DevCPL486.GenMove(sp, cx); (* MOVE ECX, ESP *)
DevCPL486.MakeConst(c, -16, Int32);
DevCPL486.GenAnd(c, sp); (* AND ESP,-16*)
DevCPL486.GenPush(cx); (* push ecx *)
val:= (-4 - val) MOD 16;
IF val # 0 THEN
DevCPL486.MakeConst(c, val, Int32);
DevCPL486.GenSub(c, sp, FALSE) (* sub ESP, val *)
END
END PreCcall16;
PROCEDURE PostCcall16* (val: INTEGER);
VAR c, sp: DevCPL486.Item;
BEGIN
val := (-4 - val) MOD 16 + val;
DevCPL486.MakeConst(c, val, Int32);
DevCPL486.MakeReg(sp, SP, Int32);
DevCPL486.GenAdd(c, sp, FALSE); (* ADD ESP, val *)
DevCPL486.GenPop(sp) (* POP ESP*)
END PostCcall16;
PROCEDURE CCallParSize* (proc: DevCPT.Object; typ: DevCPT.Struct): INTEGER;
VAR p: DevCPT.Object; n: INTEGER; t: DevCPT.Struct;
BEGIN
n := 0;
IF proc # NIL THEN p := proc.link; ELSE p := typ.link; END;
WHILE p # NIL DO
IF p.mode = VarPar THEN
IF (p.typ.comp = DynArr) & ~p.typ.untagged THEN INC(n, p.typ.size)
ELSIF (p.typ.comp = Record) & ~p.typ.untagged THEN INC(n, 4 + 4)
ELSE INC(n, 4)
END
ELSE
INC(n, (p.typ.size + 3) DIV 4 * 4)
END;
p := p.link
END;
RETURN n
END CCallParSize;
PROCEDURE Call* (VAR x, tag: DevCPL486.Item); (* TProc: tag.typ = actual receiver type *)
CONST
ccall16 = -12;
VAR i, n: INTEGER; r, y: DevCPL486.Item; typ: DevCPT.Struct; lev: BYTE; saved: BOOLEAN;
BEGIN
IF x.mode IN {LProc, XProc, IProc} THEN
lev := x.obj.mnolev; saved := FALSE;
IF (slNeeded IN x.obj.conval.setval) & (imLevel[lev] > 0) THEN (* pass static link *)
n := imLevel[DevCPL486.level] - imLevel[lev];
IF n > 0 THEN
saved := TRUE;
y.mode := Ind; y.scale := 0; y.form := Pointer; y.reg := BX; y.offset := -4;
DevCPL486.MakeReg(r, BX, Pointer);
WHILE n > 0 DO DevCPL486.GenMove(y, r); DEC(n) END
END
END;
DevCPL486.GenCall(x);
IF (x.obj.sysflag = ccall) OR (x.obj.sysflag = ccall16) THEN
n:=CCallParSize(x.obj, NIL);
IF (x.obj.sysflag = ccall) THEN
AdjustStack(n)
ELSE (* ccall16*)
PostCcall16(n)
END;
END;
IF saved THEN DevCPL486.GenPop(r) END;
ELSIF x.mode = TProc THEN
IF x.scale = 1 THEN (* super *)
DevCPL486.MakeConst(tag, 0, Pointer); tag.obj := DevCPE.TypeObj(tag.typ.BaseTyp)
ELSIF x.scale = 2 THEN (* static call *)
DevCPL486.MakeConst(tag, 0, Pointer); typ := x.obj.link.typ;
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
tag.obj := DevCPE.TypeObj(typ)
ELSIF x.scale = 3 THEN (* interface method call *)
DevCPM.err(200)
END;
IF tag.mode = Con THEN
y.mode := Abs; y.offset := tag.offset; y.obj := tag.obj; y.scale := 0
ELSIF (x.obj.conval.setval * {absAttr, empAttr, extAttr} = {}) & ~(DevCPM.oberon IN DevCPM.options) THEN (* final method *)
y.mode := Abs; y.offset := 0; y.obj := DevCPE.TypeObj(tag.typ); y.scale := 0;
IF tag.mode = Ind THEN (* nil test *)
DevCPL486.MakeReg(r, AX, Int32); tag.offset := 0; DevCPL486.GenTest(r, tag)
END
ELSE
IF tag.mode = Reg THEN y.reg := tag.reg
ELSE GetReg(y, Pointer, {}, {}); DevCPL486.GenMove(tag, y)
END;
y.mode := Ind; y.offset := 0; y.scale := 0
END;
IF (tag.typ.sysflag = interface) & (y.mode = Ind) THEN y.offset := 4 * x.offset
ELSIF tag.typ.untagged THEN DevCPM.err(140)
ELSE
IF x.obj.link.typ.sysflag = interface THEN (* correct method number *)
x.offset := numPreIntProc + NumOfIntProc(tag.typ) - 1 - x.offset
END;
INC(y.offset, Mth0Offset - 4 * x.offset)
END;
DevCPL486.GenCall(y); Free(y)
ELSIF x.mode = CProc THEN
IF x.obj.link # NIL THEN (* tag = first param *)
IF x.obj.link.mode = VarPar THEN
GetAdr(tag, {}, wreg - {AX} + {stk, mem, con}); Free(tag)
ELSE
(* Load(tag, {}, wreg - {AX} + {con}); Free(tag) *)
Result(x.obj.link, tag) (* use result load for first parameter *)
END
END;
IF x.obj.conval.ext # NIL THEN i := 0; n := LEN(x.obj.conval.ext^);
WHILE i < n DO DevCPL486.GenCode(ORD(x.obj.conval.ext^[i])); INC(i) END
END
ELSE (* proc var *)
DevCPL486.GenCall(x); Free(x);
IF (x.typ.sysflag = ccall) OR (x.typ.sysflag = ccall16) THEN
n:=CCallParSize(NIL, x.typ);
IF x.typ.sysflag = ccall THEN
AdjustStack(n)
ELSE (* ccall16*)
PostCcall16(n)
END
END;
x.typ := x.typ.BaseTyp
END;
IF procedureUsesFpu & (x.mode = XProc) & (x.obj.mnolev < 0) & (x.obj.mnolev > -128)
& ((x.obj.library # NIL) OR (DevCPT.GlbMod[-x.obj.mnolev].library # NIL)) THEN (* restore fpu *)
InitFpu
END;
CheckReg;
IF x.typ.form = Int64 THEN
GetReg(x, Int32, {}, wreg - {AX}); GetReg(y, Int32, {}, wreg - {DX});
x.index := y.reg; x.form := Int64
ELSIF x.typ.form # NoTyp THEN GetReg(x, x.typ.form, {}, wreg - {AX} + {high})
END
END Call;
PROCEDURE CopyDynArray* (adr: INTEGER; typ: DevCPT.Struct); (* needs CX, SI, DI *)
VAR len, ptr, c, sp, src, dst: DevCPL486.Item; bt: DevCPT.Struct;
BEGIN
IF typ.untagged THEN DevCPM.err(-137) END;
ptr.mode := Ind; ptr.reg := BP; ptr.offset := adr+4; ptr.scale := 0; ptr.form := Pointer;
DevCPL486.MakeReg(len, CX, Int32); DevCPL486.MakeReg(sp, SP, Int32);
DevCPL486.MakeReg(src, SI, Int32); DevCPL486.MakeReg(dst, DI, Int32);
DevCPL486.GenMove(ptr, len); bt := typ.BaseTyp;
WHILE bt.comp = DynArr DO
INC(ptr.offset, 4); DevCPL486.GenMul(ptr, len, FALSE); bt := bt.BaseTyp
END;
ptr.offset := adr; DevCPL486.GenMove(ptr, src);
DevCPL486.MakeConst(c, bt.size, Int32); DevCPL486.GenMul(c, len, FALSE);
(* CX = length in bytes *)
StackAlloc;
(* CX = length in 32bit words *)
DevCPL486.GenMove(sp, dst); DevCPL486.GenMove(dst, ptr);
DevCPL486.GenBlockMove(4, 0) (* 32bit moves *)
END CopyDynArray;
PROCEDURE Sort (VAR tab: ARRAY OF INTEGER; VAR n: INTEGER);
VAR i, j, x: INTEGER;
BEGIN
(* align *)
i := 1;
WHILE i < n DO
x := tab[i]; j := i-1;
WHILE (j >= 0) & (tab[j] < x) DO tab[j+1] := tab[j]; DEC(j) END;
tab[j+1] := x; INC(i)
END;
(* eliminate equals *)
i := 1; j := 1;
WHILE i < n DO
IF tab[i] # tab[i-1] THEN tab[j] := tab[i]; INC(j) END;
INC(i)
END;
n := j
END Sort;
PROCEDURE FindPtrs (typ: DevCPT.Struct; adr: INTEGER; VAR num: INTEGER);
VAR fld: DevCPT.Object; btyp: DevCPT.Struct; i, n: INTEGER;
BEGIN
IF typ.form IN {Pointer, ProcTyp} THEN
IF num < MaxPtrs THEN ptrTab[num] := adr DIV 4 * 4 END;
INC(num);
IF adr MOD 4 # 0 THEN
IF num < MaxPtrs THEN ptrTab[num] := adr DIV 4 * 4 + 4 END;
INC(num)
END
ELSIF typ.comp = Record THEN
btyp := typ.BaseTyp;
IF btyp # NIL THEN FindPtrs(btyp, adr, num) END ;
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF (fld.name^ = DevCPM.HdPtrName) OR
(fld.name^ = DevCPM.HdUtPtrName) OR
(fld.name^ = DevCPM.HdProcName) THEN
FindPtrs(DevCPT.sysptrtyp, fld.adr + adr, num)
ELSE FindPtrs(fld.typ, fld.adr + adr, num)
END;
fld := fld.link
END
ELSIF typ.comp = Array THEN
btyp := typ.BaseTyp; n := typ.n;
WHILE btyp.comp = Array DO n := btyp.n * n; btyp := btyp.BaseTyp END ;
IF (btyp.form = Pointer) OR (btyp.comp = Record) THEN
i := num; FindPtrs(btyp, adr, num);
IF num # i THEN i := 1;
WHILE (i < n) & (num <= MaxPtrs) DO
INC(adr, btyp.size); FindPtrs(btyp, adr, num); INC(i)
END
END
END
END
END FindPtrs;
PROCEDURE InitOutPar (par: DevCPT.Object; VAR zreg: DevCPL486.Item);
VAR x, y, c, len: DevCPL486.Item; lbl: DevCPL486.Label; size, s: INTEGER; bt: DevCPT.Struct;
BEGIN
x.mode := Ind; x.reg := BP; x.scale := 0; x.form := Pointer; x.offset := par.adr;
DevCPL486.MakeReg(y, DI, Int32);
IF par.typ.comp # DynArr THEN
DevCPL486.GenMove(x, y);
lbl := DevCPL486.NewLbl;
IF ODD(par.sysflag DIV nilBit) THEN
DevCPL486.GenComp(zreg, y);
DevCPL486.GenJump(ccE, lbl, TRUE)
END;
size := par.typ.size;
IF size <= 16 THEN
x.mode := Ind; x.reg := DI; x.form := Int32; x.offset := 0;
WHILE size > 0 DO
IF size = 1 THEN x.form := Int8; s := 1
ELSIF size = 2 THEN x.form := Int16; s := 2
ELSE x.form := Int32; s := 4
END;
zreg.form := x.form; DevCPL486.GenMove(zreg, x); INC(x.offset, s); DEC(size, s)
END;
zreg.form := Int32
ELSE
DevCPL486.GenBlockStore(1, size)
END;
DevCPL486.SetLabel(lbl)
ELSIF initializeDyn & ~par.typ.untagged THEN (* untagged open arrays not initialized !!! *)
DevCPL486.GenMove(x, y);
DevCPL486.MakeReg(len, CX, Int32);
INC(x.offset, 4); DevCPL486.GenMove(x, len); (* first len *)
bt := par.typ.BaseTyp;
WHILE bt.comp = DynArr DO
INC(x.offset, 4); DevCPL486.GenMul(x, len, FALSE); bt := bt.BaseTyp
END;
size := bt.size;
IF size MOD 4 = 0 THEN size := size DIV 4; s := 4
ELSIF size MOD 2 = 0 THEN size := size DIV 2; s := 2
ELSE s := 1
END;
DevCPL486.MakeConst(c, size, Int32); DevCPL486.GenMul(c, len, FALSE);
DevCPL486.GenBlockStore(s, 0)
END
END InitOutPar;
PROCEDURE AllocAndInitAll (proc: DevCPT.Object; adr, size: INTEGER; VAR nofptrs: INTEGER);
VAR x, y, z, zero: DevCPL486.Item; par: DevCPT.Object; op: INTEGER;
BEGIN
op := 0; par := proc.link;
WHILE par # NIL DO (* count out parameters [with COM pointers] *)
IF (par.mode = VarPar) & (par.vis = outPar) & (initializeOut OR ContainsIPtrs(par.typ)) THEN INC(op) END;
par := par.link
END;
DevCPL486.MakeConst(zero, 0, Int32);
IF (op = 0) & (size <= 8) THEN (* use PUSH 0 *)
WHILE size > 0 DO DevCPL486.GenPush(zero); DEC(size, 4) END
ELSE
DevCPL486.MakeReg(z, AX, Int32); DevCPL486.GenMove(zero, z);
IF size <= 32 THEN (* use PUSH reg *)
WHILE size > 0 DO DevCPL486.GenPush(z); DEC(size, 4) END
ELSE (* use string store *)
AdjustStack(-size);
DevCPL486.MakeReg(x, SP, Int32); DevCPL486.MakeReg(y, DI, Int32); DevCPL486.GenMove(x, y);
DevCPL486.GenBlockStore(1, size)
END;
IF op > 0 THEN
par := proc.link;
WHILE par # NIL DO (* init out parameters [with COM pointers] *)
IF (par.mode = VarPar) & (par.vis = outPar) & (initializeOut OR ContainsIPtrs(par.typ)) THEN InitOutPar(par, z) END;
par := par.link
END
END
END
END AllocAndInitAll;
PROCEDURE AllocAndInitPtrs1 (proc: DevCPT.Object; adr, size: INTEGER; VAR nofptrs: INTEGER); (* needs AX *)
VAR i, base, a, gaps: INTEGER; x, z: DevCPL486.Item; obj: DevCPT.Object;
BEGIN
IF ptrinit & (proc.scope # NIL) THEN
nofptrs := 0; obj := proc.scope.scope; (* local variables *)
WHILE (obj # NIL) & (nofptrs <= MaxPtrs) DO
FindPtrs(obj.typ, obj.adr, nofptrs);
obj := obj.link
END;
IF (nofptrs > 0) & (nofptrs <= MaxPtrs) THEN
base := proc.conval.intval2;
Sort(ptrTab, nofptrs); i := 0; a := size + base; gaps := 0;
WHILE i < nofptrs DO
DEC(a, 4);
IF a # ptrTab[i] THEN a := ptrTab[i]; INC(gaps) END;
INC(i)
END;
IF a # base THEN INC(gaps) END;
IF (gaps <= (nofptrs + 1) DIV 2) & (size < stackAllocLimit) THEN
DevCPL486.MakeConst(z, 0, Pointer);
IF (nofptrs > 4) THEN x := z; DevCPL486.MakeReg(z, AX, Int32); DevCPL486.GenMove(x, z) END;
i := 0; a := size + base;
WHILE i < nofptrs DO
DEC(a, 4);
IF a # ptrTab[i] THEN AdjustStack(ptrTab[i] - a); a := ptrTab[i] END;
DevCPL486.GenPush(z); INC(i)
END;
IF a # base THEN AdjustStack(base - a) END
ELSE
AdjustStack(-size);
DevCPL486.MakeConst(x, 0, Pointer); DevCPL486.MakeReg(z, AX, Int32); DevCPL486.GenMove(x, z);
x.mode := Ind; x.reg := BP; x.scale := 0; x.form := Pointer; i := 0;
WHILE i < nofptrs DO
x.offset := ptrTab[i]; DevCPL486.GenMove(z, x); INC(i)
END
END
ELSE
AdjustStack(-size)
END
ELSE
nofptrs := 0;
AdjustStack(-size)
END
END AllocAndInitPtrs1;
PROCEDURE InitPtrs2 (proc: DevCPT.Object; adr, size, nofptrs: INTEGER); (* needs AX, CX, DI *)
VAR x, y, z, zero: DevCPL486.Item; obj: DevCPT.Object; zeroed: BOOLEAN; i: INTEGER; lbl: DevCPL486.Label;
BEGIN
IF ptrinit THEN
zeroed := FALSE; DevCPL486.MakeConst(zero, 0, Pointer);
IF nofptrs > MaxPtrs THEN
DevCPL486.MakeReg(z, AX, Int32); DevCPL486.GenMove(zero, z); zeroed := TRUE;
x.mode := Ind; x.reg := BP; x.scale := 0; x.form := Pointer; x.offset := adr;
DevCPL486.MakeReg(y, DI, Int32); DevCPL486.GenLoadAdr(x, y);
DevCPL486.GenStrStore(size)
END;
obj := proc.link; (* parameters *)
WHILE obj # NIL DO
IF (obj.mode = VarPar) & (obj.vis = outPar) THEN
nofptrs := 0;
IF obj.typ.comp = DynArr THEN (* currently not initialized *)
ELSE FindPtrs(obj.typ, 0, nofptrs)
END;
IF nofptrs > 0 THEN
IF ~zeroed THEN
DevCPL486.MakeReg(z, AX, Int32); DevCPL486.GenMove(zero, z); zeroed := TRUE
END;
x.mode := Ind; x.reg := BP; x.scale := 0; x.form := Pointer; x.offset := obj.adr;
DevCPL486.MakeReg(y, DI, Int32); DevCPL486.GenMove(x, y);
IF ODD(obj.sysflag DIV nilBit) THEN
DevCPL486.GenComp(zero, y);
lbl := DevCPL486.NewLbl; DevCPL486.GenJump(ccE, lbl, TRUE)
END;
IF nofptrs > MaxPtrs THEN
DevCPL486.GenStrStore(obj.typ.size)
ELSE
Sort(ptrTab, nofptrs);
x.reg := DI; i := 0;
WHILE i < nofptrs DO
x.offset := ptrTab[i]; DevCPL486.GenMove(z, x); INC(i)
END
END;
IF ODD(obj.sysflag DIV nilBit) THEN DevCPL486.SetLabel(lbl) END
END
END;
obj := obj.link
END
END
END InitPtrs2;
PROCEDURE NeedOutPtrInit (proc: DevCPT.Object): BOOLEAN;
VAR obj: DevCPT.Object; nofptrs: INTEGER;
BEGIN
IF ptrinit THEN
obj := proc.link;
WHILE obj # NIL DO
IF (obj.mode = VarPar) & (obj.vis = outPar) THEN
nofptrs := 0;
IF obj.typ.comp = DynArr THEN (* currently not initialized *)
ELSE FindPtrs(obj.typ, 0, nofptrs)
END;
IF nofptrs > 0 THEN RETURN TRUE END
END;
obj := obj.link
END
END;
RETURN FALSE
END NeedOutPtrInit;
PROCEDURE Enter* (proc: DevCPT.Object; empty, useFpu: BOOLEAN);
VAR sp, fp, r, r1: DevCPL486.Item; par: DevCPT.Object; adr, size, np: INTEGER;
BEGIN
procedureUsesFpu := useFpu;
SetReg({AX, CX, DX, SI, DI});
DevCPL486.MakeReg(fp, BP, Pointer); DevCPL486.MakeReg(sp, SP, Pointer);
IF proc # NIL THEN (* enter proc *)
DevCPL486.SetLabel(proc.adr);
IF (~empty OR NeedOutPtrInit(proc)) & (proc.sysflag # noframe) THEN
DevCPL486.GenPush(fp);
DevCPL486.GenMove(sp, fp);
adr := proc.conval.intval2; size := -adr;
IF size < 0 THEN DevCPM.err(214); size := 256 END;
IF isGuarded IN proc.conval.setval THEN
DevCPL486.MakeReg(r, BX, Pointer); DevCPL486.GenPush(r);
DevCPL486.MakeReg(r, DI, Pointer); DevCPL486.GenPush(r);
DevCPL486.MakeReg(r, SI, Pointer); DevCPL486.GenPush(r);
r1.mode := Con; r1.form := Int32; r1.offset := proc.conval.intval - 8; r1.obj := NIL;
DevCPL486.GenPush(r1);
intHandler.used := TRUE;
r1.mode := Con; r1.form := Int32; r1.offset := 0; r1.obj := intHandler;
DevCPL486.GenPush(r1);
r1.mode := Abs; r1.form := Int32; r1.offset := 0; r1.scale := 0; r1.obj := NIL;
DevCPL486.GenCode(64H); DevCPL486.GenPush(r1);
DevCPL486.GenCode(64H); DevCPL486.GenMove(sp, r1);
DEC(size, 24)
ELSE
IF imVar IN proc.conval.setval THEN (* set down pointer *)
DevCPL486.MakeReg(r, BX, Pointer); DevCPL486.GenPush(r); DEC(size, 4)
END;
IF isCallback IN proc.conval.setval THEN
DevCPL486.MakeReg(r, DI, Pointer); DevCPL486.GenPush(r);
DevCPL486.MakeReg(r, SI, Pointer); DevCPL486.GenPush(r); DEC(size, 8)
END
END;
ASSERT(size >= 0);
IF initializeAll THEN
AllocAndInitAll(proc, adr, size, np)
ELSE
AllocAndInitPtrs1(proc, adr, size, np); (* needs AX *)
InitPtrs2(proc, adr, size, np); (* needs AX, CX, DI *)
END;
par := proc.link; (* parameters *)
WHILE par # NIL DO
IF (par.mode = Var) & (par.typ.comp = DynArr) THEN
CopyDynArray(par.adr, par.typ)
END;
par := par.link
END;
IF imVar IN proc.conval.setval THEN
DevCPL486.MakeReg(r, BX, Pointer); DevCPL486.GenMove(fp, r)
END
END
ELSIF ~empty THEN (* enter module *)
DevCPL486.GenPush(fp);
DevCPL486.GenMove(sp, fp);
DevCPL486.MakeReg(r, DI, Int32); DevCPL486.GenPush(r);
DevCPL486.MakeReg(r, SI, Int32); DevCPL486.GenPush(r)
END;
IF useFpu THEN InitFpu END
END Enter;
PROCEDURE Exit* (proc: DevCPT.Object; empty: BOOLEAN);
VAR sp, fp, r, x: DevCPL486.Item; size: INTEGER;
BEGIN
DevCPL486.MakeReg(sp, SP, Pointer); DevCPL486.MakeReg(fp, BP, Pointer);
IF proc # NIL THEN (* exit proc *)
IF proc.sysflag # noframe THEN
IF ~empty OR NeedOutPtrInit(proc) THEN
IF isGuarded IN proc.conval.setval THEN (* remove exception frame *)
x.mode := Ind; x.reg := BP; x.offset := -24; x.scale := 0; x.form := Int32;
DevCPL486.MakeReg(r, CX, Int32); DevCPL486.GenMove(x, r);
x.mode := Abs; x.offset := 0; x.scale := 0; x.form := Int32; x.obj := NIL;
DevCPL486.GenCode(64H); DevCPL486.GenMove(r, x);
size := 12
ELSE
size := 0;
IF imVar IN proc.conval.setval THEN INC(size, 4) END;
IF isCallback IN proc.conval.setval THEN INC(size, 8) END
END;
IF size > 0 THEN
x.mode := Ind; x.reg := BP; x.offset := -size; x.scale := 0; x.form := Int32;
DevCPL486.GenLoadAdr(x, sp);
IF size > 4 THEN
DevCPL486.MakeReg(r, SI, Int32); DevCPL486.GenPop(r);
DevCPL486.MakeReg(r, DI, Int32); DevCPL486.GenPop(r)
END;
IF size # 8 THEN
DevCPL486.MakeReg(r, BX, Int32); DevCPL486.GenPop(r)
END
ELSE
DevCPL486.GenMove(fp, sp)
END;
DevCPL486.GenPop(fp)
END;
IF proc.sysflag = ccall THEN DevCPL486.GenReturn(0)
ELSE DevCPL486.GenReturn(proc.conval.intval - 8)
END
END
ELSE (* exit module *)
IF ~empty THEN
DevCPL486.MakeReg(r, SI, Int32); DevCPL486.GenPop(r);
DevCPL486.MakeReg(r, DI, Int32); DevCPL486.GenPop(r);
DevCPL486.GenMove(fp, sp); DevCPL486.GenPop(fp)
END;
DevCPL486.GenReturn(0)
END
END Exit;
PROCEDURE InstallStackAlloc*;
VAR name: ARRAY 32 OF SHORTCHAR; ax, cx, sp, c, x: DevCPL486.Item; l1, l2: DevCPL486.Label;
BEGIN
IF stkAllocLbl # DevCPL486.NewLbl THEN
DevCPL486.SetLabel(stkAllocLbl);
DevCPL486.MakeReg(ax, AX, Int32);
DevCPL486.MakeReg(cx, CX, Int32);
DevCPL486.MakeReg(sp, SP, Int32);
DevCPL486.GenPush(ax);
DevCPL486.MakeConst(c, -5, Int32); DevCPL486.GenAdd(c, cx, FALSE);
l1 := DevCPL486.NewLbl; DevCPL486.GenJump(ccNS, l1, TRUE);
DevCPL486.MakeConst(c, 0, Int32); DevCPL486.GenMove(c, cx);
DevCPL486.SetLabel(l1);
DevCPL486.MakeConst(c, -4, Int32); DevCPL486.GenAnd(c, cx);
DevCPL486.GenMove(cx, ax);
DevCPL486.MakeConst(c, 4095, Int32); DevCPL486.GenAnd(c, ax);
DevCPL486.GenSub(ax, sp, FALSE);
DevCPL486.GenMove(cx, ax);
DevCPL486.MakeConst(c, 12, Int32); DevCPL486.GenShiftOp(SHR, c, ax);
l2 := DevCPL486.NewLbl; DevCPL486.GenJump(ccE, l2, TRUE);
l1 := DevCPL486.NewLbl; DevCPL486.SetLabel(l1);
DevCPL486.MakeConst(c, 0, Int32); DevCPL486.GenPush(c);
DevCPL486.MakeConst(c, 4092, Int32); DevCPL486.GenSub(c, sp, FALSE);
DevCPL486.MakeConst(c, -1, Int32); DevCPL486.GenAdd(c, ax, FALSE);
DevCPL486.GenJump(ccNE, l1, TRUE);
DevCPL486.SetLabel(l2);
DevCPL486.MakeConst(c, 8, Int32); DevCPL486.GenAdd(c, cx, FALSE);
x.mode := Ind; x.form := Int32; x.offset := -4; x.index := CX; x.reg := SP; x.scale := 1;
DevCPL486.GenMove(x, ax);
DevCPL486.GenPush(ax);
DevCPL486.GenMove(x, ax);
DevCPL486.MakeConst(c, 2, Int32); DevCPL486.GenShiftOp(SHR, c, cx);
DevCPL486.GenReturn(0);
name := "$StackAlloc"; DevCPE.OutRefName(name);
END
END InstallStackAlloc;
PROCEDURE Trap* (n: INTEGER);
BEGIN
DevCPL486.GenAssert(ccNever, n)
END Trap;
PROCEDURE Jump* (VAR L: DevCPL486.Label);
BEGIN
DevCPL486.GenJump(ccAlways, L, FALSE)
END Jump;
PROCEDURE JumpT* (VAR x: DevCPL486.Item; VAR L: DevCPL486.Label);
BEGIN
DevCPL486.GenJump(x.offset, L, FALSE);
END JumpT;
PROCEDURE JumpF* (VAR x: DevCPL486.Item; VAR L: DevCPL486.Label);
BEGIN
DevCPL486.GenJump(Inverted(x.offset), L, FALSE);
END JumpF;
PROCEDURE CaseTableJump* (VAR x: DevCPL486.Item; low, high: INTEGER; VAR else: DevCPL486.Label);
VAR c: DevCPL486.Item; n: INTEGER;
BEGIN
n := high - low + 1;
DevCPL486.MakeConst(c, low, Int32); DevCPL486.GenSub(c, x, FALSE);
DevCPL486.MakeConst(c, n, Int32); DevCPL486.GenComp(c, x);
DevCPL486.GenJump(ccAE, else, FALSE);
DevCPL486.GenCaseJump(x)
END CaseTableJump;
PROCEDURE CaseJump* (VAR x: DevCPL486.Item; low, high: INTEGER; VAR this, else: DevCPL486.Label; tree, first: BOOLEAN);
VAR c: DevCPL486.Item;
BEGIN
IF high = low THEN
DevCPL486.MakeConst(c, low, Int32); DevCPL486.GenComp(c, x);
IF tree THEN DevCPL486.GenJump(ccG, else, FALSE) END;
DevCPL486.GenJump(ccE, this, FALSE)
ELSIF first THEN
DevCPL486.MakeConst(c, low, Int32); DevCPL486.GenComp(c, x);
DevCPL486.GenJump(ccL, else, FALSE);
DevCPL486.MakeConst(c, high, Int32); DevCPL486.GenComp(c, x);
DevCPL486.GenJump(ccLE, this, FALSE);
ELSE
DevCPL486.MakeConst(c, high, Int32); DevCPL486.GenComp(c, x);
DevCPL486.GenJump(ccG, else, FALSE);
DevCPL486.MakeConst(c, low, Int32); DevCPL486.GenComp(c, x);
DevCPL486.GenJump(ccGE, this, FALSE);
END
END CaseJump;
BEGIN
imLevel[0] := 0
END DevCPC486.
| Dev/Mod/CPC486.odc |
MODULE DevCPE;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems, Robert Campbell"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, support for signatures added
- 20070816, bh, ProcTyp inserted in base type handling in PrepDesc
- 20080202, bh, Real comparison corrected in AllocConst (proposed by Robert Campbell)
- 20160324, center #111, code cleanups
- 20170612, center #160, outdated link to OP2.Paper.ps
"
issues = "
- ...
"
**)
IMPORT SYSTEM, Dates, DevCPM, DevCPT;
CONST
(* item base modes (=object modes) *)
Var = 1; VarPar = 2; Con = 3; LProc = 6; XProc = 7; CProc = 9; IProc = 10; TProc = 13;
(* structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; String16 = 17; Int64 = 18; Guid = 23;
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(* object modes *)
Fld = 4; Typ = 5; Head = 12;
(* module visibility of objects *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* history of imported objects *)
inserted = 0; same = 1; pbmodified = 2; pvmodified = 3; removed = 4; inconsistent = 5;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval)*)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
(* meta interface consts *)
mConst = 1; mTyp = 2; mVar = 3; mProc = 4; mField = 5;
mBool = 1; mChar8 = 2; mChar16 = 3; mInt8 = 4; mInt16 = 5; mInt32 = 6;
mReal32 = 7; mReal64 = 8; mSet = 9; mInt64 = 10; mAnyRec = 11; mAnyPtr = 12; mSysPtr = 13;
mProctyp = 0; mRecord = 1; mArray = 2; mPointer = 3;
mInternal = 1; mReadonly = 2; mPrivate = 3; mExported = 4;
mValue = 10; mInPar = 11; mOutPar = 12; mVarPar = 13;
mInterface = 32; mGuid = 33; mResult = 34;
(* sysflag *)
untagged = 1; noAlign = 3; union = 7; interface = 10;
(* fixup types *)
absolute = 100; relative = 101; copy = 102; table = 103; tableend = 104; short = 105;
(* kernel flags *)
iptrs = 30;
expAllFields = TRUE;
(* implementation restrictions *)
CodeBlocks = 512;
CodeLength = 16384;
MaxNameTab = 800000H;
useAllRef = FALSE;
outSignatures = TRUE;
TYPE
CodeBlock = POINTER TO ARRAY CodeLength OF SHORTCHAR;
VAR
pc*: INTEGER;
dsize*: INTEGER; (* global data size *)
KNewRec*, KNewArr*: DevCPT.Object;
closeLbl*: INTEGER;
CaseLinks*: DevCPT.LinkList;
processor: INTEGER;
bigEndian: BOOLEAN;
procVarIndirect: BOOLEAN;
idx8, idx16, idx32, idx64, namex, nofptrs, headSize: INTEGER;
Const8, Const16, Const32, Const64, Code, Data, Meta, Mod, Proc, nameList, descList, untgd: DevCPT.Object;
outRef, outAllRef, outURef, outSrc, outObj: BOOLEAN;
codePos, srcPos: INTEGER;
options: SET;
code: ARRAY CodeBlocks OF CodeBlock;
actual: CodeBlock;
actIdx, blkIdx: INTEGER;
CodeOvF: BOOLEAN;
zero: ARRAY 16 OF SHORTCHAR; (* all 0X *)
imports: INTEGER;
dllList, dllLast: DevCPT.Object;
PROCEDURE GetLongWords* (con: DevCPT.Const; OUT hi, low: INTEGER);
CONST N = 4294967296.0; (* 2^32 *)
VAR rh, rl: REAL;
BEGIN
rl := con.intval; rh := con.realval / N;
IF rh >= MAX(INTEGER) + 1.0 THEN rh := rh - 1; rl := rl + N
ELSIF rh < MIN(INTEGER) THEN rh := rh + 1; rl := rl - N
END;
hi := SHORT(ENTIER(rh));
rl := rl + (rh - hi) * N;
IF rl < 0 THEN hi := hi - 1; rl := rl + N
ELSIF rl >= N THEN hi := hi + 1; rl := rl - N
END;
IF rl >= MAX(INTEGER) + 1.0 THEN rl := rl - N END;
low := SHORT(ENTIER(rl))
(*
hi := SHORT(ENTIER((con.realval + con.intval) / 4294967296.0));
r := con.realval + con.intval - hi * 4294967296.0;
IF r > MAX(INTEGER) THEN r := r - 4294967296.0 END;
low := SHORT(ENTIER(r))
*)
END GetLongWords;
PROCEDURE GetRealWord* (con: DevCPT.Const; OUT x: INTEGER);
VAR r: SHORTREAL;
BEGIN
r := SHORT(con.realval); x := SYSTEM.VAL(INTEGER, r)
END GetRealWord;
PROCEDURE GetRealWords* (con: DevCPT.Const; OUT hi, low: INTEGER);
TYPE A = ARRAY 2 OF INTEGER;
VAR a: A;
BEGIN
a := SYSTEM.VAL(A, con.realval);
IF DevCPM.LEHost THEN hi := a[1]; low := a[0] ELSE hi := a[0]; low := a[1] END
END GetRealWords;
PROCEDURE IsSame (x, y: REAL): BOOLEAN;
BEGIN
RETURN (x = y) & ((x # 0.) OR (1. / x = 1. / y))
END IsSame;
PROCEDURE AllocConst* (con: DevCPT.Const; form: BYTE; VAR obj: DevCPT.Object; VAR adr: INTEGER);
VAR c: DevCPT.Const;
BEGIN
INCL(con.setval, form);
CASE form OF
| String8:
obj := Const8; c := obj.conval;
WHILE (c # NIL) & ((con.setval # c.setval) OR (con.intval2 # c.intval2) OR (con.ext^ # c.ext^)) DO c := c.link END;
IF c = NIL THEN adr := idx8; INC(idx8, (con.intval2 + 3) DIV 4 * 4) END
| String16:
obj := Const16; c := obj.conval;
WHILE (c # NIL) & ((con.setval # c.setval) OR (con.intval2 # c.intval2) OR (con.ext^ # c.ext^)) DO c := c.link END;
IF c = NIL THEN adr := idx16; INC(idx16, (con.intval2 + 1) DIV 2 * 4) END
| Int64:
obj := Const64; c := obj.conval;
WHILE (c # NIL) & ((con.setval # c.setval) OR (con.intval # c.intval2) OR (con.realval # c.realval)) DO
c := c.link
END;
IF c = NIL THEN con.intval2 := con.intval; adr := idx64; INC(idx64, 8) END
| Real32:
obj := Const32; c := obj.conval;
WHILE (c # NIL) & ((con.setval # c.setval) OR ~IsSame(con.realval, c.realval)) DO c := c.link END;
IF c = NIL THEN adr := idx32; INC(idx32, 4) END
| Real64:
obj := Const64; c := obj.conval;
WHILE (c # NIL) & ((con.setval # c.setval) OR ~IsSame(con.realval, c.realval)) DO c := c.link END;
IF c = NIL THEN adr := idx64; INC(idx64, 8) END
| Guid:
obj := Const32; c := obj.conval;
WHILE (c # NIL) & ((con.setval # c.setval) OR (con.intval2 # c.intval2) OR (con.ext^ # c.ext^)) DO c := c.link END;
IF c = NIL THEN adr := idx32; INC(idx32, 16) END
END;
IF c = NIL THEN con.link := obj.conval; obj.conval := con ELSE adr := c.intval END;
con.intval := adr
END AllocConst;
PROCEDURE AllocTypDesc* (typ: DevCPT.Struct); (* typ.comp = Record *)
VAR obj: DevCPT.Object; name: DevCPT.Name;
BEGIN
IF typ.strobj = NIL THEN
name := "@"; DevCPT.Insert(name, obj); obj.name := DevCPT.null; (* avoid err 1 *)
obj.mode := Typ; obj.typ := typ; typ.strobj := obj
END
END AllocTypDesc;
PROCEDURE PutByte* (a, x: INTEGER);
BEGIN
code[a DIV CodeLength]^[a MOD CodeLength] := SHORT(CHR(x MOD 256))
END PutByte;
PROCEDURE PutShort* (a, x: INTEGER);
BEGIN
IF bigEndian THEN
PutByte(a, x DIV 256); PutByte(a + 1, x)
ELSE
PutByte(a, x); PutByte(a + 1, x DIV 256)
END
END PutShort;
PROCEDURE PutWord* (a, x: INTEGER);
BEGIN
IF bigEndian THEN
PutByte(a, x DIV 1000000H); PutByte(a + 1, x DIV 10000H);
PutByte(a + 2, x DIV 256); PutByte(a + 3, x)
ELSE
PutByte(a, x); PutByte(a + 1, x DIV 256);
PutByte(a + 2, x DIV 10000H); PutByte(a + 3, x DIV 1000000H)
END
END PutWord;
PROCEDURE ThisByte* (a: INTEGER): INTEGER;
BEGIN
RETURN ORD(code[a DIV CodeLength]^[a MOD CodeLength])
END ThisByte;
PROCEDURE ThisShort* (a: INTEGER): INTEGER;
BEGIN
IF bigEndian THEN
RETURN ThisByte(a) * 256 + ThisByte(a+1)
ELSE
RETURN ThisByte(a+1) * 256 + ThisByte(a)
END
END ThisShort;
PROCEDURE ThisWord* (a: INTEGER): INTEGER;
BEGIN
IF bigEndian THEN
RETURN ((ThisByte(a) * 256 + ThisByte(a+1)) * 256 + ThisByte(a+2)) * 256 + ThisByte(a+3)
ELSE
RETURN ((ThisByte(a+3) * 256 + ThisByte(a+2)) * 256 + ThisByte(a+1)) * 256 + ThisByte(a)
END
END ThisWord;
PROCEDURE GenByte* (x: INTEGER);
BEGIN
IF actIdx >= CodeLength THEN
IF blkIdx < CodeBlocks THEN
NEW(actual); code[blkIdx] := actual; INC(blkIdx); actIdx := 0
ELSE
IF ~CodeOvF THEN DevCPM.err(210); CodeOvF := TRUE END;
actIdx := 0; pc := 0
END
END;
actual[actIdx] := SHORT(CHR(x MOD 256)); INC(actIdx); INC(pc)
END GenByte;
PROCEDURE GenShort* (x: INTEGER);
BEGIN
IF bigEndian THEN
GenByte(x DIV 256); GenByte(x)
ELSE
GenByte(x); GenByte(x DIV 256)
END
END GenShort;
PROCEDURE GenWord* (x: INTEGER);
BEGIN
IF bigEndian THEN
GenByte(x DIV 1000000H); GenByte(x DIV 10000H); GenByte(x DIV 256); GenByte(x)
ELSE
GenByte(x); GenByte(x DIV 256); GenByte(x DIV 10000H); GenByte(x DIV 1000000H)
END
END GenWord;
PROCEDURE WriteCode;
VAR i, j, k, n: INTEGER; b: CodeBlock;
BEGIN
j := 0; k := 0;
WHILE j < pc DO
n := pc - j; i := 0; b := code[k];
IF n > CodeLength THEN n := CodeLength END;
WHILE i < n DO DevCPM.ObjW(b^[i]); INC(i) END;
INC(j, n); INC(k)
END
END WriteCode;
PROCEDURE OffsetLink* (obj: DevCPT.Object; offs: INTEGER): DevCPT.LinkList;
VAR link: DevCPT.LinkList; m: DevCPT.Object;
BEGIN
ASSERT((obj.mode # Typ) OR (obj.typ # DevCPT.int32typ));
ASSERT((obj.mode # Typ) OR (obj.typ # DevCPT.iunktyp) & (obj.typ # DevCPT.guidtyp));
IF obj.mnolev >= 0 THEN (* not imported *)
CASE obj.mode OF
| Typ: IF obj.links = NIL THEN obj.link := descList; descList := obj END
| TProc: IF obj.adr = -1 THEN obj := obj.nlink ELSE offs := offs + obj.adr; obj := Code END
| Var: offs := offs + dsize; obj := Data
| Con, IProc, XProc, LProc:
END
ELSIF obj.mode = Typ THEN
IF obj.typ.untagged THEN (* add desc for imported untagged types *)
IF obj.links = NIL THEN obj.link := descList; descList := obj END
ELSE
m := DevCPT.GlbMod[-obj.mnolev];
IF m.library # NIL THEN RETURN NIL END (* type import from dll *)
END
END;
link := obj.links;
WHILE (link # NIL) & (link.offset # offs) DO link := link.next END;
IF link = NIL THEN
NEW(link); link.offset := offs; link.linkadr := 0;
link.next := obj.links; obj.links := link
END;
RETURN link
END OffsetLink;
PROCEDURE TypeObj* (typ: DevCPT.Struct): DevCPT.Object;
VAR obj: DevCPT.Object;
BEGIN
obj := typ.strobj;
IF obj = NIL THEN
obj := DevCPT.NewObj(); obj.leaf := TRUE; obj.mnolev := 0;
obj.name := DevCPT.null; obj.mode := Typ; obj.typ := typ; typ.strobj := obj
END;
RETURN obj
END TypeObj;
PROCEDURE Align (n: INTEGER);
VAR p: INTEGER;
BEGIN
p := DevCPM.ObjLen();
DevCPM.ObjWBytes(zero, (-p) MOD n)
END Align;
PROCEDURE OutName (IN name: ARRAY OF SHORTCHAR);
VAR ch: SHORTCHAR; i: SHORTINT;
BEGIN i := 0;
REPEAT ch := name[i]; DevCPM.ObjW(ch); INC(i) UNTIL ch = 0X
END OutName;
PROCEDURE Out2 (x: INTEGER); (* byte ordering must correspond to target machine *)
BEGIN
IF bigEndian THEN
DevCPM.ObjW(SHORT(CHR(x DIV 256))); DevCPM.ObjW(SHORT(CHR(x)))
ELSE
DevCPM.ObjW(SHORT(CHR(x))); DevCPM.ObjW(SHORT(CHR(x DIV 256)))
END
END Out2;
PROCEDURE Out4 (x: INTEGER); (* byte ordering must correspond to target machine *)
BEGIN
IF bigEndian THEN
DevCPM.ObjW(SHORT(CHR(x DIV 1000000H))); DevCPM.ObjW(SHORT(CHR(x DIV 10000H)));
DevCPM.ObjW(SHORT(CHR(x DIV 256))); DevCPM.ObjW(SHORT(CHR(x)))
ELSE
DevCPM.ObjWLInt(x)
END
END Out4;
PROCEDURE OutReference (obj: DevCPT.Object; offs, typ: INTEGER);
VAR link: DevCPT.LinkList;
BEGIN
link := OffsetLink(obj, offs);
IF link # NIL THEN
Out4(typ * 1000000H + link.linkadr MOD 1000000H);
link.linkadr := -(DevCPM.ObjLen() - headSize - 4)
ELSE Out4(0)
END
END OutReference;
PROCEDURE FindPtrs (typ: DevCPT.Struct; adr: INTEGER; ip: BOOLEAN; VAR num: INTEGER);
VAR fld: DevCPT.Object; btyp: DevCPT.Struct; i, n: INTEGER;
BEGIN
IF typ.form = Pointer THEN
IF ip & (typ.sysflag = interface)
OR ~ip & ~typ.untagged THEN Out4(adr); INC(num) END
ELSIF (typ.comp = Record) & (typ.sysflag # union) THEN
btyp := typ.BaseTyp;
IF btyp # NIL THEN FindPtrs(btyp, adr, ip, num) END ;
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF ip & (fld.name^ = DevCPM.HdUtPtrName) & (fld.sysflag = interface)
OR ~ip & (fld.name^ = DevCPM.HdPtrName) THEN Out4(fld.adr + adr); INC(num)
ELSE FindPtrs(fld.typ, fld.adr + adr, ip, num)
END;
fld := fld.link
END
ELSIF typ.comp = Array THEN
btyp := typ.BaseTyp; n := typ.n;
WHILE btyp.comp = Array DO n := btyp.n * n; btyp := btyp.BaseTyp END ;
IF (btyp.form = Pointer) OR (btyp.comp = Record) THEN
i := num; FindPtrs(btyp, adr, ip, num);
IF num # i THEN i := 1;
WHILE i < n DO
INC(adr, btyp.size); FindPtrs(btyp, adr, ip, num); INC(i)
END
END
END
END
END FindPtrs;
PROCEDURE OutRefName* (IN name: ARRAY OF SHORTCHAR);
BEGIN
DevCPM.ObjW(0FCX); DevCPM.ObjWNum(pc); OutName(name)
END OutRefName;
PROCEDURE OutRefs* (obj: DevCPT.Object);
VAR f: BYTE;
BEGIN
IF outRef & (obj # NIL) THEN
OutRefs(obj.left);
IF ((obj.mode = Var) OR (obj.mode = VarPar)) & (obj.history # removed) & (obj.name[0] # "@") THEN
f := obj.typ.form;
IF (f IN {Byte .. Set, Pointer, ProcTyp, Char16, Int64})
OR outURef & (obj.typ.comp # DynArr)
OR outAllRef & ~obj.typ.untagged
OR (obj.typ.comp = Array) & (obj.typ.BaseTyp.form = Char8) THEN
IF obj.mode = Var THEN DevCPM.ObjW(0FDX) ELSE DevCPM.ObjW(0FFX) END;
IF obj.typ = DevCPT.anyptrtyp THEN DevCPM.ObjW(SHORT(CHR(mAnyPtr)))
ELSIF obj.typ = DevCPT.anytyp THEN DevCPM.ObjW(SHORT(CHR(mAnyRec)))
ELSIF obj.typ = DevCPT.sysptrtyp THEN DevCPM.ObjW(SHORT(CHR(mSysPtr)))
ELSIF f = Char16 THEN DevCPM.ObjW(SHORT(CHR(mChar16)))
ELSIF f = Int64 THEN DevCPM.ObjW(SHORT(CHR(mInt64)))
ELSIF obj.typ = DevCPT.guidtyp THEN DevCPM.ObjW(SHORT(CHR(mGuid)))
ELSIF obj.typ = DevCPT.restyp THEN DevCPM.ObjW(SHORT(CHR(mResult)))
ELSIF f = Pointer THEN
IF obj.typ.sysflag = interface THEN DevCPM.ObjW(SHORT(CHR(mInterface)))
ELSIF obj.typ.untagged THEN DevCPM.ObjW(SHORT(CHR(mSysPtr)))
ELSE DevCPM.ObjW(10X); OutReference(TypeObj(obj.typ), 0, absolute)
END
ELSIF (f = Comp) & outAllRef & (~obj.typ.untagged OR outURef & (obj.typ.comp # DynArr)) THEN
DevCPM.ObjW(10X); OutReference(TypeObj(obj.typ), 0, absolute)
ELSIF f < Int8 THEN DevCPM.ObjW(SHORT(CHR(f - 1)))
ELSE DevCPM.ObjW(SHORT(CHR(f)))
END;
IF obj.mnolev = 0 THEN DevCPM.ObjWNum(obj.adr + dsize) ELSE DevCPM.ObjWNum(obj.adr) END;
OutName(obj.name)
END
END ;
OutRefs(obj.right)
END
END OutRefs;
PROCEDURE OutSourceRef* (pos: INTEGER);
BEGIN
IF outSrc & (pos # 0) & (pos # srcPos) & (pc > codePos) THEN
WHILE pc > codePos + 250 DO
DevCPM.ObjW(SHORT(CHR(250)));
INC(codePos, 250);
DevCPM.ObjWNum(0)
END;
DevCPM.ObjW(SHORT(CHR(pc - codePos)));
codePos := pc;
DevCPM.ObjWNum(pos - srcPos);
srcPos := pos
END
END OutSourceRef;
PROCEDURE OutPLink (link: DevCPT.LinkList; adr: INTEGER);
BEGIN
WHILE link # NIL DO
ASSERT(link.linkadr # 0);
DevCPM.ObjWNum(link.linkadr);
DevCPM.ObjWNum(adr + link.offset);
link := link.next
END
END OutPLink;
PROCEDURE OutLink (link: DevCPT.LinkList);
BEGIN
OutPLink(link, 0); DevCPM.ObjW(0X)
END OutLink;
PROCEDURE OutNames;
VAR a, b, c: DevCPT.Object;
BEGIN
a := nameList; b := NIL;
WHILE a # NIL DO c := a; a := c.nlink; c.nlink := b; b := c END;
DevCPM.ObjW(0X); (* names[0] = 0X *)
WHILE b # NIL DO
OutName(b.name);
b := b.nlink
END;
END OutNames;
PROCEDURE OutGuid* (VAR str: ARRAY OF SHORTCHAR);
PROCEDURE Copy (n: INTEGER);
VAR x, y: INTEGER;
BEGIN
x := ORD(str[n]); y := ORD(str[n + 1]);
IF x >= ORD("a") THEN DEC(x, ORD("a") - 10)
ELSIF x >= ORD("A") THEN DEC(x, ORD("A") - 10)
ELSE DEC(x, ORD("0"))
END;
IF y >= ORD("a") THEN DEC(y, ORD("a") - 10)
ELSIF y >= ORD("A") THEN DEC(y, ORD("A") - 10)
ELSE DEC(y, ORD("0"))
END;
DevCPM.ObjW(SHORT(CHR(x * 16 + y)))
END Copy;
BEGIN
IF bigEndian THEN
Copy(1); Copy(3); Copy(5); Copy(7); Copy(10); Copy(12); Copy(15); Copy(17)
ELSE
Copy(7); Copy(5); Copy(3); Copy(1); Copy(12); Copy(10); Copy(17); Copy(15)
END;
Copy(20); Copy(22); Copy(25); Copy(27); Copy(29); Copy(31); Copy(33); Copy(35)
END OutGuid;
PROCEDURE OutConst (obj: DevCPT.Object);
TYPE A4 = ARRAY 4 OF SHORTCHAR; A8 = ARRAY 8 OF SHORTCHAR;
VAR a, b, c: DevCPT.Const; r: SHORTREAL; lr: REAL; a4: A4; a8: A8; ch: SHORTCHAR; i, x, hi, low: INTEGER;
BEGIN
a := obj.conval; b := NIL;
WHILE a # NIL DO c := a; a := c.link; c.link := b; b := c END;
WHILE b # NIL DO
IF String8 IN b.setval THEN
DevCPM.ObjWBytes(b.ext^, b.intval2);
Align(4)
ELSIF String16 IN b.setval THEN
i := 0; REPEAT DevCPM.GetUtf8(b.ext^, x, i); Out2(x) UNTIL x = 0;
Align(4)
ELSIF Real32 IN b.setval THEN
r := SHORT(b.realval); a4 := SYSTEM.VAL(A4, r);
IF DevCPM.LEHost = bigEndian THEN
ch := a4[0]; a4[0] := a4[3]; a4[3] := ch;
ch := a4[1]; a4[1] := a4[2]; a4[2] := ch
END;
DevCPM.ObjWBytes(a4, 4)
ELSIF Real64 IN b.setval THEN
a8 := SYSTEM.VAL(A8, b.realval);
IF DevCPM.LEHost = bigEndian THEN
ch := a8[0]; a8[0] := a8[7]; a8[7] := ch;
ch := a8[1]; a8[1] := a8[6]; a8[6] := ch;
ch := a8[2]; a8[2] := a8[5]; a8[5] := ch;
ch := a8[3]; a8[3] := a8[4]; a8[4] := ch
END;
DevCPM.ObjWBytes(a8, 8)
ELSIF Int64 IN b.setval THEN
(* intval moved to intval2 by AllocConst *)
x := b.intval; b.intval := b.intval2; GetLongWords(b, hi, low); b.intval := x;
IF bigEndian THEN Out4(hi); Out4(low) ELSE Out4(low); Out4(hi) END
ELSIF Guid IN b.setval THEN
OutGuid(b.ext)
END;
b := b.link
END
END OutConst;
PROCEDURE OutStruct (typ: DevCPT.Struct; unt: BOOLEAN);
BEGIN
IF typ = NIL THEN Out4(0)
ELSIF typ = DevCPT.sysptrtyp THEN Out4(mSysPtr)
ELSIF typ = DevCPT.anytyp THEN Out4(mAnyRec)
ELSIF typ = DevCPT.anyptrtyp THEN Out4(mAnyPtr)
ELSIF typ = DevCPT.guidtyp THEN Out4(mGuid)
ELSIF typ = DevCPT.restyp THEN Out4(mResult)
ELSE
CASE typ.form OF
| Undef, Byte, String8, NilTyp, NoTyp, String16: Out4(0)
| Bool, Char8: Out4(typ.form - 1)
| Int8..Set: Out4(typ.form)
| Char16: Out4(mChar16)
| Int64: Out4(mInt64)
| ProcTyp: OutReference(TypeObj(typ), 0, absolute)
| Pointer:
IF typ.sysflag = interface THEN Out4(mInterface)
ELSIF typ.untagged THEN Out4(mSysPtr)
ELSE OutReference(TypeObj(typ), 0, absolute)
END
| Comp:
IF ~typ.untagged OR (outURef & unt) THEN OutReference(TypeObj(typ), 0, absolute)
ELSE Out4(0)
END
END
END
END OutStruct;
PROCEDURE NameIdx (obj: DevCPT.Object): INTEGER;
VAR n: INTEGER;
BEGIN
n := 0;
IF obj.name # DevCPT.null THEN
IF obj.num = 0 THEN
obj.num := namex;
WHILE obj.name[n] # 0X DO INC(n) END;
INC(namex, n + 1);
obj.nlink := nameList; nameList := obj
END;
n := obj.num;
END;
RETURN n
END NameIdx;
PROCEDURE OutSignature (par: DevCPT.Object; retTyp: DevCPT.Struct; OUT pos: INTEGER);
VAR p: DevCPT.Object; n, m: INTEGER;
BEGIN
pos := DevCPM.ObjLen() - headSize;
OutStruct(retTyp, TRUE);
p := par; n := 0;
WHILE p # NIL DO INC(n); p := p.link END;
Out4(n); p := par;
WHILE p # NIL DO
IF p.mode # VarPar THEN m := mValue
ELSIF p.vis = inPar THEN m := mInPar
ELSIF p.vis = outPar THEN m := mOutPar
ELSE m := mVarPar
END;
Out4(NameIdx(p) * 256 + m);
OutStruct(p.typ, TRUE);
p := p.link
END
END OutSignature;
PROCEDURE PrepObject (obj: DevCPT.Object);
BEGIN
IF (obj.mode IN {LProc, XProc, IProc}) & outSignatures THEN (* write param list *)
OutSignature(obj.link, obj.typ, obj.conval.intval)
END
END PrepObject;
PROCEDURE OutObject (mode, fprint, offs: INTEGER; typ: DevCPT.Struct; obj: DevCPT.Object);
VAR vis: INTEGER;
BEGIN
Out4(fprint);
Out4(offs);
IF obj.vis = internal THEN vis := mInternal
ELSIF obj.vis = externalR THEN vis := mReadonly
ELSIF obj.vis = external THEN vis := mExported
END;
Out4(mode + vis * 16 + NameIdx(obj) * 256);
IF (mode = mProc) & outSignatures THEN OutReference(Meta, obj.conval.intval, absolute) (* ref to par list *)
ELSE OutStruct(typ, mode = mField)
END
END OutObject;
PROCEDURE PrepDesc (desc: DevCPT.Struct);
VAR fld: DevCPT.Object; n: INTEGER; l: DevCPT.LinkList; b: DevCPT.Struct;
BEGIN
IF desc.comp = Record THEN (* write field list *)
desc.strobj.adr := DevCPM.ObjLen() - headSize;
n := 0; fld := desc.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF expAllFields OR (fld.vis # internal) THEN INC(n) END;
fld := fld.link
END;
Out4(n); fld := desc.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF expAllFields OR (fld.vis # internal) THEN
OutObject(mField, 0, fld.adr, fld.typ, fld)
END;
fld := fld.link
END
ELSIF (desc.form = ProcTyp) & outSignatures THEN (* write param list *)
OutSignature(desc.link, desc.BaseTyp, desc.n)
END;
(* assert name and base type are included *)
IF desc.untagged THEN n := NameIdx(untgd)
ELSE n := NameIdx(desc.strobj)
END;
IF desc.form # ProcTyp THEN b := desc.BaseTyp;
IF (b # NIL) & (b # DevCPT.anytyp) & (b # DevCPT.anyptrtyp) & (b.form IN {Pointer, Comp, ProcTyp})
& (b.sysflag # interface) & (b # DevCPT.guidtyp)
& (~b.untagged OR outURef & (b.form = Comp)) THEN
l := OffsetLink(TypeObj(b), 0)
END
END
END PrepDesc;
PROCEDURE NumMeth (root: DevCPT.Object; num: INTEGER): DevCPT.Object;
VAR obj: DevCPT.Object;
BEGIN
IF (root = NIL) OR (root.mode = TProc) & (root.num = num) THEN RETURN root END;
obj := NumMeth(root.left, num);
IF obj = NIL THEN obj := NumMeth(root.right, num) END;
RETURN obj
END NumMeth;
PROCEDURE OutDesc (desc: DevCPT.Struct);
VAR m: DevCPT.Object; i, nofptr, flddir, size: INTEGER; t, xb: DevCPT.Struct; form, lev, attr: BYTE;
BEGIN
ASSERT(~desc.untagged);
IF desc.comp = Record THEN
xb := desc; flddir := desc.strobj.adr;
REPEAT xb := xb.BaseTyp UNTIL (xb = NIL) OR (xb.mno # 0) OR xb.untagged;
Out4(-1); i := desc.n;
WHILE i > 0 DO DEC(i); t := desc;
REPEAT
m := NumMeth(t.link, i); t := t.BaseTyp
UNTIL (m # NIL) OR (t = xb);
IF m # NIL THEN
IF absAttr IN m.conval.setval THEN Out4(0)
ELSE OutReference(m, 0, absolute)
END
ELSIF (xb = NIL) OR xb.untagged THEN Out4(0) (* unimplemented ANYREC method *)
ELSE OutReference(xb.strobj, -4 - 4 * i, copy)
END
END;
desc.strobj.adr := DevCPM.ObjLen() - headSize; (* desc adr *)
Out4(desc.size);
OutReference(Mod, 0, absolute);
IF desc.untagged THEN m := untgd ELSE m := desc.strobj END;
IF desc.attribute = extAttr THEN attr := 1
ELSIF desc.attribute = limAttr THEN attr := 2
ELSIF desc.attribute = absAttr THEN attr := 3
ELSE attr := 0
END;
Out4(mRecord + attr * 4 + desc.extlev * 16 + NameIdx(m) * 256); i := 0;
WHILE i <= desc.extlev DO
t := desc;
WHILE t.extlev > i DO t := t.BaseTyp END;
IF t.sysflag = interface THEN Out4(0)
ELSIF t.untagged THEN OutReference(TypeObj(t), 0, absolute)
ELSIF (t.mno = 0) THEN OutReference(t.strobj, 0, absolute)
ELSIF t = xb THEN OutReference(xb.strobj, 0, absolute)
ELSE OutReference(xb.strobj, 12 + 4 * i, copy)
END;
INC(i)
END;
WHILE i <= DevCPM.MaxExts DO Out4(0); INC(i) END;
OutReference(Meta, flddir, absolute); (* ref to field list *)
nofptr := 0; FindPtrs(desc, 0, FALSE, nofptr);
Out4(-(4 * nofptr + 4));
nofptr := 0; FindPtrs(desc, 0, TRUE, nofptr);
Out4(-1)
ELSE
desc.strobj.adr := DevCPM.ObjLen() - headSize;
lev := 0; size := 0;
IF desc.comp = Array THEN
size := desc.n; form := mArray
ELSIF desc.comp = DynArr THEN
form := mArray; lev := SHORT(SHORT(desc.n + 1))
ELSIF desc.form = Pointer THEN
form := mPointer
ELSE ASSERT(desc.form = ProcTyp);
DevCPM.FPrint(size, XProc); DevCPT.FPrintSign(size, desc.BaseTyp, desc.link); form := mProctyp;
END;
Out4(size);
OutReference(Mod, 0, absolute);
IF desc.untagged THEN m := untgd ELSE m := desc.strobj END;
Out4(form + lev * 16 + NameIdx(m) * 256);
IF desc.form # ProcTyp THEN OutStruct(desc.BaseTyp, TRUE)
ELSIF outSignatures THEN OutReference(Meta, desc.n, absolute) (* ref to par list *)
END
END
END OutDesc;
PROCEDURE OutModDesc (nofptr, refSize, namePos, ptrPos, expPos, impPos: INTEGER);
VAR i: INTEGER; t: Dates.Time; d: Dates.Date;
BEGIN
Out4(0); (* link *)
Out4(ORD(options)); (* opts *)
Out4(0); (* refcnt *)
Dates.GetDate(d); Dates.GetTime(t); (* compile time *)
Out2(d.year); Out2(d.month); Out2(d.day);
Out2(t.hour); Out2(t.minute); Out2(t.second);
Out4(0); Out4(0); Out4(0); (* load time *)
Out4(0); (* ext *)
IF closeLbl # 0 THEN OutReference(Code, closeLbl, absolute); (* terminator *)
ELSE Out4(0)
END;
Out4(imports); (* nofimps *)
Out4(nofptr); (* nofptrs *)
Out4(pc); (* csize *)
Out4(dsize); (* dsize *)
Out4(refSize); (* rsize *)
OutReference(Code, 0, absolute); (* code *)
OutReference(Data, 0, absolute); (* data *)
OutReference(Meta, 0, absolute); (* refs *)
IF procVarIndirect THEN
OutReference(Proc, 0, absolute); (* procBase *)
ELSE
OutReference(Code, 0, absolute); (* procBase *)
END;
OutReference(Data, 0, absolute); (* varBase *)
OutReference(Meta, namePos, absolute); (* names *)
OutReference(Meta, ptrPos, absolute); (* ptrs *)
OutReference(Meta, impPos, absolute); (* imports *)
OutReference(Meta, expPos, absolute); (* export *)
i := 0; (* name *)
WHILE DevCPT.SelfName[i] # 0X DO DevCPM.ObjW(DevCPT.SelfName[i]); INC(i) END;
DevCPM.ObjW(0X);
Align(4)
END OutModDesc;
PROCEDURE OutProcTable (obj: DevCPT.Object); (* 68000 *)
BEGIN
IF obj # NIL THEN
OutProcTable(obj.left);
IF obj.mode IN {XProc, IProc} THEN
Out2(4EF9H); OutReference(Code, obj.adr, absolute); Out2(0);
END;
OutProcTable(obj.right);
END;
END OutProcTable;
PROCEDURE PrepExport (obj: DevCPT.Object);
BEGIN
IF obj # NIL THEN
PrepExport(obj.left);
IF (obj.mode IN {LProc, XProc, IProc}) & (obj.history # removed) & (obj.vis # internal) THEN
PrepObject(obj)
END;
PrepExport(obj.right)
END
END PrepExport;
PROCEDURE OutExport (obj: DevCPT.Object);
VAR num: INTEGER;
BEGIN
IF obj # NIL THEN
OutExport(obj.left);
IF (obj.history # removed) & ((obj.vis # internal) OR
(obj.mode = Typ) & (obj.typ.strobj = obj) & (obj.typ.form = Comp)) THEN
DevCPT.FPrintObj(obj);
IF obj.mode IN {LProc, XProc, IProc} THEN
IF procVarIndirect THEN
ASSERT(obj.nlink = NIL);
num := obj.num; obj.num := 0;
OutObject(mProc, obj.fprint, num, NIL, obj);
obj.num := num
ELSE
OutObject(mProc, obj.fprint, obj.adr, NIL, obj)
END
ELSIF obj.mode = Var THEN
OutObject(mVar, obj.fprint, dsize + obj.adr, obj.typ, obj)
ELSIF obj.mode = Typ THEN
OutObject(mTyp, obj.typ.pbfp, obj.typ.pvfp, obj.typ, obj)
ELSE ASSERT(obj.mode IN {Con, CProc});
OutObject(mConst, obj.fprint, 0, NIL, obj)
END
END;
OutExport(obj.right)
END
END OutExport;
PROCEDURE OutCLinks (obj: DevCPT.Object);
BEGIN
IF obj # NIL THEN
OutCLinks(obj.left);
IF obj.mode IN {LProc, XProc, IProc} THEN OutPLink(obj.links, obj.adr) END;
OutCLinks(obj.right)
END
END OutCLinks;
PROCEDURE OutCPLinks (obj: DevCPT.Object; base: INTEGER);
BEGIN
IF obj # NIL THEN
OutCPLinks(obj.left, base);
IF obj.mode IN {LProc, XProc, IProc} THEN OutPLink(obj.links, obj.num + base) END;
OutCPLinks(obj.right, base)
END
END OutCPLinks;
PROCEDURE OutImport (obj: DevCPT.Object);
VAR typ: DevCPT.Struct; strobj: DevCPT.Object; opt: INTEGER;
BEGIN
IF obj # NIL THEN
OutImport(obj.left);
IF obj.mode = Typ THEN typ := obj.typ;
IF obj.used OR
(typ.form IN {Pointer, Comp}) & (typ.strobj = obj) &
((obj.links # NIL) OR (obj.name # DevCPT.null) & (typ.pvused OR typ.pbused)) THEN
DevCPT.FPrintStr(typ);
DevCPM.ObjW(SHORT(CHR(mTyp))); OutName(obj.name^);
IF obj.used THEN opt := 2 ELSE opt := 0 END;
IF (typ.form = Comp) & ((typ.pvused) OR (obj.name = DevCPT.null)) THEN
DevCPM.ObjWNum(typ.pvfp); DevCPM.ObjW(SHORT(CHR(opt + 1)));
IF obj.history = inconsistent THEN DevCPT.FPrintErr(obj, 249) END
ELSE DevCPM.ObjWNum(typ.pbfp); DevCPM.ObjW(SHORT(CHR(opt)))
END;
OutLink(obj.links)
END
ELSIF obj.used THEN
DevCPT.FPrintObj(obj);
IF obj.mode = Var THEN
DevCPM.ObjW(SHORT(CHR(mVar))); OutName(obj.name^);
DevCPM.ObjWNum(obj.fprint); OutLink(obj.links)
ELSIF obj.mode IN {XProc, IProc} THEN
DevCPM.ObjW(SHORT(CHR(mProc))); OutName(obj.name^);
DevCPM.ObjWNum(obj.fprint); OutLink(obj.links)
ELSE ASSERT(obj.mode IN {Con, CProc});
DevCPM.ObjW(SHORT(CHR(mConst))); OutName(obj.name^); DevCPM.ObjWNum(obj.fprint)
END
END;
OutImport(obj.right)
END
END OutImport;
PROCEDURE OutUseBlock;
VAR m, obj: DevCPT.Object; i: INTEGER;
BEGIN
m := dllList;
WHILE m # NIL DO
obj := m.nlink;
WHILE obj # NIL DO
IF obj.mode = Var THEN DevCPM.ObjW(SHORT(CHR(mVar)))
ELSE DevCPM.ObjW(SHORT(CHR(mProc)))
END;
IF obj.entry # NIL THEN OutName(obj.entry)
ELSE OutName(obj.name);
END;
DevCPT.FPrintObj(obj); DevCPM.ObjWNum(obj.fprint); OutLink(obj.links);
obj := obj.nlink
END;
DevCPM.ObjW(0X); m := m.link
END;
i := 1;
WHILE i < DevCPT.nofGmod DO
obj := DevCPT.GlbMod[i];
IF obj.library = NIL THEN OutImport(obj.right); DevCPM.ObjW(0X) END;
INC(i)
END;
END OutUseBlock;
PROCEDURE CollectDll (obj: DevCPT.Object; mod: DevCPT.String);
VAR name: DevCPT.String; dll: DevCPT.Object;
BEGIN
IF obj # NIL THEN
CollectDll(obj.left, mod);
IF obj.used & (obj.mode IN {Var, XProc, IProc}) THEN
IF obj.library # NIL THEN name := obj.library
ELSE name := mod
END;
dll := dllList;
WHILE (dll # NIL) & (dll.library^ # name^) DO dll := dll.link END;
IF dll = NIL THEN
NEW(dll); dll.library := name; INC(imports);
IF dllList = NIL THEN dllList := dll ELSE dllLast.link := dll END;
dllLast := dll; dll.left := dll;
END;
dll.left.nlink := obj; dll.left := obj
END;
CollectDll(obj.right, mod)
END
END CollectDll;
PROCEDURE EnumXProc(obj: DevCPT.Object; VAR num: INTEGER);
BEGIN
IF obj # NIL THEN
EnumXProc(obj.left, num);
IF obj.mode IN {XProc, IProc} THEN
obj.num := num; INC(num, 8);
END;
EnumXProc(obj.right, num)
END;
END EnumXProc;
PROCEDURE OutHeader*;
VAR i: INTEGER; m: DevCPT.Object;
BEGIN
DevCPM.ObjWLInt(processor); (* processor type *)
DevCPM.ObjWLInt(0); DevCPM.ObjWLInt(0); DevCPM.ObjWLInt(0);
DevCPM.ObjWLInt(0); DevCPM.ObjWLInt(0); (* sizes *)
imports := 0; i := 1;
WHILE i < DevCPT.nofGmod DO
m := DevCPT.GlbMod[i];
IF m.library # NIL THEN (* dll import *)
CollectDll(m.right, m.library);
ELSE INC(imports) (* module import *)
END;
INC(i)
END;
DevCPM.ObjWNum(imports); (* num of import *)
OutName(DevCPT.SelfName);
m := dllList;
WHILE m # NIL DO DevCPM.ObjW("$"); OutName(m.library^); m := m.link END;
i := 1;
WHILE i < DevCPT.nofGmod DO
m := DevCPT.GlbMod[i];
IF m.library = NIL THEN OutName(m.name) END;
INC(i)
END;
Align(16); headSize := DevCPM.ObjLen();
IF procVarIndirect THEN
i := 0; EnumXProc(DevCPT.topScope.right, i)
END
END OutHeader;
PROCEDURE OutCode*;
VAR i, refSize, expPos, ptrPos, impPos, namePos, procPos,
con8Pos, con16Pos, con32Pos, con64Pos, modPos, codePos: INTEGER;
obj, dlist: DevCPT.Object;
BEGIN
(* Ref *)
DevCPM.ObjW(0X); (* end mark *)
refSize := DevCPM.ObjLen() - headSize;
(* Export *)
Align(4);
IF outSignatures THEN PrepExport(DevCPT.topScope.right) END; (* procedure signatures *)
Align(8); expPos := DevCPM.ObjLen();
Out4(0);
OutExport(DevCPT.topScope.right); (* export objects *)
i := DevCPM.ObjLen(); DevCPM.ObjSet(expPos); Out4((i - expPos - 4) DIV 16); DevCPM.ObjSet(i);
(* Pointers *)
ptrPos := DevCPM.ObjLen();
obj := DevCPT.topScope.scope; nofptrs := 0;
WHILE obj # NIL DO FindPtrs(obj.typ, dsize + obj.adr, FALSE, nofptrs); obj := obj.link END;
obj := DevCPT.topScope.scope; i := 0;
WHILE obj # NIL DO FindPtrs(obj.typ, dsize + obj.adr, TRUE, i); obj := obj.link END;
IF i > 0 THEN Out4(-1); INCL(options, iptrs) END;
(* Prepare Type Descriptors *)
dlist := NIL;
WHILE descList # NIL DO
obj := descList; descList := descList.link;
PrepDesc(obj.typ);
obj.link := dlist; dlist := obj
END;
(* Import List *)
impPos := DevCPM.ObjLen(); i := 0;
WHILE i < imports DO Out4(0); INC(i) END;
(* Names *)
namePos := DevCPM.ObjLen(); OutNames;
(* Const *)
Align(4); con8Pos := DevCPM.ObjLen();
OutConst(Const8); con16Pos := DevCPM.ObjLen();
ASSERT(con16Pos MOD 4 = 0); ASSERT(con16Pos - con8Pos = idx8);
OutConst(Const16); con32Pos := DevCPM.ObjLen();
ASSERT(con32Pos MOD 4 = 0); ASSERT(con32Pos - con16Pos = idx16);
OutConst(Const32); con64Pos := DevCPM.ObjLen();
ASSERT(con64Pos MOD 4 = 0); ASSERT(con64Pos - con32Pos = idx32);
IF ODD(con64Pos DIV 4) THEN Out4(0); INC(con64Pos, 4) END;
OutConst(Const64); ASSERT(DevCPM.ObjLen() - con64Pos = idx64);
(* Module Descriptor *)
Align(16); modPos := DevCPM.ObjLen();
OutModDesc(nofptrs, refSize, namePos - headSize, ptrPos - headSize, expPos - headSize, impPos - headSize);
(* Procedure Table *)
procPos := DevCPM.ObjLen();
OutProcTable(DevCPT.topScope.right);
Out4(0); Out4(0); (* at least one entry in ProcTable *)
Out4(0); (* sentinel *)
(* Type Descriptors *)
obj := dlist;
WHILE obj # NIL DO OutDesc(obj.typ); obj := obj.link END;
(* Code *)
codePos := DevCPM.ObjLen(); WriteCode;
WHILE pc MOD 4 # 0 DO DevCPM.ObjW(90X); INC(pc) END;
(* Fixups *)
OutLink(KNewRec.links); OutLink(KNewArr.links);
(* metalink *)
OutPLink(Const8.links, con8Pos - headSize);
OutPLink(Const16.links, con16Pos - headSize);
OutPLink(Const32.links, con32Pos - headSize);
OutPLink(Const64.links, con64Pos - headSize);
OutLink(Meta.links);
(* desclink *)
obj := dlist; i := modPos - headSize;
WHILE obj # NIL DO OutPLink(obj.links, obj.adr - i); obj.links := NIL; obj := obj.link END;
IF procVarIndirect THEN
OutPLink(Proc.links, procPos - modPos);
OutCPLinks(DevCPT.topScope.right, procPos - modPos)
END;
OutLink(Mod.links);
(* codelink *)
IF ~procVarIndirect THEN OutCLinks(DevCPT.topScope.right) END;
OutPLink(CaseLinks, 0); OutLink(Code.links);
(* datalink *)
OutLink(Data.links);
(* Use *)
OutUseBlock;
(* Header Fixups *)
DevCPM.ObjSet(8);
DevCPM.ObjWLInt(headSize);
DevCPM.ObjWLInt(modPos - headSize);
DevCPM.ObjWLInt(codePos - modPos);
DevCPM.ObjWLInt(pc);
DevCPM.ObjWLInt(dsize);
IF namex > MaxNameTab THEN DevCPM.err(242) END;
IF DevCPM.noerr & outObj THEN DevCPM.RegisterObj END
END OutCode;
PROCEDURE Init* (proc: INTEGER; opt: SET);
CONST obj = 3; ref = 4; allref = 5; srcpos = 6; bigEnd = 15; pVarInd = 14;
BEGIN
processor := proc;
bigEndian := bigEnd IN opt; procVarIndirect := pVarInd IN opt;
outRef := ref IN opt; outAllRef := allref IN opt; outObj := obj IN opt;
outURef := useAllRef & outAllRef & (DevCPM.comAware IN DevCPM.options);
outSrc := srcpos IN opt;
pc := 0; actIdx := CodeLength; blkIdx := 0;
idx8 := 0; idx16 := 0; idx32 := 0; idx64 := 0; namex := 1;
options := opt * {0..15}; CodeOvF := FALSE;
KNewRec.links := NIL; KNewArr.links := NIL; CaseLinks := NIL;
Const8.links := NIL; Const8.conval := NIL; Const16.links := NIL; Const16.conval := NIL;
Const32.links := NIL; Const32.conval := NIL; Const64.links := NIL; Const64.conval := NIL;
Code.links := NIL; Data.links := NIL; Mod.links := NIL; Proc.links := NIL; Meta.links := NIL;
nameList := NIL; descList := NIL; dllList := NIL; dllLast := NIL;
codePos := 0; srcPos := 0;
NEW(untgd); untgd.name := DevCPT.NewName("!");
closeLbl := 0
END Init;
PROCEDURE Close*;
BEGIN
KNewRec.links := NIL; KNewArr.links := NIL; CaseLinks := NIL;
Const8.links := NIL; Const8.conval := NIL; Const16.links := NIL; Const16.conval := NIL;
Const32.links := NIL; Const32.conval := NIL; Const64.links := NIL; Const64.conval := NIL;
Code.links := NIL; Data.links := NIL; Mod.links := NIL; Proc.links := NIL; Meta.links := NIL;
nameList := NIL; descList := NIL; dllList := NIL; dllLast := NIL;
WHILE blkIdx > 0 DO DEC(blkIdx); code[blkIdx] := NIL END;
actual := NIL; untgd := NIL;
END Close;
BEGIN
NEW(KNewRec); KNewRec.mnolev := -128;
NEW(KNewArr); KNewArr.mnolev := -128;
NEW(Const8); Const8.mode := Con; Const8.mnolev := 0;
NEW(Const16); Const16.mode := Con; Const16.mnolev := 0;
NEW(Const32); Const32.mode := Con; Const32.mnolev := 0;
NEW(Const64); Const64.mode := Con; Const64.mnolev := 0;
NEW(Code); Code.mode := Con; Code.mnolev := 0;
NEW(Data); Data.mode := Con; Data.mnolev := 0;
NEW(Mod); Mod.mode := Con; Mod.mnolev := 0;
NEW(Proc); Proc.mode := Con; Proc.mnolev := 0;
NEW(Meta); Meta.mode := Con; Mod.mnolev := 0;
END DevCPE.
| Dev/Mod/CPE.odc |
MODULE DevCPH;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20170612, center #160, outdated link to OP2.Paper.ps
"
issues = "
- ...
"
**)
IMPORT DevCPT;
CONST
(* UseCalls options *)
longMop* = 0; longDop* = 1; longConv* = 2; longOdd* = 3;
realMop* = 8; realDop* = 9; realConv* = 10;
intMulDiv* = 11;
force = 16; hide = 17;
(* nodes classes *)
Nvar = 0; Nvarpar = 1; Nfield = 2; Nderef = 3; Nindex = 4; Nguard = 5; Neguard = 6;
Nconst = 7; Ntype = 8; Nproc = 9; Nupto = 10; Nmop = 11; Ndop = 12; Ncall = 13;
Ninittd = 14; Nif = 15; Ncaselse = 16; Ncasedo = 17; Nenter = 18; Nassign = 19;
Nifelse =20; Ncase = 21; Nwhile = 22; Nrepeat = 23; Nloop = 24; Nexit = 25;
Nreturn = 26; Nwith = 27; Ntrap = 28; Ncomp = 30;
Ndrop = 50; Nlabel = 51; Ngoto = 52; Njsr = 53; Nret = 54; Ncmp = 55;
(*function number*)
assign = 0; newfn = 1; incfn = 13; decfn = 14;
inclfn = 15; exclfn = 16; copyfn = 18; assertfn = 32;
getfn = 24; putfn = 25; getrfn = 26; putrfn = 27; sysnewfn = 30; movefn = 31;
(* symbol values and ops *)
times = 1; slash = 2; div = 3; mod = 4;
and = 5; plus = 6; minus = 7; or = 8; eql = 9;
neq = 10; lss = 11; leq = 12; gtr = 13; geq = 14;
in = 15; is = 16; ash = 17; msk = 18; len = 19;
conv = 20; abs = 21; cap = 22; odd = 23; not = 33;
adr = 24; cc = 25; bit = 26; lsh = 27; rot = 28; val = 29;
min = 34; max = 35; typfn = 36;
thisrecfn = 45; thisarrfn = 46;
shl = 50; shr = 51; lshr = 52; xor = 53;
(* structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; String16 = 17; Int64 = 18;
VString16to8 = 29; VString8 = 30; VString16 = 31;
realSet = {Real32, Real64};
Basic = 1; Array = 2; DynArr = 3; Record = 4;
PROCEDURE UseThisCall (n: DevCPT.Node; IN name: ARRAY OF SHORTCHAR);
VAR mod, nm, moda: DevCPT.Name; mobj, obj: DevCPT.Object; done: BOOLEAN;
BEGIN
IF (n.typ.form = Real64) OR (n.left.typ.form = Real64) THEN mod := "Real"
ELSIF (n.typ.form = Real32) OR (n.left.typ.form = Real32) THEN mod := "SReal"
ELSIF (n.typ.form = Int64) OR (n.left.typ.form = Int64) THEN mod := "Long"
ELSE mod := "Int"
END;
moda := mod + "%";
DevCPT.Find(moda, mobj);
IF mobj = NIL THEN
DevCPT.Import(moda, mod, done);
IF done THEN DevCPT.Find(moda, mobj) END
END;
nm := name$; DevCPT.FindImport(nm, mobj, obj);
n.class := Ncall; n.subcl := 0; n.obj := obj.link;
n.left.link := n.right; n.right := n.left;
n.left := DevCPT.NewNode(Nproc);
n.left.obj := obj; n.left.typ := obj.typ;
ASSERT(n.typ.form = obj.typ.form)
END UseThisCall;
PROCEDURE Convert (n: DevCPT.Node; typ: DevCPT.Struct);
VAR new: DevCPT.Node; r: REAL;
BEGIN
IF n.class = Nconst THEN
ASSERT((n.typ.form IN {Int32, Int64}) & (typ = DevCPT.intrealtyp));
r := n.conval.realval + n.conval.intval;
IF r = n.conval.realval + n.conval.intval THEN
n.conval.realval := r; n.conval.intval := -1; n.typ := typ; n.obj := NIL
END
END;
IF (n.typ # typ)
& ((n.class # Nmop) OR (n.subcl # conv)
OR ~DevCPT.Includes(n.typ.form, n.left.typ.form) & ~DevCPT.Includes(n.typ.form, typ.form)) THEN
new := DevCPT.NewNode(0); new^ := n^;
n.class := Nmop; n.subcl := conv; n.left := new; n.right := NIL; n.obj := NIL
END;
n.typ := typ
END Convert;
PROCEDURE UseCallForComp (n: DevCPT.Node);
VAR new: DevCPT.Node;
BEGIN
new := DevCPT.NewNode(0);
new.left := n.left; new.right := n.right;
new.typ := DevCPT.int32typ;
UseThisCall(new, "Comp");
n.left := new;
n.right := DevCPT.NewNode(Nconst); n.right.conval := DevCPT.NewConst();
n.right.conval.intval := 0; n.right.conval.realval := 0; n.right.typ := DevCPT.int32typ;
END UseCallForComp;
PROCEDURE UseCallForConv (n: DevCPT.Node; opts: SET);
VAR f, g: INTEGER; typ: DevCPT.Struct;
BEGIN
typ := n.typ; f := typ.form; g := n.left.typ.form;
IF realConv IN opts THEN
IF f IN realSet THEN
IF g = Real32 THEN UseThisCall(n, "Long")
ELSIF g = Real64 THEN UseThisCall(n, "Short")
ELSIF g = Int64 THEN UseThisCall(n, "LFloat")
ELSIF g = Int32 THEN UseThisCall(n, "Float")
ELSE Convert(n.left, DevCPT.int32typ); UseThisCall(n, "Float")
END
ELSIF g IN realSet THEN
IF f = Int64 THEN UseThisCall(n, "LFloor")
ELSIF f = Int32 THEN UseThisCall(n, "Floor")
ELSE n.typ := DevCPT.int32typ; UseThisCall(n, "Floor"); Convert(n, typ)
END
END
END;
IF longConv IN opts THEN
IF f = Int64 THEN
IF g = Int32 THEN UseThisCall(n, "Long")
ELSIF ~(g IN realSet) THEN Convert(n.left, DevCPT.int32typ); UseThisCall(n, "IntToLong")
END
ELSIF g = Int64 THEN
IF f = Int32 THEN UseThisCall(n, "Short")
ELSIF ~(f IN realSet) THEN n.typ := DevCPT.int32typ; UseThisCall(n, "LongToInt"); Convert(n, typ)
END
END
END
END UseCallForConv;
PROCEDURE UseCallForMop (n: DevCPT.Node; opts: SET);
BEGIN
CASE n.subcl OF
| minus:
IF (realMop IN opts) & (n.typ.form IN realSet) OR (longMop IN opts) & (n.typ.form = Int64) THEN
UseThisCall(n, "Neg")
END
| abs:
IF (realMop IN opts) & (n.typ.form IN realSet) OR (longMop IN opts) & (n.typ.form = Int64) THEN
UseThisCall(n, "Abs")
END
| odd:
IF (longOdd IN opts) & (n.left.typ.form = Int64) THEN UseThisCall(n, "Odd") END
| conv:
UseCallForConv(n, opts)
ELSE
END
END UseCallForMop;
PROCEDURE UseCallForDop (n: DevCPT.Node; opts: SET);
BEGIN
IF (realDop IN opts) & (n.left.typ.form IN realSet)
OR (longDop IN opts) & (n.left.typ.form = Int64)
OR (intMulDiv IN opts) & (n.subcl IN {times, div, mod}) & (n.typ.form = Int32) THEN
CASE n.subcl OF
| times: UseThisCall(n, "Mul")
| slash: UseThisCall(n, "Div")
| div: UseThisCall(n, "Div")
| mod: UseThisCall(n, "Mod")
| plus: UseThisCall(n, "Add")
| minus: UseThisCall(n, "Sub")
| ash: UseThisCall(n, "Ash")
| min: UseThisCall(n, "Min")
| max: UseThisCall(n, "Max")
| eql..geq: UseCallForComp(n)
ELSE
END
END
END UseCallForDop;
PROCEDURE UseCallForMove (n: DevCPT.Node; typ: DevCPT.Struct; opts: SET);
VAR f, g: INTEGER;
BEGIN
f := n.typ.form; g := typ.form;
IF f # g THEN
IF (realConv IN opts) & ((f IN realSet) OR (g IN realSet))
OR (longConv IN opts) & ((f = Int64) OR (g = Int64)) THEN
Convert(n, typ);
UseCallForConv(n, opts)
END
END
END UseCallForMove;
PROCEDURE UseCallForAssign (n: DevCPT.Node; opts: SET);
BEGIN
IF n.subcl = assign THEN UseCallForMove(n.right, n.left.typ, opts) END
END UseCallForAssign;
PROCEDURE UseCallForReturn (n: DevCPT.Node; opts: SET);
BEGIN
IF (n.left # NIL) & (n.obj # NIL) THEN UseCallForMove(n.left, n.obj.typ, opts) END
END UseCallForReturn;
PROCEDURE UseCallForParam (n: DevCPT.Node; fp: DevCPT.Object; opts: SET);
BEGIN
WHILE n # NIL DO
UseCallForMove(n, fp.typ, opts);
n := n.link; fp := fp.link
END
END UseCallForParam;
PROCEDURE UseCalls* (n: DevCPT.Node; opts: SET);
BEGIN
WHILE n # NIL DO
CASE n.class OF
| Nmop:
UseCalls(n.left, opts); UseCallForMop(n, opts)
| Ndop:
UseCalls(n.left, opts); UseCalls(n.right, opts); UseCallForDop(n, opts)
| Ncase:
UseCalls(n.left, opts); UseCalls(n.right.left, opts); UseCalls(n.right.right, opts)
| Nassign:
UseCalls(n.left, opts); UseCalls(n.right, opts); UseCallForAssign(n, opts)
| Ncall:
UseCalls(n.left, opts); UseCalls(n.right, opts); UseCallForParam(n.right, n.obj, opts)
| Nreturn:
UseCalls(n.left, opts); UseCallForReturn(n, opts)
| Ncasedo:
UseCalls(n.right, opts)
| Ngoto, Ndrop, Nloop, Nfield, Nderef, Nguard:
UseCalls(n.left, opts)
| Nenter, Nifelse, Nif, Nwhile, Nrepeat, Nwith, Ncomp, Nupto, Nindex:
UseCalls(n.left, opts); UseCalls(n.right, opts)
| Njsr, Nret, Nlabel, Ntrap, Nexit, Ninittd, Ntype, Nproc, Nconst, Nvar, Nvarpar:
END;
n := n.link
END
END UseCalls;
PROCEDURE UseReals* (n: DevCPT.Node; opts: SET);
BEGIN
WHILE n # NIL DO
CASE n.class OF
| Nmop:
IF (longMop IN opts) & (n.typ.form = Int64) & ((n.subcl = abs) OR (n.subcl = minus)) THEN
UseReals(n.left, opts - {hide} + {force}); n.typ := DevCPT.intrealtyp
ELSIF n.subcl = conv THEN UseReals(n.left, opts - {force} + {hide})
ELSE UseReals(n.left, opts - {force, hide})
END
| Ndop:
IF (longDop IN opts) & (n.left.typ.form = Int64) THEN
UseReals(n.left, opts - {hide} + {force}); UseReals(n.right, opts - {hide} + {force});
IF n.typ.form = Int64 THEN n.typ := DevCPT.intrealtyp END
ELSE UseReals(n.left, opts - {force, hide}); UseReals(n.right, opts - {force, hide})
END
| Ncase:
UseReals(n.left, opts - {force, hide}); UseReals(n.right.left, opts - {force, hide});
UseReals(n.right.right, opts - {force, hide})
| Ncasedo:
UseReals(n.right, opts - {force, hide})
| Ngoto, Ndrop, Nloop, Nreturn, Nfield, Nderef, Nguard:
UseReals(n.left, opts - {force, hide})
| Nenter, Nassign, Ncall, Nifelse, Nif, Nwhile, Nrepeat, Nwith, Ncomp, Nupto, Nindex:
UseReals(n.left, opts - {force, hide}); UseReals(n.right, opts - {force, hide})
| Njsr, Nret, Nlabel, Ntrap, Nexit, Ninittd, Ntype, Nproc, Nconst, Nvar, Nvarpar:
END;
IF force IN opts THEN Convert(n, DevCPT.intrealtyp)
ELSIF ~(hide IN opts) & (n.typ = DevCPT.intrealtyp) THEN Convert(n, DevCPT.int64typ)
END;
n := n.link
END
END UseReals;
END DevCPH.
PROCEDURE Traverse (n: DevCPT.Node; opts: SET);
BEGIN
WHILE n # NIL DO
CASE n.class OF
| Ncase:
Traverse(n.left, opts); Traverse(n.right.left, opts); Traverse(n.right.right, opts)
| Ncasedo:
Traverse(n.right, opts)
| Ngoto, Ndrop, Nloop, Nreturn, Nmop, Nfield, Nderef, Nguard:
Traverse(n.left, opts)
| Nenter, Nassign, Ncall, Nifelse, Nif, Nwhile, Nrepeat, Nwith, Ncomp, Ndop, Nupto, Nindex:
Traverse(n.left, opts); Traverse(n.right, opts)
| Njsr, Nret, Nlabel, Ntrap, Nexit, Ninittd, Ntype, Nproc, Nconst, Nvar, Nvarpar:
END;
n := n.link
END
END Traverse;
| Dev/Mod/CPH.odc |
MODULE DevCPL486;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20160324, center #111, code cleanups
- 20170612, center #160, outdated link to OP2.Paper.ps
"
issues = "
- ...
"
**)
IMPORT DevCPM, DevCPT, DevCPE;
TYPE
Item* = RECORD
mode*, tmode*, form*: BYTE;
offset*, index*, reg*, scale*: INTEGER; (* adr = offset + index * scale *)
typ*: DevCPT.Struct;
obj*: DevCPT.Object
END ;
(* Items:
mode | offset index scale reg obj
------------------------------------------------
1 Var | adr xreg scale obj (ea = FP + adr + xreg * scale)
2 VarPar| off xreg scale obj (ea = [FP + obj.adr] + off + xreg * scale)
3 Con | val (val2) NIL
Con | off obj (val = adr(obj) + off)
Con | id NIL (for predefined reals)
6 LProc | obj
7 XProc | obj
9 CProc | obj
10 IProc | obj
13 TProc | mthno 0/1 obj (0 = normal / 1 = super call)
14 Ind | off xreg scale Reg (ea = Reg + off + xreg * scale)
15 Abs | adr xreg scale NIL (ea = adr + xreg * scale)
Abs | off xreg scale obj (ea = adr(obj) + off + xreg * scale)
Abs | off len 0 obj (for constant strings and reals)
16 Stk | (ea = ESP)
17 Cond | CC
18 Reg | (Reg2) Reg
19 DInd | off xreg scale Reg (ea = [Reg + off + xreg * scale])
tmode | record tag array desc
-------------------------------------
VarPar | [FP + obj.adr + 4] [FP + obj.adr]
Ind | [Reg - 4] [Reg + 8]
Con | Adr(typ.strobj)
*)
CONST
processor* = 10; (* for i386 *)
NewLbl* = 0;
TYPE
Label* = INTEGER; (* 0: unassigned, > 0: address, < 0: - (linkadr + linktype * 2^24) *)
VAR
level*: BYTE;
one*: DevCPT.Const;
CONST
(* item base modes (=object modes) *)
Var = 1; VarPar = 2; Con = 3; LProc = 6; XProc = 7; CProc = 9; IProc = 10; TProc = 13;
(* item modes for i386 (must not overlap item basemodes, > 13) *)
Ind = 14; Abs = 15; Stk = 16; Cond = 17; Reg = 18; DInd = 19;
(* structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; String16 = 17; Int64 = 18; Guid = 23;
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(* condition codes *)
ccB = 2; ccAE = 3; ccBE = 6; ccA = 7; (* unsigned *)
ccL = 12; ccGE = 13; ccLE = 14; ccG = 15; (* signed *)
ccE = 4; ccNE = 5; ccS = 8; ccNS = 9; ccO = 0; ccNO = 1;
ccAlways = -1; ccNever = -2; ccCall = -3;
(* registers *)
AX = 0; CX = 1; DX = 2; BX = 3; SP = 4; BP = 5; SI = 6; DI = 7; AH = 4; CH = 5; DH = 6; BH = 7;
(* fixup types *)
absolute = 100; relative = 101; copy = 102; table = 103; tableend = 104; short = 105;
(* system trap numbers *)
withTrap = -1; caseTrap = -2; funcTrap = -3; typTrap = -4;
recTrap = -5; ranTrap = -6; inxTrap = -7; copyTrap = -8;
VAR
Size: ARRAY 32 OF INTEGER; (* Size[typ.form] == +/- typ.size *)
a1, a2: Item;
PROCEDURE MakeReg* (VAR x: Item; reg: INTEGER; form: BYTE);
BEGIN
ASSERT((reg >= 0) & (reg < 8));
x.mode := Reg; x.reg := reg; x.form := form
END MakeReg;
PROCEDURE MakeConst* (VAR x: Item; val: INTEGER; form: BYTE);
BEGIN
x.mode := Con; x.offset := val; x.form := form; x.obj := NIL;
END MakeConst;
PROCEDURE AllocConst* (VAR x: Item; con: DevCPT.Const; form: BYTE);
VAR r: REAL; short: SHORTREAL;
BEGIN
IF form IN {Real32, Real64} THEN
r := con.realval;
IF ABS(r) <= MAX(SHORTREAL) THEN
short := SHORT(r);
IF short = r THEN form := Real32 (* a shortreal can represent the exact value *)
ELSE form := Real64 (* use a real *)
END
ELSE form := Real64 (* use a real *)
END
ELSIF form IN {String8, String16, Guid} THEN
x.index := con.intval2 (* string length *)
END;
DevCPE.AllocConst(con, form, x.obj, x.offset);
x.form := form; x.mode := Abs; x.scale := 0
END AllocConst;
(*******************************************************)
PROCEDURE BegStat*; (* general-purpose procedure which is called before each statement *)
BEGIN
END BegStat;
PROCEDURE EndStat*; (* general-purpose procedure which is called after each statement *)
BEGIN
END EndStat;
(*******************************************************)
PROCEDURE SetLabel* (VAR L: Label);
VAR link, typ, disp, x: INTEGER;
BEGIN
ASSERT(L <= 0); link := -L;
WHILE link # 0 DO
typ := link DIV 1000000H; link := link MOD 1000000H;
IF typ = short THEN
disp := DevCPE.pc - link - 1; ASSERT(disp < 128);
DevCPE.PutByte(link, disp); link := 0
ELSIF typ = relative THEN
x := DevCPE.ThisWord(link); DevCPE.PutWord(link, DevCPE.pc - link - 4); link := x
ELSE
x := DevCPE.ThisWord(link); DevCPE.PutWord(link, DevCPE.pc + typ * 1000000H); link := x
END
END;
L := DevCPE.pc;
a1.mode := 0; a2.mode := 0
END SetLabel;
(*******************************************************)
PROCEDURE GenWord (x: INTEGER);
BEGIN
DevCPE.GenByte(x); DevCPE.GenByte(x DIV 256)
END GenWord;
PROCEDURE GenDbl (x: INTEGER);
BEGIN
DevCPE.GenByte(x); DevCPE.GenByte(x DIV 256); DevCPE.GenByte(x DIV 10000H); DevCPE.GenByte(x DIV 1000000H)
END GenDbl;
PROCEDURE CaseEntry* (tab, from, to: INTEGER);
VAR a, e: INTEGER;
BEGIN
a := tab + 4 * from; e := tab + 4 * to;
WHILE a <= e DO
DevCPE.PutByte(a, DevCPE.pc);
DevCPE.PutByte(a + 1, DevCPE.pc DIV 256);
DevCPE.PutByte(a + 2, DevCPE.pc DIV 65536);
INC(a, 4)
END;
a1.mode := 0; a2.mode := 0
END CaseEntry;
PROCEDURE GenLinked (VAR x: Item; type: BYTE);
VAR link: DevCPT.LinkList;
BEGIN
IF x.obj = NIL THEN GenDbl(x.offset)
ELSE
link := DevCPE.OffsetLink(x.obj, x.offset);
IF link # NIL THEN
GenDbl(type * 1000000H + link.linkadr MOD 1000000H);
link.linkadr := DevCPE.pc - 4
ELSE GenDbl(0)
END
END
END GenLinked;
PROCEDURE CheckSize (form: BYTE; VAR w: INTEGER);
BEGIN
IF form IN {Int16, Char16} THEN DevCPE.GenByte(66H); w := 1
ELSIF form >= Int32 THEN ASSERT(form IN {Int32, Set, NilTyp, Pointer, ProcTyp}); w := 1
ELSE w := 0
END
END CheckSize;
PROCEDURE CheckForm (form: BYTE; VAR mf: INTEGER);
BEGIN
IF form = Real32 THEN mf := 0
ELSIF form = Real64 THEN mf := 4
ELSIF form = Int32 THEN mf := 2
ELSE ASSERT(form = Int16); mf := 6
END
END CheckForm;
PROCEDURE CheckConst (VAR x: Item; VAR s: INTEGER);
BEGIN
IF (x.form > Int8) & (x.offset >= -128) & (x.offset < 128) & (x.obj = NIL) THEN s := 2
ELSE s := 0
END
END CheckConst;
PROCEDURE GenConst (VAR x: Item; short: BOOLEAN);
BEGIN
IF x.obj # NIL THEN GenLinked(x, absolute)
ELSIF x.form <= Int8 THEN DevCPE.GenByte(x.offset)
ELSIF short & (x.offset >= -128) & (x.offset < 128) THEN DevCPE.GenByte(x.offset)
ELSIF x.form IN {Int16, Char16} THEN GenWord(x.offset)
ELSE GenDbl(x.offset)
END
END GenConst;
PROCEDURE GenCExt (code: INTEGER; VAR x: Item);
VAR disp, mod, base, scale: INTEGER;
BEGIN
ASSERT(x.mode IN {Reg, Ind, Abs, Stk});
ASSERT((code MOD 8 = 0) & (code < 64));
disp := x.offset; base := x.reg; scale := x.scale;
IF x.mode = Reg THEN mod := 0C0H; scale := 0
ELSIF x.mode = Stk THEN base := SP; mod := 0; disp := 0; scale := 0
ELSIF x.mode = Abs THEN
IF scale = 1 THEN base := x.index; mod := 80H; scale := 0
ELSE base := BP; mod := 0
END
ELSIF (disp = 0) & (base # BP) THEN mod := 0
ELSIF (disp >= -128) & (disp < 128) THEN mod := 40H
ELSE mod := 80H
END;
IF scale # 0 THEN
DevCPE.GenByte(mod + code + 4); base := base + x.index * 8;
IF scale = 8 THEN DevCPE.GenByte(0C0H + base);
ELSIF scale = 4 THEN DevCPE.GenByte(80H + base);
ELSIF scale = 2 THEN DevCPE.GenByte(40H + base);
ELSE ASSERT(scale = 1); DevCPE.GenByte(base);
END;
ELSE
DevCPE.GenByte(mod + code + base);
IF (base = SP) & (mod <= 80H) THEN DevCPE.GenByte(24H) END
END;
IF x.mode = Abs THEN GenLinked(x, absolute)
ELSIF mod = 80H THEN GenDbl(disp)
ELSIF mod = 40H THEN DevCPE.GenByte(disp)
END
END GenCExt;
PROCEDURE GenDExt (VAR r, x: Item);
BEGIN
ASSERT(r.mode = Reg);
GenCExt(r.reg * 8, x)
END GenDExt;
(*******************************************************)
PROCEDURE GenMove* (VAR from, to: Item);
VAR w: INTEGER;
BEGIN
ASSERT(Size[from.form] = Size[to.form]);
IF to.mode = Reg THEN
IF from.mode = Con THEN
IF to.reg = AX THEN
IF (a1.mode = Con) & (from.offset = a1.offset) & (from.obj = a1.obj) & (from.form = a1.form) THEN
RETURN
END;
a1 := from; a2.mode := 0
END;
CheckSize(from.form, w);
IF (from.offset = 0) & (from.obj = NIL) THEN
DevCPE.GenByte(30H + w); DevCPE.GenByte(0C0H + 9 * to.reg) (* XOR r,r *)
ELSE
DevCPE.GenByte(0B0H + w * 8 + to.reg); GenConst(from, FALSE)
END;
ELSIF (to.reg = AX) & (from.mode = Abs) & (from.scale = 0) THEN
IF (a1.mode = Abs) & (from.offset = a1.offset) & (from.obj = a1.obj) & (from.form = a1.form)
OR (a2.mode = Abs) & (from.offset = a2.offset) & (from.obj = a2.obj) & (from.form = a2.form) THEN
RETURN
END;
a1 := from; a2.mode := 0;
CheckSize(from.form, w);
DevCPE.GenByte(0A0H + w); GenLinked(from, absolute);
ELSIF (from.mode # Reg) OR (from.reg # to.reg) THEN
IF to.reg = AX THEN
IF (from.mode = Ind) & (from.scale = 0) & ((from.reg = BP) OR (from.reg = BX)) THEN
IF (a1.mode = Ind) & (from.offset = a1.offset) & (from.reg = a1.reg) & (from.form = a1.form)
OR (a2.mode = Ind) & (from.offset = a2.offset) & (from.reg = a2.reg) & (from.form = a2.form) THEN
RETURN
END;
a1 := from
ELSE a1.mode := 0
END;
a2.mode := 0
END;
CheckSize(from.form, w);
DevCPE.GenByte(8AH + w); GenDExt(to, from)
END
ELSE
CheckSize(from.form, w);
IF from.mode = Con THEN
DevCPE.GenByte(0C6H + w); GenCExt(0, to); GenConst(from, FALSE);
a1.mode := 0; a2.mode := 0
ELSIF (from.reg = AX) & (to.mode = Abs) & (to.scale = 0) THEN
DevCPE.GenByte(0A2H + w); GenLinked(to, absolute);
a2 := to
ELSE
DevCPE.GenByte(88H + w); GenDExt(from, to);
IF from.reg = AX THEN
IF (to.mode = Ind) & (to.scale = 0) & ((to.reg = BP) OR (to.reg = BX)) THEN a2 := to END
ELSE a1.mode := 0; a2.mode := 0
END
END
END
END GenMove;
PROCEDURE GenExtMove* (VAR from, to: Item);
VAR op: INTEGER;
BEGIN
ASSERT(from.mode # Con);
IF from.form IN {Byte, Char8, Char16} THEN op := 0B6H (* MOVZX *)
ELSE op := 0BEH (* MOVSX *)
END;
IF from.form IN {Int16, Char16} THEN INC(op) END;
DevCPE.GenByte(0FH); DevCPE.GenByte(op); GenDExt(to, from);
IF to.reg = AX THEN a1.mode := 0; a2.mode := 0 END
END GenExtMove;
PROCEDURE GenSignExt* (VAR from, to: Item);
BEGIN
ASSERT(to.mode = Reg);
IF (from.mode = Reg) & (from.reg = AX) & (to.reg = DX) THEN
DevCPE.GenByte(99H) (* cdq *)
ELSE
GenMove(from, to); (* mov to, from *)
DevCPE.GenByte(0C1H); GenCExt(38H, to); DevCPE.GenByte(31) (* sar to, 31 *)
END
END GenSignExt;
PROCEDURE GenLoadAdr* (VAR from, to: Item);
BEGIN
ASSERT(to.form IN {Int32, Pointer, ProcTyp});
IF (from.mode = Abs) & (from.scale = 0) THEN
DevCPE.GenByte(0B8H + to.reg); GenLinked(from, absolute)
ELSIF from.mode = Stk THEN
DevCPE.GenByte(89H); GenCExt(SP * 8, to)
ELSIF (from.mode # Ind) OR (from.offset # 0) OR (from.scale # 0) THEN
DevCPE.GenByte(8DH); GenDExt(to, from)
ELSIF from.reg # to.reg THEN
DevCPE.GenByte(89H); GenCExt(from.reg * 8, to)
ELSE RETURN
END;
IF to.reg = AX THEN a1.mode := 0; a2.mode := 0 END
END GenLoadAdr;
PROCEDURE GenPush* (VAR src: Item);
VAR s: INTEGER;
BEGIN
IF src.mode = Con THEN
ASSERT(src.form >= Int32);
CheckConst(src, s); DevCPE.GenByte(68H + s); GenConst(src, TRUE)
ELSIF src.mode = Reg THEN
ASSERT((src.form >= Int16) OR (src.reg < 4));
DevCPE.GenByte(50H + src.reg)
ELSE
ASSERT(src.form >= Int32);
DevCPE.GenByte(0FFH); GenCExt(30H, src)
END
END GenPush;
PROCEDURE GenPop* (VAR dst: Item);
BEGIN
IF dst.mode = Reg THEN
ASSERT((dst.form >= Int16) OR (dst.reg < 4));
DevCPE.GenByte(58H + dst.reg);
IF dst.reg = AX THEN a1.mode := 0; a2.mode := 0 END
ELSE
DevCPE.GenByte(08FH); GenCExt(0, dst)
END
END GenPop;
PROCEDURE GenConOp (op: INTEGER; VAR src, dst: Item);
VAR w, s: INTEGER;
BEGIN
ASSERT(Size[src.form] = Size[dst.form]);
CheckSize(src.form, w);
CheckConst(src, s);
IF (dst.mode = Reg) & (dst.reg = AX) & (s = 0) THEN
DevCPE.GenByte(op + 4 + w); GenConst(src, FALSE)
ELSE
DevCPE.GenByte(80H + s + w); GenCExt(op, dst); GenConst(src, TRUE)
END
END GenConOp;
PROCEDURE GenDirOp (op: INTEGER; VAR src, dst: Item);
VAR w: INTEGER;
BEGIN
ASSERT(Size[src.form] = Size[dst.form]);
CheckSize(src.form, w);
IF dst.mode = Reg THEN
DevCPE.GenByte(op + 2 + w); GenDExt(dst, src)
ELSE
DevCPE.GenByte(op + w); GenDExt(src, dst)
END
END GenDirOp;
PROCEDURE GenAdd* (VAR src, dst: Item; ovflchk: BOOLEAN);
VAR w: INTEGER;
BEGIN
ASSERT(Size[src.form] = Size[dst.form]);
IF src.mode = Con THEN
IF src.obj = NIL THEN
IF src.offset = 1 THEN
IF (dst.mode = Reg) & (dst.form >= Int32) THEN DevCPE.GenByte(40H + dst.reg) (* inc *)
ELSE CheckSize(dst.form, w); DevCPE.GenByte(0FEH + w); GenCExt(0, dst)
END
ELSIF src.offset = -1 THEN
IF (dst.mode = Reg) & (dst.form >= Int32) THEN DevCPE.GenByte(48H + dst.reg) (* dec *)
ELSE CheckSize(dst.form, w); DevCPE.GenByte(0FEH + w); GenCExt(8, dst)
END
ELSIF src.offset # 0 THEN
GenConOp(0, src, dst)
ELSE RETURN
END
ELSE
GenConOp(0, src, dst)
END
ELSE
GenDirOp(0, src, dst)
END;
IF ovflchk THEN DevCPE.GenByte(0CEH) END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenAdd;
PROCEDURE GenAddC* (VAR src, dst: Item; first, ovflchk: BOOLEAN);
VAR op: INTEGER;
BEGIN
ASSERT(Size[src.form] = Size[dst.form]);
IF first THEN op := 0 ELSE op := 10H END;
IF src.mode = Con THEN GenConOp(op, src, dst)
ELSE GenDirOp(op, src, dst)
END;
IF ovflchk THEN DevCPE.GenByte(0CEH) END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenAddC;
PROCEDURE GenSub* (VAR src, dst: Item; ovflchk: BOOLEAN);
VAR w: INTEGER;
BEGIN
ASSERT(Size[src.form] = Size[dst.form]);
IF src.mode = Con THEN
IF src.obj = NIL THEN
IF src.offset = 1 THEN
IF (dst.mode = Reg) & (dst.form >= Int32) THEN DevCPE.GenByte(48H + dst.reg) (* dec *)
ELSE CheckSize(dst.form, w); DevCPE.GenByte(0FEH + w); GenCExt(8, dst)
END
ELSIF src.offset = -1 THEN
IF (dst.mode = Reg) & (dst.form >= Int32) THEN DevCPE.GenByte(40H + dst.reg) (* inc *)
ELSE CheckSize(dst.form, w); DevCPE.GenByte(0FEH + w); GenCExt(0, dst)
END
ELSIF src.offset # 0 THEN
GenConOp(28H, src, dst)
ELSE RETURN
END
ELSE
GenConOp(28H, src, dst)
END
ELSE
GenDirOp(28H, src, dst)
END;
IF ovflchk THEN DevCPE.GenByte(0CEH) END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenSub;
PROCEDURE GenSubC* (VAR src, dst: Item; first, ovflchk: BOOLEAN);
VAR op: INTEGER;
BEGIN
ASSERT(Size[src.form] = Size[dst.form]);
IF first THEN op := 28H ELSE op := 18H END;
IF src.mode = Con THEN GenConOp(op, src, dst)
ELSE GenDirOp(op, src, dst)
END;
IF ovflchk THEN DevCPE.GenByte(0CEH) END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenSubC;
PROCEDURE GenComp* (VAR src, dst: Item);
VAR w: INTEGER;
BEGIN
IF src.mode = Con THEN
IF (src.offset = 0) & (src.obj = NIL) & (dst.mode = Reg) THEN
CheckSize(dst.form, w); DevCPE.GenByte(8 + w); DevCPE.GenByte(0C0H + 9 * dst.reg) (* or r,r *)
ELSE GenConOp(38H, src, dst)
END
ELSE
GenDirOp(38H, src, dst)
END
END GenComp;
PROCEDURE GenAnd* (VAR src, dst: Item);
BEGIN
IF src.mode = Con THEN
IF (src.obj # NIL) OR (src.offset # -1) THEN GenConOp(20H, src, dst) END
ELSE GenDirOp(20H, src, dst)
END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenAnd;
PROCEDURE GenOr* (VAR src, dst: Item);
BEGIN
IF src.mode = Con THEN
IF (src.obj # NIL) OR (src.offset # 0) THEN GenConOp(8H, src, dst) END
ELSE GenDirOp(8H, src, dst)
END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenOr;
PROCEDURE GenXor* (VAR src, dst: Item);
BEGIN
IF src.mode = Con THEN
IF (src.obj # NIL) OR (src.offset # 0) THEN GenConOp(30H, src, dst) END
ELSE GenDirOp(30H, src, dst)
END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenXor;
PROCEDURE GenTest* (VAR x, y: Item);
VAR w: INTEGER;
BEGIN
ASSERT(Size[x.form] = Size[y.form]);
CheckSize(x.form, w);
IF x.mode = Con THEN
IF (x.mode = Reg) & (x.reg = AX) THEN
DevCPE.GenByte(0A8H + w); GenConst(x, FALSE)
ELSE
DevCPE.GenByte(0F6H + w); GenCExt(0, y); GenConst(x, FALSE)
END
ELSE
DevCPE.GenByte(84H + w);
IF y.mode = Reg THEN GenDExt(y, x) ELSE GenDExt(x, y) END
END
END GenTest;
PROCEDURE GenNeg* (VAR dst: Item; ovflchk: BOOLEAN);
VAR w: INTEGER;
BEGIN
CheckSize(dst.form, w); DevCPE.GenByte(0F6H + w); GenCExt(18H, dst);
IF ovflchk THEN DevCPE.GenByte(0CEH) END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenNeg;
PROCEDURE GenNot* (VAR dst: Item);
VAR w: INTEGER;
BEGIN
CheckSize(dst.form, w); DevCPE.GenByte(0F6H + w); GenCExt(10H, dst);
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenNot;
PROCEDURE GenMul* (VAR src, dst: Item; ovflchk: BOOLEAN);
VAR w, s, val, f2, f5, f9: INTEGER;
BEGIN
ASSERT((dst.mode = Reg) & (Size[src.form] = Size[dst.form]));
IF (src.mode = Con) & (src.offset = 1) THEN RETURN END;
IF src.form <= Int8 THEN
ASSERT(dst.reg = 0);
DevCPE.GenByte(0F6H); GenCExt(28H, src)
ELSIF src.mode = Con THEN
val := src.offset;
IF (src.obj = NIL) & (val # 0) & ~ovflchk THEN
f2 := 0; f5 := 0; f9 := 0;
WHILE ~ODD(val) DO val := val DIV 2; INC(f2) END;
WHILE val MOD 9 = 0 DO val := val DIV 9; INC(f9) END;
WHILE val MOD 5 = 0 DO val := val DIV 5; INC(f5) END;
IF ABS(val) <= 3 THEN
WHILE f9 > 0 DO
DevCPE.GenByte(8DH);
DevCPE.GenByte(dst.reg * 8 + 4);
DevCPE.GenByte(0C0H + dst.reg * 9);
DEC(f9)
END;
WHILE f5 > 0 DO
DevCPE.GenByte(8DH);
DevCPE.GenByte(dst.reg * 8 + 4);
DevCPE.GenByte(80H + dst.reg * 9);
DEC(f5)
END;
IF ABS(val) = 3 THEN
DevCPE.GenByte(8DH); DevCPE.GenByte(dst.reg * 8 + 4); DevCPE.GenByte(40H + dst.reg * 9)
END;
IF f2 > 1 THEN DevCPE.GenByte(0C1H); DevCPE.GenByte(0E0H + dst.reg); DevCPE.GenByte(f2)
ELSIF f2 = 1 THEN DevCPE.GenByte(1); DevCPE.GenByte(0C0H + dst.reg * 9)
END;
IF val < 0 THEN DevCPE.GenByte(0F7H); GenCExt(18H, dst) END;
IF dst.reg = AX THEN a1.mode := 0; a2.mode := 0 END;
RETURN
END
END;
CheckSize(src.form, w); CheckConst(src, s);
DevCPE.GenByte(69H + s); GenDExt(dst, dst); GenConst(src, TRUE)
ELSE
CheckSize(src.form, w);
DevCPE.GenByte(0FH); DevCPE.GenByte(0AFH); GenDExt(dst, src)
END;
IF ovflchk THEN DevCPE.GenByte(0CEH) END;
IF dst.reg = AX THEN a1.mode := 0; a2.mode := 0 END
END GenMul;
PROCEDURE GenDiv* (VAR src: Item; mod, pos: BOOLEAN);
VAR w, rem: INTEGER;
BEGIN
ASSERT(src.mode = Reg);
IF src.form >= Int32 THEN DevCPE.GenByte(99H) (* cdq *)
ELSIF src.form = Int16 THEN DevCPE.GenByte(66H); DevCPE.GenByte(99H) (* cwd *)
ELSE DevCPE.GenByte(66H); DevCPE.GenByte(98H) (* cbw *)
END;
CheckSize(src.form, w); DevCPE.GenByte(0F6H + w); GenCExt(38H, src); (* idiv src *)
IF src.form > Int8 THEN rem := 2 (* edx *) ELSE rem := 4 (* ah *) END;
IF pos THEN (* src > 0 *)
CheckSize(src.form, w); DevCPE.GenByte(8 + w); DevCPE.GenByte(0C0H + 9 * rem); (* or rem,rem *)
IF mod THEN
DevCPE.GenByte(79H); DevCPE.GenByte(2); (* jns end *)
DevCPE.GenByte(2 + w); GenCExt(8 * rem, src); (* add rem,src *)
ELSE
DevCPE.GenByte(79H); DevCPE.GenByte(1); (* jns end *)
DevCPE.GenByte(48H); (* dec eax *)
END
ELSE
CheckSize(src.form, w); DevCPE.GenByte(30H + w); GenCExt(8 * rem, src); (* xor src,rem *)
IF mod THEN
DevCPE.GenByte(79H); (* jns end *)
IF src.form = Int16 THEN DevCPE.GenByte(9); DevCPE.GenByte(66H) ELSE DevCPE.GenByte(8) END;
DevCPE.GenByte(8 + w); DevCPE.GenByte(0C0H + 9 * rem); (* or rem,rem *)
DevCPE.GenByte(74H); DevCPE.GenByte(4); (* je end *)
DevCPE.GenByte(30H + w); GenCExt(8 * rem, src); (* xor src,rem *)
DevCPE.GenByte(2 + w); GenCExt(8 * rem, src); (* add rem,src *)
ELSE
DevCPE.GenByte(79H); (* jns end *)
IF src.form = Int16 THEN DevCPE.GenByte(6); DevCPE.GenByte(66H) ELSE DevCPE.GenByte(5) END;
DevCPE.GenByte(8 + w); DevCPE.GenByte(0C0H + 9 * rem); (* or rem,rem *)
DevCPE.GenByte(74H); DevCPE.GenByte(1); (* je end *)
DevCPE.GenByte(48H); (* dec eax *)
END
(*
CheckSize(src.form, w); DevCPE.GenByte(3AH + w); GenCExt(8 * rem, src); (* cmp rem,src *)
IF mod THEN
DevCPE.GenByte(72H); DevCPE.GenByte(4); (* jb end *)
DevCPE.GenByte(7FH); DevCPE.GenByte(2); (* jg end *)
DevCPE.GenByte(2 + w); GenCExt(8 * rem, src); (* add rem,src *)
ELSE
DevCPE.GenByte(72H); DevCPE.GenByte(3); (* jb end *)
DevCPE.GenByte(7FH); DevCPE.GenByte(1); (* jg end *)
DevCPE.GenByte(48H); (* dec eax *)
END
*)
END;
a1.mode := 0; a2.mode := 0
END GenDiv;
PROCEDURE GenShiftOp* (op: INTEGER; VAR cnt, dst: Item);
VAR w: INTEGER;
BEGIN
CheckSize(dst.form, w);
IF cnt.mode = Con THEN
ASSERT(cnt.offset >= 0); ASSERT(cnt.obj = NIL);
IF cnt.offset = 1 THEN
IF (op = 10H) & (dst.mode = Reg) THEN (* shl r *)
DevCPE.GenByte(w); GenDExt(dst, dst) (* add r, r *)
ELSE
DevCPE.GenByte(0D0H + w); GenCExt(op, dst)
END
ELSIF cnt.offset > 1 THEN
DevCPE.GenByte(0C0H + w); GenCExt(op, dst); DevCPE.GenByte(cnt.offset)
END
ELSE
ASSERT((cnt.mode = Reg) & (cnt.reg = CX));
DevCPE.GenByte(0D2H + w); GenCExt(op, dst)
END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenShiftOp;
PROCEDURE GenBitOp* (op: INTEGER; VAR num, dst: Item);
BEGIN
DevCPE.GenByte(0FH);
IF num.mode = Con THEN
ASSERT(num.obj = NIL);
DevCPE.GenByte(0BAH); GenCExt(op, dst); DevCPE.GenByte(num.offset)
ELSE
ASSERT((num.mode = Reg) & (num.form = Int32));
DevCPE.GenByte(83H + op); GenDExt(num, dst)
END;
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenBitOp;
PROCEDURE GenSetCC* (cc: INTEGER; VAR dst: Item);
BEGIN
ASSERT((dst.form = Bool) & (cc >= 0));
DevCPE.GenByte(0FH); DevCPE.GenByte(90H + cc); GenCExt(0, dst);
IF (dst.mode # Reg) OR (dst.reg = AX) THEN a1.mode := 0; a2.mode := 0 END
END GenSetCC;
PROCEDURE GenFLoad* (VAR src: Item);
VAR mf: INTEGER;
BEGIN
IF src.mode = Con THEN (* predefined constants *)
DevCPE.GenByte(0D9H); DevCPE.GenByte(0E8H + src.offset)
ELSIF src.form = Int64 THEN
DevCPE.GenByte(0DFH); GenCExt(28H, src)
ELSE
CheckForm(src.form, mf);
DevCPE.GenByte(0D9H + mf); GenCExt(0, src)
END
END GenFLoad;
PROCEDURE GenFStore* (VAR dst: Item; pop: BOOLEAN);
VAR mf: INTEGER;
BEGIN
IF dst.form = Int64 THEN ASSERT(pop);
DevCPE.GenByte(0DFH); GenCExt(38H, dst); DevCPE.GenByte(9BH) (* wait *)
ELSE
CheckForm(dst.form, mf); DevCPE.GenByte(0D9H + mf);
IF pop THEN GenCExt(18H, dst); DevCPE.GenByte(9BH) (* wait *)
ELSE GenCExt(10H, dst)
END
END;
a1.mode := 0; a2.mode := 0
END GenFStore;
PROCEDURE GenFDOp* (op: INTEGER; VAR src: Item);
VAR mf: INTEGER;
BEGIN
IF src.mode = Reg THEN
DevCPE.GenByte(0DEH); DevCPE.GenByte(0C1H + op)
ELSE
CheckForm(src.form, mf);
DevCPE.GenByte(0D8H + mf); GenCExt(op, src)
END
END GenFDOp;
PROCEDURE GenFMOp* (op: INTEGER);
BEGIN
DevCPE.GenByte(0D8H + op DIV 256);
DevCPE.GenByte(op MOD 256);
IF op = 07E0H THEN a1.mode := 0; a2.mode := 0 END (* FSTSW AX *)
END GenFMOp;
PROCEDURE GenJump* (cc: INTEGER; VAR L: Label; shortjmp: BOOLEAN);
BEGIN
IF cc # ccNever THEN
IF shortjmp OR (L > 0) & (DevCPE.pc + 2 - L <= 128) & (cc # ccCall) THEN
IF cc = ccAlways THEN DevCPE.GenByte(0EBH)
ELSE DevCPE.GenByte(70H + cc)
END;
IF L > 0 THEN DevCPE.GenByte(L - DevCPE.pc - 1)
ELSE ASSERT(L = 0); L := -(DevCPE.pc + short * 1000000H); DevCPE.GenByte(0)
END
ELSE
IF cc = ccAlways THEN DevCPE.GenByte(0E9H)
ELSIF cc = ccCall THEN DevCPE.GenByte(0E8H)
ELSE DevCPE.GenByte(0FH); DevCPE.GenByte(80H + cc)
END;
IF L > 0 THEN GenDbl(L - DevCPE.pc - 4)
ELSE GenDbl(-L); L := -(DevCPE.pc - 4 + relative * 1000000H)
END
END
END
END GenJump;
PROCEDURE GenExtJump* (cc: INTEGER; VAR dst: Item);
BEGIN
IF cc = ccAlways THEN DevCPE.GenByte(0E9H)
ELSE DevCPE.GenByte(0FH); DevCPE.GenByte(80H + cc)
END;
dst.offset := 0; GenLinked(dst, relative)
END GenExtJump;
PROCEDURE GenIndJump* (VAR dst: Item);
BEGIN
DevCPE.GenByte(0FFH); GenCExt(20H, dst)
END GenIndJump;
PROCEDURE GenCaseJump* (VAR src: Item);
VAR link: DevCPT.LinkList; tab: INTEGER;
BEGIN
ASSERT((src.form = Int32) & (src.mode = Reg));
DevCPE.GenByte(0FFH); DevCPE.GenByte(24H); DevCPE.GenByte(85H + 8 * src.reg);
tab := (DevCPE.pc + 7) DIV 4 * 4;
NEW(link); link.offset := tab; link.linkadr := DevCPE.pc;
link.next := DevCPE.CaseLinks; DevCPE.CaseLinks := link;
GenDbl(absolute * 1000000H + tab);
WHILE DevCPE.pc < tab DO DevCPE.GenByte(90H) END;
END GenCaseJump;
(*
PROCEDURE GenCaseJump* (VAR src: Item; num: LONGINT; VAR tab: LONGINT);
VAR link: DevCPT.LinkList; else, last: LONGINT;
BEGIN
ASSERT((src.form = Int32) & (src.mode = Reg));
DevCPE.GenByte(0FFH); DevCPE.GenByte(24H); DevCPE.GenByte(85H + 8 * src.reg);
tab := (DevCPE.pc + 7) DIV 4 * 4;
else := tab + num * 4; last := else - 4;
NEW(link); link.offset := tab; link.linkadr := DevCPE.pc;
link.next := CaseLinks; CaseLinks := link;
GenDbl(absolute * 1000000H + tab);
WHILE DevCPE.pc < tab DO DevCPE.GenByte(90H) END;
WHILE DevCPE.pc < last DO GenDbl(table * 1000000H + else) END;
GenDbl(tableend * 1000000H + else)
END GenCaseJump;
*)
PROCEDURE GenCaseEntry* (VAR L: Label; last: BOOLEAN);
VAR typ: INTEGER;
BEGIN
IF last THEN typ := tableend * 1000000H ELSE typ := table * 1000000H END;
IF L > 0 THEN GenDbl(L + typ) ELSE GenDbl(-L); L := -(DevCPE.pc - 4 + typ) END
END GenCaseEntry;
PROCEDURE GenCall* (VAR dst: Item);
BEGIN
IF dst.mode IN {LProc, XProc, IProc} THEN
DevCPE.GenByte(0E8H);
IF dst.obj.mnolev >= 0 THEN (* local *)
IF dst.obj.adr > 0 THEN GenDbl(dst.obj.adr - DevCPE.pc - 4)
ELSE GenDbl(-dst.obj.adr); dst.obj.adr := -(DevCPE.pc - 4 + relative * 1000000H)
END
ELSE (* imported *)
dst.offset := 0; GenLinked(dst, relative)
END
ELSE DevCPE.GenByte(0FFH); GenCExt(10H, dst)
END;
a1.mode := 0; a2.mode := 0
END GenCall;
PROCEDURE GenAssert* (cc, no: INTEGER);
BEGIN
IF cc # ccAlways THEN
IF cc >= 0 THEN
DevCPE.GenByte(70H + cc); (* jcc end *)
IF no < 0 THEN DevCPE.GenByte(2) ELSE DevCPE.GenByte(3) END
END;
IF no < 0 THEN
DevCPE.GenByte(8DH); DevCPE.GenByte(0E0H - no)
ELSE
DevCPE.GenByte(8DH); DevCPE.GenByte(0F0H); DevCPE.GenByte(no)
END
END
END GenAssert;
PROCEDURE GenReturn* (val: INTEGER);
BEGIN
IF val = 0 THEN DevCPE.GenByte(0C3H)
ELSE DevCPE.GenByte(0C2H); GenWord(val)
END;
a1.mode := 0; a2.mode := 0
END GenReturn;
PROCEDURE LoadStr (size: INTEGER);
BEGIN
IF size = 2 THEN DevCPE.GenByte(66H) END;
IF size <= 1 THEN DevCPE.GenByte(0ACH) ELSE DevCPE.GenByte(0ADH) END (* lods *)
END LoadStr;
PROCEDURE StoreStr (size: INTEGER);
BEGIN
IF size = 2 THEN DevCPE.GenByte(66H) END;
IF size <= 1 THEN DevCPE.GenByte(0AAH) ELSE DevCPE.GenByte(0ABH) END (* stos *)
END StoreStr;
PROCEDURE ScanStr (size: INTEGER; rep: BOOLEAN);
BEGIN
IF size = 2 THEN DevCPE.GenByte(66H) END;
IF rep THEN DevCPE.GenByte(0F2H) END;
IF size <= 1 THEN DevCPE.GenByte(0AEH) ELSE DevCPE.GenByte(0AFH) END (* scas *)
END ScanStr;
PROCEDURE TestNull (size: INTEGER);
BEGIN
IF size = 2 THEN DevCPE.GenByte(66H) END;
IF size <= 1 THEN DevCPE.GenByte(8); DevCPE.GenByte(0C0H); (* or al,al *)
ELSE DevCPE.GenByte(9); DevCPE.GenByte(0C0H); (* or ax,ax *)
END
END TestNull;
PROCEDURE GenBlockMove* (wsize, len: INTEGER); (* len = 0: len in ECX *)
VAR w: INTEGER;
BEGIN
IF len = 0 THEN (* variable size move *)
IF wsize = 4 THEN w := 1 ELSIF wsize = 2 THEN w := 1; DevCPE.GenByte(66H) ELSE w := 0 END;
DevCPE.GenByte(0F3H); DevCPE.GenByte(0A4H + w); (* rep:movs *)
ELSE (* fixed size move *)
len := len * wsize;
IF len >= 16 THEN
DevCPE.GenByte(0B9H); GenDbl(len DIV 4); (* ld ecx,len/4 *)
DevCPE.GenByte(0F3H); DevCPE.GenByte(0A5H); (* rep:movs long*)
len := len MOD 4
END;
WHILE len >= 4 DO DevCPE.GenByte(0A5H); DEC(len, 4) END; (* movs long *);
IF len >= 2 THEN DevCPE.GenByte(66H); DevCPE.GenByte(0A5H) END; (* movs word *);
IF ODD(len) THEN DevCPE.GenByte(0A4H) END; (* movs byte *)
END
END GenBlockMove;
PROCEDURE GenBlockStore* (wsize, len: INTEGER); (* len = 0: len in ECX *)
VAR w: INTEGER;
BEGIN
IF len = 0 THEN (* variable size move *)
IF wsize = 4 THEN w := 1 ELSIF wsize = 2 THEN w := 1; DevCPE.GenByte(66H) ELSE w := 0 END;
DevCPE.GenByte(0F3H); DevCPE.GenByte(0AAH + w); (* rep:stos *)
ELSE (* fixed size move *)
len := len * wsize;
IF len >= 16 THEN
DevCPE.GenByte(0B9H); GenDbl(len DIV 4); (* ld ecx,len/4 *)
DevCPE.GenByte(0F3H); DevCPE.GenByte(0ABH); (* rep:stos long*)
len := len MOD 4
END;
WHILE len >= 4 DO DevCPE.GenByte(0ABH); DEC(len, 4) END; (* stos long *);
IF len >= 2 THEN DevCPE.GenByte(66H); DevCPE.GenByte(0ABH) END; (* stos word *);
IF ODD(len) THEN DevCPE.GenByte(0ABH) END; (* stos byte *)
END
END GenBlockStore;
PROCEDURE GenBlockComp* (wsize, len: INTEGER); (* len = 0: len in ECX *)
VAR w: INTEGER;
BEGIN
ASSERT(len >= 0);
IF len > 0 THEN DevCPE.GenByte(0B9H); GenDbl(len) END; (* ld ecx,len *)
IF wsize = 4 THEN w := 1 ELSIF wsize = 2 THEN w := 1; DevCPE.GenByte(66H) ELSE w := 0 END;
DevCPE.GenByte(0F3H); DevCPE.GenByte(0A6H + w) (* repe:cmps *)
END GenBlockComp;
PROCEDURE GenStringMove* (excl: BOOLEAN; wsize, dsize, len: INTEGER);
(*
len = 0: len in ECX, len = -1: len undefined; wsize # dsize -> convert; size = 0: opsize = 1, incsize = 2; excl: don't move 0X
*)
VAR loop, end: Label;
BEGIN
IF len > 0 THEN DevCPE.GenByte(0B9H); GenDbl(len) END; (* ld ecx,len *)
(* len >= 0: len IN ECX *)
IF (dsize = 2) & (wsize < 2) THEN DevCPE.GenByte(31H); DevCPE.GenByte(0C0H) END; (* xor eax,eax *)
loop := NewLbl; end := NewLbl;
SetLabel(loop); LoadStr(wsize);
IF wsize = 0 THEN DevCPE.GenByte(46H) END; (* inc esi *)
IF len < 0 THEN (* no limit *)
StoreStr(dsize); TestNull(wsize); GenJump(ccNE, loop, TRUE);
IF excl THEN (* dec edi *)
DevCPE.GenByte(4FH);
IF dsize # 1 THEN DevCPE.GenByte(4FH) END
END;
ELSE (* cx limit *)
IF excl THEN TestNull(wsize); GenJump(ccE, end, TRUE); StoreStr(dsize)
ELSE StoreStr(dsize); TestNull(wsize); GenJump(ccE, end, TRUE)
END;
DevCPE.GenByte(49H); (* dec ecx *)
GenJump(ccNE, loop, TRUE);
GenAssert(ccNever, copyTrap); (* trap *)
SetLabel(end)
END;
a1.mode := 0; a2.mode := 0
END GenStringMove;
PROCEDURE GenStringComp* (wsize, dsize: INTEGER);
(* wsize # dsize -> convert; size = 0: opsize = 1, incsize = 2; *)
VAR loop, end: Label;
BEGIN
IF (dsize = 2) & (wsize < 2) THEN DevCPE.GenByte(31H); DevCPE.GenByte(0C0H); (* xor eax,eax *) END;
loop := NewLbl; end := NewLbl;
SetLabel(loop); LoadStr(wsize);
IF wsize = 0 THEN DevCPE.GenByte(46H) END; (* inc esi *)
ScanStr(dsize, FALSE); GenJump(ccNE, end, TRUE);
IF dsize = 0 THEN DevCPE.GenByte(47H) END; (* inc edi *)
TestNull(wsize); GenJump(ccNE, loop, TRUE);
SetLabel(end);
a1.mode := 0; a2.mode := 0
END GenStringComp;
PROCEDURE GenStringLength* (wsize, len: INTEGER); (* len = 0: len in ECX, len = -1: len undefined *)
BEGIN
DevCPE.GenByte(31H); DevCPE.GenByte(0C0H); (* xor eax,eax *)
IF len # 0 THEN DevCPE.GenByte(0B9H); GenDbl(len) END; (* ld ecx,len *)
ScanStr(wsize, TRUE);
a1.mode := 0; a2.mode := 0
END GenStringLength;
PROCEDURE GenStrStore* (size: INTEGER);
VAR w: INTEGER;
BEGIN
IF size # 0 THEN
IF size MOD 4 = 0 THEN w := 1; size := size DIV 4
ELSIF size MOD 2 = 0 THEN w := 2; size := size DIV 2
ELSE w := 0
END;
DevCPE.GenByte(0B9H); GenDbl(size); (* ld ecx,size *)
IF w = 2 THEN DevCPE.GenByte(66H); w := 1 END
ELSE w := 0
END;
DevCPE.GenByte(0F3H); DevCPE.GenByte(0AAH + w); (* rep:stos *)
a1.mode := 0; a2.mode := 0
END GenStrStore;
PROCEDURE GenCode* (op: INTEGER);
BEGIN
DevCPE.GenByte(op);
a1.mode := 0; a2.mode := 0
END GenCode;
PROCEDURE Init*(opt: SET);
BEGIN
DevCPE.Init(processor, opt);
level := 0;
NEW(one); one.realval := 1.0; one.intval := DevCPM.ConstNotAlloc;
END Init;
PROCEDURE Close*;
BEGIN
a1.obj := NIL; a1.typ := NIL; a2.obj := NIL; a2.typ := NIL; one := NIL;
DevCPE.Close
END Close;
BEGIN
Size[Undef] := 0;
Size[Byte] := 1;
Size[Bool] := 1;
Size[Char8] := 1;
Size[Int8] := 1;
Size[Int16] := 2;
Size[Int32] := 4;
Size[Real32] := -4;
Size[Real64] := -8;
Size[Set] := 4;
Size[String8] := 0;
Size[NilTyp] := 4;
Size[NoTyp] := 0;
Size[Pointer] := 4;
Size[ProcTyp] := 4;
Size[Comp] := 0;
Size[Char16] := 2;
Size[Int64] := 8;
Size[String16] := 0
END DevCPL486.
| Dev/Mod/CPL486.odc |
MODULE DevCPM;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, A.A. Dmitriev, I.A. Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, GetL added (Unicode support)
- 20070123, bh, MaxStruct increased
- 20070123, bh, support for procedure type sysflags
- 20070224, bh, fingerprints changed to CRC32
- 20080208, bh, file checksum for symbol files
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20160324, center #111, code cleanups
- 20170215, center #139, localization support for error messages
- 20170612, center #160, outdated link to OP2.Paper.ps
- 20170811, luowy, support for 16 bit aligment "ccall16"
- 2021, ad, use of StdLibrarian
- 20230103, dia, remove code, sym and system dirs
"
issues = "
- ...
"
**)
IMPORT SYSTEM, Files, Stores, Models, TextModels, StdLog, DevMarkers, Dialog, Utf, Librarian;
CONST
ProcSize* = 4; (* PROCEDURE type *)
PointerSize* = 4; (* POINTER type *)
DArrSizeA* = 8; (* dyn array descriptor *)
DArrSizeB* = 4; (* size = A + B * typ.n *)
MaxSet* = 31;
MaxIndex* = 7FFFFFFFH; (* maximal index value for array declaration *)
MinReal32Pat = 0FF7FFFFFH; (* most positive, 32-bit pattern *)
MinReal64PatL = 0FFFFFFFFH; (* most negative, lower 32-bit pattern *)
MinReal64PatH = 0FFEFFFFFH; (* most negative, higher 32-bit pattern *)
MaxReal32Pat = 07F7FFFFFH; (* most positive, 32-bit pattern *)
MaxReal64PatL = 0FFFFFFFFH; (* most positive, lower 32-bit pattern *)
MaxReal64PatH = 07FEFFFFFH; (* most positive, higher 32-bit pattern *)
InfRealPat = 07F800000H; (* real infinity pattern *)
(* inclusive range of parameter of standard procedure HALT *)
MinHaltNr* = 0;
MaxHaltNr* = 128;
(* inclusive range of register number of procedures SYSTEM.GETREG and SYSTEM.PUTREG *)
MinRegNr* = 0;
MaxRegNr* = 31;
(* maximal value of flag used to mark interface structures *)
MaxSysFlag* = 127; (* shortint *)
CProcFlag* = 1; (* code procedures *)
(* maximal condition value of parameter of SYSTEM.CC *)
MaxCC* = 15;
(* initialization of constant address, must be different from any valid constant address *)
ConstNotAlloc* = -1;
(* whether hidden pointer fields have to be nevertheless exported *)
ExpHdPtrFld* = TRUE;
HdPtrName* = "@ptr";
(* whether hidden untagged pointer fields have to be nevertheless exported *)
ExpHdUtPtrFld* = TRUE;
HdUtPtrName* = "@utptr";
(* whether hidden procedure fields have to be nevertheless exported (may be used for System.Free) *)
ExpHdProcFld* = TRUE;
HdProcName* = "@proc";
(* whether hidden bound procedures have to be nevertheless exported *)
ExpHdTProc* = FALSE;
HdTProcName* = "@tproc";
(* maximal number of exported stuctures: *)
MaxStruct* = 16000; (* must be < MAX(INTEGER) DIV 2 in object model *)
(* maximal number of record extensions: *)
MaxExts* = 15; (* defined by type descriptor layout *)
(* whether field leaf of pointer variable p has to be set to FALSE, when NEW(p) or SYSTEM.NEW(p, n) is used *)
NEWusingAdr* = FALSE;
(* special character (< " ") returned by procedure Get, if end of text reached *)
Eot* = 0X;
(* warnings *)
longreal* = 0; largeint* = 1; realConst* = 2; copy* = 3; lchr* = 4; lentier* = 5; invar* = 6; outvar* = 7;
(* language options *)
interface* = 1;
com* = 2; comAware* = 3;
som* = 4; somAware* = 5;
oberon* = 6;
java* = 7; javaAware* = 8;
noCode* = 9;
allSysVal* = 14;
sysImp* = 15;
trap* = 31;
sys386 = 10; sys68k = 20; (* processor type in options if system imported *)
cacheLineSize* = 64;
CONST
SFtag = 6F4F5346H; (* symbol file tag *)
OFtag = 6F4F4346H; (* object file tag *)
maxErrors = 64;
VAR
LEHost*: BOOLEAN; (* little or big endian host *)
MinReal32*, MaxReal32*, InfReal*,
MinReal64*, MaxReal64*: REAL;
noerr*: BOOLEAN; (* no error found until now *)
curpos*, startpos*, errpos*: INTEGER; (* character, start, and error position in source file *)
searchpos*: INTEGER; (* search position in source file *)
errors*: INTEGER;
breakpc*: INTEGER; (* set by OPV.Init *)
options*: SET; (* language options *)
file*: Files.File; (* used for sym file import *)
checksum*: INTEGER; (* symbol file checksum *)
lastpos: INTEGER;
ObjFName: Files.Name;
SymFName: Files.Name;
in: TextModels.Reader;
oldSymFile, symFile, objFile: Files.File;
inSym: Files.Reader;
outSym, outObj: Files.Writer;
errNo, errPos: ARRAY maxErrors OF INTEGER;
lineReader: TextModels.Reader;
lineNum: INTEGER;
crc32tab: ARRAY 256 OF INTEGER;
ask*: BOOLEAN; (* ask create folders for symbol and code files *)
PROCEDURE^ err* (n: INTEGER);
PROCEDURE Init* (source: TextModels.Reader; logtext_: TextModels.Model);
BEGIN
in := source;
DevMarkers.Unmark(in.Base());
noerr := TRUE; options := {};
curpos := in.Pos(); errpos := curpos; lastpos := curpos - 11; errors := 0;
END Init;
PROCEDURE Close*;
BEGIN
oldSymFile := NIL; inSym := NIL;
symFile := NIL; outSym := NIL;
objFile := NIL; outObj := NIL;
in := NIL; lineReader := NIL
END Close;
PROCEDURE Get* (VAR ch: CHAR);
BEGIN
REPEAT in.ReadChar(ch); INC(curpos) UNTIL ch # TextModels.viewcode;
END Get;
PROCEDURE LineOf* (pos: INTEGER): INTEGER;
VAR ch: CHAR;
BEGIN
IF lineReader = NIL THEN lineReader := in.Base().NewReader(NIL); lineReader.SetPos(0); lineNum := 0 END;
IF lineReader.Pos() > pos THEN lineReader.SetPos(0); lineNum := 0 END;
WHILE lineReader.Pos() < pos DO
lineReader.ReadChar(ch);
IF ch = 0DX THEN INC(lineNum) END
END;
RETURN lineNum
END LineOf;
PROCEDURE LoWord (r: REAL): INTEGER;
VAR x: INTEGER;
BEGIN
x := SYSTEM.ADR(r);
IF ~LEHost THEN INC(x, 4) END;
SYSTEM.GET(x, x);
RETURN x
END LoWord;
PROCEDURE HiWord (r: REAL): INTEGER;
VAR x: INTEGER;
BEGIN
x := SYSTEM.ADR(r);
IF LEHost THEN INC(x, 4) END;
SYSTEM.GET(x, x);
RETURN x
END HiWord;
PROCEDURE Compound (lo, hi: INTEGER): REAL;
VAR r: REAL;
BEGIN
IF LEHost THEN
SYSTEM.PUT(SYSTEM.ADR(r), lo); SYSTEM.PUT(SYSTEM.ADR(r) + 4, hi)
ELSE
SYSTEM.PUT(SYSTEM.ADR(r) + 4, lo); SYSTEM.PUT(SYSTEM.ADR(r), hi)
END;
RETURN r
END Compound;
(* sysflag control *)
PROCEDURE ValidGuid* (IN str: ARRAY OF SHORTCHAR): BOOLEAN;
VAR i: INTEGER; ch: SHORTCHAR;
BEGIN
IF (LEN(str$) # 38) OR (str[0] # "{") & (str[37] # "}") THEN RETURN FALSE END;
i := 1;
WHILE i < 37 DO
ch := str[i];
IF (i = 9) OR (i = 14) OR (i = 19) OR (i = 24) THEN
IF ch # "-" THEN RETURN FALSE END
ELSE
IF (ch < "0") OR (ch > "9") & (CAP(ch) < "A") OR (CAP(ch) > "Z") THEN
RETURN FALSE
END
END;
INC(i)
END;
RETURN TRUE
END ValidGuid;
PROCEDURE GetProcSysFlag* (IN id: ARRAY OF SHORTCHAR; num: SHORTINT; VAR flag: SHORTINT);
BEGIN
IF id # "" THEN
IF id = "code" THEN num := 1
ELSIF id = "callback" THEN num := 2
ELSIF id = "nostkchk" THEN num := 4
ELSIF id = "ccall" THEN num := -10
ELSIF id = "ccall16" THEN num := -12
ELSIF id = "guarded" THEN num := 8
ELSIF id = "noframe" THEN num := 16
ELSIF id = "native" THEN num := -33
ELSIF id = "bytecode" THEN num := -35
END
END;
IF (options * {sysImp, sys386, sys68k} # {}) & ((num = 1) OR (num = 2)) THEN INC(flag, num)
ELSIF (sys68k IN options) & (num = 4) THEN INC(flag, num)
ELSIF (options * {sys386, interface} # {}) & (num = -10) & (flag = 0) THEN flag := -10
ELSIF (options * {sys386, interface} # {}) & (num = -12) & (flag = 0) THEN flag := -12
ELSIF (options * {sys386, com} # {}) & (num = 8) & (flag = 0) THEN flag := 8
ELSIF (options * {sysImp, sys386} # {}) & (num = 16) & (flag = 0) THEN flag := 16
ELSIF ({sysImp, java} - options = {}) & ((num= -33) OR (num = -35)) & (flag = 0) THEN flag := num
ELSE err(225); flag := 0
END
END GetProcSysFlag;
PROCEDURE GetVarParSysFlag* (IN id: ARRAY OF SHORTCHAR; num: SHORTINT; VAR flag: SHORTINT);
VAR old: SHORTINT;
BEGIN
old := flag; flag := 0;
IF (options * {sys386, sys68k, interface, com} # {}) THEN
IF (num = 1) OR (id = "nil") THEN
IF ~ODD(old) THEN flag := SHORT(old + 1) END
ELSIF ((num = 2) OR (id = "in")) & (oberon IN options) THEN
IF old <= 1 THEN flag := SHORT(old + 2) END
ELSIF ((num = 4) OR (id = "out")) & (oberon IN options) THEN
IF old <= 1 THEN flag := SHORT(old + 4) END
ELSIF ((num = 8) OR (id = "new")) & (options * {com, interface} # {}) THEN
IF old <= 1 THEN flag := SHORT(old + 8) END
ELSIF ((num = 16) OR (id = "iid")) & (com IN options) THEN
IF old <= 1 THEN flag := SHORT(old + 16) END
END
END;
IF flag = 0 THEN err(225) END
END GetVarParSysFlag;
PROCEDURE GetRecordSysFlag* (IN id: ARRAY OF SHORTCHAR; num: SHORTINT; VAR flag: SHORTINT);
VAR old: SHORTINT;
BEGIN
old := flag; flag := 0;
IF (num = 1) OR (id = "untagged") THEN
IF (options * {sysImp, sys386, sys68k, interface, com, som} # {}) & (old = 0) THEN flag := 1 END
ELSIF (num = 3) OR (id = "noalign") THEN
IF (options * {sys386, sys68k, interface, com, som} # {}) & (old = 0) THEN flag := 3 END
ELSIF (num = 4) OR (id = "align2") THEN
IF (options * {sys386, interface, com} # {}) & (old = 0) THEN flag := 4 END
ELSIF (num = 5) OR (id = "align4") THEN
IF (options * {sys386, interface, com} # {}) & (old = 0) THEN flag := 5 END
ELSIF (num = 6) OR (id = "align8") THEN
IF (options * {sys386, interface, com} # {}) & (old = 0) THEN flag := 6 END
ELSIF (num = 7) OR (id = "union") THEN
IF (options * {sys386, sys68k, interface, com} # {}) & (old = 0) THEN flag := 7 END
ELSIF (num = 10) OR (id = "interface") OR ValidGuid(id) THEN
IF (com IN options) & (old = 0) THEN flag := 10 END
ELSIF (num = -11) OR (id = "jint") THEN
IF (java IN options) & (old = 0) THEN flag := -11 END
ELSIF (num = -13) OR (id = "jstr") THEN
IF (java IN options) & (old = 0) THEN flag := -13 END
ELSIF (num = 20) OR (id = "som") THEN
IF (som IN options) & (old = 0) THEN flag := 20 END
END;
IF flag = 0 THEN err(225) END
END GetRecordSysFlag;
PROCEDURE GetArraySysFlag* (IN id: ARRAY OF SHORTCHAR; num: SHORTINT; VAR flag: SHORTINT);
VAR old: SHORTINT;
BEGIN
old := flag; flag := 0;
IF (num = 1) OR (id = "untagged") THEN
IF (options * {sysImp, sys386, sys68k, interface, com, som} # {}) & (old = 0) THEN flag := 1 END
ELSIF (num = 8) OR (id = "align16") THEN
IF (options * {sysImp, sys386, sys68k, interface, com, som} # {}) & (old = 0) THEN flag := 8 END
ELSIF (num = -12) OR (id = "jarr") THEN
IF (java IN options) & (old = 0) THEN flag := -12 END
ELSIF (num = -13) OR (id = "jstr") THEN
IF (java IN options) & (old = 0) THEN flag := -13 END
END;
IF flag = 0 THEN err(225) END
END GetArraySysFlag;
PROCEDURE GetPointerSysFlag* (IN id: ARRAY OF SHORTCHAR; num: SHORTINT; VAR flag: SHORTINT);
VAR old: SHORTINT;
BEGIN
old := flag; flag := 0;
IF (num = 1) OR (id = "untagged") THEN
IF (options * {sys386, sys68k, interface, com, som} # {}) & (old = 0) THEN flag := 1 END
ELSIF (num = 2) OR (id = "handle") THEN
IF (sys68k IN options) & (old = 0) THEN flag := 2 END
ELSIF (num = 10) OR (id = "interface") THEN
IF (com IN options) & (old = 0) THEN flag := 10 END
ELSIF (num = 20) OR (id = "som") THEN
IF (som IN options) & (old = 0) THEN flag := 20 END
END;
IF flag = 0 THEN err(225) END
END GetPointerSysFlag;
PROCEDURE GetProcTypSysFlag* (IN id: ARRAY OF SHORTCHAR; num: SHORTINT; VAR flag: SHORTINT);
BEGIN
IF ((num = -10) OR (id = "ccall")) & (options * {sys386, interface} # {}) THEN flag := -10
ELSIF ((num = -12) OR (id = "ccall16")) & (options * {sys386, interface} # {}) THEN flag := -12
ELSE err(225); flag := 0
END
END GetProcTypSysFlag;
PROCEDURE PropagateRecordSysFlag* (baseFlag: SHORTINT; VAR flag: SHORTINT);
BEGIN
IF (baseFlag = 1) OR (baseFlag >= 3) & (baseFlag <= 7) THEN (* propagate untagged .. union *)
IF flag = 0 THEN flag := baseFlag
ELSIF (flag = 6) & (baseFlag < 6) THEN (* OK *) (* special case for 8 byte aligned records *)
ELSIF flag # baseFlag THEN err(225); flag := 0
END
ELSIF (baseFlag # 10) & (flag = 10) THEN err(225)
END
END PropagateRecordSysFlag;
PROCEDURE PropagateRecPtrSysFlag* (baseFlag: SHORTINT; VAR flag: SHORTINT);
BEGIN
IF (baseFlag = 1) OR (baseFlag >= 3) & (baseFlag <= 7) THEN (* pointer to untagged .. union is untagged *)
IF flag = 0 THEN flag := 1
ELSIF (flag # 1) & (flag # 2) THEN err(225); flag := 0
END
ELSIF baseFlag = 10 THEN (* pointer to interface is interface *)
IF flag = 0 THEN flag := 10
ELSIF flag # 10 THEN err(225); flag := 0
END
ELSIF baseFlag = -11 THEN (* pointer to java interface is java interface *)
IF flag # 0 THEN err(225) END;
flag := -11
ELSIF baseFlag = -13 THEN (* pointer to java string is java string *)
IF flag # 0 THEN err(225) END;
flag := -13
END
END PropagateRecPtrSysFlag;
PROCEDURE PropagateArrPtrSysFlag* (baseFlag: SHORTINT; VAR flag: SHORTINT);
BEGIN
IF baseFlag = 1 THEN (* pointer to untagged or guid is untagged *)
IF flag = 0 THEN flag := 1
ELSIF (flag # 1) & (flag # 2) THEN err(225); flag := 0
END
ELSIF baseFlag = -12 THEN (* pointer to java array is java array *)
IF flag # 0 THEN err(225) END;
flag := -12
ELSIF baseFlag = -13 THEN (* pointer to java string is java string *)
IF flag # 0 THEN err(225) END;
flag := -13
END
END PropagateArrPtrSysFlag;
(* utf8 strings *)
PROCEDURE PutUtf8* (VAR str: ARRAY OF SHORTCHAR; val: INTEGER; VAR idx: INTEGER);
BEGIN
ASSERT((val >= 0) & (val < 65536));
IF val < 128 THEN
str[idx] := SHORT(CHR(val)); INC(idx)
ELSIF val < 2048 THEN
str[idx] := SHORT(CHR(val DIV 64 + 192)); INC(idx);
str[idx] := SHORT(CHR(val MOD 64 + 128)); INC(idx)
ELSE
str[idx] := SHORT(CHR(val DIV 4096 + 224)); INC(idx);
str[idx] := SHORT(CHR(val DIV 64 MOD 64 + 128)); INC(idx);
str[idx] := SHORT(CHR(val MOD 64 + 128)); INC(idx)
END
END PutUtf8;
PROCEDURE GetUtf8* (IN str: ARRAY OF SHORTCHAR; VAR val, idx: INTEGER);
VAR ch: SHORTCHAR;
BEGIN
ch := str[idx]; INC(idx);
IF ch < 80X THEN
val := ORD(ch)
ELSIF ch < 0E0X THEN
val := ORD(ch) - 192;
ch := str[idx]; INC(idx); val := val * 64 + ORD(ch) - 128
ELSE
val := ORD(ch) - 224;
ch := str[idx]; INC(idx); val := val * 64 + ORD(ch) - 128;
ch := str[idx]; INC(idx); val := val * 64 + ORD(ch) - 128
END
END GetUtf8;
(* log output *)
PROCEDURE LogW* (ch: CHAR);
BEGIN
StdLog.Char(ch)
END LogW;
PROCEDURE LogWStr* (IN s: ARRAY OF CHAR);
BEGIN
StdLog.String(s)
END LogWStr;
PROCEDURE LogWPar* (IN key: ARRAY OF CHAR; IN p0, p1: ARRAY OF SHORTCHAR);
VAR s0, s1, s: Dialog.String; res: INTEGER;
BEGIN
Utf.Utf8ToString(p0, s0, res);
Utf.Utf8ToString(p1, s1, res);
Dialog.MapParamString(key, s0, s1, "", s);
StdLog.String(s)
END LogWPar;
PROCEDURE LogWNum* (i, len: INTEGER);
BEGIN
StdLog.Int(i)
END LogWNum;
PROCEDURE LogWLn*;
BEGIN
StdLog.Ln
END LogWLn;
(*
PROCEDURE LogW* (ch: CHAR);
BEGIN
out.WriteChar(ch);
END LogW;
PROCEDURE LogWStr* (s: ARRAY OF CHAR);
BEGIN
out.WriteString(s);
END LogWStr;
PROCEDURE LogWNum* (i, len: LONGINT);
BEGIN
out.WriteChar(" "); out.WriteInt(i);
END LogWNum;
PROCEDURE LogWLn*;
BEGIN
out.WriteLn;
Views.RestoreDomain(logbuf.Domain())
END LogWLn;
*)
PROCEDURE Mark* (n, pos: INTEGER);
BEGIN
IF (n >= 0) & ~((oberon IN options) & (n >= 181) & (n <= 190)) THEN
noerr := FALSE;
IF pos < 0 THEN pos := 0 END;
IF (pos < lastpos) OR (lastpos + 9 < pos) THEN
lastpos := pos;
IF errors < maxErrors THEN
errNo[errors] := n; errPos[errors] := pos
END;
INC(errors)
END;
IF trap IN options THEN HALT(100) END;
ELSIF (n <= -700) & (errors < maxErrors) THEN
errNo[errors] := -n; errPos[errors] := pos; INC(errors)
END
END Mark;
PROCEDURE err* (n: INTEGER);
BEGIN
Mark(n, errpos)
END err;
PROCEDURE InsertMarks* (text: TextModels.Model);
VAR i, j, x, y, n: INTEGER; script: Stores.Operation;
BEGIN
n := errors;
IF n > maxErrors THEN n := maxErrors END;
(* sort *)
i := 1;
WHILE i < n DO
x := errPos[i]; y := errNo[i]; j := i-1;
WHILE (j >= 0) & (errPos[j] > x) DO errPos[j+1] := errPos[j]; errNo[j+1] := errNo[j]; DEC(j) END;
errPos[j+1] := x; errNo[j+1] := y; INC(i)
END;
(* insert *)
Models.BeginModification(Models.clean, text);
Models.BeginScript(text, "#Dev:InsertMarkers", script);
WHILE n > 0 DO DEC(n);
DevMarkers.Insert(text, errPos[n], DevMarkers.dir.New(errNo[n]))
END;
Models.EndScript(text, script);
Models.EndModification(Models.clean, text);
END InsertMarks;
(* fingerprinting *)
PROCEDURE InitCrcTab;
(* CRC32, high bit first, pre & post inverted *)
CONST poly = {0, 1, 2, 4, 5, 7, 8, 10, 11, 12, 16, 22, 23, 26}; (* CRC32 polynom *)
VAR x, c, i: INTEGER;
BEGIN
x := 0;
WHILE x < 256 DO
c := x * 1000000H; i := 0;
WHILE i < 8 DO
IF c < 0 THEN c := ORD(BITS(c * 2) / poly)
ELSE c := c * 2
END;
INC(i)
END;
crc32tab[ORD(BITS(x) / BITS(255))] := ORD(BITS(c) / BITS(255));
INC(x)
END
END InitCrcTab;
PROCEDURE FPrint* (VAR fp: INTEGER; val: INTEGER);
VAR c: INTEGER;
BEGIN
(*
fp := SYSTEM.ROT(ORD(BITS(fp) / BITS(val)), 1) (* bad collision detection *)
*)
(* CRC32, high bit first, pre & post inverted *)
c := ORD(BITS(fp * 256) / BITS(crc32tab[ORD(BITS(fp DIV 1000000H) / BITS(val DIV 1000000H)) MOD 256]));
c := ORD(BITS(c * 256) / BITS(crc32tab[ORD(BITS(c DIV 1000000H) / BITS(val DIV 10000H)) MOD 256]));
c := ORD(BITS(c * 256) / BITS(crc32tab[ORD(BITS(c DIV 1000000H) / BITS(val DIV 100H)) MOD 256]));
fp := ORD(BITS(c * 256) / BITS(crc32tab[ORD(BITS(c DIV 1000000H) / BITS(val)) MOD 256]));
END FPrint;
PROCEDURE FPrintSet* (VAR fp: INTEGER; set: SET);
BEGIN FPrint(fp, ORD(set))
END FPrintSet;
PROCEDURE FPrintReal* (VAR fp: INTEGER; real: SHORTREAL);
BEGIN FPrint(fp, SYSTEM.VAL(INTEGER, real))
END FPrintReal;
PROCEDURE FPrintLReal* (VAR fp: INTEGER; lr: REAL);
BEGIN
FPrint(fp, LoWord(lr)); FPrint(fp, HiWord(lr))
END FPrintLReal;
PROCEDURE ChkSum (VAR fp: INTEGER; val: INTEGER); (* symbolfile checksum *)
BEGIN
(* same as FPrint, 8 bit only *)
fp := ORD(BITS(fp * 256) / BITS(crc32tab[ORD(BITS(fp DIV 1000000H) / BITS(val)) MOD 256]))
END ChkSum;
(* compact format *)
PROCEDURE WriteLInt (w: Files.Writer; i: INTEGER);
BEGIN
ChkSum(checksum, i);
w.WriteByte(SHORT(SHORT(i MOD 256))); i := i DIV 256;
ChkSum(checksum, i);
w.WriteByte(SHORT(SHORT(i MOD 256))); i := i DIV 256;
ChkSum(checksum, i);
w.WriteByte(SHORT(SHORT(i MOD 256))); i := i DIV 256;
ChkSum(checksum, i);
w.WriteByte(SHORT(SHORT(i MOD 256)))
END WriteLInt;
PROCEDURE ReadLInt (r: Files.Reader; VAR i: INTEGER);
VAR b: BYTE; x: INTEGER;
BEGIN
r.ReadByte(b); x := b MOD 256;
ChkSum(checksum, b);
r.ReadByte(b); x := x + 100H * (b MOD 256);
ChkSum(checksum, b);
r.ReadByte(b); x := x + 10000H * (b MOD 256);
ChkSum(checksum, b);
r.ReadByte(b); i := x + 1000000H * b;
ChkSum(checksum, b)
END ReadLInt;
PROCEDURE WriteNum (w: Files.Writer; i: INTEGER);
BEGIN (* old format of Oberon *)
WHILE (i < -64) OR (i > 63) DO ChkSum(checksum, i MOD 128 - 128); w.WriteByte(SHORT(SHORT(i MOD 128 - 128))); i := i DIV 128 END;
ChkSum(checksum, i MOD 128);
w.WriteByte(SHORT(SHORT(i MOD 128)))
END WriteNum;
PROCEDURE ReadNum (r: Files.Reader; VAR i: INTEGER);
VAR b: BYTE; s, y: INTEGER;
BEGIN
s := 0; y := 0; r.ReadByte(b);
IF ~r.eof THEN ChkSum(checksum, b) END;
WHILE b < 0 DO INC(y, ASH(b + 128, s)); INC(s, 7); r.ReadByte(b); ChkSum(checksum, b) END;
i := ASH((b + 64) MOD 128 - 64, s) + y;
END ReadNum;
PROCEDURE WriteNumSet (w: Files.Writer; x: SET);
BEGIN
WriteNum(w, ORD(x))
END WriteNumSet;
PROCEDURE ReadNumSet (r: Files.Reader; VAR x: SET);
VAR i: INTEGER;
BEGIN
ReadNum(r, i); x := BITS(i)
END ReadNumSet;
PROCEDURE WriteReal (w: Files.Writer; x: SHORTREAL);
BEGIN
WriteLInt(w, SYSTEM.VAL(INTEGER, x))
END WriteReal;
PROCEDURE ReadReal (r: Files.Reader; VAR x: SHORTREAL);
VAR i: INTEGER;
BEGIN
ReadLInt(r, i); x := SYSTEM.VAL(SHORTREAL, i)
END ReadReal;
PROCEDURE WriteLReal (w: Files.Writer; x: REAL);
BEGIN
WriteLInt(w, LoWord(x)); WriteLInt(w, HiWord(x))
END WriteLReal;
PROCEDURE ReadLReal (r: Files.Reader; VAR x: REAL);
VAR h, l: INTEGER;
BEGIN
ReadLInt(r, l); ReadLInt(r, h); x := Compound(l, h)
END ReadLReal;
(* read symbol file *)
PROCEDURE SymRCh* (VAR ch: SHORTCHAR);
VAR b: BYTE;
BEGIN
inSym.ReadByte(b); ch := SHORT(CHR(b));
ChkSum(checksum, b)
END SymRCh;
PROCEDURE SymRInt* (): INTEGER;
VAR k: INTEGER;
BEGIN
ReadNum(inSym, k); RETURN k
END SymRInt;
PROCEDURE SymRSet* (VAR s: SET);
BEGIN
ReadNumSet(inSym, s)
END SymRSet;
PROCEDURE SymRReal* (VAR r: SHORTREAL);
BEGIN
ReadReal(inSym, r)
END SymRReal;
PROCEDURE SymRLReal* (VAR lr: REAL);
BEGIN
ReadLReal(inSym, lr)
END SymRLReal;
PROCEDURE eofSF* (): BOOLEAN;
BEGIN
RETURN inSym.eof
END eofSF;
PROCEDURE OldSym* (IN modName: ARRAY OF SHORTCHAR; VAR done: BOOLEAN);
VAR tag, res: INTEGER; loc: Files.Locator; name: Files.Name;
BEGIN
done := FALSE;
IF modName = "@file" THEN
oldSymFile := file
ELSE
Utf.Utf8ToString(modName, name, res);
Librarian.lib.GetSpec(name, "Sym", loc, name);
oldSymFile := Files.dir.Old(loc, name, Files.shared);
END;
IF oldSymFile # NIL THEN
inSym := oldSymFile.NewReader(inSym);
IF inSym # NIL THEN
ReadLInt(inSym, tag);
IF tag = SFtag THEN done := TRUE ELSE err(151) END
END
END
END OldSym;
PROCEDURE CloseOldSym*;
BEGIN
IF oldSymFile # NIL THEN oldSymFile.Close; oldSymFile := NIL END
END CloseOldSym;
(* write symbol file *)
PROCEDURE SymWCh* (ch: SHORTCHAR);
BEGIN
ChkSum(checksum, ORD(ch));
outSym.WriteByte(SHORT(ORD(ch)))
END SymWCh;
PROCEDURE SymWInt* (i: INTEGER);
BEGIN
WriteNum(outSym, i)
END SymWInt;
PROCEDURE SymWSet* (s: SET);
BEGIN
WriteNumSet(outSym, s)
END SymWSet;
PROCEDURE SymWReal* (r: SHORTREAL);
BEGIN
WriteReal(outSym, r)
END SymWReal;
PROCEDURE SymWLReal* (r: REAL);
BEGIN
WriteLReal(outSym, r)
END SymWLReal;
PROCEDURE SymReset*;
BEGIN
outSym.SetPos(4)
END SymReset;
PROCEDURE NewSym* (IN modName: ARRAY OF SHORTCHAR);
VAR res: INTEGER; loc: Files.Locator; name: Files.Name;
BEGIN
Utf.Utf8ToString(modName, name, res);
Librarian.lib.GetSpec(name, "Sym", loc, SymFName);
symFile := Files.dir.New(loc, ask);
IF symFile # NIL THEN
outSym := symFile.NewWriter(NIL);
WriteLInt(outSym, SFtag)
ELSE
err(153)
END
END NewSym;
PROCEDURE RegisterNewSym*;
VAR res: INTEGER;
BEGIN
IF symFile # NIL THEN
symFile.Register(SymFName, "", Files.ask, res);
symFile := NIL
END
END RegisterNewSym;
PROCEDURE DeleteNewSym*;
BEGIN
IF symFile # NIL THEN symFile.Close; symFile := NIL END
END DeleteNewSym;
(* write object file *)
PROCEDURE ObjW* (ch: SHORTCHAR);
BEGIN
outObj.WriteByte(SHORT(ORD(ch)))
END ObjW;
PROCEDURE ObjWNum* (i: INTEGER);
BEGIN
WriteNum(outObj, i)
END ObjWNum;
PROCEDURE ObjWInt (i: SHORTINT);
BEGIN
outObj.WriteByte(SHORT(SHORT(i MOD 256)));
outObj.WriteByte(SHORT(SHORT(i DIV 256)))
END ObjWInt;
PROCEDURE ObjWLInt* (i: INTEGER);
BEGIN
ObjWInt(SHORT(i MOD 65536));
ObjWInt(SHORT(i DIV 65536))
END ObjWLInt;
PROCEDURE ObjWBytes* (IN bytes: ARRAY OF SHORTCHAR; n: INTEGER);
TYPE P = POINTER TO ARRAY [untagged] 100000H OF BYTE;
VAR p: P;
BEGIN
p := SYSTEM.VAL(P, SYSTEM.ADR(bytes));
outObj.WriteBytes(p^, 0, n)
END ObjWBytes;
PROCEDURE ObjLen* (): INTEGER;
BEGIN
RETURN outObj.Pos()
END ObjLen;
PROCEDURE ObjSet* (pos: INTEGER);
BEGIN
outObj.SetPos(pos)
END ObjSet;
PROCEDURE NewObj* (IN modName: ARRAY OF SHORTCHAR);
VAR res: INTEGER; loc: Files.Locator; name: Files.Name;
BEGIN
errpos := 0;
Utf.Utf8ToString(modName, name, res);
Librarian.lib.GetSpec(name, "Code", loc, ObjFName);
objFile := Files.dir.New(loc, ask);
IF objFile # NIL THEN
outObj := objFile.NewWriter(NIL);
WriteLInt(outObj, OFtag)
ELSE
err(153)
END
END NewObj;
PROCEDURE RegisterObj*;
VAR res: INTEGER;
BEGIN
IF objFile # NIL THEN
objFile.Register(ObjFName, "", Files.ask, res);
objFile := NIL; outObj := NIL
END
END RegisterObj;
PROCEDURE DeleteObj*;
BEGIN
IF objFile # NIL THEN objFile.Close; objFile := NIL END
END DeleteObj;
PROCEDURE Ask*;
BEGIN
ask := TRUE
END Ask;
PROCEDURE InitHost;
VAR test: SHORTINT; lo: SHORTCHAR;
BEGIN
test := 1; SYSTEM.GET(SYSTEM.ADR(test), lo); LEHost := lo = 1X;
InfReal := SYSTEM.VAL(SHORTREAL, InfRealPat);
MinReal32 := SYSTEM.VAL(SHORTREAL, MinReal32Pat);
MaxReal32 := SYSTEM.VAL(SHORTREAL, MaxReal32Pat);
MinReal64 := Compound(MinReal64PatL, MinReal64PatH);
MaxReal64 := Compound(MaxReal64PatL, MaxReal64PatH)
END InitHost;
BEGIN
InitCrcTab;
InitHost;
ask := FALSE
END DevCPM.
| Dev/Mod/CPM.odc |
MODULE DevCPP;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, NewString call changed (Unicode support)
- 20070123, bh, support for procedure type sysflags
- 20070308, bh, longint excluded as case labels
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150415, center #38, report passing receiver parameter IN to VAR
- 20150513, center #43, extending the size of code procedures
- 20150514, center #47, avoid a compiler TRAP with SYSTEM.PTR
- 20160324, center #111, code cleanups
- 20170215, center #139, localization support for error messages
- 20170612, center #160, outdated link to OP2.Paper.ps
- 20180509, center #186, aligning code procedure syntax with docu
"
issues = "
- ...
"
**)
IMPORT
DevCPM, DevCPT, DevCPB, DevCPS;
CONST
anchorVarPar = TRUE;
(* numtyp values *)
char = 1; integer = 2; real = 4; int64 = 5; real32 = 6; real64 = 7;
(*symbol values*)
null = 0; times = 1; slash = 2; div = 3; mod = 4;
and = 5; plus = 6; minus = 7; or = 8; eql = 9;
neq = 10; lss = 11; leq = 12; gtr = 13; geq = 14;
in = 15; is = 16; arrow = 17; dollar = 18; period = 19;
comma = 20; colon = 21; upto = 22; rparen = 23; rbrak = 24;
rbrace = 25; of = 26; then = 27; do = 28; to = 29;
by = 30; not = 33;
lparen = 40; lbrak = 41; lbrace = 42; becomes = 44;
number = 45; nil = 46; string = 47; ident = 48; semicolon = 49;
bar = 50; end = 51; else = 52; elsif = 53; until = 54;
if = 55; case = 56; while = 57; repeat = 58; for = 59;
loop = 60; with = 61; exit = 62; return = 63; array = 64;
record = 65; pointer = 66; begin = 67; const = 68; type = 69;
var = 70; out = 71; procedure = 72; close = 73; import = 74;
module = 75; eof = 76;
(* object modes *)
Var = 1; VarPar = 2; Con = 3; Fld = 4; Typ = 5; LProc = 6; XProc = 7;
SProc = 8; CProc = 9; IProc = 10; Mod = 11; Head = 12; TProc = 13; Attr = 20;
(* Structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; String16 = 17; Int64 = 18;
intSet = {Int8..Int32, Int64}; charSet = {Char8, Char16};
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(*function number*)
haltfn = 0; newfn = 1; incfn = 13; sysnewfn = 30;
(* nodes classes *)
Nvar = 0; Nvarpar = 1; Nfield = 2; Nderef = 3; Nindex = 4; Nguard = 5; Neguard = 6;
Nconst = 7; Ntype = 8; Nproc = 9; Nupto = 10; Nmop = 11; Ndop = 12; Ncall = 13;
Ninittd = 14; Nif = 15; Ncaselse = 16; Ncasedo = 17; Nenter = 18; Nassign = 19;
Nifelse = 20; Ncase = 21; Nwhile = 22; Nrepeat = 23; Nloop = 24; Nexit = 25;
Nreturn = 26; Nwith = 27; Ntrap = 28; Ncomp = 30;
(* node subclasses *)
super = 1;
(* module visibility of objects *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* procedure flags (conval.setval) *)
hasBody = 1; isRedef = 2; slNeeded = 3; imVar = 4;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval)*)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
(* case statement flags (conval.setval) *)
useTable = 1; useTree = 2;
(* sysflags *)
nilBit = 1; inBit = 2; outBit = 4; newBit = 8; iidBit = 16; interface = 10; som = 20; jstr = -13;
TYPE
Elem = POINTER TO RECORD
next: Elem;
struct: DevCPT.Struct;
obj, base: DevCPT.Object;
pos: INTEGER;
name: DevCPT.String
END;
VAR
sym, level: BYTE;
LoopLevel: SHORTINT;
TDinit, lastTDinit: DevCPT.Node;
userList: Elem;
recList: Elem;
hasReturn: BOOLEAN;
PROCEDURE^ Type(VAR typ: DevCPT.Struct; VAR name: DevCPT.String);
PROCEDURE^ Expression(VAR x: DevCPT.Node);
PROCEDURE^ Block(VAR procdec, statseq: DevCPT.Node);
(* forward type handling *)
PROCEDURE IncompleteType (typ: DevCPT.Struct): BOOLEAN;
BEGIN
IF typ.form = Pointer THEN
IF typ = DevCPT.sysptrtyp THEN RETURN FALSE END;
typ := typ.BaseTyp
END;
RETURN (typ = DevCPT.undftyp) OR (typ.comp = Record) & (typ.BaseTyp = DevCPT.undftyp)
END IncompleteType;
PROCEDURE SetType (struct: DevCPT.Struct; obj: DevCPT.Object; typ: DevCPT.Struct; name: DevCPT.String);
VAR u: Elem;
BEGIN
IF obj # NIL THEN obj.typ := typ ELSE struct.BaseTyp := typ END;
IF name # NIL THEN
NEW(u); u.struct := struct; u.obj := obj; u.pos := DevCPM.errpos; u.name := name;
u.next := userList; userList := u
END
END SetType;
PROCEDURE CheckAlloc (VAR typ: DevCPT.Struct; dynAllowed: BOOLEAN; pos: INTEGER);
BEGIN
typ.pvused := TRUE;
IF typ.comp = DynArr THEN
IF ~dynAllowed THEN DevCPM.Mark(88, pos); typ := DevCPT.undftyp END
ELSIF typ.comp = Record THEN
IF (typ.attribute = absAttr) OR (typ.attribute = limAttr) & (typ.mno # 0) THEN
DevCPM.Mark(193, pos); typ := DevCPT.undftyp
END
END
END CheckAlloc;
PROCEDURE CheckRecursiveType (outer, inner: DevCPT.Struct; pos: INTEGER);
VAR fld: DevCPT.Object;
BEGIN
IF outer = inner THEN DevCPM.Mark(58, pos)
ELSIF inner.comp IN {Array, DynArr} THEN CheckRecursiveType(outer, inner.BaseTyp, pos)
ELSIF inner.comp = Record THEN
fld := inner.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
CheckRecursiveType(outer, fld.typ, pos);
fld := fld.link
END;
IF inner.BaseTyp # NIL THEN CheckRecursiveType(outer, inner.BaseTyp, pos) END
END
END CheckRecursiveType;
PROCEDURE FixType (struct: DevCPT.Struct; obj: DevCPT.Object; typ: DevCPT.Struct; pos: INTEGER);
(* fix forward reference *)
VAR t: DevCPT.Struct; f, bf: DevCPT.Object; i: SHORTINT;
BEGIN
IF obj # NIL THEN
IF obj.mode = Var THEN (* variable type *)
IF struct # NIL THEN (* receiver type *)
IF (typ.form # Pointer) OR (typ.BaseTyp # struct) THEN DevCPM.Mark(180, pos) END;
ELSE CheckAlloc(typ, obj.mnolev > level, pos) (* TRUE for parameters *)
END
ELSIF obj.mode = VarPar THEN (* varpar type *)
IF struct # NIL THEN (* varpar receiver type *)
IF typ # struct THEN DevCPM.Mark(180, pos) END
END
ELSIF obj.mode = Fld THEN (* field type *)
CheckAlloc(typ, FALSE, pos);
CheckRecursiveType(struct, typ, pos)
ELSIF obj.mode = TProc THEN (* proc return type *)
IF typ.form = Comp THEN typ := DevCPT.undftyp; DevCPM.Mark(54, pos) END
ELSIF obj.mode = Typ THEN (* alias type *)
IF typ.form IN {Byte..Set, Char16, Int64} THEN (* make alias structure *)
t := DevCPT.NewStr(typ.form, Basic); i := t.ref;
t^ := typ^; t.ref := i; t.strobj := obj; t.mno := 0;
t.BaseTyp := typ; typ := t
END;
IF obj.vis # internal THEN
IF typ.comp = Record THEN typ.exp := TRUE
ELSIF typ.form = Pointer THEN typ.BaseTyp.exp := TRUE
END
END
ELSE HALT(100)
END;
obj.typ := typ
ELSE
IF struct.form = Pointer THEN (* pointer base type *)
IF typ.comp = Record THEN DevCPM.PropagateRecPtrSysFlag(typ.sysflag, struct.sysflag)
ELSIF typ.comp IN {Array, DynArr} THEN DevCPM.PropagateArrPtrSysFlag(typ.sysflag, struct.sysflag)
ELSE typ := DevCPT.undftyp; DevCPM.Mark(57, pos)
END;
struct.untagged := struct.sysflag > 0;
IF (struct.strobj # NIL) & (struct.strobj.vis # internal) THEN typ.exp := TRUE END;
ELSIF struct.comp = Array THEN (* array base type *)
CheckAlloc(typ, FALSE, pos);
CheckRecursiveType(struct, typ, pos)
ELSIF struct.comp = DynArr THEN (* array base type *)
CheckAlloc(typ, TRUE, pos);
CheckRecursiveType(struct, typ, pos)
ELSIF struct.comp = Record THEN (* record base type *)
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
typ.pvused := TRUE; struct.extlev := SHORT(SHORT(typ.extlev + 1));
DevCPM.PropagateRecordSysFlag(typ.sysflag, struct.sysflag);
IF (typ.attribute = 0) OR (typ.attribute = limAttr) & (typ.mno # 0) THEN DevCPM.Mark(181, pos)
ELSIF (struct.attribute = absAttr) & (typ.attribute # absAttr) THEN DevCPM.Mark(191, pos)
ELSIF (typ.attribute = limAttr) & (struct.attribute # limAttr) THEN DevCPM.Mark(197, pos)
END;
f := struct.link;
WHILE f # NIL DO (* check for field name conflicts *)
DevCPT.FindField(f.name, typ, bf);
IF bf # NIL THEN DevCPM.Mark(1, pos) END;
f := f.link
END;
CheckRecursiveType(struct, typ, pos);
struct.untagged := struct.sysflag > 0;
ELSIF struct.form = ProcTyp THEN (* proc type return type *)
IF typ.form = Comp THEN typ := DevCPT.undftyp; DevCPM.Mark(54, pos) END;
ELSE HALT(100)
END;
struct.BaseTyp := typ
END
END FixType;
PROCEDURE CheckForwardTypes;
VAR u, next: Elem; progress: BOOLEAN;
BEGIN
u := userList; userList := NIL;
WHILE u # NIL DO
next := u.next; DevCPS.name := u.name$; DevCPT.Find(DevCPS.name, u.base);
IF u.base = NIL THEN DevCPM.Mark(0, u.pos)
ELSIF u.base.mode # Typ THEN DevCPM.Mark(72, u.pos)
ELSE u.next := userList; userList := u (* reinsert *)
END;
u := next
END;
REPEAT (* iteration for multy level alias *)
u := userList; userList := NIL; progress := FALSE;
WHILE u # NIL DO
next := u.next;
IF IncompleteType(u.base.typ) THEN
u.next := userList; userList := u (* reinsert *)
ELSE
progress := TRUE;
FixType(u.struct, u.obj, u.base.typ, u.pos)
END;
u := next
END
UNTIL (userList = NIL) OR ~progress;
u := userList; (* remaining type relations are cyclic *)
WHILE u # NIL DO
IF (u.obj = NIL) OR (u.obj.mode = Typ) THEN DevCPM.Mark(58, u.pos) END;
u := u.next
END;
END CheckForwardTypes;
PROCEDURE CheckUnimpl (m: DevCPT.Object; typ: DevCPT.Struct; pos: INTEGER);
VAR obj: DevCPT.Object;
BEGIN
IF m # NIL THEN
IF (m.mode = TProc) & (absAttr IN m.conval.setval) THEN
DevCPT.FindField(m.name^, typ, obj);
IF (obj = NIL) OR (obj.mode # TProc) OR (absAttr IN obj.conval.setval) THEN
DevCPM.Mark(192, pos);
DevCPM.LogWLn; DevCPM.LogWStr(" ");
IF typ.strobj # NIL THEN
DevCPM.LogWPar("#Dev:NotImplementedIn", m.name, typ.strobj.name)
ELSE
DevCPM.LogWPar("#Dev:NotImplemented", m.name, "")
END
END
END;
CheckUnimpl(m.left, typ, pos);
CheckUnimpl(m.right, typ, pos)
END
END CheckUnimpl;
PROCEDURE CheckRecords (rec: Elem);
VAR b: DevCPT.Struct;
BEGIN
WHILE rec # NIL DO (* check for unimplemented methods in base type *)
b := rec.struct.BaseTyp;
WHILE (b # NIL) & (b # DevCPT.undftyp) DO
CheckUnimpl(b.link, rec.struct, rec.pos);
b := b.BaseTyp
END;
rec := rec.next
END
END CheckRecords;
PROCEDURE err(n: SHORTINT);
BEGIN DevCPM.err(n)
END err;
PROCEDURE CheckSym(s: SHORTINT);
BEGIN
IF sym = s THEN DevCPS.Get(sym) ELSE DevCPM.err(s) END
END CheckSym;
PROCEDURE qualident(VAR id: DevCPT.Object);
VAR obj: DevCPT.Object; lev: BYTE;
BEGIN (*sym = ident*)
DevCPT.Find(DevCPS.name, obj); DevCPS.Get(sym);
IF (sym = period) & (obj # NIL) & (obj.mode = Mod) THEN
DevCPS.Get(sym);
IF sym = ident THEN
DevCPT.FindImport(DevCPS.name, obj, obj); DevCPS.Get(sym)
ELSE err(ident); obj := NIL
END
END ;
IF obj = NIL THEN err(0);
obj := DevCPT.NewObj(); obj.mode := Var; obj.typ := DevCPT.undftyp; obj.adr := 0
ELSE lev := obj.mnolev;
IF (obj.mode IN {Var, VarPar}) & (lev # level) THEN
obj.leaf := FALSE;
IF lev > 0 THEN DevCPB.StaticLink(SHORT(SHORT(level-lev)), TRUE) END (* !!! *)
END
END ;
id := obj
END qualident;
PROCEDURE ConstExpression(VAR x: DevCPT.Node);
BEGIN Expression(x);
IF x.class # Nconst THEN
err(50); x := DevCPB.NewIntConst(1)
END
END ConstExpression;
PROCEDURE CheckMark(obj: DevCPT.Object); (* !!! *)
VAR n: INTEGER; mod: ARRAY 256 OF DevCPT.String;
BEGIN DevCPS.Get(sym);
IF (sym = times) OR (sym = minus) THEN
IF (level > 0) OR ~(obj.mode IN {Var, Fld, TProc}) & (sym = minus) THEN err(41) END ;
IF sym = times THEN obj.vis := external ELSE obj.vis := externalR END ;
DevCPS.Get(sym)
ELSE obj.vis := internal
END;
IF (obj.mode IN {TProc, LProc, XProc, CProc, Var, Typ, Con, Fld}) & (sym = lbrak) THEN
DevCPS.Get(sym);
IF (sym = number) & (DevCPS.numtyp = char) THEN
NEW(DevCPS.str, 2); DevCPS.str[0] := SHORT(CHR(DevCPS.intval)); DevCPS.str[1] := 0X; sym := string
END;
IF sym = string THEN
IF DevCPS.str^ # "" THEN obj.entry := DevCPS.str END;
DevCPS.Get(sym); n := 0;
IF (sym = comma) & (obj.mode IN {LProc, XProc, CProc, Var, Con}) THEN
DevCPS.Get(sym);
IF (sym = number) & (DevCPS.numtyp = char) THEN
NEW(DevCPS.str, 2); DevCPS.str[0] := SHORT(CHR(DevCPS.intval)); DevCPS.str[1] := 0X; sym := string
END;
IF sym = string THEN
obj.library := obj.entry; obj.entry := NIL;
IF DevCPS.str^ # "" THEN obj.entry := DevCPS.str END;
DevCPS.Get(sym);
ELSE err(string)
END
END;
WHILE sym = comma DO
DevCPS.Get(sym);
IF (sym = number) & (DevCPS.numtyp = char) THEN
NEW(DevCPS.str, 2); DevCPS.str[0] := SHORT(CHR(DevCPS.intval)); DevCPS.str[1] := 0X; sym := string
END;
IF sym = string THEN
IF n < LEN(mod) THEN mod[n] := DevCPS.str; INC(n)
ELSE err(235)
END;
DevCPS.Get(sym)
ELSE err(string)
END
END;
IF n > 0 THEN
NEW(obj.modifiers, n);
WHILE n > 0 DO DEC(n); obj.modifiers[n] := mod[n] END
END
ELSE err(string)
END;
CheckSym(rbrak);
IF DevCPM.options * {DevCPM.interface, DevCPM.java} = {} THEN err(225) END
END
END CheckMark;
PROCEDURE CheckSysFlag (VAR sysflag: SHORTINT;
GetSF: PROCEDURE(IN id: ARRAY OF SHORTCHAR; num: SHORTINT; VAR flag: SHORTINT));
VAR x: DevCPT.Object; i: SHORTINT;
BEGIN
sysflag := 0;
IF sym = lbrak THEN
DevCPS.Get(sym);
WHILE (sym = number) OR (sym = ident) OR (sym = string) DO
IF sym = number THEN
IF DevCPS.numtyp = integer THEN
i := SHORT(DevCPS.intval); GetSF("", i, sysflag)
ELSE err(225)
END
ELSIF sym = ident THEN
DevCPT.Find(DevCPS.name, x);
IF (x # NIL) & (x.mode = Con) & (x.typ.form IN {Int8, Int16, Int32}) THEN
i := SHORT(x.conval.intval); GetSF("", i, sysflag)
ELSE
GetSF(DevCPS.name, 0, sysflag)
END
ELSE
GetSF(DevCPS.str, 0, sysflag)
END;
DevCPS.Get(sym);
IF (sym = comma) OR (sym = plus) THEN DevCPS.Get(sym) END
END;
CheckSym(rbrak)
END
END CheckSysFlag;
PROCEDURE Receiver(VAR mode, vis: BYTE; VAR name: DevCPT.Name; VAR typ, rec: DevCPT.Struct);
VAR tname: DevCPT.String;
BEGIN typ := DevCPT.undftyp; rec := NIL; vis := 0;
IF sym = var THEN DevCPS.Get(sym); mode := VarPar;
ELSIF sym = in THEN DevCPS.Get(sym); mode := VarPar; vis := inPar (* ??? *)
ELSE mode := Var
END ;
name := DevCPS.name; CheckSym(ident); CheckSym(colon);
IF sym # ident THEN err(ident) END;
Type(typ, tname);
IF tname = NIL THEN
IF typ.form = Pointer THEN rec := typ.BaseTyp ELSE rec := typ END;
IF ~((mode = Var) & (typ.form = Pointer) & (rec.comp = Record) OR
(mode = VarPar) & (typ.comp = Record)) THEN err(70); rec := NIL END;
IF (rec # NIL) & (rec.mno # level) THEN err(72); rec := NIL END
ELSE err(0)
END;
CheckSym(rparen);
IF rec = NIL THEN rec := DevCPT.NewStr(Comp, Record); rec.BaseTyp := NIL END
END Receiver;
PROCEDURE FormalParameters(
VAR firstPar: DevCPT.Object; VAR resTyp: DevCPT.Struct; VAR name: DevCPT.String
);
VAR mode, vis: BYTE; sys: SHORTINT;
par, first, last, newPar, iidPar: DevCPT.Object; typ: DevCPT.Struct;
BEGIN
first := NIL; last := firstPar;
newPar := NIL; iidPar := NIL;
IF (sym = ident) OR (sym = var) OR (sym = in) OR (sym = out) THEN
LOOP
sys := 0; vis := 0;
IF sym = var THEN DevCPS.Get(sym); mode := VarPar
ELSIF sym = in THEN DevCPS.Get(sym); mode := VarPar; vis := inPar
ELSIF sym = out THEN DevCPS.Get(sym); mode := VarPar; vis := outPar
ELSE mode := Var
END ;
IF mode = VarPar THEN CheckSysFlag(sys, DevCPM.GetVarParSysFlag) END;
IF ODD(sys DIV inBit) THEN vis := inPar
ELSIF ODD(sys DIV outBit) THEN vis := outPar
END;
IF ODD(sys DIV newBit) & (vis # outPar) THEN err(225)
ELSIF ODD(sys DIV iidBit) & (vis # inPar) THEN err(225)
END;
LOOP
IF sym = ident THEN
DevCPT.Insert(DevCPS.name, par); DevCPS.Get(sym);
par.mode := mode; par.link := NIL; par.vis := vis; par.sysflag := SHORT(sys);
IF first = NIL THEN first := par END ;
IF firstPar = NIL THEN firstPar := par ELSE last.link := par END ;
last := par
ELSE err(ident)
END;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF sym = ident THEN err(comma)
ELSIF sym = var THEN err(comma); DevCPS.Get(sym)
ELSE EXIT
END
END ;
CheckSym(colon); Type(typ, name);
IF mode # VarPar THEN CheckAlloc(typ, TRUE, DevCPM.errpos) END;
(* IN only allowed for records and arrays *)
IF (mode = VarPar) & (vis = inPar) & (typ.form # Undef) & (typ.form # Comp) & (typ.sysflag = 0) THEN err(177)
END;
(* typ.pbused is set when parameter type name is parsed *)
WHILE first # NIL DO
SetType (NIL, first, typ, name);
IF DevCPM.com IN DevCPM.options THEN
IF ODD(sys DIV newBit) THEN
IF (newPar # NIL) OR (typ.form # Pointer) OR (typ.sysflag # interface) THEN err(168) END;
newPar := first
ELSIF ODD(sys DIV iidBit) THEN
IF (iidPar # NIL) OR (typ # DevCPT.guidtyp) THEN err(168) END;
iidPar := first
END
END;
first := first.link
END;
IF sym = semicolon THEN DevCPS.Get(sym)
ELSIF sym = ident THEN err(semicolon)
ELSE EXIT
END
END
END;
CheckSym(rparen);
IF (newPar = NIL) # (iidPar = NIL) THEN err(168) END;
name := NIL;
IF sym = colon THEN
DevCPS.Get(sym);
Type(resTyp, name);
IF resTyp.form = Comp THEN resTyp := DevCPT.undftyp; err(54) END
ELSE resTyp := DevCPT.notyp
END
END FormalParameters;
PROCEDURE CheckOverwrite (proc, base: DevCPT.Object; rec: DevCPT.Struct);
VAR o, bo: DevCPT.Object;
BEGIN
IF base # NIL THEN
IF base.conval.setval * {absAttr, empAttr, extAttr} = {} THEN err(182) END;
IF (proc.link.mode # base.link.mode) OR (proc.link.vis # base.link.vis)
OR ~DevCPT.Extends(proc.link.typ, base.link.typ) THEN err(115) END;
o := proc.link; bo := base.link;
WHILE (o # NIL) & (bo # NIL) DO
IF (bo.sysflag # 0) & (o.sysflag = 0) THEN (* propagate sysflags *)
o.sysflag := bo.sysflag
END;
o := o.link; bo := bo.link
END;
DevCPB.CheckParameters(proc.link.link, base.link.link, FALSE);
IF ~DevCPT.Extends(proc.typ, base.typ) THEN err(117) END;
IF (base.vis # proc.vis) & ((proc.vis # internal) OR rec.exp) THEN err(183) END;
INCL(proc.conval.setval, isRedef)
END;
END CheckOverwrite;
PROCEDURE GetAttributes (proc, base: DevCPT.Object; owner: DevCPT.Struct); (* read method attributes *)
VAR attr, battr: SET; o: DevCPT.Object;
BEGIN
attr := {};
IF sym = comma THEN (* read attributes *)
DevCPS.Get(sym);
IF sym = ident THEN
DevCPT.Find(DevCPS.name, o);
IF (o # NIL) & (o.mode = SProc) & (o.adr = newfn) THEN
IF ~(DevCPM.oberon IN DevCPM.options) THEN INCL(attr, newAttr) ELSE err(178) END;
DevCPS.Get(sym);
IF sym = comma THEN
DevCPS.Get(sym);
IF sym = ident THEN DevCPT.Find(DevCPS.name, o) ELSE o := NIL; err(ident) END
ELSE o := NIL
END
END;
IF o # NIL THEN
IF (o.mode # Attr) OR (o.adr = limAttr) OR (DevCPM.oberon IN DevCPM.options) THEN err(178)
ELSE INCL(attr, o.adr)
END;
DevCPS.Get(sym)
END
ELSE err(ident)
END
END;
IF (base = NIL) & ~(newAttr IN attr) THEN err(185); INCL(attr, newAttr)
ELSIF (base # NIL) & (newAttr IN attr) THEN err(186)
END;
IF absAttr IN attr THEN
IF owner.attribute # absAttr THEN err(190) END;
IF (proc.vis = internal) & owner.exp THEN err(179) END
END;
IF (owner.attribute = 0) OR (owner.attribute = limAttr) THEN
IF (empAttr IN attr) & (newAttr IN attr) THEN err(187)
(*
ELSIF extAttr IN attr THEN err(188)
*)
END
END;
IF base # NIL THEN
battr := base.conval.setval;
IF empAttr IN battr THEN
IF absAttr IN attr THEN err(189) END
ELSIF ~(absAttr IN battr) THEN
IF (absAttr IN attr) OR (empAttr IN attr) THEN err(189) END
END
END;
IF empAttr IN attr THEN
IF proc.typ # DevCPT.notyp THEN err(195)
ELSE
o := proc.link; WHILE (o # NIL) & (o.vis # outPar) DO o := o.link END;
IF o # NIL THEN err(195) END
END
END;
IF (owner.sysflag = interface) & ~(absAttr IN attr) THEN err(162) END;
proc.conval.setval := attr
END GetAttributes;
PROCEDURE RecordType(VAR typ: DevCPT.Struct; attr: DevCPT.Object);
VAR fld, first, last: DevCPT.Object; r: Elem; ftyp: DevCPT.Struct; name: DevCPT.String;
BEGIN typ := DevCPT.NewStr(Comp, Record); typ.BaseTyp := NIL;
CheckSysFlag(typ.sysflag, DevCPM.GetRecordSysFlag);
IF attr # NIL THEN
IF ~(DevCPM.oberon IN DevCPM.options) & (attr.adr # empAttr) THEN typ.attribute := SHORT(SHORT(attr.adr))
ELSE err(178)
END
END;
IF typ.sysflag = interface THEN
IF (DevCPS.str # NIL) & (DevCPS.str[0] = "{") THEN typ.ext := DevCPS.str END;
IF typ.attribute # absAttr THEN err(163) END;
IF sym # lparen THEN err(160) END
END;
IF sym = lparen THEN
DevCPS.Get(sym); (*record extension*)
IF sym = ident THEN
Type(ftyp, name);
IF ftyp.form = Pointer THEN ftyp := ftyp.BaseTyp END;
SetType(typ, NIL, ftyp, name);
IF (ftyp.comp = Record) & (ftyp # DevCPT.anytyp) THEN
ftyp.pvused := TRUE; typ.extlev := SHORT(SHORT(ftyp.extlev + 1));
DevCPM.PropagateRecordSysFlag(ftyp.sysflag, typ.sysflag);
IF (ftyp.attribute = 0) OR (ftyp.attribute = limAttr) & (ftyp.mno # 0) THEN err(181)
ELSIF (typ.attribute = absAttr) & (ftyp.attribute # absAttr) & ~(DevCPM.java IN DevCPM.options) THEN err(191)
ELSIF (ftyp.attribute = limAttr) & (typ.attribute # limAttr) THEN err(197)
END
ELSIF ftyp # DevCPT.undftyp THEN err(53)
END
ELSE err(ident)
END ;
IF typ.attribute # absAttr THEN (* save typ for unimplemented method check *)
NEW(r); r.struct := typ; r.pos := DevCPM.errpos; r.next := recList; recList := r
END;
CheckSym(rparen)
END;
(*
DevCPT.OpenScope(0, NIL);
*)
first := NIL; last := NIL;
LOOP
IF sym = ident THEN
LOOP
IF sym = ident THEN
IF (typ.BaseTyp # NIL) & (typ.BaseTyp # DevCPT.undftyp) THEN
DevCPT.FindBaseField(DevCPS.name, typ, fld);
IF fld # NIL THEN err(1) END
END ;
DevCPT.InsertField(DevCPS.name, typ, fld);
fld.mode := Fld; fld.link := NIL; fld.typ := DevCPT.undftyp;
CheckMark(fld);
IF first = NIL THEN first := fld END ;
IF last = NIL THEN typ.link := fld ELSE last.link := fld END ;
last := fld
ELSE err(ident)
END ;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF sym = ident THEN err(comma)
ELSE EXIT
END
END ;
CheckSym(colon); Type(ftyp, name);
CheckAlloc(ftyp, FALSE, DevCPM.errpos);
WHILE first # NIL DO
SetType(typ, first, ftyp, name); first := first.link
END;
IF typ.sysflag = interface THEN err(161) END
END;
IF sym = semicolon THEN DevCPS.Get(sym)
ELSIF sym = ident THEN err(semicolon)
ELSE EXIT
END
END;
(*
IF typ.link # NIL THEN ASSERT(typ.link = DevCPT.topScope.right) END;
typ.link := DevCPT.topScope.right; DevCPT.CloseScope;
*)
typ.untagged := typ.sysflag > 0;
DevCPB.Inittd(TDinit, lastTDinit, typ); CheckSym(end)
END RecordType;
PROCEDURE ArrayType(VAR typ: DevCPT.Struct);
VAR x: DevCPT.Node; n: INTEGER; sysflag: SHORTINT; name: DevCPT.String;
BEGIN CheckSysFlag(sysflag, DevCPM.GetArraySysFlag);
IF sym = of THEN (*dynamic array*)
typ := DevCPT.NewStr(Comp, DynArr); typ.mno := 0; typ.sysflag := sysflag;
DevCPS.Get(sym); Type(typ.BaseTyp, name); SetType(typ, NIL, typ.BaseTyp, name);
CheckAlloc(typ.BaseTyp, TRUE, DevCPM.errpos);
IF typ.BaseTyp.comp = DynArr THEN typ.n := typ.BaseTyp.n + 1 ELSE typ.n := 0 END
ELSE
typ := DevCPT.NewStr(Comp, Array); typ.sysflag := sysflag; ConstExpression(x);
IF x.typ.form IN {Int8, Int16, Int32} THEN n := x.conval.intval;
IF (n <= 0) OR (n > DevCPM.MaxIndex) THEN err(63); n := 1 END
ELSE err(42); n := 1
END ;
typ.n := n;
IF sym = of THEN
DevCPS.Get(sym); Type(typ.BaseTyp, name); SetType(typ, NIL, typ.BaseTyp, name);
CheckAlloc(typ.BaseTyp, FALSE, DevCPM.errpos)
ELSIF sym = comma THEN
DevCPS.Get(sym);
IF sym # of THEN ArrayType(typ.BaseTyp) END
ELSE err(35)
END
END;
typ.untagged := typ.sysflag > 0
END ArrayType;
PROCEDURE PointerType(VAR typ: DevCPT.Struct);
VAR name: DevCPT.String;
BEGIN typ := DevCPT.NewStr(Pointer, Basic); CheckSysFlag(typ.sysflag, DevCPM.GetPointerSysFlag);
CheckSym(to);
Type(typ.BaseTyp, name);
SetType(typ, NIL, typ.BaseTyp, name);
IF (typ.BaseTyp # DevCPT.undftyp) & (typ.BaseTyp.comp = Basic) THEN
typ.BaseTyp := DevCPT.undftyp; err(57)
END;
IF typ.BaseTyp.comp = Record THEN DevCPM.PropagateRecPtrSysFlag(typ.BaseTyp.sysflag, typ.sysflag)
ELSIF typ.BaseTyp.comp IN {Array, DynArr} THEN DevCPM.PropagateArrPtrSysFlag(typ.BaseTyp.sysflag, typ.sysflag)
END;
typ.untagged := typ.sysflag > 0
END PointerType;
PROCEDURE Type (VAR typ: DevCPT.Struct; VAR name: DevCPT.String); (* name # NIL => forward reference *)
VAR id: DevCPT.Object; tname: DevCPT.String;
BEGIN
typ := DevCPT.undftyp; name := NIL;
IF sym < lparen THEN err(12);
REPEAT DevCPS.Get(sym) UNTIL sym >= lparen
END ;
IF sym = ident THEN
DevCPT.Find(DevCPS.name, id);
IF (id = NIL) OR (id.mode = -1) OR (id.mode = Typ) & IncompleteType(id.typ) THEN (* forward type definition *)
name := DevCPT.NewName(DevCPS.name); DevCPS.Get(sym);
IF (id = NIL) & (sym = period) THEN (* missing module *)
err(0); DevCPS.Get(sym); name := NIL;
IF sym = ident THEN DevCPS.Get(sym) END
ELSIF sym = record THEN (* wrong attribute *)
err(178); DevCPS.Get(sym); name := NIL; RecordType(typ, NIL)
END
ELSE
qualident(id);
IF id.mode = Typ THEN
IF ~(DevCPM.oberon IN DevCPM.options)
& ((id.typ = DevCPT.lreal64typ) OR (id.typ = DevCPT.lint64typ) OR (id.typ = DevCPT.lchar16typ)) THEN
err(198)
END;
typ := id.typ
ELSIF id.mode = Attr THEN
IF sym = record THEN
DevCPS.Get(sym); RecordType(typ, id)
ELSE err(12)
END
ELSE err(52)
END
END
ELSIF sym = array THEN
DevCPS.Get(sym); ArrayType(typ)
ELSIF sym = record THEN
DevCPS.Get(sym); RecordType(typ, NIL)
ELSIF sym = pointer THEN
DevCPS.Get(sym); PointerType(typ)
ELSIF sym = procedure THEN
DevCPS.Get(sym); typ := DevCPT.NewStr(ProcTyp, Basic);
CheckSysFlag(typ.sysflag, DevCPM.GetProcTypSysFlag);
typ.untagged := typ.sysflag > 0;
IF sym = lparen THEN
DevCPS.Get(sym); DevCPT.OpenScope(level, NIL);
FormalParameters(typ.link, typ.BaseTyp, tname); SetType(typ, NIL, typ.BaseTyp, tname); DevCPT.CloseScope
ELSE typ.BaseTyp := DevCPT.notyp; typ.link := NIL
END
ELSE err(12)
END ;
LOOP
IF (sym >= semicolon) & (sym <= else) OR (sym = rparen) OR (sym = eof)
OR (sym = number) OR (sym = comma) OR (sym = string) THEN EXIT END;
err(15); IF sym = ident THEN EXIT END;
DevCPS.Get(sym)
END
END Type;
PROCEDURE ActualParameters(VAR aparlist: DevCPT.Node; fpar: DevCPT.Object; VAR pre, lastp: DevCPT.Node);
VAR apar, last, newPar, iidPar, n: DevCPT.Node;
BEGIN
aparlist := NIL; last := NIL;
IF sym # rparen THEN
newPar := NIL; iidPar := NIL;
LOOP Expression(apar);
IF fpar # NIL THEN
IF (apar.typ.form = Pointer) & (fpar.typ.form = Comp) THEN DevCPB.DeRef(apar) END;
DevCPB.Param(apar, fpar);
IF (fpar.mode = Var) OR (fpar.vis = inPar) THEN DevCPB.CheckBuffering(apar, NIL, fpar, pre, lastp) END;
DevCPB.Link(aparlist, last, apar);
IF ODD(fpar.sysflag DIV newBit) THEN newPar := apar
ELSIF ODD(fpar.sysflag DIV iidBit) THEN iidPar := apar
END;
IF (newPar # NIL) & (iidPar # NIL) THEN DevCPB.CheckNewParamPair(newPar, iidPar) END;
IF anchorVarPar & (fpar.mode = VarPar) & ~(DevCPM.java IN DevCPM.options)
OR (DevCPM.allSysVal IN DevCPM.options) (* source output: avoid double evaluation *)
& ((fpar.mode = VarPar) & (fpar.typ.comp = Record) & ~fpar.typ.untagged
OR (fpar.typ.comp = DynArr) & ~fpar.typ.untagged) THEN
n := apar;
WHILE n.class IN {Nfield, Nindex, Nguard} DO n := n.left END;
IF (n.class = Nderef) & (n.subcl = 0) THEN
IF n.left.class = Nguard THEN n := n.left END;
DevCPB.CheckVarParBuffering(n.left, pre, lastp)
END
END;
fpar := fpar.link
ELSE err(64)
END;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF (lparen <= sym) & (sym <= ident) THEN err(comma)
ELSE EXIT
END
END
END;
IF fpar # NIL THEN err(65) END
END ActualParameters;
PROCEDURE selector(VAR x: DevCPT.Node);
VAR obj, proc, p, fpar: DevCPT.Object; y, apar, pre, lastp: DevCPT.Node; typ: DevCPT.Struct; name: DevCPT.Name;
BEGIN
LOOP
IF sym = lbrak THEN DevCPS.Get(sym);
LOOP
IF (x.typ # NIL) & (x.typ.form = Pointer) THEN DevCPB.DeRef(x) END ;
Expression(y); DevCPB.Index(x, y);
IF sym = comma THEN DevCPS.Get(sym) ELSE EXIT END
END ;
CheckSym(rbrak)
ELSIF sym = period THEN DevCPS.Get(sym);
IF sym = ident THEN name := DevCPS.name; DevCPS.Get(sym);
IF x.typ # NIL THEN
IF x.typ.form = Pointer THEN DevCPB.DeRef(x) END ;
IF x.typ.comp = Record THEN
typ := x.typ; DevCPT.FindField(name, typ, obj); DevCPB.Field(x, obj);
IF (obj # NIL) & (obj.mode = TProc) THEN
IF sym = arrow THEN (* super call *) DevCPS.Get(sym);
y := x.left;
IF y.class = Nderef THEN y := y.left END ; (* y = record variable *)
IF y.obj # NIL THEN
proc := DevCPT.topScope; (* find innermost scope which owner is a TProc *)
WHILE (proc.link # NIL) & (proc.link.mode # TProc) DO proc := proc.left END ;
IF (proc.link = NIL) OR (proc.link.link # y.obj) (* OR (proc.link.name^ # name) *) THEN err(75)
END ;
typ := y.obj.typ;
IF typ.form = Pointer THEN typ := typ.BaseTyp END ;
DevCPT.FindBaseField(x.obj.name^, typ, p);
IF p # NIL THEN
x.subcl := super; x.typ := p.typ; (* correct result type *)
IF p.conval.setval * {absAttr, empAttr} # {} THEN err(194) END;
IF (p.vis = externalR) & (p.mnolev < 0) & (proc.link.name^ # name) THEN err(196) END;
ELSE err(74)
END
ELSE err(75)
END
ELSE
proc := obj;
IF (x.left.readonly) & (proc.link.mode = VarPar) & (proc.link.vis = 0) THEN err(76) END;
WHILE (proc.mnolev >= 0) & ~(newAttr IN proc.conval.setval) & (typ.BaseTyp # NIL) DO
(* find base method *)
typ := typ.BaseTyp; DevCPT.FindField(name, typ, proc);
END;
IF (proc.vis = externalR) & (proc.mnolev < 0) THEN err(196) END;
END ;
IF (obj.typ # DevCPT.notyp) & (sym # lparen) THEN err(lparen) END
END
ELSE err(53)
END
ELSE err(52)
END
ELSE err(ident)
END
ELSIF sym = arrow THEN DevCPS.Get(sym); DevCPB.DeRef(x)
ELSIF sym = dollar THEN
IF x.typ.form = Pointer THEN DevCPB.DeRef(x) END;
DevCPS.Get(sym); DevCPB.StrDeref(x)
ELSIF sym = lparen THEN
IF (x.obj # NIL) & (x.obj.mode IN {XProc, LProc, CProc, TProc}) THEN typ := x.obj.typ
ELSIF x.typ.form = ProcTyp THEN typ := x.typ.BaseTyp
ELSIF x.class = Nproc THEN EXIT (* standard procedure *)
ELSE typ := NIL
END;
IF typ # DevCPT.notyp THEN
DevCPS.Get(sym);
IF typ = NIL THEN (* type guard *)
IF sym = ident THEN
qualident(obj);
IF obj.mode = Typ THEN DevCPB.TypTest(x, obj, TRUE)
ELSE err(52)
END
ELSE err(ident)
END
ELSE (* function call *)
pre := NIL; lastp := NIL;
DevCPB.PrepCall(x, fpar);
IF (x.obj # NIL) & (x.obj.mode = TProc) THEN DevCPB.CheckBuffering(x.left, NIL, x.obj.link, pre, lastp)
END;
ActualParameters(apar, fpar, pre, lastp);
DevCPB.Call(x, apar, fpar);
IF pre # NIL THEN DevCPB.Construct(Ncomp, pre, x); pre.typ := x.typ; x := pre END;
IF level > 0 THEN DevCPT.topScope.link.leaf := FALSE END
END;
CheckSym(rparen)
ELSE EXIT
END
(*
ELSIF (sym = lparen) & (x.class # Nproc) & (x.typ.form # ProcTyp) &
((x.obj = NIL) OR (x.obj.mode # TProc)) THEN
DevCPS.Get(sym);
IF sym = ident THEN
qualident(obj);
IF obj.mode = Typ THEN DevCPB.TypTest(x, obj, TRUE)
ELSE err(52)
END
ELSE err(ident)
END ;
CheckSym(rparen)
*)
ELSE EXIT
END
END
END selector;
PROCEDURE StandProcCall(VAR x: DevCPT.Node);
VAR y: DevCPT.Node; m: BYTE; n: SHORTINT;
BEGIN m := SHORT(SHORT(x.obj.adr)); n := 0;
IF sym = lparen THEN DevCPS.Get(sym);
IF sym # rparen THEN
LOOP
IF n = 0 THEN Expression(x); DevCPB.StPar0(x, m); n := 1
ELSIF n = 1 THEN Expression(y); DevCPB.StPar1(x, y, m); n := 2
ELSE Expression(y); DevCPB.StParN(x, y, m, n); INC(n)
END ;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF (lparen <= sym) & (sym <= ident) THEN err(comma)
ELSE EXIT
END
END ;
CheckSym(rparen)
ELSE DevCPS.Get(sym)
END ;
DevCPB.StFct(x, m, n)
ELSE err(lparen)
END ;
IF (level > 0) & ((m = newfn) OR (m = sysnewfn)) THEN DevCPT.topScope.link.leaf := FALSE END
END StandProcCall;
PROCEDURE Element(VAR x: DevCPT.Node);
VAR y: DevCPT.Node;
BEGIN Expression(x);
IF sym = upto THEN
DevCPS.Get(sym); Expression(y); DevCPB.SetRange(x, y)
ELSE DevCPB.SetElem(x)
END
END Element;
PROCEDURE Sets(VAR x: DevCPT.Node);
VAR y: DevCPT.Node;
BEGIN
IF sym # rbrace THEN
Element(x);
LOOP
IF sym = comma THEN DevCPS.Get(sym)
ELSIF (lparen <= sym) & (sym <= ident) THEN err(comma)
ELSE EXIT
END ;
Element(y); DevCPB.Op(plus, x, y)
END
ELSE x := DevCPB.EmptySet()
END ;
CheckSym(rbrace)
END Sets;
PROCEDURE Factor(VAR x: DevCPT.Node);
VAR id: DevCPT.Object;
BEGIN
IF sym < not THEN err(13);
REPEAT DevCPS.Get(sym) UNTIL sym >= lparen
END ;
IF sym = ident THEN
qualident(id); x := DevCPB.NewLeaf(id); selector(x);
IF (x.class = Nproc) & (x.obj.mode = SProc) THEN StandProcCall(x) (* x may be NIL *)
(*
ELSIF sym = lparen THEN
DevCPS.Get(sym); DevCPB.PrepCall(x, fpar);
ActualParameters(apar, fpar);
DevCPB.Call(x, apar, fpar);
CheckSym(rparen);
IF level > 0 THEN DevCPT.topScope.link.leaf := FALSE END
*)
END
ELSIF sym = number THEN
CASE DevCPS.numtyp OF
char:
x := DevCPB.NewIntConst(DevCPS.intval); x.typ := DevCPT.char8typ;
IF DevCPS.intval > 255 THEN x.typ := DevCPT.char16typ END
| integer: x := DevCPB.NewIntConst(DevCPS.intval)
| int64: x := DevCPB.NewLargeIntConst(DevCPS.intval, DevCPS.realval)
| real: x := DevCPB.NewRealConst(DevCPS.realval, NIL)
| real32: x := DevCPB.NewRealConst(DevCPS.realval, DevCPT.real32typ)
| real64: x := DevCPB.NewRealConst(DevCPS.realval, DevCPT.real64typ)
END ;
DevCPS.Get(sym)
ELSIF sym = string THEN
x := DevCPB.NewString(DevCPS.str, DevCPS.lstr, DevCPS.intval);
DevCPS.Get(sym)
ELSIF sym = nil THEN
x := DevCPB.Nil(); DevCPS.Get(sym)
ELSIF sym = lparen THEN
DevCPS.Get(sym); Expression(x); CheckSym(rparen)
ELSIF sym = lbrak THEN
DevCPS.Get(sym); err(lparen); Expression(x); CheckSym(rparen)
ELSIF sym = lbrace THEN DevCPS.Get(sym); Sets(x)
ELSIF sym = not THEN
DevCPS.Get(sym); Factor(x); DevCPB.MOp(not, x)
ELSE err(13); DevCPS.Get(sym); x := NIL
END ;
IF x = NIL THEN x := DevCPB.NewIntConst(1); x.typ := DevCPT.undftyp END
END Factor;
PROCEDURE Term(VAR x: DevCPT.Node);
VAR y: DevCPT.Node; mulop: BYTE;
BEGIN Factor(x);
WHILE (times <= sym) & (sym <= and) DO
mulop := sym; DevCPS.Get(sym);
Factor(y); DevCPB.Op(mulop, x, y)
END
END Term;
PROCEDURE SimpleExpression(VAR x: DevCPT.Node);
VAR y: DevCPT.Node; addop: BYTE;
BEGIN
IF sym = minus THEN DevCPS.Get(sym); Term(x); DevCPB.MOp(minus, x)
ELSIF sym = plus THEN DevCPS.Get(sym); Term(x); DevCPB.MOp(plus, x)
ELSE Term(x)
END ;
WHILE (plus <= sym) & (sym <= or) DO
addop := sym; DevCPS.Get(sym); Term(y);
IF x.typ.form = Pointer THEN DevCPB.DeRef(x) END;
IF (x.typ.comp IN {Array, DynArr}) & (x.typ.BaseTyp.form IN charSet) (* OR (x.typ.sysflag = jstr) *) THEN
DevCPB.StrDeref(x)
END;
IF y.typ.form = Pointer THEN DevCPB.DeRef(y) END;
IF (y.typ.comp IN {Array, DynArr}) & (y.typ.BaseTyp.form IN charSet) (* OR (y.typ.sysflag = jstr) *) THEN
DevCPB.StrDeref(y)
END;
DevCPB.Op(addop, x, y)
END
END SimpleExpression;
PROCEDURE Expression(VAR x: DevCPT.Node);
VAR y, pre, last: DevCPT.Node; obj: DevCPT.Object; relation: BYTE;
BEGIN SimpleExpression(x);
IF (eql <= sym) & (sym <= geq) THEN
relation := sym; DevCPS.Get(sym); SimpleExpression(y);
pre := NIL; last := NIL;
IF (x.typ.comp IN {Array, DynArr}) & (x.typ.BaseTyp.form IN charSet) THEN
DevCPB.StrDeref(x)
END;
IF (y.typ.comp IN {Array, DynArr}) & (y.typ.BaseTyp.form IN charSet) THEN
DevCPB.StrDeref(y)
END;
DevCPB.CheckBuffering(x, NIL, NIL, pre, last);
DevCPB.CheckBuffering(y, NIL, NIL, pre, last);
DevCPB.Op(relation, x, y);
IF pre # NIL THEN DevCPB.Construct(Ncomp, pre, x); pre.typ := x.typ; x := pre END
ELSIF sym = in THEN
DevCPS.Get(sym); SimpleExpression(y); DevCPB.In(x, y)
ELSIF sym = is THEN
DevCPS.Get(sym);
IF sym = ident THEN
qualident(obj);
IF obj.mode = Typ THEN DevCPB.TypTest(x, obj, FALSE)
ELSE err(52)
END
ELSE err(ident)
END
END
END Expression;
PROCEDURE ProcedureDeclaration(VAR x: DevCPT.Node);
VAR proc, fwd: DevCPT.Object;
name: DevCPT.Name;
mode: BYTE;
forward: BOOLEAN;
sys: SHORTINT;
PROCEDURE GetCode;
VAR ext: DevCPT.ConstExt; n, c, i: INTEGER; s: POINTER TO ARRAY OF SHORTCHAR;
cx: DevCPT.Node;
PROCEDURE EnsureLen(len: INTEGER);
VAR j: INTEGER; s2: POINTER TO ARRAY OF SHORTCHAR;
BEGIN
IF len > LEN(s) THEN (* if overflow then increase size of array s *)
NEW(s2, LEN(s) * 2); FOR j := 0 TO n - 1 DO s2[j] := s[j] END; s := s2
END
END EnsureLen;
BEGIN
n := 0; NEW(s, 64);
WHILE (sym # semicolon) & (sym # eof) DO
ConstExpression(cx);
IF cx.typ.form IN {Int8, Int16, Int32, Char8, Char16} THEN c :=cx.conval.intval; EnsureLen(n + 1);
IF (0 <= c) & (c <= 255) THEN s[n] := SHORT(CHR(c)); INC(n)
ELSE err(63)
END
ELSIF cx.typ.form = String8 THEN c := cx.conval.intval2 - 1 (*exclude 0X*); EnsureLen(n + c);
FOR i := 0 TO c - 1 DO s[n + i] := cx.conval.ext[i] END;
INC(n, c)
ELSE (* Int64, Real32, Real64, String16, Bool, etc. *) err(63)
END ;
IF sym = comma THEN DevCPS.Get(sym); IF sym = semicolon THEN err(13) END
ELSIF sym # semicolon THEN err(comma)
END
END;
IF n # 0 THEN NEW(ext, n); i := 0;
WHILE i < n DO ext[i] := s[i]; INC(i) END;
ELSE ext := NIL
END;
proc.conval.ext := ext;
INCL(proc.conval.setval, hasBody)
END GetCode;
PROCEDURE GetParams;
VAR name: DevCPT.String;
BEGIN
proc.mode := mode; proc.typ := DevCPT.notyp;
proc.sysflag := SHORT(sys);
proc.conval.setval := {};
IF sym = lparen THEN
DevCPS.Get(sym); FormalParameters(proc.link, proc.typ, name);
IF name # NIL THEN err(0) END
END;
CheckForwardTypes; userList := NIL;
IF fwd # NIL THEN
DevCPB.CheckParameters(proc.link, fwd.link, TRUE);
IF ~DevCPT.EqualType(proc.typ, fwd.typ) THEN err(117) END ;
proc := fwd; DevCPT.topScope := proc.scope;
IF mode = IProc THEN proc.mode := IProc END
END
END GetParams;
PROCEDURE Body;
VAR procdec, statseq: DevCPT.Node; c: INTEGER;
BEGIN
c := DevCPM.errpos;
INCL(proc.conval.setval, hasBody);
CheckSym(semicolon); Block(procdec, statseq);
DevCPB.Enter(procdec, statseq, proc); x := procdec;
x.conval := DevCPT.NewConst(); x.conval.intval := c; x.conval.intval2 := DevCPM.startpos;
CheckSym(end);
IF sym = ident THEN
IF DevCPS.name # proc.name^ THEN err(4) END ;
DevCPS.Get(sym)
ELSE err(ident)
END
END Body;
PROCEDURE TProcDecl;
VAR baseProc, o: DevCPT.Object;
objTyp, recTyp: DevCPT.Struct;
objMode, objVis: BYTE;
objName: DevCPT.Name;
pnode: DevCPT.Node;
fwdAttr: SET;
BEGIN
DevCPS.Get(sym); mode := TProc;
IF level > 0 THEN err(73) END;
Receiver(objMode, objVis, objName, objTyp, recTyp);
IF sym = ident THEN
name := DevCPS.name;
DevCPT.FindField(name, recTyp, fwd);
DevCPT.FindBaseField(name, recTyp, baseProc);
IF (baseProc # NIL) & (baseProc.mode # TProc) THEN baseProc := NIL; err(1) END ;
IF fwd = baseProc THEN fwd := NIL END ;
IF (fwd # NIL) & (fwd.mnolev # level) THEN fwd := NIL END ;
IF (fwd # NIL) & (fwd.mode = TProc) & (fwd.conval.setval * {hasBody, absAttr, empAttr} = {}) THEN
(* there exists a corresponding forward declaration *)
proc := DevCPT.NewObj(); proc.leaf := TRUE;
proc.mode := TProc; proc.conval := DevCPT.NewConst();
CheckMark(proc);
IF fwd.vis # proc.vis THEN err(118) END;
fwdAttr := fwd.conval.setval
ELSE
IF fwd # NIL THEN err(1); fwd := NIL END ;
DevCPT.InsertField(name, recTyp, proc);
proc.mode := TProc; proc.conval := DevCPT.NewConst();
CheckMark(proc);
IF recTyp.strobj # NIL THEN (* preserve declaration order *)
o := recTyp.strobj.link;
IF o = NIL THEN recTyp.strobj.link := proc
ELSE
WHILE o.nlink # NIL DO o := o.nlink END;
o.nlink := proc
END
END
END;
INC(level); DevCPT.OpenScope(level, proc);
DevCPT.Insert(objName, proc.link); proc.link.mode := objMode; proc.link.vis := objVis; proc.link.typ := objTyp;
ASSERT(DevCPT.topScope # NIL);
GetParams; (* may change proc := fwd !!! *)
ASSERT(DevCPT.topScope # NIL);
GetAttributes(proc, baseProc, recTyp);
IF (fwd # NIL) & (fwdAttr / proc.conval.setval * {absAttr, empAttr, extAttr} # {}) THEN err(184) END;
CheckOverwrite(proc, baseProc, recTyp);
IF ~forward THEN
IF empAttr IN proc.conval.setval THEN (* insert empty procedure *)
pnode := NIL; DevCPB.Enter(pnode, NIL, proc);
pnode.conval := DevCPT.NewConst();
pnode.conval.intval := DevCPM.errpos;
pnode.conval.intval2 := DevCPM.errpos;
x := pnode;
ELSIF DevCPM.noCode IN DevCPM.options THEN INCL(proc.conval.setval, hasBody)
ELSIF ~(absAttr IN proc.conval.setval) THEN Body
END;
proc.adr := 0
ELSE
proc.adr := DevCPM.errpos;
IF proc.conval.setval * {empAttr, absAttr} # {} THEN err(184) END
END;
DEC(level); DevCPT.CloseScope;
ELSE err(ident)
END;
END TProcDecl;
BEGIN proc := NIL; forward := FALSE; x := NIL; mode := LProc; sys := 0;
IF (sym # ident) & (sym # lparen) THEN
CheckSysFlag(sys, DevCPM.GetProcSysFlag);
IF sys # 0 THEN
IF ODD(sys DIV DevCPM.CProcFlag) THEN mode := CProc END
ELSE
IF sym = times THEN (* mode set later in DevCPB.CheckAssign *)
ELSIF sym = arrow THEN forward := TRUE
ELSE err(ident)
END;
DevCPS.Get(sym)
END
END ;
IF sym = lparen THEN TProcDecl
ELSIF sym = ident THEN DevCPT.Find(DevCPS.name, fwd);
name := DevCPS.name;
IF (fwd # NIL) & ((fwd.mnolev # level) OR (fwd.mode = SProc)) THEN fwd := NIL END ;
IF (fwd # NIL) & (fwd.mode IN {LProc, XProc}) & ~(hasBody IN fwd.conval.setval) THEN
(* there exists a corresponding forward declaration *)
proc := DevCPT.NewObj(); proc.leaf := TRUE;
proc.mode := mode; proc.conval := DevCPT.NewConst();
CheckMark(proc);
IF fwd.vis # proc.vis THEN err(118) END
ELSE
IF fwd # NIL THEN err(1); fwd := NIL END ;
DevCPT.Insert(name, proc);
proc.mode := mode; proc.conval := DevCPT.NewConst();
CheckMark(proc);
END ;
IF (proc.vis # internal) & (mode = LProc) THEN mode := XProc END ;
IF (mode # LProc) & (level > 0) THEN err(73) END ;
INC(level); DevCPT.OpenScope(level, proc);
proc.link := NIL; GetParams; (* may change proc := fwd !!! *)
IF mode = CProc THEN GetCode
ELSIF DevCPM.noCode IN DevCPM.options THEN INCL(proc.conval.setval, hasBody)
ELSIF ~forward THEN Body; proc.adr := 0
ELSE proc.adr := DevCPM.errpos
END ;
DEC(level); DevCPT.CloseScope
ELSE err(ident)
END
END ProcedureDeclaration;
PROCEDURE CaseLabelList(VAR lab, root: DevCPT.Node; LabelForm: SHORTINT; VAR min, max: INTEGER);
VAR x, y: DevCPT.Node; f: SHORTINT; xval, yval: INTEGER;
PROCEDURE Insert(VAR n: DevCPT.Node); (* build binary tree of label ranges *) (* !!! *)
BEGIN
IF n = NIL THEN
IF x.hint # 1 THEN n := x END
ELSIF yval < n.conval.intval THEN Insert(n.left)
ELSIF xval > n.conval.intval2 THEN Insert(n.right)
ELSE err(63)
END
END Insert;
BEGIN lab := NIL;
LOOP ConstExpression(x); f := x.typ.form;
IF f IN {Int8..Int32} + charSet THEN xval := x.conval.intval
ELSE err(61); xval := 1
END ;
IF (f IN {Int8..Int32}) # (LabelForm IN {Int8..Int32}) THEN err(60) END;
IF sym = upto THEN
DevCPS.Get(sym); ConstExpression(y); yval := y.conval.intval;
IF (y.typ.form IN {Int8..Int32}) # (LabelForm IN {Int8..Int32}) THEN err(60) END;
IF yval < xval THEN err(63); yval := xval END
ELSE yval := xval
END ;
x.conval.intval2 := yval;
IF xval < min THEN min := xval END;
IF yval > max THEN max := yval END;
IF lab = NIL THEN lab := x; Insert(root)
ELSIF yval < lab.conval.intval - 1 THEN x.link := lab; lab := x; Insert(root)
ELSIF yval = lab.conval.intval - 1 THEN x.hint := 1; Insert(root); lab.conval.intval := xval
ELSIF xval = lab.conval.intval2 + 1 THEN x.hint := 1; Insert(root); lab.conval.intval2 := yval
ELSE
y := lab;
WHILE (y.link # NIL) & (xval > y.link.conval.intval2 + 1) DO y := y.link END;
IF y.link = NIL THEN y.link := x; Insert(root)
ELSIF yval < y.link.conval.intval - 1 THEN x.link := y.link; y.link := x; Insert(root)
ELSIF yval = y.link.conval.intval - 1 THEN x.hint := 1; Insert(root); y.link.conval.intval := xval
ELSIF xval = y.link.conval.intval2 + 1 THEN x.hint := 1; Insert(root); y.link.conval.intval2 := yval
END
END;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF (sym = number) OR (sym = ident) THEN err(comma)
ELSE EXIT
END
END
END CaseLabelList;
PROCEDURE StatSeq(VAR stat: DevCPT.Node);
VAR fpar, id, t: DevCPT.Object; idtyp: DevCPT.Struct; e: BOOLEAN;
s, x, y, z, apar, last, lastif, pre, lastp: DevCPT.Node; pos, p: INTEGER;
PROCEDURE CasePart(VAR x: DevCPT.Node);
VAR low, high: INTEGER; e: BOOLEAN; cases, lab, y, lastcase, root: DevCPT.Node;
BEGIN
Expression(x);
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126)
ELSIF x.typ.form = Int64 THEN err(260)
ELSIF ~(x.typ.form IN {Int8..Int32} + charSet) THEN err(125)
END ;
CheckSym(of); cases := NIL; lastcase := NIL; root := NIL;
low := MAX(INTEGER); high := MIN(INTEGER);
LOOP
IF sym < bar THEN
CaseLabelList(lab, root, x.typ.form, low, high);
CheckSym(colon); StatSeq(y);
DevCPB.Construct(Ncasedo, lab, y); DevCPB.Link(cases, lastcase, lab)
END ;
IF sym = bar THEN DevCPS.Get(sym) ELSE EXIT END
END;
e := sym = else;
IF e THEN DevCPS.Get(sym); StatSeq(y) ELSE y := NIL END ;
DevCPB.Construct(Ncaselse, cases, y); DevCPB.Construct(Ncase, x, cases);
cases.conval := DevCPT.NewConst();
cases.conval.intval := low; cases.conval.intval2 := high;
IF e THEN cases.conval.setval := {1} ELSE cases.conval.setval := {} END;
DevCPB.OptimizeCase(root); cases.link := root (* !!! *)
END CasePart;
PROCEDURE SetPos(x: DevCPT.Node);
BEGIN
x.conval := DevCPT.NewConst(); x.conval.intval := pos
END SetPos;
PROCEDURE CheckBool(VAR x: DevCPT.Node);
BEGIN
IF (x.class = Ntype) OR (x.class = Nproc) THEN err(126); x := DevCPB.NewBoolConst(FALSE)
ELSIF x.typ.form # Bool THEN err(120); x := DevCPB.NewBoolConst(FALSE)
END
END CheckBool;
BEGIN stat := NIL; last := NIL;
LOOP x := NIL;
IF sym < ident THEN err(14);
REPEAT DevCPS.Get(sym) UNTIL sym >= ident
END ;
pos := DevCPM.startpos;
IF sym = ident THEN
qualident(id); x := DevCPB.NewLeaf(id); selector(x);
IF sym = becomes THEN
DevCPS.Get(sym); Expression(y);
IF (y.typ.form = Pointer) & (x.typ.form = Comp) THEN DevCPB.DeRef(y) END;
pre := NIL; lastp := NIL;
DevCPB.CheckBuffering(y, x, NIL, pre, lastp);
DevCPB.Assign(x, y);
IF pre # NIL THEN SetPos(x); DevCPB.Construct(Ncomp, pre, x); x := pre END;
ELSIF sym = eql THEN
err(becomes); DevCPS.Get(sym); Expression(y); DevCPB.Assign(x, y)
ELSIF (x.class = Nproc) & (x.obj.mode = SProc) THEN
StandProcCall(x);
IF (x # NIL) & (x.typ # DevCPT.notyp) THEN err(55) END;
IF (x # NIL) & (x.class = Nifelse) THEN (* error pos for ASSERT *)
SetPos(x.left); SetPos(x.left.right)
END
ELSIF x.class = Ncall THEN err(55)
ELSE
pre := NIL; lastp := NIL;
DevCPB.PrepCall(x, fpar);
IF (x.obj # NIL) & (x.obj.mode = TProc) THEN DevCPB.CheckBuffering(x.left, NIL, x.obj.link, pre, lastp) END;
IF sym = lparen THEN
DevCPS.Get(sym); ActualParameters(apar, fpar, pre, lastp); CheckSym(rparen)
ELSE apar := NIL;
IF fpar # NIL THEN err(65) END
END ;
DevCPB.Call(x, apar, fpar);
IF x.typ # DevCPT.notyp THEN err(55) END;
IF pre # NIL THEN SetPos(x); DevCPB.Construct(Ncomp, pre, x); x := pre END;
IF level > 0 THEN DevCPT.topScope.link.leaf := FALSE END
END
ELSIF sym = if THEN
DevCPS.Get(sym); pos := DevCPM.startpos; Expression(x); CheckBool(x); CheckSym(then); StatSeq(y);
DevCPB.Construct(Nif, x, y); SetPos(x); lastif := x;
WHILE sym = elsif DO
DevCPS.Get(sym); pos := DevCPM.startpos; Expression(y); CheckBool(y); CheckSym(then); StatSeq(z);
DevCPB.Construct(Nif, y, z); SetPos(y); DevCPB.Link(x, lastif, y)
END ;
pos := DevCPM.startpos;
IF sym = else THEN DevCPS.Get(sym); StatSeq(y) ELSE y := NIL END ;
DevCPB.Construct(Nifelse, x, y); CheckSym(end); DevCPB.OptIf(x);
ELSIF sym = case THEN
DevCPS.Get(sym); pos := DevCPM.startpos; CasePart(x); CheckSym(end)
ELSIF sym = while THEN
DevCPS.Get(sym); pos := DevCPM.startpos; Expression(x); CheckBool(x); CheckSym(do); StatSeq(y);
DevCPB.Construct(Nwhile, x, y); CheckSym(end)
ELSIF sym = repeat THEN
DevCPS.Get(sym); StatSeq(x);
IF sym = until THEN DevCPS.Get(sym); pos := DevCPM.startpos; Expression(y); CheckBool(y)
ELSE err(43)
END ;
DevCPB.Construct(Nrepeat, x, y)
ELSIF sym = for THEN
DevCPS.Get(sym); pos := DevCPM.startpos;
IF sym = ident THEN qualident(id);
IF ~(id.typ.form IN intSet) THEN err(68) END ;
CheckSym(becomes); Expression(y);
x := DevCPB.NewLeaf(id); DevCPB.Assign(x, y); SetPos(x);
CheckSym(to); pos := DevCPM.startpos; Expression(y);
IF y.class # Nconst THEN
DevCPB.GetTempVar("@for", x.left.typ, t);
z := DevCPB.NewLeaf(t); DevCPB.Assign(z, y); SetPos(z); DevCPB.Link(stat, last, z);
y := DevCPB.NewLeaf(t)
ELSE
DevCPB.CheckAssign(x.left.typ, y)
END ;
DevCPB.Link(stat, last, x);
p := DevCPM.startpos;
IF sym = by THEN DevCPS.Get(sym); ConstExpression(z) ELSE z := DevCPB.NewIntConst(1) END ;
x := DevCPB.NewLeaf(id);
IF z.conval.intval > 0 THEN DevCPB.Op(leq, x, y)
ELSIF z.conval.intval < 0 THEN DevCPB.Op(geq, x, y)
ELSE err(63); DevCPB.Op(geq, x, y)
END ;
CheckSym(do); StatSeq(s);
y := DevCPB.NewLeaf(id); DevCPB.StPar1(y, z, incfn); pos := DevCPM.startpos; SetPos(y);
IF s = NIL THEN s := y
ELSE z := s;
WHILE z.link # NIL DO z := z.link END ;
z.link := y
END ;
CheckSym(end); DevCPB.Construct(Nwhile, x, s); pos := p
ELSE err(ident)
END
ELSIF sym = loop THEN
DevCPS.Get(sym); INC(LoopLevel); StatSeq(x); DEC(LoopLevel);
DevCPB.Construct(Nloop, x, NIL); CheckSym(end)
ELSIF sym = with THEN
DevCPS.Get(sym); idtyp := NIL; x := NIL;
LOOP
IF sym < bar THEN
pos := DevCPM.startpos;
IF sym = ident THEN
qualident(id); y := DevCPB.NewLeaf(id);
IF (id # NIL) & (id.typ.form = Pointer) & ((id.mode = VarPar) OR ~id.leaf) THEN
err(-302) (* warning 302 *)
END ;
CheckSym(colon);
IF sym = ident THEN qualident(t);
IF t.mode = Typ THEN
IF id # NIL THEN
idtyp := id.typ; DevCPB.TypTest(y, t, FALSE); id.typ := t.typ;
IF id.ptyp = NIL THEN id.ptyp := idtyp END
ELSE err(130)
END
ELSE err(52)
END
ELSE err(ident)
END
ELSE err(ident)
END ;
CheckSym(do); StatSeq(s); DevCPB.Construct(Nif, y, s); SetPos(y);
IF idtyp # NIL THEN
IF id.ptyp = idtyp THEN id.ptyp := NIL END;
id.typ := idtyp; idtyp := NIL
END ;
IF x = NIL THEN x := y; lastif := x ELSE DevCPB.Link(x, lastif, y) END
END;
IF sym = bar THEN DevCPS.Get(sym) ELSE EXIT END
END;
e := sym = else; pos := DevCPM.startpos;
IF e THEN DevCPS.Get(sym); StatSeq(s) ELSE s := NIL END ;
DevCPB.Construct(Nwith, x, s); CheckSym(end);
IF e THEN x.subcl := 1 END
ELSIF sym = exit THEN
DevCPS.Get(sym);
IF LoopLevel = 0 THEN err(46) END ;
DevCPB.Construct(Nexit, x, NIL)
ELSIF sym = return THEN DevCPS.Get(sym);
IF sym < semicolon THEN Expression(x) END ;
IF level > 0 THEN DevCPB.Return(x, DevCPT.topScope.link)
ELSE (* not standard Oberon *) DevCPB.Return(x, NIL)
END;
hasReturn := TRUE
END ;
IF x # NIL THEN SetPos(x); DevCPB.Link(stat, last, x) END ;
IF sym = semicolon THEN DevCPS.Get(sym)
ELSIF (sym <= ident) OR (if <= sym) & (sym <= return) THEN err(semicolon)
ELSE EXIT
END
END
END StatSeq;
PROCEDURE Block(VAR procdec, statseq: DevCPT.Node);
VAR typ: DevCPT.Struct;
obj, first, last, o: DevCPT.Object;
x, lastdec: DevCPT.Node;
i: SHORTINT;
rname: DevCPT.Name;
name: DevCPT.String;
rec: Elem;
BEGIN
IF ((sym < begin) OR (sym > var)) & (sym # procedure) & (sym # end) & (sym # close) THEN err(36) END;
first := NIL; last := NIL; userList := NIL; recList := NIL;
LOOP
IF sym = const THEN
DevCPS.Get(sym);
WHILE sym = ident DO
DevCPT.Insert(DevCPS.name, obj);
obj.mode := Con; CheckMark(obj);
obj.typ := DevCPT.int8typ; obj.mode := Var; (* Var to avoid recursive definition *)
IF sym = eql THEN
DevCPS.Get(sym); ConstExpression(x)
ELSIF sym = becomes THEN
err(eql); DevCPS.Get(sym); ConstExpression(x)
ELSE err(eql); x := DevCPB.NewIntConst(1)
END ;
obj.mode := Con; obj.typ := x.typ; obj.conval := x.conval; (* ConstDesc is not copied *)
CheckSym(semicolon)
END
END ;
IF sym = type THEN
DevCPS.Get(sym);
WHILE sym = ident DO
DevCPT.Insert(DevCPS.name, obj); obj.mode := Typ; obj.typ := DevCPT.undftyp;
CheckMark(obj); obj.mode := -1;
IF sym # eql THEN err(eql) END;
IF (sym = eql) OR (sym = becomes) OR (sym = colon) THEN
DevCPS.Get(sym); Type(obj.typ, name); SetType(NIL, obj, obj.typ, name);
END;
obj.mode := Typ;
IF obj.typ.form IN {Byte..Set, Char16, Int64} THEN (* make alias structure *)
typ := DevCPT.NewStr(obj.typ.form, Basic); i := typ.ref;
typ^ := obj.typ^; typ.ref := i; typ.strobj := NIL; typ.mno := 0; typ.txtpos := DevCPM.errpos;
typ.BaseTyp := obj.typ; obj.typ := typ;
END;
IF obj.typ.strobj = NIL THEN obj.typ.strobj := obj END ;
IF obj.typ.form = Pointer THEN (* !!! *)
typ := obj.typ.BaseTyp;
IF (typ # NIL) & (typ.comp = Record) & (typ.strobj = NIL) THEN
(* pointer to unnamed record: name record as "pointerName^" *)
rname := obj.name$; i := 0;
WHILE rname[i] # 0X DO INC(i) END;
rname[i] := "^"; rname[i+1] := 0X;
DevCPT.Insert(rname, o); o.mode := Typ; o.typ := typ; typ.strobj := o
END
END;
IF obj.vis # internal THEN
typ := obj.typ;
IF typ.form = Pointer THEN typ := typ.BaseTyp END;
IF typ.comp = Record THEN typ.exp := TRUE END
END;
CheckSym(semicolon)
END
END ;
IF sym = var THEN
DevCPS.Get(sym);
WHILE sym = ident DO
LOOP
IF sym = ident THEN
DevCPT.Insert(DevCPS.name, obj);
obj.mode := Var; obj.link := NIL; obj.leaf := obj.vis = internal; obj.typ := DevCPT.undftyp;
CheckMark(obj);
IF first = NIL THEN first := obj END ;
IF last = NIL THEN DevCPT.topScope.scope := obj ELSE last.link := obj END ;
last := obj
ELSE err(ident)
END ;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF sym = ident THEN err(comma)
ELSE EXIT
END
END ;
CheckSym(colon); Type(typ, name);
CheckAlloc(typ, FALSE, DevCPM.errpos);
WHILE first # NIL DO SetType(NIL, first, typ, name); first := first.link END ;
CheckSym(semicolon)
END
END ;
IF (sym < const) OR (sym > var) THEN EXIT END ;
END ;
CheckForwardTypes;
userList := NIL; rec := recList; recList := NIL;
DevCPT.topScope.adr := DevCPM.errpos;
procdec := NIL; lastdec := NIL;
IF (sym # procedure) & (sym # begin) & (sym # end) & (sym # close) THEN err(37) END;
WHILE sym = procedure DO
DevCPS.Get(sym); ProcedureDeclaration(x);
IF x # NIL THEN
IF lastdec = NIL THEN procdec := x ELSE lastdec.link := x END ;
lastdec := x
END ;
CheckSym(semicolon)
END ;
IF DevCPM.noerr & ~(DevCPM.oberon IN DevCPM.options) THEN CheckRecords(rec) END;
hasReturn := FALSE;
IF (sym # begin) & (sym # end) & (sym # close) THEN err(38) END;
IF sym = begin THEN DevCPS.Get(sym); StatSeq(statseq)
ELSE statseq := NIL
END ;
IF (DevCPT.topScope.link # NIL) & (DevCPT.topScope.link.typ # DevCPT.notyp)
& ~hasReturn & (DevCPT.topScope.link.sysflag = 0) THEN err(133) END;
IF (level = 0) & (TDinit # NIL) THEN
lastTDinit.link := statseq; statseq := TDinit
END
END Block;
PROCEDURE Module*(VAR prog: DevCPT.Node);
VAR impName, aliasName: DevCPT.Name;
procdec, statseq: DevCPT.Node;
c: INTEGER; done: BOOLEAN;
BEGIN
DevCPS.Init; LoopLevel := 0; level := 0; DevCPS.Get(sym);
IF sym = module THEN DevCPS.Get(sym) ELSE err(16) END ;
IF sym = ident THEN
DevCPT.Open(DevCPS.name); DevCPS.Get(sym);
DevCPT.libName := "";
IF sym = lbrak THEN
INCL(DevCPM.options, DevCPM.interface); DevCPS.Get(sym);
IF sym = eql THEN DevCPS.Get(sym)
ELSE INCL(DevCPM.options, DevCPM.noCode)
END;
IF sym = string THEN DevCPT.libName := DevCPS.str$; DevCPS.Get(sym)
ELSE err(string)
END;
CheckSym(rbrak)
END;
CheckSym(semicolon);
IF sym = import THEN DevCPS.Get(sym);
LOOP
IF sym = ident THEN
aliasName := DevCPS.name$; impName := aliasName$; DevCPS.Get(sym);
IF sym = becomes THEN DevCPS.Get(sym);
IF sym = ident THEN impName := DevCPS.name$; DevCPS.Get(sym) ELSE err(ident) END
END ;
DevCPT.Import(aliasName, impName, done)
ELSE err(ident)
END ;
IF sym = comma THEN DevCPS.Get(sym)
ELSIF sym = ident THEN err(comma)
ELSE EXIT
END
END ;
CheckSym(semicolon)
END ;
IF DevCPM.noerr THEN TDinit := NIL; lastTDinit := NIL; c := DevCPM.errpos;
Block(procdec, statseq); DevCPB.Enter(procdec, statseq, NIL); prog := procdec;
prog.conval := DevCPT.NewConst(); prog.conval.intval := c; prog.conval.intval2 := DevCPM.startpos;
IF sym = close THEN DevCPS.Get(sym); StatSeq(prog.link) END;
prog.conval.realval := DevCPM.startpos;
CheckSym(end);
IF sym = ident THEN
IF DevCPS.name # DevCPT.SelfName THEN err(4) END ;
DevCPS.Get(sym)
ELSE err(ident)
END;
IF sym # period THEN err(period) END
END
ELSE err(ident)
END ;
TDinit := NIL; lastTDinit := NIL;
DevCPS.str := NIL
END Module;
END DevCPP.
| Dev/Mod/CPP.odc |
MODULE DevCPS;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, lstr added & Str changed (Unicode support)
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20160324, center #111, code cleanups
- 20170612, center #160, outdated link to OP2.Paper.ps
"
issues = "
- ...
"
**)
IMPORT SYSTEM, Math, Strings, Utf, DevCPM, DevCPT;
CONST
MaxIdLen = LEN(DevCPT.Name);
(* name, str, numtyp, intval, realval, realval are implicit results of Get *)
VAR
name*: DevCPT.Name;
str*: DevCPT.String;
lstr*: POINTER TO ARRAY OF CHAR;
numtyp*: SHORTINT; (* 1 = char, 2 = integer, 4 = real, 5 = int64, 6 = real32, 7 = real64 *)
intval*: INTEGER; (* integer value or string length (incl. 0X) *)
realval*: REAL;
CONST
(* numtyp values *)
char = 1; integer = 2; real = 4; int64 = 5; real32 = 6; real64 = 7;
(*symbol values*)
null = 0; times = 1; slash = 2; div = 3; mod = 4;
and = 5; plus = 6; minus = 7; or = 8; eql = 9;
neq = 10; lss = 11; leq = 12; gtr = 13; geq = 14;
in = 15; is = 16; arrow = 17; dollar = 18; period = 19;
comma = 20; colon = 21; upto = 22; rparen = 23; rbrak = 24;
rbrace = 25; of = 26; then = 27; do = 28; to = 29;
by = 30; not = 33;
lparen = 40; lbrak = 41; lbrace = 42; becomes = 44;
number = 45; nil = 46; string = 47; ident = 48; semicolon = 49;
bar = 50; end = 51; else = 52; elsif = 53; until = 54;
if = 55; case = 56; while = 57; repeat = 58; for = 59;
loop = 60; with = 61; exit = 62; return = 63; array = 64;
record = 65; pointer = 66; begin = 67; const = 68; type = 69;
var = 70; out = 71; procedure = 72; close = 73; import = 74;
module = 75; eof = 76;
VAR
ch: CHAR; (*current character*)
PROCEDURE err(n: SHORTINT);
BEGIN DevCPM.err(n)
END err;
PROCEDURE Str(VAR sym: BYTE);
VAR i: INTEGER; och: CHAR; lch: CHAR; long: BOOLEAN;
s: ARRAY 256 OF CHAR; t: POINTER TO ARRAY OF CHAR;
BEGIN i := 0; och := ch; long := FALSE;
LOOP DevCPM.Get(lch);
IF lch = och THEN EXIT END ;
IF (lch < " ") & (lch # 9X) THEN err(3); EXIT END;
IF lch > 0FFX THEN long := TRUE END;
IF i < LEN(s) - 1 THEN s[i] := lch
ELSIF i = LEN(s) - 1 THEN s[i] := 0X; NEW(lstr, 2 * LEN(s)); lstr^ := s$; lstr[i] := lch
ELSIF i < LEN(lstr^) - 1 THEN lstr[i] := lch
ELSE t := lstr; t[i] := 0X; NEW(lstr, 2 * LEN(t^)); lstr^ := t^$; lstr[i] := lch
END;
INC(i)
END ;
IF i = 1 THEN sym := number; numtyp := 1; intval := ORD(s[0])
ELSE
sym := string; numtyp := 0; intval := i + 1; NEW(str, intval);
IF long THEN
IF i < LEN(s) THEN s[i] := 0X; NEW(lstr, intval); lstr^ := s$
ELSE lstr[i] := 0X
END;
str^ := SHORT(lstr$)
ELSE
IF i < LEN(s) THEN s[i] := 0X; str^ := SHORT(s$);
ELSE lstr[i] := 0X; str^ := SHORT(lstr$)
END;
lstr := NIL
END
END;
DevCPM.Get(ch)
END Str;
PROCEDURE Identifier(VAR sym: BYTE);
VAR i, res: INTEGER; n: ARRAY MaxIdLen OF CHAR;
BEGIN i := 0;
REPEAT
n[i] := ch; INC(i); DevCPM.Get(ch)
UNTIL ~Strings.IsIdent(ch) OR (i = MaxIdLen);
IF i = MaxIdLen THEN err(240); DEC(i) END ;
n[i] := 0X; Utf.StringToUtf8(n, name, res); sym := ident;
IF res = 1 (*truncated*) THEN err(240) END
END Identifier;
PROCEDURE Number;
VAR i, j, m, n, d, e, a: INTEGER; f, g: REAL; tch: CHAR; neg: BOOLEAN; r: SHORTREAL;
dig: ARRAY 30 OF CHAR; arr: ARRAY 2 OF INTEGER;
PROCEDURE Ord(ch: CHAR; hex: BOOLEAN): INTEGER;
BEGIN (* ("0" <= ch) & (ch <= "9") OR ("A" <= ch) & (ch <= "F") *)
IF ch <= "9" THEN RETURN ORD(ch) - ORD("0")
ELSIF hex THEN RETURN ORD(ch) - ORD("A") + 10
ELSE err(2); RETURN 0
END
END Ord;
BEGIN (* ("0" <= ch) & (ch <= "9") *)
i := 0; m := 0; n := 0; d := 0;
LOOP (* read mantissa *)
IF ("0" <= ch) & (ch <= "9") OR (d = 0) & ("A" <= ch) & (ch <= "F") THEN
IF (m > 0) OR (ch # "0") THEN (* ignore leading zeros *)
IF n < LEN(dig) THEN dig[n] := ch; INC(n) END;
INC(m)
END;
DevCPM.Get(ch); INC(i)
ELSIF ch = "." THEN DevCPM.Get(ch);
IF ch = "." THEN (* ellipsis *) ch := 7FX; EXIT
ELSIF d = 0 THEN (* i > 0 *) d := i
ELSE err(2)
END
ELSE EXIT
END
END; (* 0 <= n <= m <= i, 0 <= d <= i *)
IF d = 0 THEN (* integer *) realval := 0; numtyp := integer;
IF n = m THEN intval := 0; i := 0;
IF ch = "X" THEN (* character *) DevCPM.Get(ch); numtyp := char;
IF n <= 4 THEN
WHILE i < n DO intval := intval*10H + Ord(dig[i], TRUE); INC(i) END
ELSE err(203)
END
ELSIF (ch = "H") OR (ch = "S") THEN (* hex 32bit *)
tch := ch; DevCPM.Get(ch);
IF (ch = "L") & (DevCPM.oberon IN DevCPM.options) THEN (* old syntax: hex 64bit *)
DevCPM.searchpos := DevCPM.curpos - 2; DevCPM.Get(ch);
IF n <= 16 THEN
IF (n = 16) & (dig[0] > "7") THEN realval := -1 END;
WHILE (i < n) & (i < 10) DO realval := realval * 10H + Ord(dig[i], TRUE); INC(i) END;
WHILE i < n DO realval := realval * 10H; intval := intval * 10H + Ord(dig[i], TRUE); INC(i) END;
numtyp := int64
ELSE err(203)
END
ELSIF n <= 8 THEN
IF (n = 8) & (dig[0] > "7") THEN (* prevent overflow *) intval := -1 END;
WHILE i < n DO intval := intval*10H + Ord(dig[i], TRUE); INC(i) END;
IF tch = "S" THEN (* 32 bit hex float *)
r := SYSTEM.VAL(SHORTREAL, intval);
realval := r; intval := 0; numtyp := real32
END
ELSE err(203)
END
ELSIF ch = "L" THEN (* hex 64bit *)
DevCPM.searchpos := DevCPM.curpos - 1; DevCPM.Get(ch);
IF n <= 16 THEN
IF (n = 16) & (dig[0] > "7") THEN realval := -1 END;
WHILE (i < n) & (i < 10) DO realval := realval * 10H + Ord(dig[i], TRUE); INC(i) END;
WHILE i < n DO realval := realval * 10H; intval := intval * 10H + Ord(dig[i], TRUE); INC(i) END;
numtyp := int64
ELSE err(203)
END
ELSIF ch = "R" THEN (* hex float 64bit *)
DevCPM.searchpos := DevCPM.curpos - 1; DevCPM.Get(ch);
IF n <= 16 THEN
a := 0; IF (n = 16) & (dig[0] > "7") THEN (* prevent overflow *) a := -1 END;
WHILE i < n-8 DO a := a*10H + Ord(dig[i], TRUE); INC(i) END;
IF DevCPM.LEHost THEN arr[1] := a ELSE arr[0] := a END;
a := 0; IF (n >= 8) & (dig[i] > "7") THEN (* prevent overflow *) a := -1 END;
WHILE i < n DO a := a*10H + Ord(dig[i], TRUE); INC(i) END;
IF DevCPM.LEHost THEN arr[0] := a ELSE arr[1] := a END;
realval := SYSTEM.VAL(REAL, arr);
intval := 0; numtyp := real64
ELSE err(203)
END
ELSE (* decimal *)
WHILE i < n DO d := Ord(dig[i], FALSE); INC(i);
a := (MAX(INTEGER) - d) DIV 10;
IF intval > a THEN
a := (intval - a + 65535) DIV 65536 * 65536;
realval := realval + a; intval := intval - a
END;
realval := realval * 10; intval := intval * 10 + d
END;
IF realval = 0 THEN numtyp := integer
ELSIF intval < 9223372036854775808.0E0 - realval THEN numtyp := int64 (* 2^63 *)
ELSE intval := 0; err(203)
END
END
ELSE err(203)
END
ELSE (* fraction *)
f := 0; g := 0; e := 0; j := 0;
WHILE (j < 15) & (j < n) DO g := g * 10 + Ord(dig[j], FALSE); INC(j) END; (* !!! *)
WHILE n > j DO (* 0 <= f < 1 *) DEC(n); f := (Ord(dig[n], FALSE) + f)/10 END;
IF (ch = "E") OR (ch = "D") & (DevCPM.oberon IN DevCPM.options) THEN
DevCPM.searchpos := DevCPM.curpos - 1; DevCPM.Get(ch); neg := FALSE;
IF ch = "-" THEN neg := TRUE; DevCPM.Get(ch)
ELSIF ch = "+" THEN DevCPM.Get(ch)
END;
IF ("0" <= ch) & (ch <= "9") THEN
REPEAT n := Ord(ch, FALSE); DevCPM.Get(ch);
IF e <= (MAX(SHORTINT) - n) DIV 10 THEN e := SHORT(e*10 + n)
ELSE err(203)
END
UNTIL (ch < "0") OR ("9" < ch);
IF neg THEN e := -e END
ELSE err(2)
END
END;
DEC(e, i-d-m); (* decimal point shift *)
IF e < -308 - 16 THEN
realval := 0.0
ELSIF e < -308 + 14 THEN
realval := (f + g) / Math.IntPower(10, j-e-30) / 1.0E15 / 1.0E15
ELSIF e < j THEN
realval := (f + g) / Math.IntPower(10, j-e) (* Ten(j-e) *)
ELSIF e <= 308 THEN
realval := (f + g) * Math.IntPower(10, e-j) (* Ten(e-j) *)
ELSIF e = 308 + 1 THEN
realval := (f + g) * (Math.IntPower(10, e-j) / 16);
IF realval <= DevCPM.MaxReal64 / 16 THEN realval := realval * 16
ELSE err(203)
END
ELSE err(203)
END;
numtyp := real
END
END Number;
PROCEDURE Get*(VAR sym: BYTE);
VAR s: BYTE; old: INTEGER;
PROCEDURE Comment; (* do not read after end of file *)
BEGIN DevCPM.Get(ch);
LOOP
LOOP
WHILE ch = "(" DO DevCPM.Get(ch);
IF ch = "*" THEN Comment END
END ;
IF ch = "*" THEN DevCPM.Get(ch); EXIT END ;
IF ch = DevCPM.Eot THEN EXIT END ;
DevCPM.Get(ch)
END ;
IF ch = ")" THEN DevCPM.Get(ch); EXIT END ;
IF ch = DevCPM.Eot THEN err(5); EXIT END
END
END Comment;
BEGIN
DevCPM.errpos := DevCPM.curpos-1;
WHILE (ch <= " ") OR (ch = 0A0X) DO (*ignore control characters*)
IF ch = DevCPM.Eot THEN sym := eof; RETURN
ELSE DevCPM.Get(ch)
END
END ;
DevCPM.startpos := DevCPM.curpos - 1;
CASE ch OF (* ch > " " *)
| 22X, 27X : Str(s)
| "#" : s := neq; DevCPM.Get(ch)
| "&" : s := and; DevCPM.Get(ch)
| "(" : DevCPM.Get(ch);
IF ch = "*" THEN Comment; old := DevCPM.errpos; Get(s); DevCPM.errpos := old;
ELSE s := lparen
END
| ")" : s := rparen; DevCPM.Get(ch)
| "*" : s := times; DevCPM.Get(ch)
| "+" : s := plus; DevCPM.Get(ch)
| "," : s := comma; DevCPM.Get(ch)
| "-" : s := minus; DevCPM.Get(ch)
| "." : DevCPM.Get(ch);
IF ch = "." THEN DevCPM.Get(ch); s := upto ELSE s := period END
| "/" : s := slash; DevCPM.Get(ch)
| "0".."9": Number; s := number
| ":" : DevCPM.Get(ch);
IF ch = "=" THEN DevCPM.Get(ch); s := becomes ELSE s := colon END
| ";" : s := semicolon; DevCPM.Get(ch)
| "<" : DevCPM.Get(ch);
IF ch = "=" THEN DevCPM.Get(ch); s := leq ELSE s := lss END
| "=" : s := eql; DevCPM.Get(ch)
| ">" : DevCPM.Get(ch);
IF ch = "=" THEN DevCPM.Get(ch); s := geq ELSE s := gtr END
| "A": Identifier(s); IF name = "ARRAY" THEN s := array END
| "B": Identifier(s);
IF name = "BEGIN" THEN s := begin
ELSIF name = "BY" THEN s := by
END
| "C": Identifier(s);
IF name = "CASE" THEN s := case
ELSIF name = "CONST" THEN s := const
ELSIF name = "CLOSE" THEN s := close
END
| "D": Identifier(s);
IF name = "DO" THEN s := do
ELSIF name = "DIV" THEN s := div
END
| "E": Identifier(s);
IF name = "END" THEN s := end
ELSIF name = "ELSE" THEN s := else
ELSIF name = "ELSIF" THEN s := elsif
ELSIF name = "EXIT" THEN s := exit
END
| "F": Identifier(s); IF name = "FOR" THEN s := for END
| "I": Identifier(s);
IF name = "IF" THEN s := if
ELSIF name = "IN" THEN s := in
ELSIF name = "IS" THEN s := is
ELSIF name = "IMPORT" THEN s := import
END
| "L": Identifier(s); IF name = "LOOP" THEN s := loop END
| "M": Identifier(s);
IF name = "MOD" THEN s := mod
ELSIF name = "MODULE" THEN s := module
END
| "N": Identifier(s); IF name = "NIL" THEN s := nil END
| "O": Identifier(s);
IF name = "OR" THEN s := or
ELSIF name = "OF" THEN s := of
ELSIF name = "OUT" THEN s := out
END
| "P": Identifier(s);
IF name = "PROCEDURE" THEN s := procedure
ELSIF name = "POINTER" THEN s := pointer
END
| "R": Identifier(s);
IF name = "RECORD" THEN s := record
ELSIF name = "REPEAT" THEN s := repeat
ELSIF name = "RETURN" THEN s := return
END
| "T": Identifier(s);
IF name = "THEN" THEN s := then
ELSIF name = "TO" THEN s := to
ELSIF name = "TYPE" THEN s := type
END
| "U": Identifier(s); IF name = "UNTIL" THEN s := until END
| "V": Identifier(s); IF name = "VAR" THEN s := var END
| "W": Identifier(s);
IF name = "WHILE" THEN s := while
ELSIF name = "WITH" THEN s := with
END
| "G".."H", "J", "K", "Q", "S", "X".."Z", "a".."z", "_": Identifier(s)
| "[" : s := lbrak; DevCPM.Get(ch)
| "]" : s := rbrak; DevCPM.Get(ch)
| "^" : s := arrow; DevCPM.Get(ch)
| "$" : s := dollar; DevCPM.Get(ch)
| "{" : s := lbrace; DevCPM.Get(ch);
| "|" : s := bar; DevCPM.Get(ch)
| "}" : s := rbrace; DevCPM.Get(ch)
| "~" : s := not; DevCPM.Get(ch)
| 7FX : s := upto; DevCPM.Get(ch)
ELSE
IF Strings.IsIdent(ch) THEN Identifier(s) ELSE s := null; DevCPM.Get(ch) END
END ;
sym := s
END Get;
PROCEDURE Init*;
BEGIN ch := " "
END Init;
END DevCPS. | Dev/Mod/CPS.odc |
MODULE DevCPT;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070123, bh, support for preocedure type sysflags
- 20070307, bh, Extends corrected for untagged records
- 20080208, bh, file checksum for symbol files
- 20080213, bh, pvfp and pbfp calculation in FPrintStr corrected
- 20140914, center #13, bug fix in FPrintHdFld and OutHdFld
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150511, center #46, fixing undetected interface change
- 20150513, center #43, extending the size of code procedures
- 20151012, center #77, InSign uses outBit insteadd of inBit for outPar
- 20160324, center #111, code cleanups
- 20170107, center #134, interface change not detected
- 20170215, center #139, localization support for error messages
- 20170612, center #160, outdated link to OP2.Paper.ps
- 20200623, center #208, assertfn added to Nifelse in Nodes section of documentation
"
issues = "
- ...
"
**)
IMPORT DevCPM;
CONST
MaxIdLen = 256;
TYPE
Name* = ARRAY MaxIdLen OF SHORTCHAR;
String* = POINTER TO ARRAY OF SHORTCHAR;
Const* = POINTER TO ConstDesc;
Object* = POINTER TO ObjDesc;
Struct* = POINTER TO StrDesc;
Node* = POINTER TO NodeDesc;
ConstExt* = String;
LinkList* = POINTER TO LinkDesc;
ConstDesc* = RECORD
ext*: ConstExt; (* string or code for code proc (longstring in utf8) *)
intval*: INTEGER; (* constant value or adr, proc par size, text position or least case label *)
intval2*: INTEGER; (* string length (#char, incl 0X), proc var size or larger case label *)
setval*: SET; (* constant value, procedure body present or "ELSE" present in case *)
realval*: REAL; (* real or longreal constant value *)
link*: Const (* chain of constants present in obj file *)
END ;
LinkDesc* = RECORD
offset*, linkadr*: INTEGER;
next*: LinkList;
END;
ObjDesc* = RECORD
left*, right*, link*, scope*: Object;
name*: String; (* name = null OR name^ # "" *)
leaf*: BOOLEAN;
sysflag*: BYTE;
mode*, mnolev*: BYTE; (* mnolev < 0 -> mno = -mnolev *)
vis*: BYTE; (* internal, external, externalR, inPar, outPar *)
history*: BYTE; (* relevant if name # "" *)
used*, fpdone*: BOOLEAN;
fprint*: INTEGER;
typ*: Struct; (* actual type, changed in with statements *)
ptyp*: Struct; (* original type if typ is changed *)
conval*: Const;
adr*, num*: INTEGER; (* mthno *)
links*: LinkList;
nlink*: Object; (* link for name list, declaration order for methods, library link for imp obj *)
library*, entry*: String; (* library name, entry name *)
modifiers*: POINTER TO ARRAY OF String; (* additional interface strings *)
linkadr*: INTEGER; (* used in ofront *)
red: BOOLEAN;
END ;
StrDesc* = RECORD
form*, comp*, mno*, extlev*: BYTE;
ref*, sysflag*: SHORTINT;
n*, size*, align*, txtpos*: INTEGER; (* align is alignment for records and len offset for dynarrs *)
untagged*, allocated*, pbused*, pvused*, exp*, fpdone, idfpdone: BOOLEAN;
attribute*: BYTE;
idfp, pbfp*, pvfp*:INTEGER;
BaseTyp*: Struct;
link*, strobj*: Object;
ext*: ConstExt (* id string for interface records *)
END ;
NodeDesc* = RECORD
left*, right*, link*: Node;
class*, subcl*, hint*: BYTE;
readonly*: BOOLEAN;
typ*: Struct;
obj*: Object;
conval*: Const
END ;
CONST
maxImps = 127; (* must be <= MAX(SHORTINT) *)
maxStruct = DevCPM.MaxStruct; (* must be < MAX(INTEGER) DIV 2 *)
FirstRef = 32;
FirstRef0 = 16; (* correction for version 0 *)
actVersion = 1;
VAR
topScope*: Object;
undftyp*, bytetyp*, booltyp*, char8typ*, int8typ*, int16typ*, int32typ*,
real32typ*, real64typ*, settyp*, string8typ*, niltyp*, notyp*, sysptrtyp*,
anytyp*, anyptrtyp*, char16typ*, string16typ*, int64typ*,
restyp*, iunktyp*, punktyp*, guidtyp*,
intrealtyp*, lreal64typ*, lint64typ*, lchar16typ*: Struct;
nofGmod*: BYTE; (*nof imports*)
GlbMod*: ARRAY maxImps OF Object; (* .right = first object, .name = module import name (not alias) *)
SelfName*: Name; (* name of module being compiled *)
SYSimported*: BOOLEAN;
processor*, impProc*: SHORTINT;
libName*: Name; (* library alias of module being compiled *)
null*: String; (* "" *)
CONST
(* object modes *)
Var = 1; VarPar = 2; Con = 3; Fld = 4; Typ = 5; LProc = 6; XProc = 7;
SProc = 8; CProc = 9; IProc = 10; Mod = 11; Head = 12; TProc = 13; Attr = 20;
(* structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
AnyPtr = 14; AnyRec = 15; (* sym file only *)
Char16 = 16; String16 = 17; Int64 = 18;
Res = 20; IUnk = 21; PUnk = 22; Guid = 23;
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(*function number*)
assign = 0;
haltfn = 0; newfn = 1; absfn = 2; capfn = 3; ordfn = 4;
entierfn = 5; oddfn = 6; minfn = 7; maxfn = 8; chrfn = 9;
shortfn = 10; longfn = 11; sizefn = 12; incfn = 13; decfn = 14;
inclfn = 15; exclfn = 16; lenfn = 17; copyfn = 18; ashfn = 19; assertfn = 32;
lchrfn = 33; lentierfcn = 34; typfn = 36; bitsfn = 37; bytesfn = 38;
(*SYSTEM function number*)
adrfn = 20; ccfn = 21; lshfn = 22; rotfn = 23;
getfn = 24; putfn = 25; getrfn = 26; putrfn = 27;
bitfn = 28; valfn = 29; sysnewfn = 30; movefn = 31;
thisrecfn = 45; thisarrfn = 46;
(* COM function number *)
validfn = 40; iidfn = 41; queryfn = 42;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval) *)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
(* procedure flags (conval.setval) *)
isHidden = 29;
(* module visibility of objects *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* history of imported objects *)
inserted = 0; same = 1; pbmodified = 2; pvmodified = 3; removed = 4; inconsistent = 5;
(* sysflags *)
inBit = 2; outBit = 4; interface = 10;
(* symbol file items *)
Smname = 16; Send = 18; Stype = 19; Salias = 20; Svar = 21; Srvar = 22;
Svalpar = 23; Svarpar = 24; Sfld = 25; Srfld = 26; Shdptr = 27; Shdpro = 28; Stpro = 29; Shdtpro = 30;
Sxpro = 31; Sipro = 32; Scpro = 33; Sstruct = 34; Ssys = 35; Sptr = 36; Sarr = 37; Sdarr = 38; Srec = 39; Spro = 40;
Shdutptr = 41; Slib = 42; Sentry = 43; Sinpar = 25; Soutpar = 26;
Slimrec = 25; Sabsrec = 26; Sextrec = 27; Slimpro = 31; Sabspro = 32; Semppro = 33; Sextpro = 34; Simpo = 22;
TYPE
ImpCtxt = RECORD
nextTag, reffp: INTEGER;
nofr, minr, nofm: SHORTINT;
self: BOOLEAN;
ref: ARRAY maxStruct OF Struct;
old: ARRAY maxStruct OF Object;
pvfp: ARRAY maxStruct OF INTEGER; (* set only if old # NIL *)
glbmno: ARRAY maxImps OF BYTE (* index is local mno *)
END ;
ExpCtxt = RECORD
reffp: INTEGER;
ref: SHORTINT;
nofm: BYTE;
locmno: ARRAY maxImps OF BYTE (* index is global mno *)
END ;
VAR
universe, syslink, comlink, infinity: Object;
impCtxt: ImpCtxt;
expCtxt: ExpCtxt;
nofhdfld: INTEGER;
sfpresent, symExtended, symNew: BOOLEAN;
version: INTEGER;
symChanges: INTEGER;
portable: BOOLEAN;
depth: INTEGER;
PROCEDURE err(n: SHORTINT);
BEGIN DevCPM.err(n)
END err;
PROCEDURE NewConst*(): Const;
VAR const: Const;
BEGIN NEW(const); RETURN const
END NewConst;
PROCEDURE NewObj*(): Object;
VAR obj: Object;
BEGIN NEW(obj); obj.name := null; RETURN obj
END NewObj;
PROCEDURE NewStr*(form, comp: BYTE): Struct;
VAR typ: Struct;
BEGIN NEW(typ); typ.form := form; typ.comp := comp; typ.ref := maxStruct; (* ref >= maxStruct: not exported yet *)
typ.txtpos := DevCPM.errpos; typ.size := -1; typ.BaseTyp := undftyp; RETURN typ
END NewStr;
PROCEDURE NewNode*(class: BYTE): Node;
VAR node: Node;
BEGIN
NEW(node); node.class := class; RETURN node
END NewNode;
PROCEDURE NewName* (IN name: ARRAY OF SHORTCHAR): String;
VAR i: INTEGER; p: String;
BEGIN
i := LEN(name$);
IF i > 0 THEN NEW(p, i + 1); p^ := name$; RETURN p
ELSE RETURN null
END
END NewName;
PROCEDURE OpenScope*(level: BYTE; owner: Object);
VAR head: Object;
BEGIN head := NewObj();
head.mode := Head; head.mnolev := level; head.link := owner;
IF owner # NIL THEN owner.scope := head END ;
head.left := topScope; head.right := NIL; head.scope := NIL; topScope := head
END OpenScope;
PROCEDURE CloseScope*;
BEGIN topScope := topScope.left
END CloseScope;
PROCEDURE Init*(opt: SET);
BEGIN
topScope := universe; OpenScope(0, NIL); SYSimported := FALSE;
GlbMod[0] := topScope; nofGmod := 1;
sfpresent := TRUE; (* !!! *)
symChanges := 0;
infinity.conval.intval := DevCPM.ConstNotAlloc;
depth := 0
END Init;
PROCEDURE Open* (IN name: Name);
BEGIN
SelfName := name$; topScope.name := NewName(name);
END Open;
PROCEDURE Close*;
VAR i: INTEGER;
BEGIN (* garbage collection *)
CloseScope;
i := 0; WHILE i < maxImps DO GlbMod[i] := NIL; INC(i) END ;
i := FirstRef; WHILE i < maxStruct DO impCtxt.ref[i] := NIL; impCtxt.old[i] := NIL; INC(i) END
END Close;
PROCEDURE SameType* (x, y: Struct): BOOLEAN;
BEGIN
RETURN (x = y) OR (x.form = y.form) & ~(x.form IN {Pointer, ProcTyp, Comp}) OR (x = undftyp) OR (y = undftyp)
END SameType;
PROCEDURE EqualType* (x, y: Struct): BOOLEAN;
VAR xp, yp: Object; n: INTEGER;
BEGIN
n := 0;
WHILE (n < 100) & (x # y)
& (((x.comp = DynArr) & (y.comp = DynArr) & (x.sysflag = y.sysflag))
OR ((x.form = Pointer) & (y.form = Pointer))
OR ((x.form = ProcTyp) & (y.form = ProcTyp))) DO
IF x.form = ProcTyp THEN
IF x.sysflag # y.sysflag THEN RETURN FALSE END;
xp := x.link; yp := y.link;
INC(depth);
WHILE (xp # NIL) & (yp # NIL) & (xp.mode = yp.mode) & (xp.sysflag = yp.sysflag)
& (xp.vis = yp.vis) & (depth < 100) & EqualType(xp.typ, yp.typ) DO
xp := xp.link; yp := yp.link
END;
DEC(depth);
IF (xp # NIL) OR (yp # NIL) THEN RETURN FALSE END
END;
x := x.BaseTyp; y := y.BaseTyp; INC(n)
END;
RETURN SameType(x, y)
END EqualType;
PROCEDURE Extends* (x, y: Struct): BOOLEAN;
BEGIN
IF (x.form = Pointer) & (y.form = Pointer) THEN x := x.BaseTyp; y := y.BaseTyp END;
IF (x.comp = Record) & (y.comp = Record) THEN
IF (y = anytyp) & ~x.untagged THEN RETURN TRUE END;
WHILE (x # NIL) & (x # undftyp) & (x # y) DO x := x.BaseTyp END
END;
RETURN (x # NIL) & EqualType(x, y)
END Extends;
PROCEDURE Includes* (xform, yform: INTEGER): BOOLEAN;
BEGIN
CASE xform OF
| Char16: RETURN yform IN {Char8, Char16, Int8}
| Int16: RETURN yform IN {Char8, Int8, Int16}
| Int32: RETURN yform IN {Char8, Char16, Int8, Int16, Int32}
| Int64: RETURN yform IN {Char8, Char16, Int8, Int16, Int32, Int64}
| Real32: RETURN yform IN {Char8, Char16, Int8, Int16, Int32, Int64, Real32}
| Real64: RETURN yform IN {Char8, Char16, Int8, Int16, Int32, Int64, Real32, Real64}
| String16: RETURN yform IN {String8, String16}
ELSE RETURN xform = yform
END
END Includes;
PROCEDURE FindImport*(IN name: Name; mod: Object; VAR res: Object);
VAR obj: Object; (* i: INTEGER; n: Name; *)
BEGIN obj := mod.scope.right;
LOOP
IF obj = NIL THEN EXIT END ;
IF name < obj.name^ THEN obj := obj.left
ELSIF name > obj.name^ THEN obj := obj.right
ELSE (*found*)
IF (obj.mode = Typ) & (obj.vis = internal) THEN obj := NIL
ELSE obj.used := TRUE
END ;
EXIT
END
END ;
res := obj;
(* bh: checks usage of non Unicode WinApi functions and types
IF (res # NIL) & (mod.scope.library # NIL)
& ~(DevCPM.interface IN DevCPM.options)
& (SelfName # "Kernel") & (SelfName # "HostPorts") THEN
n := name + "W";
FindImport(n, mod, obj);
IF obj # NIL THEN
DevCPM.err(733)
ELSE
i := LEN(name$);
IF name[i - 1] = "A" THEN
n[i - 1] := "W"; n[i] := 0X;
FindImport(n, mod, obj);
IF obj # NIL THEN
DevCPM.err(734)
END
END
END
END;
*)
END FindImport;
PROCEDURE Find*(IN name: Name; VAR res: Object);
VAR obj, head: Object;
BEGIN head := topScope;
LOOP obj := head.right;
LOOP
IF obj = NIL THEN EXIT END ;
IF name < obj.name^ THEN obj := obj.left
ELSIF name > obj.name^ THEN obj := obj.right
ELSE (* found, obj.used not set for local objects *) EXIT
END
END ;
IF obj # NIL THEN EXIT END ;
head := head.left;
IF head = NIL THEN EXIT END
END ;
res := obj
END Find;
PROCEDURE FindFld (IN name: ARRAY OF SHORTCHAR; typ: Struct; VAR res: Object);
VAR obj: Object;
BEGIN
WHILE (typ # NIL) & (typ # undftyp) DO obj := typ.link;
WHILE obj # NIL DO
IF name < obj.name^ THEN obj := obj.left
ELSIF name > obj.name^ THEN obj := obj.right
ELSE (*found*) res := obj; RETURN
END
END ;
typ := typ.BaseTyp
END;
res := NIL
END FindFld;
PROCEDURE FindField* (IN name: ARRAY OF SHORTCHAR; typ: Struct; VAR res: Object);
BEGIN
FindFld(name, typ, res);
IF (res = NIL) & ~typ.untagged THEN FindFld(name, anytyp, res) END
END FindField;
PROCEDURE FindBaseField* (IN name: ARRAY OF SHORTCHAR; typ: Struct; VAR res: Object);
BEGIN
FindFld(name, typ.BaseTyp, res);
IF (res = NIL) & ~typ.untagged THEN FindFld(name, anytyp, res) END
END FindBaseField;
(*
PROCEDURE Rotated (y: Object; name: String): Object;
VAR c, gc: Object;
BEGIN
IF name^ < y.name^ THEN
c := y.left;
IF name^ < c.name^ THEN gc := c.left; c.left := gc.right; gc.right := c
ELSE gc := c.right; c.right := gc.left; gc.left := c
END;
y.left := gc
ELSE
c := y.right;
IF name^ < c.name^ THEN gc := c.left; c.left := gc.right; gc.right := c
ELSE gc := c.right; c.right := gc.left; gc.left := c
END;
y.right := gc
END;
RETURN gc
END Rotated;
PROCEDURE InsertIn (obj, scope: Object; VAR old: Object);
VAR gg, g, p, x: Object; name, sname: String;
BEGIN
sname := scope.name; scope.name := null;
gg := scope; g := gg; p := g; x := p.right; name := obj.name;
WHILE x # NIL DO
IF (x.left # NIL) & (x.right # NIL) & x.left.red & x.right.red THEN
x.red := TRUE; x.left.red := FALSE; x.right.red := FALSE;
IF p.red THEN
g.red := TRUE;
IF (name^ < g.name^) # (name^ < p.name^) THEN p := Rotated(g, name) END;
x := Rotated(gg, name); x.red := FALSE
END
END;
gg := g; g := p; p := x;
IF name^ < x.name^ THEN x := x.left
ELSIF name^ > x.name^ THEN x := x.right
ELSE old := x; scope.right.red := FALSE; scope.name := sname; RETURN
END
END;
x := obj; old := NIL;
IF name^ < p.name^ THEN p.left := x ELSE p.right := x END;
x.red := TRUE;
IF p.red THEN
g.red := TRUE;
IF (name^ < g.name^) # (name^ < p.name^) THEN p := Rotated(g, name) END;
x := Rotated(gg, name);
x.red := FALSE
END;
scope.right.red := FALSE; scope.name := sname
END InsertIn;
*)
PROCEDURE InsertIn (obj, scope: Object; VAR old: Object);
VAR ob0, ob1: Object; left: BOOLEAN; name: String;
BEGIN
ASSERT((scope # NIL) & (scope.mode = Head), 100);
ob0 := scope; ob1 := scope.right; left := FALSE; name := obj.name;
WHILE ob1 # NIL DO
IF name^ < ob1.name^ THEN ob0 := ob1; ob1 := ob1.left; left := TRUE
ELSIF name^ > ob1.name^ THEN ob0 := ob1; ob1 := ob1.right; left := FALSE
ELSE old := ob1; RETURN
END
END;
IF left THEN ob0.left := obj ELSE ob0.right := obj END ;
obj.left := NIL; obj.right := NIL; old := NIL
END InsertIn;
PROCEDURE Insert* (IN name: Name; VAR obj: Object);
VAR old: Object;
BEGIN
obj := NewObj(); obj.leaf := TRUE;
obj.name := NewName(name);
obj.mnolev := topScope.mnolev;
InsertIn(obj, topScope, old);
IF old # NIL THEN err(1) END (*double def*)
END Insert;
PROCEDURE InsertThisField (obj: Object; typ: Struct; VAR old: Object);
VAR ob0, ob1: Object; left: BOOLEAN; name: String;
BEGIN
IF typ.link = NIL THEN typ.link := obj
ELSE
ob1 := typ.link; name := obj.name;
REPEAT
IF name^ < ob1.name^ THEN ob0 := ob1; ob1 := ob1.left; left := TRUE
ELSIF name^ > ob1.name^ THEN ob0 := ob1; ob1 := ob1.right; left := FALSE
ELSE old := ob1; RETURN
END
UNTIL ob1 = NIL;
IF left THEN ob0.left := obj ELSE ob0.right := obj END
END
END InsertThisField;
PROCEDURE InsertField* (IN name: Name; typ: Struct; VAR obj: Object);
VAR old: Object;
BEGIN
obj := NewObj(); obj.leaf := TRUE;
obj.name := NewName(name);
InsertThisField(obj, typ, old);
IF old # NIL THEN err(1) END (*double def*)
END InsertField;
(*-------------------------- Fingerprinting --------------------------*)
PROCEDURE FPrintName(VAR fp: INTEGER; IN name: ARRAY OF SHORTCHAR);
VAR i: INTEGER; ch: SHORTCHAR;
BEGIN i := 0;
REPEAT ch := name[i]; DevCPM.FPrint(fp, ORD(ch)); INC(i) UNTIL ch = 0X
END FPrintName;
PROCEDURE ^IdFPrint*(typ: Struct);
PROCEDURE FPrintSign*(VAR fp: INTEGER; result: Struct; par: Object);
(* depends on assignment compatibility of params only *)
BEGIN
IdFPrint(result); DevCPM.FPrint(fp, result.idfp);
WHILE par # NIL DO
DevCPM.FPrint(fp, par.mode); IdFPrint(par.typ); DevCPM.FPrint(fp, par.typ.idfp);
IF (par.mode = VarPar) & (par.vis # 0) THEN DevCPM.FPrint(fp, par.vis) END; (* IN / OUT *)
IF par.sysflag # 0 THEN DevCPM.FPrint(fp, par.sysflag) END;
(* par.name and par.adr not considered *)
par := par.link
END
END FPrintSign;
PROCEDURE IdFPrint*(typ: Struct); (* idfp codifies assignment compatibility *)
VAR btyp: Struct; strobj: Object; idfp: INTEGER; f, c: SHORTINT;
BEGIN
IF ~typ.idfpdone THEN
typ.idfpdone := TRUE; (* may be recursive, temporary idfp is 0 in that case *)
idfp := 0; f := typ.form; c := typ.comp; DevCPM.FPrint(idfp, f); DevCPM.FPrint(idfp, c);
btyp := typ.BaseTyp; strobj := typ.strobj;
IF (strobj # NIL) & (strobj.name # null) THEN
FPrintName(idfp, GlbMod[typ.mno].name^); FPrintName(idfp, strobj.name^)
END ;
IF (f = Pointer) OR (c = Record) & (btyp # NIL) OR (c = DynArr) THEN
IdFPrint(btyp); DevCPM.FPrint(idfp, btyp.idfp)
ELSIF c = Array THEN IdFPrint(btyp); DevCPM.FPrint(idfp, btyp.idfp); DevCPM.FPrint(idfp, typ.n)
ELSIF f = ProcTyp THEN FPrintSign(idfp, btyp, typ.link)
END ;
IF typ.sysflag # 0 THEN DevCPM.FPrint(idfp, typ.sysflag) END;
typ.idfp := idfp
END
END IdFPrint;
PROCEDURE FPrintStr*(typ: Struct);
VAR f, c: SHORTINT; btyp: Struct; strobj, bstrobj: Object; pbfp, pvfp: INTEGER;
PROCEDURE ^FPrintFlds(fld: Object; adr: INTEGER; visible: BOOLEAN);
PROCEDURE FPrintHdFld(typ: Struct; fld: Object; adr: INTEGER); (* modifies pvfp only *)
VAR i, j, n: INTEGER; btyp: Struct;
BEGIN
IF typ.comp = Record THEN
IF typ.BaseTyp # NIL THEN FPrintHdFld(typ.BaseTyp, fld, adr) END ;
FPrintFlds(typ.link, adr, FALSE)
ELSIF typ.comp = Array THEN btyp := typ.BaseTyp; n := typ.n;
WHILE btyp.comp = Array DO n := btyp.n * n; btyp := btyp.BaseTyp END ;
IF (btyp.form = Pointer) OR (btyp.comp = Record) THEN
j := nofhdfld; FPrintHdFld(btyp, fld, adr);
IF j # nofhdfld THEN i := 1;
WHILE (i < n) (* & (nofhdfld <= DevCPM.MaxHdFld) *) DO (* !!! *)
INC(adr, btyp.size); FPrintHdFld(btyp, fld, adr); INC(i)
END
END
END
ELSIF DevCPM.ExpHdPtrFld &
((typ.form = Pointer) & ~typ.untagged OR (fld.name^ = DevCPM.HdPtrName)) THEN (* !!! *)
DevCPM.FPrint(pvfp, Pointer); DevCPM.FPrint(pvfp, adr); INC(nofhdfld)
ELSIF DevCPM.ExpHdUtPtrFld &
((typ.form = Pointer) & typ.untagged OR (fld.name^ = DevCPM.HdUtPtrName)) THEN (* !!! *)
DevCPM.FPrint(pvfp, Pointer); DevCPM.FPrint(pvfp, adr); INC(nofhdfld);
IF typ.form = Pointer THEN DevCPM.FPrint(pvfp, typ.sysflag) ELSE DevCPM.FPrint(pvfp, fld.sysflag) END
ELSIF DevCPM.ExpHdProcFld & ((typ.form = ProcTyp) OR (fld.name^ = DevCPM.HdProcName)) THEN
DevCPM.FPrint(pvfp, ProcTyp); DevCPM.FPrint(pvfp, adr); INC(nofhdfld)
END
END FPrintHdFld;
PROCEDURE FPrintFlds(fld: Object; adr: INTEGER; visible: BOOLEAN); (* modifies pbfp and pvfp *)
BEGIN
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF (fld.vis # internal) & visible THEN
DevCPM.FPrint(pvfp, fld.vis); FPrintName(pvfp, fld.name); DevCPM.FPrint(pvfp, fld.adr);
DevCPM.FPrint(pbfp, fld.vis); FPrintName(pbfp, fld.name); DevCPM.FPrint(pbfp, fld.adr);
FPrintStr(fld.typ); DevCPM.FPrint(pbfp, fld.typ.pbfp); DevCPM.FPrint(pvfp, fld.typ.pvfp)
ELSE FPrintHdFld(fld.typ, fld, fld.adr + adr)
END ;
fld := fld.link
END
END FPrintFlds;
PROCEDURE FPrintTProcs(obj: Object); (* modifies pbfp and pvfp *)
VAR fp: INTEGER;
BEGIN
IF obj # NIL THEN
FPrintTProcs(obj.left);
IF obj.mode = TProc THEN
IF obj.vis # internal THEN
fp := 0;
IF obj.vis = externalR THEN DevCPM.FPrint(fp, externalR) END;
IF limAttr IN obj.conval.setval THEN DevCPM.FPrint(fp, limAttr)
ELSIF absAttr IN obj.conval.setval THEN DevCPM.FPrint(fp, absAttr)
ELSIF empAttr IN obj.conval.setval THEN DevCPM.FPrint(fp, empAttr)
ELSIF extAttr IN obj.conval.setval THEN DevCPM.FPrint(fp, extAttr)
END;
DevCPM.FPrint(fp, TProc); DevCPM.FPrint(fp, obj.num);
FPrintSign(fp, obj.typ, obj.link); FPrintName(fp, obj.name);
IF obj.entry # NIL THEN FPrintName(fp, obj.entry) END;
DevCPM.FPrint(pvfp, fp); DevCPM.FPrint(pbfp, fp)
ELSIF DevCPM.ExpHdTProc THEN
DevCPM.FPrint(pvfp, TProc); DevCPM.FPrint(pvfp, obj.num)
END
END;
FPrintTProcs(obj.right)
END
END FPrintTProcs;
BEGIN
IF ~typ.fpdone THEN
IdFPrint(typ); pbfp := typ.idfp;
IF typ.ext # NIL THEN FPrintName(pbfp, typ.ext^) END;
IF typ.attribute # 0 THEN DevCPM.FPrint(pbfp, typ.attribute) END;
pvfp := pbfp; typ.pbfp := pbfp; typ.pvfp := pvfp; (* initial fprints may be used recursively *)
typ.fpdone := TRUE;
f := typ.form; c := typ.comp; btyp := typ.BaseTyp;
IF f = Pointer THEN
strobj := typ.strobj; bstrobj := btyp.strobj;
IF (strobj = NIL) OR (strobj.name = null) OR (bstrobj = NIL) OR (bstrobj.name = null) THEN
FPrintStr(btyp);
IF (btyp.comp = Array) & ((bstrobj = NIL) OR (bstrobj.name = null)) THEN
DevCPM.FPrint(pbfp, btyp.pbfp + 12345(*disturb fingerprint collision pattern*))
ELSE DevCPM.FPrint(pbfp, btyp.pbfp)
END;
pvfp := pbfp
(* else use idfp as pbfp and as pvfp, do not call FPrintStr(btyp) here, else cycle not broken *)
END
ELSIF f = ProcTyp THEN (* use idfp as pbfp and as pvfp *)
ELSIF c IN {Array, DynArr} THEN FPrintStr(btyp); DevCPM.FPrint(pbfp, btyp.pvfp); pvfp := pbfp
ELSE (* c = Record *)
IF btyp # NIL THEN FPrintStr(btyp); DevCPM.FPrint(pbfp, btyp.pbfp); DevCPM.FPrint(pvfp, btyp.pvfp) END ;
DevCPM.FPrint(pvfp, typ.size); DevCPM.FPrint(pvfp, typ.align); DevCPM.FPrint(pvfp, typ.n);
nofhdfld := 0; FPrintFlds(typ.link, 0, TRUE);
FPrintTProcs(typ.link); (* DevCPM.FPrint(pvfp, pbfp); *) strobj := typ.strobj;
IF (strobj = NIL) OR (strobj.name = null) THEN pbfp := pvfp END
END ;
typ.pbfp := pbfp; typ.pvfp := pvfp
END
END FPrintStr;
PROCEDURE FPrintObj*(obj: Object);
VAR fprint, f, m: INTEGER; rval: SHORTREAL; ext: ConstExt; mod: Object; r: REAL; x: INTEGER;
BEGIN
IF ~obj.fpdone THEN
fprint := 0; obj.fpdone := TRUE;
DevCPM.FPrint(fprint, obj.mode);
IF obj.mode = Con THEN
f := obj.typ.form; DevCPM.FPrint(fprint, f);
CASE f OF
| Bool, Char8, Char16, Int8, Int16, Int32:
DevCPM.FPrint(fprint, obj.conval.intval)
| Int64:
x := SHORT(ENTIER((obj.conval.realval + obj.conval.intval) / 4294967296.0));
r := obj.conval.realval + obj.conval.intval - x * 4294967296.0;
IF r > MAX(INTEGER) THEN r := r - 4294967296.0 END;
DevCPM.FPrint(fprint, SHORT(ENTIER(r)));
DevCPM.FPrint(fprint, x)
| Set:
DevCPM.FPrintSet(fprint, obj.conval.setval)
| Real32:
rval := SHORT(obj.conval.realval); DevCPM.FPrintReal(fprint, rval)
| Real64:
DevCPM.FPrintLReal(fprint, obj.conval.realval)
| String8, String16:
FPrintName(fprint, obj.conval.ext^)
| NilTyp:
ELSE err(127)
END
ELSIF obj.mode = Var THEN
DevCPM.FPrint(fprint, obj.vis); FPrintStr(obj.typ); DevCPM.FPrint(fprint, obj.typ.pbfp)
ELSIF obj.mode IN {XProc, IProc} THEN
FPrintSign(fprint, obj.typ, obj.link)
ELSIF obj.mode = CProc THEN
FPrintSign(fprint, obj.typ, obj.link); ext := obj.conval.ext;
IF ext # NIL THEN m := LEN(ext^); x := 0; DevCPM.FPrint(fprint, m);
WHILE x < m DO DevCPM.FPrint(fprint, ORD(ext^[x])); INC(x) END
ELSE DevCPM.FPrint(fprint, 0);
END
ELSIF obj.mode = Typ THEN
FPrintStr(obj.typ); DevCPM.FPrint(fprint, obj.typ.pbfp)
END ;
IF obj.sysflag < 0 THEN DevCPM.FPrint(fprint, obj.sysflag) END;
IF obj.mode IN {LProc, XProc, CProc, Var, Typ, Con} THEN
IF obj.library # NIL THEN
FPrintName(fprint, obj.library)
ELSIF obj.mnolev < 0 THEN
mod := GlbMod[-obj.mnolev];
IF (mod.library # NIL) THEN
FPrintName(fprint, mod.library)
END
ELSIF obj.mnolev = 0 THEN
IF libName # "" THEN FPrintName(fprint, libName) END
END;
IF obj.entry # NIL THEN FPrintName(fprint, obj.entry) END
END;
obj.fprint := fprint
END
END FPrintObj;
PROCEDURE FPrintErr* (obj: Object; errno: SHORTINT); (* !!! *)
BEGIN
IF errno = 249 THEN
DevCPM.LogWLn; DevCPM.LogWStr(" ");
DevCPM.LogWPar("#Dev:InconsistentImport", GlbMod[-obj.mnolev].name, obj.name);
err(249)
ELSIF obj = NIL THEN (* changed module sys flags *)
IF ~symNew & sfpresent THEN
DevCPM.LogWLn; DevCPM.LogWStr(" "); DevCPM.LogWPar("#Dev:ChangedLibFlag", "", "")
END
ELSIF obj.mnolev = 0 THEN (* don't report changes in imported modules *)
IF sfpresent THEN
IF symChanges < 20 THEN
DevCPM.LogWLn; DevCPM.LogWStr(" ");
CASE errno OF
| 250: DevCPM.LogWPar("#Dev:IsNoLongerInSymFile", obj.name, "")
| 251: DevCPM.LogWPar("#Dev:IsRedefinedInternally", obj.name, "")
| 252: DevCPM.LogWPar("#Dev:IsRedefined", obj.name, "")
| 253: DevCPM.LogWPar("#Dev:IsNewInSymFile", obj.name, "")
END
ELSIF symChanges = 20 THEN
DevCPM.LogWLn; DevCPM.LogWStr(" ...")
END;
INC(symChanges)
ELSIF (errno = 253) & ~symExtended THEN
DevCPM.LogWLn;
DevCPM.LogWStr(" "); DevCPM.LogWPar("#Dev:NewSymFile", "", "")
END
END;
IF errno = 253 THEN symExtended := TRUE ELSE symNew := TRUE END
END FPrintErr;
(*-------------------------- Import --------------------------*)
PROCEDURE InName(OUT name: String);
VAR i: INTEGER; ch: SHORTCHAR; n: Name;
BEGIN i := 0;
REPEAT
DevCPM.SymRCh(ch); n[i] := ch; INC(i)
UNTIL ch = 0X;
IF i > 1 THEN NEW(name, i); name^ := n$ ELSE name := null END
END InName;
PROCEDURE InMod(tag: INTEGER; OUT mno: BYTE); (* mno is global *)
VAR head: Object; name: String; i: BYTE; lib: String;
BEGIN
IF tag = 0 THEN mno := impCtxt.glbmno[0]
ELSIF tag > 0 THEN
lib := NIL;
IF tag = Slib THEN InName(lib); tag := DevCPM.SymRInt() END;
ASSERT(tag = Smname);
InName(name);
IF (name^ = SelfName) & ~impCtxt.self & ~(DevCPM.interface IN DevCPM.options) THEN err(154) END ;
i := 0;
WHILE (i < nofGmod) & (name^ # GlbMod[i].name^) DO INC(i) END ;
IF i < nofGmod THEN mno := i (*module already present*)
ELSE
head := NewObj(); head.mode := Head; head.name := name;
mno := nofGmod; head.mnolev := SHORT(SHORT(-mno));
head.library := lib;
IF nofGmod < maxImps THEN
GlbMod[mno] := head; INC(nofGmod)
ELSE err(227)
END
END ;
impCtxt.glbmno[impCtxt.nofm] := mno; INC(impCtxt.nofm)
ELSE
mno := impCtxt.glbmno[-tag]
END
END InMod;
PROCEDURE InConstant(f: INTEGER; conval: Const);
VAR ch: SHORTCHAR; ext, t: ConstExt; rval: SHORTREAL; r, s: REAL; i, x, y: INTEGER; str: Name;
BEGIN
CASE f OF
| Byte, Char8, Bool:
DevCPM.SymRCh(ch); conval.intval := ORD(ch)
| Char16:
DevCPM.SymRCh(ch); conval.intval := ORD(ch);
DevCPM.SymRCh(ch); conval.intval := conval.intval + ORD(ch) * 256
| Int8, Int16, Int32:
conval.intval := DevCPM.SymRInt()
| Int64:
DevCPM.SymRCh(ch); x := 0; y := 1; r := 0; s := 268435456 (*2^28*);
WHILE (y < 268435456 (*2^28*)) & (ch >= 80X) DO
x := x + (ORD(ch) - 128) * y; y := y * 128; DevCPM.SymRCh(ch)
END;
WHILE ch >= 80X DO r := r + (ORD(ch) - 128) * s; s := s * 128; DevCPM.SymRCh(ch) END;
conval.realval := r + x + ((LONG(ORD(ch)) + 64) MOD 128 - 64) * s;
conval.intval := SHORT(ENTIER(r + x + ((LONG(ORD(ch)) + 64) MOD 128 - 64) * s - conval.realval))
| Set:
DevCPM.SymRSet(conval.setval)
| Real32:
DevCPM.SymRReal(rval); conval.realval := rval;
conval.intval := DevCPM.ConstNotAlloc
| Real64:
DevCPM.SymRLReal(conval.realval);
conval.intval := DevCPM.ConstNotAlloc
| String8, String16:
i := 0;
REPEAT
DevCPM.SymRCh(ch);
IF i < LEN(str) - 1 THEN str[i] := ch
ELSIF i = LEN(str) - 1 THEN str[i] := 0X; NEW(ext, 2 * LEN(str)); ext^ := str$; ext[i] := ch
ELSIF i < LEN(ext^) - 1 THEN ext[i] := ch
ELSE t := ext; t[i] := 0X; NEW(ext, 2 * LEN(t^)); ext^ := t^$; ext[i] := ch
END;
INC(i)
UNTIL ch = 0X;
IF i < LEN(str) THEN NEW(ext, i); ext^ := str$ END;
conval.ext := ext; conval.intval := DevCPM.ConstNotAlloc;
IF f = String8 THEN conval.intval2 := i
ELSE
i := 0; y := 0;
REPEAT DevCPM.GetUtf8(ext^, x, i); INC(y) UNTIL x = 0;
conval.intval2 := y
END
| NilTyp:
conval.intval := 0
(*
| Guid:
ext := NewExt(); conval.ext := ext; i := 0;
WHILE i < 16 DO
DevCPM.SymRCh(ch); ext^[i] := ch; INC(i)
END;
ext[16] := 0X;
conval.intval2 := 16;
conval.intval := DevCPM.ConstNotAlloc;
*)
END
END InConstant;
PROCEDURE ^InStruct(VAR typ: Struct);
PROCEDURE InSign(mno: BYTE; VAR res: Struct; VAR par: Object);
VAR last, new: Object; tag: INTEGER;
BEGIN
InStruct(res);
tag := DevCPM.SymRInt(); last := NIL;
WHILE tag # Send DO
new := NewObj(); new.mnolev := SHORT(SHORT(-mno));
IF last = NIL THEN par := new ELSE last.link := new END ;
IF tag = Ssys THEN
new.sysflag := SHORT(SHORT(DevCPM.SymRInt())); tag := DevCPM.SymRInt();
IF ODD(new.sysflag DIV inBit) THEN new.vis := inPar
ELSIF ODD(new.sysflag DIV outBit) THEN new.vis := outPar
END
END;
IF tag = Svalpar THEN new.mode := Var
ELSE new.mode := VarPar;
IF tag = Sinpar THEN new.vis := inPar
ELSIF tag = Soutpar THEN new.vis := outPar
END
END ;
InStruct(new.typ); new.adr := DevCPM.SymRInt(); InName(new.name);
last := new; tag := DevCPM.SymRInt()
END
END InSign;
PROCEDURE InFld(): Object; (* first number in impCtxt.nextTag, mno set outside *)
VAR tag: INTEGER; obj: Object;
BEGIN
tag := impCtxt.nextTag; obj := NewObj();
IF tag <= Srfld THEN
obj.mode := Fld;
IF tag = Srfld THEN obj.vis := externalR ELSE obj.vis := external END ;
InStruct(obj.typ); InName(obj.name);
obj.adr := DevCPM.SymRInt()
ELSE
obj.mode := Fld;
IF tag = Shdptr THEN obj.name := NewName(DevCPM.HdPtrName)
ELSIF tag = Shdutptr THEN obj.name := NewName(DevCPM.HdUtPtrName); (* !!! *)
obj.sysflag := 1
ELSIF tag = Ssys THEN
obj.name := NewName(DevCPM.HdUtPtrName); obj.sysflag := SHORT(SHORT(DevCPM.SymRInt()))
ELSE obj.name := NewName(DevCPM.HdProcName)
END;
obj.typ := undftyp; obj.vis := internal;
obj.adr := DevCPM.SymRInt()
END;
RETURN obj
END InFld;
PROCEDURE InTProc(mno: BYTE): Object; (* first number in impCtxt.nextTag *)
VAR tag: INTEGER; obj: Object;
BEGIN
tag := impCtxt.nextTag;
obj := NewObj(); obj.mnolev := SHORT(SHORT(-mno));
IF tag = Shdtpro THEN
obj.mode := TProc; obj.name := NewName(DevCPM.HdTProcName);
obj.link := NewObj(); (* dummy, easier in Browser *)
obj.typ := undftyp; obj.vis := internal;
obj.num := DevCPM.SymRInt()
ELSE
obj.vis := external;
IF tag = Simpo THEN obj.vis := externalR; tag := DevCPM.SymRInt() END;
obj.mode := TProc; obj.conval := NewConst(); obj.conval.intval := -1;
IF tag = Sentry THEN InName(obj.entry); tag := DevCPM.SymRInt() END;
InSign(mno, obj.typ, obj.link); InName(obj.name);
obj.num := DevCPM.SymRInt();
IF tag = Slimpro THEN INCL(obj.conval.setval, limAttr)
ELSIF tag = Sabspro THEN INCL(obj.conval.setval, absAttr)
ELSIF tag = Semppro THEN INCL(obj.conval.setval, empAttr)
ELSIF tag = Sextpro THEN INCL(obj.conval.setval, extAttr)
END
END ;
RETURN obj
END InTProc;
PROCEDURE InStruct(VAR typ: Struct);
VAR mno: BYTE; ref: SHORTINT; tag: INTEGER; name: String;
t: Struct; obj, last, fld, old, dummy: Object;
BEGIN
tag := DevCPM.SymRInt();
IF tag # Sstruct THEN
tag := -tag;
IF (version = 0) & (tag >= FirstRef0) THEN tag := tag + FirstRef - FirstRef0 END; (* correction for new FirstRef *)
typ := impCtxt.ref[tag]
ELSE
ref := impCtxt.nofr; INC(impCtxt.nofr);
IF ref < impCtxt.minr THEN impCtxt.minr := ref END ;
tag := DevCPM.SymRInt();
InMod(tag, mno); InName(name); obj := NewObj();
IF name = null THEN
IF impCtxt.self THEN old := NIL (* do not insert type desc anchor here, but in OPL *)
ELSE obj.name := NewName("@"); InsertIn(obj, GlbMod[mno], old(*=NIL*)); obj.name := null
END ;
typ := NewStr(Undef, Basic)
ELSE obj.name := name; InsertIn(obj, GlbMod[mno], old);
IF old # NIL THEN (* recalculate fprints to compare with old fprints *)
FPrintObj(old); impCtxt.pvfp[ref] := old.typ.pvfp;
IF impCtxt.self THEN (* do not overwrite old typ *)
typ := NewStr(Undef, Basic)
ELSE (* overwrite old typ for compatibility reason *)
typ := old.typ; typ.link := NIL; typ.sysflag := 0; typ.ext := NIL;
typ.fpdone := FALSE; typ.idfpdone := FALSE
END
ELSE typ := NewStr(Undef, Basic)
END
END ;
impCtxt.ref[ref] := typ; impCtxt.old[ref] := old; typ.ref := SHORT(ref + maxStruct);
(* ref >= maxStruct: not exported yet, ref used for err 155 *)
typ.mno := mno; typ.allocated := TRUE;
typ.strobj := obj; obj.mode := Typ; obj.typ := typ;
obj.mnolev := SHORT(SHORT(-mno)); obj.vis := internal; (* name not visible here *)
tag := DevCPM.SymRInt();
IF tag = Ssys THEN
typ.sysflag := SHORT(DevCPM.SymRInt()); tag := DevCPM.SymRInt()
END;
typ.untagged := typ.sysflag > 0;
IF tag = Slib THEN
InName(obj.library); tag := DevCPM.SymRInt()
END;
IF tag = Sentry THEN
InName(obj.entry); tag := DevCPM.SymRInt()
END;
IF tag = String8 THEN
InName(typ.ext); tag := DevCPM.SymRInt()
END;
CASE tag OF
| Sptr:
typ.form := Pointer; typ.size := DevCPM.PointerSize; typ.n := 0; InStruct(typ.BaseTyp)
| Sarr:
typ.form := Comp; typ.comp := Array; InStruct(typ.BaseTyp); typ.n := DevCPM.SymRInt();
typ.size := typ.n * typ.BaseTyp.size (* !!! *)
| Sdarr:
typ.form := Comp; typ.comp := DynArr; InStruct(typ.BaseTyp);
IF typ.BaseTyp.comp = DynArr THEN typ.n := typ.BaseTyp.n + 1
ELSE typ.n := 0
END ;
typ.size := DevCPM.DArrSizeA + DevCPM.DArrSizeB * typ.n; (* !!! *)
IF typ.untagged THEN typ.size := DevCPM.PointerSize END
| Srec, Sabsrec, Slimrec, Sextrec:
typ.form := Comp; typ.comp := Record; InStruct(typ.BaseTyp);
(* correction by ETH 18.1.96 *)
IF typ.BaseTyp = notyp THEN typ.BaseTyp := NIL END;
typ.extlev := 0; t := typ.BaseTyp;
WHILE (t # NIL) & (t.comp = Record) DO INC(typ.extlev); t := t.BaseTyp END;
typ.size := DevCPM.SymRInt(); typ.align := DevCPM.SymRInt();
typ.n := DevCPM.SymRInt();
IF tag = Sabsrec THEN typ.attribute := absAttr
ELSIF tag = Slimrec THEN typ.attribute := limAttr
ELSIF tag = Sextrec THEN typ.attribute := extAttr
END;
impCtxt.nextTag := DevCPM.SymRInt(); last := NIL;
WHILE (impCtxt.nextTag >= Sfld) & (impCtxt.nextTag <= Shdpro)
OR (impCtxt.nextTag = Shdutptr) OR (impCtxt.nextTag = Ssys) DO
fld := InFld(); fld.mnolev := SHORT(SHORT(-mno));
IF last # NIL THEN last.link := fld END ;
last := fld;
InsertThisField(fld, typ, dummy);
impCtxt.nextTag := DevCPM.SymRInt()
END ;
WHILE impCtxt.nextTag # Send DO fld := InTProc(mno);
InsertThisField(fld, typ, dummy);
impCtxt.nextTag := DevCPM.SymRInt()
END
| Spro:
typ.form := ProcTyp; typ.size := DevCPM.ProcSize; InSign(mno, typ.BaseTyp, typ.link)
| Salias:
InStruct(t);
typ.form := t.form; typ.comp := Basic; typ.size := t.size;
typ.pbfp := t.pbfp; typ.pvfp := t.pvfp; typ.fpdone := TRUE;
typ.idfp := t.idfp; typ.idfpdone := TRUE; typ.BaseTyp := t
END ;
IF ref = impCtxt.minr THEN
WHILE ref < impCtxt.nofr DO
t := impCtxt.ref[ref]; FPrintStr(t);
obj := t.strobj; (* obj.typ.strobj = obj, else obj.fprint differs (alias) *)
IF obj.name # null THEN FPrintObj(obj) END ;
old := impCtxt.old[ref];
IF old # NIL THEN t.strobj := old; (* restore strobj *)
IF impCtxt.self THEN
IF old.mnolev < 0 THEN
IF old.history # inconsistent THEN
IF old.fprint # obj.fprint THEN old.history := pbmodified
ELSIF impCtxt.pvfp[ref] # t.pvfp THEN old.history := pvmodified
END
(* ELSE remain inconsistent *)
END
ELSIF old.fprint # obj.fprint THEN old.history := pbmodified
ELSIF impCtxt.pvfp[ref] # t.pvfp THEN old.history := pvmodified
ELSIF old.vis = internal THEN old.history := same (* may be changed to "removed" in InObj *)
ELSE old.history := inserted (* may be changed to "same" in InObj *)
END
ELSE
(* check private part, delay error message until really used *)
IF impCtxt.pvfp[ref] # t.pvfp THEN old.history := inconsistent END ;
IF old.fprint # obj.fprint THEN FPrintErr(old, 249) END
END
ELSIF impCtxt.self THEN obj.history := removed
ELSE obj.history := same
END ;
INC(ref)
END ;
impCtxt.minr := maxStruct
END
END
END InStruct;
PROCEDURE InObj(mno: BYTE): Object; (* first number in impCtxt.nextTag *)
VAR obj, old: Object; typ: Struct;
tag, i, s: INTEGER; ext: ConstExt;
BEGIN
tag := impCtxt.nextTag;
IF tag = Stype THEN
InStruct(typ); obj := typ.strobj;
IF ~impCtxt.self THEN obj.vis := external END (* type name visible now, obj.fprint already done *)
ELSE
obj := NewObj(); obj.mnolev := SHORT(SHORT(-mno)); obj.vis := external;
IF tag = Ssys THEN obj.sysflag := SHORT(SHORT(DevCPM.SymRInt())); tag := DevCPM.SymRInt() END;
IF tag = Slib THEN
InName(obj.library); tag := DevCPM.SymRInt()
END;
IF tag = Sentry THEN
InName(obj.entry); tag := DevCPM.SymRInt()
END;
IF tag >= Sxpro THEN
IF obj.conval = NIL THEN obj.conval := NewConst() END;
obj.conval.intval := -1;
InSign(mno, obj.typ, obj.link);
CASE tag OF
| Sxpro: obj.mode := XProc
| Sipro: obj.mode := IProc
| Scpro: obj.mode := CProc;
s := DevCPM.SymRInt();
IF s # 0 THEN NEW(ext, s); i := 0;
WHILE i < s DO DevCPM.SymRCh(ext^[i]); INC(i) END
ELSE ext := NIL
END;
obj.conval.ext := ext;
END
ELSIF tag = Salias THEN
obj.mode := Typ; InStruct(obj.typ)
ELSIF (tag = Svar) OR (tag = Srvar) THEN
obj.mode := Var;
IF tag = Srvar THEN obj.vis := externalR END ;
InStruct(obj.typ)
ELSE (* Constant *)
obj.conval := NewConst(); InConstant(tag, obj.conval);
IF (tag = Int8) OR (tag = Int16) THEN tag := Int32 END;
obj.mode := Con; obj.typ := impCtxt.ref[tag];
END ;
InName(obj.name)
END ;
FPrintObj(obj);
IF (obj.mode = Var) & ((obj.typ.strobj = NIL) OR (obj.typ.strobj.name = null)) THEN
(* compute a global fingerprint to avoid structural type equivalence for anonymous types *)
DevCPM.FPrint(impCtxt.reffp, obj.typ.ref - maxStruct)
END ;
IF tag # Stype THEN
InsertIn(obj, GlbMod[mno], old);
IF impCtxt.self THEN
IF old # NIL THEN
(* obj is from old symbol file, old is new declaration *)
IF old.vis = internal THEN old.history := removed
ELSE FPrintObj(old); FPrintStr(old.typ); (* FPrint(obj) already called *)
IF obj.fprint # old.fprint THEN old.history := pbmodified
ELSIF obj.typ.pvfp # old.typ.pvfp THEN old.history := pvmodified
ELSE old.history := same
END
END
ELSE obj.history := removed (* OutObj not called if mnolev < 0 *)
END
(* ELSE old = NIL, or file read twice, consistent, OutObj not called *)
END
ELSE (* obj already inserted in InStruct *)
IF impCtxt.self THEN (* obj.mnolev = 0 *)
IF obj.vis = internal THEN obj.history := removed
ELSIF obj.history = inserted THEN obj.history := same
END
(* ELSE OutObj not called for obj with mnolev < 0 *)
END
END ;
RETURN obj
END InObj;
PROCEDURE Import*(IN aliasName, name: Name; VAR done: BOOLEAN);
VAR obj, h: Object; mno: BYTE; tag, p: INTEGER; lib: String; (* done used in Browser *)
BEGIN
IF name = "SYSTEM" THEN
SYSimported := TRUE;
p := processor;
IF (p < 10) OR (p > 30) THEN p := DevCPM.sysImp END;
INCL(DevCPM.options, p); (* for sysflag handling *)
Insert(aliasName, obj); obj.mode := Mod; obj.mnolev := 0; obj.scope := syslink; obj.typ := notyp;
h := NewObj(); h.mode := Head; h.right := syslink; obj.scope := h
ELSIF name = "COM" THEN
IF DevCPM.comAware IN DevCPM.options THEN
INCL(DevCPM.options, DevCPM.com); (* for sysflag handling *)
Insert(aliasName, obj); obj.mode := Mod; obj.mnolev := 0; obj.scope := comlink; obj.typ := notyp;
h := NewObj(); h.mode := Head; h.right := comlink; obj.scope := h;
ELSE err(151)
END;
ELSIF name = "JAVA" THEN
INCL(DevCPM.options, DevCPM.java)
ELSE
impCtxt.nofr := FirstRef; impCtxt.minr := maxStruct; impCtxt.nofm := 0;
impCtxt.self := aliasName = "@self"; impCtxt.reffp := 0;
DevCPM.OldSym(name, done);
IF done THEN
lib := NIL;
impProc := SHORT(DevCPM.SymRInt());
IF (impProc # 0) & (processor # 0) & (impProc # processor) THEN err(151) END;
DevCPM.checksum := 0; (* start checksum here to avoid problems with proc id fixup *)
tag := DevCPM.SymRInt();
IF tag < Smname THEN version := tag; tag := DevCPM.SymRInt()
ELSE version := 0
END;
IF tag = Slib THEN InName(lib); tag := DevCPM.SymRInt() END;
InMod(tag, mno);
IF (name[0] # "@") & (GlbMod[mno].name^ # name) THEN (* symbol file name conflict *)
GlbMod[mno] := NIL; nofGmod := mno; DEC(impCtxt.nofm);
DevCPM.CloseOldSym; done := FALSE
END;
END;
IF done THEN
GlbMod[mno].library := lib;
impCtxt.nextTag := DevCPM.SymRInt();
WHILE ~DevCPM.eofSF() DO
obj := InObj(mno); impCtxt.nextTag := DevCPM.SymRInt()
END ;
Insert(aliasName, obj);
obj.mode := Mod; obj.scope := GlbMod[mno](*.right*);
GlbMod[mno].link := obj;
obj.mnolev := SHORT(SHORT(-mno)); obj.typ := notyp;
DevCPM.CloseOldSym
ELSIF impCtxt.self THEN
sfpresent := FALSE
ELSE err(152) (*sym file not found*)
END
END
END Import;
(*-------------------------- Export --------------------------*)
PROCEDURE OutName(IN name: ARRAY OF SHORTCHAR);
VAR i: INTEGER; ch: SHORTCHAR;
BEGIN i := 0;
REPEAT ch := name[i]; DevCPM.SymWCh(ch); INC(i) UNTIL ch = 0X
END OutName;
PROCEDURE OutMod(mno: SHORTINT);
VAR mod: Object;
BEGIN
IF expCtxt.locmno[mno] < 0 THEN (* new mod *)
mod := GlbMod[mno];
IF mod.library # NIL THEN
DevCPM.SymWInt(Slib); OutName(mod.library)
END;
DevCPM.SymWInt(Smname);
expCtxt.locmno[mno] := expCtxt.nofm; INC(expCtxt.nofm);
OutName(mod.name)
ELSE DevCPM.SymWInt(-expCtxt.locmno[mno])
END
END OutMod;
PROCEDURE ^OutStr(typ: Struct);
PROCEDURE ^OutFlds(fld: Object; adr: INTEGER; visible: BOOLEAN);
PROCEDURE OutHdFld(typ: Struct; fld: Object; adr: INTEGER);
VAR i, j, n: INTEGER; btyp: Struct;
BEGIN
IF typ.comp = Record THEN
IF typ.BaseTyp # NIL THEN OutHdFld(typ.BaseTyp, fld, adr) END ;
OutFlds(typ.link, adr, FALSE)
ELSIF typ.comp = Array THEN btyp := typ.BaseTyp; n := typ.n;
WHILE btyp.comp = Array DO n := btyp.n * n; btyp := btyp.BaseTyp END ;
IF (btyp.form = Pointer) OR (btyp.comp = Record) THEN
j := nofhdfld; OutHdFld(btyp, fld, adr);
IF j # nofhdfld THEN i := 1;
WHILE (i < n) (* & (nofhdfld <= DevCPM.MaxHdFld) *) DO (* !!! *)
INC(adr, btyp.size); OutHdFld(btyp, fld, adr); INC(i)
END
END
END
ELSIF DevCPM.ExpHdPtrFld &
((typ.form = Pointer) & ~typ.untagged OR (fld.name^ = DevCPM.HdPtrName)) THEN (* !!! *)
DevCPM.SymWInt(Shdptr); DevCPM.SymWInt(adr); INC(nofhdfld)
ELSIF DevCPM.ExpHdUtPtrFld &
((typ.form = Pointer) & typ.untagged OR (fld.name^ = DevCPM.HdUtPtrName)) THEN (* !!! *)
DevCPM.SymWInt(Ssys); (* DevCPM.SymWInt(Shdutptr); *)
IF typ.form = Pointer THEN n := typ.sysflag ELSE n := fld.sysflag END;
DevCPM.SymWInt(n);
DevCPM.SymWInt(adr); INC(nofhdfld);
IF n > 1 THEN portable := FALSE END (* hidden untagged pointer are portable *)
ELSIF DevCPM.ExpHdProcFld & ((typ.form = ProcTyp) OR (fld.name^ = DevCPM.HdProcName)) THEN
DevCPM.SymWInt(Shdpro); DevCPM.SymWInt(adr); INC(nofhdfld)
END
END OutHdFld;
PROCEDURE OutFlds(fld: Object; adr: INTEGER; visible: BOOLEAN);
BEGIN
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF (fld.vis # internal) & visible THEN
IF fld.vis = externalR THEN DevCPM.SymWInt(Srfld) ELSE DevCPM.SymWInt(Sfld) END ;
OutStr(fld.typ); OutName(fld.name); DevCPM.SymWInt(fld.adr)
ELSE OutHdFld(fld.typ, fld, fld.adr + adr)
END ;
fld := fld.link
END
END OutFlds;
PROCEDURE OutSign(result: Struct; par: Object);
BEGIN
OutStr(result);
WHILE par # NIL DO
IF par.sysflag # 0 THEN DevCPM.SymWInt(Ssys); DevCPM.SymWInt(par.sysflag) END;
IF par.mode = Var THEN DevCPM.SymWInt(Svalpar)
ELSIF par.vis = inPar THEN DevCPM.SymWInt(Sinpar)
ELSIF par.vis = outPar THEN DevCPM.SymWInt(Soutpar)
ELSE DevCPM.SymWInt(Svarpar)
END ;
OutStr(par.typ);
DevCPM.SymWInt(par.adr);
OutName(par.name); par := par.link
END ;
DevCPM.SymWInt(Send)
END OutSign;
PROCEDURE OutTProcs(typ: Struct; obj: Object);
VAR bObj: Object;
BEGIN
IF obj # NIL THEN
IF obj.mode = TProc THEN
(*
IF (typ.BaseTyp # NIL) & (obj.num < typ.BaseTyp.n) & (obj.vis = internal) & (obj.scope # NIL) THEN
FindBaseField(obj.name^, typ, bObj);
ASSERT((bObj # NIL) & (bObj.num = obj.num));
IF bObj.vis # internal THEN DevCPM.Mark(109, typ.txtpos) END
(* hidden and overriding, not detected in OPP because record exported indirectly or via aliasing *)
END;
*)
IF obj.vis # internal THEN
IF obj.vis = externalR THEN DevCPM.SymWInt(Simpo) END;
IF obj.entry # NIL THEN
DevCPM.SymWInt(Sentry); OutName(obj.entry); portable := FALSE
END;
IF limAttr IN obj.conval.setval THEN DevCPM.SymWInt(Slimpro)
ELSIF absAttr IN obj.conval.setval THEN DevCPM.SymWInt(Sabspro)
ELSIF empAttr IN obj.conval.setval THEN DevCPM.SymWInt(Semppro)
ELSIF extAttr IN obj.conval.setval THEN DevCPM.SymWInt(Sextpro)
ELSE DevCPM.SymWInt(Stpro)
END;
OutSign(obj.typ, obj.link); OutName(obj.name);
DevCPM.SymWInt(obj.num)
ELSIF DevCPM.ExpHdTProc THEN
DevCPM.SymWInt(Shdtpro);
DevCPM.SymWInt(obj.num)
END
END;
OutTProcs(typ, obj.left);
OutTProcs(typ, obj.right)
END
END OutTProcs;
PROCEDURE OutStr(typ: Struct); (* OPV.TypeAlloc already applied *)
VAR strobj: Object;
BEGIN
IF typ.ref < expCtxt.ref THEN DevCPM.SymWInt(-typ.ref)
ELSE
DevCPM.SymWInt(Sstruct);
typ.ref := expCtxt.ref; INC(expCtxt.ref);
IF expCtxt.ref >= maxStruct THEN err(228) END ;
OutMod(typ.mno); strobj := typ.strobj;
IF (strobj # NIL) & (strobj.name # null) THEN OutName(strobj.name);
CASE strobj.history OF
| pbmodified: FPrintErr(strobj, 252)
| pvmodified: FPrintErr(strobj, 251)
| inconsistent: FPrintErr(strobj, 249)
ELSE (* checked in OutObj or correct indirect export *)
END
ELSE DevCPM.SymWCh(0X) (* anonymous => never inconsistent, pvfp influences the client fp *)
END;
IF typ.sysflag # 0 THEN (* !!! *)
DevCPM.SymWInt(Ssys); DevCPM.SymWInt(typ.sysflag);
IF typ.sysflag > 0 THEN portable := FALSE END
END;
IF strobj # NIL THEN
IF strobj.library # NIL THEN
DevCPM.SymWInt(Slib); OutName(strobj.library); portable := FALSE
END;
IF strobj.entry # NIL THEN
DevCPM.SymWInt(Sentry); OutName(strobj.entry); portable := FALSE
END
END;
IF typ.ext # NIL THEN
DevCPM.SymWInt(String8); OutName(typ.ext); portable := FALSE
END;
CASE typ.form OF
| Pointer:
DevCPM.SymWInt(Sptr); OutStr(typ.BaseTyp)
| ProcTyp:
DevCPM.SymWInt(Spro); OutSign(typ.BaseTyp, typ.link)
| Comp:
CASE typ.comp OF
| Array:
DevCPM.SymWInt(Sarr); OutStr(typ.BaseTyp); DevCPM.SymWInt(typ.n)
| DynArr:
DevCPM.SymWInt(Sdarr); OutStr(typ.BaseTyp)
| Record:
IF typ.attribute = limAttr THEN DevCPM.SymWInt(Slimrec)
ELSIF typ.attribute = absAttr THEN DevCPM.SymWInt(Sabsrec)
ELSIF typ.attribute = extAttr THEN DevCPM.SymWInt(Sextrec)
ELSE DevCPM.SymWInt(Srec)
END;
IF typ.BaseTyp = NIL THEN OutStr(notyp) ELSE OutStr(typ.BaseTyp) END ;
(* BaseTyp should be Notyp, too late to change *)
DevCPM.SymWInt(typ.size); DevCPM.SymWInt(typ.align); DevCPM.SymWInt(typ.n);
nofhdfld := 0; OutFlds(typ.link, 0, TRUE);
(*
IF nofhdfld > DevCPM.MaxHdFld THEN DevCPM.Mark(223, typ.txtpos) END ; (* !!! *)
*)
OutTProcs(typ, typ.link); DevCPM.SymWInt(Send)
END
ELSE (* alias structure *)
DevCPM.SymWInt(Salias); OutStr(typ.BaseTyp)
END
END
END OutStr;
PROCEDURE OutConstant(obj: Object);
VAR f: SHORTINT; rval: SHORTREAL; a, b, c: INTEGER; r: REAL;
BEGIN
f := obj.typ.form;
(*
IF obj.typ = guidtyp THEN f := Guid END;
*)
IF f = Int32 THEN
IF (obj.conval.intval >= -128) & (obj.conval.intval <= -127) THEN f := Int8
ELSIF (obj.conval.intval >= -32768) & (obj.conval.intval <= -32767) THEN f := Int16
END
END;
DevCPM.SymWInt(f);
CASE f OF
| Bool, Char8:
DevCPM.SymWCh(SHORT(CHR(obj.conval.intval)))
| Char16:
DevCPM.SymWCh(SHORT(CHR(obj.conval.intval MOD 256)));
DevCPM.SymWCh(SHORT(CHR(obj.conval.intval DIV 256)))
| Int8, Int16, Int32:
DevCPM.SymWInt(obj.conval.intval)
| Int64:
IF ABS(obj.conval.realval + obj.conval.intval) <= MAX(INTEGER) THEN
a := SHORT(ENTIER(obj.conval.realval + obj.conval.intval)); b := -1; c := -1
ELSIF ABS(obj.conval.realval + obj.conval.intval) <= 1125899906842624.0 (*2^50*) THEN
a := SHORT(ENTIER((obj.conval.realval + obj.conval.intval) / 2097152.0 (*2^21*)));
b := SHORT(ENTIER(obj.conval.realval + obj.conval.intval - a * 2097152.0 (*2^21*))); c := -1
ELSE
a := SHORT(ENTIER((obj.conval.realval + obj.conval.intval) / 4398046511104.0 (*2^42*)));
r := obj.conval.realval + obj.conval.intval - a * 4398046511104.0 (*2^42*);
b := SHORT(ENTIER(r / 2097152.0 (*2^21*)));
c := SHORT(ENTIER(r - b * 2097152.0 (*2^21*)))
END;
IF c >= 0 THEN
DevCPM.SymWCh(SHORT(CHR(c MOD 128 + 128))); c := c DIV 128;
DevCPM.SymWCh(SHORT(CHR(c MOD 128 + 128))); c := c DIV 128;
DevCPM.SymWCh(SHORT(CHR(c MOD 128 + 128)))
END;
IF b >= 0 THEN
DevCPM.SymWCh(SHORT(CHR(b MOD 128 + 128))); b := b DIV 128;
DevCPM.SymWCh(SHORT(CHR(b MOD 128 + 128))); b := b DIV 128;
DevCPM.SymWCh(SHORT(CHR(b MOD 128 + 128)))
END;
DevCPM.SymWInt(a)
| Set:
DevCPM.SymWSet(obj.conval.setval)
| Real32:
rval := SHORT(obj.conval.realval); DevCPM.SymWReal(rval)
| Real64:
DevCPM.SymWLReal(obj.conval.realval)
| String8, String16:
OutName(obj.conval.ext^)
| NilTyp:
(*
| Guid:
i := 0;
WHILE i < 16 DO DevCPM.SymWCh(obj.conval.ext[i]); INC(i) END
*)
ELSE err(127)
END
END OutConstant;
PROCEDURE OutObj(obj: Object);
VAR i, j: INTEGER; ext: ConstExt;
BEGIN
IF obj # NIL THEN
OutObj(obj.left);
IF obj.mode IN {Con, Typ, Var, LProc, XProc, CProc, IProc} THEN
IF obj.history = removed THEN FPrintErr(obj, 250)
ELSIF obj.vis # internal THEN
CASE obj.history OF
| inserted: FPrintErr(obj, 253)
| same: (* ok *)
| pbmodified:
IF (obj.mode # Typ) OR (obj.typ.strobj # obj) THEN FPrintErr(obj, 252) END
| pvmodified:
IF (obj.mode # Typ) OR (obj.typ.strobj # obj) THEN FPrintErr(obj, 251) END
END ;
IF obj.sysflag < 0 THEN DevCPM.SymWInt(Ssys); DevCPM.SymWInt(obj.sysflag); portable := FALSE END;
IF obj.mode IN {LProc, XProc, CProc, Var, Con} THEN
(* name alias for types handled in OutStr *)
IF obj.library # NIL THEN
DevCPM.SymWInt(Slib); OutName(obj.library); portable := FALSE
END;
IF obj.entry # NIL THEN
DevCPM.SymWInt(Sentry); OutName(obj.entry); portable := FALSE
END
END;
CASE obj.mode OF
| Con:
OutConstant(obj); OutName(obj.name)
| Typ:
IF obj.typ.strobj = obj THEN DevCPM.SymWInt(Stype); OutStr(obj.typ)
ELSE DevCPM.SymWInt(Salias); OutStr(obj.typ); OutName(obj.name)
END
| Var:
IF obj.vis = externalR THEN DevCPM.SymWInt(Srvar) ELSE DevCPM.SymWInt(Svar) END ;
OutStr(obj.typ); OutName(obj.name);
IF (obj.typ.strobj = NIL) OR (obj.typ.strobj.name = null) THEN
(* compute fingerprint to avoid structural type equivalence *)
DevCPM.FPrint(expCtxt.reffp, obj.typ.ref)
END
| XProc:
DevCPM.SymWInt(Sxpro); OutSign(obj.typ, obj.link); OutName(obj.name)
| IProc:
DevCPM.SymWInt(Sipro); OutSign(obj.typ, obj.link); OutName(obj.name)
| CProc:
DevCPM.SymWInt(Scpro); OutSign(obj.typ, obj.link); ext := obj.conval.ext;
IF ext # NIL THEN j := LEN(ext^); i := 0; DevCPM.SymWInt(j);
WHILE i < j DO DevCPM.SymWCh(ext[i]); INC(i) END
ELSE DevCPM.SymWInt(0)
END;
OutName(obj.name); portable := FALSE
END
END
END ;
OutObj(obj.right)
END
END OutObj;
PROCEDURE Export*(VAR ext, new: BOOLEAN);
VAR i: INTEGER; nofmod: BYTE; done: BOOLEAN; old: Object; oldCSum: INTEGER;
BEGIN
symExtended := FALSE; symNew := FALSE; nofmod := nofGmod;
Import("@self", SelfName, done); nofGmod := nofmod;
oldCSum := DevCPM.checksum;
ASSERT(GlbMod[0].name^ = SelfName);
IF DevCPM.noerr THEN (* ~DevCPM.noerr => ~done *)
DevCPM.NewSym(SelfName);
IF DevCPM.noerr THEN
DevCPM.SymWInt(0); (* portable symfile *)
DevCPM.checksum := 0; (* start checksum here to avoid problems with proc id fixup *)
DevCPM.SymWInt(actVersion);
old := GlbMod[0]; portable := TRUE;
IF libName # "" THEN
DevCPM.SymWInt(Slib); OutName(libName); portable := FALSE;
IF done & ((old.library = NIL) OR (old.library^ # libName)) THEN
FPrintErr(NIL, 252)
END
ELSIF done & (old.library # NIL) THEN FPrintErr(NIL, 252)
END;
DevCPM.SymWInt(Smname); OutName(SelfName);
expCtxt.reffp := 0; expCtxt.ref := FirstRef;
expCtxt.nofm := 1; expCtxt.locmno[0] := 0;
i := 1; WHILE i < maxImps DO expCtxt.locmno[i] := -1; INC(i) END ;
OutObj(topScope.right);
ext := sfpresent & symExtended;
new := ~sfpresent OR symNew OR (DevCPM.checksum # oldCSum);
IF DevCPM.noerr & ~portable THEN
DevCPM.SymReset;
DevCPM.SymWInt(processor) (* nonportable symfile *)
END;
IF DevCPM.noerr & sfpresent & (impCtxt.reffp # expCtxt.reffp) THEN
new := TRUE
END ;
IF ~DevCPM.noerr THEN DevCPM.DeleteNewSym END
(* DevCPM.RegisterNewSym is called in OP2 after writing the object file *)
END
END
END Export; (* no new symbol file if ~DevCPM.noerr *)
PROCEDURE InitStruct(VAR typ: Struct; form: BYTE);
BEGIN
typ := NewStr(form, Basic); typ.ref := form; typ.size := 1; typ.allocated := TRUE;
typ.strobj := NewObj(); typ.pbfp := form; typ.pvfp := form; typ.fpdone := TRUE;
typ.idfp := form; typ.idfpdone := TRUE
END InitStruct;
PROCEDURE EnterBoolConst(IN name: Name; val: INTEGER);
VAR obj: Object;
BEGIN
Insert(name, obj); obj.conval := NewConst();
obj.mode := Con; obj.typ := booltyp; obj.conval.intval := val
END EnterBoolConst;
PROCEDURE EnterRealConst(IN name: Name; val: REAL; VAR obj: Object);
BEGIN
Insert(name, obj); obj.conval := NewConst();
obj.mode := Con; obj.typ := real32typ; obj.conval.realval := val
END EnterRealConst;
PROCEDURE EnterTyp(IN name: Name; form: BYTE; size: SHORTINT; VAR res: Struct);
VAR obj: Object; typ: Struct;
BEGIN
Insert(name, obj);
typ := NewStr(form, Basic); obj.mode := Typ; obj.typ := typ; obj.vis := external;
typ.strobj := obj; typ.size := size; typ.ref := form; typ.allocated := TRUE;
typ.pbfp := form; typ.pvfp := form; typ.fpdone := TRUE;
typ.idfp := form; typ.idfpdone := TRUE; res := typ
END EnterTyp;
PROCEDURE EnterProc(IN name: Name; num: SHORTINT);
VAR obj: Object;
BEGIN Insert(name, obj);
obj.mode := SProc; obj.typ := notyp; obj.adr := num
END EnterProc;
PROCEDURE EnterAttr(IN name: Name; num: SHORTINT);
VAR obj: Object;
BEGIN Insert(name, obj);
obj.mode := Attr; obj.adr := num
END EnterAttr;
PROCEDURE EnterTProc(ptr, rec: Struct; IN name: Name; num, typ: SHORTINT);
VAR obj, par: Object;
BEGIN
InsertField(name, rec, obj);
obj.mnolev := -128; (* for correct implement only behaviour *)
obj.mode := TProc; obj.num := num; obj.conval := NewConst();
obj.conval.setval := obj.conval.setval + {newAttr};
IF typ = 0 THEN (* FINALIZE, RELEASE *)
obj.typ := notyp; obj.vis := externalR;
INCL(obj.conval.setval, empAttr)
ELSIF typ = 1 THEN (* QueryInterface *)
par := NewObj(); par.name := NewName("int"); par.mode := VarPar; par.vis := outPar;
par.sysflag := 8; par.adr := 16; par.typ := punktyp;
par.link := obj.link; obj.link := par;
par := NewObj(); par.name := NewName("iid"); par.mode := VarPar; par.vis := inPar;
par.sysflag := 16; par.adr := 12; par.typ := guidtyp;
par.link := obj.link; obj.link := par;
obj.typ := restyp; obj.vis := external;
INCL(obj.conval.setval, extAttr)
ELSIF typ = 2 THEN (* AddRef, Release *)
obj.typ := notyp; obj.vis := externalR;
INCL(obj.conval.setval, isHidden);
INCL(obj.conval.setval, extAttr)
END;
par := NewObj(); par.name := NewName("this"); par.mode := Var;
par.adr := 8; par.typ := ptr;
par.link := obj.link; obj.link := par;
END EnterTProc;
(*
PROCEDURE EnterHdField(VAR root: Object; offs: SHORTINT);
VAR obj: Object;
BEGIN
obj := NewObj(); obj.mode := Fld;
obj.name := NewName(DevCPM.HdPtrName); obj.typ := undftyp; obj.adr := offs;
obj.link := root; root := obj
END EnterHdField;
*)
BEGIN
NEW(null, 1); null^ := "";
topScope := NIL; OpenScope(0, NIL); DevCPM.errpos := 0;
InitStruct(undftyp, Undef); InitStruct(notyp, NoTyp);
InitStruct(string8typ, String8); InitStruct(niltyp, NilTyp); niltyp.size := DevCPM.PointerSize;
InitStruct(string16typ, String16);
undftyp.BaseTyp := undftyp;
(*initialization of module SYSTEM*)
(*
EnterTyp("BYTE", Byte, 1, bytetyp);
EnterProc("NEW", sysnewfn);
*)
EnterTyp("PTR", Pointer, DevCPM.PointerSize, sysptrtyp);
EnterProc("ADR", adrfn);
EnterProc("TYP", typfn);
EnterProc("CC", ccfn);
EnterProc("LSH", lshfn);
EnterProc("ROT", rotfn);
EnterProc("GET", getfn);
EnterProc("PUT", putfn);
EnterProc("GETREG", getrfn);
EnterProc("PUTREG", putrfn);
EnterProc("BIT", bitfn);
EnterProc("VAL", valfn);
EnterProc("MOVE", movefn);
EnterProc("THISRECORD", thisrecfn);
EnterProc("THISARRAY", thisarrfn);
syslink := topScope.right; topScope.right := NIL;
(* initialization of module COM *)
EnterProc("ID", iidfn);
EnterProc("QUERY", queryfn);
EnterTyp("RESULT", Int32, 4, restyp);
restyp.ref := Res;
EnterTyp("GUID", Guid, 16, guidtyp);
guidtyp.form := Comp; guidtyp.comp := Array; guidtyp.n := 16;
EnterTyp("IUnknown^", IUnk, 12, iunktyp);
iunktyp.form := Comp; iunktyp.comp := Record; iunktyp.n := 3;
iunktyp.attribute := absAttr;
(*
EnterHdField(iunktyp.link, 12);
*)
iunktyp.BaseTyp := NIL; iunktyp.align := 4;
iunktyp.sysflag := interface; iunktyp.untagged := TRUE;
NEW(iunktyp.ext, 40); iunktyp.ext^ := "{00000000-0000-0000-C000-000000000046}";
EnterTyp("IUnknown", PUnk, DevCPM.PointerSize, punktyp);
punktyp.form := Pointer; punktyp.BaseTyp := iunktyp;
punktyp.sysflag := interface; punktyp.untagged := TRUE;
EnterTProc(punktyp, iunktyp, "QueryInterface", 0, 1);
EnterTProc(punktyp, iunktyp, "AddRef", 1, 2);
EnterTProc(punktyp, iunktyp, "Release", 2, 2);
comlink := topScope.right; topScope.right := NIL;
universe := topScope;
EnterProc("LCHR", lchrfn);
EnterProc("LENTIER", lentierfcn);
EnterTyp("ANYREC", AnyRec, 0, anytyp);
anytyp.form := Comp; anytyp.comp := Record; anytyp.n := 1;
anytyp.BaseTyp := NIL; anytyp.extlev := -1; (* !!! *)
anytyp.attribute := absAttr;
EnterTyp("ANYPTR", AnyPtr, DevCPM.PointerSize, anyptrtyp);
anyptrtyp.form := Pointer; anyptrtyp.BaseTyp := anytyp;
EnterTProc(anyptrtyp, anytyp, "FINALIZE", 0, 0);
EnterTProc(anyptrtyp, iunktyp, "RELEASE", 1, 0);
EnterProc("VALID", validfn);
EnterTyp("SHORTCHAR", Char8, 1, char8typ);
string8typ.BaseTyp := char8typ;
EnterTyp("CHAR", Char16, 2, char16typ);
EnterTyp("LONGCHAR", Char16, 2, lchar16typ);
string16typ.BaseTyp := char16typ;
EnterTyp("SET", Set, 4, settyp);
EnterTyp("BYTE", Int8, 1, int8typ);
guidtyp.BaseTyp := int8typ;
EnterTyp("SHORTINT", Int16, 2, int16typ);
EnterTyp("INTEGER", Int32, 4, int32typ);
EnterTyp("LONGINT", Int64, 8, int64typ);
EnterTyp("LARGEINT", Int64, 8, lint64typ);
EnterTyp("SHORTREAL", Real32, 4, real32typ);
EnterTyp("REAL", Real64, 8, real64typ);
EnterTyp("LONGREAL", Real64, 8, lreal64typ);
EnterTyp("BOOLEAN", Bool, 1, booltyp);
EnterBoolConst("FALSE", 0); (* 0 and 1 are compiler internal representation only *)
EnterBoolConst("TRUE", 1);
EnterRealConst("INF", DevCPM.InfReal, infinity);
EnterProc("HALT", haltfn);
EnterProc("NEW", newfn);
EnterProc("ABS", absfn);
EnterProc("CAP", capfn);
EnterProc("ORD", ordfn);
EnterProc("ENTIER", entierfn);
EnterProc("ODD", oddfn);
EnterProc("MIN", minfn);
EnterProc("MAX", maxfn);
EnterProc("CHR", chrfn);
EnterProc("SHORT", shortfn);
EnterProc("LONG", longfn);
EnterProc("SIZE", sizefn);
EnterProc("INC", incfn);
EnterProc("DEC", decfn);
EnterProc("INCL", inclfn);
EnterProc("EXCL", exclfn);
EnterProc("LEN", lenfn);
EnterProc("COPY", copyfn);
EnterProc("ASH", ashfn);
EnterProc("ASSERT", assertfn);
(*
EnterProc("ADR", adrfn);
EnterProc("TYP", typfn);
*)
EnterProc("BITS", bitsfn);
EnterAttr("ABSTRACT", absAttr);
EnterAttr("LIMITED", limAttr);
EnterAttr("EMPTY", empAttr);
EnterAttr("EXTENSIBLE", extAttr);
NEW(intrealtyp); intrealtyp^ := real64typ^;
impCtxt.ref[Undef] := undftyp; impCtxt.ref[Byte] := bytetyp;
impCtxt.ref[Bool] := booltyp; impCtxt.ref[Char8] := char8typ;
impCtxt.ref[Int8] := int8typ; impCtxt.ref[Int16] := int16typ;
impCtxt.ref[Int32] := int32typ; impCtxt.ref[Real32] := real32typ;
impCtxt.ref[Real64] := real64typ; impCtxt.ref[Set] := settyp;
impCtxt.ref[String8] := string8typ; impCtxt.ref[NilTyp] := niltyp;
impCtxt.ref[NoTyp] := notyp; impCtxt.ref[Pointer] := sysptrtyp;
impCtxt.ref[AnyPtr] := anyptrtyp; impCtxt.ref[AnyRec] := anytyp;
impCtxt.ref[Char16] := char16typ; impCtxt.ref[String16] := string16typ;
impCtxt.ref[Int64] := int64typ;
impCtxt.ref[IUnk] := iunktyp; impCtxt.ref[PUnk] := punktyp;
impCtxt.ref[Guid] := guidtyp; impCtxt.ref[Res] := restyp;
END DevCPT.
Objects:
mode | adr conval link scope leaf
------------------------------------------------
Undef | Not used
Var | vadr next regopt Glob or loc var or proc value parameter
VarPar| vadr next regopt Var parameter (vis = 0 | inPar | outPar)
Con | val Constant
Fld | off next Record field
Typ | Named type
LProc | entry sizes firstpar scope leaf Local procedure, entry adr set in back-end
XProc | entry sizes firstpar scope leaf External procedure, entry adr set in back-end
SProc | fno sizes Standard procedure
CProc | code firstpar scope Code procedure
IProc | entry sizes scope leaf Interrupt procedure, entry adr set in back-end
Mod | scope Module
Head | txtpos owner firstvar Scope anchor
TProc | entry sizes firstpar scope leaf Bound procedure, mthno = obj.num
Structures:
form comp | n BaseTyp link mno txtpos sysflag
----------------------------------------------------------------------------------
Undef Basic |
Byte Basic |
Bool Basic |
Char8 Basic |
Int8 Basic |
Int16 Basic |
Int32 Basic |
Real32 Basic |
Real64 Basic |
Set Basic |
String8 Basic |
NilTyp Basic |
NoTyp Basic |
Pointer Basic | PBaseTyp mno txtpos sysflag
ProcTyp Basic | ResTyp params mno txtpos sysflag
Comp Array | nofel ElemTyp mno txtpos sysflag
Comp DynArr| dim ElemTyp mno txtpos sysflag
Comp Record| nofmth RBaseTyp fields mno txtpos sysflag
Char16 Basic |
String16Basic |
Int64 Basic |
Nodes:
design = Nvar|Nvarpar|Nfield|Nderef|Nindex|Nguard|Neguard|Ntype|Nproc.
expr = design|Nconst|Nupto|Nmop|Ndop|Ncall.
nextexpr = NIL|expr.
ifstat = NIL|Nif.
casestat = Ncaselse.
sglcase = NIL|Ncasedo.
stat = NIL|Ninittd|Nenter|Nassign|Ncall|Nifelse|Ncase|Nwhile|Nrepeat|
Nloop|Nexit|Nreturn|Nwith|Ntrap.
class subcl obj left right link
---------------------------------------------------------
design Nvar var nextexpr
Nvarpar varpar nextexpr
Nfield field design nextexpr
Nderef ptr/str design nextexpr
Nindex design expr nextexpr
Nguard design nextexpr (typ = guard type)
Neguard design nextexpr (typ = guard type)
Ntype type nextexpr
Nproc normal proc nextexpr
super proc nextexpr
expr design
Nconst const (val = node.conval)
Nupto expr expr nextexpr
Nmop not expr nextexpr
minus expr nextexpr
is tsttype expr nextexpr
conv expr nextexpr
abs expr nextexpr
cap expr nextexpr
odd expr nextexpr
bit expr nextexpr {x}
adr expr nextexpr SYSTEM.ADR
typ expr nextexpr SYSTEM.TYP
cc Nconst nextexpr SYSTEM.CC
val expr nextexpr SYSTEM.VAL
Ndop times expr expr nextexpr
slash expr expr nextexpr
div expr expr nextexpr
mod expr expr nextexpr
and expr expr nextexpr
plus expr expr nextexpr
minus expr expr nextexpr
or expr expr nextexpr
eql expr expr nextexpr
neq expr expr nextexpr
lss expr expr nextexpr
leq expr expr nextexpr
grt expr expr nextexpr
geq expr expr nextexpr
in expr expr nextexpr
ash expr expr nextexpr
msk expr Nconst nextexpr
len design Nconst nextexpr
min expr expr nextexpr MIN
max expr expr nextexpr MAX
bit expr expr nextexpr SYSTEM.BIT
lsh expr expr nextexpr SYSTEM.LSH
rot expr expr nextexpr SYSTEM.ROT
Ncall fpar design nextexpr nextexpr
Ncomp stat expr nextexpr
nextexpr NIL
expr
ifstat NIL
Nif expr stat ifstat
casestat Ncaselse sglcase stat (minmax = node.conval)
sglcase NIL
Ncasedo Nconst stat sglcase
stat NIL
Ninittd stat (of node.typ)
Nenter proc stat stat stat (proc=NIL for mod)
Nassign assign design expr stat
newfn design nextexp stat
incfn design expr stat
decfn design expr stat
inclfn design expr stat
exclfn design expr stat
copyfn design expr stat
getfn design expr stat SYSTEM.GET
putfn expr expr stat SYSTEM.PUT
getrfn design Nconst stat SYSTEM.GETREG
putrfn Nconst expr stat SYSTEM.PUTREG
sysnewfn design expr stat SYSTEM.NEW
movefn expr expr stat SYSTEM.MOVE
(right.link = 3rd par)
Ncall fpar design nextexpr stat
Nifelse ifstat stat stat
assertfn ifstat stat
Ncase expr casestat stat
Nwhile expr stat stat
Nrepeat stat expr stat
Nloop stat stat
Nexit stat
Nreturn proc nextexpr stat (proc = NIL for mod)
Nwith ifstat stat stat
Ntrap expr stat
Ncomp stat stat stat
| Dev/Mod/CPT.odc |
MODULE DevCPV486;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, luowy"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = "http://e-collection.library.ethz.ch/eserv/eth:39386/eth-39386-02.pdf"
changes = "
- 20070216, bh, expr call in CaseStat corrected
- 20070307, bh, pop in Dim corrected
- 20160324, center #111, code cleanups
- 20160825, center #125, compiler TRAP for WITH statement was fixed
- 20170612, center #160, outdated link to OP2.Paper.ps
- 20170811, luowy, support for 16 bit aligment "ccall16"
"
issues = "
- ...
"
**)
IMPORT SYSTEM, DevCPM, DevCPT, DevCPE, DevCPH, DevCPL486, DevCPC486;
CONST
processor* = 10; (* for i386 *)
(* object modes *)
Var = 1; VarPar = 2; Con = 3; Fld = 4; Typ = 5; LProc = 6; XProc = 7;
SProc = 8; CProc = 9; IProc = 10; Mod = 11; Head = 12; TProc = 13;
(* item modes for i386 *)
Ind = 14; Abs = 15; Stk = 16; Cond = 17; Reg = 18; DInd = 19;
(* symbol values and ops *)
times = 1; slash = 2; div = 3; mod = 4;
and = 5; plus = 6; minus = 7; or = 8; eql = 9;
neq = 10; lss = 11; leq = 12; gtr = 13; geq = 14;
in = 15; is = 16; ash = 17; msk = 18; len = 19;
conv = 20; abs = 21; cap = 22; odd = 23; not = 33;
(*SYSTEM*)
adr = 24; cc = 25; bit = 26; lsh = 27; rot = 28; val = 29;
min = 34; max = 35; typfn = 36;
thisrecfn = 45; thisarrfn = 46;
shl = 50; shr = 51; lshr = 52; xor = 53;
(* structure forms *)
Undef = 0; Byte = 1; Bool = 2; Char8 = 3; Int8 = 4; Int16 = 5; Int32 = 6;
Real32 = 7; Real64 = 8; Set = 9; String8 = 10; NilTyp = 11; NoTyp = 12;
Pointer = 13; ProcTyp = 14; Comp = 15;
Char16 = 16; String16 = 17; Int64 = 18;
VString16to8 = 29; VString8 = 30; VString16 = 31;
realSet = {Real32, Real64};
(* composite structure forms *)
Basic = 1; Array = 2; DynArr = 3; Record = 4;
(* nodes classes *)
Nvar = 0; Nvarpar = 1; Nfield = 2; Nderef = 3; Nindex = 4; Nguard = 5; Neguard = 6;
Nconst = 7; Ntype = 8; Nproc = 9; Nupto = 10; Nmop = 11; Ndop = 12; Ncall = 13;
Ninittd = 14; Nif = 15; Ncaselse = 16; Ncasedo = 17; Nenter = 18; Nassign = 19;
Nifelse =20; Ncase = 21; Nwhile = 22; Nrepeat = 23; Nloop = 24; Nexit = 25;
Nreturn = 26; Nwith = 27; Ntrap = 28; Ncomp = 30;
Ndrop = 50; Nlabel = 51; Ngoto = 52; Njsr = 53; Nret = 54; Ncmp = 55;
(*function number*)
assign = 0; newfn = 1; incfn = 13; decfn = 14;
inclfn = 15; exclfn = 16; copyfn = 18; assertfn = 32;
(*SYSTEM function number*)
getfn = 24; putfn = 25; getrfn = 26; putrfn = 27; sysnewfn = 30; movefn = 31;
(* COM function number *)
validfn = 40; queryfn = 42;
(* procedure flags (conval.setval) *)
hasBody = 1; isRedef = 2; slNeeded = 3; imVar = 4; isHidden = 29; isGuarded = 30; isCallback = 31;
(* attribute flags (attr.adr, struct.attribute, proc.conval.setval) *)
newAttr = 16; absAttr = 17; limAttr = 18; empAttr = 19; extAttr = 20;
(* case statement flags (conval.setval) *)
useTable = 1; useTree = 2;
(* registers *)
AX = 0; CX = 1; DX = 2; BX = 3; SP = 4; BP = 5; SI = 6; DI = 7; AH = 4; CH = 5; DH = 6; BH = 7;
stk = 31; mem = 30; con = 29; float = 28; high = 27; short = 26; deref = 25; loaded = 24;
wreg = {AX, BX, CX, DX, SI, DI};
(* module visibility of objects *)
internal = 0; external = 1; externalR = 2; inPar = 3; outPar = 4;
(* sysflag *)
untagged = 1; noAlign = 3; align2 = 4; align8 = 6; union = 7; align16=8;
interface = 10; guarded = 8; noframe = 16;
nilBit = 1; enumBits = 8; new = 1; iid = 2;
stackArray = 120;
(* system trap numbers *)
withTrap = -1; caseTrap = -2; funcTrap = -3; typTrap = -4;
recTrap = -5; ranTrap = -6; inxTrap = -7; copyTrap = -8;
ParOff = 8;
interfaceSize = 16; (* SIZE(Kernel.Interface) *)
addRefFP = 4E27A847H; (* fingerprint of AddRef and Release procedures *)
intHandlerFP = 24B0EAE3H; (* fingerprint of InterfaceTrapHandler *)
numPreIntProc = 2;
VAR
Exit, Return: DevCPL486.Label;
assert, sequential: BOOLEAN;
nesting, actual: INTEGER;
query, addRef, release, release2: DevCPT.Object;
PROCEDURE Init*(opt: SET);
CONST ass = 2;
BEGIN
DevCPL486.Init(opt); DevCPC486.Init(opt);
assert := ass IN opt;
DevCPM.breakpc := MAX(INTEGER);
query := NIL; addRef := NIL; release := NIL; release2 := NIL; DevCPC486.intHandler := NIL;
END Init;
PROCEDURE Close*;
BEGIN
DevCPL486.Close
END Close;
PROCEDURE Align(VAR offset: INTEGER; align: INTEGER);
BEGIN
CASE align OF
1: (* ok *)
| 2: INC(offset, offset MOD 2)
| 4: INC(offset, (-offset) MOD 4)
| 8: INC(offset, (-offset) MOD 8)
END
END Align;
PROCEDURE NegAlign(VAR offset: INTEGER; align: INTEGER);
BEGIN
CASE align OF
1: (* ok *)
| 2: DEC(offset, offset MOD 2)
| 4: DEC(offset, offset MOD 4)
| 8: DEC(offset, offset MOD 8)
| 16: DEC(offset, offset MOD 16)
END
END NegAlign;
PROCEDURE Base(typ: DevCPT.Struct; limit: INTEGER): INTEGER; (* typ.comp # DynArr *)
VAR align: INTEGER;
BEGIN
WHILE typ.comp = Array DO typ := typ.BaseTyp END ;
IF typ.comp = Record THEN
align := typ.align
ELSE
align := typ.size;
END;
IF align > limit THEN RETURN limit ELSE RETURN align END
END Base;
(* -----------------------------------------------------
reference implementation of TypeSize for portable symbol files
mandatory for all non-system structures
PROCEDURE TypeSize (typ: DevCPT.Struct);
VAR f, c: SHORTINT; offset: LONGINT; fld: DevCPT.Object; btyp: DevCPT.Struct;
BEGIN
IF typ.size = -1 THEN
f := typ.form; c := typ.comp; btyp := typ.BaseTyp;
IF c = Record THEN
IF btyp = NIL THEN offset := 0 ELSE TypeSize(btyp); offset := btyp.size END;
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
btyp := fld.typ; TypeSize(btyp);
IF btyp.size >= 4 THEN INC(offset, (-offset) MOD 4)
ELSIF btyp.size >= 2 THEN INC(offset, offset MOD 2)
END;
fld.adr := offset; INC(offset, btyp.size);
fld := fld.link
END;
IF offset > 2 THEN INC(offset, (-offset) MOD 4) END;
typ.size := offset; typ.align := 4;
typ.n := -1 (* methods not counted yet *)
ELSIF c = Array THEN
TypeSize(btyp);
typ.size := typ.n * btyp.size
ELSIF f = Pointer THEN
typ.size := DevCPM.PointerSize
ELSIF f = ProcTyp THEN
typ.size := DevCPM.ProcSize
ELSE (* c = DynArr *)
TypeSize(btyp);
IF btyp.comp = DynArr THEN typ.size := btyp.size + 4
ELSE typ.size := 8
END
END
END
END TypeSize;
----------------------------------------------------- *)
PROCEDURE GTypeSize (typ: DevCPT.Struct; guarded: BOOLEAN);
VAR f, c: BYTE; offset, align, falign, alignLimit: INTEGER;
fld: DevCPT.Object; btyp: DevCPT.Struct;
BEGIN
IF typ.untagged THEN guarded := TRUE END;
IF typ = DevCPT.undftyp THEN DevCPM.err(58)
ELSIF typ.size = -1 THEN
f := typ.form; c := typ.comp; btyp := typ.BaseTyp;
IF c = Record THEN
IF btyp = NIL THEN offset := 0; align := 1;
ELSE GTypeSize(btyp, guarded); offset := btyp.size; align := btyp.align
END ;
IF typ.sysflag = noAlign THEN alignLimit := 1
ELSIF typ.sysflag = align2 THEN alignLimit := 2
ELSIF typ.sysflag = align8 THEN alignLimit := 8
ELSIF typ.sysflag = align16 THEN alignLimit := 16
ELSE alignLimit := 4
END;
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
btyp := fld.typ; GTypeSize(btyp, guarded);
IF typ.sysflag > 0 THEN falign := Base(btyp, alignLimit)
ELSIF btyp.size >= 4 THEN falign := 4
ELSIF btyp.size >= 2 THEN falign := 2
ELSE falign := 1
END;
IF typ.sysflag = union THEN
fld.adr := 0;
IF btyp.size > offset THEN offset := btyp.size END;
ELSE
Align(offset, falign);
fld.adr := offset;
IF offset <= MAX(INTEGER) - 4 - btyp.size THEN INC(offset, btyp.size)
ELSE offset := 4; DevCPM.Mark(214, typ.txtpos)
END
END;
IF falign > align THEN align := falign END ;
fld := fld.link
END;
(*
IF (typ.sysflag = interface) & (typ.BaseTyp = NIL) THEN
fld := DevCPT.NewObj(); fld.name^ := DevCPM.HdPtrName; fld.mode := Fld;
fld.typ := DevCPT.undftyp; fld.adr := 8;
fld.right := typ.link; typ.link := fld;
fld := DevCPT.NewObj(); fld.name^ := DevCPM.HdPtrName; fld.mode := Fld;
fld.typ := DevCPT.undftyp; fld.adr := 12;
typ.link.link := fld; typ.link.left := fld;
offset := interfaceSize; align := 4
END;
*)
IF typ.sysflag <= 0 THEN align := 4 END;
typ.align := align;
IF (typ.sysflag > 0) OR (offset > 2) THEN Align(offset, align) END;
typ.size := offset;
typ.n := -1 (* methods not counted yet *)
ELSIF c = Array THEN
GTypeSize(btyp, guarded);
IF (btyp.size = 0) OR (typ.n <= MAX(INTEGER) DIV btyp.size) THEN typ.size := typ.n * btyp.size
ELSE typ.size := 4; DevCPM.Mark(214, typ.txtpos)
END
ELSIF f = Pointer THEN
typ.size := DevCPM.PointerSize;
IF guarded & ~typ.untagged THEN DevCPM.Mark(143, typ.txtpos) END
ELSIF f = ProcTyp THEN
typ.size := DevCPM.ProcSize
ELSE (* c = DynArr *)
GTypeSize(btyp, guarded);
IF (typ.sysflag = untagged) OR typ.untagged THEN typ.size := 4
ELSE
IF btyp.comp = DynArr THEN typ.size := btyp.size + 4
ELSE typ.size := 8
END
END
END
END
END GTypeSize;
PROCEDURE TypeSize*(typ: DevCPT.Struct); (* also called from DevCPT.InStruct for arrays *)
BEGIN
GTypeSize(typ, FALSE)
END TypeSize;
PROCEDURE GetComKernel;
BEGIN
IF addRef = NIL THEN
DevCPT.OpenScope(SHORT(SHORT(-DevCPT.nofGmod)), NIL);
DevCPT.topScope.name := DevCPT.NewName("$$");
DevCPT.Insert("AddRef", addRef);
addRef.mode := XProc;
addRef.fprint := addRefFP;
addRef.fpdone := TRUE;
DevCPT.Insert("Release", release);
release.mode := XProc;
release.fprint := addRefFP;
release.fpdone := TRUE;
DevCPT.Insert("Release2", release2);
release2.mode := XProc;
release2.fprint := addRefFP;
release2.fpdone := TRUE;
DevCPT.Insert("InterfaceTrapHandler", DevCPC486.intHandler);
DevCPC486.intHandler.mode := XProc;
DevCPC486.intHandler.fprint := intHandlerFP;
DevCPC486.intHandler.fpdone := TRUE;
DevCPT.GlbMod[DevCPT.nofGmod] := DevCPT.topScope;
INC(DevCPT.nofGmod);
DevCPT.CloseScope;
END
END GetComKernel;
PROCEDURE EnumTProcs(rec: DevCPT.Struct); (* method numbers in declaration order *)
VAR btyp: DevCPT.Struct; obj, redef: DevCPT.Object;
BEGIN
IF rec.n = -1 THEN
rec.n := 0; btyp := rec.BaseTyp;
IF btyp # NIL THEN
EnumTProcs(btyp); rec.n := btyp.n;
END;
obj := rec.strobj.link;
WHILE obj # NIL DO
DevCPT.FindBaseField(obj.name^, rec, redef);
IF redef # NIL THEN obj.num := redef.num (*mthno*);
IF ~(isRedef IN obj.conval.setval) OR (redef.conval.setval * {extAttr, absAttr, empAttr} = {}) THEN
DevCPM.Mark(119, rec.txtpos)
END
ELSE obj.num := rec.n; INC(rec.n)
END ;
IF obj.conval.setval * {hasBody, absAttr, empAttr} = {} THEN DevCPM.Mark(129, obj.adr) END;
obj := obj.nlink
END
END
END EnumTProcs;
PROCEDURE CountTProcs(rec: DevCPT.Struct);
VAR btyp: DevCPT.Struct; comProc: INTEGER; m, rel: DevCPT.Object; name: DevCPT.Name;
PROCEDURE TProcs(obj: DevCPT.Object); (* obj.mnolev = 0, TProcs of base type already counted *)
VAR redef: DevCPT.Object;
BEGIN
IF obj # NIL THEN
TProcs(obj.left);
IF obj.mode = TProc THEN
DevCPT.FindBaseField(obj.name^, rec, redef);
(* obj.adr := 0 *)
IF redef # NIL THEN
obj.num := redef.num (*mthno*);
IF (redef.link # NIL) & (redef.link.typ.sysflag = interface) THEN
obj.num := numPreIntProc + comProc - 1 - obj.num
END;
IF ~(isRedef IN obj.conval.setval) OR (redef.conval.setval * {extAttr, absAttr, empAttr} = {}) THEN
DevCPM.Mark(119, rec.txtpos)
END
ELSE obj.num := rec.n; INC(rec.n)
END ;
IF obj.conval.setval * {hasBody, absAttr, empAttr} = {} THEN DevCPM.Mark(129, obj.adr) END
END ;
TProcs(obj.right)
END
END TProcs;
BEGIN
IF rec.n = -1 THEN
comProc := 0;
IF rec.untagged THEN rec.n := 0 ELSE rec.n := DevCPT.anytyp.n END;
btyp := rec.BaseTyp;
IF btyp # NIL THEN
IF btyp.sysflag = interface THEN
EnumTProcs(btyp); rec.n := btyp.n + numPreIntProc; comProc := btyp.n;
ELSE
CountTProcs(btyp); rec.n := btyp.n
END
END;
WHILE (btyp # NIL) & (btyp # DevCPT.undftyp) & (btyp.sysflag # interface) DO btyp := btyp.BaseTyp END;
IF (btyp # NIL) & (btyp.sysflag = interface) THEN
IF comProc > 0 THEN
name := "QueryInterface"; DevCPT.FindField(name, rec, m);
IF m.link.typ.sysflag = interface THEN
DevCPT.InsertField(name, rec, m); m.mode := TProc; m.typ := rec;
m.conval := DevCPT.NewConst(); m.conval.setval := {isRedef, hasBody, isCallback, extAttr};
m.nlink := query; query := m
END;
name := "AddRef";
DevCPT.InsertField(name, rec, m); m.mode := TProc; m.mnolev := 0;
m.conval := DevCPT.NewConst(); m.conval.setval := {isRedef, hasBody, isCallback, isHidden, extAttr};
GetComKernel; addRef.used := TRUE; m.adr := -1; m.nlink := addRef;
END;
name := "RELEASE";
DevCPT.FindField(name, rec, rel);
IF (rel # NIL) & (rel.link.typ = DevCPT.anyptrtyp) THEN rel := NIL END;
IF (comProc > 0) OR (rel # NIL) THEN
name := "Release";
DevCPT.InsertField(name, rec, m); m.mode := TProc; m.mnolev := 0;
m.conval := DevCPT.NewConst(); m.conval.setval := {isRedef, hasBody, isCallback, isHidden, extAttr};
GetComKernel; m.adr := -1;
IF rel # NIL THEN release2.used := TRUE; m.nlink := release2
ELSE release.used := TRUE; m.nlink := release
END
END
END;
TProcs(rec.link);
END
END CountTProcs;
PROCEDURE ^Parameters(firstPar, proc: DevCPT.Object);
PROCEDURE ^TProcedures(obj: DevCPT.Object);
PROCEDURE TypeAlloc(typ: DevCPT.Struct);
VAR f, c: SHORTINT; fld: DevCPT.Object; btyp: DevCPT.Struct;
BEGIN
IF ~typ.allocated THEN (* not imported, not predefined, not allocated yet *)
typ.allocated := TRUE;
TypeSize(typ);
f := typ.form; c := typ.comp; btyp := typ.BaseTyp;
IF c = Record THEN
IF typ.sysflag = interface THEN
EnumTProcs(typ);
ELSE
CountTProcs(typ)
END;
IF typ.extlev > 14 THEN DevCPM.Mark(233, typ.txtpos) END;
IF btyp # NIL THEN TypeAlloc(btyp) END;
IF ~typ.untagged THEN DevCPE.AllocTypDesc(typ) END;
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
TypeAlloc(fld.typ); fld := fld.link
END;
TProcedures(typ.link)
ELSIF f = Pointer THEN
IF btyp = DevCPT.undftyp THEN DevCPM.Mark(128, typ.txtpos)
ELSE TypeAlloc(btyp);
END
ELSIF f = ProcTyp THEN
TypeAlloc(btyp);
Parameters(typ.link, NIL)
ELSE (* c IN {Array, DynArr} *)
TypeAlloc(btyp);
IF (btyp.comp = DynArr) & btyp.untagged & ~typ.untagged THEN DevCPM.Mark(225, typ.txtpos) END;
END
END
END TypeAlloc;
PROCEDURE NumOfIntProc (typ: DevCPT.Struct): INTEGER;
BEGIN
WHILE (typ # NIL) & (typ.sysflag # interface) DO typ := typ.BaseTyp END;
IF typ # NIL THEN RETURN typ.n
ELSE RETURN 0
END
END NumOfIntProc;
PROCEDURE Parameters(firstPar, proc: DevCPT.Object);
(* firstPar.mnolev = 0 *)
VAR par: DevCPT.Object; typ: DevCPT.Struct; padr, vadr: INTEGER;
BEGIN
padr := ParOff; par := firstPar;
WHILE par # NIL DO
typ := par.typ; TypeAlloc(typ);
par.adr := padr;
IF (par.mode = VarPar) & (typ.comp # DynArr) THEN
IF (typ.comp = Record) & ~typ.untagged THEN INC(padr, 8)
ELSE INC(padr, 4)
END
ELSE
IF (par.mode = Var) & (typ.comp = DynArr) & typ.untagged THEN DevCPM.err(145) END;
INC(padr, typ.size); Align(padr, 4)
END;
par := par.link
END;
IF proc # NIL THEN
IF proc.mode = XProc THEN
INCL(proc.conval.setval, isCallback)
ELSIF (proc.mode = TProc)
& (proc.num >= numPreIntProc)
& (proc.num < numPreIntProc + NumOfIntProc(proc.link.typ))
THEN
INCL(proc.conval.setval, isCallback);
INCL(proc.conval.setval, isGuarded)
END;
IF proc.sysflag = guarded THEN INCL(proc.conval.setval, isGuarded) END;
IF isGuarded IN proc.conval.setval THEN
GetComKernel; vadr := -24
ELSE
vadr := 0;
IF imVar IN proc.conval.setval THEN DEC(vadr, 4) END;
IF isCallback IN proc.conval.setval THEN DEC(vadr, 8) END
END;
proc.conval.intval := padr; proc.conval.intval2 := vadr;
END
END Parameters;
PROCEDURE Variables(var: DevCPT.Object; VAR varSize: INTEGER);
(* allocates only offsets, regs allocated in DevCPC486.Enter *)
VAR adr: INTEGER; typ: DevCPT.Struct;
BEGIN
adr := varSize;
WHILE var # NIL DO
typ := var.typ; TypeAlloc(typ);
DEC(adr, typ.size);
IF typ.sysflag = align16 THEN
NegAlign(adr, 16)
ELSE
NegAlign(adr, Base(typ, 4));
END;
var.adr := adr;
var := var.link
END;
NegAlign(adr, 4); varSize := adr
END Variables;
PROCEDURE ^Objects(obj: DevCPT.Object);
PROCEDURE Procedure(obj: DevCPT.Object);
(* obj.mnolev = 0 *)
VAR oldPos: INTEGER;
BEGIN
oldPos := DevCPM.errpos; DevCPM.errpos := obj.scope.adr;
TypeAlloc(obj.typ);
Parameters(obj.link, obj);
IF ~(hasBody IN obj.conval.setval) THEN DevCPM.Mark(129, obj.adr) END ;
Variables(obj.scope.scope, obj.conval.intval2); (* local variables *)
Objects(obj.scope.right);
DevCPM.errpos := oldPos
END Procedure;
PROCEDURE TProcedures(obj: DevCPT.Object);
(* obj.mnolev = 0 *)
BEGIN
IF obj # NIL THEN
TProcedures(obj.left);
IF (obj.mode = TProc) & (obj.scope # NIL) THEN
TypeAlloc(obj.typ);
Parameters(obj.link, obj);
Variables(obj.scope.scope, obj.conval.intval2); (* local variables *)
Objects(obj.scope.right);
END ;
TProcedures(obj.right)
END
END TProcedures;
PROCEDURE Objects(obj: DevCPT.Object);
BEGIN
IF obj # NIL THEN
Objects(obj.left);
IF obj.mode IN {Con, Typ, LProc, XProc, CProc, IProc} THEN
IF (obj.mode IN {Con, Typ}) THEN TypeAlloc(obj.typ);
ELSE Procedure(obj)
END
END ;
Objects(obj.right)
END
END Objects;
PROCEDURE Allocate*;
VAR gvarSize: INTEGER;
BEGIN
DevCPM.errpos := DevCPT.topScope.adr; (* text position of scope used if error *)
gvarSize := 0;
Variables(DevCPT.topScope.scope, gvarSize); DevCPE.dsize := -gvarSize;
INC(DevCPE.dsize, DevCPM.cacheLineSize);(* gap to prevent cache line share between code and data*)
Objects(DevCPT.topScope.right)
END Allocate;
(************************)
PROCEDURE SameExp (n1, n2: DevCPT.Node): BOOLEAN;
BEGIN
WHILE (n1.class = n2.class) & (n1.typ = n2.typ) DO
CASE n1.class OF
| Nvar, Nvarpar, Nproc: RETURN n1.obj = n2.obj
| Nconst: RETURN (n1.typ.form IN {Int8..Int32}) & (n1.conval.intval = n2.conval.intval)
| Nfield: IF n1.obj # n2.obj THEN RETURN FALSE END
| Nderef, Nguard:
| Nindex: IF ~SameExp(n1.right, n2.right) THEN RETURN FALSE END
| Nmop: IF (n1.subcl # n2.subcl) OR (n1.subcl = is) THEN RETURN FALSE END
| Ndop: IF (n1.subcl # n2.subcl) OR ~SameExp(n1.right, n2.right) THEN RETURN FALSE END
ELSE RETURN FALSE
END ;
n1 := n1.left; n2 := n2.left
END;
RETURN FALSE
END SameExp;
PROCEDURE Check (n: DevCPT.Node; VAR used: SET; VAR size: INTEGER);
VAR ux, uy: SET; sx, sy, sf: INTEGER; f: BYTE;
BEGIN
used := {}; size := 0;
WHILE n # NIL DO
IF n.class # Ncomp THEN
Check(n.left, ux, sx);
Check(n.right, uy, sy)
END;
ux := ux + uy; sf := 0;
CASE n.class OF
| Nvar, Nvarpar:
IF (n.class = Nvarpar) OR (n.typ.comp = DynArr) OR
(n.obj.mnolev > 0) &
(DevCPC486.imLevel[n.obj.mnolev] < DevCPC486.imLevel[DevCPL486.level]) THEN sf := 1 END
| Nguard: sf := 2
| Neguard, Nderef: sf := 1
| Nindex:
IF (n.right.class # Nconst) OR (n.left.typ.comp = DynArr) THEN sf := 1 END;
IF sx > 0 THEN INC(sy) END
| Nmop:
CASE n.subcl OF
| is, adr, typfn, minus, abs, cap, val: sf := 1
| bit: sf := 2; INCL(ux, CX)
| conv:
IF n.typ.form = Int64 THEN sf := 2
ELSIF ~(n.typ.form IN realSet) THEN sf := 1;
IF n.left.typ.form IN realSet THEN INCL(ux, AX) END
END
| odd, cc, not:
END
| Ndop:
f := n.left.typ.form;
IF f # Bool THEN
CASE n.subcl OF
| times:
sf := 1;
IF f = Int8 THEN INCL(ux, AX) END
| div, mod:
sf := 3; INCL(ux, AX);
IF f > Int8 THEN INCL(ux, DX) END
| eql..geq:
IF f IN {String8, String16, Comp} THEN ux := ux + {AX, CX, SI, DI}; sf := 4
ELSIF f IN realSet THEN INCL(ux, AX); sf := 1
ELSE sf := 1
END
| ash, lsh, rot:
IF n.right.class = Nconst THEN sf := 1 ELSE sf := 2; INCL(ux, CX) END
| slash, plus, minus, msk, in, bit:
sf := 1
| len:
IF f IN {String8, String16} THEN ux := ux + {AX, CX, DI}; sf := 3
ELSE sf := 1
END
| min, max:
sf := 1;
IF f IN realSet THEN INCL(ux, AX) END
| queryfn:
ux := ux + {CX, SI, DI}; sf := 4
END;
IF sy > sx THEN INC(sx) ELSE INC(sy) END
END
| Nupto:
IF (n.right.class = Nconst) OR (n.left.class = Nconst) THEN sf := 2
ELSE sf := 3
END;
INCL(ux, CX); INC(sx)
| Ncall, Ncomp:
sf := 10; ux := wreg + {float}
| Nfield, Nconst, Nproc, Ntype:
END;
used := used + ux;
IF sx > size THEN size := sx END;
IF sy > size THEN size := sy END;
IF sf > size THEN size := sf END;
n := n.link
END;
IF size > 10 THEN size := 10 END
END Check;
PROCEDURE^ expr (n: DevCPT.Node; VAR x: DevCPL486.Item; hint, stop: SET);
PROCEDURE DualExp (left, right: DevCPT.Node; VAR x, y: DevCPL486.Item; hx, hy, stpx, stpy: SET);
VAR ux, uy: SET; sx, sy: INTEGER;
BEGIN
Check(left, ux, sx); Check(right, uy, sy);
IF sy > sx THEN
expr(right, y, hy + stpy, ux + stpy * {AX, CX});
expr(left, x, hx, stpx);
DevCPC486.Assert(y, hy, stpy)
ELSE
expr(left, x, hx + stpx, uy);
expr(right, y, hy, stpy);
DevCPC486.Assert(x, hx, stpx)
END;
END DualExp;
PROCEDURE IntDOp (n: DevCPT.Node; VAR x: DevCPL486.Item; hint: SET);
VAR y: DevCPL486.Item;
BEGIN
DualExp(n.left, n.right, x, y, hint, hint, {stk}, {stk});
IF (x.mode = Reg) & DevCPC486.Fits(x, hint) THEN
DevCPC486.IntDOp(x, y, n.subcl, FALSE)
ELSIF (y.mode = Reg) & DevCPC486.Fits(y, hint) THEN
DevCPC486.IntDOp(y, x, n.subcl, TRUE); x := y
ELSIF x.mode # Reg THEN
DevCPC486.Load(x, hint, {con}); DevCPC486.IntDOp(x, y, n.subcl, FALSE)
ELSIF y.mode # Reg THEN
DevCPC486.Load(y, hint, {con}); DevCPC486.IntDOp(y, x, n.subcl, TRUE); x := y
ELSE
DevCPC486.IntDOp(x, y, n.subcl, FALSE)
END
END IntDOp;
PROCEDURE FloatDOp (n: DevCPT.Node; VAR x: DevCPL486.Item);
VAR y: DevCPL486.Item; ux, uy, uf: SET; sx, sy: INTEGER;
BEGIN
Check(n.left, ux, sx); Check(n.right, uy, sy);
IF (n.subcl = min) OR (n.subcl = max) THEN uf := {AX} ELSE uf := {} END;
IF (sy > sx) OR (sy = sx) & ((n.subcl = mod) OR (n.subcl = ash)) THEN
expr(n.right, x, {}, ux + {mem, stk});
expr(n.left, y, {}, uf);
DevCPC486.FloatDOp(x, y, n.subcl, TRUE)
ELSIF float IN uy THEN (* function calls in both operands *)
expr(n.left, y, {}, uy + {mem});
expr(n.right, x, {}, {mem, stk});
DevCPC486.FloatDOp(x, y, n.subcl, TRUE)
ELSE
expr(n.left, x, {}, uy + {mem, stk});
expr(n.right, y, {}, uf);
DevCPC486.FloatDOp(x, y, n.subcl, FALSE)
END
END FloatDOp;
PROCEDURE design (n: DevCPT.Node; VAR x: DevCPL486.Item; hint, stop: SET);
VAR obj: DevCPT.Object; y: DevCPL486.Item; ux, uy: SET; sx, sy: INTEGER;
BEGIN
CASE n.class OF
Nvar, Nvarpar:
obj := n.obj; x.mode := obj.mode; x.obj := obj; x.scale := 0;
IF obj.typ.comp = DynArr THEN x.mode := VarPar END;
IF obj.mnolev < 0 THEN x.offset := 0; x.tmode := Con
ELSIF x.mode = Var THEN x.offset := obj.adr; x.tmode := Con
ELSE x.offset := 0; x.tmode := VarPar
END
| Nfield:
design(n.left, x, hint, stop); DevCPC486.Field(x, n.obj)
| Nderef:
IF n.subcl # 0 THEN
expr(n.left, x, hint, stop);
IF n.typ.form = String8 THEN x.form := VString8 ELSE x.form := VString16 END
ELSE
expr(n.left, x, hint, stop + {mem} - {loaded}); DevCPC486.DeRef(x)
END
| Nindex:
Check(n.left, ux, sx); Check(n.right, uy, sy);
IF wreg - uy = {} THEN
expr(n.right, y, hint + stop, ux);
design(n.left, x, hint, stop);
IF x.scale # 0 THEN DevCPC486.Index(x, y, {}, {}) ELSE DevCPC486.Index(x, y, hint, stop) END
ELSE
design(n.left, x, hint, stop + uy);
IF x.scale # 0 THEN expr(n.right, y, {}, {}); DevCPC486.Index(x, y, {}, {})
ELSE expr(n.right, y, hint, stop); DevCPC486.Index(x, y, hint, stop)
END
END
| Nguard, Neguard:
IF n.typ.form = Pointer THEN
IF loaded IN stop THEN expr(n.left, x, hint, stop) ELSE expr(n.left, x, hint, stop + {mem}) END
ELSE design(n.left, x, hint, stop)
END;
DevCPC486.TypTest(x, n.typ, TRUE, n.class = Neguard)
| Nproc:
obj := n.obj; x.mode := obj.mode; x.obj := obj;
IF x.mode = TProc THEN x.offset := obj.num; (*mthno*) x.scale := n.subcl (* super *) END
END;
x.typ := n.typ
END design;
PROCEDURE IsAllocDynArr (x: DevCPT.Node): BOOLEAN;
BEGIN
IF (x.typ.comp = DynArr) & ~x.typ.untagged THEN
WHILE x.class = Nindex DO x := x.left END;
IF x.class = Nderef THEN RETURN TRUE END
END;
RETURN FALSE
END IsAllocDynArr;
PROCEDURE StringOp (left, right: DevCPT.Node; VAR x, y: DevCPL486.Item; useLen: BOOLEAN);
VAR ax, ay: DevCPL486.Item; ux: SET; sx: INTEGER;
BEGIN
Check(left, ux, sx);
expr(right, y, wreg - {SI} + ux, {});
ay := y; DevCPC486.GetAdr(ay, wreg - {SI} + ux, {}); DevCPC486.Assert(ay, wreg - {SI}, ux);
IF useLen & IsAllocDynArr(left) THEN (* keep len descriptor *)
design(left, x, wreg - {CX}, {loaded});
DevCPC486.Prepare(x, wreg - {CX} + {deref}, {DI})
ELSE
expr(left, x, wreg - {DI}, {})
END;
ax := x; DevCPC486.GetAdr(ax, {}, wreg - {DI} + {stk, con});
DevCPC486.Load(ay, {}, wreg - {SI} + {con});
DevCPC486.Free(ax); DevCPC486.Free(ay)
END StringOp;
PROCEDURE AdrExpr (n: DevCPT.Node; VAR x: DevCPL486.Item; hint, stop: SET);
BEGIN
IF n.class < Nconst THEN
design(n, x, hint + stop, {loaded}); DevCPC486.Prepare(x, hint + {deref}, stop)
ELSE expr(n, x, hint, stop)
END
END AdrExpr;
(* ---------- interface pointer reference counting ---------- *)
PROCEDURE HandleIPtrs (typ: DevCPT.Struct; VAR x, y: DevCPL486.Item; add, rel, init: BOOLEAN);
PROCEDURE FindPtrs (typ: DevCPT.Struct; adr: INTEGER);
VAR fld: DevCPT.Object; btyp: DevCPT.Struct; i, n: INTEGER;
BEGIN
IF (typ.form = Pointer) & (typ.sysflag = interface) THEN
IF add THEN DevCPC486.IPAddRef(y, adr, TRUE) END;
IF rel THEN DevCPC486.IPRelease(x, adr, TRUE, init) END
ELSIF (typ.comp = Record) & (typ.sysflag # union) THEN
btyp := typ.BaseTyp;
IF btyp # NIL THEN FindPtrs(btyp, adr) END ;
fld := typ.link;
WHILE (fld # NIL) & (fld.mode = Fld) DO
IF (fld.sysflag = interface) & (fld.name^ = DevCPM.HdUtPtrName) THEN
IF add THEN DevCPC486.IPAddRef(y, fld.adr + adr, TRUE) END;
IF rel THEN DevCPC486.IPRelease(x, fld.adr + adr, TRUE, init) END
ELSE FindPtrs(fld.typ, fld.adr + adr)
END;
fld := fld.link
END
ELSIF typ.comp = Array THEN
btyp := typ.BaseTyp; n := typ.n;
WHILE btyp.comp = Array DO n := btyp.n * n; btyp := btyp.BaseTyp END ;
IF DevCPC486.ContainsIPtrs(btyp) THEN
i := 0;
WHILE i < n DO FindPtrs(btyp, adr); INC(adr, btyp.size); INC(i) END
END
ELSIF typ.comp = DynArr THEN
IF DevCPC486.ContainsIPtrs(typ) THEN DevCPM.err(221) END
END
END FindPtrs;
BEGIN
FindPtrs(typ, 0)
END HandleIPtrs;
PROCEDURE CountedPtr (n: DevCPT.Node): BOOLEAN;
BEGIN
RETURN (n.typ.form = Pointer) & (n.typ.sysflag = interface)
& ((n.class = Ncall) OR (n.class = Ncomp) & (n.right.class = Ncall))
END CountedPtr;
PROCEDURE IPAssign (nx, ny: DevCPT.Node; VAR x, y: DevCPL486.Item; ux: SET);
(* nx.typ.form = Pointer & nx.typ.sysflag = interface *)
BEGIN
expr(ny, y, {}, wreg - {SI} + {mem, stk});
IF (ny.class # Nconst) & ~CountedPtr(ny) THEN
DevCPC486.IPAddRef(y, 0, TRUE)
END;
IF nx # NIL THEN
DevCPC486.Assert(y, {}, wreg - {SI} + ux);
expr(nx, x, wreg - {DI}, {loaded});
IF (x.mode = Ind) & (x.reg IN wreg - {SI, DI}) OR (x.scale # 0) THEN
DevCPC486.GetAdr(x, {}, wreg - {DI} + {con});
x.mode := Ind; x.offset := 0; x.scale := 0
END;
DevCPC486.IPRelease(x, 0, TRUE, FALSE);
END
END IPAssign;
PROCEDURE IPStructAssign (typ: DevCPT.Struct);
VAR x, y: DevCPL486.Item;
BEGIN
IF typ.comp = DynArr THEN DevCPM.err(270) END;
(* addresses in SI and DI *)
x.mode := Ind; x.reg := DI; x.offset := 0; x.scale := 0;
y.mode := Ind; y.reg := SI; y.offset := 0; y.scale := 0;
HandleIPtrs(typ, x, y, TRUE, TRUE, FALSE)
END IPStructAssign;
PROCEDURE IPFree (nx: DevCPT.Node; VAR x: DevCPL486.Item);
BEGIN
expr(nx, x, wreg - {DI}, {loaded}); DevCPC486.GetAdr(x, {}, wreg - {DI} + {con});
x.mode := Ind; x.offset := 0; x.scale := 0;
IF nx.typ.form = Comp THEN
HandleIPtrs(nx.typ, x, x, FALSE, TRUE, TRUE)
ELSE (* nx.typ.form = Pointer & nx.typ.sysflag = interface *)
DevCPC486.IPRelease(x, 0, TRUE, TRUE);
END
END IPFree;
(* unchanged val parameters allways counted because of aliasing problems REMOVED! *)
PROCEDURE InitializeIPVars (proc: DevCPT.Object);
VAR x: DevCPL486.Item; obj: DevCPT.Object;
BEGIN
x.mode := Ind; x.reg := BP; x.scale := 0; x.form := Pointer;
obj := proc.link;
WHILE obj # NIL DO
IF (obj.mode = Var) & obj.used THEN (* changed value parameters *)
x.offset := obj.adr;
HandleIPtrs(obj.typ, x, x, TRUE, FALSE, FALSE)
END;
obj := obj.link
END
END InitializeIPVars;
PROCEDURE ReleaseIPVars (proc: DevCPT.Object);
VAR x, ax, dx, si, di: DevCPL486.Item; obj: DevCPT.Object;
BEGIN
obj := proc.link;
WHILE (obj # NIL) & ((obj.mode # Var) OR ~obj.used OR ~DevCPC486.ContainsIPtrs(obj.typ)) DO
obj := obj.link
END;
IF obj = NIL THEN
obj := proc.scope.scope;
WHILE (obj # NIL) & ~DevCPC486.ContainsIPtrs(obj.typ) DO obj := obj.link END;
IF obj = NIL THEN RETURN END
END;
DevCPL486.MakeReg(ax, AX, Int32); DevCPL486.MakeReg(si, SI, Int32);
DevCPL486.MakeReg(dx, DX, Int32); DevCPL486.MakeReg(di, DI, Int32);
IF ~(proc.typ.form IN {Real32, Real64, NoTyp}) THEN DevCPL486.GenMove(ax, si) END;
IF proc.typ.form = Int64 THEN DevCPL486.GenMove(dx, di) END;
x.mode := Ind; x.reg := BP; x.scale := 0; x.form := Pointer;
obj := proc.link;
WHILE obj # NIL DO
IF (obj.mode = Var) & obj.used THEN (* value parameters *)
x.offset := obj.adr;
HandleIPtrs(obj.typ, x, x, FALSE, TRUE, FALSE)
END;
obj := obj.link
END;
obj := proc.scope.scope;
WHILE obj # NIL DO (* local variables *)
IF obj.used THEN
x.offset := obj.adr;
HandleIPtrs(obj.typ, x, x, FALSE, TRUE, FALSE);
END;
obj := obj.link
END;
IF ~(proc.typ.form IN {Real32, Real64, NoTyp}) THEN DevCPL486.GenMove(si, ax) END;
IF proc.typ.form = Int64 THEN DevCPL486.GenMove(di, dx) END
END ReleaseIPVars;
PROCEDURE CompareIntTypes (
typ: DevCPT.Struct; VAR id: DevCPL486.Item; VAR exit: DevCPL486.Label; VAR num: INTEGER
);
VAR x, y: DevCPL486.Item; local: DevCPL486.Label;
BEGIN
local := DevCPL486.NewLbl;
typ := typ.BaseTyp; num := 0;
WHILE (typ # NIL) & (typ # DevCPT.undftyp) DO
IF (typ.sysflag = interface) & (typ.ext # NIL) THEN
IF num > 0 THEN DevCPC486.JumpT(x, local) END;
DevCPC486.GuidFromString(typ.ext, y);
x := id; DevCPC486.GetAdr(x, wreg - {SI}, {mem});
x := y; DevCPC486.GetAdr(x, wreg - {DI}, {});
x := id; DevCPC486.CmpString(x, y, eql, FALSE);
INC(num)
END;
typ := typ.BaseTyp
END;
IF num > 0 THEN DevCPC486.JumpF(x, exit) END;
IF num > 1 THEN DevCPL486.SetLabel(local) END
END CompareIntTypes;
PROCEDURE InstallQueryInterface (typ: DevCPT.Struct; proc: DevCPT.Object);
VAR this, id, int, unk, c: DevCPL486.Item; nil, end: DevCPL486.Label; num: INTEGER;
BEGIN
nil := DevCPL486.NewLbl; end := DevCPL486.NewLbl;
this.mode := Ind; this.reg := BP; this.offset := 8; this.scale := 0; this.form := Pointer; this.typ := DevCPT.anyptrtyp;
id.mode := DInd; id.reg := BP; id.offset := 12; id.scale := 0; id.form := Pointer;
int.mode := DInd; int.reg := BP; int.offset := 16; int.scale := 0; int.form := Pointer;
DevCPC486.GetAdr(int, {}, {AX, CX, SI, DI, mem}); int.mode := Ind; int.offset := 0;
DevCPL486.MakeConst(c, 0, Pointer); DevCPC486.Assign(int, c);
unk.mode := Ind; unk.reg := BP; unk.offset := 8; unk.scale := 0; unk.form := Pointer; unk.typ := DevCPT.punktyp;
DevCPC486.Load(unk, {}, {});
unk.mode := Ind; unk.offset := 8;
DevCPC486.Load(unk, {}, {});
DevCPL486.GenComp(c, unk);
DevCPL486.GenJump(4, nil, TRUE);
DevCPL486.MakeReg(c, int.reg, Pointer);
DevCPL486.GenPush(c);
c.mode := Ind; c.reg := BP; c.offset := 12; c.scale := 0; c.form := Pointer;
DevCPL486.GenPush(c);
DevCPL486.GenPush(unk);
c.mode := Ind; c.reg := unk.reg; c.offset := 0; c.scale := 0; c.form := Pointer;
DevCPL486.GenMove(c, unk);
unk.mode := Ind; unk.offset := 0; unk.scale := 0; unk.form := Pointer;
DevCPL486.GenCall(unk);
DevCPC486.Free(unk);
DevCPL486.GenJump(-1, end, FALSE);
DevCPL486.SetLabel(nil);
DevCPL486.MakeConst(c, 80004002H, Int32); (* E_NOINTERFACE *)
DevCPC486.Result(proc, c);
CompareIntTypes(typ, id, end, num);
IF num > 0 THEN
DevCPC486.Load(this, {}, {});
DevCPC486.Assign(int, this);
DevCPC486.IPAddRef(this, 0, FALSE);
DevCPL486.MakeConst(c, 0, Int32); (* S_OK *)
DevCPC486.Result(proc, c);
END;
DevCPL486.SetLabel(end)
END InstallQueryInterface;
(* -------------------- *)
PROCEDURE ActualPar (n: DevCPT.Node; fp: DevCPT.Object; rec: BOOLEAN; VAR tag: DevCPL486.Item);
VAR ap: DevCPL486.Item; x: DevCPT.Node; niltest: BOOLEAN;
BEGIN
IF n # NIL THEN
ActualPar(n.link, fp.link, FALSE, ap);
niltest := FALSE;
IF fp.mode = VarPar THEN
IF (n.class = Ndop) & ((n.subcl = thisarrfn) OR (n.subcl = thisrecfn)) THEN
expr(n.right, ap, {}, {}); DevCPC486.Push(ap); (* push type/length *)
expr(n.left, ap, {}, {}); DevCPC486.Push(ap); (* push adr *)
RETURN
ELSIF (fp.vis = outPar) & DevCPC486.ContainsIPtrs(fp.typ) & (ap.typ # DevCPT.niltyp) THEN
IPFree(n, ap)
ELSE
x := n;
WHILE (x.class = Nfield) OR (x.class = Nindex) DO x := x.left END;
niltest := x.class = Nderef; (* explicit nil test needed *)
AdrExpr(n, ap, {}, {})
END
ELSIF (n.class = Nmop) & (n.subcl = conv) THEN
IF n.typ.form IN {String8, String16} THEN expr(n, ap, {}, {}); DevCPM.err(265)
ELSIF (DevCPT.Includes(n.typ.form, n.left.typ.form) OR DevCPT.Includes(n.typ.form, fp.typ.form))
& (n.typ.form # Set) & (fp.typ # DevCPT.bytetyp) THEN expr(n.left, ap, {}, {high});
ELSE expr(n, ap, {}, {high});
END
ELSE expr(n, ap, {}, {high});
IF CountedPtr(n) THEN DevCPM.err(270) END
END;
DevCPC486.Param(fp, rec, niltest, ap, tag)
END
END ActualPar;
PROCEDURE Call (n: DevCPT.Node; VAR x: DevCPL486.Item);
CONST
ccall16 = -12;
VAR tag: DevCPL486.Item; proc: DevCPT.Object; m: BYTE;
p: DevCPT.Object; val :INTEGER; c16: BOOLEAN;
BEGIN
c16 := FALSE; val := 0;
IF n.left.class = Nproc THEN
proc := n.left.obj; m := proc.mode;
IF proc.sysflag = ccall16 THEN
val:=DevCPC486.CCallParSize(proc,NIL);
c16:=TRUE
END;
ELSE
proc := NIL; m := 0;
IF n.left.typ.sysflag = ccall16 THEN
val:=DevCPC486.CCallParSize(NIL,n.left.typ);
c16:=TRUE
END
END;
IF (m = CProc) & (n.right # NIL) THEN
ActualPar(n.right.link, n.obj.link, FALSE, tag);
expr(n.right, tag, wreg - {AX}, {}); (* tag = first param *)
ELSE
IF proc # NIL THEN DevCPC486.PrepCall(proc) END;
IF c16 THEN DevCPC486.PreCcall16(val) END;
ActualPar(n.right, n.obj, (m = TProc) & (n.left.subcl = 0), tag);
END;
IF proc # NIL THEN design(n.left, x, {}, {}) ELSE expr(n.left, x, {}, {}) END;
DevCPC486.Call(x, tag)
END Call;
PROCEDURE Mem (n: DevCPT.Node; VAR x: DevCPL486.Item; typ: DevCPT.Struct; hint, stop: SET);
VAR offset: INTEGER;
BEGIN
IF (n.class = Ndop) & (n.subcl IN {plus, minus}) & (n.right.class = Nconst) THEN
expr(n.left, x, hint, stop + {mem}); offset := n.right.conval.intval;
IF n.subcl = minus THEN offset := -offset END
ELSE
expr(n, x, hint, stop + {mem}); offset := 0
END;
DevCPC486.Mem(x, offset, typ)
END Mem;
PROCEDURE^ CompStat (n: DevCPT.Node);
PROCEDURE^ CompRelease (n: DevCPT.Node; VAR res: DevCPL486.Item);
PROCEDURE condition (n: DevCPT.Node; VAR x: DevCPL486.Item; VAR false, true: DevCPL486.Label);
VAR local: DevCPL486.Label; y: DevCPL486.Item; ux: SET; sx, num: INTEGER; f: BYTE;
BEGIN
IF n.class = Nmop THEN
CASE n.subcl OF
not: condition(n.left, x, true, false); DevCPC486.Not(x)
| is: IF n.left.typ.form = Pointer THEN expr(n.left, x, {}, {mem})
ELSE design(n.left, x, {}, {})
END;
DevCPC486.TypTest(x, n.obj.typ, FALSE, FALSE)
| odd: expr(n.left, x, {}, {}); DevCPC486.Odd(x)
| cc: expr(n.left, x, {}, {}); x.mode := Cond; x.form := Bool
| val: DevCPM.err(220)
END
ELSIF n.class = Ndop THEN
CASE n.subcl OF
and: local := DevCPL486.NewLbl; condition(n.left, y, false, local);
DevCPC486.JumpF(y, false);
IF local # DevCPL486.NewLbl THEN DevCPL486.SetLabel(local) END;
condition(n.right, x, false, true)
| or: local := DevCPL486.NewLbl; condition(n.left, y, local, true);
DevCPC486.JumpT(y, true);
IF local # DevCPL486.NewLbl THEN DevCPL486.SetLabel(local) END;
condition(n.right, x, false, true)
| eql..geq:
f := n.left.typ.form;
IF f = Int64 THEN DevCPM.err(260)
ELSIF f IN {String8, String16, Comp} THEN
IF (n.left.class = Nmop) & (n.left.subcl = conv) THEN (* converted must be source *)
StringOp(n.right, n.left, x, y, FALSE); DevCPC486.CmpString(x, y, n.subcl, TRUE)
ELSE
StringOp(n.left, n.right, x, y, FALSE); DevCPC486.CmpString(x, y, n.subcl, FALSE)
END
ELSIF f IN {Real32, Real64} THEN FloatDOp(n, x)
ELSE
IF CountedPtr(n.left) OR CountedPtr(n.right) THEN DevCPM.err(270) END;
DualExp(n.left, n.right, x, y, {}, {}, {stk}, {stk});
IF (x.mode = Reg) OR (y.mode = Con) THEN DevCPC486.IntDOp(x, y, n.subcl, FALSE)
ELSIF (y.mode = Reg) OR (x.mode = Con) THEN DevCPC486.IntDOp(y, x, n.subcl, TRUE); x := y
ELSE DevCPC486.Load(x, {}, {}); DevCPC486.IntDOp(x, y, n.subcl, FALSE)
END
END
| in: DualExp(n.left, n.right, x, y, {}, {}, {short, mem, stk}, {con, stk});
DevCPC486.In(x, y)
| bit: Check(n.left, ux, sx);
expr(n.right, x, {}, ux + {short});
Mem(n.left, y, DevCPT.notyp, {}, {});
DevCPC486.Load(x, {}, {short});
DevCPC486.In(x, y)
| queryfn:
AdrExpr(n.right, x, {}, {CX, SI, DI});
CompareIntTypes(n.left.typ, x, false, num);
IF num > 0 THEN
Check(n.right.link, ux, sx); IPAssign(n.right.link, n.left, x, y, ux); DevCPC486.Assign(x, y);
x.offset := 1 (* true *)
ELSE x.offset := 0 (* false *)
END;
x.mode := Con; DevCPC486.MakeCond(x)
END
ELSIF n.class = Ncomp THEN
CompStat(n.left); condition(n.right, x, false, true); CompRelease(n.left, x);
IF x.mode = Stk THEN DevCPL486.GenCode(9DH); (* pop flags *) x.mode := Cond END
ELSE expr(n, x, {}, {}); DevCPC486.MakeCond(x) (* const, var, or call *)
END
END condition;
PROCEDURE expr(n: DevCPT.Node; VAR x: DevCPL486.Item; hint, stop: SET);
VAR y, z: DevCPL486.Item; f, g: BYTE; cval: DevCPT.Const; false, true: DevCPL486.Label;
uy: SET; sy: INTEGER;
BEGIN
f := n.typ.form;
IF (f = Bool) & (n.class IN {Ndop, Nmop}) THEN
false := DevCPL486.NewLbl; true := DevCPL486.NewLbl;
condition(n, y, false, true);
DevCPC486.LoadCond(x, y, false, true, hint, stop + {mem})
ELSE
CASE n.class OF
Nconst:
IF n.obj = NIL THEN cval := n.conval ELSE cval := n.obj.conval END;
CASE f OF
Byte..Int32, NilTyp, Pointer, Char16: DevCPL486.MakeConst(x, cval.intval, f)
| Int64:
DevCPL486.MakeConst(x, cval.intval, f);
DevCPE.GetLongWords(cval, x.scale, x.offset)
| Set: DevCPL486.MakeConst(x, SYSTEM.VAL(INTEGER, cval.setval), Set)
| String8, String16, Real32, Real64: DevCPL486.AllocConst(x, cval, f)
| Comp:
ASSERT(n.typ = DevCPT.guidtyp);
IF n.conval # NIL THEN DevCPC486.GuidFromString(n.conval.ext, x)
ELSE DevCPC486.GuidFromString(n.obj.typ.ext, x)
END
END
| Nupto: (* n.typ = DevCPT.settyp *)
Check(n.right, uy, sy);
expr(n.left, x, {}, wreg - {CX} + {high, mem, stk});
DevCPC486.MakeSet(x, TRUE, FALSE, hint + stop + uy, {});
DevCPC486.Assert(x, {}, uy);
expr(n.right, y, {}, wreg - {CX} + {high, mem, stk});
DevCPC486.MakeSet(y, TRUE, TRUE, hint + stop, {});
DevCPC486.Load(x, hint + stop, {});
IF x.mode = Con THEN DevCPC486.IntDOp(y, x, msk, TRUE); x := y
ELSE DevCPC486.IntDOp(x, y, msk, FALSE)
END
| Nmop:
CASE n.subcl OF
| bit:
expr(n.left, x, {}, wreg - {CX} + {high, mem, stk});
DevCPC486.MakeSet(x, FALSE, FALSE, hint + stop, {})
| conv:
IF f IN {String8, String16} THEN
expr(n.left, x, hint, stop);
IF f = String8 THEN x.form := VString16to8 END (* SHORT *)
ELSE
IF n.left.class = Nconst THEN (* largeint -> longreal *)
ASSERT((n.left.typ.form = Int64) & (f = Real64));
DevCPL486.AllocConst(x, n.left.conval, n.left.typ.form);
ELSE
expr(n.left, x, hint + stop, {high});
END;
DevCPC486.Convert(x, f, -1, hint + stop, {}) (* ??? *)
END
| val:
expr(n.left, x, hint + stop, {high, con}); DevCPC486.Convert(x, f, n.typ.size, hint, stop) (* ??? *)
| adr:
IF n.left.class = Ntype THEN
x.mode := Con; x.offset := 0; x.obj := n.left.obj; x.form := Int32; x.typ := n.left.typ;
ELSE
AdrExpr(n.left, x, hint + stop, {});
END;
DevCPC486.GetAdr(x, hint + stop, {})
| typfn:
IF n.left.class = Ntype THEN
x.mode := Con; x.offset := 0; x.obj := n.left.obj; x.form := Int32; x.typ := n.left.typ;
IF x.obj.typ.untagged THEN DevCPM.err(111) END
ELSE
expr(n.left, x, hint + stop, {});
DevCPC486.Tag(x, y); DevCPC486.Free(x); x := y
END;
DevCPC486.Load(x, hint + stop, {})
| minus, abs, cap:
expr(n.left, x, hint + stop, {mem, stk});
IF f = Int64 THEN DevCPM.err(260)
ELSIF f IN realSet THEN DevCPC486.FloatMOp(x, n.subcl)
ELSE DevCPC486.IntMOp(x, n.subcl)
END
END
| Ndop:
IF (f IN realSet) & (n.subcl # lsh) & (n.subcl # rot) THEN
IF (n.subcl = ash) & (n.right.class = Nconst) & (n.right.conval.realval >= 0) THEN
expr(n.left, x, {}, {mem, stk});
cval := n.right.conval; sy := SHORT(ENTIER(cval.realval)); cval.realval := 1;
WHILE sy > 0 DO cval.realval := cval.realval * 2; DEC(sy) END;
DevCPL486.AllocConst(y, cval, Real32);
DevCPC486.FloatDOp(x, y, times, FALSE)
ELSE FloatDOp(n, x)
END
ELSIF (f = Int64) OR (n.typ = DevCPT.intrealtyp) THEN DevCPM.err(260); expr(n.left, x, {}, {})
ELSE
CASE n.subcl OF
times:
IF f = Int8 THEN
DualExp(n.left, n.right, x, y, {}, {}, wreg - {AX} + {high, mem, stk, con}, {AX, con, stk});
DevCPC486.IntDOp(x, y, times, FALSE)
ELSE IntDOp(n, x, hint + stop)
END
| div, mod:
DualExp(n.left, n.right, x, y, {}, {}, wreg - {AX} + {high, mem, stk, con}, {AX, DX, mem, stk});
DevCPC486.DivMod(x, y, n.subcl = mod)
| plus:
IF n.typ.form IN {String8, String16} THEN DevCPM.err(265); expr(n.left, x, {}, {})
ELSE IntDOp(n, x, hint + stop)
END
| slash, minus, msk, min, max:
IntDOp(n, x, hint + stop)
| ash, lsh, rot:
uy := {}; IF n.right.class # Nconst THEN uy := {CX} END;
DualExp(n^.right, n^.left, y, x, {}, hint + stop, wreg - {CX} + {high, mem, stk}, uy + {con, mem, stk});
DevCPC486.Shift(x, y, n^.subcl)
| len:
IF n.left.typ.form IN {String8, String16} THEN
expr(n.left, x, wreg - {DI} , {}); DevCPC486.GetAdr(x, {}, wreg - {DI} + {con});
DevCPC486.StrLen(x, n.left.typ, FALSE)
ELSE
design(n.left, x, hint + stop, {}); expr(n.right, y, {}, {}); DevCPC486.Len(x, y)
END
END
END
| Ncall:
Call(n, x)
| Ncomp:
CompStat(n.left); expr(n.right, x, hint, stop); CompRelease(n.left, x);
IF x.mode = Stk THEN DevCPC486.Pop(x, x.form, hint, stop) END
ELSE
design(n, x, hint + stop, stop * {loaded}); DevCPC486.Prepare(x, hint + stop, {}) (* ??? *)
END
END;
x.typ := n.typ;
DevCPC486.Assert(x, hint, stop)
END expr;
PROCEDURE AddCopy (n: DevCPT.Node; VAR dest, dadr, len: DevCPL486.Item; last: BOOLEAN);
VAR adr, src: DevCPL486.Item; u: SET; s: INTEGER;
BEGIN
Check(n, u, s);
DevCPC486.Assert(dadr, wreg - {DI}, u + {SI, CX});
IF len.mode # Con THEN DevCPC486.Assert(len, wreg - {CX}, u + {SI, DI}) END;
expr(n, src, wreg - {SI}, {});
adr := src; DevCPC486.GetAdr(adr, {}, wreg - {SI} + {con});
IF len.mode # Con THEN DevCPC486.Load(len, {}, wreg - {CX} + {con}) END;
DevCPC486.Load(dadr, {}, wreg - {DI} + {con});
DevCPC486.AddCopy(dest, src, last)
END AddCopy;
PROCEDURE StringCopy (left, right: DevCPT.Node);
VAR x, y, ax, ay, len: DevCPL486.Item;
BEGIN
IF IsAllocDynArr(left) THEN expr(left, x, wreg - {CX}, {DI}) (* keep len descriptor *)
ELSE expr(left, x, wreg - {DI}, {})
END;
ax := x; DevCPC486.GetAdr(ax, {}, wreg - {DI});
DevCPC486.Free(x); DevCPC486.ArrayLen(x, len, wreg - {CX}, {});
WHILE right.class = Ndop DO
ASSERT(right.subcl = plus);
AddCopy(right.left, x, ax, len, FALSE);
right := right.right
END;
AddCopy(right, x, ax, len, TRUE);
DevCPC486.Free(len)
END StringCopy;
PROCEDURE Checkpc;
BEGIN
DevCPE.OutSourceRef(DevCPM.errpos)
END Checkpc;
PROCEDURE^ stat (n: DevCPT.Node; VAR end: DevCPL486.Label);
PROCEDURE CondStat (if, last: DevCPT.Node; VAR hint: INTEGER; VAR else, end: DevCPL486.Label);
VAR local: DevCPL486.Label; x: DevCPL486.Item; cond, lcond: DevCPT.Node;
BEGIN
local := DevCPL486.NewLbl;
DevCPM.errpos := if.conval.intval; Checkpc; cond := if.left;
IF (last # NIL) & (cond.class = Ndop) & (cond.subcl >= eql) & (cond.subcl <= geq)
& (last.class = Ndop) & (last.subcl >= eql) & (last.subcl <= geq)
& SameExp(cond.left, last.left) & SameExp(cond.right, last.right) THEN (* reuse comparison *)
DevCPC486.setCC(x, cond.subcl, ODD(hint), hint >= 2)
ELSIF (last # NIL) & (cond.class = Nmop) & (cond.subcl = is) & (last.class = Nmop) & (last.subcl = is)
& SameExp(cond.left, last.left) THEN
DevCPC486.ShortTypTest(x, cond.obj.typ) (* !!! *)
ELSE condition(cond, x, else, local)
END;
hint := x.reg;
DevCPC486.JumpF(x, else);
IF local # DevCPL486.NewLbl THEN DevCPL486.SetLabel(local) END;
stat(if.right, end);
END CondStat;
PROCEDURE IfStat (n: DevCPT.Node; withtrap: BOOLEAN; VAR end: DevCPL486.Label);
VAR else: DevCPL486.Label; if, last: DevCPT.Node; hint: INTEGER;
BEGIN (* n.class = Nifelse *)
if := n.left; last := NIL;
WHILE (if # NIL) & ((if.link # NIL) OR (n.right # NIL) OR withtrap) DO
else := DevCPL486.NewLbl;
CondStat(if, last, hint, else, end);
IF sequential THEN DevCPC486.Jump(end) END;
DevCPL486.SetLabel(else); last := if.left; if := if.link
END;
IF n.right # NIL THEN stat(n.right, end)
ELSIF withtrap THEN DevCPM.errpos := n.conval.intval; Checkpc; DevCPC486.Trap(withTrap); sequential := FALSE
ELSE CondStat(if, last, hint, end, end)
END
END IfStat;
PROCEDURE CasePart (n: DevCPT.Node; VAR x: DevCPL486.Item; VAR else: DevCPL486.Label; last: BOOLEAN);
VAR this, higher: DevCPL486.Label; m: DevCPT.Node; low, high: INTEGER;
BEGIN
IF n # NIL THEN
this := SHORT(ENTIER(n.conval.realval));
IF useTree IN n.conval.setval THEN
IF n.left # NIL THEN
IF n.right # NIL THEN
higher := DevCPL486.NewLbl;
DevCPC486.CaseJump(x, n.conval.intval, n.conval.intval2, this, higher, TRUE, FALSE);
CasePart(n.left, x, else, FALSE);
DevCPL486.SetLabel(higher);
CasePart(n.right, x, else, last)
ELSE
DevCPC486.CaseJump(x, n.conval.intval, n.conval.intval2, this, else, FALSE, FALSE);
CasePart(n.left, x, else, last);
END
ELSE
DevCPC486.CaseJump(x, n.conval.intval, n.conval.intval2, this, else, FALSE, TRUE);
IF n.right # NIL THEN CasePart(n.right, x, else, last)
ELSIF ~last THEN DevCPC486.Jump(else)
END
END
ELSE
IF useTable IN n.conval.setval THEN
m := n; WHILE m.left # NIL DO m := m.left END; low := m.conval.intval;
m := n; WHILE m.right # NIL DO m := m.right END; high := m.conval.intval2;
DevCPC486.CaseTableJump(x, low, high, else);
actual := low; last := TRUE
END;
CasePart(n.left, x, else, FALSE);
WHILE actual < n.conval.intval DO
DevCPL486.GenCaseEntry(else, FALSE); INC(actual)
END;
WHILE actual < n.conval.intval2 DO
DevCPL486.GenCaseEntry(this, FALSE); INC(actual)
END;
DevCPL486.GenCaseEntry(this, last & (n.right = NIL)); INC(actual);
CasePart(n.right, x, else, last)
END;
n.conval.realval := this
END
END CasePart;
PROCEDURE CaseStat (n: DevCPT.Node; VAR end: DevCPL486.Label);
VAR x: DevCPL486.Item; case, lab: DevCPT.Node; low, high, tab: INTEGER; else, this: DevCPL486.Label;
BEGIN
expr(n.left, x, {}, {mem, con, short, float, stk}); else := DevCPL486.NewLbl;
IF (n.right.right # NIL) & (n.right.right.class = Ngoto) THEN (* jump to goto optimization *)
CasePart(n.right.link, x, else, FALSE); DevCPC486.Free(x);
n.right.right.right.conval.intval2 := else; sequential := FALSE
ELSE
CasePart(n.right.link, x, else, TRUE); DevCPC486.Free(x);
DevCPL486.SetLabel(else);
IF n.right.conval.setval # {} THEN stat(n.right.right, end)
ELSE DevCPC486.Trap(caseTrap); sequential := FALSE
END
END;
case := n.right.left;
WHILE case # NIL DO (* case.class = Ncasedo *)
IF sequential THEN DevCPC486.Jump(end) END;
lab := case.left;
IF (case.right # NIL) & (case.right.class = Ngoto) THEN (* jump to goto optimization *)
case.right.right.conval.intval2 := SHORT(ENTIER(lab.conval.realval));
ASSERT(lab.link = NIL); sequential := FALSE
ELSE
WHILE lab # NIL DO
this := SHORT(ENTIER(lab.conval.realval)); DevCPL486.SetLabel(this); lab := lab.link
END;
stat(case.right, end)
END;
case := case.link
END
END CaseStat;
PROCEDURE Dim(n: DevCPT.Node; VAR x, nofel: DevCPL486.Item; VAR fact: INTEGER; dimtyp: DevCPT.Struct);
VAR len: DevCPL486.Item; u: SET; s: INTEGER;
BEGIN
Check(n, u, s);
IF (nofel.mode = Reg) & (nofel.reg IN u) THEN DevCPC486.Push(nofel) END;
expr(n, len, {}, {mem, short});
IF nofel.mode = Stk THEN DevCPC486.Pop(nofel, Int32, {}, {}) END;
IF len.mode = Stk THEN DevCPC486.Pop(len, Int32, {}, {}) END;
DevCPC486.MulDim(len, nofel, fact, dimtyp);
IF n.link # NIL THEN
Dim(n.link, x, nofel, fact, dimtyp.BaseTyp);
ELSE
DevCPC486.New(x, nofel, fact)
END;
DevCPC486.SetDim(x, len, dimtyp)
END Dim;
PROCEDURE CompStat (n: DevCPT.Node);
VAR x, y, sp, old, len: DevCPL486.Item; typ: DevCPT.Struct;
BEGIN
Checkpc;
WHILE (n # NIL) & DevCPM.noerr DO
ASSERT(n.class = Nassign);
IF n.subcl = assign THEN
IF n.right.typ.form IN {String8, String16} THEN
StringCopy(n.left, n.right)
ELSE
IF (n.left.typ.sysflag = interface) & ~CountedPtr(n.right) THEN
IPAssign(NIL, n.right, x, y, {}); (* no Release *)
ELSE expr(n.right, y, {}, {})
END;
expr(n.left, x, {}, {});
DevCPC486.Assign(x, y)
END
ELSE ASSERT(n.subcl = newfn);
typ := n.left.typ.BaseTyp;
ASSERT(typ.comp = DynArr);
ASSERT(n.right.link = NIL);
expr(n.right, y, {}, wreg - {CX} + {mem, stk});
DevCPL486.MakeReg(sp, SP, Int32);
DevCPC486.CopyReg(sp, old, {}, {CX});
DevCPC486.CopyReg(y, len, {}, {CX});
IF typ.BaseTyp.form = Char16 THEN
DevCPL486.MakeConst(x, 2, Int32); DevCPL486.GenMul(x, y, FALSE)
END;
DevCPC486.StackAlloc;
DevCPC486.Free(y);
expr(n.left, x, {}, {}); DevCPC486.Assign(x, sp);
DevCPC486.Push(len);
DevCPC486.Push(old);
typ.sysflag := stackArray
END;
n := n.link
END
END CompStat;
PROCEDURE CompRelease (n: DevCPT.Node; VAR res: DevCPL486.Item);
VAR x, y, sp: DevCPL486.Item;
BEGIN
IF n.link # NIL THEN CompRelease(n.link, res) END;
ASSERT(n.class = Nassign);
IF n.subcl = assign THEN
IF (n.left.typ.form = Pointer) & (n.left.typ.sysflag = interface) THEN
IF res.mode = Cond THEN
DevCPL486.GenCode(9CH); (* push flags *)
res.mode := Stk
ELSIF res.mode = Reg THEN
IF res.form < Int16 THEN DevCPC486.Push(res)
ELSE DevCPC486.Assert(res, {}, {AX, CX, DX})
END
END;
expr(n.left, x, wreg - {DI}, {loaded});
DevCPC486.IPRelease(x, 0, TRUE, TRUE);
n.left.obj.used := FALSE
END
ELSE ASSERT(n.subcl = newfn);
DevCPL486.MakeReg(sp, SP, Int32); DevCPL486.GenPop(sp);
DevCPL486.MakeConst(y, 0, Pointer);
expr(n.left, x, {}, {}); DevCPC486.Assign(x, y)
END
END CompRelease;
PROCEDURE Assign(n: DevCPT.Node; ux: SET);
VAR r: DevCPT.Node; f: BYTE; false, true: DevCPL486.Label; x, y, z: DevCPL486.Item; uf, uy: SET;
BEGIN
r := n.right; f := r.typ.form; uf := {};
IF (r.class IN {Nmop, Ndop}) THEN
IF (r.subcl = conv) & (f # Set) &
(*
(DevCPT.Includes(f, r.left.typ.form) OR DevCPT.Includes(f, n.left.typ.form)) THEN r := r.left;
IF ~(f IN realSet) & (r.typ.form IN realSet) & (r.typ # DevCPT.intrealtyp) THEN uf := {AX} END (* entier *)
*)
(DevCPT.Includes(f, r.left.typ.form) OR DevCPT.Includes(f, n.left.typ.form)) &
((f IN realSet) OR ~(r.left.typ.form IN realSet)) THEN r := r.left
ELSIF (f IN {Char8..Int32, Set, Char16, String8, String16}) & SameExp(n.left, r.left) THEN
IF r.class = Ndop THEN
IF (r.subcl IN {slash, plus, minus, msk}) OR (r.subcl = times) & (f = Set) THEN
expr(r.right, y, {}, ux); expr(n.left, x, {}, {});
DevCPC486.Load(y, {}, {}); DevCPC486.IntDOp(x, y, r.subcl, FALSE);
RETURN
ELSIF r.subcl IN {ash, lsh, rot} THEN
expr(r.right, y, wreg - {CX} + {high, mem}, ux); expr(n.left, x, {}, {});
DevCPC486.Load(y, {}, wreg - {CX} + {high}); DevCPC486.Shift(x, y, r.subcl);
RETURN
END
ELSE
IF r.subcl IN {minus, abs, cap} THEN
expr(n.left, x, {}, {}); DevCPC486.IntMOp(x, r.subcl); RETURN
END
END
ELSIF f = Bool THEN
IF (r.subcl = not) & SameExp(n.left, r.left) THEN
expr(n.left, x, {}, {}); DevCPC486.IntMOp(x, not); RETURN
END
END
END;
IF (n.left.typ.sysflag = interface) & (n.left.typ.form = Pointer) THEN IPAssign(n.left, r, x, y, ux)
ELSE expr(r, y, {high}, ux); expr(n.left, x, {}, uf + {loaded}); (* high ??? *)
END;
DevCPC486.Assign(x, y)
END Assign;
PROCEDURE stat (n: DevCPT.Node; VAR end: DevCPL486.Label);
VAR x, y, nofel: DevCPL486.Item; local, next, loop, prevExit: DevCPL486.Label; fact, sx, sz: INTEGER; ux, uz: SET;
BEGIN
sequential := TRUE; INC(nesting);
WHILE (n # NIL) & DevCPM.noerr DO
IF n.link = NIL THEN next := end ELSE next := DevCPL486.NewLbl END;
DevCPM.errpos := n.conval.intval; DevCPL486.BegStat;
CASE n.class OF
| Ninittd:
(* done at load-time *)
| Nassign:
Checkpc;
Check(n.left, ux, sx);
CASE n.subcl OF
assign:
IF n.left.typ.form = Comp THEN
IF (n.right.class = Ndop) & (n.right.typ.form IN {String8, String16}) THEN
StringCopy(n.left, n.right)
ELSE
StringOp(n.left, n.right, x, y, TRUE);
IF DevCPC486.ContainsIPtrs(n.left.typ) THEN IPStructAssign(n.left.typ) END;
DevCPC486.Copy(x, y, FALSE)
END
ELSE Assign(n, ux)
END
| getfn:
Mem(n.right, y, n.left.typ, {}, ux);
expr(n.left, x, {}, {loaded});
DevCPC486.Assign(x, y)
| putfn:
expr(n.right, y, {}, ux);
Mem(n.left, x, n.right.typ, {}, {});
DevCPC486.Assign(x, y)
| incfn, decfn:
expr(n.right, y, {}, ux); expr(n.left, x, {}, {});
IF n.left.typ.form = Int64 THEN
DevCPC486.LargeInc(x, y, n.subcl = decfn)
ELSE
DevCPC486.Load(y, {}, {}); DevCPC486.IntDOp(x, y, SHORT(SHORT(plus - incfn + n.subcl)), FALSE)
END
| inclfn:
expr(n.right, y, {}, wreg - {CX} + {high, mem, stk}); DevCPC486.MakeSet(y, FALSE, FALSE, ux, {});
DevCPC486.Assert(y, {}, ux); expr(n.left, x, {}, {});
DevCPC486.Load(y, {}, {}); DevCPC486.IntDOp(x, y, plus, FALSE)
| exclfn:
expr(n.right, y, {}, wreg - {CX} + {high, mem, stk}); DevCPC486.MakeSet(y, FALSE, TRUE, ux, {});
DevCPC486.Assert(y, {}, ux); expr(n.left, x, {}, {});
DevCPC486.Load(y, {}, {}); DevCPC486.IntDOp(x, y, times, FALSE)
| getrfn:
expr(n.right, y, {}, {});
IF y.offset < 8 THEN
DevCPL486.MakeReg(y, y.offset, n.left.typ.form); (* ??? *)
expr(n.left, x, {}, {loaded}); DevCPC486.Assign(x, y)
ELSE DevCPM.err(220)
END
| putrfn:
expr(n.left, x, {}, {});
IF x.offset < 8 THEN
DevCPL486.MakeReg(x, x.offset, n.right.typ.form); (* ??? *)
expr(n.right, y, wreg - {x.reg}, {}); DevCPC486.Assign(x, y)
ELSE DevCPM.err(220)
END
| newfn:
y.typ := n.left.typ;
IF n.right # NIL THEN
IF y.typ.BaseTyp.comp = Record THEN
expr(n.right, nofel, {}, {AX, CX, DX, mem, stk});
DevCPC486.New(y, nofel, 1);
ELSE (*open array*)
nofel.mode := Con; nofel.form := Int32; fact := 1;
Dim(n.right, y, nofel, fact, y.typ.BaseTyp)
END
ELSE
DevCPL486.MakeConst(nofel, 0, Int32);
DevCPC486.New(y, nofel, 1);
END;
DevCPC486.Assert(y, {}, ux); expr(n.left, x, {}, {loaded}); DevCPC486.Assign(x, y)
| sysnewfn:
expr(n.right, y, {}, {mem, short}); DevCPC486.SysNew(y);
DevCPC486.Assert(y, {}, ux); expr(n.left, x, {}, {}); DevCPC486.Assign(x, y)
| copyfn:
StringOp(n.left, n.right, x, y, TRUE);
DevCPC486.Copy(x, y, TRUE)
| movefn:
Check(n.right.link, uz, sz);
expr(n.right, y, {}, wreg - {SI} + {short} + ux + uz);
expr(n.left, x, {}, wreg - {DI} + {short} + uz);
expr(n.right.link, nofel, {}, wreg - {CX} + {mem, stk, short});
DevCPC486.Load(x, {}, wreg - {DI} + {con});
DevCPC486.Load(y, {}, wreg - {SI} + {con});
DevCPC486.SysMove(nofel)
END;
sequential := TRUE
| Ncall:
Checkpc;
Call(n, x); sequential := TRUE
| Nifelse:
IF (n.subcl # assertfn) OR assert THEN IfStat(n, FALSE, next) END
| Ncase:
Checkpc;
CaseStat(n, next)
| Nwhile:
local := DevCPL486.NewLbl;
IF n.right # NIL THEN DevCPC486.Jump(local) END;
loop := DevCPL486.NewLbl; DevCPL486.SetLabel(loop);
stat(n.right, local); DevCPL486.SetLabel(local);
DevCPM.errpos := n.conval.intval; Checkpc;
condition(n.left, x, next, loop); DevCPC486.JumpT(x, loop); sequential := TRUE
| Nrepeat:
loop := DevCPL486.NewLbl; DevCPL486.SetLabel(loop);
local := DevCPL486.NewLbl; stat(n.left, local); DevCPL486.SetLabel(local);
DevCPM.errpos := n.conval.intval; Checkpc;
condition(n.right, x, loop, next); DevCPC486.JumpF(x, loop); sequential := TRUE
| Nloop:
prevExit := Exit; Exit := next;
loop := DevCPL486.NewLbl; DevCPL486.SetLabel(loop); stat(n.left, loop);
IF sequential THEN DevCPC486.Jump(loop) END;
next := Exit; Exit := prevExit; sequential := FALSE
| Nexit:
Checkpc;
DevCPC486.Jump(Exit); sequential := FALSE
| Nreturn:
IF n.left # NIL THEN
Checkpc;
IF (n.obj.typ.sysflag = interface) & (n.obj.typ.form = Pointer)
& (n.left.class # Nconst) & ~CountedPtr(n.left) THEN IPAssign(NIL, n.left, y, x, {})
ELSE expr(n.left, x, wreg - {AX}, {})
END;
DevCPC486.Result(n.obj, x)
END;
IF (nesting > 1) OR (n.link # NIL) THEN DevCPC486.Jump(Return) END;
sequential := FALSE
| Nwith:
IF (n.left # NIL) OR (n.right # NIL) OR (n.subcl = 0) THEN IfStat(n, n.subcl = 0, next) END
| Ntrap:
Checkpc;
DevCPC486.Trap(n.right.conval.intval); sequential := TRUE
| Ncomp:
CompStat(n.left); stat(n.right, next); x.mode := 0; CompRelease(n.left, x)
| Ndrop:
Checkpc;
expr(n.left, x, {}, {}); DevCPC486.Free(x)
| Ngoto:
IF n.left # NIL THEN
Checkpc;
condition(n.left, x, next, n.right.conval.intval2);
DevCPC486.JumpT(x, n.right.conval.intval2)
ELSE
DevCPC486.Jump(n.right.conval.intval2);
sequential := FALSE
END
| Njsr:
DevCPL486.GenJump(-3, n.right.conval.intval2, FALSE) (* call n.right *)
| Nret:
DevCPL486.GenReturn(0); sequential := FALSE (* ret 0 *)
| Nlabel:
DevCPL486.SetLabel(n.conval.intval2)
END;
DevCPC486.CheckReg; DevCPL486.EndStat; n := n.link;
IF n = NIL THEN end := next
ELSIF next # DevCPL486.NewLbl THEN DevCPL486.SetLabel(next)
END
END;
DEC(nesting)
END stat;
PROCEDURE CheckFpu (n: DevCPT.Node; VAR useFpu: BOOLEAN);
BEGIN
WHILE n # NIL DO
IF n.typ.form IN {Real32, Real64} THEN useFpu := TRUE END;
CASE n.class OF
| Ncase:
CheckFpu(n.left, useFpu); CheckFpu(n.right.left, useFpu); CheckFpu(n.right.right, useFpu)
| Ncasedo:
CheckFpu(n.right, useFpu)
| Ngoto, Ndrop, Nloop, Nreturn, Nmop, Nfield, Nderef, Nguard:
CheckFpu(n.left, useFpu)
| Nassign, Ncall, Nifelse, Nif, Nwhile, Nrepeat, Nwith, Ncomp, Ndop, Nupto, Nindex:
CheckFpu(n.left, useFpu); CheckFpu(n.right, useFpu)
| Njsr, Nret, Nlabel, Ntrap, Nexit, Ninittd, Ntype, Nproc, Nconst, Nvar, Nvarpar:
END;
n := n.link
END
END CheckFpu;
PROCEDURE procs(n: DevCPT.Node);
VAR proc, obj: DevCPT.Object; i, j: INTEGER; end: DevCPL486.Label;
ch: SHORTCHAR; name: DevCPT.Name; useFpu: BOOLEAN;
BEGIN
INC(DevCPL486.level); nesting := 0;
WHILE (n # NIL) & DevCPM.noerr DO
DevCPC486.imLevel[DevCPL486.level] := DevCPC486.imLevel[DevCPL486.level - 1]; proc := n.obj;
IF imVar IN proc.conval.setval THEN INC(DevCPC486.imLevel[DevCPL486.level]) END;
procs(n.left);
DevCPM.errpos := n.conval.intval;
useFpu := FALSE; CheckFpu(n.right, useFpu);
DevCPC486.Enter(proc, n.right = NIL, useFpu);
InitializeIPVars(proc);
end := DevCPL486.NewLbl; Return := DevCPL486.NewLbl; stat(n.right, end);
DevCPM.errpos := n.conval.intval2; Checkpc;
IF sequential OR (end # DevCPL486.NewLbl) THEN
DevCPL486.SetLabel(end);
IF (proc.typ # DevCPT.notyp) & (proc.sysflag # noframe) THEN DevCPC486.Trap(funcTrap) END
END;
DevCPL486.SetLabel(Return);
ReleaseIPVars(proc);
DevCPC486.Exit(proc, n.right = NIL);
IF proc.mode = TProc THEN
name := proc.link.typ.strobj.name^$; i := 0;
WHILE name[i] # 0X DO INC(i) END;
name[i] := "."; INC(i); j := 0; ch := proc.name[0];
WHILE (ch # 0X) & (i < LEN(name)-1) DO name[i] := ch; INC(i); INC(j); ch := proc.name[j] END ;
name[i] := 0X;
ELSE name := proc.name^$
END;
DevCPE.OutRefName(name); DevCPE.OutRefs(proc.scope.right);
n := n.link
END;
DEC(DevCPL486.level)
END procs;
PROCEDURE Module*(prog: DevCPT.Node);
VAR end: DevCPL486.Label; name: DevCPT.Name; obj, p: DevCPT.Object; n: DevCPT.Node;
aAd, rAd: INTEGER; typ: DevCPT.Struct; useFpu: BOOLEAN;
BEGIN
DevCPH.UseReals(prog, {DevCPH.longDop, DevCPH.longMop});
DevCPM.NewObj(DevCPT.SelfName);
IF DevCPM.noerr THEN
DevCPE.OutHeader; n := prog.right;
WHILE (n # NIL) & (n.class = Ninittd) DO n := n.link END;
useFpu := FALSE; CheckFpu(n, useFpu);
DevCPC486.Enter(NIL, n = NIL, useFpu);
end := DevCPL486.NewLbl; stat(n, end); DevCPL486.SetLabel(end);
DevCPM.errpos := prog.conval.intval2; Checkpc;
DevCPC486.Exit(NIL, n = NIL);
IF prog.link # NIL THEN (* close section *)
DevCPL486.SetLabel(DevCPE.closeLbl);
useFpu := FALSE; CheckFpu(prog.link, useFpu);
DevCPC486.Enter(NIL, FALSE, useFpu);
end := DevCPL486.NewLbl; stat(prog.link, end); DevCPL486.SetLabel(end);
DevCPM.errpos := SHORT(ENTIER(prog.conval.realval)); Checkpc;
DevCPC486.Exit(NIL, FALSE)
END;
name := "$$"; DevCPE.OutRefName(name); DevCPE.OutRefs(DevCPT.topScope.right);
DevCPM.errpos := prog.conval.intval;
WHILE query # NIL DO
typ := query.typ; query.typ := DevCPT.int32typ;
query.conval.intval := 20; (* parameters *)
query.conval.intval2 := -8; (* saved registers *)
DevCPC486.Enter(query, FALSE, FALSE);
InstallQueryInterface(typ, query);
DevCPC486.Exit(query, FALSE);
name := "QueryInterface"; DevCPE.OutRefName(name);
query := query.nlink
END;
procs(prog.left);
DevCPC486.InstallStackAlloc;
addRef := NIL; release := NIL; release2 := NIL;
DevCPC486.intHandler := NIL;
IF DevCPM.noerr THEN DevCPE.OutCode END;
IF ~DevCPM.noerr THEN DevCPM.DeleteObj END
END
END Module;
END DevCPV486.
| Dev/Mod/CPV486.odc |
MODULE DevDebug;
(**
project = "BlackBox 2.0, new module"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070123, bh, WriteString, ShowArray, & ShowVar changed (Unicode support)
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150326, center #33, adding platform detection for wine, Windows 7, and Windows 8
- 20150527, center #54, UnloadThis must use DevCommanders.par.text
- 20150929, center #72, speeding up the dump of large data structures by avoiding fold.Flip
- 20151106, center #84, unloading DevDebug produces a sequence of Traps
- 20160324, center #111, code cleanups
- 20161103, center #140, unwrapping import aliasses
- 20170215, center #139, localization support for error messages
- 20170623, Nikita Plynskii, remove digitspaces from loaded modules
- 20180515, center #187, fixing the type of vi in ShowArray
- 20181207, center #195, support for long identifiers in trap handlers
- 20210123, bbcp #23, per module string resources
"
issues = "
- ...
"
**)
IMPORT SYSTEM,
Kernel, Strings, Utf, Librarian, Dates, Files, Fonts, Services, Ports, Stores, Converters,
Models, Views, Controllers, Properties, Dialog, Containers, Controls,
Windows, StdDialog, StdFolds, StdLinks,
TextModels, TextMappers, TextControllers, TextViews, TextRulers, StdLog,
DevReferences, DevCommanders;
CONST
refViewSize = 9 * Ports.point;
heap = 1; source = 2; module = 3; modules = 4; (* RefView types *)
open = 1; undo = 2; update = 3; (* RefView commands *)
(* additional scanner types *)
import = 100; smodule = 101; semicolon = 102; becomes = 103; stop = 104; comEnd = 105;
TYPE
ArrayPtr = POINTER TO EXTENSIBLE RECORD
last, t, first: INTEGER; (* gc header *)
len: ARRAY 16 OF INTEGER (* dynamic array length table *)
END;
RefView = POINTER TO RECORD (Views.View)
type: SHORTINT;
command: SHORTINT;
back: RefView;
adr: INTEGER;
desc: Kernel.Type;
ptr: ArrayPtr;
name: Kernel.Utf8Name
END;
Action = POINTER TO RECORD (Services.Action)
text: TextModels.Model
END;
Cluster = POINTER TO RECORD [untagged] (* must correspond to Kernel.Cluster *)
size: INTEGER;
next: Cluster
END;
FoldContext = RECORD
prevText: TextModels.Model;
prevPos: INTEGER
END;
VAR
out: TextMappers.Formatter;
path: ARRAY 4 OF Ports.Point;
empty: Kernel.Name;
PROCEDURE NewRuler (): TextRulers.Ruler;
CONST mm = Ports.mm;
VAR r: TextRulers.Ruler;
BEGIN
r := TextRulers.dir.New(NIL);
TextRulers.SetRight(r, 140 * mm);
TextRulers.AddTab(r, 4 * mm); TextRulers.AddTab(r, 34 * mm); TextRulers.AddTab(r, 80 * mm);
RETURN r
END NewRuler;
PROCEDURE NewModRuler (): TextRulers.Ruler;
CONST mm = Ports.mm;
VAR r: TextRulers.Ruler;
BEGIN
r := TextRulers.dir.New(NIL);
TextRulers.SetRight(r, 144 * mm);
TextRulers.AddTab(r, 48 * mm); TextRulers.MakeRightTab(r);
TextRulers.AddTab(r, 64 * mm); TextRulers.MakeRightTab(r);
TextRulers.AddTab(r, 76 * mm); TextRulers.AddTab(r, 110 * mm);
RETURN r
END NewModRuler;
PROCEDURE OpenViewer (t: TextModels.Model; title: Views.Title; ruler:TextRulers.Ruler);
VAR v: TextViews.View; c: Containers.Controller;
BEGIN
Dialog.MapString(title, title);
v := TextViews.dir.New(t);
v.SetDefaults(ruler, TextViews.dir.defAttr);
c := v.ThisController();
IF c # NIL THEN
c.SetOpts(c.opts - {Containers.noFocus, Containers.noSelection} + {Containers.noCaret})
END;
Views.OpenAux(v, title)
END OpenViewer;
PROCEDURE OpenFold (OUT fc: FoldContext);
BEGIN
fc.prevText := out.rider.Base();
fc.prevPos := out.Pos();
out.ConnectTo(TextModels.CloneOf(StdLog.buf))
END OpenFold;
PROCEDURE CloseFold (IN fc: FoldContext; collapsed: BOOLEAN; IN hidden: ARRAY OF CHAR);
VAR fold: StdFolds.Fold; t: TextModels.Model; w: TextMappers.Formatter; hiddenx: ARRAY 32 OF CHAR;
BEGIN
Dialog.MapString(hidden, hiddenx);
(* avoid expensive fold.Flip operation *)
IF collapsed THEN
fold := StdFolds.dir.New(StdFolds.collapsed, "", out.rider.Base());
out.ConnectTo(fc.prevText);
out.WriteView(fold);
out.WriteString(hiddenx)
ELSE
t := TextModels.CloneOf(StdLog.buf);
w.ConnectTo(t); w.WriteString(hiddenx);
fold := StdFolds.dir.New(StdFolds.expanded, "", t);
t := out.rider.Base();
out.ConnectTo(fc.prevText);
out.WriteView(fold);
fc.prevText.Insert(out.Pos(), t, 0, t.Length());
out.SetPos(out.rider.Base().Length())
END;
fold := StdFolds.dir.New(collapsed, "", NIL);
out.WriteView(fold)
END CloseFold;
PROCEDURE WriteHex (n: INTEGER);
BEGIN
out.WriteIntForm(n, TextMappers.hexadecimal, 9, "0", TextMappers.showBase)
END WriteHex;
PROCEDURE WriteString (adr, len, base: INTEGER; zterm, unicode: BOOLEAN);
CONST beg = 0; char = 1; code = 2;
VAR ch: CHAR; sc: SHORTCHAR; val, mode: INTEGER; str: ARRAY 16 OF CHAR;
BEGIN
mode := beg;
IF base = 2 THEN SYSTEM.GET(adr, ch); val := ORD(ch) ELSE SYSTEM.GET(adr, sc); val := ORD(sc) END;
IF zterm & (val = 0) THEN out.WriteString('""')
ELSE
REPEAT
IF (val >= ORD(" ")) & (val < 7FH) OR (val > 0A0H) & (val < 100H) OR unicode & (val >= 100H) THEN
IF mode # char THEN
IF mode = code THEN out.WriteString(", ") END;
out.WriteChar(22X); mode := char
END;
out.WriteChar(CHR(val))
ELSE
IF mode = char THEN out.WriteChar(22X) END;
IF mode # beg THEN out.WriteString(", ") END;
mode := code; Strings.IntToStringForm(val, Strings.hexadecimal, 1, "0", FALSE, str);
IF str[0] > "9" THEN out.WriteChar("0") END;
out.WriteString(str); out.WriteChar("X")
END;
INC(adr, base); DEC(len);
IF base = 2 THEN SYSTEM.GET(adr, ch); val := ORD(ch) ELSE SYSTEM.GET(adr, sc); val := ORD(sc) END
UNTIL (len = 0) OR zterm & (val = 0)
END;
IF mode = char THEN out.WriteChar(22X) END
END WriteString;
PROCEDURE IsIdent (s: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; ch: CHAR;
BEGIN
ch := s[0];
IF Strings.IsIdentStart(ch) THEN
i := 1; ch := s[1];
WHILE Strings.IsIdent(ch) DO
INC(i); ch := s[i]
END;
RETURN (s[i] = 0X) & (i < 256)
ELSE RETURN FALSE
END
END IsIdent;
PROCEDURE OutString (s: ARRAY OF CHAR);
VAR str: Dialog.String;
BEGIN
Dialog.MapString(s, str);
out.WriteString(str);
END OutString;
(* ------------------- variable display ------------------- *)
PROCEDURE FormOf (t: Kernel.Type): SHORTCHAR;
BEGIN
IF SYSTEM.VAL(INTEGER, t) DIV 256 = 0 THEN
RETURN SHORT(CHR(SYSTEM.VAL(INTEGER, t)))
ELSE
RETURN SHORT(CHR(16 + t.id MOD 4))
END
END FormOf;
PROCEDURE LenOf (t: Kernel.Type; ptr: ArrayPtr): INTEGER;
BEGIN
IF t.size # 0 THEN RETURN t.size
ELSIF ptr # NIL THEN RETURN ptr.len[t.id DIV 16 MOD 16 - 1]
ELSE RETURN 0
END
END LenOf;
PROCEDURE SizeOf (t: Kernel.Type; ptr: ArrayPtr): INTEGER;
BEGIN
CASE FormOf(t) OF
| 0BX: RETURN 0
| 1X, 2X, 4X: RETURN 1
| 3X, 5X: RETURN 2
| 8X, 0AX: RETURN 8
| 11X: RETURN t.size
| 12X: RETURN LenOf(t, ptr) * SizeOf(t.base[0], ptr)
ELSE RETURN 4
END
END SizeOf;
PROCEDURE WriteName (t: Kernel.Type; ptr: ArrayPtr);
VAR modName, name: Kernel.Name; f: SHORTCHAR;
BEGIN
f := FormOf(t);
CASE f OF
| 0X: OutString("#Dev:Unknown")
| 1X: out.WriteString("BOOLEAN")
| 2X: out.WriteString("SHORTCHAR")
| 3X: out.WriteString("CHAR")
| 4X: out.WriteString("BYTE")
| 5X: out.WriteString("SHORTINT")
| 6X: out.WriteString("INTEGER")
| 7X: out.WriteString("SHORTREAL")
| 8X: out.WriteString("REAL")
| 9X: out.WriteString("SET")
| 0AX: out.WriteString("LONGINT")
| 0BX: out.WriteString("ANYREC")
| 0CX: out.WriteString("ANYPTR")
| 0DX: out.WriteString("POINTER")
| 0EX: out.WriteString("PROCEDURE")
| 0FX: out.WriteString("STRING")
| 10X..13X:
IF (t.mod # NIL) & (t.id DIV 256 # 0) & (t.mod.refcnt >= 0) THEN
Kernel.GetTypeName(t, name);
IF name = "!" THEN
IF f = 11X THEN out.WriteString("RECORD")
ELSIF f = 12X THEN out.WriteString("ARRAY")
ELSE OutString("#Dev:Unknown")
END
ELSE
Kernel.GetModName(t.mod, modName);
out.WriteString(modName); out.WriteChar("."); out.WriteString(name)
END
ELSIF f = 11X THEN
IF t.mod # NIL THEN Kernel.GetModName(t.mod, modName); out.WriteString(modName); out.WriteChar(".") END;
out.WriteString("RECORD");
ELSIF f = 12X THEN
out.WriteString("ARRAY "); out.WriteInt(LenOf(t, ptr)); t := t.base[0];
WHILE (FormOf(t) = 12X) & ((t.id DIV 256 = 0) OR (t.mod = NIL) OR (t.mod.refcnt < 0)) DO
out.WriteString(", "); out.WriteInt(LenOf(t, ptr)); t := t.base[0]
END;
out.WriteString(" OF "); WriteName(t, ptr)
ELSIF f = 13X THEN
out.WriteString("POINTER")
ELSE
out.WriteString("PROCEDURE")
END
| 20X: out.WriteString("COM.IUnknown")
| 21X: out.WriteString("COM.GUID")
| 22X: out.WriteString("COM.RESULT")
ELSE OutString("#Dev:UnknownFormat"); out.WriteInt(ORD(f))
END
END WriteName;
PROCEDURE WriteGuid (a: INTEGER);
PROCEDURE Hex (a: INTEGER);
VAR x: SHORTCHAR;
BEGIN
SYSTEM.GET(a, x);
out.WriteIntForm(ORD(x), TextMappers.hexadecimal, 2, "0", FALSE)
END Hex;
BEGIN
out.WriteChar("{");
Hex(a + 3); Hex(a + 2); Hex(a + 1); Hex(a);
out.WriteChar("-");
Hex(a + 5); Hex(a + 4);
out.WriteChar("-");
Hex(a + 7); Hex(a + 6);
out.WriteChar("-");
Hex(a + 8);
Hex(a + 9);
out.WriteChar("-");
Hex(a + 10);
Hex(a + 11);
Hex(a + 12);
Hex(a + 13);
Hex(a + 14);
Hex(a + 15);
out.WriteChar("}")
END WriteGuid;
PROCEDURE^ ShowVar (
ad, ind: INTEGER; f, c: SHORTCHAR; desc: Kernel.Type; ptr: ArrayPtr; back: RefView; VAR name, sel: Kernel.Name);
PROCEDURE^ NewRefView (type, command: SHORTINT; adr: INTEGER; back: RefView;
desc: Kernel.Type; ptr: ArrayPtr; name: Kernel.Name): RefView;
PROCEDURE^ InsertRefView (type, command: SHORTINT; adr: INTEGER; back: RefView;
desc: Kernel.Type; ptr: ArrayPtr; name: Kernel.Name);
PROCEDURE ShowRecord (a, ind: INTEGER; desc: Kernel.Type; back: RefView; VAR sel: Kernel.Name);
VAR dir: Kernel.Directory; obj: Kernel.Object; name: Kernel.Name; i, j, n: INTEGER; base: Kernel.Type;
fc: FoldContext;
BEGIN
WriteName(desc, NIL); out.WriteTab;
IF desc.mod.refcnt >= 0 THEN
OpenFold(fc);
n := desc.id DIV 16 MOD 16; j := 0;
WHILE j <= n DO
base := desc.base[j];
IF base # NIL THEN
dir := base.fields; i := 0;
WHILE i < dir.num DO
obj := SYSTEM.VAL(Kernel.Object, SYSTEM.ADR(dir.obj[i]));
Kernel.GetObjName(base.mod, obj, name);
ShowVar(a + obj.offs, ind, FormOf(obj.struct), 1X, obj.struct, NIL, back, name, sel);
INC(i)
END
END;
INC(j)
END;
out.WriteString(" ");
CloseFold(fc, (ind > 1) OR (sel # ""), "#Dev:Fields")
ELSE
OutString("#Dev:Unloaded")
END
END ShowRecord;
PROCEDURE ShowArray (a, ind: INTEGER; desc: Kernel.Type; ptr: ArrayPtr; back: RefView; VAR sel: Kernel.Name);
VAR f: SHORTCHAR; i, n, m, size, len: INTEGER; name: Kernel.Name; eltyp, t: Kernel.Type;
vi: SHORTINT; vs: BYTE; str: Dialog.String; high: BOOLEAN;
fc: FoldContext;
BEGIN
WriteName(desc, ptr); out.WriteTab;
len := LenOf(desc, ptr); eltyp := desc.base[0]; f := FormOf(eltyp); size := SizeOf(eltyp, ptr);
IF (f = 2X) OR (f = 3X) THEN (* string *)
n := 0; m := len; high := FALSE;
IF f = 2X THEN
REPEAT SYSTEM.GET(a + n, vs); INC(n) UNTIL (n = 32) OR (n = len) OR (vs = 0);
REPEAT DEC(m); SYSTEM.GET(a + m, vs) UNTIL (m = 0) OR (vs # 0)
ELSE
REPEAT
SYSTEM.GET(a + n * 2, vi); INC(n);
IF vi DIV 256 # 0 THEN high := TRUE END
UNTIL (n = len) OR (vi = 0);
n := MIN(n, 32);
REPEAT DEC(m); SYSTEM.GET(a + m * 2, vi) UNTIL (m = 0) OR (vi # 0)
END;
WriteString(a, n, size, TRUE, TRUE);
INC(m, 2);
IF m > len THEN m := len END;
IF high OR (m > n) THEN
out.WriteString(" ");
OpenFold(fc);
out.WriteLn;
IF high & (n = 32) THEN
WriteString(a, m, size, TRUE, TRUE);
out.WriteLn; out.WriteLn
END;
WriteString(a, m, size, FALSE, FALSE);
IF m < len THEN out.WriteString(", ..., 0X") END;
out.WriteString(" ");
CloseFold(fc, TRUE, "...")
END
ELSE
t := eltyp;
WHILE FormOf(t) = 12X DO t := t.base[0] END;
IF FormOf(t) # 0X THEN
OpenFold(fc);
i := 0;
WHILE i < len DO
Strings.IntToString(i, str);
name := "[" + SHORT(str$) + "]";
ShowVar(a, ind, f, 1X, eltyp, ptr, back, name, sel);
INC(i); INC(a, size)
END;
out.WriteString(" ");
CloseFold(fc, StdFolds.collapsed, "#Dev:Elements")
END
END
END ShowArray;
PROCEDURE ShowProcVar (a: INTEGER);
VAR vli, n, ref: INTEGER; m: Kernel.Module; modName, name: Kernel.Name; res: INTEGER; nn: Kernel.Utf8Name;
BEGIN
SYSTEM.GET(a, vli);
Kernel.SearchProcVar(vli, m, vli);
IF m = NIL THEN
IF vli = 0 THEN out.WriteString("NIL")
ELSE WriteHex(vli)
END
ELSE
IF m.refcnt >= 0 THEN
Kernel.GetModName(m, modName); out.WriteString(modName); ref := m.refs;
REPEAT Kernel.GetRefProc(ref, n, nn) UNTIL (n = 0) OR (vli < n);
IF vli < n THEN out.WriteChar("."); Utf.Utf8ToString(nn, name, res); out.WriteString(name) END
ELSE
OutString("#Dev:ProcInUnloadedMod");
Kernel.GetModName(m, modName); out.WriteString( modName); out.WriteString(" !!!")
END
END
END ShowProcVar;
PROCEDURE ShowPointer (a: INTEGER; f: SHORTCHAR; desc: Kernel.Type; back: RefView; VAR sel: Kernel.Name);
VAR adr, x: INTEGER; ptr: ArrayPtr; c: Cluster; btyp: Kernel.Type;
BEGIN
SYSTEM.GET(a, adr);
IF f = 13X THEN btyp := desc.base[0] ELSE btyp := NIL END;
IF adr = 0 THEN out.WriteString("NIL")
ELSIF f = 20X THEN
out.WriteChar("["); WriteHex(adr); out.WriteChar("]");
out.WriteChar(" "); c := SYSTEM.VAL(Cluster, Kernel.Root());
WHILE (c # NIL) & ((adr < SYSTEM.VAL(INTEGER, c)) OR (adr >= SYSTEM.VAL(INTEGER, c) + c.size)) DO c := c.next END;
IF c # NIL THEN
ptr := SYSTEM.VAL(ArrayPtr, adr);
InsertRefView(heap, open, adr, back, btyp, ptr, sel)
END
ELSE
IF (f = 13X) OR (f = 0CX) THEN x := adr - 4 ELSE x := adr END;
IF ((adr < -4) OR (adr >= 65536)) & Kernel.IsReadable(x, adr + 16) THEN
out.WriteChar("["); WriteHex(adr); out.WriteChar("]");
IF (f = 13X) OR (f = 0CX) THEN
out.WriteChar(" "); c := SYSTEM.VAL(Cluster, Kernel.Root());
WHILE (c # NIL) & ((adr < SYSTEM.VAL(INTEGER, c)) OR (adr >= SYSTEM.VAL(INTEGER, c) + c.size)) DO
c := c.next
END;
IF c # NIL THEN
ptr := SYSTEM.VAL(ArrayPtr, adr);
IF (f = 13X) & (FormOf(btyp) = 12X) THEN (* array *)
adr := SYSTEM.ADR(ptr.len[btyp.id DIV 16 MOD 16])
END;
InsertRefView(heap, open, adr, back, btyp, ptr, sel)
ELSE OutString("#Dev:IllegalPointer");
END
END
ELSE OutString("#Dev:IllegalAddress"); WriteHex(adr)
END
END
END ShowPointer;
PROCEDURE ShowSelector (ref: RefView);
VAR b: RefView; n: INTEGER; a, a0: TextModels.Attributes; res: INTEGER; nn: Kernel.Name;
BEGIN
b := ref.back; n := 1;
IF b # NIL THEN
WHILE (b.name = ref.name) & (b.back # NIL) DO INC(n); b := b.back END;
ShowSelector(b);
IF n > 1 THEN out.WriteChar("(") END;
out.WriteChar(".")
END;
Utf.Utf8ToString(ref.name, nn, res); out.WriteString(nn);
IF ref.type = heap THEN out.WriteChar("^") END;
IF n > 1 THEN
out.WriteChar(")");
a0 := out.rider.attr; a := TextModels.NewOffset(a0, 2 * Ports.point);
out.rider.SetAttr(a);
out.WriteInt(n); out.rider.SetAttr(a0)
END;
END ShowSelector;
PROCEDURE ShowVar (
ad, ind: INTEGER; f, c: SHORTCHAR; desc: Kernel.Type; ptr: ArrayPtr; back: RefView; VAR name, sel: Kernel.Name
);
VAR i, j, vli, a: INTEGER; tsel: Kernel.Name; a0: TextModels.Attributes;
vc: SHORTCHAR; vsi: BYTE; vi: SHORTINT; vr: SHORTREAL; vlr: REAL; vs: SET;
BEGIN
out.WriteLn; out.WriteTab; i := 0;
WHILE i < ind DO out.WriteString(" "); INC(i) END;
a := ad; i := 0; j := 0;
IF sel # "" THEN
WHILE sel[i] # 0X DO tsel[i] := sel[i]; INC(i) END;
IF (tsel[i-1] # ":") & (name[0] # "[") THEN tsel[i] := "."; INC(i) END
END;
WHILE name[j] # 0X DO tsel[i] := name[j]; INC(i); INC(j) END;
tsel[i] := 0X;
a0 := out.rider.attr;
IF c = 3X THEN (* varpar *)
SYSTEM.GET(ad, a);
out.rider.SetAttr(TextModels.NewStyle(a0, {Fonts.italic}))
END;
IF name[0] # "[" THEN out.WriteChar(".") END;
out.WriteString(name);
out.rider.SetAttr(a0); out.WriteTab;
IF (c = 3X) & (a >= 0) & (a < 65536) THEN
out.WriteTab; out.WriteString("NIL VARPAR");
ELSIF f = 11X THEN
Kernel.GetTypeName(desc, name);
IF (c = 3X) & (name[0] # "!") THEN SYSTEM.GET(ad + 4, desc) END; (* dynamic type *)
ShowRecord(a, ind + 1, desc, back, tsel)
ELSIF (c = 3X) & (f = 0BX) THEN (* VAR anyrecord *)
SYSTEM.GET(ad + 4, desc);
ShowRecord(a, ind + 1, desc, back, tsel)
ELSIF f = 12X THEN
IF (desc.size = 0) & (ptr = NIL) THEN SYSTEM.GET(ad, a) END; (* dyn array val par *)
IF ptr = NIL THEN ptr := SYSTEM.VAL(ArrayPtr, ad - 8) END;
ShowArray(a, ind + 1, desc, ptr, back, tsel)
ELSE
IF desc = NIL THEN desc := SYSTEM.VAL(Kernel.Type, ORD(f)) END;
WriteName(desc, NIL); out.WriteTab;
CASE f OF
| 0X: (* SYSTEM.GET(a, vli); WriteHex(vli) *)
| 1X: SYSTEM.GET(a, vc);
IF vc = 0X THEN out.WriteString("FALSE")
ELSIF vc = 1X THEN out.WriteString("TRUE")
ELSE OutString("#Dev:Undefined"); out.WriteInt(ORD(vc))
END
| 2X: WriteString(a, 1, 1, FALSE, FALSE)
| 3X: WriteString(a, 1, 2, FALSE, TRUE);
SYSTEM.GET(a, vi);
IF vi DIV 256 # 0 THEN out.WriteString(" "); WriteString(a, 1, 2, FALSE, FALSE) END
| 4X: SYSTEM.GET(a, vsi); out.WriteInt(vsi)
| 5X: SYSTEM.GET(a, vi); out.WriteInt(vi)
| 6X: SYSTEM.GET(a, vli); out.WriteInt(vli)
| 7X: SYSTEM.GET(a, vli);
IF BITS(vli) * {23..30} = {23..30} THEN
IF BITS(vli) = {23..30} THEN out.WriteString("inf")
ELSIF BITS(vli) = {23..31} THEN out.WriteString("-inf")
ELSE out.WriteString("nan ("); WriteHex(vli); out.WriteString(")")
END
ELSE
SYSTEM.GET(a, vr); out.WriteReal(vr)
END
| 8X: IF Kernel.littleEndian THEN SYSTEM.GET(a, vli); SYSTEM.GET(a + 4, i)
ELSE SYSTEM.GET(a + 4, vli); SYSTEM.GET(a, i)
END;
IF BITS(i) * {20..30} = {20..30} THEN
IF (BITS(i) = {20..30}) & (vli = 0) THEN out.WriteString("inf")
ELSIF (BITS(i) = {20..31}) & (vli = 0) THEN out.WriteString("-inf")
ELSE out.WriteString("nan ("); out.WriteIntForm(i, TextMappers.hexadecimal, 8, "0", TextMappers.hideBase);
WriteHex(vli); out.WriteString(")")
END
ELSE
SYSTEM.GET(a, vlr); out.WriteReal(vlr)
END
| 9X: SYSTEM.GET(a, vs); out.WriteSet(vs)
| 0AX: IF Kernel.littleEndian THEN SYSTEM.GET(a, vli); SYSTEM.GET(a + 4, i)
ELSE SYSTEM.GET(a + 4, vli); SYSTEM.GET(a, i)
END;
IF (vli >= 0) & (i = 0) OR (vli < 0) & (i = -1) THEN out.WriteInt(vli)
ELSE out.WriteIntForm(i, TextMappers.hexadecimal, 8, "0", TextMappers.hideBase); WriteHex(vli)
END
| 0CX, 0DX, 13X, 20X: ShowPointer(a, f, desc, back, tsel)
| 0EX, 10X: ShowProcVar(a)
| 0FX: WriteString(a, 256, 1, TRUE, FALSE)
| 21X: WriteGuid(a)
| 22X: SYSTEM.GET(a, vli); WriteHex(vli)
ELSE
END
END
END ShowVar;
PROCEDURE WriteTimeStamp (ts: ARRAY OF SHORTINT);
VAR d: Dates.Date; t: Dates.Time; str: ARRAY 64 OF CHAR;
BEGIN
IF ts[0] = 0 THEN
out.WriteString(" "); OutString("#Dev:Linked")
ELSE
d.year := ts[0]; d.month := ts[1]; d.day := ts[2];
t.hour := ts[3]; t.minute := ts[4]; t.second := ts[5];
Dates.DateToString(d, Dates.short, str);
out.WriteString(str); out.WriteString(" ");
Dates.TimeToString(t, str);
out.WriteString(str);
END
END WriteTimeStamp;
PROCEDURE ShowModules;
VAR m, m1: Kernel.Module; a0: TextModels.Attributes; n, h, t, h1: Kernel.Name; res: INTEGER;
BEGIN
a0 := out.rider.attr;
out.rider.SetAttr(TextModels.NewStyle(a0, {Fonts.italic}));
OutString("#Dev:ModuleName"); out.WriteTab;
OutString("#Dev:BytesUsed"); out.WriteTab;
OutString("#Dev:Clients"); out.WriteTab;
OutString("#Dev:Compiled"); out.WriteTab;
OutString("#Dev:Loaded");
out.rider.SetAttr(a0); out.WriteTab; out.WriteTab;
out.rider.SetAttr(TextModels.NewStyle(out.rider.attr, {Fonts.underline}));
out.rider.SetAttr(TextModels.NewColor(out.rider.attr, Ports.blue));
out.WriteView(StdLinks.dir.NewLink("DevDebug.UpdateModules"));
OutString("#Dev:Update");
out.WriteView(StdLinks.dir.NewLink(""));
out.rider.SetAttr(a0); out.WriteLn;
m := Kernel.modList;
WHILE m # NIL DO
IF m.refcnt >= 0 THEN
Utf.Utf8ToString(m.name, n, res); Librarian.lib.SplitName(n, h, t);
m1 := Kernel.modList; h1 := "*";
WHILE (m1 # m) & (h1 # h) DO
IF m1.refcnt >= 0 THEN
Utf.Utf8ToString(m1.name, n, res); Librarian.lib.SplitName(n, h1, t)
END;
m1 := m1.next
END;
IF h1 # h THEN
out.WriteLn;
m1 := m;
WHILE m1 # NIL DO
Utf.Utf8ToString(m1.name, n, res); Librarian.lib.SplitName(n, h1, t);
IF (h1 = h) & (m1.refcnt >= 0) THEN
out.WriteString(n); out.WriteTab;
out.WriteInt(m1.csize + m1.dsize + m1.rsize);
out.WriteTab;
out.WriteInt(m1.refcnt);
out.WriteTab;
WriteTimeStamp(m1.compTime);
out.WriteTab;
WriteTimeStamp(m1.loadTime);
out.WriteLn
END;
m1 := m1.next
END
END
END;
m := m.next
END
END ShowModules;
PROCEDURE ShowGlobals (mod: Kernel.Module);
VAR ref, x: INTEGER; m, f: SHORTCHAR; name: ARRAY 256 OF CHAR; modName, mname: Kernel.Name;
d: Kernel.Type; v: RefView; a0: TextModels.Attributes; res: INTEGER; nn: Kernel.Utf8Name;
BEGIN
IF mod # NIL THEN
Kernel.GetModName(mod, modName); out.WriteString(modName);
out.WriteTab; out.WriteTab; out.WriteTab;
a0 := out.rider.attr;
out.rider.SetAttr(TextModels.NewStyle(out.rider.attr, {Fonts.underline}));
out.rider.SetAttr(TextModels.NewColor(out.rider.attr, Ports.blue));
Kernel.GetModName(mod, modName); name := "DevDebug.UpdateGlobals('" + modName + "')";
out.WriteView(StdLinks.dir.NewLink(name));
OutString("#Dev:Update");
out.WriteView(StdLinks.dir.NewLink(""));
out.rider.SetAttr(a0); out.WriteLn;
ref := mod.refs; Kernel.GetRefProc(ref, x, nn); Utf.Utf8ToString(nn, mname, res); (* get body *)
IF x # 0 THEN
Kernel.GetModName(mod, modName); v := NewRefView (module, open, 0, NIL, NIL, NIL, modName);
Kernel.GetRefVar(ref, m, f, d, x, nn); Utf.Utf8ToString(nn, mname, res);
WHILE m = 1X DO
ShowVar(mod.data + x, 0, f, m, d, NIL, v, mname, empty);
Kernel.GetRefVar(ref, m, f, d, x, nn); Utf.Utf8ToString(nn, mname, res);
END
END;
out.WriteLn
END
END ShowGlobals;
PROCEDURE ShowObject (adr: INTEGER);
VAR eltyp: Kernel.Type; ptr: ArrayPtr; desc: ARRAY 64 OF INTEGER; i, n, lev, elsize: INTEGER;
BEGIN
SYSTEM.GET(adr - 4, eltyp);
IF ODD(SYSTEM.VAL(INTEGER, eltyp) DIV 2) THEN
DEC(SYSTEM.VAL(INTEGER, eltyp), 2);
ptr := SYSTEM.VAL(ArrayPtr, adr);
elsize := eltyp.size;
IF (eltyp.mod.name = "Kernel") & (eltyp.fields.num = 1) THEN
eltyp := eltyp.fields.obj[0].struct
END;
n := (ptr.last - ptr.first) DIV elsize + 1;
lev := (ptr.first - adr - 12) DIV 4; i := 0;
WHILE lev > 0 DO (* dynamic levels *)
DEC(lev);
desc[i] := ptr.len[lev]; n := n DIV desc[i]; INC(i); (* size *)
desc[i] := 0; INC(i); (* module *)
desc[i] := 2; INC(i); (* id *)
desc[i] := SYSTEM.ADR(desc[i+1]); INC(i) (* desc *)
END;
IF n > 1 THEN (* static level *)
desc[i] := n; INC(i); (* size *)
desc[i] := 0; INC(i); (* module *)
desc[i] := 2; INC(i); (* id *)
ELSE DEC(i)
END;
desc[i] := SYSTEM.VAL(INTEGER, eltyp); (* desc *)
ShowArray(ptr.first, 1, SYSTEM.VAL(Kernel.Type, SYSTEM.ADR(desc)), ptr, NIL, empty);
out.WriteLn
ELSE ShowRecord(adr, 1, eltyp, NIL, empty)
END;
END ShowObject;
PROCEDURE ShowPtrDeref (ref: RefView);
VAR b: RefView; res: INTEGER; name: Kernel.Name;
BEGIN
ShowSelector(ref); b := ref.back;
IF b # NIL THEN
out.WriteChar(" ");
Utf.Utf8ToString(b.name, name, res); InsertRefView(b.type, undo, b.adr, b.back, b.desc, b.ptr, name)
END;
out.WriteLn; out.WriteLn;
out.WriteChar("["); WriteHex(ref.adr); out.WriteChar("]"); out.WriteTab;
IF ref.desc = NIL THEN
ShowObject(ref.adr)
ELSIF FormOf(ref.desc) = 12X THEN
ShowArray(ref.adr, 1, ref.desc, ref.ptr, ref, empty)
ELSE
ShowRecord(ref.adr, 1, Kernel.TypeOf(SYSTEM.VAL(ANYPTR, ref.ptr)), ref, empty)
END;
out.WriteLn
END ShowPtrDeref;
PROCEDURE Scan (VAR s: TextMappers.Scanner);
BEGIN
s.Scan;
IF s.type = TextMappers.string THEN
IF s.string = "IMPORT" THEN s.type := import
ELSIF s.string = "MODULE" THEN s.type := smodule
ELSIF s.string = "THEN" THEN s.type := stop
ELSIF s.string = "OF" THEN s.type := stop
ELSIF s.string = "DO" THEN s.type := stop
ELSIF s.string = "END" THEN s.type := stop
ELSIF s.string = "ELSE" THEN s.type := stop
ELSIF s.string = "ELSIF" THEN s.type := stop
ELSIF s.string = "UNTIL" THEN s.type := stop
ELSIF s.string = "TO" THEN s.type := stop
ELSIF s.string = "BY" THEN s.type := stop
END
ELSIF s.type = TextMappers.char THEN
IF s.char = ";" THEN s.type := semicolon
ELSIF s.char = "|" THEN s.type := stop
ELSIF s.char = ":" THEN
IF s.rider.char = "=" THEN s.rider.Read; s.type := becomes END
ELSIF s.char = "(" THEN
IF s.rider.char = "*" THEN
s.rider.Read;
REPEAT Scan(s) UNTIL (s.type = TextMappers.eot) OR (s.type = comEnd);
Scan(s)
END
ELSIF s.char = "*" THEN
IF s.rider.char = ")" THEN s.rider.Read; s.type := comEnd END
END
END
END Scan;
PROCEDURE ShowSourcePos (name: Kernel.Utf8Name; adr: INTEGER);
VAR loc: Files.Locator; fname: Files.Name; v: Views.View; m: Models.Model; conv: Converters.Converter;
c: Containers.Controller; beg, end: INTEGER; s: TextMappers.Scanner; w: Windows.Window;
res: INTEGER; n: Kernel.Name;
BEGIN
(* search source by name heuristic *)
Utf.Utf8ToString(name, n, res); StdDialog.GetSubLoc(n, "Mod", loc, fname);
Librarian.lib.GetSpec(n, "Mod", loc, fname);
v := Views.OldView(loc, fname); m := NIL;
IF v # NIL THEN
Views.Open(v, loc, fname, NIL);
m := v.ThisModel();
IF ~(m IS TextModels.Model) THEN m := NIL END
END;
IF m = NIL THEN
(* search in open windows *)
w := Windows.dir.First();
WHILE (w # NIL) & (m = NIL) DO
v := w.doc.ThisView();
m := v.ThisModel();
IF m # NIL THEN
WITH m: TextModels.Model DO
s.ConnectTo(m); s.SetPos(0);
REPEAT
REPEAT s.Scan UNTIL s.rider.eot OR (s.type = TextMappers.string) & (s.string = "MODULE");
s.Scan;
UNTIL s.rider.eot OR (s.type = TextMappers.string) & (s.string = n);
IF ~s.rider.eot THEN Windows.dir.Select(w, Windows.eager)
ELSE m := NIL
END
ELSE m := NIL
END
END;
w := Windows.dir.Next(w)
END
END;
IF m = NIL THEN
(* ask user for source file *)
conv := NIL; v := Views.Old(Views.ask, loc, fname, conv);
IF v # NIL THEN
Views.Open(v, loc, fname, conv);
m := v.ThisModel();
IF ~(m IS TextModels.Model) THEN m := NIL END
END
END;
IF m # NIL THEN
(* mark error position in text *)
WITH m: TextModels.Model DO
beg := Kernel.SourcePos(Kernel.ThisMod(n), adr);
IF beg >= 0 THEN
IF beg > m.Length() THEN beg := m.Length() - 10 END;
s.ConnectTo(m); s.SetPos(beg);
Scan(s); beg := s.start; end := beg + 3;
IF s.type = stop THEN end := s.Pos() - 1
ELSE
WHILE (s.type # TextMappers.eot) & (s.type # stop) & (s.type # semicolon) DO
end := s.Pos() - 1; Scan(s)
END
END;
c := v(TextViews.View).ThisController();
v(TextViews.View).ShowRange(beg, end, TextViews.any);
c(TextControllers.Controller).SetSelection(beg, end)
END
END
ELSE Dialog.ShowParamMsg("#Dev:SourcefileNotFound", n, "", "")
END
END ShowSourcePos;
(* ------------------- RefView ------------------- *)
PROCEDURE (v: RefView) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER;
BEGIN
v.Internalize^(rd); IF rd.cancelled THEN RETURN END;
rd.ReadVersion(0, 0, thisVersion); IF rd.cancelled THEN RETURN END;
v.command := open;
rd.ReadSInt(v.type);
IF v.type = source THEN
rd.ReadInt(v.adr);
rd.ReadSString(v.name)
ELSIF v.type = module THEN
rd.ReadSString(v.name)
ELSIF v.type # modules THEN
v.type := 0
END
END Internalize;
PROCEDURE (v: RefView) Externalize (VAR wr: Stores.Writer);
VAR t: SHORTINT;
BEGIN
v.Externalize^(wr);
wr.WriteVersion(0);
t := v.type;
IF v.command # open THEN t := 0 END;
wr.WriteSInt(t);
IF t = source THEN
wr.WriteInt(v.adr);
wr.WriteSString(v.name)
ELSIF t = module THEN
wr.WriteSString(v.name)
END
END Externalize;
PROCEDURE (v: RefView) CopyFromSimpleView (source: Views.View);
BEGIN
(* v.CopyFrom^(source); *)
WITH source: RefView DO
v.type := source.type; v.command := source.command; v.adr := source.adr; v.back := source.back;
v.desc := source.desc; v.ptr := source.ptr; v.name := source.name$;
END
END CopyFromSimpleView;
PROCEDURE (v: RefView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawPath(path, 4, Ports.fill, Ports.blue, Ports.closedPoly)
END Restore;
PROCEDURE (v: RefView) GetBackground (VAR color: Ports.Color);
BEGIN
color := Ports.background
END GetBackground;
PROCEDURE (v: RefView) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR t, t0: TextModels.Model; m: Models.Model; x, y: INTEGER;
isDown, new: BOOLEAN; mo: SET; script: Stores.Operation;
res: INTEGER; n: Kernel.Name;
BEGIN
WITH msg: Controllers.TrackMsg DO
IF v.type > 0 THEN
REPEAT
f.MarkRect(0, 0, refViewSize, refViewSize, Ports.fill, Ports.hilite, Ports.show);
IF v.command = undo THEN Dialog.ShowStatus("#Dev:ShowPrecedingObject")
ELSIF v.command = update THEN Dialog.ShowStatus("#Dev:UpdateWindow")
ELSIF v.type = module THEN Dialog.ShowStatus("#Dev:ShowGlobalVariables")
ELSIF v.type = source THEN Dialog.ShowStatus("#Dev:ShowSourcePosition")
ELSIF v.type = heap THEN Dialog.ShowStatus("#Dev:ShowReferencedObject")
END;
REPEAT
f.Input(x, y, mo, isDown)
UNTIL (x < 0) OR (x > refViewSize) OR (y < 0) OR (y > refViewSize) OR ~isDown;
f.MarkRect(0, 0, refViewSize, refViewSize, Ports.fill, Ports.hilite, Ports.hide);
Dialog.ShowStatus("");
WHILE isDown & ((x < 0) OR (x > refViewSize) OR (y < 0) OR (y > refViewSize)) DO
f.Input(x, y, mo, isDown)
END
UNTIL ~isDown;
IF (x >= 0) & (x <= refViewSize) & (y >= 0) & (y <= refViewSize) THEN
IF v.type = source THEN ShowSourcePos(v.name, v.adr)
ELSE
m := v.context.ThisModel();
new := (v.command = open) & (v.back = NIL)
OR (Controllers.modify IN msg.modifiers) & (v.command # update)
OR ~(m IS TextModels.Model) ;
IF new THEN
t := TextModels.CloneOf(StdLog.buf); t0 := NIL
ELSE
t0 := m(TextModels.Model); t := TextModels.CloneOf(t0);
END;
out.ConnectTo(t);
IF v.type = heap THEN ShowPtrDeref(v)
ELSIF v.type = module THEN Utf.Utf8ToString(v.name, n, res); ShowGlobals(Kernel.ThisLoadedMod(n))
ELSIF v.type = modules THEN ShowModules
END;
out.ConnectTo(NIL);
IF new THEN
OpenViewer(t, "#Dev:Variables", NewRuler())
ELSE
Models.BeginScript(t0, "#Dev:Change", script);
t0.Delete(0, t0.Length()); t0.Insert(0, t, 0, t.Length());
Models.EndScript(t0, script)
END
END
END
END
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: RefView) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.ResizePref DO msg.fixed := TRUE
| msg: Properties.SizePref DO msg.w := refViewSize; msg.h := refViewSize
| msg: Properties.FocusPref DO msg.hotFocus := TRUE
ELSE
END
ELSE
END
END HandlePropMsg;
PROCEDURE NewRefView (type, command: SHORTINT; adr: INTEGER; back: RefView;
desc: Kernel.Type; ptr: ArrayPtr; name: Kernel.Name): RefView;
VAR v: RefView; res: INTEGER;
BEGIN
NEW(v); v.type := type; v.command := command; v.adr := adr; v.back := back;
v.desc := desc; v.ptr := ptr; Utf.StringToUtf8(name, v.name, res);
RETURN v
END NewRefView;
PROCEDURE InsertRefView (type, command: SHORTINT; adr: INTEGER; back: RefView;
desc: Kernel.Type; ptr: ArrayPtr; name: Kernel.Name);
VAR v: RefView; a0: TextModels.Attributes;
BEGIN
v := NewRefView(type, command, adr, back, desc, ptr, name);
a0 := out.rider.attr;
out.rider.SetAttr(TextModels.NewOffset(a0, Ports.point));
out.WriteView(v);
out.rider.SetAttr(a0)
END InsertRefView;
PROCEDURE HeapRefView* (adr: INTEGER; name: ARRAY OF CHAR): Views.View;
VAR ptr: ArrayPtr;
BEGIN
ptr := SYSTEM.VAL(ArrayPtr, adr);
RETURN NewRefView(heap, open, adr, NIL, NIL, ptr, name$)
END HeapRefView;
(* ----------------------------------------- *)
PROCEDURE GetMod (VAR mod: Kernel.Module);
VAR c: TextControllers.Controller; s: TextMappers.Scanner; beg, end: INTEGER;
BEGIN
mod := NIL;
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
s.ConnectTo(c.text); s.SetPos(beg); s.Scan;
IF s.type = TextMappers.string THEN
DevReferences.ResolveImportAlias(s.string, c.text);
mod := Kernel.ThisMod(s.string);
IF mod = NIL THEN
Dialog.ShowParamMsg("#Dev:ModuleNotFound", s.string, "", "")
END
ELSE Dialog.ShowMsg("#Dev:NoModuleNameSelected")
END
ELSE Dialog.ShowMsg("#Dev:NoSelectionFound")
END
END GetMod;
PROCEDURE ShowLoadedModules*;
BEGIN
out.ConnectTo(TextModels.CloneOf(StdLog.buf));
ShowModules;
OpenViewer(out.rider.Base(), "#Dev:LoadedModules", NewModRuler());
out.ConnectTo(NIL)
END ShowLoadedModules;
PROCEDURE UpdateModules*;
VAR t, t0: TextModels.Model; script: Stores.Operation;
BEGIN
t0 := TextViews.FocusText();
Models.BeginScript(t0, "#Dev:Change", script);
t := TextModels.CloneOf(t0);
out.ConnectTo(t);
ShowModules;
(*Stores.InitDomain(t, t0.domain);*) Stores.Join(t, t0); (* not efficient to init domain before writing *)
t0.Delete(0, t0.Length()); t0.Insert(0, t, 0, t.Length());
Models.EndScript(t0, script);
out.ConnectTo(NIL)
END UpdateModules;
PROCEDURE ShowGlobalVariables*;
VAR mod: Kernel.Module;
BEGIN
GetMod(mod);
IF mod # NIL THEN
out.ConnectTo(TextModels.CloneOf(StdLog.buf));
ShowGlobals(mod);
OpenViewer(out.rider.Base(), "#Dev:Variables", NewRuler());
out.ConnectTo(NIL)
END
END ShowGlobalVariables;
PROCEDURE UpdateGlobals* (name: ARRAY OF CHAR);
VAR t, t0: TextModels.Model; script: Stores.Operation; mod: Kernel.Module;
BEGIN
mod := Kernel.ThisLoadedMod(name);
IF mod # NIL THEN
t0 := TextViews.FocusText();
Models.BeginScript(t0, "#Dev:Change", script);
t := TextModels.CloneOf(t0);
out.ConnectTo(t);
ShowGlobals(mod);
(*Stores.InitDomain(t, t0.domain);*) Stores.Join(t, t0); (* not efficient to init domain before writing *)
t0.Delete(0, t0.Length()); t0.Insert(0, t, 0, t.Length());
Models.EndScript(t0, script);
out.ConnectTo(NIL)
END
END UpdateGlobals;
PROCEDURE ShowHeapObject* (adr: INTEGER; title: ARRAY OF CHAR);
BEGIN
out.ConnectTo(TextModels.CloneOf(StdLog.buf));
IF title # "" THEN
out.WriteString(title); out.WriteLn; out.WriteLn
END;
out.WriteChar("["); WriteHex(adr); out.WriteChar("]"); out.WriteTab;
ShowObject(adr);
out.WriteLn;
OpenViewer(out.rider.Base(), "#Dev:HeapObject", NewRuler());
out.ConnectTo(NIL)
END ShowHeapObject;
PROCEDURE ShowViewState*;
VAR ops: Controllers.PollOpsMsg;
BEGIN
Controllers.PollOps(ops);
IF ops.singleton # NIL THEN
ShowHeapObject(SYSTEM.VAL(INTEGER, ops.singleton), "")
END
END ShowViewState;
PROCEDURE LogClients (m: Kernel.Module);
VAR n: Kernel.Module; name: Kernel.Name; i, j, res: INTEGER;
BEGIN
IF m # NIL THEN
n := Kernel.modList;
WHILE n # NIL DO
IF n.refcnt >= 0 THEN
j := n.nofimps;
i := 0; WHILE (i < j) & (n.imports[i] # m) DO INC(i) END;
IF i < j THEN
Utf.Utf8ToString(n.name, name, res); StdLog.String(name); StdLog.Char(' ')
END
END;
n := n.next
END
END
END LogClients;
PROCEDURE UnloadMod (name: TextMappers.String; VAR ok: BOOLEAN);
VAR mod: Kernel.Module; str: Dialog.String;
BEGIN
mod := Kernel.ThisLoadedMod(name);
IF mod # NIL THEN
IF name # "DevDebug" THEN
Dialog.ShowParamStatus("#Dev:Unloading", name, "", "");
Kernel.UnloadMod(mod)
END;
IF mod.refcnt < 0 THEN
Dialog.MapParamString("#Dev:Unloaded", name, "", "", str);
StdLog.String(str); StdLog.Ln
ELSE
Dialog.ShowParamMsg("#Dev:UnloadingFailed", name, "", "");
IF mod.refcnt > 0 THEN
StdLog.ParamMsg("#Dev:ReferencedBy", name, '', ''); LogClients(mod); StdLog.Ln
END;
ok := FALSE
END
ELSE
Dialog.ShowParamMsg("#Dev:NotFound", name, "", "");
ok := FALSE;
END
END UnloadMod;
PROCEDURE Unload*;
VAR t: TextModels.Model; s: TextMappers.Scanner; ok: BOOLEAN;
BEGIN
t := TextViews.FocusText();
IF t # NIL THEN
s.ConnectTo(t); s.SetPos(0);
REPEAT Scan(s) UNTIL (s.type = smodule) OR s.rider.eot;
IF (s.type = smodule) THEN
Scan(s);
IF (s.type = TextMappers.string) & IsIdent(s.string) THEN
ok := TRUE; UnloadMod(s.string, ok);
IF ok THEN Dialog.ShowStatus("#Dev:Ok") END;
Controls.Relink
ELSE
Dialog.ShowMsg("#Dev:NoModNameFound");
END
ELSE
Dialog.ShowMsg("#Dev:NoModNameFound");
END
END
END Unload;
PROCEDURE UnloadList(beg, end: INTEGER; text: TextModels.Model);
VAR s: TextMappers.Scanner; ok, num: BOOLEAN; linked: ARRAY 16 OF CHAR;
BEGIN
s.ConnectTo(text); s.SetPos(beg); s.Scan; ok := TRUE; num := FALSE;
WHILE (s.start < end) & (s.type # TextMappers.invalid) DO
Dialog.MapString("#Dev:Linked", linked);
IF (s.type = TextMappers.string) & (s.string # linked) THEN
IF num & ((s.string = "AM") OR (s.string = "PM")) THEN s.Scan (* skip am & pm *)
ELSIF IsIdent(s.string) THEN UnloadMod(s.string, ok); s.Scan
ELSE s.type := TextMappers.invalid
END
ELSE
(* skip numbers to allow selection of list of loaded modules *)
num := TRUE; s.Scan
END
END;
IF ok THEN Dialog.ShowStatus("#Dev:Ok") END;
Controls.Relink
END UnloadList;
PROCEDURE UnloadModuleList*;
VAR c: TextControllers.Controller; beg, end: INTEGER;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
UnloadList(beg, end, c.text)
END
END UnloadModuleList;
PROCEDURE UnloadThis*;
VAR p: DevCommanders.Par; beg, end: INTEGER;
BEGIN
p := DevCommanders.par;
IF p # NIL THEN
DevCommanders.par := NIL;
beg := p.beg; end := p.end;
UnloadList(beg, end, p.text)
ELSE Dialog.ShowMsg("#Dev:NoTextViewFound")
END
END UnloadThis;
PROCEDURE Execute*;
VAR beg, end, res: INTEGER; done: BOOLEAN;
c: TextControllers.Controller; s: TextMappers.Scanner; cmd: Dialog.String;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
s.ConnectTo(c.text); s.SetPos(beg); s.Scan; TextMappers.ScanQualIdent(s, cmd, done);
IF done THEN
Dialog.Call(cmd, " ", res)
ELSIF s.type = TextMappers.string THEN
Dialog.Call(s.string, " ", res)
ELSE
Dialog.ShowMsg("#Dev:StringExpected")
END
ELSE Dialog.ShowMsg("#Dev:NoSelectionFound")
END
END Execute;
PROCEDURE ShowStack;
VAR ref, end, i, j, x, a, b, c: INTEGER; m, f: SHORTCHAR; mod: Kernel.Module; modName, name, sel: Kernel.Name;
d: Kernel.Type; res: INTEGER; nn: Kernel.Utf8Name;
BEGIN
a := Kernel.pc; b := Kernel.fp; c := 100;
REPEAT
mod := Kernel.modList;
WHILE (mod # NIL) & ((a < mod.code) OR (a >= mod.code + mod.csize)) DO mod := mod.next END;
IF mod # NIL THEN
DEC(a, mod.code);
IF mod.refcnt >= 0 THEN
Kernel.GetModName(mod, modName); InsertRefView(module, open, 0, NIL, NIL, NIL, modName);
out.WriteChar(" "); out.WriteString(modName); ref := mod.refs;
REPEAT Kernel.GetRefProc(ref, end, nn) UNTIL (end = 0) OR (a < end);
Utf.Utf8ToString(nn, name, res);
IF a < end THEN
out.WriteChar("."); out.WriteString(name);
sel := mod.name$; i := 0;
WHILE sel[i] # 0X DO INC(i) END;
sel[i] := "."; INC(i); j := 0;
WHILE name[j] # 0X DO sel[i] := name[j]; INC(i); INC(j) END;
sel[i] := ":"; sel[i+1] := 0X;
out.WriteString(" ["); WriteHex(a);
out.WriteString("] ");
i := Kernel.SourcePos(mod, 0);
IF i >= 0 THEN
Kernel.GetModName(mod, modName); InsertRefView(source, open, a, NIL, NIL, NIL, modName);
END;
IF name # "$$" THEN
Kernel.GetRefVar(ref, m, f, d, x, nn); Utf.Utf8ToString(nn, name, res);
WHILE m # 0X DO
ShowVar(b + x, 0, f, m, d, NIL, NIL, name, sel);
Kernel.GetRefVar(ref, m, f, d, x, nn); Utf.Utf8ToString(nn, name, res);
END
END;
out.WriteLn
ELSE out.WriteString(".???"); out.WriteLn
END
ELSE
out.WriteChar("("); Kernel.GetModName(mod, modName); out.WriteString(modName);
out.WriteString(") (pc="); WriteHex(a);
out.WriteString(", fp="); WriteHex(b); out.WriteChar(")");
out.WriteLn
END
ELSE
out.WriteString("<system> (pc="); WriteHex(a);
out.WriteString(", fp="); WriteHex(b); out.WriteChar(")");
out.WriteLn
END;
IF (b >= Kernel.fp) & (b < Kernel.stack) THEN
SYSTEM.GET(b+4, a); (* stacked pc *)
SYSTEM.GET(b, b); (* dynamic link *)
DEC(a); DEC(c)
ELSE c := 0
END
UNTIL c = 0
END ShowStack;
PROCEDURE (a: Action) Do; (* delayed trap window open *)
BEGIN
Kernel.SetTrapGuard(TRUE);
OpenViewer(a.text, "#Dev:Trap", NewRuler());
Kernel.SetTrapGuard(FALSE);
END Do;
PROCEDURE GetTrapMsg(OUT msg: ARRAY OF CHAR);
VAR ref, end, a, res: INTEGER; mod: Kernel.Module; nn: Kernel.Utf8Name;
name, head, tail: Kernel.Name; errstr: ARRAY 12 OF CHAR;
key: ARRAY Kernel.nameLen * 3 + LEN(errstr) OF CHAR;
BEGIN
a := Kernel.pc; mod := Kernel.modList; msg := "";
WHILE (mod # NIL) & ((a < mod.code) OR (a >= mod.code + mod.csize)) DO mod := mod.next END;
IF mod # NIL THEN
DEC(a, mod.code); ref := mod.refs;
REPEAT Kernel.GetRefProc(ref, end, nn) UNTIL (end = 0) OR (a < end);
Utf.Utf8ToString(nn, name, res);
IF a < end THEN
Kernel.GetModName(mod, head); Librarian.lib.SplitName (head, head, tail);
Strings.IntToString(Kernel.err, errstr);
key := "#" + head + tail + ":" + name + "." + errstr;
Dialog.MapString(key, msg);
IF Dialog.mapRes IN {4, 5} THEN
key := "#" + head + ":" + tail + "." + name + "." + errstr;
Dialog.MapString(key, msg)
END;
IF ~(Dialog.mapRes IN {0, 6}) THEN msg := "" END
END
END
END GetTrapMsg;
PROCEDURE OutAdr (adr: INTEGER);
BEGIN
out.WriteString(" ("); OutString("#System:adr"); out.WriteString(" = "); WriteHex(adr); out.WriteChar(")")
END OutAdr;
PROCEDURE Trap;
VAR a0: TextModels.Attributes; action: Action;
msg: ARRAY 512 OF CHAR;
BEGIN
out.ConnectTo(TextModels.CloneOf(StdLog.buf));
a0 := out.rider.attr;
out.rider.SetAttr(TextModels.NewWeight(a0, Fonts.bold));
IF Kernel.err = 129 THEN OutString("#System:invalid WITH")
ELSIF Kernel.err = 130 THEN OutString("#System:invalid CASE")
ELSIF Kernel.err = 131 THEN OutString("#System:function without RETURN")
ELSIF Kernel.err = 132 THEN OutString("#System:type guard")
ELSIF Kernel.err = 133 THEN OutString("#System:implied type guard")
ELSIF Kernel.err = 134 THEN OutString("#System:value out of range")
ELSIF Kernel.err = 135 THEN OutString("#System:index out of range")
ELSIF Kernel.err = 136 THEN OutString("#System:string too long")
ELSIF Kernel.err = 137 THEN OutString("#System:stack overflow")
ELSIF Kernel.err = 138 THEN OutString("#System:integer overflow")
ELSIF Kernel.err = 139 THEN OutString("#System:division by zero")
ELSIF Kernel.err = 140 THEN OutString("#System:infinite real result")
ELSIF Kernel.err = 141 THEN OutString("#System:real underflow")
ELSIF Kernel.err = 142 THEN OutString("#System:real overflow")
ELSIF Kernel.err = 143 THEN
OutString("#System:undefined real result"); out.WriteString(" (");
out.WriteIntForm(Kernel.val MOD 10000H, TextMappers.hexadecimal, 4, "0", TextMappers.hideBase); out.WriteString(", ");
out.WriteIntForm(Kernel.val DIV 10000H, TextMappers.hexadecimal, 3, "0", TextMappers.hideBase); out.WriteChar(")")
ELSIF Kernel.err = 144 THEN OutString("#System:not a number")
ELSIF Kernel.err = 200 THEN OutString("#System:keyboard interrupt")
ELSIF Kernel.err = 201 THEN
OutString("#System:NIL dereference")
ELSIF Kernel.err = 202 THEN
OutString("#System:illegal instruction"); out.WriteString(": ");
out.WriteIntForm(Kernel.val, TextMappers.hexadecimal, 5, "0", TextMappers.showBase)
ELSIF Kernel.err = 203 THEN
IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN OutString("#System:NIL dereference (read)")
ELSE OutString("#System:illegal memory read"); OutAdr(Kernel.val)
END
ELSIF Kernel.err = 204 THEN
IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN OutString("#System:NIL dereference (write)")
ELSE OutString("#System:illegal memory write"); OutAdr(Kernel.val)
END
ELSIF Kernel.err = 205 THEN
IF (Kernel.val >= -4) & (Kernel.val < 65536) THEN OutString("#System:NIL procedure call")
ELSE OutString("#System:illegal execution"); OutAdr(Kernel.val)
END
ELSIF Kernel.err = 257 THEN OutString("#System:out of memory")
ELSIF Kernel.err = 10001H THEN OutString("#System:bus error")
ELSIF Kernel.err = 10002H THEN OutString("#System:address error")
ELSIF Kernel.err = 10007H THEN OutString("#System:fpu error")
ELSIF Kernel.err < 0 THEN
OutString("#System:Exception"); out.WriteChar(" ");
out.WriteIntForm(-Kernel.err, TextMappers.hexadecimal, 3, "0", TextMappers.showBase)
ELSE
OutString("#System:TRAP"); out.WriteChar(" "); out.WriteInt(Kernel.err);
IF Kernel.err = 126 THEN out.WriteString(" ("); OutString("#System:not yet implemented"); out.WriteChar(")")
ELSIF Kernel.err = 125 THEN out.WriteString(" ("); OutString("#System:call of obsolete procedure"); out.WriteChar(")")
ELSIF Kernel.err >= 100 THEN out.WriteString(" ("); OutString("#System:invariant violated"); out.WriteChar(")")
ELSIF Kernel.err >= 60 THEN out.WriteString(" ("); OutString("#System:postcondition violated"); out.WriteChar(")")
ELSIF Kernel.err >= 20 THEN out.WriteString(" ("); OutString("#System:precondition violated"); out.WriteChar(")")
END
END;
GetTrapMsg(msg);
IF msg # "" THEN out.WriteLn; out.WriteString(msg) END;
out.WriteLn; out.rider.SetAttr(a0);
out.WriteLn; ShowStack;
NEW(action); action.text := out.rider.Base();
Services.DoLater(action, Services.now);
out.ConnectTo(NIL)
END Trap;
BEGIN
Kernel.InstallTrapViewer(Trap);
empty := "";
path[0].x := refViewSize DIV 2; path[0].y := 0;
path[1].x := refViewSize; path[1].y := refViewSize DIV 2;
path[2].x := refViewSize DIV 2; path[2].y := refViewSize;
path[3].x := 0; path[3].y := refViewSize DIV 2
END DevDebug.
| Dev/Mod/Debug.odc |
MODULE DevDecoder386;
(**
project = "BlackBox"
organization = "BlackBox Framework Center"
contributors = "Niklaus Mannhart, ETH Zurich, 1992/93"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
references = ""
changes = "
- 20161104, center #142, adding a disassembler to the ocf importer
"
issues = "
- ...
"
Intel i386, i387 Decoder
Derived from a diploma thesis at ETH-Zurich by Niklaus Mannhart, 87-913-117I.
Downloaded as file Decoder.Mod from ftp://ftp.ssw.uni-linz.ac.at/pub/Oberon/.
Main changes: support for inlined TRAPs and CASE jump tables added. Bug fix in Lods.
**)
IMPORT SYSTEM, Kernel, Utf, Files, TextMappers, TextRulers, Ports, Strings, Views, TextModels,
StdDialog, Dialog, TextViews, StdLinks, TextControllers;
CONST
(* prefix *)
pCS = 2EH; pDS = 3EH; pES = 26H; pFS = 64H; pGS = 65H; pSS = 36H;
AdrSize = 67H; OpSize = 66H; none = -1;
(* addressing modes *)
Reg = 0; (* Register *)
Mem1 = 1; (* addressing mode 1 *)
Mem2 = 2; (* addressing mode 2 *)
RegImm = 3; (* immediate to register *)
MemImm = 4; (* memory to register *)
MemFull = 5; (* full 32 bit adr *)
(* i386 Register *)
EAX = 0; ECX = 1; EDX = 2; EBX = 3; ESP = 4; EBP = 5; ESI = 6; EDI = 7; (* 32 bit register *)
AX = 0; CX = 1; DX = 2; BX = 3; SP = 4; BP = 5; SI = 6; DI = 7; (* 16 bit register *)
AL = 0; CL = 1; DL = 2; BL = 3; AH = 4; CH = 5; DH = 6; BH = 7; (* 8 bit register *)
ES = 20; CS = 21; SS = 22; DS = 23; FS = 24; GS = 25; (* 6, 7 reserved *) (* Segment register *)
CR = 0; DR = 8; TR = 16;
(* i387 *)
SReal = 0; (* single real 32 bit*)
LReal = 1; (* long real 64 bit *)
EReal = 2; (* extended real 80 bit *)
WInt = 3; (* word integer 16 bit *)
SInt = 4; (* single integer 32 bit *)
LInt = 5; (* long integer 64 bit *)
Byte14 = 6; Byte28 = 7; Byte94 = 8; Byte108 = 9;
Decimal = 10; (* BCD *)
nothing = 11;
PROCEDURE NewRuler (): TextRulers.Ruler;
VAR r: TextRulers.Ruler;
BEGIN
r := TextRulers.dir.New(NIL);
TextRulers.AddTab(r, 22 * Ports.mm); TextRulers.AddTab(r, 75 * Ports.mm);
RETURN r
END NewRuler;
PROCEDURE Decode* (IN modName: ARRAY OF CHAR; inp: Files.Reader;
hs, ms, ds, cs, vs, selectProc: INTEGER;
VAR out: TextMappers.Formatter);
VAR pc, op, column, prefix, w: INTEGER;
adrPrefix, opPrefix: BOOLEAN;
procRef, procAdr, res: INTEGER; procName: Kernel.Utf8Name;
jmpTabEnd: INTEGER; meta: POINTER TO ARRAY OF BYTE;
srcRd: TextModels.Reader; from, to, lastFrom: INTEGER;
PROCEDURE Error;
BEGIN
out.WriteLn; out.WriteString("*** decode error ***")
END Error;
PROCEDURE Next (VAR b: BYTE);
BEGIN
INC(pc); inp.ReadByte(b)
END Next;
PROCEDURE GetByte (VAR byte: INTEGER);
VAR b0: BYTE;
BEGIN
Next(b0);
byte:= b0 MOD 100H
END GetByte;
PROCEDURE GetWord (VAR word: INTEGER);
VAR b0, b1: BYTE;
BEGIN
Next(b0);
Next(b1);
word := b0 MOD 100H + b1 * 100H;
END GetWord;
PROCEDURE GetDWord (VAR dword: INTEGER);
VAR b0, b1, b2, b3: BYTE;
BEGIN
Next(b0);
Next(b1);
Next(b2);
Next(b3);
dword := b0 MOD 100H + b1 MOD 100H * 100H + b2 MOD 100H * 10000H + b3 * (1000000H)
END GetDWord;
PROCEDURE WriteLn;
BEGIN
out.WriteLn; column:= 0
END WriteLn;
PROCEDURE WriteString (str: ARRAY OF CHAR);
BEGIN
out.WriteString(str)
END WriteString;
PROCEDURE Write (ch: CHAR);
BEGIN
out.WriteChar(ch)
END Write;
PROCEDURE WriteComma;
BEGIN
out.WriteString(", ")
END WriteComma;
PROCEDURE WriteTab;
BEGIN
out.WriteTab(); INC(column)
END WriteTab;
(* write byte in hexadecimal form *)
PROCEDURE WriteByte (byte: INTEGER);
VAR str: ARRAY 20 OF CHAR; showBase: BOOLEAN; width: INTEGER;
BEGIN
showBase := column >= 2;
IF showBase THEN width := 3 ELSE width := 2 END;
Strings.IntToStringForm(byte MOD 256, Strings.hexadecimal, width, "0", showBase, str);
out.WriteString(str)
END WriteByte;
(* write word in byte form, little endian notation *)
PROCEDURE WriteWord (word: LONGINT);
BEGIN
WriteByte(SHORT(word MOD 100H)); Write(" ");
WriteByte(SHORT(word DIV 100H) MOD 100H)
END WriteWord;
(* write dword in byte form, little endian notation *)
PROCEDURE WriteDWord (dword: LONGINT);
BEGIN
WriteWord(dword MOD 10000H); Write(" ");
WriteWord((dword DIV 10000H) MOD 10000H)
END WriteDWord;
(* write dword hexadecimal, with showBase = TRUE *)
PROCEDURE WriteDWHex (dword: LONGINT);
VAR str: ARRAY 20 OF CHAR;
BEGIN
Strings.IntToStringForm(dword, Strings.hexadecimal, 9, "0", TRUE, str);
out.WriteString(str)
END WriteDWHex;
PROCEDURE WriteDisp (disp: LONGINT);
BEGIN
out.WriteInt(disp);
END WriteDisp;
PROCEDURE WriteOp (opStr: ARRAY OF CHAR);
BEGIN
WriteTab; out.WriteString(opStr); out.WriteString(" ")
END WriteOp;
PROCEDURE WriteReg (reg: INTEGER);
(* w = 0: 8 bit; w = 1: 16/32 bit *)
BEGIN
IF reg >= ES (*DS*) THEN (* <<<< MH 15.3.1994 *)
IF reg = CS THEN WriteString("cs")
ELSIF reg = DS THEN WriteString("ds")
ELSIF reg = ES THEN WriteString("es")
ELSIF reg = SS THEN WriteString("ss")
ELSIF reg = FS THEN WriteString("fs")
ELSIF reg = GS THEN WriteString("gs")
ELSE Error
END
ELSIF w = 0 THEN
IF reg = 0 THEN WriteString("al")
ELSIF reg = 1 THEN WriteString("cl")
ELSIF reg = 2 THEN WriteString("dl")
ELSIF reg = 3 THEN WriteString("bl")
ELSIF reg = 4 THEN WriteString("ah")
ELSIF reg = 5 THEN WriteString("ch")
ELSIF reg = 6 THEN WriteString("dh")
ELSIF reg = 7 THEN WriteString("bh")
ELSE Error
END
ELSIF opPrefix THEN
IF reg = 0 THEN WriteString("ax")
ELSIF reg = 1 THEN WriteString("cx")
ELSIF reg = 2 THEN WriteString("dx")
ELSIF reg = 3 THEN WriteString("bx")
ELSIF reg = 4 THEN WriteString("sp")
ELSIF reg = 5 THEN WriteString("bp")
ELSIF reg = 6 THEN WriteString("si")
ELSIF reg = 7 THEN WriteString("di")
ELSE Error
END
ELSE
IF reg = 0 THEN WriteString("eax")
ELSIF reg = 1 THEN WriteString("ecx")
ELSIF reg = 2 THEN WriteString("edx")
ELSIF reg = 3 THEN WriteString("ebx")
ELSIF reg = 4 THEN WriteString("esp")
ELSIF reg = 5 THEN WriteString("ebp")
ELSIF reg = 6 THEN WriteString("esi")
ELSIF reg = 7 THEN WriteString("edi")
ELSE Error
END
END
END WriteReg;
PROCEDURE WriteAdrReg(reg: INTEGER);
BEGIN
IF adrPrefix THEN
IF reg = 0 THEN WriteString("ax")
ELSIF reg = 1 THEN WriteString("cx")
ELSIF reg = 2 THEN WriteString("dx")
ELSIF reg = 3 THEN WriteString("bx")
ELSIF reg = 4 THEN WriteString("sp")
ELSIF reg = 5 THEN WriteString("bp")
ELSIF reg = 6 THEN WriteString("si")
ELSIF reg = 7 THEN WriteString("di")
ELSE Error
END
ELSE
IF reg = 0 THEN WriteString("eax")
ELSIF reg = 1 THEN WriteString("ecx")
ELSIF reg = 2 THEN WriteString("edx")
ELSIF reg = 3 THEN WriteString("ebx")
ELSIF reg = 4 THEN WriteString("esp")
ELSIF reg = 5 THEN WriteString("ebp")
ELSIF reg = 6 THEN WriteString("esi")
ELSIF reg = 7 THEN WriteString("edi")
ELSE Error
END
END
END WriteAdrReg;
PROCEDURE WriteSpecialReg(reg: INTEGER);
BEGIN
IF reg >= TR THEN
WriteString("tr"); Write(CHR( reg-TR + ORD("0")))
ELSIF reg >= DR THEN
WriteString("dr"); Write(CHR( reg-DR + ORD("0")))
ELSE
WriteString("cr"); Write(CHR( reg-CR + ORD("0")))
END
END WriteSpecialReg;
PROCEDURE WritePrefix (prefix: INTEGER);
BEGIN
IF prefix = pCS THEN WriteString("CS:")
ELSIF prefix = pDS THEN WriteString("DS: ")
ELSIF prefix = pES THEN WriteString("ES: ")
ELSIF prefix = pFS THEN WriteString("FS: ")
ELSIF prefix = pGS THEN WriteString("GS: ")
ELSIF prefix = pSS THEN WriteString("SS: ")
ELSE
END
END WritePrefix;
PROCEDURE WriteRegReg (d, reg1, reg2: INTEGER);
BEGIN
IF d = 1 THEN
WriteReg(reg1); WriteComma; WriteReg(reg2)
ELSE
WriteReg(reg2); WriteComma; WriteReg(reg1)
END
END WriteRegReg;
PROCEDURE WriteMem (base, inx, scale: INTEGER; disp: LONGINT);
BEGIN
WritePrefix(prefix);
IF base # none THEN(* register relative *)
WriteDisp(disp);
Write("["); WriteAdrReg(base)
ELSE (* absolute *)
Write("["); WriteDisp(disp)
END ;
IF (inx # none) & ~((inx = ESP) & (base = ESP))(* !! 15.4.93 Bug? & (base # ESP) *) THEN (* indexed *)
IF scale = 0 THEN WriteString(" + 1 * ")
ELSIF scale = 1 THEN WriteString(" + 2 * ")
ELSIF scale = 2 THEN WriteString(" + 4 * ")
ELSE WriteString(" + 8* ")
END ;
WriteAdrReg(inx)
END ;
Write("]")
END WriteMem;
PROCEDURE WriteMem1 (d, reg, base: INTEGER; disp: LONGINT);
(* d = TRUE: reg, mem ; d = FALSE: mem, reg *)
BEGIN
IF d = 1 THEN
WriteReg(reg); WriteComma
END ;
WriteMem(base, none, 0, disp);
IF d = 0 THEN
WriteComma; WriteReg(reg)
END
END WriteMem1;
PROCEDURE WriteMem2 (d, reg, base, inx: INTEGER; scale: SHORTINT; disp: LONGINT);
(* d = TRUE: reg, mem; d= FALSE: mem, reg *)
BEGIN
IF d = 1 THEN
WriteReg(reg); WriteComma
END ;
WriteMem(base, inx, scale, disp);
IF d = 0 THEN
WriteComma; WriteReg(reg)
END
END WriteMem2;
PROCEDURE WriteRegImm (reg: INTEGER; imm: LONGINT; hex: BOOLEAN);
BEGIN
WriteReg(reg); WriteComma;
IF hex THEN WriteDWHex(imm) ELSE WriteDisp(imm) END
END WriteRegImm;
PROCEDURE WriteMemImm (base, inx: INTEGER; scale: SHORTINT; disp, imm: LONGINT; hex: BOOLEAN);
BEGIN
WritePrefix(prefix);
WriteMem(base, inx, scale, disp);
WriteComma;
IF hex THEN WriteDWHex(imm) ELSE WriteDisp(imm) END
END WriteMemImm;
PROCEDURE WriteRM (mode: SHORTINT; d, reg, base, inx, scale: INTEGER; disp, imm: LONGINT; hex: BOOLEAN);
BEGIN
CASE mode OF
RegImm:
WriteRegImm(reg, imm, hex)
| MemImm:
WriteMemImm(base, inx, SHORT(scale), disp, imm, hex)
| Reg:
WriteRegReg(d, reg, base)
| Mem1:
WriteMem1(d, reg, base, disp)
| Mem2:
WriteMem2(d, reg, base, inx, SHORT(scale), disp)
| MemFull:
IF d = 1 THEN
WriteReg(reg); WriteComma
END ;
WritePrefix(prefix);
Write("["); WriteDisp(disp); Write("]");
IF d = 0 THEN
WriteComma; WriteReg(reg)
END
ELSE Error
END
END WriteRM;
(* writes the jump table as undecoded block even if it contains instructions for complex CASEs *)
PROCEDURE WriteJmpTab;
VAR align, dw: INTEGER;
BEGIN
IF pc MOD 4 # 0 THEN
WriteLn; WriteDWHex(pc); Write(":"); WriteTab;
WHILE pc MOD 4 # 0 DO GetByte(align); WriteByte(align); Write(" ") END
END;
WHILE pc < jmpTabEnd - 4 DO
WriteLn; WriteDWHex(pc); Write(":"); WriteTab; GetDWord(dw); WriteDWord(dw)
END;
IF pc < jmpTabEnd THEN
WriteLn; WriteDWHex(pc); Write(":"); WriteTab;
WHILE pc < jmpTabEnd DO GetByte(align); WriteByte(align); Write(" ") END
END;
END WriteJmpTab;
PROCEDURE GetImm (w: INTEGER; VAR imm: INTEGER);
VAR byte: INTEGER;
BEGIN
IF w = 0 THEN (* 8 bit *)
GetByte(byte); WriteByte(byte); Write(" ");
IF byte >= 128 THEN byte:= byte - 256 END ;
imm:= byte
ELSIF opPrefix THEN (* 16 bit *)
GetWord(imm); WriteWord(imm); Write(" ");
IF imm >= 32768 THEN imm:= imm - 65536 END
ELSE (* 32 bit *)
GetDWord(imm); WriteDWord(imm); Write(" ")
END
END GetImm;
PROCEDURE ModRm (VAR mode: SHORTINT; VAR reg, base, inx: INTEGER; VAR scale: SHORTINT; VAR disp: INTEGER);
VAR mod, byte: INTEGER;
BEGIN
GetByte(byte); WriteByte(byte); Write(" ");
mod:= byte DIV 40H;
reg:=(byte DIV 8) MOD 8;
base:= byte MOD 8;
IF mod = 3 THEN (* reg *)
mode:= Reg; inx:= none
ELSE
IF base = 4 THEN (* escape to two bytes *)
mode:= Mem2;
GetByte(byte);
WriteByte(byte); Write(" ");
scale:= SHORT(byte DIV 40H);
inx:= (byte DIV 8) MOD 8;
base:= byte MOD 8
ELSE (* one byte addressing mode *)
mode:= Mem1; inx:= none
END ;
IF mod = 0 THEN (* no displ, or 32 bit address *)
IF base = 5 THEN (* disp32 *)
base:= none;
GetDWord(disp);
WriteDWord(disp); Write(" ")
ELSE disp:= 0
END
ELSIF mod = 1 THEN (* 8 bit displ *)
GetImm(0, disp)
ELSE (* 32 bit displacement *)
GetDWord(disp);
WriteDWord(disp); Write(" ")
END
END
END ModRm;
PROCEDURE Type1 (op: INTEGER; VAR mode: SHORTINT; VAR d, reg, base, inx: INTEGER;
VAR scale: SHORTINT; VAR disp, imm: INTEGER);
(* type 1: add, or, adc, sbb, and, sub, xor, cmp *)
BEGIN
IF op = 4 THEN
mode:= RegImm; w:= 0; reg:= AL; GetImm(0, imm)
ELSIF op = 5 THEN
mode:= RegImm; w:= 1; reg:= AX; GetImm(1, imm)
ELSE
CASE op OF
0: w:= 0; d:= 0
| 1: w:= 1; d:= 0
| 2: w:= 0; d:= 1
| 3: w:= 1; d:= 1
ELSE Error
END ;
ModRm(mode, reg, base, inx, scale, disp)
END
END Type1;
PROCEDURE Add (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("add");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, FALSE)
END Add;
PROCEDURE Push (op: INTEGER);
VAR imm: INTEGER;
BEGIN
w:= 1;
IF op = 60H THEN
IF opPrefix THEN WriteOp("pusha") ELSE WriteOp("pushad") END ;
ELSIF op = 68H THEN
IF adrPrefix THEN
GetWord(imm); WriteWord(imm)
ELSE
GetDWord(imm); WriteDWord(imm)
END ;
WriteOp("push"); WriteDisp(imm)
ELSIF op = 6AH THEN
GetImm(0, imm);
WriteOp("push"); WriteDisp(imm)
ELSIF op = 9CH THEN
IF opPrefix THEN WriteOp("pushf") ELSE WriteOp("pushfd") END ;
ELSE
WriteOp("push");
CASE op OF
6: WriteReg(ES)
| 0EH: WriteReg(CS)
| 16H: WriteReg(SS)
| 1EH: WriteReg(DS)
| 50H..57H: WriteReg(op - 50H)
ELSE Error
END
END
END Push;
PROCEDURE Push2 (op: INTEGER);
BEGIN Error (* not yet implemented *)
END Push2;
PROCEDURE Pop(op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
IF op = 61H THEN
IF opPrefix THEN WriteOp("popa") ELSE WriteOp("popad") END ;
ELSIF op = 8FH THEN
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("pop");
IF opPrefix THEN WriteString("word ptr ")
ELSE WriteString("dword ptr ")
END ;
WriteMem(base, inx, scale, disp)
ELSIF op = 9DH THEN
IF opPrefix THEN WriteOp("popf") ELSE WriteOp("popfd") END ;
ELSE
WriteOp("pop");
w := 1; (* pop takes only 16 or 32 bit ops *)
CASE op OF
7: WriteReg(ES)
| 17H: WriteReg(SS)
| 1FH: WriteReg(DS)
| 58H..5FH: WriteReg(op - 58H)
ELSE Error
END
END
END Pop;
PROCEDURE Pop2 (op: INTEGER);
BEGIN Error (* not yet implemented *)
END Pop2;
PROCEDURE Or (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op - 08H, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("or");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, TRUE)
END Or;
PROCEDURE Adc (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op -10H, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("adc");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, FALSE)
END Adc;
PROCEDURE Sbb (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op - 18H, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("sbb");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, FALSE)
END Sbb;
PROCEDURE And (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op - 20H, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("and");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, TRUE)
END And;
PROCEDURE Sub (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op - 28H, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("sub");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, FALSE)
END Sub;
PROCEDURE Xor (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op - 30H, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("xor");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, TRUE)
END Xor;
PROCEDURE Cmp (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
Type1(op - 38H, mode, d, reg, base, inx, scale, disp, imm);
WriteOp("cmp");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, FALSE)
END Cmp ;
PROCEDURE Inc (op: INTEGER);
BEGIN
WriteOp("inc"); w := 1; (* set width to 16/32 bits, bug2 *)
WriteReg(op - 40H)
END Inc;
PROCEDURE Dec (op: INTEGER);
BEGIN
WriteOp("dec");
WriteReg(op - 48H)
END Dec;
PROCEDURE Bound (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w:= 1;
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("bound");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Bound;
PROCEDURE Imul (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
w:= 1;
IF op = 69H THEN GetImm(1, imm)
ELSIF op = 6BH THEN GetImm(0, imm) (* sign extended *)
END ;
WriteOp("imul");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE);
WriteComma; WriteDisp(imm)
END Imul;
PROCEDURE Imul2 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w:= 1;
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("imul");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Imul2;
PROCEDURE Ins (op: INTEGER);
BEGIN
IF op = 6CH THEN WriteOp("insb")
ELSIF opPrefix THEN WriteOp("insw")
ELSE WriteOp("insd")
END
END Ins;
PROCEDURE Outs (op: INTEGER);
BEGIN
IF op = 6EH THEN WriteOp("outsb")
ELSIF opPrefix THEN WriteOp("outsw")
ELSE WriteOp("outsd")
END
END Outs;
PROCEDURE Jcc (op: INTEGER);
VAR disp: INTEGER;
BEGIN
GetByte(disp); WriteByte(disp);
IF disp >= 128 THEN disp:= disp - 256 END ;
CASE op OF
70H: WriteOp("jo")
| 71H: WriteOp("jno")
| 72H: WriteOp("jb")
| 73H: WriteOp("jnb")
| 74H: WriteOp("jz")
| 75H: WriteOp("jnz")
| 76H: WriteOp("jbe")
| 77H: WriteOp("jnbe")
| 78H: WriteOp("js")
| 79H: WriteOp("jns")
| 7AH: WriteOp("jp")
| 7BH: WriteOp("jnp")
| 7CH: WriteOp("jl")
| 7DH: WriteOp("jnl")
| 7EH: WriteOp("jle")
| 7FH: WriteOp("jnle")
ELSE Error
END ;
WriteDisp(disp); WriteString(" ("); WriteDWHex(pc + disp); Write(")")
END Jcc;
PROCEDURE Jcc2 (op: INTEGER);
VAR disp: INTEGER;
BEGIN
IF adrPrefix THEN
GetWord(disp); WriteWord(disp)
ELSE
GetDWord(disp); WriteDWord(disp)
END ;
CASE op OF
80H: WriteOp("jo")
| 81H: WriteOp("jno")
| 82H: WriteOp("jb")
| 83H: WriteOp("jnb"); jmpTabEnd := pc + disp
| 84H: WriteOp("jz")
| 85H: WriteOp("jnz")
| 86H: WriteOp("jbe")
| 87H: WriteOp("jnbe")
| 88H: WriteOp("js")
| 89H: WriteOp("jns")
| 8AH: WriteOp("jp")
| 8BH: WriteOp("jnp")
| 8CH: WriteOp("jl")
| 8DH: WriteOp("jnl")
| 8EH: WriteOp("jle")
| 8FH: WriteOp("jnle")
ELSE Error
END ;
WriteDisp(disp); WriteString(" ("); WriteDWHex(pc + disp); Write(")")
END Jcc2;
PROCEDURE Test (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
IF (op = 0A8H) OR (op = 0A9H) THEN
IF op = 0A8H THEN
w:= 0; reg:= AL
ELSE
w:= 1; reg:= AX
END ;
GetImm(w, imm);
mode:= RegImm
ELSE
ModRm(mode, reg, base, inx, scale, disp);
IF op = 84H THEN w:= 0
ELSE w:= 1
END
END ;
WriteOp("test");
WriteRM(mode, 0, reg, base, inx, scale, disp, imm, FALSE) (* bug1 *)
END Test;
PROCEDURE Xchg (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
IF (op >= 91H) & (op <= 97H) THEN (* xchg .ax, reg *)
w:= 1; reg:= AX; base:= op MOD 8;
mode:= Reg
ELSE
ModRm(mode, reg, base, inx, scale, disp);
IF op = 86H THEN w:= 0
ELSE w:= 1
END
END ;
WriteOp("xchg");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Xchg;
PROCEDURE Mov (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
IF (op >= 88H) & (op <= 8BH) THEN
Type1(op - 88H, mode, d, reg, base, inx, scale, disp, imm)
ELSIF (op >= 0B0H) & (op <= 0B7H) THEN
mode:= RegImm; w:= 0; reg:= op - 0B0H; GetImm(w, imm)
ELSIF (op >= 0B8H) & (op <= 0BFH) THEN
mode:= RegImm; w:= 1; reg:= op - 0B8H; GetImm(w, imm)
ELSIF (op >= 0A0H) & (op <= 0A3H) THEN
CASE op OF
0A0H: w:= 0; d:= 1; reg:= AL
| 0A1H: w:= 1; d:= 1; reg:= AX
| 0A2H: w:= 0; d:= 0; reg:= AL
| 0A3H: w:= 1; d:= 0; reg:= AX
END ;
mode:= MemFull;
IF adrPrefix THEN
GetWord(disp); WriteWord(disp)
ELSE
GetDWord(disp); WriteDWord(disp)
END
ELSIF op = 8CH THEN (* mov mem, seg *)
w:= 1; d:= 0; opPrefix:= TRUE;
ModRm(mode, reg, base, inx, scale, disp);
reg:= reg + ES (* reg is a segment register *)
ELSIF op = 8EH THEN (* mov seg, mem *)
w:= 1; d:= 1; opPrefix:= TRUE;
ModRm(mode, reg, base, inx, scale, disp);
reg:= reg + ES (* reg is segment register *)
ELSIF (op = 0C6H) OR (op = 0C7H) THEN
d:= 1;
IF op = 0C6H THEN w:= 0
ELSE w:= 1
END ;
ModRm(mode, reg, base, inx, scale, disp);
IF mode = Reg THEN
reg:= base; mode:= RegImm
ELSE mode:= MemImm
END ;
GetImm(w, imm)
END ;
WriteOp("mov");
WriteRM(mode, d, reg, base, inx, scale, disp, imm, FALSE)
END Mov;
PROCEDURE Mov2 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN (* reg, base only used, because Mov2 op codes contains special registers (debug/test/controll) *)
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("mov");
CASE op OF
20H: WriteReg(base); WriteComma; WriteSpecialReg(CR+reg)
| 21H: WriteReg(base); WriteComma; WriteSpecialReg(DR+reg)
| 22H: WriteSpecialReg(CR+reg); WriteComma; WriteReg(base)
| 23H: WriteSpecialReg(DR+reg); WriteComma; WriteReg(base)
| 24H: WriteReg(base); WriteComma; WriteSpecialReg(TR+reg)
| 26H: WriteSpecialReg(TR+reg); WriteComma; WriteReg(base)
ELSE Error
END
END Mov2;
PROCEDURE Movzx (op: INTEGER);
VAR VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("movzx");
WriteReg(reg); WriteComma;
IF mode = Reg THEN WriteReg(base)
ELSE
IF op = 0B6H THEN WriteString("byte ptr ")
ELSE WriteString("word ptr ")
END ;
WriteMem(base, inx, scale, disp)
END
END Movzx;
PROCEDURE Movsx (op: INTEGER);
VAR VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("movsx");
w:= 1;
WriteReg(reg); WriteComma;
IF mode = Reg THEN
IF op = 0BEH THEN
w:= 0; WriteReg(base)
ELSE
w:= 1; opPrefix:= TRUE; WriteReg(base)
END ;
ELSE
IF op = 0BEH THEN WriteString("byte ptr ")
ELSE WriteString("word ptr ")
END ;
WriteMem(base, inx, scale, disp)
END
END Movsx;
PROCEDURE Lea (op: INTEGER);
VAR reg, base, inx, byte, trap: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
IF mode = Reg THEN
byte := 3 * 40H + reg * 8 + base; (* reconstruct 2nd byte *)
IF byte = 0F0H THEN GetByte(trap); WriteByte(trap); WriteOp("illegal");
WriteString("(TRAP "); out.WriteInt(trap); WriteString(")"); RETURN
ELSIF (byte > 0E0H) & (byte <= 0EFH) THEN WriteOp("illegal");
WriteString("(TRAP "); out.WriteInt(0E0H - byte); WriteString(")"); RETURN
END
END;
w:= 1;
WriteOp("lea");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, TRUE)
END Lea;
PROCEDURE Call (op: INTEGER);
VAR imm, sel: INTEGER;
BEGIN
IF op = 0E8H THEN
IF adrPrefix THEN
GetWord(imm); WriteWord(imm)
ELSE
GetDWord(imm); WriteDWord(imm)
END
ELSE (* intrasegment *)
(* Update Start -- 7.08.96 prk *)
IF adrPrefix THEN
(* GetWord(sel); GetWord(imm);
WriteWord(sel); Write(" "); WriteWord(imm) *)
GetWord(imm); WriteWord(imm)
ELSE
(* GetWord(sel); GetDWord(imm);
WriteWord(sel); Write(" "); WriteDWord(imm) *)
GetDWord(imm); WriteDWord(imm)
END ;
GetWord(sel); Write(" "); WriteWord(sel);
(* Update End -- 7.08.96 prk *)
END ;
WriteOp("call");
IF op = 09AH THEN
WriteDisp(sel); Write(":")
END ;
WriteDisp(imm); WriteString(" ("); WriteDWHex(pc + imm); Write(")")
END Call;
PROCEDURE Movs (op: INTEGER);
BEGIN
IF op = 0A4H THEN WriteOp("movsb")
ELSIF (op = 0A5H) & opPrefix THEN WriteOp("movsw")
ELSIF op = 0A5H THEN WriteOp("movsd")
ELSE Error
END
END Movs;
PROCEDURE Cmps (op: INTEGER);
BEGIN
IF op = 0A6H THEN WriteOp("cmpsb")
ELSIF (op = 0A7H) & opPrefix THEN WriteOp("cmpsb")
ELSIF op = 0A7H THEN WriteOp("cmpsw")
ELSE Error
END
END Cmps;
PROCEDURE Stos (op: INTEGER);
BEGIN
IF op = 0AAH THEN WriteOp("stosb")
ELSIF (op = 0ABH) & opPrefix THEN WriteOp("stosw")
ELSIF op = 0ABH THEN WriteOp("stosd")
ELSE Error
END
END Stos;
PROCEDURE Lods (op: INTEGER);
BEGIN
IF op = 0ACH THEN WriteOp("lodsb")
ELSIF (op = 0ADH) & opPrefix THEN WriteOp("lodsw")
ELSIF op = 0ADH THEN WriteOp("lodsd")
ELSE Error
END
END Lods;
PROCEDURE Scas (op: INTEGER);
BEGIN
IF op = 0AEH THEN WriteOp("scasb")
ELSIF (op = 0AFH) & opPrefix THEN WriteOp("scasw")
ELSIF op = 0AFH THEN WriteOp("scasd")
ELSE Error
END
END Scas;
PROCEDURE Ret (op: INTEGER);
VAR imm: INTEGER;
BEGIN
IF (op = 0C2H) OR (op = 0CAH) THEN
GetWord(imm); WriteWord(imm)
END ;
IF (op = 0CAH) OR (op = 0CBH) THEN WriteOp("ret far")
ELSE WriteOp("ret")
END ;
IF (op = 0C2H) OR (op = 0CAH) THEN WriteDisp(imm) END
END Ret;
PROCEDURE Enter (op: INTEGER);
VAR l: INTEGER; b: INTEGER;
BEGIN
GetWord(l); WriteWord(l); Write(" ");
GetByte(b); WriteByte(b); Write(" ");
WriteOp("enter");
WriteDisp(l); WriteComma; WriteDisp(b)
END Enter;
PROCEDURE Les (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("les");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Les;
PROCEDURE Lds (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("lds");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Lds;
PROCEDURE Ldseg (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
IF op = 0B2H THEN WriteOp("lss")
ELSIF op = 0B4H THEN WriteOp("lfs")
ELSE WriteOp("lgs")
END ;
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Ldseg;
PROCEDURE Int (op: INTEGER);
VAR imm: INTEGER;
BEGIN
IF op = 0CDH THEN
GetByte(imm); WriteByte(imm)
ELSE imm := 3
END ;
WriteOp("int");
WriteDisp(imm)
END Int;
PROCEDURE Loop (op: INTEGER);
VAR imm: INTEGER;
BEGIN
GetImm(0, imm);
CASE op OF
0E0H: WriteOp("loopne")
| 0E1H: WriteOp("loope")
| 0E2H: WriteOp("loop")
| 0E3H: WriteOp("jcxz")
ELSE Error
END ;
WriteDisp(imm)
END Loop;
PROCEDURE InOut (op: INTEGER);
VAR port: INTEGER; in, dx: BOOLEAN;
BEGIN
in := op MOD 4 < 2;
dx := op MOD 16 >= 8;
IF ~dx THEN GetByte(port); WriteByte(port) END ;
IF in THEN WriteOp("in") ELSE WriteOp("out") END ;
IF ~in & dx THEN WriteString("dx,")
ELSIF ~in THEN WriteDisp(port); WriteComma END ;
IF ODD(op) THEN
IF opPrefix THEN WriteString("ax") ELSE WriteString("eax") END
ELSE WriteString("al") END ;
IF in THEN
IF dx THEN WriteString(",dx") ELSE WriteString(","); WriteDisp(port) END
END
END InOut;
PROCEDURE Jmp (op: INTEGER);
VAR imm: INTEGER; byte: INTEGER;
BEGIN
IF (op = 0E9H) OR (op = 0EAH) THEN
GetDWord(imm); WriteDWord(imm)
ELSE
GetByte(byte); WriteByte(byte);
IF byte >= 128 THEN imm:= byte - 256
ELSE imm:= byte
END ;
END ;
IF op = 0EAH THEN WriteOp("jmp far")
ELSE WriteOp("jmp")
END ;
WriteDisp(imm); WriteString (" ("); WriteDWHex(pc + imm); Write(")")
END Jmp;
PROCEDURE Lar (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("lar");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Lar;
PROCEDURE Lsl (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
WriteOp("lsl");
WriteRM(mode, 1, reg, base, inx, scale, disp, 0, FALSE)
END Lsl;
PROCEDURE Setcc (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w:= 0; (* always 8 bit wide *)
ModRm(mode, reg, base, inx, scale, disp);
(* not nice but necessary -> no more constant memory for case table *)
IF op = 90H THEN WriteOp("seto")
ELSIF op = 91H THEN WriteOp("setno")
ELSIF op = 92H THEN WriteOp("setb/setc/setnae")
ELSIF op = 93H THEN WriteOp("setnb/setae/setnc")
ELSIF op = 94H THEN WriteOp("setz/sete")
ELSIF op = 95H THEN WriteOp("setnz/setne")
ELSIF op = 96H THEN WriteOp("setbe/setna")
ELSIF op = 97H THEN WriteOp("setnbe/seta")
ELSIF op = 98H THEN WriteOp("sets")
ELSIF op = 99H THEN WriteOp("setns")
ELSIF op = 9AH THEN WriteOp("setp/setpe")
ELSIF op = 9BH THEN WriteOp("setnp/setnp")
ELSIF op = 9CH THEN WriteOp("setl/setnge")
ELSIF op = 9DH THEN WriteOp("setnl/setge")
ELSIF op = 9EH THEN WriteOp("setle/setng")
ELSIF op = 9FH THEN WriteOp("setnle/setg")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp)
END
END Setcc;
PROCEDURE Bit (op: INTEGER);
VAR reg, base, inx, d: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w:= 1;
ModRm(mode, reg, base, inx, scale, disp);
IF op = 0A3H THEN
WriteOp("bt"); d:= 1
ELSIF op = 0ABH THEN
WriteOp("bts"); d:= 1
ELSIF op = 0B3H THEN
WriteOp("btr"); d:= 1
ELSIF op = 0BBH THEN
WriteOp("btc"); d:= 1
ELSIF op = 0BCH THEN
WriteOp("bsf"); d:= 1
ELSE
WriteOp("bsr"); d:= 1
END ;
IF mode = Reg THEN WriteRM(Reg, d, base, reg, none, 0, 0, 0, FALSE)
ELSE WriteRM(mode, d, reg, base, inx, scale, disp, 0, FALSE)
END
END Bit;
PROCEDURE Shift (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
IF (op = 0A4H) OR (op = 0ACH) THEN (* immediate byte *)
w:= 0; GetImm(0, imm)
ELSE
imm := -1
END ;
IF (op = 0A4H) OR (op = 0A5H) THEN WriteOp("shld")
ELSIF (op = 0ACH) OR (op = 0ADH) THEN WriteOp("shrd")
ELSE Error
END ;
w := 1;
WriteRM(mode, 0, reg, base, inx, scale, disp, imm, FALSE);
WriteComma;
IF imm = -1 THEN WriteString("cl")
ELSE WriteDisp(imm)
END
END Shift;
PROCEDURE Grp1 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
IF op = 80H THEN (* byte *)
w:= 0; GetImm(0, imm)
ELSIF op = 81H THEN (* full immediate *)
w:= 1; GetImm(w, imm)
ELSE (* op = 83H, signed extendes *)
w:= 1; GetImm(0, imm)
END ;
CASE reg OF
0: WriteOp("add")
| 1: WriteOp("or")
| 2: WriteOp("adc")
| 3: WriteOp("sbb")
| 4: WriteOp("and")
| 5: WriteOp("sub")
| 6: WriteOp("xor")
| 7: WriteOp("cmp")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp)
END ;
WriteComma;
IF (reg = 0) OR (reg = 2) OR (reg = 3) OR (reg = 5) OR (reg = 7) THEN WriteDisp(imm)
ELSE WriteDWHex(imm)
END
END Grp1;
PROCEDURE Grp2 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
IF (op >= 0D0H) & (op <= 0D3H) THEN
IF (op = 0D0H) OR (op = 0D2H) THEN w:= 0
ELSE w:= 1
END
ELSE
IF op = 0C0H THEN w:= 0
ELSE w:= 1
END ;
GetImm(0, imm); (* only 8 bit possible *)
END ;
CASE reg OF
0: WriteOp("rol")
| 1: WriteOp("ror")
| 2: WriteOp("rcl")
| 3: WriteOp("rcr")
| 4: WriteOp("shl/sal")
| 5: WriteOp("shr")
| 7: WriteOp("sar")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp)
END ;
WriteComma;
IF (op = 0D0H) OR (op = 0D1H) THEN Write("1")
ELSIF (op = 0D2H) OR (op = 0D3H) THEN WriteString("cl")
ELSE WriteDisp(imm)
END
END Grp2;
PROCEDURE Grp3 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
ModRm(mode, reg, base, inx, scale, disp);
IF op = 0F6H THEN w:= 0
ELSE w:= 1
END ;
IF reg = 0 (* test *) THEN GetImm(w, imm) END ;
CASE reg OF
0: WriteOp("test")
| 2: WriteOp("not")
| 3: WriteOp("neg")
| 4: WriteOp("mul")
| 5: WriteOp("imul")
| 6: WriteOp("div")
| 7: WriteOp("idiv")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp)
END ;
IF reg = 0 THEN
WriteComma; WriteDisp(imm)
END
END Grp3;
PROCEDURE Grp4 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w:= 0;
ModRm(mode, reg, base, inx, scale, disp);
IF reg = 0 THEN WriteOp("inc")
ELSE WriteOp("dec")
END ;
IF mode # Reg THEN
WriteString("byte ptr "); WriteMem(base, inx, scale, disp)
ELSE WriteReg(base)
END
END Grp4;
PROCEDURE Grp5 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w:= 1;
ModRm(mode, reg, base, inx, scale, disp);
IF reg = 0 THEN WriteOp("inc")
ELSIF reg = 1 THEN WriteOp("dec")
ELSIF reg = 2 THEN WriteOp("call")
ELSIF reg = 3 THEN WriteOp("call far")
ELSIF reg = 4 THEN WriteOp("jmp")
ELSIF reg = 5 THEN WriteOp("jmp far")
ELSIF reg = 6 THEN WriteOp("push")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp);
IF (pc < jmpTabEnd) & (mode = Mem2) THEN WriteJmpTab END
END
END Grp5;
PROCEDURE Grp6 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w := 1;
ModRm(mode, reg, base, inx, scale, disp);
CASE reg OF
| 0: WriteOp("sldt")
| 1: WriteOp("str")
| 2: WriteOp("lldt")
| 3: WriteOp("ltr")
| 4: WriteOp("verr")
| 6: WriteOp("verw")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp)
END ;
END Grp6;
PROCEDURE Grp7 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
w := 1;
ModRm(mode, reg, base, inx, scale, disp);
CASE reg OF
| 0: WriteOp("sgdt")
| 1: WriteOp("sidt")
| 2: WriteOp("lgdt")
| 3: WriteOp("lidt")
| 4: WriteOp("smsw")
| 6: WriteOp("lmsw")
| 7: WriteOp("invlpg")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp)
END ;
END Grp7;
PROCEDURE Grp8 (op: INTEGER);
VAR reg, base, inx: INTEGER; scale, mode: SHORTINT; disp, imm: INTEGER;
BEGIN
w:= 1;
ModRm(mode, reg, base, inx, scale, disp);
GetImm(0, imm); (* always 8 bit wide *)
CASE reg OF
4: WriteOp("bt")
| 5: WriteOp("bts")
| 6: WriteOp("btr")
| 7: WriteOp("btc")
ELSE Error
END ;
IF mode = Reg THEN WriteReg(base)
ELSE WriteMem(base, inx, scale, disp)
END ;
WriteComma; WriteDisp(imm)
END Grp8;
PROCEDURE Escape (op: INTEGER);
BEGIN
GetByte(op); WriteByte(op); Write(" ");
IF op < 40H THEN (* because of DOSOberon *)
CASE op OF
0:
Grp6(op)
| 1:
Grp7(op)
| 2:
Lar(op)
| 3:
Lsl(op)
| 6:
WriteOp("clts")
| 20H..24H, 26H:
Mov2(op)
ELSE Error
END
ELSIF op < 0C0H THEN
CASE op OF
| 80H..8FH:
Jcc2(op)
| 90H..9FH:
Setcc(op)
| 0A0H, 0A8H:
Push2(op)
| 0A1H, 0A9H:
Pop2(op)
| 0A2H:
WriteOp ("cpuid")
| 0A3H, 0ABH, 0B3H, 0BBH..0BDH:
Bit(op)
| 0A4H, 0A5H, 0ACH, 0ADH:
Shift(op)
| 0AFH:
Imul2(op)
| 0B2H, 0B4H, 0B5H:
Ldseg(op)
| 0B6H, 0B7H:
Movzx(op)
| 0BEH, 0BFH:
Movsx(op)
| 0BAH:
Grp8(op)
ELSE Error
END
ELSE Error
END
END Escape;
(* floating point i387 instruction set *)
PROCEDURE WriteFReg (freg: INTEGER);
BEGIN
IF freg = 0 THEN WriteString("st")
ELSE
WriteString("st("); WriteDisp(freg); Write(")")
END
END WriteFReg;
PROCEDURE WriteFloat (form: SHORTINT; base, inx: INTEGER; scale: SHORTINT; disp: LONGINT);
BEGIN
(* not nice but necessary -> no more constant memory for case table *)
IF form = SReal THEN WriteString("single ")
ELSIF form = LReal THEN WriteString("double ")
ELSIF form = EReal THEN WriteString("extended ")
ELSIF form = WInt THEN WriteString("word ")
ELSIF form = SInt THEN WriteString("short ")
ELSIF form = LInt THEN WriteString("long ")
ELSIF (form = Byte14) OR (form = Byte94) THEN WriteString("small ")
ELSIF (form = Byte28) OR (form = Byte108) THEN WriteString("big ")
ELSIF form = Decimal THEN WriteString("bcd ")
END ;
WriteMem(base, inx, scale, disp)
END WriteFloat;
PROCEDURE Float0 (op: INTEGER);
(* op is 0D8H *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN (* memory *)
CASE stat OF
0: WriteOp("fadd")
| 1: WriteOp("fmul")
| 2: WriteOp("fcom")
| 3: WriteOp("fcomp")
| 4: WriteOp("fsub")
| 5: WriteOp("fsubr")
| 6: WriteOp("fdiv")
| 7: WriteOp("fdivr")
ELSE Error
END ;
WriteFloat(SReal, base, inx, scale, disp)
ELSE
CASE stat OF
0: WriteOp("fadd"); WriteFReg(0); WriteComma
| 1: WriteOp("fmul"); WriteFReg(0); WriteComma
| 2: WriteOp("fcom")
| 3: WriteOp("fcomp")
| 4: WriteOp("fsub"); WriteFReg(0); WriteComma
| 5: WriteOp("fsubr"); WriteFReg(0); WriteComma
| 6: WriteOp("fdiv"); WriteFReg(0); WriteComma
| 7: WriteOp("fdivr"); WriteFReg(0); WriteComma
ELSE Error
END ;
WriteFReg(base)
END
END Float0;
PROCEDURE Float1 (op: INTEGER);
(* op is 0D9H *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN
CASE stat OF
0: WriteOp("fld")
| 2: WriteOp("fst")
| 3: WriteOp("fstp")
| 4: WriteOp("fldenv")
| 5: WriteOp("fldcw")
| 6: WriteOp("fstenv")
| 7: WriteOp("fstcw")
ELSE Error
END ;
IF (stat = 4) OR (stat = 6) THEN
IF opPrefix THEN WriteFloat(Byte14, base, inx, scale, disp)
ELSE WriteFloat(Byte28, base, inx, scale, disp)
END
ELSIF (stat = 2) OR (stat = 3) THEN WriteFloat(SReal, base, inx, scale, disp)
ELSE WriteFloat(nothing, base, inx, scale, disp)
END
ELSIF stat = 0 THEN
WriteOp("fld"); WriteFReg(base)
ELSIF stat = 1 THEN
WriteOp("fxch"); WriteFReg(base)
ELSE
stat:= stat * 8 + base;
IF stat = 10H THEN WriteOp("fnop")
ELSE
CASE stat OF
20H: WriteOp("fchs")
| 21H: WriteOp("fabs")
| 24H: WriteOp("ftst")
| 25H: WriteOp("fxam")
| 28H: WriteOp("fld1")
| 29H: WriteOp("fldl2t")
| 2AH: WriteOp("fldl2e")
| 2BH: WriteOp("fldpi")
| 2CH: WriteOp("fldlg2")
| 2DH: WriteOp("fldln2")
| 2EH: WriteOp("fldz")
| 30H: WriteOp("f2xm1")
| 31H: WriteOp("fyl2x")
| 32H: WriteOp("fptan")
| 33H: WriteOp("fpatan")
| 34H: WriteOp("fxtract")
| 35H: WriteOp("fprem1")
| 36H: WriteOp("fdecstp")
| 37H: WriteOp("fincstp")
| 38H: WriteOp("fprem")
| 39H: WriteOp("fyl2xp1")
| 3AH: WriteOp("fsqrt")
| 3BH: WriteOp("fsincos")
| 3CH: WriteOp("frndint")
| 3DH: WriteOp("fscale")
| 3EH: WriteOp("fsin")
| 3FH: WriteOp("fcos")
ELSE Error
END
END
END
END Float1;
PROCEDURE Float2 (op: INTEGER);
(* op is 0DAH *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN
CASE stat OF
0: WriteOp("fiadd")
| 1: WriteOp("fimul")
| 2: WriteOp("ficom")
| 3: WriteOp("ficomp")
| 4: WriteOp("fisub")
| 5: WriteOp("fisubr")
| 6: WriteOp("fidiv")
| 7: WriteOp("fidivr")
ELSE Error
END ;
WriteFloat(SInt, base, inx, scale, disp)
ELSIF stat = 5 THEN WriteOp("fucompp")
ELSE Error
END
END Float2;
PROCEDURE Float3 (op: INTEGER);
(* op is 0DBH *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN
CASE stat OF
0: WriteOp("fild")
| 2: WriteOp("fist")
| 3: WriteOp("fistp")
| 5: WriteOp("fld")
| 7: WriteOp("fstp")
ELSE Error
END ;
IF (stat = 5) OR (stat = 7) THEN WriteFloat(EReal, base, inx, scale, disp)
ELSE WriteFloat(SInt, base, inx, scale, disp)
END
ELSIF base = 2 THEN WriteOp("fclex")
ELSIF base = 3 THEN WriteOp("finit")
ELSE Error
END
END Float3;
PROCEDURE Float4 (op: INTEGER);
(* op is 0DCH *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN
CASE stat OF
0: WriteOp("fadd")
| 1: WriteOp("fmul")
| 2: WriteOp("fcom")
| 3: WriteOp("fcomp")
| 4: WriteOp("fsub")
| 5: WriteOp("fsubr")
| 6: WriteOp("fdiv")
| 7: WriteOp("fdivr")
ELSE Error
END ;
WriteFloat(LReal, base, inx, scale, disp)
ELSE
CASE stat OF
0: WriteOp("fadd")
| 1: WriteOp("fmul")
| 4: WriteOp("fsubr")
| 5: WriteOp("fsub")
| 6: WriteOp("fdivr")
| 7: WriteOp("fdiv")
ELSE Error
END ;
WriteFReg(base); WriteComma; WriteFReg(0)
END
END Float4;
PROCEDURE Float5 (op: INTEGER);
(* op is 0DDH *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN (* memory *)
CASE stat OF
0: WriteOp("fld")
| 2: WriteOp("fst")
| 3: WriteOp("fstp")
| 4: WriteOp("frstor")
| 6: WriteOp("fsave")
| 7: WriteOp("fstsw")
ELSE Error
END ;
IF (stat = 4) OR (stat = 6) THEN
IF opPrefix THEN WriteFloat(Byte94, base, inx, scale, disp)
ELSE WriteFloat(Byte108, base, inx, scale, disp)
END
ELSIF stat = 7 THEN WriteFloat(nothing, base, inx, scale, disp)
ELSE WriteFloat(LReal, base, inx, scale, disp)
END
ELSE
CASE stat OF
0: WriteOp("ffree")
| 2: WriteOp("fst")
| 3: WriteOp("fstp")
| 4: WriteOp("fucom")
| 5: WriteOp("fucomp")
ELSE Error
END ;
WriteFReg(base)
END
END Float5;
PROCEDURE Float6(op: INTEGER);
(* op is 0DEH *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN (* memory *)
CASE stat OF
0: WriteOp("fiadd")
| 1: WriteOp("fimul")
| 2: WriteOp("ficom")
| 3: WriteOp("ficomp")
| 4: WriteOp("fisub")
| 5: WriteOp("fisubr")
| 6: WriteOp("fidiv")
| 7: WriteOp("fidivr")
ELSE Error
END ;
WriteFloat(WInt, base, inx, scale, disp)
ELSE
CASE stat OF
0: WriteOp("faddp")
| 1: WriteOp("fmulp")
| 3: WriteOp("fcompp")
| 4: WriteOp("fsubrp")
| 5: WriteOp("fsubp")
| 6: WriteOp("fdivrp")
| 7: WriteOp("fdivp")
ELSE Error
END ;
IF stat # 3 THEN
WriteFReg(base); WriteComma; WriteFReg(0)
END
END
END Float6;
PROCEDURE Float7(op: INTEGER);
(* op is 0DFH *)
VAR stat, base, inx: INTEGER; scale, mode: SHORTINT; disp: INTEGER;
BEGIN
ModRm(mode, stat, base, inx, scale, disp);
IF mode # Reg THEN (* memory *)
CASE stat OF
0, 5: WriteOp("fild")
| 2: WriteOp("fist")
| 3, 7: WriteOp("fistp")
| 4: WriteOp("fbld")
| 6: WriteOp("fbstp")
ELSE Error
END ;
IF (stat = 4) OR (stat = 6) THEN WriteFloat(Decimal, base, inx, scale, disp)
ELSIF (stat = 5) OR (stat = 7) THEN WriteFloat(LInt, base, inx, scale, disp)
ELSE WriteFloat(WInt, base, inx, scale, disp)
END
ELSIF stat = 4 THEN WriteOp("fstsw"); WriteString("ax")
ELSE Error
END
END Float7;
PROCEDURE Prefix (VAR op: INTEGER);
BEGIN
IF (op = pCS) OR (op = pDS) OR (op = pES) OR (op = pFS) OR (op = pGS) OR (op = pSS) THEN
prefix:= op;
WriteByte(op); Write("|");
GetByte(op);
Prefix(op)
ELSIF op = AdrSize THEN
adrPrefix:= TRUE;
WriteByte(op); Write("|");
GetByte(op);
Prefix(op)
ELSIF op = OpSize THEN
opPrefix:= TRUE;
WriteByte(op); Write("|");
GetByte(op);
Prefix(op)
END
END Prefix;
PROCEDURE DecodeInstruction;
BEGIN
GetByte(op);
Prefix(op);
WriteByte(op); Write(" ");
IF op < 40H THEN (* because of DOSOberon *)
CASE op OF
0..5:
Add(op)
| 6, 0EH, 16H, 1EH:
Push(op)
| 7, 17H, 1FH:
Pop(op)
| 8..0DH:
Or(op)
| 0FH:
Escape(op)
| 10H..15H:
Adc(op)
| 18H..1DH:
Sbb(op)
| 20H..25H:
And(op)
| 27H:
WriteOp("daa")
| 28H..2DH:
Sub(op)
| 2FH:
WriteOp("das")
| 30H..35H:
Xor(op)
| 37H:
WriteOp("aaa")
| 38H..3DH:
Cmp(op)
| 3FH:
WriteOp("aas")
ELSE Error
END
ELSIF op < 80H THEN
CASE op OF
40H..47H:
Inc(op)
| 48H..4FH:
Dec(op)
| 50H..57H, 60H, 68H, 6AH:
Push(op)
| 58H..5FH, 61H:
Pop(op)
| 62H:
Bound(op)
| 69H, 6BH:
Imul(op)
| 6CH, 6DH:
Ins(op)
| 6EH, 06FH:
Outs(op)
| 70H..7FH:
Jcc(op)
ELSE Error
END
ELSIF op < 0C0H THEN
CASE op OF
80H..81H, 83H:
Grp1(op)
| 84H..85H:
Test(op)
| 86H..87H, 91H..97H:
Xchg(op)
| 88H..8CH, 8EH, 0A0H..0A3H, 0B0H..0BFH:
Mov(op)
| 8DH:
Lea(op)
| 8FH, 9DH:
Pop(op)
| 90H:
WriteOp("nop")
| 98H:
WriteOp("cbw")
| 99H:
WriteOp("cwd")
| 9AH:
Call(op)
| 9BH:
WriteOp("wait")
| 9CH:
Push(op)
| 9EH:
WriteOp("sahf")
| 9FH:
WriteOp("lahf")
| 0A4H..0A5H:
Movs(op)
| 0A6H..0A7H:
Cmps(op)
| 0A8H..0A9H:
Test(op)
| 0AAH..0ABH:
Stos(op)
| 0ACH..0ADH:
Lods(op)
| 0AEH..0AFH:
Scas(op)
ELSE Error
END
ELSIF op <= 0FFH THEN
CASE op OF
0C0H..0C1H:
Grp2(op)
| 0C2H..0C3H, 0CAH, 0CBH:
Ret(op)
| 0C4H:
Les(op)
| 0C5H:
Lds(op)
| 0C6H..0C7H:
Mov(op)
| 0C8H:
Enter(op)
| 0C9H:
WriteOp("leave")
| 0CCH..0CDH:
Int(op)
| 0CEH:
WriteOp("into")
| 0CFH:
WriteOp("iret")
| 0D0H..0D3H:
Grp2(op)
| 0D4H:
WriteOp("aam")
| 0D5H:
WriteOp("aad")
| 0D7H:
WriteOp("xlat")
| 0D8H:
Float0(op)
| 0D9H, 0D6H:
Float1(op)
| 0DAH:
Float2(op)
| 0DBH:
Float3(op)
| 0DCH:
Float4(op)
| 0DDH:
Float5(op)
| 0DEH:
Float6(op)
| 0DFH:
Float7(op)
| 0E0H..0E3H:
Loop(op) (* and jcxz *)
| 0E4H..0E7H, 0ECH..0EFH:
InOut(op)
| 0E8H:
Call(op)
| 0E9H..0EBH:
Jmp(op)
| 0F0H:
WriteOp("Lock")
| 0F2H:
WriteOp("repne")
| 0F3H:
WriteOp("rep")
| 0F4H:
WriteOp("hlt")
| 0F5H:
WriteOp("cmc")
| 0F6H..0F7H:
Grp3(op)
| 0F8H:
WriteOp("clc")
| 0F9H:
WriteOp("stc")
| 0FAH:
WriteOp("cli")
| 0FBH:
WriteOp("sti")
| 0FCH:
WriteOp("cld")
| 0FDH:
WriteOp("std")
| 0FEH:
Grp4(op)
| 0FFH:
Grp5(op)
ELSE Error
END
ELSE Error
END;
WriteLn
END DecodeInstruction;
PROCEDURE OpenSourceReader(): TextModels.Reader;
VAR v: Views.View; loc: Files.Locator; name: Files.Name;
BEGIN
StdDialog.GetSubLoc(modName, "Mod", loc, name);
v := Views.OldView(loc, name);
IF (v # NIL) & (v.ThisModel() # NIL) & (v.ThisModel() IS TextModels.Model) THEN
RETURN v.ThisModel()(TextModels.Model).NewReader(NIL)
ELSE
RETURN NIL
END
END OpenSourceReader;
PROCEDURE WriteSrc;
VAR ref, pos, ad, d: INTEGER; ch: SHORTCHAR; name: Kernel.Utf8Name;
PROCEDURE RefCh (VAR ref: INTEGER; OUT ch: SHORTCHAR);
BEGIN
SYSTEM.GET(ref, ch); INC(ref)
END RefCh;
PROCEDURE RefNum (VAR ref: INTEGER; OUT x: INTEGER);
VAR s, n: INTEGER; ch: SHORTCHAR;
BEGIN
s := 0; n := 0; RefCh(ref, ch);
WHILE ORD(ch) >= 128 DO INC(n, ASH(ORD(ch) - 128, s) ); INC(s, 7); RefCh(ref, ch) END;
x := n + ASH(ORD(ch) MOD 64 - ORD(ch) DIV 64 * 64, s)
END RefNum;
PROCEDURE RefName (VAR ref: INTEGER; OUT n: Kernel.Utf8Name);
VAR i: INTEGER; ch: SHORTCHAR;
BEGIN
i := 0; RefCh(ref, ch);
WHILE ch # 0X DO n[i] := ch; INC(i); RefCh(ref, ch) END;
n[i] := 0X
END RefName;
PROCEDURE WriteSrcLink;
VAR ch: CHAR; attr: TextModels.Attributes; left, right: StdLinks.Link; fromStr, toStr: ARRAY 20 OF CHAR;
BEGIN
Strings.IntToString(from, fromStr);
Strings.IntToString(to, toStr);
left := StdLinks.dir.NewLink("DevDecoder386.ShowSrc('" + modName + "', "
+ fromStr + ", " + toStr + ")");
right := StdLinks.dir.NewLink("");
attr := out.rider.attr;
out.rider.SetAttr(TextModels.NewColor(attr, Ports.blue));
out.WriteView(left);
srcRd.SetPos(from);
WHILE srcRd.Pos() < to DO
srcRd.ReadChar(ch);
IF ch = 09X THEN WriteString(" ") (* a TAB would use the ruler's tab positions *)
ELSIF ch = 0DX THEN
WHILE (ch <= " ") & (srcRd.Pos() < to) DO srcRd.ReadChar(ch) END; (* trim left *)
IF ch > " " THEN WriteLn; Write(ch) END
ELSIF ch >= " " THEN Write(ch)
END
END;
out.WriteView(right);
out.rider.SetAttr(attr);
WriteLn
END WriteSrcLink;
PROCEDURE FindEnd(): INTEGER; (* search for nearest statement following from *)
VAR end: INTEGER;
BEGIN end := MAX(INTEGER);
ref := SYSTEM.ADR(meta[0]); pos := 0; ad := 0; SYSTEM.GET(ref, ch);
WHILE ch # 0X DO
WHILE (ch > 0X) & (ch < 0FCX) DO (* srcref: {dAdr,dPos} *)
INC(ad, ORD(ch)); INC(ref); RefNum(ref, d);
INC(pos, d); SYSTEM.GET(ref, ch);
IF (pos > from) & (pos < end) THEN end := pos END
END;
IF ch = 0FCX THEN (* proc: 0FCX,Adr,Name *)
INC(ref); RefNum(ref, d); RefName(ref, name); SYSTEM.GET(ref, ch)
END;
WHILE ch >= 0FDX DO (* skip variables: Mode, Form, adr, Name *)
INC(ref); RefCh(ref, ch);
IF ch = 10X THEN INC(ref, 4) END;
RefNum(ref, d); RefName(ref, name); SYSTEM.GET(ref, ch)
END
END;
RETURN end
END FindEnd;
BEGIN (* not tuned for speed because used only when decoding a single procedure *)
from := 0; to := 0;
ref := SYSTEM.ADR(meta[0]); pos := 0; ad := 0; SYSTEM.GET(ref, ch);
WHILE ch # 0X DO
WHILE (ch > 0X) & (ch < 0FCX) DO (* srcref: {dAdr,dPos} *)
INC(ad, ORD(ch)); INC(ref); RefNum(ref, d);
INC(pos, d); SYSTEM.GET(ref, ch);
(* statement starting at source position 'pos' starts at instruction 'ad' *)
IF (pc = ad) & (ch > 0X) & (ch < 0FCX) THEN (* start of statement found *)
from := pos;
IF (from # lastFrom) & (from # 0) THEN
to := FindEnd();
lastFrom := from;
WriteSrcLink;
RETURN;
END
END
END;
IF ch = 0FCX THEN (* proc: 0FCX,Adr,Name *)
INC(ref); RefNum(ref, d); RefName(ref, name); SYSTEM.GET(ref, ch)
END;
WHILE ch >= 0FDX DO (* skip variables: Mode, Form, adr, Name *)
INC(ref); RefCh(ref, ch);
IF ch = 10X THEN INC(ref, 4) END;
RefNum(ref, d); RefName(ref, name); SYSTEM.GET(ref, ch)
END
END
END WriteSrc;
PROCEDURE WriteProcLink;
VAR pname: Kernel.Name; adrStr: ARRAY 20 OF CHAR;
left, right: StdLinks.Link; attr: TextModels.Attributes;
BEGIN
Utf.Utf8ToString(procName, pname, res);
IF (pname[0] # "$") OR (pname = "$$") THEN
attr := out.rider.attr;
out.rider.SetAttr(TextModels.NewColor(attr, Ports.blue));
Strings.IntToString(pc, adrStr);
left := StdLinks.dir.NewLink("DevDecoder386.DecodeProc('" + modName + "', '"
+ pname + "', " + adrStr + ")");
right := StdLinks.dir.NewLink("");
out.WriteView(left);
out.WriteString("PROCEDURE " + pname);
out.WriteView(right);
out.rider.SetAttr(attr)
ELSE
out.WriteString("PROCEDURE " + pname)
END
END WriteProcLink;
BEGIN
inp.SetPos(hs); NEW(meta, ms); inp.ReadBytes(meta, 0, ms);
inp.SetPos(hs + ms + ds);
procRef := SYSTEM.ADR(meta[0]);
IF selectProc >= 0 THEN
srcRd := OpenSourceReader(); pc := selectProc; procAdr := 0; inp.SetPos(inp.Pos() + selectProc);
REPEAT Kernel.GetRefProc(procRef, procAdr, procName)
UNTIL (procAdr > selectProc) OR (procAdr = 0);
cs := procAdr
ELSE srcRd := NIL; pc := 0; procAdr := 0
END;
column := 0; jmpTabEnd := 0;
out.WriteView(NewRuler());
WHILE pc < cs DO
IF pc >= jmpTabEnd THEN jmpTabEnd := 0 END; (* clear CASE jump table *)
IF pc >= procAdr THEN
Kernel.GetRefProc(procRef, procAdr, procName);
IF procAdr = 0 THEN RETURN END;
WriteLn; WriteProcLink; WriteLn;
END;
IF srcRd # NIL THEN WriteSrc END;
adrPrefix:= FALSE; opPrefix:= FALSE; prefix:= none;
WriteDWHex(pc); Write(":"); WriteTab;
DecodeInstruction
END
END Decode;
PROCEDURE DecodeProc*(modName, procName: ARRAY OF CHAR; adr: INTEGER);
VAR loc: Files.Locator; name: Files.Name; f: Files.File;
text: TextModels.Model; v: TextViews.View; inp: Files.Reader; out: TextMappers.Formatter;
n, p, hs, ms, ds, cs, vs: INTEGER;
PROCEDURE RWord (VAR x: INTEGER);
VAR b: BYTE; y: INTEGER;
BEGIN
inp.ReadByte(b); y := b MOD 256;
inp.ReadByte(b); y := y + 100H * (b MOD 256);
inp.ReadByte(b); y := y + 10000H * (b MOD 256);
inp.ReadByte(b); x := y + 1000000H * b
END RWord;
BEGIN
StdDialog.GetSubLoc(modName, "Code", loc, name);
f := Files.dir.Old(loc, name, Files.shared);
IF f # NIL THEN
text := TextModels.dir.New(); out.ConnectTo(text);
inp := f.NewReader(NIL);
inp.SetPos(0); RWord(n); RWord(p);
v := TextViews.dir.New(text);
IF (n = 6F4F4346H) & (p = 10) THEN
RWord(hs); RWord(ms); RWord(ds); RWord(cs); RWord(vs);
Decode(modName, inp, hs, ms, ds, cs, vs, adr, out);
v.SetDefaults(NewRuler(), TextViews.dir.defAttr);
ELSE out.WriteString("wrong file or processor tag")
END;
Views.OpenAux(v, "PROCEDURE " + modName + "." + procName)
ELSE Dialog.ShowParamMsg("#Dev:ModuleNotFound", modName, "", "")
END
END DecodeProc;
PROCEDURE ShowSrc*(modName: ARRAY OF CHAR; from, to: INTEGER);
VAR loc: Files.Locator; name: Files.Name;
v: Views.View; tv: TextViews.View; tc: TextControllers.Controller;
BEGIN
StdDialog.GetSubLoc(modName, "Mod", loc, name);
v := Views.OldView(loc, name);
IF (v # NIL) & (v IS TextViews.View) THEN
Views.Open(v, loc, name, NIL);
tv := v(TextViews.View);
tc := tv.ThisController()(TextControllers.Controller);
tc.SetSelection(from, to);
tv.ShowRange(from, to, TextViews.focusOnly);
ELSE Dialog.ShowParamMsg("#Dev:ModuleNotFound", modName, "", "")
END
END ShowSrc;
END DevDecoder386.
| Dev/Mod/Decoder386.odc |
MODULE DevDependencies; (* Eliminate HostMenus import *)
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20151106, center #85, Trap in DevDependencies with long module names
- 20161103, center #140, unwrapping import aliasses
- 20170905, center #173, adding new modifiers to Controllers
- 20210425, ad, Eliminated HostMenus import, replaced with StdMenyTool import
"
issues = "
- ...
"
**)
IMPORT
Kernel, Files, Utf, Dialog, TextMappers, TextControllers,
StdMenuTool, StdDialog, StdFolds, Strings, Views, Ports, Librarian,
Fonts, Properties, Controllers, Stores, (*HostMenus, *)StdCmds, Math,
TextModels, TextViews, Dates, DevReferences, DevCommanders;
CONST
bold = 0; italic = 1; (* used with SetStyle *)
full = TRUE; (* used with DependencyList *)
implicit = TRUE; (* used with GetNode *)
TYPE
String = ARRAY 256 OF CHAR;
(** Data structure types **)
Subgraph = POINTER TO RECORD (Stores.Store)
node: List;
isImplicit: BOOLEAN;
next: Subgraph
END;
SubsystemList = POINTER TO RECORD (Stores.Store)
name: String;
isExpanded, isLayedout, isHidden, isBasic, isStart, isSelected: BOOLEAN;
l, b, w, h, level: INTEGER;
next: SubsystemList
END;
List = POINTER TO RECORD (Stores.Store)
name: String;
imports: Subgraph;
subsystem: SubsystemList;
l, b, w, h: INTEGER;
isLayedout, isHidden, isStart, isSelected, isImported, onlyImplicit: BOOLEAN;
next: List
END;
NameList = POINTER TO RECORD (Stores.Store)
name: String;
next: NameList
END;
(** View type **)
View = POINTER TO RECORD (Views.View)
list: List;
startList: NameList;
subsystems: SubsystemList;
maxLevel, nofMods: INTEGER;
selfont, normfont: Fonts.Font;
showBasic: BOOLEAN
END;
(** Meta types **)
MetaList = POINTER TO RECORD list: List; next: MetaList END;
MetaSSList = POINTER TO RECORD sslist: SubsystemList; next: MetaSSList END;
(** Operation types **)
DepOp = POINTER TO ABSTRACT RECORD (Stores.Operation)
view: View;
mods: MetaList; subs: MetaSSList
END;
ExpandOp = POINTER TO RECORD (DepOp) expand: BOOLEAN END;
MoveOp = POINTER TO RECORD (DepOp) dx, dy, l, t, r, b: INTEGER END;
HideOp = POINTER TO RECORD (DepOp) END;
HideBasicOp = POINTER TO RECORD (Stores.Operation) view: View END;
ShowAllOp = POINTER TO RECORD (DepOp) END;
ExpandAllOp = POINTER TO RECORD (DepOp) expand: BOOLEAN END;
(** Forward declaragions **)
PROCEDURE^ StartAnalysis (startList: NameList; font: Fonts.Font; incImpl: BOOLEAN; OUT v: View);
(** Auxiliary procedures **)
PROCEDURE RWord (reader: Files.Reader; OUT x: INTEGER);
VAR b: BYTE; y: INTEGER;
BEGIN
reader.ReadByte(b); y := b MOD 256;
reader.ReadByte(b); y := y + 100H * (b MOD 256);
reader.ReadByte(b); y := y + 10000H * (b MOD 256);
reader.ReadByte(b); x := y + 1000000H * b
END RWord;
PROCEDURE RNum (reader: Files.Reader; OUT x: INTEGER);
VAR b: BYTE; s, y: INTEGER;
BEGIN
s := 0; y := 0; reader.ReadByte(b);
WHILE b < 0 DO INC(y, ASH(b + 128, s)); INC(s, 7); reader.ReadByte(b) END;
x := ASH((b + 64) MOD 128 - 64, s) + y
END RNum;
PROCEDURE RName (reader: Files.Reader; OUT name: ARRAY OF CHAR);
VAR b: BYTE; i, n, res: INTEGER; s: ARRAY 256 OF SHORTCHAR;
BEGIN
i := 0; n := LEN(name) - 1; reader.ReadByte(b);
WHILE (i < n) & (b # 0) DO s[i] := SHORT(CHR(b)); INC(i); reader.ReadByte(b) END;
WHILE b # 0 DO reader.ReadByte(b) END;
s[i] := 0X;
Utf.Utf8ToString(s, name, res); ASSERT(res = 0)
END RName;
PROCEDURE GetImports(IN name: String;
OUT imps: POINTER TO ARRAY OF String; OUT nofImps: INTEGER; OUT found: BOOLEAN);
VAR
file: Files.File; loc: Files.Locator; fileName: Files.Name; reader: Files.Reader;
n, i, j, tmpWord: INTEGER;
impName, dollarStr: String; tmpImps: POINTER TO ARRAY OF String;
BEGIN
found := TRUE;
StdDialog.GetSubLoc(name, "Code", loc, fileName);
file := Files.dir.Old(loc, fileName, Files.shared);
IF file # NIL THEN
reader := file.NewReader(NIL); reader.SetPos(0); RWord(reader, n);
IF n = 6F4F4346H THEN
RWord(reader, tmpWord); RWord(reader, tmpWord); RWord(reader, tmpWord); RWord(reader, tmpWord);
RWord(reader, tmpWord); RWord(reader, tmpWord); RNum(reader, n); RName(reader, impName);
i := 0; nofImps := n; IF nofImps > 0 THEN NEW(imps, nofImps) END;
FOR i :=0 TO n - 1 DO
RName(reader, impName); Strings.Extract(impName$, 0, 1, dollarStr);
IF dollarStr = "$" THEN (* To avoid analysis of windows platform imports *)
imps[i] := ""; DEC(nofImps)
ELSE
imps[i] := impName$
END
END;
IF nofImps # n THEN (* some names are empty, delete them *)
IF nofImps = 0 THEN
imps := NIL
ELSE
NEW(tmpImps, nofImps); j := 0;
FOR i := 0 TO n-1 DO IF imps[i] # "" THEN tmpImps[j] := imps[i]; INC(j) END END;
imps := tmpImps
END
END
END
ELSE
found := FALSE
END
END GetImports;
PROCEDURE GetImplicitDependencies(
IN name: String; OUT imps: POINTER TO ARRAY OF String; OUT nofImps: INTEGER
);
VAR deps: String; t: TextModels.Model; s: TextMappers.Scanner; i: INTEGER;
BEGIN
Dialog.MapString("#Dev:Implicit." + name, deps);
IF deps # "Implicit." + name THEN
t := TextModels.dir.NewFromString(deps); s.ConnectTo(t); s.SetPos(0); s.Scan; i := 0;
WHILE s.type # TextMappers.eot DO
IF s.type = TextMappers.string THEN INC(i) END;
s.Scan
END;
nofImps := i; NEW(imps, nofImps);
s.SetPos(0); s.Scan; i := 0;
WHILE s.type # TextMappers.eot DO
IF s.type = TextMappers.string THEN imps[i] := s.string$; INC(i) END;
s.Scan
END
ELSE
imps := NIL; nofImps := 0
END
END GetImplicitDependencies;
PROCEDURE GetModuleList (OUT modList: NameList);
VAR c: TextControllers.Controller; s: TextMappers.Scanner; beg, end: INTEGER; l: NameList;
BEGIN
modList := NIL;
c := TextControllers.Focus();
IF (c # NIL) & c.HasSelection() THEN
c.GetSelection(beg, end);
s.ConnectTo(c.text); s.SetPos(beg); s.Scan;
WHILE (s.start < end) & (s.type # TextMappers.invalid) DO
IF (s.type = TextMappers.string) THEN
NEW(l); IF modList # NIL THEN Stores.Join(modList, l) END;
l.next := modList;
DevReferences.ResolveImportAlias(s.string, c.text);
l.name := s.string$; modList := l; s.Scan
ELSE
s.Scan
END
END
END
END GetModuleList;
(** List **)
PROCEDURE (l: List) GetExtent(OUT w, h: INTEGER), NEW;
BEGIN
IF l.subsystem.isExpanded THEN w := l.w; h:= l.h
ELSE w := l.subsystem.w; h := l.subsystem.h END
END GetExtent;
PROCEDURE (l: List) GetPosition(OUT x, y: INTEGER), NEW;
BEGIN
IF l.subsystem.isExpanded THEN x := l.l; y:= l.b
ELSE x := l.subsystem.l; y := l.subsystem.b END
END GetPosition;
PROCEDURE (l: List) SetPosition(x, y: INTEGER), NEW;
BEGIN
IF x < 1 THEN x := 1 END; IF y < 1 THEN y := 1 END; (* To keep objects in the second quadrant *)
IF l.subsystem.isExpanded THEN l.l := x; l.b:= y
ELSE l.subsystem.l := x; l.subsystem.b := y END
END SetPosition;
PROCEDURE (l: List) Selected(): BOOLEAN, NEW;
BEGIN
RETURN l.subsystem.isExpanded & l.isSelected
END Selected;
PROCEDURE (l: List) Visible(showBasic: BOOLEAN): BOOLEAN, NEW;
BEGIN
RETURN l.subsystem.isExpanded
& ~l.isHidden & ~l.subsystem.isHidden & (~l.subsystem.isBasic OR showBasic)
END Visible;
(** SubsystemList **)
PROCEDURE (s: SubsystemList) Selected(): BOOLEAN, NEW;
BEGIN
RETURN ~s.isExpanded & s.isSelected
END Selected;
PROCEDURE (s: SubsystemList) Visible(showBasic: BOOLEAN): BOOLEAN, NEW;
BEGIN
RETURN ~s.isExpanded & ~s.isHidden & (~s.isBasic OR showBasic)
END Visible;
(** View **)
PROCEDURE (v: View) GetNode (name: String; incImpl: BOOLEAN; VAR node: List), NEW;
VAR
tmpList, tmpNode: List; sl: NameList;
tmpGraph, prevGraph: Subgraph;
nofImps, i: INTEGER; found: BOOLEAN;
head, tail: String;
sslist: SubsystemList;
imps: POINTER TO ARRAY OF String;
BEGIN
(* First check if a node with the sought name exists in the nodeList.
Otherwise build a new subgraph from objectfiles. *)
tmpList := v.list;
WHILE (tmpList # NIL) & (tmpList.name # name) DO tmpList := tmpList.next END;
IF tmpList # NIL THEN
node := tmpList
ELSE
(* Create a new node from an objectfile. *)
GetImports(name, imps, nofImps, found);
IF found THEN
NEW(tmpList); Stores.Join(v, tmpList); INC(v.nofMods);
tmpList.name := name;
(* if subsystem exists then use it otherwise create a new one *)
Librarian.lib.SplitName(name, head, tail);
sslist := v.subsystems;
WHILE (sslist # NIL) & (sslist.name # head) DO sslist := sslist.next END;
IF sslist = NIL THEN
NEW (sslist); Stores.Join(v, sslist); sslist.name := head; sslist.next := v.subsystems;
sslist.level := v.maxLevel; sslist.isExpanded := FALSE;
v.subsystems := sslist
END;
sl := v.startList; (* If it is one of the start modules it should be expanded *)
WHILE (sl # NIL) & (sl.name # name) DO sl := sl.next END;
IF sl # NIL THEN
sslist.isExpanded := TRUE; sslist.level := 1; sslist.isStart := TRUE; tmpList.isStart := TRUE
END;
tmpList.subsystem := sslist; tmpList.imports := NIL;
tmpList.next := v.list; v.list := tmpList; tmpGraph := NIL;
FOR i := 0 TO nofImps - 1 DO
prevGraph := tmpGraph; NEW(tmpGraph); tmpGraph.isImplicit := FALSE; Stores.Join(v, tmpGraph);
v.GetNode(imps[i], incImpl, tmpNode);
tmpNode.isImported := TRUE; (* to be able to identify root modules *)
tmpGraph.node := tmpNode; tmpGraph.next := prevGraph
END;
IF incImpl THEN
GetImplicitDependencies(name, imps, nofImps);
FOR i := 0 TO nofImps - 1 DO
prevGraph := tmpGraph; NEW(tmpGraph); tmpGraph.isImplicit := TRUE; Stores.Join(v, tmpGraph);
v.GetNode(imps[i], incImpl, tmpNode);
tmpGraph.node := tmpNode; tmpGraph.next := prevGraph
END
END;
tmpList.imports := tmpGraph; node := tmpList
ELSE
Dialog.ShowParamMsg("#Dev:ModuleNotFound", name, "", "")
END
END
END GetNode;
PROCEDURE (v: View) OnSelectedObject(x, y: INTEGER): BOOLEAN, NEW;
VAR
l: List; s: SubsystemList;
BEGIN
l := v.list;
WHILE l # NIL DO
IF l.Visible(v.showBasic) & l.Selected() & (x > l.l) & (x < l.l + l.w) & (y < l.b) & (y > l.b - l.h) THEN
RETURN TRUE
END;
l := l.next
END;
s := v.subsystems;
WHILE s # NIL DO
IF s.Visible(v.showBasic) & s.Selected() & (x > s.l) & (x < s.l + s.w) & (y < s.b) & (y > s.b - s.h) THEN
RETURN TRUE
END;
s := s.next
END;
RETURN FALSE
END OnSelectedObject;
PROCEDURE (v: View) OnObject(x, y: INTEGER): BOOLEAN, NEW;
VAR
l: List; s: SubsystemList;
BEGIN
l := v.list;
WHILE l # NIL DO
IF l.Visible(v.showBasic) & (x > l.l) & (x < l.l + l.w) & (y < l.b) & (y > l.b - l.h) THEN
RETURN TRUE
END;
l := l.next
END;
s := v.subsystems;
WHILE s # NIL DO
IF s.Visible(v.showBasic) & (x > s.l) & (x < s.l + s.w) & (y < s.b) & (y > s.b - s.h) THEN
RETURN TRUE
END;
s := s.next
END;
RETURN FALSE
END OnObject;
PROCEDURE OverLap(l1, t1, r1, b1, l2, t2, r2, b2: INTEGER): BOOLEAN;
BEGIN
RETURN ~((l1 > r2) OR (l2 > r1) OR (t1 > b2) OR (t2 > b1))
END OverLap;
PROCEDURE (v: View) Select(x1, y1, x2, y2: INTEGER; modifiers: SET), NEW;
VAR l: List; s: SubsystemList;
BEGIN
l := v.list;
WHILE l # NIL DO
IF l.Visible(v.showBasic) & OverLap(l.l, l.b - l.h, l.l + l.w, l.b, x1, y1, x2, y2) THEN
IF (Controllers.extend IN modifiers) OR (Controllers.modify IN modifiers) THEN
l.isSelected := ~l.isSelected
ELSE
l.isSelected := TRUE
END
ELSE
IF ~(Controllers.extend IN modifiers) & ~(Controllers.modify IN modifiers) THEN l.isSelected := FALSE END
END;
l := l.next
END;
s := v.subsystems;
WHILE s # NIL DO
IF s.Visible(v.showBasic) & OverLap(s.l, s.b - s.h, s.l + s.w, s.b, x1, y1, x2, y2) THEN
IF (Controllers.extend IN modifiers) OR (Controllers.modify IN modifiers) THEN
s.isSelected := ~s.isSelected
ELSE
s.isSelected := TRUE
END
ELSE
IF ~(Controllers.extend IN modifiers) & ~(Controllers.modify IN modifiers) THEN
s.isSelected := FALSE
END
END;
s := s.next
END
END Select;
PROCEDURE (v: View) SelectAll(set: BOOLEAN), NEW;
VAR l: List; s: SubsystemList;
BEGIN
l := v.list;
WHILE l # NIL DO l.isSelected := set & l.Visible(v.showBasic); l := l.next END;
s := v.subsystems;
WHILE s # NIL DO s.isSelected := set & s.Visible(v.showBasic); s := s.next END;
Views.Update(v, Views.keepFrames)
END SelectAll;
(** Operations on the View **)
PROCEDURE (dop: DepOp) AddSelection(), NEW;
VAR ml: MetaList; ms: MetaSSList; l: List; s: SubsystemList;
BEGIN
ASSERT(dop.view # NIL, 20);
l := dop.view.list;
WHILE l # NIL DO
IF l.Selected() THEN NEW(ml); ml.list := l; ml.next := dop.mods; dop.mods := ml END; l := l.next
END;
s := dop.view.subsystems;
WHILE s # NIL DO
IF s.Selected() THEN NEW(ms); ms.sslist := s; ms.next := dop.subs; dop.subs := ms END; s := s.next
END
END AddSelection;
PROCEDURE (e: ExpandOp) Do;
VAR l: MetaList; s: MetaSSList;
BEGIN
l := e.mods;
WHILE l # NIL DO l.list.subsystem.isExpanded := e.expand; l := l.next END;
s := e.subs;
WHILE s # NIL DO s.sslist.isExpanded := e.expand; s := s.next END;
e.expand := ~e.expand;
Views.Update(e.view, Views.keepFrames)
END Do;
PROCEDURE (m: MoveOp) BoundingBox, NEW;
VAR l: MetaList; s: MetaSSList; h, d, w: INTEGER;
BEGIN
m.l := MAX(INTEGER); m.t := m.l; m.b := 0; m.r := 0;
l := m.mods;
WHILE l # NIL DO
IF (l.list.l < m.l) THEN m.l := l.list.l END;
IF (l.list.b - l.list.h < m.t) THEN m.t := l.list.b - l.list.h END;
IF (l.list.l + l.list.w > m.r) THEN m.r := l.list.l + l.list.w END;
IF (l.list.b > m.b) THEN m.b := l.list.b END;
l := l.next
END;
s := m.subs;
WHILE s # NIL DO
IF (s.sslist.l < m.l) THEN m.l := s.sslist.l END;
IF (s.sslist.b - s.sslist.h < m.t) THEN m.t := s.sslist.b - s.sslist.h END;
IF (s.sslist.l + s.sslist.w > m.r) THEN m.r := s.sslist.l + s.sslist.w END;
IF (s.sslist.b > m.b) THEN m.b := s.sslist.b END;
s := s.next
END;
m.view.selfont.GetBounds(h, d, w);
m.b := m.b + d; (* correction for descent *)
m.r := m.r + w; m.l := m.l - w (* correction for incorrect values by italic fonts *)
END BoundingBox;
PROCEDURE (m: MoveOp) Do;
VAR l: MetaList; s: MetaSSList;
BEGIN
l := m.mods;
WHILE l # NIL DO l.list.l := l.list.l + m.dx; l.list.b := l.list.b + m.dy; l := l.next END;
s := m.subs;
WHILE s # NIL DO s.sslist.l := s.sslist.l + m.dx; s.sslist.b := s.sslist.b + m.dy; s := s.next END;
m.dx := -m.dx; m.dy := -m.dy;
Views.Update(m.view, Views.keepFrames)
END Do;
PROCEDURE (h: HideOp) Do;
VAR l: MetaList; s: MetaSSList;
BEGIN
l := h.mods;
WHILE l # NIL DO l.list.isHidden := ~l.list.isHidden; l := l.next END;
s := h.subs;
WHILE s # NIL DO s.sslist.isHidden := ~s.sslist.isHidden; s := s.next END;
Views.Update(h.view, Views.keepFrames)
END Do;
PROCEDURE (h: HideBasicOp) Do;
BEGIN
h.view.showBasic := ~h.view.showBasic;
Views.Update(h.view, Views.keepFrames)
END Do;
PROCEDURE (s: ShowAllOp) Do;
VAR ml: MetaList; mssl: MetaSSList;
BEGIN
ml := s.mods; mssl := s.subs;
WHILE ml # NIL DO ml.list.isHidden := ~ml.list.isHidden; ml := ml.next END;
WHILE mssl # NIL DO mssl.sslist.isHidden := ~mssl.sslist.isHidden; mssl := mssl.next END;
Views.Update(s.view, Views.keepFrames)
END Do;
PROCEDURE (e: ExpandAllOp) Do;
VAR mssl: MetaSSList;
BEGIN
mssl := e.subs;
WHILE mssl # NIL DO mssl.sslist.isExpanded := e.expand; mssl := mssl.next END;
e.expand := ~e.expand;
Views.Update(e.view, Views.keepFrames)
END Do;
PROCEDURE (v: View) ExpandCollapse(expand: BOOLEAN), NEW;
VAR e: ExpandOp;
BEGIN
NEW(e); e.view := v; e.AddSelection; e.expand := expand;
IF e.expand THEN e.mods := NIL ELSE e.subs := NIL END;
Views.Do(v, "Toggle Expand/Collapse", e)
END ExpandCollapse;
(** Redrawing the view **)
PROCEDURE (v: View) SetExtents, NEW;
VAR tmpList: List; ssList: SubsystemList; h, d, w: INTEGER;
BEGIN
tmpList := v.list; v.selfont.GetBounds(h, d, w);
WHILE tmpList # NIL DO
tmpList.w := v.selfont.StringWidth(tmpList.name); tmpList.h := h; tmpList := tmpList.next
END;
ssList := v.subsystems;
WHILE ssList # NIL DO
ssList.w := v.selfont.StringWidth("[" + ssList.name + "]"); ssList.h := h; ssList := ssList.next
END
END SetExtents;
PROCEDURE (v: View) Layout, NEW;
CONST space = 5 * Ports.mm;
VAR
width, height, xindent, yindent, level: INTEGER;
levelIndent: POINTER TO ARRAY OF INTEGER;
tmpList: List;
BEGIN
NEW(levelIndent, v.maxLevel + 1); v.context.GetSize(width, height);
tmpList := v.list;
WHILE tmpList # NIL DO
IF tmpList.isStart THEN
yindent := space; level := 0
ELSE
level := tmpList.subsystem.level;
yindent := space + (15 * Ports.mm * level)
END;
xindent := space + levelIndent[level];
WHILE xindent + v.normfont.StringWidth(tmpList.name) > width DO
xindent := xindent - width;
yindent := yindent + (4 * Ports.mm)
END;
IF ~tmpList.subsystem.isBasic OR v.showBasic THEN
IF tmpList.subsystem.isExpanded THEN
IF ~tmpList.isHidden & ~tmpList.isLayedout THEN
levelIndent[level] := levelIndent[level] + tmpList.w + space;
tmpList.SetPosition(xindent, yindent); tmpList.isLayedout := TRUE
END
ELSIF ~ tmpList.subsystem.isHidden & ~tmpList.subsystem.isLayedout THEN
levelIndent[level] := levelIndent[level] + tmpList.subsystem.w + space;
tmpList.SetPosition(xindent, yindent); tmpList.subsystem.isLayedout := TRUE
END
END;
tmpList := tmpList.next
END
END Layout;
PROCEDURE (v: View) DrawArrow(f: Views.Frame; ax, ay, bx, by, s: INTEGER), NEW;
CONST ArrowLen = 1 * Ports.mm;
TYPE Vector = RECORD x, y: REAL END;
VAR a, b, c, d, e, v1, v2: Vector; lenc, m, x, y: REAL; p: ARRAY 3 OF Ports.Point;
BEGIN
a.x := ax; a.y := ay; b.x := bx; b.y := by; c.x := b.x - a.x; c.y := b.y - a.y;
m := MAX(ABS(c.x), ABS(c.y)); x := c.x / m; y := c.y / m;
lenc := m * Math.Sqrt(x * x + y * y); s := MAX(1, SHORT(ENTIER(1.5 * s)) DIV Ports.point); (* scaling factor *)
e.x := c.x * s / lenc; e.y := c.y * s / lenc;
d.x := e.y; d.y := - e.x; (* first orthogonal vector *)
v1.x := (e.x + d.x) * ArrowLen; v1.y := (e.y + d.y) * ArrowLen;
v1.x := -v1.x; v1.y := -v1.y; (* mirror vector *)
d.x := -d.x; d.y := -d.y; (* second orthogonal vector *)
v2.x := (e.x + d.x) * ArrowLen; v2.y := (e.y + d.y) * ArrowLen;
v2.x := -v2.x; v2.y := -v2.y; (* mirror vector *)
p[0].x := SHORT(ENTIER(b.x));p[0].y := SHORT(ENTIER(b.y));
p[1].x := SHORT(ENTIER(b.x + v1.x)); p[1].y := SHORT(ENTIER(b.y + v1.y));
p[2].x := SHORT(ENTIER(b.x + v2.x)); p[2].y := SHORT(ENTIER(b.y + v2.y));
f.DrawPath(p, 3, Ports.fill, Ports.black, Ports.closedPoly)
END DrawArrow;
PROCEDURE (v: View) DrawDependencies (f: Views.Frame; l, t, r, b: INTEGER), NEW;
VAR
xindent, yindent, startx, starty, middlex, middley, sx, sy, thickness: INTEGER;
subgraph: Subgraph; tmpList: List; s: SubsystemList;
BEGIN
thickness := MAX(2, (v.normfont.size DIV 8));
f.DrawRect(l, t, r, b, Ports.fill, Ports.white);
tmpList := v.list;
WHILE tmpList # NIL DO
IF tmpList.Visible(v.showBasic) OR tmpList.subsystem.Visible(v.showBasic) THEN
subgraph := tmpList.imports;
tmpList.GetPosition(startx, starty);
WHILE subgraph # NIL DO
IF subgraph.node.Visible(v.showBasic) OR subgraph.node.subsystem.Visible(v.showBasic) THEN
subgraph.node.GetPosition(sx, sy);
middlex := ABS(startx - ((startx - sx) DIV 2));
middley := ABS(starty - ((starty - sy) DIV 2));
IF ~subgraph.isImplicit THEN
f.DrawLine(startx, starty, middlex, middley, thickness, Ports.red);
f.DrawLine(middlex, middley, sx, sy, thickness, Ports.blue)
ELSE
f.DrawLine(startx, starty, middlex, middley, thickness, Ports.grey25);
f.DrawLine(middlex, middley, sx, sy, thickness, Ports.grey25)
END;
IF (middlex # startx) OR (middley # starty) THEN
v.DrawArrow(f, startx, starty, middlex, middley, thickness)
END
END;
subgraph := subgraph.next
END
END;
tmpList := tmpList.next
END;
(* Draw the names of the modules last, so they end up on top *)
tmpList := v.list;
WHILE tmpList # NIL DO
IF tmpList.Visible(v.showBasic) THEN
tmpList.GetPosition(xindent, yindent);
IF tmpList.Selected() THEN
f.DrawString(xindent, yindent, Ports.black, tmpList.name, v.selfont)
ELSE
f.DrawString(xindent, yindent, Ports.black, tmpList.name, v.normfont)
END;
f.DrawOval(xindent - (Ports.mm DIV 2), yindent - (Ports.mm DIV 2), xindent + (Ports.mm DIV 2), yindent +
(Ports.mm DIV 2), Ports.fill, Ports.black)
END;
tmpList := tmpList.next
END;
s := v.subsystems;
WHILE s # NIL DO
IF s.Visible(v.showBasic) THEN
xindent := s.l; yindent := s.b;
IF s.Selected() THEN
f.DrawString(xindent, yindent, Ports.black, "[" + s.name + "]", v.selfont)
ELSE
f.DrawString(xindent, yindent, Ports.black, "[" + s.name + "]", v.normfont)
END;
f.DrawOval(xindent - (Ports.mm DIV 2), yindent - (Ports.mm DIV 2), xindent + (Ports.mm DIV 2), yindent +
(Ports.mm DIV 2), Ports.fill, Ports.black)
END;
s := s.next
END
END DrawDependencies;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
v.Layout();
v.DrawDependencies(f, l, t, r, b)
END Restore;
(** Handle view messages **)
PROCEDURE (v: View) SetProps(p: Properties.Property), NEW;
VAR
size: INTEGER;
typeface: Fonts.Typeface;
prop: Properties.StdProp;
style: SET;
BEGIN
WHILE (p # NIL) & ~(p IS Properties.StdProp) DO p := p.next END;
IF p # NIL THEN
prop := p(Properties.StdProp); size := v.normfont.size;
typeface := v.normfont.typeface; style := v.normfont.style;
IF Properties.size IN prop.valid THEN size := prop.size END;
IF Properties.typeface IN prop.valid THEN typeface := prop.typeface END;
IF Properties.style IN prop.valid THEN
IF Fonts.underline IN prop.style.mask THEN
IF Fonts.underline IN prop.style.val THEN style := style + {Fonts.underline}
ELSE style := style - {Fonts.underline} END
END;
IF Fonts.italic IN prop.style.mask THEN
IF Fonts.italic IN prop.style.val THEN style := style + {Fonts.italic}
ELSE style := style - {Fonts.italic} END
END;
IF Fonts.strikeout IN prop.style.mask THEN
IF Fonts.strikeout IN prop.style.val THEN style := style + {Fonts.strikeout}
ELSE style := style - {Fonts.strikeout} END
END
END;
v.normfont := Fonts.dir.This(typeface, size, style, Fonts.normal);
v.selfont := Fonts.dir.This(typeface, size, style, Fonts.bold); v.SetExtents();
Views.Update(v, Views.keepFrames)
END
END SetProps;
PROCEDURE (v: View) GetProps(OUT p: Properties.Property), NEW;
VAR
prop: Properties.StdProp;
BEGIN
NEW(prop); prop.known := {Properties.weight, Properties.size, Properties.typeface, Properties.style};
prop.valid := {Properties.weight, Properties.size, Properties.typeface, Properties.style};
prop.typeface := v.normfont.typeface; prop.size := v.normfont.size; prop.weight := v.normfont.weight;
prop.style.val := v.normfont.style; prop.style.mask := v.normfont.style;
p := prop
END GetProps;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
CONST min = 50 * Ports.mm; max = 500 * Ports.mm;
BEGIN
WITH msg: Properties.SizePref DO
IF (msg.w = Views.undefined) OR (msg.h = Views.undefined) THEN
msg.w := 200 * Ports.mm; msg.h := 100 * Ports.mm
ELSE
Properties.ProportionalConstraint(2, 1, msg.fixedW, msg.fixedH,
msg.w, msg.h);
IF msg.h < min THEN
msg.h := min; msg.w := 2 * min
ELSIF msg.h > max THEN
msg.h := max; msg.w := 2 * max
END
END
| msg: Properties.ResizePref DO
msg.horFitToWin := TRUE; msg.verFitToWin := TRUE
| msg: Properties.FocusPref DO
msg.setFocus := TRUE
| msg: Properties.PollMsg DO
v.GetProps(msg.prop)
| msg: Properties.SetMsg DO
v.SetProps(msg.prop)
ELSE (* ignore other messages *)
END
END HandlePropMsg;
PROCEDURE (v: View) HandleMultiSelect (f: Views.Frame; VAR msg: Controllers.TrackMsg), NEW;
VAR
x, y, x1, y1: INTEGER;
isDown, first: BOOLEAN; m: SET;
BEGIN
first := TRUE; x1 := -1; y1 := -1;
REPEAT
f.Input(x, y, m, isDown);
IF (x1 # x) OR (y1 # y) THEN
IF first THEN
first := FALSE
ELSE
f.MarkRect(MIN(x1, msg.x), MIN(y1, msg.y), MAX(x1, msg.x), MAX(y1, msg.y), 0, Ports.dim50, FALSE)
END;
x1 := x; y1 := y;
f.MarkRect(MIN(x1, msg.x), MIN(y1, msg.y), MAX(x1, msg.x), MAX(y1, msg.y), 0, Ports.dim50, TRUE)
END
UNTIL ~isDown;
f.MarkRect(MIN(x1, msg.x), MIN(y1, msg.y), MAX(x1, msg.x), MAX(y1, msg.y), 0, Ports.dim50, FALSE);
v.Select(MIN(x1, msg.x), MIN(y1, msg.y), MAX(x1, msg.x), MAX(y1, msg.y), msg.modifiers);
Views.Update(v, Views.keepFrames)
END HandleMultiSelect;
PROCEDURE (v: View) HandleMove (f: Views.Frame; VAR msg: Controllers.TrackMsg), NEW;
VAR
x1, y1, x, y, res: INTEGER; mo: MoveOp; m: SET; isDown: BOOLEAN;
ml: MetaList; ms: MetaSSList;
BEGIN
NEW(mo); mo.view := v; mo.AddSelection; mo.BoundingBox;
x1 := msg.x; y1 := msg.y;
f.SaveRect(f.l, f.t, f.r, f.b, res);
REPEAT
f.Input(x, y, m, isDown);
IF (res = 0) & ((x # x1) OR (y # y1)) THEN
x1 := x; y1 := y;
f.RestoreRect(mo.l + mo.dx, mo.t + mo.dy, mo.r + mo.dx, mo.b + mo.dy, Ports.keepBuffer);
mo.dx := x - msg.x; mo.dy := y - msg.y;
IF mo.l + mo.dx < f.l THEN mo.dx := f.l - mo.l END; IF mo.r + mo.dx > f.r THEN mo.dx := f.r - mo.r END;
IF mo.t + mo.dy < f.t THEN mo.dy := f.t - mo.t END; IF mo.b + mo.dy > f.b THEN mo.dy := f.b - mo.b END;
ml := mo.mods;
WHILE ml # NIL DO
f.DrawString(ml.list.l + mo.dx, ml.list.b + mo.dy, Ports.grey50, ml.list.name, v.selfont); ml := ml.next
END;
ms := mo.subs;
WHILE ms # NIL DO
f.DrawString(ms.sslist.l + mo.dx, ms.sslist.b + mo.dy, Ports.grey50, '[' + ms.sslist.name + ']', v.selfont);
ms := ms.next
END
END
UNTIL ~isDown;
f.RestoreRect(f.l, f.t, f.r, f.b, Ports.disposeBuffer);
Views.Do(v, "Move", mo)
END HandleMove;
PROCEDURE OpName(op, arg: ARRAY OF CHAR): POINTER TO ARRAY OF CHAR;
VAR len: INTEGER; s: POINTER TO ARRAY OF CHAR;
BEGIN
len := LEN(op$) + 1(*space*) + LEN(arg$) + 2(*quotes*) + 1(*0X*);
NEW(s, len);
s^ := op$ + ' "' + arg$ + '"';
IF len > LEN(Stores.OpName) THEN
Strings.Replace(s, LEN(Stores.OpName) - 5, len - LEN(Stores.OpName) + 3, "...");
END;
RETURN s
END OpName;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
CONST movedist = Ports.mm * Ports.mm; arrowdist = Ports.mm;
VAR
w, h, x, y, delta: INTEGER; m: SET;
isDown, isMove: BOOLEAN;
mo: MoveOp; e: ExpandOp;
BEGIN
WITH msg: Controllers.TrackMsg DO
IF Controllers.popup IN msg.modifiers THEN
StdMenuTool.PopupMenu
ELSIF (Controllers.doubleClick IN msg.modifiers) THEN
IF v.OnSelectedObject(msg.x, msg.y) THEN
NEW(e); e.view := v; e.AddSelection;
IF (e.mods # NIL) & (e.subs = NIL) & (e.mods.next = NIL) THEN
e.expand := FALSE; Views.Do(v, OpName("Collapse", e.mods.list.name)$, e)
ELSIF (e.mods = NIL) & (e.subs # NIL) & (e.subs.next = NIL) THEN
e.expand := TRUE; Views.Do(v, OpName("Expand", e.subs.sslist.name)$, e)
END
END
ELSE
isMove := FALSE;
REPEAT
f.Input(x, y, m, isDown);
IF ~isMove & ((ABS(x - msg.x) * ABS(x - msg.x) + ABS(y - msg.y) * ABS(y - msg.y)) > movedist) THEN
isMove := TRUE
END
UNTIL ~isDown OR isMove;
IF isMove THEN
IF v.OnSelectedObject(msg.x, msg.y) THEN
v.HandleMove(f, msg)
ELSIF v.OnObject(msg.x, msg.y) THEN
v.Select(msg.x, msg.y, msg.x, msg.y, {}); v.HandleMove(f, msg)
ELSE v.HandleMultiSelect(f, msg) END
ELSE
v.Select(msg.x, msg.y, msg.x, msg.y, msg.modifiers); Views.Update(v, Views.keepFrames)
END
END
| msg: Controllers.PollOpsMsg DO
msg.valid := {Controllers.copy}; msg.selectable := TRUE; msg.type := "DevDependencies.View"
| msg: Properties.CollectMsg DO
v.GetProps(msg.poll.prop)
| msg: Properties.EmitMsg DO
v.SetProps(msg.set.prop); v.context.GetSize(w, h); v.Restore(f, 0, 0, w, h)
| msg: Controllers.SelectMsg DO
v.SelectAll(msg.set)
| msg: Controllers.EditMsg DO
IF (msg.op = Controllers.pasteChar) & (ORD(msg.char) >= 28) & (ORD(msg.char) <= 31) THEN
NEW(mo); mo.view := v; mo.AddSelection; mo.BoundingBox; mo.dx := 0; mo.dy := 0;
IF Controllers.modify IN msg.modifiers THEN delta := f.unit ELSE delta := arrowdist END;
CASE msg.char OF
| CHR(28): mo.dx := -delta | CHR(29): mo.dx := delta
| CHR(30): mo.dy := -delta | CHR(31): mo.dy := delta
END;
IF mo.l + mo.dx < f.l THEN mo.dx := f.l - mo.l END; IF mo.r + mo.dx > f.r THEN mo.dx := f.r - mo.r END;
IF mo.t + mo.dy < f.t THEN mo.dy := f.t - mo.t END; IF mo.b + mo.dy > f.b THEN mo.dy := f.b - mo.b END;
IF (mo.dy # 0) OR (mo.dx # 0) THEN Views.Do(v, "Move", mo) END
END
ELSE (* Ignore other messages *)
END
END HandleCtrlMsg;
(** Internalize/Externalize and Copy **)
PROCEDURE (s: SubsystemList) Internalize (VAR rd: Stores.Reader);
VAR
store: Stores.Store;
BEGIN
rd.ReadString(s.name); rd.ReadBool(s.isExpanded);
rd.ReadBool(s.isLayedout); rd.ReadBool(s.isHidden); rd.ReadBool(s.isBasic); rd.ReadBool(s.isStart);
rd.ReadInt(s.l); rd.ReadInt(s.b); rd.ReadInt(s.w); rd.ReadInt(s.h); rd.ReadInt(s.level);
rd.ReadStore(store);
IF store # NIL THEN
s.next := store(SubsystemList)
ELSE
s.next := NIL
END
END Internalize;
PROCEDURE (s: SubsystemList) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteString(s.name); wr.WriteBool(s.isExpanded);
wr.WriteBool(s.isLayedout);wr.WriteBool(s.isHidden); wr.WriteBool(s.isBasic); wr.WriteBool(s.isStart);
wr.WriteInt(s.l); wr.WriteInt(s.b); wr.WriteInt(s.w); wr.WriteInt(s.h); wr.WriteInt(s.level);
wr.WriteStore(s.next)
END Externalize;
PROCEDURE (l: List) Internalize (VAR rd: Stores.Reader);
VAR
store: Stores.Store;
BEGIN
rd.ReadString(l.name); rd.ReadInt(l.l); rd.ReadInt(l.b); rd.ReadInt(l.w); rd.ReadInt(l.h);
rd.ReadBool(l.isLayedout); rd.ReadBool(l.isHidden); rd.ReadBool(l.isStart);
rd.ReadStore(store); l.subsystem := store(SubsystemList);
rd.ReadStore(store);
IF store # NIL THEN l.imports := store(Subgraph) ELSE l.imports := NIL END;
rd.ReadStore(store);
IF store # NIL THEN l.next := store(List) ELSE l.next := NIL END
END Internalize;
PROCEDURE (l: List) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteString(l.name); wr.WriteInt(l.l); wr.WriteInt(l.b); wr.WriteInt(l.w); wr.WriteInt(l.h);
wr.WriteBool(l.isLayedout);wr.WriteBool(l.isHidden); wr.WriteBool(l.isStart);
wr.WriteStore(l.subsystem); wr.WriteStore(l.imports);
wr.WriteStore(l.next)
END Externalize;
PROCEDURE (l: NameList) Internalize (VAR rd: Stores.Reader);
VAR
store: Stores.Store;
BEGIN
rd.ReadString(l.name);
rd.ReadStore(store);
IF store # NIL THEN l.next := store(NameList) ELSE l.next := NIL END
END Internalize;
PROCEDURE (l: NameList) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteString(l.name); wr.WriteStore(l.next)
END Externalize;
PROCEDURE (g: Subgraph) Internalize (VAR rd: Stores.Reader);
VAR
store: Stores.Store;
BEGIN
rd.ReadBool(g.isImplicit);
rd.ReadStore(store); g.node := store(List);
rd.ReadStore(store);
IF store # NIL THEN g.next := store(Subgraph) ELSE g.next := NIL END
END Internalize;
PROCEDURE (g: Subgraph) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteBool(g.isImplicit); wr.WriteStore(g.node); wr.WriteStore(g.next)
END Externalize;
PROCEDURE (v: View) Internalize (VAR rd: Stores.Reader);
VAR
version, size: INTEGER;
store: Stores.Store;
typeface: Fonts.Typeface;
style: SET;
BEGIN
rd.ReadVersion(0, 0, version);
IF ~rd.cancelled THEN
rd.ReadInt(v.maxLevel); rd.ReadBool(v.showBasic);
rd.ReadString(typeface); rd.ReadInt(size); rd.ReadSet(style);
v.normfont := Fonts.dir.This(typeface, size, style, Fonts.normal);
v.selfont := Fonts.dir.This(typeface, size, style, Fonts.bold);
rd.ReadStore(store); v.startList := store(NameList);
rd.ReadStore(store); v.subsystems := store(SubsystemList);
rd.ReadStore(store); v.list := store(List)
END
END Internalize;
PROCEDURE (v: View) Externalize (VAR wr: Stores.Writer);
BEGIN
wr.WriteVersion(0);
wr.WriteInt(v.maxLevel); wr.WriteBool(v.showBasic);
wr.WriteString(v.normfont.typeface); wr.WriteInt(v.normfont.size); wr.WriteSet(v.normfont.style);
wr.WriteStore(v.startList); wr.WriteStore(v.subsystems); wr.WriteStore(v.list)
END Externalize;
PROCEDURE (s: SubsystemList) CopyFrom(source: Stores.Store);
BEGIN
WITH source: SubsystemList DO
s.name := source.name;
s.isExpanded := source.isExpanded;
s.isLayedout := source.isLayedout;
s.isHidden := source.isHidden;
s.isBasic := source.isBasic;
s.isStart := source.isStart;
s.l := source.l; s.b := source.b; s.w := source.w; s.h := source.h; s.level := source.level;
IF source.next # NIL THEN s.next := Stores.CopyOf(source.next)(SubsystemList) END
END
END CopyFrom;
PROCEDURE (l: List) CopyFrom(source: Stores.Store);
BEGIN
WITH source: List DO
l.name := source.name; l.l := source.l; l.b := source.b; l.w := source.w; l.h := source.h;
l.isLayedout := source.isLayedout; l.isHidden := source.isHidden; l.isStart := source.isStart;
IF source.imports # NIL THEN l.imports := Stores.CopyOf(source.imports)(Subgraph) END;
IF source.subsystem # NIL THEN
l.subsystem := Stores.CopyOf(source.subsystem)(SubsystemList)
END;
IF source.next # NIL THEN l.next := Stores.CopyOf(source.next)(List) END
END
END CopyFrom;
PROCEDURE (l: NameList) CopyFrom(source: Stores.Store);
BEGIN
WITH source: NameList DO
l.name := source.name;
IF source.next # NIL THEN l.next := Stores.CopyOf(source.next)(NameList) END
END
END CopyFrom;
PROCEDURE (g: Subgraph) CopyFrom(source: Stores.Store);
BEGIN
WITH source: Subgraph DO
g.isImplicit := source.isImplicit;
IF source.node # NIL THEN g.node := Stores.CopyOf(source.node)(List) END;
IF source.next # NIL THEN g.next := Stores.CopyOf(source.next)(Subgraph) END
END
END CopyFrom;
PROCEDURE (v: View) CopyFromSimpleView (source: Views.View);
BEGIN
WITH source: View DO
v.maxLevel := source.maxLevel;
v.normfont := source.normfont;
v.selfont := source.selfont;
v.showBasic := source.showBasic;
v.startList := Stores.CopyOf(source.startList)(NameList);
v.subsystems := Stores.CopyOf(source.subsystems)(SubsystemList);
v.list := Stores.CopyOf(source.list)(List)
END
END CopyFromSimpleView;
(** Guards and Interactors **)
PROCEDURE ExpandClick*;
VAR v: View;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN v.ExpandCollapse(TRUE) END
END ExpandClick;
PROCEDURE CollapseClick*;
VAR v: View;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN v.ExpandCollapse(FALSE) END
END CollapseClick;
PROCEDURE HideClick*;
VAR v: View; hop: HideOp;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN
NEW(hop); hop.view := v; hop.AddSelection;
Views.Do(v, "Hide Item", hop)
END
END HideClick;
PROCEDURE ToggleBasicSystemsClick*;
VAR v: View; hbop: HideBasicOp;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN
NEW(hbop); hbop.view := v;
IF v.showBasic THEN Views.Do(v, "Hide Basic Systems", hbop)
ELSE Views.Do(v, "Show Basic Systems", hbop)
END
END
END ToggleBasicSystemsClick;
PROCEDURE ShowAllClick*;
VAR v: View; l: List; sl: SubsystemList;
so: ShowAllOp; ml: MetaList; ssl: MetaSSList;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN
NEW(so); l := v.list;
WHILE l # NIL DO
IF l.isHidden THEN NEW(ml); ml.list := l; ml.next := so.mods; so.mods := ml END;
l := l.next
END;
sl := v.subsystems;
WHILE sl # NIL DO
IF sl.isHidden THEN NEW(ssl); ssl.sslist := sl; ssl.next := so.subs; so.subs := ssl END;
sl := sl.next
END;
IF (so.mods # NIL) OR (so.subs # NIL) THEN so.view := v; Views.Do(v, "Show All", so) END
END
END ShowAllClick;
PROCEDURE ECAll(eo: ExpandAllOp);
VAR v: View; sl: SubsystemList; ssl: MetaSSList;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN
sl := v.subsystems;
WHILE sl # NIL DO
IF (sl.isExpanded # eo.expand) & ~sl.isHidden & (~sl.isBasic OR v.showBasic) THEN
NEW(ssl); ssl.sslist := sl; ssl.next := eo.subs; eo.subs := ssl
END;
sl := sl.next
END;
IF eo.subs # NIL THEN eo.view := v; Views.Do(v, "Show All", eo) END
END
END ECAll;
PROCEDURE ExpandAllClick*;
VAR eo: ExpandAllOp;
BEGIN
NEW(eo); eo.expand := TRUE; ECAll(eo)
END ExpandAllClick;
PROCEDURE CollapseAllClick*;
VAR eo: ExpandAllOp;
BEGIN
NEW(eo); eo.expand := FALSE; ECAll(eo)
END CollapseAllClick;
PROCEDURE ArrangeClick*; (* Not undoable *)
VAR v: View; l: List; sl: SubsystemList;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN
Views.BeginModification(Views.notUndoable, v);
l := v.list;
WHILE l # NIL DO l.isLayedout := FALSE; l := l.next END;
sl := v.subsystems;
WHILE sl # NIL DO sl.isLayedout := FALSE; sl := sl.next END;
Views.Update(v, Views.keepFrames);
Views.EndModification(Views.notUndoable, v)
END
END ArrangeClick;
PROCEDURE DependencyList(v: View; full: BOOLEAN; VAR clist: MetaList);
VAR l: List;
PROCEDURE RecursiveList(node: List; VAR clist: MetaList);
VAR imports: Subgraph; ml, prev: MetaList;
BEGIN
IF full OR node.subsystem.isExpanded THEN
ml := clist;
WHILE (ml # NIL) & (ml.list # node) DO ml := ml.next END;
IF ml = NIL THEN
imports := node.imports;
WHILE imports # NIL DO
IF ~imports.isImplicit THEN RecursiveList(imports.node, clist) END;
imports := imports.next
END;
ml := clist; prev := ml;
WHILE (ml # NIL) & (ml.list # node) DO
(* could have been implicitly imported *)
prev := ml; ml := ml.next
END;
IF ml = NIL THEN
NEW(ml); ml.list := node;
IF prev # NIL THEN prev.next := ml END
END;
IF clist = NIL THEN clist := ml END;
imports := node.imports;
WHILE imports # NIL DO
IF imports.isImplicit THEN RecursiveList(imports.node, clist) END;
imports := imports.next
END
END
END
END RecursiveList;
BEGIN
l := v.list;
WHILE l # NIL DO
RecursiveList(l, clist);
l := l.next
END
END DependencyList;
PROCEDURE SortMetaList(VAR ml: MetaList);
VAR l, p, cur, pcur: MetaList;
BEGIN
ASSERT(ml # NIL, 20);
cur := ml.next; pcur := ml;
WHILE cur # NIL DO
p := NIL; l := ml;
WHILE (l # cur) & (cur.list.name$ > l.list.name$) DO p := l; l := l.next END;
IF l = cur THEN
pcur := cur; cur := cur.next
ELSE
pcur.next := cur.next; cur.next := l;
IF p = NIL THEN ml := cur ELSE p.next := cur END;
cur := pcur.next
END
END
END SortMetaList;
PROCEDURE MarkImplicitModules(v: View);
VAR
fullList, nonImplList: MetaList; v2: View;
BEGIN
IF v.nofMods <= 0 THEN RETURN END;
DependencyList(v, full, fullList);
SortMetaList(fullList);
StartAnalysis(v.startList, NIL, ~implicit, v2);
DependencyList(v2, full, nonImplList);
SortMetaList(nonImplList);
WHILE nonImplList # NIL DO
IF nonImplList.list.name$ = fullList.list.name$ THEN
fullList.list.onlyImplicit := FALSE
ELSE
WHILE nonImplList.list.name$ # fullList.list.name$ DO
fullList.list.onlyImplicit := TRUE; fullList := fullList.next
END
END;
fullList := fullList.next;
nonImplList := nonImplList.next
END;
WHILE fullList # NIL DO fullList.list.onlyImplicit := TRUE; fullList := fullList.next END
END MarkImplicitModules;
PROCEDURE SetStyle(f: TextMappers.Formatter; style: SET);
VAR prop: Properties.StdProp;
BEGIN
prop := f.rider.attr.Prop()(Properties.StdProp);
IF bold IN style THEN prop.weight := Fonts.bold ELSE prop.weight := Fonts.normal END;
IF italic IN style THEN INCL(prop.style.val, Fonts.italic); prop.style.mask := prop.style.val
ELSE EXCL(prop.style.val, Fonts.italic) END;
f.rider.SetAttr(TextModels.ModifiedAttr(f.rider.attr, prop))
END SetStyle;
PROCEDURE SetGray(f: TextMappers.Formatter);
VAR prop: Properties.StdProp;
BEGIN
prop := f.rider.attr.Prop()(Properties.StdProp);
prop.color.val := Ports.grey25;
f.rider.SetAttr(TextModels.ModifiedAttr(f.rider.attr, prop))
END SetGray;
PROCEDURE SetDefColor(f: TextMappers.Formatter);
VAR prop: Properties.StdProp;
BEGIN
prop := f.rider.attr.Prop()(Properties.StdProp);
prop.color.val := Ports.defaultColor;
f.rider.SetAttr(TextModels.ModifiedAttr(f.rider.attr, prop))
END SetDefColor;
PROCEDURE WritePackList(f: TextMappers.Formatter; v: View);
CONST colsPerRow = 3;
VAR head, tail: Files.Name; l: List; col: INTEGER;
BEGIN
l := v.list; col := 0;
WHILE l # NIL DO
IF l.onlyImplicit THEN SetGray(f) ELSE SetDefColor(f) END;
Librarian.lib.SplitName(l.name, head, tail);
f.WriteString(head + "/Code/" + tail + ".ocf ");
INC(col); IF col >= colsPerRow THEN f.WriteLn; col := 0 END;
l := l.next
END;
SetGray(f); f.WriteString("System/Rsrc/Menus.odc")
END WritePackList;
PROCEDURE WriteCommand (IN f: TextMappers.Formatter; title: Dialog.String; cmd: TextModels.Model);
BEGIN
SetStyle(f, {bold}); f.WriteString(title); f.WriteLn;
SetStyle(f, {});
f.WriteView(StdFolds.dir.New(StdFolds.collapsed, "", cmd));
f.WriteString('command');
f.WriteView(StdFolds.dir.New(StdFolds.collapsed, "", NIL));
f.WriteLn; f.WriteLn
END WriteCommand;
PROCEDURE AddHeader (IN f: TextMappers.Formatter; v: View);
VAR sl: NameList; date: Dates.Date; time: Dates.Time; ds, ts: String;
BEGIN
Dates.GetDate(date); Dates.DateToString(date, Dates.plainLong, ds);
Dates.GetTime(time); Dates.TimeToString(time, ts);
SetStyle(f, {bold});
f.WriteString('Tool for: '); sl := v.startList;
WHILE sl # NIL DO f.WriteString(sl.name + ' '); sl := sl.next END; f.WriteLn;
SetStyle(f, {italic});f.WriteString('Created: ' + ds + ', ' + ts); f.WriteLn; f.WriteLn
END AddHeader;
PROCEDURE AddCompileList (IN f: TextMappers.Formatter; v: View);
VAR l: MetaList; m: TextModels.Model; hf:TextMappers.Formatter;
BEGIN
m := TextModels.dir.New(); hf.ConnectTo(m);
SetStyle(hf, {}); hf.WriteLn;
hf.WriteView(DevCommanders.dir.New()); hf.WriteString(' DevCompiler.CompileThis '); hf.WriteLn;
DependencyList(v, ~full, l);
WHILE l # NIL DO
IF l.list.onlyImplicit THEN SetGray(hf) ELSE SetDefColor(hf) END;
hf.WriteString(l.list.name + ' ');
l := l.next
END;
hf.WriteView(DevCommanders.dir.NewEnd()); hf.WriteLn;
WriteCommand(f, 'To compile:', m)
END AddCompileList;
PROCEDURE WriteUnloadList(f: TextMappers.Formatter; l: MetaList);
BEGIN
IF l # NIL THEN
WriteUnloadList(f, l.next);
IF l.list.onlyImplicit THEN SetGray(f) ELSE SetDefColor(f) END;
f.WriteString(l.list.name + ' ')
END
END WriteUnloadList;
PROCEDURE AddUnloadList (IN f: TextMappers.Formatter; v: View);
VAR l: MetaList; m: TextModels.Model; hf:TextMappers.Formatter;
BEGIN
m := TextModels.dir.New(); hf.ConnectTo(m);
SetStyle(hf, {}); hf.WriteLn;
hf.WriteView(DevCommanders.dir.New()); hf.WriteString(' DevDebug.UnloadThis '); hf.WriteLn;
DependencyList(v, ~full, l);
WriteUnloadList(hf, l); hf.WriteView(DevCommanders.dir.NewEnd()); hf.WriteLn;
WriteCommand(f, 'To unload:', m)
END AddUnloadList;
PROCEDURE AddLinkList (IN f: TextMappers.Formatter);
VAR m: TextModels.Model; hf:TextMappers.Formatter;
BEGIN
m := TextModels.dir.New(); hf.ConnectTo(m);
SetStyle(hf, {}); hf.WriteLn;
hf.WriteView(DevCommanders.dir.New()); hf.WriteString(' DevLinker.Link exefilename.exe := '); hf.WriteLn;
hf.WriteString('Kernel$+ Files HostFiles HostPackedFiles StdLoader'); hf.WriteLn;
hf.WriteString('1 Applogo.ico 2 Doclogo.ico 3 SFLogo.ico 4 CFLogo.ico 5 DtyLogo.ico'); hf.WriteLn;
hf.WriteString('6 folderimg.ico 7 openimg.ico 8 leafimg.ico'); hf.WriteLn;
hf.WriteString('1 Move.cur 2 Copy.cur 3 Link.cur 4 Pick.cur 5 Stop.cur 6 Hand.cur 7 Table.cur');
hf.WriteView(DevCommanders.dir.NewEnd()); hf.WriteLn;
WriteCommand(f, 'To link (executable to which files can be packed):', m)
END AddLinkList;
PROCEDURE AddPackList (IN f: TextMappers.Formatter; v: View);
VAR m: TextModels.Model; hf:TextMappers.Formatter;
BEGIN
m := TextModels.dir.New(); hf.ConnectTo(m);
SetStyle(hf, {}); hf.WriteLn;
hf.WriteView(DevCommanders.dir.New()); hf.WriteString(' DevPacker.PackThis exefilename.exe :='); hf.WriteLn;
WritePackList(hf, v);
hf.WriteView(DevCommanders.dir.NewEnd()); hf.WriteLn;
WriteCommand(f, 'To pack:', m)
END AddPackList;
PROCEDURE AddRootList (IN f: TextMappers.Formatter; v: View);
VAR m: TextModels.Model; hf:TextMappers.Formatter; l: List;
BEGIN
m := TextModels.dir.New(); hf.ConnectTo(m);
SetStyle(hf, {italic}); hf.WriteLn;
hf.WriteString('(modules which are not imported from any other modules)'); hf.WriteLn;
SetStyle(hf, {});
l := v.list;
WHILE l # NIL DO
IF ~l.isImported THEN
IF l.onlyImplicit THEN SetGray(hf) ELSE SetDefColor(hf) END;
hf.WriteString(l.name + ' ')
END;
l := l.next
END;
hf.WriteLn;
WriteCommand(f, 'Root modules:', m)
END AddRootList;
PROCEDURE (v: View) CreateTool, NEW;
VAR t: TextModels.Model; f: TextMappers.Formatter; tv: TextViews.View;
BEGIN
MarkImplicitModules(v);
t := TextModels.dir.New(); f.ConnectTo(t); f.SetPos(0); SetStyle(f, {bold});
AddHeader(f, v);
AddCompileList(f, v);
AddUnloadList(f, v);
AddLinkList(f);
AddPackList(f, v);
AddRootList(f, v);
tv := TextViews.dir.New(t); Views.OpenView(tv)
END CreateTool;
PROCEDURE CreateToolClick*;
VAR v: View;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN v.CreateTool END
END CreateToolClick;
PROCEDURE SelGuard* (VAR par: Dialog.Par);
VAR e: ExpandOp; v: View;
BEGIN
v := Controllers.FocusView()(View);
IF v = NIL THEN
par.disabled := TRUE
ELSE
NEW(e); e.view := v; e.AddSelection;
par.disabled := (e.mods = NIL) & (e.subs = NIL)
END
END SelGuard;
PROCEDURE ModsGuard* (VAR par: Dialog.Par);
VAR e: ExpandOp; v: View;
BEGIN
v := Controllers.FocusView()(View);
IF v = NIL THEN
par.disabled := TRUE
ELSE
NEW(e); e.view := v; e.AddSelection;
par.disabled := e.mods = NIL
END
END ModsGuard;
PROCEDURE SubsGuard* (VAR par: Dialog.Par);
VAR e: ExpandOp; v: View;
BEGIN
v := Controllers.FocusView()(View);
IF v = NIL THEN
par.disabled := TRUE
ELSE
NEW(e); e.view := v; e.AddSelection;
par.disabled := e.subs = NIL
END
END SubsGuard;
PROCEDURE ShowBasicGuard* (VAR par: Dialog.Par);
VAR v: View;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN
par.checked := v.showBasic
ELSE
par.disabled := TRUE
END
END ShowBasicGuard;
(** Initialization **)
PROCEDURE SetBasic(v: View);
VAR str: String; t: TextModels.Model; s: TextMappers.Scanner; l, n, sl: NameList; sslist: SubsystemList;
sub, mod: String;
BEGIN
Dialog.MapString("#Dev:BasicSystems", str);
l := NIL;
IF str # "BasicSystems" THEN
t := TextModels.dir.NewFromString(str); s.ConnectTo(t); s.SetPos(0); s.Scan;
WHILE s.type # TextMappers.eot DO
IF s.type = TextMappers.string THEN
sl := v.startList;
Librarian.lib.SplitName(sl.name, sub, mod);
WHILE (sl # NIL) & (sub # s.string) DO
Librarian.lib.SplitName(sl.name, sub, mod);
sl := sl.next
END;
IF sl = NIL THEN NEW(n); n.name := s.string$; n.next := l; l := n END
END;
s.Scan
END;
sslist := v.subsystems; INC(v.maxLevel);
WHILE sslist # NIL DO
n := l;
WHILE (n # NIL) & (sslist.name # n.name) DO n := n.next END;
IF n # NIL THEN
sslist.isBasic := TRUE; INC(sslist.level)
END;
sslist := sslist.next
END
END
END SetBasic;
PROCEDURE StartAnalysis(startList: NameList; font: Fonts.Font; incImpl: BOOLEAN; OUT v: View);
VAR rootNode: List; sl: NameList;
BEGIN
NEW(v); Stores.Join(v, startList);
v.showBasic := FALSE;
IF font = NIL THEN font := Fonts.dir.Default() END;
v.normfont := Fonts.dir.This(font.typeface, font.size, font.style, Fonts.normal);
v.selfont := Fonts.dir.This(font.typeface, font.size, font.style, Fonts.bold);
v.startList := startList; v.subsystems := NIL; v.list := NIL; v.maxLevel := 2; v.nofMods := 0;
sl := startList;
WHILE sl # NIL DO
v.GetNode(sl.name, incImpl, rootNode);
sl := sl.next
END;
SetBasic(v); v.SetExtents()
END StartAnalysis;
PROCEDURE NewAnalysisClick*;
VAR
v, nv: View;
l: List; nl, start: NameList;
BEGIN
v := Controllers.FocusView()(View);
IF v # NIL THEN
l := v.list; start := NIL;
WHILE l # NIL DO
IF l.Selected() THEN NEW(nl); nl.name := l.name; nl.next := start; start := nl END;
l := l.next
END;
IF start # NIL THEN
StartAnalysis(start, v.normfont, implicit, nv);
IF nv.list # NIL THEN Views.Deposit(nv); StdCmds.Open END
END
END
END NewAnalysisClick;
PROCEDURE Analyze (OUT v: View);
VAR startList: NameList;
BEGIN
GetModuleList(startList);
IF startList # NIL THEN StartAnalysis(startList, NIL, implicit, v)
ELSE Dialog.ShowMsg("#Dev:NoModuleNameSelected")
END
END Analyze;
PROCEDURE Deposit*;
VAR v: View;
BEGIN
Analyze(v); Views.Deposit(v)
END Deposit;
PROCEDURE CreateTool*;
VAR v: View;
BEGIN
Analyze(v); IF v.list # NIL THEN v.CreateTool END
END CreateTool;
END DevDependencies.
"DevDependencies.Deposit;StdCmds.Open"
DevDependencies.CreateTool
| Dev/Mod/Dependencies.odc |
MODULE DevHeapSpy;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20160324, center #111, code cleanups
"
issues = "
- ...
"
**)
IMPORT
S := SYSTEM, Kernel, Utf, Strings, Ports, Models, Views, Services, Stores,
Properties, Dialog, Controllers, Documents, DevDebug;
CONST
resolution = 8; (* one pixel represents resolution bytes *)
lineW = 512; (* one line is 512 pixels long, i.e. represents 512 * resolution bytes *)
lineH = 5; (* one line is lineH pixels high *)
lineVertM = 3; (* margin between two lines *)
lineHorM = 2; (* margin between vertical cluster edge and lines *)
cluW = lineW + 2*lineHorM;
cluHorM = 4; (* cluHorM pixels between left view edge and vertical cluster edge *)
cluTopM = 8; (* cluTopM pixels between clusters *)
W = (2*cluHorM + cluW) * Ports.point;
TYPE
Block = POINTER TO RECORD [untagged]
tag: Kernel.Type;
size: INTEGER; (* size of free blocks *)
actual: INTEGER;
first: INTEGER
END;
Cluster = POINTER TO RECORD [untagged]
size: INTEGER; (* total size *)
next: Cluster;
END;
View = POINTER TO RECORD (Views.View)
height: INTEGER
END;
Model = POINTER TO RECORD (Models.Model)
alloc: INTEGER
END;
Action = POINTER TO RECORD (Services.Action) END;
Msg = RECORD (Models.Message) END;
VAR
mem: Model;
par-: RECORD
allocated-: INTEGER; (* number of bytes currently allocated *)
clusters-: INTEGER; (* number of clusters currently allocated *)
heapsize-: INTEGER (* total bytes currently allocated for heap *)
END;
PROCEDURE Append (VAR s: ARRAY OF CHAR; t: ARRAY OF CHAR);
VAR len, i, j: INTEGER; ch: CHAR;
BEGIN
len := LEN(s);
i := 0; WHILE s[i] # 0X DO INC(i) END;
j := 0; REPEAT ch := t[j]; s[i] := ch; INC(j); INC(i) UNTIL (ch = 0X) OR (i = len);
s[len - 1] := 0X
END Append;
PROCEDURE SizeOf (f: SHORTCHAR; t: Kernel.Type): INTEGER;
VAR x: INTEGER;
BEGIN
CASE f OF
| 0BX: RETURN 0
| 1X, 2X, 4X: RETURN 1
| 3X, 5X: RETURN 2
| 8X, 0AX: RETURN 8
| 11X: RETURN t.size
| 12X:
x := S.VAL(INTEGER, t.base[0]);
IF x DIV 256 # 0 THEN x := t.base[0].id MOD 4 + 16 END;
RETURN t.size * SizeOf(SHORT(CHR(x)), t.base[0])
ELSE RETURN 4
END
END SizeOf;
PROCEDURE FormOf (t: Kernel.Type): SHORTCHAR;
BEGIN
IF S.VAL(INTEGER, t) DIV 256 = 0 THEN
RETURN SHORT(CHR(S.VAL(INTEGER, t)))
ELSE
RETURN SHORT(CHR(16 + t.id MOD 4))
END
END FormOf;
PROCEDURE WriteName (t: Kernel.Type; OUT s: ARRAY OF CHAR);
VAR modName, name: Kernel.Name; f: SHORTCHAR;
BEGIN
f := FormOf(t);
CASE f OF
| 0X: Dialog.MapString("#Dev:Undefined", s)
| 1X: s := "BOOLEAN"
| 2X: s := "SHORTCHAR"
| 3X: s := "CHAR"
| 4X: s := "BYTE"
| 5X: s := "SHORTINT"
| 6X: s := "INTEGER"
| 7X: s := "SHORTREAL"
| 8X: s := "REAL"
| 9X: s := "SET"
| 0AX: s := "LONGINT"
| 0BX: s := "ANYREC"
| 0CX: s := "ANYPTR"
| 0DX: s := "POINTER"
| 0EX: s := "PROCEDURE"
| 0FX: s := "STRING"
| 10X, 11X, 13X:
IF (t.id DIV 256 # 0) & (t.mod.refcnt >= 0) THEN
Kernel.GetModName(t.mod, modName); s := modName$; Append(s, ".");
Kernel.GetTypeName(t, name); Append(s, name)
(* s := modName + "." + name; *)
ELSIF f = 11X THEN
Kernel.GetModName(t.mod, modName); s := modName$; Append(s, ".RECORD");
(* s := modName + ".RECORD"; *)
ELSIF f = 13X THEN
s := "POINTER"
ELSE
s := "PROCEDURE"
END
| 20X: s := "COM.IUnknown"
| 21X: s := "COM.GUID"
| 22X: s := "COM.RESULT"
ELSE Dialog.MapString("#Dev:UnknownFormat", s)
END
END WriteName;
PROCEDURE Next (b: Block): Block; (* next block in same cluster *)
VAR size: INTEGER; tag: Kernel.Type;
BEGIN
tag := S.VAL(Kernel.Type, S.VAL(INTEGER, b.tag) DIV 4 * 4);
size := tag.size + 4;
IF ODD(S.VAL(INTEGER, b.tag) DIV 2) THEN size := b.size - S.ADR(b.size) + size END;
size := (size + 15) DIV 16 * 16;
RETURN S.VAL(Block, S.VAL(INTEGER, b) + size)
END Next;
PROCEDURE ClusterHeight (size: INTEGER): INTEGER;
(* height of a cluster in pixels *)
VAR noflines: INTEGER;
BEGIN
noflines := ((size DIV resolution) + (lineW-1)) DIV lineW;
RETURN noflines * (lineH + lineVertM) + lineVertM;
END ClusterHeight;
PROCEDURE ViewHeight(): INTEGER;
(* height of view in universal units *)
VAR cluster: Cluster; h: INTEGER;
BEGIN
cluster := S.VAL(Cluster, Kernel.Root()); h := 0;
WHILE cluster # NIL DO
INC(h, (cluTopM + ClusterHeight(cluster.size)) * Ports.point);
cluster := cluster.next;
END;
INC(h, cluTopM * Ports.point);
RETURN h;
END ViewHeight;
PROCEDURE PaintMem (f: Views.Frame; top, bottom: INTEGER);
VAR cluster: Cluster; b0, blk, next: Block; end: INTEGER;
clusterTop, clusterH, x, x1, y: INTEGER; (* units *)
dot, painted, runlen: INTEGER;
c, c0: INTEGER;
BEGIN
dot := (Ports.point DIV f.dot) * f.dot;
IF dot = 0 THEN dot := f.dot END;
clusterTop := 0;
cluster := S.VAL(Cluster, Kernel.Root());
WHILE cluster # NIL DO
INC(clusterTop, cluTopM*dot);
clusterH := ClusterHeight(cluster.size) * dot;
IF (clusterTop - cluTopM < bottom) OR (clusterTop + clusterH > top) THEN
f.DrawRect(cluHorM*dot, clusterTop, (cluHorM+cluW)*dot, clusterTop + clusterH,
Ports.fill, Ports.grey25);
(* scan cluster and draw blocks *)
blk := S.VAL(Block, S.VAL(INTEGER, cluster) + 12);
end := S.VAL(INTEGER, blk) + (cluster.size - 12) DIV 16 * 16;
b0 := blk; c0 := -1;
y := clusterTop + lineVertM*dot;
painted := 16 DIV resolution; (* nof pixels already painted on current line *)
x := (cluHorM+lineHorM+painted)*dot;
WHILE S.VAL(INTEGER, blk) < end DO
IF S.VAL(INTEGER, blk.tag) = S.ADR(blk.size) THEN (* free block *)
c := -1; next := S.VAL(Block, S.VAL(INTEGER, blk) + blk.size + 4)
ELSIF 1 IN S.VAL(SET, blk.tag) THEN (* array *)
c := Ports.blue; next := Next(blk)
ELSE (* record *)
c := Ports.red; next := S.VAL(Block, S.VAL(INTEGER, blk) + (blk.tag.size + 19) DIV 16 * 16)
END;
IF c # c0 THEN
runlen := (S.VAL(INTEGER, blk) - S.VAL(INTEGER, b0)) DIV resolution;
WHILE runlen > lineW-painted DO
x1 := (cluHorM+lineHorM+lineW)*dot;
IF (c0 # -1) & (x < x1) THEN
f.DrawRect(x, y, x1, y + lineH * dot, Ports.fill, c0)
END;
DEC(runlen, lineW-painted); painted := 0;
x := (cluHorM+lineHorM)*dot; INC(y, (lineH+lineVertM) * dot);
END;
IF runlen > 0 THEN
IF c0 # -1 THEN f.DrawRect(x, y, x + runlen*dot, y + lineH * dot, Ports.fill, c0) END;
INC(painted, runlen); INC(x, runlen*dot);
END;
b0 := blk; c0 := c
END;
blk := next
END;
IF c0 # -1 THEN
runlen := (S.VAL(INTEGER, end) - S.VAL(INTEGER, b0)) DIV resolution;
WHILE runlen > lineW-painted DO
f.DrawRect(x, y, (cluHorM+lineHorM+lineW)*dot, y + lineH * dot, Ports.fill, c0);
DEC(runlen, lineW-painted); painted := 0;
x := (cluHorM+lineHorM)*dot; INC(y, (lineH+lineVertM) * dot);
END;
IF runlen > 0 THEN f.DrawRect(x, y, x + runlen*dot, y + lineH * dot, Ports.fill, c0) END;
END
END;
cluster := cluster.next;
INC(clusterTop, clusterH);
END
END PaintMem;
PROCEDURE MarkBlock (f: Views.Frame; sel: Block; on: BOOLEAN);
VAR cluster: Cluster; next: Block; end, offs, dot, col: INTEGER; found: BOOLEAN;
clusterTop, x, y, r, e: INTEGER; (* units *)
BEGIN
dot := (Ports.point DIV f.dot) * f.dot;
IF dot = 0 THEN dot := f.dot END;
clusterTop := 0;
cluster := S.VAL(Cluster, Kernel.Root()); found := FALSE;
WHILE (cluster # NIL) & ~found DO
end := S.VAL(INTEGER, cluster) + 12 + (cluster.size - 12) DIV 16 * 16;
INC(clusterTop, cluTopM * dot);
IF (S.VAL(INTEGER, cluster) <= S.VAL(INTEGER, sel)) & (S.VAL(INTEGER, sel) < end) THEN
found := TRUE;
ELSE
INC(clusterTop, ClusterHeight(cluster.size) * dot);
cluster := cluster.next;
END
END;
IF found THEN (* sel is contained in cluster *)
IF on THEN col := Ports.green
ELSIF 1 IN S.VAL(SET, sel.tag) THEN col := Ports.blue
ELSE col := Ports.red
END;
next := Next(sel);
r := (cluHorM + lineHorM + lineW) * dot;
offs := (S.VAL(INTEGER, sel) + 4 (* tag *) - S.VAL(INTEGER, cluster)) DIV resolution;
y := clusterTop + ((offs DIV lineW) * (lineH+lineVertM) + lineVertM) * dot;
x := (cluHorM + lineHorM + (offs MOD lineW)) * dot;
e := x + (S.VAL(INTEGER, next) - S.VAL(INTEGER, sel)) DIV resolution * dot;
WHILE e >= r DO
f.DrawRect(x, y, r, y + lineH * dot, Ports.fill, col);
INC(y, (lineH + lineVertM) * dot);
x := (cluHorM + lineHorM) * dot;
e := x + e - r;
END;
IF e > x THEN f.DrawRect(x, y, e, y + lineH * dot, Ports.fill, col) END;
END
END MarkBlock;
PROCEDURE ThisCluster (f: Views.Frame; sx, sy: INTEGER): Cluster;
VAR cluster: Cluster; dot, clusterTop, clusterH: INTEGER;
BEGIN
dot := (Ports.point DIV f.dot) * f.dot;
IF dot = 0 THEN dot := f.dot END;
cluster := NIL;
IF (cluHorM * dot <= sx) & (sx < (cluHorM + 2*lineHorM + lineW) * dot) THEN
cluster := S.VAL(Cluster, Kernel.Root());
clusterTop := 0;
WHILE cluster # NIL DO
INC(clusterTop, cluTopM * dot);
clusterH := ClusterHeight(cluster.size) * dot;
IF (clusterTop <= sy) & (sy < clusterTop + clusterH) THEN RETURN cluster
ELSE INC(clusterTop, clusterH); cluster := cluster.next;
END
END
END;
RETURN cluster;
END ThisCluster;
PROCEDURE ThisBlock (f: Views.Frame; sx, sy: INTEGER): Block;
VAR cluster: Cluster; blk, next: Block; found: BOOLEAN;
dot, lineno, offs, end, adr: INTEGER;
clusterTop, clusterH: INTEGER;
BEGIN
dot := (Ports.point DIV f.dot) * f.dot;
IF dot = 0 THEN dot := f.dot END;
IF (sx < (cluHorM + lineHorM) * dot) OR ((cluHorM + lineHorM + lineW) * dot <= sx) THEN
RETURN NIL
END;
cluster := S.VAL(Cluster, Kernel.Root());
clusterTop :=0; found := FALSE;
WHILE (cluster # NIL) & ~found DO
INC(clusterTop, cluTopM * dot);
clusterH := ClusterHeight(cluster.size) * dot;
IF (clusterTop <= sy) & (sy < clusterTop + clusterH) THEN found := TRUE
ELSE INC(clusterTop, clusterH); cluster := cluster.next;
END
END;
IF found THEN (* (sx, sy) points into cluster *)
lineno := ((sy - clusterTop) DIV dot) DIV (lineH + lineVertM);
offs := ((sy - clusterTop) DIV dot) MOD (lineH + lineVertM); (* vertical offset in line *)
IF (lineVertM <= offs) & (offs < lineH + lineVertM) THEN
offs := (sx DIV dot) - cluHorM - lineHorM; (* hor offset from left into line *)
adr := S.VAL(INTEGER, cluster) + (lineno * lineW + offs) * resolution;
(* we're looking for the block that contains address adr *)
blk := S.VAL(Block, S.VAL(INTEGER, cluster) + 12);
end := S.VAL(INTEGER, blk) + (cluster.size - 12) DIV 16 * 16;
WHILE S.VAL(INTEGER, blk) < end DO
next := Next(blk);
IF adr < S.VAL(INTEGER, next) THEN
IF S.VAL(INTEGER, blk.tag) # S.ADR(blk.size) THEN RETURN blk
ELSE RETURN NIL (* blk is a free block *)
END
ELSE blk := next
END
END;
RETURN NIL
ELSE (* (sx, sy) points between two lines *) RETURN NIL
END
ELSE RETURN NIL
END
END ThisBlock;
PROCEDURE SearchPath (this, that: Block; VAR path: ARRAY OF INTEGER; VAR len: INTEGER);
VAR father, son: Block; tag: Kernel.Type; flag, offset, actual, i: INTEGER; found: BOOLEAN;
BEGIN
i := 1; len := 0; found := FALSE;
IF ~ODD(S.VAL(INTEGER, this.tag)) THEN
father := NIL;
LOOP
INC(S.VAL(INTEGER, this.tag));
flag := S.VAL(INTEGER, this.tag) MOD 4;
tag := S.VAL(Kernel.Type, S.VAL(INTEGER, this.tag) - flag);
IF flag >= 2 THEN actual := this.first; this.actual := actual
ELSE actual := S.ADR(this.size)
END;
LOOP
IF (this = that) & ~found THEN len := i; found := TRUE END;
offset := tag.ptroffs[0];
IF offset < 0 THEN
INC(S.VAL(INTEGER, tag), offset + 4); (* restore tag *)
IF (flag >= 2) & (actual < this.size) & (offset < -4) THEN (* next array element *)
INC(actual, tag.size); this.actual := actual
ELSE (* up *)
this.tag := S.VAL(Kernel.Type, S.VAL(INTEGER, tag) + flag);
IF father = NIL THEN RETURN END;
son := this; this := father; DEC(i);
flag := S.VAL(INTEGER, this.tag) MOD 4;
tag := S.VAL(Kernel.Type, S.VAL(INTEGER, this.tag) - flag);
offset := tag.ptroffs[0];
IF flag >= 2 THEN actual := this.actual ELSE actual := S.ADR(this.size) END;
S.GET(actual + offset, father); S.PUT(actual + offset, S.ADR(son.size));
INC(S.VAL(INTEGER, tag), 4)
END
ELSE
S.GET(actual + offset, son);
IF (son # NIL) & ~found THEN
DEC(S.VAL(INTEGER, son), 4);
IF ~ODD(S.VAL(INTEGER, son.tag)) THEN (* down *)
IF i < LEN(path) THEN
IF flag < 2 THEN path[i] := offset
ELSE path[i] := actual - S.ADR(this.size) + offset
END
END;
INC(i);
this.tag := S.VAL(Kernel.Type, S.VAL(INTEGER, tag) + flag);
S.PUT(actual + offset, father); father := this; this := son;
EXIT
END
END;
INC(S.VAL(INTEGER, tag), 4)
END
END
END
END
END SearchPath;
PROCEDURE ResetMarks;
VAR cluster: Cluster; blk: Block; end: INTEGER;
BEGIN
cluster := S.VAL(Cluster, Kernel.Root());
WHILE cluster # NIL DO
blk := S.VAL(Block, S.VAL(INTEGER, cluster) + 12);
end := S.VAL(INTEGER, blk) + (cluster.size - 12) DIV 16 * 16;
WHILE S.VAL(INTEGER, blk) < end DO EXCL(S.VAL(SET, blk.tag), 0); blk := Next(blk) END;
cluster := cluster.next
END
END ResetMarks;
PROCEDURE SearchAnchor (blk: Block; VAR path: ARRAY OF CHAR);
VAR m, mod: Kernel.Module; ref, offs, i, j, k, p, x, a, n: INTEGER; offsets: ARRAY 1 OF INTEGER;
t, f: SHORTCHAR; desc: Kernel.Type; modName, name: Kernel.Name; tag, typ: Kernel.Type;
res: INTEGER; nn: Kernel.Utf8Name;
BEGIN
mod := NIL; offs := 0;
m := Kernel.ThisLoadedMod("HostWindows");
IF m # NIL THEN
ref := m.refs; Kernel.GetRefProc(ref, x, nn); Utf.Utf8ToString(nn, name, res);
IF x # 0 THEN
REPEAT
Kernel.GetRefVar(ref, t, f, desc, a, nn); Utf.Utf8ToString(nn, name, res);
UNTIL (t # 1X) OR (name = "winAnchor");
IF t = 1X THEN
S.GET(m.data + a, p);
IF p # 0 THEN
SearchPath(S.VAL(Block, p - 4), blk, offsets, n);
IF n > 0 THEN offs := 1 END
END
END
END
END;
m := Kernel.modList;
WHILE (mod = NIL) & (offs = 0) & (m # NIL) DO
IF m.refcnt >= 0 THEN
i := 0;
WHILE (mod = NIL) & (i < m.nofptrs) DO
S.GET(m.data + m.ptrs[i], p);
IF p # 0 THEN
SearchPath(S.VAL(Block, p - 4), blk, offsets, n);
IF n > 0 THEN mod := m; offs := m.ptrs[i] END
END;
INC(i)
END
END;
m := m.next
END;
ResetMarks;
IF offs # 0 THEN
IF mod # NIL THEN
Kernel.GetModName(mod, modName); path := modName$; Append(path, ".");
ref := mod.refs; Kernel.GetRefProc(ref, x, nn); Utf.Utf8ToString(nn, name, res);
IF x # 0 THEN
REPEAT
Kernel.GetRefVar(ref, t, f, desc, a, nn); Utf.Utf8ToString(nn, name, res);
UNTIL (t # 1X) OR (offs >= a) & (offs < a + SizeOf(f, desc));
IF t = 1X THEN Utf.Utf8ToString(nn, name, res); Append(path, name);
ELSE Append(path, "???")
END
END
ELSE path := "window list"
END;
i := 1;
WHILE (i < n) & (i < LEN(offsets)) DO
S.GET(p - 4, tag);
IF 1 IN S.VAL(SET, tag) THEN Append(path, "[]")
ELSE
k := 0;
REPEAT
typ := tag.base[k]; INC(k); j := 0;
WHILE (j < typ.fields.num) & (typ.fields.obj[j].offs # offsets[i]) DO INC(j) END;
UNTIL (j < typ.fields.num) OR (k > tag.id DIV 16 MOD 16);
IF j < typ.fields.num THEN
Kernel.GetObjName(typ.mod, S.ADR(typ.fields.obj[j]), name);
Append(path, "."); Utf.Utf8ToString(nn, name, res); Append(path, name);
ELSE
Append(path, ".?")
END
END;
S.GET(p + offsets[i], p); INC(i)
END
ELSE path := ""
END
END SearchAnchor;
PROCEDURE ShowBlock (blk: Block);
VAR title: ARRAY 1024 OF CHAR; path: ARRAY 1024 OF CHAR;
BEGIN
SearchAnchor(blk, path);
IF path # "" THEN
title := "Object anchored in ";
Append(title, path);
ELSE title := "Object not globally anchored"
END;
DevDebug.ShowHeapObject(S.ADR(blk.size), title)
END ShowBlock;
PROCEDURE BlockInfo (blk: Block; VAR s: ARRAY OF CHAR);
VAR tag: Kernel.Type; str: ARRAY 256 OF CHAR;
BEGIN
tag := blk.tag;
IF ODD(S.VAL(INTEGER, tag) DIV 2) THEN (* array *)
DEC(S.VAL(INTEGER, tag), 2);
IF (tag.mod.name = "Kernel") & (tag.fields.num = 1) THEN
tag := tag.fields.obj[0].struct
END;
WriteName(tag, str);
s := "ARRAY OF "; Append(s, str)
ELSE (* record *)
WriteName(tag, s)
END
END BlockInfo;
PROCEDURE HeapInfo (VAR size, nofclusters: INTEGER);
VAR cluster: Cluster;
BEGIN
nofclusters := 0; size := 0; cluster := S.VAL(Cluster, Kernel.Root());
WHILE cluster # NIL DO
INC(nofclusters); INC(size, cluster.size);
cluster := cluster.next
END;
END HeapInfo;
PROCEDURE (v: View) ThisModel (): Models.Model;
BEGIN
RETURN mem
END ThisModel;
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR h: INTEGER;
BEGIN
PaintMem(f, t, b);
h := ViewHeight();
IF h # v.height THEN v.context.SetSize(W, h) END;
END Restore;
PROCEDURE (v: View) HandleCtrlMsg (
f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View
);
VAR x, y: INTEGER; isDown: BOOLEAN; blk, b: Block; m: SET; c, lastC: Cluster;
s: ARRAY 100 OF CHAR; num: ARRAY 16 OF CHAR;
BEGIN
WITH msg: Controllers.TrackMsg DO
blk := NIL; lastC := NIL;
REPEAT
f.Input(x, y, m, isDown);
c := ThisCluster(f, x, y); b := ThisBlock(f, x, y);
IF (b # blk) OR (c # lastC) THEN
IF b # NIL THEN BlockInfo(b, s);
ELSIF c # NIL THEN s := "cluster of length ";
IF c.size MOD 1024 = 0 THEN
Strings.IntToString(c.size DIV 1024, num); Append(s, num); Append(s, " KB")
ELSE Strings.IntToString(c.size, num); Append(s, num); Append(s, " bytes")
END;
Append(s, " at address ");
Strings.IntToStringForm(S.VAL(INTEGER, c), Strings.hexadecimal, 9, "0", TRUE, num);
Append(s, num)
ELSE s := ""
END;
Dialog.ShowStatus(s)
END;
lastC := c;
IF b # blk THEN
IF blk # NIL THEN MarkBlock(f, blk, FALSE) END;
blk := b;
IF blk # NIL THEN MarkBlock(f, blk, TRUE) END
END
UNTIL ~isDown;
(* IF ~Dialog.showsStatus & (s # "") THEN Dialog.ShowMsg(s) END; *)
IF blk # NIL THEN
MarkBlock(f, blk, FALSE);
ShowBlock(blk)
END;
Dialog.ShowStatus("");
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: View) HandleModelMsg (VAR msg: Models.Message);
BEGIN
WITH msg: Msg DO Views.Update(v, Views.keepFrames)
ELSE
END
END HandleModelMsg;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.ResizePref DO msg.fixed := TRUE
| msg: Properties.FocusPref DO msg.hotFocus := TRUE
| msg: Properties.SizePref DO msg.w := W; msg.h := ViewHeight();
ELSE
END
ELSE
END
END HandlePropMsg;
PROCEDURE (m: Model) CopyFrom (source: Stores.Store), EMPTY;
PROCEDURE (a: Action) Do;
VAR alloc, size, nofclusters: INTEGER; msg: Msg;
BEGIN
alloc := Kernel.Allocated();
IF mem.alloc # alloc THEN
mem.alloc := alloc;
Models.Broadcast(mem, msg);
par.allocated := alloc;
HeapInfo(size, nofclusters);
IF nofclusters # par.clusters THEN par.clusters := nofclusters END;
IF size # par.heapsize THEN par.heapsize := size END;
Dialog.Update(par)
END;
Services.DoLater(a, Services.Ticks() + Services.resolution)
END Do;
PROCEDURE ShowHeap*;
VAR v: View; d: Documents.Document;
BEGIN
NEW(v); v.height := ViewHeight();
d := Documents.dir.New(v, W, v.height);
Views.OpenAux(d, "Heap Layout")
END ShowHeap;
PROCEDURE GetAnchor* (adr: INTEGER; OUT anchor: ARRAY OF CHAR);
BEGIN
SearchAnchor(S.VAL(Block, adr - 4), anchor);
END GetAnchor;
PROCEDURE ShowAnchor* (adr: INTEGER);
BEGIN
ShowBlock(S.VAL(Block, adr - 4))
END ShowAnchor;
PROCEDURE Init;
VAR action: Action;
BEGIN
NEW(mem); mem.alloc := 0;
Stores.InitDomain(mem);
NEW(action); Services.DoLater(action, Services.now)
END Init;
BEGIN Init
END DevHeapSpy.
| Dev/Mod/HeapSpy.odc |
MODULE DevInspector;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20151027, center #80, bug fix in GetTypeName/MapLabel for System resources
- 20160129, center #101, source link buttons added
"
issues = "
- ...
"
**)
IMPORT
Kernel, Services, Stores, Views, Controllers, Properties, Containers, Dialog,
Controls, Librarian,
TextModels, Files, Models, StdDialog, TextViews, TextControllers, Strings;
CONST
multiView = TRUE;
TYPE
Action = POINTER TO RECORD (Services.Action) END;
VAR
inspect*: RECORD
control-: Dialog.String;
label*: Dialog.String; (* ARRAY 40 OF CHAR; *)
link*, guard*, notifier*: Dialog.String;
level*: INTEGER;
opt0*, opt1*, opt2*, opt3*, opt4*: BOOLEAN;
known, valid: SET;
type: Stores.TypeName
END;
fingerprint: INTEGER;
action: Action;
PROCEDURE GetTypeName (v: Views.View; VAR t, s: ARRAY OF CHAR);
VAR c: Containers.Controller; w: Views.View; subs, cntr: Dialog.String;
BEGIN
s := ""; t := "";
IF multiView THEN
c := Containers.Focus();
IF c # NIL THEN
c.GetFirstView(Containers.selection, v); w := v;
WHILE (w # NIL) & Services.SameType(w, v) DO c.GetNextView(Containers.selection, w) END;
IF w # NIL THEN v := NIL END
END
END;
IF v # NIL THEN
Services.GetTypeName(v, t);
Librarian.lib.SplitName(t, subs, cntr);
Dialog.MapString("#" + subs + ":" + cntr, s);
IF s = cntr THEN Dialog.MapString("#Dev:" + t, s) END
END
END GetTypeName;
PROCEDURE PollProp (v: Views.View);
VAR msg: Properties.PollMsg; q: Properties.Property; p: Controls.Prop;
BEGIN
inspect.control := ""; inspect.link := ""; inspect.label := '';
inspect.guard := ""; inspect.notifier := ""; inspect.level := 0;
inspect.opt0 := FALSE; inspect.opt1 := FALSE;
inspect.opt2 := FALSE; inspect.opt3 := FALSE; inspect.opt4 := FALSE;
inspect.known := {}; inspect.valid := {};
IF multiView OR (v # NIL) THEN
GetTypeName(v, inspect.type, inspect.control);
IF multiView THEN
Properties.CollectProp(q)
ELSE
msg.prop := NIL; Views.HandlePropMsg(v, msg); q := msg.prop
END;
WHILE (q # NIL) & ~(q IS Controls.Prop) DO q := q.next END;
IF q # NIL THEN
p := q(Controls.Prop);
inspect.known := p.known; inspect.valid := p.valid;
IF Controls.link IN p.valid THEN inspect.link := p.link$ END;
IF Controls.label IN p.valid THEN inspect.label := p.label$ END;
IF Controls.guard IN p.valid THEN inspect.guard := p.guard$ END;
IF Controls.notifier IN p.valid THEN inspect.notifier := p.notifier$ END;
IF Controls.level IN p.valid THEN inspect.level := p.level END;
IF Controls.opt0 IN p.valid THEN inspect.opt0 := p.opt[0] END;
IF Controls.opt1 IN p.valid THEN inspect.opt1 := p.opt[1] END;
IF Controls.opt2 IN p.valid THEN inspect.opt2 := p.opt[2] END;
IF Controls.opt3 IN p.valid THEN inspect.opt3 := p.opt[3] END;
IF Controls.opt4 IN p.valid THEN inspect.opt4 := p.opt[4] END
END
END;
Dialog.Update(inspect)
END PollProp;
PROCEDURE SetProp (v: Views.View);
VAR p: Controls.Prop; msg: Properties.SetMsg;
BEGIN
IF multiView OR (v # NIL) THEN
NEW(p);
p.valid := inspect.valid;
p.link := inspect.link$; p.label := inspect.label$;
p.guard := inspect.guard$; p.notifier := inspect.notifier$;
p.level := inspect.level;
p.opt[0] := inspect.opt0;
p.opt[1] := inspect.opt1;
p.opt[2] := inspect.opt2;
p.opt[3] := inspect.opt3;
p.opt[4] := inspect.opt4;
IF multiView THEN Properties.EmitProp(NIL, p)
ELSE msg.old := NIL; msg.prop := p; Views.HandlePropMsg(v, msg)
END
END
END SetProp;
PROCEDURE Singleton (): Views.View;
VAR v: Views.View;
BEGIN
v := Containers.FocusSingleton();
RETURN v
END Singleton;
PROCEDURE (a: Action) Do;
VAR c: Containers.Controller; v: Views.View; fp: INTEGER;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
IF multiView THEN
c := Containers.Focus(); fp := 0;
IF c # NIL THEN
c.GetFirstView(TRUE, v);
WHILE v # NIL DO fp := fp + Services.AdrOf(v); c.GetNextView(TRUE, v) END
END
ELSE
v := Singleton();
IF v = NIL THEN fp := 0 ELSE fp := Services.AdrOf(v) END
END;
IF fp # fingerprint THEN PollProp(v); fingerprint := fp END;
Controllers.ResetCurrentPath();
Services.DoLater(action, Services.Ticks() + Services.resolution DIV 2)
END Do;
PROCEDURE InitDialog*;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
PollProp(Singleton());
Controllers.ResetCurrentPath()
END InitDialog;
PROCEDURE GetNext*;
VAR c: Containers.Controller; v: Views.View;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
c := Containers.Focus();
IF c # NIL THEN
IF c.HasSelection() THEN v := c.Singleton() ELSE v := NIL END;
IF v = NIL THEN
c.GetFirstView(Containers.any, v)
ELSE
c.GetNextView(Containers.any, v);
IF v = NIL THEN c.GetFirstView(Containers.any, v) END
END;
c.SelectAll(FALSE);
IF v # NIL THEN c.SetSingleton(v); c.MakeViewVisible(v) END;
PollProp(v)
ELSE Dialog.ShowMsg("#Dev:NoTargetFocusFound")
END;
Controllers.ResetCurrentPath()
END GetNext;
PROCEDURE Set*;
VAR v: Views.View;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
v := Singleton();
IF multiView OR (v # NIL) THEN SetProp(v); PollProp(v) END;
Controllers.ResetCurrentPath()
END Set;
PROCEDURE MapLabel (
IN control: Stores.TypeName; IN type: Dialog.String; i: INTEGER; VAR label: Dialog.String
);
VAR l, k, subs, cntr: Dialog.String; si: ARRAY 2 OF CHAR;
BEGIN
Librarian.lib.SplitName(control, subs, cntr);
si[0] := CHR(i + ORD("0")); si[1] := 0X;
k := cntr + "." + type + si;
Dialog.MapString("#" + subs + ":" + k, l);
IF l$ # k$ THEN label := l$ END
END MapLabel;
PROCEDURE OptGuard* (opt: INTEGER; VAR par: Dialog.Par);
VAR name: ARRAY 64 OF CHAR; num: ARRAY 2 OF CHAR;
BEGIN
ASSERT((opt >= 0) & (opt <= 9), 20);
IF ~(opt IN inspect.known) OR (inspect.type = "") THEN
par.disabled := TRUE
ELSE
num[0] := CHR(opt + ORD("0")); num[1] := 0X;
name := inspect.type + ".Opt" + num;
par.label := "#Dev:" + name;
Dialog.MapString(par.label, par.label);
IF par.label = name THEN par.label := "" END;
IF ~(opt IN inspect.valid) THEN par.undef := TRUE END;
MapLabel(inspect.type, "Opt", opt, par.label)
END
END OptGuard;
PROCEDURE LevelGuard* (VAR par: Dialog.Par);
BEGIN
IF ~(Controls.level IN inspect.known) THEN par.disabled := TRUE
ELSIF ~(Controls.level IN inspect.valid) THEN par.undef := TRUE
END;
IF inspect.type # "" THEN MapLabel(inspect.type, "Field", 5, par.label) END
END LevelGuard;
PROCEDURE NotifierGuard* (VAR par: Dialog.Par);
BEGIN
IF ~(Controls.notifier IN inspect.known) THEN par.disabled := TRUE
ELSIF ~(Controls.notifier IN inspect.valid) THEN par.undef := TRUE
END;
IF inspect.type # "" THEN MapLabel(inspect.type, "Field", 4, par.label) END
END NotifierGuard;
PROCEDURE GuardGuard* (VAR par: Dialog.Par);
BEGIN
IF ~(Controls.guard IN inspect.known) THEN par.disabled := TRUE
ELSIF ~(Controls.guard IN inspect.valid) THEN par.undef := TRUE
END;
IF inspect.type # "" THEN MapLabel(inspect.type, "Field", 3, par.label) END
END GuardGuard;
PROCEDURE LabelGuard* (VAR par: Dialog.Par);
BEGIN
IF ~(Controls.label IN inspect.known) THEN par.disabled := TRUE
ELSIF ~(Controls.label IN inspect.valid) THEN par.undef := TRUE
END;
IF inspect.type # "" THEN MapLabel(inspect.type, "Field", 2, par.label) END
END LabelGuard;
PROCEDURE LinkGuard* (VAR par: Dialog.Par);
BEGIN
IF ~(Controls.link IN inspect.known) THEN par.disabled := TRUE
ELSIF ~(Controls.link IN inspect.valid) THEN par.undef := TRUE
END;
IF inspect.type # "" THEN MapLabel(inspect.type, "Field", 1, par.label) END
END LinkGuard;
PROCEDURE ControlGuard* (VAR par: Dialog.Par);
BEGIN
IF inspect.known = {} THEN par.disabled := TRUE END
END ControlGuard;
PROCEDURE Notifier* (idx, op, from, to: INTEGER);
BEGIN
IF op = Dialog.changed THEN INCL(inspect.valid, idx) END
END Notifier;
PROCEDURE SearchIdent(t: TextModels.Model; startPos: INTEGER; ident: ARRAY OF CHAR; exp: BOOLEAN;
VAR beg, end: INTEGER);
VAR r: TextModels.Reader; found: BOOLEAN; ch: CHAR; len, i: INTEGER;
BEGIN
end := 0;
IF ident # "" THEN
r := t.NewReader(NIL); found := FALSE;
beg := startPos; r.SetPos(startPos); r.ReadChar(ch);
WHILE ~r.eot & ~found DO
(* search legal start symbol *)
WHILE ~r.eot & ~Strings.IsIdentStart(ch) DO
INC(beg); r.ReadChar(ch)
END;
i := 0; len := LEN(ident$);
WHILE ~r.eot & (i # len) & (ch = ident[i]) DO
r.ReadChar(ch); INC(i)
END;
found := (i = len) & ~Strings.IsIdent(ch);
IF ~r.eot & ~found THEN (* skip rest of identifier *)
beg := r.Pos() - 1;
WHILE ~r.eot & Strings.IsIdent(ch) DO
INC(beg); r.ReadChar(ch)
END
END;
IF found THEN
end := r.Pos() - 1;
IF exp THEN (* check for export mark *)
WHILE ~r.eot & (ch <= ' ') DO
r.ReadChar(ch);
END;
IF r.eot OR ((ch # '*') & (ch # '-')) THEN found := FALSE; beg := r.Pos() - 1; end := 0 END
END
ELSE
end := 0
END
END
END
END SearchIdent;
PROCEDURE OpenModule(module: ARRAY OF CHAR): TextModels.Model;
VAR loc: Files.Locator; name: Files.Name;
v: Views.View; m: Models.Model;
BEGIN
StdDialog.GetSubLoc(module, "Mod", loc, name);
Files.dir.GetFileName(name, Files.docType, name);
v := Views.OldView(loc, name);
IF v # NIL THEN
Views.Open(v, loc, name, NIL);
m := v.ThisModel();
IF (m # NIL) & (m IS TextModels.Model) THEN
RETURN m(TextModels.Model);
ELSE
Dialog.ShowParamMsg("#Dev:NoTextFileFound", "'" + name + "'", "", "")
END
ELSIF module = "" THEN Dialog.ShowMsg("#Dev:NoModNameFound")
ELSE Dialog.ShowParamMsg("#Dev:SourcefileNotFound", "'" + module + "'", "", "")
END;
RETURN NIL
END OpenModule;
PROCEDURE StartPos(t: TextModels.Model): INTEGER;
VAR varPos, procPos, beg, end: INTEGER;
BEGIN
SearchIdent(t, 0, "VAR", FALSE, beg, end);
IF end > 0 THEN varPos :=beg ELSE varPos := t.Length() END;
SearchIdent(t, 0, "PROCEDURE", FALSE, beg, end);
IF end > 0 THEN procPos :=beg ELSE procPos := t.Length() END;
(* note that guards and notifiers can also be procedure variables *)
RETURN MIN(varPos, procPos)
END StartPos;
PROCEDURE SearchSource(qualident: ARRAY OF CHAR);
VAR i, j, pos, beg, end, lastBeg, lastEnd: INTEGER; ch: CHAR; module, ident: ARRAY 256 OF CHAR;
t: TextModels.Model; found: BOOLEAN;
BEGIN
i := 0; ch := qualident[0];
WHILE (ch # 0X) & (ch # '.') DO
module[i] := ch; INC(i); ch := qualident[i]
END;
module[i] := 0X;
t := OpenModule(module$);
IF t # NIL THEN
found := TRUE; pos := StartPos(t); lastEnd := 0; ident := "";
WHILE found & (ch = '.') DO
j := 0; INC(i); ch := qualident[i];
WHILE Strings.IsIdent(ch) DO
ident[j] := ch; INC(i); INC(j); ch := qualident[i]
END;
ident[j] := 0X;
SearchIdent(t, pos, ident$, TRUE, beg, end);
found := end > 0;
IF found THEN lastBeg := beg; lastEnd := end; pos := end + 1
ELSIF ident # "" THEN
Dialog.ShowParamMsg("#Dev:NotFound", "'" + ident + "'", "", "")
END
END;
IF lastEnd > 0 THEN
TextViews.ShowRange(t, lastBeg, lastEnd, TextViews.any);
TextControllers.SetSelection(t, lastBeg, lastEnd)
END
END
END SearchSource;
PROCEDURE SearchKey(v: Views.View; loc: Files.Locator; name: Files.Name; key: ARRAY OF CHAR;
OUT found: BOOLEAN);
VAR m: Models.Model; t: TextModels.Model; R: TextModels.Reader; ch: CHAR; i, len, beg: INTEGER;
BEGIN
found := FALSE; m := v.ThisModel(); len := LEN(key$);
IF (m # NIL) & (m IS TextModels.Model) THEN
t := m(TextModels.Model);
R := t.NewReader(NIL); R.ReadChar(ch);
WHILE ~R.eot & ~found DO
i := 0; beg := R.Pos() - 1;
WHILE (~R.eot) & (i < len) & (ch = key[i]) DO INC(i); R.ReadChar(ch) END;
IF ~R.eot & (i = len) & (ch = TextModels.tab) THEN (* found *)
Views.Open(v, loc, name, NIL);
TextViews.ShowRange(t, beg, R.Pos() - 1, TextViews.any); (* works only if v is open *)
TextControllers.SetSelection(t, beg, R.Pos() - 1); (* works only if v is open *)
found := TRUE
ELSE (* skip rest of line *)
WHILE ~R.eot & (ch # TextModels.line) DO R.ReadChar(ch) END;
R.ReadChar(ch)
END
END
END
END SearchKey;
PROCEDURE OpenStrings(subsys: Files.Name; key, language: ARRAY OF CHAR;
OUT v: Views.View; OUT loc: Files.Locator; OUT name: Files.Name; OUT found: BOOLEAN);
BEGIN
name := "Strings"; v := NIL; found := FALSE;
loc := Files.dir.This(subsys).This("Rsrc");
IF language # "" THEN loc := loc.This(language) END ;
v := Views.OldView(loc, name);
IF v # NIL THEN
IF key # "" THEN SearchKey(v, loc, name, key, found)
ELSE found := TRUE; Views.Open(v, loc, name, NIL)
END
END
END OpenStrings;
PROCEDURE SearchStrings(key: ARRAY OF CHAR);
VAR subsys: Files.Name; i: INTEGER; ch: CHAR;
v: Views.View; loc: Files.Locator; name: Files.Name; found: BOOLEAN;
BEGIN
ASSERT(key[0] = "#", 20); ASSERT(key[1] # 0X, 21); ASSERT(key[1] # ":", 22);
i := 0; ch := key[1];
WHILE (ch # 0X) & (ch # ":") DO subsys[i] := ch; INC(i); ch := key[i + 1] END;
subsys[i] := 0X;
IF ch = ":" THEN Strings.Extract(key, i + 2, LEN(key$), key)
ELSE key := ""
END;
IF (Dialog.language # Dialog.defaultLanguage) & (Dialog.language # "") THEN
OpenStrings(subsys, key, Dialog.language, v, loc, name, found);
IF ~found THEN OpenStrings(subsys, key, "", v, loc, name, found) END
ELSE
OpenStrings(subsys, key, "", v, loc, name, found)
END ;
IF v = NIL THEN
Dialog.ShowParamMsg("#Dev:ResourceNotFound", "'" + name + "'", "'" + subsys + "'", "")
ELSIF ~found THEN
Views.Open(v, loc, name, NIL); Dialog.ShowParamMsg("#Dev:NotFound", "'" + key + "'", "", "")
END
END SearchStrings;
PROCEDURE LinkSourceGuard* (VAR par: Dialog.Par);
BEGIN
IF inspect.link = "" THEN par.disabled := TRUE END
END LinkSourceGuard;
PROCEDURE LinkSource*;
BEGIN
SearchSource(inspect.link)
END LinkSource;
PROCEDURE LabelSourceGuard* (VAR par: Dialog.Par);
BEGIN
IF (inspect.label[0] # "#") OR (inspect.label[1] = 0X) OR (inspect.label[1] = ":") THEN
par.disabled := TRUE
END
END LabelSourceGuard;
PROCEDURE LabelSource*;
BEGIN
SearchStrings(inspect.label)
END LabelSource;
PROCEDURE GuardSourceGuard* (VAR par: Dialog.Par);
BEGIN
IF inspect.guard = "" THEN par.disabled := TRUE END
END GuardSourceGuard;
PROCEDURE GuardSource*;
BEGIN
SearchSource(inspect.guard)
END GuardSource;
PROCEDURE NotifierSourceGuard* (VAR par: Dialog.Par);
BEGIN
IF inspect.notifier = "" THEN par.disabled := TRUE END
END NotifierSourceGuard;
PROCEDURE NotifierSource*;
BEGIN
SearchSource(inspect.notifier)
END NotifierSource;
BEGIN
NEW(action); Services.DoLater(action, Services.now)
END DevInspector.
DevCompiler.Compile
" DevInspector.InitDialog; StdCmds.OpenAuxDialog('Dev/Rsrc/Inspect', '#Dev:Inspect') "
" DevDebug.Unload; DevInspector.InitDialog; StdCmds.OpenAuxDialog('Dev/Rsrc/Inspect', '#Dev:Inspect') "
| Dev/Mod/Inspector.odc |
MODULE DevLinkChk;
(**
project = "BlackBox 2.0"
organization = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20150226, center #29, inconsistent checks for valid subsystem names
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 20170811, center #168, improvements in DevLinkChk
- 20170819, center #172, adding BOOLEAN parameters to StdInterpreter
"
issues = "
- ...
"
**)
IMPORT
Strings, Dialog, Files, Fonts, Ports, Converters, Views, Containers,
TextModels, TextMappers, TextViews, TextControllers, StdLinks, StdCmds;
CONST
oneSubsystem* = 0; globalSubsystem* = 1; allSubsystems* = 2;
linkCommand = "DevLinkChk.Open('";
TYPE
Iterator = POINTER TO IteratorDesc;
IteratorDesc = RECORD
root: Files.Locator;
locs: Files.LocInfo;
files: Files.FileInfo
END;
VAR
par*: RECORD
scope*: INTEGER; (* IN {oneSubsystem, globalSubsystem, allSubsystems} *)
subsystem*: ARRAY 16 OF CHAR;
legal: BOOLEAN (* legal => correct syntax for a subsystem name # "" *)
END;
default, link: TextModels.Attributes;
PROCEDURE MakeDocName (VAR name: Files.Name);
BEGIN
Files.dir.GetFileName(name, Files.docType, name);
END MakeDocName;
PROCEDURE New (root: Files.Locator): Iterator;
VAR i: Iterator;
BEGIN
NEW(i); i.root := root; i.locs := Files.dir.LocList(root); i.files := Files.dir.FileList(root);
(* could sort by name *)
RETURN i
END New;
PROCEDURE ReadLoc (i: Iterator; VAR loc: Files.Locator; VAR name: Files.Name);
BEGIN
IF i.locs # NIL THEN
loc := i.root.This(i.locs.name); ASSERT(loc.res = 0, 60);
name := i.locs.name$;
i.locs := i.locs.next
ELSE
loc := NIL; name := ""
END
END ReadLoc;
PROCEDURE ReadFile (i: Iterator; OUT name: Files.Name);
BEGIN
IF i.files # NIL THEN
name := i.files.name$;
i.files := i.files.next
ELSE
name := ""
END
END ReadFile;
(* similar to StdInterpreter.CallHook.Call but without calling the commands*)
PROCEDURE Stale (IN proc: ARRAY OF CHAR; text: TextModels.Model): BOOLEAN;
TYPE
Ident = Dialog.String;
CONST
ident = 0; dot = 1; semicolon = 2; eot = 3;
lparen = 4; rparen = 5; quote = 6; comma = 7; int = 8;
VAR
i, type, res: INTEGER; ch: CHAR; id: Ident; x: INTEGER;
par0: POINTER TO Dialog.String; numPar: INTEGER;
focusLoc: Files.Locator; focusFile: Files.Name;
PROCEDURE Error;
BEGIN res := 1
END Error;
PROCEDURE Init (VAR s: ARRAY OF CHAR);
BEGIN s := ""
END Init;
PROCEDURE GetCh;
BEGIN
IF i < LEN(proc) THEN ch := proc[i]; INC(i) ELSE ch := 0X END
END GetCh;
PROCEDURE Scan;
VAR j: INTEGER; num: ARRAY 32 OF CHAR; r: INTEGER;
BEGIN
IF res = 0 THEN
WHILE (ch # 0X) & (ch <= " ") DO GetCh END;
IF ch = 0X THEN
type := eot
ELSIF ch = "." THEN
type := dot; GetCh
ELSIF ch = ";" THEN
type := semicolon; GetCh
ELSIF ch = "(" THEN
type := lparen; GetCh
ELSIF ch = ")" THEN
type := rparen; GetCh
ELSIF ch = "'" THEN
type := quote; GetCh
ELSIF ch = "," THEN
type := comma; GetCh
ELSIF (ch >= "0") & (ch <= "9") OR (ch = "-") THEN
type := int; j := 0;
REPEAT
num[j] := ch; INC(j); GetCh
UNTIL (ch < "0") OR (ch > "9") & (ch < "A") OR (ch > "H");
num[j] := 0X; Strings.StringToInt(num, x, r)
ELSIF Strings.IsIdentStart(ch) THEN
type := ident;
id[0] := ch; j := 1; GetCh;
WHILE (ch # 0X) & (i < LEN(proc)) & Strings.IsIdent(ch) DO
id[j] := ch; INC(j); GetCh
END;
id[j] := 0X
ELSE Error
END
END
END Scan;
PROCEDURE String (VAR s: ARRAY OF CHAR);
VAR j: INTEGER;
BEGIN
IF type = quote THEN
j := 0;
WHILE (ch # 0X) & (ch # "'") & (j < LEN(s) - 1) DO
s[j] := ch; INC(j); GetCh
END;
s[j] := 0X;
IF ch = "'" THEN
GetCh; Scan
ELSE Error
END
ELSE Error
END
END String;
PROCEDURE ParamList ();
VAR sv: Ident;
BEGIN
numPar := 0; par0 := NIL;
IF type = lparen THEN Scan;
WHILE (type # rparen) & (res = 0) DO
IF type = quote THEN
String(sv);
IF numPar = 0 THEN NEW(par0); par0^ := sv$ END;
INC(numPar)
ELSIF type IN {int, ident} THEN (* non string params can be ignored here *)
Scan
ELSE Error
END;
IF type = comma THEN Scan
ELSIF type # rparen THEN Error
END
END;
Scan
END
END ParamList;
PROCEDURE CheckLink (IN m, p: ARRAY OF CHAR);
VAR loc: Files.Locator; i, j: INTEGER; ch: CHAR; fn: Files.Name;
rd: TextModels.Reader; v: Views.View; ident: Ident; lnk: StdLinks.Target;
BEGIN
IF m = "StdCmds" THEN
IF (p = "OpenBrowser") OR (p = "OpenDoc") OR (p = "OpenAuxDialog")
OR (p = "OpenToolDialog") OR (p = "OpenAux") THEN
IF (p = "OpenDoc") & (numPar = 1) OR (p # "OpenDoc") & (numPar = 2) THEN
loc := Files.dir.This(""); i := 0;
REPEAT
j := 0; ch := par0[i];
WHILE (ch # "/") & (ch # "\") & (ch # 0X) DO
fn[j] := ch; INC(j); INC(i); ch := par0[i]
END;
fn[j] := 0X;
IF ch # 0X THEN loc := loc.This(fn); INC(i)
END
UNTIL ch = 0X;
MakeDocName(fn);
focusLoc := loc;
focusFile := fn;
IF Files.dir.Old(loc, fn, Files.shared) = NIL THEN Error (* file not found *) END
ELSE Error
END
END
ELSIF m = "StdLinks" THEN
IF p = "ShowTarget" THEN
IF numPar = 1 THEN
IF focusLoc # NIL THEN v := Views.OldView(focusLoc, focusFile);
IF (v # NIL) & (v IS TextViews.View) THEN
rd := v(TextViews.View).ThisModel().NewReader(NIL)
ELSE
Error; RETURN
END
ELSE rd := text.NewReader(NIL)
END;
rd.ReadView(v);
WHILE ~rd.eot DO
IF v IS StdLinks.Target THEN
lnk := v(StdLinks.Target);
IF lnk.leftSide THEN lnk.GetIdent(ident);
IF ident = par0$ THEN RETURN (* target found *) END
END
END;
rd.ReadView(v)
END
END;
Error
END
END
END CheckLink;
PROCEDURE Command;
VAR left, right: Ident;
BEGIN
Init(left); Init(right);
left := id; Scan;
IF type = dot THEN (* Oberon command *)
Scan;
IF type = ident THEN
right := id; Scan; ParamList();
IF res = 0 THEN CheckLink(left, right) END
ELSE Error
END
ELSE Error
END
END Command;
BEGIN
res := 0; i := 0; type := 0; GetCh; Init(id); x := 0; focusLoc := NIL; focusFile := "";
Scan;
IF type = ident THEN
Command;
WHILE (type = semicolon) & (res = 0) DO Scan; Command END;
IF type # eot THEN Error END
ELSE Error
END;
RETURN res # 0
END Stale;
PROCEDURE GetCmd (IN path, file: Files.Name; pos: INTEGER; OUT cmd: ARRAY OF CHAR);
VAR p, bug0, bug1, bug2: ARRAY 128 OF CHAR;
BEGIN
Strings.IntToString(pos, p);
bug0 := linkCommand + path + "', '";
bug1 := bug0 + file + "', ";
bug2 := bug1 + p + ")";
cmd := bug2$
END GetCmd;
PROCEDURE CheckDoc (IN path, file: Files.Name; t: TextModels.Model;
VAR f: TextMappers.Formatter; tabs: INTEGER; check: BOOLEAN; VAR hit: BOOLEAN);
VAR r: TextModels.Reader; v: Views.View; cmd, cmd0: ARRAY 1024 OF CHAR;
i: INTEGER;
BEGIN
r := t.NewReader(NIL);
r.ReadView(v);
WHILE v # NIL DO
WITH v: StdLinks.Link DO
IF v.leftSide THEN
v.GetCmd(cmd);
IF (cmd # "") & (~check OR Stale(cmd, t)) THEN
hit := TRUE;
i := 0; WHILE i # tabs DO f.WriteTab; INC(i) END;
GetCmd(path, file, r.Pos() - 1, cmd0);
f.WriteView(StdLinks.dir.NewLink(cmd0));
f.rider.SetAttr(link);
f.WriteString(cmd);
f.rider.SetAttr(default);
f.WriteView(StdLinks.dir.NewLink(""));
f.WriteLn
END
END
ELSE
END;
r.ReadView(v)
END
END CheckDoc;
PROCEDURE CheckLoc (
IN path: Files.Name; loc: Files.Locator; name: Files.Name;
VAR f: TextMappers.Formatter; check: BOOLEAN; OUT hit: BOOLEAN
);
VAR i: Iterator; fname: Files.Name; v: Views.View; conv: Converters.Converter;
label, label0: INTEGER; hit0: BOOLEAN;
BEGIN
label := f.Pos(); hit := FALSE;
loc := loc.This(name);
i := New(loc);
ReadFile(i, fname);
IF fname # "" THEN f.WriteTab; f.WriteString(name); f.WriteLn END;
hit := FALSE;
WHILE fname # "" DO
label0 := f.Pos(); hit0 := FALSE;
MakeDocName(fname);
v := Views.Old(Views.dontAsk, loc, fname, conv);
IF (v # NIL) & (v IS TextViews.View) THEN
f.WriteTab; f.WriteTab; f.WriteString(fname); f.WriteLn;
CheckDoc(path, fname, v(TextViews.View).ThisModel(), f, 3, check, hit0);
IF ~hit0 THEN f.SetPos(label0) END;
hit := hit OR hit0
END;
ReadFile(i, fname)
END;
IF ~hit THEN f.SetPos(label) END
END CheckLoc;
PROCEDURE Equal (IN a, b: ARRAY OF CHAR): BOOLEAN;
VAR al, bl: Files.Name;
BEGIN
IF a = b THEN RETURN TRUE
ELSE Strings.ToLower(a, al); Strings.ToLower(b, bl); RETURN al = bl
END
END Equal;
PROCEDURE Check* (subsystem: ARRAY OF CHAR; scope: INTEGER; check: BOOLEAN);
VAR i: Iterator; root, loc: Files.Locator; name: Files.Name; hit0, hit1: BOOLEAN;
out: TextModels.Model; f: TextMappers.Formatter; label: INTEGER; title: Views.Title;
v: TextViews.View; c: Containers.Controller; path: Files.Name;
BEGIN
out := TextModels.dir.New(); f.ConnectTo(out);
IF check THEN
Dialog.MapString("#Dev:InconsistentLinks", title)
ELSE
Dialog.MapString("#Dev:Links", title)
END;
v := TextViews.dir.New(out);
(* set Browser mode: *)
c := v.ThisController();
c.SetOpts(c.opts + {Containers.noCaret} - {Containers.noSelection, Containers.noFocus});
Views.OpenAux(v, title);
default := TextModels.dir.attr;
link := TextModels.NewColor(default, Ports.blue);
link := TextModels.NewStyle(link, {Fonts.underline});
root := Files.dir.This("");
IF scope IN {globalSubsystem, allSubsystems} THEN
label := f.Pos();
Dialog.ShowStatus(".");
f.WriteString("."); f.WriteLn;
path := "Docu";
CheckLoc(path, root, "Docu", f, check, hit0);
path := "Mod";
CheckLoc(path, root, "Mod", f, check, hit1);
IF ~hit0 & ~hit1 THEN f.SetPos(label) END
END;
i := New(root);
ReadLoc(i, loc, name);
WHILE loc # NIL DO
IF (scope = allSubsystems) OR (scope = oneSubsystem) & Equal(name, subsystem) THEN
label := f.Pos();
Dialog.ShowStatus(name);
f.WriteString(name); f.WriteLn;
path := name + "/" + "Docu";
CheckLoc(path, loc, "Docu", f, check, hit0);
path := name + "/" + "Mod";
CheckLoc(path, loc, "Mod", f, check, hit1);
IF ~hit0 & ~hit1 THEN f.SetPos(label) END
END;
ReadLoc(i, loc, name)
END;
out.Delete(f.Pos(), out.Length());
Dialog.ShowStatus(""); default := NIL; link := NIL
END Check;
PROCEDURE PathToLoc (IN path: ARRAY OF CHAR; OUT loc: Files.Locator);
VAR i, j: INTEGER; ch: CHAR; name: ARRAY 256 OF CHAR;
BEGIN
loc := Files.dir.This("");
IF path # "" THEN
i := 0; j := 0;
REPEAT
ch := path[i]; INC(i);
IF (ch = "/") OR (ch = 0X) THEN name[j] := 0X; j := 0; loc := loc.This(name)
ELSE name[j] := ch; INC(j)
END
UNTIL (ch = 0X) OR (loc.res # 0)
END
END PathToLoc;
PROCEDURE Open* (path, file: ARRAY OF CHAR; pos: INTEGER);
VAR loc: Files.Locator; v: Views.View; bug: Files.Name; c: TextControllers.Controller;
BEGIN
ASSERT(file # "", 20); ASSERT(pos >= 0, 21);
PathToLoc(path, loc); ASSERT(loc # NIL, 22);
bug := file$;
v := Views.OldView(loc, bug);
IF v # NIL THEN
WITH v: TextViews.View DO
(* v.DisplayMarks(TextViews.show); *)
Views.Open(v, loc, bug, NIL);
c := v.ThisController()(TextControllers.Controller);
c.SetCaret(pos);
v.ShowRange(pos, pos + 1, TextViews.focusOnly);
ELSE
HALT(23)
END
END
END Open;
PROCEDURE ListLinks*;
(** Guard: CommandGuard **)
BEGIN
StdCmds.CloseDialog; Check(par.subsystem, par.scope, FALSE)
END ListLinks;
PROCEDURE CheckLinks*;
(** Guard: CommandGuard **)
BEGIN
StdCmds.CloseDialog; Check(par.subsystem, par.scope, TRUE)
END CheckLinks;
PROCEDURE SubsystemGuard* (VAR p: Dialog.Par);
BEGIN
p.readOnly := par.scope # oneSubsystem
END SubsystemGuard;
PROCEDURE CommandGuard* (VAR p: Dialog.Par);
BEGIN
p.disabled := (par.scope = oneSubsystem) & ~par.legal
END CommandGuard;
PROCEDURE SyntaxOK(IN s: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; ch: CHAR;
BEGIN
i := 0; ch := s[0];
IF ~Strings.IsIdentStart(ch) THEN RETURN FALSE END ;
WHILE Strings.IsUpper(ch) DO INC(i); ch := s[i] END ;
IF ch = 0X THEN RETURN FALSE END ;
WHILE Strings.IsIdent(ch) & ~Strings.IsUpper(ch) DO INC(i); ch := s[i] END ;
RETURN ch = 0X
END SyntaxOK;
PROCEDURE SubsystemNotifier* (op, from, to: INTEGER);
BEGIN
IF par.scope = oneSubsystem THEN
par.legal := SyntaxOK(par.subsystem)
ELSE
par.subsystem := ""; par.legal := FALSE
END
END SubsystemNotifier;
END DevLinkChk.
| Dev/Mod/LinkChk.odc |
MODULE DevLinker;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070123, bh, support for more general resource files
- 20120531, BdT, changes for correction of Microsoft AppLocker problem
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20141027, center #24, fixing the name table handling in DevLinker
- 20160324, center #111, code cleanups
- 20181111, center #190, add comment about stack and heap memory configuration
- 20210405, Riga, error variable now exported as read-only, being set in LinkIt
"
issues = "
- ...
"
**)
IMPORT
Kernel, Files, Dates, Dialog, Strings, TextMappers, StdLog, DevCommanders, Utf, Librarian;
CONST
NewRecFP = 4E27A847H;
NewArrFP = 76068C78H;
ImageBase = 00400000H;
ObjAlign = 1000H;
FileAlign = 200H;
HeaderSize = 400H;
FixLen = 30000;
RsrcDir = "Rsrc";
WinDir = "Win";
(* meta interface consts *)
mConst = 1; mTyp = 2; mVar = 3; mProc = 4; mField = 5;
mInternal = 1; mReadonly = 2; mExported = 4;
(* fixup types *)
absolute = 100; relative = 101; copy = 102; table = 103; tableend = 104;
(* mod desc fields *)
modOpts = 4; modRefcnt = 8; modTerm = 40; modNames = 84; modImports = 92; modExports = 96;
TYPE
Name = Kernel.Utf8Name;
Export = POINTER TO RECORD
next: Export;
name: Name;
adr: INTEGER
END;
Resource = POINTER TO RECORD
next, local: Resource;
typ, id, lid, size, pos, x, y: INTEGER;
opts: SET;
file: Files.File;
name: Files.Name
END;
Module = POINTER TO RECORD
next: Module;
name: Files.Name;
file: Files.File;
hs, ms, ds, cs, vs, ni, ma, ca, va: INTEGER;
dll, intf: BOOLEAN;
exp: Export;
imp: POINTER TO ARRAY OF Module;
data: POINTER TO ARRAY OF BYTE;
END;
VAR
W: TextMappers.Formatter;
Out: Files.File;
R: Files.Reader;
Ro: Files.Writer;
error-, (* TRUE if a command has been successful, see LinkIt *)
isDll, isStatic, comLine: BOOLEAN;
modList, kernel, main, last, impg, impd: Module;
numMod, lastTerm: INTEGER;
resList: Resource;
numType, resHSize: INTEGER;
numId: ARRAY 32 OF INTEGER;
rsrcName: ARRAY 16 OF CHAR; (* name of resource file *)
firstExp, lastExp: Export;
entryPos, isPos, fixPos, himpPos, hexpPos, hrsrcPos, termPos: INTEGER;
codePos, dataPos, conPos, rsrcPos, impPos, expPos, relPos: INTEGER;
CodeSize, DataSize, ConSize, RsrcSize, ImpSize, ImpHSize, ExpSize, RelocSize, DllSize: INTEGER;
CodeRva, DataRva, ConRva, RsrcRva, ImpRva, ExpRva, RelocRva, ImagesSize: INTEGER;
CodeBase, DataBase, ConBase, maxCode, numImp, numExp, noffixup, timeStamp: INTEGER;
newRec, newArr: Name;
fixups: POINTER TO ARRAY OF INTEGER;
code: POINTER TO ARRAY OF BYTE;
atab: POINTER TO ARRAY OF INTEGER;
ntab: POINTER TO ARRAY OF SHORTCHAR;
PROCEDURE TimeStamp (): INTEGER; (* seconds since 1.1.1970 00:00:00 *)
VAR a: INTEGER; t: Dates.Time; d, epoch: Dates.Date;
BEGIN
Dates.GetUTCTime(t); Dates.GetUTCDate(d);
epoch.year := 1970; epoch.month := 1; epoch.day := 1;
a := Dates.Day(d) - Dates.Day(epoch);
RETURN ((a * 24 + t.hour) * 60 + t.minute) * 60 + t.second;
END TimeStamp;
PROCEDURE ThisFile (modname: ARRAY OF CHAR): Files.File;
VAR name: Files.Name; loc: Files.Locator;
BEGIN
Librarian.lib.GetSpec(modname, "CodeInt", loc, name);
RETURN Files.dir.Old(loc, name, TRUE)
END ThisFile;
PROCEDURE ThisResFile (VAR name: Files.Name): Files.File;
VAR loc: Files.Locator; f: Files.File;
BEGIN
f := Files.dir.Old(Files.dir.This(RsrcDir), name, TRUE);
IF f = NIL THEN
loc := Files.dir.This(WinDir); loc := loc.This(RsrcDir);
f := Files.dir.Old(loc, name, TRUE);
IF f = NIL THEN
f := Files.dir.Old(Files.dir.This(""), name, TRUE)
END
END;
RETURN f
END ThisResFile;
PROCEDURE Read2 (VAR x: INTEGER);
VAR b: BYTE;
BEGIN
R.ReadByte(b); x := b MOD 256;
R.ReadByte(b); x := x + 100H * (b MOD 256)
END Read2;
PROCEDURE Read4 (VAR x: INTEGER);
VAR b: BYTE;
BEGIN
R.ReadByte(b); x := b MOD 256;
R.ReadByte(b); x := x + 100H * (b MOD 256);
R.ReadByte(b); x := x + 10000H * (b MOD 256);
R.ReadByte(b); x := x + 1000000H * b
END Read4;
PROCEDURE ReadName (VAR name: ARRAY OF SHORTCHAR);
VAR i: INTEGER; b: BYTE;
BEGIN i := 0;
REPEAT
R.ReadByte(b); name[i] := SHORT(CHR(b)); INC(i)
UNTIL b = 0
END ReadName;
PROCEDURE RNum (VAR i: INTEGER);
VAR b: BYTE; s, y: INTEGER;
BEGIN
s := 0; y := 0; R.ReadByte(b);
WHILE b < 0 DO INC(y, ASH(b + 128, s)); INC(s, 7); R.ReadByte(b) END;
i := ASH((b + 64) MOD 128 - 64, s) + y
END RNum;
PROCEDURE WriteCh (ch: SHORTCHAR);
BEGIN
Ro.WriteByte(SHORT(ORD(ch)))
END WriteCh;
PROCEDURE Write2 (x: INTEGER);
BEGIN
Ro.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
Ro.WriteByte(SHORT(SHORT(x MOD 256)))
END Write2;
PROCEDURE Write4 (x: INTEGER);
BEGIN
Ro.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
Ro.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
Ro.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
Ro.WriteByte(SHORT(SHORT(x MOD 256)))
END Write4;
PROCEDURE WriteName (s: ARRAY OF SHORTCHAR; len: SHORTINT);
VAR i: SHORTINT;
BEGIN i := 0;
WHILE s[i] # 0X DO Ro.WriteByte(SHORT(ORD(s[i]))); INC(i) END;
WHILE i < len DO Ro.WriteByte(0); INC(i) END
END WriteName;
PROCEDURE WriteUtf8 (name: ARRAY OF SHORTCHAR);
VAR res: INTEGER; s: ARRAY 256 OF CHAR;
BEGIN
Utf.Utf8ToString(name, s, res); ASSERT(res = 0); W.WriteString(s)
END WriteUtf8;
PROCEDURE Reloc (a: INTEGER);
VAR p: POINTER TO ARRAY OF INTEGER; i: INTEGER;
BEGIN
IF noffixup >= LEN(fixups) THEN
NEW(p, 2 * LEN(fixups));
i := 0; WHILE i < LEN(fixups) DO p[i] := fixups[i]; INC(i) END;
fixups := p
END;
fixups[noffixup] := a; INC(noffixup)
(*
ELSE
IF ~error THEN W.WriteString(" too many fixups") END;
error := TRUE
END
*)
END Reloc;
PROCEDURE Put (mod: Module; a, x: INTEGER);
BEGIN
mod.data[a] := SHORT(SHORT(x)); INC(a); x := x DIV 256;
mod.data[a] := SHORT(SHORT(x)); INC(a); x := x DIV 256;
mod.data[a] := SHORT(SHORT(x)); INC(a); x := x DIV 256;
mod.data[a] := SHORT(SHORT(x))
END Put;
PROCEDURE Get (mod: Module; a: INTEGER; VAR x: INTEGER);
BEGIN
x := ((mod.data[a + 3] * 256 +
(mod.data[a + 2] MOD 256)) * 256 +
(mod.data[a + 1] MOD 256)) * 256 +
(mod.data[a] MOD 256)
END Get;
PROCEDURE Fixup0 (link, adr: INTEGER);
VAR offset, linkadr, t, n, x: INTEGER;
BEGIN
WHILE link # 0 DO
RNum(offset);
WHILE link # 0 DO
IF link > 0 THEN
n := (code[link] MOD 256) + (code[link+1] MOD 256) * 256 + code[link+2] * 65536;
t := code[link+3]; linkadr := CodeBase + impg.ca + link
ELSE
n := (impg.data[-link] MOD 256) + (impg.data[-link+1] MOD 256) * 256 + impg.data[-link+2] * 65536;
t := impg.data[-link+3]; linkadr := ConBase + impg.ma - link
END;
IF t = absolute THEN x := adr + offset
ELSIF t = relative THEN x := adr + offset - linkadr - 4
ELSIF t = copy THEN Get(impd, adr + offset - ConBase - impd.ma, x)
ELSIF t = table THEN x := adr + n; n := link + 4
ELSIF t = tableend THEN x := adr + n; n := 0
ELSE HALT(99)
END;
IF link > 0 THEN
code[link] := SHORT(SHORT(x));
code[link+1] := SHORT(SHORT(x DIV 100H));
code[link+2] := SHORT(SHORT(x DIV 10000H));
code[link+3] := SHORT(SHORT(x DIV 1000000H))
ELSE
link := -link;
impg.data[link] := SHORT(SHORT(x));
impg.data[link+1] := SHORT(SHORT(x DIV 100H));
impg.data[link+2] := SHORT(SHORT(x DIV 10000H));
impg.data[link+3] := SHORT(SHORT(x DIV 1000000H))
END;
IF (t # relative) & ((t # copy) OR (x DIV 65536 # 0)) THEN Reloc(linkadr) END;
link := n
END;
RNum(link)
END
END Fixup0;
PROCEDURE Fixup (adr: INTEGER);
VAR link: INTEGER;
BEGIN
RNum(link); Fixup0(link, adr)
END Fixup;
PROCEDURE CheckDllImports (mod: Module);
VAR i, x, y: INTEGER; name: Name; imp: Module; exp: Export;
PROCEDURE SkipLink;
VAR a: INTEGER;
BEGIN
RNum(a);
WHILE a # 0 DO RNum(a); RNum(a) END
END SkipLink;
BEGIN
R := mod.file.NewReader(R);
R.SetPos(mod.hs + mod.ms + mod.ds + mod.cs);
SkipLink; SkipLink; SkipLink; SkipLink; SkipLink; SkipLink; i := 0;
WHILE i < mod.ni DO
imp := mod.imp[i];
IF imp # NIL THEN
RNum(x);
WHILE x # 0 DO
ReadName(name); RNum(y);
IF x = mVar THEN SkipLink;
IF imp.dll THEN
W.WriteString("variable (");
W.WriteString(imp.name); W.WriteChar(".");
WriteUtf8(name);
W.WriteString(") imported from DLL in ");
W.WriteString(mod.name);
W.WriteLn; StdLog.text.Append(StdLog.buf); error := TRUE;
RETURN
END
ELSIF x = mTyp THEN RNum(y);
IF imp.dll THEN
RNum(y);
IF y # 0 THEN
W.WriteString("type descriptor (");
W.WriteString(imp.name); W.WriteChar(".");
WriteUtf8(name);
W.WriteString(") imported from DLL in ");
W.WriteString(mod.name);
W.WriteLn; StdLog.text.Append(StdLog.buf); error := TRUE;
RETURN
END
ELSE SkipLink
END
ELSIF x = mProc THEN
IF imp.dll THEN
SkipLink; exp := imp.exp;
WHILE (exp # NIL) & (exp.name # name) DO exp := exp.next END;
IF exp = NIL THEN
NEW(exp); exp.name := name$;
exp.next := imp.exp; imp.exp := exp; INC(DllSize, 6)
END
END
END;
RNum(x)
END
END;
INC(i)
END
END CheckDllImports;
PROCEDURE ReadHeaders;
VAR mod, im, t: Module; x, i: INTEGER; impdll: BOOLEAN; exp: Export; name: Name;
BEGIN
mod := modList; modList := NIL; numMod := 0;
WHILE mod # NIL DO (* reverse mod list & count modules *)
IF ~mod.dll THEN INC(numMod) END;
t := mod; mod := t.next; t.next := modList; modList := t
END;
IF isStatic THEN
IF isDll THEN
(* push ebx; cmp [12, esp], 1; jne L1; mov ebx, modlist; { call body; } jp L2 *)
(* L1: cmp [12, esp], 0; jne L2; { call term; } *)
(* L2: pop ebx; mov aex,1; ret 12 *)
CodeSize := 42 + 10 * numMod
ELSE
(* push ebx; push ebx; push ebx; mov ebx, modlist; { call body; } { call term; } *)
(* pop ebx; pop ebx; pop ebx; ret *)
CodeSize := 12 + 10 * numMod
END
ELSE
IF isDll THEN
(* push ebx; cmp [12, esp], 1; jne L1; mov ebx, modlist; call main; jp L2 *)
(* L1: cmp [12, esp], 0; jne L2; call mainTerm; *)
(* L2: pop ebx; mov aex,1; ret 12 *)
CodeSize := 41
ELSE
(* mov ebx, modlist; jmp main *)
CodeSize := 10
END
END;
(*
IF isDll THEN
CodeSize := 24 (* push ebx, esi, edi; mov bx, modlist; call main; pop edi, esi, ebx; mov aex,1; ret 12 *)
ELSE
CodeSize := 10 (* mov bx, modlist; jmp main *)
END
*)
DataSize := 0; ConSize := 0;
ImpSize := 0; ImpHSize := 0; ExpSize := 0;
RelocSize := 0; DllSize := 0; noffixup := 0; maxCode := 0; numImp := 0; numExp := 0;
mod := modList;
WHILE mod # NIL DO
IF ~mod.dll THEN
mod.file := ThisFile(mod.name);
IF mod.file # NIL THEN
R := mod.file.NewReader(R); R.SetPos(0); Read4(x);
IF x = 6F4F4346H THEN
Read4(x);
Read4(mod.hs); Read4(mod.ms); Read4(mod.ds); Read4(mod.cs);
Read4(mod.vs); RNum(mod.ni); ReadName(name); impdll := FALSE;
IF mod.ni > 0 THEN
NEW(mod.imp, mod.ni); x := 0;
WHILE x < mod.ni DO
ReadName(name);
IF name = "$$" THEN
IF (mod # kernel) & (kernel # NIL) THEN
mod.imp[x] := kernel
ELSE
W.WriteString("no kernel"); W.WriteLn;
StdLog.text.Append(StdLog.buf); error := TRUE
END
ELSIF name[0] = "$" THEN
i := 1;
WHILE name[i] # 0X DO name[i-1] := name[i]; INC(i) END;
name[i-1] := 0X; impdll := TRUE; im := modList;
WHILE (im # mod) & (im.name # name) DO im := im.next END;
IF (im = NIL) OR ~im.dll THEN
NEW(im); im.next := modList; modList := im;
im.name := name$;
im.dll := TRUE
END;
mod.imp[x] := im;
ELSE
im := modList;
WHILE (im # mod) & (im.name # name) DO im := im.next END;
IF im # mod THEN
mod.imp[x] := im;
ELSE
WriteUtf8(name);
W.WriteString(" not present (imported in ");
W.WriteString(mod.name); W.WriteChar(")");
W.WriteLn; StdLog.text.Append(StdLog.buf); error := TRUE
END
END;
INC(x)
END
END;
IF impdll & ~error THEN CheckDllImports(mod) END;
mod.ma := ConSize; INC(ConSize, mod.ms + mod.ds);
mod.va := DataSize; INC(DataSize, mod.vs);
mod.ca := CodeSize; INC(CodeSize, mod.cs);
IF mod.cs > maxCode THEN maxCode := mod.cs END
ELSE
W.WriteString(mod.name); W.WriteString(": wrong file type");
W.WriteLn; StdLog.text.Append(StdLog.buf); error := TRUE
END;
mod.file.Close; mod.file := NIL
ELSE
W.WriteString(mod.name); W.WriteString(" not found");
W.WriteLn; StdLog.text.Append(StdLog.buf); error := TRUE
END;
last := mod
END;
mod := mod.next
END;
IF ~isStatic & (main = NIL) THEN
W.WriteString("no main module specified"); W.WriteLn;
StdLog.text.Append(StdLog.buf); error := TRUE
END;
(* calculate rva's *)
IF DataSize = 0 THEN DataSize := 1 END;
CodeRva := ObjAlign;
DataRva := CodeRva + (CodeSize + DllSize + (ObjAlign - 1)) DIV ObjAlign * ObjAlign;
ConRva := DataRva + (DataSize + (ObjAlign - 1)) DIV ObjAlign * ObjAlign;
RsrcRva := ConRva + (ConSize + (ObjAlign - 1)) DIV ObjAlign * ObjAlign;
CodeBase := ImageBase + CodeRva;
DataBase := ImageBase + DataRva;
ConBase := ImageBase + ConRva;
(* write dll export adresses *)
mod := modList; x := 0;
WHILE mod # NIL DO
IF mod.dll THEN
exp := mod.exp; INC(ImpSize, 20);
WHILE exp # NIL DO exp.adr := x; INC(x, 6); exp := exp.next END
END;
mod := mod.next
END;
ASSERT(x = DllSize); INC(ImpSize, 20); (* sentinel *)
END ReadHeaders;
PROCEDURE MenuSize (r: Resource): INTEGER;
VAR s, i: INTEGER;
BEGIN
s := 0;
WHILE r # NIL DO
INC(s, 2);
IF r.local = NIL THEN INC(s, 2) END;
i := 0; WHILE r.name[i] # 0X DO INC(s, 2); INC(i) END;
INC(s, 2);
s := s + MenuSize(r.local);
r := r.next
END;
RETURN s
END MenuSize;
PROCEDURE PrepResources;
VAR res, r, s: Resource; n, i, j, t, x: INTEGER;
BEGIN
r := resList;
WHILE r # NIL DO
IF r.lid = 0 THEN r.lid := 1033 END;
IF r.name = "MENU" THEN
r.typ := 4; r.size := 4 + MenuSize(r.local);
ELSIF r.name = "ACCELERATOR" THEN
r.typ := 9; r.size := 0; s := r.local;
WHILE s # NIL DO INC(r.size, 8); s := s.next END;
ELSIF r.name = "MANIFEST" THEN
IF r.local # NIL THEN
r.file := ThisResFile(r.local.name);
IF r.file # NIL THEN
r.typ := 24; r.size := r.file.Length()
END
END
ELSE
r.file := ThisResFile(r.name);
IF r.file # NIL THEN
IF r.typ = -1 THEN (* typelib *)
r.typ := 0; r.size := r.file.Length(); r.pos := 0; rsrcName := "TYPELIB"
ELSE
R := r.file.NewReader(R); R.SetPos(0); Read2(n);
IF n = 4D42H THEN (* bitmap *)
Read4(n); r.typ := 2; r.size := n - 14; r.pos := 14;
ELSE
Read2(x);
IF x = 1 THEN (* icon *)
Read2(n); r.typ := 14; r.size := 6 + 14 * n; r.pos := 0; i := 0;
WHILE i < n DO
NEW(s); s.typ := 3; s.id := 10 * r.id + i; s.lid := r.lid; s.name := r.name$;
Read4(x); Read4(x); Read4(s.size); Read2(s.pos); Read2(x);
s.next := resList; resList := s;
INC(i)
END
ELSIF x = 2 THEN (* cursor *)
Read2(n); r.typ := 12; r.size := 6 + 14 * n; r.pos := 0; i := 0;
WHILE i < n DO
NEW(s); s.typ := 1; s.id := 10 * r.id + i; s.lid := r.lid; s.name := r.name$;
Read4(x); Read2(s.x); Read2(s.y); Read4(s.size); INC(s.size, 4); Read2(s.pos); Read2(x);
s.next := resList; resList := s;
INC(i)
END
ELSE
Read4(n);
IF (x = 0) & (n = 20H) THEN (* resource file *)
Read4(n); Read4(n); Read4(n); Read4(n); Read4(n); Read4(n); (* 32 bit marker *)
Read4(r.size); Read4(n); Read2(i);
IF i = 0FFFFH THEN
Read2(j);
IF (j >= 4) & ((j <= 11) OR (j = 16)) THEN
r.typ := j; r.pos := n + 32;
ELSE
W.WriteString(r.name); W.WriteString(": invalid type"); W.WriteLn;
StdLog.text.Append(StdLog.buf); error := TRUE
END
ELSE
j := 0;
WHILE i # 0 DO rsrcName[j] := CHR(i); INC(j); Read2(i) END;
rsrcName[j] := 0X;
r.typ := 0; r.pos := n + 32
END
ELSE
W.WriteString(r.name); W.WriteString(": unknown type"); W.WriteLn;
StdLog.text.Append(StdLog.buf); error := TRUE
END
END
END
END;
r.file.Close; r.file := NIL
ELSE
W.WriteString(r.name); W.WriteString(" not found"); W.WriteLn;
StdLog.text.Append(StdLog.buf); error := TRUE
END
END;
r := r.next
END;
res := resList; resList := NIL; (* sort resources *)
WHILE res # NIL DO
r := res; res := res.next;
IF (resList = NIL) OR (r.typ < resList.typ) OR (r.typ = resList.typ) & ((r.id < resList.id) OR (r.id = resList.id) & (r.lid < resList.lid))
THEN
r.next := resList; resList := r
ELSE
s := resList;
WHILE (s.next # NIL) & (r.typ >= s.next.typ)
& ((r.typ # s.next.typ) OR (r.id >= s.next.id) & ((r.id # s.next.id) OR (r.lid >= s.next.lid))) DO s := s.next END;
r.next := s.next; s.next := r
END
END;
r := resList; numType := 0; resHSize := 16; t := 0; n := 0; (* get resource size *)
WHILE t < LEN(numId) DO numId[t] := 0; INC(t) END;
WHILE r # NIL DO
INC(numType); INC(resHSize, 24); t := r.typ;
WHILE (r # NIL) & (r.typ = t) DO
INC(numId[t]); INC(resHSize, 24); i := r.id;
WHILE (r # NIL) & (r.typ = t) & (r.id = i) DO
INC(resHSize, 24); INC(n, (r.size + 3) DIV 4 * 4); r := r.next
END
END
END;
IF numId[0] > 0 THEN INC(n, (LEN(rsrcName$) + 1) * 2) END;
RsrcSize := resHSize + n;
ImpRva := RsrcRva + (RsrcSize + (ObjAlign - 1)) DIV ObjAlign * ObjAlign
END PrepResources;
PROCEDURE WriteHeader(VAR name: Files.Name);
BEGIN
Out := Files.dir.New(Files.dir.This(""), Files.ask); Ro := Out.NewWriter(Ro); Ro.SetPos(0);
(* DOS header *)
Write4(905A4DH); Write4(3); Write4(4); Write4(0FFFFH);
Write4(0B8H); Write4(0); Write4(40H); Write4(0);
Write4(0); Write4(0); Write4(0); Write4(0);
Write4(0); Write4(0); Write4(0); Write4(80H);
Write4(0EBA1F0EH); Write4(0CD09B400H); Write4(4C01B821H); Write2(21CDH);
WriteName("This program cannot be run in DOS mode.", 39);
WriteCh(0DX); WriteCh(0DX); WriteCh(0AX);
Write4(24H); Write4(0);
(* Win32 header *)
WriteName("PE", 4); (* signature bytes *)
Write2(014CH); (* cpu type (386) *)
IF isDll THEN
Write2(7); (* 7 objects *)
ELSE
Write2(6); (* 6 objects *)
END;
Write4(timeStamp); (* time/date *)
Write4(0); Write4(0);
Write2(0E0H); (* NT header size *)
IF isDll THEN
Write2(0A38EH); (* library image flags *)
ELSE
Write2(838EH); (* program image flags *)
END;
Write2(10BH); (* magic (normal ececutable file) *)
Write2(0502H); (* linker version !!! *) (* BdT: if value < 2.5, Microsoft AppLocker may report "not a valid Win32 application" *)
Write4(CodeSize); (* code size *)
Write4(ConSize); (* initialized data size *)
Write4(DataSize); (* uninitialized data size *)
entryPos := Ro.Pos();
Write4(0); (* entry point *) (* !!! *)
Write4(CodeRva); (* base of code *)
Write4(ConRva); (* base of data *)
Write4(400000H); (* image base *)
Write4(ObjAlign); (* object align *)
Write4(FileAlign); (* file align *)
Write4(3); (* OS version *)
Write4(4); (* user version *)
Write4(4); (* subsys version *) (* mf 14.3.04: value changed from 0A0003H to 4. Corrects menubar pixel bug on Windows XP *)
Write4(0);
isPos := Ro.Pos();
Write4(0); (* image size *) (* !!! *)
Write4(HeaderSize); (* header size !!! *)
Write4(0); (* checksum *)
IF comLine THEN
Write2(3) (* dos subsystem *)
ELSE
Write2(2) (* gui subsystem *)
END;
Write2(0); (* dll flags *)
Write4(200000H); (* stack reserve size *) (* WARNING: see note on Stack Size when changing this value *)
Write4(10000H); (* stack commit size *)
IF isDll THEN
Write4(00100000H); (* heap reserve size *)
ELSE
Write4(00400000H); (* heap reserve size *)
END;
Write4(10000H); (* heap commit size *)
Write4(0);
Write4(16); (* num of rva/sizes *)
hexpPos := Ro.Pos();
Write4(0); Write4(0); (* export table *)
himpPos := Ro.Pos();
Write4(0); Write4(0); (* import table *) (* !!! *)
hrsrcPos := Ro.Pos();
Write4(0); Write4(0); (* resource table *) (* !!! *)
Write4(0); Write4(0); (* exception table *)
Write4(0); Write4(0); (* security table *)
fixPos := Ro.Pos();
Write4(0); Write4(0); (* fixup table *) (* !!! *)
Write4(0); Write4(0); (* debug table *)
Write4(0); Write4(0); (* image description *)
Write4(0); Write4(0); (* machine specific *)
Write4(0); Write4(0); (* thread local storage *)
Write4(0); Write4(0); (* ??? *)
Write4(0); Write4(0); (* ??? *)
Write4(0); Write4(0); (* ??? *)
Write4(0); Write4(0); (* ??? *)
Write4(0); Write4(0); (* ??? *)
Write4(0); Write4(0); (* ??? *)
(* object directory *)
WriteName(".text", 8); (* code object *)
Write4(0); (* object size (always 0) *)
codePos := Ro.Pos();
Write4(0); (* object rva *)
Write4(0); (* physical size *)
Write4(0); (* physical offset *)
Write4(0); Write4(0); Write4(0);
Write4(60000020H); (* flags: code, exec, read *)
WriteName(".var", 8); (* variable object *)
Write4(0); (* object size (always 0) *)
dataPos := Ro.Pos();
Write4(0); (* object rva *)
Write4(0); (* physical size *)
Write4(0); (* physical offset *) (* zero! (noinit) *)
Write4(0); Write4(0); Write4(0);
Write4(0C0000080H); (* flags: noinit, read, write *)
WriteName(".data", 8); (* constant object *)
Write4(0); (* object size (always 0) *)
conPos := Ro.Pos();
Write4(0); (* object rva *)
Write4(0); (* physical size *)
Write4(0); (* physical offset *)
Write4(0); Write4(0); Write4(0);
Write4(0C0000040H); (* flags: data, read, write *)
WriteName(".rsrc", 8); (* resource object *)
Write4(0); (* object size (always 0) *)
rsrcPos := Ro.Pos();
Write4(0); (* object rva *)
Write4(0); (* physical size *)
Write4(0); (* physical offset *)
Write4(0); Write4(0); Write4(0);
Write4(0C0000040H); (* flags: data, read, write *)
WriteName(".idata", 8); (* import object *)
Write4(0); (* object size (always 0) *)
impPos := Ro.Pos();
Write4(0); (* object rva *)
Write4(0); (* physical size *)
Write4(0); (* physical offset *)
Write4(0); Write4(0); Write4(0);
Write4(0C0000040H); (* flags: data, read, write *)
IF isDll THEN
WriteName(".edata", 8); (* export object *)
Write4(0); (* object size (always 0) *)
expPos := Ro.Pos();
Write4(0); (* object rva *)
Write4(0); (* physical size *)
Write4(0); (* physical offset *)
Write4(0); Write4(0); Write4(0);
Write4(0C0000040H); (* flags: data, read, write *)
END;
WriteName(".reloc", 8); (* relocation object *)
Write4(0); (* object size (always 0) *)
relPos := Ro.Pos();
Write4(0); (* object rva *)
Write4(0); (* physical size *)
Write4(0); (* physical offset *)
Write4(0); Write4(0); Write4(0);
Write4(42000040H); (* flags: data, read, ? *)
END WriteHeader;
PROCEDURE SearchObj (mod: Module; VAR name: ARRAY OF SHORTCHAR; m, fp, opt: INTEGER; VAR adr: INTEGER);
VAR dir, len, ntab, f, id, l, r, p, n, i, j: INTEGER; nch, och: SHORTCHAR;
BEGIN
Get(mod, mod.ms + modExports, dir); DEC(dir, ConBase + mod.ma); Get(mod, dir, len); INC(dir, 4);
Get(mod, mod.ms + modNames, ntab); DEC(ntab, ConBase + mod.ma);
IF name # "" THEN
l := 0; r := len;
WHILE l < r DO (* binary search *)
n := (l + r) DIV 2; p := dir + n * 16;
Get(mod, p + 8, id);
i := 0; j := ntab + id DIV 256; nch := name[0]; och := SHORT(CHR(mod.data[j]));
WHILE (nch = och) & (nch # 0X) DO INC(i); INC(j); nch := name[i]; och := SHORT(CHR(mod.data[j])) END;
IF och = nch THEN
IF id MOD 16 = m THEN Get(mod, p, f);
IF m = mTyp THEN
IF ODD(opt) THEN Get(mod, p + 4, f) END;
IF (opt > 1) & (id DIV 16 MOD 16 # mExported) THEN
W.WriteString(mod.name); W.WriteChar(".");
WriteUtf8(name);
W.WriteString(" imported from "); W.WriteString(impg.name);
W.WriteString(" has wrong visibility"); W.WriteLn; error := TRUE
END;
Get(mod, p + 12, adr)
ELSIF m = mVar THEN
Get(mod, p + 4, adr); INC(adr, DataBase + mod.va)
ELSIF m = mProc THEN
Get(mod, p + 4, adr); INC(adr, CodeBase + mod.ca)
END;
IF f # fp THEN
W.WriteString(mod.name); W.WriteChar(".");
WriteUtf8(name);
W.WriteString(" imported from "); W.WriteString(impg.name);
W.WriteString(" has wrong fprint"); W.WriteLn; error := TRUE
END
ELSE
W.WriteString(mod.name); W.WriteChar("."); WriteUtf8(name);
W.WriteString(" imported from "); W.WriteString(impg.name);
W.WriteString(" has wrong class"); W.WriteLn; error := TRUE
END;
RETURN
END;
IF och < nch THEN l := n + 1 ELSE r := n END
END;
W.WriteString(mod.name); W.WriteChar("."); WriteUtf8(name);
W.WriteString(" not found (imported from "); W.WriteString(impg.name);
W.WriteChar(")"); W.WriteLn; error := TRUE
ELSE (* anonymous type *)
WHILE len > 0 DO
Get(mod, dir + 4, f); Get(mod, dir + 8, id);
IF (f = fp) & (id MOD 16 = mTyp) & (id DIV 256 = 0) THEN
Get(mod, dir + 12, adr); RETURN
END;
DEC(len); INC(dir, 16)
END;
W.WriteString("anonymous type in "); W.WriteString(mod.name);
W.WriteString(" not found"); W.WriteLn; error := TRUE
END
END SearchObj;
PROCEDURE CollectExports (mod: Module);
VAR dir, len, ntab, id, i, j, n: INTEGER; e, exp: Export;
BEGIN
Get(mod, mod.ms + modExports, dir); DEC(dir, ConBase + mod.ma); Get(mod, dir, len); INC(dir, 4);
Get(mod, mod.ms + modNames, ntab); DEC(ntab, ConBase + mod.ma); n := 0;
WHILE n < len DO
Get(mod, dir + 8, id);
IF (id DIV 16 MOD 16 # mInternal) & ((id MOD 16 = mProc) OR (id MOD 16 = mVar))THEN (* exported procedure & var *)
NEW(exp);
i := 0; j := ntab + id DIV 256;
WHILE mod.data[j] # 0 DO exp.name[i] := SHORT(CHR(mod.data[j])); INC(i); INC(j) END;
exp.name[i] := 0X;
Get(mod, dir + 4, exp.adr);
IF id MOD 16 = mProc THEN INC(exp.adr, CodeRva + mod.ca)
ELSE ASSERT(id MOD 16 = mVar); INC(exp.adr, DataRva + mod.va)
END;
IF (firstExp = NIL) OR (exp.name < firstExp.name) THEN
exp.next := firstExp; firstExp := exp;
IF lastExp = NIL THEN lastExp := exp END
ELSE
e := firstExp;
WHILE (e.next # NIL) & (exp.name > e.next.name) DO e := e.next END;
exp.next := e.next; e.next := exp;
IF lastExp = e THEN lastExp := exp END
END;
INC(numExp);
END;
INC(n); INC(dir, 16)
END
END CollectExports;
PROCEDURE WriteTermCode (m: Module; i: INTEGER);
VAR x: INTEGER;
BEGIN
IF m # NIL THEN
IF m.dll THEN WriteTermCode(m.next, i)
ELSE
IF isStatic THEN WriteTermCode(m.next, i + 1) END;
Get(m, m.ms + modTerm, x); (* terminator address in mod desc*)
IF x = 0 THEN
WriteCh(005X); Write4(0) (* add EAX, 0 (nop) *)
ELSE
WriteCh(0E8X); Write4(x - lastTerm + 5 * i - CodeBase) (* call term *)
END
END
END
END WriteTermCode;
PROCEDURE WriteCode;
VAR mod, m: Module; i, x, a, fp, opt: INTEGER; exp: Export; name: Name;
BEGIN
IF isStatic THEN
WriteCh(053X); (* push ebx *)
a := 1;
IF isDll THEN
WriteCh(083X); WriteCh(07CX); WriteCh(024X); WriteCh(00CX); WriteCh(001X); (* cmp [12, esp], 1 *)
WriteCh(00FX); WriteCh(085X); Write4(10 + 5 * numMod); (* jne L1 *)
INC(a, 11)
ELSE
WriteCh(053X); WriteCh(053X); (* push ebx; push ebx *)
INC(a, 2)
END;
WriteCh(0BBX); Write4(ConBase + last.ma + last.ms); Reloc(CodeBase + a + 1); (* mov bx, modlist *)
INC(a, 5); m := modList;
WHILE m # NIL DO
IF ~m.dll THEN
WriteCh(0E8X); INC(a, 5); Write4(m.ca - a) (* call body *)
END;
m := m.next
END;
IF isDll THEN
WriteCh(0E9X); Write4(11 + 5 * numMod); (* jp L2 *)
WriteCh(083X); WriteCh(07CX); WriteCh(024X); WriteCh(00CX); WriteCh(000X); (* L1: cmp [12, esp], 0 *)
WriteCh(00FX); WriteCh(085X); Write4(5 * numMod); (* jne L2 *)
INC(a, 16)
END;
termPos := Ro.Pos(); i := 0;
WHILE i < numMod DO (* nop for call terminator *)
WriteCh(02DX); Write4(0); (* sub EAX, 0 *)
INC(i); INC(a, 5)
END;
lastTerm := a;
WriteCh(05BX); (* L2: pop ebx *)
IF isDll THEN
WriteCh(0B8X); Write4(1); (* mov eax,1 *)
WriteCh(0C2X); Write2(12) (* ret 12 *)
ELSE
WriteCh(05BX); WriteCh(05BX); (* pop ebx; pop ebx *)
WriteCh(0C3X) (* ret *)
END
ELSIF isDll THEN
WriteCh(053X); (* push ebx *)
WriteCh(083X); WriteCh(07CX); WriteCh(024X); WriteCh(00CX); WriteCh(001X); (* cmp [12, esp], 1 *)
WriteCh(075X); WriteCh(SHORT(CHR(12))); (* jne L1 *)
WriteCh(0BBX); Write4(ConBase + last.ma + last.ms); Reloc(CodeBase + 9); (* mov bx, modlist *)
WriteCh(0E8X); Write4(main.ca - 18); (* call main *)
WriteCh(0EBX); WriteCh(SHORT(CHR(12))); (* jp L2 *)
WriteCh(083X); WriteCh(07CX); WriteCh(024X); WriteCh(00CX); WriteCh(000X); (* L1: cmp [12, esp], 0 *)
WriteCh(075X); WriteCh(SHORT(CHR(5))); (* jne L2 *)
termPos := Ro.Pos();
WriteCh(02DX); Write4(0); (* sub EAX, 0 *) (* nop for call terminator *)
lastTerm := 32;
WriteCh(05BX); (* L2: pop ebx *)
WriteCh(0B8X); Write4(1); (* mov eax,1 *)
WriteCh(0C2X); Write2(12) (* ret 12 *)
ELSE
WriteCh(0BBX); Write4(ConBase + last.ma + last.ms); Reloc(CodeBase + 1); (* mov bx, modlist *)
WriteCh(0E9X); Write4(main.ca - 10); (* jmp main *)
END;
NEW(code, maxCode);
mod := modList;
WHILE mod # NIL DO impg := mod; impd := mod;
IF ~mod.dll THEN
mod.file := ThisFile(mod.name);
R := mod.file.NewReader(R); R.SetPos(mod.hs);
NEW(mod.data, mod.ms + mod.ds);
R.ReadBytes(mod.data^, 0, mod.ms + mod.ds);
R.ReadBytes(code^, 0, mod.cs);
RNum(x);
IF x # 0 THEN
IF (mod # kernel) & (kernel # NIL) THEN
SearchObj(kernel, newRec, mProc, NewRecFP, -1, a); Fixup0(x, a)
ELSE
W.WriteString("no kernel"); W.WriteLn;
StdLog.text.Append(StdLog.buf); error := TRUE; RETURN
END
END;
RNum(x);
IF x # 0 THEN
IF (mod # kernel) & (kernel # NIL) THEN
SearchObj(kernel, newArr, mProc, NewArrFP, -1, a); Fixup0(x, a)
ELSE
W.WriteString("no kernel"); W.WriteLn;
StdLog.text.Append(StdLog.buf); error := TRUE; RETURN
END
END;
Fixup(ConBase + mod.ma);
Fixup(ConBase + mod.ma + mod.ms);
Fixup(CodeBase + mod.ca);
Fixup(DataBase + mod.va); i := 0;
WHILE i < mod.ni DO
m := mod.imp[i]; impd := m; RNum(x);
WHILE x # 0 DO
ReadName(name); RNum(fp); opt := 0;
IF x = mTyp THEN RNum(opt) END;
IF m.dll THEN
IF x = mProc THEN exp := m.exp;
WHILE exp.name # name DO exp := exp.next END;
a := exp.adr + CodeBase + CodeSize
END
ELSE
SearchObj(m, name, x, fp, opt, a)
END;
IF x # mConst THEN Fixup(a) END;
RNum(x)
END;
IF ~m.dll THEN
Get(mod, mod.ms + modImports, x); DEC(x, ConBase + mod.ma); INC(x, 4 * i);
Put(mod, x, ConBase + m.ma + m.ms); (* imp ref *)
Reloc(ConBase + mod.ma + x);
Get(m, m.ms + modRefcnt, x); Put(m, m.ms + modRefcnt, x + 1) (* inc ref count *)
END;
INC(i)
END;
Ro.WriteBytes(code^, 0, mod.cs);
IF mod.intf THEN CollectExports(mod) END;
mod.file.Close; mod.file := NIL
END;
mod := mod.next
END;
(* dll links *)
mod := modList; ImpHSize := ImpSize;
WHILE mod # NIL DO
IF mod.dll THEN
exp := mod.exp;
WHILE exp # NIL DO
WriteCh(0FFX); WriteCh(25X); Write4(ImageBase + ImpRva + ImpSize); (* JMP indirect *)
Reloc(CodeBase + CodeSize + exp.adr + 2);
INC(ImpSize, 4); INC(numImp); exp := exp.next
END;
INC(ImpSize, 4); INC(numImp) (* sentinel *)
END;
mod := mod.next
END
END WriteCode;
PROCEDURE WriteConst;
VAR mod, last: Module; x: INTEGER;
BEGIN
mod := modList; last := NIL;
WHILE mod # NIL DO
IF ~mod.dll THEN
IF last # NIL THEN
Put(mod, mod.ms, ConBase + last.ma + last.ms); (* mod list *)
Reloc(ConBase + mod.ma + mod.ms);
END;
Get(mod, mod.ms + modOpts, x);
IF isStatic THEN INC(x, 10000H) END; (* set init bit (16) *)
IF isDll THEN INC(x, 1000000H) END; (* set dll bit (24) *)
Put(mod, mod.ms + modOpts, x);
Ro.WriteBytes(mod.data^, 0, mod.ms + mod.ds);
last := mod
END;
mod := mod.next
END
END WriteConst;
PROCEDURE WriteResDir (n, i: INTEGER);
BEGIN
Write4(0); (* flags *)
Write4(timeStamp);
Write4(0); (* version *)
Write2(n); (* name entries *)
Write2(i); (* id entries *)
END WriteResDir;
PROCEDURE WriteResDirEntry (id, adr: INTEGER; dir: BOOLEAN);
BEGIN
IF id = 0 THEN id := resHSize + 80000000H END; (* name Rva *)
Write4(id);
IF dir THEN Write4(adr + 80000000H) ELSE Write4(adr) END
END WriteResDirEntry;
PROCEDURE WriteMenu (res: Resource);
VAR f, i: INTEGER;
BEGIN
WHILE res # NIL DO
IF res.next = NIL THEN f := 80H ELSE f := 0 END;
IF 29 IN res.opts THEN INC(f, 1) END; (* = grayed *)
IF 13 IN res.opts THEN INC(f, 2) END; (* - inctive *)
IF 3 IN res.opts THEN INC(f, 4) END; (* # bitmap *)
IF 10 IN res.opts THEN INC(f, 8) END; (* * checked *)
IF 1 IN res.opts THEN INC(f, 20H) END; (* ! menubarbreak *)
IF 15 IN res.opts THEN INC(f, 40H) END; (* / menubreak *)
IF 31 IN res.opts THEN INC(f, 100H) END; (* ? ownerdraw *)
IF res.local # NIL THEN Write2(f + 10H) ELSE Write2(f); Write2(res.id) END;
i := 0; WHILE res.name[i] # 0X DO Write2(ORD(res.name[i])); INC(i) END;
Write2(0);
WriteMenu(res.local);
res := res.next
END
END WriteMenu;
PROCEDURE WriteResource;
VAR r, s: Resource; i, t, a, x, n, nlen, nsize: INTEGER; b: BYTE;
BEGIN
IF numId[0] > 0 THEN WriteResDir(1, numType - 1); nlen := LEN(rsrcName$); nsize := (nlen + 1) * 2;
ELSE WriteResDir(0, numType)
END;
a := 16 + 8 * numType; t := 0;
WHILE t < LEN(numId) DO
IF numId[t] > 0 THEN WriteResDirEntry(t, a, TRUE); INC(a, 16 + 8 * numId[t]) END;
INC(t)
END;
r := resList; t := -1;
WHILE r # NIL DO
IF t # r.typ THEN t := r.typ; WriteResDir(0, numId[t]) END;
WriteResDirEntry(r.id, a, TRUE); INC(a, 16); i := r.id;
WHILE (r # NIL) & (r.typ = t) & (r.id = i) DO INC(a, 8); r := r.next END
END;
r := resList;
WHILE r # NIL DO
n := 0; s := r;
WHILE (s # NIL) & (s.typ = r.typ) & (s.id = r.id) DO INC(n); s := s.next END;
WriteResDir(0, n);
WHILE r # s DO WriteResDirEntry(r.lid, a, FALSE); INC(a, 16); r := r.next END
END;
ASSERT(a = resHSize);
IF numId[0] > 0 THEN INC(a, nsize) END; (* TYPELIB string *)
r := resList;
WHILE r # NIL DO
Write4(a + RsrcRva); INC(a, (r.size + 3) DIV 4 * 4);
Write4(r.size);
Write4(0); Write4(0);
r := r.next
END;
ASSERT(a = RsrcSize);
IF numId[0] > 0 THEN
Write2(nlen); i := 0;
WHILE rsrcName[i] # 0X DO Write2(ORD(rsrcName[i])); INC(i) END
END;
r := resList;
WHILE r # NIL DO
IF r.typ = 4 THEN (* menu *)
Write2(0); Write2(0);
WriteMenu(r.local);
WHILE Ro.Pos() MOD 4 # 0 DO WriteCh(0X) END
ELSIF r.typ = 9 THEN (* accelerator *)
s := r.local;
WHILE s # NIL DO
i := 0; a := 0;
IF 10 IN s.opts THEN INC(a, 4) END; (* * shift *)
IF 16 IN s.opts THEN INC(a, 8) END; (* ^ ctrl *)
IF 0 IN s.opts THEN INC(a, 16) END; (* @ alt *)
IF 13 IN s.opts THEN INC(a, 2) END; (* - noinv *)
IF s.next = NIL THEN INC(a, 80H) END;
IF (s.name[0] = "v") & (s.name[1] # 0X) THEN
s.name[0] := " "; Strings.StringToInt(s.name, x, n); INC(a, 1)
ELSE x := ORD(s.name[0])
END;
Write2(a); Write2(x); Write2(s.id); Write2(0); s := s.next
END
ELSIF r.typ = 24 THEN (* manifest *)
IF r.local # NIL THEN
r.file := ThisResFile(r.local.name);
r.size := r.file.Length();
IF r.file # NIL THEN
R := r.file.NewReader(R);
R.SetPos(0);
i := 0;
WHILE i < r.size DO
R.ReadByte(b); Ro.WriteByte(b); INC(i)
END;
r.file.Close; r.file := NIL
ELSE
W.WriteString("can't open manifest file: " + r.local.name); W.WriteLn
END;
ELSE
W.WriteString("manifest file isn't specified"); W.WriteLn
END
ELSE
r.file := ThisResFile(r.name);
IF r.file # NIL THEN
R := r.file.NewReader(R); R.SetPos(r.pos); i := 0;
IF r.typ = 12 THEN (* cursor group *)
Read4(x); Write4(x); Read2(n); Write2(n);
WHILE i < n DO
Read4(x); Write2(x MOD 256); Write2(x DIV 256 MOD 256 * 2);
Write2(1); Write2(1); Read4(x); (* ??? *)
Read4(x); Write4(x + 4); Read4(x); Write2(r.id * 10 + i); INC(i)
END;
IF ~ODD(n) THEN Write2(0) END
ELSIF r.typ = 14 THEN (* icon group *)
Read4(x); Write4(x); Read2(n); Write2(n);
WHILE i < n DO
Read2(x); Write2(x); Read2(x);
IF (13 IN r.opts) & (x = 16) THEN x := 4 END;
Write2(x);
a := x MOD 256; Read4(x); Write2(1);
IF a <= 2 THEN Write2(1)
ELSIF a <= 4 THEN Write2(2)
ELSIF a <= 16 THEN Write2(4)
ELSE Write2(8)
END;
Read4(x);
IF (13 IN r.opts) & (x = 744) THEN x := 440 END;
IF (13 IN r.opts) & (x = 296) THEN x := 184 END;
Write4(x); Read4(x); Write2(r.id * 10 + i); INC(i)
END;
IF ~ODD(n) THEN Write2(0) END
ELSE
IF r.typ = 1 THEN Write2(r.x); Write2(r.y); i := 4 END; (* cursor hot spot *)
WHILE i < r.size DO Read4(x); Write4(x); INC(i, 4) END
END;
r.file.Close; r.file := NIL
END
END;
r := r.next
END
END WriteResource;
PROCEDURE Insert(VAR name: ARRAY OF SHORTCHAR; VAR idx: INTEGER; hint: INTEGER);
VAR i: INTEGER; ntabx: POINTER TO ARRAY OF SHORTCHAR;
BEGIN
IF idx + LEN(name) + (2 + 4) >= LEN(ntab) THEN (* expand ntab *)
NEW(ntabx, (idx + LEN(name) + (2 + 4)) * 2);
FOR i := 0 TO LEN(ntab) - 1 DO ntabx[i] := ntab[i] END ;
ntab := ntabx;
END ;
IF hint >= 0 THEN
ntab[idx] := SHORT(CHR(hint)); INC(idx);
ntab[idx] := SHORT(CHR(hint DIV 256)); INC(idx);
END;
i := 0;
WHILE name[i] # 0X DO ntab[idx] := name[i]; INC(idx); INC(i) END;
IF (hint = -1)
& ((idx < 4) OR ((ntab[idx-4] # ".") OR (CAP(ntab[idx-3]) # "D") OR (CAP(ntab[idx-2]) # "L") OR (CAP(ntab[idx-1]) # "L"))) THEN
ntab[idx] := "."; INC(idx);
ntab[idx] := "d"; INC(idx);
ntab[idx] := "l"; INC(idx);
ntab[idx] := "l"; INC(idx);
END;
ntab[idx] := 0X; INC(idx);
IF ODD(idx) THEN ntab[idx] := 0X; INC(idx) END
END Insert;
PROCEDURE WriteImport;
VAR i, lt, at, nt, ai, ni: INTEGER; mod: Module; exp: Export; ss: ARRAY 256 OF SHORTCHAR;
BEGIN
IF numImp > 0 THEN NEW(atab, numImp) END;
IF numExp > numImp THEN i := numExp ELSE i := numImp END;
IF i > 0 THEN NEW(ntab, 40 * i) END;
at := ImpRva + ImpHSize; ai := 0; ni := 0;
lt := ImpRva + ImpSize; nt := lt + ImpSize - ImpHSize;
mod := modList;
WHILE mod # NIL DO
IF mod.dll THEN
Write4(lt); (* lookup table rva *)
Write4(0); (* time/data (always 0) *)
Write4(0); (* version (always 0) *)
Write4(nt + ni); (* name rva *)
ss := SHORT(mod.name$); Insert(ss, ni, -1);
Write4(at); (* addr table rva *)
exp := mod.exp;
WHILE exp # NIL DO
atab[ai] := nt + ni; (* hint/name rva *)
Insert(exp.name, ni, 0);
INC(lt, 4); INC(at, 4); INC(ai); exp := exp.next
END;
atab[ai] := 0; INC(lt, 4); INC(at, 4); INC(ai)
END;
mod := mod.next
END;
Write4(0); Write4(0); Write4(0); Write4(0); Write4(0);
i := 0;
WHILE i < ai DO Write4(atab[i]); INC(i) END; (* address table *)
i := 0;
WHILE i < ai DO Write4(atab[i]); INC(i) END; (* lookup table *)
i := 0;
WHILE i < ni DO WriteCh(ntab[i]); INC(i) END;
ASSERT(ai * 4 = ImpSize - ImpHSize);
INC(ImpSize, ai * 4 + ni);
ExpRva := ImpRva + (ImpSize + (ObjAlign - 1)) DIV ObjAlign * ObjAlign;
RelocRva := ExpRva;
END WriteImport;
PROCEDURE WriteExport (VAR name: ARRAY OF CHAR);
VAR i, ni: INTEGER; e: Export; ss: ARRAY 256 OF SHORTCHAR;
BEGIN
Write4(0); (* flags *)
Write4(timeStamp); (* time stamp *)
Write4(0); (* version *)
Write4(ExpRva + 40 + 10 * numExp); (* name rva *)
Write4(1); (* ordinal base *)
Write4(numExp); (* # entries *)
Write4(numExp); (* # name ptrs *)
Write4(ExpRva + 40); (* address table rva *)
Write4(ExpRva + 40 + 4 * numExp); (* name ptr table rva *)
Write4(ExpRva + 40 + 8 * numExp); (* ordinal table rva *)
ExpSize := 40 + 10 * numExp;
(* adress table *)
e := firstExp;
WHILE e # NIL DO Write4(e.adr); e := e.next END;
(* name ptr table *)
ni := 0; e := firstExp;
ss := SHORT(name$); Insert(ss, ni, -2);
WHILE e # NIL DO
Write4(ExpRva + ExpSize + ni); Insert(e.name, ni, -2); e := e.next
END;
(* ordinal table *)
i := 0;
WHILE i < numExp DO Write2(i); INC(i) END;
(* name table *)
i := 0;
WHILE i < ni DO WriteCh(ntab[i]); INC(i) END;
ExpSize := (ExpSize + ni + 15) DIV 16 * 16;
RelocRva := ExpRva + (ExpSize + (ObjAlign - 1)) DIV ObjAlign * ObjAlign;
END WriteExport;
PROCEDURE Sort (l, r: INTEGER);
VAR i, j, x, t: INTEGER;
BEGIN
i := l; j := r; x := fixups[(l + r) DIV 2];
REPEAT
WHILE fixups[i] < x DO INC(i) END;
WHILE fixups[j] > x DO DEC(j) END;
IF i <= j THEN t := fixups[i]; fixups[i] := fixups[j]; fixups[j] := t; INC(i); DEC(j) END
UNTIL i > j;
IF l < j THEN Sort(l, j) END;
IF i < r THEN Sort(i, r) END
END Sort;
PROCEDURE WriteReloc;
VAR i, j, h, a, p: INTEGER;
BEGIN
Sort(0, noffixup - 1); i := 0;
WHILE i < noffixup DO
p := fixups[i] DIV 4096 * 4096; j := i; a := p + 4096;
WHILE (j < noffixup) & (fixups[j] < a) DO INC(j) END;
Write4(p - ImageBase); (* page rva *)
h := 8 + 2 * (j - i);
Write4(h + h MOD 4); (* block size *)
INC(RelocSize, h);
WHILE i < j DO Write2(fixups[i] - p + 3 * 4096); INC(i) END; (* long fix *)
IF h MOD 4 # 0 THEN Write2(0); INC(RelocSize, 2) END
END;
Write4(0); Write4(0); INC(RelocSize, 8);
ImagesSize := RelocRva + (RelocSize + (ObjAlign - 1)) DIV ObjAlign * ObjAlign;
END WriteReloc;
PROCEDURE Align(VAR pos: INTEGER);
BEGIN
WHILE Ro.Pos() MOD FileAlign # 0 DO WriteCh(0X) END;
pos := Ro.Pos()
END Align;
PROCEDURE WriteOut (VAR name: Files.Name);
VAR res, codepos, conpos, rsrcpos, imppos, exppos, relpos, relend, end: INTEGER;
BEGIN
IF ~error THEN Align(codepos); WriteCode END;
IF ~error THEN Align(conpos); WriteConst END;
IF ~error THEN Align(rsrcpos); WriteResource END;
IF ~error THEN Align(imppos); WriteImport END;
IF ~error & isDll THEN Align(exppos); WriteExport(name) END;
IF ~error THEN Align(relpos); WriteReloc END;
relend := Ro.Pos() - 8; Align(end);
IF ~error THEN
Ro.SetPos(entryPos); Write4(CodeRva);
Ro.SetPos(isPos); Write4(ImagesSize);
IF isDll THEN
Ro.SetPos(hexpPos); Write4(ExpRva); Write4(ExpSize);
END;
Ro.SetPos(himpPos); Write4(ImpRva); Write4(ImpHSize);
Ro.SetPos(hrsrcPos); Write4(RsrcRva); Write4(RsrcSize);
Ro.SetPos(fixPos); Write4(RelocRva); Write4(relend - relpos);
Ro.SetPos(codePos); Write4(CodeRva); Write4(conpos - HeaderSize); Write4(HeaderSize);
Ro.SetPos(dataPos); Write4(DataRva); Write4((DataSize + (FileAlign-1)) DIV FileAlign * FileAlign);
Ro.SetPos(conPos); Write4(ConRva); Write4(rsrcpos - conpos); Write4(conpos);
Ro.SetPos(rsrcPos); Write4(RsrcRva); Write4(imppos - rsrcpos); Write4(rsrcpos);
IF isDll THEN
Ro.SetPos(impPos); Write4(ImpRva); Write4(exppos - imppos); Write4(imppos);
Ro.SetPos(expPos); Write4(ExpRva); Write4(relpos - exppos); Write4(exppos)
ELSE
Ro.SetPos(impPos); Write4(ImpRva); Write4(relpos - imppos); Write4(imppos);
END;
Ro.SetPos(relPos); Write4(RelocRva); Write4(end - relpos); Write4(relpos);
IF isStatic THEN
Ro.SetPos(termPos); WriteTermCode(modList, 0)
ELSIF isDll THEN
Ro.SetPos(termPos); WriteTermCode(main, 0)
END
END;
IF ~error THEN
Out.Register(name, "exe", Files.ask, res);
IF res # 0 THEN error := TRUE END
END
END WriteOut;
PROCEDURE ScanRes (VAR S: TextMappers.Scanner; end: INTEGER; VAR list: Resource);
VAR res, tail: Resource; n: INTEGER;
BEGIN
tail := NIL;
WHILE (S.start < end) & (S.type = TextMappers.int) DO
NEW(res); res.id := S.int; S.Scan;
IF (S.type = TextMappers.char) & (S.char = "[") THEN
S.Scan;
IF S.type = TextMappers.int THEN res.lid := S.int; S.Scan END;
IF (S.type = TextMappers.char) & (S.char = "]") THEN S.Scan
ELSE W.WriteString("missing ']'"); error := TRUE
END
END;
WHILE S.type = TextMappers.char DO
IF S.char = "@" THEN n := 0
ELSIF S.char = "^" THEN n := 16
ELSIF S.char = "~" THEN n := 17
ELSIF S.char <= "?" THEN n := ORD(S.char) - ORD(" ")
END;
INCL(res.opts, n); S.Scan
END;
IF S.type = TextMappers.string THEN
res.name := S.string$; S.Scan;
IF (S.type = TextMappers.char) & (S.char = ".") THEN S.Scan;
IF S.type = TextMappers.string THEN
IF (S.string = "tlb") OR (S.string = "TLB") THEN res.typ := -1 END;
Files.dir.GetFileName(res.name, S.string$, res.name); S.Scan
END
END;
IF (S.type = TextMappers.char) & (S.char = "(") THEN S.Scan;
ScanRes(S, end, res.local);
IF (S.type = TextMappers.char) & (S.char = ")") THEN S.Scan
ELSE W.WriteString("missing ')'"); error := TRUE
END
END;
IF tail = NIL THEN list := res ELSE tail.next := res END;
tail := res
ELSE
W.WriteString("wrong resource name"); error := TRUE
END
END;
END ScanRes;
(*
post:
error = TRUE: linking failed
error = FALSE: linking successful
*)
PROCEDURE LinkIt;
VAR S: TextMappers.Scanner; name: Files.Name; mod: Module; end: INTEGER;
BEGIN
comLine := FALSE;
modList := NIL; kernel := NIL; main := NIL;
last := NIL; impg := NIL; impd := NIL; resList := NIL;
firstExp := NIL; lastExp := NIL;
NEW(fixups, FixLen);
Dialog.ShowStatus("linking");
timeStamp := TimeStamp();
error := FALSE; modList := NIL; resList := NIL;
IF DevCommanders.par = NIL THEN error := TRUE; RETURN END;
S.ConnectTo(DevCommanders.par.text);
S.SetPos(DevCommanders.par.beg);
end := DevCommanders.par.end;
DevCommanders.par := NIL;
W.ConnectTo(StdLog.buf); S.Scan;
IF S.type = TextMappers.string THEN
IF S.string = "dos" THEN comLine := TRUE; S.Scan END;
IF S.type = TextMappers.string THEN
name := S.string$; S.Scan;
IF (S.type = TextMappers.char) & (S.char = ".") THEN S.Scan;
IF S.type = TextMappers.string THEN
Files.dir.GetFileName(name, S.string$, name); S.Scan
END
ELSE
Files.dir.GetFileName(name, "exe", name)
END;
IF (S.type = TextMappers.char) & (S.char = ":") THEN S.Scan;
IF (S.type = TextMappers.char) & (S.char = "=") THEN S.Scan;
WHILE (S.start < end) & (S.type = TextMappers.string) DO
NEW(mod); mod.name := S.string$;
mod.next := modList; modList := mod;
S.Scan;
WHILE (S.start < end) & (S.type = TextMappers.char) &
((S.char = "*") OR (S.char = "+") OR (S.char = "$") OR (S.char = "#")) DO
IF S.char = "*" THEN mod.dll := TRUE
ELSIF S.char = "+" THEN kernel := mod
ELSIF S.char = "$" THEN main := mod
ELSE mod.intf := TRUE;
IF ~isDll THEN
W.WriteString("Exports from Exe not possible. Use LinkDll or LinkDynDll.");
W.WriteLn; StdLog.text.Append(StdLog.buf); error := TRUE
END
END;
S.Scan
END
END;
ScanRes(S, end, resList);
ReadHeaders;
PrepResources;
IF ~error THEN WriteHeader(name) END;
IF ~error THEN WriteOut(name) END;
IF ~error THEN
W.WriteString(name); W.WriteString(" written ");
W.WriteInt(Out.Length()); W.WriteString(" "); W.WriteInt(CodeSize)
END
ELSE W.WriteString(" := missing"); error := TRUE
END
ELSE W.WriteString(" := missing"); error := TRUE
END
ELSE W.WriteString("name missing"); error := TRUE
END;
W.WriteLn; StdLog.text.Append(StdLog.buf)
ELSE W.WriteString("name missing"); error := TRUE
END;
IF error THEN Dialog.ShowStatus("failed") ELSE Dialog.ShowStatus("ok") END;
W.ConnectTo(NIL); S.ConnectTo(NIL);
modList := NIL; kernel := NIL; main := NIL; firstExp := NIL; lastExp := NIL;
last := NIL; impg := NIL; impd := NIL; resList := NIL; code := NIL; atab := NIL; ntab := NIL;
fixups := NIL
END LinkIt;
PROCEDURE Link*;
BEGIN
isDll := FALSE; isStatic := FALSE;
LinkIt
END Link;
PROCEDURE LinkExe*;
BEGIN
isDll := FALSE; isStatic := TRUE;
LinkIt
END LinkExe;
PROCEDURE LinkDll*;
BEGIN
isDll := TRUE; isStatic := TRUE;
LinkIt
END LinkDll;
PROCEDURE LinkDynDll*;
BEGIN
isDll := TRUE; isStatic := FALSE;
LinkIt
END LinkDynDll;
(*
PROCEDURE Show*;
VAR S: TextMappers.Scanner; name: Name; mod: Module; t: TextModels.Model;
BEGIN
t := TextViews.FocusText(); IF t = NIL THEN RETURN END;
W.ConnectTo(StdLog.buf); S.ConnectTo(t); S.Scan;
IF S.type = TextMappers.string THEN
mod := modList;
WHILE (mod # NIL) & (mod.name # S.string) DO mod := mod.next END;
IF mod # NIL THEN
W.WriteString(S.string);
W.WriteString(" ca = ");
W.WriteIntForm(CodeBase + mod.ca, TextMappers.hexadecimal, 8, "0", TRUE);
W.WriteLn; StdLog.text.Append(StdLog.buf)
END
END;
W.ConnectTo(NIL); S.ConnectTo(NIL)
END Show;
*)
BEGIN
newRec := "NewRec"; newArr := "NewArr"
END DevLinker.
DevLinker.Link Usekrnl.exe := TestKernel$+ Usekrnl ~ "DevDecExe.Decode('', 'Usekrnl.exe')"
DevLinker.LinkDynDll MYDLL.dll := TestKernel+ MYDLL$# ~ "DevDecExe.Decode('', 'MYDLL.dll')"
DevLinker.LinkExe Usekrnl.exe := TestKernel+ Usekrnl ~ "DevDecExe.Decode('', 'Usekrnl.exe')"
DevLinker.LinkDll MYDLL.dll := TestKernel+ MYDLL# ~ "DevDecExe.Decode('', 'MYDLL.dll')"
MODULE TestKernel;
IMPORT KERNEL32;
PROCEDURE Beep*;
BEGIN
KERNEL32.Beep(500, 200)
END Beep;
BEGIN
CLOSE
KERNEL32.ExitProcess(0)
END TestKernel.
MODULE Usekrnl;
(* empty windows application using BlackBox Kernel *)
(* Ominc *)
IMPORT KERNEL32, USER32, GDI32, S := SYSTEM, Kernel := TestKernel;
VAR Instance, MainWnd: USER32.Handle;
PROCEDURE WndHandler (wnd, message, wParam, lParam: INTEGER): INTEGER;
VAR res: INTEGER; ps: USER32.PaintStruct; dc: GDI32.Handle;
BEGIN
IF message = USER32.WMDestroy THEN
USER32.PostQuitMessage(0)
ELSIF message = USER32.WMPaint THEN
dc := USER32.BeginPaint(wnd, ps);
res := GDI32.TextOutA(dc, 50, 50, "Hello World", 11);
res := USER32.EndPaint(wnd, ps)
ELSIF message = USER32.WMChar THEN
Dialog.Beep
ELSE
RETURN USER32.DefWindowProcA(wnd, message, wParam, lParam)
END;
RETURN 0
END WndHandler;
PROCEDURE OpenWindow;
VAR class: USER32.WndClass; res: INTEGER;
BEGIN
class.cursor := USER32.LoadCursorA(0, USER32.MakeIntRsrc(USER32.IDCArrow));
class.icon := USER32.LoadIconA(Instance, USER32.MakeIntRsrc(1));
class.menuName := NIL;
class.className := "Simple";
class.backgnd := GDI32.GetStockObject(GDI32.WhiteBrush);
class.style := {0, 1, 5, 7};
class.instance := Instance;
class.wndProc := WndHandler;
class.clsExtra := 0;
class.wndExtra := 0;
USER32.RegisterClassA(class);
MainWnd := USER32.CreateWindowExA({}, "Simple", "Empty Windows Application",
{16..19, 22, 23, 25},
USER32.CWUseDefault, USER32.CWUseDefault,
USER32.CWUseDefault, USER32.CWUseDefault,
0, 0, Instance, 0);
res := USER32.ShowWindow(MainWnd, 10);
res := USER32.UpdateWindow(MainWnd);
END OpenWindow;
PROCEDURE MainLoop;
VAR msg: USER32.Message; res: INTEGER;
BEGIN
WHILE USER32.GetMessageA(msg, 0, 0, 0) # 0 DO
res := USER32.TranslateMessage(msg);
res := USER32.DispatchMessageA(msg);
END;
(*
KERNEL32.ExitProcess(msg.wParam)
*)
END MainLoop;
BEGIN
Instance := KERNEL32.GetModuleHandleA(NIL);
OpenWindow;
MainLoop
CLOSE
Kernel.Beep
END Usekrnl.
MODULE MYDLL;
(* sample module to be linked into a dll *)
(* Ominc *)
IMPORT SYSTEM, KERNEL32;
VAR expVar*: INTEGER;
PROCEDURE GCD* (a, b: INTEGER): INTEGER;
BEGIN
WHILE a # b DO
IF a < b THEN b := b - a ELSE a := a - b END
END;
expVar := a;
RETURN a
END GCD;
PROCEDURE Beep*;
BEGIN
KERNEL32.Beep(500, 200)
END Beep;
CLOSE
Beep
END MYDLL.
Resource = Id [ "[" Language "]" ] Options name [ "." ext ] [ "(" { Resource } ")" ]
Id = number
Language = number
Options = { "@" | "!" .. "?" | "^" | "~" }
names
MENU
1 MENU (0 File (11 New 12 Open 13 Save 0 "" 14 Exit) 0 Edit (21 Cut 22 Copy 23 Paste))
= grayed
- inctive
# bitmap
* checked
! menuBarBreak
/ menuBreak
? ownerDraw
ACCELERATOR
1 ACCELERATOR (11 ^N 12 ^O 13 ^S 21 ^X 22 ^C 23 ^V)
* shift
^ ctrl
@ alt
- noInvert
filename.ico
filename.cur
filname.bmp
filename.res
filename.tlb
| Dev/Mod/Linker.odc |
MODULE DevLinker1;
(** project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Igor Dehtyarenko, Alexander Shiryaev"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- ...
"
issues = "
- ...
"
**)
IMPORT
LB := DevLnkBase, Load := DevLnkLoad,
WrPe := DevLnkWritePe,
WrElf := DevLnkWriteElf, WrElfS := DevLnkWriteElfStatic,
Kernel, Files, Log := StdLog, Dialog, DevCommanders, TextMappers;
CONST
tgtElfStatic = 0; tgtElfExe = 1; tgtElfDll = 2; tgtPeExe = 3; tgtPeDll = 4;
VAR
W: TextMappers.Formatter;
PROCEDURE LinkIt0;
VAR codeBase, dataBase, varsBase : INTEGER;
BEGIN
LB.BeginLinking;
IF LB.outPe THEN
WrPe.Init;
WrPe.GetBases(codeBase, dataBase, varsBase);
LB.SetAddr(codeBase, dataBase, varsBase);
LB.DoFixups;
WrPe.WriteOut;
ELSIF LB.outElf & LB.opt.elfStatic THEN
WrElfS.Init;
WrElfS.GetBases(codeBase, dataBase, varsBase);
LB.SetAddr(codeBase, dataBase, varsBase);
LB.DoFixups;
WrElfS.WriteOut;
ELSIF LB.outElf THEN
WrElf.Init;
WrElf.GetBases(codeBase, dataBase, varsBase);
LB.SetAddr(codeBase, dataBase, varsBase);
LB.DoFixups;
WrElf.WriteOut;
END;
IF ~LB.error THEN
W.WriteString(LB.outputName$); W.WriteString(" written")
END
END LinkIt0;
PROCEDURE LinkIt;
VAR S: TextMappers.Scanner; name: Files.Name; end: INTEGER;
modName: TextMappers.String;
error, isFreeBSD, flag0: BOOLEAN;
BEGIN
Dialog.ShowStatus("linking");
error := FALSE;
IF DevCommanders.par = NIL THEN RETURN END;
S.ConnectTo(DevCommanders.par.text);
S.SetPos(DevCommanders.par.beg);
end := DevCommanders.par.end;
DevCommanders.par := NIL;
isFreeBSD := FALSE;
W.ConnectTo(Log.buf); S.Scan;
IF S.type = TextMappers.string THEN
IF LB.target = tgtElfExe THEN
IF S.string = "Linux" THEN
LB.opt.OSABI := WrElf.ELFOSABI_NONE;
LB.opt.elfInterpreter := WrElf.linuxInterpreter
ELSIF S.string = "FreeBSD" THEN
LB.opt.OSABI := WrElf.ELFOSABI_FREEBSD;
LB.opt.elfInterpreter := WrElf.freeBSDInterpreter;
isFreeBSD := TRUE
ELSIF S.string = "OpenBSD" THEN
LB.opt.OSABI := WrElf.ELFOSABI_NONE;
LB.opt.elfInterpreter := WrElf.openBSDInterpreter
ELSE
W.WriteString("unknown OS: "); W.WriteString(S.string); W.WriteLn;
error := TRUE
END;
S.Scan
END;
name := S.string$; S.Scan;
IF (S.type = TextMappers.char) & (S.char = ".") THEN S.Scan;
IF S.type = TextMappers.string THEN
Files.dir.GetFileName(name, S.string$, name); S.Scan
END
END;
IF (S.type = TextMappers.char) & (S.char = ":") THEN S.Scan;
IF (S.type = TextMappers.char) & (S.char = "=") THEN S.Scan;
LB.outputName := name$;
WHILE (S.start < end) & (S.type = TextMappers.string) DO
modName := S.string$; S.Scan;
flag0 := FALSE;
WHILE (S.start < end) & (S.type = TextMappers.char) &
((S.char = "+") OR (S.char = "$")) DO
IF S.char = "+" THEN LB.KernelName := SHORT(modName$);
flag0 := TRUE
ELSIF S.char = "$" THEN LB.mainName := SHORT(modName$);
flag0 := TRUE
ELSE
END;
S.Scan
END;
IF ~flag0 THEN
IF LB.target = tgtElfStatic THEN
Load.AddModule(modName$)
ELSIF LB.target = tgtElfExe THEN
Load.AddModule(modName$)
ELSIF LB.target = tgtElfDll THEN
Load.ExportModule(modName$)
ELSIF LB.target = tgtPeExe THEN
Load.AddModule(modName$)
ELSIF LB.target = tgtPeDll THEN
Load.ExportModule(modName$)
ELSE HALT(102)
END
END
END;
IF LB.target = tgtElfStatic THEN
ELSIF LB.target = tgtElfExe THEN
IF isFreeBSD THEN
Load.ExportVariable(LB.KernelName$, "__progname");
Load.ExportVariable(LB.KernelName$, "environ")
END;
Load.ExportAll
ELSIF LB.target = tgtElfDll THEN
ELSIF LB.target = tgtPeExe THEN
Load.ExportAll
ELSIF LB.target = tgtPeDll THEN
ELSE HALT(101)
END;
IF ~error THEN LinkIt0 END
ELSE W.WriteString(" := missing")
END
ELSE W.WriteString(" := missing")
END;
W.WriteLn; Log.text.Append(Log.buf)
END;
IF error THEN Dialog.ShowStatus("failed") ELSE Dialog.ShowStatus("ok") END;
W.ConnectTo(NIL); S.ConnectTo(NIL)
END LinkIt;
PROCEDURE LinkPeExe*;
BEGIN
LB.Init(tgtPeExe);
LB.dynaInit := FALSE;
LinkIt
END LinkPeExe;
PROCEDURE LinkPe*;
BEGIN
LB.Init(tgtPeExe);
LB.dynaInit := TRUE;
LinkIt
END LinkPe;
PROCEDURE LinkPeDll*;
BEGIN
LB.Init(tgtPeDll);
LinkIt
END LinkPeDll;
PROCEDURE LinkElfStatic*;
BEGIN
LB.Init(tgtElfStatic);
LinkIt
END LinkElfStatic;
PROCEDURE LinkElfDll*;
BEGIN
LB.Init(tgtElfDll);
LinkIt
END LinkElfDll;
PROCEDURE LinkElfExe*;
BEGIN
LB.Init(tgtElfExe);
LB.dynaInit := FALSE;
LinkIt
END LinkElfExe;
PROCEDURE LinkElf*;
BEGIN
LB.Init(tgtElfExe);
LB.dynaInit := TRUE;
LinkIt
END LinkElf;
END DevLinker1.
DevCompiler.CompileThis Dev2LnkBase Dev2LnkLoad Dev2LnkWritePe Dev2LnkWriteElf Dev2LnkWriteElfStatic Dev2LnkChmod DevLinker1
DevDebug.UnloadThis DevLinker1 Dev2LnkLoad Dev2LnkWritePe Dev2LnkWriteElf Dev2LnkWriteElfStatic Dev2LnkChmod Dev2LnkBase
DevLinker1.LinkPeExe BlackBox1 := Kernel$+ HostFiles StdLoader ~
DevLinker1.LinkElfExe Linux BlackBox1 := Kernel$+ HostFiles StdLoader ~
DevLinker1.LinkElfExe FreeBSD BlackBox1 := Kernel$+ HostFiles StdLoader ~
DevLinker1.LinkElfExe OpenBSD BlackBox1 := Kernel$+ HostFiles StdLoader ~
DevLinker1.LinkPe BlackBox1 := Kernel$+ HostFiles StdLoader ~
DevLinker1.LinkElf Linux BlackBox1 := Kernel$+ HostFiles StdLoader ~
DevLinker1.LinkElf FreeBSD BlackBox1 := Kernel$+ HostFiles StdLoader ~
DevLinker1.LinkElf OpenBSD BlackBox1 := Kernel$+ HostFiles StdLoader ~
| Dev/Mod/Linker1.odc |
MODULE DevLnkBase;
(** project = "BlackBox 2.0, new module"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Igor Dehtyarenko"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 2016.11 initial version by Igor Dehtyarenko (Trurl)
"
issues = "
- ...
"
**)
IMPORT Files, Log, Dialog, Kernel, Librarian;
TYPE
ChmodHook* = POINTER TO ABSTRACT RECORD END;
CONST
(* targets *)
tgtElfStatic = 0; tgtElfExe = 1; tgtElfDll = 2; tgtPeExe = 3; tgtPeDll = 4;
(* fixup types *)
fixAbs = 1; fixRel = 2; fixCopy = 5;
(* Symbol type *)
typProc* = 0;
typObj* = 1;
TYPE
Name* = ARRAY 256 OF SHORTCHAR;
SName = ARRAY 256 OF SHORTCHAR;
STRING* = ARRAY OF SHORTCHAR;
BYTES* = ARRAY OF BYTE;
Section* = POINTER TO RECORD
addr*:INTEGER;
size*:INTEGER;
bytes*: POINTER TO BYTES;
END;
Symbol* = POINTER TO RECORD
next*: Symbol;
sect*: Section;
addr*: INTEGER;
namIdx*: INTEGER;
symIdx*: INTEGER;
name*: SName;
typ*: INTEGER;
END;
FixRec* = RECORD
ftype* : INTEGER;
offs*: INTEGER;
sec*: Section;
END;
FixTable* = RECORD
sec-: Section;
tab-: POINTER TO ARRAY OF FixRec;
len-: INTEGER
END;
StringTable* = RECORD
tab-: POINTER TO ARRAY OF SHORTCHAR;
len-: INTEGER
END;
Module* = POINTER TO RECORD
next*: Module;
name*: Name;
data*: Section;
code*: Section;
vars*: Section;
codeFix*: FixTable;
dataFix*: FixTable;
mDesc*: INTEGER;
termadr*: INTEGER;
isDll*: BOOLEAN;
exported*: BOOLEAN;
exp*: Symbol;
END;
VAR
error-: BOOLEAN;
target-: INTEGER;
outPe-, outElf-, outDll- : BOOLEAN;
dynaInit*: BOOLEAN;
outputName*: Files.Name; outputType-: Files.Type;
KernelName*, mainName*: Name;
kernelMod*: Module;
mainMod*: Module;
modList-: Module;
lastMod-: Module;
initMod-:Module;
dllList-: Module;
modCount-:INTEGER;
impCount-, impDllCount-: INTEGER;
expCount- : INTEGER;
expList-: Symbol;
ImageBase*: INTEGER;
codeSize-, dataSize-, varsSize-: INTEGER;
initOffs-, finiOffs-: INTEGER;
pltEntrySize, pltIniSize : INTEGER;
relCount-: INTEGER;
relTab-: POINTER TO ARRAY OF INTEGER;
opt*: RECORD
imageBase*: INTEGER;
subsystem*: INTEGER;
elfStatic*: BOOLEAN;
elfInterpreter*: ARRAY 128 OF SHORTCHAR;
rpath*: ARRAY 128 OF SHORTCHAR;
OSABI*: SHORTCHAR;
END;
chmodHook: ChmodHook;
PROCEDURE SetChmodHook* (hook: ChmodHook);
BEGIN
chmodHook := hook
END SetChmodHook;
PROCEDURE (hook: ChmodHook) Chmod* (name0: Files.Name; mode: SET), NEW, ABSTRACT;
PROCEDURE Chmod* (name0: Files.Name; mode: SET);
BEGIN
IF chmodHook # NIL THEN
chmodHook.Chmod(name0, mode)
END
END Chmod;
PROCEDURE Init* (tgt: INTEGER);
BEGIN
error := FALSE;
outPe := FALSE; outElf := FALSE; outDll := FALSE;
dynaInit := FALSE;
opt.imageBase := 0;
opt.subsystem := 0;
opt.elfStatic := FALSE;
opt.elfInterpreter := '';
opt.OSABI := 0X;
opt.rpath := '';
modCount:= 0;
modList:= NIL;
lastMod:= NIL;
kernelMod:= NIL;
mainMod:= NIL;
initMod:= NIL;
dllList:= NIL;
impCount:=0; impDllCount:=0;
expList:= NIL;
expCount :=0;
relCount := 0;
ImageBase:= 0;
varsSize := 0;
dataSize := 0;
codeSize := 0;
outputName := "";
mainName := "";
KernelName := "Kernel";
target := tgt;
CASE tgt OF
| tgtPeExe: outputType := "exe"; outPe := TRUE;
| tgtPeDll: outputType := "dll"; outPe := TRUE; outDll := TRUE;
| tgtElfExe: outputType := ""; outElf := TRUE;
| tgtElfDll: outputType := "so" ; outElf := TRUE; outDll := TRUE;
| tgtElfStatic: outputType := "out"; outElf := TRUE; opt.elfStatic := TRUE;
END;
pltIniSize := 0; pltEntrySize := 6;
(* got: IF outElf THEN pltEntrySize := 16; pltIniSize := 16 END; *)
END Init;
PROCEDURE Error*(msg:ARRAY OF CHAR);
BEGIN
error := TRUE;
Log.String(msg); Log.Ln;
END Error;
PROCEDURE NewSection*(size: INTEGER): Section;
VAR sec: Section;
BEGIN
NEW(sec);
sec.size := size;
sec.addr := 0;
RETURN sec
END NewSection;
PROCEDURE RegMod*(mod: Module);
BEGIN
IF mod.name$ = KernelName THEN kernelMod := mod END;
IF mod.name$ = mainName THEN mainMod := mod END;
IF lastMod = NIL THEN
modList := mod;
ELSE
lastMod.next := mod;
END;
lastMod := mod;
INC(modCount);
INC(codeSize, mod.code.size);
INC(varsSize, mod.vars.size);
INC(dataSize, mod.data.size);
END RegMod;
PROCEDURE ThisDll*(IN name: STRING): Module;
VAR i, j: INTEGER; lib: Module;
BEGIN
lib := dllList;
WHILE (lib # NIL) & (lib.name$ # name) DO lib := lib.next END;
IF lib = NIL THEN
NEW(lib);
lib.name := name$;
lib.isDll := TRUE;
lib.code := NewSection(0);
NEW(lib.exp);
(* name witout '$' *)
i:=0; j:= 1;
WHILE name[j] # 0X DO lib.exp.name[i] := name[j]; INC(i); INC(j) END;
lib.exp.name[i] := 0X;
lib.exp.addr := -1;
lib.next := dllList;
dllList := lib;
INC(impDllCount);
END;
RETURN lib
END ThisDll;
PROCEDURE ImportProc*(mod: Module; IN name: STRING; OUT adr: INTEGER);
VAR sym, prev: Symbol;
BEGIN
prev := mod.exp;
sym := prev.next;
WHILE (sym # NIL) & (sym.name # name) DO prev := sym; sym := prev.next END;
IF (sym = NIL) THEN
NEW(sym);
sym.name := name$;
sym.addr := mod.code.size;
prev.next := sym;
INC(mod.code.size, pltEntrySize);
INC(impCount);
END;
adr := sym.addr;
END ImportProc;
PROCEDURE ExportProc*(mod: Module; IN name: STRING; addr: INTEGER);
VAR sym: Symbol;
BEGIN
NEW(sym);
sym.name := mod.name$ + '_' + name$;
sym.sect := mod.code;
sym.addr := addr;
sym.next := expList;
sym.typ := typProc;
expList := sym;
INC(expCount);
END ExportProc;
PROCEDURE ExportVar*(mod: Module; IN name: STRING; addr: INTEGER);
VAR sym: Symbol;
BEGIN
NEW(sym);
sym.name := name$;
sym.sect := mod.data;
sym.addr := addr;
sym.next := expList;
sym.typ := typObj;
expList := sym;
INC(expCount);
END ExportVar;
PROCEDURE InitFixTable*(VAR t: FixTable; sec: Section);
BEGIN
t.sec := sec;
t.len := 0;
END InitFixTable;
PROCEDURE CheckFixSize(VAR t: FixTable);
VAR newtab: POINTER TO ARRAY OF FixRec;
i:INTEGER;
BEGIN
IF t.tab = NIL THEN
NEW(t.tab, 256);
ELSIF t.len >= LEN(t.tab) THEN (* enlarge *)
NEW(newtab, 2 * LEN(t.tab));
i := 0;
WHILE i < LEN(t.tab) DO newtab[i] := t.tab[i]; INC(i) END;
t.tab := newtab
END;
END CheckFixSize;
PROCEDURE AddFix(VAR t: FixTable; addr, fixtype: INTEGER; sec: Section);
BEGIN
ASSERT(sec#NIL);
CheckFixSize(t);
t.tab[t.len].offs := addr;
t.tab[t.len].ftype := fixtype;
t.tab[t.len].sec:= sec;
INC(t.len)
END AddFix;
PROCEDURE FixCode*(mod: Module; addr: INTEGER; sec: Section);
BEGIN
AddFix(mod.codeFix, addr, fixAbs, sec); INC(relCount)
END FixCode;
PROCEDURE FixRel*(mod: Module; addr: INTEGER; sec: Section);
BEGIN
AddFix(mod.codeFix, addr, fixRel, sec);
END FixRel;
PROCEDURE FixData*(mod: Module; addr: INTEGER; sec: Section);
BEGIN
AddFix(mod.dataFix, addr, fixAbs, sec); INC(relCount)
END FixData;
PROCEDURE FixCopy*(mod: Module; addr: INTEGER; sec: Section);
BEGIN
AddFix(mod.dataFix, addr, fixCopy, sec); INC(relCount)
END FixCopy;
PROCEDURE Get4(VAR d:BYTES; a: INTEGER): INTEGER;
BEGIN
RETURN ((d[a+3] * 256 + d[a+2] MOD 256) * 256 + d[a+1] MOD 256) * 256 + d[a] MOD 256
END Get4;
PROCEDURE Put4(VAR d:BYTES; a: INTEGER; x: INTEGER);
BEGIN
d[a] := SHORT(SHORT(x));
d[a+1] := SHORT(SHORT(x DIV 100H));
d[a+2] := SHORT(SHORT(x DIV 10000H));
d[a+3] := SHORT(SHORT(x DIV 1000000H))
END Put4;
PROCEDURE AddReloc*(addr: INTEGER);
BEGIN
relTab[relCount] := addr;
INC(relCount)
END AddReloc;
PROCEDURE DoFixups*;
VAR mod: Module;
PROCEDURE DoFix(t: FixTable);
VAR i, offs, old, new: INTEGER; tsec, ssec: Section;
BEGIN
tsec := t.sec;
FOR i := 0 TO t.len - 1 DO
offs := t.tab[i].offs;
ssec := t.tab[i].sec;
old := Get4(tsec.bytes, offs);
CASE t.tab[i].ftype OF
|fixAbs:
new := ssec.addr + old ;
AddReloc(t.sec.addr + offs)
|fixRel:
new := ssec.addr - t.sec.addr + old;
|fixCopy:
new := Get4(ssec.bytes, old);
IF new # 0 THEN AddReloc(t.sec.addr + offs) END;
END;
Put4(tsec.bytes, offs, new);
END;
END DoFix;
BEGIN
NEW(relTab, relCount + impCount);
relCount := 0;
DoFix(initMod.codeFix);
mod := modList;
WHILE (mod # NIL) DO
DoFix(mod.dataFix);
DoFix(mod.codeFix);
mod := mod.next
END;
END DoFixups;
PROCEDURE SortReloc*;
PROCEDURE QuickSort(l, r: INTEGER);
VAR i, j, x, t: INTEGER;
BEGIN
i := l; j := r;
x := relTab[(l + r) DIV 2];
REPEAT
WHILE relTab[i] < x DO INC(i) END;
WHILE relTab[j] > x DO DEC(j) END;
IF i <= j THEN
t := relTab[i]; relTab[i] := relTab[j]; relTab[j] := t;
INC(i); DEC(j)
END
UNTIL i > j;
IF l < j THEN QuickSort(l, j) END;
IF i < r THEN QuickSort(i, r) END
END QuickSort;
BEGIN
QuickSort(0, relCount - 1);
END SortReloc;
PROCEDURE InitStringTable* (VAR t: StringTable; size:INTEGER);
BEGIN
IF (size > 0) & ((t.tab = NIL) OR (LEN(t.tab) < size)) THEN
NEW(t.tab, size);
END;
t.len := 0;
END InitStringTable;
PROCEDURE CheckStrSize (VAR t: StringTable; len:INTEGER);
VAR newtab: POINTER TO ARRAY OF SHORTCHAR;
i:INTEGER;
BEGIN
IF t.tab = NIL THEN
NEW(t.tab, 500);
ELSIF t.len + len >= LEN(t.tab) THEN (* enlarge *)
NEW(newtab, 2 * LEN(t.tab));
i := 0;
WHILE i < LEN(t.tab) DO newtab[i] := t.tab[i]; INC(i) END;
t.tab := newtab
END;
END CheckStrSize;
PROCEDURE AddName* (VAR t: StringTable; IN name: STRING; OUT idx: INTEGER);
VAR i,len : INTEGER;
BEGIN
len:= LEN(name$);
CheckStrSize(t, len);
idx := t.len;
i := 0;
WHILE name[i] # 0X DO t.tab[t.len] := name[i]; INC(t.len); INC(i) END;
t.tab[t.len] := 0X; INC(t.len);
IF ODD(t.len) THEN t.tab[t.len] := 0X; INC(t.len) END
END AddName;
PROCEDURE AddHintName* (VAR t: StringTable; hint: INTEGER; IN name: STRING; OUT idx: INTEGER);
VAR i: INTEGER;
BEGIN
CheckStrSize(t, 2);
idx := t.len;
t.tab[t.len] := SHORT(CHR(hint)); INC(t.len);
t.tab[t.len] := SHORT(CHR(hint DIV 256)); INC(t.len);
AddName(t, name, i);
END AddHintName;
PROCEDURE AddDllName* (VAR t: StringTable; IN name, ext: STRING; VAR idx: INTEGER);
VAR i, dot: INTEGER;
BEGIN
i := 0; dot := 0;
WHILE name[i] # 0X DO IF name[i] = "." THEN dot := i END; INC(i) END;
IF dot > 0 THEN
AddName(t, name, idx);
ELSE
AddName(t, name$ + ext$, idx);
END;
END AddDllName;
PROCEDURE WriteStringTable* (out: Files.Writer; VAR t: StringTable);
VAR i: INTEGER;
BEGIN
i := 0;
WHILE i # t.len DO out.WriteByte(SHORT(ORD(t.tab[i]))); INC(i) END
END WriteStringTable;
PROCEDURE Aligned* (pos, alignment: INTEGER): INTEGER;
BEGIN
RETURN (pos + (alignment - 1)) DIV alignment * alignment
END Aligned;
PROCEDURE ThisObjFile* (IN modname: ARRAY OF CHAR): Files.File;
VAR loc: Files.Locator; fname: Files.Name;
BEGIN
Librarian.lib.GetSpec(modname, "Code", loc, fname);
RETURN Files.stdDir.Old(loc, fname, TRUE)
END ThisObjFile;
PROCEDURE CountDllSizes;
VAR lib: Module;
BEGIN
lib := dllList;
INC(codeSize, pltIniSize);
WHILE lib # NIL DO
INC(codeSize, lib.code.size);
lib := lib.next
END;
END CountDllSizes;
PROCEDURE GenInitCode;
VAR init, fini, dllmain : INTEGER;
cp: INTEGER; bytes: POINTER TO BYTES;
PROCEDURE Emit1(c: SHORTCHAR);
BEGIN
bytes[cp] := SHORT(ORD(c));
INC(cp);
END Emit1;
PROCEDURE Emit2(x0, x1: SHORTCHAR);
BEGIN
Emit1(x0);
Emit1(x1);
END Emit2;
PROCEDURE Emit3(x0, x1, x2: SHORTCHAR);
BEGIN
Emit1(x0);
Emit1(x1);
Emit1(x2)
END Emit3;
PROCEDURE Emit1W(c: SHORTCHAR; x: INTEGER);
BEGIN
bytes[cp] := SHORT(ORD(c));
bytes[cp+1] := SHORT(SHORT(x));
bytes[cp+2] := SHORT(SHORT(x DIV 100H));
bytes[cp+3] := SHORT(SHORT(x DIV 10000H));
bytes[cp+4] := SHORT(SHORT(x DIV 1000000H));
INC(cp,5);
END Emit1W;
PROCEDURE InitDynamic;
BEGIN
Emit1W(0BBX, lastMod.mDesc); (* mov ebx, modlist *)
FixCode(initMod, cp - 4, lastMod.data);
Emit1W(0E8X, - cp - 5); (* call main *)
FixRel(initMod, cp-4, mainMod.code);
END InitDynamic;
PROCEDURE InitStatic(mod: Module);
BEGIN
WHILE mod # NIL DO
IF (mod = kernelMod) OR (mod = mainMod) THEN
Emit1W(0BBX, lastMod.mDesc); (* mov ebx, modlist *)
FixCode(initMod, cp-4, lastMod.data);
END;
Emit1W(0E8X, - cp - 5); (* call body *)
FixRel(initMod, cp-4, mod.code);
mod := mod.next
END;
END InitStatic; (* 10 + n*5 *)
PROCEDURE FiniDynamic;
BEGIN
IF mainMod.termadr # 0 THEN
Emit1W(0E8X, mainMod.termadr - cp - 5); (* call terminator *)
FixRel(initMod, cp-4, mainMod.code);
END;
Emit1(0C3X); (* ret *)
END FiniDynamic;
PROCEDURE FiniStatic(mod: Module);
BEGIN
IF mod # NIL THEN
FiniStatic(mod.next);
IF mod.termadr # 0 THEN
Emit1W(0E8X, mod.termadr- cp - 5); (* call terminator *)
FixRel(initMod, cp-4, mod.code);
END;
END;
END FiniStatic; (* 1 + n*5 *)
PROCEDURE WinDllMain;
BEGIN
Emit1(055X); (* push ebp *)
Emit2(089X, 0E5X); (* mov ebp, esp *)
Emit3(08BX, 045X, 0CX); (* mov eax, [12, ebp] *)
Emit3(083X, 0F8X, 01X); (* cmp eax, 1 *)
Emit2(074X, 0BX); (* je L1 *)
Emit2(085X, 0C0X); (* test eax,eax *)
Emit2(075X, 0CX); (* jnz R *)
(* L0: *)
Emit1W(0E8X, fini - cp - 5); (* call fini *)
Emit2(0EBX, 05X); (* jmp R *)
(* L1: *)
Emit1W(0E8X, init - cp - 5); (* call init *)
(* R: *)
Emit1W(0B8X, 1); (* mov eax,1 *)
Emit1(0C9X); (* leave *)
Emit3(0C2X, 0CX, 0X); (* ret 12 *)
END WinDllMain; (* 24 *)
BEGIN
NEW(initMod);
initMod.code := NewSection(50 + 10 * modCount);
NEW(initMod.code.bytes, initMod.code.size);
InitFixTable(initMod.codeFix, initMod.code);
bytes := initMod.code.bytes;
cp := 0;
init := cp;
IF dynaInit THEN InitDynamic ELSE InitStatic(modList) END;
IF outDll THEN Emit1(0C3X) END; (* ret *)
fini := cp;
IF dynaInit THEN FiniDynamic ELSE FiniStatic(modList) END;
Emit1(0C3X); (* ret *)
initOffs:= init;
finiOffs:= fini;
IF outDll & outPe THEN
dllmain := cp;
WinDllMain;
initOffs:= dllmain;
END;
initMod.code.size := cp;
INC(codeSize, initMod.code.size);
END GenInitCode;
PROCEDURE BeginLinking*;
BEGIN
IF mainMod = NIL THEN mainMod := lastMod END;
IF outputName = "" THEN
outputName := mainMod.name$;
Files.stdDir.GetFileName(outputName, outputType, outputName);
END;
GenInitCode;
CountDllSizes;
END BeginLinking;
PROCEDURE SetAddr* (codeBase, dataBase, varsBase: INTEGER);
VAR mod: Module; sym: Symbol;
BEGIN
mod := initMod;
mod.code.addr := codeBase; INC(codeBase, mod.code.size);
mod := modList;
WHILE (mod # NIL) DO
mod.code.addr := codeBase; INC(codeBase, mod.code.size);
mod.data.addr := dataBase; INC(dataBase, mod.data.size);
mod.vars.addr := varsBase; INC(varsBase, mod.vars.size);
mod := mod.next
END;
INC(codeBase, pltIniSize);
mod := dllList;
WHILE (mod # NIL) DO
mod.code.addr := codeBase; INC(codeBase, mod.code.size);
sym := mod.exp.next;
WHILE sym # NIL DO
INC(sym.addr, mod.code.addr);
sym := sym.next
END;
mod := mod.next
END;
sym := expList;
WHILE sym # NIL DO
INC(sym.addr, sym.sect.addr);
sym := sym.next
END;
END SetAddr;
BEGIN
IF Dialog.platform = Dialog.linux THEN
Kernel.LoadMod("DevChmod__Lin")
ELSIF Dialog.platform = Dialog.openbsd THEN
Kernel.LoadMod("DevChmod__Obsd")
ELSIF Dialog.platform = Dialog.freebsd THEN
Kernel.LoadMod("DevChmod__Fbsd")
END
END DevLnkBase.
| Dev/Mod/LnkBase.odc |
MODULE DevLnkLoad;
(** project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Igor Dehtyarenko"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 2016.11 initial version by Igor Dehtyarenko (Trurl)
"
issues = "
- ...
"
**)
IMPORT LB := DevLnkBase, SYSTEM, Files;
CONST
newRecName = "NewRec"; NewRecFP = 4E27A847H;
newArrName = "NewArr"; NewArrFP = 76068C78H;
(* meta interface consts *)
mConst = 1; mTyp = 2; mVar = 3; mProc = 4;
mInternal = 1; mExported = 4;
(* Module descriptor fields *)
mdf_next = 0; mdf_opts = 4; mdf_refcnt = 8; mdf_term = 40;
mdf_names = 84; mdf_imports = 92; mdf_export= 96;
TYPE
Module = LB.Module;
Section = LB.Section;
STRING = LB.STRING;
StrPtr = POINTER TO ARRAY [untagged] OF SHORTCHAR;
PROCEDURE^ LoadModule(IN modName: STRING):Module;
PROCEDURE ThisMod*(IN name: STRING): Module;
VAR mod: Module;
BEGIN
IF name[0] = "$" THEN
mod := LB.ThisDll(name)
ELSE
mod := LB.modList;
WHILE (mod # NIL) & (mod.name$ # name) DO mod := mod.next END;
IF mod = NIL THEN
mod := LoadModule(name);
IF mod # NIL THEN LB.RegMod(mod) END;
END;
END;
RETURN mod
END ThisMod;
PROCEDURE Read4(inp: Files.Reader; VAR x: INTEGER);
VAR b: BYTE; y: INTEGER;
BEGIN
inp.ReadByte(b); y := b MOD 256;
inp.ReadByte(b); y := y + 100H * (b MOD 256);
inp.ReadByte(b); y := y + 10000H * (b MOD 256);
inp.ReadByte(b); x := y + 1000000H * b
END Read4;
PROCEDURE ReadNum(inp: Files.Reader; VAR x: INTEGER);
VAR b: BYTE; s, y: INTEGER;
BEGIN
s := 0; y := 0;
inp.ReadByte(b);
WHILE b < 0 DO
INC(y, ASH(b + 128, s));
INC(s, 7);
inp.ReadByte(b)
END;
x := ASH((b + 64) MOD 128 - 64, s) + y
END ReadNum;
PROCEDURE ReadName (inp: Files.Reader; VAR name: STRING);
VAR i: INTEGER; b: BYTE;
BEGIN
i := 0;
REPEAT
inp.ReadByte(b); name[i] := SHORT(CHR(b)); INC(i)
UNTIL b = 0
END ReadName;
PROCEDURE Get3(VAR d:ARRAY OF BYTE; a: INTEGER): INTEGER;
BEGIN
RETURN d[a] MOD 256 + d[a+1] MOD 256 * 256 + d[a+2] * 10000H;
END Get3;
PROCEDURE Get4(VAR d:ARRAY OF BYTE; a: INTEGER): INTEGER;
BEGIN
RETURN ((d[a+3] * 256 + d[a+2] MOD 256) * 256 + d[a+1] MOD 256) * 256 + d[a] MOD 256
END Get4;
PROCEDURE Put4(VAR d:ARRAY OF BYTE; a: INTEGER; x: INTEGER);
BEGIN
d[a] := SHORT(SHORT(x));
d[a+1] := SHORT(SHORT(x DIV 100H));
d[a+2] := SHORT(SHORT(x DIV 10000H));
d[a+3] := SHORT(SHORT(x DIV 1000000H))
END Put4;
PROCEDURE DWord(mod: Module; a: INTEGER): INTEGER;
BEGIN
RETURN Get4(mod.data.bytes, a);
END DWord;
PROCEDURE MWord(mod: Module; offs: INTEGER): INTEGER;
BEGIN
RETURN Get4(mod.data.bytes, mod.mDesc + offs);
END MWord;
PROCEDURE PutMWord(mod: Module; offs: INTEGER; x: INTEGER);
BEGIN
Put4(mod.data.bytes, mod.mDesc + offs, x);
END PutMWord;
PROCEDURE GetPName(mod: Module; idx: INTEGER): StrPtr;
VAR pNames: INTEGER;
BEGIN
pNames := MWord(mod, mdf_names);
RETURN SYSTEM.VAL(StrPtr, SYSTEM.ADR(mod.data.bytes[pNames + idx]));
END GetPName;
PROCEDURE GetDir(mod: Module; VAR pDir, numobj: INTEGER);
BEGIN
pDir := MWord(mod, mdf_export); (* numobj:4 {Object} *)
numobj := DWord(mod, pDir);
pDir := pDir + 4;
END GetDir;
PROCEDURE SearchFprint(mod: Module; fprint: INTEGER): INTEGER;
VAR p, numobj, fp: INTEGER;
BEGIN
GetDir(mod, p, numobj);
fp := DWord(mod, p + 4);
WHILE (fp # fprint) & (numobj > 0) DO
INC(p, 16); DEC(numobj);
fp := DWord(mod, p + 4);
END;
IF fp = fprint THEN RETURN p ELSE RETURN -1 END;
END SearchFprint;
PROCEDURE SearchName(mod: Module; IN name: STRING): INTEGER;
VAR l, r, m, p, id: INTEGER;
p0, numobj: INTEGER;
s:StrPtr;
BEGIN
GetDir(mod, p0, numobj);
l := 0; r := numobj-1;
WHILE (l <= r) DO (* binary search *)
m := (l + r) DIV 2;
p := p0 + m * 16;
id := DWord(mod, p + 8);
s := GetPName(mod, id DIV 256);
IF name = s$ THEN
RETURN p
ELSIF name > s$ THEN
l := m + 1
ELSE
r := m - 1
END
END;
RETURN -1
END SearchName;
PROCEDURE SearchObj(mod: Module; IN name: STRING; mode, fprint, opt: INTEGER;
OUT sec: Section; OUT adr: INTEGER);
VAR pObj, id, md, fp: INTEGER;
BEGIN
sec:= NIL; adr := -1;
IF mod.isDll THEN
IF mode = mProc THEN
sec := mod.code;
LB.ImportProc(mod, name, adr);
ELSIF mode = mTyp THEN
LB.Error(name$ + " import type from DLL");
ELSIF mode = mVar THEN
LB.Error(name$ + " import var from DLL");
END;
ELSIF name = "" THEN
pObj := SearchFprint(mod, fprint);
IF pObj < 0 THEN
LB.Error("anonymous type not found");
ELSE
id := DWord(mod, pObj + 8);
IF (id MOD 16 = mTyp) & (id DIV 256 = 0) THEN
adr := DWord(mod, pObj + 12);
sec := mod.data;
ELSE
LB.Error("anonymous type not found");
END;
END
ELSE
pObj := SearchName(mod, name);
IF pObj < 0 THEN
LB.Error(mod.name$+ "."+ name$ + " not found ");
ELSE
fp := DWord(mod, pObj);
id := DWord(mod, pObj + 8);
md := id MOD 16;
IF ODD(opt) & (mode = mTyp) THEN fp := DWord(mod, pObj + 4) END;
IF md # mode THEN
LB.Error(mod.name$+ "."+ name$ + " has wrong class");
ELSIF fp # fprint THEN
LB.Error(mod.name$+ "."+ name$ + " has wrong fingerprint");
ELSIF mode = mTyp THEN
IF (opt > 1) & (id DIV 16 MOD 16 # mExported) THEN
LB.Error(mod.name$+ "."+ name$ + " has wrong visibility");
END;
sec := mod.data;
adr := DWord(mod, pObj + 12)
ELSIF mode = mVar THEN
sec := mod.vars;
adr := DWord(mod, pObj + 4);
ELSIF mode = mProc THEN
sec := mod.code;
adr := DWord(mod, pObj + 4)
END;
END;
END;
END SearchObj;
PROCEDURE LoadModule(IN modName: STRING):Module;
VAR mod: Module;
file: Files.File;
inp: Files.Reader;
nofimp: INTEGER;
import: ARRAY 128 OF Module;
PROCEDURE ReadHeader;
CONST OFtag = 6F4F4346H; (* "oOCF" *)
VAR mtag, processor, i : INTEGER;
iname: LB.Name;
headSize, descSize, metaSize, codeSize, varsSize: INTEGER;
dataSize: INTEGER;
BEGIN
Read4(inp, mtag); (* mtag = OFtag *);
Read4(inp, processor); (* processor = proc386 *)
Read4(inp, headSize);
Read4(inp, metaSize);
Read4(inp, descSize);
Read4(inp, codeSize);
Read4(inp, varsSize);
dataSize := metaSize + descSize;
mod.mDesc := metaSize;
mod.data := LB.NewSection(dataSize);
mod.code := LB.NewSection(codeSize);
mod.vars := LB.NewSection(varsSize);
ReadNum(inp, nofimp);
ReadName(inp, iname);
mod.name := modName$;
FOR i := 1 TO nofimp DO
ReadName(inp, iname);
IF iname = "$$" THEN iname := LB.KernelName END;
import[i] := ThisMod(iname);
END;
inp.SetPos(headSize);
END ReadHeader;
PROCEDURE ReadSection(sec: Section);
BEGIN
NEW(sec.bytes, sec.size);
inp.ReadBytes(sec.bytes, 0, sec.size);
END ReadSection;
PROCEDURE WrongLink (fixt, link : INTEGER);
BEGIN
LB.Error(" Wrong link in " + modName$);
END WrongLink;
PROCEDURE FixChain(link, offset: INTEGER; sec: Section; val: INTEGER);
CONST absolute = 100; relative = 101; copy = 102; table = 103; tableend = 104;
VAR fixtype, fixdat: INTEGER;
BEGIN
WHILE link # 0 DO
IF link > 0 THEN (* code *)
fixdat := Get3(mod.code.bytes, link);
fixtype := mod.code.bytes[link+3];
IF fixtype = absolute THEN
Put4(mod.code.bytes, link, offset + val);
LB.FixCode(mod, link, sec);
link := fixdat;
ELSIF fixtype = relative THEN
Put4(mod.code.bytes, link, offset + val - link - 4);
LB.FixRel(mod, link, sec);
link := fixdat;
ELSIF fixtype = table THEN
Put4(mod.code.bytes, link, fixdat);
LB.FixCode(mod, link, sec);
link := link + 4;
ELSIF fixtype = tableend THEN
Put4(mod.code.bytes, link, fixdat);
LB.FixCode(mod, link, sec);
link := 0;
ELSE
WrongLink(fixtype, link);
RETURN;
END;
ELSE (* data *)
link := -link;
fixdat := Get3(mod.data.bytes, link);
fixtype := mod.data.bytes[link+3];
IF fixtype = absolute THEN
Put4(mod.data.bytes, link, offset + val);
LB.FixData(mod, link, sec);
link := fixdat;
ELSIF fixtype = copy THEN
Put4(mod.data.bytes, link, offset + val);
LB.FixCopy(mod, link, sec);
link := fixdat;
ELSE
WrongLink(fixtype, link);
RETURN;
END;
END;
END;
END FixChain;
PROCEDURE FixLocal(sec: Section; val: INTEGER);
VAR offset, link: INTEGER;
BEGIN
ReadNum(inp, link);
WHILE link # 0 DO
ReadNum(inp, offset);
FixChain(link, offset, sec, val);
ReadNum(inp, link)
END
END FixLocal;
PROCEDURE FixExt(imod:Module; IN name: STRING; mode, fp, opt: INTEGER);
VAR offset, link: INTEGER; sec: Section; adr: INTEGER;
BEGIN
SearchObj(imod, name, mode, fp, opt, sec, adr);
ReadNum(inp, link);
WHILE link # 0 DO
ReadNum(inp, offset);
FixChain(link, offset, sec, adr);
ReadNum(inp,link)
END
END FixExt;
PROCEDURE FixKernel(IN name: STRING; fp: INTEGER);
VAR offset, link: INTEGER; sec: Section; oadr: INTEGER;
BEGIN
ReadNum(inp, link);
IF link # 0 THEN
IF (LB.kernelMod # NIL) & (mod # LB.kernelMod) THEN
SearchObj(LB.kernelMod, name, mProc, fp, -1, sec, oadr);
WHILE link # 0 DO
ReadNum(inp, offset);
FixChain(link, offset, sec, oadr);
ReadNum(inp, link)
END
ELSE
LB.Error("no kernel"); RETURN
END
END;
END FixKernel;
PROCEDURE ReadFixups;
VAR mno : INTEGER; otag, fprint, opt: INTEGER;
name: LB.Name;
BEGIN
(* FixBlk *)
FixKernel(newRecName, NewRecFP);
FixKernel(newArrName, NewArrFP);
FixLocal(mod.data, 0); (* Const, Meta *);
FixLocal(mod.data, mod.mDesc); (* Descriptors *)
FixLocal(mod.code, 0); (* proc, CaseLinks, Code.links *)
FixLocal(mod.vars, 0);
(* UseBlk: dlls, modules *)
FOR mno := 1 TO nofimp DO
ReadNum(inp, otag);
WHILE otag # 0 DO
ReadName(inp, name);
ReadNum(inp, fprint);
IF otag = mTyp THEN ReadNum(inp, opt) ELSE opt := 0 END;
IF otag # mConst THEN
FixExt(import[mno], name, otag, fprint, opt);
IF LB.error THEN RETURN END;
END;
ReadNum(inp, otag)
END;
END;
END ReadFixups;
PROCEDURE FixImpRef;
VAR imod: Module; i, imptab, refcnt: INTEGER;
BEGIN
imptab := MWord(mod, mdf_imports);
FOR i := 1 TO nofimp DO
imod := import[i];
IF ~imod.isDll THEN
(* import ref *)
Put4(mod.data.bytes, imptab, imod.mDesc); (* ->DescBlk*)
LB.FixData(mod, imptab, imod.data);
(* inc ref count of imported module *)
refcnt := MWord(imod, mdf_refcnt);
PutMWord(imod, mdf_refcnt, refcnt + 1);
END;
INC(imptab, 4);
END;
END FixImpRef;
PROCEDURE SetOpts;
VAR opts: SET;
BEGIN
opts := BITS(MWord(mod, mdf_opts));
IF ~LB.dynaInit THEN INCL(opts, 16) END; (* init bit (16) *)
IF LB.outDll THEN INCL(opts, 24) END; (* dll bit (24) *)
PutMWord(mod, mdf_opts, ORD(opts));
END SetOpts;
BEGIN
file := LB.ThisObjFile(modName$);
IF file = NIL THEN
LB.Error(modName$ + " not found");
RETURN NIL;
END;
inp := file.NewReader(NIL);
inp.SetPos(0);
NEW(mod);
mod.isDll := FALSE;
ReadHeader;
ReadSection(mod.data);
ReadSection(mod.code);
LB.InitFixTable(mod.dataFix, mod.data);
LB.InitFixTable(mod.codeFix, mod.code);
ReadFixups;
mod.termadr := MWord(mod, mdf_term);
FixImpRef;
SetOpts;
IF LB.lastMod # NIL THEN
PutMWord(mod, mdf_next, LB.lastMod.mDesc);
LB.FixData(mod, mod.mDesc, LB.lastMod.data);
END;
file.Close;
RETURN mod;
END LoadModule;
PROCEDURE CollectExports(mod: Module);
VAR p, numobj: INTEGER;
id, vis, mode, addr: INTEGER;
name: StrPtr;
BEGIN
IF ~mod.exported THEN
GetDir(mod, p, numobj);
WHILE numobj > 0 DO
id := DWord(mod, p + 8); (* id = nameIdx*256 + vis*16 + mode *)
mode := id MOD 16;
vis := id DIV 16 MOD 16;
IF (vis # mInternal) & (mode = mProc) THEN
name := GetPName(mod, id DIV 256);
addr := DWord(mod, p + 4);
LB.ExportProc(mod, name$, addr);
END;
DEC(numobj); INC(p, 16)
END;
mod.exported := TRUE;
END;
END CollectExports;
PROCEDURE ExportVariable*(IN modname: ARRAY OF CHAR; varname: ARRAY OF SHORTCHAR);
VAR p, numobj: INTEGER;
id, vis, mode, addr: INTEGER;
name: StrPtr;
mod: Module;
BEGIN
mod := LB.modList;
WHILE mod # NIL DO
(* Log.String(mod.name$);Log.Ln; *)
mod := mod.next
END;
(* Log.String("HIA: varname = " + varname$); Log.Ln; *)
mod := ThisMod(SHORT(modname$));
GetDir(mod, p, numobj);
WHILE numobj > 0 DO
id := DWord(mod, p + 8); (* id = nameIdx*256 + vis*16 + mode *)
mode := id MOD 16;
vis := id DIV 16 MOD 16;
IF (vis # mInternal) & (mode = mVar) THEN
name := GetPName(mod, id DIV 256);
(* Log.String("HIA: name = " + name$); Log.Ln; *)
addr := DWord(mod, p + 4);
IF varname$ = name$ THEN
(* Log.String("Export var " + varname);Log.Ln; *)
LB.ExportVar(mod, name$, addr);
END;
END;
DEC(numobj); INC(p, 16)
END;
END ExportVariable;
PROCEDURE AddModule*(IN modname: ARRAY OF CHAR);
VAR mod: Module;
BEGIN
mod := ThisMod(SHORT(modname$));
END AddModule;
PROCEDURE MainModule*(IN modname: ARRAY OF CHAR);
VAR mod: Module;
BEGIN
mod := ThisMod(SHORT(modname$));
IF mod # NIL THEN LB.mainMod := mod END;
END MainModule;
PROCEDURE ExportModule*(IN modname: ARRAY OF CHAR);
VAR mod: Module;
BEGIN
mod := ThisMod(SHORT(modname$));
IF mod # NIL THEN CollectExports(mod) END;
END ExportModule;
PROCEDURE ExportAll*;
VAR mod: Module;
BEGIN
mod := LB.modList;
WHILE (mod # NIL) DO
CollectExports(mod);
mod := mod.next
END;
END ExportAll;
END DevLnkLoad.
| Dev/Mod/LnkLoad.odc |
MODULE DevLnkWriteElf;
(** project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Igor Dehtyarenko"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 2016.11 initial version by Igor Dehtyarenko (Trurl)
- 2016.11 Dmitry Solomennikov, FreeBSD 11.0
- 2016.11 Alexander Shiryaev, OpenBSD 6.0
- 2016.11 Ivan Denisov, 2016.11: Chmod
"
issues = "
- ...
"
**)
IMPORT Dialog, LB := DevLnkBase, Files, SYSTEM(*LSH*);
CONST
exeBaseAddress = 8048000H; dllBaseAddress = 0;
linuxInterpreter* = "/lib/ld-linux.so.2"; (* ELF32 x86 *)
openBSDInterpreter* = "/usr/libexec/ld.so"; (* ELF32, ELF64 *)
freeBSDInterpreter* = "/libexec/ld-elf.so.1";
(* OS ABI *)
ELFOSABI_NONE* = 0X;
ELFOSABI_NETBSD* = 2X;
ELFOSABI_LINUX* = 3X;
ELFOSABI_FREEBSD* = 9X;
ELFOSABI_OPENBSD* = 0BX;
ELFOSABI_ARM* = 61X;
TYPE
Module = LB.Module;
Section = RECORD
namIdx: INTEGER;
type: INTEGER;
flags: INTEGER;
size: INTEGER;
addr: INTEGER;
offs: INTEGER;
align: INTEGER;
link: INTEGER;
info: INTEGER;
entrySize: INTEGER;
END;
Segment = RECORD
type: INTEGER;
addr: INTEGER; (* virtual address *)
offs: INTEGER;
msize: INTEGER; (* size in memory *)
fsize: INTEGER; (* size in file image *)
align: INTEGER; (* alignment in memory and in the file *)
flags: INTEGER;
END;
CONST
pageSize = 1000H; (* I386 page size *)
elfHeaderSize = 52; (* ELF32 *)
(* program header table *)
phtOffset = elfHeaderSize;
phtEntrySize = 32; (* ELF32 *)
segmentCount = 8;
phtSize = phtEntrySize * segmentCount;
(* section header table *)
shtEntrySize = 40; (* ELF32 *)
VAR
outFile: Files.File;
out: Files.Writer;
entry_addr, init_addr, fini_addr: INTEGER;
interpreter: ARRAY 128 OF SHORTCHAR;
elfType : INTEGER;
sectionCount: INTEGER;
shtOffset, shtSize: INTEGER; (* section header table offset&size *)
idxSecNames: INTEGER; (* index of section names string table *)
code, data, vars, dyna, dsym, dstr, hash, relo: Section;
empty, intp, noteobsd, shstr: Section;
phtseg, intseg, codeseg, dataseg, dynaseg, noteobsdseg, obsdwxneedseg, dsymseg: Segment;
symNames, secNames: LB.StringTable;
siOutName, siRPath: INTEGER;
symCount, symIdx, symImp : INTEGER;
hashtab: POINTER TO ARRAY OF INTEGER;
(**********************************)
PROCEDURE WriteCh (ch: SHORTCHAR);
BEGIN
out.WriteByte(SHORT(ORD(ch)))
END WriteCh;
PROCEDURE Write1(x: INTEGER);
BEGIN
out.WriteByte(SHORT(SHORT(x MOD 256)))
END Write1;
PROCEDURE Write2 (x: INTEGER);
BEGIN
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256)))
END Write2;
PROCEDURE Write4 (x: INTEGER);
BEGIN
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256)))
END Write4;
PROCEDURE WriteStr(IN s: LB.STRING; len: INTEGER);
VAR i: INTEGER;
BEGIN
i := 0;
WHILE s[i] # 0X DO out.WriteByte(SHORT(ORD(s[i]))); INC(i) END;
WHILE i < len DO out.WriteByte(0); INC(i) END
END WriteStr;
PROCEDURE PadTo(pos: INTEGER);
BEGIN
ASSERT(pos >= out.Pos(), 101);
WHILE out.Pos() < pos DO out.WriteByte(0) END;
END PadTo;
(**********************************)
PROCEDURE HashStr (IN name: LB.STRING): INTEGER;
VAR i, h: INTEGER; g: SET;
BEGIN
h := 0; i := 0;
WHILE name[i] # 0X DO
h := h * 16 + ORD(name[i]);
g := BITS(h) * {28..31};
h := ORD(BITS(h) / SYSTEM.LSH(g, -24) - g);
INC(i)
END;
RETURN h
END HashStr;
PROCEDURE AddSymbol(IN name: LB.STRING; OUT idx, namIdx: INTEGER);
BEGIN
LB.AddName(symNames, name, namIdx);
idx := symIdx;
hashtab[idx] := HashStr(name$);
INC(symIdx);
END AddSymbol;
(**********************************)
PROCEDURE DefSegments;
CONST
PT_NULL = 0; PT_LOAD = 1; PT_DYNAMIC = 2; PT_INTERP = 3; PT_NOTE = 4; PT_PHDR = 6;
PT_OPENBSD_WXNEEDED = 65A3DBE7H; (* types *)
exec = 0; write = 1; read = 2; (* flags *)
PROCEDURE DefSeg(VAR seg: Segment; type: INTEGER; flags:SET; align: INTEGER);
BEGIN
seg.type := type;
seg.flags:= ORD(flags);
seg.align := align;
END DefSeg;
BEGIN
DefSeg(phtseg, PT_PHDR, {read, exec}, 4 );
DefSeg(intseg, PT_INTERP, {read}, 1 );
DefSeg(codeseg, PT_LOAD, {read, exec}, pageSize);
DefSeg(dataseg, PT_LOAD, {read, write}, pageSize);
DefSeg(dynaseg, PT_DYNAMIC, {read, write}, 4);
(* required for OpenBSD, ignored in other OS *)
DefSeg(noteobsdseg, PT_NOTE, {read}, 4);
DefSeg(obsdwxneedseg, PT_OPENBSD_WXNEEDED, {exec}, 4);
DefSeg(dsymseg, PT_LOAD, {read, write}, pageSize);
END DefSegments;
PROCEDURE DefSections;
CONST
(* section types *)
SHT_NULL = 0; SHT_PROGBITS = 1; SHT_SYMTAB = 2; SHT_STRTAB = 3;
SHT_DYNAMIC = 6; SHT_DYNSYM = 11;
SHT_HASH = 5; SHT_REL = 9; SHT_NOBITS = 8;
SHT_NOTE = 7;
(* section flags : is writable (0), occupies memory(1), is executable(2) *)
write = 0; alloc = 1; exec = 2;
PROCEDURE DefSection(VAR scn: Section; IN name: LB.STRING; type, align: INTEGER; flags:SET); BEGIN
LB.AddName(secNames, name, scn.namIdx);
scn.type := type;
scn.flags:= ORD(flags);
scn.align := align;
END DefSection;
BEGIN
(* 0 *) DefSection(empty, "", SHT_NULL,0, {});
(* 1 *) DefSection(code, ".text", SHT_PROGBITS, 4, {alloc, exec});
(* 2 *) DefSection(data, ".data", SHT_PROGBITS, 8, {alloc});
(* 3 *) DefSection(vars, ".bss", SHT_NOBITS, 4, {alloc, write});
(* 4 *) DefSection(dstr, ".dynstr", SHT_STRTAB, 1, {alloc});
(* 5 *) DefSection(dsym, ".dynsym", SHT_DYNSYM, 4, {alloc});
(* 6 *) DefSection(hash, ".hash", SHT_HASH, 4, {alloc});
(* 7 *) DefSection(relo, ".relo", SHT_REL, 4, {alloc});
(* 8 *) DefSection(dyna, ".dynamic", SHT_DYNAMIC, 4, {alloc});
(* 9 *) DefSection(shstr, ".shstrtab", SHT_STRTAB, 4, {});
(*10 *) DefSection(intp, ".interp", SHT_PROGBITS, 1, {alloc});
(*11 *) DefSection(noteobsd, ".note.openbsd.ident", SHT_NOTE, 4, {alloc}); (* for OpenBSD, ignored in other OS *)
dsym.entrySize := 16 (* ELF32 *); dsym.link := 4; dsym.info := 1;
relo.entrySize := 8 (* ELF32 *); relo.link := 5; relo.info := 1;
dyna.entrySize := 8 (* ELF32 *); dyna.link := 4;
hash.entrySize := 4; hash.link := 5;
noteobsd.size := 18H; noteobsd.entrySize := 0; noteobsd.link := 0; noteobsd.info := 0;
dstr.link := 5;
idxSecNames := 9;
sectionCount := 12;
END DefSections;
PROCEDURE Init*;
CONST ET_REL = 1; ET_EXEC = 2; ET_DYN = 3;
VAR si, symi: INTEGER;
BEGIN
LB.InitStringTable(symNames, 1000);
LB.InitStringTable(secNames, 100);
NEW(hashtab, LB.impCount + LB.expCount + 1);
symIdx := 0;
AddSymbol("", symi, si);
siOutName :=0; siRPath := 0;
IF LB.opt.rpath # "" THEN
LB.AddName(symNames, LB.opt.rpath, siRPath);
END;
DefSections;
DefSegments;
IF LB.outDll THEN
elfType := ET_DYN;
LB.ImageBase := dllBaseAddress;;
LB.AddName(symNames, SHORT(LB.outputName$), siOutName);
intp.size := 0;
ELSE
elfType := ET_EXEC;
LB.ImageBase := exeBaseAddress;
ASSERT(LB.opt.elfInterpreter[0] # 0X);
interpreter := LB.opt.elfInterpreter$;
intp.size := LEN(interpreter$) + 1;
END;
intp.offs := elfHeaderSize + phtSize;
intp.addr := intp.offs + LB.ImageBase;
code.size := LB.codeSize;
data.size := LB.dataSize;
vars.size := LB.varsSize;
noteobsd.offs := LB.Aligned(intp.offs + intp.size, noteobsd.align);
noteobsd.addr := noteobsd.offs + LB.ImageBase;
code.offs := LB.Aligned(noteobsd.offs + noteobsd.size, code.align);
code.addr := code.offs + LB.ImageBase;
data.offs := LB.Aligned(code.offs + code.size, pageSize);
data.addr := LB.Aligned(code.addr + code.size, pageSize);
vars.addr := LB.Aligned(data.addr + data.size, vars.align);
entry_addr:= code.addr + LB.initOffs;
init_addr := entry_addr;
fini_addr := code.addr + LB.finiOffs;
END Init;
(**********************************)
PROCEDURE GetBases*(OUT codeBase, dataBase, varsBase: INTEGER);
BEGIN
codeBase := code.addr;
dataBase := data.addr;
varsBase := vars.addr;
END GetBases;
(**********************************)
PROCEDURE CollectImport;
VAR lib: Module; sym: LB.Symbol;
BEGIN
symImp := symIdx;
lib := LB.dllList;
WHILE lib # NIL DO
LB.AddDllName(symNames, lib.exp.name, ".so", lib.exp.namIdx);
sym := lib.exp.next;
WHILE sym # NIL DO
AddSymbol(sym.name, sym.symIdx, sym.namIdx);
sym := sym.next
END;
lib := lib.next
END
END CollectImport;
PROCEDURE CollectExport;
VAR sym: LB.Symbol;
BEGIN
IF LB.expCount > 0 THEN
sym := LB.expList;
WHILE sym # NIL DO
AddSymbol(sym.name, sym.symIdx, sym.namIdx);
sym := sym.next
END
ELSE
END;
END CollectExport;
PROCEDURE CalculateLayout;
PROCEDURE DefSeg(VAR seg: Segment; offs, addr, size: INTEGER);
BEGIN
seg.offs:= offs;
seg.addr:= addr;
seg.msize:= size;
seg.fsize:= size;
END DefSeg;
BEGIN
CollectImport;
CollectExport;
symCount := symIdx;
dyna.size := (LB.impDllCount + 20) * dyna.entrySize;
dsym.size := symCount * dsym.entrySize;
dstr.size := symNames.len;
hash.size := 8 + symCount * 4 * 2;
relo.size := relo.entrySize * (LB.relCount + LB.impCount);
dyna.offs := LB.Aligned(data.offs + data.size, pageSize);
dyna.addr := LB.Aligned(vars.addr + vars.size, pageSize);
dsym.offs := LB.Aligned(dyna.offs + dyna.size, dsym.align);
dstr.offs := LB.Aligned(dsym.offs + dsym.size, dstr.align);
hash.offs := LB.Aligned(dstr.offs + dstr.size, hash.align);
relo.offs := LB.Aligned(hash.offs + hash.size, relo.align);
dsym.addr := dsym.offs + dyna.addr - dyna.offs;
dstr.addr := dstr.offs + dsym.addr - dsym.offs;
hash.addr := hash.offs + dstr.addr - dstr.offs;
relo.addr := relo.offs + hash.addr - hash.offs;
shtOffset := LB.Aligned(relo.offs + relo.size, 4);
shtSize := sectionCount * shtEntrySize;
DefSeg(phtseg, phtOffset, LB.ImageBase + phtOffset, phtSize);
DefSeg(intseg, intp.offs, LB.ImageBase + intp.offs, intp.size);
DefSeg(codeseg, 0, LB.ImageBase, code.offs + code.size);
DefSeg(dataseg, data.offs, data.addr, data.size);
dataseg.msize := dataseg.fsize + vars.size;
DefSeg(dynaseg, dyna.offs, dyna.addr, dyna.size);
(* required for OpenBSD, ignored in other OS *)
DefSeg(noteobsdseg, noteobsd.offs, noteobsd.addr, noteobsd.size);
DefSeg(obsdwxneedseg, 0, 0, 0);
DefSeg(dsymseg, dyna.offs, dyna.addr, shtOffset - dyna.offs);
END CalculateLayout;
(**********************************)
PROCEDURE WriteElfHeader; (* ELF32 x86 *)
CONST
ELFCLASS32 = 1X; ELFDATA2LSB = 1X; EV_CURRENT = 1X;
EM_386 = 3;
VAR e_ident : ARRAY 16 OF SHORTCHAR;
BEGIN
e_ident := 7FX + 'ELF'+ ELFCLASS32 + ELFDATA2LSB + EV_CURRENT;
e_ident[7] := LB.opt.OSABI;
e_ident[8] := 0X;
WriteStr(e_ident,16);
Write2(elfType);
Write2(EM_386);
Write4(1); (* version *)
Write4(entry_addr);
Write4(phtOffset);
Write4(shtOffset);
Write4(0); (* flags *)
Write2(elfHeaderSize);
Write2(phtEntrySize);
Write2(segmentCount);
Write2(shtEntrySize);
Write2(sectionCount);
Write2(idxSecNames);
ASSERT(out.Pos() = elfHeaderSize, 101)
END WriteElfHeader;
PROCEDURE WriteProgramHeaderTable;
PROCEDURE WritePhtEntry(VAR seg: Segment); (* ELF32 *)
BEGIN
Write4(seg.type);
Write4(seg.offs);
Write4(seg.addr);
Write4(seg.addr); (* physical address, ignored *)
Write4(seg.fsize);
Write4(seg.msize);
Write4(seg.flags);
Write4(seg.align)
END WritePhtEntry;
BEGIN
WritePhtEntry(phtseg);
WritePhtEntry(intseg);
WritePhtEntry(codeseg);
WritePhtEntry(dataseg);
WritePhtEntry(dsymseg);
WritePhtEntry(dynaseg);
(* required for OpenBSD, ignored in other OS *)
WritePhtEntry(noteobsdseg);
WritePhtEntry(obsdwxneedseg)
END WriteProgramHeaderTable;
PROCEDURE WriteInterpreter;
BEGIN
IF intp.size > 0 THEN
WriteStr(interpreter, 0);
END;
END WriteInterpreter;
PROCEDURE WritePlt;
VAR mod: Module; sym: LB.Symbol;
BEGIN
mod := LB.dllList;
WHILE mod # NIL DO
sym := mod.exp.next;
WHILE sym # NIL DO
WriteCh(0E9X); Write4(-4); (* jmp rel *)
WriteCh(90X); (* nop *)
sym := sym.next
END;
mod := mod.next
END
END WritePlt;
PROCEDURE WriteCode;
VAR mod: Module;
BEGIN
PadTo(code.offs);
out.WriteBytes(LB.initMod.code.bytes, 0, LB.initMod.code.size);
mod := LB.modList;
WHILE mod # NIL DO
out.WriteBytes(mod.code.bytes, 0, mod.code.size);
mod := mod.next
END;
WritePlt;
END WriteCode;
PROCEDURE WriteData;
VAR mod: Module;
BEGIN
PadTo(data.offs);
mod := LB.modList;
WHILE mod # NIL DO
out.WriteBytes(mod.data.bytes, 0, mod.data.size);
mod := mod.next
END;
END WriteData;
PROCEDURE WriteSymbol(namIdx, val, si, typ: INTEGER); (* ELF32 *)
CONST GLOBAL_FUNC = 18; GLOBAL_OBJECT = 17; GLOBAL_NOTYPE = 16;
BEGIN
Write4(namIdx);
Write4(val);
IF typ = LB.typObj THEN
Write4(4); (*size*);
Write1(GLOBAL_OBJECT)
ELSIF typ = LB.typProc THEN
Write4(0); (*size*);
Write1(GLOBAL_FUNC)
ELSE HALT(100)
END;
Write1(0);
Write2(si);
END WriteSymbol;
PROCEDURE WriteSymbolTable;
VAR sym: LB.Symbol; m: Module;
BEGIN
PadTo(dsym.offs);
WriteSymbol(0, 0, 0, LB.typProc);
(* import *)
m := LB.dllList;
WHILE m # NIL DO
sym := m.exp.next;
WHILE sym # NIL DO
WriteSymbol(sym.namIdx, 0, 0, sym.typ);
sym := sym.next
END;
m := m.next
END;
(* export *)
sym := LB.expList;
WHILE sym # NIL DO
WriteSymbol(sym.namIdx, sym.addr, 1, sym.typ);
sym := sym.next
END;
ASSERT(dsym.size = out.Pos() - dsym.offs, 101);
PadTo(dstr.offs);
LB.WriteStringTable(out, symNames);
END WriteSymbolTable;
PROCEDURE MakeHash(OUT bucket, chain: POINTER TO ARRAY OF INTEGER);
VAR nbucket, symi, hi, k: INTEGER;
BEGIN
nbucket := symCount;
NEW(bucket, nbucket);
NEW(chain, symCount);
FOR symi := 0 TO symCount - 1 DO
chain[symi] := 0;
hi := hashtab[symi] MOD nbucket;
IF bucket[hi] # 0 THEN
k := symi;
WHILE chain[k] # 0 DO k := chain[k] END;
chain[k] := bucket[hi]
END;
bucket[hi] := symi;
END;
END MakeHash;
PROCEDURE WriteHash;
VAR i: INTEGER;
bucket, chain: POINTER TO ARRAY OF INTEGER;
BEGIN
MakeHash(bucket, chain);
PadTo(hash.offs);
Write4(LEN(bucket));
Write4(LEN(chain));
FOR i := 0 TO LEN(bucket)-1 DO Write4(bucket[i]) END;
FOR i := 0 TO LEN(chain)-1 DO Write4(chain[i]) END;
ASSERT(hash.size = out.Pos() - hash.offs, 101)
END WriteHash;
PROCEDURE WriteReloc; (* ELF32 x86 *)
CONST R_386_RELATIVE = 8; R_386_JMP_SLOT = 7; R_386_PC32 = 2; R_386_32 = 1;
VAR mod: Module; sym: LB.Symbol; i: INTEGER;
BEGIN
PadTo(relo.offs);
(* Import *)
mod := LB.dllList;
WHILE mod # NIL DO
sym := mod.exp.next;
WHILE sym # NIL DO
Write4(sym.addr + 1);
Write4(R_386_PC32 + sym.symIdx * 256);
sym := sym.next
END;
mod := mod.next
END;
(* Image *)
LB.SortReloc;
FOR i := 0 TO LB.relCount-1 DO
Write4(LB.relTab[i]); Write4(R_386_RELATIVE);
END;
END WriteReloc;
PROCEDURE WriteDynamic;
CONST DT_NULL = 0; DT_NEEDED = 1; DT_PLTRELSZ = 2; DT_PLTGOT = 3;
DT_HASH = 4; DT_STRTAB = 5; DT_SYMTAB = 6; DT_STRSZ = 10; DT_SYMENT = 11;
DT_INIT = 12; DT_FINI = 13; DT_SONAME = 14; DT_RPATH = 15;
DT_REL = 17; DT_RELSZ = 18; DT_RELENT = 19; DT_PLTREL = 20;
DT_TEXTREL = 22; DT_JMPREL = 23; DT_BIND_NOW = 24;
VAR lib: Module;
PROCEDURE DynaEntry(tag, val: INTEGER); (* ELF32 *)
BEGIN
Write4(tag);
Write4(val)
END DynaEntry;
BEGIN
PadTo(dyna.offs);
lib := LB.dllList;
WHILE lib # NIL DO
DynaEntry(DT_NEEDED, lib.exp.namIdx);
lib := lib.next
END;
IF siRPath > 0 THEN DynaEntry(DT_RPATH, siRPath) END;
DynaEntry(DT_SYMTAB, dsym.addr);
DynaEntry(DT_SYMENT, dsym.entrySize);
DynaEntry(DT_HASH, hash.addr);
DynaEntry(DT_STRTAB, dstr.addr);
DynaEntry(DT_STRSZ, dstr.size);
DynaEntry(DT_TEXTREL, 0);
DynaEntry(DT_REL, relo.addr);
DynaEntry(DT_RELSZ, relo.size);
DynaEntry(DT_RELENT, relo.entrySize);
IF LB.outDll THEN
DynaEntry(DT_SONAME, siOutName);
DynaEntry(DT_INIT, init_addr);
DynaEntry(DT_FINI, fini_addr);
END;
DynaEntry(DT_BIND_NOW, 1);
DynaEntry(DT_NULL, 0); (* marks the end *)
END WriteDynamic;
PROCEDURE WriteObsdNote;
CONST
namesz = 8;
descsz = 4;
type = 1;
BEGIN
PadTo(noteobsd.offs);
Write4(namesz);
Write4(descsz);
Write4(type);
WriteStr("OpenBSD", 8);
Write4(0)
END WriteObsdNote;
PROCEDURE WriteSectionTable;
PROCEDURE WriteSHEntry(VAR scn: Section); (* ELF32 *)
BEGIN
Write4(scn.namIdx);
Write4(scn.type);
Write4(scn.flags);
Write4(scn.addr);
Write4(scn.offs);
Write4(scn.size);
Write4(scn.link);
Write4(scn.info);
Write4(scn.align);
Write4(scn.entrySize);
END WriteSHEntry;
BEGIN
PadTo(shtOffset);
shstr.offs := shtOffset + shtSize;
shstr.size := secNames.len;
WriteSHEntry(empty);
WriteSHEntry(code);
WriteSHEntry(data);
WriteSHEntry(vars);
WriteSHEntry(dstr);
WriteSHEntry(dsym);
WriteSHEntry(hash);
WriteSHEntry(relo);
WriteSHEntry(dyna);
WriteSHEntry(shstr);
WriteSHEntry(intp);
WriteSHEntry(noteobsd); (* for OpenBSD, ignored in other OS *)
PadTo(shstr.offs);
LB.WriteStringTable(out, secNames);
END WriteSectionTable;
PROCEDURE WriteOut*;
VAR res: INTEGER; loc: Files.Locator; path: Dialog.String;
BEGIN
CalculateLayout;
loc := Files.dir.This("");
outFile := Files.dir.New(loc, Files.ask);
out := outFile.NewWriter(out);
out.SetPos(0);
WriteElfHeader;
WriteProgramHeaderTable;
WriteInterpreter;
WriteObsdNote;
WriteCode;
WriteData;
WriteDynamic;
WriteSymbolTable;
WriteHash;
WriteReloc;
WriteSectionTable;
out.SetPos(0);
WriteElfHeader;
IF ~LB.error THEN
outFile.Register(LB.outputName, LB.outputType, Files.ask, res);
IF res # 0 THEN LB.Error('Register') ELSE
Dialog.GetLocPath(loc, path);
IF path # "" THEN path := path + "/" END;
LB.Chmod(path + LB.outputName, {0, 2, 3, 4, 5, 6, 7, 8}) (* rwxrwxr-x *)
END
END
END WriteOut;
END DevLnkWriteElf.
/ Elf
PHT
interpreter
obsdnote (* required for OpenBSD, ignored in other OS *)
\ Code
/ Data
\ Vars
/ Dynamic
SymbolTable
StringTable
Hash;
\ Reloc;
SectionHeaderTable
SectionNames
| Dev/Mod/LnkWriteElf.odc |
MODULE DevLnkWriteElfStatic;
(** project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Igor Dehtyarenko"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 2016.11 initial version by Igor Dehtyarenko (Trurl)
- 2016.11 Dmitry Solomennikov, FreeBSD 11.0
- 2016.11 Alexander Shiryaev, OpenBSD 6.0
- 2016.11 Ivan Denisov, 2016.11: Chmod
"
issues = "
- ...
"
**)
IMPORT Dialog, LB := DevLnkBase, Files;
CONST
defBaseAddress = 8048000H;
TYPE
Module = LB.Module;
Section = RECORD
size: INTEGER;
addr: INTEGER;
offs: INTEGER;
END;
Segment = RECORD
type: INTEGER;
addr: INTEGER; (* virtual address *)
offs: INTEGER;
msize: INTEGER; (* size in memory *)
fsize: INTEGER; (* size in file image *)
align: INTEGER; (* alignment in memory and in the file *)
flags: INTEGER;
END;
CONST
pageSize = 1000H; (* I386 page size *)
elfHeaderSize = 52;
(* program header table *)
phtOffset = elfHeaderSize;
phtEntrySize = 32;
phtEntryCount = 3;
phtSize = phtEntrySize * phtEntryCount;
VAR
outFile: Files.File;
out: Files.Writer;
entry_addr: INTEGER;
elfType : INTEGER;
code, data, vars: Section;
phtseg, codeseg, dataseg: Segment;
(**********************************)
PROCEDURE WriteCh (ch: SHORTCHAR);
BEGIN
out.WriteByte(SHORT(ORD(ch)))
END WriteCh;
PROCEDURE Write2 (x: INTEGER);
BEGIN
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256)))
END Write2;
PROCEDURE Write4 (x: INTEGER);
BEGIN
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256)))
END Write4;
PROCEDURE WriteStr(IN s: LB.STRING);
VAR i: INTEGER;
BEGIN
i := 0;
WHILE s[i] # 0X DO out.WriteByte(SHORT(ORD(s[i]))); INC(i) END;
out.WriteByte(0);
END WriteStr;
PROCEDURE PadTo(pos: INTEGER);
BEGIN
WHILE out.Pos() < pos DO out.WriteByte(0) END;
END PadTo;
(**********************************)
PROCEDURE AddReloc*(addr: INTEGER);
BEGIN
END AddReloc;
(**********************************)
PROCEDURE DefSegments;
CONST
PT_LOAD = 1; PT_PHDR = 6; (* types *)
exec = 0; write = 1; read = 2; (* flags *)
PROCEDURE DefSeg(VAR seg: Segment; type: INTEGER; flags:SET; align: INTEGER);
BEGIN
seg.type := type;
seg.flags:= ORD(flags);
seg.align := align;
END DefSeg;
BEGIN
DefSeg(phtseg, PT_PHDR, {read, exec}, 4 );
DefSeg(codeseg, PT_LOAD, {read, exec}, pageSize);
DefSeg(dataseg, PT_LOAD, {read, write}, pageSize);
END DefSegments;
PROCEDURE Init*;
CONST ET_EXEC = 2;
BEGIN
IF LB.impCount >0 THEN LB.Error('Import ffrom dll') END;
DefSegments;
elfType := ET_EXEC;
LB.ImageBase := defBaseAddress;
code.size := LB.codeSize;
data.size := LB.dataSize;
vars.size := LB.varsSize;
code.offs := LB.Aligned(elfHeaderSize + phtSize, 4);
code.addr := code.offs + LB.ImageBase;
data.offs := LB.Aligned(code.offs + code.size, pageSize);
data.addr := LB.Aligned(code.addr + code.size, pageSize);
vars.addr := LB.Aligned(data.addr + data.size, 4);
entry_addr:= code.addr + LB.initOffs;
END Init;
(**********************************)
PROCEDURE GetBases*(OUT codeBase, dataBase, varsBase: INTEGER);
BEGIN
codeBase := code.addr;
dataBase := data.addr;
varsBase := vars.addr;
END GetBases;
(**********************************)
PROCEDURE CalculateLayout;
PROCEDURE DefSeg(VAR seg: Segment; offs, addr, size: INTEGER);
BEGIN
seg.offs:= offs;
seg.addr:= addr;
seg.msize:= size;
seg.fsize:= size;
END DefSeg;
BEGIN
DefSeg(phtseg, phtOffset, LB.ImageBase + phtOffset, phtSize);
DefSeg(codeseg, 0, LB.ImageBase, code.offs + code.size);
DefSeg(dataseg, data.offs, data.addr, data.size);
dataseg.msize := dataseg.fsize + vars.size;
END CalculateLayout;
(**********************************)
PROCEDURE WriteElfHeader;
CONST
ELFCLASS32 = 1X; ELFDATA2LSB = 1X; EV_CURRENT = 1X;
(* OS ABI *)
ELFOSABI_NONE = 0X;
ELFOSABI_LINUX = 3X;
ELFOSABI_NETBSD = 2X; ELFOSABI_FREEBSD =9X; ELFOSABI_OPENBSD = 0BX;
ELFOSABI_ARM = 61X;
EM_386 = 3;
VAR e_ident : ARRAY 16 OF SHORTCHAR;
BEGIN
e_ident := 7FX + 'ELF'+ ELFCLASS32 + ELFDATA2LSB + EV_CURRENT + ELFOSABI_NONE;
WriteStr(e_ident); PadTo(16);
Write2(elfType);
Write2(EM_386);
Write4(1); (* version *)
Write4(entry_addr);
Write4(phtOffset);
Write4(0);
Write4(0); (* flags *)
Write2(elfHeaderSize);
Write2(phtEntrySize);
Write2(phtEntryCount);
Write2(0);
Write2(0);
Write2(0);
ASSERT(out.Pos() = elfHeaderSize, 101)
END WriteElfHeader;
PROCEDURE WriteProgramHeaderTable;
PROCEDURE WritePhtEntry(VAR seg: Segment);
BEGIN
Write4(seg.type);
Write4(seg.offs);
Write4(seg.addr);
Write4(seg.addr); (* physical address, ignored *)
Write4(seg.fsize);
Write4(seg.msize);
Write4(seg.flags);
Write4(seg.align)
END WritePhtEntry;
BEGIN
WritePhtEntry(phtseg);
WritePhtEntry(codeseg);
WritePhtEntry(dataseg);
END WriteProgramHeaderTable;
PROCEDURE WriteCode;
VAR mod: Module;
BEGIN
PadTo(code.offs);
out.WriteBytes(LB.initMod.code.bytes, 0, LB.initMod.code.size);
mod := LB.modList;
WHILE mod # NIL DO
out.WriteBytes(mod.code.bytes, 0, mod.code.size);
mod := mod.next
END;
END WriteCode;
PROCEDURE WriteData;
VAR mod: Module;
BEGIN
PadTo(data.offs);
mod := LB.modList;
WHILE mod # NIL DO
out.WriteBytes(mod.data.bytes, 0, mod.data.size);
mod := mod.next
END
END WriteData;
PROCEDURE WriteOut*;
VAR res: INTEGER; loc: Files.Locator; path: Dialog.String;
BEGIN
CalculateLayout;
loc := Files.dir.This("");
outFile := Files.dir.New(loc, Files.ask);
out := outFile.NewWriter(out);
out.SetPos(0);
WriteElfHeader;
WriteProgramHeaderTable;
WriteCode;
WriteData;
out.SetPos(0);
WriteElfHeader;
IF ~LB.error THEN
outFile.Register(LB.outputName, LB.outputType, Files.ask, res);
IF res # 0 THEN LB.Error('Register') ELSE
Dialog.GetLocPath(loc, path);
IF path # "" THEN path := path + "/" END;
LB.Chmod(path + LB.outputName, {0, 2, 3, 4, 5, 6, 7, 8}) (* rwxrwxr-x *)
END
END
END WriteOut;
END DevLnkWriteElfStatic.
/ Elf
PHT
\ Code;
/ Const
\ Vars
| Dev/Mod/LnkWriteElfStatic.odc |
MODULE DevLnkWritePe;
(** project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Igor Dehtyarenko"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 2016.11 initial version by Igor Dehtyarenko (Trurl)
"
issues = "
- ...
"
**)
IMPORT LB := DevLnkBase, Files;
TYPE
Module = LB.Module;
Section = RECORD
size: INTEGER;
offs: INTEGER;
addr: INTEGER; (* rva *)
END;
VAR
outFile: Files.File;
out: Files.Writer;
CONST
cui = 3; gui = 2;
ExeImageBase = 400000H; DllImageBase = 10000000H;
SizeOfHeapReserve = 400000H; (* primary heap *)
SizeOfHeapCommit = 10000H;
SizeOfStackReserve = 200000H;
SizeOfStackCommit= 10000H;
SectionAlignment = 1000H;
FileAlignment = 512;
SizeOfHeaders = 1024;
expDirSize = 40;
VAR
subsystem: INTEGER;
AddressOfEntryPoint: INTEGER;
NumberOfSections: INTEGER;
TimeDateStamp: INTEGER;
SizeOfImage : INTEGER;
code, data, vars, rsrc, impo, expo, relo: Section;
impDirSize: INTEGER;
expStrTable, impStrTable: LB.StringTable;
outNameStrIndex: INTEGER;
exeFlags: SET;
PROCEDURE WriteCh (ch: SHORTCHAR);
BEGIN
out.WriteByte(SHORT(ORD(ch)))
END WriteCh;
PROCEDURE Write2 (x: INTEGER);
BEGIN
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256)))
END Write2;
PROCEDURE Write4 (x: INTEGER);
BEGIN
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256))); x := x DIV 256;
out.WriteByte(SHORT(SHORT(x MOD 256)))
END Write4;
PROCEDURE WriteStr(IN s: LB.STRING; len: INTEGER);
VAR i: INTEGER;
BEGIN
i := 0;
WHILE s[i] # 0X DO out.WriteByte(SHORT(ORD(s[i]))); INC(i) END;
WHILE i < len DO out.WriteByte(0); INC(i) END
END WriteStr;
PROCEDURE PadTo(pos: INTEGER);
BEGIN
WHILE out.Pos() < pos DO out.WriteByte(0) END;
END PadTo;
(**********************************)
PROCEDURE Init*;
CONST relocs_stripped = 0; executable_image = 1;
line_nums_stripped = 2; local_syms_stripped = 3;
machine_32bit = 8; debug_stripped = 9;
removable_run_from_swap = 10; net_run_from_swap = 11;
system = 12; dll = 13; up_system_only = 14;
BEGIN
LB.InitStringTable(impStrTable, 1000);
LB.InitStringTable(expStrTable, 0);
subsystem := gui; (* *)
IF LB.opt.subsystem # 0 THEN
subsystem := LB.opt.subsystem;
END;
exeFlags := {executable_image, line_nums_stripped, debug_stripped};
IF LB.outDll THEN
INCL(exeFlags, dll);
LB.ImageBase := DllImageBase;
ELSE
LB.ImageBase := ExeImageBase;
END;
IF LB.opt.imageBase > 0 THEN
LB.ImageBase := LB.opt.imageBase;
END;
NumberOfSections := 0;
code.size := LB.codeSize;
data.size := LB.dataSize;
vars.size := LB.varsSize;
code.addr := SectionAlignment;
data.addr := LB.Aligned(code.addr + code.size, SectionAlignment);
vars.addr := LB.Aligned(data.addr + data.size, SectionAlignment);
AddressOfEntryPoint := code.addr + LB.initOffs;
END Init;
(**********************************)
PROCEDURE GetBases*(OUT codeBase, dataBase, varsBase: INTEGER);
BEGIN
codeBase := code.addr + LB.ImageBase;
dataBase := data.addr + LB.ImageBase;
varsBase := vars.addr + LB.ImageBase;
END GetBases;
(**********************************)
PROCEDURE CollectImp;
VAR lib: Module; sym: LB.Symbol;
symIdx: INTEGER;
BEGIN
symIdx := 0;
lib := LB.dllList;
WHILE lib # NIL DO
LB.AddDllName(impStrTable, lib.exp.name, ".dll", lib.exp.namIdx);
lib.exp.symIdx := symIdx;
sym := lib.exp.next;
WHILE sym # NIL DO
LB.AddHintName(impStrTable, 0, sym.name, sym.namIdx);
sym.symIdx := symIdx;
INC(symIdx);
sym := sym.next
END;
INC(symIdx);
lib := lib.next
END;
impDirSize := 20 * (LB.impDllCount + 1);
impo.size := impDirSize + 8 * (LB.impCount + LB.impDllCount) + impStrTable.len;
END CollectImp;
PROCEDURE CollectExport;
VAR sym: LB.Symbol;
BEGIN
IF LB.expCount > 0 THEN
LB.AddName(expStrTable, SHORT(LB.outputName$), outNameStrIndex);
sym := LB.expList;
WHILE sym # NIL DO
LB.AddName(expStrTable, sym.name, sym.namIdx);
sym := sym.next
END;
expo.size := expDirSize + 10 * LB.expCount + expStrTable.len;
ELSE
expo.size := 0;
END;
END CollectExport;
PROCEDURE CalculateLayout;
VAR
BEGIN
CollectImp;
CollectExport;
(* rva's *)
impo.addr := LB.Aligned(vars.addr + vars.size, SectionAlignment);
expo.addr := LB.Aligned(impo.addr + impo.size, SectionAlignment);
rsrc.addr := LB.Aligned(expo.addr + expo.size, SectionAlignment);
relo.addr := LB.Aligned(rsrc.addr + rsrc.size, SectionAlignment);
(* file pos's *)
code.offs := LB.Aligned(SizeOfHeaders, FileAlignment);
data.offs := LB.Aligned(code.offs + code.size, FileAlignment);
vars.offs := 0;
impo.offs := LB.Aligned(data.offs + data.size, FileAlignment);
expo.offs := LB.Aligned(impo.offs + impo.size, FileAlignment);
rsrc.offs := LB.Aligned(expo.offs + expo.size, FileAlignment);
relo.offs := LB.Aligned(rsrc.offs + rsrc.size, FileAlignment);
IF expo.size = 0 THEN expo.addr := 0; expo.offs := 0 END;
rsrc.addr := 0;
rsrc.size := 0;
rsrc.offs := 0;
END CalculateLayout;
(**********************************)
PROCEDURE WriteSectionHeaders;
CONST cnt_code=5; cnt_data= 6; cnt_udata= 7; discard = 25; exec = 29; read = 30; write = 31;
TYPE
SectName = ARRAY 8 OF SHORTCHAR;
PROCEDURE SectionHeader(IN scn: Section; name:SectName; flags:SET);
BEGIN
IF scn.addr # 0 THEN
WriteStr(name, 8);
Write4(0); (* Misc (always 0) *)
Write4(scn.addr); (* VirtualAddress *)
Write4(LB.Aligned(scn.size, FileAlignment)); (* SizeOfRawData *)
Write4(scn.offs); (* PointerToRawData *)
Write4(0); (* PointerToRelocations *)
Write4(0); (* PointerToLinenumbers *)
Write4(0); (* NumberOfRelocations, NumberOfLinenumbers *)
Write4(ORD(flags));
INC(NumberOfSections)
END
END SectionHeader;
BEGIN
SectionHeader(code, ".text", {cnt_code, read, exec});
SectionHeader(data, ".data", {cnt_data, read, write});
SectionHeader(vars, ".var", {cnt_udata, read, write});
SectionHeader(rsrc, ".rsrc", {cnt_data, read, write});
SectionHeader(impo, ".idata", {cnt_data, read, write});
SectionHeader(expo, ".edata", {cnt_data, read, write});
SectionHeader(relo, ".reloc", {cnt_data, read, discard});
END WriteSectionHeaders;
PROCEDURE WriteHeader;
CONST SizeOfOptionalHeader = 224;
PROCEDURE WriteDosStub;
CONST sizeOfStub = 128; (* >= 64 *)
BEGIN
WriteStr('MZ',60);
Write4(sizeOfStub); (* offset to the PE signature*)
PadTo(sizeOfStub);
END WriteDosStub;
PROCEDURE WriteDirEntry(rva, Size: INTEGER);
BEGIN
Write4(rva); Write4(Size);
END WriteDirEntry;
BEGIN
WriteDosStub;
WriteStr("PE", 4); (* signature *)
(* COFF header *)
Write2(014CH); (* Machine (386) *)
Write2(NumberOfSections);
Write4(TimeDateStamp);
Write4(0);
Write4(0);
Write2(SizeOfOptionalHeader);
Write2(ORD(exeFlags)) ;
(* 'Optional' header *)
Write2(10BH); (* magic (normal ececutable file) *)
WriteCh(2X); WriteCh(5X); (* linker version 2.5 *)
Write4(code.size); (* SizeOfCode *)
Write4(data.size); (* SizeOfInitializedData *)
Write4(vars.size); (* SizeOfUninitializedData *)
Write4(AddressOfEntryPoint);
Write4(code.addr); (* BaseOfCode rva *)
Write4(data.addr); (* BaseOfData rva *)
Write4(LB.ImageBase);
Write4(SectionAlignment);
Write4(FileAlignment);
Write2(5); Write2(0); (* OperatingSystemVersion (Major, Minor) *)
Write2(4); Write2(0); (* ImageVersion *)
Write2(5); Write2(0); (* SubsystemVersion: 5.0 - Windows 2000 *)
Write4(0); (* reserved = 0*)
Write4(SizeOfImage);
Write4(SizeOfHeaders);
Write4(0); (* CheckSum *)
Write2(subsystem);
Write2(0); (* DllCharacteristics *)
Write4(SizeOfStackReserve);
Write4(SizeOfStackCommit);
Write4(SizeOfHeapReserve);
Write4(SizeOfHeapCommit);
Write4(0); (* LoaderFlags =0 *)
Write4(16); (* NumberOfRvaAndSizes *)
(* IMAGE_DIRECTORY: [16] *)
WriteDirEntry(expo.addr, expo.size); (* Export Table *)
WriteDirEntry(impo.addr, impo.size); (* Import Table *)
WriteDirEntry(rsrc.addr, rsrc.size); (* Resource Table *)
WriteDirEntry(0, 0); (* Exception Table *)
WriteDirEntry(0, 0); (* Certificate Table *)
WriteDirEntry(relo.addr, relo.size); (* Base Relocation Table *)
WriteDirEntry(0, 0); (* Debug *)
WriteDirEntry(0, 0); (* Architecture =0 *)
WriteDirEntry(0, 0); (* Global Ptr, size=0 *)
WriteDirEntry(0, 0); (* TLS Table *)
WriteDirEntry(0, 0); (* Load Config Table *)
WriteDirEntry(0, 0); (* Bound Import *)
WriteDirEntry(0, 0); (* Import Address Table *)
WriteDirEntry(0, 0); (* Delay Import Descriptor *)
WriteDirEntry(0, 0); (* CLR Runtime Header *)
WriteDirEntry(0, 0); (* Reserved *)
WriteSectionHeaders;
END WriteHeader;
PROCEDURE WriteInitCode;
BEGIN
out.WriteBytes(LB.initMod.code.bytes, 0, LB.initMod.code.size);
END WriteInitCode;
PROCEDURE WritePlt;
VAR lib: Module; sym: LB.Symbol;
VAR thunk: INTEGER;
BEGIN
thunk := LB.ImageBase + impo.addr + impDirSize; (* absolute addr *)
lib := LB.dllList;
WHILE lib # NIL DO
sym := lib.exp.next;
WHILE sym # NIL DO
WriteCh(0FFX); WriteCh(25X); Write4(thunk + sym.symIdx*4); (* jmp indirect *)
LB.AddReloc(sym.addr + 2);
sym := sym.next
END;
lib := lib.next
END;
END WritePlt;
PROCEDURE WriteCode;
VAR mod: Module;
BEGIN
PadTo(code.offs);
WriteInitCode;
mod := LB.modList;
WHILE mod # NIL DO
out.WriteBytes(mod.code.bytes, 0, mod.code.size);
mod := mod.next
END;
WritePlt;
END WriteCode;
PROCEDURE WriteData;
VAR mod: Module;
BEGIN
PadTo(data.offs);
mod := LB.modList;
WHILE mod # NIL DO
out.WriteBytes(mod.data.bytes, 0, mod.data.size);
mod := mod.next
END
END WriteData;
PROCEDURE WriteImport;
VAR i, lookup, thunk, names: INTEGER;
VAR lib: Module; sym: LB.Symbol;
BEGIN
PadTo(impo.offs);
thunk := impo.addr + impDirSize; (* Address Table *)
lookup := thunk + 4 * (LB.impCount + LB.impDllCount); (* Lookup Table *)
names := lookup + 4 * (LB.impCount + LB.impDllCount); (* Hint/Name Table *)
(* Import Directory *)
lib := LB.dllList;
WHILE lib # NIL DO
Write4(lookup + lib.exp.symIdx * 4);
Write4(0); (* time/data = 0 *)
Write4(0); (* ForwarderChain *)
Write4(names + lib.exp.namIdx);
Write4(thunk + lib.exp.symIdx * 4);
lib := lib.next
END;
Write4(0); Write4(0); Write4(0); Write4(0); Write4(0);
FOR i := 1 TO 2 DO (* lookup table, name table *)
lib := LB.dllList;
WHILE lib # NIL DO
sym := lib.exp.next;
WHILE sym # NIL DO Write4(names + sym.namIdx); sym := sym.next END;
Write4(0);
lib := lib.next
END;
END;
LB.WriteStringTable(out, impStrTable);
END WriteImport;
PROCEDURE WriteExport;
CONST OrdinalBase = 1;
VAR sym: LB.Symbol;
functions, names, ordinals, strings, i: INTEGER;
BEGIN
PadTo(expo.offs);
functions := expo.addr + expDirSize; (* Address Table *)
names := functions + 4 * LB.expCount; (* Name Pointer Table *)
ordinals := names + 4 * LB.expCount; (* Ordinal Table *)
strings := ordinals+ 2 * LB.expCount; (* Name Table *)
(* EXPORT_DIRECTORY *)
Write4(0); (* Characteristics *)
Write4(TimeDateStamp);
Write4(0); (* version *)
Write4(strings + outNameStrIndex); (* Name of the DLL *)
Write4(OrdinalBase);
Write4(LB.expCount); (* NumberOfFunctions *)
Write4(LB.expCount); (* NumberOfNames *)
Write4(functions);
Write4(names);
Write4(ordinals);
sym := LB.expList;
WHILE sym # NIL DO Write4(sym.addr- LB.ImageBase); sym := sym.next END; (* rva *)
sym := LB.expList;
WHILE sym # NIL DO Write4(strings + sym.namIdx); sym := sym.next END;
i := 0; WHILE i < LB.expCount DO Write2(i); INC(i) END;
LB.WriteStringTable(out, expStrTable);
END WriteExport;
PROCEDURE WriteReloc;
CONST pageSize = 4096; IMAGE_REL_BASED_HIGHLOW = 3;
VAR i, hi, blockSize, page, limit, pad: INTEGER;
BEGIN
LB.SortReloc;
PadTo(relo.offs);
relo.size := 0;
i := 0;
WHILE i < LB.relCount DO
page := LB.relTab[i] DIV pageSize * pageSize;
limit := page + pageSize;
hi := i;
WHILE (hi < LB.relCount) & (LB.relTab[hi] < limit) DO INC(hi) END;
blockSize := 8 + 2 * (hi - i);
pad := blockSize MOD 4;
INC(blockSize, pad);
Write4(page - LB.ImageBase); (* rva *)
Write4(blockSize);
WHILE i < hi DO
Write2(LB.relTab[i] - page + IMAGE_REL_BASED_HIGHLOW * pageSize);
INC(i)
END;
IF pad # 0 THEN Write2(0) END;
INC(relo.size, blockSize);
END;
Write4(0); Write4(0);
INC(relo.size, 8);
PadTo(LB.Aligned(relo.offs + relo.size, FileAlignment));
END WriteReloc;
PROCEDURE WriteOut*;
VAR res: INTEGER;
BEGIN
CalculateLayout;
outFile := Files.dir.New(Files.dir.This(""), Files.ask);
out := outFile.NewWriter(out);
out.SetPos(0);
WriteHeader;
WriteCode;
WriteData;
WriteImport;
IF LB.expCount > 0 THEN WriteExport END;
WriteReloc;
SizeOfImage := LB.Aligned(relo.addr + relo.size, SectionAlignment);
out.SetPos(0);
WriteHeader;
IF ~LB.error THEN
outFile.Register(LB.outputName, LB.outputType, Files.ask, res);
IF res # 0 THEN LB.Error('Register') END
END
END WriteOut;
END DevLnkWritePe.
| Dev/Mod/LnkWritePe.odc |
MODULE DevMarkers;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, A.A. Dmitriev, I.A. Denisov, Ketmar Dark"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070301, bh, helper strings enlarged to 1024 characters
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 20170215, center #139, localization support for error messages
-20200605, adimetrius, introduce View.CopyFromSimpleView2 to really enable extensions https://forum.oberoncore.ru/viewtopic.php?f=29&t=6621
-20211123, dia, toggle first error & and unmark errors on right click
-20230307, dia, make toogle does not mark document as dirty
-20230324, k8, unmark with care to caret
"
issues = "
- ...
"
**)
IMPORT
Kernel, Files, Stores, Fonts, Ports, Models, Views, Controllers, Properties, Dialog,
TextModels, TextSetters, TextViews, TextControllers, TextMappers, Windows;
CONST
(** View.mode **)
undefined* = 0; mark* = 1; message* = 2;
firstMode = 1; lastMode = 2;
(** View.err **)
noCode* = 9999;
errFile = "Errors"; point = Ports.point;
TYPE
View* = POINTER TO ABSTRACT RECORD (Views.View)
mode-: INTEGER;
err-: INTEGER;
msg-: POINTER TO ARRAY OF CHAR;
era: INTEGER
END;
Directory* = POINTER TO ABSTRACT RECORD END;
StdView = POINTER TO RECORD (View) END;
StdDirectory = POINTER TO RECORD (Directory) END;
SetModeOp = POINTER TO RECORD (Stores.Operation)
view: View;
mode: INTEGER
END;
VAR
dir-, stdDir-: Directory;
globR: TextModels.Reader; globW: TextModels.Writer; (* recycling done in Load, Insert *)
thisEra: INTEGER;
(** View **)
PROCEDURE (v: View) CopyFromSimpleView2- (source: View), NEW, EMPTY;
PROCEDURE (v: View) CopyFromSimpleView- (source: Views.View), EXTENSIBLE;
BEGIN
(* v.CopyFrom^(source); *)
WITH source: View DO
v.err := source.err; v.mode := source.mode;
IF source.msg # NIL THEN
NEW(v.msg, LEN(source.msg^)); v.msg^ := source.msg^$
END;
v.CopyFromSimpleView2(source)
END
END CopyFromSimpleView;
(*
PROCEDURE (v: View) InitContext* (context: Models.Context), EXTENSIBLE;
BEGIN
ASSERT(v.mode # undefined, 20);
v.InitContext^(context)
END InitContext;
*)
PROCEDURE (v: View) InitErr* (err: INTEGER), NEW, EXTENSIBLE;
BEGIN
ASSERT(v.msg = NIL, 20);
IF v.err # err THEN v.err := err; v.mode := mark END;
IF v.mode = undefined THEN v.mode := mark END
END InitErr;
PROCEDURE (v: View) InitMsg* (msg: ARRAY OF CHAR), NEW, EXTENSIBLE;
VAR i: INTEGER; str: ARRAY 1024 OF CHAR;
BEGIN
ASSERT(v.msg = NIL, 20);
Dialog.MapString(msg, str);
i := 0; WHILE str[i] # 0X DO INC(i) END;
NEW(v.msg, i + 1); v.msg^ := str$;
v.mode := mark
END InitMsg;
PROCEDURE (v: View) SetMode* (mode: INTEGER), NEW, EXTENSIBLE;
VAR op: SetModeOp;
BEGIN
ASSERT((firstMode <= mode) (*& (mode <= lastMode)*), 20);
IF v.mode # mode THEN
NEW(op); op.view := v; op.mode := mode;
Views.Do(v, "#System:ViewSetting", op)
END
END SetMode;
(** Directory **)
PROCEDURE (d: Directory) New* (type: INTEGER): View, NEW, ABSTRACT;
PROCEDURE (d: Directory) NewMsg* (msg: ARRAY OF CHAR): View, NEW, ABSTRACT;
(* SetModeOp *)
PROCEDURE (op: SetModeOp) Do;
VAR v: View; mode: INTEGER;
BEGIN
v := op.view;
mode := v.mode; v.mode := op.mode; op.mode := mode;
Views.Update(v, Views.keepFrames);
IF v.context # NIL THEN v.context.SetSize(Views.undefined, Views.undefined) END
END Do;
PROCEDURE ToggleMode (v: View);
VAR mode: INTEGER;
BEGIN
IF ABS(v.err) # noCode THEN
IF v.mode < lastMode THEN mode := v.mode + 1 ELSE mode := firstMode END
ELSE
IF v.mode < message THEN mode := v.mode + 1 ELSE mode := firstMode END
END;
v.SetMode(mode)
END ToggleMode;
(* primitives for StdView *)
PROCEDURE NumToStr (x: INTEGER; VAR s: ARRAY OF CHAR; VAR i: INTEGER);
VAR j: INTEGER; m: ARRAY 32 OF CHAR;
BEGIN
ASSERT(x >= 0, 20);
j := 0; REPEAT m[j] := CHR(x MOD 10 + ORD("0")); x := x DIV 10; INC(j) UNTIL x = 0;
i := 0; REPEAT DEC(j); s[i] := m[j]; INC(i) UNTIL j = 0;
s[i] := 0X
END NumToStr;
PROCEDURE Load (v: StdView);
VAR view: Views.View; t: TextModels.Model; s: TextMappers.Scanner;
err: INTEGER; i: INTEGER; ch: CHAR; loc, langLoc: Files.Locator;
msg: ARRAY 1024 OF CHAR;
BEGIN
view := NIL;
err := ABS(v.err); NumToStr(err, msg, i);
loc := Files.dir.This("Dev"); IF loc.res # 0 THEN RETURN END;
loc := loc.This("Rsrc"); IF loc.res # 0 THEN RETURN END;
IF (Dialog.language # "") & (Dialog.language # Dialog.defaultLanguage) THEN
langLoc := loc.This(Dialog.language);
IF langLoc.res = 0 THEN
view := Views.OldView(langLoc, errFile)
END
END;
IF (view = NIL) OR ~ (view IS TextViews.View) THEN
view := Views.OldView(loc, errFile)
END;
IF (view # NIL) & (view IS TextViews.View) THEN
t := view(TextViews.View).ThisModel();
IF t # NIL THEN
s.ConnectTo(t);
REPEAT
s.Scan
UNTIL ((s.type = TextMappers.int) & (s.int = err)) OR (s.type = TextMappers.eot);
IF s.type = TextMappers.int THEN
s.Skip(ch); i := 0;
WHILE (ch >= " ") & (i < LEN(msg) - 1) DO
msg[i] := ch; INC(i); s.rider.ReadChar(ch)
END;
msg[i] := 0X
END
END
END;
NEW(v.msg, i + 1); v.msg^ := msg$
END Load;
PROCEDURE DrawMsg (v: StdView; f: Views.Frame; font: Fonts.Font; color: Ports.Color);
VAR w, h, asc, dsc: INTEGER;
BEGIN
CASE v.mode OF
mark:
v.context.GetSize(w, h);
f.DrawLine(point, 0, w - f.dot, h, 0, color);
f.DrawLine(0, h + f.dot, w, - 2 * f.dot, 0, color)
| message:
font.GetBounds(asc, dsc, w);
f.DrawString(2 * point, asc, color, v.msg^, font)
END
END DrawMsg;
PROCEDURE ShowMsg (v: StdView);
BEGIN
IF v.msg = NIL THEN Load(v) END;
Dialog.ShowStatus(v.msg^)
END ShowMsg;
PROCEDURE Track (v: StdView; f: Views.Frame; x, y: INTEGER; buttons: SET);
VAR c: Models.Context; t: TextModels.Model; u, w, h: INTEGER; isDown, in, in0: BOOLEAN; m: SET;
BEGIN
v.context.GetSize(w, h); u := f.dot; in0 := FALSE;
in := (0 <= x) & (x < w) & (0 <= y) & (y < h);
REPEAT
IF in # in0 THEN
f.MarkRect(u, 0, w - u, h, Ports.fill, Ports.invert, Ports.show); in0 := in
END;
f.Input(x, y, m, isDown);
in := (0 <= x) & (x < w) & (0 <= y) & (y < h)
UNTIL ~isDown;
IF in0 THEN
f.MarkRect(u, 0, w - u, h, Ports.fill, Ports.invert, Ports.hide);
IF Dialog.showsStatus & ~(Controllers.modify IN buttons) & ~(Controllers.doubleClick IN buttons) THEN
ShowMsg(v)
ELSE
ToggleMode(v)
END;
c := v.context;
WITH c: TextModels.Context DO
t := c.ThisModel();
TextControllers.SetCaret(t, c.Pos() + 1)
ELSE
END
END
END Track;
PROCEDURE SizePref (v: StdView; VAR p: Properties.SizePref);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; asc, dsc, w: INTEGER;
BEGIN
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN a := c(TextModels.Context).Attr(); font := a.font
ELSE font := Fonts.dir.Default()
END;
font.GetBounds(asc, dsc, w);
p.h := asc + dsc;
CASE v.mode OF
mark:
p.w := p.h + 2 * point
| message:
IF v.msg = NIL THEN Load(v) END;
p.w := font.StringWidth(v.msg^) + 4 * point
END
END SizePref;
(** miscellaneous **)
PROCEDURE Insert* (text: TextModels.Model; pos: INTEGER; v: View);
VAR w: TextModels.Writer; r: TextModels.Reader;
BEGIN
ASSERT(v.era = 0, 20);
Models.BeginModification(Models.clean, text);
v.era := thisEra;
IF pos > text.Length() THEN pos := text.Length() END;
globW := text.NewWriter(globW); w := globW; w.SetPos(pos);
IF pos > 0 THEN DEC(pos) END;
globR := text.NewReader(globR); r := globR; r.SetPos(pos); r.Read;
IF r.attr # NIL THEN w.SetAttr(r.attr) END;
w.WriteView(v, Views.undefined, Views.undefined);
Models.EndModification(Models.clean, text);
END Insert;
PROCEDURE FindController (text: TextModels.Model): TextControllers.Controller;
VAR
w: Windows.Window;
tc: TextControllers.Controller;
c: Controllers.Controller;
v: Views.View;
BEGIN
ASSERT(text # NIL, 20);
tc := TextControllers.Focus();
IF (tc = NIL) OR (tc.text # text) THEN
tc := NIL; w := Windows.dir.First();
WHILE (tc = NIL) & (w # NIL) DO
IF w.doc # NIL THEN
v := w.doc.OriginalView();
IF (v # NIL) & (v IS TextViews.View) THEN
c := v(TextViews.View).ThisController();
IF (c # NIL) & (c IS TextControllers.Controller) THEN
tc := c(TextControllers.Controller);
IF tc.text # text THEN tc := NIL END
END
END
END;
w := Windows.dir.Next(w)
END
END;
RETURN tc
END FindController;
PROCEDURE UnmarkWithCareToCaret (text: TextModels.Model; c: TextControllers.Controller);
VAR
r: TextModels.Reader;
v: Views.View;
pos: INTEGER;
script: Stores.Operation;
oldpos, obeg, oend: INTEGER;
BEGIN
IF c # NIL THEN
oldpos := c.CaretPos();
c.GetSelection(obeg, oend);
ELSE oldpos := 0; obeg := 0; oend := 0
END;
Models.BeginModification(Models.clean, text);
Models.BeginScript(text, "#Dev:DeleteMarkers", script);
r := text.NewReader(NIL); r.ReadView(v);
WHILE ~r.eot DO
IF r.view IS View THEN
pos := r.Pos() - 1;
IF oldpos > pos THEN DEC(oldpos) END;
IF obeg < oend THEN
IF obeg > pos THEN DEC(obeg) END;
IF oend > pos THEN DEC(oend) END;
IF obeg >= oend THEN oldpos := obeg END
END;
text.Delete(pos, pos + 1);
r.SetPos(pos)
END;
r.ReadView(v)
END;
IF c # NIL THEN
IF obeg < oend THEN c.SetSelection(obeg, oend)
ELSIF (oldpos >= 0) & (oldpos <= text.Length()) THEN c.SetCaret(oldpos)
END
END;
INC(thisEra);
Models.EndScript(text, script);
Models.EndModification(Models.clean, text);
END UnmarkWithCareToCaret;
PROCEDURE Unmark* (text: TextModels.Model);
BEGIN UnmarkWithCareToCaret(text, FindController(text))
END Unmark;
(** command **)
PROCEDURE ToggleCurrent*;
VAR c: TextControllers.Controller; t: TextModels.Model; v: Views.View; pos: INTEGER;
BEGIN
c := TextControllers.Focus();
IF (c # NIL) & c.HasCaret() THEN
t := c.text; pos := c.CaretPos();
Models.BeginModification(Models.clean, t);
globR := t.NewReader(globR); globR.SetPos(pos); globR.ReadPrev;
v := globR.view;
IF (v # NIL) & (v IS View) THEN ToggleMode(v(View)) END;
TextViews.ShowRange(t, pos, pos, TextViews.focusOnly);
TextControllers.SetCaret(t, pos);
Models.EndModification(Models.clean, t);
globR := NIL
END
END ToggleCurrent;
(** miscellaneous **)
PROCEDURE ShowFirstError* (text: TextModels.Model; focusOnly: BOOLEAN);
VAR v1: Views.View; pos: INTEGER;
BEGIN
globR := text.NewReader(globR); globR.SetPos(0);
REPEAT globR.ReadView(v1) UNTIL globR.eot OR (v1 IS View);
IF ~globR.eot THEN
pos := globR.Pos();
TextViews.ShowRange(text, pos, pos, focusOnly);
TextControllers.SetCaret(text, pos);
v1(View).SetMode(v1(View).mode);
ToggleCurrent
END
END ShowFirstError;
(** commands **)
PROCEDURE NextError*;
VAR c: TextControllers.Controller; t: TextModels.Model; v1: Views.View;
beg, pos: INTEGER;
BEGIN
c := TextControllers.Focus();
IF c # NIL THEN
t := c.text;
IF c.HasCaret() THEN pos := c.CaretPos()
ELSIF c.HasSelection() THEN c.GetSelection(beg, pos)
ELSE pos := 0
END;
TextControllers.SetSelection(t, TextControllers.none, TextControllers.none);
globR := t.NewReader(globR); globR.SetPos(pos);
REPEAT globR.ReadView(v1) UNTIL globR.eot OR (v1 IS View);
IF ~globR.eot THEN
pos := globR.Pos(); v1(View).SetMode(v1(View).mode);
TextViews.ShowRange(t, pos, pos, TextViews.focusOnly)
ELSE
pos := 0; Dialog.Beep
END;
TextControllers.SetCaret(t, pos);
globR := NIL
END
END NextError;
PROCEDURE UnmarkErrors*;
VAR tv: TextViews.View; c: Controllers.Controller; tc: TextControllers.Controller;
BEGIN
tv := TextViews.Focus();
c := tv.ThisController();
IF (c # NIL) & (c IS TextControllers.Controller) THEN
tc := c(TextControllers.Controller)
END;
IF tv # NIL THEN UnmarkWithCareToCaret(tv.ThisModel(), tc) END
END UnmarkErrors;
(* StdView *)
PROCEDURE (v: StdView) ExternalizeAs (VAR s1: Stores.Store);
BEGIN
s1 := NIL
END ExternalizeAs;
PROCEDURE (v: StdView) SetMode(mode: INTEGER);
BEGIN v.SetMode^(mode); ShowMsg(v)
END SetMode;
PROCEDURE (v: StdView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; color: Ports.Color;
w, h: INTEGER;
BEGIN
c := v.context; c.GetSize(w, h);
WITH c: TextModels.Context DO a := c.Attr(); font := a.font ELSE font := Fonts.dir.Default() END;
IF TRUE (*f.colors >= 4*) THEN color := Ports.grey50 ELSE color := Ports.defaultColor END;
IF v.err >= 0 THEN
f.DrawRect(point, 0, w - point, h, Ports.fill, color);
DrawMsg(v, f, font, Ports.background)
ELSE
f.DrawRect(point, 0, w - point, h, 0, color);
DrawMsg(v, f, font, Ports.defaultColor)
END
END Restore;
PROCEDURE (v: StdView) GetBackground (VAR color: Ports.Color);
BEGIN
color := Ports.background
END GetBackground;
PROCEDURE (v: StdView) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message;
VAR focus: Views.View);
BEGIN
WITH msg: Controllers.TrackMsg DO
IF Controllers.popup IN msg.modifiers THEN
UnmarkErrors
ELSE
Track(v, f, msg.x, msg.y, msg.modifiers)
END
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: StdView) HandlePropMsg (VAR msg: Properties.Message);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; asc, w: INTEGER;
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.SizePref DO
SizePref(v, msg)
| msg: Properties.ResizePref DO
msg.fixed := TRUE
| msg: Properties.FocusPref DO
msg.hotFocus := TRUE
(*
| msg: Properties.StorePref DO
msg.view := NIL
*)
| msg: TextSetters.Pref DO
c := v.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr(); font := a.font
ELSE
font := Fonts.dir.Default()
END;
font.GetBounds(asc, msg.dsc, w)
ELSE
END
ELSE
END
END HandlePropMsg;
(* StdDirectory *)
PROCEDURE (d: StdDirectory) New (err: INTEGER): View;
VAR v: StdView;
BEGIN
NEW(v); v.InitErr(err); RETURN v
END New;
PROCEDURE (d: StdDirectory) NewMsg (msg: ARRAY OF CHAR): View;
VAR v: StdView;
BEGIN
NEW(v); v.InitErr(noCode); v.InitMsg(msg); RETURN v
END NewMsg;
(** Cleaner **)
PROCEDURE Cleanup;
BEGIN
globR := NIL; globW := NIL
END Cleanup;
PROCEDURE SetDir* (d: Directory);
BEGIN
dir := d
END SetDir;
PROCEDURE Init;
VAR d: StdDirectory;
BEGIN
thisEra := 1;
NEW(d); dir := d; stdDir := d
END Init;
BEGIN
Init; Kernel.InstallCleaner(Cleanup)
CLOSE
Kernel.RemoveCleaner(Cleanup)
END DevMarkers.
| Dev/Mod/Markers.odc |
MODULE DevMsgSpy;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
"
issues = "
- ...
"
**)
IMPORT SYSTEM,
Strings, DevDebug, Dialog, Stores, Models, Views, Controllers, Properties, Kernel,
Ports, TextModels, TextViews, TextMappers, StdDialog,
Files, Converters, FormViews, FormModels, Windows, Containers, Services;
CONST
refViewSize = 9 * Ports.point;
TYPE
View = POINTER TO RECORD (Views.View)
inner: Views.View
END;
RefView = POINTER TO RECORD (Views.View)
msg: ANYPTR
END;
Msgs = POINTER TO RECORD
left, right: Msgs;
mod, ident: Kernel.Name;
index: INTEGER;
END;
VAR
para* : RECORD
sel*: Dialog.Selection;
selectNewMessages*: BOOLEAN;
showMessages*: BOOLEAN
END;
text*: TextModels.Model;
msgs: Msgs;
size: INTEGER;
path: ARRAY 4 OF Ports.Point;
(* ------------------- Selection ------------------- *)
PROCEDURE Find(mod, ident: Kernel.Name): Msgs;
VAR m: Msgs;
BEGIN m := msgs;
WHILE m # NIL DO
IF mod < m.mod THEN m := m.left
ELSIF mod > m.mod THEN m := m.right
ELSIF ident < m.ident THEN m := m.left
ELSIF ident > m.ident THEN m := m.right
ELSE RETURN m
END
END;
RETURN NIL
END Find;
PROCEDURE Insert(mod, ident: Kernel.Name);
PROCEDURE InsertTree(VAR m: Msgs);
VAR name: ARRAY 64 OF CHAR;
BEGIN
IF m = NIL THEN
NEW(m); m.mod := mod; m.ident := ident; m.index := size-1;
name := m.mod + "." + m.ident;
para.sel.SetItem(m.index, name);
IF para.selectNewMessages THEN para.sel.Incl(m.index, m.index) END
ELSE
IF mod < m.mod THEN InsertTree(m.left)
ELSIF mod > m.mod THEN InsertTree(m.right)
ELSIF ident < m.ident THEN InsertTree(m.left)
ELSIF ident > m.ident THEN InsertTree(m.right)
END
END
END InsertTree;
BEGIN
INC(size); para.sel.SetLen(size); (* increase size and reset all items *)
InsertTree(msgs); (* insert the new item *)
Dialog.UpdateList(para.sel)
END Insert;
(* ------------------- RefView ------------------- *)
PROCEDURE (v: RefView) Internalize (VAR rd: Stores.Reader);
VAR thisVersion: INTEGER;
BEGIN
v.Internalize^(rd); IF rd.cancelled THEN RETURN END;
rd.ReadVersion(0, 0, thisVersion); IF rd.cancelled THEN RETURN END;
END Internalize;
PROCEDURE (v: RefView) Externalize (VAR wr: Stores.Writer);
BEGIN
v.Externalize^(wr);
wr.WriteVersion(0);
END Externalize;
PROCEDURE (v: RefView) CopyFromSimpleView (source: Views.View);
BEGIN
(* v.CopyFrom^(source); *)
v.msg := source(RefView).msg
END CopyFromSimpleView;
PROCEDURE (v: RefView) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
f.DrawPath(path, 4, Ports.fill, Ports.blue, Ports.closedPoly)
END Restore;
PROCEDURE (v: RefView) HandleCtrlMsg (
f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View
);
TYPE ControllersMessage = POINTER TO Controllers.Message;
ViewsMessage = POINTER TO Views.Message;
ModelsMessage = POINTER TO Models.Message;
PropMessage = POINTER TO Properties.Message;
VAR x, y: INTEGER; isDown: BOOLEAN; mo: SET;name: ARRAY 32 OF CHAR;
BEGIN
WITH msg: Controllers.TrackMsg DO
IF v.msg # NIL THEN
REPEAT
f.MarkRect(0, 0, refViewSize, refViewSize, Ports.fill, Ports.hilite, Ports.show);
REPEAT
f.Input(x, y, mo, isDown)
UNTIL (x < 0) OR (x > refViewSize) OR (y < 0) OR (y > refViewSize) OR ~isDown;
f.MarkRect(0, 0, refViewSize, refViewSize, Ports.fill, Ports.hilite, Ports.hide);
WHILE isDown & ((x < 0) OR (x > refViewSize) OR (y < 0) OR (y > refViewSize)) DO
f.Input(x, y, mo, isDown)
END
UNTIL ~isDown;
IF (x >= 0) & (x <= refViewSize) & (y >= 0) & (y <= refViewSize) THEN
IF v.msg IS ControllersMessage THEN name := "Controllers.Message"
ELSIF v.msg IS PropMessage THEN name := "Properties.Message"
ELSIF v.msg IS ViewsMessage THEN name := "Views.Message"
ELSIF v.msg IS ModelsMessage THEN name := "Models.Message"
ELSE name := "Message Record"
END;
DevDebug.ShowHeapObject(SYSTEM.ADR(v.msg^), name)
END
END
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor
ELSE
END
END HandleCtrlMsg;
PROCEDURE (v: RefView) HandlePropMsg (VAR msg: Properties.Message);
BEGIN
WITH msg: Properties.Preference DO
WITH msg: Properties.ResizePref DO msg.fixed := TRUE
| msg: Properties.SizePref DO msg.w := refViewSize; msg.h := refViewSize
| msg: Properties.FocusPref DO msg.hotFocus := TRUE
ELSE
END
ELSE
END
END HandlePropMsg;
(* ------------------- Wrapper ------------------- *)
PROCEDURE (v: View) CopyFromModelView (source: Views.View; model: Models.Model);
BEGIN
WITH source: View DO
IF model = NIL THEN v.inner := Views.CopyOf(source.inner, Views.shallow)
ELSE v.inner := Views.CopyWithNewModel(source.inner, model)
END;
Stores.Join(v, v.inner)
END
END CopyFromModelView;
PROCEDURE (v: View) ThisModel (): Models.Model;
BEGIN
RETURN v.inner.ThisModel()
END ThisModel;
PROCEDURE (v: View) InitContext (context: Models.Context);
BEGIN
v.InitContext^(context);
v.inner.InitContext(context) (* wrapper and wrapped view share the same context *)
END InitContext;
(*
PROCEDURE (v: View) PropagateDomain;
BEGIN
Stores.InitDomain(v.inner, v.domain)
END PropagateDomain;
*)
PROCEDURE (v: View) Neutralize;
BEGIN
v.inner.Neutralize
END Neutralize;
(* NewFrame: wrapper uses standard frame *)
(* Background: wrapper has no intrinsic background color *)
PROCEDURE (v: View) Restore (f: Views.Frame; l, t, r, b: INTEGER);
BEGIN
Views.InstallFrame(f, v.inner, 0, 0, 0, TRUE)
END Restore;
(* RestoreMarks: wrapper has no intrinsic marks, wrapped view's RestoreMarks is called by framework *)
PROCEDURE DescOfMsg (VAR x: ANYREC): Kernel.Type;
VAR desc: Kernel.Type;
BEGIN
desc := SYSTEM.VAL(Kernel.Type, SYSTEM.TYP(x)); (* tdesc of x *)
RETURN desc
END DescOfMsg;
PROCEDURE WriteLog(t: Kernel.Type; VAR msg: ANYREC; name: ARRAY OF CHAR);
VAR link: RefView; p: ANYPTR; modName, name2 : Kernel.Name; f: TextMappers.Formatter;
BEGIN
Kernel.NewObj(p, t);
SYSTEM.MOVE(SYSTEM.ADR(msg), p, t.size);
NEW(link); link.msg := p;
Kernel.GetModName(t.mod, modName);
name2 := modName$ + "." + name$;
f.ConnectTo(text);
f.WriteString(name2 + " ");
f.WriteView(link);
f.WriteLn;
TextViews.ShowRange(text, text.Length(), text.Length(), ~TextViews.focusOnly)
END WriteLog;
PROCEDURE (v: View) HandleCtrlMsg (f: Views.Frame; VAR msg: Controllers.Message; VAR focus: Views.View);
VAR modName, name: Kernel.Name; t: Kernel.Type; m: Msgs;
BEGIN
t := DescOfMsg(msg);
Kernel.GetModName(t.mod, modName);
Kernel.GetTypeName (t, name);
m := Find(modName, name);
IF m = NIL THEN Insert(modName, name)
ELSIF para.sel.In(m.index) & para.showMessages THEN WriteLog(t, msg, name);
END;
focus := v.inner (* forward all controller messages to wrapped view *)
END HandleCtrlMsg;
PROCEDURE (v: View) ExternalizeAs (VAR s: Stores.Store);
BEGIN
s := v.inner
END ExternalizeAs;
PROCEDURE (v: View) HandlePropMsg (VAR msg: Properties.Message);
VAR modName, name: Kernel.Name; t: Kernel.Type; m: Msgs; res: INTEGER; nn: Kernel.Utf8Name;
BEGIN
t := DescOfMsg(msg);
Kernel.GetModName(t.mod, modName);
Kernel.GetTypeName (t, name);
m := Find(modName, name);
IF m = NIL THEN Insert(modName, name)
ELSIF para.sel.In(m.index) & para.showMessages THEN WriteLog(t, msg, name);
END;
Views.HandlePropMsg(v.inner, msg)
END HandlePropMsg;
PROCEDURE (v: View) HandleViewMsg (f: Views.Frame; VAR msg: Views.Message);
VAR modName, name: Kernel.Name; t: Kernel.Type; m: Msgs;
BEGIN
t := DescOfMsg(msg);
Kernel.GetModName(t.mod, modName);
Kernel.GetTypeName (t, name);
m := Find(modName, name);
IF m = NIL THEN Insert(modName, name)
ELSIF para.sel.In(m.index) & para.showMessages THEN WriteLog(t, msg, name);
END;
WITH msg: Views.ScrollClassMsg DO
msg.allowBitmapScrolling := TRUE
ELSE
END
(* framework performs message propagation *)
END HandleViewMsg;
PROCEDURE (v: View) HandleModelMsg (VAR msg: Models.Message);
VAR modName, name: Kernel.Name; t: Kernel.Type; m: Msgs;
BEGIN
t := DescOfMsg(msg);
Kernel.GetModName(t.mod, modName);
Kernel.GetTypeName (t, name);
m := Find(modName, name);
IF m = NIL THEN Insert(modName, name)
ELSIF para.sel.In(m.index) & para.showMessages THEN WriteLog(t, msg, name);
END;
(* framework performs message propagation *)
END HandleModelMsg;
PROCEDURE Toggle*;
VAR v: Views.View; w: View; replace: Controllers.ReplaceViewMsg;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
v := Containers.FocusSingleton();
Controllers.ResetCurrentPath();
IF v # NIL THEN
WITH v: View DO
replace.old := v; replace.new := v.inner;
ELSE
NEW(w); w.inner := v;
replace.old := v; replace.new := w;
END;
Controllers.Forward(replace)
ELSE Dialog.Beep
END
END Toggle;
PROCEDURE ToggleGuard* (VAR par: Dialog.Par);
VAR v : Views.View;
BEGIN
Controllers.SetCurrentPath(Controllers.targetPath);
v := Containers.FocusSingleton();
Controllers.ResetCurrentPath();
IF (v = NIL) OR ~(v IS View) THEN
par.label := "#Dev:AddView";
par.disabled := v = NIL
ELSE
par.label := "#Dev:RemoveView"
END
END ToggleGuard;
PROCEDURE Reset*;
BEGIN
msgs := NIL; size := 0; para.sel.SetLen(size);
Dialog.UpdateList(para.sel)
END Reset;
PROCEDURE Clear*;
BEGIN
text.Delete(0, text.Length())
END Clear;
PROCEDURE PathToSpec (VAR path: ARRAY OF CHAR; VAR loc: Files.Locator; VAR name: Files.Name);
VAR i, j: INTEGER; ch: CHAR;
BEGIN
i := 0; j := 0; loc := Files.dir.This("");
WHILE (loc.res = 0) & (i < LEN(path) - 1) & (j < LEN(name) - 1) & (path[i] # 0X) DO
ch := path[i]; INC(i);
IF (j > 0) & ((ch = "/") OR (ch = "\")) THEN
name[j] := 0X; j := 0; loc := loc.This(name)
ELSE
name[j] := ch; INC(j)
END
END;
IF path[i] = 0X THEN name[j] := 0X
ELSE loc.res := 1; name := ""
END
END PathToSpec;
PROCEDURE OpenDialog*(file, title: ARRAY OF CHAR);
VAR loc: Files.Locator; fname: Files.Name; conv: Converters.Converter; view, v, t: Views.View;
r: FormModels.Reader; t0: Views.Title; done: BOOLEAN; c: Containers.Controller;
BEGIN
Dialog.MapString(title, t0);
Windows.SelectByTitle(NIL, {Windows.isTool}, t0, done);
IF ~ done THEN
PathToSpec(file, loc, fname);
IF loc.res = 0 THEN
conv := NIL;
view := Views.Old(Views.dontAsk, loc, fname, conv);
IF view IS FormViews.View THEN t := NIL;
r := view(FormViews.View).ThisModel().NewReader(NIL);
r.ReadView(v);
WHILE (v # NIL) & (t = NIL) DO
t := Properties.ThisType(v, "TextViews.View");
r.ReadView(v)
END;
IF t # NIL THEN
text := t(TextViews.View).ThisModel();
text.Delete(0, text.Length())
END;
END;
IF view # NIL THEN
WITH view: Containers.View DO
c := view.ThisController();
IF c # NIL THEN
c.SetOpts(c.opts - {Containers.noFocus} + {Containers.noCaret, Containers.noSelection})
ELSE Dialog.ShowMsg("#System:NotEditable")
END
ELSE Dialog.ShowMsg("#System:ContainerExpected")
END;
IF text # NIL THEN
StdDialog.Open(view, title, NIL, "", NIL, TRUE, FALSE, TRUE, FALSE, TRUE)
ELSE
Dialog.ShowMsg("#Dev:TextInDialogExpected")
END
END
ELSE Dialog.ShowParamMsg("#System:FileNotFound", file, "", "")
END;
END
END OpenDialog;
BEGIN
(* NEW(action); action.Do; *)
para.showMessages := TRUE;
size := 0;
path[0].x := refViewSize DIV 2; path[0].y := 0;
path[1].x := refViewSize; path[1].y := refViewSize DIV 2;
path[2].x := refViewSize DIV 2; path[2].y := refViewSize;
path[3].x := 0; path[3].y := refViewSize DIV 2;
END DevMsgSpy.
"DevMsgSpy.OpenDialog('Dev/Rsrc/MsgSpy', 'Message Spy')"
Menu:
"Message Spy..." "" "DevMsgSpy.OpenDialog('Dev/Rsrc/MsgSpy', 'Message Spy')" ""
Strings: (Dev)
AddView Add View
RemoveView Remove View
TextInDialogExpected Text in Dialog expected
Dialog:
StdCoder.Decode ..,, ..qX....3Qw7uP5PRPPNR9Rbf9b8R79FTvMf1uZlbcjRAktYcjRgp,
xW1xhiZiVBhihgmRiioedhgrp9XjJHPNjvQRdJHXS7wb8RTfQ9vQRtIdvPZHjU..D.JA06.Css
HorC4sQqorGqmmKjAST1.PuP.PuP7PNCLLq2o9ZD,6.ciDU7Umy.0E.0.3IXyKtqKfaqmQCb8R
7fJHPNjfL4TXyKt.bHfEjIy0.,.s,cMD.,6.5IXyKtgdjZACbHlayKmKaSNwB0UnNHEjIy4.,U
uq.e.8P16.,6.cUCoruamxhgRiiQeZZhZRgoBhjph0xhsp9XzE.QcjphoVSdw5.0.Z00.p,0E0
GYZdRqYntNCZkNSuWkNM8bVd9CbZ7P6..k.E.0ke59,BXgevQ4,TCbE,5zV.C5FPN5vO3uPlfL
8z4U.EEF.E2F.Y....05.C5MNCaodHKarNHKantQ4abNNCb.MH4amtO0WC,0WBNNsQ.66aai76
mYdtQGb.6...YiVA.1hBFlSzs9gh6Z33gwRE.6.YF0E.Eu0.,E0Uq,S4.05MMsQWajtRq2sQ.6
.CZc,0WB,C5.0WddPUjtN0E.0E...2cNA.fCKNl2Ts9Aoe343Qw.6IfvQFfEf9RdvPRfL8z4U.
EjU.EXU.Y..sNC3U17PKaVV.2U17P.00U.E...AYJ51f9APldCmGghh443gwT.0.,X.2.272.7
.O5UH,cIKanNNG5C2MM.aan7R6...A2guy23bu69lajvJIkmz,6.o96.o66.7sIGbYtEqaYtQu
W1VjtQKa2NO4agtPSa.sEm4C50.,.U,E.Yyvp2188PFHeQNAbZ443Qwb8R7vI5fQT9PNPNZvQR
dJ.5.,6.Yo0k1E49.,E.8cIhgsZiKBhZtQC3h0xmsHpmW5sQO3uZmL.0U..w.oa0.,sUGpmWbB
xhYltQeoNHEjAyI,ktg7cL8T1U.kk2.T.n0,6.Eb2.86.QC18RdfQHfMf9R9vQxGtH.0..c4E.
k.UesFnQ.E.0t.U,UzjV0CyIhACoruKuEqUHZC58RZ9Pxms,.U1xB.uZlT6AA.cQ...b1.o9ZD
,6.636.M00U.2..AU0CyIVGhighgmRCbWGhigFjAyI,ktIepVSdw5.,6.IIw.IH2U.sU.ktQ8C
JuaLqKKjAyI,.AjgVmz.2U..2,w86.IE.U,ZC..2..EGE.4E.E.EECOhU.wcNC.zwPA.A.2U.E
,9z8U...p.0.4.I3E.6.VQ.E..2eHJ.6...Z1Jsp0E9mr72YKQ4hO8BF,9z5U.E41.,.d1,E0G
2O5sNC3a5GZjtNSagNN0U,7NGaUMHC5C36.GYZdR..u0Ub7PsFKbVdQG40..EulEPHIoY8L4nw
gLF.3U..8ssP2Coru4UntIGqVyKr.o9XjF..Cb1,USdwl.,..A,,E.0U06.,6.,c.16QBaywPW
.0.161lbA2TmNeHXGBnmcUXDF.sET1.4zVkk.Um,..QC.Ej2yHZCQCwBu32..W.0..0F6Cb.yy
W8Utj00My7Yb6OQzL0yl1...
--- end of encoding --- | Dev/Mod/MsgSpy.odc |
MODULE DevPacker;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems, I.A. Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070402, bh, SplitName corrected
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150527, center #55, RemoveWhiteSpaces no longer loops at the end of the text
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
- 20211028, ia, intruduce cross-platform GetModDate
"
issues = "
- ...
"
**)
(* WinPackedFiles and LinPackedFiles depend on the way files are packed here *)
IMPORT
Kernel, Services, Strings, Files, Dialog, Stores, Views, Librarian,
TextModels, TextViews, TextMappers, StdLog, DevCommanders;
CONST
packTag = 12681268H; (* same as in HostPackedFiles *)
chunksize = 65536;
version = 1; (* same as in HostPackedFiles *)
TYPE
FileList = POINTER TO RECORD
path, name: Files.Name;
aliasPath, aliasName: Files.Name;
adr, len: INTEGER;
year, month, day, hour, minute, second: INTEGER;
next: FileList
END;
PROCEDURE Diff (VAR a, b: ARRAY OF CHAR; caseSens: BOOLEAN): INTEGER;
VAR i: INTEGER; cha, chb: CHAR;
BEGIN
i := 0;
REPEAT
cha := a[i]; chb := b[i]; INC(i);
IF cha # chb THEN
IF ~caseSens THEN
cha := Strings.Upper(cha);
chb := Strings.Upper(chb);
END;
IF cha = "\" THEN cha := "/" END;
IF chb = "\" THEN chb := "/" END;
IF cha # chb THEN RETURN ORD(cha) - ORD(chb) END
END
UNTIL cha = 0X;
RETURN 0
END Diff;
PROCEDURE SplitName (IN name: Files.Name; OUT path, fname: Files.Name);
VAR i, l, sp: INTEGER;
BEGIN
path := ""; fname := "";
l := LEN(name$);
i := 0; sp := -1;
WHILE i < l DO
path[i] := name[i];
IF (name[i] = "\") OR (name[i] = "/") THEN sp := i END;
INC(i)
END;
IF sp < 0 THEN
fname := name; path := ""
ELSE
path[sp] := 0X;
i := 0; INC(sp);
WHILE name[sp] # 0X DO fname[i] := name[sp]; INC(sp); INC(i) END;
fname[i] := 0X
END
END SplitName;
PROCEDURE PackExe(files: FileList; exe: Files.File);
VAR tableadr, tot, err, ok, i, dl: INTEGER; l: FileList;
wr: Files.Writer; sw: Stores.Writer;
bytes: ARRAY chunksize OF BYTE;
loc: Files.Locator; f: Files.File; r: Files.Reader; shared: BOOLEAN;
num: ARRAY 7 OF CHAR;
PROCEDURE GetModDate (loc: Files.Locator; name: Files.Name;
VAR year, month, day, hour, minute, second: INTEGER);
VAR res: INTEGER; list: Files.FileInfo;
BEGIN
list := Files.dir.FileList(loc);
WHILE (list # NIL) & ~ Files.dir.SameFile(loc, name, loc, list.name) DO
list := list.next
END;
IF list # NIL THEN
year := list.modified.year; month := list.modified.month;
day := list.modified.day; hour := list.modified.hour;
minute := list.modified.minute; second := list.modified.second
END
END GetModDate;
BEGIN
tot := 0; err := 0; ok := 0;
l := files; wr := exe.NewWriter(NIL);
Dialog.ShowStatus('Packing...');
WHILE l # NIL DO
StdLog.String("Packing file: " + l.path + '/' + l.name); StdLog.Ln;
INC(tot);
loc := Files.dir.This(l.path); shared := FALSE;
f := Files.dir.Old(loc, l.name, shared);
IF f = NIL THEN shared := TRUE; f := Files.dir.Old(loc, l.name, shared) END;
IF f # NIL THEN
l.len := f.Length();
l.adr := exe.Length();
GetModDate(loc, l.name, l.year, l.month, l.day, l.hour, l.minute, l.second);
r := f.NewReader(NIL); r.SetPos(0);
wr.SetPos(l.adr);
i := 0; dl := MIN(chunksize, l.len);
WHILE dl > 0 DO
r.ReadBytes(bytes, 0, dl);
wr.WriteBytes(bytes, 0, dl); exe.Flush;
INC(i); dl := MIN(chunksize, l.len - i * chunksize)
END;
IF ~shared THEN f.Close END;
INC(ok);
Kernel.Collect
ELSE
StdLog.String("Could not read file: " + l.path + '/' + l.name); StdLog.Ln; INC(err)
END;
l := l.next
END;
l := files; tableadr := exe.Length();
sw.ConnectTo(exe); sw.SetPos(tableadr);
sw.WriteInt(tot);
WHILE l # NIL DO
sw.WriteString(l.aliasPath); sw.WriteString(l.aliasName);
sw.WriteInt(l.adr); sw.WriteInt(l.len);
sw.WriteInt(l.year); sw.WriteInt(l.month); sw.WriteInt(l.day);
sw.WriteInt(l.hour); sw.WriteInt(l.minute); sw.WriteInt(l.second);
l := l.next
END;
sw.WriteInt(packTag);
sw.WriteInt(version);
sw.WriteInt(tableadr);
IF err > 0 THEN
Strings.IntToString(err, num);
Dialog.ShowMsg("Pack failed for: " + num + " files.");
Dialog.ShowStatus("failed")
ELSE
StdLog.String("Packed files: "); StdLog.Int(ok); StdLog.Ln;
Dialog.ShowStatus("ok")
END
END PackExe;
PROCEDURE RecAdd(path: Files.Name; VAR files: FileList; VAR tot: INTEGER);
VAR loc: Files.Locator; fi: Files.FileInfo; li: Files.LocInfo; l: FileList;
BEGIN
loc := Files.dir.This(path); fi := Files.dir.FileList(loc);
WHILE fi # NIL DO
NEW(l); l.path := path$; l.name := fi.name;
l.next := files; files := l; INC(tot);
fi := fi.next
END;
li := Files.dir.LocList(loc);
WHILE li # NIL DO
IF path = "" THEN RecAdd(li.name, files, tot) ELSE RecAdd(path + '/' + li.name, files, tot) END;
li := li.next
END
END RecAdd;
PROCEDURE ListFromSub* (sdir: ARRAY OF CHAR);
CONST colPerRow = 3;
VAR tot, col: INTEGER; files: FileList; t: TextModels.Model; f: TextMappers.Formatter; tv: TextViews.View;
name: Files.Name;
BEGIN
StdLog.String("Examining subdirectory: " + sdir); StdLog.Ln;
files := NIL; tot := 0;
RecAdd(sdir$, files, tot);
IF files # NIL THEN
t := TextModels.dir.New(); f.ConnectTo(t); f.SetPos(0);
f.WriteView(DevCommanders.dir.New()); f.WriteString(' DevPacker.PackThis exefilename.exe :='); f.WriteLn;
col := 0;
WHILE files # NIL DO
IF files.path # "" THEN name := '"' + files.path + '/' ELSE name := '"' END;
name := name + files.name + '"';
IF files.next # NIL THEN name := name + ' ' END;
f.WriteString(name);
INC(col); IF col >= colPerRow THEN f.WriteLn; col := 0 END; (* To avoid long lines *)
files := files.next
END;
f.WriteView(DevCommanders.dir.NewEnd()); f.WriteLn;
tv := TextViews.dir.New(t);
Views.OpenView(tv)
END;
StdLog.String("Found "); StdLog.Int(tot); StdLog.String(" files."); StdLog.Ln
END ListFromSub;
PROCEDURE ListLoadedModules*;
VAR
t: TextModels.Model; f: TextMappers.Formatter; tv: TextViews.View;
path, name: Files.Name; m: Kernel.Module; modName: Kernel.Name;
BEGIN
t := TextModels.dir.New(); f.ConnectTo(t); f.SetPos(0);
f.WriteView(DevCommanders.dir.New()); f.WriteString(' DevPacker.PackThis exefilename.exe :='); f.WriteLn;
m := Kernel.modList;
WHILE m # NIL DO
Kernel.GetModName(m, modName);
Librarian.lib.SplitName(modName, path, name);
path := path + '/Code/';
f.WriteString(path + name + '.ocf ');
m := m.next
END;
f.WriteView(DevCommanders.dir.NewEnd()); f.WriteLn;
tv := TextViews.dir.New(t);
Views.OpenView(tv)
END ListLoadedModules;
PROCEDURE FilesOk(files: FileList; exeloc: Files.Locator; IN exefile: Files.Name): BOOLEAN;
VAR l: FileList; loc: Files.Locator; fi: Files.FileInfo; ret: BOOLEAN;
err, tot: INTEGER;
BEGIN
StdLog.String("Validating files..."); StdLog.Ln;
IF files = NIL THEN StdLog.String("No files to pack."); StdLog.Ln; RETURN FALSE END;
l := files; ret := TRUE; err := 0; tot := 0;
WHILE l # NIL DO
loc := Files.dir.This(l.path);
IF loc.res = 0 THEN
fi := Files.dir.FileList(loc);
WHILE (fi # NIL) & (Diff(l.name, fi.name, FALSE) # 0) DO fi := fi.next END
END;
IF (loc.res # 0) OR (fi = NIL) THEN
IF l.path # "" THEN StdLog.String(l.path + "/") END;
StdLog.String(l.name);
StdLog.String(" ...not found"); ret := FALSE; INC(err);
StdLog.Ln
ELSIF Files.dir.SameFile(exeloc, exefile, loc, fi.name) THEN
StdLog.String(
'Cannot pack a file into itself. (' + l.name + ' cannot be both the target exe and included in the list)');
StdLog.Ln; ret := FALSE; INC(err)
END;
INC(tot); l := l.next
END;
IF err > 0 THEN
StdLog.Int(err); StdLog.String(" files of"); StdLog.Int(tot); StdLog.String(" not correct.");
Dialog.ShowStatus("failed")
ELSE
StdLog.String("All"); StdLog.Int(tot); StdLog.String(" files found.")
END;
StdLog.Ln;
RETURN ret
END FilesOk;
(* Parse the file list *)
PROCEDURE GetCh (rd: TextModels.Reader);
BEGIN
REPEAT rd.Read UNTIL rd.char # TextModels.viewcode
END GetCh;
PROCEDURE RemoveWhiteSpaces (rd: TextModels.Reader; end: INTEGER);
BEGIN
WHILE ~rd.eot & (rd.Pos() <= end) & (rd.char <= 20X) DO GetCh(rd) END
END RemoveWhiteSpaces;
PROCEDURE FileName (rd: TextModels.Reader; end: INTEGER;
OUT name: ARRAY OF CHAR; OUT ok: BOOLEAN
);
VAR i: INTEGER; dquote, squote: BOOLEAN;
PROCEDURE ValidChar(ch: CHAR): BOOLEAN;
BEGIN
IF dquote THEN RETURN ch # '"'
ELSIF squote THEN RETURN ch # "'"
ELSE RETURN ch > 20X
END
END ValidChar;
BEGIN
ok := TRUE;
RemoveWhiteSpaces(rd, end);
i := 0; dquote := FALSE; squote := FALSE;
IF rd.char = '"' THEN dquote := TRUE
ELSIF rd.char = "'" THEN squote := TRUE
END;
IF dquote OR squote THEN GetCh(rd) END;
WHILE (rd.Pos() <= end) & ValidChar(rd.char) DO
name[i] := rd.char;
INC(i);
GetCh(rd)
END;
name[i] := 0X;
IF dquote THEN ok := rd.char = '"'; rd.Read END;
IF squote THEN ok := rd.char = "'"; rd.Read END
END FileName;
PROCEDURE GetNextFileName (rd: TextModels.Reader; end: INTEGER; VAR file: FileList; OUT ok: BOOLEAN);
VAR name: Files.Name;
BEGIN
FileName(rd, end, name, ok);
SplitName(name, file.path, file.name);
RemoveWhiteSpaces(rd, end);
IF ok & (rd.char = "=") THEN
GetCh(rd);
IF rd.char = ">" THEN
GetCh(rd);
FileName(rd, end, name, ok);
IF name # "" THEN
SplitName(name, file.aliasPath, file.aliasName)
ELSE
ok := FALSE
END
ELSE
ok := FALSE
END
ELSE
file.aliasPath := file.path; file.aliasName := file.name
END
END GetNextFileName;
PROCEDURE ParseExe (rd: TextModels.Reader; end: INTEGER;
OUT exepath, exefile: Files.Name; OUT ok: BOOLEAN
);
VAR name: Files.Name;
BEGIN
ok := FALSE;
GetCh(rd);
FileName(rd, end, name, ok);
IF ok THEN
SplitName(name, exepath, exefile);
RemoveWhiteSpaces(rd, end);
IF ok & (rd.char = ":") THEN
GetCh(rd);
IF rd.char = "=" THEN
GetCh(rd);
ok := TRUE
END
END
END
END ParseExe;
PROCEDURE AlreadyPacked (f: Files.File): BOOLEAN;
VAR rd: Stores.Reader; int: INTEGER;
BEGIN
rd.ConnectTo(f);
rd.SetPos(f.Length() - 12);
rd.ReadInt(int);
rd.ConnectTo(NIL);
RETURN int = packTag
END AlreadyPacked;
PROCEDURE PackThis*;
VAR rd: TextModels.Reader; end, diff: INTEGER; exepath, exefile: Files.Name; ok: BOOLEAN;
files, l, tf, last: FileList; f: Files.File; loc: Files.Locator;
BEGIN
StdLog.String("Sorting file list..."); StdLog.Ln;
rd := DevCommanders.par.text.NewReader(NIL);
rd.SetPos(DevCommanders.par.beg);
end := DevCommanders.par.end;
ParseExe(rd, end, exepath, exefile, ok);
IF ~ok THEN
StdLog.String("exe file not correctly specified"); StdLog.Ln
ELSE
files := NIL; NEW(l);
GetNextFileName(rd, end, l, ok);
WHILE ok & (l.name # "") DO
IF files = NIL THEN
files := l
ELSE
tf := files; last := NIL;
diff := Diff(l.aliasPath, tf.aliasPath, FALSE);
WHILE (tf # NIL) & (diff < 0) DO
last := tf; tf := tf.next;
IF tf # NIL THEN diff := Diff(l.aliasPath, tf.aliasPath, FALSE) END
END;
IF (tf = NIL) OR (diff > 0) THEN
IF last = NIL THEN
l.next := files; files := l
ELSE
l.next := last.next; last.next := l
END
ELSE
diff := Diff(l.aliasName, tf.aliasName, FALSE);
WHILE (tf # NIL) & (diff < 0) & (Diff(l.aliasPath, tf.aliasPath, FALSE) = 0) DO
last := tf; tf := tf.next;
IF tf # NIL THEN diff := Diff(l.aliasName, tf.aliasName, FALSE) END
END;
IF (diff = 0) & (Diff(l.aliasPath, tf.aliasPath, FALSE) = 0) THEN
StdLog.String("File " + l.path + "/" + l.name + " appears more than once in the list."); StdLog.Ln
ELSE
IF last = NIL THEN
l.next := files; files := l
ELSE
l.next := last.next; last.next := l
END
END
END
END;
NEW(l);
GetNextFileName(rd, end, l, ok)
END;
loc := Files.dir.This(exepath$)
END;
IF ok & FilesOk(files, loc, exefile) THEN
f := Files.dir.Old(loc, exefile$, Files.exclusive);
IF f # NIL THEN
IF ~AlreadyPacked(f) THEN
StdLog.String("Packing files to exe..."); StdLog.Ln;
PackExe(files, f);
f.Flush; f.Close;
StdLog.String("Done."); StdLog.Ln
ELSE
f.Flush; f.Close;
IF exepath # "" THEN exepath := exepath + "/" END;
StdLog.String(
"Executable (" + exepath + exefile + ") already contains packed files. Link a new executable.");
StdLog.Ln;
Dialog.ShowMsg("failed")
END
ELSE
IF exepath # "" THEN exepath := exepath + "/" END;
StdLog.String("Could not open exe file: " + exepath + exefile); StdLog.Ln;
Dialog.ShowStatus("failed")
END
ELSE
StdLog.String("Packing canceled."); StdLog.Ln;
Dialog.ShowStatus("failed")
END
END PackThis;
END DevPacker.
"DevPacker.ListFromSub('')"
"DevPacker.ListLoadedModules"
DevPacker.PackThis BlackBoxP.exe := Host/Mod/files.odc
Host/Mod/cmds.odc Std\mod\log.odc Host/Sym\CFrames.osf host\Mod\CFrames.odc
DevPacker.PackThis exefile.exe := Host/Mod/files.odc => Host/Mod/Hoi.odc "host\Mod\CFrames.odc" Std/Mod/Log.odc => 'Std/Mod/Logg.odc'
DevLinker.Link BlackBoxP.exe := Kernel$+ Files HostFiles HostPackedFiles StdLoader
1 Applogo.ico 2 Doclogo.ico 3 SFLogo.ico 4 CFLogo.ico 5 DtyLogo.ico 6 folderimg.ico 7 openimg.ico
8 leafimg.ico
1 Move.cur 2 Copy.cur 3 Link.cur 4 Pick.cur 5 Stop.cur 6 Hand.cur 7 Table.cur | Dev/Mod/Packer.odc |
MODULE DevProfiler;
(**
project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Ilya E. Ermakov, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070523, ie, ShowProfile: calculation of samples in profiled modules corrected
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20160324, center #111, code cleanups
- 20170623, Nikita Plynskii, version for Linux with some reduced functions
- 20230911, dia, moved platform specific part to hook
"
issues = "
- ...
"
**)
IMPORT
Kernel, Strings, Dialog, Utf, Fonts, Ports, Views,
TextModels, TextRulers, TextViews, TextControllers, TextMappers, StdLog;
CONST
maxMod = 256;
TYPE
Module = RECORD
start, end: INTEGER; (* address range *)
first, last: INTEGER; (* procedures *)
mod: Kernel.Module;
count: INTEGER;
END;
Proc = POINTER TO RECORD
name: Kernel.Utf8Name;
p: INTEGER;
next: Proc
END;
ProfilerHook* = POINTER TO ABSTRACT RECORD END;
VAR
mod: ARRAY maxMod OF Module;
pEnd, pCount: POINTER TO ARRAY OF INTEGER;
numMod, numProc, listLen: INTEGER;
otherCount, totalCount: INTEGER;
out: TextMappers.Formatter;
started: BOOLEAN;
hook: ProfilerHook;
PROCEDURE SetProfilerHook* (p: ProfilerHook);
BEGIN
hook := p
END SetProfilerHook;
PROCEDURE (p: ProfilerHook) Count* (pc: INTEGER), NEW;
VAR l, r, m: INTEGER;
BEGIN
l := 0; r := numMod;
WHILE l < r DO (* binary search on modules *)
m := (l + r) DIV 2;
IF pc >= mod[m].end THEN l := m + 1 ELSE r := m END
END;
IF (r < numMod) & (pc >= mod[r].start) & (pc < mod[r].end) THEN
INC(mod[r].count); INC(totalCount);
l := mod[r].first; r := mod[r].last + 1;
WHILE l < r DO (* binary search on procedures *)
m := (l + r) DIV 2;
IF pc >= pEnd[m] THEN l := m + 1 ELSE r := m END
END;
INC(pCount[r])
ELSE INC(otherCount)
END
END Count;
PROCEDURE (p: ProfilerHook) StartRecording*, NEW, ABSTRACT;
PROCEDURE (p: ProfilerHook) StopRecording*, NEW, ABSTRACT;
(* ---------- programming interface ---------- *)
PROCEDURE InsertModule (m: Kernel.Module; VAR done: BOOLEAN);
VAR i: INTEGER;
BEGIN
IF (m # NIL) & (numMod < maxMod) THEN
i := numMod; INC(numMod);
WHILE (i > 0) & (m.code < mod[i-1].mod.code) DO mod[i] := mod[i-1]; DEC(i) END;
mod[i].mod := m;
done := TRUE
ELSE
done := FALSE
END
END InsertModule;
PROCEDURE Start*;
VAR ref, end, i, j: INTEGER; n: Kernel.Utf8Name; m: Kernel.Module; ok: BOOLEAN;
BEGIN
IF hook = NIL THEN
StdLog.String("no profiler for platform"); StdLog.Ln;
ELSE
IF ~started THEN
IF listLen = 0 THEN (* all modules *)
m := Kernel.modList;
WHILE m # NIL DO
IF m.refcnt >= 0 THEN InsertModule(m, ok) END;
m := m.next
END
END;
otherCount := 0; totalCount := 0; numProc := 0; i := 0;
WHILE i < numMod DO
m := mod[i].mod;
mod[i].start := m.code;
mod[i].first := numProc;
ref := m.refs;
Kernel.GetRefProc(ref, end, n);
WHILE end # 0 DO INC(numProc); Kernel.GetRefProc(ref, end, n) END;
mod[i].last := numProc - 1;
INC(i)
END;
NEW(pEnd, numProc);
NEW(pCount, numProc);
i := 0; j := 0;
WHILE i < numMod DO
m := mod[i].mod; ref := m.refs;
Kernel.GetRefProc(ref, end, n);
WHILE end # 0 DO
pEnd[j] := m.code + end; pCount[j] := 0; INC(j);
Kernel.GetRefProc(ref, end, n)
END;
mod[i].end := pEnd[mod[i].last];
mod[i].count := 0;
INC(i)
END;
IF numMod > 0 THEN hook.StartRecording END;
started := TRUE
END
END
END Start;
PROCEDURE Stop*;
BEGIN
IF hook = NIL THEN
StdLog.String("no profiler for platform"); StdLog.Ln;
ELSE
IF started THEN
hook.StopRecording;
started := FALSE
END
END
END Stop;
PROCEDURE Reset*;
BEGIN
Stop;
numMod := 0; numProc := 0; listLen := 0;
pEnd := NIL; pCount := NIL
END Reset;
PROCEDURE SetModuleList* (list: ARRAY OF CHAR);
VAR i, j: INTEGER; name: ARRAY 256 OF CHAR; ch: CHAR; done: BOOLEAN;
BEGIN
Stop;
Reset;
i := 0;
ch := list[i];
WHILE (i < LEN(list)) & (ch # 0X) DO
WHILE (ch # 0X) & ~Strings.IsIdentStart(ch) DO INC(i); ch := list[i] END;
IF ch # 0X THEN
j := 0;
WHILE Strings.IsIdent(ch) DO
name[j] := ch; INC(j); INC(i); ch := list[i]
END;
name[j] := 0X;
InsertModule(Kernel.ThisMod(name), done);
IF done THEN INC(listLen) END
END
END
END SetModuleList;
(*
PROCEDURE GetModuleCount* (name: ARRAY OF CHAR; VAR count: LONGINT);
VAR i: LONGINT;
BEGIN
i := 0;
WHILE (i < numMod) & (mod[i].mod.name # name) DO INC(i) END;
IF i < numMod THEN count := mod[i].count
ELSE count := -1
END
END GetModuleCount;
PROCEDURE GetProcedureCount* (modName, procName: ARRAY OF CHAR; VAR count: LONGINT);
VAR i, j, last, ref, end: LONGINT; name: Kernel.Utf8Name;
BEGIN
i := 0;
WHILE (i < numMod) & (mod[i].mod.name # modName) DO INC(i) END;
IF i < numMod THEN
ref := mod[i].mod.refs; j := mod[i].first - 1; last := mod[i].last;
REPEAT INC(j); Kernel.GetRefProc(ref, end, name); UNTIL (j > last) OR (name = procName);
IF j <= last THEN count := pCount[j]
ELSE count := -1
END
ELSE count := -1
END
END GetProcedureCount;
PROCEDURE GetTotalCount* (VAR inModules, outside: LONGINT);
BEGIN
inModules := totalCount;
outside := otherCount
END GetTotalCount;
*)
(* ---------- menu commands ---------- *)
PROCEDURE Execute*;
VAR t0: LONGINT; res: INTEGER; str: Dialog.String;
BEGIN
t0 := Kernel.Time();
Dialog.Call("DevDebug.Execute", "", res);
StdLog.Int(SHORT((Kernel.Time() - t0) * 1000 DIV Kernel.timeResolution));
Dialog.MapString("#Dev:msec", str);
StdLog.Char(" "); StdLog.String(str);
StdLog.Ln
END Execute;
PROCEDURE NewRuler (): TextRulers.Ruler;
CONST mm = Ports.mm;
VAR p: TextRulers.Prop;
BEGIN
NEW(p);
p.valid := {TextRulers.right, TextRulers.tabs, TextRulers.opts};
p.opts.val := {TextRulers.rightFixed}; p.opts.mask := p.opts.val;
p.right := 130 * mm;
p.tabs.len := 5;
p.tabs.tab[0].stop := 4 * mm; p.tabs.tab[1].stop := 50 * mm;
p.tabs.tab[2].stop := 54 * mm; p.tabs.tab[3].stop := 70 * mm;
p.tabs.tab[4].stop := 74 * mm;
RETURN TextRulers.dir.NewFromProp(p)
END NewRuler;
PROCEDURE ShowModule (VAR m: Module);
VAR i, p, ref, end: INTEGER; proc, list, a, b: Proc; modName, nn: Kernel.Name; res: INTEGER;
BEGIN
ASSERT(totalCount > 0, 20);
p := m.count * 100 DIV totalCount;
IF p > 0 THEN
Kernel.GetModName(m.mod, modName); out.WriteString(modName); out.WriteTab; out.WriteTab;
out.WriteIntForm(p, 10, 2, "", FALSE); out.WriteLn;
NEW(proc); list := NIL;
ref := m.mod.refs; i := m.first;
WHILE i <= m.last DO
Kernel.GetRefProc(ref, end, proc.name);
proc.p := pCount[i] * 100 DIV totalCount;
IF proc.p > 0 THEN proc.next := list; list := proc; NEW(proc) END;
INC(i)
END;
(* sort list *)
WHILE list # NIL DO
a := proc; b := proc.next;
WHILE (b # NIL) & (list.p < b.p) DO a := b; b := b.next END;
a.next := list; a := list.next; list.next := b; list := a
END;
list := proc.next;
WHILE list # NIL DO
Utf.Utf8ToString(list.name, nn, res); out.WriteTab; out.WriteString(nn); out.WriteTab; out.WriteTab;
out.WriteIntForm(list.p, 10, 2, "", FALSE); out.WriteLn;
list := list.next
END;
out.WriteLn;
END
END ShowModule;
PROCEDURE ShowProfile*;
VAR max, limit, maxi, pos, c, n, i: INTEGER; v: TextViews.View; a0: TextModels.Attributes; str: Views.Title;
BEGIN
Stop;
out.ConnectTo(TextModels.dir.New());
a0 := out.rider.attr;
out.rider.SetAttr(TextModels.NewStyle(a0, {Fonts.italic}));
Dialog.MapString("#Dev:Module", str); out.WriteString(str);
out.WriteTab; out.WriteTab;
Dialog.MapString("#Dev:PercentPerModule", str); out.WriteString(str);
out.WriteLn; out.WriteTab;
Dialog.MapString("#Dev:Procedure", str); out.WriteString(str);
out.WriteTab; out.WriteTab;
Dialog.MapString("#Dev:PercentPerProc", str); out.WriteString(str);
out.WriteLn; out.WriteLn;
out.rider.SetAttr(a0);
IF totalCount > 0 THEN
n := numMod; limit := MAX(INTEGER); pos := -1;
WHILE n > 0 DO
i := 0; max := -1;
WHILE i < numMod DO
c := mod[i].count;
IF (c > max) & ((c < limit) OR (c = limit) & (i > pos)) THEN max := c; maxi := i END;
INC(i)
END;
ShowModule(mod[maxi]);
pos := maxi; limit := max;
DEC(n)
END
END;
Dialog.MapString("#Dev:Samples", str); out.WriteString(str);
out.WriteTab; out.WriteTab; out.WriteInt(totalCount + otherCount);
out.WriteTab; out.WriteTab; out.WriteString("100%"); out.WriteLn;
out.WriteTab;
Dialog.MapString("#Dev:InProfiledModules", str); out.WriteString(str);
out.WriteTab; out.WriteTab;
out.WriteInt(totalCount); out.WriteTab; out.WriteTab;
IF totalCount + otherCount > 0 THEN
n := totalCount * 100 DIV (totalCount + otherCount)
ELSE
n := 0
END;
out.WriteInt(n); out.WriteChar("%"); out.WriteLn;
out.WriteTab;
Dialog.MapString("#Dev:Other", str); out.WriteString(str);
out.WriteTab; out.WriteTab;
out.WriteInt(otherCount); out.WriteTab; out.WriteTab;
out.WriteInt(100 - n); out.WriteChar("%"); out.WriteLn;
v := TextViews.dir.New(out.rider.Base());
v.SetDefaults(NewRuler(), TextViews.dir.defAttr);
Dialog.MapString("#Dev:Profile", str);
Views.OpenAux(v, str);
out.ConnectTo(NIL)
END ShowProfile;
PROCEDURE SetProfileList*;
VAR beg, end: INTEGER; s: TextMappers.Scanner;
c: TextControllers.Controller; done: BOOLEAN;
BEGIN
IF ~started THEN
Reset;
c := TextControllers.Focus();
IF c # NIL THEN
s.ConnectTo(c.text);
IF c.HasSelection() THEN c.GetSelection(beg, end)
ELSE beg := 0; end := c.text.Length()
END;
Reset;
s.SetPos(beg); s.Scan;
WHILE (s.start < end) & (s.type # TextMappers.eot) DO
IF s.type = TextMappers.string THEN
IF numMod < maxMod THEN
InsertModule(Kernel.ThisMod(s.string), done);
IF done THEN INC(listLen)
ELSE Dialog.ShowParamMsg("module ^0 not found", s.string, "", "")
END
ELSE
Dialog.ShowMsg("too many modules");
RETURN
END
END;
s.Scan
END
END
END
END SetProfileList;
PROCEDURE StartGuard* (VAR par: Dialog.Par);
BEGIN
IF started THEN par.disabled := TRUE END
END StartGuard;
PROCEDURE StopGuard* (VAR par: Dialog.Par);
BEGIN
IF ~started THEN par.disabled := TRUE END
END StopGuard;
PROCEDURE Init;
BEGIN
IF Dialog.platform = Dialog.windows THEN
Kernel.LoadMod("DevProfiler__Win")
END
END Init;
BEGIN
Init
END DevProfiler.
| Dev/Mod/Profiler.odc |
MODULE DevProfiler__Win;
(**
project = "BlackBox 2.0"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Contributors, Ilya E. Ermakov, Ivan Denisov"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070523, ie, ShowProfile: calculation of samples in profiled modules corrected
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20160324, center #111, code cleanups
- 20170623, Nikita Plynskii, version for Linux with some reduced functions
- 20230911, dia, moved platform specific part to hook
"
issues = "
- ...
"
**)
IMPORT
WinApi, WinMM, DevProfiler;
TYPE
ProfilerHook = POINTER TO RECORD (DevProfiler.ProfilerHook) END;
VAR
id, periode: INTEGER;
hook: ProfilerHook;
PROCEDURE Recorder (id_, msg_, user, dw1_, dw2_: INTEGER);
VAR res_: INTEGER; context: WinApi.CONTEXT;
BEGIN
context.ContextFlags := WinApi.CONTEXT_CONTROL;
res_ := WinApi.GetThreadContext(user, context);
hook.Count(context.Eip) (* current pc of main thread *)
END Recorder;
PROCEDURE (p: ProfilerHook) StartRecording;
(* Start calling Count periodically by an interrupt handler *)
VAR res_: INTEGER; main: WinApi.HANDLE; tc: WinMM.TIMECAPS;
BEGIN
res_ := WinApi.DuplicateHandle(WinApi.GetCurrentProcess(), WinApi.GetCurrentThread(),
WinApi.GetCurrentProcess(), main, {1, 3, 4, 16..19}, 0, {});
res_ := WinMM.timeGetDevCaps(tc, SIZE(WinMM.TIMECAPS));
periode := tc.wPeriodMin * 3;
res_ := WinMM.timeBeginPeriod(periode);
id := WinMM.timeSetEvent(periode, 0, Recorder, main, WinMM.TIME_PERIODIC);
ASSERT(id # 0, 100)
END StartRecording;
PROCEDURE (p: ProfilerHook) StopRecording;
(* stop calling Count *)
VAR res_: INTEGER;
BEGIN
res_ := WinMM.timeKillEvent(id);
res_ := WinMM.timeEndPeriod(periode)
END StopRecording;
BEGIN
NEW(hook);
DevProfiler.SetProfilerHook(hook)
END DevProfiler__Win.
| Dev/Mod/Profiler__Win.odc |
MODULE DevRBrowser;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20070205, bh, Win32s handling removed
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150326, center #33, adding platform detection for wine, Windows 7, and Windows 8
- 20150610, center #60, adaptations for underlined white space
- 20160324, center #111, code cleanups
- 20161216, center #144, inconsistent docu and usage of Files.Locator error codes
"
issues = "
- ...
"
**)
IMPORT
Strings, Dialog, Files, Stores, Converters, Fonts, Ports, Views, Containers,
TextModels, TextMappers, TextRulers, TextViews, StdLinks, StdFolds, Models;
TYPE
SubDesc = RECORD (* description of subsystem contents *)
rsrc: BOOLEAN; (* does subsystem directory have a Rsrc subdirectory? *)
sym, code, mod, docu: Files.FileInfo (* file lists of Sym/Code/Mod/Docu subdirectories *)
END;
PROCEDURE Eq (a, b: CHAR): BOOLEAN;
BEGIN
a := Strings.Upper(a);
b := Strings.Upper(b);
RETURN a = b
END Eq;
PROCEDURE Gt (a, b: CHAR): BOOLEAN;
BEGIN
a := Strings.Upper(a);
b := Strings.Upper(b);
RETURN a > b
END Gt;
PROCEDURE ClipName (VAR s: ARRAY OF CHAR);
VAR h, k: INTEGER; ch: CHAR;
BEGIN (* strip file name suffix *)
k := - 1; h := 0; ch := s[0];
WHILE ch # 0X DO
IF ch = "." THEN k := h END;
INC(h); ch := s[h]
END;
IF k # - 1 THEN s[k] := 0X END
END ClipName;
PROCEDURE Equal (IN a, b: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; cha, chb: CHAR;
BEGIN (* string comparison, not case sensitive *)
i := 0; cha := a[0]; chb := b[0];
WHILE (cha # 0X) & (chb # 0X) & Eq(cha, chb) DO INC(i); cha := a[i]; chb := b[i] END;
RETURN Eq(cha, chb)
END Equal;
PROCEDURE ClippedEqual (a, b: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; cha, chb: CHAR;
BEGIN (* string comparison, not case sensitive *)
ClipName(a); ClipName(b);
i := 0; cha := a[0]; chb := b[0];
WHILE (cha # 0X) & (chb # 0X) & Eq(cha, chb) DO INC(i); cha := a[i]; chb := b[i] END;
RETURN Eq(cha, chb)
END ClippedEqual;
PROCEDURE ClippedGreater (a, b: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; cha, chb: CHAR;
BEGIN (* string comparison, not case sensitive *)
ClipName(a); ClipName(b);
i := 0; cha := a[0]; chb := b[0];
WHILE (cha # 0X) & (chb # 0X) & Eq(cha, chb) DO INC(i); cha := a[i]; chb := b[i] END;
RETURN Gt(cha, chb)
END ClippedGreater;
PROCEDURE Ident (s: ARRAY OF CHAR): BOOLEAN;
CONST MaxIdLen = 256;
VAR i: INTEGER; ch: CHAR;
BEGIN
ClipName(s); i := 0;
REPEAT
ch := s[i]; INC(i)
UNTIL ~Strings.IsIdent(ch) OR (i = MaxIdLen);
RETURN ch = 0X
END Ident;
PROCEDURE WriteOpenFold (VAR f: TextMappers.Formatter; hidden: ARRAY OF CHAR);
VAR fold: StdFolds.Fold; t: TextModels.Model; w: TextMappers.Formatter;
BEGIN
t := TextModels.CloneOf(f.rider.Base());
w.ConnectTo(t); w.WriteString(hidden);
fold := StdFolds.dir.New(StdFolds.expanded, "", t);
f.WriteView(fold)
END WriteOpenFold;
PROCEDURE WriteCloseFold (VAR f: TextMappers.Formatter; collaps: BOOLEAN);
VAR fold: StdFolds.Fold; m: TextModels.Model;
BEGIN
fold := StdFolds.dir.New(StdFolds.expanded, "", NIL);
f.WriteView(fold);
IF collaps THEN fold.Flip; m := f.rider.Base(); f.SetPos(m.Length()) END
END WriteCloseFold;
PROCEDURE WriteLink (VAR f: TextMappers.Formatter; subsystem, directory, file: ARRAY OF CHAR;
attr: TextModels.Attributes);
VAR v: Views.View; s: Files.Name;
BEGIN
IF directory = "" THEN
s := "StdCmds.OpenBrowser('";
s := s + subsystem + "/Docu/";
s := s + file + "', '";
s := s + subsystem + "/Docu/";
s := s + file + "')"
ELSIF Equal(directory , "Rsrc") THEN
s := "DevRBrowser.ShowFiles('";
s := s + subsystem + "/Rsrc')"
ELSE
s := "StdCmds.OpenBrowser('";
s := s + subsystem + "/" + directory;
s := s + "/" + file + "', '";
IF subsystem # "System" THEN s := s + subsystem END;
s := s + file + "')"
END;
f.rider.SetAttr(attr);
v := StdLinks.dir.NewLink(s);
f.WriteView(v); (* insert left link view in text *)
IF directory # "" THEN s := directory$ ELSE s := file$; ClipName(s) END;
f.WriteString(s);
v := StdLinks.dir.NewLink("");
f.WriteView(v) (* insert right link view in text *)
END WriteLink;
PROCEDURE WriteString (VAR f: TextMappers.Formatter; s: ARRAY OF CHAR; attr: TextModels.Attributes);
BEGIN
f.rider.SetAttr(attr); f.WriteString(s);
END WriteString;
PROCEDURE WriteTab (VAR f: TextMappers.Formatter; attr: TextModels.Attributes);
BEGIN
f.rider.SetAttr(attr); f.WriteTab;
END WriteTab;
PROCEDURE WriteLn (VAR f: TextMappers.Formatter; attr: TextModels.Attributes);
BEGIN
f.rider.SetAttr(attr); f.WriteLn;
END WriteLn;
PROCEDURE NewRuler (): TextRulers.Ruler;
VAR p: TextRulers.Prop;
BEGIN
NEW(p);
p.tabs.len := 5;
p.tabs.tab[0].stop := 4 * Ports.mm;
p.tabs.tab[1].stop := 50 * Ports.mm;
p.tabs.tab[2].stop := 70 * Ports.mm;
p.tabs.tab[3].stop := 90 * Ports.mm;
p.tabs.tab[4].stop := 110 * Ports.mm;
p.valid := {TextRulers.tabs};
RETURN TextRulers.dir.NewFromProp(p)
END NewRuler;
PROCEDURE MSort (l: Files.FileInfo; n: INTEGER): Files.FileInfo;
VAR h, h0, r: Files.FileInfo; n2, i: INTEGER;
BEGIN
IF n > 2 THEN
n2 := n DIV 2; h := l; i := n2; WHILE i # 1 DO DEC(i); h := h.next END;
r := h.next; h.next := NIL; (* split list into two half-length lists*)
l := MSort(l, n2); r := MSort(r, n - n2); (* sort both lists separately *)
IF ClippedGreater(r.name, l.name) THEN h := l; l := l.next ELSE h := r; r := r.next END;
h0 := h; (* h0 is back pointer of newly constructed list h *)
WHILE (l # NIL) & (r # NIL) DO
IF ClippedGreater(r.name, l.name) THEN h0.next := l; l := l.next ELSE h0.next := r; r := r.next END;
h0 := h0.next
END;
IF l # NIL THEN h0.next := l ELSIF r # NIL THEN h0.next := r END;
l := h
ELSIF n = 2 THEN
IF ClippedGreater(l.name, l.next.name) THEN l.next.next := l; l := l.next; l.next.next := NIL END
END;
RETURN l
END MSort;
PROCEDURE Sort (i: Files.FileInfo): Files.FileInfo;
VAR n: INTEGER; h: Files.FileInfo;
BEGIN (* merge sort *)
n := 0; h := i; WHILE h # NIL DO INC(n); h := h.next END; (* count number of list elements *)
RETURN MSort(i, n)
END Sort;
PROCEDURE GetThisSubsystem (loc: Files.Locator; VAR sub: SubDesc; VAR isSubsystem: BOOLEAN);
VAR i: Files.LocInfo;
BEGIN
isSubsystem := FALSE; sub.rsrc := FALSE;
i := Files.dir.LocList(loc);
WHILE i # NIL DO
IF Equal(i.name, "Rsrc") THEN
isSubsystem := TRUE; sub.rsrc := TRUE
ELSIF Equal(i.name, "Sym") OR Equal(i.name, "Code") OR
Equal(i.name, "Mod") OR Equal(i.name, "Docu") THEN
isSubsystem := TRUE
END;
i := i.next
END;
sub.sym := Files.dir.FileList(loc.This("Sym"));
sub.code := Files.dir.FileList(loc.This("Code"));
sub.mod := Files.dir.FileList(loc.This("Mod"));
sub.docu := Files.dir.FileList(loc.This("Docu"));
sub.sym := Sort(sub.sym);
sub.code := Sort(sub.code);
sub.mod := Sort(sub.mod);
sub.docu := Sort(sub.docu)
END GetThisSubsystem;
PROCEDURE Convertible (l: Files.FileInfo): BOOLEAN;
VAR c: Converters.Converter;
BEGIN
c := Converters.list; WHILE (c # NIL) & (c.fileType # l.type) DO c := c.next END;
RETURN c # NIL
END Convertible;
PROCEDURE GetModule (VAR sub: SubDesc; OUT i: Files.FileInfo);
BEGIN
i := sub.sym;
IF (sub.code # NIL) & ((i = NIL) OR ClippedGreater(i.name, sub.code.name)) THEN i := sub.code END;
IF (sub.mod # NIL) & ((i = NIL) OR ClippedGreater(i.name, sub.mod.name)) THEN i := sub.mod END;
IF (sub.docu # NIL) & ((i = NIL) OR ClippedGreater(i.name, sub.docu.name)) THEN i := sub.docu END
END GetModule;
PROCEDURE GetNonmodule (VAR l: Files.FileInfo; OUT i: Files.FileInfo);
VAR h: Files.FileInfo;
BEGIN
h := l;
IF (h # NIL) & ~Ident(h.name) THEN
i := l; l := l.next
ELSIF h # NIL THEN
WHILE (h.next # NIL) & Ident(h.next.name) DO h := h.next END;
IF h.next # NIL THEN i := h.next; h.next := i.next ELSE i := NIL END
ELSE
i := NIL
END
END GetNonmodule;
PROCEDURE WriteSubsystem (VAR f: TextMappers.Formatter; old, new, bold: TextModels.Attributes;
VAR sub: SubDesc; name: Files.Name);
VAR i: Files.FileInfo; modname: Files.Name;
BEGIN
WriteString(f, name, bold);
WriteString(f, " ", old);
WriteOpenFold(f, ""); WriteLn(f, old);
IF sub.rsrc THEN WriteTab(f, old); WriteLink(f, name, "Rsrc", "", new); WriteLn(f, old) END;
GetNonmodule(sub.docu, i);
IF i # NIL THEN
WriteTab(f, old);
REPEAT
WriteLink(f, name, "", i.name, new); WriteString(f, " ", old);
GetNonmodule(sub.docu, i)
UNTIL i = NIL;
WriteLn(f, old)
END;
GetModule(sub, i);
WHILE i # NIL DO (* iterate over all modules for which there is a symbol file *)
WriteTab(f, old);
IF ~Equal(name, "System") THEN WriteString(f, name, old) END; (* subsystem name *)
modname := i.name;
ClipName(modname); (* file name => module name *)
WriteString(f, modname, old);
WriteTab(f, old);
IF (sub.sym # NIL) & ClippedEqual(sub.sym.name, i.name) THEN
IF Convertible(sub.sym) THEN WriteLink(f, name, "Sym", sub.sym.name, new) END;
sub.sym := sub.sym.next
END;
WriteTab(f, old);
IF (sub.code # NIL) & ClippedEqual(sub.code.name, i.name) THEN
IF Convertible(sub.code) THEN WriteLink(f, name, "Code", sub.code.name, new) END;
sub.code := sub.code.next
END;
WriteTab(f, old);
IF (sub.mod # NIL) & ClippedEqual(sub.mod.name, i.name) THEN
IF Convertible(sub.mod) THEN WriteLink(f, name, "Mod", sub.mod.name, new) END;
sub.mod := sub.mod.next
END;
WriteTab(f, old);
IF (sub.docu # NIL) & ClippedEqual(sub.docu.name, i.name) THEN
IF Convertible(sub.docu) THEN WriteLink(f, name, "Docu", sub.docu.name, new) END;
sub.docu := sub.docu.next
END;
WriteLn(f, old);
GetModule(sub, i)
END;
WriteCloseFold(f, TRUE);
WriteLn(f, old)
END WriteSubsystem;
PROCEDURE AddFiles(VAR t: TextModels.Model);
VAR f: TextMappers.Formatter;
old, new, bold: TextModels.Attributes;
subinfo: Files.LocInfo; root, subloc: Files.Locator; subdesc: SubDesc; isSubsystem: BOOLEAN;
v: Views.View;
BEGIN
f.ConnectTo(t);
old := f.rider.attr;
new := TextModels.NewStyle(old, old.font.style + {Fonts.underline}); (* use underline style *)
new := TextModels.NewColor(new, Ports.blue); (* use blue color *)
bold := TextModels.NewWeight(old, Fonts.bold); (* use bold outline *)
f.WriteView(NewRuler());
v := StdLinks.dir.NewLink("DevRBrowser.Update");
f.rider.SetAttr(new);
f.WriteView(v); (* insert left link view in text *)
f.WriteString("Update"); f.WriteLn;
v := StdLinks.dir.NewLink("");
f.WriteView(v); (* insert right link view in text *)
f.WriteLn;
root := Files.dir.This("");
subinfo := Files.dir.LocList(root);
WHILE subinfo # NIL DO (* iterate over all locations; no particular sorting order is guaranteed *)
subloc := root.This(subinfo.name);
IF subloc.res = 0 THEN
GetThisSubsystem(subloc, subdesc, isSubsystem);
IF isSubsystem THEN WriteSubsystem(f, old, new, bold, subdesc, subinfo.name) END
END;
subinfo := subinfo.next
END
END AddFiles;
PROCEDURE ShowRepository*;
VAR t: TextModels.Model; tv: TextViews.View;
c: Containers.Controller;
BEGIN
t := TextModels.dir.New();
AddFiles(t);
tv := TextViews.dir.New(t);
c := tv.ThisController();
(* set Browser mode: *)
c.SetOpts(c.opts + {Containers.noCaret} - {Containers.noSelection, Containers.noFocus});
Views.OpenAux(tv, "Repository")
END ShowRepository;
PROCEDURE Update*;
VAR t, t0: TextModels.Model; script: Stores.Operation;
BEGIN
t0 := TextViews.FocusText();
Models.BeginScript(t0, "Update repository", script);
t := TextModels.CloneOf(t0);
AddFiles(t);
t0.Delete(0, t0.Length()); t0.Insert(0, t, 0, t.Length());
Models.EndScript(t0, script)
END Update;
PROCEDURE PathToLoc (path: ARRAY OF CHAR; VAR loc: Files.Locator);
VAR i, j: INTEGER; ch: CHAR; name: Files.Name;
BEGIN
loc := Files.dir.This("");
IF path # "" THEN
i := 0; j := 0;
REPEAT
ch := path[i]; INC(i);
IF (ch = "/") OR (ch = 0X) THEN name[j] := 0X; j := 0; loc := loc.This(name)
ELSE name[j] := ch; INC(j)
END
UNTIL (ch = 0X) OR (loc.res # 0)
END
END PathToLoc;
PROCEDURE ShowFiles* (path: ARRAY OF CHAR);
VAR t: TextModels.Model; f: TextMappers.Formatter; v: Views.View; tv: TextViews.View;
c: Containers.Controller; old, new: TextModels.Attributes; conv: Converters.Converter;
loc: Files.Locator; fi: Files.FileInfo; s: Files.Name;
BEGIN
t := TextModels.dir.New();
f.ConnectTo(t);
old := f.rider.attr; (* save old text attributes for later use *)
new := TextModels.NewStyle(old, old.font.style + {Fonts.underline}); (* use underline style *)
new := TextModels.NewColor(new, Ports.blue); (* use blue color *)
f.rider.SetAttr(new); (* change current attributes of formatter *)
(* generate list of all locations *)
PathToLoc(path, loc);
fi := Files.dir.FileList(loc);
fi := Sort(fi);
WHILE fi # NIL DO (* no particular sorting order is guaranteed *)
conv := Converters.list; WHILE (conv # NIL) & (conv.fileType # fi.type) DO conv := conv.next END;
IF conv # NIL THEN (* there is a converter for this file type *)
s := "DevRBrowser.OpenFile('";
s := s + path + "', '" + fi.name + "')";
v := StdLinks.dir.NewLink(s);
f.WriteView(v); (* insert left link view in text *)
s := fi.name$; ClipName(s); f.WriteString(fi.name);
v := StdLinks.dir.NewLink("");
f.WriteView(v); (* insert right link view in text *)
f.WriteLn
END;
fi := fi.next
END;
tv := TextViews.dir.New(t);
c := tv.ThisController();
(* set Browser mode: *)
c.SetOpts(c.opts + {Containers.noCaret} - {Containers.noSelection, Containers.noFocus});
Views.OpenAux(tv, path$)
END ShowFiles;
PROCEDURE OpenFile* (path, name: ARRAY OF CHAR);
VAR loc: Files.Locator; f: Files.File; c: Converters.Converter; n: Files.Name; s: Stores.Store;
BEGIN
PathToLoc(path, loc); n := name$;
IF loc # NIL THEN
f := Files.dir.Old(loc, n, Files.shared);
IF f # NIL THEN
c := Converters.list; WHILE (c # NIL) & (c.fileType # f.type) DO c := c.next END;
IF c # NIL THEN
Converters.Import(loc, n, c, s);
WITH s: Views.View DO
Views.Open(s, loc, n, c)
ELSE
END
END
END
END
END OpenFile;
END DevRBrowser.
| Dev/Mod/RBrowser.odc |
MODULE DevReferences;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20151201, center #88, support for localizable documentation
- 20161103, center #140, unwrapping import aliasses
- 20211028, ia, export show for it can be possbile for seraching sources in over folders
"
issues = "
- ...
"
**)
IMPORT
Strings, Files, Fonts, Models, Views, Dialog, StdDialog, StdApi, Converters,
TextModels, TextMappers, TextViews, TextControllers, Librarian, Log;
CONST
(* additional scanner types *)
import = 100; module = 101; semicolon = 102; becomes = 103; comEnd = 104;
PROCEDURE SpecialFont (r: TextModels.Reader): BOOLEAN;
CONST max = 14 * Fonts.point;
BEGIN
RETURN (r.attr.font.weight > Fonts.normal) & (r.attr.font.size <= max)
END SpecialFont;
PROCEDURE SearchIdent (
t: TextModels.Model; ident: TextMappers.String; VAR beg, end: INTEGER; bold: BOOLEAN
);
VAR r: TextModels.Reader; found: BOOLEAN; ch: CHAR; len, i: INTEGER;
BEGIN
end := 0;
IF ident # "" THEN
len := 0; WHILE ident[len] # 0X DO INC(len) END;
r := t.NewReader(NIL); found := FALSE;
beg := 0; r.SetPos(0); r.ReadChar(ch);
WHILE ~r.eot & ~found DO
(* search legal start symbol *)
WHILE ~r.eot & ~Strings.IsIdentStart(ch) DO
INC(beg); r.ReadChar(ch)
END;
i := 0;
WHILE ~r.eot & (~bold OR SpecialFont(r)) & (i # len) & (ch = ident[i]) DO
r.ReadChar(ch); INC(i)
END;
found := (i = len) & ~Strings.IsIdent(ch);
IF ~r.eot & ~found THEN (* skip rest of identifier *)
beg := r.Pos() - 1;
WHILE ~r.eot & Strings.IsIdent(ch) DO
INC(beg); r.ReadChar(ch)
END
END
END;
IF found THEN end := r.Pos() - 1 END
END
END SearchIdent;
PROCEDURE ShowText* (module, ident: TextMappers.String; category: Files.Name);
VAR loc: Files.Locator; sub, name: Files.Name; conv: Converters.Converter;
v: Views.View; m: Models.Model; t: TextModels.Model; beg, end: INTEGER;
BEGIN
IF category = "Docu" THEN
Librarian.lib.SplitName(module, sub, name);
Files.dir.GetFileName(name, Files.docType, name);
StdApi.OpenBrowser(sub + "/Docu/" + name, module, v)
ELSE
StdDialog.GetSubLoc(module, category, loc, name);
conv := NIL;
v := Views.Old(Views.dontAsk, loc, name, conv);
IF v # NIL THEN Views.Open(v, loc, name, conv) END
END;
IF v # NIL THEN
m := v.ThisModel();
IF (m # NIL) & (m IS TextModels.Model) THEN
t := m(TextModels.Model);
SearchIdent(t, ident, beg, end, TRUE);
IF end <= 0 THEN SearchIdent(t, ident, beg, end, FALSE) END;
IF end > 0 THEN
TextViews.ShowRange(t, beg, end, TextViews.any);
TextControllers.SetSelection(t, beg, end)
ELSIF ident # "" THEN Dialog.Beep
END
ELSE Dialog.ShowMsg("#System:WrongSelection")
END
ELSE Dialog.ShowParamMsg("#System:FileNotFound", name, "", "")
END
END ShowText;
PROCEDURE Scan (VAR s: TextMappers.Scanner);
BEGIN
s.Scan;
IF s.type = TextMappers.string THEN
IF s.string = "IMPORT" THEN s.type := import
ELSIF s.string = "MODULE" THEN s.type := module
END
ELSIF s.type = TextMappers.char THEN
IF s.char = ";" THEN s.type := semicolon
ELSIF s.char = ":" THEN
IF s.rider.char = "=" THEN s.rider.Read; s.type := becomes END
ELSIF s.char = "(" THEN
IF s.rider.char = "*" THEN
s.rider.Read;
REPEAT Scan(s) UNTIL (s.type = TextMappers.eot) OR (s.type = comEnd);
Scan(s)
END
ELSIF s.char = "*" THEN
IF s.rider.char = ")" THEN s.rider.Read; s.type := comEnd END
END
END
END Scan;
PROCEDURE ResolveImportAlias* (VAR mod: TextMappers.String; t: TextModels.Model);
VAR s: TextMappers.Scanner;
BEGIN
s.ConnectTo(t); s.SetPos(0); Scan(s);
IF s.type = module THEN
Scan(s);
WHILE (s.type # TextMappers.eot) & (s.type # import) DO Scan(s) END;
WHILE (s.type # TextMappers.eot) & (s.type # semicolon)
& ((s.type # TextMappers.string) OR (s.string # mod)) DO Scan(s) END;
IF s.type = TextMappers.string THEN
Scan(s);
IF s.type = becomes THEN
Scan(s);
IF s.type = TextMappers.string THEN
mod := s.string$
END
END
END
END
END ResolveImportAlias;
PROCEDURE Show* (category: Files.Name);
VAR c: TextControllers.Controller; s: TextMappers.Scanner; beg, end: INTEGER;
module, ident: TextMappers.String;
BEGIN
c := TextControllers.Focus();
IF c # NIL THEN
IF c.HasSelection() THEN
c.GetSelection(beg, end);
s.ConnectTo(c.text); s.SetOpts({7}); (* acceptUnderscores *)
s.SetPos(beg); s.Scan;
IF s.type = TextMappers.string THEN
module := s.string; ident := "";
ResolveImportAlias(module, c.text);
s.Scan;
IF (s.type = TextMappers.char) & (s.char = ".") THEN
s.Scan;
IF s.type = TextMappers.string THEN ident := s.string END
END;
ShowText(module, ident, category)
ELSE Dialog.ShowMsg("#System:WrongSelection")
END
ELSE Dialog.ShowMsg("#System:NoSelection")
END
ELSE Dialog.ShowMsg("#System:NoFocus")
END
END Show;
PROCEDURE ShowSource*;
BEGIN
Show("Mod")
END ShowSource;
PROCEDURE ShowDocu*;
BEGIN
Show("Docu")
END ShowDocu;
END DevReferences.
| Dev/Mod/References.odc |
MODULE DevSearch;
(**
project = "BlackBox 2.0, diffs vs 1.7.2 are marked by green"
organizations = "Oberon microsystems, BBWFC, OberonCore, BBCP Team"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- 20070307, bh, caseSens handling in Find corrected
- 20150403, center #37, fixing traps with long search patterns in DevSearch
- 20151201, center #88, support for localizable documentation
- 20170309, center #150, improvements in DevSearch
"
issues = "
- ...
"
**)
IMPORT
Kernel, Files, Fonts, Ports, Models, Views, Containers, Dialog, Windows, Strings,
TextModels, TextRulers, TextViews, TextControllers, TextMappers, TextCmds, StdLinks;
CONST
N = 32; T = 10;
maxPat = LEN(TextCmds.find.find);
noMatchFoundKey = "#Dev:NoMatchFound";
locationKey = "#Dev:Location";
countKey = "#Dev:Count";
searchingKey = "#Dev:Searching";
searchForKey = "#Dev:SearchFor";
TYPE
Pattern = ARRAY maxPat OF CHAR;
Text = POINTER TO RECORD
next: Text;
num: INTEGER;
title: Files.Name
END;
VAR
w: TextMappers.Formatter;
ignoreCase*: BOOLEAN;
PROCEDURE Find (t: TextModels.Model; pat: Pattern; title: Files.Name; VAR list: Text; caseSens: BOOLEAN);
VAR r: TextModels.Reader; num: INTEGER; i, j, b, e, n: INTEGER; ch: CHAR; ref: Pattern; l: Text;
BEGIN
n := 0; num := 0;
WHILE pat[n] # 0X DO
IF ~caseSens THEN pat[n] := Strings.Upper(pat[n]) END ;
INC(n)
END;
r := t.NewReader(NIL);
r.SetPos(0); r.ReadChar(ch);
IF ~caseSens THEN ch := Strings.Upper(ch) END ;
WHILE ~r.eot DO
ref[0] := ch; i := 0; j := 0; b := 0; e := 1;
WHILE ~r.eot & (i < n) DO
IF ch = pat[i] THEN
INC(i); j := (j + 1) MOD maxPat
ELSE
i := 0; b := (b + 1) MOD maxPat; j := b
END;
IF j # e THEN ch := ref[j]
ELSE r.ReadChar(ch);
IF ~caseSens THEN ch := Strings.Upper(ch) END ;
ref[j] := ch; e := (e + 1) MOD maxPat
END
END;
IF i = n THEN INC(num) END
END;
IF num > 0 THEN
NEW(l); l.num := num; l.title := title; l.next := list; list := l
END
END Find;
PROCEDURE List (list: Text; pat: Pattern; source, caseSens: BOOLEAN);
VAR a0: TextModels.Attributes; this, t: Text; max: INTEGER;
cmd: ARRAY maxPat + LEN(t.title) + 50 OF CHAR;
BEGIN
IF list = NIL THEN
Dialog.MapString(noMatchFoundKey, cmd);
w.WriteString(cmd)
ELSE
a0 := w.rider.attr;
w.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.italic}));
Dialog.MapString(locationKey, cmd);
w.WriteString(cmd); w.WriteTab;
Dialog.MapString(countKey, cmd);
w.WriteString(cmd); w.WriteLn;
w.rider.SetAttr(a0);
REPEAT
t := list; max := 1; this := NIL;
WHILE t # NIL DO
IF t.num >= max THEN max := t.num; this := t END;
t := t.next
END;
IF this # NIL THEN
w.rider.SetAttr(TextModels.NewStyle(w.rider.attr, {Fonts.underline}));
w.rider.SetAttr(TextModels.NewColor(w.rider.attr, Ports.blue));
IF source THEN
cmd := "StdCmds.OpenDoc('" + this.title + "'); DevSearch.SelectCaseSens('" + pat + "')"
ELSE
IF caseSens THEN
cmd := "StdCmds.OpenBrowser('" + this.title + "', '" + this.title + "'); " +
"DevSearch.SelectCaseSens('" + pat + "')"
ELSE
cmd := "StdCmds.OpenBrowser('" + this.title + "', '" + this.title + "'); " +
"DevSearch.SelectCaseInSens('" + pat + "')"
END
END;
w.WriteView(StdLinks.dir.NewLink(cmd));
w.WriteString(this.title);
w.WriteView(StdLinks.dir.NewLink(""));
w.rider.SetAttr(a0);
w.WriteTab; w.WriteInt(this.num); w.WriteLn;
this.num := 0
END
UNTIL this = NIL
END
END List;
PROCEDURE NewRuler (): TextRulers.Ruler;
CONST mm = Ports.mm;
VAR p: TextRulers.Prop;
BEGIN
NEW(p);
p.valid := {TextRulers.right, TextRulers.tabs, TextRulers.opts};
p.opts.val := {TextRulers.rightFixed}; p.opts.mask := p.opts.val;
p.right := 100 * mm;
p.tabs.len := 1;
p.tabs.tab[0].stop := 70 * mm;
RETURN TextRulers.dir.NewFromProp(p)
END NewRuler;
PROCEDURE ThisText (loc: Files.Locator; VAR name: Files.Name; useLang: BOOLEAN): TextModels.Model;
VAR v: Views.View; m: Models.Model;
BEGIN
IF useLang & (Dialog.language # "") & (Dialog.language # Dialog.defaultLanguage) THEN
v := Views.OldView(loc.This(Dialog.language), name)
ELSE v := NIL
END;
IF v = NIL THEN v := Views.OldView(loc, name) END;
IF v # NIL THEN
m := v.ThisModel();
IF m # NIL THEN
WITH m: TextModels.Model DO RETURN m ELSE END
END
END;
RETURN NIL
END ThisText;
PROCEDURE GetTitle(IN pat: ARRAY OF CHAR; OUT title: Views.Title);
VAR pos: INTEGER; i, j: INTEGER; ch: CHAR;
BEGIN
Dialog.MapString(searchForKey, title);
title := title + ' "'; i := LEN(title$); j := 0; ch := pat[0];
WHILE (ch # 0X) & (i < LEN(title) - 2) DO
IF ch < " " THEN title[i] := " " ELSE title[i] := ch END ; (* replace tabs and line feeds by spaces *)
INC(i); INC(j); ch := pat[j]
END ;
IF ch # 0X THEN title[i - 3] := "."; title[i - 2] := "."; title[i - 1] := "." END ;
title[i] := '"'; title[i + 1] := 0X
END GetTitle;
PROCEDURE Search (source, caseSens: BOOLEAN);
VAR pat: Pattern; t, log: TextModels.Model; v: Views.View;
title: Views.Title; c: Containers.Controller;
files: Files.FileInfo; dirs: Files.LocInfo;
loc: Files.Locator; path, p: Files.Name; list: Text;
BEGIN
(*TextCmds.InitFindDialog; *)
pat := TextCmds.find.find$;
IF pat # "" THEN
Dialog.ShowStatus(searchingKey);
TextCmds.find.find := pat$;
log := TextModels.dir.New();
w.ConnectTo(log); w.SetPos(0);
IF source THEN loc := Files.dir.This("Mod"); path := "Mod"
ELSE loc := Files.dir.This("Docu"); path := "Docu"
END;
files := Files.dir.FileList(loc); list := NIL;
WHILE files # NIL DO
IF files.type = Files.docType THEN
p := path + "/" + files.name;
Find(ThisText(loc, files.name, ~source), pat, p, list, caseSens)
END;
files := files.next
END;
loc := Files.dir.This("");
dirs := Files.dir.LocList(loc);
WHILE dirs # NIL DO
loc := Files.dir.This(dirs.name); path := dirs.name + "/";
IF source THEN loc := loc.This("Mod"); path := path + "Mod"
ELSE loc := loc.This("Docu"); path := path +"Docu"
END;
files := Files.dir.FileList(loc);
WHILE files # NIL DO
IF files.type = Files.docType THEN
p := path + "/" + files.name;
t := ThisText(loc, files.name, ~source);
IF t # NIL THEN
Find(t, pat, p, list, caseSens)
END
END;
files := files.next
END;
dirs := dirs.next
END;
List(list, pat, source, caseSens);
v := TextViews.dir.New(log);
GetTitle(pat, title);
v(TextViews.View).SetDefaults(NewRuler(), TextViews.dir.defAttr);
Views.OpenAux(v, title);
c := v(Containers.View).ThisController();
c.SetOpts(c.opts + {Containers.noCaret});
w.ConnectTo(NIL);
Dialog.ShowStatus("")
END
END Search;
PROCEDURE SearchInSources*;
BEGIN
Search(TRUE, TRUE)
END SearchInSources;
PROCEDURE SearchInDocu* (opts: ARRAY OF CHAR);
VAR caseSens: BOOLEAN;
BEGIN
caseSens := ~ignoreCase;
IF LEN(opts$) > 0 THEN
IF CAP(opts[0]) = 'S' THEN
caseSens := TRUE
ELSIF CAP(opts[0]) = 'I' THEN
caseSens := FALSE
END
END;
Search(FALSE, caseSens)
END SearchInDocu;
PROCEDURE SelectFirst (IN pat: ARRAY OF CHAR; ignoreCase: BOOLEAN);
BEGIN
TextCmds.ResetFindDialog;
TextCmds.find.find := pat$;
TextCmds.find.ignoreCase := ignoreCase;
Dialog.Update(TextCmds.find);
TextCmds.FindFirst("")
END SelectFirst;
PROCEDURE SelectCaseSens* (pat: ARRAY OF CHAR);
BEGIN
SelectFirst(pat, FALSE);
END SelectCaseSens;
PROCEDURE SelectCaseInSens* (pat: ARRAY OF CHAR);
VAR res: INTEGER; cmd: Dialog.String;
BEGIN
SelectFirst(pat, TRUE);
END SelectCaseInSens;
PROCEDURE NextChar (r: TextModels.Reader): CHAR;
VAR ch: CHAR;
BEGIN
REPEAT r.ReadChar(ch) UNTIL (ch > " ") OR r.eot;
RETURN ch
END NextChar;
PROCEDURE CompTexts (ta, tb: TextModels.Model; VAR sa, sb, ea, eb: INTEGER);
VAR da, db, d, i, j, p: INTEGER; t: LONGINT; ra, rb: TextModels.Reader;
cha, chb: CHAR; s: ARRAY N OF CHAR;
BEGIN
ra := ta.NewReader(NIL); ra.SetPos(ea);
rb := tb.NewReader(NIL); rb.SetPos(eb);
REPEAT
cha := NextChar(ra); chb := NextChar(rb)
UNTIL (cha # chb) OR ra.eot OR rb.eot;
IF ra.eot THEN sa := ra.Pos() ELSE sa := ra.Pos() - 1 END;
IF rb.eot THEN sb := rb.Pos() ELSE sb := rb.Pos() - 1 END;
t := Kernel.Time() + T * Kernel.timeResolution;
da := sa + 1; db := sb + 1; d := 1; j := 0;
REPEAT
ea := da;
IF ea < ta.Length() THEN
ra.SetPos(ea); s[0] := NextChar(ra);
da := ra.Pos(); i := 1;
WHILE i < N DO s[i] := NextChar(ra); INC(i) END;
i := 0; rb.SetPos(sb);
REPEAT
eb := rb.Pos(); chb := NextChar(rb);
IF chb = s[0] THEN
p := rb.Pos(); j := 0;
WHILE (j < N) & (chb = s[j]) DO chb := NextChar(rb); INC(j) END;
rb.SetPos(p)
END;
INC(i)
UNTIL (j = N) OR (i = d) OR rb.eot
END;
INC(d);
IF j < N THEN
eb := db;
IF eb < tb.Length() THEN
rb.SetPos(eb); s[0] := NextChar(rb);
db := rb.Pos(); i := 1;
WHILE i < N DO s[i] := NextChar(rb); INC(i) END;
i := 0; ra.SetPos(sa);
REPEAT
ea := ra.Pos(); cha := NextChar(ra);
IF cha = s[0] THEN
p := ra.Pos(); j := 0;
WHILE (j < N) & (cha = s[j]) DO cha := NextChar(ra); INC(j) END;
ra.SetPos(p)
END;
INC(i)
UNTIL (j = N) OR (i = d) OR ra.eot
END
END
UNTIL (j = N) OR (ea >= ta.Length()) & (eb >= tb.Length()) OR (Kernel.Time() > t);
IF j < N THEN ea := ta.Length(); eb := tb.Length() END
END CompTexts;
PROCEDURE Compare*;
VAR wa, wb: Windows.Window; va, vb: Views.View;
ca, cb: Containers.Controller; sa, sb, ea, eb: INTEGER;
BEGIN
wa := Windows.dir.First();
IF wa # NIL THEN
wb := Windows.dir.Next(wa);
IF wb # NIL THEN
va := wa.doc.ThisView();
WITH va: TextViews.View DO
vb := wb.doc.ThisView();
WITH vb: TextViews.View DO
ca := va.ThisController();
WITH ca: TextControllers.Controller DO
cb := vb.ThisController();
WITH cb: TextControllers.Controller DO
ca.GetSelection(sa, ea);
IF (* ea = -1 *) sa = ea THEN ea := MAX(0, ca.CaretPos()) END;
cb.GetSelection(sb, eb);
IF (* eb = -1 *) sb = eb THEN eb := MAX(0, cb.CaretPos()) END;
CompTexts(va.ThisModel(), vb.ThisModel(), sa, sb, ea, eb);
IF ea > sa THEN ca.SetSelection(sa, ea) ELSE ca.SetCaret(sa) END;
IF eb > sb THEN cb.SetSelection(sb, eb) ELSE cb.SetCaret(sb) END;
va.ShowRangeIn(Views.ThisFrame(wa.frame, va), sa, ea);
vb.ShowRangeIn(Views.ThisFrame(wb.frame, vb), sb, eb)
END
END
ELSE
END
ELSE
END
END
END
END Compare;
BEGIN
ignoreCase := TRUE
END DevSearch.
| Dev/Mod/Search.odc |
MODULE DevSelectors;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20120530, Oleg-N-Cher, Fixed error hat occurs when saving a document after copying of a selector.
The error was found by Eugene Temirgaleev.
"
issues = "
- ...
"
**)
IMPORT
Ports, Stores, Models, Views, Controllers, Fonts, Properties, TextModels, TextViews, TextSetters;
CONST
left* = 1; middle* = 2; right* = 3;
minVersion = 0; currentVersion = 0;
changeSelectorsKey = "#Dev:Change Selectors";
TYPE
Selector* = POINTER TO RECORD (Views.View)
position-: INTEGER; (* left, middle, right *)
leftHidden: TextModels.Model; (* valid iff (position = left) *)
rightHidden: TextModels.Model (* valid iff (position = left) *)
END;
Directory* = POINTER TO ABSTRACT RECORD END;
StdDirectory = POINTER TO RECORD (Directory) END;
VAR
dir-, stdDir-: Directory;
PROCEDURE (d: Directory) New* (position: INTEGER): Selector, NEW, ABSTRACT;
PROCEDURE GetFirst (selector: Selector; OUT first: Selector; OUT pos: INTEGER);
VAR c: Models.Context; rd: TextModels.Reader; v: Views.View; nest: INTEGER;
BEGIN
c := selector.context; first := NIL; pos := 0;
WITH c: TextModels.Context DO
IF selector.position = left THEN
first := selector
ELSE
rd := c.ThisModel().NewReader(NIL); rd.SetPos(c.Pos());
nest := 1; pos := 1; rd.ReadPrevView(v);
WHILE (v # NIL) & (nest > 0) DO
WITH v: Selector DO
IF v.position = left THEN DEC(nest);
IF nest = 0 THEN first := v END
ELSIF v.position = right THEN INC(nest)
ELSIF nest = 1 THEN INC(pos)
END
ELSE
END;
rd.ReadPrevView(v)
END
END
ELSE (* selector not embedded in a text *)
END;
ASSERT((first = NIL) OR (first.position = left), 100)
END GetFirst;
PROCEDURE GetNext (rd: TextModels.Reader; OUT next: Selector);
VAR nest: INTEGER; v: Views.View;
BEGIN
nest := 1; next := NIL; rd.ReadView(v);
WHILE v # NIL DO
WITH v: Selector DO
IF v.position = left THEN INC(nest)
ELSIF nest = 1 THEN next := v; RETURN
ELSIF v.position = right THEN DEC(nest)
END
ELSE
END;
rd.ReadView(v)
END
END GetNext;
PROCEDURE CalcSize (f: Selector; OUT w, h: INTEGER);
VAR c: Models.Context; a: TextModels.Attributes; font: Fonts.Font; asc, dsc, fw: INTEGER;
BEGIN
c := f.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr();
font := a.font
ELSE font := Fonts.dir.Default();
END;
font.GetBounds(asc, dsc, fw);
h := asc + dsc; w := 3 * h DIV 4
END CalcSize;
PROCEDURE GetSection (first: Selector; rd: TextModels.Reader; n: INTEGER; OUT name: ARRAY OF CHAR);
VAR i, p0, p1: INTEGER; ch: CHAR; sel: Selector;
BEGIN
sel := first;
IF first.leftHidden.Length() > 0 THEN
rd := first.leftHidden.NewReader(rd); rd.SetPos(0);
REPEAT p0 := rd.Pos(); GetNext(rd, sel); DEC(n) UNTIL (n < 0) OR (sel = NIL);
IF sel = NIL THEN INC(n) END;
p1 := rd.Pos() - 1
END;
IF n >= 0 THEN
rd := first.context(TextModels.Context).ThisModel().NewReader(rd);
rd.SetPos(first.context(TextModels.Context).Pos() + 1);
REPEAT p0 := rd.Pos(); GetNext(rd, sel); DEC(n) UNTIL (n < 0) OR (sel = NIL) OR (sel.position = right);
p1 := rd.Pos() - 1
END;
IF (n >= 0) & (first.rightHidden.Length() > 0) THEN
rd := first.rightHidden.NewReader(rd); rd.SetPos(1);
REPEAT p0 := rd.Pos(); GetNext(rd, sel); DEC(n) UNTIL (n < 0) OR (sel = NIL);
p1 := rd.Pos() - 1;
IF sel = NIL THEN p1 := first.rightHidden.Length() END
END;
IF n < 0 THEN
rd.SetPos(p0); rd.ReadChar(ch); i := 0;
WHILE (ch <= " ") & (rd.Pos() <= p1) DO rd.ReadChar(ch) END;
WHILE (i < LEN(name) - 1) & (rd.Pos() <= p1) & (ch # 0X) DO
IF ch >= " " THEN name[i] := ch; INC(i) END;
rd.ReadChar(ch)
END;
WHILE (i > 0) & (name[i - 1] = " ") DO DEC(i) END;
name[i] := 0X
ELSE
name := 7FX + ""
END
END GetSection;
PROCEDURE ChangeSelector (first: Selector; rd: TextModels.Reader; selection: INTEGER);
VAR pos, p0, len, s: INTEGER; text: TextModels.Model; sel: Selector;
BEGIN
text := rd.Base();
pos := first.context(TextModels.Context).Pos() + 1;
(* expand *)
rd.SetPos(pos);
REPEAT GetNext(rd, sel) UNTIL (sel = NIL) OR (sel.position = right);
IF sel # NIL THEN
len := first.rightHidden.Length();
IF len > 0 THEN text.Insert(rd.Pos() - 1, first.rightHidden, 0, len) END;
len := first.leftHidden.Length();
IF len > 0 THEN text.Insert(pos, first.leftHidden, 0, len) END;
IF selection # 0 THEN (* collapse *)
rd.SetPos(pos); s := 0;
REPEAT GetNext(rd, sel); INC(s) UNTIL (s = selection) OR (sel = NIL) OR (sel.position = right);
IF (sel # NIL) & (sel.position = middle) THEN
first.leftHidden.Insert(0, text, pos, rd.Pos());
rd.SetPos(pos); GetNext(rd, sel);
p0 := rd.Pos() - 1;
WHILE (sel # NIL) & (sel.position # right) DO GetNext(rd, sel) END;
IF sel # NIL THEN
first.rightHidden.Insert(0, text, p0, rd.Pos() - 1)
END
END
END
END;
rd.SetPos(pos)
END ChangeSelector;
PROCEDURE ChangeThis (
text: TextModels.Model; rd, rd1: TextModels.Reader; title: ARRAY OF CHAR; selection: INTEGER
);
VAR v: Views.View; str: ARRAY 256 OF CHAR;
BEGIN
rd := text.NewReader(rd);
rd.SetPos(0); rd.ReadView(v);
WHILE v # NIL DO
WITH v: Selector DO
IF v.position = left THEN
GetSection(v, rd1, 0, str);
IF str = title THEN
ChangeSelector(v, rd, selection)
END;
IF v.leftHidden.Length() > 0 THEN ChangeThis(v.leftHidden, NIL, rd1, title, selection) END;
IF v.rightHidden.Length() > 0 THEN ChangeThis(v.rightHidden, NIL, rd1, title, selection) END
END
ELSE
END;
rd.ReadView(v)
END
END ChangeThis;
PROCEDURE Change* (text: TextModels.Model; title: ARRAY OF CHAR; selection: INTEGER);
VAR rd, rd1: TextModels.Reader; script: Stores.Operation;
BEGIN
rd := text.NewReader(NIL);
rd1 := text.NewReader(NIL);
Models.BeginModification(Models.clean, text);
Models.BeginScript(text, changeSelectorsKey, script);
ChangeThis(text, rd, rd1, title, selection);
Models.EndScript(text, script);
Models.EndModification(Models.clean, text);
END Change;
PROCEDURE ChangeTo* (text: TextModels.Model; title, entry: ARRAY OF CHAR);
VAR rd, rd1: TextModels.Reader; str: ARRAY 256 OF CHAR; v: Views.View; sel: INTEGER;
BEGIN
rd := text.NewReader(NIL);
rd1 := text.NewReader(NIL);
rd.SetPos(0); rd.ReadView(v);
WHILE v # NIL DO
WITH v: Selector DO
IF v.position = left THEN
GetSection(v, rd1, 0, str);
IF title = str THEN
sel := 0;
REPEAT
INC(sel); GetSection(v, rd1, sel, str)
UNTIL (str[0] = 7FX) OR (str = entry);
IF str[0] # 7FX THEN
Change(text, title, sel);
RETURN
END
END
END
ELSE
END;
rd.ReadView(v)
END
END ChangeTo;
PROCEDURE (selector: Selector) HandlePropMsg- (VAR msg: Properties.Message);
VAR c: Models.Context; a: TextModels.Attributes; asc, w: INTEGER;
BEGIN
WITH msg: Properties.SizePref DO CalcSize(selector, msg.w, msg.h)
| msg: Properties.ResizePref DO msg.fixed := TRUE;
| msg: Properties.FocusPref DO msg.hotFocus := TRUE;
| msg: TextSetters.Pref DO c := selector.context;
IF (c # NIL) & (c IS TextModels.Context) THEN
a := c(TextModels.Context).Attr();
a.font.GetBounds(asc, msg.dsc, w)
END
ELSE (*selector.HandlePropMsg^(msg);*)
END
END HandlePropMsg;
PROCEDURE Track (selector: Selector; f: Views.Frame; x, y: INTEGER; buttons: SET; VAR hit: BOOLEAN);
VAR a: TextModels.Attributes; font: Fonts.Font; c: Models.Context;
w, h, asc, dsc, fw: INTEGER; isDown, in, in0: BOOLEAN; modifiers: SET;
BEGIN
c := selector.context; hit := FALSE;
WITH c: TextModels.Context DO
a := c.Attr(); font := a.font;
c.GetSize(w, h); in0 := FALSE;
in := (0 <= x) & (x < w) & (0 <= y) & (y < h);
REPEAT
IF in # in0 THEN
f.MarkRect(0, 0, w, h, Ports.fill, Ports.hilite, FALSE); in0 := in
END;
f.Input(x, y, modifiers, isDown);
in := (0 <= x) & (x < w) & (0 <= y) & (y < h)
UNTIL ~isDown;
IF in0 THEN hit := TRUE;
font.GetBounds(asc, dsc, fw);
f.MarkRect(0, 0, w, asc + dsc, Ports.fill, Ports.hilite, FALSE);
END
ELSE
END
END Track;
PROCEDURE (selector: Selector) HandleCtrlMsg* (
f: Views.Frame; VAR msg: Views.CtrlMessage; VAR focus: Views.View
);
VAR hit: BOOLEAN; sel, pos: INTEGER; text: TextModels.Model; title: ARRAY 256 OF CHAR; first: Selector;
BEGIN
WITH msg: Controllers.TrackMsg DO
IF selector.context IS TextModels.Context THEN
Track(selector, f, msg.x, msg.y, msg.modifiers, hit);
IF hit THEN
text := selector.context(TextModels.Context).ThisModel();
GetFirst(selector, first, pos);
IF first # NIL THEN
GetSection(first, NIL, 0, title);
IF selector.position = middle THEN sel := pos ELSE sel := 0 END;
Change(text, title, sel);
text := selector.context(TextModels.Context).ThisModel();
IF TextViews.FocusText() = text THEN
pos := selector.context(TextModels.Context).Pos();
TextViews.ShowRange(text, pos, pos+1, TRUE)
END
END
END
END
| msg: Controllers.PollCursorMsg DO
msg.cursor := Ports.refCursor;
ELSE
END
END HandleCtrlMsg;
PROCEDURE (selector: Selector) Restore* (f: Views.Frame; l, t, r, b: INTEGER);
VAR w, h, d: INTEGER;
BEGIN
selector.context.GetSize(w, h);
(*
GetFirst(selector, first, pos);
*)
w := w - w MOD f.unit; d := 2 * f.dot;
f.DrawLine(d, d, w - d, d, d, Ports.grey25);
f.DrawLine(d, h - d, w - d, h - d, d, Ports.grey25);
IF selector.position # right THEN f.DrawLine(d, d, d, h - d, d, Ports.grey25) END;
IF selector.position # left THEN f.DrawLine(w - d, d, w - d, h - d, d, Ports.grey25) END
END Restore;
PROCEDURE (selector: Selector) CopyFromSimpleView- (source: Views.View);
BEGIN
(* selector.CopyFrom^(source); *)
WITH source: Selector DO
selector.position := source.position;
IF source.leftHidden # NIL THEN
selector.leftHidden := TextModels.CloneOf(source.leftHidden);
selector.leftHidden.InsertCopy(0, source.leftHidden, 0, source.leftHidden.Length());
Stores.Join(selector, selector.leftHidden)
END;
IF source.rightHidden # NIL THEN
selector.rightHidden := TextModels.CloneOf(source.rightHidden);
selector.rightHidden.InsertCopy(0, source.rightHidden, 0, source.rightHidden.Length());
Stores.Join(selector, selector.rightHidden)
END
END
END CopyFromSimpleView;
PROCEDURE (selector: Selector) InitContext* (context: Models.Context);
BEGIN
selector.InitContext^(context);
IF selector.position = left THEN
WITH context: TextModels.Context DO
IF selector.leftHidden = NIL THEN
selector.leftHidden := TextModels.CloneOf(context.ThisModel());
Stores.Join(selector, selector.leftHidden);
END;
IF selector.rightHidden = NIL THEN
selector.rightHidden := TextModels.CloneOf(context.ThisModel());
Stores.Join(selector, selector.rightHidden)
END
ELSE
END
END
END InitContext;
PROCEDURE (selector: Selector) Internalize- (VAR rd: Stores.Reader);
VAR version: INTEGER; store: Stores.Store;
BEGIN
selector.Internalize^(rd);
IF rd.cancelled THEN RETURN END;
rd.ReadVersion(minVersion, currentVersion, version);
IF rd.cancelled THEN RETURN END;
rd.ReadInt(selector.position);
rd.ReadStore(store);
IF store # NIL THEN selector.leftHidden := store(TextModels.Model)
ELSE selector.leftHidden := NIL
END;
rd.ReadStore(store);
IF store # NIL THEN selector.rightHidden := store(TextModels.Model)
ELSE selector.rightHidden := NIL
END
END Internalize;
PROCEDURE (selector: Selector) Externalize- (VAR wr: Stores.Writer);
BEGIN
selector.Externalize^(wr);
wr.WriteVersion(currentVersion);
wr.WriteInt(selector.position);
wr.WriteStore(selector.leftHidden);
wr.WriteStore(selector.rightHidden)
END Externalize;
PROCEDURE (d: StdDirectory) New (position: INTEGER): Selector;
VAR selector: Selector;
BEGIN
NEW(selector);
selector.position := position;
RETURN selector
END New;
PROCEDURE SetDir* (d: Directory);
BEGIN
ASSERT(d # NIL, 20);
dir := d
END SetDir;
PROCEDURE DepositLeft*;
BEGIN
Views.Deposit(dir.New(left))
END DepositLeft;
PROCEDURE DepositMiddle*;
BEGIN
Views.Deposit(dir.New(middle))
END DepositMiddle;
PROCEDURE DepositRight*;
BEGIN
Views.Deposit(dir.New(right))
END DepositRight;
PROCEDURE InitMod;
VAR d: StdDirectory;
BEGIN
NEW(d); dir := d; stdDir := d;
END InitMod;
BEGIN
InitMod
END DevSelectors. | Dev/Mod/Selectors.odc |
MODULE DevSubTool;
(**
project = "BlackBox"
organization = "www.oberon.ch"
contributors = "Oberon microsystems"
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "Docu/BB-License"
changes = "
- 20141027, center #19, full Unicode support for Component Pascal identifiers added
- 20150226, center #29, finconsistent checks for valid subsystem names
"
issues = "
- ...
"
**)
IMPORT Strings, Files, Fonts, Views, TextModels, TextMappers, TextViews,
StdCmds, Dialog, DevCommanders;
CONST
textCmds* = 0; formCmds* = 1; otherCmds = 2;
noModelView* = 3; modelView* = 4; complexView* = 5;
wrapper = 6; specialContainer = 7; generalContainer = 8;
VAR
create*: RECORD
subsystem*: ARRAY 16 OF CHAR;
kind*: INTEGER;
Create*: PROCEDURE
END;
PROCEDURE TranslateText (t: TextModels.Model; s: ARRAY OF CHAR);
VAR r: TextModels.Reader; w: TextModels.Writer; from, to: INTEGER; i: INTEGER; ch: CHAR;
BEGIN
r := t.NewReader(NIL); w := t.NewWriter(NIL);
r.ReadChar(ch);
WHILE ~r.eot DO
WHILE ~r.eot & ~(Fonts.strikeout IN r.attr.font.style) DO
r.ReadChar(ch);
END;
IF ~r.eot THEN
from := r.Pos() - 1;
WHILE ~r.eot & (Fonts.strikeout IN r.attr.font.style) DO
r.ReadChar(ch);
END;
IF ~r.eot THEN
to := r.Pos() - 1;
t.Delete(from, to);
w.SetPos(from);
w.SetAttr(TextModels.NewStyle(r.attr, r.attr.font.style - {Fonts.strikeout}));
i := 0; ch := s[0]; WHILE ch # 0X DO w.WriteChar(ch); INC(i); INC(from); ch := s[i] END;
r.SetPos(from); r.ReadChar(ch);
END
END
END
END TranslateText;
PROCEDURE TranslateFile (floc: Files.Locator; fname: Files.Name; tloc: Files.Locator; tname: Files.Name;
string: ARRAY OF CHAR; VAR res: INTEGER);
VAR v: Views.View;
BEGIN
v := Views.OldView(floc, fname);
IF v # NIL THEN
IF v IS TextViews.View THEN
TranslateText(v(TextViews.View).ThisModel(), string);
tloc.res := 76; (* don't ask whether directory should be created *)
Views.RegisterView(v, tloc, tname);
res := tloc.res
ELSE res := 101
END
ELSE res := 100
END
END TranslateFile;
PROCEDURE TranslateSubsystem (kind: INTEGER; string: ARRAY OF CHAR);
VAR loc, new: Files.Locator; t: TextModels.Model; res: INTEGER; f: TextMappers.Formatter;
v: Views.View;
PROCEDURE Message (sub, dir, old: ARRAY OF CHAR);
VAR dummy: INTEGER;
BEGIN
IF res = 0 THEN
f.WriteString(sub); f.WriteString(dir); f.WriteLn
ELSE
Dialog.GetOK("#Dev:CannotTranslate", old, "", "", {Dialog.ok}, dummy)
END
END Message;
BEGIN
t := TextModels.dir.New(); f.ConnectTo(t);
loc := Files.dir.This("Dev"); loc := loc.This("Rsrc"); loc := loc.This("New");
new := Files.dir.This(string); new := new.This("Mod");
IF kind = textCmds THEN
TranslateFile(loc, "Cmds0", new, "Cmds", string, res);
Message(string, "Cmds", "Cmds0")
ELSIF kind = formCmds THEN
TranslateFile(loc, "Cmds1", new, "Cmds", string, res);
Message(string, "Cmds", "Cmds1")
ELSIF kind = otherCmds THEN
TranslateFile(loc, "Cmds2", new, "Cmds", string, res);
Message(string, "Cmds", "Cmds2")
ELSIF kind = noModelView THEN
TranslateFile(loc, "Views3", new, "Views", string, res);
Message(string, "Views", "Views3");
f.WriteLn;
f.WriteView(DevCommanders.dir.New());
f.WriteString(' "'); f.WriteString(string); f.WriteString('Views.Deposit; StdCmds.Open"'); f.WriteLn
ELSIF kind = modelView THEN
TranslateFile(loc, "Views4", new, "Views", string, res);
Message(string, "Views", "Views4");
f.WriteLn;
f.WriteView(DevCommanders.dir.New());
f.WriteString(' "'); f.WriteString(string); f.WriteString('Views.Deposit; StdCmds.Open"'); f.WriteLn
ELSIF kind = complexView THEN
TranslateFile(loc, "Models5", new, "Models", string, res);
Message(string, "Models", "Models5");
TranslateFile(loc, "Views5", new, "Views", string, res);
Message(string, "Views", "Views5");
TranslateFile(loc, "Cmds5", new, "Cmds", string, res);
Message(string, "Cmds", "Cmds5");
f.WriteLn;
f.WriteView(DevCommanders.dir.New());
f.WriteString(' "'); f.WriteString(string); f.WriteString('Views.Deposit; StdCmds.Open"'); f.WriteLn
ELSIF kind = wrapper THEN
TranslateFile(loc, "Views6", new, "Views", string, res);
Message(string, "Views", "Views6");
f.WriteLn;
f.WriteView(DevCommanders.dir.New());
f.WriteString(' "'); f.WriteString(string); f.WriteString('Views.Deposit; StdCmds.Open"'); f.WriteLn
ELSIF kind = specialContainer THEN
TranslateFile(loc, "Views7", new, "Views", string, res);
Message(string, "Views", "Views7");
f.WriteLn;
f.WriteView(DevCommanders.dir.New());
f.WriteString(' "'); f.WriteString(string); f.WriteString('Views.Deposit; StdCmds.Open"'); f.WriteLn
ELSIF kind = generalContainer THEN
TranslateFile(loc, "Models8", new, "Models", string, res);
Message(string, "Models", "Models8");
TranslateFile(loc, "Views8", new, "Views", string, res);
Message(string, "Views", "Views8");
TranslateFile(loc, "Controllers8", new, "Controllers", string, res);
Message(string, "Controllers", "Controllers8");
TranslateFile(loc, "Cmds8", new, "Cmds", string, res);
Message(string, "Cmds", "Cmds8");
f.WriteLn;
f.WriteView(DevCommanders.dir.New());
f.WriteString(' "'); f.WriteString(string); f.WriteString('Views.Deposit; StdCmds.Open"'); f.WriteLn
ELSE HALT(20)
END;
v := TextViews.dir.New(t);
Views.Open(v, new, "List", NIL);
IF t.Length() > 0 THEN Views.RegisterView(v, new, "List") END
END TranslateSubsystem;
PROCEDURE SyntaxOK(IN s: ARRAY OF CHAR): BOOLEAN;
VAR i: INTEGER; ch: CHAR;
BEGIN
i := 0; ch := s[0];
IF ~Strings.IsIdentStart(ch) THEN RETURN FALSE END ;
WHILE Strings.IsUpper(ch) DO INC(i); ch := s[i] END ;
IF ch = 0X THEN RETURN FALSE END ;
WHILE Strings.IsIdent(ch) & ~Strings.IsUpper(ch) DO INC(i); ch := s[i] END ;
RETURN ch = 0X
END SyntaxOK;
PROCEDURE Create;
VAR res: INTEGER;
BEGIN
IF (LEN(create.subsystem$) < 3) THEN
Dialog.GetOK("#Dev:PrefixTooShort", "", "", "", {Dialog.ok, Dialog.cancel}, res);
IF res = Dialog.cancel THEN RETURN END
END ;
IF ~Strings.IsUpper(create.subsystem[0]) THEN
Dialog.GetOK("#Dev:NotUppercase", "", "", "", {Dialog.ok, Dialog.cancel}, res);
IF res = Dialog.cancel THEN RETURN END
END ;
IF (create.kind >= textCmds) & (create.kind <= generalContainer) THEN
IF SyntaxOK(create.subsystem) THEN
StdCmds.CloseDialog;
TranslateSubsystem(create.kind, create.subsystem);
create.subsystem := ""
ELSE Dialog.GetOK("#Dev:IllegalSyntax", "", "", "", {Dialog.ok}, res)
END
ELSE Dialog.GetOK("#Dev:IllegalKind", "", "", "", {Dialog.ok}, res)
END
END Create;
BEGIN
create.Create := Create; create.kind := textCmds
END DevSubTool. | Dev/Mod/SubTool.odc |
Dev/Rsrc/Analyzer.odc |
|
Dev/Rsrc/Browser.odc |
|
Dev/Rsrc/Create.odc |
|
List of Oberon Error Numbers
Oberon microsystems 28. 2. 2003
1. Incorrect use of language Oberon
0 undeclared identifier
1 multiply defined identifier
2 illegal character in number
3 illegal character in string
4 identifier does not match procedure name
5 comment not closed
6
7
8
9 "=" expected
10
11
12 type definition starts with incorrect symbol
13 factor starts with incorrect symbol
14 statement starts with incorrect symbol
15 declaration followed by incorrect symbol
16 MODULE expected
17
18
19 "." missing
20 "," missing
21 ":" missing
22
23 ")" missing
24 "]" missing
25 "}" missing
26 OF missing
27 THEN missing
28 DO missing
29 TO missing
30
31
32
33
34
35 "," or OF expected
36 CONST, TYPE, VAR, PROCEDURE, BEGIN, or END missing
37 PROCEDURE, BEGIN, or END missing
38 BEGIN or END missing
39
40 "(" missing
41 illegally marked identifier
42 constant not an integer
43 UNTIL missing
44 ":=" missing
45
46 EXIT not within loop statement
47 string expected
48 identifier expected
49 ";" missing
50 expression should be constant
51 END missing
52 identifier does not denote a type
53 identifier does not denote a record type
54 result type of procedure is not a basic type
55 procedure call of a function
56 assignment to non-variable
57 pointer not bound to record or array type
58 recursive type definition
59 illegal open array parameter
60 wrong type of case label
61 inadmissible type of case label
62 case label defined more than once
63 illegal value of constant
64 more actual than formal parameters
65 fewer actual than formal parameters
66 element types of actual array and formal open array differ
67 actual parameter corresponding to open array is not an array
68 control variable must be integer
69 parameter must be an integer constant
70 pointer or VAR / IN record required as formal receiver
71 pointer expected as actual receiver
72 procedure must be bound to a record of the same scope
73 procedure must have level 0
74 procedure unknown in base type
75 invalid call of base procedure
76 this variable (field) is read only
77 object is not a record
78 dereferenced object is not a variable
79 indexed object is not a variable
80 index expression is not an integer
81 index out of specified bounds
82 indexed variable is not an array
83 undefined record field
84 dereferenced variable is not a pointer
85 guard or test type is not an extension of variable type
86 guard or testtype is not a pointer
87 guarded or tested variable is neither a pointer nor a VAR- or IN-parameter record
88 open array not allowed as variable, record field or array element
89 ANYRECORD may not be allocated
90 dereferenced variable is not a character array
91
92 operand of IN not an integer, or not a set
93 set element type is not an integer
94 operand of & is not of type BOOLEAN
95 operand of OR is not of type BOOLEAN
96 operand not applicable to (unary) +
97 operand not applicable to (unary) -
98 operand of ~ is not of type BOOLEAN
99 ASSERT fault
100 incompatible operands of dyadic operator
101 operand type inapplicable to *
102 operand type inapplicable to /
103 operand type inapplicable to DIV
104 operand type inapplicable to MOD
105 operand type inapplicable to +
106 operand type inapplicable to -
107 operand type inapplicable to = or #
108 operand type inapplicable to relation
109 overriding method must be exported
110 operand is not a type
111 operand inapplicable to (this) function
112 operand is not a variable
113 incompatible assignment
114 string too long to be assigned
115 parameter does not match
116 number of parameters does not match
117 result type does not match
118 export mark does not match with forward declaration
119 redefinition textually precedes procedure bound to base type
120 type of expression following IF, WHILE, UNTIL or ASSERT is not BOOLEAN
121 called object is not a procedure
122 actual VAR-, IN-, or OUT-parameter is not a variable
123 type is not identical with that of formal VAR-, IN-, or OUT-parameter
124 type of result expression differs from that of procedure
125 type of case expression is neither INTEGER nor CHAR
126 this expression cannot be a type or a procedure
127 illegal use of object
128 unsatisfied forward reference
129 unsatisfied forward procedure
130 WITH clause does not specify a variable
131 LEN not applied to array
132 dimension in LEN too large or negative
133 function without RETURN
135 SYSTEM not imported
136 LEN applied to untagged array
137 unknown array length
138 NEW not allowed for untagged structures
139 Test applied to untagged record
140 untagged receiver
141 SYSTEM.NEW not implemented
142 tagged structures not allowed for NIL compatible var parameters
143 tagged pointer not allowed in untagged structure
144 no pointers allowed in BYTES argument
145 untagged open array not allowed as value parameter
150 key inconsistency of imported module
151 incorrect symbol file
152 symbol file of imported module not found
153 object or symbol file not opened (disk full?)
154 recursive import not allowed
155 generation of new symbol file not allowed
160 interfaces must be extensions of IUnknown
161 interfaces must not have fields
162 interface procedures must be abstract
163 interface records must be abstract
164 pointer must be extension of queried interface type
165 illegal guid constant
166 AddRef & Release may not be used
167 illegal assignment to [new] parameter
168 wrong [iid] - [new] pair
169 must be an interface pointer
177 IN only allowed for records and arrays
178 illegal attribute
179 abstract methods of exported records must be exported
180 illegal receiver type
181 base type is not extensible
182 base procedure is not extensible
183 non-matching export
184 Attribute does not match with forward declaration
185 missing NEW attribute
186 illegal NEW attribute
187 new empty procedure in non extensible record
188 extensible procedure in non extensible record
189 illegal attribute change
190 record must be abstract
191 base type must be abstract
192 unimplemented abstract procedures in base types
193 abstract or limited records may not be allocated
194 no supercall allowed to abstract or empty procedures
195 empty procedures may not have out parameters or return a value
196 procedure is implement-only exported
197 extension of limited type must be limited
198 obsolete oberon type
199 obsolete oberon function
2. Limitations of implementation
200 not yet implemented
201 lower bound of set range greater than higher bound
202 set element greater than MAX(SET) or less than 0
203 number too large
204 product too large
205 division by zero
206 sum too large
207 difference too large
208 overflow in arithmetic shift
209 case range too large
210 code too long
211 jump distance too large
212 illegal real operation
213 too many cases in case statement
214 structure too large
215 not enough registers: simplify expression
216 not enough floating-point registers: simplify expression
217 unimplemented SYSTEM function
218 illegal value of parameter (0 <= p < 128)
219 illegal value of parameter (0 <= p < 16)
220 illegal value of parameter
221 too many pointers in a record
222 too many global pointers
223 too many record types
224 too many pointer types
225 illegal sys flag
226 too many exported procedures
227 too many imported modules
228 too many exported structures
229 too many nested records for import
230 too many constants (strings) in module
231 too many link table entries (external procedures)
232 too many commands in module
233 record extension hierarchy too high
235 too many modifiers
240 identifier too long
241 string too long
242 too many meta names
243 too many imported variables
249 inconsistent import
250 code proc must not be exported
251 too many nested function calls
254 debug position not found
255 debug position
260 illegal LONGINT operation
261 unsupported mode or size of second argument of SYSTEM.VAL
265 unsupported string operation
270 interface pointer reference counting restriction violated
3. Warnings
301 implicit type cast
302 guarded variable can be side-effected
303 open array (or pointer to array) containing pointers
3.5 Analyzer Warnings
900 never used
901 never set
902 used before set
903 set but never used
904 used as varpar, possibly not set
905 also declared in outer scope
906 access/assignment to intermediate
907 redefinition
908 new definition
909 statement after RETURN/EXIT
910 for loop variable set
911 implied type guard
912 superfluous type guard
913 call might depend on evaluation sequence of params.
930 superfluous semicolon
4.0 Bytecode Errors
401 bytecode restriction: no structured assignment
402 bytecode restriction: no procedure types
403 bytecode restriction: no nested procedures
404 bytecode restriction: illegal SYSTEM function
410 variable may not have been assigned
411 no proofable return
412 illegal constructor call
413 missing constructor call
| Dev/Rsrc/Errors.odc |
Dev/Rsrc/HeapSpy.odc |
|
Dev/Rsrc/Inspect.odc |
|
Dev/Rsrc/LinkChk.odc |
|
MENU "#Dev:&Info"
"#Dev:&Open Log" "" "StdLog.Open" ""
"#Dev:&Clear Log" "" "StdLog.Clear" ""
SEPARATOR
"#Dev:&Loaded Modules" "" "DevDebug.ShowLoadedModules" ""
"#Dev:&Global Variables" "" "DevDebug.ShowGlobalVariables" "TextCmds.SelectionGuard"
"#Dev:&View State" "" "DevDebug.ShowViewState" "StdCmds.SingletonGuard"
"#Dev:&About Alien" "" "DevAlienTool.Analyze" "StdCmds.SingletonGuard"
"#Dev:&Heap Spy..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/HeapSpy', '#Dev:Heap Spy')" ""
"#Dev:&Message Spy..." "" "DevMsgSpy.OpenDialog('Dev/Rsrc/MsgSpy', '#Dev:Message Spy')" ""
"#Dev:&Control List" "" "DevCmds.ShowControlList" "StdCmds.ContainerGuard"
SEPARATOR
"#Dev:&Source" "" "DevReferences.ShowSource" "TextCmds.SelectionGuard"
"#Dev:&Client Interface" "D" "DevBrowser.ShowInterface('@c')" "TextCmds.SelectionGuard"
"#Dev:&Extension Interface" "*D" "DevBrowser.ShowInterface('@e')" "TextCmds.SelectionGuard"
"#Dev:&Interface..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/Browser', '#Dev:Browser')" ""
"#Dev:&Documentation" "" "DevReferences.ShowDocu" "TextCmds.SelectionGuard"
"#Dev:&Dependencies" "" "DevDependencies.Deposit;StdCmds.Open" "TextCmds.SelectionGuard"
"#Dev:&Create Tool" "" "DevDependencies.CreateTool" "TextCmds.SelectionGuard"
"#Dev:&Repository" "" "DevRBrowser.ShowRepository" ""
SEPARATOR
"#Dev:&Search In Sources" "" "TextCmds.InitFindDialog; DevSearch.SearchInSources" "TextCmds.SelectionGuard"
"#Dev:&Search In Docu (Case Sensitive)" "" "TextCmds.InitFindDialog; DevSearch.SearchInDocu('s')" "TextCmds.SelectionGuard"
"#Dev:&Search In Docu (Case Insensitive)" "" "TextCmds.InitFindDialog; DevSearch.SearchInDocu('i')" "TextCmds.SelectionGuard"
"#Dev:&Compare Texts" "F9" "DevSearch.Compare" "TextCmds.FocusGuard"
"#Dev:&Check Links..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/LinkChk', '#Dev:Check Links')" ""
"#Dev:&Analyzer Options..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/Analyzer', '#Dev:Analyzer')" ""
"#Dev:&Analyze Module" "" "DevAnalyzer.Analyze" "TextCmds.FocusGuard"
SEPARATOR
"#Dev:&Menus" "" "StdMenuTool.ListAllMenus" ""
"#Dev:&Update Menus" "" "StdMenuTool.UpdateAllMenus" ""
END
MENU "#Dev:&Dev"
"#Dev:&Edit Mode" "" "StdCmds.SetEditMode" "StdCmds.SetEditModeGuard"
"#Dev:&Layout Mode" "" "StdCmds.SetLayoutMode" "StdCmds.SetLayoutModeGuard"
"#Dev:&Browser Mode" "" "StdCmds.SetBrowserMode" "StdCmds.SetBrowserModeGuard"
"#Dev:&Mask Mode" "" "StdCmds.SetMaskMode" "StdCmds.SetMaskModeGuard"
SEPARATOR
"#Dev:&Open Module List" "0" "DevCmds.OpenModuleList" "TextCmds.SelectionGuard"
"#Dev:&Open File List" "" "DevCmds.OpenFileList" "TextCmds.SelectionGuard"
SEPARATOR
"#Dev:&Compile" "K" "DevCompiler.Compile" "TextCmds.FocusGuard"
"#Dev:&Compile And Unload" "" "DevCompiler.CompileAndUnload" "TextCmds.FocusGuard"
"#Dev:&Compile Selection" "" "DevCompiler.CompileSelection" "TextCmds.SelectionGuard"
"#Dev:&Compile Module List" "" "DevCompiler.CompileModuleList" "TextCmds.SelectionGuard"
SEPARATOR
"#Dev:&Unmark Errors" "" "DevMarkers.UnmarkErrors" "TextCmds.FocusGuard"
"#Dev:&Next Error" "E" "DevMarkers.NextError" "TextCmds.FocusGuard"
"#Dev:&Toggle Error Mark" "T" "DevMarkers.ToggleCurrent" "TextCmds.FocusGuard"
SEPARATOR
"#Dev:&Execute" "" "DevDebug.Execute" "TextCmds.SelectionGuard"
"#Dev:&Unload" "" "DevDebug.Unload" "TextCmds.FocusGuard"
"#Dev:&Unload Module List" "" "DevDebug.UnloadModuleList" "TextCmds.SelectionGuard"
"#Dev:&Flush Resources" "" "DevCmds.FlushResources" ""
"#Dev:&Revalidate View" "" "DevCmds.RevalidateView" "DevCmds.RevalidateViewGuard"
SEPARATOR
"#Dev:&Set Profile List" "" "DevProfiler.SetProfileList" "DevProfiler.StartGuard"
"#Dev:&Start Profiler" "" "DevProfiler.Start" "DevProfiler.StartGuard"
"#Dev:&Stop Profiler" "" "DevProfiler.Stop; DevProfiler.ShowProfile" "DevProfiler.StopGuard"
"#Dev:&Timed Execute" "" "DevProfiler.Execute" "TextCmds.SelectionGuard"
SEPARATOR
"#Dev:&Debug Command" "" "DevDebugCmds.DebugCommand" "TextCmds.SelectionGuard"
"#Dev:&Debug Module" "" "DevDebugCmds.DebugModule" "TextCmds.SelectionGuard"
END
MENU "#Dev:&Tools"
"#Dev:&Document Size..." "" "StdCmds.InitLayoutDialog; StdCmds.OpenToolDialog('Std/Rsrc/Cmds1', '#Dev:Document Size')"
"StdCmds.WindowGuard"
"#Dev:&View Size..." "" "StdViewSizer.InitDialog;StdCmds.OpenToolDialog('Std/Rsrc/ViewSizer', '#Dev:View Size')"
"StdCmds.SingletonGuard"
SEPARATOR
"#Dev:&Insert Commander" "Q" "DevCommanders.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Stamp" "" "StdStamps.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Clock" "" "StdClocks.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Header" "" "StdHeaders.Deposit; StdCmds.PasteView; TextCmds.ShowMarks" "TextCmds.FocusGuard"
"#Dev:Insert &Figure" "" "FigCmds.Deposit; StdCmds.PasteView" "TextCmds.FocusGuard"
SEPARATOR
"#Dev:&Add Scroller" "" "StdScrollers.AddScroller" "StdCmds.SingletonGuard"
"#Dev:&Remove Scroller" "" "StdScrollers.RemoveScroller" "StdCmds.SingletonGuard"
SEPARATOR
"#Dev:&Create Link" "L" "StdLinks.CreateLink" "StdLinks.CreateGuard"
"#Dev:&Create Target" "" "StdLinks.CreateTarget" "StdLinks.CreateGuard"
SEPARATOR
"#Dev:&Create Fold" "" "StdFolds.Create(1)" "StdFolds.CreateGuard"
"#Dev:&Expand All" "" "StdFolds.Expand" "TextCmds.FocusGuard"
"#Dev:&Collapse All" "" "StdFolds.Collapse" "TextCmds.FocusGuard"
"#Dev:&Fold..." "" "StdCmds.OpenToolDialog('Std/Rsrc/Folds', '#Dev:Zoom')" ""
SEPARATOR
"#Dev:&Encode Document" "" "StdCoder.EncodeDocument" "StdCmds.WindowGuard"
"#Dev:&Encode Selection" "" "StdCoder.EncodeSelection" "TextCmds.SelectionGuard"
"#Dev:&Encode File..." "" "StdCoder.EncodeFile" ""
"#Dev:&Encode File List" "" "StdCoder.EncodeFileList" "TextCmds.SelectionGuard"
"#Dev:&Decode" "" "StdCoder.Decode" "TextCmds.FocusGuard"
"#Dev:&About Encoded Material" "" "StdCoder.ListEncodedMaterial" "TextCmds.FocusGuard"
SEPARATOR
"#Dev:&Create Subsystem..." "" "StdCmds.OpenToolDialog('Dev/Rsrc/Create', '#Dev:Create Subsystem')" ""
END
MENU "#Dev:&Controls"
"#Dev:&New Form..." "" "StdCmds.OpenToolDialog('Form/Rsrc/Gen', '#Dev:New Form')" ""
"#Dev:&Open As Tool Dialog" "" "StdCmds.OpenAsToolDialog" "StdCmds.ContainerGuard"
"#Dev:&Open As Aux Dialog" "" "StdCmds.OpenAsAuxDialog" "StdCmds.ContainerGuard"
SEPARATOR
"#Dev:&Insert Tab View" "" "StdTabViews.Deposit; StdCmds.PasteView" "StdCmds.PasteViewGuard"
SEPARATOR
"#Dev:&Insert Command Button" "" "Controls.DepositPushButton; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Check Box" "" "Controls.DepositCheckBox; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Radio Button" "" "Controls.DepositRadioButton; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Edit Field" "" "Controls.DepositField; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert List Box" "" "Controls.DepositListBox; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Selection Box" "" "Controls.DepositSelectionBox; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Combo Box" "" "Controls.DepositComboBox; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Up/Down Field" "" "Controls.DepositUpDownField; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Time Field" "" "Controls.DepositTimeField; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Date Field" "" "Controls.DepositDateField; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Color Field" "" "Controls.DepositColorField; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Tree Control" "" "Controls.DepositTreeControl; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Table Control" "" "StdTables.DepositControl; StdCmds.PasteView" "StdCmds.PasteViewGuard"
SEPARATOR
"#Dev:&Insert Cancel Button" "" "Controls.DepositCancelButton; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Caption" "" "Controls.DepositCaption; StdCmds.PasteView" "StdCmds.PasteViewGuard"
"#Dev:&Insert Group Box" "" "Controls.DepositGroup; FormCmds.InsertAround; FormCmds.SetAsFirst" "StdCmds.PasteViewGuard"
END
MENU "*" ("DevDependencies.View")
"#Dev:&Expand" "" "DevDependencies.ExpandClick" "DevDependencies.SubsGuard"
"#Dev:&Collapse" "" "DevDependencies.CollapseClick" "DevDependencies.ModsGuard"
"#Dev:&New Analysis" "" "DevDependencies.NewAnalysisClick" "DevDependencies.ModsGuard"
"#Dev:&Hide" "" "DevDependencies.HideClick" "DevDependencies.SelGuard"
SEPARATOR
"#Dev:&Show All Items" "" "DevDependencies.ShowAllClick" ""
"#Dev:&Show Basic System" "" "DevDependencies.ToggleBasicSystemsClick" "DevDependencies.ShowBasicGuard"
"#Dev:&Expand All" "" "DevDependencies.ExpandAllClick" ""
"#Dev:&Collapse All" "" "DevDependencies.CollapseAllClick" ""
"#Dev:&Arrange Items" "" "DevDependencies.ArrangeClick" ""
SEPARATOR
"#Dev:&Create tool..." "" "DevDependencies.CreateToolClick" ""
SEPARATOR
"#Dev:&Properties..." "" "StdCmds.ShowProp" "StdCmds.ShowPropGuard"
END | Dev/Rsrc/Menus.odc |
Dev/Rsrc/MsgSpy.odc |
|
Dev/Rsrc/RTDebug.odc |
|
STRINGS
&Info &Info
&Open Log &Open Log
&Clear Log &Clear Log
&Loaded Modules &Loaded Modules
&Global Variables &Global Variables
&View State &View State
&About Alien About &Alien
&Heap Spy... &Heap Spy...
&Message Spy... Message Spy...
&Control List Control List
&Source &Source
&Client Interface Client Interface
&Extension Interface Extension Interface
&Interface... &Interface...
&Documentation &Documentation
&Dependencies De&pendencies
&Create Tool Create Tool
&Repository &Repository
&Search In Sources Search In Sources
&Search In Docu (Case Sensitive) Search In Docu (Case Sensitive)
&Search In Docu (Case Insensitive) Search In Docu (Case Insensitive)
&Compare Texts Compare Texts
&Check Links... Check Links...
&Analyzer Options... Analyzer Options...
&Analyze Module Analyze Module
&Menus &Menus
&Update Menus &Update Menus
&Dev &Dev
&Edit Mode &Edit Mode
&Layout Mode &Layout Mode
&Browser Mode &Browser Mode
&Mask Mode &Mask Mode
&Open Module List &Open Module List
&Open File List Open &File List
&Compile &Compile
&Compile And Unload Compile And Unload
&Compile Selection Compile &Selection
&Compile Module List Com&pile Module List
&Unmark Errors Unmar&k Errors
&Next Error Next E&rror
&Toggle Error Mark To&ggle Error Mark
&Execute E&xecute
&Unload &Unload
&Unload Module List Unloa&d Module List
&Flush Resources Flus&h Resources
&Revalidate View Re&validate View
&Set Profile List Set Profile List
&Start Profiler Start Profiler
&Stop Profiler Stop Profiler
&Timed Execute Timed Execute
&Debug Command Debug Command
&Debug Module Debug Module
&Tools &Tools
&Document Size... Document Size...
&View Size... View Size...
&Insert Commander Insert Co&mmander
&Insert Stamp Insert &Stamp
&Insert Clock Insert Cloc&k
&Insert Header Insert &Header
&Add Scroller &Add Scroller
&Remove Scroller &Remove Scroller
&Create Link Create &Link
&Create Target Create &Target
&Create Fold Create Fold
&Expand All Expand All
&Collapse All Collapse All
&Fold... Fold...
&Encode Document Encode Document
&Encode Selection Encode Selection
&Encode File... Encode File...
&Encode File List Encode File List
&Decode Decode
&About Encoded Material About Encoded Material
&Create Subsystem... Create Subsystem...
&Controls &Controls
&New Form... &New Form...
&Open As Tool Dialog Open As &Tool Dialog
&Open As Aux Dialog Open As &Aux Dialog
&Insert Tab View Insert Tab &View
&Insert Command Button Insert Co&mmand Button
&Insert Check Box Insert Chec&k Box
&Insert Radio Button Insert &Radio Button
&Insert Edit Field Insert &Edit Field
&Insert List Box Insert &List Box
&Insert Selection Box Insert &Selection Box
&Insert Combo Box Insert Com&bo Box
&Insert Up/Down Field Insert &Up/Down Field
&Insert Time Field Insert &Time Field
&Insert Date Field Insert &Date Field
&Insert Color Field Insert C&olor Field
&Insert Tree Control Insert Tree Control
&Insert Table Control Insert Table Control
&Insert Cancel Button Insert &Cancel Button
&Insert Caption Insert Captio&n
&Insert Group Box Insert &Group Box
&Expand Expand
&Collapse Collapse
&New Analysis New Analysis
&Hide Hide
&Show All Items Show All Items
&Show Basic System Show Basic System
&Arrange Items Arrange Items
&Create tool... Create tool...
&Properties... P&roperties...
Add MsgSpy Add MsgSpy
All subsystems &All subsystems
Allocated: Allocated:
Analyze Analyze
Analyzer Analyzer
Apply Appl&y
Browse... Browse...
Browse Type Library Browse Type Library
Browser Browser
Cancel Cancel
Check Links Check Links
Clear List Clear List
Clear Log Clear Log
Close &Close
Clusters: Clusters:
Command Package (Form) Command Package (Form)
Command Package (Text) Command Package (Text)
Control: Control:
Create Create
Create Subsystem Create Subsystem
Document Size Document Size
Exported Items Exported Items
File Name: File Name:
Flat Interface Flat Interface
Font... &Font...
Formatted Formatted
Generate Automation Interface Generate Automation Interface
Generate Custom Interface Generate Custom Interface
Generate Interface Module Generate Interface Module
Global Docu and Mod directories &Global Docu and Mod directories
Guard: &Guard:
Heap Information Heap Information
Heap size: Heap size:
Heap Spy Heap Spy
Interface Hints Interface Hints
Intermediate Items Intermediate Items
Label: &Label:
Level: Le&vel:
Levels Levels
Link: Lin&k:
List Links &List Links
Load Options Load Options
Mark New Messages in List Mark New Messages in List
Message Spy Message Spy
Module Name: Module Name:
New Form New Form
Next Ne&xt
Notifier: &Notifier:
OK OK
Option 0 Option 0
Option 1 Option 1
Option 2 Option 2
Option 3 Option 3
Option 4 Option 4
Reset Options Reset Options
Save Options Save Options
Semicolons Semicolons
Show Client Interface Show Client Interface
Show Complete Interface Show Complete Interface
Show Extension Interface Show Extension Interface
Show Heap Show Heap
Show Messages in Log Show Messages in Log
Side Effects Side Effects
Statements in Statements in
Subsystem: Subsystem:
&Subsystem: &Subsystem:
Type Library: Type Library:
VAR Parameter VAR Parameter
View + Model in one Module View + Model in one Module
View + Model in three Modules View + Model in three Modules
View without Model View without Model
View Size View Size
Zoom Zoom
CannotOpenFile cannot open file ^0
InsertMarkers Insert Markers
DeleteMarkers Delete Markers
Log Log
LogSettings Log Settings
ModuleNotFound module ^0 not found
NoAlienView no alien view
NoItemNameSelected no item name selected
NoModuleNameSelected no module name selected
NoTargetFocusFound no target focus found
NoTextFileFound no text file ^0 found
NoTextViewFound no text view found
NotOnlyModNames selection should only contain module names
NoSelectionFound no selection found
NoSingletonFound no singleton found
NoSuchItemExported no item ^1 exported from ^0
NoSuchExtItemExported no item ^1 exported for extension from ^0
NotOnlyFileNames only file names expected in selection
StringExpected string expected
IllegalKind illegal value for kind
PrefixTooShort Subsystem name should be at least 3 characters long
NotUppercase Subsystem name should start with an uppercase letter
IllegalSyntax Subsystem name must be a valid Component Pascal identifier with uppercase letters only at the beginning
Change Change
Unloading unloading ^0
Unknown unknown
Analyzing Analyzing
Ok ok
Failed failed
OneErrorDetected one error detected
ErrorsDetected errors detected
Compiling compiling
Converting converting
Conversion Conversion
ModuleName module name
BytesUsed bytes used
Clients clients
Compiled compiled
Loaded loaded
Linked linked
FileAccessPathsInUse file access paths in use:
FontsInUse fonts in use:
HeapBytesAllocated heap bytes allocated:
SourcefileNotFound sourcefile for ^0 not found
Unloaded ^0 unloaded
UnloadingFailed unloading ^0 failed
ReferencedBy ^0 referenced by:
NotFound ^0 not found
NoModNameFound no module name found
ResourceNotFound resource file ^0 not found for subsystem ^1
ProcInUnloadedMod procedure in unloaded module
IllegalAddress illegal address:
IllegalPointer illegal pointer !!!
Undefined undefined:
UnknownFormat unknown format:
HeapObject Heap Object
Variables Variables
LoadedModules Loaded Modules
LoadedTopModules Loaded Top-Level Modules
Commands Commands
Resources Resources
Trap Trap
Update Update
Fields fields
Elements elements
RemoteState Remote State
RemoteVariables Remote Variables
RemoteModules Remote Modules
RemoteSource Remote Source
ShowPrecedingObject show preceding object
ShowGlobalVariables show global variables
ShowSourcePosition show source position
ShowReferencedObject show referenced object
UpdateWindow update window
Option Option
Controls.PushButton Command Button
Controls.PushButton.Opt0 Default
Controls.PushButton.Opt1 Cancel
Controls.CheckBox Check Box
Controls.RadioButton Radio Button
Controls.Field Text Field
Controls.Field.Opt0 Left
Controls.Field.Opt1 Right
Controls.Field.Opt2 Multi Line
Controls.Field.Opt3 Password
Controls.ListBox List Box
Controls.ListBox.Opt0 Sorted
Controls.SelectionBox Selection Box
Controls.SelectionBox.Opt0 Sorted
Controls.ComboBox Combo Box
Controls.ComboBox.Opt0 Sorted
Controls.Caption Caption
Controls.Caption.Opt0 Left
Controls.Caption.Opt1 Right
Controls.Group Group
Controls.TreeControl.Opt0 Sorted
Controls.TreeControl.Opt1 Lines
Controls.TreeControl.Opt2 Buttons
Controls.TreeControl.Opt3 Lines/Buttons at root
Controls.TreeControl.Opt4 Folder icons
StdTables.Control StdTables.Table
OleClient.View OLE Object
DevBrowser.ImportSymFile Symbol File
DevBrowser.ImportCodeFile Code File
msec msec
Module Module
PercentPerModule % per module
Procedure Procedure
PercentPerProc % per procedure
Samples samples:
InProfiledModules in profiled modules
Other other
Profile Profile
NoBasicType type of ^0 is not a basic type
NoVariable ^0 is not a variable
NoVarName no varaible name selected
NoQualident no qualified name selected
NoModule module ^0 not found
NoModuleName no module name selected
NoSourcePosInfoIn no source position info in ^0
NoSelectionOrCaret no selection or caret
NoModuleSource not a module source text
NoText no text
AlreadyExists Cannot create subsystem, because directory already exists
InconsistentLinks Inconsistent Links
Links List of all Links
CannotTranslate Cannot translate source code template ^0
AddView Add View
RemoveView Remove View
BasicSystems System, Text, Std, Ole
Implicit.CommStreams CommTCP
Implicit.Config StdLog
Implicit.Containers StdCmds, HostMenus
Implicit.Dates HostDialog
Implicit.Dialog HostDialog, StdLog, StdInterpreter, Views
Implicit.Files HostFiles
Implicit.Fonts HostFonts
Implicit.Init StdMenuTool, Config
Implicit.Kernel StdLoader, Init, Config
Implicit.Log StdLog
Implicit.Mechanisms HostMechanisms
Implicit.Printers HostPrinters
Implicit.Printing Documents
Implicit.Sequencers Windows
Implicit.Views HostDialog, StdDialog, Windows
Implicit.Windows HostWindows
Implicit.DevProfiler DevDebug
Implicit.FormViews FormControllers
Implicit.HostDialog StdCmds, TextCmds
Implicit.HostMenus StdMenuTool
Implicit.HostPrinters StdCmds
Implicit.MailerCmds MailerFolds
Implicit.StdCFrames HostCFrames
Implicit.StdCmds TextViews
Implicit.StdMeters StdCmds
Implicit.StdTabViews HostTabFrames
Implicit.TextViews TextControllers
Location Location
Count Count
Searching Searching
NoMatchFound No match found.
SearchFor Search for
NewSymFile new symbol file
ChangedLibFlag changed library flag
InconsistentImport ^0.^1 is not consistently imported
IsNoLongerInSymFile ^0 is no longer in symbol file
IsRedefinedInternally ^0 is redefined internally
IsRedefined ^0 is redefined
IsNewInSymFile ^0 is new in symbol file
NotImplementedIn ^0 not implemented in ^1
NotImplemented ^0 not implemented
RTDebugApp BlackBox Debugger
RTDebugTool Debug
RTDebugDocu Debug Docu
AttachDebuggerFailed Attaching a debugger failed.
Debugging debugging process ID ^0
Detached debugger detached
InvalidCmdSyntax invalid command syntax
UnknownEvent unknown debugging event
DataBreakpoint data breakpoint ^0: ^1
Locals locals
StopFailed stop failed, please retry
RemoteState: Remote State: ^0
StepOver Step &Over
StepInto Step &Into
Continue &Continue
ContinueTo Continue &To
HandleTrap &Handle Trap
Stop &Stop
LoadedModulesBtn Loaded &Modules
GlobalVariables Global &Variables
Terminate Terminate
Breakpoint1 Breakpoint &1
Breakpoint2 Breakpoint &2
Breakpoint3 Breakpoint &3
RemoteStateBtn &Remote State
RemoteSourceBtn Remote So&urce
SingleSourceWindow Single source window
ExpandAllStackFrames Expand all stack frames
running running
stopped stopped
breakpoint breakpoint
data breakpoint data breakpoint
trapped trapped
terminated terminated
| Dev/Rsrc/Strings.odc |
BlackBox Object File Format
bh 25.01.2007 procedure signatures added
bj 19.04.2001 updated file header with correct file tag and added processor field. Added semantic part of this docu.
bh 12.12.95
Syntax:
ObjFile = HeaderBlk MetaBlk DescBlk CodeBlk FixBlk UseBlk.
HeaderBlk = OFTag processor4 headsize4 metasize4 descsize4 codesize4 datasize4 nofimp modname {impname} Align.
OFTag = 6FX 4FX 43X 46X.
MetaBlk = RefBlk Align SigBlk ExpBlk PtrBlk FldBlk ImpBlk Names Consts Align.
DescBlk = ModBlk Align TDescBlk.
ExpBlk = Directory.
Directory = numobj4 {Object}.
Object = fprint4 offs4 id4 Struct.
SigBlk = {Signature}.
Signature = Struct numPar4 {id4 Struct}.
Struct = form4 | strRef4 | sigRef4.
PtrBlk = {offset4}.
FldBlk = {Directory | Signature}.
ImpBlk = {0.4}.
Names = {char}.
Consts = {byte}.
Align = {0X}.
ModBlk = 0.4 opts4 0.4 0.4 term4 nofimp4 nofptr4 csize4 dsize4 rsize4
codeRef4 dataRef4 refsRef4 namesRef4 ptrsRef4 impRef4 expRef4 name.
TDescBlk = {RecDesc | ArrDesc | DArrDesc | PtrDesc | ProcDesc | FieldList}.
RecDesc = 0.4 {methRef4} size4 modRef4 id4 {btypRef4} flistRef4 {ptrOffs4} sent4.
ArrDesc = nofele4 modRef4 id4 btypRef4.
PtrDesc = 0.4 modRef4 id4 btypRef4.
ProcDesc = fprint4 modRef4 id4 sigRef4.
FieldList = Directory.
FixBlk = newreclink newarrlink metalink desclink codelink datalink.
link = {fixupadr offset} 0X.
UseBlk = {{UConst | UType | UVar | UProc} 0X}.
UConst = 1X name fprint.
UType = 2X name fprint opt link.
UVar = 3X name fprint link.
UProc = 4X name fprint link.
RefBlk = {0F8X procend name {Mode Form adr name}}.
Mode = Var | VarPar.
Var = 0FDX.
VarPar = 0FFX.
Form = Bool | Char | LChar | SInt | Int | LInt | Real | LReal | Set | LargeInt | AnyRec | AnyPtr | Pointer | Proc | String | Struct.
Bool = 1X.
Char = 2X.
LChar = 3X.
SInt = 4X.
Int = 5X.
LInt = 6X.
Real = 7X.
LReal = 8X.
Set = 9X.
LargeInt = 0AX.
AnyRec = 0BX.
AnyPtr = 0CX.
Pointer = 0DX.
Proc = 0EX.
String = 0FX.
Struct = 10X descRef4.
Semantics:
Header
Contains the sizes of the different blocks, the name of the module and a list of the names of the imported modules.
Meta
Meta information about the module. Only used by the modules Meta and DevDebug.
Desc
Meta information about the module which should stay in memory even when the module have been unloaded. Consists of two parts corresponding to the types Kernel.Module and Kernel.Type. The layout is made so the memory addresses can be directly mapped to variables of these types.
Code
Contains the code for the module. The address of the Code section is the entry point to the body of the module.
Data
Memory space for the variables. Variables are stored in reversed order, i.e. the last global variable starts at this address.
Fixup
The fixup bulk contains links into the different memory blocks where there is a need for updating the addresses. The following links exist:
newreclink link to the memory location where the procedure pointer for allocating new records is stored
newarrlink link to the memory location where the procedure pointer for allocating new arrays is stored
metalink link to the start of the fixup links in the meta bulk
desclink link to the start of the fixup links in the desc bulk
codelink link to the start of the fixup links in the code bulk
datalink link to the start of the fixup links in the data bulk
For each memory block there is a list of fixup links. A link consists of two parts:
fixupadr the start of the memory location in need of fixup
offset the offset within the memory location to the first address which needs a fixup
When fixupadr = 0X then the end of the list of fixups for the corresponding memory block has been reached.
At the position given by fixupadr + offset there are four bytes which should be overwritten with the new fixed value. But before writning to this address the four bytes should be read and interpreted as follows:
- The most significant byte indicates the type of fixup that should be done.
- The other three bytes, interpreted as an INTEGER, x.
The type and x are used as in the table.
Fixup Types (mem[adr] = id * 2^24 + x, mem[adr] := value)
id type value next adr
100 absolute objadr + offs x
101 relative objadr + offs - adr - 4 x
102 copy mem[objadr + offs] x
103 table objadr + x adr + 4
104 table end objadr + x -
x = 0 indicates end of fixup for this address.
Use
For each imported module this section contains a list of imported constants, types, variabled and procedures. With exception for constants they all need to be fixed in the same way as other links.
| Dev/Spec/ObjFile.odc |
HostPackedFiles
DEFINITION HostPackedFiles;
CONST magicnum = 4711;
PROCEDURE IsInstalled;
PROCEDURE RestoreFilesDir;
PROCEDURE SetFilesDir;
END HostPackedFiles.
Module HostPackedFiles is an implementation of Files.Directory. The implementation is basically a wrapper around the HostFiles implementation with one major difference: when a file is not present in the file system HostPackedFiles searches the current executable for files packed in there by DevPacker.
Since HostPackedFiles wraps HostFiles it cannot work unless HostFiles is installed first. For HostPackedFiles to work properly it is also important that the exe-file has the right format. This format is explained below.
Whenever HostPackedFiles is loaded it tries to install itself as the Files.Directory. There are two preconditions for HostPackedFiles to be installed; first the current Files.Directory must be a HostFiles implementation and secondly there must be some files packed into the current directory.
CONST magicnum
Used as a magic number in the exe-file to mark the position of the address to the file table. This constant is only exported to make it possible for DevPacker to write the appropriate magic number into the exe-file.
PROCEDURE SetFilesDir
If no files are found in the current executable a call to this procedure does nothing. Otherwise it checks if HostFiles is the current directory of Files. In that case it holds a reference to this directory and calls Files.SetDir with the HostPackedFiles.Directory. This procedure is called the first time the module is loaded.
PROCEDURE RestoreFilesDir
Calls Files.SetDir with the original directory saved by SetFilesDir. Thus, uninstalling HostPackedFiles as the current Files directory.
PROCEDURE IsInstalled
Checks wether HostPackedFiles.Directory is the directory used by Files or not. This is not always a reliable test, since HostPackedFiles installs itself when it is loaded. A call to IsInstalled may cause HostPackedFiles to be installed. If, however, the result is that HostPackedFiles is not installed then this is a reliable result.
Executable File Format Required by HostPackedFiles
(* Should this really be here? *)
When DevPacker is used to pack files into an executable file it simply appends its information at the end of the file. This means that the first part of such an executable is exactly the same as a normal Windows executable. This text therefore only explains the appended information that DevPacker adds to the file.
The format of the exe-file can be separated into four parts:
1) A Windows executable part
2) Contents of files packed in by DevPacker
3) File table of the files packed in by DevPacker
4) Address of the file table
The four parts appear in this order in the executable, which makes the executable look like Figure 1.
Figure 1. Executable file structure.
The first part contains the executable generated by the linker command and all Windows resources, such as icons and cursors. Since DevPacker only appends information to the file, it is important that all resources are added before files are packed into the executable. Otherwise the information about how to find the files within the executable will be destroyed.
The second part is the content of all the files packed in by DevPacker. The contents are simply an array of bytes. To know where a file starts and how long it is the third part, the file table, is needed. The file table has the structure described in Figure 2.
Figure 2. File table structure.
To avoid sorting each time the HostPackedFiles is loaded, DevPacker does the sorting when files are packed. HostPackedFiles therefore assumes that the files are listed in reversed alphabetical order.
The last eight bytes of the executable are interpreted as two integers, having the meaning shown in Figure 3.
Figure 3. Address of the file table.
If the first integer does not equal HostPackedFiles.magicnum it is assumed that no files are packed into the executable. Otherwise the next integer is interpreted as the address of the file table within the executable.
| Dev/Spec/PackedFiles.odc |
Stores File Format
Stream = { Byte | Structure }.
Structure = Nil | Link | Object.
Nil = nil Comment Next.
Link = (link | newlink) ObjectId Comment Next.
(* newlink and link have same meaning in new format, but newlink causes assertion trap in old *)
(* if Next = 0 & Comment = 0 indecates end of link chain, whereas Next = 0 & Comment = 1 indicates
next store at Pos(Next) + 4 *)
Object = (elem | store) TypePath Comment Next Down Length Stream.
(* elem = Models.Model-derived type; for backward comp only *)
Comment = 00000000. (* extension hook *)
ObjectId = 32bits. (* index into object dictionary *)
Next = 32bits. (* offset to next object on same nesting level; 00000000 if none *)
Down = 32bits. (* offset to first object on next lower nesting level; 00000000 if none *)
Length = 32bits. (* length of this object (including all subobjects) *)
TypePath = OldType | NewType. (* sequence of type names from most precise to root base type *)
OldType = oldType TypeId.
NewType = { NewExtension } (NewBase | OldType).
NewExtension = newExt TypeName.
NewBase = newBase TypeName.
TypeName = String.
TypeId = 32bits. (* index into type dictionary *)
nil = 80. (* nil store *)
link = 81. (* link to another elem in same file *)
store = 82. (* general store *)
elem = 83. (* elem store *)
newlink = 84. (* link to another non-elem store in same file *)
| Dev/Spec/StoresFileFormat.odc |
Oberon/F Symbol File Format bh
漜
SymFile = tag4 processor version Module { Object } .
Module = 0 | negmno | [ LIB name ] MNAME name .
Object = [ SYS value ] [ LIB name ] [ ENTRY name ]
( Constant name
| TYPE Struct
| ALIAS Struct name
| (RVAR | VAR) Struct name
| (XPRO | IPRO) Signature name
| CPRO Signature len { code1 } name
).
Constant = CHAR8 value1
| CHAR16 value2
| BOOL ( FALSE | TRUE )
| ( INT8 | INT16 | INT32 | INT64 | SET ) value
| REAL32 value4
| REAL64 value8
| STRING8 name
| STRING16 length utf8string
| NIL .
Struct = negref
| STRUCT Module name [ SYS value ] [ LIB name ] [ ENTRY name ] [ STRING name ]
( PTR Struct
| ARR Struct nofElem
| DARR Struct
| ( REC | ABSREC | EXTREC | FINREC ) Struct size align nofMeth { Field } { Method } END
| PRO Signature
| ALIAS Struct
) .
Field = ( FLD | RFLD ) Struct name offset | ( HDPTR | SYS value | HDPRO ) offset .
Method = [ IMPO ] [ ENTRY name ]
( TPRO | ABSPRO | EMPPRO | EXTPRO | FINPRO ) Signature name methno | HDTPRO methno .
Signature = Struct { [ SYS value ] ( VALPAR | VARPAR | INPAR | OUTPAR ) Struct offset name } END .
MNAME = 16 BYTE = 1 byte = 1
END = 18 BOOL = 2 boolean = 2
TYPE = 19 CHAR8 = 3 char8 = 3
ALIAS = 20 INT8 = 4 int8 = 4
VAR = 21 INT16 = 5 int16 = 5
RVAR = 22 INT32 = 6 int32 = 6
VALPAR = 23 REAL32 = 7 real32 = 7
VARPAR = 24 REAL64 = 8 real64 = 8
FLD = 25 SET = 9 set = 9
RFLD = 26 STRING8 = 10
HDPTR = 27 NIL = 11
HDPRO = 28 notyp = 12
TPRO = 29 sysptr = 13
HDTPRO = 30 anypointer = 14
XPRO = 31 anyrecord = 15
IPRO = 32 CHAR16 = 16 char16 = 16
CPRO = 33 STRING16 = 17
STRUCT = 34 INT64 = 18 int64 = 18
SYS = 35 result = 20
PTR = 36 iunknown = 21
ARR = 37 ptriunk = 22
DARR = 38 guid = 23
REC = 39 HDUTPTR = 41
PRO = 40 LIB = 42
INPAR = 25 ENTRY = 43 FALSE = 0
OUTPAR = 26 FINPRO = 31 TRUE = 1
FINREC = 25 ABSPRO = 32
ABSREC = 26 EMPPRO = 33
EXTREC = 27 EXTPRO = 34 IMPO = 22 | Dev/Spec/SymFile.odc |
Character Set
Contents
Charactersetlisting
ControlcodesusedinBlackBox
The character set for the Component Pascal SHORTCHAR data type is an 8-bit character set based on the ISO 8859-1 standard. It includes the ASCII (American Standard Code for Information Interchange) and the so-called Latin-1 extension to ASCII. Latin-1 includes most characters necessary for writing in languages which are based on Latin.
The character set for the Component Pascal CHAR data type is Unicode.
Both ASCII and Latin-1 contain slots for control characters, which are character codes used for various purposes, but which do not correspond to any glyph, i.e. visual representation of a character.
For BlackBox, several punctuation marks from the 16-bit Unicode standard have been mapped into the unused upper control code portion of Latin-1.
Character set listing
The following list gives the names of every non-control code in the character set. The same naming conventions are used as in the Unicode standard, of which the Component Pascal character set is a subset.
Hex Char Name Comment
20 SPACE
21 ! EXCLAMATION MARK
22 " QUOTATION MARK
23 # NUMBER SIGN
24 $ DOLLAR SIGN
25 % PERCENT SIGN
26 & AMPERSAND
27 ' APOSTROPHE-QUOTE
28 ( OPENING PARENTHESIS
29 ) CLOSING PARENTHESIS
2A * ASTERISK
2B + PLUS SIGN
2C , COMMA
2D - HYPHEN-MINUS use as minus only, for hyphens
see codes 90, 91 and AD
2E . PERIOD
2F / SLASH
30 0 DIGIT ZERO
31 1 DIGIT ONE
32 2 DIGIT TWO
33 3 DIGIT THREE
34 4 DIGIT FOUR
35 5 DIGIT FIVE
36 6 DIGIT SIX
37 7 DIGIT SEVEN
38 8 DIGIT EIGHT
39 9 DIGIT NINE
3A : COLON
3B ; SEMICOLON
3C < LESS-THAN SIGN
3D = EQUAL SIGN
3E > GREATER-THAN SIGN
3F ? QUESTION MARK
40 @ COMMERCIAL AT
41 A LATIN CAPITAL LETTER A
42 B LATIN CAPITAL LETTER B
43 C LATIN CAPITAL LETTER C
44 D LATIN CAPITAL LETTER D
45 E LATIN CAPITAL LETTER E
46 F LATIN CAPITAL LETTER F
47 G LATIN CAPITAL LETTER G
48 H LATIN CAPITAL LETTER H
49 I LATIN CAPITAL LETTER I
4A J LATIN CAPITAL LETTER J
4B K LATIN CAPITAL LETTER K
4C L LATIN CAPITAL LETTER L
4D M LATIN CAPITAL LETTER M
4E N LATIN CAPITAL LETTER N
4F O LATIN CAPITAL LETTER O
50 P LATIN CAPITAL LETTER P
51 Q LATIN CAPITAL LETTER Q
52 R LATIN CAPITAL LETTER R
53 S LATIN CAPITAL LETTER S
54 T LATIN CAPITAL LETTER T
55 U LATIN CAPITAL LETTER U
56 V LATIN CAPITAL LETTER V
57 W LATIN CAPITAL LETTER W
58 X LATIN CAPITAL LETTER X
59 Y LATIN CAPITAL LETTER Y
5A Z LATIN CAPITAL LETTER Z
5B [ OPENING-SQUARE BRACKET
5C \ BACKSLASH
5D ] CLOSING SQUARE BRACKET
5E ^ SPACING CIRCUMFLEX
5F _ SPACING UNDERSCORE
60 ` SPACING GRAVE
61 a LATIN SMALL LETTER A
62 b LATIN SMALL LETTER B
63 c LATIN SMALL LETTER C
64 d LATIN SMALL LETTER D
65 e LATIN SMALL LETTER E
66 f LATIN SMALL LETTER F
67 g LATIN SMALL LETTER G
68 h LATIN SMALL LETTER H
69 i LATIN SMALL LETTER I
6A j LATIN SMALL LETTER J
6B k LATIN SMALL LETTER K
6C l LATIN SMALL LETTER L
6D m LATIN SMALL LETTER M
6E n LATIN SMALL LETTER N
6F o LATIN SMALL LETTER O
70 p LATIN SMALL LETTER P
71 q LATIN SMALL LETTER Q
72 r LATIN SMALL LETTER R
73 s LATIN SMALL LETTER S
74 t LATIN SMALL LETTER T
75 u LATIN SMALL LETTER U
76 v LATIN SMALL LETTER V
77 w LATIN SMALL LETTER W
78 x LATIN SMALL LETTER X
79 y LATIN SMALL LETTER Y
7A z LATIN SMALL LETTER Z
7B { OPENING CURLY BRACKET
7C | VERTICAL BAR
7D } CLOSING CURLY BRACKET
7E ~ TILDE
7F reserved
80 .. 89 reserved
8A Š LATIN CAPITAL LETTER S CARON (Unicode 0160)
8B ZERO WIDTH SPACE (Unicode 200B)
8C Œ LATIN CAPITAL LIGATURE OE (Unicode 0152)
8D reserved
8E Ž LATIN CAPITAL LETTER Z CARON (Unicode 017D)
8F DIGIT SPACE (not in Unicode)
90 HYPHEN (Unicode 2010)
91 ‑ NON-BREAKING HYPHEN (Unicode 2011)
92 .. 99 reserved
9A š LATIN SMALL LETTER S CARON (Unicode 0161)
9B reserved
9C œ LATIN SMALL LIGATURE OE (Unicode 0153)
9D reserved
9E ž LATIN SMALL LETTER Z CARON (Unicode 017E)
9F Ÿ LATIN CAPITAL LETTER Y DIAERESIS (Unicode 0178)
A0 NON-BREAKING SPACE
A1 INVERTED EXCLAMATION MARK
A2 CENT SIGN
A3 POUND SIGN
A4 CURRENCY SIGN
A5 YEN SIGN
A6 BROKEN VERTICAL BAR
A7 SECTION SIGN
A8 SPACING DIAERESIS
A9 COPYRIGHT SIGN
AA FEMININE ORDINAL INDICATOR
AB LEFT POINTING GUILLEMET
AC NOT SIGN
AD SOFT HYPHEN
AE REGISTERED TRADE MARK SIGN
AF SPACING MACRON
B0 DEGREE SIGN
B1 PLUS-OR-MINUS SIGN
B2 SUPERSCRIPT DIGIT TWO
B3 SUPERSCRIPT DIGIT THREE
B4 SPACING ACUTE
B5 MICRO SIGN
B6 PARAGRAPH SIGN
B7 MIDDLE DOT
B8 SPACING CEDILLA
B9 SUPERSCRIPT DIGIT ONE
BA MASCULINE ORDINAL INDICATOR
BB RIGHT POINTING GUILLEMET
BC FRACTION ONE QUARTER
BD FRACTION ONE HALF
BE FRACTION THREE QUARTERS
BF INVERTED QUESTION MARK
C0 LATIN CAPITAL LETTER A GRAVE
C1 LATIN CAPITAL LETTER A ACUTE
C2 LATIN CAPITAL LETTER A CIRCUMFLEX
C3 LATIN CAPITAL LETTER A TILDE
C4 LATIN CAPITAL LETTER A DIAERESIS
C5 LATIN CAPITAL LETTER A RING
C6 LATIN CAPITAL LETTER A E
C7 LATIN CAPITAL LETTER C CEDILLA
C8 LATIN CAPITAL LETTER E GRAVE
C9 LATIN CAPITAL LETTER E ACUTE
CA LATIN CAPITAL LETTER E CIRCUMFLEX
CB LATIN CAPITAL LETTER E DIAERESIS
CC LATIN CAPITAL LETTER I GRAVE
CD LATIN CAPITAL LETTER I ACUTE
CE LATIN CAPITAL LETTER I CIRCUMFLEX
CF LATIN CAPITAL LETTER I DIAERESIS
D0 LATIN CAPITAL LETTER ETH
D1 LATIN CAPITAL LETTER N TILDE
D2 LATIN CAPITAL LETTER O GRAVE
D3 LATIN CAPITAL LETTER O ACUTE
D4 LATIN CAPITAL LETTER O CIRCUMFLEX
D5 LATIN CAPITAL LETTER O TILDE
D6 LATIN CAPITAL LETTER O DIAERESIS
D7 MULTIPLICATION SIGN
D8 LATIN CAPITAL LETTER 0 SLASH
D9 LATIN CAPITAL LETTER U GRAVE
DA LATIN CAPITAL LETTER U ACUTE
DB LATIN CAPITAL LETTER U CIRCUMFLEX
DC LATIN CAPITAL LETTER U DIAERESIS
DD LATIN CAPITAL LETTER Y ACUTE
DE LATIN CAPITAL LETTER THORN
DF LATIN SMALL LETTER SHARP S
E0 LATIN SMALL LETTER A GRAVE
E1 LATIN SMALL LETTER A ACUTE
E2 LATIN SMALL LETTER A CIRCUMFLEX
E3 LATIN SMALL LETTER A TILDE
E4 LATIN SMALL LETTER A DIAERESIS
E5 LATIN SMALL LETTER A RING
E6 LATIN SMALL LETTER A E
E7 LATIN SMALL LETTER C CEDILLA
E8 LATIN SMALL LETTER E GRAVE
E9 LATIN SMALL LETTER E ACUTE
EA LATIN SMALL LETTER E CIRCUMFLEX
EB LATIN SMALL LETTER E DIAERESIS
EC LATIN SMALL LETTER I GRAVE
ED LATIN SMALL LETTER I ACUTE
EE LATIN SMALL LETTER I CIRCUMFLEX
EF LATIN SMALL LETTER I DIAERESIS
F0 LATIN SMALL LETTER ETH
F1 LATIN SMALL LETTER N TILDE
F2 LATIN SMALL LETTER O GRAVE
F3 LATIN SMALL LETTER O ACUTE
F4 LATIN SMALL LETTER O CIRCUMFLEX
F5 LATIN SMALL LETTER O TILDE
F6 LATIN SMALL LETTER O DIAERESIS
F7 DIVISION SIGN
F8 LATIN SMALL LETTER O SLASH
F9 LATIN SMALL LETTER U GRAVE
FA LATIN SMALL LETTER U ACUTE
FB LATIN SMALL LETTER U CIRCUMFLEX
FC LATIN SMALL LETTER U DIAERESIS
FD LATIN SMALL LETTER Y ACUTE
FE LATIN SMALL LETTER THORN
FF LATIN SMALL LETTER Y DIAERESIS
Control codes used in BlackBox
The following control codes are used in the BlackBox Component Framework:
00X nul string terminator
01X unicode unicode mask character
02X viewcode view mask character
07X rdel right delete key
08X del left delete key
09X tab tabulator key
0AX ltab reverse tabulator key
0DX line return key (Unicode 2028, LINE SEPARATOR)
0EX para paragraph separator (Unicode 2029, PARAGRAPH SEPARATOR)
10X pL page left
11X pR page right
12X pU page up
13X pD page down
14X dL document left
15X dR document right
16X dU document up
17X dD document down
1BX esc escape key
1CX aL arrow left key
1DX aR arrow right key
1EX aU arrow up key
1FX aD arrow down key
Of these codes, only tab, line, and para should ever be stored in a text, i.e., are not considered to be control codes in BlackBox. The ASCII DEL code (07FX) is not used in BlackBox and remains reserved.
| Docu/BB-Chars.odc |
Documentation Conventions
Documentation has two major purposes: to communicate how a program's service can be used interactively (user manual) and how the program's service can be used programmatically (developer manual). In BlackBox, services are arranged in subsystems. A subsystem typically consists of several possibly cooperating modules. In the general case, we need three kinds of documentation texts: a user manual, one module interface description per module, and an overview over how the modules may interact with each other, i.e., an introduction to the overall architecture of the subsystem (developer manual).
A subsystem is represented on the disk as a directory, e.g., directory Text. In this directory, there is a nested directory called Docu, e.g. Text/Docu. This documentation directory may contain the following text documents:
• a user manual called User-Man
• a hypertext map to the documentation, called Sys-Map
• a programmer's introduction called Dev-Man
• and one module interface description per module, having the module name without its subsystem prefix, e.g. Views for module TextViews.
Note that all documentation texts which do not directly denote the programmer's reference for a particular module must have a dash ("-") in their names, so that the repository browser can distinguish between module documentations and other documentation files.
The remainder of this text describes the format of a module interface description.
Each module description begins with a module definition. The Component Pascal notation for module definitions is used, which lists all exported items of a module, and only those. A module begins with the keyword DEFINITION instead of MODULE, export marks are omitted (except read-only marks), and procedure bodies and the module body are left out as well. A method appears in the corresponding record declaration itself, without the PROCEDURE keyword.
The hypothetical module "Dictionaries" serves as an example:
DEFINITION Dictionaries;
CONST maxElems = 32;
TYPE
Dictionary = POINTER TO LIMITED RECORD
elems-: INTEGER;
(d: Dictionary) Put (string: ARRAY OF CHAR; OUT key: INTEGER), NEW;
(d: Dictionary) Get (key: INTEGER; OUT string: ARRAY OF CHAR), NEW
END;
VAR someDict: Dictionary;
PROCEDURE Init;
END Dictionaries.
In an extended record, the inherited procedures are not listed, only the new procedures, or the procedures which have changed signatures or where the semantics are specialized so that they need to be clarified.
A changed signature may be caused by a covariant function result, i.e., the procedure returns a pointer that is an extension of the one returned by the base procedure. Or it may be caused by changed method attributes (final, ABSTRACT, EMPTY, EXTENSIBLE), e.g., an abstract method may have been implemented and made final.
A module definition is followed by a brief description of the abstraction(s) provided by the module.
This module provides a concrete type Dictionary for the manipulation of string dictionaries.
Then the constants of the module are listed, without their values:
CONST maxElems
Maximum number of elements in a dictionary.
This is followed by the module's types:
TYPE Dictionary
LIMITED
Manages a dictionary of strings, with an integer number as key.
Record attributes are given in the second line, as above. Record attributes are either none (final by default), EXTENSIBLE, ABSTRACT, or LIMITED.
If the type is an extension of another type, this is marked, e.g., as
Dictionary (OtherModule.Dictionary)
Then the record fields are listed:
elems-: INTEGER 0 <= elems <= maxElems
The number of elements currently in the dictionary.
As in the above example, an invariant over the record field's value may optionally be given.
Then the procedures bound to this type are given:
PROCEDURE (d: Dictionary) Put (string: ARRAY OF CHAR; OUT key: INTEGER)
NEW
For each method, it is specified whether this procedure is final (default), extensible, abstract, or empty.
An abstract procedure must not be called.
An empty procedure must not be called by an extending procedure (i.e., through a super-call of an implementing procedure).
In the second line, the method attributes are given, which are either none (final by default), EXTENSIBLE, ABSTRACT, or EMPTY. Before this attribute, NEW is written for newly introduced methods.
An implement-only method can only be called in its defining module. This module can thus establish the method's preconditions before every call to it that occurs in the module implementation. If the implementation is correct, these preconditions can never be violated, since no other module may perform a call. Thus an implementor can assume that the preconditions hold, and need not test them. Preconditions of implement-only methods are thus not attributed with a trap number; instead, they are marked as "guaranteed", meaning that the defining module guarantees them.
An explanation of the procedure's behavior follows:
Put a string into dictionary d, and receive key in return. If the string is already in the dictionary, the same key is returned as when it was inserted first. If the string is not in the dictionary, it is inserted and a value which has not been used before is returned.
After an explanation in plain English, some preconditions for this procedure may be specified. These preconditions are given in a semi-formal notation:
Pre
20 string # ""
This means that if the precondition is violated (i.e. if string = ""), the currently executing command is aborted with exception number 20. Instead of a number, the following exceptions may be specified as well:
invalid index
type guard check
A second precondition may thus be the following:
invalid index string in d OR d.elems < maxElems
In older parts of the documentation, the precondition numbers may also be given after the expression, instead of in front of it. Over time, all documentation should be adapted to the new and better readable style.
After the preconditions, some postconditions may be specified:
Post
string in d'
old key returned
~(string in d')
string in d
d.elems = d.elems' + 1
new key returned
This postcondition contains two cases, namely what happens if the string is already contained in d, and what happens if the string is not yet contained in d. The conditions are textually aligned to the left, while the respective conclusions are indented. Occasionally, conditions are nested by further indentations.
To refer to values before the operation, an expression is followed by an apostrophe if this is necessary for clarity (i.e. if the value may be changed at all). Thus the expression
d.elems = d.elems' + 1
means that the value of d.elems has been incremented by one.
Component Pascal is generally used as syntax for such expressions, although some liberties are taken, e.g., simple auxiliary procedures that are not described further may be used.
Function results are generically called "result".
The amount of formalism is kept small. It is attempted to limit formal specifications to few and simple conditions, or to the explanation of particularly subtle situations. It is not intended to specify complete formal semantics of the library, thus the formalism does not replace plain text explanations, examples, or graphical illustrations completely.
However, it is felt that checked preconditions in particular are often helpful even in this incomplete and semi-formal way, both for documentation and for debugging purposes.
PROCEDURE (d: Dictionary) Get (key: INTEGER; OUT string: ARRAY OF CHAR)
NEW
Retrieve a string from the dictionary, by using key. If the value is not found, string is set to the empty string.
Post
key in d
return corresponding string
~(key in d)
return ""
Procedures which are inherited through type extension are usually not listed here. Exceptions are procedures which have extended their semantics. Semantic extensions are restricted to having weaker preconditions or stronger postconditions.
After all types, the global variables are listed:
VAR someDict: Dictionary someDict # NIL
This variable contains a dictionary.
The optional invariant is established by the module body.
Finally, the procedures exported by the module are listed:
PROCEDURE Init (d: Dictionary)
Initializes a dictionary. Any dictionary may be allocated once only.
Pre
20 d not yet initialized
In BlackBox, all procedures whose names start with "Init" may be called only once per object, i.e., they are "snappy".
| Docu/BB-Docu.odc |
Roadmap
Contents
1 Twokindsofcomponents
2 Commands
3 Views
4 Overview
5 Tableofcontents
1 Two kinds of components
BlackBox contains a component framework, which is a new concept for most programmers. This document gives a quick overview over which kinds of BlackBox components there are, when you need which, and where the documentation is.
Generally, BlackBox distinguishes two major categories of components: commands and views. Commands are comparable to traditional scripts or macros, except that they are implemented in a "real" programming language, rather than in a limited or inefficient special purpose scripting language. This means that if a problem grows, its programmatic solution can grow along; you'll not suddenly need to switch to another language. Thus commands range from simple automation tasks to complex programs such as compilers. The main purpose of commands is to assemble visual objects, i.e., to make them work together. Views are the visual objects of the BlackBox Component Framework.
2 Commands
Often, programs are built around data entry masks; these are forms in BlackBox. Module Controls and the form subsystem provide the necessary support to build form-based user interfaces.
Often, you'll also want to generate texts, e.g., for reporting purposes. You can use all capabilities of the BlackBox text subsystem, including fonts, type sizes, color, embedded components such as stamp views or link views, and so on. An example command which uses both the form and text subsystems is ObxOrders.
Before looking at this advanced example, you may want to have a look at simpler text and form sample programs. The Obx subsystem ("Overview by Example") provides a variety of such examples.
BlackBox programs are document-centric. This means that you typically work with documents and document parts; and not directly with files or windows. Files are used only for simple databases or for manipulating legacy data. Sometimes it's possible to convert legacy data to a BlackBox data type by writing a new converter. Obx also contains an example of such a converter.
3 Views
If the built-in subsystems are not sufficient for your purposes, you need to develop a new BlackBox component. Usually this is a document component, a so-called view implementation. In contrast to old-style programs, a view only owns a part of a document, and not the whole screen or even a whole window. If the view is the outermost view (root view), the result cannot be distinguished from a traditional application. However, a view is always able to be embedded in texts, forms, and so on.
Examples of views are text views; form views; link views (hypertext); stamp views (time stamps); clock views; Oberon microsystems logo views; bitmap (picture) views; commander views (buttons which execute a command); fold views; error views generated by the compiler; various controls (command buttons, check boxes, edit fields, ...) and so on. Before implementing your own view type, take a look at these views to get an idea of the variety of ways in which views can be used. Sometimes it's not necessary to implement a whole new complex subsystem in order to solve a problem, but rather some additional view which extends the functionality of the existing text subsystem, for example.
Views may or may not have a model. A model is the datastructure which is visually represented by the view. In simple cases where the view needs no editable persistent state, no model is needed. Examples are logo views, controls, etc. Full-fledged editors on the other hand should contain a separate model. Such more complex views are typically implemented in several modules, while simple views without separate modules are usually implemented in a single module.
Advanced views may contain other views. Such advanced views are called containers. There are three useful categories of containers:
• A Wrapper contains another view and modifies or extends its behavior. Typically, a wrapper has the same size as the wrapped view. For example, a terminal view may wrap a standard text view; it adds the communication facilities, while the text view provides the echoing of communicated text.
• A Special Container contains one or several embedded views. The container knows about the types of the embedded views and their layout. Views cannot be inserted or deleted. For example, such a special container could have a query view at the top where database queries can be typed in, and a larger text view at the bottom where the results of the query appear. Another example is given in ObxTwins.
• A General Container may contain an arbitrary number of embedded views, and they may change over time. This is the most general and most complex kind of view, e.g., the built-in text and form subsystems. The form subsystem is available in source form. Examples for the other kinds of view are available as Obx examples.
Views may have no programming interface, a simple procedural interface (typically based on properties, see Controls), or a full-fledged extensible interface. For the latter, it is recommended that the exported interface is separated from the hidden default implementation; in order to achieve maximum extensibility.
4 Overview
How should you start to get acquainted with BlackBox? We suggest that you start with the introduction texts A Brief History of Pascal and GuidedTour.
The documentation consists of four major parts:
•A user manual that describes the user interface and most important commands of the BlackBox Component Builder
•A tutorial that first introduces the general BlackBox design patterns (chapters 1 to 3). Graphical user interfaces, forms, and controls are discussed in chapter4. The text subsystem is explained in chapter5. The remaining chapter6 deals with view programming.
•Overview by Example is a rich source of examples, ordered by category and difficulty.
•The programmer's reference consists of one documentation file per module. Each subsystem has a Sys-Map text which contains links to the individual texts.
Apart from the Obx samples and the tutorial examples, another documentation for the most important kinds of BlackBox programs is available in Dev/Rsrc/New. These are template documents that you can use as basis for your own programs. The template documents' module names are renamed automatically by the Tools->CreateSubsystem... command. This command also creates a suitable new subsystem directory structure (see DevSubTool).
Programmers who need to interface with non-BlackBox software should consult the text Platform-SpecificIssues.
Note that you can reach the entire on-line documentation via the help menu, or from the table of contents below.
5 Table of contents
Quick Start
GuidedTour
OverviewbyExample
Tutorial
Table of Contents
1 UserInteraction
2 CompoundDocuments
3 DesignPractices
4 Forms
5 Texts
6 ViewConstruction
Appendix A: ABriefHistoryofPascal
Appendix B: FromPascaltoComponentPascal
User Manuals
Framework
TextSubsystem
FormSubsystem
DevSubsystem
StdSubsystem
Developer Manuals
Framework
TextSubsystem
FormSubsystem
DevSubsystem
SqlSubsystem
Component Pascal
LanguageReport
What'sNew?
CharacterSet
DocumentationConventions
ProgrammingConventions
Miscellaneous
License
Contributors
Platform-SpecificIssues
Ctl Subsystem
| Docu/BB-Road.odc |
Programming Conventions
Contents
1 Essentials
2 Oberon
3 Basictypes
4 Fontattributes
5 Comments
6 Semicolons
7 Dereferencing
8 Case
9 Names
10 Whitespace
11 Example
12 OpenSourceHeader
This text describes the programming guidelines and source code formatting conventions which have been used for the BlackBox Component Framework. For the documentation there exist similar conventions.
Some programming guidelines are more important than others. In the first section, the more important ones are described. The remaining sections contain more cosmetic rules which describe the look-and-feel of programs published by Oberon microsystems. If you like them, feel free to use them for your programs as well. It may make your programs easier to understand for someone who is used to the design, documentation, and coding patterns of the BlackBox Component Framework.
1 Essentials
The most important programming conventions all center around the aspect of evolvability. It should be made as easy as possible to change existing programs in a reliable way, even if the program has been written a long time ago or by someone else. Evolvability can often be improved by increasing the locality of program pieces: if a piece of program may only have an effect on a clearly locatable stretch of program text, it is easier to know where a program modification may necessitate further changes. Basically, it's all a matter of keeping "ripple effects" under control.
Preconditions are one of the most useful tools to detect unaccounted ripple effects. Precondition checks allow to pinpoint semantic errors as early as possible, i.e. as closely to their true source as possible. After larger design changes, properly used assertions can help to dramatically reduce debugging time.
Whenever possible, use static means to express what you know about a program's design. In particular, use the type and module systems of Component Pascal for this purpose; so the compiler can help you to find inconsistencies, and thus can become an effective refactoring tool.
• Precondition assertions should be used consequently. Don't allow client code to "enter" your module if it doesn't fulfill the preconditions of your module's entry points (procedures, methods). In this way, you avoid propagation of foreign errors into your own code.
Use the following numbers to be consistent with the rest of the BlackBox Component Builder:
Free 0 .. 19 use for temporary breakpoints
Preconditions 20 .. 59 validate parameters at procedure entry
Postconditions 60 .. 99 validate results at procedure end
Invariants 100 .. 120 validate intermediate states
(detect local error)
Reserved 121 .. 125 reserved for future use
Not Yet Implemented 126 procedure is not yet implemented
Reserved 127 reserved for future use
Silent Trap 128 termination without trap window
• There should be as few global variables as possible.
Global variables can be accessed from many places in a program, at different times. This makes it difficult to keep track of all possible interactions ("side effects") with such variables. This in turn increases the likelihood of introducing errors when changing the use of them.
• Function procedures, i.e., procedures which return a result, should not modify global variables or VAR parameters as side effects. It is easier to deal with function procedures if they are true functions in the mathematical sense, i.e., if the don't have side effects. Returning function results and assigning OUT parameters is ok.
• Only use ELSE in CASE or WITH if input data is extensible.
ELSE clauses in CASE x OF or WITH x DO statements should only be used if x is genuinely extensible. If x is not extensible, all cases that can occur should be statically known, and can be listed in the statement.
2 Oberon
For new software, don't use the special Oberon features that are not part of Component Pascal. In particular, this is the LONGREAL type and the COPY procedure. Try to avoid super calls (use composition instead of inheritance) and procedure types (use objects and methods instead).
3 Basictypes
Use the types INTEGER, REAL and CHAR as defaults. BYTE, SHORTINT, LONGINT, SHORTREAL and SHORTCHAR should only be used if there is a strong particular reason to justify this choice. The auxiliary types are there mainly for interfacing purposes, for packing of very large structures, or for computation of extremely large integers. This rule is more important for exported interfaces than for hidden implementations, of course.
4 Font attributes
Programs are written in plain text, in the default color, with the following exceptions:
• Comments are written in italics, e.g. (* this is a comment *)
• Exported items, except for record fields and method signatures in record declarations, are written in bold, e.g. PROCEDURE Do*;
• Keywords which indicate non-local control flow are written in bold, i.e. RETURN, EXIT, and HALT
• Text parts which are currently being changed and tested may temporarily be written in a different color
5 Comments
Comments which are part of an interface description (rather than a mere implementation description) have additional asterisks, a kind of "export mark" for comments, e.g. (** guard for xyz command **)
6 Semicolons
Semicolons are used to separate statements, not to terminate statements. This means that there should be no superfluous semicolons.
Good
IF done THEN
Print(result)
END
Bad
IF done THEN
Print(result);
END
7 Dereferencing
The dereferencing operator ^ should be left out wherever possible.
Good
h.next := p.prev.next
Bad
h^.next := p^.prev^.next
8 Case
In general, each identifier starts with a small letter, except
• A module name always starts with a capital letter
• A type name always starts with a capital letter
• A procedure always starts with a capital letter, this is true for procedure constants, types, variables, parameters, and record fields.
Good
null = 0X;
DrawDot = PROCEDURE (x, y: INTEGER);
PROCEDURE Proc (i, j: INTEGER; Draw: DrawDot);
Bad
NULL = 0X;
PROCEDURE isEmpty (q: Queue): BOOLEAN;
R = RECORD
draw: DrawDot
END;
Don't use all-caps identifiers with more than one character. They should be reserved for the language.
9 Names
• A proper procedure has a verb as name, e.g. DrawDot
• A function procedure has a noun or a predicate as name, e.g. NewObject(), IsEmpty(q)
• Only declare a record type if necessary (FooDesc for each Foo are normally not needed anymore)
• Procedure names which start with the prefix Init are snappy, i.e., they have an effect only when called for the first time. If called a second time, a snappy procedure either does nothing, or it halts. In contrast, a procedure which sets some state and may be called several times starts with the prefix Set.
Examples
PROCEDURE InitDir (dir: Directory);
PROCEDURE (p: Port) Init (unit, colors: LONGINT);
• Guard procedures have the same name as the guarded command, except that they have a Guard suffix appended.
Example
PROCEDURE PasteChar;
PROCEDURE PasteCharGuard (VAR par: Dialog.Par);
10 White space
• A new indentation level is realized by adding one further tabulator character
• Between lists of symbols, between actual parameters, and between operators a single space is inserted
Good
VAR a, b, c: INTEGER;
DrawRect(l, t, r, b);
a := i * 8 + j - m[i, j];
Bad
VAR a,b,c: INTEGER;
DrawRect(l,t,r,b);
a:=b;
a := i*8 + j - m[i,j];
• There is a space between a procedure name (or its export mark) and the parameter list in a declaration, but not in a call
Good
PROCEDURE DrawDot* (x, y: INTEGER);
DrawDot(3, 5);
Bad
PROCEDURE DrawDot*(x, y: INTEGER);
DrawDot (3, 5);
• Opening and closing keywords are either aligned or on the same line
• IMPORT, CONST, TYPE, VAR, PROCEDURE sections are one level further indented than the outer level.
• LOOP statements are never on one line
• PROCEDURE X and END X are always aligned
• If the whole construct does not fit on one line, there is never a statement or a type declaration after a keyword
• The contents of IF, WHILE, REPEAT, LOOP, FOR, CASE constructs is one level further indented if it does not fit on one line.
Good
IF expr THEN S0 ELSE S1 END;
REPEAT S0 UNTIL expr;
WHILE expr DO S0 END;
IF expr THEN
S0
ELSE
S1
END;
REPEAT
S0
UNTIL expr;
LOOP
S0;
IF expr THEN EXIT END;
S1
END;
i := 0; WHILE i # 15 DO DrawDot(a, i); INC(i) END;
TYPE View = POINTER TO RECORD (Views.ViewDesc) END;
IMPORT Views, Containers,
TextModels, TextViews;
VAR a, b: INTEGER;
s: TextMappers.Scanner;
Bad
IF expr THEN S0
ELSE S1 END;
PROCEDURE P;
BEGIN ... END P;
BEGIN i := 0;
j := a + 2;
...
REPEAT i := 0;
j := a + 2;
...
11 Example
MODULE StdExample;
IMPORT Models, Views, Controllers;
CONST null = 0X;
TYPE
View* = POINTER TO RECORD (Views.View)
a*, b*: INTEGER
END;
VAR view-: View;
PROCEDURE Calculate* (x, y: INTEGER);
VAR area: LONGINT;
PROCEDURE IsOdd (x: INTEGER): BOOLEAN;
BEGIN
RETURN ODD(x)
END IsOdd;
BEGIN
area := x * y;
IF IsOdd(area) THEN area := 1000 END
END Calculate;
BEGIN
Calculate(7, 9)
END StdExample.
12 Open Source Header
Modules published under the The 2-Clause BSD License include a header text along the lines of the following template.
(**
project = "BlackBox 2.0"
organization = "Oberon microsystems, ..."
contributors = "Contributors, ..."
version = "System/Rsrc/About"
copyright = "System/Rsrc/About"
license = "The 2-Clause BSD License"
changes = "
- YYYYMMDD, nn, ...
"
issues = "
- ...
"
**)
| Docu/BB-Rules.odc |
BlackBox Contributors
BlackBox is based on the foundation laid at ETH Zrich by the professors Niklaus Wirth and Jrg Gutknecht (Oberon language and system), Hanspeter Mssenbck (Oberon-2 extensions) and several former research assistants, e.g., Rgis Crelier, Josef Templ and Stefan Ludwig. At Oberon microsystems, the following (current or former) employees have contributed to BlackBox:
- Beat Heeb
- Cuno Pfister
- Clemens Szyperski
- Thomas Amberg
- Daniel Diez
- Christian Di Giorgio
- Marc Frei
- Dominik Gruntz
- Matthias Hausner
- Stephan Koch
- Ivan Posva
- Bengt Rutisson
- Wolfgang Weck
- Jrg Wullschleger
The following members of the BlackBox community have contributed to BlackBox:
- Werner Bossert
- Werner Braun
- Chris Burrows
- Robert D. Campbell
- Oleg N. Cher
- Marco Ciot
- Doug Danforth
- Ivan Denisov
- Koen Desaeger
- Ilya Ermakov
- Ivan Goryachev
- Alexander Iljin
- Boris Ilov
- Ivan Kuzmitski
- Wenying Luo (Luowy)
- Gerhard Marent
- Grard Meunier
- Rainer Neubauer
- Katarzyna Regent Nguyen
- Roman Miro (Romiras)
- Manuel Martn Snchez
- Wojtek Skulski
- Dmitry Solomennikov
- Eugene Temirgaleev
- Josef Templ
- Andrew Thomas
- Fyodor Tkachov
- Bernhard Treutwein
- Igor Dehtyarenko (Trurl)
- Eric Wehrli
- Mathieu Westerweele
- Helmut Zinn
- Anton Dmitriev
- Peter Kushnir
(We hope that this list is reasonably complete at least for the more recent releases of BlackBox, otherwise we apologize.) | Docu/Contributors.odc |
Component Pascal Language Report
Copyright 1994-2013 by Oberon microsystems, Inc., Switzerland.
All rights reserved. No part of this publication may be reproduced in any form or by any means, without prior written permission by Oberon microsystems except for the free electronic distribution of the unmodified document.
Oberon microsystems, Inc.
Technoparkstrasse 1
CH-8005 Zrich
Switzerland
Oberon is a trademark of Prof. Niklaus Wirth.
Component Pascal is a trademark of Oberon microsystems, Inc.
All other trademarks and registered trademarks belong to their respective owners.
Authors
Oberon microsystems, Inc.
March 2001, last update October 2006
Authors of Oberon-2 report
H. Mssenbck, N. Wirth
Institut fr Computersysteme, ETH Zrich
October 1993
Author of Oberon report
N. Wirth
Institut fr Computersysteme, ETH Zrich
1987
Contents
1. Introduction
2. Syntax
3. VocabularyandRepresentation
4. DeclarationsandScopeRules
5. ConstantDeclarations
6. TypeDeclarations
6.1 BasicTypes
6.2 ArrayTypes
6.3 RecordTypes
6.4 PointerTypes
6.5 ProcedureTypes
6.6 StringTypes
7. VariableDeclarations
8. Expressions
8.1 Operands
8.2 Operators
9. Statements
9.1 Assignments
9.2 ProcedureCalls
9.3 StatementSequences
9.4 IfStatements
9.5 CaseStatements
9.6 WhileStatements
9.7 RepeatStatements
9.8 ForStatements
9.9 LoopStatements
9.10 ReturnandExitStatements
9.11 WithStatements
10. ProcedureDeclarations
10.1 FormalParameters
10.2 Methods
10.3 PredeclaredProcedures
10.4 Finalization
11. Modules
AppendixA: DefinitionofTerms
AppendixB: SyntaxofComponentPascal
AppendixC: DomainsofBasicTypes
AppendixD: MandatoryRequirementsforEnvironment
1. Introduction
Component Pascal is Oberon microsystems' refinement of the Oberon-2 language. Oberon microsystems thanks H. Mssenbck and N. Wirth for the friendly permission to use their Oberon-2 report as basis for this document.
Component Pascal is a general-purpose language in the tradition of Pascal, Modula-2, and Oberon. Its most important features are block structure, modularity, separate compilation, static typing with strong type checking (also across module boundaries), type extension with methods, dynamic loading of modules, and garbage collection.
Type extension makes Component Pascal an object-oriented language. An object is a variable of an abstract data type consisting of private data (its state) and procedures that operate on this data. Abstract data types are declared as extensible records. Component Pascal covers most terms of object-oriented languages by the established vocabulary of imperative languages in order to minimize the number of notions for similar concepts.
Complete type safety and the requirement of a dynamic object model make Component Pascal a component-oriented language.
This report is not intended as a programmer's tutorial. It is intentionally kept concise. Its function is to serve as a reference for programmers. What remains unsaid is mostly left so intentionally, either because it can be derived from stated rules of the language, or because it would require to commit the definition when a general commitment appears as unwise.
Appendix A defines some terms that are used to express the type checking rules of Component Pascal. Where they appear in the text, they are written in italics to indicate their special meaning (e.g. the same type).
It is recommended to minimize the use of procedure types and super calls, since they are considered obsolete. They are retained for the time being, in order to simplify the use of existing Oberon-2 code. Support for these features may be reduced in later product releases.
2. Syntax
An extended Backus-Naur formalism (EBNF) is used to describe the syntax of Component Pascal: Alternatives are separated by |. Brackets [ and ] denote optionality of the enclosed expression, and braces { and } denote its repetition (possibly 0 times). Ordinary parentheses ( and ) are used to group symbols if necessary. Non-terminal symbols start with an upper-case letter (e.g., Statement). Terminal symbols either start with a lower-case letter (e.g., ident), or are written all in upper-case letters (e.g., BEGIN), or are denoted by strings (e.g., ":=").
3. Vocabulary and Representation
The representation of (terminal) symbols in terms of characters is defined using the 16-bit Unicode character set, which includes ISO8859-1 (the Latin‑1extensionoftheASCIIcharacterset) as the first 256 characters. Symbols are identifiers, numbers, strings, operators, and delimiters. The following lexical rules must be observed: Blanks and line breaks must not occur within symbols (except in comments, and blanks in strings). They are ignored unless they are essential to separate two consecutive symbols. Capital and lower-case letters are considered as distinct.
1. Identifiers are sequences of letters, digits, and underscores. The first character must not be a digit.
ident = (letter | "_") {letter | "_" | digit}.
letter = "A" .. "Z" | "a" .. "z" | UnicodeLetter.
digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9".
Examples: x Scan Oberon2 GetSymbol firstLetter π
2. Numbers are (unsigned) integer or real constants. The type of an integer constant is INTEGER if the constant value belongs to INTEGER, or LONGINT otherwise (see 6.1). If the constant is specified with the suffix 'H' or 'L', the representation is hexadecimal, otherwise the representation is decimal. The suffix 'H' is used to specify 32-bit constants in the range -2147483648 .. 2147483647. At most 8 significant hex digits are allowed. The suffix 'L' is used to specify 64-bit constants.
A real number always contains a decimal point. Optionally it may also contain a decimal scale factor. The letter E means "times ten to the power of". A real number is always of type REAL.
number = integer | real.
integer = digit {digit} | digit {hexDigit} ( "H" | "L" ).
real = digit {digit} "." {digit} [ScaleFactor].
ScaleFactor = "E" ["+" | "-"] digit {digit}.
hexDigit = digit | "A" | "B" | "C" | "D" | "E" | "F".
Examples:
1234567 INTEGER 1234567
0DH INTEGER 13
12.3 REAL 12.3
4.567E8 REAL 456700000
0FFFF0000H INTEGER -65536
0FFFF0000L LONGINT 4294901760
3. Character constants are denoted by the ordinal number of the character in hexadecimal notation followed by the letter X.
character = digit {hexDigit} "X".
4. Strings are sequences of characters enclosed in single (') or double (") quote marks. The opening quote must be the same as the closing quote and must not occur within the string. The number of characters in a string is called its length. A string of length 1 can be used wherever a character constant is allowed and vice versa. Characters in string constants are allowed to be Unicode (16 bit) characters.
string = ' " ' {char} ' " ' | " ' " {char} " ' ".
Examples: "Component Pascal" "Don't worry!" "x" "αβ"
5. Operators and delimiters are the special characters, character pairs, or reserved words listed below. The reserved words consist exclusively of capital letters and cannot be used as identifiers.
+ := ABSTRACT EXTENSIBLE POINTER
- ^ ARRAY FOR PROCEDURE
* = BEGIN IF RECORD
/ # BY IMPORT REPEAT
~ < CASE IN RETURN
& > CLOSE IS THEN
. <= CONST LIMITED TO
, >= DIV LOOP TYPE
; .. DO MOD UNTIL
| : ELSE MODULE VAR
$ ELSIF NIL WHILE
( ) EMPTY OF WITH
[ ] END OR
{ } EXIT OUT
6. Comments may be inserted between any two symbols in a program. They are arbitrary character sequences opened by the bracket (* and closed by *). Comments may be nested. They do not affect the meaning of a program.
4. Declarations and Scope Rules
Every identifier occurring in a program must be introduced by a declaration, unless it is a predeclared identifier. Declarations also specify certain permanent properties of an object, such as whether it is a constant, a type, a variable, or a procedure. The identifier is then used to refer to the associated object.
The scope of an object x extends textually from the point of its declaration to the end of the block (module, procedure, or record) to which the declaration belongs and hence to which the object is local. It excludes the scopes of equally named objects which are declared in nested blocks. The scope rules are:
1. No identifier may denote more than one object within a given scope (i.e., no identifier may be declared twice in a block);
2. An object may only be referenced within its scope;
3. A declaration of a type T containing references to another type T1 may occur at a point where T1 is still unknown. The declaration of T1 must follow in the same block to which T is local;
4. Identifiers denoting record fields (see 6.3) or methods (see 10.2) are valid in record designators only.
An identifier declared in a module block may be followed by an export mark (" * " or " - ") in its declaration to indicate that it is exported. An identifier x exported by a module M may be used in other modules, if they import M (see Ch.11). The identifier is then denoted as M.x in these modules and is called a qualified identifier. Variables and record fields marked with " - " in their declaration are read-only (variables and fields) or implement-only (methods) in importing modules.
Qualident = [ident "."] ident.
IdentDef = ident [" * " | " - "].
The following identifiers are predeclared; their meaning is defined in the indicated sections:
ABS (10.3) INF (6.1)
ANYPTR (6.4) INTEGER (6.1)
ANYREC (6.3) LEN (10.3)
ASH (10.3) LONG (10.3)
ASSERT (10.3) LONGINT (6.1)
BITS (10.3) MAX (10.3)
BOOLEAN (6.1) MIN (10.3)
BYTE (6.1) NEW (10.3)
CAP (10.3) ODD (10.3)
CHAR (6.1) ORD (10.3)
CHR (10.3) REAL (6.1)
DEC (10.3) SET (6.1)
ENTIER (10.3) SHORT (10.3)
EXCL (10.3) SHORTCHAR (6.1)
FALSE (6.1) SHORTINT (6.1)
HALT (10.3) SHORTREAL (6.1)
INC (10.3) SIZE (10.3)
INCL (10.3) TRUE (6.1)
5. Constant Declarations
A constant declaration associates an identifier with a constant value.
ConstantDeclaration = IdentDef "=" ConstExpression.
ConstExpression = Expression.
A constant expression is an expression that can be evaluated by a mere textual scan without actually executing the program. Its operands are constants (Ch.8) or predeclared functions (Ch.10.3) that can be evaluated at compile time. Examples of constant declarations are:
N = 100
limit = 2*N - 1
fullSet = {MIN(SET) .. MAX(SET)}
6. Type Declarations
A data type determines the set of values which variables of that type may assume, and the operators that are applicable. A type declaration associates an identifier with a type. In the case of structured types (arrays and records) it also defines the structure of variables of this type. A structured type cannot contain itself.
TypeDeclaration = IdentDef "=" Type.
Type = Qualident | ArrayType | RecordType | PointerType | ProcedureType.
Examples:
Table = ARRAY N OF REAL
Tree = POINTER TO Node
Node = EXTENSIBLE RECORD
key : INTEGER;
left, right: Tree
END
CenterTree = POINTER TO CenterNode
CenterNode = RECORD (Node)
width: INTEGER;
subnode: Tree
END
Object = POINTER TO ABSTRACT RECORD END;
Function = PROCEDURE (x: INTEGER): INTEGER
6.1 Basic Types
The basic types are denoted by predeclared identifiers. The associated operators are defined in 8.2 and the predeclared function procedures in 10.3. The values of the given basic types are the following:
1. BOOLEAN the truth values TRUE and FALSE
2. SHORTCHAR the characters of the Latin‑1character set (0X .. 0FFX)
3. CHAR the characters of the Unicode character set (0X .. 0FFFFX)
4. BYTE the integers between MIN(BYTE) and MAX(BYTE)
5. SHORTINT the integers between MIN(SHORTINT) and MAX(SHORTINT)
6. INTEGER the integers between MIN(INTEGER) and MAX(INTEGER)
7. LONGINT the integers between MIN(LONGINT) and MAX(LONGINT)
8. SHORTREAL the real numbers between MIN(SHORTREAL) and MAX(SHORTREAL), the value INF
9. REAL the real numbers between MIN(REAL) and MAX(REAL), the value INF
10. SET the sets of integers between 0 and MAX(SET)
Types 4 to 7 are integer types, types 8 and 9 are real types, and together they are called numeric types. They form a hierarchy; the larger type includes (the values of) the smaller type:
REAL >= SHORTREAL >= LONGINT >= INTEGER
>= SHORTINT >= BYTE
Types 2 and 3 are character types with the type hierarchy:
CHAR >= SHORTCHAR
6.2 Array Types
An array is a structure consisting of a number of elements which are all of the same type, called the element type. The number of elements of an array is called its length. The elements of the array are designated by indices, which are integers between 0 and the length minus 1.
ArrayType = ARRAY [Length {"," Length}] OF Type.
Length = ConstExpression.
A type of the form
ARRAY L0, L1, ..., Ln OF T
is understood as an abbreviation of
ARRAY L0 OF
ARRAY L1 OF
...
ARRAY Ln OF T
Arrays declared without length are called open arrays. They are restricted to pointer base types (see 6.4), element types of open array types, and formal parameter types (see 10.1). Examples:
ARRAY 10, N OF INTEGER
ARRAY OF CHAR
6.3 Record Types
A record type is a structure consisting of a fixed number of elements, called fields, with possibly different types. The record type declaration specifies the name and type of each field. The scope of the field identifiers extends from the point of their declaration to the end of the record type, but they are also visible within designators referring to elements of record variables (see 8.1). If a record type is exported, field identifiers that are to be visible outside the declaring module must be marked. They are called public fields; unmarked elements are called private fields.
RecordType = RecAttributes RECORD ["("BaseType")"]
FieldList {";" FieldList} END.
RecAttributes = [ABSTRACT | EXTENSIBLE | LIMITED].
BaseType = Qualident.
FieldList = [IdentList ":" Type].
IdentList = IdentDef {"," IdentDef}.
The usage of a record type is restricted by the presence or absence of one of the following attributes:
ABSTRACT, EXTENSIBLE, and LIMITED.
A record type marked as ABSTRACT cannot be instantiated. No variables or fields of such a type can ever exist. Abstract types are only used as base types for other record types (see below).
Variables of a LIMITED record type can only be allocated inside the module where the record type is defined. The restriction applies to static allocation by a variable declaration (Ch. 7) as well as to dynamic allocation by the standard procedure NEW (Ch. 10.3).
Record types marked as ABSTRACT or EXTENSIBLE are extensible, i.e., a record type can be declared as an extension of such a record type. In the example
T0 = EXTENSIBLE RECORD x: INTEGER END
T1 = RECORD (T0) y: REAL END
T1 is a (direct) extension of T0 and T0 is the (direct) base type of T1 (see App. A). An extended type T1 consists of the fields of its base type and of the fields which are declared in T1. All identifiers declared in the extended record must be different from the identifiers declared in its base type record(s). The base type of an abstract record must be abstract.
Alternatively, a pointer type can be specified as the base type. The record base type of the pointer is used as the base type of the declared record in this case.
A record which is an extension of a hidden (i.e., non-exported) record type may not be exported.
Each record is implicitly an extension of the predeclared type ANYREC. ANYREC does not contain any fields and can only be used in pointer and variable parameter declarations.
Summary of attributes:
attribute extension allocate
none no yes
EXTENSIBLE yes yes
ABSTRACT yes no
LIMITED in defining module only
Examples of record type declarations:
RECORD
day, month, year: INTEGER
END
LIMITED RECORD
name, firstname: ARRAY 32 OF CHAR;
age: INTEGER;
salary: REAL
END
6.4 Pointer Types
Variables of a pointer type P assume as values pointers to variables of some type T. T is called the pointer base type of P and must be a record or array type. Pointer types adopt the extension relation of their pointer base types: if a type T1 is an extension of T, and P1 is of type POINTER TO T1, then P1 is also an extension of P.
PointerType = POINTER TO Type.
If p is a variable of type P = POINTER TO T, a call of the predeclared procedure NEW(p) (see 10.3) allocates a variable of type T in free storage. If T is a record type or an array type with fixed length, the allocation has to be done with NEW(p); if T is an n-dimensional open array type the allocation has to be done with NEW(p, e0, ..., en-1) where T is allocated with lengths given by the expressions e0, ..., en-1. In either case a pointer to the allocated variable is assigned to p. p is of type P. The referenced variable p^ (pronounced as p-referenced) is of type T. Any pointer variable may assume the value NIL, which points to no variable at all.
All fields or elements of a newly allocated record or array are cleared, which implies that all embedded pointers and procedure variables are initialized to NIL.
The predeclared type ANYPTR is defined as POINTER TO ANYREC. Any pointer to a record type is therefore an extension of ANYPTR. The procedure NEW cannot be used for variables of type ANYPTR.
6.5 Procedure Types
Variables of a procedure type T have a procedure (or NIL) as value. If a procedure P is assigned to a variable of type T, the formal parameter lists (see Ch. 10.1) of P and T must match (see App. A). P must not be a predeclared procedure or a method nor may it be local to another procedure.
ProcedureType = PROCEDURE [FormalParameters].
6.6 String Types
Values of a string type are sequences of characters terminated by a null character (0X). The length of a string is the number of characters it contains excluding the null character.
Strings are either constants or stored in an array of character type. There are no predeclared identifiers for string types because there is no need to use them in a declaration.
Constant strings which consist solely of characters in the range 0X..0FFX and strings stored in an array of SHORTCHAR are of type Shortstring, all others are of type String.
7. Variable Declarations
Variable declarations introduce variables by defining an identifier and a data type for them.
VariableDeclaration = IdentList ":" Type.
Record and pointer variables have both a static type (the type with which they are declared — simply called their type) and a dynamic type (the type of their value at run-time). For pointers and variable parameters of record type the dynamic type may be an extension of their static type. The static type determines which fields of a record are accessible. The dynamic type is used to call methods (see 10.2).
Examples of variable declarations (refer to examples in Ch. 6):
i, j, k: INTEGER
x, y: REAL
p, q: BOOLEAN
s: SET
F: Function
a: ARRAY 100 OF REAL
w: ARRAY 16 OF
RECORD
name: ARRAY 32 OF CHAR;
count: INTEGER
END
t, c: Tree
8. Expressions
Expressions are constructs denoting rules of computation whereby constants and current values of variables are combined to compute other values by the application of operators and function procedures. Expressions consist of operands and operators. Parentheses may be used to express specific associations of operators and operands.
8.1 Operands
With the exception of set constructors and literal constants (numbers, character constants, or strings), operands are denoted by designators. A designator consists of an identifier referring to a constant, variable, or procedure. This identifier may possibly be qualified by a module identifier (see Ch. 4 and 11) and may be followed by selectors if the designated object is an element of a structure.
Designator = Qualident {"." ident | "[" ExpressionList "]" | "^" |
"(" Qualident ")" | ActualParameters} [ "$" ].
ExpressionList = Expression {"," Expression}.
ActualParameters = "(" [ExpressionList] ")".
If a designates an array, then a[e] denotes that element of a whose index is the current value of the expression e. The type of e must be an integer type. A designator of the form a[e0, e1, ..., en] stands for a[e0][e1]...[en]. If r designates a record, then r.f denotes the field f of r or the method f of the dynamic type of r (Ch. 10.2). If a or r are read-only, then also a[e] and r.f are read-only.
If p designates a pointer, p^ denotes the variable which is referenced by p. The designators p^.f, p^[e], and p^$ may be abbreviated as p.f, p[e], and p$, i.e., record, array, and string selectors imply dereferencing. Dereferencing is also implied if a pointer is assigned to a variable of a record or array type (Ch. 9.1), if a pointer is used as actual parameter for a formal parameter of a record or array type (Ch. 10.1), or if a pointer is used as argument of the standard procedure LEN (Ch. 10.3).
A type guard v(T) asserts that the dynamic type of v is T (or an extension of T), i.e., program execution is aborted, if the dynamic type of v is not T (or an extension of T). Within the designator, v is then regarded as having the static type T. The guard is applicable, if
1. v is an IN or VAR parameter of record type or v is a pointer to a record type, and if
2. T is an extension of the static type of v
If the designated object is a constant or a variable, then the designator refers to its current value. If it is a procedure, the designator refers to that procedure unless it is followed by a (possibly empty) parameter list in which case it implies an activation of that procedure and stands for the value resulting from its execution. The actual parameters must correspond to the formal parameters as in proper procedure calls (see 10.1).
If a designates an array of character type, then a$ denotes the null terminated string contained in a. It leads to a run-time error if a does not contain a 0X character. The $ selector is applied implicitly if a is used as an operand of the concatenation operator (Ch. 8.2.4), a relational operator (Ch. 8.2.5), or one of the predeclared procedures LONG and SHORT (Ch. 10.3).
Examples of designators (refer to examples in Ch.7):
i (INTEGER)
a[i] (REAL)
w[3].name[i] (CHAR)
t.left.right (Tree)
t(CenterTree).subnode (Tree)
w[i].name$ (String)
8.2 Operators
Four classes of operators with different precedences (binding strengths) are syntactically distinguished in expressions. The operator ~ has the highest precedence, followed by multiplication operators, addition operators, and relations. Operators of the same precedence associate from left to right.
For example, x-y-z stands for (x-y)-z.
Expression = SimpleExpression [Relation SimpleExpression].
SimpleExpression = ["+" | "-"] Term {AddOperator Term}.
Term = Factor {MulOperator Factor}.
Factor = Designator | number | character | string | NIL | Set |
"(" Expression ")" | "~" Factor.
Set = "{" [Element {"," Element}] "}".
Element = Expression [".." Expression].
Relation = "=" | "#" | "<" | "<=" | ">" | ">=" | IN | IS.
AddOperator = "+" | "-" | OR.
MulOperator = "*" | "/" | DIV | MOD | "&".
The available operators are listed in the following tables. Some operators are applicable to operands of various types, denoting different operations. In these cases, the actual operation is identified by the type of the operands. The operands must be expression compatible with respect to the operator (see App. A).
8.2.1 Logical operators
OR logical disjunction p OR q "if p then TRUE, else q"
& logical conjunction p & q "if p then q, else FALSE"
~ negation ~ p "not p"
These operators apply to BOOLEAN operands and yield a BOOLEAN result. The second operand of a disjunction is only evaluated if the result of the first is FALSE. The second oprand of a conjunction is only evaluated if the result of the first is TRUE.
8.2.2 Arithmetic operators
+ sum
- difference
* product
/ real quotient
DIV integer quotient
MOD modulus
The operators +, -, *, and / apply to operands of numeric types. The type of the result is REAL if the operation is a division (/) or one of the operand types is a REAL. Otherwise the result type is SHORTREAL if one of the operand types is SHORTREAL, LONGINT if one of the operand types is LONGINT, or INTEGER in any other case. If the result of a real operation is too large to be represented as a real number, it is changed to the predeclared value INF with the same sign as the original result. Note that this also applies to 1.0/0.0, but not to 0.0/0.0 which has no defined result at all and leads to a run-time error. When used as monadic operators, the operator - denotes sign inversion and + denotes the identity operation. The operators DIV and MOD apply to integer operands only. They are related by the following formulas:
x = (x DIV y) * y + (x MOD y)
0 <= (x MOD y) < y or0>=(xMODy)>y
Note:xDIVy=ENTIER(x/y)
Examples:
x y x DIV y x MOD y
5 3 1 2
-5 3 -2 1
5 -3 -2 -1
-5 -3 1 -2
Note:
(-5) DIV 3 = -2
but
-5 DIV 3 = -(5 DIV 3) = -1
8.2.3 Set operators
+ union
- difference (x - y = x * (-y))
* intersection
/ symmetric set difference (x / y = (x-y) + (y-x))
Set operators apply to operands of type SET and yield a result of type SET. The monadic minus sign denotes the complement of x, i.e., -x denotes the set of integers between 0 and MAX(SET) which are not elements of x. Set operators are not associative ((a+b)-c # a+(b-c)).
A set constructor defines the value of a set by listing its elements between curly brackets. The elements must be integers in the range 0..MAX(SET). A range a..b denotes all integers iwith i>=aandi<=b.
8.2.4 String operators
+ string concatenation
The concatenation operator applies to operands of string types. The resulting string consists of the characters of the first operand followed by the characters of the second operand. If both operands are of type Shortstring the result is of type Shortstring, otherwise the result is of type String.
8.2.5 Relations
= equal
# unequal
< less
<= less or equal
> greater
>= greater or equal
IN set membership
IS type test
Relations yield a BOOLEAN result. The relations =, #, <, <=, >, and >= apply to the numeric types, character types, and string types. The relations = and # also apply to BOOLEAN and SET, as well as to pointer and procedure types (including the value NIL). x IN s stands for "x is an element of s". x must be an integer in the range 0..MAX(SET), and s of type SET. v IS T stands for "the dynamic type of v is T (or an extension of T)" and is called a type test. It is applicable if
1. v is an IN or VAR parameter of record type or v is a pointer to a record type, and if
2. T is an extension of the static type of v
Examples of expressions (refer to examples in Ch.7):
1991 INTEGER
i DIV 3 INTEGER
~p OR q BOOLEAN
(i+j) * (i-j) INTEGER
s - {8, 9, 13} SET
i + x REAL
a[i+j] * a[i-j] REAL
(0<=i) & (i<100) BOOLEAN
t.key = 0 BOOLEAN
k IN {i..j-1} BOOLEAN
w[i].name$ <= "John" BOOLEAN
t IS CenterTree BOOLEAN
9. Statements
Statements denote actions. There are elementary and structured statements. Elementary statements are not composed of any parts that are themselves statements. They are the assignment, the procedure call, the return, and the exit statement. Structured statements are composed of parts that are themselves statements. They are used to express sequencing and conditional, selective, and repetitive execution. A statement may also be empty, in which case it denotes no action. The empty statement is included in order to relax punctuation rules in statement sequences.
Statement = [ Assignment | ProcedureCall | IfStatement | CaseStatement |
WhileStatement | RepeatStatement |
ForStatement | LoopStatement | WithStatement |
EXIT | RETURN [Expression] ].
9.1 Assignments
Assignments replace the current value of a variable by a new value specified by an expression. The expression must be assignment compatible with the variable (see App. A). The assignment operator is written as ":=" and pronounced as becomes.
Assignment = Designator ":=" Expression.
If an expression e of type Te is assigned to a variable v of type Tv, the following happens:
1. if Tv and Te are record types, all fields of that type are assigned.
2. if Tv and Te are pointer types, the dynamic type of v becomes the dynamic type of e;
3. if Tv is an array of character type and e is a string of length m < LEN(v), v[i] becomes ei for i = 0..m-1 and v[m] becomes 0X. It leads to a run-time error if m >= LEN(v).
Examples of assignments (refer to examples in Ch.7):
i := 0
p := i = j
x := i + 1
k := Log2(i+j)
F := Log2 (* see 10.1 *)
s := {2, 3, 5, 7, 11, 13}
a[i] := (x+y) * (x-y)
t.key := i
w[i+1].name := "John"
t := c
9.2 Procedure Calls
A procedure call activates a procedure. It may contain a list of actual parameters which replace the corresponding formal parameters defined in the procedure declaration (see Ch. 10). The correspondence is established by the positions of the parameters in the actual and formal parameter lists. There are two kinds of parameters: variable and value parameters.
If a formal parameter is a variable parameter, the corresponding actual parameter must be a designator denoting a variable. If it denotes an element of a structured variable, the component selectors are evaluated when the formal/actual parameter substitution takes place, i.e., before the execution of the procedure. If a formal parameter is a value parameter, the corresponding actual parameter must be an expression. This expression is evaluated before the procedure activation, and the resulting value is assigned to the formal parameter (see also 10.1).
ProcedureCall = Designator [ActualParameters].
Examples:
WriteInt(i*2+1) (* see 10.1 *)
INC(w[k].count)
t.Insert("John") (* see 11 *)
9.3 Statement Sequences
Statement sequences denote the sequence of actions specified by the component statements which are separated by semicolons.
StatementSequence = Statement {";" Statement}.
9.4 If Statements
IfStatement =
IF Expression THEN StatementSequence
{ELSIF Expression THEN StatementSequence}
[ELSE StatementSequence]
END.
If statements specify the conditional execution of guarded statement sequences. The Boolean expression preceding a statement sequence is called its guard. The guards are evaluated in sequence of occurrence, until one evaluates to TRUE, whereafter its associated statement sequence is executed. If no guard is satisfied, the statement sequence following the symbol ELSE is executed, if there is one.
Example:
IF (ch >= "A") & (ch <= "Z") THEN ReadIdentifier
ELSIF (ch >= "0") & (ch <= "9") THEN ReadNumber
ELSIF (ch = "'") OR (ch = '"') THEN ReadString
ELSE SpecialCharacter
END
9.5 Case Statements
Case statements specify the selection and execution of a statement sequence according to the value of an expression. First the case expression is evaluated, then that statement sequence is executed whose case label list contains the obtained value. The case expression must be of an integer or character type that includes the values of all case labels. Case labels are constants, and no value must occur more than once. If the value of the expression does not occur as a label of any case, the statement sequence following the symbol ELSE is selected, if there is one, otherwise the program is aborted.
CaseStatement = CASE Expression OF Case {"|" Case}
[ELSE StatementSequence] END.
Case = [CaseLabelList ":" StatementSequence].
CaseLabelList = CaseLabels {"," CaseLabels}.
CaseLabels = ConstExpression [".." ConstExpression].
Example:
CASE ch OF
"A" .. "Z": ReadIdentifier
| "0" .. "9": ReadNumber
| "'", '"': ReadString
ELSE SpecialCharacter
END
9.6 While Statements
While statements specify the repeated execution of a statement sequence while the Boolean expression (its guard) yields TRUE. The guard is checked before every execution of the statement sequence.
WhileStatement = WHILE Expression DO StatementSequence END.
Examples:
WHILE i > 0 DO i := i DIV 2; k := k + 1 END
WHILE (t # NIL) & (t.key # i) DO t := t.left END
9.7 Repeat Statements
A repeat statement specifies the repeated execution of a statement sequence until a condition specified by a Boolean expression is satisfied. The statement sequence is executed at least once.
RepeatStatement = REPEAT StatementSequence UNTIL Expression.
9.8 For Statements
A for statement specifies the repeated execution of a statement sequence while a progression of values is assigned to an integer variable called the control variable of the for statement.
ForStatement =
FOR ident ":=" Expression TO Expression [BY ConstExpression]
DO StatementSequence END.
The statement
FOR v := beg TO end BY step DO statements END
is equivalent to
temp := end; v := beg;
IF step > 0 THEN
WHILE v <= temp DO statements; INC(v, step) END
ELSE
WHILE v >= temp DO statements; INC(v, step) END
END
temp has the same type as v. step must be a nonzero constant expression. If step is not specified, it is assumed to be 1.
Examples:
FOR i := 0 TO 79 DO k := k + a[i] END
FOR i := 79 TO 1 BY -1 DO a[i] := a[i-1] END
9.9 Loop Statements
A loop statement specifies the repeated execution of a statement sequence. It is terminated upon execution of an exit statement within that sequence (see 9.10).
LoopStatement = LOOP StatementSequence END.
Example:
LOOP
ReadInt(i);
IF i < 0 THEN EXIT END;
WriteInt(i)
END
Loop statements are useful to express repetitions with several exit points or cases where the exit condition is in the middle of the repeated statement sequence.
9.10 Return and Exit Statements
A return statement indicates the termination of a procedure. It is denoted by the symbol RETURN, followed by an expression if the procedure is a function procedure. The type of the expression must be assignment compatible (see App. A) with the result type specified in the procedure heading (see Ch.10).
Function procedures require the presence of a return statement indicating the result value. In proper procedures, a return statement is implied by the end of the procedure body. Any explicit return statement therefore appears as an additional (probably exceptional) termination point.
An exit statement is denoted by the symbol EXIT. It specifies termination of the enclosing loop statement and continuation with the statement following that loop statement. Exit statements are contextually, although not syntactically associated with the loop statement which contains them.
9.11 With Statements
With statements execute a statement sequence depending on the result of a type test and apply a type guard to every occurrence of the tested variable within this statement sequence.
WithStatement = WITH [ Guard DO StatementSequence ]
{"|" [ Guard DO StatementSequence ] }
[ELSE StatementSequence] END.
Guard = Qualident ":" Qualident.
If v is a variable parameter of record type or a pointer variable, and if it is of a static type T0, the statement
WITH v: T1 DO S1 | v: T2 DO S2 ELSE S3 END
has the following meaning: if the dynamic type of v is T1, then the statement sequence S1 is executed where v is regarded as if it had the static type T1; else if the dynamic type of v is T2, then S2 is executed where v is regarded as if it had the static type T2; else S3 is executed. T1 and T2 must be extensions of T0. If no type test is satisfied and if an else clause is missing the program is aborted.
Example:
WITH t: CenterTree DO i := t.width; c := t.subnode END
10. Procedure Declarations
A procedure declaration consists of a procedure heading and a procedure body. The heading specifies the procedure identifier and the formal parameters. For methods it also specifies the receiver parameter and the attributes (see 10.2). The body contains declarations and statements. The procedure identifier is repeated at the end of the procedure declaration.
There are two kinds of procedures: proper procedures and function procedures. The latter are activated by a function designator as a constituent of an expression and yield a result that is an operand of the expression. Proper procedures are activated by a procedure call. A procedure is a function procedure if its formal parameters specify a result type. The body of a function procedure must contain a return statement which defines its result.
All constants, variables, types, and procedures declared within a procedure body are local to the procedure. Since procedures may be declared as local objects too, procedure declarations may be nested. The call of a procedure within its declaration implies recursive activation.
Local variables whose types are pointer types or procedure types are initialized to NIL before the body of the procedure is executed.
Objects declared in the environment of the procedure are also visible in those parts of the procedure in which they are not concealed by a locally declared object with the same name.
ProcedureDeclaration = ProcedureHeading [";" ProcedureBody ident ].
ProcedureHeading = PROCEDURE [Receiver] IdentDef
[FormalParameters] MethAttributes.
ProcedureBody = DeclarationSequence
[BEGIN StatementSequence] END.
DeclarationSequence = {CONST {ConstantDeclaration ";"} |
TYPE {TypeDeclaration ";"} |
VAR {VariableDeclaration ";"} }
{ProcedureDeclaration ";" | ForwardDeclaration ";"}.
ForwardDeclaration = PROCEDURE " ^ " [Receiver] IdentDef
[FormalParameters] MethAttributes.
If a procedure declaration specifies a receiver parameter, the procedure is considered to be a method of the type of the receiver (see 10.2). A forward declaration serves to allow forward references to a procedure whose actual declaration appears later in the text. The formal parameter lists of the forward declaration and the actual declaration must match (see App. A) and the names of corresponding parameters must be equal.
10.1 Formal Parameters
Formal parameters are identifiers declared in the formal parameter list of a procedure. They correspond to actual parameters specified in the procedure call. The correspondence between formal and actual parameters is established when the procedure is called. There are two kinds of parameters, value and variable parameters, the latter indicated in the formal parameter list by the presence of one of the keywords VAR, IN, or OUT. Value parameters are local variables to which the value of the corresponding actual parameter is assigned as an initial value. Variable parameters correspond to actual parameters that are variables, and they stand for these variables. Variable parameters can be used for input only (keyword IN), output only (keyword OUT), or input and output (keyword VAR). IN can only be used for array and record parameters. Inside the procedure, input parameters are read-only. Like local variables, output parameters of pointer types and procedure types are initialized to NIL. Other output parameters must be considered as undefined prior to the first assignment in the procedure. The scope of a formal parameter extends from its declaration to the end of the procedure block in which it is declared. A function procedure without parameters must have an empty parameter list. It must be called by a function designator whose actual parameter list is empty too. The result type of a procedure can be neither a record nor an array.
FormalParameters = "(" [FPSection {";" FPSection}] ")" [":" Type].
FPSection = [VAR | IN | OUT] ident {"," ident} ":" Type.
Let f be the formal parameter and a the corresponding actual parameter. If f is an open array, then a must be array compatible to f and the lengths of f are taken from a. Otherwise a must be parameter compatible to f (see App. A)
Examples of procedure declarations:
PROCEDURE ReadInt (OUT x: INTEGER);
VAR i: INTEGER; ch: CHAR;
BEGIN
i := 0; Read(ch);
WHILE ("0" <= ch) & (ch <= "9") DO
i := 10 * i + (ORD(ch) - ORD("0")); Read(ch)
END;
x := i
END ReadInt
PROCEDURE WriteInt (x: INTEGER); (* 0 <= x < 100000 *)
VAR i: INTEGER; buf: ARRAY 5 OF INTEGER;
BEGIN
i := 0;
REPEAT buf[i] := x MOD 10; x := x DIV 10; INC(i) UNTIL x = 0;
REPEAT DEC(i); Write(CHR(buf[i] + ORD("0"))) UNTIL i = 0
END WriteInt
PROCEDURE WriteString (IN s: ARRAY OF CHAR);
VAR i: INTEGER;
BEGIN
i := 0; WHILE (i < LEN(s)) & (s[i] # 0X) DO Write(s[i]); INC(i) END
END WriteString
PROCEDURE Log2 (x: INTEGER): INTEGER;
VAR y: INTEGER; (* assume x > 0 *)
BEGIN
y := 0; WHILE x > 1 DO x := x DIV 2; INC(y) END;
RETURN y
END Log2
PROCEDURE Modify (VAR n: Node);
BEGIN
INC(n.key)
END Modify
10.2 Methods
Globally declared procedures may be associated with a record type declared in the same module. The procedures are said to be methods bound to the record type. The binding is expressed by the type of the receiver in the heading of a procedure declaration. The receiver may be either a VAR or IN parameter of record type T or a value parameter of type POINTER TO T (where T is a record type). The method is bound to the type T and is considered local to it.
ProcedureHeading = PROCEDURE [Receiver] IdentDef
[FormalParameters] MethAttributes.
Receiver = "(" [VAR | IN] ident ":" ident ")".
MethAttributes = ["," NEW] ["," (ABSTRACT | EMPTY | EXTENSIBLE)].
If a method M is bound to a type T0, it is implicitly also bound to any type T1 which is an extension of T0. However, if a method M' (with the same name as M) is declared to be bound to T1, this overrides the binding of M to T1. M' is considered a redefinition of M for T1. The formal parameters of M and M' must match,except if M is a function returning a pointer type. In the latter case, the function result type of M' must be an extension ofthefunctionresulttypeofM(covariance) (see App. A). If M and T1 are exported (see Chapter 4) M' must be exported too.
If M is not exported, M' must not be exported either. If M and M' are exported, they must use the same export marks.
The following attributes are used to restrict and document the desired usage of a method:
NEW, ABSTRACT, EMPTY, and EXTENSIBLE.
NEW must be used on all newly introduced methods and must not be used on redefining methods. The attribute helps to detect inconsistencies between a record and its extension when one of the two is changed without updating the other.
Abstract and empty method declarations consist of a procedure header only. Abstract methods are never called. A record containing abstract methods must be abstract. A method redefined by an abstract method must be abstract. An abstract method of an exported record must be exported. Calling an empty method has no effect. Empty methods may not return function results and may not have OUT parameters. A record containing new empty methods must be extensible or abstract. A method redefined by an empty method must be empty or abstract. Abstract or empty methods are usually redefined (implemented) in a record extension. They may not be called via super calls. A concrete (nonabstract) record extending an abstract record must implement all abstract methods bound to the base record.
Concrete methods (which contain a procedure body) are either extensible or final (no attribute). A final method cannot be redefined in a record extension. A record containing extensible methods must be extensible or abstract.
If v is a designator and M is a method, then v.M denotes that method M which is bound to the dynamic type of v. Note, that this may be a different method than the one bound to the static type of v. v is passed to M's receiver according to the parameter passing rules specified in Chapter 10.1.
If r is a receiver parameter declared with type T, r.M^ denotes the method M bound to the base type of T (super call). In a forward declaration of a method the receiver parameter must be of the same type as in the actual method declaration. The formal parameter lists of both declarations must match (App. A) and the names of corresponding parameters must be equal.
Methods marked with " - " are "implement-only" exported. Such a method can be redefined in any importing module but can only be called within the module containing the method declaration. (Currently, the compiler also allows super calls to implement-only methods outside of their defining module. This is a temporary feature to make migration easier.)
Examples:
PROCEDURE (t: Tree) Insert (node: Tree), NEW, EXTENSIBLE;
VAR p, father: Tree;
BEGIN p := t;
REPEAT father := p;
IF node.key = p.key THEN RETURN END;
IF node.key < p.key THEN p := p.left ELSE p := p.right END
UNTIL p = NIL;
IF node.key < father.key THEN
father.left := node
ELSE
father.right := node
END;
node.left := NIL; node.right := NIL
END Insert
PROCEDURE (t: CenterTree) Insert (node: Tree); (* redefinition *)
BEGIN
WriteInt(node(CenterTree).width);
t.Insert^ (node) (* calls the Insert method of Tree *)
END Insert
PROCEDURE (obj: Object) Draw (w: Window), NEW, ABSTRACT
PROCEDURE (obj: Object) Notify (e: Event), NEW, EMPTY
10.3 Predeclared Procedures
The following table lists the predeclared procedures. Some are generic procedures, i.e., they apply to several types of operands. v stands for a variable, x and y for expressions, and T for a type. The first matching line gives the correct result type.
Function procedures
Name Argument type Result type Function
ABS(x) <= INTEGER INTEGER absolute value
real type, LONGINT type of x
ASH(x, y) x: <= INTEGER INTEGER arithmetic shift (x * 2^y)
x: LONGINT LONGINT
y: integer type
BITS(x) INTEGER SET {i | ODD(x DIV 2^i)}
CAP(x) character type type of x x is a Latin-1 letter:
corresponding capital letter
CHR(x) integer type CHAR character with ordinal number
x
ENTIER(x) real type LONGINT largest integer not greater
than x
LEN(v, x) v: array; x: integer INTEGER length of v in dimension x
constant (first dimension = 0)
LEN(v) array type INTEGER equivalent to LEN(v, 0)
String INTEGER length of string
(not counting 0X)
LONG(x) BYTE SHORTINT identity
SHORTINT INTEGER
INTEGER LONGINT
SHORTREAL REAL
SHORTCHAR CHAR
Shortstring String
MAX(T) T = basic type T maximum value of type T
T = SET INTEGER maximum element of a set
MAX(x, y) <= INTEGER INTEGER the larger value of x and y
integer type LONGINT
<= SHORTREAL SHORTREAL
numeric type REAL
SHORTCHAR SHORTCHAR
character type CHAR
MIN(T) T = basic type T minimum value of type T
T = SET INTEGER 0
MIN(x, y) <= INTEGER INTEGER the smaller of x and y
integer type LONGINT
<= SHORTREAL SHORTREAL
numeric type REAL
SHORTCHAR SHORTCHAR
character type CHAR
ODD(x) integer type BOOLEAN x MOD 2 = 1
ORD(x) CHAR INTEGER ordinal number of x
SHORTCHAR SHORTINT ordinal number of x
SET INTEGER (SUM i: i IN x: 2^i)
SHORT(x) LONGINT INTEGER identity
INTEGER SHORTINT identity
SHORTINT BYTE identity
REAL SHORTREAL identity (truncation possible)
CHAR SHORTCHAR projection
String Shortstring projection
SIZE(T) any type INTEGER number of bytes required by T
SIZE cannot be used in constant expressions because its value depends on the actual compiler implementation.
Proper procedures
Name Argument types Function
ASSERT(x) x: Boolean expression terminate program execution if not x
ASSERT(x, n) x: Boolean expression; terminate program execution
n: integer constant if not x
DEC(v) integer type v := v - 1
DEC(v, n) v, n: integer type v := v - n
EXCL(v, x) v: SET; x: integer type, v := v - {x}
0 <= x <= MAX(SET)
HALT(n) integer constant terminate program execution
INC(v) integer type v := v + 1
INC(v, n) v, n: integer type v := v + n
INCL(v, x) v: SET; x: integer type, v := v + {x}
0 <= x <= MAX(SET)
NEW(v) pointer to record or allocate v ^
fixed array
NEW(v, x0, ..., xn) v: pointer to open array; allocate v ^ with
xi: integer type lengths x0.. xn
In ASSERT(x, n) and HALT(n), the interpretation of n is left to the underlying system implementation.
10.4 Finalization
A predeclared method named FINALIZE is associated with each record type as if it were declared to be bound to the type ANYREC:
PROCEDURE (a: ANYPTR) FINALIZE-, NEW, EMPTY;
The FINALIZE procedure can be implemented for any pointer type. The method is called at some unspecified time after an object of that type (or a base type of it) has become unreachable via other pointers (not globally anchored anymore) and before the object is deallocated.
It is not recommended to re-anchor an object in its finalizer and the finalizer is not called again when the object repeatedly becomes unreachable. Multiple unreachable objects are finalized in an unspecified order.
11. Modules
A module is a collection of declarations of constants, types, variables, and procedures, together with a sequence of statements for the purpose of assigning initial values to the variables. A module constitutes a text that is compilable as a unit.
Module = MODULE ident ";" [ImportList] DeclarationSequence
[BEGIN StatementSequence]
[CLOSE StatementSequence] END ident ".".
ImportList = IMPORT Import {"," Import} ";".
Import = [ident ":="] ident.
The import list specifies the names of the imported modules. If a module A is imported by a module M and A exports an identifier x, then x is referred to as A.x within M. If A is imported as B := A, the object x must be referenced as B.x. This allows short alias names in qualified identifiers. A module must not import itself. Identifiers that are to be exported (i.e., that are to be visible in client modules) must be marked by an export mark in their declaration (see Chapter 4).
The statement sequence following the symbol BEGIN is executed when the module is added to a system (loaded), which is done after the imported modules have been loaded. It follows that cyclic import of modules is illegal. Individual exported procedures can be activated from the system, and these procedures serve as commands .
Variables declared in a module are cleared prior to the execution of the module body. This implies that all pointer or procedure typed variables are initialized to NIL.
The statement sequence following the symbol CLOSE is executed when the module is removed from the system.
Example:
MODULE Trees; (* exports: Tree, Node, Insert, Search, Write, Init *)
IMPORT StdLog;
TYPE
Tree* = POINTER TO Node;
Node* = RECORD (* exports read-only: Node.name *)
name-: POINTER TO ARRAY OF CHAR;
left, right: Tree
END;
PROCEDURE (t: Tree) Insert* (name: ARRAY OF CHAR), NEW;
VAR p, father: Tree;
BEGIN
p := t;
REPEAT father := p;
IF name = p.name^ THEN RETURN END;
IF name < p.name^ THEN p := p.left ELSE p := p.right END
UNTIL p = NIL;
NEW(p); p.left := NIL; p.right := NIL;
NEW(p.name, LEN(name$) + 1); p.name^ := name$;
IF name < father.name^ THEN father.left := p ELSE father.right := p END
END Insert;
PROCEDURE (t: Tree) Search* (name: ARRAY OF CHAR): Tree, NEW;
VAR p: Tree;
BEGIN
p := t;
WHILE (p # NIL) & (name # p.name^) DO
IF name < p.name^ THEN p := p.left ELSE p := p.right END
END;
RETURN p
END Search;
PROCEDURE (t: Tree) Write*, NEW;
BEGIN
IF t.left # NIL THEN t.left.Write END;
StdLog.String(t.name); StdLog.Ln;
IF t.right # NIL THEN t.right.Write END
END Write;
PROCEDURE Init* (t: Tree);
BEGIN
NEW(t.name, 1); t.name[0] := 0X; t.left := NIL; t.right := NIL
END Init;
BEGIN
StdLog.String("Trees loaded"); StdLog.Ln
CLOSE
StdLog.String("Trees removed"); StdLog.Ln
END Trees.
Appendix A: Definition of Terms
Character types SHORTCHAR, CHAR
Integer types BYTE, SHORTINT, INTEGER, LONGINT
Real types SHORTREAL, REAL
Numeric types integer types, real types
String types Shortstring, String
Basic types BOOLEAN, SET, character types, numeric types
Same types
Two variables a and b with types Ta and Tb are of the same type if
1. Ta and Tb are both denoted by the same type identifier, or
2. Ta is declared in a type declaration of the form Ta = Tb, or
3. a and b appear in the same identifier list in a variable, record field,
or formal parameter declaration.
Equal types
Two types Ta and Tb are equal if
1. Ta and Tb are the same type, or
2. Ta and Tb are open array types with equal element types, or
3. Ta and Tb are procedure types whose formal parameter lists match, or
4. Ta and Tb are pointer types with equal base types.
Matching formal parameter lists
Two formal parameter lists match if
1. they have the same number of parameters, and
2. they have either equal function result types or none, and
3. parameters at corresponding positions have equal types, and
4. parameters at corresponding positions are both either value, IN, OUT, or VAR parameters.
Type inclusion
Numeric and character types include (the values of) smaller types of the same class according to the following hierarchies:
REAL >= SHORTREAL >= LONGINT >= INTEGER >= SHORTINT >= BYTE
CHAR >= SHORTCHAR
Type extension (base type)
Given a type declaration Tb = RECORD (Ta) ... END, Tb is a direct extension of Ta, and Ta is a direct base type of Tb. A type Tb is an extension of a type Ta (Ta is a base type of Tb) if
1. Ta and Tb are the same types, or
2. Tb is a direct extension of an extension of Ta, or
3. Ta is of type ANYREC.
If Pa = POINTER TO Ta and Pb = POINTER TO Tb, Pb is an extension of Pa (Pa is a base type of Pb) if Tb is an extension of Ta.
Assignment compatible
An expression e of type Te is assignment compatible with a variable v of type Tv if one of the following conditions hold:
1. Te and Tv are equal and neither abstract, extensible, or limited record nor open array types;
2. Te and Tv are numeric or character types and Tv includes Te;
3. Te and Tv are pointer types and Te is an extension of Tv;
4. Tv is a pointer or a procedure type and e is NIL;
5. Tv is a numeric type and e is a constant expression whose value is contained in Tv;
6. Tv is an array of CHAR, Te is String or Shortstring, and LEN(e) < LEN(v);
7. Tv is an array of SHORTCHAR, Te is Shortstring, and LEN(e) < LEN(v);
8. Tv is a procedure type and e is the name of a procedure whose formal parameters match those of Tv.
Array compatible
An actual parameter a of type Ta is array compatible with a formal parameter f of type Tf if
1. Tf and Ta are equal types, or
2. Tf is an open array, Ta is any array, and their element types are array compatible, or
3. Tf is an open array of CHAR and Ta is String, or
4. Tf is an open array of SHORTCHAR and Ta is Shortstring.
Parameter compatible
An actual parameter a of type Ta is parameter compatible with a formal parameter f of type Tf if
1. Tf and Ta are equal types, or
2. f is a value parameter and Ta is assignment compatible with Tf, or
3. f is an IN or VAR parameter and Tf and Ta are record types and Ta is an extension of Tf.
Expression compatible
For a given operator, the types of its operands are expression compatible if they conform to the following table. The first matching line gives the correct result type. Type T1 must be an extension of type T0:
operator first operand second operand result type
+ - * DIV MOD <= INTEGER <= INTEGER INTEGER
integer type integer type LONGINT
/ integer type integer type REAL
+ - * / <= SHORTREAL <= SHORTREAL SHORTREAL
numeric type numeric type REAL
SET SET SET
+ Shortstring Shortstring Shortstring
string type string type String
OR & ~ BOOLEAN BOOLEAN BOOLEAN
= # < <= > >= numeric type numeric type BOOLEAN
character type character type BOOLEAN
string type string type BOOLEAN
= # BOOLEAN BOOLEAN BOOLEAN
SET SET BOOLEAN
NIL, pointer type T0 or T1 NIL, pointer type T0 or T1 BOOLEAN
procedure type T, NIL procedure type T, NIL BOOLEAN
IN integer type, 0..MAX(SET) SET BOOLEAN
IS T0 type T1 BOOLEAN
Constant expressions are calculated at compile time with maximum precision (LONGINT for integer types, REAL for real types) and the result is handled like a numeric literal of the same value.
If a real constant x with |x| <= MAX(SHORTREAL) or x = INF is combined with a nonconstant operand of type SHORTREAL, the constant is considered a SHORTREAL and the result type is SHORTREAL.
Appendix B: Syntax of Component Pascal
Module = MODULE ident ";" [ImportList] DeclSeq
[BEGIN StatementSeq]
[CLOSE StatementSeq] END ident ".".
ImportList = IMPORT [ident ":="] ident {"," [ident ":="] ident} ";".
DeclSeq = { CONST {ConstDecl ";" } | TYPE {TypeDecl ";"} |
VAR {VarDecl ";"}} {ProcDecl ";" | ForwardDecl ";"}.
ConstDecl = IdentDef "=" ConstExpr.
TypeDecl = IdentDef "=" Type.
VarDecl = IdentList ":" Type.
ProcDecl = PROCEDURE [Receiver] IdentDef [FormalPars] MethAttributes
[";" DeclSeq [BEGIN StatementSeq] END ident].
MethAttributes = ["," NEW] ["," (ABSTRACT | EMPTY | EXTENSIBLE)].
ForwardDecl = PROCEDURE " ^ " [Receiver] IdentDef [FormalPars] MethAttributes.
FormalPars = "(" [FPSection {";" FPSection}] ")" [":" Type].
FPSection = [VAR | IN | OUT] ident {"," ident} ":" Type.
Receiver = "(" [VAR | IN] ident ":" ident ")".
Type = Qualident
| ARRAY [ConstExpr {"," ConstExpr}] OF Type
| [ABSTRACT | EXTENSIBLE | LIMITED]
RECORD ["("Qualident")"] FieldList {";" FieldList} END
| POINTER TO Type
| PROCEDURE [FormalPars].
FieldList = [IdentList ":" Type].
StatementSeq = Statement {";" Statement}.
Statement = [ Designator ":=" Expr
| Designator ["(" [ExprList] ")"]
| IF Expr THEN StatementSeq
{ELSIF Expr THEN StatementSeq}
[ELSE StatementSeq] END
| CASE Expr OF Case {"|" Case}
[ELSE StatementSeq] END
| WHILE Expr DO StatementSeq END
| REPEAT StatementSeq UNTIL Expr
| FOR ident ":=" Expr TO Expr [BY ConstExpr]
DO StatementSeq END
| LOOP StatementSeq END
| WITH [ Guard DO StatementSeq ]
{"|" [ Guard DO StatementSeq ] }
[ELSE StatementSeq] END
| EXIT
| RETURN [Expr]
].
Case = [CaseLabels {"," CaseLabels} ":" StatementSeq].
CaseLabels = ConstExpr [".." ConstExpr].
Guard = Qualident ":" Qualident.
ConstExpr = Expr.
Expr = SimpleExpr [Relation SimpleExpr].
SimpleExpr = ["+" | "-"] Term {AddOp Term}.
Term = Factor {MulOp Factor}.
Factor = Designator | number | character | string | NIL | Set |
"(" Expr ")" | " ~ " Factor.
Set = "{" [Element {"," Element}] "}".
Element = Expr [".." Expr].
Relation = "=" | "#" | "<" | "<=" | ">" | ">=" | IN | IS.
AddOp = "+" | "-" | OR.
MulOp = " * " | "/" | DIV | MOD | "&".
Designator = Qualident {"." ident | "[" ExprList "]" | " ^ " | "(" Qualident ")"
| "(" [ExprList] ")"} [ "$" ].
ExprList = Expr {"," Expr}.
IdentList = IdentDef {"," IdentDef}.
Qualident = [ident "."] ident.
IdentDef = ident [" * " | "-"].
AppendixC:DomainsofBasicTypes
Type Domain
BOOLEAN FALSE, TRUE
SHORTCHAR 0X .. 0FFX
CHAR 0X .. 0FFFFX
BYTE -128 .. 127
SHORTINT -32768 .. 32767
INTEGER -2147483648 .. 2147483647
LONGINT -9223372036854775808 .. 9223372036854775807
SHORTREAL -3.4E38 .. 3.4E38, INF (32-bit IEEE format)
REAL -1.8E308 .. 1.8E308, INF (64-bit IEEE format)
SET set of 0 .. 31
AppendixD: Mandatory Requirements for Environment
The Component Pascal definition implicitly relies on four fundamental assumptions.
1) There exists some run-time type information that allows to check the dynamic type of an object. This is necessary to implement type tests and type guards.
2) There is no DISPOSE procedure. Memory cannot be deallocated manually, since this would introduce the safety problem of memory leaks and of dangling pointers, i.e., premature deallocation. Except for those embedded systems where no dynamic memory is used, or where it can be allocated once and never needs to be released, an automatic garbage collector is required.
3) Modules and at least their exported procedures (commands) and exported types must be retrievable dynamically. If necessary, this may cause modules to be loaded. The programming interface used to load modules or to access the mentioned meta information is not defined by the language, but the language compiler needs to preserve this information when generating code.
Except for fully linked applications where no modules will ever be added at run-time, a linking loader for modules is required. Embedded systems are important examples of applications that can be fully linked.
4) The environment must provide the ability to display Unicode characters, except for "headless" embedded applications that need no display.
An implementation that doesn't fulfill these compiler and environment requirements is not compliant with Component Pascal.
| Docu/CP-Lang.odc |
What's New iыыыn Coывыыыmponent Pascal?
Except for some minor points, Componeыыnt Pascal is a superset of Oberon-2. Compared to Oberon-2, it provides several clarifications and improvements. This text summarizes the differences.
The language revision was driven by the experience with the BlackBox Component Framework, and the desire to further improve support for the specification, documentation, development, maintenance, and refactoring of component frameworks. The goal was to give a framework architect the means to better control the overall integrity of large component-based software systems. Control over a system's integrity is key to increased reliability, reduced maintenance costs, and to higher confidence in the system's correctness when it evolves over time.
Care was taken that the language remains small, easy to use, and easy to learn. The new features are most visible to framework designers, less visible to framework extenders, and least visible to mere framework clients. This ensures that these different categories of developers are burdened with the minimal amounts of complexity that their respective tasks require.
More expressive type system
Covariant pointer function results
A type-bound function which returns a pointer may be redefined, such that it returns an extended type. For example, the function
PROCEDURE (v: View) ThisModel (): Model
could be extended in a subtype MyView, which is assumed to be a subtype of View, to the following function signature
PROCEDURE (v: MyView) ThisModel (): MyModel
where MyModel is assumed to be a subtype of Model. Note that covariant function results are type safe; they simply strengthen the postcondition of a function, which is always legal. They allow to make interface declarations more precise.
Pointer compatibility
The compatibility rules for pointers have been relaxed and simplified. Pointers are now compatible by structure; i.e., two pointer types that have the same base type are compatible. This can be useful mostly in procedure signatures, where it previously wasn't possible to use a function like the following:
PROCEDURE P (p: POINTER TO ARRAY OF INTEGER)
Pointer function results
A function's return type is now Type not Ident; e.g.,
PROCEDURE Bla (): POINTER TO Rec
is now legal, and due to simplified compatibility rules (see previous point) their use can actually make sense.
IN and OUT
These parameter modes are like the VAR mode, except that some restrictions apply. IN parameters cannot directly be modified inside a procedure, OUT parameters are considered undefined upon procedure entry (except for pointers and procedure variables, which are set to NIL upon procedure entry). OUT record parameters must have identical actual and formal parameter types.
These parameter modes are important for procedure signatures of distributed objects, and they can increase convenience and efficiency. Most importantly, they allow to make interface declarations more precise and more self-documenting. In particular, where formerly VAR parameters have been used for efficiency reasons only, it is now possible to use IN parameters. IN parameters are only allowed for record and array types.
Example:
PROCEDURE ShowModes (value: INTEGER; VAR inout: INTEGER;
(* value and VAR parameters *)
IN in: ARRAY OF SET;
(* IN for efficiency *)
OUT res: INTEGER): INTEGER;
(* OUT parameter and function result *)
Since IN and OUT are specializations of VAR, it is not possible to pass constants to IN parameters. There is one convenient exception: string constants may be passed to open-array IN parameters, since they are implemented by the compiler as a kind of "read-only variable" anyway.
NEW methods
Component Pascal requires that the introduction of a new method is indicated explicitly. This is done by appending the identifier NEW to the method's signature. NEW may not be used for extending methods.
In the following example, method SomeMethod is newly introduced in T and inherited in T1, which is assumed to be an extension of T:
PROCEDURE (t: T) SomeMethod (x, y: INTEGER), NEW;
BEGIN
...
END SomeMethod;
PROCEDURE (t: T1) SomeMethod (x, y: INTEGER);
BEGIN
...
END SomeMethod;
NEW indicates that a method is new, not extending. The need to declare this fact explicitly is useful whenever changes to a framework are made, which often happens during the initial design iterations, and later when the software architecture undergoes refactoring. NEW makes it possible for the compiler to detect for example if a base method's name has been changed, but extending methods have not been renamed accordingly. Also, the compiler detects if a method is newly introduced, although it already exists in a base type or in a subtype. These checks make it easier to achieve consistency again after a change to a framework's interfaces.
Default, EXTENSIBLE, ABSTRACT, and LIMITED record types
Component Pascal uses a single construct to denote both interfaces of objects and their implementations: record types. This unification allows to freeze some implementation aspects of an interface while leaving others open. This flexibility is often desirable in complex frameworks. But it is important to communicate such architectural decisions as precisely as possible, since they may affect a large number of clients.
For this reason, a Component Pascal record type can be attributed to allow an interface designer to formulate several fundamental architectural decisions explicitly. This has the advantage that the compiler can help to verify compliance with these decisions. The carefully chosen attributes are EXTENSIBLE, ABSTRACT, and LIMITED. They allow to distinguish four different combinations of extension and allocation possibilities:
modifier extension allocation record assignment
none ("final") no yes yes
EXTENSIBLE yes yes no
ABSTRACT yes no no
LIMITED no* no* no
*except in the defining module
Record types may either be extensible or non-extensible ("final"). By default, a record type is final. Final types allow to "close" a type, such that an implementor can perform a complete analysis of the type's implementation, e.g., to find out how it could be improved without breaking clients.
Record types may either be allocatable (as static or dynamic variables), or allocation may be prevented (ABSTRACT) or limited to the defining module (LIMITED). With limited types, allocation and extension is possible in the defining module only, never by an importing module.
Final types typically are simple auxiliary data types, e.g.:
Point = RECORD
x, y: INTEGER
END
Variables of such types can be copied using the assignment operator, e.g. pt := pt2. The compiler never needs to generate the hidden type guard that is sometimes necessary for such an assignment in Oberon.
On the other hand, extensible records can neither be copied, nor passed as value parameters (since value parameters imply a record assignment).
Final types, like extensible types, may be extensions of other record types and they may have methods.
Extensible types are declared in the following way:
Frame = EXTENSIBLE RECORD
l-, t-, r-, b-: INTEGER
END
Plain EXTENSIBLE types are rare, it is more typical to use ABSTRACT types instead, which are a special case of extensible types that cannot be instantiated. The following paragraph gives a more precise description of what this restriction means:
Types of values can never be abstract, but types of variables may be abstract. The type of a value can be different from the type of its holding variable only if the variable is referential; i.e., a pointer; or a VAR, IN, or OUT parameter. Thus, only those variables may be declared to be of an abstract type. In all other cases; i.e., static variables, record fields, array base types, and value parameters, non-abstract types or pointers (possibly to abstract types) must be used. Since the allocation operation NEW produces a value of the argument's type, NEW can only be used with variables of non-abstract type.
Example of an abstract type:
TextView = POINTER TO ABSTRACT RECORD (Views.View) END
Abstract types are design tools, they denote interfaces of objects. They are the primary means of Component Pascal to model component interfaces. Denoting records as abstract allows to indicate more precisely the use of a record: as an interfacing construct rather than an implementation construct.
Nevertheless, an abstract type may have all types of methods (see below), i.e., it is not forced to be fully abstract.
LIMITED types are a special case of final types. They are special in that they can be instantiated only within the defining module, and they cannot be copied. For example, a client may not perform a NEW on variables of limited types. Since allocation is under complete control of the defining module, the programmer of this module can guarantee that all newly allocated variables are correctly initialized before they are made accessible to client modules. This means that clients can only see variables that respect the type's invariants (which are established during initialization). An implementor is free to change the type's internal representation with less risk of breaking client code; there is no need for lazy initialization schemes; there cannot be delayed run-time errors due to missing initializations; and invariants (e.g., invariants over hidden record fields) cannot be violated through copying.
Typically, factory functions or factory objects are provided to create new instances of dynamic LIMITED types.
Example:
Semaphore = POINTER TO LIMITED RECORD END;
PROCEDURE New (level: INTEGER): Semaphore;
In the BlackBox Component Framework, most abstractions are represented as abstract types, which are implemented by (non-exported) final types. This is another approach that allows to guarantee correct initialization, but it is too inconvenient for simple non-extensible abstractions. Moreover, LIMITED types cannot be substituted by client-side extensions. This is important, because it allows to protect non-extensible services, such as a real-time kernel, from being used with illegal types.
Record syntax
The record syntax looks as follows:
RecordType = [EXTENSIBLE | ABSTRACT | LIMITED] RECORD ["(" QualIdent ")"] FieldList {";" FieldList} END.
Note that a pure client programmer never needs to write any of the above attributes. The same is true for an implementor of a framework extension. Even the framework designer may save some time using these attributes, because they are an important part of the documentation that can be extracted automatically from the source code.
The goal for the introduction of these attributes was to increase the static expressiveness of interfaces, such that important architectural decisions can be written down explicitly, in a way that a compiler can check conformance of an implementation or a client with the interface contract. A pure implementation language wouldn't need the new attributes, only a component-oriented implementation and design language needs to be able to express such design constraints. Control over such constraints enables a framework designer to establish important invariants over a whole software system (= system architecture), thus improving safety, maintainability, and evolvability.
Some of the new attributes also add convenience; e.g., abstract methods need no procedure body anymore. Such additional convenience is a welcome benefit, but it was by no means the reason for the introduction of the attributes.
Default and EXTENSIBLE methods
Like record types, methods of a record type can also be attributed. The attributes available are the default (no attribute), EXTENSIBLE, ABSTRACT and EMPTY.
Like record types, methods are final by default:
PROCEDURE (t: T) StaticProcedure (x, y: INTEGER), NEW;
BEGIN
...
END StaticProcedure;
Methods that are both new and final can be treated by a compiler like normal procedures, since they don't require late binding. Nevertheless, their use can be appropriate if they clearly belong to a particular type.
Extensible methods on the other hand are marked as such, e.g.:
PROCEDURE (t: T) Method (x, y: INTEGER), NEW, EXTENSIBLE;
BEGIN
...
END Method;
It is much more common to use abstract or empty methods, which are special cases of extensible methods (see below).
Declaring a method as final is achieved by simply leaving away the EXTENSIBLE attribute:
PROCEDURE (t: T) FinalInheritedMethod (x, y: INTEGER);
BEGIN
...
END FinalInheritedMethod;
If a black-box design style is used, most methods that need to be implemented for a framework extension are of the above kind, which requires no special attributes in the method signature. This is reasonable, because there are more framework extension programmers than there are framework designers, thus extensions should be as convenient as possible to write down.
Final methods may be bound to any record types. Extensible methods may only be bound to extensible types (i.e., EXTENSIBLE or ABSTRACT).
Since final methods cannot be "overridden", the invariants that they guarantee and the postconditions that they establish cannot be violated. Note that correct "extension" of a method means that the extending method implements a refinement of the extended method. Semantically, this means that the extending method accepts a weaker precondition or establishes a stronger postcondition compared to the extended method.
ABSTRACT methods
An abstract method is declared in the following way:
PROCEDURE (t: T) SomeMethod (s: SET), NEW, ABSTRACT;
PROCEDURE (t: T) CovariantMethod2 (): NarrowedType, ABSTRACT;
Abstract methods are extensible. The compiler checks that a concrete type implements all abstract methods that it inherits. A concrete extension of an abstract method (or type) can be regarded as its implementation. Abstract methods may only be bound to abstract types, and they may not be called via super calls.
An abstract method has no corresponding procedure body, it only exists as a signature. There is no need anymore to write a procedure body with a HALT statement.
EMPTY methods
A method can be declared as empty. Empty methods are extensible. An empty method is very similar to an abstract method, in that it is a hook for functionality that can be provided in later extensions. However, empty methods are concrete and can be called. If they have not been extended (i.e., implemented), calling them has no effect.
Empty methods represent optional interfaces. For example, a BlackBox Component Framework View provides an empty method for handling user events (HandleCtrlMsg). This method is implemented in interactive views, passive views ignore it.
It is not possible to introduce code in an empty procedure. For this reason, an empty method has no corresponding procedure body, and may not be called via super calls.
Empty procedures may not return function results and may not have OUT parameters.
Example:
PROCEDURE (t: T) Broadcast (msg: Message), NEW, EMPTY;
Method syntax
The method syntax looks as follows:
TBProc = PROCEDURE Receiver IdentDef [FormalPars] [Attribution].
Attribution = ["," NEW] ["," (EXTENSIBLE | ABSTRACT | EMPTY)].
Note that a pure client programmer never needs to write any of these attributes. The same is true for an implementor of a framework extension. Even the framework designer may save some time using these attributes, because they are an important part of the documentation that can be extracted automatically from the source code.
Implement-only export of methods
A method may now also be exported as implement-only, using the "-" export mark instead of the "*". Implement-only export means that the method may be implemented outside the defining module, but may not be called from there.
Whether a method is exported normally or implement-only is decided when the method is first introduced (NEW method). Later extensions must use the same export mode if exported.
Implement-only exported methods are called from within the module where a method is newly introduced; they go "upwards" in the module hierarchy (upcalls). For frameworks, the existence of such upcalls is typical. Implement-only export allows to prevent framework clients from violating the framework's invariants, while still making it possible to provide new implementations of the framework's types.
Every framework has two "faces": an interface for clients, and an interface for implementors, the so-called specialization interface. These two interfaces may overlap. Implement-only export allows to clearly label those parts of an interface that belong to the specialization interface only.
Super calls
Because of the so-called semantic fragile base class problem, it is recommended to avoid super calls whenever possible. It is possible to design new software such that they are not needed, by relying on composition rather than on implementation inheritance. Super calls are considered to be an obsolete feature. For the time being, they are retained for backward compatibility. In the long run, support for super calls may be reduced.
Procedure types
Procedure types are less flexible than objects with methods. Even standard examples for procedure types in numerical software can benefit from modeling them as objects. Objects are extensible, procedure types are not. Procedure types can pose considerable implementation difficulties concerning the safe unloading of code. For these reasons, procedure types are considered as obsolete. For the time being, they are retained for backward compatibility and for implementation low-level interfacing code (callbacks). In the long run, support for super calls may be reduced.
ANYREC and ANYPTR
Each base record is implicitly regarded as an extension of the new abstract standard type ANYREC, even if it is declared without explicit base type. ANYREC is an empty record that forms the root of all record type hierarchies. ANYPTR is a new standard type that corresponds to a POINTER TO ANYREC.
These new types make it easier to achieve interoperability between independently developed frameworks, by allowing completely generic parameters.
The following pseudo definitions can be assumed:
ANYREC = ABSTRACT RECORD END;
ANYPTR = POINTER TO ANYREC;
PROCEDURE (a: ANYPTR) FINALIZE-, NEW, EMPTY;
The FINALIZE procedure is empty. It can be implemented for a pointer type extension. The procedure is called at some unspecified time after the object has become unreachable via other pointers (not globally anchored anymore) and before the object is deallocated. Finalizers are needed to release resources that are not directly Component Pascal objects; e.g., file sectors, font handles, window pointers of the operating system, and so on.
The finalization order is not defined. An object is only finalized once.
String support
Explicit string types
We can distinguish a string value (the actual character values) from the variable in which it is contained (an array of character). Some operations in Component Pascal operate on the string value (e.g., comparison for equality), others operate on the container variable (e.g., assignment). A compiler can automatically derive which interpretation is needed in a given situation. Unfortunately, there are situations where both interpretations make sense. For example, passing an array of character to a value parameter (which is also an array of character) should be interpreted as an assignment. But often it is more efficient only to copy the string value in the actual parameter, rather than the whole array. Consider passing a Unix path name, declared as an array of character with 2048 elements, when it usually contains only a few dozen characters.
In Component Pascal, it can be made explicit that the programmer wants to work with the string value, rather than the character array variable. Selecting the string value in a variable is denoted with the $ operator; for example
OpenFile(pathname$)
where OpenFile is declared as
PROCEDURE OpenFile (name: ARRAY 2048 CHAR)
Note an additional benefit: it is now more attractive to declare character array parameters with a fixed number of elements, like in the above example. In Oberon, this is inconvenient since often the type of the actual parameter is not compatible with the formal parameter. Since string values are always compatible with character arrays, this problem vanishes in Component Pascal. This is important because it is more precise to specify a fixed size array when the array is known to be limited. Note that declaring an open array would be a contract to accept arrays of any length whatsoever (without ever leading to an out-of-range error at run-time!).
String concatenation
The + operator now allows to concatenate strings. The target variable must be of sufficient length to hold the resulting string.
Elimination of COPY
The auxiliary procedure COPY is not necessary anymore, since the $ operator makes it superfluous. For example,
COPY(a, varpar) is replaced by varpar := a$
Specified domains of types
To achieve fully portable code, it is necessary to fully specify the domains of all base types. The Component Pascal base types are a superset of the Java base types.
Type Size Domain
SHORTCHAR 1 byte Latin-1 character set
(first Unicode page and a superset of ASCII)
CHAR 2 byte Unicode character set
BYTE 1 byte signed integer
SHORTINT 2 byte signed integer
INTEGER 4 byte signed integer
LONGINT 8 byte signed integer
SHORTREAL 32 bit IEEE
REAL 64 bit IEEE
SET 4 byte bitset
BOOLEAN 1 byte FALSE or TRUE
Type LONGREAL has been eliminated. Longreal literals have been eliminated; i.e., use 1.0E2 instead of 1.0D2. The identifier LONGREAL is reserved for possible future use. Real constants are always REAL (64 bit) values.
Hexadecimal integer constants now can be specified either as 4 byte (e.g., 0FFFFFFFFH) or 8 byte constants (e.g., 0FFFFFFFFFFFFFFFFL). This allows to distinguish negative INTEGER hex constants from positive LONGINT hex constants. For example, 0FFFFFFFF denotes -1 when interpreted as INTEGER, but 4294967295 when interpreted as a LONGINT.
Integer constants are always INTEGER (4 byte) values. Assignment of an integer constant to a smaller type (e.g., BYTE) is legal if the constant lies within the range of the target type. Integer constants of other types can only be constructed using SHORT or LONG, except that sufficiently large constants automatically have type LONGINT.
Integer arithmetic is now always performed with 32-bit precision, except for expressions that contain LONGINT values. In the latter case, 64-bit precision is used. This rule makes it less likely to produce hard-to-find overflows of intermediate results that are calculated at insufficient precision.
Floating-point arithmetic is always perfomed at 64-bit precision.
Miscellaneous
The semantics of DIV is strengthened, by specifying the result of divisions by negative numbers.
The new real value INF for infinity has been introduced. This value may be generated e.g. through floating-point division by zero. The meaning of infinity for floating-point numbers is defined by the IEEE standard for floating-point numbers.
It has been specified more comprehensively where pointer dereferencing is implicit. For example, it is now also available when passing a pointer variable to a record type formal parameter.
Record types can be declared as extensions of other record types by mentioning a pointer type as base type (instead of a record type). This makes the explicit naming of a record type superfluous, if the record variables are used via pointers only.
Within a scope, type names can be considered as forward-declared. This means that any type name can be used before it is declared. Old-style pointer forward declarations like T = POINTER TO TDesc are still allowed, since they are simply a special case of the new rule, but they are not necessary anymore.
BITS is a new standard function that converts an INTEGER value to a SET value, such that BITS(1) yields {0}. For example, this allows to write more portable device drivers, since it doesn't depend on the processor's bit ordering (which differs for 68k and PowerPC, for example).
ORD can now also be applied to SET values (inverse operation of BITS).
MIN and MAX now also accept two parameters; e.g. real0 := MAX(someInt, real1). They select the minimal/maximal values of the two inputs, which must be number types.
LEN can also be used on string values. LEN(chararray) returns the length of the chararray variable, while LEN(chararray$) returns the length of the string value. Note that a character array must have at least one more element than the string value contains characters, to hold the terminating 0X character.
Designators are generalized to allow dereferencing etc. on a function result. For example, the following is now legal:
length := view.ThisModel()(TextModels.Model).Length() or
view.Context().GetSize(w, h)
The relaxation of the designator syntax makes it easier to use methods instead of record fields. Methods are more flexible and make it simpler to implement wrappers (forwarding of method calls) than record fields do.
Global variables, including heap variables allocated with NEW, now have a defined initial value (FALSE, 0X, 0, 0.0, {}, NIL, ""). Local (i.e., stack) variables are not initialized, except for pointers and procedure variables which are set to NIL for safety reasons.
An appendix of the language report specifies the minimal environment requirements that any Component Pascal implementation must fulfill. In particular, commands, dynamic loading, and garbage collection are fundamental requirements for component-oriented systems. Like for all dynamic languages, this appendix acknowledges that the language cannot be regarded completely independently from its environment. The object model, whether assumed in the language definition or accessed as an external service, is always part of the environment.
To simplify interfacing of existing C libraries, underscores in identifiers are allowed.
The rules for export marks have been simplified compared to Oberon: An extending method must have exactly the same export mark as the method that it extends. The only exception occurs if the method is part of a non-exported record; in this case it may not be exported.
A module now has an optional CLOSE section, after the BEGIN section. The close section is called before a module is unloaded. A module's BEGIN section is called after all the imported modules' BEGIN sections have been called. A module's CLOSE section may only be called after all the importing modules' CLOSE sections have been called.
In summary, you'll note that this revised language definition contains one major extension: a more expressive interface definition language (IDL) subset (NEW; EXTENSIBLE; ABSTRACT; LIMITED; EMPTY; implement-only export of methods) that makes it easier to specify architectural properties of a component framework.
The other points are mostly detail improvements based on a decade of experience in using the language. Particularly noteworthy are the more general and systematic treatment of strings and the new specification of the base type sizes.
Acknowledgements
We would like to thank Beat Heeb, Dominik Gruntz, Matthias Hausner, and Daniel Diez of Oberon microsystems for their valuable input. In particular, without Beat's work this endeavour would have been impossible. The most important external contributions came from Clemens Szyperski (Queensland University of Technology, Australia) and Wolfgang Weck (bo Akademi, Finland). Last but not least, we would like to thank Prof. Niklaus Wirth for commenting an early revision of the Component Pascal language report, and for having created such a great foundation.
| Docu/CP-New.odc |
Map to the BlackBox Component Builder Documentation
GuidedTour Roadmap OverviewbyExample
Tutorial: Component-based Software Development with BlackBox Table of Contents
Part I Part II Part III
UserInteraction Forms ViewConstruction
CompoundDocuments Texts
DesignPractices
Appendices A:BriefHistoryofPascal B: Differences between Pascal and Component Pascal
User Manuals Developer Manuals Component Pascal Miscellaneous
Framework Framework LanguageReport License
TextSubsystem TextSubsystem What'sNew? Contributors
FormSubsystem FormSubsystem CharacterSet Platform SpecificIssues
DevSubsystem DevSubsystem DocumentationConventions
Std Subsystem SqlSubsystem ProgrammingConventions
| Docu/Help.odc |