Initial contribution

This commit is contained in:
Michiel Beemster 2018-04-10 17:03:59 +02:00
parent 7b5cc4fa59
commit 11d9ce37aa
580 changed files with 155133 additions and 162 deletions

61
src/idlc/CMakeLists.txt Normal file
View file

@ -0,0 +1,61 @@
#
# Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v. 2.0 which is available at
# http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
# v. 1.0 which is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
#
# Verify Maven is available
find_package(Maven 3.0 REQUIRED)
file(GLOB_RECURSE IDLC_G_SOURCES LIST_DIRECTORIES true *.g)
file(GLOB_RECURSE IDLC_G4_SOURCES LIST_DIRECTORIES true *.g4)
file(GLOB_RECURSE IDLC_JAVA_SOURCES LIST_DIRECTORIES true *.java)
file(GLOB_RECURSE IDLC_ST_SOURCES LIST_DIRECTORIES true *.st?)
set(IDLC_JAR "${CMAKE_CURRENT_BINARY_DIR}/target/idlc-jar-with-dependencies.jar")
mark_as_advanced(IDLC_JAR)
# Maven is executed within the idlc directory located in the build directory
# and generated sources are stored in idlc/target. Non-generated sources,
# however, do not reside in the build directory and Maven must be instructed
# to use those. To allow maven to be executed from both the source and build
# directories (idlc may be moved to it's own repository), the pom.xml file is
# pulled through the configure_file function with basedir set to the original
# source directory. It is a cute little hack to avoid having to use different
# profiles etc.
set(basedir "${CMAKE_CURRENT_SOURCE_DIR}/src")
mark_as_advanced(basedir)
set(IDLC_POM_FILE "src/pom.xml.in")
configure_file(${IDLC_POM_FILE} "pom.xml")
configure_file("src/org/eclipse/cyclonedds/Project.java.in" "org/eclipse/cyclonedds/Project.java")
add_custom_command(
OUTPUT "${IDLC_JAR}"
COMMAND "${Maven_EXECUTABLE}"
ARGS "-q" "package"
DEPENDS ${IDLC_POM_FILE} ${IDLC_G_SOURCES} ${IDLC_G4_SOURCES} ${IDLC_JAVA_SOURCES} ${IDLC_ST_SOURCES}
COMMENT "Building JAR file ${IDLC_JAR}")
include(cmake/IdlcGenerate.cmake)
install(
FILES "cmake/IdlcGenerate.cmake"
DESTINATION "${CMAKE_INSTALL_DATADIR}/${CMAKE_PROJECT_NAME}/idlc"
COMPONENT dev)
install(
FILES "${IDLC_SCRIPT_IN}"
DESTINATION "${CMAKE_INSTALL_DATADIR}/${CMAKE_PROJECT_NAME}/idlc"
COMPONENT dev)
install(
FILES "${IDLC_JAR}"
DESTINATION "${CMAKE_INSTALL_DATADIR}/${CMAKE_PROJECT_NAME}/idlc"
PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_WRITE GROUP_EXECUTE WORLD_READ WORLD_EXECUTE
COMPONENT dev)

View file

@ -0,0 +1,88 @@
#
# Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v. 2.0 which is available at
# http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
# v. 1.0 which is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
#
if(NOT IDLC_JAR)
set(IDLC_JAR "${CMAKE_CURRENT_LIST_DIR}/idlc-jar-with-dependencies.jar")
endif()
set(LINE_ENDINGS "UNIX")
if("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows")
set(EXTENSION ".bat")
set(LINE_ENDINGS "WIN32")
endif()
set(IDLC_DIR "${CMAKE_CURRENT_BINARY_DIR}" CACHE STRING "")
set(IDLC "dds_idlc${EXTENSION}" CACHE STRING "")
mark_as_advanced(IDLC_DIR IDLC)
set(IDLC_SCRIPT_IN "${CMAKE_CURRENT_LIST_DIR}/dds_idlc${EXTENSION}.in")
configure_file(
"${IDLC_SCRIPT_IN}" "${IDLC}"
@ONLY
NEWLINE_STYLE ${LINE_ENDINGS})
# FIXME: C++ IDL compiler depends idlpp. Leave it disabled for now.
#configure_file(
# "cmake/dds_idlcpp${EXTENSION}.in"
# "dds_idlcpp${EXTENSION}"
# @ONLY
# NEWLINE_STYLE ${LINE_ENDINGS})
if(NOT ("${CMAKE_SYSTEM_NAME}" STREQUAL "Windows"))
execute_process(COMMAND chmod +x "${IDLC_DIR}/${IDLC}")
endif()
add_custom_target(idlc ALL DEPENDS "${IDLC_JAR}")
function(IDLC_GENERATE _target)
if(NOT ARGN)
message(FATAL_ERROR "idlc_generate called without any idl files")
endif()
if (NOT IDLC_ARGS)
set(IDLC_ARGS)
endif()
set(_dir "${CMAKE_CURRENT_BINARY_DIR}")
set(_sources)
set(_headers)
foreach(FIL ${ARGN})
get_filename_component(ABS_FIL ${FIL} ABSOLUTE)
get_filename_component(FIL_WE ${FIL} NAME_WE)
set(_source "${_dir}/${FIL_WE}.c")
set(_header "${_dir}/${FIL_WE}.h")
list(APPEND _sources "${_source}")
list(APPEND _headers "${_header}")
add_custom_command(
OUTPUT "${_source}" "${_header}"
COMMAND "${IDLC_DIR}/${IDLC}"
ARGS ${IDLC_ARGS} ${ABS_FIL}
DEPENDS "${ABS_FIL}" idlc
COMMENT "Running idlc on ${FIL}"
VERBATIM)
endforeach()
add_custom_target(
"${_target}_idlc_generate"
DEPENDS "${_sources}" "${_headers}"
)
set_source_files_properties(
${_sources} ${_headers} PROPERTIES GENERATED TRUE)
add_library(${_target} INTERFACE)
target_sources(${_target} INTERFACE ${_sources} ${_headers})
target_include_directories(${_target} INTERFACE "${_dir}")
add_dependencies(${_target} "${_target}_idlc_generate")
endfunction()

View file

@ -0,0 +1,19 @@
@echo off
REM Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
REM
REM This program and the accompanying materials are made available under the
REM terms of the Eclipse Public License v. 2.0 which is available at
REM http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
REM v. 1.0 which is available at
REM http://www.eclipse.org/org/documents/edl-v10.php.
REM
REM SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
if "%CLASSPATH%"=="" (
set "CLASSPATH=@IDLC_JAR@"
) else (
set "CLASSPATH=@IDLC_JAR@;%CLASSPATH%"
)
java org.eclipse.cyclonedds.compilers.Idlc %*

View file

@ -0,0 +1,13 @@
#!/bin/sh
#
# Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v. 2.0 which is available at
# http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
# v. 1.0 which is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
#
java -classpath "@IDLC_JAR@" org.eclipse.cyclonedds.compilers.Idlc "$@"

View file

@ -0,0 +1,19 @@
@echo off
REM Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
REM
REM This program and the accompanying materials are made available under the
REM terms of the Eclipse Public License v. 2.0 which is available at
REM http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
REM v. 1.0 which is available at
REM http://www.eclipse.org/org/documents/edl-v10.php.
REM
REM SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
if "%CLASSPATH%"=="" (
set "CLASSPATH=@IDLC_JAR@"
) else (
set "CLASSPATH=@IDLC_JAR@;%CLASSPATH%"
)
java org.eclipse.cyclonedds.compilers.Idlcpp %*

View file

@ -0,0 +1,13 @@
#!/bin/sh
#
# Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
#
# This program and the accompanying materials are made available under the
# terms of the Eclipse Public License v. 2.0 which is available at
# http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
# v. 1.0 which is available at
# http://www.eclipse.org/org/documents/edl-v10.php.
#
# SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
#
java -classpath "@IDLC_JAR@" org.eclipse.cyclonedds.compilers.Idlcpp "$@"

View file

@ -0,0 +1,245 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import java.io.*;
import java.util.*;
import org.antlr.v4.runtime.*;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.*;
import org.eclipse.cyclonedds.parser.*;
import org.eclipse.cyclonedds.generator.GenVisitor;
import org.eclipse.cyclonedds.compilers.IdlcCmdOptions;
public class Compiler
{
private static class PreProcAwareListener extends BaseErrorListener
{
public void syntaxError
(
Recognizer<?,?> recognizer,
Object wrongSymbol,
int line,
int column,
String msg,
RecognitionException e
)
{
System.err.println
("Error: At " + params.linetab.getRealPosition (line) + ", " + msg);
}
}
public static void run (IdlcCmdOptions opts)
{
if (opts.version)
{
version ();
return;
}
try
{
if (!LicenseMgr.checkout (Project.nameCaps + "_IDLC"))
{
System.exit (1);
}
String pathSep = System.getProperty ("file.separator");
String outpath = (opts.outputdir == null) ? "" : opts.outputdir + pathSep;
String fileRoot;
IIdlPreprocessor preprocessor = IdlPreprocessorFactory.create ();
IIdlPreprocessorStatus ppstatus;
Map<File, List<File>> ppdependencies = new TreeMap<File, List<File>> ();
CharArrayWriter ppresult = new CharArrayWriter ();
IIdlPreprocessorParams ppparams = preprocessor.createPreprocessorParams ();
for (String s : opts.includes)
{
ppparams.addIncludeDirectory (new File (s));
}
for (Map.Entry <String, String> macro : opts.macros.entrySet ())
{
ppparams.addMacroDefinition (macro.getKey (), macro.getValue ());
}
for (String arg : opts.files)
{
params = new IdlParams (opts);
if (!arg.endsWith (".idl"))
{
arg += ".idl";
}
if (System.getProperty ("file.separator").equals ("\\"))
{
/* Preprocessor does this conversion on Windows, so we do the same */
arg = arg.replace ('\\', '/');
}
File idl = new File(arg);
if (idl.exists() && idl.isFile())
{
if (!opts.quiet && !opts.pponly)
{
System.out.println ("Compiling " + idl.getPath ());
}
}
else
{
System.err.println
("Input IDL file " + idl.getPath () + " is not valid");
licenseCheckAndExit (1);
}
fileRoot =
idl.getName ().substring (0, idl.getName ().lastIndexOf ('.'));
ppstatus =
preprocessor.preprocess (ppparams, idl, ppresult, ppdependencies);
if (!ppstatus.isOK ())
{
System.err.println ("Error: At " + ppstatus.getFilename () + ":" + ppstatus.getLine () + ", " + ppstatus.getMessage ());
licenseCheckAndExit(1);
}
if (opts.pponly)
{
System.out.println (ppresult.toCharArray ());
licenseCheckAndExit (0);
}
ANTLRInputStream input =
new ANTLRInputStream (ppresult.toCharArray(), ppresult.size ());
Lexer lexer = new IDLLexer (input);
CommonTokenStream tokens = new CommonTokenStream (lexer);
tokens.fill ();
if (opts.dumptokens)
{
List<Token> tlist = tokens.getTokens ();
Iterator<Token> it = tlist.iterator ();
Token t;
while (it.hasNext ())
{
t = it.next ();
if (t.getChannel() == Token.DEFAULT_CHANNEL)
{
System.out.println (t.getText ());
}
}
licenseCheckAndExit (0);
}
params.linetab =
new LineTable (arg, tokens.getTokens ().iterator (), params.forcpp);
IDLParser parser = new IDLParser (tokens);
parser.removeErrorListeners ();
parser.addErrorListener (new PreProcAwareListener ());
try
{
ParserRuleContext tree = (ParserRuleContext)parser.specification ();
if (parser.getNumberOfSyntaxErrors () != 0)
{
licenseCheckAndExit (1);
}
if (opts.dumptree)
{
if (java.awt.GraphicsEnvironment.isHeadless ())
{
System.out.println (tree.toStringTree (parser));
}
else
{
javax.swing.JDialog jd = tree.inspect (parser).get ();
jd.setVisible (false);
jd.setModalityType (java.awt.Dialog.ModalityType.APPLICATION_MODAL);
jd.setVisible (true);
}
licenseCheckAndExit(0);
}
params.symtab = new SymbolTable ();
GenSymbolTable gst = new GenSymbolTable (params);
gst.visit (tree);
if (gst.getErrorCount () != 0)
{
licenseCheckAndExit (1);
}
if (gst.unresolvedSymbols ())
{
licenseCheckAndExit (1);
}
if (opts.dumpsymbols)
{
System.out.println ("Symbol table pass complete, symbols are:");
params.symtab.dump ();
licenseCheckAndExit (0);
}
params.basename = fileRoot;
if (params.forcpp)
{
fileRoot = fileRoot.concat ("-cyclonedds");
}
try
{
GenVisitor codegenh = new GenVisitor (params, "org/eclipse/cyclonedds/templates/h/templates.stg");
codegenh.visit (tree);
codegenh.writeToFile (outpath + fileRoot + ".h");
if (!params.notopics)
{
params.quiet = true;
GenVisitor codegenc = new GenVisitor (params, "org/eclipse/cyclonedds/templates/c/templates.stg");
codegenc.visit (tree);
codegenc.writeToFile (outpath + fileRoot + ".c");
}
}
catch (IOException x)
{
System.err.format("IOException: %s%n", x);
licenseCheckAndExit (1);
}
}
catch (RecognitionException r)
{
r.printStackTrace ();
licenseCheckAndExit (1);
}
}
}
catch (Exception e)
{
e.printStackTrace ();
}
finally
{
LicenseMgr.checkin ();
}
}
private static void licenseCheckAndExit (int exitStatus)
{
LicenseMgr.checkin ();
System.exit (exitStatus);
}
private static void version ()
{
System.out.print (Project.name);
System.out.println ("C IDL Compiler v" + Project.version);
}
private static IdlParams params;
}

View file

@ -0,0 +1,25 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
public class EnumSymbol extends TypeDefSymbol
{
public EnumSymbol (ScopedName name)
{
super (name);
}
public String toString ()
{
return "Enum";
}
}

View file

@ -0,0 +1,676 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import java.io.*;
import java.util.*;
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.tree.TerminalNode;
import org.eclipse.cyclonedds.parser.IDLParser;
public class GenSymbolTable extends org.eclipse.cyclonedds.parser.IDLBaseVisitor <Void>
{
private static class TD
{
private void invalidate ()
{
valid = false;
}
private boolean isValid ()
{
return valid;
}
private void setInteger ()
{
isint = true;
}
private boolean isInteger ()
{
return isint;
}
private void setNonintConst ()
{
isnonint = true;
}
private boolean isNonintConst ()
{
return isnonint;
}
private boolean isint = false;
private boolean valid = true;
private boolean isnonint = false;
}
public GenSymbolTable (IdlParams params)
{
currentscope = new ScopedName ();
currentstruct = null;
currentTD = null;
inIntConst = false;
inNonintConst = false;
inSwitch = false;
declarations = new HashSet <ScopedName> ();
errorcount = 0;
this.params = params;
}
public int getErrorCount ()
{
return errorcount;
}
public Void visitModule (IDLParser.ModuleContext ctx)
{
Void result;
currentscope.addComponent (ctx.ID().getText());
result = super.visitModule (ctx);
currentscope.popComponent ();
return result;
}
public Void visitInterface_decl (IDLParser.Interface_declContext ctx)
{
Void result;
currentscope.addComponent (ctx.interface_header ().ID ().getText ());
result = super.visitInterface_body (ctx.interface_body ());
currentscope.popComponent ();
return result;
}
public Void visitStruct_type (IDLParser.Struct_typeContext ctx)
{
Void result;
boolean declared;
StructSymbol oldstruct = currentstruct;
currentscope.addComponent (ctx.ID ().getText ());
currentstruct = new StructSymbol (new ScopedName (currentscope));
result = super.visitStruct_type (ctx);
declared = declarations.remove (currentscope);
if (currentstruct.isValid ())
{
params.symtab.add (currentstruct);
}
else
{
if (params.lax && declared)
{
printErr
(
ctx.KW_STRUCT ().getSymbol ().getLine (),
"Definition of predeclared struct " + currentscope +
" contains unsupported data types"
);
}
}
currentstruct = oldstruct;
currentscope.popComponent ();
return result;
}
public Void visitSimple_declarator (IDLParser.Simple_declaratorContext ctx)
{
if (currentstruct != null)
{
StructSymbol stype = null;
try
{
IDLParser.MemberContext mem = (IDLParser.MemberContext)ctx.getParent ().getParent ().getParent ();
if (mem.type_spec ().simple_type_spec () != null)
{
IDLParser.Scoped_nameContext snctx = mem.type_spec ().simple_type_spec ().scoped_name ();
if (snctx != null)
{
stype = (StructSymbol)stresolve (snfromctx (snctx), isRelative (snctx));
}
}
else
{
if (mem.type_spec ().constr_type_spec () != null)
{
IDLParser.Struct_typeContext stctx = mem.type_spec ().constr_type_spec ().struct_type ();
if (stctx != null)
{
ScopedName stname = new ScopedName (currentscope);
stname.addComponent (stctx.ID ().getText ());
stype = (StructSymbol)params.symtab.getSymbol (stname);
}
}
}
}
catch (Exception ex)
{
}
if (stype != null)
{
currentstruct.addStructMember (ctx.ID ().getText (), stype);
}
else
{
currentstruct.addMember (ctx.ID ().getText ());
}
}
return super.visitSimple_declarator (ctx);
}
public Void visitArray_declarator (IDLParser.Array_declaratorContext ctx)
{
if (currentstruct != null)
{
currentstruct.addMember (ctx.ID ().getText ());
}
return super.visitArray_declarator (ctx);
}
public Void visitPragma_decl (IDLParser.Pragma_declContext ctx)
{
int line = ctx.LINE_PRAGMA().getSymbol ().getLine ();
StringTokenizer pragma = new StringTokenizer (ctx.LINE_PRAGMA().getText ());
pragma.nextToken (); /* Skip "#pragma" */
if (pragma.hasMoreTokens () && pragma.nextToken ().equals ("keylist"))
{
String topicType = pragma.nextToken ();
ScopedName topicSN = new ScopedName (topicType);
Symbol topic;
if (topicType.startsWith ("::"))
{
topic = params.symtab.resolve (null, topicSN);
}
else
{
topic = params.symtab.resolve (currentscope, topicSN);
}
if (topic == null || !(topic instanceof StructSymbol))
{
printErr
(
line,
"unable to resolve topic " + topicType + " for key, in scope " +
currentscope
);
}
else
{
StructSymbol topicStruct = (StructSymbol)topic;
String field;
while (pragma.hasMoreTokens ())
{
field = pragma.nextToken ();
if (!topicStruct.hasMember (field))
{
printErr
(line, "keyfield " + field + " is either missing or unsupported");
}
}
}
}
return super.visitPragma_decl (ctx);
}
public Void visitEnum_type (IDLParser.Enum_typeContext ctx)
{
Void result;
currentscope.addComponent (ctx.ID ().getText ());
params.symtab.add (new EnumSymbol (new ScopedName (currentscope)));
result = super.visitEnum_type (ctx);
currentscope.popComponent ();
return result;
}
public Void visitEnumerator (IDLParser.EnumeratorContext ctx)
{
ScopedName SN = new ScopedName (currentscope);
SN.popComponent ();
SN.addComponent (ctx.ID ().getText ());
params.symtab.add (new IntConstSymbol (SN));
return super.visitEnumerator (ctx);
}
public Void visitType_declarator (IDLParser.Type_declaratorContext ctx)
{
ScopedName newscope;
TypeDeclSymbol newTD;
Void result;
currentTD = new TD ();
result = super.visitType_declarator (ctx);
if (currentTD.isValid ())
{
for (IDLParser.DeclaratorContext dctx : ctx.declarators ().declarator ())
{
newscope = new ScopedName (currentscope);
if (dctx.simple_declarator () != null)
{
newscope.addComponent (dctx.simple_declarator ().ID ().getText ());
newTD = new TypeDeclSymbol
(
newscope,
ctx.type_spec (),
null,
currentTD.isInteger (),
currentTD.isNonintConst ()
);
}
else
{
newscope.addComponent
(dctx.complex_declarator ().array_declarator ().ID ().getText ());
newTD = new TypeDeclSymbol
(
newscope,
ctx.type_spec (),
dctx.complex_declarator ().array_declarator ().fixed_array_size (),
currentTD.isInteger (),
currentTD.isNonintConst ()
);
}
params.symtab.add (newTD);
}
}
currentTD = null;
return result;
}
private boolean isStructMember (IDLParser.Scoped_nameContext ctx)
{
try
{
return ctx.getParent ().getParent ().getParent () instanceof IDLParser.MemberContext;
}
catch (NullPointerException ex)
{
}
return false;
}
private ScopedName snfromctx (IDLParser.Scoped_nameContext ctx)
{
ScopedName result = new ScopedName ();
for (TerminalNode element : ctx.ID ())
{
result.addComponent (element.getSymbol ().getText ());
}
return result;
}
private boolean isRelative (IDLParser.Scoped_nameContext ctx)
{
return ctx.ID ().size () > ctx.DOUBLE_COLON ().size ();
}
private Symbol stresolve (ScopedName sn, boolean relative)
{
return params.symtab.resolve ((relative ? currentscope : null), sn);
}
public Void visitScoped_name (IDLParser.Scoped_nameContext ctx)
{
Symbol target;
ScopedName requestSN = snfromctx (ctx);
boolean relative = isRelative (ctx);
int line = ctx.ID (0).getSymbol ().getLine ();
target = stresolve (requestSN, relative);
if (target == null)
{
if (isStructMember (ctx) || inIntConst)
{
printErr (line, requestSN + " is not defined.");
}
else if (relative)
{
boolean found;
ScopedName s = new ScopedName (currentscope);
do
{
found = declarations.contains (s.catenate (requestSN));
}
while (!found && !s.popComponent().equals (""));
if (!found)
{
printErr (line, "unable to resolve name " + requestSN + " in scope " + currentscope);
}
}
else
{
if (!declarations.contains (requestSN))
{
printErr (line, "unable to resolve name " + requestSN);
}
}
}
else
{
boolean targetint = target instanceof IntConstSymbol;
boolean targetnonint = target instanceof OtherConstSymbol;
if (target instanceof TypeDeclSymbol)
{
targetint = ((TypeDeclSymbol)target).isInteger ();
targetnonint = ((TypeDeclSymbol)target).isNonintConst ();
}
if (currentTD != null)
{
if (targetint)
{
currentTD.setInteger ();
}
if (targetnonint)
{
currentTD.setNonintConst ();
}
}
boolean valid = true;
if (inIntConst || inSwitch)
{
valid = targetint;
}
else
if (inNonintConst)
{
valid = targetnonint;
}
if (!valid)
{
printErr (line, "scoped name " + target.name () + " does not refer to a valid type");
}
}
return super.visitScoped_name (ctx);
}
public Void visitConstr_forward_decl (IDLParser.Constr_forward_declContext ctx)
{
ScopedName decl = new ScopedName (currentscope);
decl.addComponent (ctx.ID ().getText ());
declarations.add (decl);
return super.visitConstr_forward_decl (ctx);
}
public Void visitCase_label (IDLParser.Case_labelContext ctx)
{
Void result;
inSwitch = true;
result = super.visitCase_label (ctx);
inSwitch = false;
return result;
}
public Void visitLiteral (IDLParser.LiteralContext ctx)
{
if (inIntConst)
{
if (ctx.INTEGER_LITERAL () == null && ctx.HEX_LITERAL () == null && ctx.OCTAL_LITERAL () == null)
{
printErr
(
ctx.getStart ().getLine (),
"non-integer literal in integer constant definition"
);
}
}
return super.visitLiteral (ctx);
}
public Void visitConst_decl (IDLParser.Const_declContext ctx)
{
Void result;
boolean iic = inIntConst;
boolean inic = inNonintConst;
boolean integral = false;
boolean valid = true;
IDLParser.Const_typeContext const_type = ctx.const_type ();
currentscope.addComponent (ctx.ID ().getText ());
if (const_type.integer_type() != null || const_type.octet_type () != null)
{
integral = true;
}
else
{
if (const_type.scoped_name() != null)
{
IDLParser.Scoped_nameContext snctx = const_type.scoped_name ();
Symbol stype = stresolve (snfromctx (snctx), isRelative (snctx));
if (stype instanceof TypeDeclSymbol)
{
if (((TypeDeclSymbol)stype).isInteger ())
{
integral = true;
}
else if (((TypeDeclSymbol)stype).isNonintConst ())
{
integral = false;
}
else
{
valid = false;
printErr
(
ctx.KW_CONST ().getSymbol ().getLine (),
"typedef " + stype.name () + " is not valid for const declaration"
);
}
}
else
{
// Error will be generated upstream
}
}
else
{
integral = false;
}
}
if (valid)
{
if (integral)
{
params.symtab.add (new IntConstSymbol (new ScopedName (currentscope)));
inIntConst = true;
}
else
{
params.symtab.add
(new OtherConstSymbol (new ScopedName (currentscope)));
inNonintConst = true;
}
}
result = super.visitConst_decl (ctx);
currentscope.popComponent ();
inIntConst = iic;
inNonintConst = inic;
return result;
}
public Void visitPositive_int_const (IDLParser.Positive_int_constContext ctx)
{
Void result;
boolean iic = inIntConst;
inIntConst = true;
result = super.visitPositive_int_const (ctx);
inIntConst = iic;
return result;
}
public Void visitUnion_type (IDLParser.Union_typeContext ctx)
{
Void result;
currentscope.addComponent (ctx.ID ().getText ());
params.symtab.add (new UnionSymbol (new ScopedName (currentscope)));
result = super.visitUnion_type (ctx);
currentscope.popComponent ();
return result;
}
/* Unsupported types */
private void bogusType (String reason, TerminalNode where)
{
if (currentstruct != null)
{
if (params.lax)
{
currentstruct.invalidate ();
}
else
{
printErr (where.getSymbol ().getLine (), reason);
}
}
if (currentTD != null)
{
if (params.lax)
{
currentTD.invalidate ();
}
else
{
printErr (where.getSymbol ().getLine (), reason);
}
}
}
/* Unsupported but mappable types */
public Void visitWide_char_type (IDLParser.Wide_char_typeContext ctx)
{
if (!params.mapwide)
{
bogusType
("wide char data not supported in" + Project.name, ctx.KW_WCHAR ());
}
return super.visitWide_char_type (ctx);
}
public Void visitWide_string_type (IDLParser.Wide_string_typeContext ctx)
{
if (!params.mapwide)
{
bogusType
("wide string data not supported in " + Project.name, ctx.KW_WSTRING ());
}
return super.visitWide_string_type (ctx);
}
/* These next ones NYI or potentially so */
public Void visitFixed_pt_type (IDLParser.Fixed_pt_typeContext ctx)
{
bogusType
("fixed point data not supported in " + Project.name, ctx.KW_FIXED ());
return super.visitFixed_pt_type (ctx);
}
public Void visitSequence_type (IDLParser.Sequence_typeContext ctx)
{
if (ctx.positive_int_const() != null)
{
bogusType
("bounded sequences not supported in " + Project.name, ctx.KW_SEQUENCE ());
}
return super.visitSequence_type (ctx);
}
/* And these aren't DDS */
public Void visitAny_type (IDLParser.Any_typeContext ctx)
{
bogusType ("any data not valid for DDS", ctx.KW_ANY ());
return super.visitAny_type (ctx);
}
public Void visitObject_type (IDLParser.Object_typeContext ctx)
{
bogusType ("Object data not valid for DDS", ctx.KW_OBJECT ());
return super.visitObject_type (ctx);
}
public Void visitValue_base_type (IDLParser.Value_base_typeContext ctx)
{
bogusType ("ValueBase data not valid for DDS", ctx.KW_VALUEBASE ());
return super.visitValue_base_type (ctx);
}
/* Verification of const types */
public Void visitInteger_type (IDLParser.Integer_typeContext ctx)
{
if (currentTD != null)
{
currentTD.setInteger ();
}
return super.visitInteger_type (ctx);
}
public Void visitFloating_pt_type (IDLParser.Floating_pt_typeContext ctx)
{
if (ctx.KW_LONG () != null && !params.mapld)
{
bogusType
("long double data not supported in " + Project.name, ctx.KW_LONG ());
}
if (currentTD != null)
{
currentTD.setNonintConst ();
}
return super.visitFloating_pt_type (ctx);
}
public Void visitBoolean_type (IDLParser.Boolean_typeContext ctx)
{
if (currentTD != null)
{
currentTD.setNonintConst ();
}
return super.visitBoolean_type (ctx);
}
public boolean unresolvedSymbols ()
{
if (declarations.isEmpty ())
{
return false;
}
else
{
System.err.print ("Error: The following declarations were not defined:");
for (ScopedName decl : declarations)
{
System.err.print (" " + decl);
}
System.err.println ();
return true;
}
}
private void printErr (int line, String err)
{
System.err.println
("Error: At " + params.linetab.getRealPosition (line) + ", " + err);
errorcount++;
}
private IdlParams params;
private ScopedName currentscope;
private StructSymbol currentstruct;
private TD currentTD;
private boolean inIntConst, inNonintConst, inSwitch;
private Set <ScopedName> declarations;
private int errorcount;
}

View file

@ -0,0 +1,48 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import org.eclipse.cyclonedds.compilers.IdlcCmdOptions;
public class IdlParams
{
public IdlParams (IdlcCmdOptions opts)
{
timestamp = !opts.nostamp;
quiet = opts.quiet;
lax = opts.lax;
mapwide = opts.mapwide;
mapld = opts.mapld;
forcpp = opts.forcpp;
dllname = opts.dllname;
dllfile = opts.dllfile;
xmlgen = !opts.noxml;
allstructs = opts.allstructs;
notopics = opts.notopics;
}
public boolean timestamp;
public boolean quiet;
public boolean lax;
public boolean mapwide;
public boolean mapld;
public boolean forcpp;
public boolean xmlgen;
public boolean allstructs;
public boolean notopics;
public String dllname;
public String dllfile;
public String basename = null;
public SymbolTable symtab = null;
public LineTable linetab = null;
}

View file

@ -0,0 +1,25 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
public class IntConstSymbol extends Symbol
{
public IntConstSymbol (ScopedName name)
{
super (name);
}
public String toString ()
{
return "Integer constant";
}
}

View file

@ -0,0 +1,25 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
class LicenseMgr
{
static boolean checkout (String feature)
{
return true;
}
static boolean checkin ()
{
return true;
}
}

View file

@ -0,0 +1,304 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import com.reprisesoftware.rlm.RlmHandle;
import com.reprisesoftware.rlm.RlmLicense;
import com.reprisesoftware.rlm.RlmException;
import java.util.Properties;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.File;
class LicenseMgr
{
private static final String FS = System.getProperty ("file.separator");
private static final String LIC_PROPS_FILE = "license.properties";
private static final String LIC_FEATURE = Project.nameCaps + "_IDLC";
private static final String LIC_VERSION = "#VERSION#";
private static final String LIC_REL_PATH = "etc";
private static final String LIC_FILE_NAME = "license.lic";
private static final String PROJECT_HOME_PROP = Project.nameCaps + "_HOME";
private static final String LIC_RLM_PROP = "RLM_LICENSE";
private static final String LIC_LOC_PROP = "prismtech_LICENSE";
private static RlmLicense license = null;
private static RlmHandle handle = null;
private static String vlHome = System.getProperty (PROJECT_HOME_PROP);
private static String licPropsPath;
private static String defaultLic;
private static String licRelPath;
private static String licLoc = null; // Final var that contains where it is
private LicenseMgr ()
{
}
private static boolean getProjectHome()
{
// Use the property, if null then fall back to the env
if (vlHome == null)
{
vlHome = System.getenv(Project.nameCaps + "_HOME");
if (vlHome == null)
{
System.err.println (Project.nameCaps + "_HOME environment variable or property must be set");
return false;
}
}
// Need to re-ajust each time we get osplHome
setupGlobals();
return true;
}
private static void setupGlobals()
{
licRelPath = vlHome + FS + LIC_REL_PATH + FS;
licPropsPath = licRelPath + LIC_PROPS_FILE;
defaultLic = licRelPath + LIC_FILE_NAME;
}
/* Locations for license:
1 : ${PROJECTNAME}_HOME/etc/ANY.lic
2 : ../../../license/ANY.lic
3 : Read from environment variable prismtech_LICENSE or RLM_LICENSE
*/
static boolean checkout (String feature)
{
try
{
String licLocProp = System.getProperty (LIC_LOC_PROP);
if (licLocProp == null)
{
licLocProp = System.getenv(LIC_LOC_PROP);
}
if (licLocProp != null && licLocProp.length() != 0)
{
File f = new File(licLocProp);
if (f.exists())
{
// Property pointed at a license file directly
licLoc = licLocProp;
}
else
{
String licFileLoc = licLocProp+FS+LIC_FILE_NAME;
f = new File(licFileLoc);
if (f.exists())
{
// Property pointed at the directory containing
// a license.lic
licLoc = licFileLoc;
}
else
{
// Try whatever they put on the property as it could
// be the server setting
licLoc = licLocProp;
}
}
}
else
{
// check RLM_LICENSE
String licRlmProp = System.getProperty (LIC_RLM_PROP);
if (licRlmProp == null)
{
licRlmProp = System.getenv(LIC_RLM_PROP);
}
if (licRlmProp != null && licRlmProp.length() != 0)
{
File f = new File(licRlmProp);
if (f.exists())
{
// Property pointed at a license file directly
licLoc = licRlmProp;
}
else
{
String licFileLoc = licRlmProp+FS+LIC_FILE_NAME;
f = new File(licFileLoc);
if (f.exists())
{
// Property pointed at the directory containing
// a license.lic
licLoc = licFileLoc;
}
else
{
// Try whatever they put on the property as it could
// be the server setting
licLoc = licRlmProp;
}
}
}
}
// NOTE: VortexLite - This section is not used??
if (licLoc == null)
{
// No Property set lets check for a properties file
FileInputStream fis = null;
Properties licProps = null;
if (!getProjectHome())
{
return false;
}
// check for license file location in properties file
File f = new File(licPropsPath);
if (f.exists())
{
licProps = new Properties ();
try
{
fis = new FileInputStream (licPropsPath);
licProps.load (fis);
}
catch (FileNotFoundException ex)
{} // Ignore
finally
{
fis.close();
}
String licFileLoc = licProps.getProperty (LIC_LOC_PROP);
if (licFileLoc == null)
{
licFileLoc = System.getenv(LIC_LOC_PROP);
}
if (licFileLoc != null)
{
// Property pointed at the directory containing it
licLoc = licFileLoc;
}
}
}
if (licLoc == null)
{
// No valid source set or found use the default as
// ${PROJECTNAME}_HOME/etc/license.lic as fall back
if (!getProjectHome())
{
return false;
}
File f = new File(defaultLic);
if (f.exists())
{
// Property pointed at the directory containing a license.lic
licLoc = defaultLic;
}
else
{
// Try whatever they put on the property
licLoc = licRelPath;
}
}
handle = new RlmHandle(licLoc, "", "");
license = new RlmLicense(handle, feature, LIC_VERSION, 1);
return true;
}
catch (Exception ex)
{
// From Vortex_v2 there will be a license directory under Vortex_v2 where
// a license can be installed for use by all products. If a valid license
// is not found in the normal locations then we check this directory for a
// valid license. The location of the Vortex_v2 directory will be set by
// the release.com/release.bat file.
String altLicRelPath = vlHome + FS + ".." + FS + ".." + FS + ".." + FS + "license";
String altDefaultLic = null;
if (altLicRelPath != null)
{
try
{
altDefaultLic = altLicRelPath + FS + "license" + FS + LIC_FILE_NAME;
File f = new File(altDefaultLic);
if (f.exists())
{
// Property pointed at the directory containing a license.lic
licLoc = altDefaultLic;
}
else
{
// Try whatever they put on the property
licLoc = altLicRelPath;
}
handle = new RlmHandle(licLoc, "", "");
license = new RlmLicense(handle, feature, LIC_VERSION, 1);
return true;
}
catch (Exception ex2)
{
System.err.println ("dds_idlc: License checkout failed!");
System.err.print (" Caught " + ex2.getClass().getName() + ": ");
System.err.println (ex2.getMessage());
}
}
else
{
System.err.println ("dds_idlc: License checkout failed!");
System.err.print (" Caught " + ex.getClass().getName() + ": ");
System.err.println (ex.getMessage());
}
// If we get here then we have not found a valid license
if (license != null)
{
license.checkin ();
}
if (handle != null)
{
handle.close();
}
}
return false;
}
static boolean checkin ()
{
if (license != null)
{
try
{
license.checkin ();
if (handle != null)
{
handle.close ();
}
return true;
}
catch (Exception ex)
{
System.err.println ("dds_idlc: License checkin failed!");
System.err.print (" Caught " + ex.getClass().getName() + ": ");
System.err.println (ex.getMessage());
}
}
return false;
}
}

View file

@ -0,0 +1,122 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import java.util.*;
import java.io.File;
import org.antlr.v4.runtime.*;
import org.stringtemplate.v4.ST;
import org.eclipse.cyclonedds.parser.IDLParser;
public class LineTable
{
private static class Entry
{
int position;
int line;
String file;
}
public LineTable (String filename, Iterator<Token> it, boolean forcpp)
{
Token t;
Entry e;
StringTokenizer lineinfo;
StringBuffer realfile;
String basename;
int depth = 0;
this.filename = filename;
if (forcpp)
{
suffix = "-cyclone";
}
else
{
suffix = "";
}
table = new LinkedList <Entry> ();
subfiles = new ArrayList <String> ();
while (it.hasNext ())
{
t = it.next ();
if (t.getType () == IDLParser.CODEPOS)
{
e = new Entry ();
e.position = t.getLine ();
lineinfo = new StringTokenizer (t.getText ());
lineinfo.nextToken (); // Skip '#'
e.line = Integer.parseInt (lineinfo.nextToken ());
realfile = new StringBuffer (lineinfo.nextToken ());
while (realfile.charAt (realfile.length () - 1) != '"')
{
realfile.append (" " + lineinfo.nextToken ());
}
e.file = realfile.substring (1, realfile.length () - 1); // Strip quotes
table.add (e);
if (t.getText ().endsWith (" 1"))
{
if (depth++ == 0)
{
subfiles.add
(e.file.substring (0, e.file.lastIndexOf (".")) + suffix);
}
}
else if (t.getText ().endsWith (" 2"))
{
depth--;
}
}
}
}
private Entry getRelevantEntry (int pos)
{
Entry e;
Iterator <Entry> iter = table.descendingIterator ();
do
{
e = iter.next ();
} while (e.position > pos);
return e;
}
public String getRealPosition (int pos)
{
Entry e = getRelevantEntry (pos);
return e.file + ":" + (pos + e.line - e.position - 1);
}
public boolean inMain (int pos)
{
return getRelevantEntry (pos).file.equals (filename);
}
public void populateIncs (ST template)
{
for (String s : subfiles)
{
template.add ("includes", new File (s).getName ());
}
}
private String filename;
private String suffix;
private LinkedList <Entry> table;
private ArrayList <String> subfiles;
}

View file

@ -0,0 +1,25 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
public class OtherConstSymbol extends Symbol
{
public OtherConstSymbol (ScopedName name)
{
super (name);
}
public String toString ()
{
return "Non-integer constant";
}
}

View file

@ -0,0 +1,19 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
public class Project
{
public static String version = "@PROJECT_VERSION@";
public static String name = "@CMAKE_PROJECT_NAME@";
public static String nameCaps = "@CMAKE_PROJECT_NAME_CAPS@";
}

View file

@ -0,0 +1,220 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import java.util.*;
public class ScopedName implements Comparable <ScopedName>
{
public ScopedName ()
{
components = new ArrayList<String> ();
}
public ScopedName (ScopedName rhs)
{
components = new ArrayList <String> (rhs.components.size ());
for (String s : rhs.components)
{
components.add (s);
}
}
public ScopedName (String[] components)
{
this.components = new ArrayList<String> (components.length);
for (String s : components)
{
if (!s.equals (""))
{
this.components.add (s);
}
}
}
public ScopedName (List <String> components)
{
this.components = new ArrayList<String> (components);
}
public ScopedName (String colonscopedname)
{
this (colonscopedname.split ("::"));
}
public void addComponent (String x)
{
components.add (x);
}
public String popComponent ()
{
if (components.isEmpty ())
{
return "";
}
else
{
return components.remove (components.size () - 1);
}
}
public String getLeaf ()
{
if (components.isEmpty ())
{
return "";
}
else
{
return components.get (components.size () - 1);
}
}
public String[] getPath ()
{
String[] result = new String[0];
if (components.size () >= 2)
{
result = components.subList (0, components.size () - 1).toArray (result);
}
return result;
}
public String[] getComponents ()
{
return components.toArray (new String[0]);
}
public String toString (String scoper)
{
boolean first = true;
StringBuffer result = new StringBuffer ("");
for (String element: components)
{
if (first)
{
first = false;
}
else
{
result.append (scoper);
}
result.append (element);
}
return result.toString ();
}
public String toString ()
{
return toString ("::");
}
public ScopedName catenate (ScopedName more)
{
ScopedName result = new ScopedName ();
result.components.addAll (components);
result.components.addAll (more.components);
return result;
}
public int compareTo (ScopedName rhs)
{
int result = 0, pos = 0;
int ldepth = depth ();
int rdepth = rhs.depth ();
while (result == 0 && pos < ldepth && pos < rdepth)
{
result = components.get (pos).compareTo (rhs.components.get (pos));
pos++;
}
if (result == 0)
{
result = Integer.compare (ldepth, rdepth);
}
return result;
}
public static Comparator<ScopedName> osplComparator
= new Comparator<ScopedName> ()
{
public int compare(ScopedName lhs, ScopedName rhs)
{
int ldepth = lhs.depth ();
int rdepth = rhs.depth ();
if (ldepth == 0 || rdepth == 0)
{
return Integer.compare (ldepth, rdepth);
}
else
{
int result = 0, pos = 0;
while (result == 0 && pos < ldepth && pos < rdepth)
{
result =
lhs.components.get (pos).compareTo (rhs.components.get (pos));
pos++;
}
if (result == 0)
{
result = Integer.compare (rdepth, ldepth);
}
return result;
}
}
};
public boolean isParentOf (ScopedName other)
{
if (other.components.size() <= components.size ())
{
return false;
}
for (int i = 0; i < components.size (); i++)
{
if (!components.get (i).equals (other.components.get (i)))
{
return false;
}
}
return true;
}
public boolean equals (Object o)
{
return (o instanceof ScopedName && compareTo ((ScopedName)o) == 0);
}
public int hashCode ()
{
int result = 0;
for (String c : components)
{
result ^= c.hashCode ();
}
return result;
}
public int depth ()
{
return components.size ();
}
public void reset ()
{
components.clear ();
}
private ArrayList<String> components;
}

View file

@ -0,0 +1,66 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import java.util.*;
public class StructSymbol extends TypeDefSymbol
{
public StructSymbol (ScopedName name)
{
super (name);
members = new ArrayList <String> ();
valid = true;
}
public String toString ()
{
StringBuffer result = new StringBuffer ("Struct, members are");
for (String s : members)
{
result.append (' ');
result.append (s);
}
return result.toString ();
}
public void addMember (String membername)
{
members.add (membername);
}
public void addStructMember (String membername, StructSymbol membertype)
{
for (String s : membertype.members)
{
members.add (membername + "." + s);
}
}
public boolean hasMember (String membername)
{
return members.contains (membername);
}
public void invalidate ()
{
valid = false;
}
public boolean isValid ()
{
return valid;
}
private List <String> members;
private boolean valid;
}

View file

@ -0,0 +1,27 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
public abstract class Symbol
{
Symbol (ScopedName name)
{
this.name = name;
}
public ScopedName name ()
{
return new ScopedName (name);
}
private ScopedName name;
}

View file

@ -0,0 +1,69 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import java.util.*;
public class SymbolTable
{
public SymbolTable()
{
map = new HashMap <ScopedName, Symbol> ();
}
public void add (Symbol newsym)
{
Symbol oldval;
oldval = map.put (newsym.name (), newsym);
if (oldval != null)
{
System.err.println ("Internal inconsistency, multiple definition for " + newsym.name ());
System.err.println ("Old value was " + oldval.toString ());
System.err.println ("New value is " + newsym.toString ());
}
}
public Symbol resolve (ScopedName current, ScopedName request)
{
Symbol result = null;
if (current != null)
{
ScopedName searchscope = new ScopedName (current);
do
{
result = map.get (searchscope.catenate (request));
}
while (result == null && ! searchscope.popComponent().equals (""));
}
if (result == null)
{
result = map.get (request);
}
return result;
}
public Symbol getSymbol (ScopedName request)
{
return map.get (request);
}
public void dump ()
{
for (Map.Entry <ScopedName, Symbol> sym : map.entrySet ())
{
System.out.println (sym.getKey () + " is a " + sym.getValue ());
}
}
Map <ScopedName, Symbol> map;
}

View file

@ -0,0 +1,52 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
import java.util.List;
import org.eclipse.cyclonedds.parser.IDLParser;
public class TypeDeclSymbol extends TypeDefSymbol
{
public TypeDeclSymbol
(
ScopedName name,
IDLParser.Type_specContext definition,
List<IDLParser.Fixed_array_sizeContext> dimensions,
boolean isint,
boolean isnonint
)
{
super (name);
def = definition.getText ();
this.isint = isint;
this.isnonint = isnonint;
}
public String toString ()
{
return "Typedef = " + def;
}
public boolean isInteger ()
{
return isint;
}
public boolean isNonintConst ()
{
return isnonint;
}
private String def;
private boolean isint;
private boolean isnonint;
}

View file

@ -0,0 +1,20 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
public abstract class TypeDefSymbol extends Symbol
{
public TypeDefSymbol (ScopedName name)
{
super (name);
}
}

View file

@ -0,0 +1,38 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds;
public class UnionSymbol extends TypeDefSymbol
{
public UnionSymbol (ScopedName name)
{
super (name);
valid = true;
}
public String toString ()
{
return "Union";
}
public void invalidate ()
{
valid = false;
}
public boolean isValid ()
{
return valid;
}
private boolean valid;
}

View file

@ -0,0 +1,22 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.compilers;
public class CmdException extends Exception
{
public CmdException (int retcode)
{
this.retcode = retcode;
}
public final int retcode;
}

View file

@ -0,0 +1,198 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.compilers;
import java.util.*;
public class CmdOptions
{
public CmdOptions (String compilername, String[] args) throws CmdException
{
this.name = compilername;
files = new ArrayList <String> ();
includes = new ArrayList <String> ();
macros = new HashMap <String, String> ();
int i = 0;
while (i < args.length && args[i].startsWith ("-"))
{
if (process (args[i], ((i + 1 < args.length) ? args[i + 1] : null)))
{
i++;
}
i++;
}
while (i < args.length)
{
files.add (args[i++]);
}
}
public CmdOptions (CmdOptions rhs)
{
dllname = rhs.dllname;
dllfile = rhs.dllfile;
outputdir = rhs.outputdir;
includes = new ArrayList <String> (rhs.includes);
macros = new HashMap <String, String> (rhs.macros);
version = rhs.version;
files = new ArrayList <String> (rhs.files);
name = rhs.name;
noxml = rhs.noxml;
}
public void optHelp (java.io.PrintStream io)
{
io.println ("Usage: " + name + " [options] file(s).idl");
io.println ();
io.println (" options:");
io.println (" -help This help screen");
io.println (" -version Print compiler version");
io.println (" -d directory Output directory for generated files");
io.println (" -I path Add directory to #include search path");
io.println (" -D macro Define conditional compilation symbol");
io.println (" -dll name[,file] Generate DLL linkage declarations");
io.println (" -noxml Do not generate XML Topic descriptors");
}
public boolean process (String arg1, String arg2) throws CmdException
{
boolean result = false; // whether or not we used arg2
if (arg1.equals ("-h") || arg1.equals ("-?") || arg1.equals ("-help"))
{
optHelp (System.out);
throw new CmdException (0);
}
else if (arg1.equals ("-v") || arg1.equals ("-version"))
{
version = true;
}
else if (arg1.equals ("-d"))
{
if (arg2 == null || arg2.charAt (0) == '-')
{
System.err.println
(name + ": Directory name expected following -d option");
throw new CmdException (1);
}
outputdir = arg2;
result = true;
}
else if (arg1.startsWith ("-dll") || arg1.startsWith ("-P"))
{
if (arg1.equals ("-dll") || arg1.equals ("-P"))
{
if (arg2 == null || arg2.charAt (0) == '-')
{
System.err.println
(name + ": DLL name expected following " + arg1 + " option");
throw new CmdException (1);
}
processDll (arg2);
result = true;
}
else
{
if (arg1.startsWith ("-dll"))
{
processDll (arg2.substring (4));
}
else
{
processDll (arg2.substring (2));
}
}
}
else if (arg1.equals ("-noxml"))
{
noxml = true;
}
else if (arg1.startsWith ("-I"))
{
if (arg1.equals ("-I"))
{
if (arg2 == null || arg2.charAt (0) == '-')
{
System.err.println (name + ": Include search path directory expected following -I option");
throw new CmdException (1);
}
includes.add (arg2);
result = true;
}
else
{
includes.add (arg1.substring (2));
}
}
else if (arg1.startsWith ("-D"))
{
if (arg1.equals ("-D"))
{
if (arg2 == null || arg2.charAt (0) == '-')
{
System.err.println (name + ": Conditional compilation identifier expected following -D option");
throw new CmdException (1);
}
addMacro (arg2);
result = true;
}
else
{
addMacro (arg1.substring (2));
}
}
else
{
optHelp (System.out);
throw new CmdException (1);
}
return result;
}
private void addMacro (String m)
{
int pos = m.indexOf ("=");
if (pos > 0)
{
macros.put (m.substring (0, pos), m.substring (pos + 1));
}
else
{
macros.put (m, "");
}
}
private void processDll (String arg)
{
int pos = arg.indexOf (",");
if (pos > 0)
{
dllname = arg.substring (0, pos);
dllfile = arg.substring (pos + 1);
}
else
{
dllname = arg;
}
}
public String dllname = null;
public String dllfile = null;
public String outputdir = null;
public boolean noxml;
public List <String> includes;
public Map <String, String> macros;
public boolean version = false;
public List <String> files;
final String name;
}

View file

@ -0,0 +1,31 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.compilers;
public class Idlc
{
public static void main (String[] args)
{
IdlcCmdOptions opts = null;
try
{
opts = new IdlcCmdOptions (args);
}
catch (CmdException ex)
{
System.exit (ex.retcode);
}
org.eclipse.cyclonedds.Compiler.run (opts);
}
}

View file

@ -0,0 +1,123 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.compilers;
public class IdlcCmdOptions extends CmdOptions
{
public IdlcCmdOptions (String[] args) throws CmdException
{
super ("dds_idlc", args);
}
public IdlcCmdOptions (IdlcppCmdOptions cppopts)
{
super (cppopts);
forcpp = true;
pponly = cppopts.pponly;
quiet = cppopts.quiet;
nostamp = cppopts.nostamp;
}
public void optHelp (java.io.PrintStream io)
{
super.optHelp (io);
io.println (" -E Preprocess only, to standard output");
io.println (" -allstructs All structs are Topics");
io.println (" -notopics Generate type definitions only");
io.println (" -nostamp Do not timestamp generated code");
io.println (" -lax Skip over structs containing unsupported datatypes");
io.println (" -quiet Suppress console output other than error messages");
io.println (" -map_wide Map the unsupported wchar and wstring types to char and string");
io.println (" -map_longdouble Map the unsupported long double type to double");
}
public boolean process (String arg1, String arg2) throws CmdException
{
if (arg1.equals ("-E"))
{
pponly = true;
}
else if (arg1.equals ("-allstructs"))
{
if (notopics)
{
System.err.println (name + ": -allstructs and -notopics are mutually exclusive options");
throw new CmdException (1);
}
allstructs = true;
}
else if (arg1.equals ("-notopics"))
{
if (allstructs)
{
System.err.println (name + ": -allstructs and -notopics are mutually exclusive options");
throw new CmdException (1);
}
notopics = true;
}
else if (arg1.equals ("-nostamp"))
{
nostamp = true;
}
else if (arg1.equals ("-quiet") || arg1.equals ("-q"))
{
quiet = true;
}
else if (arg1.equals ("-lax"))
{
lax = true;
}
else if (arg1.equals ("-map_wide"))
{
mapwide = true;
}
else if (arg1.equals ("-map_longdouble"))
{
mapld = true;
}
else if (arg1.equals ("-dumptokens"))
{
dumptokens = true;
}
else if (arg1.equals ("-dumptree"))
{
dumptree = true;
}
else if (arg1.equals ("-dumpsymbols"))
{
dumpsymbols = true;
}
else if (arg1.equals ("-forcpp"))
{
forcpp = true;
}
else
{
return super.process (arg1, arg2);
}
return false;
}
public boolean pponly;
public boolean allstructs;
public boolean notopics;
public boolean nostamp;
public boolean quiet;
public boolean lax;
public boolean mapwide;
public boolean mapld;
public boolean dumptokens;
public boolean dumptree;
public boolean dumpsymbols;
public boolean forcpp;
}

View file

@ -0,0 +1,149 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.compilers;
import java.util.*;
import org.eclipse.cyclonedds.Project;
public class Idlcpp
{
public static void main (String[] args)
{
IdlcppCmdOptions opts = null;
int status = 0;
try
{
opts = new IdlcppCmdOptions (args);
}
catch (CmdException ex)
{
System.exit (ex.retcode);
}
List <String> idlppcmd = new ArrayList <String> ();
if (opts.version)
{
System.out.print ("Cyclone DDS ");
System.out.println ("IDL to C++ compiler v" + Project.version);
}
else
{
String FS = System.getProperty ("file.separator");
String projecthome = System.getProperty (Project.nameCaps + "_HOME");
String projecthost = System.getProperty (Project.nameCaps + "_HOST");
opts.includes.add (projecthome + FS + "etc" + FS + "idl");
IdlcCmdOptions idlcopts = new IdlcCmdOptions (opts);
if (!opts.pponly)
{
idlppcmd.add (projecthome + FS + "bin" + FS + projecthost + FS + "idlpp");
idlppcmd.add ("-S");
idlppcmd.add ("-a");
idlppcmd.add (projecthome + FS + "etc" + FS + "idlpp");
idlppcmd.add ("-x");
idlppcmd.add ("cyclone");
idlppcmd.add ("-l");
if (opts.language == null)
{
idlppcmd.add ("isoc++");
}
else
{
idlppcmd.add (opts.language);
}
if (opts.dllname != null)
{
idlppcmd.add ("-P");
if (opts.dllfile != null)
{
idlppcmd.add (opts.dllname + "," + opts.dllfile);
}
else
{
idlppcmd.add (opts.dllname);
}
}
if (opts.outputdir != null)
{
idlppcmd.add ("-d");
idlppcmd.add (opts.outputdir);
}
for (String s : opts.includes)
{
idlppcmd.add ("-I");
idlppcmd.add (s);
}
for (String s : opts.macros.keySet ())
{
idlppcmd.add ("-D");
String val = opts.macros.get (s);
if (!val.equals (""))
{
idlppcmd.add (s + "=" + val);
}
else
{
idlppcmd.add (s);
}
}
if (opts.testmethods)
{
idlppcmd.add ("-T");
}
idlppcmd.addAll (opts.files);
status = runcmd (idlppcmd);
}
org.eclipse.cyclonedds.Compiler.run (idlcopts);
}
System.exit (status);
}
private static int runcmd (List<String> cmdline)
{
int result;
try
{
result = new ProcessBuilder (cmdline).inheritIO ().start (). waitFor ();
if (result != 0)
{
System.err.print ("dds_idlcpp: nonzero return from");
for (String s : cmdline)
{
System.err.print (" " + s);
}
System.err.println ();
}
}
catch (Exception ex)
{
System.err.print ("dds_idlcpp: exception when running");
for (String s : cmdline)
{
System.err.print (" " + s);
}
System.err.println ();
System.err.println (ex);
result = 1;
}
return result;
}
}

View file

@ -0,0 +1,84 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.compilers;
public class IdlcppCmdOptions extends CmdOptions
{
public IdlcppCmdOptions (String[] args) throws CmdException
{
super ("dds_idlcpp", args);
}
public void optHelp (java.io.PrintStream io)
{
super.optHelp (io);
io.println (" -l [isocpp|cpp] Select ISO C++ or classic generation");
io.println (" -E Preprocess only, to standard output");
io.println (" -nostamp Do not timestamp generated code");
io.println (" -quiet Suppress console output other than error messages");
}
public boolean process (String arg1, String arg2) throws CmdException
{
boolean result = false;
if (arg1.equals ("-E"))
{
pponly = true;
}
else if (arg1.equals ("-nostamp"))
{
nostamp = true;
}
else if (arg1.equals ("-quiet") || arg1.equals ("-q"))
{
quiet = true;
}
else if (arg1.equals ("-T"))
{
testmethods = true;
}
else if (arg1.equals ("-l"))
{
if (arg2 == null || arg2.charAt (0) == '-')
{
System.err.println
(name + ": target language expected following -l option");
throw new CmdException (1);
}
if (arg2.equals ("cpp") || arg2.equals ("c++"))
{
language = "c++";
}
else if (arg2.equals ("isocpp") || arg2.equals ("isoc++"))
{
language = "isoc++";
}
else
{
System.err.println (name + ": supported target languages are isocpp (isoc++) and cpp (c++)");
throw new CmdException (1);
}
result = true;
}
else
{
return super.process (arg1, arg2);
}
return result;
}
public boolean pponly;
public boolean nostamp;
public boolean quiet;
public String language;
public boolean testmethods;
}

View file

@ -0,0 +1,27 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
public abstract class AbstractType implements Type
{
public void makeKeyField ()
{
iskey = true;
}
public boolean isKeyField ()
{
return iskey;
}
private boolean iskey = false;
}

View file

@ -0,0 +1,77 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
public enum Alignment
{
ONE (1, 0, "1u"),
BOOL (0, 0, "sizeof(bool)"),
ONE_OR_BOOL (0, 1, "(sizeof(bool)>1u)?sizeof(bool):1u"),
TWO (2, 2, "2u"),
TWO_OR_BOOL (0, 3, "(sizeof(bool)>2u)?sizeof(bool):2u"),
FOUR (4, 4, "4u"),
PTR (0, 6, "sizeof (char *)"),
EIGHT (8, 8, "8u");
private final int value;
private final int ordering;
private final String rendering;
Alignment (int val, int order, String render)
{
value = val;
ordering = order;
rendering = render;
}
public String toString ()
{
return rendering;
}
public Alignment maximum (Alignment rhs)
{
if (rhs.equals (BOOL))
{
if (this.equals (ONE))
{
return ONE_OR_BOOL;
}
else if (this.equals (TWO))
{
return TWO_OR_BOOL;
}
else
{
return this;
}
}
if (rhs.ordering > ordering)
{
return rhs;
}
else
{
return this;
}
}
public boolean isUncertain ()
{
return (this.value == 0);
}
public int getValue ()
{
return value;
}
}

View file

@ -0,0 +1,61 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import java.util.*;
public class ArrayDeclarator
{
public ArrayDeclarator (String name)
{
this.name = name;
this.dims = new ArrayList <Long> ();
size = 1;
}
public void addDimension (long dim)
{
dims.add (new Long (dim));
size *= dim;
}
public String getName ()
{
return name;
}
public long getSize ()
{
return size;
}
public String getDimString ()
{
StringBuffer result = new StringBuffer ();
for (Long dim : dims)
{
result.append ("[");
result.append (dim.toString ());
result.append ("]");
}
return result.toString ();
}
public Collection <Long> getDims ()
{
return dims;
}
private final String name;
private List<Long> dims;
private long size;
}

View file

@ -0,0 +1,181 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import java.util.*;
import org.eclipse.cyclonedds.ScopedName;
public class ArrayType extends AbstractType
{
public ArrayType (Collection <Long> dimensions, Type subtype)
{
realsub = subtype;
while (realsub instanceof TypedefType)
{
realsub = ((TypedefType)realsub).getRef ();
}
this.dimensions = new ArrayList <Long> ();
if (realsub instanceof ArrayType)
{
ArrayType subarray = (ArrayType)realsub;
dimensions.addAll (subarray.dimensions);
this.subtype = subarray.subtype;
realsub = this.subtype;
while (realsub instanceof TypedefType)
{
realsub = ((TypedefType)realsub).getRef ();
}
}
else
{
this.subtype = subtype;
}
this.dimensions.addAll (dimensions);
}
public Type dup ()
{
return new ArrayType (dimensions, subtype);
}
public ArrayList <String> getMetaOp (String myname, String structname)
{
ArrayList <String> result = new ArrayList <String> ();
String offset;
if (myname != null)
{
offset = "offsetof (" + structname + ", " + myname + ")";
}
else
{
offset = "0u";
}
result.add (new String
(
"DDS_OP_ADR | DDS_OP_TYPE_ARR | " + realsub.getSubOp () + (isKeyField () ? " | DDS_OP_FLAG_KEY" : "") + ", " +
offset + ", " + Long.toString (size ())
));
if (!(realsub instanceof BasicType))
{
if (realsub instanceof BoundedStringType)
{
result.add ("0, " + Long.toString (((BoundedStringType)realsub).getBound () + 1));
}
else
{
result.add (new String ("(" + new Integer (getMetaOpSize ()) + "u << 16u) + 5u, sizeof (" + realsub.getCType () + ")"));
result.addAll (realsub.getMetaOp (null, null));
result.add (new String ("DDS_OP_RTS"));
}
}
return result;
}
public String getSubOp ()
{
return "DDS_OP_SUBTYPE_ARR";
}
public String getOp ()
{
return "DDS_OP_TYPE_ARR";
}
public String getCType ()
{
StringBuffer str = new StringBuffer (subtype.getCType ());
for (Long d : dimensions)
{
str.append ("[");
str.append (d.toString ());
str.append ("]");
}
return str.toString ();
}
public int getMetaOpSize ()
{
if (realsub instanceof BasicType)
{
return 3;
}
else
{
if (realsub instanceof BoundedStringType)
{
return 5;
}
else
{
return 6 + realsub.getMetaOpSize ();
}
}
}
public Alignment getAlignment ()
{
return subtype.getAlignment ();
}
public long getKeySize ()
{
long keysize = subtype.getKeySize ();
if (keysize == -1)
{
return -1;
}
return keysize * size ();
}
public void getXML (StringBuffer str, ModuleContext mod)
{
for (Long d : dimensions)
{
str.append ("<Array size=\\\"");
str.append (d.toString ());
str.append ("\\\">");
}
subtype.getXML (str, mod);
for (Long d : dimensions)
{
str.append ("</Array>");
}
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
subtype.populateDeps (depset, current);
}
public boolean depsOK (Set <ScopedName> deps)
{
return TypeUtil.deptest (subtype, deps, null);
}
private long size()
{
long result = 1;
for (Long d : dimensions)
{
result *= d.longValue ();
}
return result;
}
private final Type subtype;
private Type realsub;
private final List <Long> dimensions;
}

View file

@ -0,0 +1,126 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import java.util.*;
import org.eclipse.cyclonedds.ScopedName;
public class BasicType extends AbstractType
{
public enum BT
{
BOOLEAN ("bool", "DDS_OP_TYPE_BOO", "DDS_OP_SUBTYPE_BOO", Alignment.BOOL, "Boolean"),
OCTET ("uint8_t", "DDS_OP_TYPE_1BY", "DDS_OP_SUBTYPE_1BY", Alignment.ONE, "Octet"),
CHAR ("char", "DDS_OP_TYPE_1BY", "DDS_OP_SUBTYPE_1BY", Alignment.ONE, "Char"),
SHORT ("int16_t", "DDS_OP_TYPE_2BY", "DDS_OP_SUBTYPE_2BY", Alignment.TWO, "Short"),
USHORT ("uint16_t", "DDS_OP_TYPE_2BY", "DDS_OP_SUBTYPE_2BY", Alignment.TWO, "UShort"),
LONG ("int32_t", "DDS_OP_TYPE_4BY", "DDS_OP_SUBTYPE_4BY", Alignment.FOUR, "Long"),
ULONG ("uint32_t", "DDS_OP_TYPE_4BY", "DDS_OP_SUBTYPE_4BY", Alignment.FOUR, "ULong"),
LONGLONG ("int64_t", "DDS_OP_TYPE_8BY", "DDS_OP_SUBTYPE_8BY", Alignment.EIGHT, "LongLong"),
ULONGLONG ("uint64_t", "DDS_OP_TYPE_8BY", "DDS_OP_SUBTYPE_8BY", Alignment.EIGHT, "ULongLong"),
FLOAT ("float", "DDS_OP_TYPE_4BY", "DDS_OP_SUBTYPE_4BY", Alignment.FOUR, "Float"),
DOUBLE ("double", "DDS_OP_TYPE_8BY", "DDS_OP_SUBTYPE_8BY", Alignment.EIGHT, "Double"),
STRING ("char *", "DDS_OP_TYPE_STR", "DDS_OP_SUBTYPE_STR", Alignment.PTR, "String");
public final String cType;
public final String op;
public final String subop;
public final Alignment align;
public final String XML;
BT (String cType, String op, String subop, Alignment align, String XML)
{
this.cType = cType;
this.op = op;
this.subop = subop;
this.align = align;
this.XML = XML;
}
}
public BasicType (BT type)
{
this.type = type;
}
public Type dup ()
{
return new BasicType (type);
}
public ArrayList <String> getMetaOp (String myname, String structname)
{
ArrayList <String> result = new ArrayList <String> (1);
result.add (new String
(
"DDS_OP_ADR | " + type.op + (isKeyField () ? " | DDS_OP_FLAG_KEY" : "") +
", offsetof (" + structname + ", " + myname + ")"
));
return result;
}
public String getSubOp ()
{
return type.subop;
}
public String getOp ()
{
return type.op;
}
public String getCType ()
{
return type.cType;
}
public int getMetaOpSize ()
{
return 2;
}
public Alignment getAlignment ()
{
return type.align;
}
public long getKeySize ()
{
switch (type)
{
case BOOLEAN:
return 1;
case STRING:
return -1;
default:
return type.align.getValue ();
}
}
public void getXML (StringBuffer str, ModuleContext mod)
{
str.append ("<");
str.append (type.XML);
str.append ("/>");
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
}
public boolean depsOK (Set <ScopedName> deps)
{
return true;
}
final BT type;
}

View file

@ -0,0 +1,68 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import org.eclipse.cyclonedds.ScopedName;
import java.util.*;
public class BasicTypedefType extends BasicType implements NamedType
{
public BasicTypedefType (ScopedName name, BasicType ref)
{
super (ref.type);
this.name = new ScopedName (name);
}
public Type dup ()
{
return new TypedefType (name, new BasicType (type));
}
public void getToplevelXML (StringBuffer str, ModuleContext mod)
{
mod.enter (str, name);
str.append ("<TypeDef name=\\\"");
str.append (name.getLeaf ());
str.append ("\\\">");
super.getXML (str, mod);
str.append ("</TypeDef>");
}
public void getXML (StringBuffer str, ModuleContext mod)
{
str.append ("<Type name=\\\"");
str.append (mod.nameFrom (name));
str.append ("\\\"/>");
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
depset.add (name);
}
public boolean depsOK (Set <ScopedName> deps)
{
return true;
}
public ScopedName getSN ()
{
return name;
}
public boolean isInline ()
{
return false;
}
private final ScopedName name;
}

View file

@ -0,0 +1,104 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import java.util.*;
import org.eclipse.cyclonedds.ScopedName;
public class BoundedStringType extends AbstractType
{
public BoundedStringType (long size)
{
this.size = size;
}
public Type dup ()
{
return new BoundedStringType (size);
}
public long getKeySize ()
{
return size + 5;
}
public long getBound ()
{
return size;
}
public ArrayList <String> getMetaOp (String myname, String structname)
{
ArrayList <String> result = new ArrayList <String> ();
String offset;
if (myname != null)
{
offset = "offsetof (" + structname + ", " + myname + ")";
}
else
{
offset = "0u";
}
result.add (new String
(
"DDS_OP_ADR | DDS_OP_TYPE_BST" +
(isKeyField () ? " | DDS_OP_FLAG_KEY" : "") + ", " +
offset + ", " + Long.toString (size + 1)
));
return result;
}
public String getSubOp ()
{
return "DDS_OP_SUBTYPE_BST";
}
public String getOp ()
{
return "DDS_OP_TYPE_BST";
}
public String getCType ()
{
return "char";
}
public int getMetaOpSize ()
{
return 3;
}
public Alignment getAlignment ()
{
return Alignment.ONE;
}
public void getXML (StringBuffer str, ModuleContext mod)
{
str.append ("<String length=\\\"");
str.append (Long.toString (size));
str.append ("\\\"/>");
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
}
public boolean depsOK (Set <ScopedName> deps)
{
return true;
}
private final long size;
}

View file

@ -0,0 +1,124 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import java.util.*;
import org.eclipse.cyclonedds.ScopedName;
public class EnumType extends BasicType implements NamedType
{
public EnumType (ScopedName SN, NamedType parent)
{
super (BT.LONG);
this.SN = SN;
this.parent = parent;
vals = new ArrayList<String> ();
scopelen = SN.toString ("_").length () - SN.getLeaf ().length ();
}
public Type dup ()
{
EnumType res = new EnumType (SN, parent);
for (String s : vals)
{
res.addEnumerand (s);
}
return res;
}
public String getCType ()
{
return SN.toString ("_");
}
public void addEnumerand (String val)
{
vals.add (val);
}
public Iterable<String> getEnumerands ()
{
return vals;
}
private void getXMLbase (StringBuffer str)
{
int val = 0;
str.append ("<Enum name=\\\"");
str.append (SN.getLeaf ());
str.append ("\\\">");
for (String s : vals)
{
str.append ("<Element name=\\\"");
str.append (s);
str.append ("\\\" value=\\\"");
str.append (Integer.toString (val++));
str.append ("\\\"/>");
}
str.append ("</Enum>");
}
public void getXML (StringBuffer str, ModuleContext mod)
{
if (parent != null && mod.isParent (SN))
{
getXMLbase (str);
}
else
{
str.append ("<Type name=\\\"");
str.append (mod.nameFrom (SN));
str.append ("\\\"/>");
}
}
public void getToplevelXML (StringBuffer str, ModuleContext mod)
{
mod.enter (str, SN);
getXMLbase (str);
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
if (parent == null)
{
depset.add (SN);
}
else
{
if (!(parent.getSN ().equals (current.getSN ())))
{
parent.populateDeps (depset, current);
}
}
}
public boolean depsOK (Set <ScopedName> deps)
{
return true;
}
public String descope (String s)
{
return s.substring (scopelen);
}
public ScopedName getSN ()
{
return SN;
}
private final NamedType parent;
private final ScopedName SN;
private final int scopelen;
private List<String> vals;
}

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,120 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import java.util.*;
import org.eclipse.cyclonedds.ScopedName;
public class ModuleContext
{
public ModuleContext ()
{
current = new ScopedName ();
struct = new ScopedName ();
}
public void enter (StringBuffer str, ScopedName target)
{
ScopedName common = new ScopedName (target);
common.popComponent ();
while (common.depth () > current.depth ())
{
common.popComponent ();
}
while (common.depth () < current.depth ())
{
current.popComponent ();
str.append ("</Module>");
}
while (!common.equals (current))
{
current.popComponent ();
common.popComponent ();
str.append ("</Module>");
}
String[] submods = target.getComponents ();
for (int i = current.depth (); i < submods.length - 1; i++)
{
current.addComponent (submods [i]);
str.append ("<Module name=\\\"");
str.append (submods [i]);
str.append ("\\\">");
}
}
public void exit (StringBuffer str)
{
for (int i = 0; i < current.depth (); i++)
{
str.append ("</Module>");
}
current.reset ();
}
public void pushStruct (String s)
{
struct.addComponent (s);
}
public void popStruct ()
{
struct.popComponent ();
}
public boolean isParent (ScopedName name)
{
ScopedName dup = new ScopedName (name);
dup.popComponent ();
return dup.equals (current.catenate (struct));
}
public String nameFrom (ScopedName to)
{
String[] toArr = to.getComponents ();
String[] fromArr = current.getComponents ();
if (toArr.length == fromArr.length + 1)
{
boolean same = true;
for (int i = 0; i < fromArr.length; i++)
{
if (!toArr[i].equals (fromArr[i]))
{
same = false;
break;
}
}
if (same)
{
return to.getLeaf ();
}
}
if (fromArr.length > 0 && toArr.length > 0 && fromArr[0].equals (toArr[0]))
{
return to.toString ("::");
}
else
{
return "::" + to.toString ("::");
}
}
public ScopedName getScope ()
{
return new ScopedName (current);
}
private ScopedName current;
private ScopedName struct;
}

View file

@ -0,0 +1,20 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import org.eclipse.cyclonedds.ScopedName;
public interface NamedType extends Type
{
public ScopedName getSN ();
public void getToplevelXML (StringBuffer str, ModuleContext mod);
}

View file

@ -0,0 +1,150 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import java.util.*;
import org.eclipse.cyclonedds.ScopedName;
public class SequenceType extends AbstractType
{
public SequenceType (Type subtype)
{
this.subtype = subtype;
realsub = subtype;
while (realsub instanceof TypedefType)
{
realsub = ((TypedefType)realsub).getRef ();
}
ctype = "dds_sequence_t";
}
private SequenceType (Type subtype, String ctype)
{
this.subtype = subtype;
realsub = subtype;
while (realsub instanceof TypedefType)
{
realsub = ((TypedefType)realsub).getRef ();
}
this.ctype = ctype;
}
public Type dup ()
{
return new SequenceType (subtype.dup (), ctype);
}
public SequenceType clone (String name)
{
return new SequenceType (subtype.dup (), name);
}
public ArrayList <String> getMetaOp (String myname, String structname)
{
ArrayList <String> result = new ArrayList <String> ();
String offset;
if (myname != null)
{
offset = "offsetof (" + structname + ", " + myname + ")";
}
else
{
offset = "0u";
}
result.add (new String
(
"DDS_OP_ADR | DDS_OP_TYPE_SEQ | " + realsub.getSubOp () + ", " + offset
));
if (!(realsub instanceof BasicType))
{
if (realsub instanceof BoundedStringType)
{
result.add (Long.toString (((BoundedStringType)realsub).getBound () + 1));
}
else
{
result.add (new String ("sizeof (" + realsub.getCType () + "), (" + new Integer (getMetaOpSize ()) + "u << 16u) + 4u"));
result.addAll (realsub.getMetaOp (null, null));
result.add (new String ("DDS_OP_RTS"));
}
}
return result;
}
public String getSubOp ()
{
return "DDS_OP_SUBTYPE_SEQ";
}
public String getOp ()
{
return "DDS_OP_TYPE_SEQ";
}
public String getCType ()
{
return ctype;
}
public long getKeySize ()
{
return -1;
}
public int getMetaOpSize ()
{
if (realsub instanceof BasicType)
{
return 2;
}
else
{
if (realsub instanceof BoundedStringType)
{
return 3;
}
else
{
return 5 + realsub.getMetaOpSize ();
}
}
}
public Alignment getAlignment ()
{
return Alignment.PTR;
}
public void getXML (StringBuffer str, ModuleContext mod)
{
str.append ("<Sequence>");
subtype.getXML (str, mod);
str.append ("</Sequence>");
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
subtype.populateDeps (depset, current);
}
public boolean depsOK (Set <ScopedName> deps)
{
return TypeUtil.deptest (subtype, deps, null);
}
private final Type subtype;
private Type realsub;
private final String ctype;
}

View file

@ -0,0 +1,305 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import org.eclipse.cyclonedds.ScopedName;
import java.util.*;
public class StructType extends AbstractType implements NamedType
{
private static class Member
{
private Member (String n, Type t)
{
name = n;
type = t;
}
private final String name;
private final Type type;
};
public StructType (ScopedName name, NamedType parent)
{
this.name = name;
this.parent = parent;
members = new ArrayList <Member> ();
}
public void addMember (String name, Type type)
{
members.add (new Member (name, type.dup ()));
}
public int addKeyField (String fieldname)
{
// returns the offset in metadata of the field
int result = 0;
String search;
Type mtype = null;
int dotpos = fieldname.indexOf ('.');
if (dotpos == -1)
{
search = fieldname;
}
else
{
search = fieldname.substring (0, dotpos);
}
for (Member m : members)
{
mtype = m.type;
while (mtype instanceof TypedefType)
{
mtype = ((TypedefType)mtype).getRef ();
}
if (m.name.equals (search))
{
if (dotpos != -1)
{
result +=
((StructType)mtype).addKeyField (fieldname.substring (dotpos + 1));
}
mtype.makeKeyField ();
break;
}
else
{
result += mtype.getMetaOpSize ();
}
}
return result;
}
public ArrayList <String> getMetaOp (String myname, String structname)
{
ArrayList <String> result = new ArrayList <String> ();
for (Member m : members)
{
if (myname == null)
{
result.addAll (m.type.getMetaOp (m.name, getCType ()));
}
else
{
result.addAll (m.type.getMetaOp (myname + "." + m.name, structname));
}
}
return result;
}
public String getSubOp ()
{
return "DDS_OP_SUBTYPE_STU";
}
public String getOp ()
{
return "DDS_OP_TYPE_STU";
}
public String getCType ()
{
return name.toString ("_");
}
public int getMetaOpSize ()
{
int result = 0;
for (Member m : members)
{
result += m.type.getMetaOpSize ();
}
return result;
}
public Alignment getAlignment ()
{
Alignment result = Alignment.ONE;
for (Member m : members)
{
result = result.maximum (m.type.getAlignment ());
}
return result;
}
public boolean isUnoptimizable ()
{
Type mtype;
for (Member m : members)
{
mtype = m.type;
while (mtype instanceof TypedefType)
{
mtype = ((TypedefType)mtype).getRef ();
}
if (mtype instanceof UnionType && !((UnionType)mtype).canOptimize ())
{
return true;
}
if (mtype instanceof BoundedStringType)
{
return true;
}
if (mtype instanceof StructType)
{
if (((StructType)mtype).isUnoptimizable ())
{
return true;
}
}
if (mtype.getAlignment ().equals (Alignment.PTR))
{
return true;
}
}
return false;
}
public long getKeySize ()
{
Type mtype;
long result = 0;
for (Member m : members)
{
mtype = m.type;
while (mtype instanceof TypedefType)
{
mtype = ((TypedefType)mtype).getRef ();
}
if (mtype.isKeyField ())
{
long subresult = mtype.getKeySize ();
if (subresult == -1)
{
return -1;
}
else
{
result += subresult;
}
}
}
return result;
}
public StructType dup ()
{
StructType result = new StructType (getSN (), parent);
for (Member m : members)
{
result.addMember (m.name, m.type);
}
return result;
}
public void getXML (StringBuffer str, ModuleContext mod)
{
if (parent != null && mod.isParent (name))
{
getXMLbase (str, mod);
}
else
{
str.append ("<Type name=\\\"");
str.append (mod.nameFrom (name));
str.append ("\\\"/>");
}
}
public void getToplevelXML (StringBuffer str, ModuleContext mod)
{
mod.enter (str, name);
getXMLbase (str, mod);
}
private void getXMLbase (StringBuffer str, ModuleContext mod)
{
mod.pushStruct (name.getLeaf ());
str.append ("<Struct name=\\\"");
str.append (name.getLeaf ());
str.append ("\\\">");
for (Member m : members)
{
str.append ("<Member name=\\\"");
str.append (m.name);
str.append ("\\\">");
m.type.getXML (str, mod);
str.append ("</Member>");
}
str.append ("</Struct>");
mod.popStruct ();
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
if (parent != null && current != null && !(parent.getSN ().equals (current.getSN ())))
{
parent.populateDeps (depset, current);
}
else
{
for (Member m : members)
{
m.type.populateDeps (depset, this);
}
if (parent == null || current == null)
{
depset.add (name);
}
}
}
public boolean depsOK (Set <ScopedName> deps)
{
for (Member m : members)
{
if (!TypeUtil.deptest (m.type, deps, name))
{
return false;
}
}
return true;
}
public ScopedName getSN ()
{
return new ScopedName (name);
}
public void invalidate ()
{
invalid = true;
}
public boolean isInvalid ()
{
return invalid;
}
private final NamedType parent;
private final ScopedName name;
private boolean invalid = false;
private ArrayList <Member> members;
}

View file

@ -0,0 +1,33 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import org.eclipse.cyclonedds.ScopedName;
import java.util.*;
public interface Type
{
public ArrayList <String> getMetaOp (String myname, String structname);
public String getSubOp ();
public String getOp ();
public String getCType ();
public void getXML (StringBuffer str, ModuleContext mod);
public void populateDeps (Set <ScopedName> depset, NamedType current);
public boolean depsOK (Set <ScopedName> deps);
public void makeKeyField ();
public boolean isKeyField ();
public long getKeySize ();
public int getMetaOpSize ();
public Alignment getAlignment ();
public Type dup ();
}

View file

@ -0,0 +1,62 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import org.eclipse.cyclonedds.ScopedName;
import java.util.Set;
public class TypeUtil
{
public static boolean deptest
(Type t, Set <ScopedName> deps, ScopedName parent)
/* t - the Type we're testing for
* deps - the types that have been written
* parent - the containing type, if any
*/
{
if (!t.depsOK (deps))
{
return false;
}
if (t instanceof NamedType)
{
NamedType nt = (NamedType)t;
ScopedName sn;
if (parent != null)
{
sn = new ScopedName (nt.getSN ());
sn.popComponent ();
if (sn.equals (parent)) // It's inline
{
return true;
}
}
sn = new ScopedName (nt.getSN ());
// deps only has toplevel containing types, so we may need to go up
do
{
if (deps.contains (sn))
{
return true;
}
} while (!sn.popComponent ().equals (""));
return false;
}
else
{
return true;
}
}
}

View file

@ -0,0 +1,105 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import org.eclipse.cyclonedds.ScopedName;
import java.util.*;
public class TypedefType extends AbstractType implements NamedType
{
public TypedefType (ScopedName name, Type ref)
{
this.ref = ref.dup ();
this.name = new ScopedName (name);
}
public Type dup ()
{
return new TypedefType (name, ref);
}
public ArrayList <String> getMetaOp (String myname, String structname)
{
return ref.getMetaOp (myname, structname);
}
public String getSubOp ()
{
return ref.getSubOp ();
}
public String getOp ()
{
return ref.getOp ();
}
public String getCType ()
{
return ref.getCType ();
}
public long getKeySize ()
{
return ref.getKeySize ();
}
public int getMetaOpSize ()
{
return ref.getMetaOpSize ();
}
public Alignment getAlignment ()
{
return ref.getAlignment ();
}
public void getToplevelXML (StringBuffer str, ModuleContext mod)
{
mod.enter (str, name);
str.append ("<TypeDef name=\\\"");
str.append (name.getLeaf ());
str.append ("\\\">");
ref.getXML (str, mod);
str.append ("</TypeDef>");
}
public void getXML (StringBuffer str, ModuleContext mod)
{
str.append ("<Type name=\\\"");
str.append (mod.nameFrom (name));
str.append ("\\\"/>");
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
ref.populateDeps (depset, this);
depset.add (name);
}
public boolean depsOK (Set <ScopedName> deps)
{
return TypeUtil.deptest (ref, deps, name);
}
public ScopedName getSN ()
{
return name;
}
public Type getRef ()
{
return ref;
}
private final Type ref;
private final ScopedName name;
}

View file

@ -0,0 +1,361 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.generator;
import org.eclipse.cyclonedds.ScopedName;
import java.util.*;
public class UnionType extends AbstractType implements NamedType
{
private static class Member
{
private Member (String n, Type t, String[] l)
{
name = n;
type = t;
labels = l;
}
private final String name;
private final Type type;
private final String[] labels;
};
public UnionType (ScopedName name, NamedType parent)
{
this.name = name;
members = new LinkedList <Member> ();
discriminant = null;
cardinality = 0;
hasdefault = false;
this.parent = parent;
}
public void setDiscriminant (Type discriminant)
{
this.discriminant = discriminant;
}
public void addMember
(String name, Type type, String[] labels, boolean isdefault)
{
/* We add an extra label for 'default'. Given the different requirements
* for meta-op gen and xml gen, it may be better not to, and remember that
* if (hasdefault && we are on the last member), there should be a default.
*/
if (isdefault)
{
String[] alllabels = new String[labels.length + 1];
System.arraycopy (labels, 0, alllabels, 0, labels.length);
alllabels [labels.length] = "0";
members.addLast (new Member (name, type, alllabels));
cardinality += alllabels.length;
hasdefault = true;
}
else
{
if (hasdefault)
{
Member def = members.removeLast ();
members.addLast (new Member (name, type, labels));
members.addLast (def);
}
else
{
members.addLast (new Member (name, type, labels));
}
cardinality += labels.length;
}
}
public ArrayList <String> getMetaOp (String myname, String structname)
{
ArrayList <String> result = new ArrayList <String> ();
String mynamedot;
if (structname == null)
{
structname = getCType ();
mynamedot = "";
}
else
{
mynamedot = myname + ".";
}
/* pre-calculate offsets for JEQ instructions */
int[] offsets = new int[getCardinality ()];
int opcount = 0;
int i = 0;
int l = 0;
for (Member m : members)
{
if (m.type instanceof BasicType)
{
for (l = 0; l < m.labels.length; l++)
{
offsets [i++] = 0;
}
}
else
{
for (l = 0; l < m.labels.length; l++)
{
offsets [i] = 3 * (getCardinality () - i) + opcount;
i++;
}
opcount += (m.type.getMetaOpSize () + 1);
}
}
/* discriminant */
result.add
(
"DDS_OP_ADR | DDS_OP_TYPE_UNI | " + discriminant.getSubOp () +
(hasdefault ? " | DDS_OP_FLAG_DEF" : "") + ", " +
"offsetof (" + structname + ", " + mynamedot + "_d), " +
new Integer (getCardinality ()) + "u, " +
"(" + new Integer (getMetaOpSize ()) + "u << 16) + 4u"
);
/* JEQs */
i = 0;
for (Member m : members)
{
for (l = 0; l < m.labels.length; l++)
{
result.add
(
"DDS_OP_JEQ | " + m.type.getOp () + " | " +
new Integer (offsets [i++]) + ", " +
m.labels[l] + ", " +
"offsetof (" + structname + ", " + mynamedot + "_u." + m.name + ")"
);
}
}
/* Subroutines for nonbasic types */
for (Member m : members)
{
if (!(m.type instanceof BasicType))
{
result.addAll (m.type.getMetaOp (null, null));
result.add (new String ("DDS_OP_RTS"));
}
}
/* Done */
return result;
}
public String getSubOp ()
{
return "DDS_OP_SUBTYPE_UNI";
}
public String getOp ()
{
return "DDS_OP_TYPE_UNI";
}
public String getCType ()
{
return name.toString ("_");
}
public long getKeySize ()
{
return -1;
}
public int getMetaOpSize ()
{
int result = 4 + 3 * getCardinality ();
for (Member m : members)
{
if (!(m.type instanceof BasicType))
{
result += (m.type.getMetaOpSize () + 1);
}
}
return result;
}
public boolean canOptimize ()
{
return false;
/* strictly speaking this could be true. condition would be, if all the
members have the same size, and if the non-basetype members are all
optimizable themselves, and the alignment of the discriminant is not
less than the alignment of the members. */
}
public Alignment getAlignment ()
{
Alignment result = discriminant.getAlignment ();
for (Member m : members)
{
result = result.maximum (m.type.getAlignment ());
}
return result;
}
public UnionType dup ()
{
UnionType result = new UnionType (name, parent);
result.setDiscriminant (discriminant);
result.members.addAll (members);
result.hasdefault = hasdefault;
result.cardinality = cardinality;
return result;
}
public void getXML (StringBuffer str, ModuleContext mod)
{
if (parent != null && mod.isParent (name))
{
getXMLbase (str, mod);
}
else
{
str.append ("<Type name=\\\"");
str.append (mod.nameFrom (name));
str.append ("\\\"/>");
}
}
public void getToplevelXML (StringBuffer str, ModuleContext mod)
{
mod.enter (str, name);
getXMLbase (str, mod);
}
private void getXMLbase (StringBuffer str, ModuleContext mod)
{
mod.pushStruct (name.getLeaf ());
str.append ("<Union name=\\\"");
str.append (name.getLeaf ());
str.append ("\\\"><SwitchType>");
discriminant.getXML (str, mod);
str.append ("</SwitchType>");
for (Member m : members)
{
str.append ("<Case name=\\\"");
str.append (m.name);
str.append ("\\\">");
m.type.getXML (str, mod);
for (int l = 0; l < m.labels.length; l++)
{
if (!hasdefault || m != members.getLast () || l != m.labels.length - 1)
{
str.append ("<Label value=\\\"");
str.append (mungeLabel (m.labels[l]));
str.append ("\\\"/>");
}
if (hasdefault && m == members.getLast () && m.labels.length == 1)
{
str.append ("<Default/>");
}
}
str.append ("</Case>");
}
str.append ("</Union>");
mod.popStruct ();
}
private String mungeLabel (String orig)
{
Type rt = discriminant;
while (rt instanceof TypedefType)
{
rt = ((TypedefType)rt).getRef ();
}
if (((BasicType)rt).type == BasicType.BT.CHAR)
{
return orig.substring (1, 2);
}
else if (((BasicType)rt).type == BasicType.BT.BOOLEAN)
{
return (orig.equals ("true") ? "True" : "False");
}
else if (discriminant instanceof EnumType)
{
return ((EnumType)discriminant).descope (orig);
}
else
{
return orig;
}
}
public void populateDeps (Set <ScopedName> depset, NamedType current)
{
if (parent != null && current != null && !(parent.getSN ().equals (current.getSN ())))
{
parent.populateDeps (depset, current);
}
else
{
for (Member m : members)
{
m.type.populateDeps (depset, this);
}
discriminant.populateDeps (depset, this);
if (parent == null || current == null)
{
depset.add (name);
}
}
}
public boolean depsOK (Set <ScopedName> deps)
{
if (!TypeUtil.deptest (discriminant, deps, name))
{
return false;
}
for (Member m : members)
{
if (!TypeUtil.deptest (m.type, deps, name))
{
return false;
}
}
return true;
}
private int getCardinality()
{
return cardinality;
}
public ScopedName getSN ()
{
return name;
}
private final NamedType parent;
private final ScopedName name;
private Type discriminant;
private LinkedList <Member> members;
private int cardinality;
private boolean hasdefault;
}

View file

@ -0,0 +1,782 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
/*
* Based on CppPreprocessor by Eric Mahurin
*/
header
{
package org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor;
}
options
{
language="Java";
}
{
import java.io.*;
import java.util.*;
import antlr.*;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessorStatus;
}
class CppLexer extends Lexer;
options
{
charVocabulary = '\3'..'\377';
testLiterals = false;
caseSensitive = true;
noConstructors = true;
k = 4;
}
tokens
{
ENDIF ;
}
{
private List<IIdlPreprocessorStatus> m_status = new ArrayList<IIdlPreprocessorStatus> ();
protected TokenStreamSelector selector;
protected Integer ifState = 1; // -1: no-else false, 0: false, 1: true
protected List<Integer> ifStates = new ArrayList<Integer>(); // holds nested if conditions
protected List<File> includePath = new ArrayList<File>();
protected List<PreprocessorFile> openFiles = new ArrayList<PreprocessorFile>();
protected Map<String, List<String>> defines = new HashMap<String, List<String>>(); // holds the defines
protected Map<String, List<String>> defineArgs = new HashMap<String, List<String>>(); // holds the args for a macro call
protected Map<File, List<File>> dependencies = new HashMap<File, List<File>>();
protected boolean stripComments = true;
protected boolean generateHashLine = true;
protected boolean processIncludes = true;
protected boolean inIncludeFile = false;
protected boolean concat = false;
protected boolean inMacro = false;
protected String escaped = "";
protected String stripped = "";
protected PreprocessorFile currentFile;
protected File baseDir;
protected CppLexer parent;
public CppLexer(PreprocessorFile file, File baseDir, Map<File, List<File>> dependencies, boolean generateHashLine) throws FileNotFoundException
{
this(file.getInputStream());
this.setFilename(file.getOriginalPath());
this.currentFile = file;
this.openFiles.add(currentFile);
this.baseDir = baseDir;
if(dependencies != null)
this.dependencies = dependencies;
this.dependencies.put(file.getOriginalFile(), new ArrayList<File>());
this.generateHashLine = generateHashLine;
selector = new TokenStreamSelector();
selector.select(this);
String line = "# " + getLine() + " \"" + getFilename() + "\"\n";
CppLexer sublexer = new CppLexer(line, this);
selector.push(sublexer);
}
private CppLexer(String str, CppLexer parent)
{
this(new ByteArrayInputStream(str.getBytes()));
this.selector = parent.selector;
this.ifState = parent.ifState;
this.ifStates = parent.ifStates;
this.defines = parent.defines;
this.defineArgs = parent.defineArgs;
this.stripComments = parent.stripComments;
this.generateHashLine = parent.generateHashLine;
this.processIncludes = parent.processIncludes;
this.inIncludeFile = parent.inIncludeFile;
this.inMacro = parent.inMacro;
this.m_status = parent.m_status;
selector.push(this);
}
private CppLexer(PreprocessorFile file, CppLexer parent) throws FileNotFoundException
{
this(file.getInputStream());
this.setFilename(file.getOriginalPath());
this.dependencies = parent.dependencies;
dependencies.put(file.getOriginalFile(), new ArrayList<File>());
this.currentFile = file;
this.openFiles = parent.openFiles;
this.openFiles.add(currentFile);
this.baseDir = parent.baseDir;
this.includePath = parent.includePath;
this.selector = parent.selector;
this.ifState = parent.ifState;
this.ifStates = parent.ifStates;
this.defines = parent.defines;
this.stripComments = parent.stripComments;
this.generateHashLine = parent.generateHashLine;
this.processIncludes = parent.processIncludes;
this.inIncludeFile = true;
this.m_status = parent.m_status;
this.parent = parent;
if(cycleCheck(file))
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, "Cycle in includes; " + file + " included with itself", null));
}
else
{
selector.push(this);
String line = "# " + getLine() + " \"" + getFilename() + "\" 1\n";
new CppLexer(line, this);
}
}
private boolean cycleCheck(PreprocessorFile file)
{
if(parent == null)
return false;
else if(parent.currentFile.equals(file))
return true;
else
return parent.cycleCheck(file);
}
private void include(String name)
{
PreprocessorFile toInclude = null;
File temp = null;
File currentDir = null;
//Evaluate included file against directory containing the current file
String currentFilePath = currentFile.getOriginalPath();
if(currentFilePath.contains("/"))
{
currentDir = new File(currentFilePath.substring(0, currentFilePath.lastIndexOf("/")));
}
temp = new File(currentDir, name);
if(currentDir != null && currentDir.isAbsolute())
{
toInclude = new PreprocessorFile(null, temp.getPath());
}
else
{
toInclude = new PreprocessorFile(baseDir, temp.getPath());
}
//Search include paths for included file
if(!toInclude.exists())
{
for(File dir:includePath)
{
temp = new File(dir, name);
if(dir.isAbsolute())
{
toInclude = new PreprocessorFile(null, temp.getPath());
}
else
{
toInclude = new PreprocessorFile(baseDir, temp.getPath());
}
if(toInclude.exists())
{
break;
}
}
}
List<File> deps = dependencies.get(currentFile.getOriginalFile());
deps.add(toInclude.getOriginalFile());
try
{
String line = "# " + getLine() + " \"" + getFilename() + "\" 2\n";
new CppLexer(line, this);
new CppLexer(toInclude, this);
}
catch (FileNotFoundException fnf)
{
setLine(getLine()-1);
reportError("Could not find file " + name);
newline();
}
}
public void close()
{
for(PreprocessorFile toClose : openFiles)
{
toClose.close();
}
}
public void setTokenStreamSelector(TokenStreamSelector selector)
{
this.selector = selector;
}
public void setProcessIncludes(boolean processIncludes)
{
this.processIncludes = processIncludes;
}
public void setCurrentFile(PreprocessorFile currentFile)
{
this.currentFile = currentFile;
}
public void setDefines(Map<String, List<String>> defines)
{
this.defines = defines;
}
public void setDependencies(Map<File, List<File>> dependencies)
{
this.dependencies = dependencies;
}
public void setIncludePath(List<File> includePath)
{
this.includePath = includePath;
}
public void setBaseDir(File baseDir)
{
this.baseDir = baseDir;
}
public void setStripComments(boolean stripComments)
{
this.stripComments = stripComments;
}
public Map<File, List<File>> getDependencies()
{
return dependencies;
}
public boolean evaluateExpression(String expr) throws TokenStreamException, RecognitionException, PreprocessorException
{
//Perform macro substitution on the expression
expr = subLex(expr);
//Parse the expression
ExpLexer lexer = new ExpLexer(new ByteArrayInputStream(expr.getBytes()));
ExpParser parser = new ExpParser(this, lexer);
IIdlPreprocessorStatus parseStatus = parser.parse();
if(!parseStatus.isOK())
{
m_status.add(parseStatus);
throw new PreprocessorException();
}
//Evaluate the expression
ExpTreeParser treeParser = new ExpTreeParser(this);
boolean result = treeParser.expression(parser.getAST());
IIdlPreprocessorStatus treeParseStatus = treeParser.getStatus();
if(!treeParseStatus.isOK())
{
m_status.add(treeParseStatus);
throw new PreprocessorException();
}
return result;
}
public String subLex(String str) throws TokenStreamException, RecognitionException, PreprocessorException
{
CppLexer cppLexer = new CppLexer(new ByteArrayInputStream(str.getBytes()));
cppLexer.defines = defines;
cppLexer.selector = new TokenStreamSelector();
cppLexer.selector.select(cppLexer);
IIdlPreprocessorStatus cppStatus = cppLexer.getStatus();
if(!cppStatus.isOK())
{
m_status.add(cppStatus);
throw new PreprocessorException();
}
str = "";
for (;;)
{
Token t = cppLexer.getNextToken();
if (t.getType() == Token.EOF_TYPE)
{
break;
}
str += t.getText();
}
return str;
}
public void consumeConditionBody() throws TokenStreamException
{
String consumed = "";
int lineNo = getLine();
for (;;)
{
try
{
consumeUntil('#');
Token t = selector.nextToken();
if (t.getType() == ENDIF || t.getType() == EOF)
{
break;
}
}
catch (ANTLRException r)
{
// just continue if someone tried retry
}
}
for(int i = lineNo; i < getLine(); i++)
{
consumed += "\n";
}
new CppLexer(consumed, this);
}
public Token getNextToken() throws TokenStreamException
{
try
{
Token t = selector.nextToken();
return t;
}
catch (TokenStreamException e)
{
m_status.add(new PreprocessorStatus(this, IIdlPreprocessorStatus.ERROR, e.getMessage(), e));
throw e;
}
}
public void uponEOF() throws TokenStreamException
{
try
{
selector.pop(); // return to old lexer/stream
selector.retry();
}
catch (NoSuchElementException e)
{
// return a real EOF if nothing in stack
}
if(ifStates.size() != 0)
{
ifStates.remove(ifStates.size()-1);
reportError("Reached EOF expecting #endif");
}
}
public IIdlPreprocessorStatus getStatus()
{
switch (m_status.size())
{
case 0 :
{
return new PreprocessorStatus(IIdlPreprocessorStatus.OK);
}
case 1 :
{
return m_status.get(0);
}
default :
{
PreprocessorStatus status = new PreprocessorStatus();
for (IIdlPreprocessorStatus s : m_status)
status.add (s);
return status;
}
}
}
@Override
public void reportError(RecognitionException recex)
{
m_status.add(new PreprocessorStatus(this, IIdlPreprocessorStatus.ERROR, recex.getMessage(), recex));
}
@Override
public void reportError(String message)
{
m_status.add(new PreprocessorStatus(this, IIdlPreprocessorStatus.ERROR, message, null));
}
@Override
public void reportWarning(String message)
{
m_status.add(new PreprocessorStatus(this, IIdlPreprocessorStatus.WARNING, message, null));
}
}
DIRECTIVE
{
List<String> args = new ArrayList<String>();
boolean condition = true;
}
: "#"! ( { inMacro && LA(1)=='#'}?
{
concat = true;
}
| { inMacro }? (WS)* hashExpr:EXPR!
{
if(ifState == 1)
{
if(concat)
{
concat = false;
CppLexer subLexer = new CppLexer(hashExpr.getText(), this);
}
else
{
CppLexer subLexer = new CppLexer('"' + hashExpr.getText() + '"', this);
}
}
}
| (WS)* ("include" (WS)+ includeFile:INCLUDE_STRING (WS)* DNL
{
if (ifState==1)
{
$setType(Token.SKIP);
String name = includeFile.getText();
name = name.substring(1,name.length()-1);
include(name);
selector.retry();
}
}
|"define" (WS)+ defineMacro:RAW_IDENTIFIER (WS)* {args.add("");}
(
( '('
(WS)* defineArg0:RAW_IDENTIFIER (WS)* {args.add(defineArg0.getText());}
( COMMA (WS)* defineArg1:RAW_IDENTIFIER (WS)* {args.add(defineArg1.getText());} )*
')'
| WS
)
(WS)*
defineText:MACRO_TEXT {args.set(0,defineText.getText());}
)? NL
{
if (ifState==1)
{
defines.put( defineMacro.getText(), args );
}
$setText("\n" + escaped);
escaped = "";
}
|"undef" (WS)+ undefMacro:RAW_IDENTIFIER (WS)* DNL
{
if (ifState==1)
{
defines.remove(undefMacro.getText());
}
$setText("\n");
}
|("ifdef"|"ifndef"{condition=false;}) (WS)+ ifMacro:RAW_IDENTIFIER (WS)* DNL
{
ifStates.add(ifState);
if (ifState==1)
{
condition = (defines.containsKey(ifMacro.getText())==condition);
ifState = condition?1:0;
}
else
{
ifState = -1;
}
if (ifState==1)
{
$setText("\n");
}
else
{
// gobble up tokens until ENDIF (could be caused by else)
consumeConditionBody();
}
}
| "if" (WS)+ ifExpr:MACRO_TEXT NL
{
ifStates.add(ifState);
if (ifState==1)
{
try
{
condition = evaluateExpression(ifExpr.getText());;
ifState = condition?1:0;
}
catch(PreprocessorException p)
{
// failed to evaluate expression set ifState so the rest of the ifstatement is discarded
ifState = -1;
}
}
else
{
ifState = -1;
}
if (ifState==1)
{
$setText("\n");
}
else
{
// gobble up tokens until ENDIF (could be caused by else)
consumeConditionBody();
}
}
| ( "else" {condition=true;} (WS)* DNL // treat like elif (true)
|"elif" (WS)+ expr:MACRO_TEXT NL
{
try
{
condition=evaluateExpression(expr.getText());
}
catch(PreprocessorException p)
{
// failed to evaluate expression set ifState so the rest of the ifstatement is discarded
ifState = 1;
}
}
)
{
if (ifState==1)
{
// previous if/elif was taken - discard rest
ifState = -1;
consumeConditionBody();
}
else if (ifState==0 && condition)
{
// "elif" (true) or "else"
$setText("\n");
$setType(ENDIF);
ifState = 1;
}
}
| "endif" (WS)* DNL
{
condition = (ifState==1);
try
{
// return to previous if state
ifState = ifStates.remove(ifStates.size()-1);
$setText("\n");
if (!condition)
{
// tell if/else/elif to stop discarding tokens
$setType(ENDIF);
}
}
catch (ArrayIndexOutOfBoundsException e)
{
reportError("#endif without matching #if");
}
}
| "line" (WS)+ ln:NUMBER ((WS)+ file:STRING)? (WS)* DNL
{
if(ifState==1)
{
$setType(Token.SKIP);
String line = "# " + ln.getText();
if(file != null)
{
String filename = file.getText();
line += " " + filename;
setFilename(filename.substring(1,filename.length()-1));
}
else
{
line += " \"" + getFilename() + "\"";
}
line += "\n";
setLine(Integer.parseInt(ln.getText()));
CppLexer subLexer = new CppLexer(line, this);
selector.retry();
}
}
| "error" (WS)+ errMsg:MACRO_TEXT NL
{
if(ifState == 1)
{
reportError(errMsg.getText());
}
}
| "warning" (WS)+ warnMsg:MACRO_TEXT NL
{
if(ifState == 1)
{
$setText("\n" + escaped);
escaped = "";
reportWarning(warnMsg.getText());
}
}
| "pragma" (WS)+ pragma:MACRO_TEXT NL
{
if(inIncludeFile && !processIncludes)
{
$setType(Token.SKIP);
}
else
{
try
{
String pText = pragma.getText() + '\n';
$setText("#pragma " + subLex(pText));
}
catch(PreprocessorException e)
{
//Status already updated ignore error and continue
$setText('\n');
}
}
}
| l:NUMBER (WS)+ f:STRING ((WS)+ flag:NUMBER)? (WS)* DNL
{
if(!generateHashLine)
{
$setText('\n');
}
else
{
String fl = (flag == null) ? "" : " " + flag.getText();
$setText("# " + l.getText() + " " + f.getText() + fl + '\n');
}
}
| DNL
{
$setText('\n');
}
)
)
;
NON_DIRECTIVE
{
if(inIncludeFile && !processIncludes)
$setType(Token.SKIP);
}
: (STRING | NUMBER | COMMENT | LEFT | RIGHT | COMMA | OPERATOR | WS)
;
IDENTIFIER options {testLiterals=true;}
{
List<String> define = new ArrayList<String>();
List<String> args = new ArrayList<String>();
if(inIncludeFile && !processIncludes)
$setType(Token.SKIP);
}
: identifier:RAW_IDENTIFIER
{
define = defineArgs.get(identifier.getText());
if (_createToken && define==null)
{
define = defines.get(identifier.getText());
}
}
( { (define!=null) && (define.size()>1) }? (WS)*
'(' (WS)*
callArg0:EXPR {args.add(callArg0.getText());}
( (WS)* COMMA (WS)* callArg1:EXPR {args.add(callArg1.getText());} )*
{ args.size()==define.size()-1 }? // better have right amount
(WS)* ')'
| { !((define!=null) && (define.size()>1)) }?
)
{
if (define!=null)
{
String defineText = define.get(0);
if (!_createToken)
{
$setText(defineText);
}
else
{
for (int i=0;i<args.size();++i)
{
List<String> arg = new ArrayList<String>();
arg.add(args.get(i));
defineArgs.put(define.get(1+i), arg);
}
inMacro=true;
CppLexer sublexer = new CppLexer(defineText, this);
selector.retry();
inMacro=false;
}
}
}
;
protected STRING
: '"' ( '\\' . | ~('\\'|'"') )* '"' // double quoted string
| '\'' ( '\\' . | ~('\\'|'\'') )* '\'' // single quoted string
;
protected INCLUDE_STRING
: '<' (~'>')* '>'
| STRING
;
protected MACRO_TEXT : ( options{greedy=false;} : . | ESC_NL )+;
protected WS: (' ' | '\t' | '\f');
protected DNL: (COMMENT | NL);
NL: (CR)? '\n' {newline();};
CR!: ('\r')+;
protected ESC_NL : '\\'! NL! {escaped += "\n";};
protected COMMENT
: ( "//" ( options{greedy=false;} : . )* NL {if(stripComments || (inIncludeFile && !processIncludes))stripped+="\n";} // single line comment
| "/*" ( options{greedy=false;} : NL {if(stripComments || (inIncludeFile && !processIncludes))stripped+="\n";}
| . {if(stripComments || (inIncludeFile && !processIncludes))stripped+=" ";})* "*/" // multi-line comment
)
{
if(stripComments || (inIncludeFile && !processIncludes))
{
$setText(stripped);
stripped="";
}
}
;
protected RAW_IDENTIFIER : ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')* ;
protected INT_SUFFIX: ("l"|"L"|"u"|"U"|"lu"|"Lu"|"lU"|"LU"|"ul"|"Ul"|"uL"|"UL");
protected DEC_DIGITS: ('1'..'9') ('0'..'9')*;
protected HEX_PREFIX: '0' ('x'|'X');
protected HEX_DIGITS: ('0'..'9' | 'a'..'f' | 'A'..'F')+;
protected OCT_PREFIX: '0';
protected OCT_DIGITS: ('0'..'7')*;
protected DEC_INT: DEC_DIGITS (INT_SUFFIX)? ;
protected HEX_INT: HEX_PREFIX HEX_DIGITS (INT_SUFFIX)? ;
protected OCT_INT: OCT_PREFIX OCT_DIGITS (INT_SUFFIX)? ;
protected NUMBER : (DEC_INT | HEX_INT | OCT_INT); // allow alpha suffixes on numbers (i.e. L:long)
// group symbols into categories to parse EXPR
protected LEFT : '(' | '[' | '{' ;
protected RIGHT : ')' | ']' | '}' ;
protected COMMA : ',' ;
protected OPERATOR : '!' | '$' | '%' | '&' | '*' | '+' | '-' | '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '\\' | '^' | '`' | '|' | '~' ;
DEFINED : "defined" ((LEFT) RAW_IDENTIFIER (RIGHT)| (WS)+ RAW_IDENTIFIER);
protected EXPR // allow just about anything without being ambiguous
: (WS)? (NUMBER|IDENTIFIER)?
(
( LEFT EXPR ( COMMA EXPR )* RIGHT
| STRING
| OPERATOR // quotes, COMMA, LEFT, and RIGHT not in here
| WS
)
EXPR
)?
;

View file

@ -0,0 +1,311 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
header
{
package org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor;
}
options
{
language = "Java";
}
class ExpLexer extends Lexer;
options
{
k=2;
}
RAW_IDENTIFIER: ('a'..'z'|'A'..'Z'|'_') ('a'..'z'|'A'..'Z'|'_'|'0'..'9')*;
protected INT_SUFFIX: ("l"|"L"|"u"|"U"|"lu"|"Lu"|"lU"|"LU"|"ul"|"Ul"|"uL"|"UL");
protected DEC_DIGITS: ('1'..'9') ('0'..'9')*;
protected HEX_PREFIX: '0' ('x'|'X');
protected HEX_DIGITS: ('0'..'9' | 'a'..'f' | 'A'..'F')+;
protected OCT_PREFIX: '0';
protected OCT_DIGITS: ('0'..'7')*;
DEC_INT: DEC_DIGITS (INT_SUFFIX!)? ;
HEX_INT: HEX_PREFIX! HEX_DIGITS (INT_SUFFIX!)? ;
OCT_INT: OCT_PREFIX OCT_DIGITS (INT_SUFFIX!)? ;
WS : (' '|'\t'|'\r'|'\n') { $setType(Token.SKIP); } ;
LPAREN : '(' ;
RPAREN : ')' ;
PLUS : '+' ;
MINUS : '-' ;
MULTIPLY : '*' ;
DIVIDE : '/' ;
REMAINDER : '%' ;
COMPLIMENT: '~' ;
LSHIFT : "<<" ;
RSHIFT : ">>" ;
BIT_AND : "&" ;
BIT_INC_OR: "|" ;
BIT_EXC_OR: "^" ;
OR : "||" ;
AND : "&&" ;
EQUAL : "==" ;
NOT_EQUAL : "!=" ;
NOT : '!' ;
LT : '<' ;
LE : "<=" ;
GE : ">=" ;
GT : '>' ;
DEFINED : "defined";
{
import java.util.*;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessorStatus;
}
class ExpParser extends Parser;
options
{
k=4;
buildAST = true;
}
{
private List<IIdlPreprocessorStatus> m_status = new ArrayList<IIdlPreprocessorStatus> ();
CppLexer parent;
public ExpParser(CppLexer parent, ExpLexer expLexer)
{
this(expLexer);
this.parent = parent;
}
public IIdlPreprocessorStatus parse()
{
try
{
orExpr();
if(LA(1) != EOF)
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, "Invalid token " + LA(1), null));
}
catch (RecognitionException e)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, e.getMessage(), e));
}
catch (TokenStreamException e)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, e.getMessage(), e));
}
return getStatus ();
}
public IIdlPreprocessorStatus getStatus()
{
switch (m_status.size())
{
case 0 :
{
return new PreprocessorStatus(IIdlPreprocessorStatus.OK);
}
case 1 :
{
return m_status.get(0);
}
default :
{
PreprocessorStatus status = new PreprocessorStatus();
for (IIdlPreprocessorStatus s : m_status)
status.add (s);
return status;
}
}
}
@Override
public void reportError(RecognitionException recex)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, recex.getMessage(), recex));
}
@Override
public void reportError(String message)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, message, null));
}
@Override
public void reportWarning(String message)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.WARNING, message, null));
}
}
value
: HEX_INT | DEC_INT | OCT_INT | RAW_IDENTIFIER
;
orExpr
: andExpr (OR^ andExpr)*
;
andExpr
: bitIncOr (AND^ bitIncOr)*
;
bitIncOr
: bitExcOr (BIT_INC_OR^ bitExcOr)*
;
bitExcOr
: bitAnd (BIT_EXC_OR^ bitAnd)*
;
bitAnd
: equal (BIT_AND^ equal)*
;
equal
: compare ((EQUAL^ | NOT_EQUAL^) compare)*
;
compare
: shift ((LT^ | LE^ | GE^ | GT^) shift)*
;
shift
: addition ((LSHIFT^|RSHIFT^) addition)*
;
addition
: multiplication ((PLUS^|MINUS^) multiplication)*
;
multiplication
: unary ((MULTIPLY^|DIVIDE^|REMAINDER^) unary)*
;
unary
: (PLUS^ | MINUS^ | COMPLIMENT^)? value
| NOT^ unary
| DEFINED^ LPAREN! RAW_IDENTIFIER RPAREN!
| DEFINED^ RAW_IDENTIFIER
| LPAREN! orExpr RPAREN!
;
{
import java.util.*;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessorStatus;
}
class ExpTreeParser extends TreeParser;
{
private List<IIdlPreprocessorStatus> m_status = new ArrayList<IIdlPreprocessorStatus> ();
CppLexer parent;
public ExpTreeParser(CppLexer parent)
{
this.parent = parent;
}
public IIdlPreprocessorStatus getStatus()
{
switch (m_status.size())
{
case 0 :
{
return new PreprocessorStatus(IIdlPreprocessorStatus.OK);
}
case 1 :
{
return m_status.get(0);
}
default :
{
PreprocessorStatus status = new PreprocessorStatus();
for (IIdlPreprocessorStatus s : m_status)
status.add (s);
return status;
}
}
}
@Override
public void reportError(RecognitionException recex)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, recex.getMessage(), recex));
}
@Override
public void reportError(String message)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.ERROR, message, null));
}
@Override
public void reportWarning(String message)
{
m_status.add(new PreprocessorStatus(parent, IIdlPreprocessorStatus.WARNING, message, null));
}
}
value returns [ int i ]
{
int x, y;
i = 0;
}
: #(BIT_INC_OR x=value y=value { i = x|y; } )
| #(BIT_EXC_OR x=value y=value { i = x^y; } )
| #(BIT_AND x=value y=value { i = x&y; } )
| #(LSHIFT x=value y=value { i = x<<y; } )
| #(RSHIFT x=value y=value { i = x>>y; } )
| (#(PLUS x=value y=value)) => #(PLUS x=value y=value { i = x+y; } )
| #(PLUS x=value { i = x; } )
| (#(MINUS x=value y=value)) => #(MINUS x=value y=value { i = x-y; } )
| #(MINUS x=value { i = -1*x; } )
| #(MULTIPLY x=value y=value { i = x*y; } )
| #(DIVIDE x=value y=value { i = x/y; } )
| #(REMAINDER x=value y=value { i = x%y; } )
| #(COMPLIMENT x=value { i = ~x; } )
| d:DEC_INT { i = Integer.parseInt(d.getText(), 10); }
| h:HEX_INT { i = Integer.parseInt(h.getText(), 16); }
| o:OCT_INT { i = Integer.parseInt(o.getText(), 8); }
| r:RAW_IDENTIFIER { i = 0; }
;
identifier returns [ String s ]
{
s = null;
}
: i:RAW_IDENTIFIER
{
s = i.getText();
}
;
expression returns [ boolean e ]
{
boolean a, b;
int l, r;
String i;
e = false;
}
: #(AND a=expression b=expression { e = a && b; } )
| #(BAND a=expression b=expression { e = a & b; } )
| #(OR a=expression b=expression { e = a || b; } )
| #(BOR a=expression b=expression { e = a | b; } )
| #(NOT a=expression { e = !a; } )
| #(EQUAL l=value r=value { e = l==r; } )
| #(NOT_EQUAL l=value r=value { e = l!=r; } )
| #(LT l=value r=value { e = l<r; } )
| #(LE l=value r=value { e = l<=r; } )
| #(GE l=value r=value { e = l>=r; } )
| #(GT l=value r=value { e = l>r; } )
| #(DEFINED i=identifier { e = parent.defines.containsKey(i); } )
;

View file

@ -0,0 +1,304 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileWriter;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import antlr.Token;
import antlr.TokenStreamRecognitionException;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessor;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessorParams;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessorStatus;
/**
* Public interface to the C IIdlPreprocessor. This preprocessor will produce <em>almost</em> the
* same output as running the {@link http://gcc.gnu.org/onlinedocs/cpp/ gcc preprocessor}. Details
* of the output format can be found
* {@link http://gcc.gnu.org/onlinedocs/cpp/IIdlPreprocessor-Output.html#Preprocessor-Output here}.
* <p>
* This preprocessor differs from gcc in the way it deals with blank lines. The gcc preprocessor
* removes long sequences of blank lines and replaces them with an appropriate <em>line marker</em>,
* whereas this preprocessor preserves all blank lines..
*
* <pre><code>
* File input = ..;
* StringWriter output = new StringWriter ();
*
* IIdlPreprocessor preprocessor = new IIdlPreprocessor ();
*
* preprocessor.setWorkingDirectory (new File (&quot;/home/ted/project1&quot;);
* preprocessor.addIncludeDirectory (new File (&quot;includes&quot;));
* preprocessor.setStripComments (false);
* preprocessor.setStripIncludes (true);
*
* IStatus status = preprocessor.preprocess (input, output, null);
* </code></pre>
*/
public class IdlPreprocessor implements IIdlPreprocessor
{
public IIdlPreprocessorParams createPreprocessorParams ()
{
return new IdlPreprocessorParams ();
}
/**
* Runs the preprocessor on the specified {@link File file} and sends the resulting output to the
* specified {@link Writer writer}. It also populates the optional <code>dependencies</code>
* map, if one is provided.
*
* @param input
* The file to be preprocessed
* @param output
* Where to put the preprocessed output
* @param dependencies
* An optional Map containing a key for each file encountered during preprocessing.
* Each key (file) entry lists the files that it included.
*/
public IIdlPreprocessorStatus preprocess (IIdlPreprocessorParams params, File input, Writer output, Map<File, List<File>> dependencies)
{
CppLexer mainLexer = null;
try
{
PreprocessorFile toProcess;
if (input.isAbsolute ())
{
toProcess = new PreprocessorFile (null, input.getPath ());
}
else
{
toProcess = new PreprocessorFile (params.getWorkingDirectory (), input.getPath ());
}
List<File> includes = new ArrayList<File> ();
includes.addAll (params.getIncludeDirectories ());
String path = input.getPath ().substring (0, input.getPath ().length () - input.getName ().length ());
if (!path.equals (""))
{
includes.add (new File (path));
}
Map<String, List<String>> defines = new HashMap<String, List<String>> ();
defines.putAll (params.getMacroDefinitions ());
mainLexer = new CppLexer (toProcess, params.getWorkingDirectory (), dependencies, !params.getStripLineMarkers ());
mainLexer.setIncludePath (includes);
mainLexer.setDefines (defines);
mainLexer.setProcessIncludes (!params.getStripIncludes ());
mainLexer.setStripComments (params.getStripComments ());
for (;;)
{
Token t = mainLexer.getNextToken ();
if (t.getType () == Token.EOF_TYPE)
{
break;
}
output.write (t.getText ());
output.flush ();
}
IIdlPreprocessorStatus status = mainLexer.getStatus ();
return status;
}
catch (TokenStreamRecognitionException e)
{
return new PreprocessorStatus (e);
}
catch (FileNotFoundException e)
{
return new PreprocessorStatus (e, input);
}
catch (Exception e)
{
String message = e.getClass ().getSimpleName () + " caught during preprocessing";
return new PreprocessorStatus (mainLexer, IIdlPreprocessorStatus.ERROR, message, e);
}
finally
{
if (mainLexer != null)
mainLexer.close ();
}
}
/**
* An example command line driver. This is not really part of the public API
*/
public static void main (String[] args)
{
try
{
File input = null;
IdlPreprocessor preprocessor = new IdlPreprocessor ();
IIdlPreprocessorParams params = new IdlPreprocessorParams ();
Map<File, List<File>> dependencies = null;
Writer output = new OutputStreamWriter (System.out);
for (int i = 0; i < args.length;)
{
String arg = args[i++];
if (arg.equals ("-I"))
{
if (i >= args.length)
{
usage ();
System.exit (-1);
}
else
{
params.addIncludeDirectory (new File (args[i++]));
}
}
else if (arg.equals ("-O"))
{
if (i >= args.length)
{
usage ();
System.exit (-1);
}
else
{
output = new FileWriter (args[i++]);
}
}
else if (arg.equals ("-D"))
{
if (i >= args.length)
{
usage ();
System.exit (-1);
}
else
{
arg = args[i++];
int equals = arg.indexOf ('=');
if (equals == -1)
{
params.addMacroDefinition (arg);
}
else
{
String name = arg.substring (0, equals);
String value = arg.substring (equals + 1);
params.addMacroDefinition (name, value);
}
}
}
else if (arg.equals ("-U"))
{
if (i >= args.length)
{
usage ();
System.exit (-1);
}
else
{
params.removeMacroDefinition (args[i++]);
}
}
else if (arg.equals ("-B"))
{
if (i >= args.length)
{
usage ();
System.exit (-1);
}
else
{
params.setWorkingDirectory (new File (args[i++]));
}
}
else if (arg.equals ("-M"))
{
dependencies = new HashMap<File, List<File>> ();
}
else if (arg.equals ("--LeaveComments"))
{
params.setStripComments (false);
}
else if (arg.equals ("--NoFileInline"))
{
params.setStripIncludes (true);
}
else if (arg.equals ("--NoLineMarkers"))
{
params.setStripLineMarkers (true);
}
else
{
if (i < args.length)
{
usage ();
System.exit (-1);
}
else
{
input = new File (arg);
}
}
}
if (input == null)
{
usage ();
System.exit (-1);
}
IIdlPreprocessorStatus status = preprocessor.preprocess (params, input, output, dependencies);
if (status.getChildStati ().length == 0)
System.err.println (status);
for (IIdlPreprocessorStatus child : status.getChildStati ())
{
System.err.println (child);
}
if (dependencies != null)
{
for (File file : dependencies.keySet ())
{
System.out.println ();
System.out.println (" " + file.getPath () + " :");
for (File included : dependencies.get (file))
{
System.out.println (" " + included.getPath ());
}
}
}
}
catch (Exception e)
{
e.printStackTrace ();
}
}
private static void usage ()
{
System.err
.println ("USAGE : "
+ IdlPreprocessor.class.getName ()
+ " [-I <dir>] [-B <working dir>] [-O <output filename] [--LeaveComments] [--NoFileInline] [--NoLineMarkers] [-D <name>[=<value>]] [-U <name>] <filename>");
}
}

View file

@ -0,0 +1,127 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessorParams;
public class IdlPreprocessorParams implements IIdlPreprocessorParams
{
private List<File> includeDirectories = new ArrayList<File> ();
private boolean stripComments = true;
private boolean stripIncludes = false;
private boolean stripLineMarkers = false;
private File workingDirectory = new File (System.getProperty ("user.dir"));
private Map<String, List<String>> defines = new HashMap<String, List<String>> ();
public void addIncludeDirectory (File directory) throws FileNotFoundException
{
if (directory != null && directory.exists () && directory.isDirectory ())
{
includeDirectories.add (directory);
}
}
public void addMacroDefinition (String name)
{
List<String> args = new ArrayList<String> ();
args.add ("");
defines.put (name, args);
}
public void addMacroDefinition (String name, String value)
{
List<String> args = new ArrayList<String> ();
args.add (value);
defines.put (name, args);
}
public List<File> getIncludeDirectories ()
{
return includeDirectories;
}
public Map<String, List<String>> getMacroDefinitions ()
{
return defines;
}
public boolean getStripComments ()
{
return stripComments;
}
public boolean getStripIncludes ()
{
return stripIncludes;
}
public boolean getStripLineMarkers ()
{
return stripLineMarkers;
}
public File getWorkingDirectory ()
{
return workingDirectory;
}
public void removeIncludeDirectory (File directory)
{
includeDirectories.remove (directory);
}
public void removeMacroDefinition (String name)
{
defines.remove (name);
}
public void setStripComments (boolean stripComments)
{
this.stripComments = stripComments;
}
public void setStripIncludes (boolean stripIncludes)
{
this.stripIncludes = stripIncludes;
}
public void setStripLineMarkers (boolean stripLineMarkers)
{
this.stripLineMarkers = stripLineMarkers;
}
public void setWorkingDirectory (File directory) throws FileNotFoundException
{
if (directory != null && directory.exists () && directory.isDirectory ())
{
this.workingDirectory = directory;
}
else
{
throw new FileNotFoundException ("Can't find directory " + directory.getPath ());
}
}
}

View file

@ -0,0 +1,27 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor;
public class PreprocessorException extends Exception
{
static final long serialVersionUID = 1;
public PreprocessorException ()
{
super ();
}
public PreprocessorException (String message)
{
super (message);
}
}

View file

@ -0,0 +1,93 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
public class PreprocessorFile extends File
{
/**
*
*/
private static final long serialVersionUID = 1L;
private String originalPath;
private File originalFile;
private FileInputStream inputStr;
private boolean reachedEOF = false;
public PreprocessorFile (File workingDir, String originalPath)
{
super (workingDir, originalPath.replace ('\\', '/'));
this.originalPath = originalPath.replace ('\\', '/');
this.originalFile = new File (this.originalPath);
}
public String getOriginalPath ()
{
return originalPath;
}
public File getOriginalFile ()
{
return originalFile;
}
public InputStream getInputStream () throws FileNotFoundException
{
if (inputStr == null)
{
inputStr = new FileInputStream (this)
{
@Override
public int read () throws IOException
{
int i = super.read ();
if (reachedEOF)
{
return -1;
}
else if (i == -1)
{
reachedEOF = true;
return '\n';
}
else
{
return i;
}
}
};
}
return inputStr;
}
public void close ()
{
try
{
inputStr.close ();
}
catch (Exception e)
{
}
}
}

View file

@ -0,0 +1,152 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.ArrayList;
import java.util.List;
import antlr.TokenStreamRecognitionException;
import org.eclipse.cyclonedds.idt.imports.idl.preprocessor.IIdlPreprocessorStatus;
public class PreprocessorStatus implements IIdlPreprocessorStatus
{
private int m_severity;
private String m_message;
private String m_filename;
private int m_line;
private int m_column;
private Throwable m_cause;
private List<IIdlPreprocessorStatus> m_children;
public PreprocessorStatus ()
{
m_children = new ArrayList<IIdlPreprocessorStatus>();
}
public PreprocessorStatus (int severity)
{
m_severity = severity;
m_children = new ArrayList<IIdlPreprocessorStatus>();
}
public PreprocessorStatus (CppLexer lexer, int severity, String message, Throwable cause)
{
m_severity = severity;
m_message = message;
m_filename = lexer.getFilename ();
m_line = lexer.getLine ();
m_column = lexer.getColumn ();
m_cause = cause;
m_children = new ArrayList<IIdlPreprocessorStatus>();
}
public PreprocessorStatus (TokenStreamRecognitionException cause)
{
m_severity = IIdlPreprocessorStatus.ERROR;
m_message = cause.getMessage ();
m_filename = cause.recog.getFilename ();
m_line = cause.recog.getLine ();
m_column = cause.recog.getColumn ();
m_cause = cause;
m_children = new ArrayList<IIdlPreprocessorStatus>();
}
public PreprocessorStatus (FileNotFoundException cause, File file)
{
m_severity = IIdlPreprocessorStatus.ERROR;
m_message = cause.getMessage ();
m_filename = file.getName ();
m_line = -1;
m_column = -1;
m_cause = cause;
m_children = new ArrayList<IIdlPreprocessorStatus>();
}
public int getSeverity ()
{
return m_severity;
}
public String getMessage ()
{
return m_message;
}
public String getFilename ()
{
return m_filename;
}
public int getLine ()
{
return m_line;
}
public int getColumn ()
{
return m_column;
}
public Throwable getException ()
{
return m_cause;
}
public IIdlPreprocessorStatus[] getChildStati ()
{
return (IIdlPreprocessorStatus[]) m_children.toArray (new IIdlPreprocessorStatus[m_children.size ()]);
}
public void add (IIdlPreprocessorStatus status)
{
m_children.add (status);
if(this.m_severity < status.getSeverity ())
{
this.m_severity = status.getSeverity ();
}
}
public boolean isMultiStatus ()
{
return !m_children.isEmpty ();
}
public boolean isOK ()
{
if(isMultiStatus())
{
for(IIdlPreprocessorStatus child : m_children)
{
if(!child.isOK ())
{
return false;
}
}
}
return m_severity == IIdlPreprocessorStatus.OK;
}
public String toString ()
{
return m_filename + ':' + m_line + ':' + m_column + ':' + getMessage ();
}
}

View file

@ -0,0 +1,64 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.preprocessor;
import java.io.File;
import java.io.Writer;
import java.util.List;
import java.util.Map;
/**
* Public interface to the C Preprocessor. This preprocessor will produce <em>almost</em> the same
* output as running the {@link http://gcc.gnu.org/onlinedocs/cpp/ gcc preprocessor}. Details of
* the output format can be found
* {@link http://gcc.gnu.org/onlinedocs/cpp/IIdlPreprocessor-Output.html#Preprocessor-Output here}.
* <p>
* This preprocessor differs from gcc in the way it deals with blank lines. The gcc preprocessor
* removes long sequences of blank lines and replaces them with an appropriate <em>line marker</em>,
* whereas this preprocessor preserves all blank lines..
*
* <pre><code>
* File input = ..;
* StringWriter output = new StringWriter ();
*
* IIdlPreprocessor preprocessor = IdlPreprocessorFactory.create ();
*
* preprocessor.setWorkingDirectory (new File (&quot;/home/ted/project1&quot;);
* preprocessor.addIncludeDirectory (new File (&quot;includes&quot;));
* preprocessor.setStripComments (false);
* preprocessor.setStripIncludes (true);
*
* IStatus status = preprocessor.preprocess (input, output, null);
* </code></pre>
*/
public interface IIdlPreprocessor
{
static final String PLUGIN_ID = IIdlPreprocessor.class.getPackage ().getName ();
/**
* Runs the preprocessor on the specified {@link File file} and sends the resulting output to the
* specified {@link Writer writer}. It also populates the optional <code>dependencies</code>
* map, if one is provided.
*
* @param input
* The file to be preprocessed
* @param output
* Where to put the preprocessed output
* @param dependencies
* An optional Map containing a key for each file encountered during preprocessing.
* Each key (file) entry lists the files that it included.
*/
public IIdlPreprocessorStatus preprocess (IIdlPreprocessorParams params, File input, Writer output, Map<File, List<File>> dependencies);
public IIdlPreprocessorParams createPreprocessorParams ();
}

View file

@ -0,0 +1,158 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.preprocessor;
import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;
/**
* FIXME: Document it!
*/
public interface IIdlPreprocessorParams
{
/**
* Sets the <em>working directory</em> for this preprocessor. Any relative paths, such as the
* input file, or include directories, are resolved relative to this directory. The default value
* is taken as the value of the <code>user.dir</code> system property.
* <p>
* Setting this property on the preprocessor is equivalent to changing the current working
* directory prior to running it.
*
* @param directory
* The <em>workig directory</em> for this preprocessor.
* @throws FileNotFoundException
* @see System#getProperties()
* @see #getWorkingDirectory()
*/
public void setWorkingDirectory (File directory) throws FileNotFoundException;
/**
* Returns the preprocessors current <em>working directory</em>.
*
* @return File
* @see #setWorkingDirectory(File)
*/
public File getWorkingDirectory ();
/**
* Determines whether to preserve comments in the preprocessed output. The default value is
* <code>true</code>, meaning that comments will be stripped and therefore not present in the
* output.
*
* @param strip
*/
public void setStripComments (boolean strip);
/**
* @return boolean
* @see #setStripComments(boolean)
*/
public boolean getStripComments ();
/**
* Controls whether the content of included files is passed through to the preprocessed output.
* The default value is <code>false</code>, meaning that all content from the primary,
* <em>and</em> included files is passed through to the preprocessed output. If set to
* <code>true</code>, only the content from the primary file will be present in the
* preprocessed output. In both cases, full preprocessing takes place. This option only controls
* what is present in the output.
*
* @param strip
*/
public void setStripIncludes (boolean strip);
/**
* @return boolean
* @see #setStripIncludes(boolean)
*/
public boolean getStripIncludes ();
/**
* Controls whether <em>line markers</em> are produced in the output of this preprocessor. Line
* markers are additional lines, introduced into the output, which look like this:
* <p> # &lt;line&gt; &lt;filename&gt; &lt;flags&gt;
* <p>
* These lines are inserted as needed into the output (but never within a string or character
* constant). They mean that the following line originated in file &lt;filename&gt; at line
* &lt;line&gt;. &lt;filename&gt; will never contain any non-printing characters; they are
* replaced with octal escape sequences.
*
* @param strip
* @see #getStripLineMarkers()
*/
public void setStripLineMarkers (boolean strip);
/**
* @return boolean
* @see #setStripLineMarkers(boolean)
*/
public boolean getStripLineMarkers ();
/**
* Adds the specified <code>directory</code> to the include path (like the
* <code>-I&lt;directory&gt;</code> flag). If the specified <code>directory</code> is
* {@link File#isAbsolute() relative} then it will be interpreted relative to this preprocessors
* current {@link #setWorkingDirectory(File) working directory}.
*
* @param directory
* @throws FileNotFoundException
* @see #setWorkingDirectory(File)
*/
public void addIncludeDirectory (File directory) throws FileNotFoundException;
/**
* Removes the specified <code>directory</code> from the include path.
*
* @param directory
*/
public void removeIncludeDirectory (File directory);
/**
* Returns the list of include directories that make up the include path
*
* @return List
*/
public List<File> getIncludeDirectories ();
/**
* Predefine the specified <code>name</code> as a macro, with the value <code>1</code>.
*
* @param name
*/
public void addMacroDefinition (String name);
/**
* Predefine the specified <code>name</code> as a macro, with the specified <code>value</code>
*
* @param name
* @param value
*/
public void addMacroDefinition (String name, String value);
/**
* Cancel any previous definition of <code>name</code>, either built in or provided with
* {@link #addMacroDefinition(String)}
*
* @param name
*/
public void removeMacroDefinition (String name);
/**
* Returns the list of macro definitions for this preprocessor
*
* @return Map
*/
public Map<String, List<String>> getMacroDefinitions ();
}

View file

@ -0,0 +1,43 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.preprocessor;
public interface IIdlPreprocessorStatus
{
public static final int OK = 0;
public static final int INFO = 0x01;
public static final int WARNING = 0x02;
public static final int ERROR = 0x04;
public static final int CANCEL = 0x08;
public int getSeverity ();
public String getMessage ();
public String getFilename ();
public int getLine ();
public int getColumn ();
public Throwable getException ();
public IIdlPreprocessorStatus[] getChildStati();
public boolean isOK();
public boolean isMultiStatus();
}

View file

@ -0,0 +1,23 @@
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
package org.eclipse.cyclonedds.idt.imports.idl.preprocessor;
import org.eclipse.cyclonedds.idt.imports.idl.internal.preprocessor.IdlPreprocessor;
public abstract class IdlPreprocessorFactory
{
public static IIdlPreprocessor create ()
{
return new IdlPreprocessor ();
}
}

View file

@ -0,0 +1,3 @@
Classes in org.eclipse.cyclonedds.parser generated from IDL.g4:
java org.antlr.v4.Tool -visitor -no-listener -package org.eclipse.cyclonedds.parser IDL.g4

View file

@ -0,0 +1,32 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
banner (file, date, version) ::= <<
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
/****************************************************************
Generated by Cyclone DDS IDL to C Translator
File name: <file>.c
Source: <file>.idl
<if(date)> Generated: <date><endif>
Cyclone DDS: V<version>
*****************************************************************/
>>

View file

@ -0,0 +1,13 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
dlldef (name, dllname, dllfile) ::= <<
#define _<name>_DLL_
>>

View file

@ -0,0 +1,17 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
file (banner, name, nameupper, declarations, dll, includes) ::= <<
<banner>
<if(dll)><dll><endif>
#include "<name>.h"
<declarations; separator="\n">
>>

View file

@ -0,0 +1,13 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
module (name, scope, declarations) ::= <<
<declarations; separator="\n">
>>

View file

@ -0,0 +1,41 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
struct (name, scope, extern, alignment, fields, keys, flags, declarations, marshalling, xml, istopic) ::= <<
<declarations>
<if(istopic)>
<if(keys)>
static const dds_key_descriptor_t <scopedname(...)>_keys[<length(keys)>] =
{
<keys:{ k | { "<k.name>", <k.offset> }; separator="},\n">}
};
<endif>
static const uint32_t <scopedname(...)>_ops [] =
{
<marshalling; separator=",\n">
};
const dds_topic_descriptor_t <scopedname(...)>_desc =
{
sizeof (<scopedname(...)>),
<alignment>,
<if(flags)><flags; separator=" | "><else>0u<endif>,
<if(keys)><length(keys)><else>0<endif>u,
"<colonscopedname(...)>",
<if(keys)><scopedname(...)>_keys<else>NULL<endif>,
<length(marshalling)>,
<scopedname(...)>_ops,
<if(xml)>"\<MetaData version=\"1.0.0\"><xml>\</MetaData>"<else>NULL<endif>
};
<endif>
>>

View file

@ -0,0 +1,46 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
import "banner.st"
import "file.st"
import "dlldef.st"
import "module.st"
import "struct.st"
scopedname (scope, name) ::= <<
<if(scope)><scope;separator="_">_<endif><name>
>>
colonscopedname (scope, name) ::= << <if(scope)><scope;separator="::">::<endif><name>
>>
member (name, arraydim, scope, type, str_size) ::= <<
>>
scalar_typedef (namescope, name, scope, type, arraydim, str_size) ::= <<
>>
enum (name, scope, values) ::= <<
>>
const (name, scope, expression) ::= <<
>>
union (name, scope, disc, discscope, fields, declarations) ::= <<
>>
keyfield (name, offset) ::= <<
>>
seqdef (name, scope, type, typescope) ::= <<
>>
seqdef_base (name, scope, type, arraydim, str_size) ::= <<
>>

View file

@ -0,0 +1,14 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
allocs (scope, name) ::= <<
#define <scopedname(...)>__alloc() \
((<scopedname(...)>*) dds_alloc (sizeof (<scopedname(...)>)));
>>

View file

@ -0,0 +1,32 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
banner (file, date, version) ::= <<
/*
* Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
*
* This program and the accompanying materials are made available under the
* terms of the Eclipse Public License v. 2.0 which is available at
* http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
* v. 1.0 which is available at
* http://www.eclipse.org/org/documents/edl-v10.php.
*
* SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
*/
/****************************************************************
Generated by Cyclone DDS IDL to C Translator
File name: <file>.h
Source: <file>.idl
<if(date)> Generated: <date><endif>
Cyclone DDS: V<version>
*****************************************************************/
>>

View file

@ -0,0 +1,13 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
const (name, scope, expression) ::= <<
#define <scopedname(...)> <expression>
>>

View file

@ -0,0 +1,29 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
dlldef (name, dllname, dllfile) ::= <<
<if(dllfile)>#include "<dllfile>"<else>
#undef DDS_EXPORT
#ifdef _WIN32_DLL_
#ifdef _<name>_DLL_
#define DDS_EXPORT extern __declspec (dllexport)
#else
#ifdef DDS_BUILD_<dllname>_DLL
#define DDS_EXPORT extern
#else
#define DDS_EXPORT extern __declspec (dllimport)
#endif
#endif
#else
#define DDS_EXPORT extern
#endif
<endif>
>>

View file

@ -0,0 +1,18 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
enum (name, scope, values) ::= <<
typedef enum <scopedname(...)>
{
<values:{ v | <scopedname(scope,v)>}; separator=",\n">
} <scopedname(...)>;
<allocs(...)>
>>

View file

@ -0,0 +1,32 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
file (banner, name, nameupper, declarations, dll, includes) ::= <<
<banner>
#include "ddsc/dds_public_impl.h"
<includes:{n | #include "<n>.h"}; separator="\n">
#ifndef _DDSL_<nameupper>_H_
#define _DDSL_<nameupper>_H_
<if(dll)><dll><endif>
#ifdef __cplusplus
extern "C" {
#endif
<declarations; separator="\n">
#ifdef __cplusplus
}
#endif
#endif /* _DDSL_<nameupper>_H_ */
>>

View file

@ -0,0 +1,13 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
module (name, scope, declarations) ::= <<
<declarations; separator="\n">
>>

View file

@ -0,0 +1,25 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
seqdef (name, scope, type, typescope) ::= <<
typedef struct <scopedname(...)>
{
uint32_t _maximum;
uint32_t _length;
<scopedname(scope=typescope,name=type)> *_buffer;
bool _release;
} <scopedname(...)>;
<allocs(...)>
#define <scopedname(...)>_allocbuf(l) \
((<scopedname(scope=typescope,name=type)> *) dds_alloc ((l) * sizeof (<scopedname(scope=typescope,name=type)>)))
>>

View file

@ -0,0 +1,25 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
seqdef_base (name, scope, type, arraydim, str_size) ::= <<
typedef struct <scopedname(...)>
{
uint32_t _maximum;
uint32_t _length;
<type> (*_buffer)<str_size><arraydim>;
bool _release;
} <scopedname(...)>;
<allocs(...)>
#define <scopedname(...)>_allocbuf(l) \
((<type> (*)<str_size><arraydim>) dds_alloc ((l) * sizeof (<type><str_size><arraydim>)))
>>

View file

@ -0,0 +1,28 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
struct (name, scope, fields, extern, alignment, keys, flags, declarations, marshalling, xml, istopic) ::= <<
<declarations; separator="\n">
typedef struct <scopedname(...)>
{
<fields; separator="\n">
} <scopedname(...)>;
<if(istopic)>
<extern> const dds_topic_descriptor_t <scopedname(...)>_desc;
<allocs(...)>
#define <scopedname(...)>_free(d,o) \
dds_sample_free ((d), &<scopedname(...)>_desc, (o))
<endif>
>>

View file

@ -0,0 +1,59 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
import "allocs.st"
import "banner.st"
import "file.st"
import "module.st"
import "struct.st"
import "union.st"
import "dlldef.st"
import "enum.st"
import "seqdef.st"
import "seqdef_base.st"
import "const.st"
idlToCTypeMap ::= [
"octet":"uint8_t",
"boolean":"bool",
"char":"char",
"short":"int16_t",
"unsigned short":"uint16_t",
"long":"int32_t",
"unsigned long":"uint32_t",
"long long":"int64_t",
"unsigned long long":"uint64_t",
"float":"float",
"double":"double",
"string":"char *",
"bstring":"char",
default:key
]
ctype (scope, type) ::= <<
<if(scope)><scopedname(scope,type)><else><idlToCTypeMap.(type)><endif>
>>
member (name, arraydim, scope, type, str_size) ::= <<
<ctype(...)> <name><str_size><arraydim>;
>>
scalar_typedef (namescope, name, scope, type, arraydim, str_size) ::= <<
typedef <ctype(scope, type)> <scopedname(namescope, name)> <str_size><arraydim>;
<allocs(namescope, name)>
>>
scopedname (scope, name) ::= <<
<if(scope)><scope;separator="_">_<endif><name>
>>
keyfield (name, offset) ::= <<
>>

View file

@ -0,0 +1,25 @@
// Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
// v. 1.0 which is available at
// http://www.eclipse.org/org/documents/edl-v10.php.
//
// SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
union (name, scope, disc, discscope, fields, declarations) ::= <<
<declarations; separator="\n">
typedef struct <scopedname(...)>
{
<ctype(discscope, disc)> _d;
union
{
<fields; separator="\n">
} _u;
} <scopedname(...)>;
<allocs(...)>
>>

181
src/idlc/src/pom.xml.in Normal file
View file

@ -0,0 +1,181 @@
<!--
Copyright(c) 2006 to 2018 ADLINK Technology Limited and others
This program and the accompanying materials are made available under the
terms of the Eclipse Public License v. 2.0 which is available at
http://www.eclipse.org/legal/epl-2.0, or the Eclipse Distribution License
v. 1.0 which is available at
http://www.eclipse.org/org/documents/edl-v10.php.
SPDX-License-Identifier: EPL-2.0 OR BSD-3-Clause
-->
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.eclipse.cyclonedds</groupId>
<artifactId>idlc</artifactId>
<version>@PROJECT_VERSION@</version>
<packaging>jar</packaging>
<name>IDL Compiler</name>
<dependencies>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr-complete</artifactId>
<version>3.5.2</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>antlr4-runtime</artifactId>
<version>4.5</version>
</dependency>
<dependency>
<groupId>org.antlr</groupId>
<artifactId>ST4</artifactId>
<version>4.0.8</version>
</dependency>
</dependencies>
<build>
<finalName>idlc</finalName>
<sourceDirectory>${basedir}</sourceDirectory>
<resources>
<resource>
<directory>${basedir}</directory>
<includes>
<include>org/eclipse/cyclonedds/templates/**</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
<configuration>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
<plugin>
<groupId>org.antlr</groupId>
<artifactId>antlr4-maven-plugin</artifactId>
<version>4.5</version>
<configuration>
<sourceDirectory>${basedir}/org/eclipse/cyclonedds/parser/grammar</sourceDirectory>
<visitor>true</visitor>
<listener>false</listener>
</configuration>
<executions>
<execution>
<id>antlr</id>
<phase>generate-sources</phase>
<goals>
<goal>antlr4</goal>
</goals>
</execution>
</executions>
</plugin>
<!-- FIXME: Support for licensing is currently not included.
Obviously this should be fixed before the product is
released. Using different profiles for development and
release build is probably a good idea. -->
<plugin>
<groupId>com.coderplus.maven.plugins</groupId>
<artifactId>copy-rename-maven-plugin</artifactId>
<version>1.0</version>
<executions>
<execution>
<id>copy-Version</id>
<phase>generate-sources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<sourceFile>${CMAKE_CURRENT_BINARY_DIR}/org/eclipse/cyclonedds/Project.java</sourceFile>
<destinationFile>target/generated-sources/idlc/org/eclipse/cyclonedds/Project.java</destinationFile>
</configuration>
</execution>
<execution>
<id>copy-LicenseMgr</id>
<phase>generate-sources</phase>
<goals>
<goal>copy</goal>
</goals>
<configuration>
<sourceFile>${basedir}/org/eclipse/cyclonedds/LicenseMgr.java.dummy</sourceFile>
<destinationFile>target/generated-sources/idlc/org/eclipse/cyclonedds/LicenseMgr.java</destinationFile>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.codehaus.mojo</groupId>
<artifactId>build-helper-maven-plugin</artifactId>
<version>3.0.0</version>
<executions>
<execution>
<phase>generate-sources</phase>
<goals>
<goal>add-source</goal>
</goals>
<configuration>
<sources>
<source>target/generated-sources/idlc</source>
</sources>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>single</goal>
</goals>
</execution>
</executions>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.8</version>
<dependencies>
<dependency>
<groupId>antlr</groupId>
<artifactId>antlr</artifactId>
<version>2.7.7</version>
</dependency>
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant-antlr</artifactId>
<version>1.9.4</version>
</dependency>
</dependencies>
<executions>
<execution>
<id>compile</id>
<phase>generate-sources</phase>
<configuration>
<target>
<mkdir dir="target/generated-sources/idlc/org/eclipse/cyclonedds/idt/imports/idl/internal/preprocessor"/>
<antlr target="${basedir}/org/eclipse/cyclonedds/idt/imports/idl/internal/preprocessor/CppLexer.g" outputdirectory="target/generated-sources/idlc/org/eclipse/cyclonedds/idt/imports/idl/internal/preprocessor"/>
<antlr target="${basedir}/org/eclipse/cyclonedds/idt/imports/idl/internal/preprocessor/ExpLexer.g" outputdirectory="target/generated-sources/idlc/org/eclipse/cyclonedds/idt/imports/idl/internal/preprocessor"/>
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
</plugins>
</build>
</project>