Skip to contentSkip to conversation

Clarifying a “syntax error” in SmPL Python code?

cocci Markus Elfring 2 participants 8 messages Oct 17, 2024

lore
Share & tools
lore
#0 lore raw

Hello,

I constructed an SmPL script a while ago. It contains a bit of Python code for querying a database by the means of the class library “SQLAlchemy”. It can still work (as expected) also together with the software combination “Coccinelle 1.2-00038-g2297fc0f”.

I adjusted this SmPL script for another source code analysis approach. Unfortunately, I stumbled on the following information.

Markus_Elfring@Sonne:…/Projekte/Linux/next-analyses> spatch drivers/base/auxiliary_sysfs.c …/Projekte/Coccinelle/janitor/list_free_attribute_usage_incidence.cocci …
SPECIAL NAMES: adding __free as a attribute
File "<string>", line 19
name: Mapped[str] = mapped_column(String, primary_key=True)
^
SyntaxError: invalid syntax
Error in Python script, line 1, file "…/Projekte/Coccinelle/janitor/list_free_attribute_usage_incidence.cocci": Python failure

I did not modify the mentioned line (because it was working before). Will any more software testers and developers (besides me) get into the mood to clarify such a surprising data processing result?

Regards,
Markus

#1 lore raw
Quoted 20 lines · Markus Elfring

Hello,

I constructed an SmPL script a while ago. It contains a bit of Python code for querying a database by the means of the class library “SQLAlchemy”. It can still work (as expected) also together with the software combination “Coccinelle 1.2-00038-g2297fc0f”.

I adjusted this SmPL script for another source code analysis approach. Unfortunately, I stumbled on the following information.

Markus_Elfring@Sonne:…/Projekte/Linux/next-analyses> spatch drivers/base/auxiliary_sysfs.c …/Projekte/Coccinelle/janitor/list_free_attribute_usage_incidence.cocci …
SPECIAL NAMES: adding __free as a attribute
File "<string>", line 19
name: Mapped[str] = mapped_column(String, primary_key=True)
^
SyntaxError: invalid syntax
Error in Python script, line 1, file "…/Projekte/Coccinelle/janitor/list_free_attribute_usage_incidence.cocci": Python failure

Quoted 3 lines

I did not modify the mentioned line (because it was working before). Will any more software testers and developers (besides me) get into the mood to clarify such a surprising data processing result?

Please provide the code, if you want others to check on something.

julia

#2 lore raw
Quoted 5 lines
Quoted 3 lines

I did not modify the mentioned line (because it was working before). Will any more software testers and developers (besides me) get into the mood to clarify such a surprising data processing result?

Please provide the code, if you want others to check on something.

Would you like to try the attached SmPL scripts out once more?

Do you get any helpful insights from corresponding code comparisons?

Regards,
Markus

@initialize:python@
@@
import sqlalchemy, sys sys.stderr.write("\n".join(["Using SQLAlchemy version:",

                            sqlalchemy.__version__]))

sys.stderr.write("\n")
from sqlalchemy import Column, Integer, String, create_engine # outdated: from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped, mapped_column
from sqlalchemy.orm import sessionmaker
engine = create_engine("sqlite:///:memory:", echo=False) # outdated: base = declarative_base()

class Base(DeclarativeBase):
pass

class action(Base):
__tablename__ = "statements"
name: Mapped[str] = mapped_column(String, primary_key=True)
source_file: Mapped[str] = mapped_column(String, primary_key=True)
line: Mapped[int] = mapped_column(Integer, primary_key=True)
column: Mapped[int] = mapped_column(Integer, primary_key=True)
statement1: Mapped[str] = mapped_column(String)
statement2: Mapped[str] = mapped_column(String)

def __repr__(self):

      return """<action(name='%s',

source_file='%s',
line='%s',
column='%s',
statement1='%s',
statement2='%s')>""" % (self.name,
self.source_file,
self.line,
self.column,
self.statement1,
self.statement2)

configured_session = sessionmaker(bind=engine)
session = configured_session()
# base.metadata.create_all(engine)
#
# See also:
# https://stackoverflow.com/questions/70402667/how-to-use-create-all-for-sqlalchemy-orm-objects-across-files

Base.metadata.create_all(engine)

def store_statements(fun, source, s1, s2):
"""Add data to an internal table."""
for place in source:
entry = action(name = fun,
source_file = place.file, line = place.line, column = int(place.column) + 1, statement1 = s1, statement2 = s2)
session.add(entry)

@searching@
identifier work;
statement s1, s2;
position pos;
type T;
@@
T work(...)
{
... when any
if (...)
{
... when any
s1@pos
s2
}
... when any
}

@script:python collection@
fun << searching.work;
s1 << searching.s1;
s2 << searching.s2;
place << searching.pos;
@@
store_statements(fun, place, s1, s2)

@finalize:python@
@@
session.commit()
from sqlalchemy import func
entries = session.query(func.count("*")).select_from(action).scalar()

if entries > 0:
from sqlalchemy import Index, Table, MetaData, select, text from sqlalchemy.engine.reflection import Inspector from sqlalchemy.sql import literal_column

pairs = Index("pairs", action.statement1, action.statement2) pairs.create(engine)

# See also:
# https://stackoverflow.com/questions/30575111/how-to-create-a-new-table-from-select-statement-in-sqlalchemy#answer-30577608

q = session.query(action.statement1, action.statement2, action.name, action.source_file,

                     func.count(literal_column("*")).label("C")
                    ).group_by(action.statement1,
                               action.statement2,
                               action.name,
                               action.source_file) \
                     .having(func.count(literal_column("*")) > literal_column("1"))

session.execute(text('create table t2 as ' + str(q.statement)))

   class results(Base):
       __table__ = Table("t2", Base.metadata, autoload_with = session.connection())
       __mapper_args__ = {
           "primary_key": [__table__.c.source_file,
                           __table__.c.name,
                           __table__.c.statement1,
                           __table__.c.statement2]
                         }

entries2 = session.query(func.count("*")).select_from(results).scalar()

if entries2 > 0:

      delimiter = "|"
      sys.stdout.write(delimiter.join(["statement1",
                                       "statement2",
                                       '"function name"',
                                       '"source file"',
                                       "incidence"]))
      sys.stdout.write("\r\n")
      for statement1, statement2, name, source_file, incidence \
          in session.query(results.statement1,
                           results.statement2,
                           results.name,
                           results.source_file,
                           results.C).order_by(results.source_file,
                                               results.name,
                                               results.statement1,
                                               results.statement2):
         sys.stdout.write(delimiter.join([statement1,
                                          statement2,
                                          name,
                                          source_file,
                                          str(incidence)]))
         sys.stdout.write("\r\n")
   else:
      sys.stderr.write("Duplicate statements were not determined from "
                       + str(entries) + " records.\n")
      delimiter = "|"
      sys.stderr.write(delimiter.join(["statement1",
                                       "statement2",
                                       '"function name"',
                                       '"source file"',
                                       "line"]))
      sys.stderr.write("\r\n")
      for statement1, statement2, name, source_file, line \
          in session.query(action.statement1,
                           action.statement2,
                           action.name,
                           action.source_file,
                           action.line).order_by(action.source_file,
                                               action.name,
                                               action.statement1,
                                               action.statement2,
                                               action.line):
         sys.stderr.write(delimiter.join([statement1,
                                          statement2,
                                          name,
                                          source_file,
                                          str(line)]))
         sys.stderr.write("\r\n")

else:
sys.stderr.write("No result for this analysis!\n")

@initialize:python@
@@
import sqlalchemy, sys sys.stderr.write("\n".join(["Using SQLAlchemy version:",

                            sqlalchemy.__version__]))

sys.stderr.write("\n")
from sqlalchemy import Column, Integer, String, create_engine from sqlalchemy.orm import DeclarativeBase
from sqlalchemy.orm import Mapped, mapped_column from sqlalchemy.orm import sessionmaker
engine = create_engine("sqlite:///:memory:", echo=False)

class Base(DeclarativeBase):
pass

class action(Base):
__tablename__ = "variants"
name: Mapped[str] = mapped_column(String, primary_key=True)
source_file: Mapped[str] = mapped_column(String, primary_key=True)
line: Mapped[int] = mapped_column(Integer, primary_key=True)
column: Mapped[int] = mapped_column(Integer, primary_key=True)
variant: Mapped[str] = mapped_column(String)

def __repr__(self):

      return """<action(name='%s',

source_file='%s',
line='%s',
column='%s',
variant='%s')>""" % (self.name,
self.source_file,
self.line,
self.column,
self.variant)

configured_session = sessionmaker(bind=engine)
session = configured_session()

# See also:
# https://stackoverflow.com/questions/70402667/how-to-use-create-all-for-sqlalchemy-orm-objects-across-files

Base.metadata.create_all(engine)

def store_data(source, free):
"""Add data to an internal table."""
for place in source:
entry = action(name = place.current_element,
source_file = place.file, line = place.line, column = int(place.column) + 1, variant = free)
session.add(entry)

@searching@
attribute name __free;
identifier name, variant;
position pos;
type t;
@@
(t* name __free(variant@pos) = ...;
|t* name __free(variant@pos);
)

@script:python collection@
variant << searching.variant;
place << searching.pos;
@@
store_data(place, variant)

@finalize:python@
@@
session.commit()
from sqlalchemy import func
entries = session.query(func.count("*")).select_from(action).scalar()

if entries > 0:
from sqlalchemy import Index, Table, MetaData, select, text from sqlalchemy.engine.reflection import Inspector from sqlalchemy.sql import literal_column

names = Index("names", action.variant)
names.create(engine)

# See also:
# https://stackoverflow.com/questions/30575111/how-to-create-a-new-table-from-select-statement-in-sqlalchemy#answer-30577608

q = session.query(action.variant,

                     func.count(literal_column("*")).label("C")
                    ).group_by(action.variant)

session.execute(text('create table t2 as ' + str(q.statement)))

   class results(Base):
       __table__ = Table("t2", Base.metadata, autoload_with = session.connection())
       __mapper_args__ = {
           "primary_key": [__table__.c.variant]
                         }

entries2 = session.query(func.count("*")).select_from(results).scalar()

if entries2 > 0:

      delimiter = "|"
      sys.stdout.write(delimiter.join(["variant", "incidence"]))
      sys.stdout.write("\r\n")
      for variant, incidence \
          in session.query(results.variant,
                           results.C).order_by(results.C):
         sys.stdout.write(delimiter.join([variant, str(incidence)]))
         sys.stdout.write("\r\n")
   else:
      sys.stderr.write("Attribute usage incidence was not determined from "
                       + str(entries) + " records.\n")
      delimiter = "|"
      sys.stderr.write(delimiter.join(["variant",
                                       '"function name"',
                                       '"source file"',
                                       "line"]))
      sys.stderr.write("\r\n")
      for variant, name, source_file, line \
          in session.query(action.variant,
                           action.name,
                           action.source_file,
                           action.line).order_by(action.source_file,
                                               action.name,
                                               action.variant,
                                               action.line):
         sys.stderr.write(delimiter.join([variant,
                                          name,
                                          source_file,
                                          str(line)]))
         sys.stderr.write("\r\n")

else:
sys.stderr.write("No result for this analysis!\n")

#3 lore raw

Re: [cocci] Challenges with selection of an SmPL Python version?

In reply to Markus Elfring
Quoted 1 line

I adjusted this SmPL script for another source code analysis approach.

Another command parameter should eventually be specified for the desired data processing.

Markus_Elfring@Sonne:…/Projekte/Linux/next-analyses> spatch --python /usr/bin/python3 drivers/base/auxiliary_sysfs.c …/Projekte/Coccinelle/janitor/list_free_attribute_usage_incidence.cocci …
SPECIAL NAMES: adding __free as a attribute
Using SQLAlchemy version:
2.0.32
HANDLING: drivers/base/auxiliary_sysfs.c
variant|incidence
kfree|2

Will any corresponding discussions become more interesting?

Regards,
Markus

#4 lore raw

Re: [cocci] Challenges with selection of an SmPL Python version?

Quoted 4 lines · Markus Elfring
Quoted 1 line

I adjusted this SmPL script for another source code analysis approach.

Another command parameter should eventually be specified for the desired data processing.

Quoted 8 lines

Markus_Elfring@Sonne:…/Projekte/Linux/next-analyses> spatch --python /usr/bin/python3 drivers/base/auxiliary_sysfs.c …/Projekte/Coccinelle/janitor/list_free_attribute_usage_incidence.cocci …
SPECIAL NAMES: adding __free as a attribute
Using SQLAlchemy version:
2.0.32
HANDLING: drivers/base/auxiliary_sysfs.c
variant|incidence
kfree|2

I can't test this because you use libraries that I don't have. But it looks the problem is just with your installation of python. Maybe you need to specify which version of python you want when you run configure.

julia

Quoted 7 lines

Will any corresponding discussions become more interesting?

Regards,
Markus

#5 lore raw

Re: [cocci] Challenges with selection of an SmPL Python version?

Quoted 1 line

I can't test this because you use libraries that I don't have.

Would you dare to install any of the mentioned software libraries (on demand)?

Regards,
Markus

#6 lore raw

Re: [cocci] Challenges with selection of an SmPL Python version?

Quoted 3 lines · Markus Elfring
Quoted 1 line

I can't test this because you use libraries that I don't have.

Would you dare to install any of the mentioned software libraries (on demand)?

I tried, but it was not obvious to me how to do that, so I gave up. If you want me to look at it, mke the code simpler in some way. I don't use python.

julia

#7 lore raw

Re: [cocci] Challenges with selection of an SmPL Python version?

Quoted 3 lines
Quoted 1 line

Would you dare to install any of the mentioned software libraries (on demand)?

I tried, but it was not obvious to me how to do that, so I gave up.

Is the used component available also in your software package sources? Python SQL Toolkit and Object Relational Mapper
https://www.sqlalchemy.org/

See also:
https://pypi.org/project/SQLAlchemy/

Regards,
Markus