Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

53 add option to parsejava to print ast in json #68

Merged
merged 39 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
39 commits
Select commit Hold shift + click to select a range
0734e66
feat: add base jackson files to lib folder
Rarity-Belle Oct 11, 2023
00e878e
fix: move lib into src
Rarity-Belle Oct 16, 2023
8d8b5cf
Merge branch 'main' into 53-add-option-to-parsejava-to-print-ast-in-json
Rarity-Belle Oct 18, 2023
fa122d2
feat: add ParseJSONAST and test grammar
Rarity-Belle Oct 18, 2023
caf1594
update java version (revert me later?)
StoneyJackson Oct 18, 2023
94213cb
update java (part 2)
StoneyJackson Oct 18, 2023
f6a67ef
fix: use raw strings for regex in plcc.py
StoneyJackson Oct 18, 2023
2bcabca
permission test
Rarity-Belle Oct 20, 2023
299b2cf
Revert "permission test"
Rarity-Belle Oct 20, 2023
390d6ca
fix: update ParseJSONAST
WilliamBowery Oct 23, 2023
5c52d8e
feat: update parse script to include json option
WilliamBowery Oct 24, 2023
21bad33
feat: convert the parse tree to json format
WilliamBowery Oct 24, 2023
1542328
feat: add compiler command for jar files
WilliamBowery Oct 24, 2023
4395892
fix: update name of ParseJSONAST
WilliamBowery Oct 24, 2023
4d8fb68
fix: fixed grep eating --json
Rarity-Belle Oct 24, 2023
32adb59
fix: fixed missing bracket
Rarity-Belle Oct 24, 2023
4392582
fix: fix parse brackets
Rarity-Belle Oct 24, 2023
fcbb81f
make it compile, run, and explode
StoneyJackson Oct 25, 2023
ad0e317
fix: serializer serializes now
Rarity-Belle Nov 1, 2023
b96260c
fix: show parent class names & indent output
Rarity-Belle Nov 1, 2023
3a2e60f
fix: remove use of new Java switch statements/expressions (#62)
StoneyJackson Oct 29, 2023
d0bc717
wip: show class names in generated JSON file
Rarity-Belle Nov 1, 2023
302f7cd
wip: add python option to plccmk
Rarity-Belle Nov 9, 2023
7c8eeba
wip: add --python option to plcc.py
Rarity-Belle Nov 15, 2023
07e545b
fix: incorrect array index in --python option
Rarity-Belle Nov 15, 2023
22b7f8d
test: prints-json-ast
StoneyJackson Nov 16, 2023
f7e7837
test: fix last commit
StoneyJackson Nov 16, 2023
38ec7d8
fix: update python option to json-ast
Rarity-Belle Nov 16, 2023
2856e54
fix: fix malformed flag, temp fix?
Rarity-Belle Nov 16, 2023
fd9e674
fix make --jsonast option copy ParseJsonAst.java to /Java
WilliamBowery Nov 16, 2023
f9790fc
fix: update --jsonast to --json_ast
WilliamBowery Nov 16, 2023
08dc5e8
fix: rename output file, fix(?) bats test
Rarity-Belle Nov 16, 2023
b4c1405
feat: ParseJsonAST prints to stdout
Rarity-Belle Nov 17, 2023
2399774
wip: test works as intended?
Rarity-Belle Nov 17, 2023
67b52f7
cleanup: remove example grammar, program, and json files from root
Rarity-Belle Nov 17, 2023
732a302
Merge branch 'main' into 53-add-option-to-parsejava-to-print-ast-in-json
StoneyJackson Nov 21, 2023
dc1f2ed
Merge branch 'main' into 53-add-option-to-parsejava-to-print-ast-in-json
Rarity-Belle Nov 29, 2023
5fa2725
docs: add info relating to --json_ast option
Rarity-Belle Nov 29, 2023
8c20da9
tweaks
StoneyJackson Nov 29, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 0 additions & 2 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ Java/
.mtj.tmp/

# Package Files #
*.jar
*.war
*.nar
*.ear
Expand All @@ -43,7 +42,6 @@ dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
Expand Down
2 changes: 2 additions & 0 deletions .gitpod.yml
Original file line number Diff line number Diff line change
Expand Up @@ -8,3 +8,5 @@ tasks:
export PATH="$LIBPLCC:$PATH"
' >> "$HOME/.bashrc"
source "$HOME/.bashrc"
- name: Update Java
command: sdk install java < /dev/null
18 changes: 14 additions & 4 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ for installing PLCC into a Bash Environment.

### Bash Environment

maxOS and Linux come with Bash. Windows users should
macOS and Linux come with Bash. Windows users should
follow the instructions above to first get a Bash
environment, then return and follow these directions.

Expand Down Expand Up @@ -257,19 +257,21 @@ $
plcc file
runs plcc.py on 'file', which generates
code in a directory named 'Java/'.
plccmk [-c] [file]
plccmk [-c] [--json_ast] [file]
runs plcc.py on file and compiles its results.
'-c' Remove 'Java/' before regenerating it.
'-c' Removes 'Java/' before regenerating it.
'--json_ast' add support to print JSON ASTs.
'file' defaults to 'grammar'
scan [file...]
Run Java/Scan on each file and then stdin.
Scans input printing recognized token.
parse [-t] [-n] [file...]
parse [-t] [-n] [--json_ast] [file...]
Run Java/Parser on each file and then stdin.
Scans and parses input, printing OK for recognized
programs and error otherwise.
'-t' Print trace (i.e., parse tree).
'-n' Suppress prompt.
'--json_ast' print JSON AST to stdout.
rep [-t] [-n] [file...]
Run Java/Rep on each file and then stdin.
REP = Read, Execute, and Print loop.
Expand All @@ -279,6 +281,14 @@ rep [-t] [-n] [file...]
'-n' Suppress prompt.
```

To print a JSON AST for a program, pass `--json_ast` to both `plccmk`
and `parse`, like so:

```bash
plccmk --json_ast -c YOUR_GRAMMAR_FILE
parse --json_ast < YOUR_PROGRAM_FILE
```

## Grammar Files

A grammar file consist of three sections separated by a line containing
Expand Down
46 changes: 46 additions & 0 deletions src/Std/ParseJsonAst.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import java.util.*;
import java.io.*;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.PolymorphicTypeValidator;
import com.fasterxml.jackson.databind.jsontype.BasicPolymorphicTypeValidator;
import com.fasterxml.jackson.core.JsonProcessingException;



public class ParseJsonAst extends ProcessFiles {

// Parse the program and call $ok() on the resulting parse tree
public void action(Scan scn, Trace trace) {
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
objectMapper.enable(SerializationFeature.WRAP_ROOT_VALUE);
objectMapper.enable(SerializationFeature.INDENT_OUTPUT);

PolymorphicTypeValidator ptv = BasicPolymorphicTypeValidator
.builder()
.allowIfBaseType(Object.class) // Can change "Object" to any type, we can look back at this later to be more specific
.build();

objectMapper.activateDefaultTypingAsProperty(ptv, ObjectMapper.DefaultTyping.NON_FINAL, "$type");

_Start parseTree = _Start.parse(scn, trace);
parseTree.$ok();
try
{
String json = objectMapper.writeValueAsString(parseTree);
System.out.println(json);
}
catch (JsonProcessingException e)
{
e.printStackTrace();
}

}

// Read programs from command-line files
// and then read programs from standard input.
public static void main(String [] args) {
new ParseJsonAst().processFiles(args);
}
}
Binary file added src/lib/jackson-annotations-2.15.2.jar
Binary file not shown.
Binary file added src/lib/jackson-core-2.15.2.jar
Binary file not shown.
Binary file added src/lib/jackson-databind-2.15.2.jar
Binary file not shown.
30 changes: 29 additions & 1 deletion src/parse
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
#!/bin/bash

JACKSON_VERSION="2.15.2"
JACKSON_ANNOTATIONS="${LIBPLCC}/lib/jackson-annotations-${JACKSON_VERSION}.jar"
JACKSON_CORE="${LIBPLCC}/lib/jackson-core-${JACKSON_VERSION}.jar"
JACKSON_DATABIND="${LIBPLCC}/lib/jackson-databind-${JACKSON_VERSION}.jar"
CP="${JACKSON_ANNOTATIONS}:${JACKSON_CORE}:${JACKSON_DATABIND}"

[ -d Java ] || {
echo "Java directory missing" >&2
exit 1
Expand All @@ -10,4 +16,26 @@
exit 2
}

java -cp ./Java Parse $*
if echo "$*" | grep -- "--json_ast" &> /dev/null
then

ARGS=()
while [ $# -gt 0 ] ; do
case "$1" in
--json_ast)
shift
;;
*)
ARGS+=("$1")
shift
;;
esac
done

if ! java -cp "./Java:${CP}" ParseJsonAst "${ARGS[@]}" ; then
>&2 echo "Did you forget to pass --json_ast to plccmk?"
exit 1
fi
else
java -cp ./Java Parse $*
fi
13 changes: 11 additions & 2 deletions src/plcc.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@
import io
import shutil
import tempfile

argv = sys.argv[1:] # skip over the command-line argument

# current file information
Expand Down Expand Up @@ -107,13 +106,15 @@ def main():
print(version.get_version())
sys.exit(0)

jsonAstInit()

nxt = nextLine() # nxt is the next line generator
lex(nxt) # lexical analyzer generation
par(nxt) # LL(1) check and parser generation
sem(nxt) # semantic actions

def plccInit():
global flags, STD, STDT, STDP
global flags, argv, STD, STDT, STDP
STDT = ['ILazy','IMatch','IScan','ITrace', 'Trace', 'PLCCException', 'Scan']
STDP = ['ProcessFiles','Parse','Rep']
STD = STDT + STDP
Expand All @@ -134,6 +135,14 @@ def plccInit():
flags['semantics'] = True # create semantics routines
flags['nowrite'] = False # when True, produce *no* file output

def jsonAstInit():
global flags, STD, STDP
if 'json_ast' in flags and flags['json_ast']:
if 'ParseJsonAst' not in STDP:
if 'ParseJsonAst' not in STD:
STDP.append('ParseJsonAst')
flags['ParseJsonAst'] = 'ParseJsonAst'

def lex(nxt):
# print('=== lexical specification')
# Handle any flags appearing at beginning of lexical spec section;
Expand Down
27 changes: 26 additions & 1 deletion src/plccmk
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,12 @@ LIB="${LIBPLCC:-/usr/local/pub/plcc/PLCC}"
PYTHON3=python3
PLCC="$LIB/plcc.py"

JACKSON_VERSION="2.15.2"
JACKSON_ANNOTATIONS="${LIBPLCC}/lib/jackson-annotations-${JACKSON_VERSION}.jar"
JACKSON_CORE="${LIBPLCC}/lib/jackson-core-${JACKSON_VERSION}.jar"
JACKSON_DATABIND="${LIBPLCC}/lib/jackson-databind-${JACKSON_VERSION}.jar"
CP="${JACKSON_ANNOTATIONS}:${JACKSON_CORE}:${JACKSON_DATABIND}"

if [ "$1" = "-c" ];
then
rm Java/*.java Java/*.class &>/dev/null
Expand Down Expand Up @@ -33,5 +39,24 @@ $PYTHON3 "$PLCC" $FILES || {
echo "Java directory missing" >&2
exit 5
}
if echo "$*" | grep -- "--json_ast" &> /dev/null
then

ARGS=()
while [ $# -gt 0 ] ; do
case "$1" in
--json_ast)
shift
;;
*)
ARGS+=("$1")
shift
;;
esac
done

(cd ./Java ; javac -cp ".:${CP}" *.java)
else
(cd ./Java ; javac *.java)
fi

(cd ./Java ; javac *.java)
36 changes: 36 additions & 0 deletions tests/plcc/can-print-json-ast/expected.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
OK
{
"Program" : {
"$type" : "Program",
"exp" : {
"$type" : "PrimappExp",
"prim" : {
"$type" : "AddPrim"
},
"rands" : {
"$type" : "Rands",
"expList" : [ "java.util.ArrayList", [ {
"$type" : "LitExp",
"lit" : {
"$type" : "Token",
"match" : "LIT",
"str" : "3",
"lno" : 1,
"line" : "+(3, 2)\n",
"eof" : false
}
}, {
"$type" : "LitExp",
"lit" : {
"$type" : "Token",
"match" : "LIT",
"str" : "2",
"lno" : 1,
"line" : "+(3, 2)\n",
"eof" : false
}
} ] ]
}
}
}
}
21 changes: 21 additions & 0 deletions tests/plcc/can-print-json-ast/given-grammar.lang
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
skip WHITESPACE '\s+'
skip COMMENT '%.*'
LIT '\d+'
LPAREN '\('
RPAREN '\)'
COMMA ','
ADDOP '\+'
SUBOP '\-'
ADD1OP 'add1'
SUB1OP 'sub1'
VAR '[A-Za-z]\w*'
%
<program> ::= <exp>
<exp>:LitExp ::= <LIT>
<exp>:VarExp ::= <VAR>
<exp>:PrimappExp ::= <prim> LPAREN <rands> RPAREN
<rands> **= <exp> +COMMA
<prim>:AddPrim ::= ADDOP
<prim>:SubPrim ::= SUBOP
<prim>:Add1Prim ::= ADD1OP
<prim>:Sub1Prim ::= SUB1OP
1 change: 1 addition & 0 deletions tests/plcc/can-print-json-ast/given-program.lang
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
+(3, 2)
19 changes: 19 additions & 0 deletions tests/plcc/can-print-json-ast/prints-json-ast.bats
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
#!/usr/bin/env bats

@test "PLCC can print JSON AST." {
FILES="expected.json given-grammar.lang given-program.lang"
for f in $FILES ; do
cp "${BATS_TEST_DIRNAME}/${f}" "${BATS_TMPDIR}"
done

cp "${BATS_TEST_DIRNAME}"/* "$BATS_TMPDIR/"
cd "${BATS_TMPDIR}"
plccmk --json_ast given-grammar.lang
parse -n --json_ast < given-program.lang > result.json
diff expected.json result.json

for f in $FILES ; do
rm "${BATS_TMPDIR}/${f}"
done
rm "${BATS_TMPDIR}/result.json"
}