Giter Site home page Giter Site logo

trufflepascal's People

Contributors

aspect26 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

trufflepascal's Issues

Readln and Writeln

Readln and Writeln buitin subroutines are a TP extension. They are not supported by wirth's standard

Unit: graph

Implement Graph unit:

  • Arc - Draw part of a circle
  • Bar - Draw filled rectangle
  • Bar3D - Draw filled 3-dimensional rectangle
  • ClearDevice - Clear the complete screen
  • Closegraph - Close graphical system.
  • DetectGraph - Detect correct graphical driver to use
  • DrawPoly - Draw a polygone
  • Ellipse - Draw an ellipse
  • FillEllipse - Draw and fill an ellipse
  • FillPoly - Draw, close and fill a polygone
  • FloodFill - Fill an area with a given color
  • GetArcCoords - Return coordinates of last drawn arc or ellipse.
  • GetAspectRatio - Return screen resolution
  • GetColor - Return current drawing color
  • GetDefaultPalette - Return default palette
  • GetDirectVideo - Determine whether direct video mode is active.
  • GetDriverName - Return current driver name
  • GetFillPattern - Return current fill pattern
  • GetFillSettings - Return current fill settings
  • GetGraphMode - Get current graphical modus
  • GetLineSettings - Get current line drawing settings
  • GetMaxColor - return maximum number of colors
  • GetMaxMode - Return biggest mode for the current driver
  • GetMaxX - Return maximal X coordinate
  • GetMaxY - Return maximal Y coordinate
  • GetModeName - Return description a modus
  • GetModeRange - Return lowest and highest modus of current driver
  • GetPalette - Return current palette
  • GetPaletteSize - Return maximal number of entries in current palette
  • GetTextSettings - Return current text style
  • GetViewSettings - Return current viewport
  • GetX - Return current cursor X position
  • GetY - Return current cursor Y position
  • GraphDefaults - Reset graphical mode to defaults
  • GraphErrorMsg - Return a description of an error
  • GraphResult - Result of last graphical operation
  • InitGraph - Initialize grpahical system
  • InstallUserDriver - Install a user driver
  • InstallUserFont - Install a user-defined font
  • LineRel - Draw a line starting from current position in given direction
  • LineTo - Draw a line starting from current position to a given point
  • MoveRel - Move cursor relative to current position
  • MoveTo - Move cursor to absolute position.
  • OutText - Write text on the screen at the current location.
  • PieSlice - Draw a pie-slice
  • queryadapterinfo - Function called to retrieve the current video adapter settings.
  • Rectangle - Draw a rectangle on the screen.
  • RegisterBGIDriver - Register a new BGI driver.
  • RegisterBGIfont - Register a new BGI font
  • RestoreCrtMode - Restore text screen
  • Sector - Draw and fill a sector of an ellipse
  • SetAspectRatio - Set aspect ration of the screen
  • SetColor - Set foreground drawing color
  • SetDirectVideo - Attempt to enter direct video mode.
  • SetFillPattern - Set drawing fill pattern
  • SetFillStyle - Set drawing fill style
  • SetGraphMode - Set graphical mode
  • SetLineStyle - Set line drawing style
  • SetPalette - Set palette entry using color constant
  • SetTextJustify - Set text placement style
  • SetTextStyle - Set text style
  • SetUserCharSize - Set user character size for vector font
  • SetViewPort - Set the graphical drawing window
  • SetWriteMode - Specify binary operation to perform when drawing on screen
  • TextHeight - Return height (in pixels) of the given string
  • TextWidth - Return width (in pixels) of the given string

Files

Implement work with files.

Unit: dos

Implement Dos unit:

  • AddDisk - Add disk definition to list if drives (Unix only)
  • DiskFree - Get free size on Disk.
  • DiskSize - Get total size of disk.
  • DosExitCode - Exit code of last executed program.
  • DosVersion - Current OS version
  • DTToUnixDate - Convert a DateTime to unix timestamp
  • EnvCount - Return the number of environment variables
  • EnvStr - Return environment variable by index
  • Exec - Execute another program, and wait for it to finish.
  • FExpand - Expand a relative path to an absolute path
  • FindClose - Dispose resources allocated by a FindFirst/FindNext sequence.
  • FindFirst - Start search for one or more files.
  • FindNext - Find next matching file after FindFirst
  • FSearch - Search a file in searchpath
  • FSplit - Split a full-path filename in parts.
  • GetCBreak - Get control-Break flag
  • GetDate - Get the current date
  • GetEnv - Get environment variable by name.
  • GetFAttr - Get file attributes
  • GetFTime - Get file last modification time.
  • GetIntVec - Get interrupt vector
  • GetLongName - Get the long filename of a DOS 8.3 filename.
  • GetMsCount - Number of milliseconds since a starting point.
  • GetShortName - Get the short (8.3) filename of a long filename.
  • GetTime - Return the current time
  • GetVerify - Get verify flag
  • Intr - Execute interrupt
  • Keep - Terminate and stay resident.
  • MSDos - Execute MS-DOS system call
  • PackTime - Pack DateTime value to a packed-time format.
  • SetCBreak - Set Control-Break flag status
  • SetDate - Set system date
  • SetFAttr - Set file attributes
  • SetFTime - Set file modification time.
  • SetIntVec - Set interrupt vector
  • SetTime - Set system time
  • SetVerify - Set verify flag
  • SwapVectors - Swap interrupt vectors
  • UnixDateToDt - Convert a unix timestamp to a DateTime record
  • UnpackTime - Unpack packed file time to a DateTime value
  • weekday - Return the day of the week

PrimitiveDescriptors

move primitive descriptors to its own file
the same with builtin procedure descriptors (even enums maybe)

Goto

Implement goto statement and labels.

readln() behaviour

The simpleMultipleRead test suggests that only new-line character is a separator for multiple arguments in the readln() procedure. However, the code readln(i, j); for two integers shall read two numbers on both inputs: 42 24 and 42\n24.

Unit: string

Implement string unit:

  • stralloc - Allocate memory for a new null-terminated string on the heap
  • strcat - Concatenate 2 null-terminated strings.
  • strcomp - Compare 2 null-terminated strings, case sensitive.
  • strcopy - Copy a null-terminated string
  • strdispose - disposes of a null-terminated string on the heap
  • strecopy - Copy a null-terminated string, return a pointer to the end.
  • strend - Return a pointer to the end of a null-terminated string
  • stricomp - Compare 2 null-terminated strings, case insensitive.
  • stripos - Return the position of a substring in a string, case insensitive.
  • striscan - Scan a string for a character, case-insensitive
  • strlcat - Concatenate 2 null-terminated strings, with length boundary.
  • strlcomp - Compare limited number of characters of 2 null-terminated strings
  • strlcopy - Copy a null-terminated string, limited in length.
  • strlen - Length of a null-terminated string.
  • strlicomp - Compare limited number of characters in 2 null-terminated strings, ignoring case.
  • strlower - Convert null-terminated string to all-lowercase.
  • strmove - Move a null-terminated string to new location.
  • strnew - Allocate room for new null-terminated string.
  • strpas - Convert a null-terminated string to a shortstring.
  • strpcopy - Copy a pascal string to a null-terminated string
  • strpos - Search for a null-terminated substring in a null-terminated string
  • strriscan - Scan a string reversely for a character, case-insensitive
  • strrscan - Find last occurrence of a character in a null-terminated string.
  • strscan - Find first occurrence of a character in a null-terminated string.
  • strupper - Convert null-terminated string to all-uppercase

Sets

Implement Pascal sets and set operations.

Support program parameters

from wirth's standard:

program = program-heading ';' program-block '.'.
program-block = block.
program-heading = 'program' identifier [ '(' program-parameter-list ')' ] .
program-parameter-list = identifier-list.

EDIT:
this includes binding of file names/paths to file type variables, example:

program copy (f, g);
var f, g : file of char;
    c: char;
begin
  reset(f) ; rewrite(g);
  while not eof(f) do begin
    read(f, c); write(g, c);
  end;
end.

execution:
trupple copy.pas alpha.txt bravo.txt

Comments

Wirth's pascal:
Where a commentary shall be any sequence of characters and separations of lines, containing neither } nor *), the construct

( '{' | '(' ) commentary ( ')' | '}' )

shall be a comment if neither the { nor the (* occurs within a character-string or within a commentary.

NOTES

1 A comment may thus commence with { and end with ), or commence with ( and end with }.

2 The sequence (*) cannot occur in a commentary even though the sequence {) can.

Turbo Pascal:
comment beginnig with { must end with } and comment beginnig with (* must end with *).

Compilation time checking

Implement type checking during compilation time:

  • make types table
  • mark expression type in ExpressionNode (Long, Boolean, Char, ...)
  • check type in assignments
  • check types in operations
  • check whether if condition is a boolean expression
  • check inside the set constructor if all values have the same type
  • check in with statement if the identifiers are records
  • compare subroutine's actual parameters with formal parameters
  • compare subroutine headers upon forwarding
  • goto - check if it possible to jump to specified label (as described in standard)
  • range type checks - this is a runtime check -> whether an assigned value to a range type is in range of that type

Record

  • defining custom record type
  • using variable of record type
  • with statement

Quote parsing broken

@Test
public void stringDoubleQuotesTwoTimes() {
    test("program quoting; begin writeln('''', '''') end.", "''");
}

The test program prints '', '' instead of ''.

Second parser

Create two separate parsers: one for wirth's pascal and the second one for turbo pascal

Type

Implement Type statements.

Fix ' in string

Character sequence '' in string shall represent ' character in string.

Block in wirth's pascal

block = label-declaration-part constant-definition-part type-definition-part
variable-declaration-part procedure-and-function-declaration-part
statement-part.

    label-declaration-part = [ 'label' label { ',' label } ' ;' ].

    constant-definition-part = [ 'const' constant-definition ' ;' { constant-definition ';' } ].

    type-definition-part = [ 'type' type-definition ' ;' { type-definition ';' } ].

    variable-declaration-part = [ 'var' variable-declaration ' ;' { variable-declaration ';' } ].

    procedure-and-function-declaration-part = { ( procedure-declaration
                                                | function-declaration ) ';' }.

Source code organization

It would be nice if the project would follow a more standardized source code organization.

The src should be split into src and src-test: that would simplify compilation of Trupple with and without tests (alternative naming is src/java and src/test-java, or src/main and src/test). And the lib folder can be a top-level one.

Unable to run JUnit from Ant

Classpath is missing in the <junit> task:

diff --git a/build.xml b/build.xml
index 3be40df..e265e95 100644
--- a/build.xml
+++ b/build.xml
@@ -67,6 +67,7 @@
                 <fileset dir="${lib.dir}">
                     <include name="**/*.jar"/>
                 </fileset>
+                <pathelement location="${build.dir}"/>
             </classpath>
 
             <batchtest todir="${reports.dir}">

Unit: crt

Implement crt unit:

  • AssignCrt - Assign file to CRT.
  • ClrEol - Clear from cursor position till end of line.
  • ClrScr - Clear current window.
  • cursorbig - Show big cursor
  • cursoroff - Hide cursor
  • cursoron - Display cursor
  • Delay - Delay program execution.
  • DelLine - Delete line at cursor position.
  • GotoXY - Set cursor position on screen.
  • HighVideo - Switch to highlighted text mode
  • InsLine - Insert an empty line at cursor position
  • KeyPressed - Check if there is a keypress in the keybuffer
  • LowVideo - Switch to low intensity colors.
  • NormVideo - Return to normal (startup) modus
  • NoSound - Stop system speaker
  • ReadKey - Read key from keybuffer
  • Sound - Sound system speaker
  • TextBackground - Set text background
  • TextColor - Set text color
  • TextMode - Set screen mode.
  • WhereX - Return X (horizontal) cursor position
  • WhereY - Return Y (vertical) cursor position
  • Window - Create new window on screen.

Support required subroutines

File handling procedures (Pre-requisite: #4 ):

  • rewrite(f)
  • put(f)
  • reset(f)
  • get(f)
  • read(f, references...);
  • write(f, references...);

Dynamic allocation procedures (Pre-requisite: #5 ):

  • new(p)
  • new(p,c l ,...,cn)
  • dispose(q)
  • dispose(q,kl ,...,km)

Arithmetic functions (Pre-requisite: none ):

  • abs(x) absolute value of x
  • sqr(x) square of x, It shall be an error if such a value does not exist.
  • sin(x) sine of x, where x is in radians
  • cos(x) cosine of x, where x is in radians
  • exp(x) base of natural logarithms raised to the power x
  • ln(x) natural logarithm of x, if x is greater than zero, It shall be an error if x is not greater than zero.
  • sqrt(x) non-negative square root of x, if x is not negative, It shall be an error if x is negative.
  • arctan(x)

Transfer functions (Pre-requisite: none ):

  • trunc(x)
  • round(x)

Ordinal functions (Pre-requisite: none ):

  • ord(x)
  • chr(x)
  • succ(x)
  • pred(x)

Boolean functions (Pre-requisite: #4 ):

  • odd(x)
  • eof(f)
  • eol(f)

Support for `program' keyword

The simplest program in standard Pascal is not runnable:

program Hello;
begin
	writeln('Hello, World!');
end.
$ java -cp build/:Trupple.jar cz.cuni.mff.d3s.trupple.compiler.CompilerMain Hello.pas
-- line 1 col 1: invalid Pascal
Errors while parsing source file, the code cannot be interpreted...

Idea: a bit more readable unit tests

The current unit tests force the developer to inherit from JUnitTest and then uses an overloaded method to actually execute the test.

Following snippet builds the test a bit more slowly but it clearly states what are the individual strings (note that newlines are added automatically to individual arguments of the setSource to decrease occurrences of the escape sequences). The first test uses fluent interface to make the code more compact.

@Test
public void copy() {
    TruppleTest
        .create()
        .setSource(
            "program copy;",
            "var i : integer;",
            "begin readln(i); writeln(i); end."
        )
        .setInput("42");
        .expectsOutput("42");
        .run();
}
@Test
public void simpleUnit() {
    TruppleTest test = new TruppleTest();
    test.addImport(
        "UNIT math;",
        "",
        "INTERFACE",
        "",
        "function add(a,b:integer): integer;",
        /* etc. */
    );
    test.setStandard("tp6");
    test.setSource(
        "uses math;",
        "begin",
        "    write(add(3,5));",
        "end."
    );
    test.expectsOutput("8");
    test.run();
}

Standard flag

The compiler shall support flag which specifies the Pascal standard that will be used during the interpretation (e.g.: --std=turbo)

NOTE: break is not supported by original standard

  • flag
  • break statement

Unit bugs

Fix bugs in custom units:

  • private/global variables
  • custom types

Support all subrange types

subrange-type = constant '..' constant.

Examples:
1..100
-10..+10
red..green
'0'..'9'

donst forget to upgrade tests for Sets

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.